verify-new-account.mjs 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  1. /** 新账号真机验收。真实动作先登记;重启后先 status,不重复请求或创建。 */
  2. import { recordProgress } from './lib/project-recovery.mjs';
  3. import fs from 'node:fs';
  4. import path from 'node:path';
  5. import assert from 'node:assert/strict';
  6. import { createHash } from 'node:crypto';
  7. import { spawnSync } from 'node:child_process';
  8. import { deflateSync } from 'node:zlib';
  9. import { connectWebView, captureNativeScreenshot } from './android-webview-cdp.mjs';
  10. import { readMatrixHistory, taskProof, retainFirstProof, checkRetryUnsent, newFrameLoader, waitForPreviewText, previewCardsMatch, resolveTaskThread, sessionFileObjects, assertSessionIsolation, otherTaskFiles } from './lib/acceptance-evidence.mjs';
  11. const arg = (name, fallback) => process.argv.find(x => x.startsWith(`--${name}=`))?.slice(name.length + 3) ?? fallback;
  12. const stage = arg('stage', 'status');
  13. const phone = arg('phone', '18182795512');
  14. assert.match(phone, /^1\d{10}$/, '必须提供明确的测试手机号');
  15. const out = path.resolve(arg('out', 'test-results/new-account-20261128'));
  16. const accountFile = path.resolve(arg('account-file', '.local-backup/new-account-20261128/account.json'));
  17. const privateDir = path.dirname(accountFile);
  18. const checkpoint = path.resolve('docs/00-tracking/接续检查点.md');
  19. assert.ok(fs.existsSync(checkpoint), '请从项目根目录执行');
  20. assert.ok(fs.existsSync(path.join(out, 'state.json')), '先登记本轮执行目标并建立 state.json');
  21. const stateFile = path.join(out, 'state.json');
  22. let state;
  23. const lockFile = path.join(out, 'runner.lock');
  24. let lock, c, networkOverridden = false;
  25. const save = () => {
  26. fs.writeFileSync(stateFile + '.next', JSON.stringify(state, null, 2) + '\n');
  27. fs.renameSync(stateFile + '.next', stateFile);
  28. };
  29. const note = text => recordProgress(process.cwd(), `[${out}] ${text}`);
  30. const begin = (key, target) => {
  31. assert.ok(!state.actions[key]?.attempted, `${key} 已有动作记录;先运行 status 核实,禁止盲目重试`);
  32. state.actions[key] = { attempted: true, at: new Date().toISOString(), target };
  33. save(); note(`准备执行 ${key},目标 ${target};结果见 ${path.relative(process.cwd(), stateFile)}。`);
  34. };
  35. const done = (key, receipt) => {
  36. Object.assign(state.actions[key], { confirmedAt: new Date().toISOString(), receipt });
  37. save(); note(`${key} 已取得回执;${JSON.stringify(receipt)}。`);
  38. };
  39. const check = (name, pass, details) => {
  40. state.checks.push({ name, pass: !!pass, at: new Date().toISOString(), ...(details ? { details } : {}) });
  41. save(); assert.ok(pass, name);
  42. };
  43. const auth = () => c.evaluate(() => ({ token: localStorage.getItem('fmode_session_token'), me: JSON.parse(localStorage.getItem('fmode_me') || 'null') }));
  44. const navigate = async route => {
  45. await c.evaluate(route => { history.pushState(null, '', route); dispatchEvent(new PopStateEvent('popstate')); }, route);
  46. await c.waitFor(route => decodeURIComponent(location.pathname) === decodeURIComponent(route), route, 60000);
  47. };
  48. const tapText = async label => {
  49. const point = await c.evaluate(label => {
  50. const el = [...document.querySelectorAll('button')].filter(el => el.innerText.trim() === label && el.getClientRects().length && !el.disabled).at(-1);
  51. if (!el) return null;
  52. el.scrollIntoView({ block: 'center' });
  53. const r = el.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
  54. }, label);
  55. assert.ok(point, `找不到唯一可用操作:${label}`);
  56. await c.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [point] });
  57. await c.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
  58. };
  59. const shot = name => c.screenshot(path.join(out, name + '.png'));
  60. const snapshot = () => c.evaluate(() => ({
  61. route: location.pathname,
  62. text: document.body.innerText,
  63. overflow: document.documentElement.scrollWidth > innerWidth,
  64. viewport: { width: innerWidth, height: innerHeight },
  65. inputs: [...document.querySelectorAll('input')].map(x => ({ label: x.getAttribute('aria-label'), type: x.type, length: x.value.length })),
  66. buttons: [...document.querySelectorAll('button')].filter(x => x.getClientRects().length).map(x => ({ text: x.innerText.trim(), label: x.getAttribute('aria-label'), disabled: x.disabled })),
  67. }));
  68. const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
  69. const deviceAdb = args => {
  70. const r = spawnSync('adb', ['-s', arg('serial', '3e529a34'), ...args], { encoding: 'utf8', timeout: 30000, maxBuffer: 8 * 1024 * 1024, windowsHide: true });
  71. assert.equal(r.status, 0, 'ADB 操作未确认:' + args.slice(0, 3).join(' ') + ' ' + (r.stderr || r.error?.message || ''));
  72. return r.stdout.trim();
  73. };
  74. async function reconnectApp() {
  75. const deadline = Date.now() + 45000;
  76. while (Date.now() < deadline) {
  77. try {
  78. const pid = deviceAdb(['shell', 'pidof', 'cn.fmode.app']);
  79. deviceAdb(['forward', 'tcp:' + arg('port', '9222'), 'localabstract:webview_devtools_remote_' + pid]);
  80. c = await connectWebView(Number(arg('port', '9222')));
  81. return;
  82. } catch { await pause(500); }
  83. }
  84. throw Error('原 App 启动后未能恢复 WebView 连接;先查进程和界面,不重试业务动作');
  85. }
  86. async function verifyOriginalTrial(label) {
  87. const task = state.actions.trialFilesV3;
  88. assert.ok(task?.proof?.completion, '缺少原文件任务回执');
  89. await c.waitFor(() => !!localStorage.getItem('fmode_me'), undefined, 60000);
  90. assert.equal((await auth()).me?.id, state.userId, label + '后身份必须仍为本轮账号');
  91. await navigate('/mobile/chat/' + state.trial.agentId + '/' + encodeURIComponent(task.threadRoot));
  92. await c.waitFor(() => document.querySelector('textarea') && !document.querySelector('textarea').disabled, undefined, 60000);
  93. const view = await snapshot();
  94. check(label + '后原会话与两份成果可回读', view.text.includes(task.inputMarker) && task.expectedFiles.every(name => view.text.includes(name)), { route: view.route });
  95. await proveMessage('trialFilesV3', 30000);
  96. return view;
  97. }
  98. function pictureFixture() {
  99. const chunk = (name, data) => {
  100. const type = Buffer.from(name); let crc = 0xffffffff;
  101. for (const byte of Buffer.concat([type, data])) { crc ^= byte; for (let n = 0; n < 8; n++) crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0); }
  102. const length = Buffer.alloc(4); length.writeUInt32BE(data.length);
  103. const checksum = Buffer.alloc(4); checksum.writeUInt32BE((crc ^ 0xffffffff) >>> 0);
  104. return Buffer.concat([length, type, data, checksum]);
  105. };
  106. const header = Buffer.alloc(13); header.writeUInt32BE(64, 0); header.writeUInt32BE(64, 4); header[8] = 8; header[9] = 2;
  107. const raw = Buffer.alloc(64 * (64 * 3 + 1));
  108. for (let y = 0; y < 64; y++) for (let x = 0; x < 64; x++) { const p = y * 193 + 1 + x * 3; raw[p] = 32; raw[p + 1] = 124; raw[p + 2] = 218; }
  109. return Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]), chunk('IHDR', header), chunk('IDAT', deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
  110. }
  111. async function accountApi(id, params) {
  112. const account = JSON.parse(fs.readFileSync(accountFile));
  113. if (id === 'THXAOGKiPK') params = { ...params, token: account.token };
  114. const response = await fetch('https://server.fmode.cn/api/functions', { method: 'POST',
  115. headers: { 'Content-Type': 'application/json', 'X-Parse-Application-Id': 'ncloudmaster', 'X-Parse-Session-Token': account.token },
  116. body: JSON.stringify({ id, token: account.token, params }), signal: AbortSignal.timeout(25000) });
  117. assert.ok(response.ok, '账号接口 HTTP ' + response.status);
  118. const data = await response.json(); assert.equal(data.code, 200, data.msg || data.mess); return data;
  119. }
  120. async function readBinding(agentId = state.trial.agentId) {
  121. // Server-side test read only. Never injected into the WebView or packaged in the APK.
  122. const cfg = JSON.parse(fs.readFileSync('.claude/dev-login.json'));
  123. const url = new URL('https://server.fmode.cn/parse/classes/FmodeMatrixBinding');
  124. url.searchParams.set('where', JSON.stringify({ userPointer: { __type: 'Pointer', className: '_User', objectId: state.userId }, agentId, status: 'active' }));
  125. const response = await fetch(url, { headers: { 'X-Parse-Application-Id': 'ncloudmaster', 'X-Parse-Master-Key': cfg.masterKey }, signal: AbortSignal.timeout(20000) });
  126. assert.ok(response.ok); const rows = (await response.json()).results;
  127. assert.equal(rows?.length, 1, '本轮账号与试用容器必须只有一个有效通信绑定');
  128. assert.equal(rows[0].userMxId, '@' + state.userId.toLowerCase() + ':fmode.cn');
  129. if (agentId === state.trial.agentId) assert.equal(rows[0].agentMxId, state.trial.agentMxId);
  130. return rows[0];
  131. }
  132. async function readRoomEvents(binding, roomId) {
  133. return readMatrixHistory(binding, roomId);
  134. }
  135. const ownInputs = (events, binding, marker) => events.filter(e => e.sender === binding.userMxId && e.type === 'm.room.message' && e.content?.body?.includes(marker));
  136. async function openTrialTask(task) {
  137. assert.ok(task?.proof?.completion && task.roomId && task.threadRoot, '缺少已完成任务的服务器回执');
  138. await navigate('/mobile/chat/' + state.trial.agentId + '/' + encodeURIComponent(task.threadRoot));
  139. await c.waitFor(() => document.querySelector('textarea') && !document.querySelector('textarea').disabled, undefined, 60000);
  140. await c.waitFor(marker => document.body.innerText.includes(marker), task.marker, 60000);
  141. }
  142. async function readHtmlPreview(marker, previousFrame) {
  143. let frame;
  144. for (let n = 0; n < 45 && !frame; n++) {
  145. const tree = await c.send('Page.getFrameTree');
  146. frame = (tree.frameTree.childFrames || []).find(x => x.frame.url.includes(state.actions.trialFilesV3.expectedFiles.find(x => x.endsWith('.html'))) && (!previousFrame || newFrameLoader(previousFrame, x.frame)));
  147. if (!frame) await pause(300);
  148. }
  149. assert.ok(frame, 'HTML 实际子框架未加载');
  150. await waitForPreviewText(async () => {
  151. const tree = await c.send('Page.getFrameTree');
  152. const sameLoader = (tree.frameTree.childFrames || []).some(x => x.frame.id === frame.frame.id && x.frame.loaderId === frame.frame.loaderId);
  153. assert.ok(sameLoader, '正在等待的目标loader已改变');
  154. const world = await c.send('Page.createIsolatedWorld', { frameId: frame.frame.id });
  155. const body = await c.send('Runtime.evaluate', { expression: 'document.body?.innerText || ""', contextId: world.executionContextId, returnByValue: true });
  156. if (body.exceptionDetails) throw Error(body.exceptionDetails.text);
  157. return body.result?.value;
  158. }, marker);
  159. await c.waitFor(() => {
  160. const dialog = document.querySelector('[role="dialog"][aria-label^="预览 "]');
  161. return dialog?.querySelector('iframe.fp-html')?.getClientRects().length && !dialog.querySelector('.fp-html-stall, .fp-html-loading');
  162. }, undefined, 45000);
  163. return frame.frame;
  164. }
  165. async function verifyIsolationViews(prefix) {
  166. const a = state.actions.trialIsolationSeed, b = state.actions.trialFilesV3;
  167. assert.notEqual(a.roomId, b.roomId, '隔离验收必须使用两个不同房间');
  168. const originals = JSON.parse(fs.readFileSync(path.join(out, 'trial-v3-file-hub.json')));
  169. for (const [key, task, other] of [['A', a, b], ['B', b, a], ['A-return', a, b]]) {
  170. await openTrialTask(task);
  171. const view = await snapshot();
  172. check('既有会话切换隔离 ' + key, view.text.includes(task.marker) && !view.text.includes(other.marker), { route: view.route, roomId: task.roomId });
  173. if (key === 'B') await c.waitFor(names => names.every(name => document.querySelector(`[aria-label="预览 ${name}"]`)?.getClientRects().length), b.expectedFiles, 45000);
  174. const labels = await c.evaluate(() => [...document.querySelectorAll('button[aria-label^="预览 "]')].filter(x => x.getClientRects().length).map(x => x.getAttribute('aria-label')));
  175. check('既有会话可见成果卡片隔离 ' + key, previewCardsMatch(b.expectedFiles, labels, key === 'B'), { labels });
  176. const listing = await accountApi('THXAOGKiPK', { action: 'listBySession', roomId: task.roomId, limit: 200 });
  177. const urls = (listing.files || []).map(x => x.url);
  178. check('既有会话成果归属隔离 ' + key, key === 'B' ? originals.every(x => urls.includes(x.url)) : originals.every(x => !urls.includes(x.url)), { roomId: task.roomId, fileIds: (listing.files || []).map(x => x.id) });
  179. await shot(prefix + '-' + key);
  180. }
  181. return { rooms: [a.roomId, b.roomId], screenshots: ['A', 'B', 'A-return'].map(key => prefix + '-' + key + '.png'), sends: 0 };
  182. }
  183. async function proveMessage(key, timeout = 180000) {
  184. const action = state.actions[key]; assert.ok(action?.attempted, '必须先有真实发送动作记录');
  185. const agentId = action.agentId || state.trial.agentId;
  186. const binding = await readBinding(agentId); const deadline = Date.now() + timeout;
  187. const stamp = new Date().toISOString().replace(/\D/g, '') + '-' + process.pid; let observation = 0;
  188. while (Date.now() < deadline) {
  189. const listing = await accountApi('oR5O67i1Cm', { op: 'list', agentId });
  190. const thread = resolveTaskThread(listing.threads || [], action);
  191. if (thread?.roomId) {
  192. if (!action.roomId) action.roomId = thread.roomId;
  193. if (!action.threadRoot) action.threadRoot = thread.threadRoot;
  194. if (!action.threadId) action.threadId = thread.objectId ?? thread.id;
  195. assert.equal(action.roomId, thread.roomId, '回读线程必须保持首次登记房间');
  196. save();
  197. const history = await readRoomEvents(binding, thread.roomId), events = history.events;
  198. const inputNames = state.actions[key.replace('Files', 'FilesInput')]?.receipt?.files?.map(x => x.name) || [];
  199. const evidenceFile = key + '-readback-' + stamp + '-' + observation++ + '.json';
  200. fs.writeFileSync(path.join(out, evidenceFile), JSON.stringify({ observedAt: new Date().toISOString(), roomId: thread.roomId, ...history }, null, 2), { flag: 'wx' });
  201. (action.observations ??= []).push({ at: new Date().toISOString(), evidenceFile, complete: history.complete }); save();
  202. const proof = taskProof(events, binding, action, inputNames);
  203. if (proof) {
  204. proof.roomId = thread.roomId;
  205. check(key + ' 输入只发送一次', proof.sent.length === 1);
  206. const firstFile = path.join(out, key + '-events.json');
  207. if (!fs.existsSync(firstFile)) fs.writeFileSync(firstFile, JSON.stringify(events, null, 2), { flag: 'wx' });
  208. retainFirstProof(action, { ...proof, evidenceFile, observedAt: new Date().toISOString() }); save();
  209. check(key + ' 真实发送、目标回复与结束回执', true, { ...proof, evidenceFile, pages: history.pages.length });
  210. note(`${key} 完整分页只读回验通过,房间 ${thread.roomId},输入 ${proof.sent[0]},结束回执 ${proof.completion};新证据 ${evidenceFile},原事件和首次proof保留。`);
  211. return action;
  212. }
  213. }
  214. await pause(2500);
  215. }
  216. throw Error(key + ' 尚无完整服务器回执;先核实事件,不可重复发送');
  217. }
  218. async function readAdvancedJob() {
  219. const action = state.actions.advancedCreate;
  220. assert.ok(action?.attempted && Array.isArray(action.jobsBefore) && Array.isArray(action.agentIdsBefore), '没有完整的进阶申请前资产记录,只能人工只读核实');
  221. const jobs = (await accountApi('VtW1GT93Ax', { op: 'list' })).items || [];
  222. const created = jobs.filter(x => !action.jobsBefore.some(y => y.jobId === x.jobId));
  223. assert.equal(created.length, 1, '必须只新增一个任务,先核实真实任务列表');
  224. assert.ok(!action.jobId || action.jobId === created[0].jobId, '新任务与已登记任务不同');
  225. assert.equal(created[0].planCode, 'advanced', '新增任务不是进阶套餐');
  226. const job = await accountApi('VtW1GT93Ax', { op: 'status', jobId: created[0].jobId });
  227. assert.equal(job.jobId, created[0].jobId, '状态回包jobId与目标不同');
  228. assert.equal(job.planCode, 'advanced', '状态回包不是进阶套餐');
  229. assert.ok(job.agentId, '进阶任务缺少目标容器身份');
  230. const agentId = job.agentId.startsWith('agent-node-app-') ? job.agentId.toLowerCase() : 'agent-node-app-' + job.agentId.toLowerCase();
  231. assert.ok(!action.agentIdsBefore.includes(agentId), '进阶任务复用了原有容器身份');
  232. const agents = (await accountApi('xlosi3m46q', { op: 'query', scope: 'mine' })).agents || [];
  233. const ids = agents.map(x => x.agentId);
  234. assert.ok(action.agentIdsBefore.every(id => ids.includes(id)), '进阶申请后原有容器丢失');
  235. assert.deepEqual(ids.filter(id => !action.agentIdsBefore.includes(id)), [agentId], '新容器差集与进阶目标不一致');
  236. const file = 'advanced-status-' + Date.now() + '.json';
  237. fs.writeFileSync(path.join(out, file), JSON.stringify({ observedAt: new Date().toISOString(), jobs, job, agentIds: ids }, null, 2), { flag: 'wx' });
  238. Object.assign(action, { jobId: job.jobId, agentId, latestStatus: job });
  239. (action.statusObservations ??= []).push(file); save();
  240. note(`进阶原任务只读回验:${job.jobId}/${agentId}/${job.status};阶段${job.currentStep?.stage || job.stage};证据${file},原资产保留且仅新增目标容器,未再次申请。`);
  241. return job;
  242. }
  243. async function verifyProvisionView(jobId) {
  244. await c.waitFor(() => !!document.querySelector('app-dk-provision-page .prov-title'), undefined, 60000);
  245. await c.waitFor(() => {
  246. const text = document.querySelector('app-dk-provision-page')?.innerText || '';
  247. return /正在创建容器|容器已就绪|开通未完成/.test(text) && !/加载开通状态失败/.test(text);
  248. }, undefined, 60000);
  249. // 网址和初始骨架不能证明状态已加载,必须回读本次页面真实发起的原job状态响应。
  250. let response;
  251. for (let n = 0; n < 150 && !response; n++) {
  252. for (const event of c.events.filter(x => x.method === 'Network.responseReceived' && /\/api\/functions/.test(x.params?.response?.url || '')).reverse()) {
  253. try {
  254. const body = await c.send('Network.getResponseBody', { requestId: event.params.requestId });
  255. const data = JSON.parse(body.base64Encoded ? Buffer.from(body.body, 'base64').toString('utf8') : body.body);
  256. if (data.code === 200 && data.jobId === jobId && data.planCode === 'advanced' && data.status) { response = data; break; }
  257. } catch { /* 响应尚未完成或不是开通状态,继续读同次页面请求。 */ }
  258. }
  259. if (!response) await pause(300);
  260. }
  261. assert.ok(response, '等待页未取得原job的真实状态响应');
  262. const view = await snapshot();
  263. assert.ok(!/加载开通状态失败/.test(view.text), '等待页显示状态加载失败');
  264. assert.ok(!view.overflow, '等待页横向溢出');
  265. if (['queued', 'provisioning', 'verifying'].includes(response.status)) {
  266. assert.equal(await c.evaluate(() => document.querySelectorAll('app-dk-provision-page .prov-stage').length), 6, '等待页没有渲染实际阶段');
  267. } else assert.ok(view.text.includes(response.status === 'ready' ? '容器已就绪' : '开通未完成'), '等待页终态与服务端不一致');
  268. return { jobId, status: response.status, stage: response.currentStep?.stage || response.stage, route: view.route };
  269. }
  270. try {
  271. if (stage !== 'status') {
  272. lock = fs.openSync(lockFile, 'wx');
  273. fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, stage, startedAt: new Date().toISOString() }));
  274. }
  275. state = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
  276. assert.equal(state.phone, phone, '手机号与本轮账本不一致');
  277. if (!['trial-cold-start', 'trial-background-resume', 'advanced-status', 'advanced-restore'].includes(stage)) c = await connectWebView(Number(arg('port', '9222')));
  278. if (stage === 'status') {
  279. const identity = await auth();
  280. const view = await snapshot();
  281. console.log(JSON.stringify({ run: state.run, phone, userId: identity.me?.id, route: view.route, inputs: view.inputs, buttons: view.buttons, actions: state.actions, checks: state.checks.map(({ name, pass }) => ({ name, pass })) }, null, 2));
  282. } else if (stage === 'request-code' || stage === 'request-relogin-code') {
  283. const relogin = stage === 'request-relogin-code';
  284. const smsKey = relogin ? 'smsRelogin' : 'sms';
  285. assert.ok(!state.actions[smsKey]?.attempted, `${smsKey} 已有动作记录;先只读核实,不重复请求验证码`);
  286. fs.mkdirSync(privateDir, { recursive: true });
  287. const identity = await auth();
  288. if (identity.token) {
  289. if (relogin) {
  290. assert.equal(identity.me?.id, state.userId, '重登前账号不是本轮用户');
  291. begin('logoutRelogin', phone + '/APK 退出并短信重登验收');
  292. }
  293. fs.writeFileSync(path.join(privateDir, relogin ? 'previous-mobile-auth-relogin.json' : 'previous-mobile-auth.json'), JSON.stringify(identity, null, 2));
  294. await navigate('/mobile/mine');
  295. await c.waitFor(() => !!document.querySelector('button.m-logout'));
  296. // debug 包沿用 1.0 版本号,账户页可能提示安装已发布版;验收保留当前构建。
  297. if (await c.evaluate(() => [...document.querySelectorAll('[role="dialog"]')].some(x => x.innerText.includes('稍后再说')))) {
  298. await tapText('稍后再说');
  299. await c.waitFor(() => ![...document.querySelectorAll('[role="dialog"]')].some(x => x.innerText.includes('稍后再说')));
  300. }
  301. await c.tap('button.m-logout');
  302. await c.waitFor(() => [...document.querySelectorAll('[role="dialog"], [role="alertdialog"]')].some(x => x.innerText.includes('退出登录')) || document.querySelectorAll('app-m-confirm button').length > 0);
  303. await tapText('退出登录');
  304. await c.waitFor(() => !!document.querySelector('input[aria-label="手机号"]'));
  305. check('通过 APK 界面退出旧账号并进入短信登录页', !(await auth()).token);
  306. if (relogin) done('logoutRelogin', { phone, loggedOut: true, loginFormVisible: true });
  307. }
  308. await c.waitFor(() => !!document.querySelector('input[aria-label="手机号"]'));
  309. await c.fill('input[aria-label="手机号"]', phone);
  310. if (!(await c.evaluate(() => document.querySelector('[aria-label="同意协议"]')?.getAttribute('aria-checked') === 'true'))) await c.tap('[aria-label="同意协议"]');
  311. await shot(relogin ? 'relogin-01-phone-form' : '01-phone-form');
  312. begin(smsKey, phone);
  313. await c.tap('button.m-btn--primary');
  314. await c.waitFor(() => !!document.querySelector('input[aria-label="验证码"]') || !!document.querySelector('[role="alert"]'));
  315. const view = await snapshot();
  316. fs.writeFileSync(path.join(out, relogin ? 'sms-relogin-ui.json' : 'sms-ui.json'), JSON.stringify(view, null, 2));
  317. await shot(relogin ? 'relogin-02-code-request-result' : '02-code-request-result');
  318. assert.ok(view.inputs.some(x => x.label === '验证码'), '短信接口未确认成功,请检查 sms-ui.json;不要重复发送');
  319. done(smsKey, { phone, codeInputVisible: true, countdown: view.buttons.find(x => /^\d+s$/.test(x.text))?.text });
  320. check('真实短信请求成功后展示验证码输入和倒计时', true);
  321. check('短信登录页无横向溢出', !view.overflow);
  322. console.log(JSON.stringify({ sent: true, phone, waitingForUserCode: true, nextStage: relogin ? 'relogin' : 'login' }));
  323. } else if (stage === 'login' || stage === 'relogin') {
  324. const relogin = stage === 'relogin';
  325. const smsKey = relogin ? 'smsRelogin' : 'sms';
  326. const loginKey = relogin ? 'loginRelogin' : 'login';
  327. const code = arg('code');
  328. assert.match(code ?? '', /^\d{6}$/, '请输入用户提供的 6 位验证码');
  329. assert.ok(state.actions[smsKey]?.confirmedAt, '本轮短信尚无成功回执');
  330. assert.ok(!state.actions[loginKey]?.attempted, '已有登录动作记录,先核实结果');
  331. await c.fill('input[aria-label="验证码"]', code);
  332. begin(loginKey, phone);
  333. await c.tap('button.m-btn--primary');
  334. await c.waitFor(() => !!localStorage.getItem('fmode_session_token') || !!document.querySelector('[role="alert"]'), undefined, 60000);
  335. const identity = await auth();
  336. assert.ok(identity.token && identity.me?.id, '登录未成功,请先核实界面错误');
  337. assert.equal(identity.me.mobile, phone, '登录返回手机号与本轮测试账号不一致');
  338. if (relogin) {
  339. assert.equal(identity.me.id, state.userId, '重登前后用户身份不一致');
  340. fs.copyFileSync(accountFile, path.join(privateDir, 'account-before-relogin.json'));
  341. }
  342. fs.writeFileSync(accountFile, JSON.stringify({ ...identity, phone, userId: identity.me.id, at: new Date().toISOString() }, null, 2));
  343. state.userId = identity.me.id;
  344. done(loginKey, { userId: identity.me.id, phone });
  345. await c.waitFor(() => !location.pathname.includes('login'), undefined, 60000);
  346. await shot(relogin ? 'relogin-03-success' : '03-login-success');
  347. const view = await snapshot();
  348. fs.writeFileSync(path.join(out, relogin ? 'relogin-ui.json' : 'login-ui.json'), JSON.stringify(view, null, 2));
  349. check('新手机号真实登录并离开登录页', true, { userId: identity.me.id, route: view.route });
  350. console.log(JSON.stringify({ loggedIn: true, userId: identity.me.id, route: view.route }));
  351. } else if (stage === 'install-pending-recovery') {
  352. const buildTag = arg('build-tag', 'pending-recovery-20261129');
  353. assert.match(buildTag, /^[A-Za-z0-9-]+$/);
  354. const installKey = 'installPendingRecovery_' + buildTag;
  355. const apkReceipt = 'apk-' + buildTag + '-receipt.json';
  356. const receipt = JSON.parse(fs.readFileSync(path.join(out, apkReceipt)));
  357. const bytes = fs.readFileSync(receipt.apk);
  358. assert.equal(createHash('sha256').update(bytes).digest('hex').toUpperCase(), receipt.sha256);
  359. begin(installKey, `${arg('serial', '3e529a34')}/cn.fmode.app/${receipt.sha256}/仅覆盖安装保留数据`);
  360. deviceAdb(['install', '-r', receipt.apk]);
  361. deviceAdb(['shell', 'am', 'start', '-n', 'cn.fmode.app/.MainActivity']);
  362. c.close(); await reconnectApp();
  363. await c.waitFor(id => JSON.parse(localStorage.getItem('fmode_me') || 'null')?.id === id, state.userId, 60000);
  364. const remote = deviceAdb(['shell', 'pm', 'path', 'cn.fmode.app']).replace(/^package:/, '');
  365. const remoteSha256 = deviceAdb(['shell', 'sha256sum', remote]).split(/\s/)[0].toUpperCase();
  366. assert.equal(remoteSha256, receipt.sha256, '安装包与手机实际包摘要不同');
  367. await navigate('/plans');
  368. await c.waitFor(() => document.querySelector('.plan-card--featured .plan-btn')?.disabled === false && !document.querySelector('app-loading-overlay'), undefined, 60000);
  369. check('新版APK恢复核对无在途任务后允许申请', true, { sha256: remoteSha256 });
  370. done(installKey, { sha256: remoteSha256, userId: state.userId, apkReceipt });
  371. } else if (stage === 'advanced-start') {
  372. assert.ok(!state.actions.advancedCreate?.attempted, '进阶申请已有动作记录,只能advanced-status核实,禁止再次申请');
  373. for (const key of ['trialEvidenceAudit', 'trialCleanOutput', 'trialDocumentPreviews', 'trialFreshChat', 'desktopBaseline', 'mobileBaseline', 'reloginReadback']) assert.ok(state.actions[key]?.confirmedAt, '基础验收尚缺 ' + key);
  374. assert.equal((await auth()).me?.id, state.userId);
  375. const jobsBefore = (await accountApi('VtW1GT93Ax', { op: 'list' })).items || [];
  376. assert.ok(jobsBefore.every(x => ['ready', 'failed'].includes(x.status)), '已有在途开通任务,停止而不新增');
  377. const agentsBefore = (await accountApi('xlosi3m46q', { op: 'query', scope: 'mine' })).agents || [];
  378. await navigate('/plans');
  379. await c.waitFor(() => document.querySelector('.plan-card--featured h3')?.innerText.trim() === '进阶' && !document.querySelector('.plan-card--featured .plan-btn')?.disabled);
  380. begin('advancedCreate', `${state.userId}/APK进阶卡片单次开通一个新容器;保留所有原资产`);
  381. Object.assign(state.actions.advancedCreate, { jobsBefore, agentIdsBefore: agentsBefore.map(x => x.agentId), phase: 'before-single-tap' }); save();
  382. await c.tap('.plan-card--featured .plan-btn');
  383. state.actions.advancedCreate.phase = 'single-tap-complete'; save();
  384. await c.waitFor(() => location.pathname === '/provision' && !!new URLSearchParams(location.search).get('jobId'), undefined, 90000);
  385. const jobId = await c.evaluate(() => new URLSearchParams(location.search).get('jobId'));
  386. state.actions.advancedCreate.jobId = jobId; save();
  387. const job = await readAdvancedJob();
  388. Object.assign(state.actions.advancedCreate, { latestStatus: job, phase: 'accepted' }); save();
  389. captureNativeScreenshot(path.join(out, 'advanced-accepted-native.png'), arg('serial', '3e529a34'));
  390. done('advancedCreate', { jobId, status: job.status, agentId: job.agentId, clicks: 1, readyVerified: false });
  391. } else if (stage === 'advanced-status') {
  392. console.log(JSON.stringify(await readAdvancedJob(), null, 2));
  393. } else if (stage === 'advanced-restore' || stage === 'advanced-restore-readback') {
  394. const action = state.actions.advancedCreate; assert.ok(action?.jobId && action.latestStatus, '缺少原进阶任务');
  395. if (stage === 'advanced-restore') {
  396. assert.ok(!['ready', 'failed'].includes(action.latestStatus.status), '仅在已有进行中任务验证等待页恢复');
  397. begin('advancedRestore', `${action.jobId}/APK强停后从入口恢复原开通等待页;不申请或重试`);
  398. deviceAdb(['shell', 'am', 'force-stop', 'cn.fmode.app']);
  399. deviceAdb(['shell', 'am', 'start', '-n', 'cn.fmode.app/.MainActivity']);
  400. state.actions.advancedRestore.restartedAt = new Date().toISOString(); save();
  401. await reconnectApp();
  402. await c.waitFor(() => location.pathname.startsWith('/mobile/'), undefined, 60000);
  403. } else {
  404. assert.ok(state.actions.advancedRestore?.attempted && state.actions.advancedRestore?.restartedAt && !state.actions.advancedRestore?.confirmedAt, '只能补查已有真实重启回执且未完成的原恢复动作');
  405. note('补查原进阶恢复动作:强停启动已发生;仅修正进度按钮实际位于plans-job-actions的定位,不再强停、申请或重试。');
  406. }
  407. assert.equal((await auth()).me?.id, state.userId);
  408. const persisted = await c.evaluate(() => localStorage.getItem('fmode_active_provision_job'));
  409. const onOriginalPage = await c.evaluate(id => location.pathname === '/provision' && new URLSearchParams(location.search).get('jobId') === id, action.jobId);
  410. if (stage === 'advanced-restore-readback' && onOriginalPage) {
  411. // 已在原任务页,重新加载仅获取新状态,不重复强停或创建。
  412. await c.send('Page.reload', { ignoreCache: true });
  413. } else {
  414. assert.equal(persisted, action.jobId, '强停后原在途任务标记丢失');
  415. await navigate('/plans');
  416. await c.waitFor(() => {
  417. const text = document.querySelector('.plans-job')?.innerText || '';
  418. return (!!document.querySelector('.plans-job-actions button') || /已就绪|开通失败/.test(text)) && !document.querySelector('app-loading-overlay');
  419. }, undefined, 60000);
  420. const canOpen = await c.evaluate(() => !![...document.querySelectorAll('.plans-job-actions button')].find(x => x.innerText.trim() === '查看开通进度'));
  421. if (canOpen) await tapText('查看开通进度');
  422. else {
  423. const terminal = await readAdvancedJob();
  424. assert.ok(['ready', 'failed'].includes(terminal.status), '页面缺少原任务进度入口且任务未终结');
  425. await c.evaluate(jobId => { history.pushState(null, '', '/provision?jobId=' + encodeURIComponent(jobId)); dispatchEvent(new PopStateEvent('popstate')); }, action.jobId);
  426. }
  427. }
  428. await c.waitFor(id => location.pathname === '/provision' && new URLSearchParams(location.search).get('jobId') === id, action.jobId);
  429. const restored = await verifyProvisionView(action.jobId);
  430. await readAdvancedJob();
  431. check('APK强停后恢复同一个进阶等待任务', true, { jobId: action.jobId });
  432. check('进阶等待页全屏且无横向溢出', await c.evaluate(() => !document.querySelector('app-mobile-shell, app-m-tab-bar, app-m-drawer') && document.documentElement.scrollWidth <= innerWidth));
  433. captureNativeScreenshot(path.join(out, 'advanced-restored-native.png'), arg('serial', '3e529a34'));
  434. done('advancedRestore', { ...restored, restored: true, creates: 0, retries: 0 });
  435. } else if (stage === 'advanced-chat') {
  436. assert.ok(!state.actions.advancedChat?.attempted, '进阶消息已有记录,只能verify-advanced-chat回读');
  437. const job = await readAdvancedJob(); assert.equal(job.status, 'ready', '进阶原任务尚未就绪');
  438. const agentId = state.actions.advancedCreate.agentId;
  439. const binding = await readBinding(agentId);
  440. assert.notEqual(binding.agentMxId, state.trial.agentMxId, '新旧容器Matrix身份必须不同');
  441. const marker = state.run + '_ADVANCED_FILES';
  442. const safeRun = state.run.toLowerCase().replaceAll('_', '-');
  443. const expectedFiles = ['advanced-' + safeRun + '.md', 'advanced-' + safeRun + '.html'];
  444. begin('advancedChat', `${agentId}/新进阶容器单次图文成果任务;不改配置或安装依赖`);
  445. Object.assign(state.actions.advancedChat, { agentId, marker, expectedFiles, bindingId: binding.objectId, phase: 'before-new-chat' }); save();
  446. await navigate('/mobile/chat/' + agentId + '/new');
  447. await c.waitFor(() => !location.pathname.endsWith('/new') && document.querySelector('textarea')?.disabled === false, undefined, 60000);
  448. const threadRoot = await c.evaluate(() => decodeURIComponent(location.pathname.split('/').at(-1)));
  449. Object.assign(state.actions.advancedChat, { threadRoot, phase: 'before-single-send' }); save();
  450. const prompt = `进阶容器实际使用验收 ${marker}。仅使用一次Python标准库在 /opt/data/work/deliverables/ 生成 ${expectedFiles.join(' 和 ')} 两份有效文件,均包含标题 Fmode advanced acceptance、完整编号 ${marker},以及表格三行 A=2879、B=179、C=64;HTML必须有完整doctype/html/body与UTF-8。不要读取其他会话、不要安装依赖或修改任何配置/插件。生成后仅回复 ${marker},让现有自动成果流程上云,不自行拼接链接。`;
  451. await c.fill('textarea', prompt); await c.waitFor(() => !document.querySelector('button.m-send')?.disabled);
  452. await c.tap('button.m-send');
  453. const action = await proveMessage('advancedChat');
  454. await c.waitFor(marker => [...document.querySelectorAll('app-assistant-turn')].some(x => x.innerText.includes(marker)), marker, 60000);
  455. done('advancedChat', { agentId, proof: action.proof, sends: 1, fileVerificationPending: true });
  456. } else if (stage === 'verify-advanced-chat') {
  457. await proveMessage('advancedChat', 30000);
  458. } else if (['advanced-files-isolation', 'advanced-files-isolation-readback', 'advanced-files-isolation-audit', 'advanced-files-isolation-audit-readback'].includes(stage)) {
  459. const task = state.actions.advancedChat; assert.ok(task?.proof?.completion, '先取得进阶单次消息完整回执');
  460. if (stage === 'advanced-files-isolation') begin('advancedFilesIsolation', `${task.agentId}/新成果真实内容、预览及双容器隔离;不发送`);
  461. else if (stage === 'advanced-files-isolation-readback') {
  462. assert.ok(state.actions.advancedFilesIsolation?.attempted && !state.actions.advancedFilesIsolation?.confirmedAt, '只能补查未完成的原成果隔离动作');
  463. note('原进阶成果隔离只读续查:按唯一URL核对交付对象,保留报告与文件台账两来源行,不重发成果任务。');
  464. } else if (stage === 'advanced-files-isolation-audit') {
  465. assert.ok(state.actions.advancedFilesIsolation?.confirmedAt, '首次成果隔离尚未完成,不能开始独立复核');
  466. begin('advancedFilesIsolationReaudit', `${task.agentId}/补验消息、成果和会话双向隔离;只读,不发送、不申请`);
  467. } else {
  468. assert.ok(state.actions.advancedFilesIsolationReaudit?.attempted && !state.actions.advancedFilesIsolationReaudit?.confirmedAt, '只读补查仅适用于未完成的双向隔离复核');
  469. note('双向隔离复核只读续查:重读已存在的进阶与试用房间/文件,沿用原输入和原proof,不发送。');
  470. }
  471. const binding = await readBinding(task.agentId);
  472. const listing = await accountApi('THXAOGKiPK', { action: 'listBySession', roomId: task.roomId, limit: 200 });
  473. const files = listing.files || [];
  474. fs.writeFileSync(path.join(out, 'advanced-file-hub-' + Date.now() + '.json'), JSON.stringify(listing, null, 2), { flag: 'wx' });
  475. // The action records predate explicit agentId on each trial task; bind their stable owner here.
  476. const trialTasks = [state.actions.trialFilesV3, state.actions.trialDocuments]
  477. .map(original => ({ ...original, agentId: state.trial.agentId }));
  478. const advancedEvents = await readRoomEvents(binding, task.roomId);
  479. fs.writeFileSync(path.join(out, 'advanced-isolation-' + Date.now() + '.json'), JSON.stringify({ side: 'advanced', history: advancedEvents, listing }, null, 2), { flag: 'wx' });
  480. const objects = assertSessionIsolation(advancedEvents, files, task, trialTasks);
  481. const urls = [];
  482. for (const { name, url } of objects) {
  483. const file = { url };
  484. assert.ok(file.url.includes('/deliverables/' + task.agentId + '/'), '进阶成果存储不属于目标容器');
  485. const response = await fetch(file.url, { signal: AbortSignal.timeout(25000) }); assert.ok(response.ok);
  486. const bytes = Buffer.from(await response.arrayBuffer()), body = bytes.toString('utf8');
  487. check('进阶成果实际字节内容 ' + name, body.includes(task.marker) && ['2879', '179', '64'].every(x => body.includes(x)), { url: file.url, sha256: createHash('sha256').update(bytes).digest('hex'), bytes: bytes.length });
  488. urls.push(file.url);
  489. }
  490. await navigate('/mobile/chat/' + task.agentId + '/' + encodeURIComponent(task.threadRoot));
  491. await c.waitFor(marker => document.body.innerText.includes(marker), task.marker, 60000);
  492. for (const name of task.expectedFiles) {
  493. await c.waitFor(name => !!document.querySelector(`[aria-label="预览 ${name}"]`), name);
  494. await c.tap(`[aria-label="预览 ${name}"]`);
  495. if (name.endsWith('.md')) await c.waitFor(marker => document.querySelector('[role="dialog"][aria-label^="预览 "]')?.innerText.includes(marker), task.marker);
  496. else {
  497. await c.waitFor(() => !!document.querySelector('iframe'));
  498. let frame;
  499. for (let n = 0; n < 50 && !frame; n++) { frame = ((await c.send('Page.getFrameTree')).frameTree.childFrames || []).find(x => x.frame.url.includes(name)); if (!frame) await pause(300); }
  500. assert.ok(frame, '进阶HTML真实文档尚未加载');
  501. await waitForPreviewText(async () => { const world = await c.send('Page.createIsolatedWorld', { frameId: frame.frame.id }); return (await c.send('Runtime.evaluate', { expression: 'document.body?.innerText || ""', contextId: world.executionContextId, returnByValue: true })).result?.value; }, task.marker);
  502. }
  503. await c.waitFor(() => !document.querySelector('.pv-stalled') && !document.querySelector('.pv-loading'));
  504. const auditSuffix = stage.startsWith('advanced-files-isolation-audit') ? `-audit-${Date.now()}` : '';
  505. captureNativeScreenshot(path.join(out, name.endsWith('.md') ? `advanced-native-md${auditSuffix}.png` : `advanced-native-html${auditSuffix}.png`), arg('serial', '3e529a34'));
  506. await c.tap('[aria-label="关闭预览"]');
  507. }
  508. const labels = await c.evaluate(() => [...document.querySelectorAll('[aria-label^="预览 "]')].map(x => x.getAttribute('aria-label')));
  509. const oldTrialFiles = trialTasks.flatMap(x => x.expectedFiles || []);
  510. check('新进阶会话只显示本任务成果卡片', task.expectedFiles.every(name => labels.includes('预览 ' + name)) && oldTrialFiles.every(name => !labels.includes('预览 ' + name)), { labels });
  511. const trialBinding = await readBinding();
  512. assert.notEqual(binding.objectId, trialBinding.objectId);
  513. for (const key of ['trialFilesV3', 'trialDocuments']) {
  514. const original = state.actions[key];
  515. const history = await readRoomEvents(trialBinding, original.roomId);
  516. const originalListing = await accountApi('THXAOGKiPK', { action: 'listBySession', roomId: original.roomId, limit: 200 });
  517. const originalFiles = originalListing.files || [];
  518. fs.writeFileSync(path.join(out, 'advanced-isolation-' + key + '-' + Date.now() + '.json'), JSON.stringify({ side: 'trial', key, history, listing: originalListing }, null, 2), { flag: 'wx' });
  519. assertSessionIsolation(history, originalFiles, { ...original, agentId: state.trial.agentId }, [task, ...trialTasks.filter(x => x !== original)]);
  520. const ownObjects = sessionFileObjects(originalFiles, state.trial.agentId, original.roomId, original.expectedFiles);
  521. check('试用原房间无进阶消息 ' + key, !history.events.some(x => x.type === 'm.room.message' && x.content?.body?.includes(task.marker)), { pages: history.pages.length, complete: history.complete });
  522. check('试用成果保持原房间归属 ' + key, ownObjects.length === original.expectedFiles.length && urls.every(url => !originalFiles.some(x => x.url === url)), { fileCount: originalFiles.length });
  523. await openTrialTask(original);
  524. const ownLabels = await c.evaluate(() => [...document.querySelectorAll('[aria-label^="预览 "]')].map(x => x.getAttribute('aria-label')));
  525. const otherNames = otherTaskFiles([task, ...trialTasks], original);
  526. check('试用会话仅显示本房间成果卡片 ' + key, original.expectedFiles.every(name => ownLabels.includes('预览 ' + name)) && otherNames.every(name => !ownLabels.includes('预览 ' + name)), { labels: ownLabels });
  527. }
  528. await openTrialTask(state.actions.trialFilesV3);
  529. check('切回试用容器无进阶成果卡片', await c.evaluate(names => names.every(name => !document.querySelector(`[aria-label="预览 ${name}"]`)), task.expectedFiles));
  530. if (stage.startsWith('advanced-files-isolation-audit')) done('advancedFilesIsolationReaudit', { agentId: task.agentId, trialAgentId: state.trial.agentId, roomId: task.roomId, urls, verifiedTasks: ['advancedChat', 'trialFilesV3', 'trialDocuments'], eventsAndFiles: true, sends: 0 });
  531. else done('advancedFilesIsolation', { agentId: task.agentId, trialAgentId: state.trial.agentId, roomId: task.roomId, urls, distinctBindings: true, sends: 0 });
  532. } else if (stage === 'relogin-readback') {
  533. assert.ok(state.actions.loginRelogin?.confirmedAt, '先完成真实短信重新登录');
  534. begin('reloginReadback', `${state.userId}/重新登录后原会话与成果恢复;不发送`);
  535. assert.equal((await auth()).me?.id, state.userId);
  536. const binding = await readBinding();
  537. const rooms = [];
  538. for (const key of ['trialFilesV3', 'trialDocuments']) {
  539. const task = state.actions[key];
  540. await openTrialTask(task);
  541. const labels = await c.evaluate(() => [...document.querySelectorAll('[aria-label^="预览 "]')].map(x => x.getAttribute('aria-label')));
  542. check('短信重登后原会话成果恢复 ' + key, task.expectedFiles.every(name => labels.includes('预览 ' + name.replaceAll('_', '-'))), { roomId: task.roomId, labels });
  543. rooms.push(task.roomId);
  544. }
  545. assert.equal(new Set(rooms).size, 2);
  546. const agents = (await accountApi('xlosi3m46q', { op: 'query', scope: 'mine' })).agents || [];
  547. check('短信重登后原有容器身份保留', state.trial.updatedInstruction.unchangedAgentIds.every(id => agents.some(x => x.agentId === id)), { agentIds: agents.map(x => x.agentId) });
  548. captureNativeScreenshot(path.join(out, 'relogin-restored-native.png'), arg('serial', '3e529a34'));
  549. done('reloginReadback', { userId: state.userId, rooms, bindingId: binding.objectId, agentIds: agents.map(x => x.agentId), sends: 0 });
  550. } else if (stage === 'mobile-baseline') {
  551. begin('mobileBaseline', `${state.userId}/APK主要页面加载、已有容器与PC成果回读;不创建、不发送`);
  552. assert.equal((await auth()).me?.id, state.userId);
  553. const views = [];
  554. for (const route of ['messages', 'contacts', 'workbench', 'my-containers', 'mine']) {
  555. await navigate('/mobile/' + route);
  556. await c.waitFor(route => !!document.querySelector('app-mb-' + route + '-page'), route);
  557. await c.waitFor(() => !document.querySelector('[aria-busy="true"]') && !/正在加载/.test(document.body.innerText), undefined, 60000);
  558. // 当前验收包可能出现更新提示,保留此已核对构建。
  559. if (await c.evaluate(() => [...document.querySelectorAll('[role="dialog"]')].some(x => x.innerText.includes('稍后再说')))) await tapText('稍后再说');
  560. const view = await snapshot();
  561. check('APK主要页面完成加载且无横向溢出 ' + route, !view.overflow && !/加载失败|登录已失效/.test(view.text), { route: view.route, viewport: view.viewport });
  562. if (route === 'my-containers') check('APK已有容器实际加载完成', view.text.includes(state.trial.agentId) && !view.text.includes('正在加载'), { text: view.text });
  563. const screenshot = 'mobile-baseline-' + route + '.png';
  564. captureNativeScreenshot(path.join(out, screenshot), arg('serial', '3e529a34'));
  565. views.push({ route: view.route, screenshot, text: view.text });
  566. }
  567. await openTrialTask(state.actions.desktopReuse);
  568. await c.waitFor(marker => [...document.querySelectorAll('app-assistant-turn')].some(x => x.innerText.includes(marker)), state.actions.desktopReuse.marker);
  569. check('APK可回读PC真实回复和复用成果卡片', await c.evaluate(() => !!document.querySelector('[aria-label="预览 trial-v3-new-mx0g1r4v.md"]')));
  570. const errors = c.events.filter(x => x.method === 'Runtime.exceptionThrown');
  571. check('APK主要页面无未处理运行异常', errors.length === 0, errors);
  572. fs.writeFileSync(path.join(out, 'mobile-baseline-views.json'), JSON.stringify(views, null, 2), { flag: 'wx' });
  573. done('mobileBaseline', { views: views.map(({ route, screenshot }) => ({ route, screenshot })), pcReadback: true, sends: 0 });
  574. } else if (stage === 'trial-cold-start') {
  575. begin('trialColdStart', `${arg('serial', '3e529a34')}/cn.fmode.app/强制停止后冷启动,回读原会话,不发送`);
  576. deviceAdb(['shell', 'am', 'force-stop', 'cn.fmode.app']);
  577. deviceAdb(['shell', 'am', 'start', '-n', 'cn.fmode.app/.MainActivity']);
  578. await reconnectApp();
  579. const view = await verifyOriginalTrial('APK 冷启动');
  580. await shot('12-trial-cold-start');
  581. done('trialColdStart', { userId: state.userId, route: view.route, screenshot: '12-trial-cold-start.png', originalTask: 'trialFilesV3' });
  582. } else if (stage === 'trial-background-start') {
  583. assert.equal((await auth()).me?.id, state.userId, '后台验收必须使用本轮账号');
  584. begin('trialBackground', `${arg('serial', '3e529a34')}/cn.fmode.app/置后台至少600秒`);
  585. const bootId = deviceAdb(['shell', 'cat', '/proc/sys/kernel/random/boot_id']);
  586. const uptime = Number(deviceAdb(['shell', 'cat', '/proc/uptime']).split(' ')[0]);
  587. assert.ok(Number.isFinite(uptime));
  588. deviceAdb(['shell', 'input', 'keyevent', 'KEYCODE_HOME']);
  589. const activity = deviceAdb(['shell', 'dumpsys', 'activity', 'activities']).split('\n').filter(x => /mResumedActivity|topResumedActivity/.test(x)).join('\n');
  590. assert.ok(activity && !activity.includes('cn.fmode.app'), '手机前台未离开 App,不能开始计算后台时间');
  591. done('trialBackground', { bootId, uptime, startedAt: new Date().toISOString(), resumeNotBefore: new Date(Date.now() + 601000).toISOString(), activity });
  592. console.log(JSON.stringify({ backgroundStarted: true, resumeNotBefore: state.actions.trialBackground.receipt.resumeNotBefore }));
  593. } else if (stage === 'trial-background-resume') {
  594. const receipt = state.actions.trialBackground?.receipt;
  595. assert.ok(receipt?.bootId, '缺少后台开始的真实回执');
  596. assert.equal(deviceAdb(['shell', 'cat', '/proc/sys/kernel/random/boot_id']), receipt.bootId, '设备已重启,不能把重启计为同一轮后台停留');
  597. const elapsed = Number(deviceAdb(['shell', 'cat', '/proc/uptime']).split(' ')[0]) - receipt.uptime;
  598. if (elapsed < 600) console.log(JSON.stringify({ backgroundResume: '尚未执行', elapsedSeconds: elapsed, requiredSeconds: 600 }));
  599. else {
  600. begin('trialBackgroundResume', `${arg('serial', '3e529a34')}/cn.fmode.app/后台${Math.floor(elapsed)}秒后恢复`);
  601. deviceAdb(['shell', 'am', 'start', '-n', 'cn.fmode.app/.MainActivity']);
  602. await reconnectApp();
  603. const view = await verifyOriginalTrial('后台超过10分钟恢复');
  604. await shot('13-trial-background-resumed');
  605. done('trialBackgroundResume', { elapsedSeconds: elapsed, userId: state.userId, route: view.route, screenshot: '13-trial-background-resumed.png' });
  606. }
  607. } else if (stage === 'trial-previews') {
  608. const task = state.actions.trialFilesV3; assert.ok(task?.proof, '先完成完整附件和成果往返');
  609. assert.equal((await auth()).me?.id, state.userId, '当前 APK 身份不是本轮账号,禁止跨账号补登记');
  610. if (!state.actions.trialExistingFileRegistration?.attempted) {
  611. begin('trialExistingFileRegistration', `${state.trial.agentId}/${task.roomId}/原会话已有两份成果自动登记;不发送聊天任务`);
  612. }
  613. await navigate('/mobile/chat/' + state.trial.agentId + '/' + encodeURIComponent(task.threadRoot));
  614. await c.waitFor(() => document.querySelector('textarea') && !document.querySelector('textarea').disabled, undefined, 60000);
  615. const events = JSON.parse(fs.readFileSync(path.join(out, 'trialFilesV3-events.json')));
  616. for (const expected of state.actions.trialFilesInputV3.receipt.files) {
  617. const event = events.find(e => e.event_id && task.proof.attachments.includes(e.event_id) && e.content?.['com.fmode.file_card']?.name === expected.name);
  618. assert.ok(event, '服务器输入附件不存在');
  619. const response = await fetch(event.content['com.fmode.file_card'].url, { signal: AbortSignal.timeout(30000) }); assert.ok(response.ok);
  620. const bytes = Buffer.from(await response.arrayBuffer());
  621. check('APK 云端输入字节一致 ' + expected.name, bytes.length === expected.bytes && createHash('sha256').update(bytes).digest('hex') === expected.sha256, { bytes: bytes.length });
  622. }
  623. let files;
  624. for (let attempt = 0; attempt < 20; attempt++) {
  625. const listing = await accountApi('THXAOGKiPK', { action: 'listBySession', roomId: task.roomId, limit: 200 });
  626. files = task.expectedFiles.map(name => (listing.files || []).find(x => x.url?.endsWith(name)));
  627. if (files.every(x => x && x.roomId === task.roomId)) break;
  628. await pause(1000);
  629. }
  630. check('两份成果均登记到本轮试用会话', files.every(x => x && x.roomId === task.roomId), files.map(x => x && ({ id: x.id, name: x.name, url: x.url, roomId: x.roomId })));
  631. if (!state.actions.trialExistingFileRegistration.confirmedAt) done('trialExistingFileRegistration', { files: files.map(x => ({ id: x.id, url: x.url, roomId: x.roomId })), source: 'APK 自行读取原回复并登记;无人工补登记、无新聊天任务' });
  632. for (const file of files) {
  633. const response = await fetch(file.url, { signal: AbortSignal.timeout(30000) }); assert.ok(response.ok);
  634. const text = await response.text();
  635. check('云端成果包含真实编号及文件尺寸 ' + file.name, [task.marker, task.inputMarker, '2879', '179', '64'].every(x => text.includes(x)));
  636. }
  637. fs.writeFileSync(path.join(out, 'trial-v3-file-hub.json'), JSON.stringify(files, null, 2));
  638. for (const name of task.expectedFiles) {
  639. await c.waitFor(name => !!document.querySelector(`[aria-label="预览 ${name}"]`), name);
  640. await c.evaluate(() => {
  641. window.__acceptancePreviewObserver?.disconnect();
  642. window.__acceptancePreviewStates = [];
  643. window.__acceptancePreviewObserver = new MutationObserver(() => {
  644. const dialog = document.querySelector('[role="dialog"][aria-label^="预览 "]');
  645. if (!dialog) return;
  646. const state = { stalled: !!dialog.querySelector('.fp-html-stall'), loading: !!dialog.querySelector('.fp-html-loading') };
  647. const previous = window.__acceptancePreviewStates.at(-1);
  648. if (!previous || previous.stalled !== state.stalled || previous.loading !== state.loading) window.__acceptancePreviewStates.push(state);
  649. });
  650. window.__acceptancePreviewObserver.observe(document.body, { childList: true, subtree: true });
  651. });
  652. await c.tap(`[aria-label="预览 ${name}"]`);
  653. await c.waitFor(() => !!document.querySelector('[role="dialog"][aria-label^="预览 "]'));
  654. if (name.endsWith('.md')) await c.waitFor(marker => document.querySelector('[role="dialog"][aria-label^="预览 "]')?.innerText.includes(marker), task.inputMarker);
  655. else {
  656. let frame;
  657. for (let n = 0; n < 30 && !frame; n++) {
  658. const tree = await c.send('Page.getFrameTree');
  659. frame = (tree.frameTree.childFrames || []).find(x => x.frame.url.includes(name));
  660. if (!frame) await pause(300);
  661. }
  662. assert.ok(frame, 'HTML 实际预览框架未加载');
  663. const world = await c.send('Page.createIsolatedWorld', { frameId: frame.frame.id });
  664. const result = await c.send('Runtime.evaluate', { expression: 'document.body.innerText', contextId: world.executionContextId, returnByValue: true });
  665. check('安卓 HTML 框架实际内容正确', result.result.value.includes(task.inputMarker) && result.result.value.includes('179'));
  666. await c.waitFor(() => {
  667. const dialog = document.querySelector('[role="dialog"][aria-label^="预览 "]');
  668. const frame = dialog?.querySelector('iframe.fp-html');
  669. return frame?.getClientRects().length && !dialog.querySelector('.fp-html-stall, .fp-html-loading');
  670. }, undefined, 45000);
  671. check('安卓 HTML 预览可见且无加载或错误遮罩', true);
  672. const states = await c.evaluate(() => window.__acceptancePreviewStates);
  673. check('安卓 HTML 加载期间未闪现失败遮罩', states.length > 0 && states.every(x => !x.stalled), states);
  674. }
  675. check('安卓实际预览 ' + name, true);
  676. await shot(name.endsWith('.md') ? '10-trial-preview-markdown' : '11-trial-preview-html');
  677. await c.tap('[aria-label="关闭预览"]');
  678. await c.waitFor(() => !document.querySelector('[role="dialog"][aria-label^="预览 "]'));
  679. await c.evaluate(() => window.__acceptancePreviewObserver?.disconnect());
  680. }
  681. state.trialCoreVerified = { at: new Date().toISOString(), text: 'trialChatReady', files: 'trialFilesV3', previews: true }; save();
  682. note('本地试用:APK 文字/快速连点、完整图片与文本字节、两份成果自动上云和归属、Markdown与HTML实际预览通过;后续补断网、重启、后台和跨会话复用。');
  683. console.log(JSON.stringify({ trialPreviews: true, files: task.expectedFiles }));
  684. } else if (['trial-files', 'trial-files-v2', 'trial-files-v3'].includes(stage)) {
  685. const number = stage.match(/-v(\d+)$/)?.[1];
  686. const revision = number ? '-v' + number : '';
  687. const key = number ? 'trialFilesV' + number : 'trialFiles';
  688. const inputKey = number ? 'trialFilesInputV' + number : 'trialFilesInput';
  689. assert.ok(state.actions.trialChatReady?.proof, '先完成本地容器真实文字往返');
  690. const current = state.actions.trialChatReady;
  691. await navigate('/mobile/chat/' + state.trial.agentId + '/' + encodeURIComponent(current.threadRoot));
  692. await c.waitFor(() => document.querySelector('textarea') && !document.querySelector('textarea').disabled, undefined, 60000);
  693. const inputMarker = 'INPUT_' + state.run;
  694. const marker = state.run + '_TRIAL_FILES' + (number ? '_V' + number : '');
  695. const textName = 'input-' + state.run + revision + '.txt'; const pictureName = 'picture-' + state.run + revision + '.png';
  696. const outputBase = 'trial' + revision + '-' + state.run.toLowerCase().replace(/_/g, '-');
  697. const fixtures = [{ name: textName, data: Buffer.from(`输入编号:${inputMarker}\n这是安卓 APK 真实附件读取验收。\n` + '文件大小验收内容。\n'.repeat(100)) }, { name: pictureName, data: pictureFixture() }];
  698. const fixtureDir = path.join(out, 'fixtures'); fs.mkdirSync(fixtureDir, { recursive: true });
  699. begin(inputKey, `${state.trial.agentId}/Android-private-cache/${fixtures.map(x => x.name).join(',')}`);
  700. for (const item of fixtures) {
  701. fs.writeFileSync(path.join(fixtureDir, item.name), item.data);
  702. assert.match(item.name, /^[A-Za-z0-9_.-]+$/);
  703. // Windows adb shell's binary stdin may treat Ctrl-Z as EOF. Transfer ASCII,
  704. // decode on device, then verify the app-private original before any upload.
  705. const result = spawnSync('adb', ['-s', arg('device', '3e529a34'), 'shell', '-T', `run-as cn.fmode.app sh -c 'base64 -d > cache/${item.name}'`], { input: item.data.toString('base64') + '\n', timeout: 20000 });
  706. assert.equal(result.status, 0, '无法准备 Android 内的真实文件');
  707. const readback = spawnSync('adb', ['-s', arg('device', '3e529a34'), 'exec-out', 'run-as', 'cn.fmode.app', 'cat', 'cache/' + item.name], { timeout: 20000 });
  708. assert.equal(readback.status, 0); assert.ok(readback.stdout.equals(item.data), 'Android 原文件与主机夹具字节不一致,禁止开始上传');
  709. }
  710. const doc = await c.send('DOM.getDocument');
  711. const node = await c.send('DOM.querySelector', { nodeId: doc.root.nodeId, selector: 'app-m-dock input[type="file"]' });
  712. assert.ok(node.nodeId, 'APK 附件输入节点不存在');
  713. await c.send('DOM.setFileInputFiles', { nodeId: node.nodeId, files: fixtures.map(x => '/data/user/0/cn.fmode.app/cache/' + x.name) });
  714. await c.waitFor(names => names.every(name => !!document.querySelector(`[aria-label="移除 ${name}"]`)), fixtures.map(x => x.name));
  715. done(inputKey, { binaryReadbackVerified: true, files: fixtures.map(x => ({ name: x.name, bytes: x.data.length, sha256: createHash('sha256').update(x.data).digest('hex') })) });
  716. await shot('08-trial-staged-files');
  717. const prompt = `安卓本地试用文件验收 ${marker}。请实际读取我附带的 ${textName} 和 ${pictureName},确认文本中的输入编号、两个文件的实际字节数、PNG尺寸。输入文件仅下载到 /opt/data/work/uploads/${outputBase}/;只用一次 terminal 或 execute_code 完成读取与生成两份文件 /opt/data/work/deliverables/${outputBase}.md 和 /opt/data/work/deliverables/${outputBase}.html,均包含输入编号、文件大小和 ${marker};HTML须能在手机阅读。自动上云 hooks 已配置,不要检查或修改其实现、系统配置或插件。生成后直接回复 ${marker},由现有自动流程交付文件。`;
  718. await c.fill('textarea', prompt);
  719. await c.waitFor(() => !document.querySelector('button.m-send')?.disabled);
  720. begin(key, `${state.trial.agentId}/${current.threadRoot}/${marker}`);
  721. Object.assign(state.actions[key], { marker, inputMarker, threadRoot: current.threadRoot, roomId: current.roomId, expectedFiles: [`${outputBase}.md`, `${outputBase}.html`] }); save();
  722. await c.tap('button.m-send');
  723. await proveMessage(key, 600000);
  724. await c.waitFor(names => names.every(name => [...document.querySelectorAll('[aria-label^="预览 "]')].some(el => el.getAttribute('aria-label').toLowerCase().endsWith(name.toLowerCase()))), state.actions[key].expectedFiles, 90000);
  725. await shot('09-trial-files-received');
  726. check('安卓真实图文附件与两份成果卡片完整显示', true);
  727. done(key, { proof: state.actions[key].proof, files: state.actions[key].expectedFiles });
  728. console.log(JSON.stringify({ filesRoundtrip: true, files: state.actions[key].expectedFiles }));
  729. } else if (stage === 'verify-trial-files') {
  730. await proveMessage('trialFiles', 30000);
  731. console.log(JSON.stringify({ proof: state.actions.trialFiles.proof }));
  732. } else if (stage === 'trial-chat' || stage === 'trial-chat-ready') {
  733. const key = stage === 'trial-chat' ? 'trialChat' : 'trialChatReady';
  734. assert.equal((await auth()).me?.id, state.userId, '当前 APK 身份不属于本轮账号');
  735. const live = await accountApi('xlosi3m46q', { op: 'query', scope: 'mine' });
  736. const agent = live.agents?.find(x => x.agentId === state.trial.agentId);
  737. check('本地试用容器真实首报且 Matrix 连接', agent?.channels?.matrixConfig?.channelState === 'connected' && Number.isFinite(agent?.heartbeatAgeSec), { agentId: agent?.agentId, status: agent?.status, heartbeatAgeSec: agent?.heartbeatAgeSec });
  738. await navigate('/mobile/chat/' + state.trial.agentId + '/new');
  739. await c.waitFor(() => !location.pathname.endsWith('/new') && document.querySelector('textarea') && !document.querySelector('textarea').disabled, undefined, 60000);
  740. const marker = state.run + (key === 'trialChat' ? '_TRIAL_TEXT' : '_TRIAL_TEXT_READY');
  741. await c.fill('textarea', `这是安卓本地试用接入验收,只回复 ${marker}。不要使用工具,不修改文件或配置。`);
  742. await c.waitFor(marker => document.querySelector('textarea')?.value.includes(marker) && !document.querySelector('button.m-send')?.disabled, marker);
  743. await pause(150); await shot(key + '-before-send');
  744. begin(key, state.trial.agentId + '/' + marker);
  745. state.actions[key].marker = marker; save();
  746. await c.evaluate(() => { const button = document.querySelector('button.m-send'); button.click(); button.click(); button.click(); });
  747. await pause(1000);
  748. state.actions[key].threadRoot = await c.evaluate(() => decodeURIComponent(location.pathname.split('/').at(-1))); save();
  749. await proveMessage(key);
  750. await c.waitFor(marker => [...document.querySelectorAll('app-assistant-turn')].some(x => x.innerText.includes(marker)), marker, 60000);
  751. check('本地试用真实回复在 APK 可见', true);
  752. check('三次连点后输入框清空', await c.evaluate(() => document.querySelector('textarea')?.value === ''));
  753. const view = await snapshot(); check('试用聊天无横向溢出', !view.overflow);
  754. await shot('07-trial-chat-verified');
  755. done(key, { proof: state.actions[key].proof, route: view.route });
  756. console.log(JSON.stringify({ trialTextRoundtrip: true, roomId: state.actions[key].roomId }));
  757. } else if (stage === 'verify-trial-chat') {
  758. await proveMessage('trialChat', 30000);
  759. console.log(JSON.stringify({ proof: state.actions.trialChat.proof }));
  760. } else if (stage === 'trial-isolation-send') {
  761. begin('trialIsolationSeed', `${state.trial.agentId}/新建一个隔离验收文字会话,单次发送;不新增容器`);
  762. assert.equal((await auth()).me?.id, state.userId);
  763. const marker = state.run + '_TRIAL_ISOLATION';
  764. state.actions.trialIsolationSeed.marker = marker; save();
  765. await navigate('/mobile/chat/' + state.trial.agentId + '/new');
  766. await c.waitFor(() => !location.pathname.endsWith('/new') && document.querySelector('textarea') && !document.querySelector('textarea').disabled, undefined, 60000);
  767. const threadRoot = await c.evaluate(() => decodeURIComponent(location.pathname.split('/').at(-1)));
  768. assert.notEqual(threadRoot, state.actions.trialFilesV3.threadRoot, '新会话不能复用原线程');
  769. check('新会话发送前没有原会话内容或成果', await c.evaluate(marker => !document.body.innerText.includes(marker), state.actions.trialFilesV3.marker));
  770. Object.assign(state.actions.trialIsolationSeed, { threadRoot, phase: 'before-single-send' }); save();
  771. await c.fill('textarea', `会话隔离验收:只回复 ${marker}。不要使用工具、不读取其他会话、不创建文件或修改任何配置。`);
  772. await c.waitFor(() => !document.querySelector('button.m-send')?.disabled);
  773. await c.tap('button.m-send');
  774. await proveMessage('trialIsolationSeed');
  775. await c.waitFor(marker => [...document.querySelectorAll('app-assistant-turn')].some(x => x.innerText.includes(marker)), marker, 60000);
  776. await shot('14-trial-isolation-seed');
  777. done('trialIsolationSeed', { proof: state.actions.trialIsolationSeed.proof, threadRoot, screenshot: '14-trial-isolation-seed.png' });
  778. } else if (stage === 'verify-trial-isolation-send') {
  779. await proveMessage('trialIsolationSeed', 30000);
  780. } else if (['trial-isolation', 'trial-isolation-verify', 'trial-isolation-readback'].includes(stage)) {
  781. const actionKey = stage === 'trial-isolation' ? 'trialIsolation' : 'trialIsolationVerified';
  782. if (stage === 'trial-isolation-readback') {
  783. assert.ok(state.actions[actionKey]?.attempted && !state.actions[actionKey]?.confirmedAt, '只允许只读补查尚未完成的隔离核验');
  784. } else begin(actionKey, `${state.trial.agentId}/两个已有会话切换及成果归属;不创建、不发送`);
  785. assert.equal((await auth()).me?.id, state.userId);
  786. done(actionKey, await verifyIsolationViews('14-trial-isolation'));
  787. } else if (stage === 'trial-fresh-chat') {
  788. begin('trialFreshChat', `${state.trial.agentId}/新隔离卷实例真实首报及原会话单次文字往返`);
  789. assert.equal((await auth()).me?.id, state.userId);
  790. const runtime = state.actions.localPromptFresh;
  791. assert.ok(runtime?.confirmedAt && runtime.containerId, '先完成真实APK提示词隔离卷安装');
  792. const inspect = name => {
  793. const result = spawnSync('docker', ['inspect', name], { encoding: 'utf8', timeout: 20000, windowsHide: true });
  794. assert.equal(result.status, 0, '实际运行实例不可核实'); return JSON.parse(result.stdout)[0];
  795. };
  796. const liveRuntime = inspect(runtime.target);
  797. assert.equal(liveRuntime.Id, runtime.containerId); assert.equal(liveRuntime.State.Running, true);
  798. assert.ok(liveRuntime.Mounts.some(x => x.Name === runtime.volume && x.Destination === '/opt/data'));
  799. for (const key of ['localRaw', 'localCandidate']) assert.equal(inspect(state.actions[key].target).State.Running, false, '同Matrix身份旧实例仍运行');
  800. let agent;
  801. for (let n = 0; n < 30; n++) {
  802. const listing = await accountApi('xlosi3m46q', { op: 'query', scope: 'mine' });
  803. agent = listing.agents?.find(x => x.agentId === state.trial.agentId);
  804. if (agent?.channels?.matrixConfig?.channelState === 'connected' && Number.isFinite(agent.heartbeatAgeSec) && agent.heartbeatAgeSec <= 120) break;
  805. await pause(1000);
  806. }
  807. check('真实APK提示词新实例平台首报及Matrix在线', agent?.channels?.matrixConfig?.channelState === 'connected' && Number.isFinite(agent.heartbeatAgeSec) && agent.heartbeatAgeSec <= 120, { agentId: agent?.agentId, heartbeatAgeSec: agent?.heartbeatAgeSec, containerId: runtime.containerId });
  808. const source = state.actions.trialIsolationSeed;
  809. await openTrialTask(source);
  810. const marker = state.run + '_TRIAL_PROMPT_FRESH';
  811. Object.assign(state.actions.trialFreshChat, { marker, roomId: source.roomId, threadRoot: source.threadRoot, bundleSha256: runtime.bundleSha256, containerId: runtime.containerId, phase: 'before-single-send' }); save();
  812. await c.fill('textarea', `这是新隔离卷按APK提示词从零接入验收。只回复 ${marker}。不要使用工具、不修改文件或配置、不引用旧文件。`);
  813. await c.waitFor(() => !document.querySelector('button.m-send')?.disabled);
  814. await c.tap('button.m-send');
  815. const action = await proveMessage('trialFreshChat');
  816. await c.waitFor(marker => [...document.querySelectorAll('app-assistant-turn')].some(x => x.innerText.includes(marker)), marker, 60000);
  817. check('从零接入后原会话真实回复无旧附件污染', !/https?:\/\/|已上云|MEDIA:/.test(action.proof.body), { body: action.proof.body });
  818. await shot('23-trial-prompt-fresh-chat');
  819. done('trialFreshChat', { proof: action.proof, containerId: runtime.containerId, volume: runtime.volume, bundleSha256: runtime.bundleSha256, heartbeatAgeSec: agent.heartbeatAgeSec, screenshot: '23-trial-prompt-fresh-chat.png', sends: 1 });
  820. } else if (stage === 'verify-trial-fresh-chat') {
  821. await proveMessage('trialFreshChat', 30000);
  822. } else if (stage === 'trial-documents') {
  823. begin('trialDocuments', `${state.trial.agentId}/既有隔离会话单次请求生成PDF和Word;不改配置/不安装依赖`);
  824. assert.equal((await auth()).me?.id, state.userId);
  825. const source = state.actions.trialIsolationSeed;
  826. await openTrialTask(source);
  827. const marker = state.run + '_TRIAL_DOCUMENTS';
  828. const names = ['preview-' + state.run.toLowerCase() + '.pdf', 'preview-' + state.run.toLowerCase() + '.docx'];
  829. Object.assign(state.actions.trialDocuments, { marker, roomId: source.roomId, threadRoot: source.threadRoot, expectedFiles: names, phase: 'before-single-send' }); save();
  830. const prompt = `本轮PDF/Word实际预览验收 ${marker}。仅用Python标准库(不得安装依赖),在 /opt/data/work/deliverables/ 生成 ${names[0]} 和 ${names[1]} 两份有效文档。内容均为一页,标题 Fmode trial document preview,正文必须完整包含 ${marker}。PDF请使用有效PDF1.4结构、Helvetica字体和未压缩内容流(编号不换行);Word请使用有效DOCX/OpenXML,ZIP_STORED存储document.xml以便字节核对。仅允许一次terminal或execute_code完成生成,不下载输入、不改任何配置或插件。自动成果hooks已配置,生成后仅回复 ${marker},由现有流程上云,不自行拼接URL。`;
  831. await c.fill('textarea', prompt);
  832. await c.waitFor(() => !document.querySelector('button.m-send')?.disabled);
  833. await c.tap('button.m-send');
  834. const action = await proveMessage('trialDocuments', 240000);
  835. await c.waitFor(marker => [...document.querySelectorAll('app-assistant-turn')].some(x => x.innerText.includes(marker)), marker, 60000);
  836. done('trialDocuments', { proof: action.proof, expectedFiles: names, sends: 1 });
  837. } else if (stage === 'verify-trial-documents') {
  838. await proveMessage('trialDocuments', 30000);
  839. } else if (stage === 'trial-document-previews' || stage === 'trial-document-previews-readback') {
  840. if (stage === 'trial-document-previews-readback') assert.ok(state.actions.trialDocumentPreviews?.attempted && !state.actions.trialDocumentPreviews?.confirmedAt, '只读补查仅适用于未完成的文档预览');
  841. else begin('trialDocumentPreviews', `${state.trial.agentId}/本轮两份PDF和Word实际字节、会话归属和APK canvas预览;不发送`);
  842. assert.equal((await auth()).me?.id, state.userId);
  843. const task = state.actions.trialDocuments;
  844. await openTrialTask(task);
  845. let files;
  846. for (let attempt = 0; attempt < 45; attempt++) {
  847. const listing = await accountApi('THXAOGKiPK', { action: 'listBySession', roomId: task.roomId, limit: 200 });
  848. files = task.expectedFiles.map(name => (listing.files || []).find(x => [name, name.replaceAll('_', '-')].some(expected => x.url?.endsWith(expected))));
  849. if (files.every(x => x?.roomId === task.roomId)) break;
  850. await pause(1000);
  851. }
  852. check('本轮PDF及Word均自动登记到当前会话', files.every(x => x?.roomId === task.roomId), files.map(x => x && ({ id: x.id, name: x.name, roomId: x.roomId })));
  853. const hubEvidence = stage === 'trial-document-previews' ? 'trial-documents-file-hub.json' : 'trial-documents-file-hub-readback-' + Date.now() + '.json';
  854. fs.writeFileSync(path.join(out, hubEvidence), JSON.stringify(files, null, 2), { flag: 'wx' });
  855. const receipts = [];
  856. for (let index = 0; index < task.expectedFiles.length; index++) {
  857. const name = task.expectedFiles[index], file = files[index];
  858. const response = await fetch(file.url, { signal: AbortSignal.timeout(30000) }); assert.ok(response.ok);
  859. const bytes = Buffer.from(await response.arrayBuffer());
  860. const format = name.endsWith('.pdf') ? bytes.subarray(0, 5).toString() === '%PDF-' : bytes.subarray(0, 4).toString('hex') === '504b0304';
  861. check('本轮文档真实字节、格式及编号 ' + name, format && bytes.includes(Buffer.from(task.marker)), { bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') });
  862. const previewLabel = await c.waitFor(names => names.map(name => document.querySelector(`[aria-label="预览 ${name}"]`)).find(x => x?.getClientRects().length)?.getAttribute('aria-label'), [name, name.replaceAll('_', '-')], 45000);
  863. await c.tap(`[aria-label="${previewLabel}"]`);
  864. await c.waitFor(() => {
  865. const dialog = document.querySelector('[role="dialog"][aria-label^="预览 "]');
  866. return [...(dialog?.querySelectorAll('canvas') || [])].some(x => x.width > 100 && x.height > 100 && x.getClientRects().length);
  867. }, undefined, 60000);
  868. const pixels = await c.evaluate(() => {
  869. const dialog = document.querySelector('[role="dialog"][aria-label^="预览 "]');
  870. const canvas = [...dialog.querySelectorAll('canvas')].find(x => x.width > 100 && x.getClientRects().length);
  871. const data = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).data;
  872. let dark = 0;
  873. for (let i = 0; i < data.length; i += 16) if (data[i + 3] > 0 && data[i] < 210 && data[i + 1] < 210 && data[i + 2] < 210) dark++;
  874. return { width: canvas.width, height: canvas.height, darkPixels: dark, error: !!dialog.querySelector('.err') };
  875. });
  876. check('APK文档canvas有真实可见内容 ' + name, pixels.darkPixels > 25 && !pixels.error, pixels);
  877. const screenshot = '22-trial-document-' + (name.endsWith('.pdf') ? 'pdf' : 'word');
  878. await c.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)))));
  879. captureNativeScreenshot(path.join(out, screenshot + '.png'), arg('serial', '3e529a34'));
  880. receipts.push({ name, url: file.url, bytes: bytes.length, ...pixels, screenshot: screenshot + '.png' });
  881. await c.tap('[aria-label="关闭预览"]');
  882. await c.waitFor(() => !document.querySelector('[role="dialog"][aria-label^="预览 "]'));
  883. }
  884. done('trialDocumentPreviews', { files: receipts, hubEvidence, sends: 0 });
  885. } else if (stage === 'trial-clean-output') {
  886. begin('trialCleanOutput', `${state.trial.agentId}/修复后在原文件会话发送一个纯文字探针;不生成文件`);
  887. assert.equal((await auth()).me?.id, state.userId);
  888. const source = state.actions.trialFilesV3;
  889. await openTrialTask(source);
  890. const marker = state.run + '_TRIAL_CLEAN_OUTPUT';
  891. Object.assign(state.actions.trialCleanOutput, { marker, roomId: source.roomId, threadRoot: source.threadRoot,
  892. bundleSha256: state.actions.localCandidate.bundleSha256, phase: 'before-single-send' }); save();
  893. await c.fill('textarea', `只回复 ${marker}。本轮只验证普通文字回复,不使用工具、不生成或修改任何文件、不引用或重复之前的文件和链接。`);
  894. await c.waitFor(() => !document.querySelector('button.m-send')?.disabled);
  895. await c.tap('button.m-send');
  896. const action = await proveMessage('trialCleanOutput');
  897. await c.waitFor(marker => [...document.querySelectorAll('app-assistant-turn')].some(x => x.innerText.includes(marker)), marker, 60000);
  898. check('修复后原文件会话纯文字回复不附带旧输入或成果', !/https?:\/\/|已上云|MEDIA:/.test(action.proof.body), { body: action.proof.body });
  899. const labels = await c.evaluate(marker => {
  900. const turn = [...document.querySelectorAll('app-assistant-turn')].find(x => x.innerText.includes(marker));
  901. if (!turn) return null;
  902. turn.scrollIntoView({ block: 'center' });
  903. return [...turn.querySelectorAll('button[aria-label^="预览 "]')].map(x => x.getAttribute('aria-label'));
  904. }, marker);
  905. check('修复后纯文字回复无旧文件卡片', Array.isArray(labels) && labels.length === 0, { labels });
  906. await shot('21-trial-clean-output');
  907. done('trialCleanOutput', { proof: action.proof, screenshot: '21-trial-clean-output.png', sends: 1 });
  908. } else if (stage === 'verify-trial-clean-output') {
  909. await proveMessage('trialCleanOutput', 30000);
  910. } else if (stage === 'trial-evidence-audit') {
  911. begin('trialEvidenceAudit', `${state.trial.agentId}/补强后的完整事件、可见卡片和真实loader审计;不发送/重试`);
  912. assert.equal((await auth()).me?.id, state.userId);
  913. for (const key of ['trialFilesV3', 'trialIsolationSeed', 'trialOffline']) await proveMessage(key, 30000);
  914. const isolation = await verifyIsolationViews('19-trial-isolation-audit');
  915. await openTrialTask(state.actions.trialFilesV3);
  916. const name = state.actions.trialFilesV3.expectedFiles.find(x => x.endsWith('.html'));
  917. await c.tap(`[aria-label="预览 ${name}"]`);
  918. const before = await readHtmlPreview(state.actions.trialFilesV3.inputMarker);
  919. await c.tap('[aria-label="重新加载"]');
  920. const after = await readHtmlPreview(state.actions.trialFilesV3.inputMarker, before);
  921. check('安卓 HTML 重新加载产生新loader且真实内容可见', newFrameLoader(before, after), { before, after });
  922. await shot('20-trial-html-loader-audit');
  923. await c.tap('[aria-label="关闭预览"]');
  924. done('trialEvidenceAudit', { isolation, htmlReload: { beforeLoader: before.loaderId, afterLoader: after.loaderId }, sends: 0, retryClicks: 0 });
  925. } else if (stage === 'trial-links-refresh') {
  926. begin('trialLinksRefresh', `${state.trial.agentId}/原成果复制链接、真实粘贴与HTML重新加载;不发送`);
  927. assert.equal((await auth()).me?.id, state.userId);
  928. const task = state.actions.trialFilesV3;
  929. await openTrialTask(task);
  930. const previousDraft = await c.evaluate(() => document.querySelector('textarea').value);
  931. assert.equal(previousDraft, '', '输入框有用户草稿,停止粘贴验收以免覆盖');
  932. const files = JSON.parse(fs.readFileSync(path.join(out, 'trial-v3-file-hub.json')));
  933. const results = [];
  934. for (const name of task.expectedFiles) {
  935. const file = files.find(x => x.url.endsWith(name)); assert.ok(file);
  936. await c.tap(`[aria-label="预览 ${name}"]`);
  937. await c.waitFor(() => !!document.querySelector('[role="dialog"][aria-label^="预览 "]'));
  938. if (name.endsWith('.html')) {
  939. const before = await readHtmlPreview(task.inputMarker);
  940. await c.tap('[aria-label="重新加载"]');
  941. await readHtmlPreview(task.inputMarker, before);
  942. check('安卓 HTML 重新加载后真实内容及可见预览', true);
  943. } else await c.waitFor(marker => document.querySelector('[role="dialog"][aria-label^="预览 "]')?.innerText.includes(marker), task.inputMarker);
  944. await c.tap('[aria-label="复制链接"], [aria-label="已复制链接"]');
  945. await c.waitFor(() => !!document.querySelector('[aria-label="已复制链接"]'));
  946. check('安卓复制反馈与无悬浮提示 ' + name, await c.evaluate(() => ![...document.querySelectorAll('[role="tooltip"]')].some(x => x.getClientRects().length)));
  947. await shot(name.endsWith('.md') ? '15-trial-copy-md' : '16-trial-copy-html');
  948. await c.tap('[aria-label="关闭预览"]');
  949. await c.waitFor(() => !document.querySelector('[role="dialog"][aria-label^="预览 "]'));
  950. await c.tap('textarea');
  951. deviceAdb(['shell', 'input', 'keyevent', 'KEYCODE_PASTE']);
  952. await c.waitFor(url => document.querySelector('textarea')?.value === url, file.url, 10000);
  953. const pasted = await c.evaluate(() => document.querySelector('textarea').value);
  954. check('安卓系统剪贴板真实粘贴URL一致 ' + name, pasted === file.url, { url: pasted });
  955. await c.fill('textarea', '');
  956. deviceAdb(['shell', 'input', 'keyevent', 'KEYCODE_BACK']);
  957. results.push({ name, url: pasted, htmlReload: name.endsWith('.html') });
  958. }
  959. done('trialLinksRefresh', { files: results, copiedBy: 'APK复制按钮→Android KEYCODE_PASTE→原输入框回读;未注入剪贴板或发送', sends: 0 });
  960. } else if (stage === 'trial-offline') {
  961. begin('trialOffline', `${state.trial.agentId}/原文字会话断网发送一次;先证实服务器零事件再单独重试`);
  962. assert.equal((await auth()).me?.id, state.userId);
  963. const task = state.actions.trialChatReady;
  964. await openTrialTask(task);
  965. const binding = await readBinding();
  966. const marker = state.run + '_TRIAL_OFFLINE';
  967. const prompt = `这是安卓断网恢复验收,只回复 ${marker}。不要使用工具,不修改任何文件或配置。`;
  968. Object.assign(state.actions.trialOffline, { marker, prompt, roomId: task.roomId, threadRoot: task.threadRoot, phase: 'before-offline' }); save();
  969. assert.equal(ownInputs((await readRoomEvents(binding, task.roomId)).events, binding, marker).length, 0);
  970. try {
  971. networkOverridden = true;
  972. await c.send('Network.emulateNetworkConditions', { offline: true, latency: 0, downloadThroughput: -1, uploadThroughput: -1 });
  973. state.actions.trialOffline.phase = 'offline-before-send'; save();
  974. await c.waitFor(() => navigator.onLine === false);
  975. await c.fill('textarea', prompt);
  976. await c.waitFor(() => !document.querySelector('button.m-send')?.disabled);
  977. state.actions.trialOffline.phase = 'before-single-tap'; save();
  978. await c.tap('button.m-send');
  979. state.actions.trialOffline.phase = 'offline-tap-complete'; save();
  980. await c.waitFor(marker => [...document.querySelectorAll('app-m-msg')].some(x => x.innerText.includes(marker) && x.innerText.includes('发送失败')), marker, 15000);
  981. check('断网消息有明确失败与重试入口', true);
  982. const history = await readRoomEvents(binding, task.roomId);
  983. fs.writeFileSync(path.join(out, 'trial-offline-server-before-retry.json'), JSON.stringify(history, null, 2), { flag: 'wx' });
  984. const inputs = ownInputs(history.events, binding, marker);
  985. check('断网失败消息服务器零输入事件', inputs.length === 0, { roomId: task.roomId, count: inputs.length });
  986. await c.evaluate(marker => [...document.querySelectorAll('app-m-msg')].find(x => x.innerText.includes(marker) && x.innerText.includes('发送失败'))?.scrollIntoView({ block: 'center' }), marker);
  987. await shot('17-trial-offline-failed');
  988. } finally {
  989. await c.send('Network.emulateNetworkConditions', { offline: false, latency: 0, downloadThroughput: -1, uploadThroughput: -1 });
  990. networkOverridden = false;
  991. state.actions.trialOffline.networkRestoredAt = new Date().toISOString(); save();
  992. }
  993. await c.waitFor(() => navigator.onLine === true);
  994. done('trialOffline', { roomId: task.roomId, marker, serverInputCount: 0, networkRestored: true, screenshot: '17-trial-offline-failed.png', retryPending: true });
  995. } else if (stage === 'trial-offline-retry') {
  996. assert.ok(!state.actions.trialOfflineRetry?.attempted, '断网重试已有动作记录,必须只读核实,不重复点击');
  997. const task = state.actions.trialOffline;
  998. assert.ok(task?.confirmedAt && task.receipt?.serverInputCount === 0 && task.networkRestoredAt, '先完成断网失败及网络恢复回验');
  999. assert.equal((await auth()).me?.id, state.userId);
  1000. const binding = await readBinding();
  1001. await c.waitFor(() => navigator.onLine && !document.body.innerText.includes('连接已断开'), undefined, 60000);
  1002. const point = await c.evaluate(marker => {
  1003. const candidates = [...document.querySelectorAll('app-m-msg')].filter(x => x.innerText.includes(marker));
  1004. if (candidates.length !== 1) return null;
  1005. const button = [...candidates[0].querySelectorAll('button')].find(x => x.innerText.includes('发送失败') && x.getClientRects().length);
  1006. if (!button) return null;
  1007. button.scrollIntoView({ block: 'center' }); const r = button.getBoundingClientRect();
  1008. return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
  1009. }, task.marker);
  1010. assert.ok(point, '原失败消息或唯一重试按钮不可见,停止而不新建消息替代');
  1011. const history = await checkRetryUnsent(async () => {
  1012. await c.waitFor(() => navigator.onLine && !document.body.innerText.includes('连接已断开'), undefined, 60000);
  1013. }, () => readRoomEvents(binding, task.roomId), binding, task.marker);
  1014. fs.writeFileSync(path.join(out, 'trial-offline-retry-preflight.json'), JSON.stringify(history, null, 2), { flag: 'wx' });
  1015. begin('trialOfflineRetry', `${state.trial.agentId}/${task.roomId}/${task.marker}/仅点原失败消息重试一次`);
  1016. await c.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [point] });
  1017. await c.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
  1018. await proveMessage('trialOffline');
  1019. await c.waitFor(marker => [...document.querySelectorAll('app-assistant-turn')].some(x => x.innerText.includes(marker)), task.marker, 60000);
  1020. check('断网恢复单次重试后真实回复与结束信号可见', true);
  1021. await shot('18-trial-offline-recovered');
  1022. done('trialOfflineRetry', { proof: task.proof, screenshot: '18-trial-offline-recovered.png', retryClicks: 1 });
  1023. } else if (stage === 'verify-trial-offline') {
  1024. await proveMessage('trialOffline', 30000);
  1025. console.log(JSON.stringify({ proof: state.actions.trialOffline.proof, retry: state.actions.trialOfflineRetry }));
  1026. } else if (stage === 'trial-refresh') {
  1027. assert.ok(state.actions.cloudPrompt?.confirmedAt, '新提示词云函数尚无定向部署回验');
  1028. const account = JSON.parse(fs.readFileSync(accountFile));
  1029. assert.equal((await auth()).me?.id, state.userId, '真机身份不属于本轮账号');
  1030. const bindingBefore = await readBinding();
  1031. const before = await accountApi('xlosi3m46q', { op: 'query', scope: 'mine' });
  1032. const idsBefore = (before.agents || []).map(x => x.agentId).sort();
  1033. begin('trialPromptRefresh', `${state.userId}/${state.trial.agentId}/已部署新版提示词;不得新增绑定或容器`);
  1034. await navigate('/plans');
  1035. await c.waitFor(() => !!document.querySelector('.plans-trial-btn'));
  1036. await c.tap('.plans-trial-btn');
  1037. await c.waitFor(() => document.querySelector('app-provision-instruction .ins-code')?.innerText.includes('接入包版本:'), undefined, 90000);
  1038. const instruction = await c.evaluate(() => document.querySelector('app-provision-instruction .ins-code').innerText);
  1039. const env = Object.fromEntries(instruction.split('\n').map(line => line.match(/^([A-Z][A-Z0-9_]*)=(.*)$/)).filter(Boolean).map(([, key, value]) => [key, value.trim()]));
  1040. assert.equal(env.AGENT_ID, state.trial.agentId, '刷新提示词意外产生不同试用身份,停止操作');
  1041. assert.equal(env.MATRIX_USER_ID, state.trial.agentMxId);
  1042. assert.equal(env.FMODE_SESSION_TOKEN, account.token);
  1043. const bundle = JSON.parse(fs.readFileSync('cloud/onboarding/bundle.json'));
  1044. assert.ok(instruction.includes(bundle.sha256) && instruction.includes(bundle.url), 'APK 未取得已回验的固定接入包');
  1045. const bindingAfter = await readBinding();
  1046. assert.equal(bindingAfter.objectId, bindingBefore.objectId, '提示词刷新改变了既有绑定');
  1047. const after = await accountApi('xlosi3m46q', { op: 'query', scope: 'mine' });
  1048. assert.deepEqual((after.agents || []).map(x => x.agentId).sort(), idsBefore, '提示词刷新新增了容器,停止后续动作');
  1049. fs.writeFileSync(path.join(privateDir, 'trial-instruction-updated.md'), instruction);
  1050. fs.writeFileSync(path.join(privateDir, 'trial-env-updated.json'), JSON.stringify(env, null, 2));
  1051. const receipt = { agentId: env.AGENT_ID, agentMxId: env.MATRIX_USER_ID, bindingId: bindingAfter.objectId, instructionSha256: createHash('sha256').update(instruction).digest('hex'), bundleSha256: bundle.sha256, bundle, unchangedAgentIds: idsBefore };
  1052. state.trial.updatedInstruction = receipt; save();
  1053. done('trialPromptRefresh', receipt);
  1054. await c.screenshot(path.join(privateDir, 'trial-instruction-updated.png'));
  1055. check('APK 取得新版真实提示词且未新增容器或绑定', true, receipt);
  1056. console.log(JSON.stringify({ updatedInstructionCaptured: true, ...receipt }));
  1057. } else if (stage === 'trial' || stage === 'capture-trial') {
  1058. const account = JSON.parse(fs.readFileSync(accountFile, 'utf8'));
  1059. assert.equal((await auth()).me?.id, account.userId, '真机当前身份不属于本轮账号');
  1060. if (stage === 'trial') {
  1061. await navigate('/plans');
  1062. await c.waitFor(() => !!document.querySelector('.plans-trial-btn'));
  1063. await shot('04-trial-before');
  1064. begin('trial', `${account.userId}/trial/我的试用容器`);
  1065. await c.tap('.plans-trial-btn');
  1066. } else assert.ok(state.actions.trial?.attempted, '无试用创建记录,不能接管');
  1067. await c.waitFor(() => !!document.querySelector('app-provision-instruction .ins-code')?.innerText.includes('AGENT_ID='), undefined, 90000);
  1068. const instruction = await c.evaluate(() => document.querySelector('app-provision-instruction .ins-code').innerText);
  1069. const env = Object.fromEntries(instruction.split('\n').map(line => line.match(/^([A-Z][A-Z0-9_]*)=(.*)$/)).filter(Boolean).map(([, k, v]) => [k, v.trim()]));
  1070. for (const key of ['AGENT_ID', 'MATRIX_USER_ID', 'MATRIX_PASSWORD', 'MATRIX_HOME_ROOM', 'FMODE_SESSION_TOKEN']) assert.ok(env[key], `提示词缺少 ${key}`);
  1071. assert.equal(env.FMODE_SESSION_TOKEN, account.token, '提示词不是本账号当前登录态');
  1072. fs.writeFileSync(path.join(privateDir, 'trial-instruction.md'), instruction);
  1073. fs.writeFileSync(path.join(privateDir, 'trial-env.json'), JSON.stringify(env, null, 2));
  1074. state.trial = { agentId: env.AGENT_ID, agentMxId: env.MATRIX_USER_ID, roomId: env.MATRIX_HOME_ROOM, instructionSha256: createHash('sha256').update(instruction).digest('hex') };
  1075. state.assets.push({ kind: 'trial-binding', ...state.trial, owner: account.userId });
  1076. done('trial', state.trial);
  1077. await shot('05-trial-instruction');
  1078. check('APK 试用入口生成本账号真实接入参数', true, state.trial);
  1079. console.log(JSON.stringify({ instructionSaved: true, ...state.trial }));
  1080. } else throw Error('未知阶段:' + stage);
  1081. } catch (error) {
  1082. if (lock !== undefined && state) {
  1083. state.lastFailure = { stage, message: error.message, at: new Date().toISOString() };
  1084. save(); note(`${stage} 未完成:${error.message}。先只读核实,不重复请求。`);
  1085. if (c) await shot(`${stage}-failure`).catch(() => {});
  1086. }
  1087. throw error;
  1088. } finally {
  1089. if (networkOverridden && c) {
  1090. await c.send('Network.emulateNetworkConditions', { offline: false, latency: 0, downloadThroughput: -1, uploadThroughput: -1 }).catch(error => note('网络仿真恢复未确认:' + error.message + ';先检查设备网络,禁止重试发送。'));
  1091. }
  1092. c?.close();
  1093. if (lock !== undefined) { fs.closeSync(lock); fs.unlinkSync(lockFile); }
  1094. }