| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158 |
- /** 当前账号PC共享流程;真实动作先登记,默认status不启动浏览器或发送。 */
- import fs from 'node:fs';
- import assert from 'node:assert/strict';
- import { createHash } from 'node:crypto';
- import { spawn } from 'node:child_process';
- import { chromium } from 'playwright';
- import { recordProgress } from './lib/project-recovery.mjs';
- import { readMatrixHistory, taskProof, retainFirstProof } from './lib/acceptance-evidence.mjs';
- const out = 'test-results/new-account-20261128', privateDir = '.local-backup/new-account-20261128';
- const stage = process.argv.find(x => x.startsWith('--stage='))?.slice(8) || 'status';
- const stateFile = out + '/state.json', lockFile = out + '/runner.lock';
- const base = 'http://127.0.0.1:51756';
- const evidenceSuffix = stage === 'continue' ? '-continue-' + Date.now() : '';
- let state, lock, browser, server, page, serverLog;
- const save = () => { fs.writeFileSync(stateFile + '.next', JSON.stringify(state, null, 2)); fs.renameSync(stateFile + '.next', stateFile); };
- const note = text => recordProgress(process.cwd(), '[PC续验] ' + text);
- const begin = (key, target, extra = {}) => {
- assert.ok(!state.actions[key]?.attempted, key + '已有动作记录,先status/verify核实,不得重复发送或启动');
- state.actions[key] = { attempted: true, at: new Date().toISOString(), target, ...extra }; save(); note('准备执行' + key + ',目标' + target);
- };
- const done = (key, receipt) => { Object.assign(state.actions[key], { confirmedAt: new Date().toISOString(), receipt }); save(); note(key + '已回验,证据' + JSON.stringify(receipt)); };
- const check = (name, pass, details) => { state.checks.push({ name, pass: !!pass, at: new Date().toISOString(), details }); save(); assert.ok(pass, name); };
- const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
- const digest = bytes => createHash('sha256').update(bytes).digest('hex');
- const account = JSON.parse(fs.readFileSync(privateDir + '/account.json'));
- async function api(id, params) {
- 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) });
- assert.ok(response.ok); const data = await response.json(); assert.equal(data.code, 200, data.msg || data.mess); return data;
- }
- async function binding() {
- const cfg = JSON.parse(fs.readFileSync('.claude/dev-login.json'));
- const url = new URL('https://server.fmode.cn/parse/classes/FmodeMatrixBinding');
- url.searchParams.set('where', JSON.stringify({ userPointer: { __type: 'Pointer', className: '_User', objectId: state.userId }, agentId: state.trial.agentId, status: 'active' }));
- const response = await fetch(url, { headers: { 'X-Parse-Application-Id': 'ncloudmaster', 'X-Parse-Master-Key': cfg.masterKey }, signal: AbortSignal.timeout(20000) });
- assert.ok(response.ok); const rows = (await response.json()).results; assert.equal(rows?.length, 1); return rows[0];
- }
- async function proveReuse(timeout = 240000) {
- const action = state.actions.desktopReuse; assert.ok(action?.attempted);
- const b = await binding(), stamp = Date.now() + '-' + process.pid; let n = 0;
- const deadline = Date.now() + timeout;
- while (Date.now() < deadline) {
- const history = await readMatrixHistory(b, action.roomId);
- const evidenceFile = 'desktopReuse-readback-' + stamp + '-' + n++ + '.json';
- fs.writeFileSync(out + '/' + evidenceFile, JSON.stringify(history, null, 2), { flag: 'wx' });
- (action.observations ??= []).push({ at: new Date().toISOString(), evidenceFile }); save();
- const proof = taskProof(history.events, b, action);
- if (proof) {
- retainFirstProof(action, { ...proof, evidenceFile, observedAt: new Date().toISOString() }); save();
- const first = out + '/desktopReuse-events.json'; if (!fs.existsSync(first)) fs.writeFileSync(first, JSON.stringify(history.events, null, 2), { flag: 'wx' });
- check('PC单次输入、目标回复及真实结束回执', true, { sent: proof.sent, completion: proof.completion, evidenceFile });
- return action;
- }
- await pause(2500);
- }
- throw Error('PC任务缺少完整回执;只允许verify,不重复发送');
- }
- async function openTask(task) {
- await page.goto(base + '/desktop/chat/' + state.trial.agentId + '/' + encodeURIComponent(task.threadRoot), { waitUntil: 'domcontentloaded' });
- await page.waitForFunction(() => document.querySelector('textarea') && !document.querySelector('textarea').disabled, undefined, { timeout: 60000 });
- await page.locator('app-assistant-turn').filter({ hasText: task.marker }).first().waitFor({ state: 'visible', timeout: 60000 });
- }
- async function preview(name, marker) {
- await page.getByRole('button', { name: '预览 ' + name, exact: true }).first().click();
- const dialog = page.getByRole('dialog', { name: '预览 ' + name, exact: true }); await dialog.waitFor({ state: 'visible' });
- if (name.endsWith('.md')) await dialog.getByText(marker, { exact: false }).first().waitFor({ state: 'visible' });
- else if (name.endsWith('.html')) {
- await page.frameLocator('iframe.fp-html').getByText(marker, { exact: false }).first().waitFor({ state: 'visible', timeout: 45000 });
- await dialog.locator('.fp-html-loading, .fp-html-stall').waitFor({ state: 'detached', timeout: 45000 });
- } else {
- await dialog.locator('canvas').first().waitFor({ state: 'visible', timeout: 60000 });
- await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)))));
- 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; });
- assert.ok(dark > 25, '文档画布没有真实正文像素');
- }
- check('PC实际预览 ' + name, true);
- await page.screenshot({ path: out + '/pc-preview-' + name.split('.').at(-1) + '-20261129.png', fullPage: true });
- let 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' });
- }
- try {
- if (stage !== 'status') { lock = fs.openSync(lockFile, 'wx'); fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, stage: 'pc-' + stage })); }
- state = JSON.parse(fs.readFileSync(stateFile)); assert.equal(account.userId, state.userId);
- if (stage === 'status') console.log(JSON.stringify({ baseline: state.actions.desktopBaseline, reuse: state.actions.desktopReuse }, null, 2));
- else if (stage === 'verify') await proveReuse(30000);
- else if (stage === 'run' || stage === 'continue') {
- if (stage === 'continue') {
- assert.ok(state.actions.desktopBaseline?.attempted && !state.actions.desktopBaseline?.confirmedAt, '仅能继续未完成的PC核验');
- assert.ok(!state.actions.desktopReuse?.attempted, '已有PC发送动作,先verify核实,不能从头继续');
- (state.actions.desktopBaseline.continuations ??= []).push({ at: new Date().toISOString(), reason: '只读页面/登录定位器修复后续验,已确认PC尚无发送动作', noPriorSend: true }); save(); note('PC仅继续未完成的登录/页面核验,原发送阶段未执行;旧日志保留。');
- } else begin('desktopBaseline', state.userId + '/' + base + '/生产构建真实Token登录及共享流程');
- assert.ok(state.actions.trialFreshChat?.confirmedAt, '先完成新隔离卷真实首报及往返');
- assert.equal(await fetch(base).then(() => true).catch(() => false), false, '临时端口已占用,不能借用未知服务');
- serverLog = fs.openSync(out + '/pc-static-server-20261129' + evidenceSuffix + '.log', 'wx');
- server = spawn(process.execPath, ['scripts/serve-dist.mjs'], { env: { ...process.env, PORT: '51756' }, windowsHide: true, stdio: ['ignore', serverLog, serverLog] });
- state.actions.desktopBaseline.serverPid = server.pid; state.actions.desktopBaseline.indexSha256 = digest(fs.readFileSync('dist/fmode-app-v2/browser/index.html')); save();
- let available = false;
- for (let n = 0; n < 50; n++) { available = await fetch(base).then(r => r.ok).catch(() => false); if (available) break; await pause(200); }
- assert.ok(available, '本机生产构建静态服务不可用');
- 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 } });
- page = await context.newPage(); page.setDefaultTimeout(45000);
- const errors = []; page.on('pageerror', error => errors.push(error.message));
- await page.goto(base + '/login?redirect=%2Fdesktop%2Fchat', { waitUntil: 'domcontentloaded' });
- await page.getByRole('button', { name: 'Token 直登', exact: true }).click();
- await page.locator('input[placeholder="r: 开头的会话令牌"]').fill(account.token);
- await page.getByRole('button', { name: /^登\s*录$/ }).click();
- await page.waitForFunction(id => JSON.parse(localStorage.getItem('fmode_me') || 'null')?.id === id && !location.pathname.includes('login'), state.userId, { timeout: 60000 });
- check('PC当前账号通过真实Token表单登录', true, { userId: state.userId });
- await context.storageState({ path: privateDir + '/pc-current-browser-state.json' });
- for (const [route, label] of [['contacts', '通讯录'], ['workbench', '工作台'], ['mine', '账户中心'], ['my-containers', '我的容器']]) {
- await page.goto(base + '/desktop/' + route, { waitUntil: 'domcontentloaded' });
- await page.getByText(label, { exact: false }).first().waitFor({ state: 'visible' });
- const view = await page.evaluate(() => ({ route: location.pathname, overflow: document.documentElement.scrollWidth > innerWidth, text: document.body.innerText.slice(-4500) }));
- check('PC主要入口加载且无横向溢出 ' + route, view.route === '/desktop/' + route && !view.overflow && !/加载失败|登录已失效/.test(view.text), view);
- await page.screenshot({ path: out + '/pc-' + route + '-20261129.png', fullPage: true });
- }
- const files = state.actions.trialFilesV3;
- await openTask(files); check('PC回读安卓原会话及成果', true, { roomId: files.roomId });
- for (const name of files.expectedFiles) await preview(name, files.inputMarker);
- await openTask(state.actions.trialDocuments);
- for (const name of state.actions.trialDocuments.expectedFiles) await preview(name.replaceAll('_', '-'), state.actions.trialDocuments.marker);
- const source = JSON.parse(fs.readFileSync(out + '/trial-v3-file-hub.json')).find(x => x.url.endsWith('.md'));
- const downloaded = await fetch(source.url, { signal: AbortSignal.timeout(20000) }); assert.ok(downloaded.ok);
- const sourceBytes = Buffer.from(await downloaded.arrayBuffer()), sourceSha256 = digest(sourceBytes);
- const before = await api('THXAOGKiPK', { action: 'listByUrl', url: source.url });
- const originalRows = (before.files || []).filter(x => x.roomId === files.roomId);
- assert.ok(originalRows.length >= 1, '缺少原成果会话归属');
- const marker = state.run + '_PC_REUSE';
- 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' });
- const name = files.expectedFiles.find(x => x.endsWith('.md'));
- const prompt = `这是PC跨会话成果复用验收 ${marker}。仅用一次Python标准库urllib从 ${source.url} 读取原始字节,必须先核对SHA256为 ${sourceSha256},再原样write_bytes保存为 /opt/data/work/deliverables/${name},文件名和全部字节完全不变。不要生成其他文件、不要安装依赖、不要改任何配置或插件。现有自动流程应复用同一云端URL并登记本会话。完成后仅回复 ${marker},不自行拼接链接。`;
- await page.locator('textarea').fill(prompt); await page.locator('button.send').click();
- const action = await proveReuse();
- check('新隔离卷跨会话成果复用原URL', action.proof.body.includes(source.url), { sourceUrl: source.url, body: action.proof.body });
- await page.locator('app-assistant-turn').filter({ hasText: marker }).first().waitFor({ state: 'visible', timeout: 60000 });
- let after;
- 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); }
- const targetRows = (after.files || []).filter(x => x.roomId === action.roomId);
- 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 });
- await page.reload({ waitUntil: 'domcontentloaded' });
- await page.locator('app-assistant-turn').filter({ hasText: marker }).first().waitFor({ state: 'visible', timeout: 60000 });
- check('PC真实发送后刷新仍回读原回复', true);
- await page.screenshot({ path: out + '/pc-reuse-roundtrip-20261129.png', fullPage: true });
- done('desktopReuse', { proof: action.proof, sourceUrl: source.url, sourceSha256, targetFileId: targetRows[0].id, sends: 1 });
- check('PC浏览器无未处理运行异常', errors.length === 0, errors);
- 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' });
- } else throw Error('未知PC阶段');
- } catch (error) {
- if (lock !== undefined && state) { state.lastFailure = { stage: 'pc-' + stage, at: new Date().toISOString(), message: error.message }; save(); note('未完成:' + error.message + ';只读核实,不重复发送。'); }
- if (page) await page.screenshot({ path: out + '/pc-' + stage + '-failure-20261129.png', fullPage: true }).catch(() => {});
- throw error;
- } finally {
- await browser?.close(); if (server) server.kill(); if (serverLog !== undefined) fs.closeSync(serverLog);
- if (lock !== undefined) { fs.closeSync(lock); fs.unlinkSync(lockFile); }
- }
|