verify-full-flow.mjs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. /** PC 与安卓真机续验。只使用已授权的独立账号/容器;发送前落盘,恢复只读核实。 */
  2. import fs from 'node:fs';
  3. import path from 'node:path';
  4. import assert from 'node:assert/strict';
  5. import { execFileSync } from 'node:child_process';
  6. import { chromium } from 'playwright';
  7. import { connectWebView } from './android-webview-cdp.mjs';
  8. const out = path.resolve('test-results/full-flow-20261128');
  9. const privateDir = path.resolve('.local-backup/full-flow-20261128');
  10. fs.mkdirSync(out, { recursive: true }); fs.mkdirSync(privateDir, { recursive: true });
  11. const priorDir = '.local-backup/acceptance-20261128';
  12. const account = JSON.parse(fs.readFileSync(`${priorDir}/account.json`, 'utf8'));
  13. const prior = JSON.parse(fs.readFileSync(`${priorDir}/acceptance-state.json`, 'utf8'));
  14. const cfg = JSON.parse(fs.readFileSync('.claude/dev-login.json', 'utf8'));
  15. const agent = 'agent-node-app-' + account.agentId.toLowerCase();
  16. assert.equal(agent, 'agent-node-app-dw20i0uvpx'); assert.equal(account.jobId, 'QxB0R9BeWv');
  17. const stage = process.argv.find(a => a.startsWith('--stage='))?.slice(8) || 'status';
  18. const stateFile = `${out}/flow-state.json`;
  19. const state = fs.existsSync(stateFile) ? JSON.parse(fs.readFileSync(stateFile)) : {
  20. run: 'FLOW_' + Date.now().toString(36), userId: account.id, agent, checks: [], data: [],
  21. };
  22. const save = () => { fs.writeFileSync(stateFile + '.next', JSON.stringify(state, null, 2)); fs.renameSync(stateFile + '.next', stateFile); };
  23. const check = (name, valid, details) => {
  24. state.checks.push({ name, pass: !!valid, at: new Date().toISOString(), ...(details ? { details } : {}) }); save();
  25. console.log(JSON.stringify(state.checks.at(-1))); assert.ok(valid, name);
  26. };
  27. const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
  28. const headers = { 'X-Parse-Application-Id': 'ncloudmaster', 'X-Parse-Master-Key': cfg.masterKey };
  29. async function records(cls, where) {
  30. const url = new URL('https://server.fmode.cn/parse/classes/' + cls);
  31. url.searchParams.set('where', JSON.stringify(where)); url.searchParams.set('limit', '1000');
  32. const response = await fetch(url, { headers, signal: AbortSignal.timeout(20000) });
  33. assert.ok(response.ok, `读取 ${cls}: ${response.status}`);
  34. const body = await response.json(); assert.ok(!body.error, body.error); return body.results || [];
  35. }
  36. async function binding() {
  37. const rows = await records('FmodeMatrixBinding', { userPointer: { __type: 'Pointer', className: '_User', objectId: account.id }, agentId: agent, status: 'active' });
  38. assert.equal(rows.length, 1); assert.ok(rows[0].accessToken); return rows[0];
  39. }
  40. const threads = () => records('FmodeChatThread', { user: { __type: 'Pointer', className: '_User', objectId: account.id }, agentId: agent });
  41. async function roomEvents(b, roomId) {
  42. const response = await fetch(b.homeserver + '/_matrix/client/v3/rooms/' + encodeURIComponent(roomId) + '/messages?dir=b&limit=200', {
  43. headers: { Authorization: 'Bearer ' + b.accessToken }, signal: AbortSignal.timeout(20000),
  44. });
  45. assert.ok(response.ok, `事件回读: ${response.status}`); return (await response.json()).chunk || [];
  46. }
  47. async function proof(key, timeout = 180000) {
  48. const b = await binding(); const row = state[key]; assert.ok(row?.attempted, '发送动作必须先有账本');
  49. const deadline = Date.now() + timeout;
  50. while (Date.now() < deadline) {
  51. if (!row.roomId) {
  52. const found = (await threads()).find(t => !t.isDeleted && (t.threadRoot === row.threadRoot || t.lastPreview?.includes(row.marker)));
  53. if (found) { Object.assign(row, { roomId: found.roomId, threadRoot: found.threadRoot, id: found.objectId }); save(); }
  54. }
  55. if (row.roomId) {
  56. const events = await roomEvents(b, row.roomId);
  57. const sent = events.filter(e => e.sender === b.userMxId && e.type === 'm.room.message' && e.content?.body?.includes(row.marker));
  58. const reply = events.find(e => e.sender === b.agentMxId && e.type === 'm.room.message' && e.content?.['fmode.kind'] !== 'process' && e.content?.body?.includes(row.marker) && e.origin_server_ts >= (sent[0]?.origin_server_ts || Infinity));
  59. const done = events.find(e => e.sender === b.agentMxId && e.type === 'm.reaction' && e.content?.['m.relates_to']?.key === '✅' && [sent[0]?.event_id, reply?.event_id].filter(Boolean).includes(e.content?.['m.relates_to']?.event_id));
  60. row.sentIds = sent.map(e => e.event_id); save();
  61. if (sent.length && reply && done) {
  62. row.proof = { sent: sent.map(e => e.event_id), reply: reply.event_id, completion: done.event_id, body: reply.content.body };
  63. fs.writeFileSync(`${out}/${key}-events.json`, JSON.stringify(events, null, 2)); save();
  64. check(key + ' 真实发送/目标回复/✅', true, row.proof); check(key + ' 输入消息只发送一次', sent.length === 1);
  65. return row;
  66. }
  67. }
  68. await pause(2500);
  69. }
  70. throw Error(key + ' 尚未收到完整回执;恢复只能 --stage=status,禁止重新发送');
  71. }
  72. function recordAttempt(key, marker, details = {}) {
  73. assert.ok(!state[key]?.attempted, `${key} 已有动作记录,请用 status 核实,不可重发`);
  74. state[key] = { marker, attempted: true, at: new Date().toISOString(), ...details };
  75. state.data.push({ kind: 'message-task', key, marker, agent, pending: true }); save();
  76. }
  77. let native, browser;
  78. async function mobile() { return native ??= await connectWebView(); }
  79. async function navigateMobile(route) {
  80. const c = await mobile();
  81. // 原生 WebView 的 URL 资源拦截器不等同于 SPA 服务器;先加载入口,再经路由事件跳转。
  82. if (!(await c.evaluate(() => location.origin === 'https://localhost' && !!document.querySelector('app-root')?.children.length))) {
  83. await c.send('Page.navigate', { url: 'https://localhost/' });
  84. await c.waitFor(() => document.readyState === 'complete' && !!document.querySelector('app-root')?.children.length);
  85. }
  86. await c.evaluate(route => { history.pushState(null, '', route); dispatchEvent(new PopStateEvent('popstate')); }, route);
  87. await c.waitFor(route => decodeURIComponent(location.pathname) === decodeURIComponent(route), route);
  88. return c;
  89. }
  90. const chatRoute = row => '/mobile/chat/' + agent + '/' + encodeURIComponent(row.threadRoot);
  91. async function shot(name) { await (await mobile()).screenshot(`${out}/${name}.png`); }
  92. async function closePreview() {
  93. const c = await mobile();
  94. await c.evaluate(() => document.querySelector('[role="dialog"][aria-label^="预览 "] [aria-label="关闭预览"]')?.click());
  95. await c.waitFor(() => !document.querySelector('[role="dialog"][aria-label^="预览 "]'));
  96. }
  97. try {
  98. save();
  99. if (stage === 'baseline' || stage === 'status') {
  100. const list = await threads(); const b = await binding();
  101. const inventory = { at: new Date().toISOString(), userId: account.id, agent, initialRoom: b.roomId, threads: list };
  102. fs.writeFileSync(`${out}/${stage}-inventory.json`, JSON.stringify(inventory, null, 2));
  103. console.log(JSON.stringify({ stage, userId: account.id, agent, threads: list.map(t => ({ id: t.objectId, roomId: t.roomId, root: t.threadRoot, deleted: !!t.isDeleted })) }));
  104. if (stage === 'baseline') { assert.ok(!state.baseline); state.baseline = inventory; save(); }
  105. else for (const key of ['mobileSend', 'offlineSend', 'pcSend']) if (state[key]?.attempted && !state[key]?.proof) await proof(key, 15000);
  106. } else if (stage === 'mobile-login') {
  107. const c = await mobile();
  108. await c.evaluate(() => { localStorage.removeItem('fmode_session_token'); localStorage.removeItem('fmode_me'); });
  109. await navigateMobile('/login');
  110. await c.waitFor(() => [...document.querySelectorAll('button')].some(x => x.innerText === '使用账号密码登录'));
  111. await c.evaluate(() => [...document.querySelectorAll('button')].find(x => x.innerText === '使用账号密码登录').click());
  112. await c.fill('input[placeholder="请输入账号"]', account.username);
  113. await c.fill('input[placeholder="请输入密码"]', account.password);
  114. await c.tap('[aria-label="同意协议"]');
  115. await shot('android-password-form');
  116. await c.tap('button.m-btn--primary');
  117. await c.waitFor(() => location.pathname === '/mobile/messages', undefined, 60000);
  118. await c.waitFor(() => document.querySelectorAll('button.m-row').length > 0, undefined, 60000);
  119. const auth = await c.evaluate(() => ({ token: localStorage.getItem('fmode_session_token'), me: JSON.parse(localStorage.getItem('fmode_me')) }));
  120. assert.equal(auth.me.id, account.id);
  121. fs.writeFileSync(`${privateDir}/mobile-auth.json`, JSON.stringify(auth, null, 2));
  122. check('安卓真实账号密码登录并进入会话列表', true, { userId: auth.me.id });
  123. state.data.push({ kind: 'login-session', userId: account.id, source: 'android-password-login', at: new Date().toISOString() }); save();
  124. await shot('android-password-login-success');
  125. } else if (stage === 'mobile-previews') {
  126. const c = await navigateMobile('/mobile/messages');
  127. await c.waitFor(() => [...document.querySelectorAll('button.m-row')].some(x => x.innerText.includes('ACCEPT_FILE_mx0a7xfs_fre')));
  128. await c.evaluate(() => [...document.querySelectorAll('button.m-row')].find(x => x.innerText.includes('ACCEPT_FILE_mx0a7xfs_fre')).click());
  129. await c.waitFor(() => location.pathname.includes('/mobile/chat/'));
  130. if (await c.evaluate(() => !!document.querySelector('[role="dialog"][aria-label^="预览 "]'))) await closePreview();
  131. await c.waitFor(() => document.querySelectorAll('.file-tile').length >= 2, undefined, 60000);
  132. const layout = await c.evaluate(() => {
  133. const back = document.querySelector('[aria-label="返回"]')?.getBoundingClientRect();
  134. const title = document.querySelector('.m-title')?.getBoundingClientRect();
  135. return { back: back && {x:back.x,right:back.right,width:back.width,height:back.height}, title: title && {x:title.x,right:title.right}, overflow: document.documentElement.scrollWidth > innerWidth };
  136. });
  137. check('安卓聊天顶栏返回按钮不被标题遮挡', layout.back?.width >= 40 && (!layout.title || layout.title.x >= layout.back.right), layout);
  138. check('安卓聊天无横向溢出', !layout.overflow);
  139. for (const ext of ['md', 'html']) {
  140. await c.evaluate(ext => document.querySelector(`[aria-label="预览 acceptance-mx0a7xfs-fresh.${ext}"]`).click(), ext);
  141. await c.waitFor(() => !!document.querySelector('[role="dialog"][aria-label^="预览 "]'));
  142. if (ext === 'md') await c.waitFor(() => document.querySelector('[role="dialog"][aria-label^="预览 "]')?.innerText.includes('INPUT_EVIDENCE_mx0a7xfs_fresh'));
  143. else {
  144. await c.waitFor(() => { const f = document.querySelector('[role="dialog"][aria-label^="预览 "] iframe'); return f?.src?.startsWith('https://s3.fmode.cn/'); });
  145. let frame;
  146. for (let n = 0; n < 30 && !frame; n++) {
  147. const tree = await c.send('Page.getFrameTree');
  148. frame = (tree.frameTree.childFrames || []).find(x => x.frame.url.includes('acceptance') && x.frame.url.endsWith('.html'));
  149. if (!frame) await pause(500);
  150. }
  151. assert.ok(frame, 'HTML 实际子框架已加载');
  152. const world = await c.send('Page.createIsolatedWorld', { frameId: frame.frame.id });
  153. const body = await c.send('Runtime.evaluate', { expression: 'document.body.innerText', contextId: world.executionContextId, returnByValue: true });
  154. check('安卓 HTML 真实框架内容含验收编号', body.result.value.includes('INPUT_EVIDENCE_mx0a7xfs_fresh'));
  155. }
  156. await c.tap('[role="dialog"][aria-label^="预览 "] [aria-label="复制链接"], [role="dialog"][aria-label^="预览 "] [aria-label="已复制链接"]');
  157. await pause(300);
  158. check('安卓 ' + ext + ' 复制链接后不弹 tooltip', await c.evaluate(() => ![...document.querySelectorAll('[role="tooltip"]')].some(x => x.getBoundingClientRect().width > 0)));
  159. await shot('android-preview-' + ext + '-verified');
  160. check('安卓 ' + ext + ' 预览', true);
  161. await closePreview();
  162. }
  163. execFileSync('adb', ['shell', 'input', 'keyevent', '4']);
  164. await c.waitFor(() => location.pathname === '/mobile/messages');
  165. check('安卓物理返回从聊天回会话列表', true);
  166. } else if (stage === 'mobile-send') {
  167. const c = await navigateMobile('/mobile/chat/' + agent + '/new');
  168. await c.waitFor(() => document.querySelector('textarea') && !document.querySelector('textarea').disabled, undefined, 60000);
  169. const marker = state.run + '_ANDROID';
  170. const prompt = `这是安卓真机验收消息,只回复 ${marker}。不要使用工具,不修改文件或配置。`;
  171. await c.fill('textarea', prompt); await pause(150);
  172. recordAttempt('mobileSend', marker, { prompt });
  173. await c.evaluate(() => { const button = document.querySelector('button.m-send'); button.click(); button.click(); button.click(); });
  174. await pause(1000);
  175. state.mobileSend.threadRoot = await c.evaluate(() => decodeURIComponent(location.pathname.split('/').at(-1))); save();
  176. await proof('mobileSend');
  177. await c.waitFor(marker => [...document.querySelectorAll('app-assistant-turn')].some(x => x.innerText.includes(marker)), marker, 60000);
  178. check('安卓三次连点后草稿清空', await c.evaluate(() => document.querySelector('textarea').value === ''));
  179. await shot('android-send-roundtrip');
  180. } else if (stage === 'mobile-offline') {
  181. assert.ok(state.mobileSend?.proof);
  182. const c = await navigateMobile(chatRoute(state.mobileSend));
  183. await c.waitFor(() => document.querySelector('textarea') && !document.querySelector('textarea').disabled);
  184. const marker = state.run + '_OFFLINE';
  185. const prompt = `这是断网恢复验收,只回复 ${marker}。不要使用工具,不修改任何文件。`;
  186. await c.send('Network.emulateNetworkConditions', { offline: true, latency: 0, downloadThroughput: -1, uploadThroughput: -1 });
  187. state.offlineNetworkActive = true; save();
  188. await c.fill('textarea', prompt); await pause(100);
  189. recordAttempt('offlineSend', marker, { prompt, roomId: state.mobileSend.roomId, threadRoot: state.mobileSend.threadRoot });
  190. await c.tap('button.m-send'); await pause(3500);
  191. const snapshot = await c.evaluate(() => ({ text: document.body.innerText.slice(-2000), draft: document.querySelector('textarea').value }));
  192. state.offlineSend.offlineSnapshot = snapshot; save();
  193. await shot('android-offline-send');
  194. check('断网发送保留可见的草稿/失败/连接提示', snapshot.draft.includes(marker) || /失败|重试|断开|连接中|发送中/.test(snapshot.text), snapshot);
  195. await c.send('Network.emulateNetworkConditions', { offline: false, latency: 0, downloadThroughput: -1, uploadThroughput: -1 });
  196. state.offlineNetworkActive = false; save();
  197. // SDK 自身排队重试;不点击重试或重新发送。
  198. await proof('offlineSend');
  199. await c.waitFor(marker => [...document.querySelectorAll('app-assistant-turn')].some(x => x.innerText.includes(marker)), marker, 60000);
  200. check('安卓断网恢复后真实回复可见', true); await shot('android-offline-recovered');
  201. } else if (stage === 'pc-flow') {
  202. const base = 'http://127.0.0.1:51755';
  203. browser = await chromium.launch({ headless: true, executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe' });
  204. const context = await browser.newContext({ viewport: { width: 1440, height: 960 }, acceptDownloads: true });
  205. const page = await context.newPage(); page.setDefaultTimeout(45000);
  206. const errors = []; page.on('pageerror', e => errors.push(e.message));
  207. await page.goto(base + '/login', { waitUntil: 'domcontentloaded' });
  208. await page.getByRole('button', { name: '账号登录', exact: true }).click();
  209. await page.locator('input[placeholder="请输入账号"]').fill(account.username);
  210. await page.locator('input[placeholder="请输入密码"]').fill(account.password);
  211. await page.getByRole('button', { name: /^登\s*录$/ }).click();
  212. await page.waitForURL(/\/desktop\/chat/, { timeout: 60000 });
  213. check('PC 真实密码登录回已开通应用', true);
  214. state.data.push({ kind: 'login-session', source: 'pc-password-login', userId: account.id, at: new Date().toISOString() }); save();
  215. await page.screenshot({ path: `${out}/pc-login-home.png`, fullPage: true });
  216. await context.storageState({ path: `${privateDir}/pc-browser-state.json` });
  217. for (const route of ['contacts', 'workbench', 'mine', 'my-containers', 'plan-access']) {
  218. await page.goto(base + '/desktop/' + route, { waitUntil: 'domcontentloaded' });
  219. await page.waitForTimeout(1000);
  220. const snapshot = await page.evaluate(() => ({ url: location.pathname, text: document.body.innerText.slice(-2000), overflow: document.documentElement.scrollWidth > innerWidth }));
  221. fs.writeFileSync(`${out}/pc-${route}.json`, JSON.stringify(snapshot, null, 2));
  222. check('PC 页面加载 ' + route, snapshot.url === '/desktop/' + route && snapshot.text.length > 10, snapshot);
  223. check('PC 无横向溢出 ' + route, !snapshot.overflow);
  224. await page.screenshot({ path: `${out}/pc-${route}.png`, fullPage: true });
  225. }
  226. await page.goto(base + '/provision?jobId=' + account.jobId, { waitUntil: 'domcontentloaded' });
  227. await page.getByRole('button', { name: '进入应用', exact: true }).waitFor({ state: 'visible', timeout: 60000 });
  228. check('PC 回读既有开通工单完成状态,不重复开通', true);
  229. await page.getByRole('button', { name: '进入应用', exact: true }).click();
  230. await page.waitForURL(/\/desktop\/chat/);
  231. await page.goto(base + '/desktop/chat/' + agent + '/' + encodeURIComponent(state.mobileSend.threadRoot), { waitUntil: 'domcontentloaded' });
  232. await page.locator('app-assistant-turn').filter({ hasText: state.mobileSend.marker }).first().waitFor({ state: 'visible', timeout: 60000 });
  233. check('PC 回读安卓真实回复,跨设备会话恢复', true);
  234. await page.screenshot({ path: `${out}/pc-android-readback.png`, fullPage: true });
  235. for (const ext of ['md', 'html']) {
  236. await page.goto(base + '/desktop/chat/' + agent + '/' + encodeURIComponent(prior.filesRepaired.threadRoot), { waitUntil: 'domcontentloaded' });
  237. const card = page.getByRole('button', { name: '预览 acceptance-mx0a7xfs-fresh.' + ext, exact: true }).first();
  238. await card.waitFor({ state: 'visible', timeout: 60000 }); await card.click();
  239. const dialog = page.getByRole('dialog', { name: '预览 acceptance-mx0a7xfs-fresh.' + ext, exact: true });
  240. await dialog.waitFor({ state: 'visible' });
  241. if (ext === 'md') await dialog.getByText('INPUT_EVIDENCE_mx0a7xfs_fresh', { exact: false }).first().waitFor();
  242. else await dialog.frameLocator('iframe').locator('body').getByText('INPUT_EVIDENCE_mx0a7xfs_fresh', { exact: false }).first().waitFor();
  243. check('PC 真实成果预览 ' + ext, true);
  244. await page.screenshot({ path: `${out}/pc-preview-${ext}.png`, fullPage: true });
  245. }
  246. const fixtureDir = path.join(out, 'fixtures'); fs.mkdirSync(fixtureDir, { recursive: true });
  247. const fixtureMarker = state.run + '_INPUT';
  248. execFileSync('python', ['-c', `import sys,pathlib,zipfile,json\np=pathlib.Path(sys.argv[1]); marker=sys.argv[2]\n(p/'flow-input.txt').write_text('测试输入编号:'+marker,encoding='utf-8')\n(p/'flow-data.json').write_text(json.dumps({'marker':marker,'items':[1,2,3]},indent=2),encoding='utf-8')\ntext='BT /F1 20 Tf 60 760 Td (Fmode acceptance) Tj 0 -40 Td ('+marker+') Tj ET'\nobjects=[b'<< /Type /Catalog /Pages 2 0 R >>',b'<< /Type /Pages /Kids [3 0 R] /Count 1 >>',b'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>',b'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>',('<< /Length '+str(len(text))+' >>\\nstream\\n'+text+'\\nendstream').encode()]\ndata=b'%PDF-1.4\\n'; offsets=[0]\nfor n,obj in enumerate(objects,1):\n offsets.append(len(data)); data+=str(n).encode()+b' 0 obj\\n'+obj+b'\\nendobj\\n'\nxref=len(data);data+=b'xref\\n0 6\\n0000000000 65535 f \\n'+b''.join(('%010d 00000 n \\n'%o).encode() for o in offsets[1:])+('trailer\\n<< /Size 6 /Root 1 0 R >>\\nstartxref\\n'+str(xref)+'\\n%%EOF').encode();(p/'flow-document.pdf').write_bytes(data)\nwith zipfile.ZipFile(p/'flow-document.docx','w',zipfile.ZIP_DEFLATED) as z:\n z.writestr('[Content_Types].xml','<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>')\n z.writestr('_rels/.rels','<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>')\n z.writestr('word/document.xml','<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>Fmode full flow acceptance</w:t></w:r></w:p><w:p><w:r><w:t>'+marker+'</w:t></w:r></w:p><w:sectPr><w:pgSz w:w="11906" w:h="16838"/></w:sectPr></w:body></w:document>')`, fixtureDir, fixtureMarker]);
  249. await page.goto(base + '/desktop/chat/' + agent + '/new', { waitUntil: 'domcontentloaded' });
  250. await page.waitForFunction(() => document.querySelector('textarea') && !document.querySelector('textarea').disabled, undefined, { timeout: 60000 });
  251. const names = ['flow-input.txt', 'flow-data.json', 'flow-document.pdf', 'flow-document.docx'];
  252. await page.locator('input[type="file"]').first().setInputFiles(names.map(n => path.join(fixtureDir, n)));
  253. await page.locator('.pending-holds').waitFor({ state: 'visible' });
  254. check('PC 四种待发送附件展示', (await page.locator('.pending-holds').innerText()).includes('flow-document.pdf') && (await page.locator('.pending-holds').innerText()).includes('flow-document.docx'));
  255. await page.screenshot({ path: `${out}/pc-staged-files.png`, fullPage: true });
  256. const marker = state.run + '_PC';
  257. const prompt = `本轮 PC 文件验收:读取刚上传 flow-input.txt 中的输入编号并复述。只读取文件,不创建、修改、删除或发布任何文件。最终回复必须包含 ${marker} 和输入完整编号。不要执行其他操作。`;
  258. await page.locator('textarea').fill(prompt);
  259. recordAttempt('pcSend', marker, { prompt, fixtureMarker, inputNames: names });
  260. await page.locator('button.send').click();
  261. await page.waitForTimeout(2000);
  262. state.pcSend.threadRoot = decodeURIComponent(new URL(page.url()).pathname.split('/').at(-1)); save();
  263. await proof('pcSend', 240000);
  264. check('PC 容器实际读取上传的文本内容', state.pcSend.proof.body.includes(fixtureMarker));
  265. await page.locator('app-assistant-turn').filter({ hasText: marker }).last().waitFor({ state: 'visible', timeout: 60000 });
  266. await page.screenshot({ path: `${out}/pc-real-roundtrip.png`, fullPage: true });
  267. await page.reload({ waitUntil: 'domcontentloaded' });
  268. await page.locator('app-assistant-turn').filter({ hasText: marker }).last().waitFor({ state: 'visible', timeout: 60000 });
  269. check('PC 发送后刷新回读', true);
  270. for (const ext of ['pdf', 'docx', 'json', 'txt']) {
  271. const name = ext === 'pdf' || ext === 'docx' ? 'flow-document.' + ext : ext === 'json' ? 'flow-data.json' : 'flow-input.txt';
  272. const card = page.locator('button').filter({ hasText: name }).filter({ hasNotText: '移除' }).first();
  273. await card.waitFor({ state: 'visible', timeout: 60000 }); await card.click();
  274. const dialog = page.getByRole('dialog', { name: '预览 ' + name, exact: true });
  275. await dialog.waitFor({ state: 'visible' });
  276. if (ext === 'pdf' || ext === 'docx') await dialog.locator('canvas').first().waitFor({ state: 'visible', timeout: 60000 });
  277. else await dialog.getByText(fixtureMarker, { exact: false }).first().waitFor({ state: 'visible' });
  278. check('PC 输入文件实际预览 ' + ext, true);
  279. await page.screenshot({ path: `${out}/pc-input-preview-${ext}.png`, fullPage: true });
  280. const close = dialog.getByRole('button', { name: '关闭预览', exact: true });
  281. if (!(await close.isVisible())) await dialog.getByRole('button', { name: '回到右侧', exact: true }).click();
  282. await close.click(); await dialog.waitFor({ state: 'hidden' });
  283. }
  284. check('PC 浏览器无运行时异常', errors.length === 0, errors);
  285. await context.storageState({ path: `${privateDir}/pc-browser-state.json` });
  286. } else throw Error('未知 stage: ' + stage);
  287. } catch (error) {
  288. state.lastFailure = { stage, error: error.message, at: new Date().toISOString() }; save();
  289. if (native) { await native.screenshot(`${out}/${stage}-failure.png`).catch(() => {}); }
  290. if (browser) {
  291. const page = browser.contexts()[0]?.pages()[0];
  292. if (page) {
  293. await page.screenshot({ path: `${out}/${stage}-failure.png`, fullPage: true }).catch(() => {});
  294. fs.writeFileSync(`${out}/${stage}-failure.json`, JSON.stringify({ url: page.url(), body: await page.locator('body').innerText().catch(() => '') }, null, 2));
  295. }
  296. }
  297. throw error;
  298. } finally {
  299. if (native && state.offlineNetworkActive) {
  300. await native.send('Network.emulateNetworkConditions', { offline: false, latency: 0, downloadThroughput: -1, uploadThroughput: -1 }).catch(() => {});
  301. state.offlineNetworkActive = false; save();
  302. }
  303. native?.close(); await browser?.close();
  304. }