| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320 |
- /** Real UI acceptance, confined to the dedicated 2026-11-28 test account/container. */
- 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 durableDir = path.resolve('.local-backup/acceptance-20261128');
- const dir = process.env.FMODE_E2E_DIR || (fs.existsSync(path.join(durableDir, 'account.json'))
- ? durableDir : path.join(os.tmpdir(), 'fmode-app-1128-acceptance'));
- const account = JSON.parse(fs.readFileSync(path.join(dir, 'account.json'), 'utf8'));
- assert.equal(account.jobId, 'QxB0R9BeWv', 'Only the explicitly created acceptance job is authorized');
- const canonical = 'agent-node-app-' + account.agentId.toLowerCase();
- assert.equal(canonical, 'agent-node-app-dw20i0uvpx');
- const base = process.env.FMODE_E2E_URL || JSON.parse(fs.readFileSync(path.join(dir, 'local-server.json'), 'utf8').replace(/^\uFEFF/, '')).base;
- const phase = process.argv.find(a => a.startsWith('--stage='))?.slice(8) || 'isolation';
- // 同一验收账本只允许一个执行器;异常退出后先核验进程,再清理失效锁。
- if (phase !== 'status') {
- const lockPath = path.join(dir, 'acceptance-run.lock.json');
- if (fs.existsSync(lockPath)) {
- const previous = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
- let alive = true;
- try { process.kill(previous.pid, 0); } catch (error) {
- if (error.code === 'ESRCH') alive = false;
- else throw error;
- }
- assert.ok(!alive, `Acceptance is already running as PID ${previous.pid}; inspect status instead of starting another run`);
- fs.unlinkSync(lockPath);
- }
- const fd = fs.openSync(lockPath, 'wx');
- fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, phase, startedAt: new Date().toISOString() }));
- fs.closeSync(fd);
- process.once('exit', () => {
- try {
- if (JSON.parse(fs.readFileSync(lockPath, 'utf8')).pid === process.pid) fs.unlinkSync(lockPath);
- } catch { /* 硬中断留下的锁由下次恢复时只读核验进程。 */ }
- });
- }
- const statePath = path.join(dir, 'acceptance-state.json');
- const state = fs.existsSync(statePath) ? JSON.parse(fs.readFileSync(statePath)) : { run: Date.now().toString(36) };
- const save = () => {
- const next = statePath + '.next';
- fs.writeFileSync(next, JSON.stringify(state, null, 2));
- fs.renameSync(next, statePath);
- };
- const cfg = JSON.parse(fs.readFileSync('.claude/dev-login.json', 'utf8'));
- const adminHeaders = { 'X-Parse-Application-Id': 'ncloudmaster', 'X-Parse-Master-Key': cfg.masterKey };
- const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
- async function records(cls, where) {
- const url = new URL('https://server.fmode.cn/parse/classes/' + cls);
- url.searchParams.set('where', JSON.stringify(where));
- url.searchParams.set('order', '-createdAt'); url.searchParams.set('limit', '100');
- const r = await fetch(url, { headers: adminHeaders, signal: AbortSignal.timeout(20000) });
- assert.ok(r.ok, `Read ${cls}: HTTP ${r.status}`);
- return (await r.json()).results || [];
- }
- const bindings = await records('FmodeMatrixBinding', {
- userPointer: { __type: 'Pointer', className: '_User', objectId: account.id },
- agentId: canonical, status: 'active',
- });
- const binding = bindings[0];
- assert.ok(binding?.accessToken && binding.agentMxId && binding.userMxId, 'Owned Matrix binding required');
- async function events(room) {
- const r = await fetch('https://matrix.fmode.cn/_matrix/client/v3/rooms/' + encodeURIComponent(room) + '/messages?dir=b&limit=100', {
- headers: { Authorization: 'Bearer ' + binding.accessToken }, signal: AbortSignal.timeout(20000),
- });
- assert.ok(r.ok, `Read Matrix events: HTTP ${r.status}`);
- return (await r.json()).chunk || [];
- }
- async function findThread(marker, threadRoot) {
- const rows = await records('FmodeChatThread', {
- user: { __type: 'Pointer', className: '_User', objectId: account.id }, agentId: canonical,
- });
- return rows.find(t => !t.isDeleted && (threadRoot ? t.threadRoot === threadRoot : t.lastPreview?.includes(marker)));
- }
- if (phase === 'status') {
- const checks = [];
- for (const key of ['A', 'B', 'files', 'filesFresh', 'filesRepaired']) {
- const row = state[key];
- if (!row?.roomId) continue;
- const thread = await findThread(row.marker, row.threadRoot);
- const roomId = thread?.roomId || row.roomId;
- const all = await events(roomId);
- const sent = all.find(e => e.type === 'm.room.message' && e.sender === binding.userMxId && e.content?.body?.includes(row.marker));
- const replies = all.filter(e => e.type === 'm.room.message' && e.sender === binding.agentMxId &&
- e.origin_server_ts >= (sent?.origin_server_ts || 0));
- const done = all.find(e => e.type === 'm.reaction' && e.sender === binding.agentMxId &&
- e.content?.['m.relates_to']?.key === '✅' && e.content?.['m.relates_to']?.event_id === sent?.event_id);
- checks.push({ key, roomId, cachedRoomId: row.roomId, dedicated: roomId !== binding.roomId,
- sentEventId: sent?.event_id || null, completionEventId: done?.event_id || null,
- latestAgentText: replies[0]?.content?.body?.slice(0, 900) || null,
- latestReply: replies.find(e => e.content?.['fmode.kind'] !== 'process')?.content?.body?.slice(0, 1400) || null });
- }
- const result = { at: new Date().toISOString(), container: canonical, checks };
- fs.writeFileSync(path.join(dir, 'acceptance-readback.json'), JSON.stringify(result, null, 2));
- console.log(JSON.stringify(result, null, 2));
- process.exit(0);
- }
- const browser = await chromium.launch({ headless: true,
- executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe' });
- const context = await browser.newContext({ viewport: { width: 1440, height: 960 },
- storageState: path.join(dir, 'browser-state.json'), acceptDownloads: true });
- const page = await context.newPage();
- const errors = [];
- page.on('pageerror', e => errors.push(e.message));
- page.setDefaultTimeout(45000);
- async function open(row, mobile = false) {
- const route = mobile ? '/mobile/chat/' : '/desktop/chat/';
- await page.goto(base + route + canonical + '/' + encodeURIComponent(row.threadRoot), { waitUntil: 'domcontentloaded' });
- await page.locator('textarea').first().waitFor({ state: 'visible' });
- }
- async function sendNew(key, marker, prompt, file) {
- if (state[key]?.roomId) {
- const row = state[key];
- // 初次发送可能早于异步建房回写,恢复时以服务端会话目录为准。
- const latest = await findThread(marker, row.threadRoot);
- if (latest?.roomId && latest.roomId !== row.roomId) {
- row.previousRoomId = row.roomId;
- row.roomId = latest.roomId;
- row.threadRoot = latest.threadRoot;
- save();
- }
- if (!row.sentEventId && !row.proof) {
- const sent = (await events(row.roomId)).find(e => e.sender === binding.userMxId && e.type === 'm.room.message' && e.content?.body?.includes(marker));
- if (sent) { row.sentEventId = sent.event_id; save(); return row; }
- assert.ok(process.argv.includes('--recover-unsent') && !row.recoveryAttempted,
- `${key}: no server send receipt; explicit recovery is required before resending`);
- // 中断恢复先核对接入房间及目标房间,不能因目标无回执就盲重发。
- const inspectedRooms = [...new Set([row.roomId, row.previousRoomId, binding.roomId].filter(Boolean))];
- const inspection = [];
- for (const rid of inspectedRooms) {
- const all = await events(rid);
- const previous = all.find(e => e.sender === binding.userMxId && e.type === 'm.room.message' && e.content?.body?.includes(marker));
- assert.ok(!previous, `Original prompt already exists in ${rid}; inspect before resending`);
- inspection.push({ roomId: rid, inputEvents: file ? all.filter(e => e.sender === binding.userMxId &&
- e.type === 'm.room.message' && e.content?.body?.includes(path.basename(file))).map(e => e.event_id) : [] });
- }
- row.recoveryInspection = { checkedAt: new Date().toISOString(), rooms: inspection }; save();
- await open(row);
- await page.waitForFunction(() => { const e = document.querySelector('textarea'); return e && !e.disabled; });
- if (file) {
- await page.locator('input[type="file"]').first().setInputFiles(file);
- await page.locator('.pending-holds').waitFor({ state: 'visible' });
- }
- await page.locator('textarea').first().fill(prompt);
- row.recoveryAttempted = true; row.recoverySentAt = Date.now(); save();
- await page.locator('button.send').click();
- await ensureSent(row);
- }
- return row;
- }
- if (state[key]?.sendAttempted) {
- const recovered = await findThread(marker);
- assert.ok(recovered, `Send ${key} was already attempted; inspect evidence before retrying`);
- state[key] = { ...state[key], roomId: recovered.roomId, threadRoot: recovered.threadRoot }; save();
- return state[key];
- }
- await page.goto(base + '/desktop/chat/' + canonical + '/new', { waitUntil: 'domcontentloaded' });
- await page.waitForFunction(() => { const e = document.querySelector('textarea'); return e && !e.disabled; });
- if (file) {
- await page.locator('input[type="file"]').first().setInputFiles(file);
- await page.locator('.pending-holds').waitFor({ state: 'visible' });
- }
- await page.locator('textarea').first().fill(prompt);
- state[key] = { marker, sendAttempted: true, sentAt: Date.now() }; save();
- await page.locator('button.send').click();
- let thread;
- for (let i = 0; i < 30 && !thread; i++) {
- const routeRoot = decodeURIComponent(new URL(page.url()).pathname.split('/').at(-1) || '');
- thread = await findThread(marker, routeRoot.startsWith('$') ? routeRoot : undefined);
- if (!thread) await sleep(1000);
- }
- assert.ok(thread?.roomId, `${key}: UI session must be persisted`);
- state[key] = { ...state[key], roomId: thread.roomId, threadRoot: thread.threadRoot }; save();
- await ensureSent(state[key]);
- console.log(JSON.stringify({ check: 'ui-send-' + key, roomId: thread.roomId, pass: true }));
- return state[key];
- }
- async function ensureSent(row) {
- for (let i = 0; i < 30; i++) {
- const sent = (await events(row.roomId)).find(e => e.sender === binding.userMxId &&
- e.type === 'm.room.message' && e.content?.body?.includes(row.marker));
- if (sent) { row.sentEventId = sent.event_id; save(); return; }
- await sleep(1000);
- }
- throw Error(`No Matrix send receipt for ${row.marker}; do not navigate away or silently resend`);
- }
- async function completed(row) {
- if (row.proof) return row.proof;
- const timeout = Number(process.env.FMODE_E2E_TASK_TIMEOUT_MS || 360000);
- assert.ok(Number.isFinite(timeout) && timeout > 0 && timeout <= 900000, 'Task timeout must be 1..900000ms');
- const deadline = Date.now() + timeout;
- let nextLog = 0;
- while (Date.now() < deadline) {
- const all = await events(row.roomId);
- const sent = all.find(e => e.sender === binding.userMxId && e.type === 'm.room.message' && e.content?.body?.includes(row.marker));
- const reply = all.find(e => e.sender === binding.agentMxId && e.type === 'm.room.message' &&
- e.origin_server_ts >= (sent?.origin_server_ts || 0) &&
- e.content?.['fmode.kind'] !== 'process' && e.content?.body?.includes(row.marker));
- const targets = [sent?.event_id, reply?.event_id].filter(Boolean);
- const done = all.find(e => e.sender === binding.agentMxId && e.type === 'm.reaction' &&
- e.origin_server_ts >= (reply?.origin_server_ts || sent?.origin_server_ts || 0) &&
- e.content?.['m.relates_to']?.key === '✅' && targets.includes(e.content['m.relates_to'].event_id));
- if (sent && reply && done) {
- const process = all.filter(e => e.sender === binding.agentMxId && e.type === 'm.room.message' && e.content?.['fmode.kind'] === 'process');
- row.proof = { sent: sent.event_id, reply: reply.event_id, completion: done.event_id,
- body: reply.content.body, processCount: process.length,
- threadBoundProcessCount: process.filter(e => e.content?.['m.relates_to']?.event_id === row.threadRoot).length };
- fs.writeFileSync(path.join(dir, row.marker + '-events.json'), JSON.stringify(all, null, 2));
- save(); return row.proof;
- }
- if (Date.now() > nextLog) { console.log(JSON.stringify({ waitingFor: row.marker, targetEvents: all.filter(e => e.sender === binding.agentMxId).length })); nextLog = Date.now() + 30000; }
- await sleep(2500);
- }
- throw Error(`No authenticated reply + completion for ${row.marker}`);
- }
- try {
- if (phase === 'isolation') {
- const ma = 'ACCEPT_A_' + state.run, mb = 'ACCEPT_B_' + state.run;
- const a = await sendNew('A', ma, `${ma}:验收任务,请分三次独立的工具调用,分别读取当前时间、查看当前工作目录、计算12345乘6789。不要修改已有文件或配置。最终回复必须包含 ${ma} 和计算结果。`);
- const b = await sendNew('B', mb, `只回复 ${mb},不要回复其他内容。`);
- const pa = await completed(a), pb = await completed(b);
- assert.notEqual(a.roomId, b.roomId);
- assert.ok(pa.processCount >= 3, 'Three separate calls must retain their process events');
- assert.ok(pa.body.replace(/[,,\s]/g, '').includes(String(12345 * 6789)), 'Calculation result required');
- await open(b);
- await page.locator('app-assistant-turn').filter({ hasText: mb }).first().waitFor({ state: 'visible' });
- assert.ok(!(await page.locator('app-assistant-turn').allTextContents()).some(s => s.includes(ma)), 'A leaked into B');
- await page.screenshot({ path: path.join(dir, '09-isolation-B.png'), fullPage: true });
- await open(a);
- await page.locator('app-assistant-turn').filter({ hasText: ma }).first().waitFor({ state: 'visible' });
- assert.ok(!(await page.locator('app-assistant-turn').allTextContents()).some(s => s.includes(mb)), 'B leaked into A');
- await page.screenshot({ path: path.join(dir, '10-isolation-A.png'), fullPage: true });
- state.isolationPassed = true; save();
- console.log(JSON.stringify({ check: 'real-two-session-isolation', processEvents: pa.processCount,
- threadBoundProcessEvents: pa.threadBoundProcessCount, completionVerified: true, pass: true }));
- } else if (phase === 'files' || phase === 'files-fresh' || phase === 'files-repair') {
- const repair = phase === 'files-repair';
- const key = repair ? 'filesRepaired' : phase === 'files-fresh' ? 'filesFresh' : 'files';
- const run = state.run + (phase !== 'files' ? '_fresh' : '');
- const marker = 'ACCEPT_FILE_' + run + (repair ? '_repair1' : ''), content = 'INPUT_EVIDENCE_' + run;
- const input = path.join(dir, 'input-' + run + '.txt');
- fs.writeFileSync(input, '这是本轮专用验收输入,编号:' + content + '\n', 'utf8');
- const stem = 'acceptance-' + run;
- if (repair && !state[key]) {
- assert.ok(state.filesFresh?.roomId && state.filesFresh?.sentEventId, 'Repair only the already verified dedicated file session');
- assert.notEqual(state.filesFresh.roomId, binding.roomId, 'Never repair by sending into the initial room');
- state[key] = { marker, roomId: state.filesFresh.roomId, threadRoot: state.filesFresh.threadRoot,
- preparedAt: new Date().toISOString(), reason: 'Runtime parent permissions corrected; retry only the two existing test deliverables' };
- save();
- }
- const repairPrompt = `${marker}:继续本会话刚才的两份测试成果 /opt/data/work/deliverables/${stem}.md 和 ${stem}.html。读取并确认输入编号 ${content},在两份测试文件各追加一行“自动上云复验 ${marker}”,通过正常文件交付流程完成自动上云和本会话登记,返回可打开的两个成果。不要手工导入或调用底层上传函数,不要修改任何配置、脚本或其他文件,不要删除文件。最终回复必须包含 ${marker} 和 ${content}。`;
- const row = await sendNew(key, marker,
- repair ? repairPrompt : `${marker}:读取我刚上传的文本,复述其中编号。在 /opt/data/work/deliverables/ 创建 ${stem}.md 和 ${stem}.html,两个文件均写入输入中的完整编号及“文件链路验收通过”。完成真实上云后返回两个可打开的链接。不要修改其他文件、配置或删除输入。最终回复必须包含 ${marker} 和输入编号。`, repair ? undefined : input);
- const proof = await completed(row);
- assert.ok(proof.body.includes(content), 'Agent must read the actual uploaded input');
- const fileEvents = await events(row.roomId);
- const inputEvent = fileEvents.find(e => e.sender === binding.userMxId && e.type === 'm.room.message' &&
- e.content?.body?.includes(path.basename(input)) && e.content?.['m.relates_to']?.event_id === row.threadRoot);
- assert.ok(inputEvent, 'Input attachment and instruction must arrive in this exact session room');
- assert.notEqual(row.roomId, binding.roomId, 'File acceptance requires a dedicated session room');
- if (row.recoverySentAt) {
- const leaked = (await events(binding.roomId)).filter(e => e.sender === binding.userMxId &&
- e.origin_server_ts >= row.recoverySentAt && (e.content?.body?.includes(marker) || e.content?.body?.includes(path.basename(input))));
- assert.equal(leaked.length, 0, 'Recovery must not leak input/instruction into the initial room');
- }
- row.inputEventId = inputEvent.event_id; save();
- const sessionToken = account.token || JSON.parse(fs.readFileSync(path.join(dir, 'browser-state.json'))).origins
- .flatMap(o => o.localStorage).find(k => k.name === 'fmode_session_token')?.value;
- const r = await fetch('https://server.fmode.cn/api/functions', {
- method: 'POST', headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ id: 'THXAOGKiPK', token: sessionToken,
- params: { action: 'listBySession', roomId: row.roomId, limit: 100 } }), signal: AbortSignal.timeout(20000),
- });
- const body = await r.json(); assert.equal(body.code, 200, 'File registration readback must succeed');
- fs.writeFileSync(path.join(dir, key + '-file-hub-readback.json'), JSON.stringify(body, null, 2));
- const registered = (body.files || []).filter(f => [stem + '.md', stem + '.html'].includes(f.name));
- // 接口兼容合并新文件台账与旧成果表,同 URL 可能有两条来源记录。
- const files = [...new Map(registered.map(f => [f.url, f])).values()];
- assert.equal(files.length, 2, 'Both distinct cloud outputs must be registered in this exact session');
- assert.equal(new Set(files.map(f => f.name)).size, 2, 'Both expected file names are required');
- for (const file of files) {
- assert.ok(file.url.startsWith('https://s3.fmode.cn/') || file.url.startsWith('https://file-cloud.fmode.cn/'));
- const response = await fetch(file.url, { signal: AbortSignal.timeout(30000) });
- assert.ok(response.ok, 'Cloud file must be downloadable');
- const text = await response.text(); assert.ok(text.includes(content), 'Cloud file content must match the input');
- }
- const mobile = process.argv.includes('--mobile');
- if (mobile) await page.setViewportSize({ width: 390, height: 844 });
- await open(row, mobile); await page.reload({ waitUntil: 'domcontentloaded' });
- const resultTurn = page.locator('app-assistant-turn').filter({ hasText: marker }).last();
- await resultTurn.waitFor({ state: 'visible', timeout: 60000 });
- for (const file of files) {
- const displayName = decodeURIComponent(new URL(file.url).pathname.split('/').at(-1)).replace(/^\d+-[a-z0-9]{6,}-/i, '');
- const button = resultTurn.getByRole('button', { name: '预览 ' + displayName, exact: true });
- await button.waitFor({ state: 'visible', timeout: 60000 });
- assert.equal(await button.count(), 1, 'Each current-round file must render exactly one card');
- await button.click();
- const dialog = page.getByRole('dialog', { name: '预览 ' + displayName, exact: true });
- await dialog.waitFor({ state: 'visible' });
- if (file.name.endsWith('.md')) await dialog.getByText(content, { exact: false }).first().waitFor({ state: 'visible' });
- else await dialog.frameLocator('iframe').locator('body').getByText(content, { exact: false }).first().waitFor({ state: 'visible' });
- await page.screenshot({ path: path.join(dir, (mobile ? 'mobile-' : '') + (file.name.endsWith('.md') ? '11-file-markdown.png' : '12-file-html.png')), fullPage: true });
- // HTML iframe 内的按键不会冒泡到外层,使用用户可见的关闭入口。
- const close = dialog.getByRole('button', { name: '关闭预览', exact: true });
- if (!(await close.isVisible())) await dialog.getByRole('button', { name: '回到右侧', exact: true }).click();
- await close.click();
- await dialog.waitFor({ state: 'hidden' });
- }
- state[key + (mobile ? 'MobilePassed' : 'Passed')] = true;
- state[key + 'OutputFiles'] = files.map(({ name, url, id }) => ({ name, url, id })); save();
- console.log(JSON.stringify({ check: 'real-upload-cloud-registration-reload-and-preview', outputs: files.map(f => f.name), pass: true }));
- } else throw Error('Unknown stage');
- assert.deepEqual(errors, [], 'Browser page errors');
- await context.storageState({ path: path.join(dir, 'browser-state.json') });
- } catch (error) {
- await page.screenshot({ path: path.join(dir, phase + '-failure.png'), fullPage: true }).catch(() => {});
- fs.writeFileSync(path.join(dir, phase + '-failure.json'), JSON.stringify({ error: error.message, url: page.url(), pageErrors: errors }, null, 2));
- throw error;
- } finally { await browser.close(); }
|