| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182 |
- /** 授权的独立验收账号全链路;凭据与截图只保存在本机临时目录。 */
- import fs from 'node:fs';
- import os from 'node:os';
- import path from 'node:path';
- import assert from 'node:assert/strict';
- import { chromium } from 'playwright';
- const dir = process.env.FMODE_E2E_DIR || path.join(os.tmpdir(), 'fmode-app-1127-e2e');
- const accountPath = path.join(dir, 'account.json');
- const account = JSON.parse(fs.readFileSync(accountPath, 'utf8'));
- const base = process.env.FMODE_E2E_URL || 'http://127.0.0.1:4200';
- const stage = process.argv.find(a => a.startsWith('--stage='))?.slice(8) || 'start';
- const executablePath = [
- 'C:/Program Files/Google/Chrome/Application/chrome.exe',
- 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
- ].find(p => fs.existsSync(p));
- const browser = await chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}) });
- const errors = [];
- const output = value => console.log(JSON.stringify(value));
- const statePath = path.join(dir, 'browser-state.json');
- async function context(mobile = false, restore = true) {
- const c = await browser.newContext({
- viewport: mobile ? { width: 390, height: 844 } : { width: 1440, height: 960 },
- isMobile: mobile, hasTouch: mobile,
- ...(restore && fs.existsSync(statePath) ? { storageState: statePath } : {}),
- });
- const page = await c.newPage();
- page.setDefaultTimeout(30000);
- page.on('pageerror', e => errors.push(e.message));
- return { c, page };
- }
- async function login(page, mobile = false) {
- await page.goto(base + '/login', { waitUntil: 'domcontentloaded' });
- await page.getByRole('button', { name: mobile ? '使用账号密码登录' : '账号登录', exact: true }).click();
- await page.locator('input[placeholder="请输入账号"]').fill(account.username);
- await page.locator('input[placeholder="请输入密码"]').fill(account.password);
- if (mobile) {
- const agreement = page.locator('input[type="checkbox"]');
- if (await agreement.count()) await agreement.first().check({ force: true });
- }
- await page.getByRole('button', { name: /^登\s*录$/ }).click();
- }
- async function chatThroughUi() {
- assert.ok(account.agentId, 'Missing isolated test agent');
- const { c, page } = await context();
- const canonical = 'agent-node-app-' + account.agentId.toLowerCase();
- const existing = process.argv.includes('--existing');
- let marker = '验收成功-' + Date.now();
- let prompt = '请只回复这段文字:' + marker;
- if (!existing) {
- await page.goto(base + '/desktop/chat/' + canonical + '/new', { waitUntil: 'domcontentloaded' });
- const area = page.locator('textarea').first();
- await area.waitFor({ state: 'visible', timeout: 60000 });
- await page.waitForFunction(() => { const el = document.querySelector('textarea'); return el && !el.disabled; }, undefined, { timeout: 60000 });
- await area.fill(prompt);
- await page.locator('button.send').click();
- }
- const cfg = JSON.parse(fs.readFileSync(new URL('../.claude/dev-login.json', import.meta.url), 'utf8'));
- const env = fs.readFileSync(new URL('../src/environments/environment.base.ts', import.meta.url), 'utf8');
- const parseBase = env.match(/parseServer:\s*'([^']+)'/)[1];
- const appId = env.match(/parseAppId:\s*'([^']+)'/)[1];
- const u = new URL(parseBase + '/classes/FmodeMatrixBinding');
- u.searchParams.set('where', JSON.stringify({
- userPointer: { __type: 'Pointer', className: '_User', objectId: account.id }, agentId: canonical, status: 'active',
- }));
- const response = await fetch(u, { headers: { 'X-Parse-Application-Id': appId, 'X-Parse-Master-Key': cfg.masterKey } });
- const binding = (await response.json()).results?.[0];
- assert.ok(binding?.roomId, 'No owned binding');
- // App 一房间一会话;绑定房间只用于初始接入,不能误拿它验收新对话。
- const threadsUrl = new URL(parseBase + '/classes/FmodeChatThread');
- threadsUrl.searchParams.set('where', JSON.stringify({ user: { __type: 'Pointer', className: '_User', objectId: account.id }, agentId: canonical }));
- threadsUrl.searchParams.set('order', '-createdAt');
- const threadsRes = await fetch(threadsUrl, { headers: { 'X-Parse-Application-Id': appId, 'X-Parse-Master-Key': cfg.masterKey } });
- const threads = (await threadsRes.json()).results || [];
- const thread = threads.find(t => !t.isDeleted && (existing ? /验收成功-\d+/.test(t.lastPreview || '') : t.lastPreview?.includes(marker)));
- assert.ok(thread?.roomId, 'Actual UI session room was not persisted');
- if (existing) {
- marker = thread.lastPreview.match(/验收成功-\d+/)[0];
- prompt = thread.lastPreview;
- }
- let proof;
- for (let i = 0; i < 60; i++) {
- const r = await fetch(binding.homeserver + '/_matrix/client/v3/rooms/' + encodeURIComponent(thread.roomId) + '/messages?dir=b&limit=100', {
- headers: { Authorization: 'Bearer ' + binding.accessToken }, signal: AbortSignal.timeout(15000),
- });
- const events = (await r.json()).chunk || [];
- const sent = events.find(e => e.sender === binding.userMxId && e.type === 'm.room.message' && e.content?.body?.includes(prompt));
- const reply = events.find(e => e.sender === binding.agentMxId && e.type === 'm.room.message' && e.content?.body?.includes(marker));
- const targets = [sent?.event_id, sent?.content?.['m.relates_to']?.event_id, reply?.event_id].filter(Boolean);
- const done = events.find(e => e.sender === binding.agentMxId && e.type === 'm.reaction' &&
- e.content?.['m.relates_to']?.key === '✅' && targets.includes(e.content['m.relates_to'].event_id));
- if (sent && reply && done) {
- proof = { sentEventId: sent.event_id, replyEventId: reply.event_id, completionEventId: done.event_id, agentId: canonical };
- break;
- }
- await new Promise(resolve => setTimeout(resolve, 3000));
- }
- assert.ok(proof, 'Actual UI send did not produce an authenticated target reply and completion');
- fs.writeFileSync(path.join(dir, 'chat-proof.json'), JSON.stringify(proof, null, 2));
- await page.goto(base + '/desktop/chat/' + canonical + '/' + encodeURIComponent(thread.threadRoot), { waitUntil: 'domcontentloaded' });
- await page.getByText(marker, { exact: true }).first().waitFor({ state: 'visible', timeout: 60000 });
- await page.screenshot({ path: path.join(dir, '07-real-chat.png'), fullPage: true });
- output({ check: 'real-ui-chat-roundtrip', ...proof, pass: true });
- await c.close();
- const mobile = await context(true);
- await mobile.page.goto(base, { waitUntil: 'domcontentloaded' });
- await mobile.page.waitForURL(/\/mobile\/messages/, { timeout: 60000 });
- await mobile.page.locator('button.m-row').first().waitFor({ state: 'visible', timeout: 60000 });
- await mobile.page.screenshot({ path: path.join(dir, '06-mobile-reopen.png'), fullPage: true });
- await mobile.page.locator('button.m-row').first().click();
- await mobile.page.getByText(marker, { exact: true }).first().waitFor({ state: 'visible', timeout: 60000 });
- await mobile.page.screenshot({ path: path.join(dir, '08-mobile-real-chat.png'), fullPage: true });
- output({ check: 'mobile-existing-chat-readback', pass: true });
- await mobile.c.close();
- }
- try {
- if (stage === 'chat') {
- await chatThroughUi();
- } else if (stage === 'start') {
- assert.ok(!account.jobId, 'This account already has an acceptance job; resume it instead of creating another.');
- const { c, page } = await context(false, false);
- await login(page);
- await page.waitForURL(/\/plans(?:\?|$)/, { timeout: 60000 });
- await page.screenshot({ path: path.join(dir, '01-new-user-plans.png'), fullPage: true });
- output({ check: 'new-user-login', url: page.url(), pass: true });
- const advanced = page.locator('article.plan-card').filter({ has: page.getByRole('heading', { name: '进阶版', exact: true }) });
- await advanced.getByRole('button', { name: '立即开通', exact: true }).click();
- await page.waitForURL(/\/provision\?jobId=/, { timeout: 90000 });
- account.jobId = new URL(page.url()).searchParams.get('jobId');
- fs.writeFileSync(accountPath, JSON.stringify(account, null, 2));
- await c.storageState({ path: statePath });
- await page.screenshot({ path: path.join(dir, '02-provisioning.png'), fullPage: true });
- output({ check: 'start-provision-through-ui', jobId: account.jobId, pass: true });
- await c.close();
- } else {
- assert.ok(account.jobId, 'No verified start-stage job');
- const { c, page } = await context();
- await page.goto(base + '/provision?jobId=' + encodeURIComponent(account.jobId), { waitUntil: 'domcontentloaded' });
- if (process.argv.includes('--refresh-running')) {
- await page.waitForTimeout(1500);
- await page.reload({ waitUntil: 'domcontentloaded' });
- assert.equal(new URL(page.url()).searchParams.get('jobId'), account.jobId);
- await page.screenshot({ path: path.join(dir, '02-provisioning-refreshed.png'), fullPage: true });
- output({ check: 'refresh-preserves-provision-job', jobId: account.jobId, pass: true });
- }
- const ticker = setInterval(() => output({ check: 'waiting-for-real-readiness', jobId: account.jobId }), 30000);
- try {
- await page.getByRole('button', { name: '进入应用', exact: true }).waitFor({ state: 'visible', timeout: 12 * 60 * 1000 });
- } finally { clearInterval(ticker); }
- await page.screenshot({ path: path.join(dir, '03-ready.png'), fullPage: true });
- await page.getByRole('button', { name: '进入应用', exact: true }).click();
- await page.waitForURL(/\/desktop\/chat(?:[/?]|$)/, { timeout: 60000 });
- await page.screenshot({ path: path.join(dir, '04-entered-app.png'), fullPage: true });
- output({ check: 'ready-enter-app', url: page.url(), pass: true });
- await page.reload({ waitUntil: 'domcontentloaded' });
- await page.waitForURL(/\/desktop\/chat(?:[/?]|$)/, { timeout: 60000 });
- output({ check: 'desktop-refresh', pass: true });
- await c.storageState({ path: statePath });
- await c.close();
- for (const mobile of [false, true]) {
- const reopened = await context(mobile);
- await reopened.page.goto(base, { waitUntil: 'domcontentloaded' });
- await reopened.page.waitForURL(mobile ? /\/mobile\/messages/ : /\/desktop\/chat/, { timeout: 60000 });
- await reopened.page.screenshot({ path: path.join(dir, mobile ? '06-mobile-reopen.png' : '05-desktop-reopen.png'), fullPage: true });
- output({ check: mobile ? 'mobile-reopen' : 'desktop-reopen', url: reopened.page.url(), pass: true });
- await reopened.c.close();
- }
- const freshLogin = await context(false, false);
- await login(freshLogin.page);
- await freshLogin.page.waitForURL(/\/desktop\/chat/, { timeout: 60000 });
- output({ check: 'fresh-password-login-after-provision', pass: true });
- await freshLogin.c.close();
- }
- assert.deepEqual(errors, [], 'Browser page errors');
- output({ stage, pageErrors: errors, evidenceDirectory: dir, success: true });
- } finally {
- await browser.close();
- }
|