verify-container-acceptance.mjs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. /** Real UI acceptance, confined to the dedicated 2026-11-28 test account/container. */
  2. import fs from 'node:fs';
  3. import os from 'node:os';
  4. import path from 'node:path';
  5. import assert from 'node:assert/strict';
  6. import { chromium } from 'playwright';
  7. const durableDir = path.resolve('.local-backup/acceptance-20261128');
  8. const dir = process.env.FMODE_E2E_DIR || (fs.existsSync(path.join(durableDir, 'account.json'))
  9. ? durableDir : path.join(os.tmpdir(), 'fmode-app-1128-acceptance'));
  10. const account = JSON.parse(fs.readFileSync(path.join(dir, 'account.json'), 'utf8'));
  11. assert.equal(account.jobId, 'QxB0R9BeWv', 'Only the explicitly created acceptance job is authorized');
  12. const canonical = 'agent-node-app-' + account.agentId.toLowerCase();
  13. assert.equal(canonical, 'agent-node-app-dw20i0uvpx');
  14. const base = process.env.FMODE_E2E_URL || JSON.parse(fs.readFileSync(path.join(dir, 'local-server.json'), 'utf8').replace(/^\uFEFF/, '')).base;
  15. const phase = process.argv.find(a => a.startsWith('--stage='))?.slice(8) || 'isolation';
  16. // 同一验收账本只允许一个执行器;异常退出后先核验进程,再清理失效锁。
  17. if (phase !== 'status') {
  18. const lockPath = path.join(dir, 'acceptance-run.lock.json');
  19. if (fs.existsSync(lockPath)) {
  20. const previous = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
  21. let alive = true;
  22. try { process.kill(previous.pid, 0); } catch (error) {
  23. if (error.code === 'ESRCH') alive = false;
  24. else throw error;
  25. }
  26. assert.ok(!alive, `Acceptance is already running as PID ${previous.pid}; inspect status instead of starting another run`);
  27. fs.unlinkSync(lockPath);
  28. }
  29. const fd = fs.openSync(lockPath, 'wx');
  30. fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, phase, startedAt: new Date().toISOString() }));
  31. fs.closeSync(fd);
  32. process.once('exit', () => {
  33. try {
  34. if (JSON.parse(fs.readFileSync(lockPath, 'utf8')).pid === process.pid) fs.unlinkSync(lockPath);
  35. } catch { /* 硬中断留下的锁由下次恢复时只读核验进程。 */ }
  36. });
  37. }
  38. const statePath = path.join(dir, 'acceptance-state.json');
  39. const state = fs.existsSync(statePath) ? JSON.parse(fs.readFileSync(statePath)) : { run: Date.now().toString(36) };
  40. const save = () => {
  41. const next = statePath + '.next';
  42. fs.writeFileSync(next, JSON.stringify(state, null, 2));
  43. fs.renameSync(next, statePath);
  44. };
  45. const cfg = JSON.parse(fs.readFileSync('.claude/dev-login.json', 'utf8'));
  46. const adminHeaders = { 'X-Parse-Application-Id': 'ncloudmaster', 'X-Parse-Master-Key': cfg.masterKey };
  47. const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
  48. async function records(cls, where) {
  49. const url = new URL('https://server.fmode.cn/parse/classes/' + cls);
  50. url.searchParams.set('where', JSON.stringify(where));
  51. url.searchParams.set('order', '-createdAt'); url.searchParams.set('limit', '100');
  52. const r = await fetch(url, { headers: adminHeaders, signal: AbortSignal.timeout(20000) });
  53. assert.ok(r.ok, `Read ${cls}: HTTP ${r.status}`);
  54. return (await r.json()).results || [];
  55. }
  56. const bindings = await records('FmodeMatrixBinding', {
  57. userPointer: { __type: 'Pointer', className: '_User', objectId: account.id },
  58. agentId: canonical, status: 'active',
  59. });
  60. const binding = bindings[0];
  61. assert.ok(binding?.accessToken && binding.agentMxId && binding.userMxId, 'Owned Matrix binding required');
  62. async function events(room) {
  63. const r = await fetch('https://matrix.fmode.cn/_matrix/client/v3/rooms/' + encodeURIComponent(room) + '/messages?dir=b&limit=100', {
  64. headers: { Authorization: 'Bearer ' + binding.accessToken }, signal: AbortSignal.timeout(20000),
  65. });
  66. assert.ok(r.ok, `Read Matrix events: HTTP ${r.status}`);
  67. return (await r.json()).chunk || [];
  68. }
  69. async function findThread(marker, threadRoot) {
  70. const rows = await records('FmodeChatThread', {
  71. user: { __type: 'Pointer', className: '_User', objectId: account.id }, agentId: canonical,
  72. });
  73. return rows.find(t => !t.isDeleted && (threadRoot ? t.threadRoot === threadRoot : t.lastPreview?.includes(marker)));
  74. }
  75. if (phase === 'status') {
  76. const checks = [];
  77. for (const key of ['A', 'B', 'files', 'filesFresh', 'filesRepaired']) {
  78. const row = state[key];
  79. if (!row?.roomId) continue;
  80. const thread = await findThread(row.marker, row.threadRoot);
  81. const roomId = thread?.roomId || row.roomId;
  82. const all = await events(roomId);
  83. const sent = all.find(e => e.type === 'm.room.message' && e.sender === binding.userMxId && e.content?.body?.includes(row.marker));
  84. const replies = all.filter(e => e.type === 'm.room.message' && e.sender === binding.agentMxId &&
  85. e.origin_server_ts >= (sent?.origin_server_ts || 0));
  86. const done = all.find(e => e.type === 'm.reaction' && e.sender === binding.agentMxId &&
  87. e.content?.['m.relates_to']?.key === '✅' && e.content?.['m.relates_to']?.event_id === sent?.event_id);
  88. checks.push({ key, roomId, cachedRoomId: row.roomId, dedicated: roomId !== binding.roomId,
  89. sentEventId: sent?.event_id || null, completionEventId: done?.event_id || null,
  90. latestAgentText: replies[0]?.content?.body?.slice(0, 900) || null,
  91. latestReply: replies.find(e => e.content?.['fmode.kind'] !== 'process')?.content?.body?.slice(0, 1400) || null });
  92. }
  93. const result = { at: new Date().toISOString(), container: canonical, checks };
  94. fs.writeFileSync(path.join(dir, 'acceptance-readback.json'), JSON.stringify(result, null, 2));
  95. console.log(JSON.stringify(result, null, 2));
  96. process.exit(0);
  97. }
  98. const browser = await chromium.launch({ headless: true,
  99. executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe' });
  100. const context = await browser.newContext({ viewport: { width: 1440, height: 960 },
  101. storageState: path.join(dir, 'browser-state.json'), acceptDownloads: true });
  102. const page = await context.newPage();
  103. const errors = [];
  104. page.on('pageerror', e => errors.push(e.message));
  105. page.setDefaultTimeout(45000);
  106. async function open(row, mobile = false) {
  107. const route = mobile ? '/mobile/chat/' : '/desktop/chat/';
  108. await page.goto(base + route + canonical + '/' + encodeURIComponent(row.threadRoot), { waitUntil: 'domcontentloaded' });
  109. await page.locator('textarea').first().waitFor({ state: 'visible' });
  110. }
  111. async function sendNew(key, marker, prompt, file) {
  112. if (state[key]?.roomId) {
  113. const row = state[key];
  114. // 初次发送可能早于异步建房回写,恢复时以服务端会话目录为准。
  115. const latest = await findThread(marker, row.threadRoot);
  116. if (latest?.roomId && latest.roomId !== row.roomId) {
  117. row.previousRoomId = row.roomId;
  118. row.roomId = latest.roomId;
  119. row.threadRoot = latest.threadRoot;
  120. save();
  121. }
  122. if (!row.sentEventId && !row.proof) {
  123. const sent = (await events(row.roomId)).find(e => e.sender === binding.userMxId && e.type === 'm.room.message' && e.content?.body?.includes(marker));
  124. if (sent) { row.sentEventId = sent.event_id; save(); return row; }
  125. assert.ok(process.argv.includes('--recover-unsent') && !row.recoveryAttempted,
  126. `${key}: no server send receipt; explicit recovery is required before resending`);
  127. // 中断恢复先核对接入房间及目标房间,不能因目标无回执就盲重发。
  128. const inspectedRooms = [...new Set([row.roomId, row.previousRoomId, binding.roomId].filter(Boolean))];
  129. const inspection = [];
  130. for (const rid of inspectedRooms) {
  131. const all = await events(rid);
  132. const previous = all.find(e => e.sender === binding.userMxId && e.type === 'm.room.message' && e.content?.body?.includes(marker));
  133. assert.ok(!previous, `Original prompt already exists in ${rid}; inspect before resending`);
  134. inspection.push({ roomId: rid, inputEvents: file ? all.filter(e => e.sender === binding.userMxId &&
  135. e.type === 'm.room.message' && e.content?.body?.includes(path.basename(file))).map(e => e.event_id) : [] });
  136. }
  137. row.recoveryInspection = { checkedAt: new Date().toISOString(), rooms: inspection }; save();
  138. await open(row);
  139. await page.waitForFunction(() => { const e = document.querySelector('textarea'); return e && !e.disabled; });
  140. if (file) {
  141. await page.locator('input[type="file"]').first().setInputFiles(file);
  142. await page.locator('.pending-holds').waitFor({ state: 'visible' });
  143. }
  144. await page.locator('textarea').first().fill(prompt);
  145. row.recoveryAttempted = true; row.recoverySentAt = Date.now(); save();
  146. await page.locator('button.send').click();
  147. await ensureSent(row);
  148. }
  149. return row;
  150. }
  151. if (state[key]?.sendAttempted) {
  152. const recovered = await findThread(marker);
  153. assert.ok(recovered, `Send ${key} was already attempted; inspect evidence before retrying`);
  154. state[key] = { ...state[key], roomId: recovered.roomId, threadRoot: recovered.threadRoot }; save();
  155. return state[key];
  156. }
  157. await page.goto(base + '/desktop/chat/' + canonical + '/new', { waitUntil: 'domcontentloaded' });
  158. await page.waitForFunction(() => { const e = document.querySelector('textarea'); return e && !e.disabled; });
  159. if (file) {
  160. await page.locator('input[type="file"]').first().setInputFiles(file);
  161. await page.locator('.pending-holds').waitFor({ state: 'visible' });
  162. }
  163. await page.locator('textarea').first().fill(prompt);
  164. state[key] = { marker, sendAttempted: true, sentAt: Date.now() }; save();
  165. await page.locator('button.send').click();
  166. let thread;
  167. for (let i = 0; i < 30 && !thread; i++) {
  168. const routeRoot = decodeURIComponent(new URL(page.url()).pathname.split('/').at(-1) || '');
  169. thread = await findThread(marker, routeRoot.startsWith('$') ? routeRoot : undefined);
  170. if (!thread) await sleep(1000);
  171. }
  172. assert.ok(thread?.roomId, `${key}: UI session must be persisted`);
  173. state[key] = { ...state[key], roomId: thread.roomId, threadRoot: thread.threadRoot }; save();
  174. await ensureSent(state[key]);
  175. console.log(JSON.stringify({ check: 'ui-send-' + key, roomId: thread.roomId, pass: true }));
  176. return state[key];
  177. }
  178. async function ensureSent(row) {
  179. for (let i = 0; i < 30; i++) {
  180. const sent = (await events(row.roomId)).find(e => e.sender === binding.userMxId &&
  181. e.type === 'm.room.message' && e.content?.body?.includes(row.marker));
  182. if (sent) { row.sentEventId = sent.event_id; save(); return; }
  183. await sleep(1000);
  184. }
  185. throw Error(`No Matrix send receipt for ${row.marker}; do not navigate away or silently resend`);
  186. }
  187. async function completed(row) {
  188. if (row.proof) return row.proof;
  189. const timeout = Number(process.env.FMODE_E2E_TASK_TIMEOUT_MS || 360000);
  190. assert.ok(Number.isFinite(timeout) && timeout > 0 && timeout <= 900000, 'Task timeout must be 1..900000ms');
  191. const deadline = Date.now() + timeout;
  192. let nextLog = 0;
  193. while (Date.now() < deadline) {
  194. const all = await events(row.roomId);
  195. const sent = all.find(e => e.sender === binding.userMxId && e.type === 'm.room.message' && e.content?.body?.includes(row.marker));
  196. const reply = all.find(e => e.sender === binding.agentMxId && e.type === 'm.room.message' &&
  197. e.origin_server_ts >= (sent?.origin_server_ts || 0) &&
  198. e.content?.['fmode.kind'] !== 'process' && e.content?.body?.includes(row.marker));
  199. const targets = [sent?.event_id, reply?.event_id].filter(Boolean);
  200. const done = all.find(e => e.sender === binding.agentMxId && e.type === 'm.reaction' &&
  201. e.origin_server_ts >= (reply?.origin_server_ts || sent?.origin_server_ts || 0) &&
  202. e.content?.['m.relates_to']?.key === '✅' && targets.includes(e.content['m.relates_to'].event_id));
  203. if (sent && reply && done) {
  204. const process = all.filter(e => e.sender === binding.agentMxId && e.type === 'm.room.message' && e.content?.['fmode.kind'] === 'process');
  205. row.proof = { sent: sent.event_id, reply: reply.event_id, completion: done.event_id,
  206. body: reply.content.body, processCount: process.length,
  207. threadBoundProcessCount: process.filter(e => e.content?.['m.relates_to']?.event_id === row.threadRoot).length };
  208. fs.writeFileSync(path.join(dir, row.marker + '-events.json'), JSON.stringify(all, null, 2));
  209. save(); return row.proof;
  210. }
  211. if (Date.now() > nextLog) { console.log(JSON.stringify({ waitingFor: row.marker, targetEvents: all.filter(e => e.sender === binding.agentMxId).length })); nextLog = Date.now() + 30000; }
  212. await sleep(2500);
  213. }
  214. throw Error(`No authenticated reply + completion for ${row.marker}`);
  215. }
  216. try {
  217. if (phase === 'isolation') {
  218. const ma = 'ACCEPT_A_' + state.run, mb = 'ACCEPT_B_' + state.run;
  219. const a = await sendNew('A', ma, `${ma}:验收任务,请分三次独立的工具调用,分别读取当前时间、查看当前工作目录、计算12345乘6789。不要修改已有文件或配置。最终回复必须包含 ${ma} 和计算结果。`);
  220. const b = await sendNew('B', mb, `只回复 ${mb},不要回复其他内容。`);
  221. const pa = await completed(a), pb = await completed(b);
  222. assert.notEqual(a.roomId, b.roomId);
  223. assert.ok(pa.processCount >= 3, 'Three separate calls must retain their process events');
  224. assert.ok(pa.body.replace(/[,,\s]/g, '').includes(String(12345 * 6789)), 'Calculation result required');
  225. await open(b);
  226. await page.locator('app-assistant-turn').filter({ hasText: mb }).first().waitFor({ state: 'visible' });
  227. assert.ok(!(await page.locator('app-assistant-turn').allTextContents()).some(s => s.includes(ma)), 'A leaked into B');
  228. await page.screenshot({ path: path.join(dir, '09-isolation-B.png'), fullPage: true });
  229. await open(a);
  230. await page.locator('app-assistant-turn').filter({ hasText: ma }).first().waitFor({ state: 'visible' });
  231. assert.ok(!(await page.locator('app-assistant-turn').allTextContents()).some(s => s.includes(mb)), 'B leaked into A');
  232. await page.screenshot({ path: path.join(dir, '10-isolation-A.png'), fullPage: true });
  233. state.isolationPassed = true; save();
  234. console.log(JSON.stringify({ check: 'real-two-session-isolation', processEvents: pa.processCount,
  235. threadBoundProcessEvents: pa.threadBoundProcessCount, completionVerified: true, pass: true }));
  236. } else if (phase === 'files' || phase === 'files-fresh' || phase === 'files-repair') {
  237. const repair = phase === 'files-repair';
  238. const key = repair ? 'filesRepaired' : phase === 'files-fresh' ? 'filesFresh' : 'files';
  239. const run = state.run + (phase !== 'files' ? '_fresh' : '');
  240. const marker = 'ACCEPT_FILE_' + run + (repair ? '_repair1' : ''), content = 'INPUT_EVIDENCE_' + run;
  241. const input = path.join(dir, 'input-' + run + '.txt');
  242. fs.writeFileSync(input, '这是本轮专用验收输入,编号:' + content + '\n', 'utf8');
  243. const stem = 'acceptance-' + run;
  244. if (repair && !state[key]) {
  245. assert.ok(state.filesFresh?.roomId && state.filesFresh?.sentEventId, 'Repair only the already verified dedicated file session');
  246. assert.notEqual(state.filesFresh.roomId, binding.roomId, 'Never repair by sending into the initial room');
  247. state[key] = { marker, roomId: state.filesFresh.roomId, threadRoot: state.filesFresh.threadRoot,
  248. preparedAt: new Date().toISOString(), reason: 'Runtime parent permissions corrected; retry only the two existing test deliverables' };
  249. save();
  250. }
  251. const repairPrompt = `${marker}:继续本会话刚才的两份测试成果 /opt/data/work/deliverables/${stem}.md 和 ${stem}.html。读取并确认输入编号 ${content},在两份测试文件各追加一行“自动上云复验 ${marker}”,通过正常文件交付流程完成自动上云和本会话登记,返回可打开的两个成果。不要手工导入或调用底层上传函数,不要修改任何配置、脚本或其他文件,不要删除文件。最终回复必须包含 ${marker} 和 ${content}。`;
  252. const row = await sendNew(key, marker,
  253. repair ? repairPrompt : `${marker}:读取我刚上传的文本,复述其中编号。在 /opt/data/work/deliverables/ 创建 ${stem}.md 和 ${stem}.html,两个文件均写入输入中的完整编号及“文件链路验收通过”。完成真实上云后返回两个可打开的链接。不要修改其他文件、配置或删除输入。最终回复必须包含 ${marker} 和输入编号。`, repair ? undefined : input);
  254. const proof = await completed(row);
  255. assert.ok(proof.body.includes(content), 'Agent must read the actual uploaded input');
  256. const fileEvents = await events(row.roomId);
  257. const inputEvent = fileEvents.find(e => e.sender === binding.userMxId && e.type === 'm.room.message' &&
  258. e.content?.body?.includes(path.basename(input)) && e.content?.['m.relates_to']?.event_id === row.threadRoot);
  259. assert.ok(inputEvent, 'Input attachment and instruction must arrive in this exact session room');
  260. assert.notEqual(row.roomId, binding.roomId, 'File acceptance requires a dedicated session room');
  261. if (row.recoverySentAt) {
  262. const leaked = (await events(binding.roomId)).filter(e => e.sender === binding.userMxId &&
  263. e.origin_server_ts >= row.recoverySentAt && (e.content?.body?.includes(marker) || e.content?.body?.includes(path.basename(input))));
  264. assert.equal(leaked.length, 0, 'Recovery must not leak input/instruction into the initial room');
  265. }
  266. row.inputEventId = inputEvent.event_id; save();
  267. const sessionToken = account.token || JSON.parse(fs.readFileSync(path.join(dir, 'browser-state.json'))).origins
  268. .flatMap(o => o.localStorage).find(k => k.name === 'fmode_session_token')?.value;
  269. const r = await fetch('https://server.fmode.cn/api/functions', {
  270. method: 'POST', headers: { 'Content-Type': 'application/json' },
  271. body: JSON.stringify({ id: 'THXAOGKiPK', token: sessionToken,
  272. params: { action: 'listBySession', roomId: row.roomId, limit: 100 } }), signal: AbortSignal.timeout(20000),
  273. });
  274. const body = await r.json(); assert.equal(body.code, 200, 'File registration readback must succeed');
  275. fs.writeFileSync(path.join(dir, key + '-file-hub-readback.json'), JSON.stringify(body, null, 2));
  276. const registered = (body.files || []).filter(f => [stem + '.md', stem + '.html'].includes(f.name));
  277. // 接口兼容合并新文件台账与旧成果表,同 URL 可能有两条来源记录。
  278. const files = [...new Map(registered.map(f => [f.url, f])).values()];
  279. assert.equal(files.length, 2, 'Both distinct cloud outputs must be registered in this exact session');
  280. assert.equal(new Set(files.map(f => f.name)).size, 2, 'Both expected file names are required');
  281. for (const file of files) {
  282. assert.ok(file.url.startsWith('https://s3.fmode.cn/') || file.url.startsWith('https://file-cloud.fmode.cn/'));
  283. const response = await fetch(file.url, { signal: AbortSignal.timeout(30000) });
  284. assert.ok(response.ok, 'Cloud file must be downloadable');
  285. const text = await response.text(); assert.ok(text.includes(content), 'Cloud file content must match the input');
  286. }
  287. const mobile = process.argv.includes('--mobile');
  288. if (mobile) await page.setViewportSize({ width: 390, height: 844 });
  289. await open(row, mobile); await page.reload({ waitUntil: 'domcontentloaded' });
  290. const resultTurn = page.locator('app-assistant-turn').filter({ hasText: marker }).last();
  291. await resultTurn.waitFor({ state: 'visible', timeout: 60000 });
  292. for (const file of files) {
  293. const displayName = decodeURIComponent(new URL(file.url).pathname.split('/').at(-1)).replace(/^\d+-[a-z0-9]{6,}-/i, '');
  294. const button = resultTurn.getByRole('button', { name: '预览 ' + displayName, exact: true });
  295. await button.waitFor({ state: 'visible', timeout: 60000 });
  296. assert.equal(await button.count(), 1, 'Each current-round file must render exactly one card');
  297. await button.click();
  298. const dialog = page.getByRole('dialog', { name: '预览 ' + displayName, exact: true });
  299. await dialog.waitFor({ state: 'visible' });
  300. if (file.name.endsWith('.md')) await dialog.getByText(content, { exact: false }).first().waitFor({ state: 'visible' });
  301. else await dialog.frameLocator('iframe').locator('body').getByText(content, { exact: false }).first().waitFor({ state: 'visible' });
  302. await page.screenshot({ path: path.join(dir, (mobile ? 'mobile-' : '') + (file.name.endsWith('.md') ? '11-file-markdown.png' : '12-file-html.png')), fullPage: true });
  303. // HTML iframe 内的按键不会冒泡到外层,使用用户可见的关闭入口。
  304. const close = dialog.getByRole('button', { name: '关闭预览', exact: true });
  305. if (!(await close.isVisible())) await dialog.getByRole('button', { name: '回到右侧', exact: true }).click();
  306. await close.click();
  307. await dialog.waitFor({ state: 'hidden' });
  308. }
  309. state[key + (mobile ? 'MobilePassed' : 'Passed')] = true;
  310. state[key + 'OutputFiles'] = files.map(({ name, url, id }) => ({ name, url, id })); save();
  311. console.log(JSON.stringify({ check: 'real-upload-cloud-registration-reload-and-preview', outputs: files.map(f => f.name), pass: true }));
  312. } else throw Error('Unknown stage');
  313. assert.deepEqual(errors, [], 'Browser page errors');
  314. await context.storageState({ path: path.join(dir, 'browser-state.json') });
  315. } catch (error) {
  316. await page.screenshot({ path: path.join(dir, phase + '-failure.png'), fullPage: true }).catch(() => {});
  317. fs.writeFileSync(path.join(dir, phase + '-failure.json'), JSON.stringify({ error: error.message, url: page.url(), pageErrors: errors }, null, 2));
  318. throw error;
  319. } finally { await browser.close(); }