verify-new-account-desktop.mjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. /** 当前账号PC共享流程;真实动作先登记,默认status不启动浏览器或发送。 */
  2. import fs from 'node:fs';
  3. import assert from 'node:assert/strict';
  4. import { createHash } from 'node:crypto';
  5. import { spawn } from 'node:child_process';
  6. import { chromium } from 'playwright';
  7. import { recordProgress } from './lib/project-recovery.mjs';
  8. import { readMatrixHistory, taskProof, retainFirstProof } from './lib/acceptance-evidence.mjs';
  9. const out = 'test-results/new-account-20261128', privateDir = '.local-backup/new-account-20261128';
  10. const stage = process.argv.find(x => x.startsWith('--stage='))?.slice(8) || 'status';
  11. const stateFile = out + '/state.json', lockFile = out + '/runner.lock';
  12. const base = 'http://127.0.0.1:51756';
  13. const evidenceSuffix = stage === 'continue' ? '-continue-' + Date.now() : '';
  14. let state, lock, browser, server, page, serverLog;
  15. const save = () => { fs.writeFileSync(stateFile + '.next', JSON.stringify(state, null, 2)); fs.renameSync(stateFile + '.next', stateFile); };
  16. const note = text => recordProgress(process.cwd(), '[PC续验] ' + text);
  17. const begin = (key, target, extra = {}) => {
  18. assert.ok(!state.actions[key]?.attempted, key + '已有动作记录,先status/verify核实,不得重复发送或启动');
  19. state.actions[key] = { attempted: true, at: new Date().toISOString(), target, ...extra }; save(); note('准备执行' + key + ',目标' + target);
  20. };
  21. const done = (key, receipt) => { Object.assign(state.actions[key], { confirmedAt: new Date().toISOString(), receipt }); save(); note(key + '已回验,证据' + JSON.stringify(receipt)); };
  22. const check = (name, pass, details) => { state.checks.push({ name, pass: !!pass, at: new Date().toISOString(), details }); save(); assert.ok(pass, name); };
  23. const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
  24. const digest = bytes => createHash('sha256').update(bytes).digest('hex');
  25. const account = JSON.parse(fs.readFileSync(privateDir + '/account.json'));
  26. async function api(id, params) {
  27. const response = await fetch('https://server.fmode.cn/api/functions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Parse-Application-Id': 'ncloudmaster', 'X-Parse-Session-Token': account.token }, body: JSON.stringify({ id, token: account.token, params: id === 'THXAOGKiPK' ? { ...params, token: account.token } : params }), signal: AbortSignal.timeout(25000) });
  28. assert.ok(response.ok); const data = await response.json(); assert.equal(data.code, 200, data.msg || data.mess); return data;
  29. }
  30. async function binding() {
  31. const cfg = JSON.parse(fs.readFileSync('.claude/dev-login.json'));
  32. const url = new URL('https://server.fmode.cn/parse/classes/FmodeMatrixBinding');
  33. url.searchParams.set('where', JSON.stringify({ userPointer: { __type: 'Pointer', className: '_User', objectId: state.userId }, agentId: state.trial.agentId, status: 'active' }));
  34. const response = await fetch(url, { headers: { 'X-Parse-Application-Id': 'ncloudmaster', 'X-Parse-Master-Key': cfg.masterKey }, signal: AbortSignal.timeout(20000) });
  35. assert.ok(response.ok); const rows = (await response.json()).results; assert.equal(rows?.length, 1); return rows[0];
  36. }
  37. async function proveReuse(timeout = 240000) {
  38. const action = state.actions.desktopReuse; assert.ok(action?.attempted);
  39. const b = await binding(), stamp = Date.now() + '-' + process.pid; let n = 0;
  40. const deadline = Date.now() + timeout;
  41. while (Date.now() < deadline) {
  42. const history = await readMatrixHistory(b, action.roomId);
  43. const evidenceFile = 'desktopReuse-readback-' + stamp + '-' + n++ + '.json';
  44. fs.writeFileSync(out + '/' + evidenceFile, JSON.stringify(history, null, 2), { flag: 'wx' });
  45. (action.observations ??= []).push({ at: new Date().toISOString(), evidenceFile }); save();
  46. const proof = taskProof(history.events, b, action);
  47. if (proof) {
  48. retainFirstProof(action, { ...proof, evidenceFile, observedAt: new Date().toISOString() }); save();
  49. const first = out + '/desktopReuse-events.json'; if (!fs.existsSync(first)) fs.writeFileSync(first, JSON.stringify(history.events, null, 2), { flag: 'wx' });
  50. check('PC单次输入、目标回复及真实结束回执', true, { sent: proof.sent, completion: proof.completion, evidenceFile });
  51. return action;
  52. }
  53. await pause(2500);
  54. }
  55. throw Error('PC任务缺少完整回执;只允许verify,不重复发送');
  56. }
  57. async function openTask(task) {
  58. await page.goto(base + '/desktop/chat/' + state.trial.agentId + '/' + encodeURIComponent(task.threadRoot), { waitUntil: 'domcontentloaded' });
  59. await page.waitForFunction(() => document.querySelector('textarea') && !document.querySelector('textarea').disabled, undefined, { timeout: 60000 });
  60. await page.locator('app-assistant-turn').filter({ hasText: task.marker }).first().waitFor({ state: 'visible', timeout: 60000 });
  61. }
  62. async function preview(name, marker) {
  63. await page.getByRole('button', { name: '预览 ' + name, exact: true }).first().click();
  64. const dialog = page.getByRole('dialog', { name: '预览 ' + name, exact: true }); await dialog.waitFor({ state: 'visible' });
  65. if (name.endsWith('.md')) await dialog.getByText(marker, { exact: false }).first().waitFor({ state: 'visible' });
  66. else if (name.endsWith('.html')) {
  67. await page.frameLocator('iframe.fp-html').getByText(marker, { exact: false }).first().waitFor({ state: 'visible', timeout: 45000 });
  68. await dialog.locator('.fp-html-loading, .fp-html-stall').waitFor({ state: 'detached', timeout: 45000 });
  69. } else {
  70. await dialog.locator('canvas').first().waitFor({ state: 'visible', timeout: 60000 });
  71. await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)))));
  72. const dark = await dialog.locator('canvas').first().evaluate(canvas => { const data = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).data; let n = 0; for (let i = 0; i < data.length; i += 16) if (data[i + 3] && Math.max(data[i], data[i + 1], data[i + 2]) < 200) n++; return n; });
  73. assert.ok(dark > 25, '文档画布没有真实正文像素');
  74. }
  75. check('PC实际预览 ' + name, true);
  76. await page.screenshot({ path: out + '/pc-preview-' + name.split('.').at(-1) + '-20261129.png', fullPage: true });
  77. let close = dialog.getByRole('button', { name: '关闭预览', exact: true });
  78. if (!(await close.isVisible())) await dialog.getByRole('button', { name: '回到右侧', exact: true }).click();
  79. await close.click(); await dialog.waitFor({ state: 'hidden' });
  80. }
  81. try {
  82. if (stage !== 'status') { lock = fs.openSync(lockFile, 'wx'); fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, stage: 'pc-' + stage })); }
  83. state = JSON.parse(fs.readFileSync(stateFile)); assert.equal(account.userId, state.userId);
  84. if (stage === 'status') console.log(JSON.stringify({ baseline: state.actions.desktopBaseline, reuse: state.actions.desktopReuse }, null, 2));
  85. else if (stage === 'verify') await proveReuse(30000);
  86. else if (stage === 'run' || stage === 'continue') {
  87. if (stage === 'continue') {
  88. assert.ok(state.actions.desktopBaseline?.attempted && !state.actions.desktopBaseline?.confirmedAt, '仅能继续未完成的PC核验');
  89. assert.ok(!state.actions.desktopReuse?.attempted, '已有PC发送动作,先verify核实,不能从头继续');
  90. (state.actions.desktopBaseline.continuations ??= []).push({ at: new Date().toISOString(), reason: '只读页面/登录定位器修复后续验,已确认PC尚无发送动作', noPriorSend: true }); save(); note('PC仅继续未完成的登录/页面核验,原发送阶段未执行;旧日志保留。');
  91. } else begin('desktopBaseline', state.userId + '/' + base + '/生产构建真实Token登录及共享流程');
  92. assert.ok(state.actions.trialFreshChat?.confirmedAt, '先完成新隔离卷真实首报及往返');
  93. assert.equal(await fetch(base).then(() => true).catch(() => false), false, '临时端口已占用,不能借用未知服务');
  94. serverLog = fs.openSync(out + '/pc-static-server-20261129' + evidenceSuffix + '.log', 'wx');
  95. server = spawn(process.execPath, ['scripts/serve-dist.mjs'], { env: { ...process.env, PORT: '51756' }, windowsHide: true, stdio: ['ignore', serverLog, serverLog] });
  96. state.actions.desktopBaseline.serverPid = server.pid; state.actions.desktopBaseline.indexSha256 = digest(fs.readFileSync('dist/fmode-app-v2/browser/index.html')); save();
  97. let available = false;
  98. for (let n = 0; n < 50; n++) { available = await fetch(base).then(r => r.ok).catch(() => false); if (available) break; await pause(200); }
  99. assert.ok(available, '本机生产构建静态服务不可用');
  100. browser = await chromium.launch({ headless: true, executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe' });
  101. const context = await browser.newContext({ viewport: { width: 1440, height: 960 } });
  102. page = await context.newPage(); page.setDefaultTimeout(45000);
  103. const errors = []; page.on('pageerror', error => errors.push(error.message));
  104. await page.goto(base + '/login?redirect=%2Fdesktop%2Fchat', { waitUntil: 'domcontentloaded' });
  105. await page.getByRole('button', { name: 'Token 直登', exact: true }).click();
  106. await page.locator('input[placeholder="r: 开头的会话令牌"]').fill(account.token);
  107. await page.getByRole('button', { name: /^登\s*录$/ }).click();
  108. await page.waitForFunction(id => JSON.parse(localStorage.getItem('fmode_me') || 'null')?.id === id && !location.pathname.includes('login'), state.userId, { timeout: 60000 });
  109. check('PC当前账号通过真实Token表单登录', true, { userId: state.userId });
  110. await context.storageState({ path: privateDir + '/pc-current-browser-state.json' });
  111. for (const [route, label] of [['contacts', '通讯录'], ['workbench', '工作台'], ['mine', '账户中心'], ['my-containers', '我的容器']]) {
  112. await page.goto(base + '/desktop/' + route, { waitUntil: 'domcontentloaded' });
  113. await page.getByText(label, { exact: false }).first().waitFor({ state: 'visible' });
  114. const view = await page.evaluate(() => ({ route: location.pathname, overflow: document.documentElement.scrollWidth > innerWidth, text: document.body.innerText.slice(-4500) }));
  115. check('PC主要入口加载且无横向溢出 ' + route, view.route === '/desktop/' + route && !view.overflow && !/加载失败|登录已失效/.test(view.text), view);
  116. await page.screenshot({ path: out + '/pc-' + route + '-20261129.png', fullPage: true });
  117. }
  118. const files = state.actions.trialFilesV3;
  119. await openTask(files); check('PC回读安卓原会话及成果', true, { roomId: files.roomId });
  120. for (const name of files.expectedFiles) await preview(name, files.inputMarker);
  121. await openTask(state.actions.trialDocuments);
  122. for (const name of state.actions.trialDocuments.expectedFiles) await preview(name.replaceAll('_', '-'), state.actions.trialDocuments.marker);
  123. const source = JSON.parse(fs.readFileSync(out + '/trial-v3-file-hub.json')).find(x => x.url.endsWith('.md'));
  124. const downloaded = await fetch(source.url, { signal: AbortSignal.timeout(20000) }); assert.ok(downloaded.ok);
  125. const sourceBytes = Buffer.from(await downloaded.arrayBuffer()), sourceSha256 = digest(sourceBytes);
  126. const before = await api('THXAOGKiPK', { action: 'listByUrl', url: source.url });
  127. const originalRows = (before.files || []).filter(x => x.roomId === files.roomId);
  128. assert.ok(originalRows.length >= 1, '缺少原成果会话归属');
  129. const marker = state.run + '_PC_REUSE';
  130. begin('desktopReuse', state.trial.agentId + '/跨会话复用原成果URL,PC只发送一次', { marker, roomId: state.actions.trialDocuments.roomId, threadRoot: state.actions.trialDocuments.threadRoot, sourceUrl: source.url, sourceSha256, originalRoomId: files.roomId, originalIds: originalRows.map(x => x.id), phase: 'before-single-send' });
  131. const name = files.expectedFiles.find(x => x.endsWith('.md'));
  132. const prompt = `这是PC跨会话成果复用验收 ${marker}。仅用一次Python标准库urllib从 ${source.url} 读取原始字节,必须先核对SHA256为 ${sourceSha256},再原样write_bytes保存为 /opt/data/work/deliverables/${name},文件名和全部字节完全不变。不要生成其他文件、不要安装依赖、不要改任何配置或插件。现有自动流程应复用同一云端URL并登记本会话。完成后仅回复 ${marker},不自行拼接链接。`;
  133. await page.locator('textarea').fill(prompt); await page.locator('button.send').click();
  134. const action = await proveReuse();
  135. check('新隔离卷跨会话成果复用原URL', action.proof.body.includes(source.url), { sourceUrl: source.url, body: action.proof.body });
  136. await page.locator('app-assistant-turn').filter({ hasText: marker }).first().waitFor({ state: 'visible', timeout: 60000 });
  137. let after;
  138. for (let n = 0; n < 30; n++) { after = await api('THXAOGKiPK', { action: 'listByUrl', url: source.url }); if ((after.files || []).some(x => x.roomId === action.roomId)) break; await pause(1000); }
  139. const targetRows = (after.files || []).filter(x => x.roomId === action.roomId);
  140. check('同URL在新会话有且仅有一份归属且保留原归属', targetRows.length === 1 && originalRows.every(x => (after.files || []).some(y => y.id === x.id && y.roomId === files.roomId)), { original: originalRows.map(x => x.id), target: targetRows.map(x => x.id), url: source.url });
  141. await page.reload({ waitUntil: 'domcontentloaded' });
  142. await page.locator('app-assistant-turn').filter({ hasText: marker }).first().waitFor({ state: 'visible', timeout: 60000 });
  143. check('PC真实发送后刷新仍回读原回复', true);
  144. await page.screenshot({ path: out + '/pc-reuse-roundtrip-20261129.png', fullPage: true });
  145. done('desktopReuse', { proof: action.proof, sourceUrl: source.url, sourceSha256, targetFileId: targetRows[0].id, sends: 1 });
  146. check('PC浏览器无未处理运行异常', errors.length === 0, errors);
  147. done('desktopBaseline', { userId: state.userId, routes: ['contacts', 'workbench', 'mine', 'my-containers'], previews: ['md', 'html', 'pdf', 'docx'], crossDeviceReadback: true, reuseAction: 'desktopReuse', errors, screenshot: 'pc-reuse-roundtrip-20261129.png' });
  148. } else throw Error('未知PC阶段');
  149. } catch (error) {
  150. if (lock !== undefined && state) { state.lastFailure = { stage: 'pc-' + stage, at: new Date().toISOString(), message: error.message }; save(); note('未完成:' + error.message + ';只读核实,不重复发送。'); }
  151. if (page) await page.screenshot({ path: out + '/pc-' + stage + '-failure-20261129.png', fullPage: true }).catch(() => {});
  152. throw error;
  153. } finally {
  154. await browser?.close(); if (server) server.kill(); if (serverLog !== undefined) fs.closeSync(serverLog);
  155. if (lock !== undefined) { fs.closeSync(lock); fs.unlinkSync(lockFile); }
  156. }