/** 新账号真机验收。真实动作先登记;重启后先 status,不重复请求或创建。 */ import { recordProgress } from './lib/project-recovery.mjs'; import fs from 'node:fs'; import path from 'node:path'; import assert from 'node:assert/strict'; import { createHash } from 'node:crypto'; import { spawnSync } from 'node:child_process'; import { deflateSync } from 'node:zlib'; import { connectWebView, captureNativeScreenshot } from './android-webview-cdp.mjs'; import { readMatrixHistory, taskProof, retainFirstProof, checkRetryUnsent, newFrameLoader, waitForPreviewText, previewCardsMatch, resolveTaskThread, sessionFileObjects, assertSessionIsolation, otherTaskFiles } from './lib/acceptance-evidence.mjs'; const arg = (name, fallback) => process.argv.find(x => x.startsWith(`--${name}=`))?.slice(name.length + 3) ?? fallback; const stage = arg('stage', 'status'); const phone = arg('phone', '18182795512'); assert.match(phone, /^1\d{10}$/, '必须提供明确的测试手机号'); const out = path.resolve(arg('out', 'test-results/new-account-20261128')); const accountFile = path.resolve(arg('account-file', '.local-backup/new-account-20261128/account.json')); const privateDir = path.dirname(accountFile); const checkpoint = path.resolve('docs/00-tracking/接续检查点.md'); assert.ok(fs.existsSync(checkpoint), '请从项目根目录执行'); assert.ok(fs.existsSync(path.join(out, 'state.json')), '先登记本轮执行目标并建立 state.json'); const stateFile = path.join(out, 'state.json'); let state; const lockFile = path.join(out, 'runner.lock'); let lock, c, networkOverridden = false; const save = () => { fs.writeFileSync(stateFile + '.next', JSON.stringify(state, null, 2) + '\n'); fs.renameSync(stateFile + '.next', stateFile); }; const note = text => recordProgress(process.cwd(), `[${out}] ${text}`); const begin = (key, target) => { assert.ok(!state.actions[key]?.attempted, `${key} 已有动作记录;先运行 status 核实,禁止盲目重试`); state.actions[key] = { attempted: true, at: new Date().toISOString(), target }; save(); note(`准备执行 ${key},目标 ${target};结果见 ${path.relative(process.cwd(), stateFile)}。`); }; const done = (key, receipt) => { Object.assign(state.actions[key], { confirmedAt: new Date().toISOString(), receipt }); save(); note(`${key} 已取得回执;${JSON.stringify(receipt)}。`); }; const check = (name, pass, details) => { state.checks.push({ name, pass: !!pass, at: new Date().toISOString(), ...(details ? { details } : {}) }); save(); assert.ok(pass, name); }; const auth = () => c.evaluate(() => ({ token: localStorage.getItem('fmode_session_token'), me: JSON.parse(localStorage.getItem('fmode_me') || 'null') })); const navigate = async route => { await c.evaluate(route => { history.pushState(null, '', route); dispatchEvent(new PopStateEvent('popstate')); }, route); await c.waitFor(route => decodeURIComponent(location.pathname) === decodeURIComponent(route), route, 60000); }; const tapText = async label => { const point = await c.evaluate(label => { const el = [...document.querySelectorAll('button')].filter(el => el.innerText.trim() === label && el.getClientRects().length && !el.disabled).at(-1); if (!el) return null; el.scrollIntoView({ block: 'center' }); const r = el.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; }, label); assert.ok(point, `找不到唯一可用操作:${label}`); await c.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [point] }); await c.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); }; const shot = name => c.screenshot(path.join(out, name + '.png')); const snapshot = () => c.evaluate(() => ({ route: location.pathname, text: document.body.innerText, overflow: document.documentElement.scrollWidth > innerWidth, viewport: { width: innerWidth, height: innerHeight }, inputs: [...document.querySelectorAll('input')].map(x => ({ label: x.getAttribute('aria-label'), type: x.type, length: x.value.length })), buttons: [...document.querySelectorAll('button')].filter(x => x.getClientRects().length).map(x => ({ text: x.innerText.trim(), label: x.getAttribute('aria-label'), disabled: x.disabled })), })); const pause = ms => new Promise(resolve => setTimeout(resolve, ms)); const deviceAdb = args => { const r = spawnSync('adb', ['-s', arg('serial', '3e529a34'), ...args], { encoding: 'utf8', timeout: 30000, maxBuffer: 8 * 1024 * 1024, windowsHide: true }); assert.equal(r.status, 0, 'ADB 操作未确认:' + args.slice(0, 3).join(' ') + ' ' + (r.stderr || r.error?.message || '')); return r.stdout.trim(); }; async function reconnectApp() { const deadline = Date.now() + 45000; while (Date.now() < deadline) { try { const pid = deviceAdb(['shell', 'pidof', 'cn.fmode.app']); deviceAdb(['forward', 'tcp:' + arg('port', '9222'), 'localabstract:webview_devtools_remote_' + pid]); c = await connectWebView(Number(arg('port', '9222'))); return; } catch { await pause(500); } } throw Error('原 App 启动后未能恢复 WebView 连接;先查进程和界面,不重试业务动作'); } async function verifyOriginalTrial(label) { const task = state.actions.trialFilesV3; assert.ok(task?.proof?.completion, '缺少原文件任务回执'); await c.waitFor(() => !!localStorage.getItem('fmode_me'), undefined, 60000); assert.equal((await auth()).me?.id, state.userId, label + '后身份必须仍为本轮账号'); await navigate('/mobile/chat/' + state.trial.agentId + '/' + encodeURIComponent(task.threadRoot)); await c.waitFor(() => document.querySelector('textarea') && !document.querySelector('textarea').disabled, undefined, 60000); const view = await snapshot(); check(label + '后原会话与两份成果可回读', view.text.includes(task.inputMarker) && task.expectedFiles.every(name => view.text.includes(name)), { route: view.route }); await proveMessage('trialFilesV3', 30000); return view; } function pictureFixture() { const chunk = (name, data) => { const type = Buffer.from(name); let crc = 0xffffffff; for (const byte of Buffer.concat([type, data])) { crc ^= byte; for (let n = 0; n < 8; n++) crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0); } const length = Buffer.alloc(4); length.writeUInt32BE(data.length); const checksum = Buffer.alloc(4); checksum.writeUInt32BE((crc ^ 0xffffffff) >>> 0); return Buffer.concat([length, type, data, checksum]); }; const header = Buffer.alloc(13); header.writeUInt32BE(64, 0); header.writeUInt32BE(64, 4); header[8] = 8; header[9] = 2; const raw = Buffer.alloc(64 * (64 * 3 + 1)); 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; } 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))]); } async function accountApi(id, params) { const account = JSON.parse(fs.readFileSync(accountFile)); if (id === 'THXAOGKiPK') params = { ...params, token: account.token }; const response = await fetch('https://server.fmode.cn/api/functions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Parse-Application-Id': 'ncloudmaster', 'X-Parse-Session-Token': account.token }, body: JSON.stringify({ id, token: account.token, params }), signal: AbortSignal.timeout(25000) }); assert.ok(response.ok, '账号接口 HTTP ' + response.status); const data = await response.json(); assert.equal(data.code, 200, data.msg || data.mess); return data; } async function readBinding(agentId = state.trial.agentId) { // Server-side test read only. Never injected into the WebView or packaged in the APK. const cfg = JSON.parse(fs.readFileSync('.claude/dev-login.json')); const url = new URL('https://server.fmode.cn/parse/classes/FmodeMatrixBinding'); url.searchParams.set('where', JSON.stringify({ userPointer: { __type: 'Pointer', className: '_User', objectId: state.userId }, agentId, status: 'active' })); const response = await fetch(url, { headers: { 'X-Parse-Application-Id': 'ncloudmaster', 'X-Parse-Master-Key': cfg.masterKey }, signal: AbortSignal.timeout(20000) }); assert.ok(response.ok); const rows = (await response.json()).results; assert.equal(rows?.length, 1, '本轮账号与试用容器必须只有一个有效通信绑定'); assert.equal(rows[0].userMxId, '@' + state.userId.toLowerCase() + ':fmode.cn'); if (agentId === state.trial.agentId) assert.equal(rows[0].agentMxId, state.trial.agentMxId); return rows[0]; } async function readRoomEvents(binding, roomId) { return readMatrixHistory(binding, roomId); } const ownInputs = (events, binding, marker) => events.filter(e => e.sender === binding.userMxId && e.type === 'm.room.message' && e.content?.body?.includes(marker)); async function openTrialTask(task) { assert.ok(task?.proof?.completion && task.roomId && task.threadRoot, '缺少已完成任务的服务器回执'); await navigate('/mobile/chat/' + state.trial.agentId + '/' + encodeURIComponent(task.threadRoot)); await c.waitFor(() => document.querySelector('textarea') && !document.querySelector('textarea').disabled, undefined, 60000); await c.waitFor(marker => document.body.innerText.includes(marker), task.marker, 60000); } async function readHtmlPreview(marker, previousFrame) { let frame; for (let n = 0; n < 45 && !frame; n++) { const tree = await c.send('Page.getFrameTree'); frame = (tree.frameTree.childFrames || []).find(x => x.frame.url.includes(state.actions.trialFilesV3.expectedFiles.find(x => x.endsWith('.html'))) && (!previousFrame || newFrameLoader(previousFrame, x.frame))); if (!frame) await pause(300); } assert.ok(frame, 'HTML 实际子框架未加载'); await waitForPreviewText(async () => { const tree = await c.send('Page.getFrameTree'); const sameLoader = (tree.frameTree.childFrames || []).some(x => x.frame.id === frame.frame.id && x.frame.loaderId === frame.frame.loaderId); assert.ok(sameLoader, '正在等待的目标loader已改变'); const world = await c.send('Page.createIsolatedWorld', { frameId: frame.frame.id }); const body = await c.send('Runtime.evaluate', { expression: 'document.body?.innerText || ""', contextId: world.executionContextId, returnByValue: true }); if (body.exceptionDetails) throw Error(body.exceptionDetails.text); return body.result?.value; }, marker); await c.waitFor(() => { const dialog = document.querySelector('[role="dialog"][aria-label^="预览 "]'); return dialog?.querySelector('iframe.fp-html')?.getClientRects().length && !dialog.querySelector('.fp-html-stall, .fp-html-loading'); }, undefined, 45000); return frame.frame; } async function verifyIsolationViews(prefix) { const a = state.actions.trialIsolationSeed, b = state.actions.trialFilesV3; assert.notEqual(a.roomId, b.roomId, '隔离验收必须使用两个不同房间'); const originals = JSON.parse(fs.readFileSync(path.join(out, 'trial-v3-file-hub.json'))); for (const [key, task, other] of [['A', a, b], ['B', b, a], ['A-return', a, b]]) { await openTrialTask(task); const view = await snapshot(); check('既有会话切换隔离 ' + key, view.text.includes(task.marker) && !view.text.includes(other.marker), { route: view.route, roomId: task.roomId }); if (key === 'B') await c.waitFor(names => names.every(name => document.querySelector(`[aria-label="预览 ${name}"]`)?.getClientRects().length), b.expectedFiles, 45000); const labels = await c.evaluate(() => [...document.querySelectorAll('button[aria-label^="预览 "]')].filter(x => x.getClientRects().length).map(x => x.getAttribute('aria-label'))); check('既有会话可见成果卡片隔离 ' + key, previewCardsMatch(b.expectedFiles, labels, key === 'B'), { labels }); const listing = await accountApi('THXAOGKiPK', { action: 'listBySession', roomId: task.roomId, limit: 200 }); const urls = (listing.files || []).map(x => x.url); 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) }); await shot(prefix + '-' + key); } return { rooms: [a.roomId, b.roomId], screenshots: ['A', 'B', 'A-return'].map(key => prefix + '-' + key + '.png'), sends: 0 }; } async function proveMessage(key, timeout = 180000) { const action = state.actions[key]; assert.ok(action?.attempted, '必须先有真实发送动作记录'); const agentId = action.agentId || state.trial.agentId; const binding = await readBinding(agentId); const deadline = Date.now() + timeout; const stamp = new Date().toISOString().replace(/\D/g, '') + '-' + process.pid; let observation = 0; while (Date.now() < deadline) { const listing = await accountApi('oR5O67i1Cm', { op: 'list', agentId }); const thread = resolveTaskThread(listing.threads || [], action); if (thread?.roomId) { if (!action.roomId) action.roomId = thread.roomId; if (!action.threadRoot) action.threadRoot = thread.threadRoot; if (!action.threadId) action.threadId = thread.objectId ?? thread.id; assert.equal(action.roomId, thread.roomId, '回读线程必须保持首次登记房间'); save(); const history = await readRoomEvents(binding, thread.roomId), events = history.events; const inputNames = state.actions[key.replace('Files', 'FilesInput')]?.receipt?.files?.map(x => x.name) || []; const evidenceFile = key + '-readback-' + stamp + '-' + observation++ + '.json'; fs.writeFileSync(path.join(out, evidenceFile), JSON.stringify({ observedAt: new Date().toISOString(), roomId: thread.roomId, ...history }, null, 2), { flag: 'wx' }); (action.observations ??= []).push({ at: new Date().toISOString(), evidenceFile, complete: history.complete }); save(); const proof = taskProof(events, binding, action, inputNames); if (proof) { proof.roomId = thread.roomId; check(key + ' 输入只发送一次', proof.sent.length === 1); const firstFile = path.join(out, key + '-events.json'); if (!fs.existsSync(firstFile)) fs.writeFileSync(firstFile, JSON.stringify(events, null, 2), { flag: 'wx' }); retainFirstProof(action, { ...proof, evidenceFile, observedAt: new Date().toISOString() }); save(); check(key + ' 真实发送、目标回复与结束回执', true, { ...proof, evidenceFile, pages: history.pages.length }); note(`${key} 完整分页只读回验通过,房间 ${thread.roomId},输入 ${proof.sent[0]},结束回执 ${proof.completion};新证据 ${evidenceFile},原事件和首次proof保留。`); return action; } } await pause(2500); } throw Error(key + ' 尚无完整服务器回执;先核实事件,不可重复发送'); } async function readAdvancedJob() { const action = state.actions.advancedCreate; assert.ok(action?.attempted && Array.isArray(action.jobsBefore) && Array.isArray(action.agentIdsBefore), '没有完整的进阶申请前资产记录,只能人工只读核实'); const jobs = (await accountApi('VtW1GT93Ax', { op: 'list' })).items || []; const created = jobs.filter(x => !action.jobsBefore.some(y => y.jobId === x.jobId)); assert.equal(created.length, 1, '必须只新增一个任务,先核实真实任务列表'); assert.ok(!action.jobId || action.jobId === created[0].jobId, '新任务与已登记任务不同'); assert.equal(created[0].planCode, 'advanced', '新增任务不是进阶套餐'); const job = await accountApi('VtW1GT93Ax', { op: 'status', jobId: created[0].jobId }); assert.equal(job.jobId, created[0].jobId, '状态回包jobId与目标不同'); assert.equal(job.planCode, 'advanced', '状态回包不是进阶套餐'); assert.ok(job.agentId, '进阶任务缺少目标容器身份'); const agentId = job.agentId.startsWith('agent-node-app-') ? job.agentId.toLowerCase() : 'agent-node-app-' + job.agentId.toLowerCase(); assert.ok(!action.agentIdsBefore.includes(agentId), '进阶任务复用了原有容器身份'); const agents = (await accountApi('xlosi3m46q', { op: 'query', scope: 'mine' })).agents || []; const ids = agents.map(x => x.agentId); assert.ok(action.agentIdsBefore.every(id => ids.includes(id)), '进阶申请后原有容器丢失'); assert.deepEqual(ids.filter(id => !action.agentIdsBefore.includes(id)), [agentId], '新容器差集与进阶目标不一致'); const file = 'advanced-status-' + Date.now() + '.json'; fs.writeFileSync(path.join(out, file), JSON.stringify({ observedAt: new Date().toISOString(), jobs, job, agentIds: ids }, null, 2), { flag: 'wx' }); Object.assign(action, { jobId: job.jobId, agentId, latestStatus: job }); (action.statusObservations ??= []).push(file); save(); note(`进阶原任务只读回验:${job.jobId}/${agentId}/${job.status};阶段${job.currentStep?.stage || job.stage};证据${file},原资产保留且仅新增目标容器,未再次申请。`); return job; } async function verifyProvisionView(jobId) { await c.waitFor(() => !!document.querySelector('app-dk-provision-page .prov-title'), undefined, 60000); await c.waitFor(() => { const text = document.querySelector('app-dk-provision-page')?.innerText || ''; return /正在创建容器|容器已就绪|开通未完成/.test(text) && !/加载开通状态失败/.test(text); }, undefined, 60000); // 网址和初始骨架不能证明状态已加载,必须回读本次页面真实发起的原job状态响应。 let response; for (let n = 0; n < 150 && !response; n++) { for (const event of c.events.filter(x => x.method === 'Network.responseReceived' && /\/api\/functions/.test(x.params?.response?.url || '')).reverse()) { try { const body = await c.send('Network.getResponseBody', { requestId: event.params.requestId }); const data = JSON.parse(body.base64Encoded ? Buffer.from(body.body, 'base64').toString('utf8') : body.body); if (data.code === 200 && data.jobId === jobId && data.planCode === 'advanced' && data.status) { response = data; break; } } catch { /* 响应尚未完成或不是开通状态,继续读同次页面请求。 */ } } if (!response) await pause(300); } assert.ok(response, '等待页未取得原job的真实状态响应'); const view = await snapshot(); assert.ok(!/加载开通状态失败/.test(view.text), '等待页显示状态加载失败'); assert.ok(!view.overflow, '等待页横向溢出'); if (['queued', 'provisioning', 'verifying'].includes(response.status)) { assert.equal(await c.evaluate(() => document.querySelectorAll('app-dk-provision-page .prov-stage').length), 6, '等待页没有渲染实际阶段'); } else assert.ok(view.text.includes(response.status === 'ready' ? '容器已就绪' : '开通未完成'), '等待页终态与服务端不一致'); return { jobId, status: response.status, stage: response.currentStep?.stage || response.stage, route: view.route }; } try { if (stage !== 'status') { lock = fs.openSync(lockFile, 'wx'); fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, stage, startedAt: new Date().toISOString() })); } state = JSON.parse(fs.readFileSync(stateFile, 'utf8')); assert.equal(state.phone, phone, '手机号与本轮账本不一致'); if (!['trial-cold-start', 'trial-background-resume', 'advanced-status', 'advanced-restore'].includes(stage)) c = await connectWebView(Number(arg('port', '9222'))); if (stage === 'status') { const identity = await auth(); const view = await snapshot(); 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)); } else if (stage === 'request-code' || stage === 'request-relogin-code') { const relogin = stage === 'request-relogin-code'; const smsKey = relogin ? 'smsRelogin' : 'sms'; assert.ok(!state.actions[smsKey]?.attempted, `${smsKey} 已有动作记录;先只读核实,不重复请求验证码`); fs.mkdirSync(privateDir, { recursive: true }); const identity = await auth(); if (identity.token) { if (relogin) { assert.equal(identity.me?.id, state.userId, '重登前账号不是本轮用户'); begin('logoutRelogin', phone + '/APK 退出并短信重登验收'); } fs.writeFileSync(path.join(privateDir, relogin ? 'previous-mobile-auth-relogin.json' : 'previous-mobile-auth.json'), JSON.stringify(identity, null, 2)); await navigate('/mobile/mine'); await c.waitFor(() => !!document.querySelector('button.m-logout')); // debug 包沿用 1.0 版本号,账户页可能提示安装已发布版;验收保留当前构建。 if (await c.evaluate(() => [...document.querySelectorAll('[role="dialog"]')].some(x => x.innerText.includes('稍后再说')))) { await tapText('稍后再说'); await c.waitFor(() => ![...document.querySelectorAll('[role="dialog"]')].some(x => x.innerText.includes('稍后再说'))); } await c.tap('button.m-logout'); await c.waitFor(() => [...document.querySelectorAll('[role="dialog"], [role="alertdialog"]')].some(x => x.innerText.includes('退出登录')) || document.querySelectorAll('app-m-confirm button').length > 0); await tapText('退出登录'); await c.waitFor(() => !!document.querySelector('input[aria-label="手机号"]')); check('通过 APK 界面退出旧账号并进入短信登录页', !(await auth()).token); if (relogin) done('logoutRelogin', { phone, loggedOut: true, loginFormVisible: true }); } await c.waitFor(() => !!document.querySelector('input[aria-label="手机号"]')); await c.fill('input[aria-label="手机号"]', phone); if (!(await c.evaluate(() => document.querySelector('[aria-label="同意协议"]')?.getAttribute('aria-checked') === 'true'))) await c.tap('[aria-label="同意协议"]'); await shot(relogin ? 'relogin-01-phone-form' : '01-phone-form'); begin(smsKey, phone); await c.tap('button.m-btn--primary'); await c.waitFor(() => !!document.querySelector('input[aria-label="验证码"]') || !!document.querySelector('[role="alert"]')); const view = await snapshot(); fs.writeFileSync(path.join(out, relogin ? 'sms-relogin-ui.json' : 'sms-ui.json'), JSON.stringify(view, null, 2)); await shot(relogin ? 'relogin-02-code-request-result' : '02-code-request-result'); assert.ok(view.inputs.some(x => x.label === '验证码'), '短信接口未确认成功,请检查 sms-ui.json;不要重复发送'); done(smsKey, { phone, codeInputVisible: true, countdown: view.buttons.find(x => /^\d+s$/.test(x.text))?.text }); check('真实短信请求成功后展示验证码输入和倒计时', true); check('短信登录页无横向溢出', !view.overflow); console.log(JSON.stringify({ sent: true, phone, waitingForUserCode: true, nextStage: relogin ? 'relogin' : 'login' })); } else if (stage === 'login' || stage === 'relogin') { const relogin = stage === 'relogin'; const smsKey = relogin ? 'smsRelogin' : 'sms'; const loginKey = relogin ? 'loginRelogin' : 'login'; const code = arg('code'); assert.match(code ?? '', /^\d{6}$/, '请输入用户提供的 6 位验证码'); assert.ok(state.actions[smsKey]?.confirmedAt, '本轮短信尚无成功回执'); assert.ok(!state.actions[loginKey]?.attempted, '已有登录动作记录,先核实结果'); await c.fill('input[aria-label="验证码"]', code); begin(loginKey, phone); await c.tap('button.m-btn--primary'); await c.waitFor(() => !!localStorage.getItem('fmode_session_token') || !!document.querySelector('[role="alert"]'), undefined, 60000); const identity = await auth(); assert.ok(identity.token && identity.me?.id, '登录未成功,请先核实界面错误'); assert.equal(identity.me.mobile, phone, '登录返回手机号与本轮测试账号不一致'); if (relogin) { assert.equal(identity.me.id, state.userId, '重登前后用户身份不一致'); fs.copyFileSync(accountFile, path.join(privateDir, 'account-before-relogin.json')); } fs.writeFileSync(accountFile, JSON.stringify({ ...identity, phone, userId: identity.me.id, at: new Date().toISOString() }, null, 2)); state.userId = identity.me.id; done(loginKey, { userId: identity.me.id, phone }); await c.waitFor(() => !location.pathname.includes('login'), undefined, 60000); await shot(relogin ? 'relogin-03-success' : '03-login-success'); const view = await snapshot(); fs.writeFileSync(path.join(out, relogin ? 'relogin-ui.json' : 'login-ui.json'), JSON.stringify(view, null, 2)); check('新手机号真实登录并离开登录页', true, { userId: identity.me.id, route: view.route }); console.log(JSON.stringify({ loggedIn: true, userId: identity.me.id, route: view.route })); } else if (stage === 'install-pending-recovery') { const buildTag = arg('build-tag', 'pending-recovery-20261129'); assert.match(buildTag, /^[A-Za-z0-9-]+$/); const installKey = 'installPendingRecovery_' + buildTag; const apkReceipt = 'apk-' + buildTag + '-receipt.json'; const receipt = JSON.parse(fs.readFileSync(path.join(out, apkReceipt))); const bytes = fs.readFileSync(receipt.apk); assert.equal(createHash('sha256').update(bytes).digest('hex').toUpperCase(), receipt.sha256); begin(installKey, `${arg('serial', '3e529a34')}/cn.fmode.app/${receipt.sha256}/仅覆盖安装保留数据`); deviceAdb(['install', '-r', receipt.apk]); deviceAdb(['shell', 'am', 'start', '-n', 'cn.fmode.app/.MainActivity']); c.close(); await reconnectApp(); await c.waitFor(id => JSON.parse(localStorage.getItem('fmode_me') || 'null')?.id === id, state.userId, 60000); const remote = deviceAdb(['shell', 'pm', 'path', 'cn.fmode.app']).replace(/^package:/, ''); const remoteSha256 = deviceAdb(['shell', 'sha256sum', remote]).split(/\s/)[0].toUpperCase(); assert.equal(remoteSha256, receipt.sha256, '安装包与手机实际包摘要不同'); await navigate('/plans'); await c.waitFor(() => document.querySelector('.plan-card--featured .plan-btn')?.disabled === false && !document.querySelector('app-loading-overlay'), undefined, 60000); check('新版APK恢复核对无在途任务后允许申请', true, { sha256: remoteSha256 }); done(installKey, { sha256: remoteSha256, userId: state.userId, apkReceipt }); } else if (stage === 'advanced-start') { assert.ok(!state.actions.advancedCreate?.attempted, '进阶申请已有动作记录,只能advanced-status核实,禁止再次申请'); for (const key of ['trialEvidenceAudit', 'trialCleanOutput', 'trialDocumentPreviews', 'trialFreshChat', 'desktopBaseline', 'mobileBaseline', 'reloginReadback']) assert.ok(state.actions[key]?.confirmedAt, '基础验收尚缺 ' + key); assert.equal((await auth()).me?.id, state.userId); const jobsBefore = (await accountApi('VtW1GT93Ax', { op: 'list' })).items || []; assert.ok(jobsBefore.every(x => ['ready', 'failed'].includes(x.status)), '已有在途开通任务,停止而不新增'); const agentsBefore = (await accountApi('xlosi3m46q', { op: 'query', scope: 'mine' })).agents || []; await navigate('/plans'); await c.waitFor(() => document.querySelector('.plan-card--featured h3')?.innerText.trim() === '进阶' && !document.querySelector('.plan-card--featured .plan-btn')?.disabled); begin('advancedCreate', `${state.userId}/APK进阶卡片单次开通一个新容器;保留所有原资产`); Object.assign(state.actions.advancedCreate, { jobsBefore, agentIdsBefore: agentsBefore.map(x => x.agentId), phase: 'before-single-tap' }); save(); await c.tap('.plan-card--featured .plan-btn'); state.actions.advancedCreate.phase = 'single-tap-complete'; save(); await c.waitFor(() => location.pathname === '/provision' && !!new URLSearchParams(location.search).get('jobId'), undefined, 90000); const jobId = await c.evaluate(() => new URLSearchParams(location.search).get('jobId')); state.actions.advancedCreate.jobId = jobId; save(); const job = await readAdvancedJob(); Object.assign(state.actions.advancedCreate, { latestStatus: job, phase: 'accepted' }); save(); captureNativeScreenshot(path.join(out, 'advanced-accepted-native.png'), arg('serial', '3e529a34')); done('advancedCreate', { jobId, status: job.status, agentId: job.agentId, clicks: 1, readyVerified: false }); } else if (stage === 'advanced-status') { console.log(JSON.stringify(await readAdvancedJob(), null, 2)); } else if (stage === 'advanced-restore' || stage === 'advanced-restore-readback') { const action = state.actions.advancedCreate; assert.ok(action?.jobId && action.latestStatus, '缺少原进阶任务'); if (stage === 'advanced-restore') { assert.ok(!['ready', 'failed'].includes(action.latestStatus.status), '仅在已有进行中任务验证等待页恢复'); begin('advancedRestore', `${action.jobId}/APK强停后从入口恢复原开通等待页;不申请或重试`); deviceAdb(['shell', 'am', 'force-stop', 'cn.fmode.app']); deviceAdb(['shell', 'am', 'start', '-n', 'cn.fmode.app/.MainActivity']); state.actions.advancedRestore.restartedAt = new Date().toISOString(); save(); await reconnectApp(); await c.waitFor(() => location.pathname.startsWith('/mobile/'), undefined, 60000); } else { assert.ok(state.actions.advancedRestore?.attempted && state.actions.advancedRestore?.restartedAt && !state.actions.advancedRestore?.confirmedAt, '只能补查已有真实重启回执且未完成的原恢复动作'); note('补查原进阶恢复动作:强停启动已发生;仅修正进度按钮实际位于plans-job-actions的定位,不再强停、申请或重试。'); } assert.equal((await auth()).me?.id, state.userId); const persisted = await c.evaluate(() => localStorage.getItem('fmode_active_provision_job')); const onOriginalPage = await c.evaluate(id => location.pathname === '/provision' && new URLSearchParams(location.search).get('jobId') === id, action.jobId); if (stage === 'advanced-restore-readback' && onOriginalPage) { // 已在原任务页,重新加载仅获取新状态,不重复强停或创建。 await c.send('Page.reload', { ignoreCache: true }); } else { assert.equal(persisted, action.jobId, '强停后原在途任务标记丢失'); await navigate('/plans'); await c.waitFor(() => { const text = document.querySelector('.plans-job')?.innerText || ''; return (!!document.querySelector('.plans-job-actions button') || /已就绪|开通失败/.test(text)) && !document.querySelector('app-loading-overlay'); }, undefined, 60000); const canOpen = await c.evaluate(() => !![...document.querySelectorAll('.plans-job-actions button')].find(x => x.innerText.trim() === '查看开通进度')); if (canOpen) await tapText('查看开通进度'); else { const terminal = await readAdvancedJob(); assert.ok(['ready', 'failed'].includes(terminal.status), '页面缺少原任务进度入口且任务未终结'); await c.evaluate(jobId => { history.pushState(null, '', '/provision?jobId=' + encodeURIComponent(jobId)); dispatchEvent(new PopStateEvent('popstate')); }, action.jobId); } } await c.waitFor(id => location.pathname === '/provision' && new URLSearchParams(location.search).get('jobId') === id, action.jobId); const restored = await verifyProvisionView(action.jobId); await readAdvancedJob(); check('APK强停后恢复同一个进阶等待任务', true, { jobId: action.jobId }); check('进阶等待页全屏且无横向溢出', await c.evaluate(() => !document.querySelector('app-mobile-shell, app-m-tab-bar, app-m-drawer') && document.documentElement.scrollWidth <= innerWidth)); captureNativeScreenshot(path.join(out, 'advanced-restored-native.png'), arg('serial', '3e529a34')); done('advancedRestore', { ...restored, restored: true, creates: 0, retries: 0 }); } else if (stage === 'advanced-chat') { assert.ok(!state.actions.advancedChat?.attempted, '进阶消息已有记录,只能verify-advanced-chat回读'); const job = await readAdvancedJob(); assert.equal(job.status, 'ready', '进阶原任务尚未就绪'); const agentId = state.actions.advancedCreate.agentId; const binding = await readBinding(agentId); assert.notEqual(binding.agentMxId, state.trial.agentMxId, '新旧容器Matrix身份必须不同'); const marker = state.run + '_ADVANCED_FILES'; const safeRun = state.run.toLowerCase().replaceAll('_', '-'); const expectedFiles = ['advanced-' + safeRun + '.md', 'advanced-' + safeRun + '.html']; begin('advancedChat', `${agentId}/新进阶容器单次图文成果任务;不改配置或安装依赖`); Object.assign(state.actions.advancedChat, { agentId, marker, expectedFiles, bindingId: binding.objectId, phase: 'before-new-chat' }); save(); await navigate('/mobile/chat/' + agentId + '/new'); await c.waitFor(() => !location.pathname.endsWith('/new') && document.querySelector('textarea')?.disabled === false, undefined, 60000); const threadRoot = await c.evaluate(() => decodeURIComponent(location.pathname.split('/').at(-1))); Object.assign(state.actions.advancedChat, { threadRoot, phase: 'before-single-send' }); save(); 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},让现有自动成果流程上云,不自行拼接链接。`; await c.fill('textarea', prompt); await c.waitFor(() => !document.querySelector('button.m-send')?.disabled); await c.tap('button.m-send'); const action = await proveMessage('advancedChat'); await c.waitFor(marker => [...document.querySelectorAll('app-assistant-turn')].some(x => x.innerText.includes(marker)), marker, 60000); done('advancedChat', { agentId, proof: action.proof, sends: 1, fileVerificationPending: true }); } else if (stage === 'verify-advanced-chat') { await proveMessage('advancedChat', 30000); } else if (['advanced-files-isolation', 'advanced-files-isolation-readback', 'advanced-files-isolation-audit', 'advanced-files-isolation-audit-readback'].includes(stage)) { const task = state.actions.advancedChat; assert.ok(task?.proof?.completion, '先取得进阶单次消息完整回执'); if (stage === 'advanced-files-isolation') begin('advancedFilesIsolation', `${task.agentId}/新成果真实内容、预览及双容器隔离;不发送`); else if (stage === 'advanced-files-isolation-readback') { assert.ok(state.actions.advancedFilesIsolation?.attempted && !state.actions.advancedFilesIsolation?.confirmedAt, '只能补查未完成的原成果隔离动作'); note('原进阶成果隔离只读续查:按唯一URL核对交付对象,保留报告与文件台账两来源行,不重发成果任务。'); } else if (stage === 'advanced-files-isolation-audit') { assert.ok(state.actions.advancedFilesIsolation?.confirmedAt, '首次成果隔离尚未完成,不能开始独立复核'); begin('advancedFilesIsolationReaudit', `${task.agentId}/补验消息、成果和会话双向隔离;只读,不发送、不申请`); } else { assert.ok(state.actions.advancedFilesIsolationReaudit?.attempted && !state.actions.advancedFilesIsolationReaudit?.confirmedAt, '只读补查仅适用于未完成的双向隔离复核'); note('双向隔离复核只读续查:重读已存在的进阶与试用房间/文件,沿用原输入和原proof,不发送。'); } const binding = await readBinding(task.agentId); const listing = await accountApi('THXAOGKiPK', { action: 'listBySession', roomId: task.roomId, limit: 200 }); const files = listing.files || []; fs.writeFileSync(path.join(out, 'advanced-file-hub-' + Date.now() + '.json'), JSON.stringify(listing, null, 2), { flag: 'wx' }); // The action records predate explicit agentId on each trial task; bind their stable owner here. const trialTasks = [state.actions.trialFilesV3, state.actions.trialDocuments] .map(original => ({ ...original, agentId: state.trial.agentId })); const advancedEvents = await readRoomEvents(binding, task.roomId); fs.writeFileSync(path.join(out, 'advanced-isolation-' + Date.now() + '.json'), JSON.stringify({ side: 'advanced', history: advancedEvents, listing }, null, 2), { flag: 'wx' }); const objects = assertSessionIsolation(advancedEvents, files, task, trialTasks); const urls = []; for (const { name, url } of objects) { const file = { url }; assert.ok(file.url.includes('/deliverables/' + task.agentId + '/'), '进阶成果存储不属于目标容器'); const response = await fetch(file.url, { signal: AbortSignal.timeout(25000) }); assert.ok(response.ok); const bytes = Buffer.from(await response.arrayBuffer()), body = bytes.toString('utf8'); 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 }); urls.push(file.url); } await navigate('/mobile/chat/' + task.agentId + '/' + encodeURIComponent(task.threadRoot)); await c.waitFor(marker => document.body.innerText.includes(marker), task.marker, 60000); for (const name of task.expectedFiles) { await c.waitFor(name => !!document.querySelector(`[aria-label="预览 ${name}"]`), name); await c.tap(`[aria-label="预览 ${name}"]`); if (name.endsWith('.md')) await c.waitFor(marker => document.querySelector('[role="dialog"][aria-label^="预览 "]')?.innerText.includes(marker), task.marker); else { await c.waitFor(() => !!document.querySelector('iframe')); let frame; 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); } assert.ok(frame, '进阶HTML真实文档尚未加载'); 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); } await c.waitFor(() => !document.querySelector('.pv-stalled') && !document.querySelector('.pv-loading')); const auditSuffix = stage.startsWith('advanced-files-isolation-audit') ? `-audit-${Date.now()}` : ''; captureNativeScreenshot(path.join(out, name.endsWith('.md') ? `advanced-native-md${auditSuffix}.png` : `advanced-native-html${auditSuffix}.png`), arg('serial', '3e529a34')); await c.tap('[aria-label="关闭预览"]'); } const labels = await c.evaluate(() => [...document.querySelectorAll('[aria-label^="预览 "]')].map(x => x.getAttribute('aria-label'))); const oldTrialFiles = trialTasks.flatMap(x => x.expectedFiles || []); check('新进阶会话只显示本任务成果卡片', task.expectedFiles.every(name => labels.includes('预览 ' + name)) && oldTrialFiles.every(name => !labels.includes('预览 ' + name)), { labels }); const trialBinding = await readBinding(); assert.notEqual(binding.objectId, trialBinding.objectId); for (const key of ['trialFilesV3', 'trialDocuments']) { const original = state.actions[key]; const history = await readRoomEvents(trialBinding, original.roomId); const originalListing = await accountApi('THXAOGKiPK', { action: 'listBySession', roomId: original.roomId, limit: 200 }); const originalFiles = originalListing.files || []; fs.writeFileSync(path.join(out, 'advanced-isolation-' + key + '-' + Date.now() + '.json'), JSON.stringify({ side: 'trial', key, history, listing: originalListing }, null, 2), { flag: 'wx' }); assertSessionIsolation(history, originalFiles, { ...original, agentId: state.trial.agentId }, [task, ...trialTasks.filter(x => x !== original)]); const ownObjects = sessionFileObjects(originalFiles, state.trial.agentId, original.roomId, original.expectedFiles); check('试用原房间无进阶消息 ' + key, !history.events.some(x => x.type === 'm.room.message' && x.content?.body?.includes(task.marker)), { pages: history.pages.length, complete: history.complete }); check('试用成果保持原房间归属 ' + key, ownObjects.length === original.expectedFiles.length && urls.every(url => !originalFiles.some(x => x.url === url)), { fileCount: originalFiles.length }); await openTrialTask(original); const ownLabels = await c.evaluate(() => [...document.querySelectorAll('[aria-label^="预览 "]')].map(x => x.getAttribute('aria-label'))); const otherNames = otherTaskFiles([task, ...trialTasks], original); check('试用会话仅显示本房间成果卡片 ' + key, original.expectedFiles.every(name => ownLabels.includes('预览 ' + name)) && otherNames.every(name => !ownLabels.includes('预览 ' + name)), { labels: ownLabels }); } await openTrialTask(state.actions.trialFilesV3); check('切回试用容器无进阶成果卡片', await c.evaluate(names => names.every(name => !document.querySelector(`[aria-label="预览 ${name}"]`)), task.expectedFiles)); 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 }); else done('advancedFilesIsolation', { agentId: task.agentId, trialAgentId: state.trial.agentId, roomId: task.roomId, urls, distinctBindings: true, sends: 0 }); } else if (stage === 'relogin-readback') { assert.ok(state.actions.loginRelogin?.confirmedAt, '先完成真实短信重新登录'); begin('reloginReadback', `${state.userId}/重新登录后原会话与成果恢复;不发送`); assert.equal((await auth()).me?.id, state.userId); const binding = await readBinding(); const rooms = []; for (const key of ['trialFilesV3', 'trialDocuments']) { const task = state.actions[key]; await openTrialTask(task); const labels = await c.evaluate(() => [...document.querySelectorAll('[aria-label^="预览 "]')].map(x => x.getAttribute('aria-label'))); check('短信重登后原会话成果恢复 ' + key, task.expectedFiles.every(name => labels.includes('预览 ' + name.replaceAll('_', '-'))), { roomId: task.roomId, labels }); rooms.push(task.roomId); } assert.equal(new Set(rooms).size, 2); const agents = (await accountApi('xlosi3m46q', { op: 'query', scope: 'mine' })).agents || []; check('短信重登后原有容器身份保留', state.trial.updatedInstruction.unchangedAgentIds.every(id => agents.some(x => x.agentId === id)), { agentIds: agents.map(x => x.agentId) }); captureNativeScreenshot(path.join(out, 'relogin-restored-native.png'), arg('serial', '3e529a34')); done('reloginReadback', { userId: state.userId, rooms, bindingId: binding.objectId, agentIds: agents.map(x => x.agentId), sends: 0 }); } else if (stage === 'mobile-baseline') { begin('mobileBaseline', `${state.userId}/APK主要页面加载、已有容器与PC成果回读;不创建、不发送`); assert.equal((await auth()).me?.id, state.userId); const views = []; for (const route of ['messages', 'contacts', 'workbench', 'my-containers', 'mine']) { await navigate('/mobile/' + route); await c.waitFor(route => !!document.querySelector('app-mb-' + route + '-page'), route); await c.waitFor(() => !document.querySelector('[aria-busy="true"]') && !/正在加载/.test(document.body.innerText), undefined, 60000); // 当前验收包可能出现更新提示,保留此已核对构建。 if (await c.evaluate(() => [...document.querySelectorAll('[role="dialog"]')].some(x => x.innerText.includes('稍后再说')))) await tapText('稍后再说'); const view = await snapshot(); check('APK主要页面完成加载且无横向溢出 ' + route, !view.overflow && !/加载失败|登录已失效/.test(view.text), { route: view.route, viewport: view.viewport }); if (route === 'my-containers') check('APK已有容器实际加载完成', view.text.includes(state.trial.agentId) && !view.text.includes('正在加载'), { text: view.text }); const screenshot = 'mobile-baseline-' + route + '.png'; captureNativeScreenshot(path.join(out, screenshot), arg('serial', '3e529a34')); views.push({ route: view.route, screenshot, text: view.text }); } await openTrialTask(state.actions.desktopReuse); await c.waitFor(marker => [...document.querySelectorAll('app-assistant-turn')].some(x => x.innerText.includes(marker)), state.actions.desktopReuse.marker); check('APK可回读PC真实回复和复用成果卡片', await c.evaluate(() => !!document.querySelector('[aria-label="预览 trial-v3-new-mx0g1r4v.md"]'))); const errors = c.events.filter(x => x.method === 'Runtime.exceptionThrown'); check('APK主要页面无未处理运行异常', errors.length === 0, errors); fs.writeFileSync(path.join(out, 'mobile-baseline-views.json'), JSON.stringify(views, null, 2), { flag: 'wx' }); done('mobileBaseline', { views: views.map(({ route, screenshot }) => ({ route, screenshot })), pcReadback: true, sends: 0 }); } else if (stage === 'trial-cold-start') { begin('trialColdStart', `${arg('serial', '3e529a34')}/cn.fmode.app/强制停止后冷启动,回读原会话,不发送`); deviceAdb(['shell', 'am', 'force-stop', 'cn.fmode.app']); deviceAdb(['shell', 'am', 'start', '-n', 'cn.fmode.app/.MainActivity']); await reconnectApp(); const view = await verifyOriginalTrial('APK 冷启动'); await shot('12-trial-cold-start'); done('trialColdStart', { userId: state.userId, route: view.route, screenshot: '12-trial-cold-start.png', originalTask: 'trialFilesV3' }); } else if (stage === 'trial-background-start') { assert.equal((await auth()).me?.id, state.userId, '后台验收必须使用本轮账号'); begin('trialBackground', `${arg('serial', '3e529a34')}/cn.fmode.app/置后台至少600秒`); const bootId = deviceAdb(['shell', 'cat', '/proc/sys/kernel/random/boot_id']); const uptime = Number(deviceAdb(['shell', 'cat', '/proc/uptime']).split(' ')[0]); assert.ok(Number.isFinite(uptime)); deviceAdb(['shell', 'input', 'keyevent', 'KEYCODE_HOME']); const activity = deviceAdb(['shell', 'dumpsys', 'activity', 'activities']).split('\n').filter(x => /mResumedActivity|topResumedActivity/.test(x)).join('\n'); assert.ok(activity && !activity.includes('cn.fmode.app'), '手机前台未离开 App,不能开始计算后台时间'); done('trialBackground', { bootId, uptime, startedAt: new Date().toISOString(), resumeNotBefore: new Date(Date.now() + 601000).toISOString(), activity }); console.log(JSON.stringify({ backgroundStarted: true, resumeNotBefore: state.actions.trialBackground.receipt.resumeNotBefore })); } else if (stage === 'trial-background-resume') { const receipt = state.actions.trialBackground?.receipt; assert.ok(receipt?.bootId, '缺少后台开始的真实回执'); assert.equal(deviceAdb(['shell', 'cat', '/proc/sys/kernel/random/boot_id']), receipt.bootId, '设备已重启,不能把重启计为同一轮后台停留'); const elapsed = Number(deviceAdb(['shell', 'cat', '/proc/uptime']).split(' ')[0]) - receipt.uptime; if (elapsed < 600) console.log(JSON.stringify({ backgroundResume: '尚未执行', elapsedSeconds: elapsed, requiredSeconds: 600 })); else { begin('trialBackgroundResume', `${arg('serial', '3e529a34')}/cn.fmode.app/后台${Math.floor(elapsed)}秒后恢复`); deviceAdb(['shell', 'am', 'start', '-n', 'cn.fmode.app/.MainActivity']); await reconnectApp(); const view = await verifyOriginalTrial('后台超过10分钟恢复'); await shot('13-trial-background-resumed'); done('trialBackgroundResume', { elapsedSeconds: elapsed, userId: state.userId, route: view.route, screenshot: '13-trial-background-resumed.png' }); } } else if (stage === 'trial-previews') { const task = state.actions.trialFilesV3; assert.ok(task?.proof, '先完成完整附件和成果往返'); assert.equal((await auth()).me?.id, state.userId, '当前 APK 身份不是本轮账号,禁止跨账号补登记'); if (!state.actions.trialExistingFileRegistration?.attempted) { begin('trialExistingFileRegistration', `${state.trial.agentId}/${task.roomId}/原会话已有两份成果自动登记;不发送聊天任务`); } await navigate('/mobile/chat/' + state.trial.agentId + '/' + encodeURIComponent(task.threadRoot)); await c.waitFor(() => document.querySelector('textarea') && !document.querySelector('textarea').disabled, undefined, 60000); const events = JSON.parse(fs.readFileSync(path.join(out, 'trialFilesV3-events.json'))); for (const expected of state.actions.trialFilesInputV3.receipt.files) { const event = events.find(e => e.event_id && task.proof.attachments.includes(e.event_id) && e.content?.['com.fmode.file_card']?.name === expected.name); assert.ok(event, '服务器输入附件不存在'); const response = await fetch(event.content['com.fmode.file_card'].url, { signal: AbortSignal.timeout(30000) }); assert.ok(response.ok); const bytes = Buffer.from(await response.arrayBuffer()); check('APK 云端输入字节一致 ' + expected.name, bytes.length === expected.bytes && createHash('sha256').update(bytes).digest('hex') === expected.sha256, { bytes: bytes.length }); } let files; for (let attempt = 0; attempt < 20; attempt++) { const listing = await accountApi('THXAOGKiPK', { action: 'listBySession', roomId: task.roomId, limit: 200 }); files = task.expectedFiles.map(name => (listing.files || []).find(x => x.url?.endsWith(name))); if (files.every(x => x && x.roomId === task.roomId)) break; await pause(1000); } 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 }))); if (!state.actions.trialExistingFileRegistration.confirmedAt) done('trialExistingFileRegistration', { files: files.map(x => ({ id: x.id, url: x.url, roomId: x.roomId })), source: 'APK 自行读取原回复并登记;无人工补登记、无新聊天任务' }); for (const file of files) { const response = await fetch(file.url, { signal: AbortSignal.timeout(30000) }); assert.ok(response.ok); const text = await response.text(); check('云端成果包含真实编号及文件尺寸 ' + file.name, [task.marker, task.inputMarker, '2879', '179', '64'].every(x => text.includes(x))); } fs.writeFileSync(path.join(out, 'trial-v3-file-hub.json'), JSON.stringify(files, null, 2)); for (const name of task.expectedFiles) { await c.waitFor(name => !!document.querySelector(`[aria-label="预览 ${name}"]`), name); await c.evaluate(() => { window.__acceptancePreviewObserver?.disconnect(); window.__acceptancePreviewStates = []; window.__acceptancePreviewObserver = new MutationObserver(() => { const dialog = document.querySelector('[role="dialog"][aria-label^="预览 "]'); if (!dialog) return; const state = { stalled: !!dialog.querySelector('.fp-html-stall'), loading: !!dialog.querySelector('.fp-html-loading') }; const previous = window.__acceptancePreviewStates.at(-1); if (!previous || previous.stalled !== state.stalled || previous.loading !== state.loading) window.__acceptancePreviewStates.push(state); }); window.__acceptancePreviewObserver.observe(document.body, { childList: true, subtree: true }); }); await c.tap(`[aria-label="预览 ${name}"]`); await c.waitFor(() => !!document.querySelector('[role="dialog"][aria-label^="预览 "]')); if (name.endsWith('.md')) await c.waitFor(marker => document.querySelector('[role="dialog"][aria-label^="预览 "]')?.innerText.includes(marker), task.inputMarker); else { let frame; for (let n = 0; n < 30 && !frame; n++) { const tree = await c.send('Page.getFrameTree'); frame = (tree.frameTree.childFrames || []).find(x => x.frame.url.includes(name)); if (!frame) await pause(300); } assert.ok(frame, 'HTML 实际预览框架未加载'); const world = await c.send('Page.createIsolatedWorld', { frameId: frame.frame.id }); const result = await c.send('Runtime.evaluate', { expression: 'document.body.innerText', contextId: world.executionContextId, returnByValue: true }); check('安卓 HTML 框架实际内容正确', result.result.value.includes(task.inputMarker) && result.result.value.includes('179')); await c.waitFor(() => { const dialog = document.querySelector('[role="dialog"][aria-label^="预览 "]'); const frame = dialog?.querySelector('iframe.fp-html'); return frame?.getClientRects().length && !dialog.querySelector('.fp-html-stall, .fp-html-loading'); }, undefined, 45000); check('安卓 HTML 预览可见且无加载或错误遮罩', true); const states = await c.evaluate(() => window.__acceptancePreviewStates); check('安卓 HTML 加载期间未闪现失败遮罩', states.length > 0 && states.every(x => !x.stalled), states); } check('安卓实际预览 ' + name, true); await shot(name.endsWith('.md') ? '10-trial-preview-markdown' : '11-trial-preview-html'); await c.tap('[aria-label="关闭预览"]'); await c.waitFor(() => !document.querySelector('[role="dialog"][aria-label^="预览 "]')); await c.evaluate(() => window.__acceptancePreviewObserver?.disconnect()); } state.trialCoreVerified = { at: new Date().toISOString(), text: 'trialChatReady', files: 'trialFilesV3', previews: true }; save(); note('本地试用:APK 文字/快速连点、完整图片与文本字节、两份成果自动上云和归属、Markdown与HTML实际预览通过;后续补断网、重启、后台和跨会话复用。'); console.log(JSON.stringify({ trialPreviews: true, files: task.expectedFiles })); } else if (['trial-files', 'trial-files-v2', 'trial-files-v3'].includes(stage)) { const number = stage.match(/-v(\d+)$/)?.[1]; const revision = number ? '-v' + number : ''; const key = number ? 'trialFilesV' + number : 'trialFiles'; const inputKey = number ? 'trialFilesInputV' + number : 'trialFilesInput'; assert.ok(state.actions.trialChatReady?.proof, '先完成本地容器真实文字往返'); const current = state.actions.trialChatReady; await navigate('/mobile/chat/' + state.trial.agentId + '/' + encodeURIComponent(current.threadRoot)); await c.waitFor(() => document.querySelector('textarea') && !document.querySelector('textarea').disabled, undefined, 60000); const inputMarker = 'INPUT_' + state.run; const marker = state.run + '_TRIAL_FILES' + (number ? '_V' + number : ''); const textName = 'input-' + state.run + revision + '.txt'; const pictureName = 'picture-' + state.run + revision + '.png'; const outputBase = 'trial' + revision + '-' + state.run.toLowerCase().replace(/_/g, '-'); const fixtures = [{ name: textName, data: Buffer.from(`输入编号:${inputMarker}\n这是安卓 APK 真实附件读取验收。\n` + '文件大小验收内容。\n'.repeat(100)) }, { name: pictureName, data: pictureFixture() }]; const fixtureDir = path.join(out, 'fixtures'); fs.mkdirSync(fixtureDir, { recursive: true }); begin(inputKey, `${state.trial.agentId}/Android-private-cache/${fixtures.map(x => x.name).join(',')}`); for (const item of fixtures) { fs.writeFileSync(path.join(fixtureDir, item.name), item.data); assert.match(item.name, /^[A-Za-z0-9_.-]+$/); // Windows adb shell's binary stdin may treat Ctrl-Z as EOF. Transfer ASCII, // decode on device, then verify the app-private original before any upload. 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 }); assert.equal(result.status, 0, '无法准备 Android 内的真实文件'); const readback = spawnSync('adb', ['-s', arg('device', '3e529a34'), 'exec-out', 'run-as', 'cn.fmode.app', 'cat', 'cache/' + item.name], { timeout: 20000 }); assert.equal(readback.status, 0); assert.ok(readback.stdout.equals(item.data), 'Android 原文件与主机夹具字节不一致,禁止开始上传'); } const doc = await c.send('DOM.getDocument'); const node = await c.send('DOM.querySelector', { nodeId: doc.root.nodeId, selector: 'app-m-dock input[type="file"]' }); assert.ok(node.nodeId, 'APK 附件输入节点不存在'); await c.send('DOM.setFileInputFiles', { nodeId: node.nodeId, files: fixtures.map(x => '/data/user/0/cn.fmode.app/cache/' + x.name) }); await c.waitFor(names => names.every(name => !!document.querySelector(`[aria-label="移除 ${name}"]`)), fixtures.map(x => x.name)); done(inputKey, { binaryReadbackVerified: true, files: fixtures.map(x => ({ name: x.name, bytes: x.data.length, sha256: createHash('sha256').update(x.data).digest('hex') })) }); await shot('08-trial-staged-files'); 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},由现有自动流程交付文件。`; await c.fill('textarea', prompt); await c.waitFor(() => !document.querySelector('button.m-send')?.disabled); begin(key, `${state.trial.agentId}/${current.threadRoot}/${marker}`); Object.assign(state.actions[key], { marker, inputMarker, threadRoot: current.threadRoot, roomId: current.roomId, expectedFiles: [`${outputBase}.md`, `${outputBase}.html`] }); save(); await c.tap('button.m-send'); await proveMessage(key, 600000); 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); await shot('09-trial-files-received'); check('安卓真实图文附件与两份成果卡片完整显示', true); done(key, { proof: state.actions[key].proof, files: state.actions[key].expectedFiles }); console.log(JSON.stringify({ filesRoundtrip: true, files: state.actions[key].expectedFiles })); } else if (stage === 'verify-trial-files') { await proveMessage('trialFiles', 30000); console.log(JSON.stringify({ proof: state.actions.trialFiles.proof })); } else if (stage === 'trial-chat' || stage === 'trial-chat-ready') { const key = stage === 'trial-chat' ? 'trialChat' : 'trialChatReady'; assert.equal((await auth()).me?.id, state.userId, '当前 APK 身份不属于本轮账号'); const live = await accountApi('xlosi3m46q', { op: 'query', scope: 'mine' }); const agent = live.agents?.find(x => x.agentId === state.trial.agentId); check('本地试用容器真实首报且 Matrix 连接', agent?.channels?.matrixConfig?.channelState === 'connected' && Number.isFinite(agent?.heartbeatAgeSec), { agentId: agent?.agentId, status: agent?.status, heartbeatAgeSec: agent?.heartbeatAgeSec }); await navigate('/mobile/chat/' + state.trial.agentId + '/new'); await c.waitFor(() => !location.pathname.endsWith('/new') && document.querySelector('textarea') && !document.querySelector('textarea').disabled, undefined, 60000); const marker = state.run + (key === 'trialChat' ? '_TRIAL_TEXT' : '_TRIAL_TEXT_READY'); await c.fill('textarea', `这是安卓本地试用接入验收,只回复 ${marker}。不要使用工具,不修改文件或配置。`); await c.waitFor(marker => document.querySelector('textarea')?.value.includes(marker) && !document.querySelector('button.m-send')?.disabled, marker); await pause(150); await shot(key + '-before-send'); begin(key, state.trial.agentId + '/' + marker); state.actions[key].marker = marker; save(); await c.evaluate(() => { const button = document.querySelector('button.m-send'); button.click(); button.click(); button.click(); }); await pause(1000); state.actions[key].threadRoot = await c.evaluate(() => decodeURIComponent(location.pathname.split('/').at(-1))); save(); await proveMessage(key); await c.waitFor(marker => [...document.querySelectorAll('app-assistant-turn')].some(x => x.innerText.includes(marker)), marker, 60000); check('本地试用真实回复在 APK 可见', true); check('三次连点后输入框清空', await c.evaluate(() => document.querySelector('textarea')?.value === '')); const view = await snapshot(); check('试用聊天无横向溢出', !view.overflow); await shot('07-trial-chat-verified'); done(key, { proof: state.actions[key].proof, route: view.route }); console.log(JSON.stringify({ trialTextRoundtrip: true, roomId: state.actions[key].roomId })); } else if (stage === 'verify-trial-chat') { await proveMessage('trialChat', 30000); console.log(JSON.stringify({ proof: state.actions.trialChat.proof })); } else if (stage === 'trial-isolation-send') { begin('trialIsolationSeed', `${state.trial.agentId}/新建一个隔离验收文字会话,单次发送;不新增容器`); assert.equal((await auth()).me?.id, state.userId); const marker = state.run + '_TRIAL_ISOLATION'; state.actions.trialIsolationSeed.marker = marker; save(); await navigate('/mobile/chat/' + state.trial.agentId + '/new'); await c.waitFor(() => !location.pathname.endsWith('/new') && document.querySelector('textarea') && !document.querySelector('textarea').disabled, undefined, 60000); const threadRoot = await c.evaluate(() => decodeURIComponent(location.pathname.split('/').at(-1))); assert.notEqual(threadRoot, state.actions.trialFilesV3.threadRoot, '新会话不能复用原线程'); check('新会话发送前没有原会话内容或成果', await c.evaluate(marker => !document.body.innerText.includes(marker), state.actions.trialFilesV3.marker)); Object.assign(state.actions.trialIsolationSeed, { threadRoot, phase: 'before-single-send' }); save(); await c.fill('textarea', `会话隔离验收:只回复 ${marker}。不要使用工具、不读取其他会话、不创建文件或修改任何配置。`); await c.waitFor(() => !document.querySelector('button.m-send')?.disabled); await c.tap('button.m-send'); await proveMessage('trialIsolationSeed'); await c.waitFor(marker => [...document.querySelectorAll('app-assistant-turn')].some(x => x.innerText.includes(marker)), marker, 60000); await shot('14-trial-isolation-seed'); done('trialIsolationSeed', { proof: state.actions.trialIsolationSeed.proof, threadRoot, screenshot: '14-trial-isolation-seed.png' }); } else if (stage === 'verify-trial-isolation-send') { await proveMessage('trialIsolationSeed', 30000); } else if (['trial-isolation', 'trial-isolation-verify', 'trial-isolation-readback'].includes(stage)) { const actionKey = stage === 'trial-isolation' ? 'trialIsolation' : 'trialIsolationVerified'; if (stage === 'trial-isolation-readback') { assert.ok(state.actions[actionKey]?.attempted && !state.actions[actionKey]?.confirmedAt, '只允许只读补查尚未完成的隔离核验'); } else begin(actionKey, `${state.trial.agentId}/两个已有会话切换及成果归属;不创建、不发送`); assert.equal((await auth()).me?.id, state.userId); done(actionKey, await verifyIsolationViews('14-trial-isolation')); } else if (stage === 'trial-fresh-chat') { begin('trialFreshChat', `${state.trial.agentId}/新隔离卷实例真实首报及原会话单次文字往返`); assert.equal((await auth()).me?.id, state.userId); const runtime = state.actions.localPromptFresh; assert.ok(runtime?.confirmedAt && runtime.containerId, '先完成真实APK提示词隔离卷安装'); const inspect = name => { const result = spawnSync('docker', ['inspect', name], { encoding: 'utf8', timeout: 20000, windowsHide: true }); assert.equal(result.status, 0, '实际运行实例不可核实'); return JSON.parse(result.stdout)[0]; }; const liveRuntime = inspect(runtime.target); assert.equal(liveRuntime.Id, runtime.containerId); assert.equal(liveRuntime.State.Running, true); assert.ok(liveRuntime.Mounts.some(x => x.Name === runtime.volume && x.Destination === '/opt/data')); for (const key of ['localRaw', 'localCandidate']) assert.equal(inspect(state.actions[key].target).State.Running, false, '同Matrix身份旧实例仍运行'); let agent; for (let n = 0; n < 30; n++) { const listing = await accountApi('xlosi3m46q', { op: 'query', scope: 'mine' }); agent = listing.agents?.find(x => x.agentId === state.trial.agentId); if (agent?.channels?.matrixConfig?.channelState === 'connected' && Number.isFinite(agent.heartbeatAgeSec) && agent.heartbeatAgeSec <= 120) break; await pause(1000); } check('真实APK提示词新实例平台首报及Matrix在线', agent?.channels?.matrixConfig?.channelState === 'connected' && Number.isFinite(agent.heartbeatAgeSec) && agent.heartbeatAgeSec <= 120, { agentId: agent?.agentId, heartbeatAgeSec: agent?.heartbeatAgeSec, containerId: runtime.containerId }); const source = state.actions.trialIsolationSeed; await openTrialTask(source); const marker = state.run + '_TRIAL_PROMPT_FRESH'; Object.assign(state.actions.trialFreshChat, { marker, roomId: source.roomId, threadRoot: source.threadRoot, bundleSha256: runtime.bundleSha256, containerId: runtime.containerId, phase: 'before-single-send' }); save(); await c.fill('textarea', `这是新隔离卷按APK提示词从零接入验收。只回复 ${marker}。不要使用工具、不修改文件或配置、不引用旧文件。`); await c.waitFor(() => !document.querySelector('button.m-send')?.disabled); await c.tap('button.m-send'); const action = await proveMessage('trialFreshChat'); await c.waitFor(marker => [...document.querySelectorAll('app-assistant-turn')].some(x => x.innerText.includes(marker)), marker, 60000); check('从零接入后原会话真实回复无旧附件污染', !/https?:\/\/|已上云|MEDIA:/.test(action.proof.body), { body: action.proof.body }); await shot('23-trial-prompt-fresh-chat'); 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 }); } else if (stage === 'verify-trial-fresh-chat') { await proveMessage('trialFreshChat', 30000); } else if (stage === 'trial-documents') { begin('trialDocuments', `${state.trial.agentId}/既有隔离会话单次请求生成PDF和Word;不改配置/不安装依赖`); assert.equal((await auth()).me?.id, state.userId); const source = state.actions.trialIsolationSeed; await openTrialTask(source); const marker = state.run + '_TRIAL_DOCUMENTS'; const names = ['preview-' + state.run.toLowerCase() + '.pdf', 'preview-' + state.run.toLowerCase() + '.docx']; Object.assign(state.actions.trialDocuments, { marker, roomId: source.roomId, threadRoot: source.threadRoot, expectedFiles: names, phase: 'before-single-send' }); save(); 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。`; await c.fill('textarea', prompt); await c.waitFor(() => !document.querySelector('button.m-send')?.disabled); await c.tap('button.m-send'); const action = await proveMessage('trialDocuments', 240000); await c.waitFor(marker => [...document.querySelectorAll('app-assistant-turn')].some(x => x.innerText.includes(marker)), marker, 60000); done('trialDocuments', { proof: action.proof, expectedFiles: names, sends: 1 }); } else if (stage === 'verify-trial-documents') { await proveMessage('trialDocuments', 30000); } else if (stage === 'trial-document-previews' || stage === 'trial-document-previews-readback') { if (stage === 'trial-document-previews-readback') assert.ok(state.actions.trialDocumentPreviews?.attempted && !state.actions.trialDocumentPreviews?.confirmedAt, '只读补查仅适用于未完成的文档预览'); else begin('trialDocumentPreviews', `${state.trial.agentId}/本轮两份PDF和Word实际字节、会话归属和APK canvas预览;不发送`); assert.equal((await auth()).me?.id, state.userId); const task = state.actions.trialDocuments; await openTrialTask(task); let files; for (let attempt = 0; attempt < 45; attempt++) { const listing = await accountApi('THXAOGKiPK', { action: 'listBySession', roomId: task.roomId, limit: 200 }); files = task.expectedFiles.map(name => (listing.files || []).find(x => [name, name.replaceAll('_', '-')].some(expected => x.url?.endsWith(expected)))); if (files.every(x => x?.roomId === task.roomId)) break; await pause(1000); } check('本轮PDF及Word均自动登记到当前会话', files.every(x => x?.roomId === task.roomId), files.map(x => x && ({ id: x.id, name: x.name, roomId: x.roomId }))); const hubEvidence = stage === 'trial-document-previews' ? 'trial-documents-file-hub.json' : 'trial-documents-file-hub-readback-' + Date.now() + '.json'; fs.writeFileSync(path.join(out, hubEvidence), JSON.stringify(files, null, 2), { flag: 'wx' }); const receipts = []; for (let index = 0; index < task.expectedFiles.length; index++) { const name = task.expectedFiles[index], file = files[index]; const response = await fetch(file.url, { signal: AbortSignal.timeout(30000) }); assert.ok(response.ok); const bytes = Buffer.from(await response.arrayBuffer()); const format = name.endsWith('.pdf') ? bytes.subarray(0, 5).toString() === '%PDF-' : bytes.subarray(0, 4).toString('hex') === '504b0304'; check('本轮文档真实字节、格式及编号 ' + name, format && bytes.includes(Buffer.from(task.marker)), { bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') }); 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); await c.tap(`[aria-label="${previewLabel}"]`); await c.waitFor(() => { const dialog = document.querySelector('[role="dialog"][aria-label^="预览 "]'); return [...(dialog?.querySelectorAll('canvas') || [])].some(x => x.width > 100 && x.height > 100 && x.getClientRects().length); }, undefined, 60000); const pixels = await c.evaluate(() => { const dialog = document.querySelector('[role="dialog"][aria-label^="预览 "]'); const canvas = [...dialog.querySelectorAll('canvas')].find(x => x.width > 100 && x.getClientRects().length); const data = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).data; let dark = 0; 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++; return { width: canvas.width, height: canvas.height, darkPixels: dark, error: !!dialog.querySelector('.err') }; }); check('APK文档canvas有真实可见内容 ' + name, pixels.darkPixels > 25 && !pixels.error, pixels); const screenshot = '22-trial-document-' + (name.endsWith('.pdf') ? 'pdf' : 'word'); await c.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve(true))))); captureNativeScreenshot(path.join(out, screenshot + '.png'), arg('serial', '3e529a34')); receipts.push({ name, url: file.url, bytes: bytes.length, ...pixels, screenshot: screenshot + '.png' }); await c.tap('[aria-label="关闭预览"]'); await c.waitFor(() => !document.querySelector('[role="dialog"][aria-label^="预览 "]')); } done('trialDocumentPreviews', { files: receipts, hubEvidence, sends: 0 }); } else if (stage === 'trial-clean-output') { begin('trialCleanOutput', `${state.trial.agentId}/修复后在原文件会话发送一个纯文字探针;不生成文件`); assert.equal((await auth()).me?.id, state.userId); const source = state.actions.trialFilesV3; await openTrialTask(source); const marker = state.run + '_TRIAL_CLEAN_OUTPUT'; Object.assign(state.actions.trialCleanOutput, { marker, roomId: source.roomId, threadRoot: source.threadRoot, bundleSha256: state.actions.localCandidate.bundleSha256, phase: 'before-single-send' }); save(); await c.fill('textarea', `只回复 ${marker}。本轮只验证普通文字回复,不使用工具、不生成或修改任何文件、不引用或重复之前的文件和链接。`); await c.waitFor(() => !document.querySelector('button.m-send')?.disabled); await c.tap('button.m-send'); const action = await proveMessage('trialCleanOutput'); await c.waitFor(marker => [...document.querySelectorAll('app-assistant-turn')].some(x => x.innerText.includes(marker)), marker, 60000); check('修复后原文件会话纯文字回复不附带旧输入或成果', !/https?:\/\/|已上云|MEDIA:/.test(action.proof.body), { body: action.proof.body }); const labels = await c.evaluate(marker => { const turn = [...document.querySelectorAll('app-assistant-turn')].find(x => x.innerText.includes(marker)); if (!turn) return null; turn.scrollIntoView({ block: 'center' }); return [...turn.querySelectorAll('button[aria-label^="预览 "]')].map(x => x.getAttribute('aria-label')); }, marker); check('修复后纯文字回复无旧文件卡片', Array.isArray(labels) && labels.length === 0, { labels }); await shot('21-trial-clean-output'); done('trialCleanOutput', { proof: action.proof, screenshot: '21-trial-clean-output.png', sends: 1 }); } else if (stage === 'verify-trial-clean-output') { await proveMessage('trialCleanOutput', 30000); } else if (stage === 'trial-evidence-audit') { begin('trialEvidenceAudit', `${state.trial.agentId}/补强后的完整事件、可见卡片和真实loader审计;不发送/重试`); assert.equal((await auth()).me?.id, state.userId); for (const key of ['trialFilesV3', 'trialIsolationSeed', 'trialOffline']) await proveMessage(key, 30000); const isolation = await verifyIsolationViews('19-trial-isolation-audit'); await openTrialTask(state.actions.trialFilesV3); const name = state.actions.trialFilesV3.expectedFiles.find(x => x.endsWith('.html')); await c.tap(`[aria-label="预览 ${name}"]`); const before = await readHtmlPreview(state.actions.trialFilesV3.inputMarker); await c.tap('[aria-label="重新加载"]'); const after = await readHtmlPreview(state.actions.trialFilesV3.inputMarker, before); check('安卓 HTML 重新加载产生新loader且真实内容可见', newFrameLoader(before, after), { before, after }); await shot('20-trial-html-loader-audit'); await c.tap('[aria-label="关闭预览"]'); done('trialEvidenceAudit', { isolation, htmlReload: { beforeLoader: before.loaderId, afterLoader: after.loaderId }, sends: 0, retryClicks: 0 }); } else if (stage === 'trial-links-refresh') { begin('trialLinksRefresh', `${state.trial.agentId}/原成果复制链接、真实粘贴与HTML重新加载;不发送`); assert.equal((await auth()).me?.id, state.userId); const task = state.actions.trialFilesV3; await openTrialTask(task); const previousDraft = await c.evaluate(() => document.querySelector('textarea').value); assert.equal(previousDraft, '', '输入框有用户草稿,停止粘贴验收以免覆盖'); const files = JSON.parse(fs.readFileSync(path.join(out, 'trial-v3-file-hub.json'))); const results = []; for (const name of task.expectedFiles) { const file = files.find(x => x.url.endsWith(name)); assert.ok(file); await c.tap(`[aria-label="预览 ${name}"]`); await c.waitFor(() => !!document.querySelector('[role="dialog"][aria-label^="预览 "]')); if (name.endsWith('.html')) { const before = await readHtmlPreview(task.inputMarker); await c.tap('[aria-label="重新加载"]'); await readHtmlPreview(task.inputMarker, before); check('安卓 HTML 重新加载后真实内容及可见预览', true); } else await c.waitFor(marker => document.querySelector('[role="dialog"][aria-label^="预览 "]')?.innerText.includes(marker), task.inputMarker); await c.tap('[aria-label="复制链接"], [aria-label="已复制链接"]'); await c.waitFor(() => !!document.querySelector('[aria-label="已复制链接"]')); check('安卓复制反馈与无悬浮提示 ' + name, await c.evaluate(() => ![...document.querySelectorAll('[role="tooltip"]')].some(x => x.getClientRects().length))); await shot(name.endsWith('.md') ? '15-trial-copy-md' : '16-trial-copy-html'); await c.tap('[aria-label="关闭预览"]'); await c.waitFor(() => !document.querySelector('[role="dialog"][aria-label^="预览 "]')); await c.tap('textarea'); deviceAdb(['shell', 'input', 'keyevent', 'KEYCODE_PASTE']); await c.waitFor(url => document.querySelector('textarea')?.value === url, file.url, 10000); const pasted = await c.evaluate(() => document.querySelector('textarea').value); check('安卓系统剪贴板真实粘贴URL一致 ' + name, pasted === file.url, { url: pasted }); await c.fill('textarea', ''); deviceAdb(['shell', 'input', 'keyevent', 'KEYCODE_BACK']); results.push({ name, url: pasted, htmlReload: name.endsWith('.html') }); } done('trialLinksRefresh', { files: results, copiedBy: 'APK复制按钮→Android KEYCODE_PASTE→原输入框回读;未注入剪贴板或发送', sends: 0 }); } else if (stage === 'trial-offline') { begin('trialOffline', `${state.trial.agentId}/原文字会话断网发送一次;先证实服务器零事件再单独重试`); assert.equal((await auth()).me?.id, state.userId); const task = state.actions.trialChatReady; await openTrialTask(task); const binding = await readBinding(); const marker = state.run + '_TRIAL_OFFLINE'; const prompt = `这是安卓断网恢复验收,只回复 ${marker}。不要使用工具,不修改任何文件或配置。`; Object.assign(state.actions.trialOffline, { marker, prompt, roomId: task.roomId, threadRoot: task.threadRoot, phase: 'before-offline' }); save(); assert.equal(ownInputs((await readRoomEvents(binding, task.roomId)).events, binding, marker).length, 0); try { networkOverridden = true; await c.send('Network.emulateNetworkConditions', { offline: true, latency: 0, downloadThroughput: -1, uploadThroughput: -1 }); state.actions.trialOffline.phase = 'offline-before-send'; save(); await c.waitFor(() => navigator.onLine === false); await c.fill('textarea', prompt); await c.waitFor(() => !document.querySelector('button.m-send')?.disabled); state.actions.trialOffline.phase = 'before-single-tap'; save(); await c.tap('button.m-send'); state.actions.trialOffline.phase = 'offline-tap-complete'; save(); await c.waitFor(marker => [...document.querySelectorAll('app-m-msg')].some(x => x.innerText.includes(marker) && x.innerText.includes('发送失败')), marker, 15000); check('断网消息有明确失败与重试入口', true); const history = await readRoomEvents(binding, task.roomId); fs.writeFileSync(path.join(out, 'trial-offline-server-before-retry.json'), JSON.stringify(history, null, 2), { flag: 'wx' }); const inputs = ownInputs(history.events, binding, marker); check('断网失败消息服务器零输入事件', inputs.length === 0, { roomId: task.roomId, count: inputs.length }); await c.evaluate(marker => [...document.querySelectorAll('app-m-msg')].find(x => x.innerText.includes(marker) && x.innerText.includes('发送失败'))?.scrollIntoView({ block: 'center' }), marker); await shot('17-trial-offline-failed'); } finally { await c.send('Network.emulateNetworkConditions', { offline: false, latency: 0, downloadThroughput: -1, uploadThroughput: -1 }); networkOverridden = false; state.actions.trialOffline.networkRestoredAt = new Date().toISOString(); save(); } await c.waitFor(() => navigator.onLine === true); done('trialOffline', { roomId: task.roomId, marker, serverInputCount: 0, networkRestored: true, screenshot: '17-trial-offline-failed.png', retryPending: true }); } else if (stage === 'trial-offline-retry') { assert.ok(!state.actions.trialOfflineRetry?.attempted, '断网重试已有动作记录,必须只读核实,不重复点击'); const task = state.actions.trialOffline; assert.ok(task?.confirmedAt && task.receipt?.serverInputCount === 0 && task.networkRestoredAt, '先完成断网失败及网络恢复回验'); assert.equal((await auth()).me?.id, state.userId); const binding = await readBinding(); await c.waitFor(() => navigator.onLine && !document.body.innerText.includes('连接已断开'), undefined, 60000); const point = await c.evaluate(marker => { const candidates = [...document.querySelectorAll('app-m-msg')].filter(x => x.innerText.includes(marker)); if (candidates.length !== 1) return null; const button = [...candidates[0].querySelectorAll('button')].find(x => x.innerText.includes('发送失败') && x.getClientRects().length); if (!button) return null; button.scrollIntoView({ block: 'center' }); const r = button.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; }, task.marker); assert.ok(point, '原失败消息或唯一重试按钮不可见,停止而不新建消息替代'); const history = await checkRetryUnsent(async () => { await c.waitFor(() => navigator.onLine && !document.body.innerText.includes('连接已断开'), undefined, 60000); }, () => readRoomEvents(binding, task.roomId), binding, task.marker); fs.writeFileSync(path.join(out, 'trial-offline-retry-preflight.json'), JSON.stringify(history, null, 2), { flag: 'wx' }); begin('trialOfflineRetry', `${state.trial.agentId}/${task.roomId}/${task.marker}/仅点原失败消息重试一次`); await c.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [point] }); await c.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); await proveMessage('trialOffline'); await c.waitFor(marker => [...document.querySelectorAll('app-assistant-turn')].some(x => x.innerText.includes(marker)), task.marker, 60000); check('断网恢复单次重试后真实回复与结束信号可见', true); await shot('18-trial-offline-recovered'); done('trialOfflineRetry', { proof: task.proof, screenshot: '18-trial-offline-recovered.png', retryClicks: 1 }); } else if (stage === 'verify-trial-offline') { await proveMessage('trialOffline', 30000); console.log(JSON.stringify({ proof: state.actions.trialOffline.proof, retry: state.actions.trialOfflineRetry })); } else if (stage === 'trial-refresh') { assert.ok(state.actions.cloudPrompt?.confirmedAt, '新提示词云函数尚无定向部署回验'); const account = JSON.parse(fs.readFileSync(accountFile)); assert.equal((await auth()).me?.id, state.userId, '真机身份不属于本轮账号'); const bindingBefore = await readBinding(); const before = await accountApi('xlosi3m46q', { op: 'query', scope: 'mine' }); const idsBefore = (before.agents || []).map(x => x.agentId).sort(); begin('trialPromptRefresh', `${state.userId}/${state.trial.agentId}/已部署新版提示词;不得新增绑定或容器`); await navigate('/plans'); await c.waitFor(() => !!document.querySelector('.plans-trial-btn')); await c.tap('.plans-trial-btn'); await c.waitFor(() => document.querySelector('app-provision-instruction .ins-code')?.innerText.includes('接入包版本:'), undefined, 90000); const instruction = await c.evaluate(() => document.querySelector('app-provision-instruction .ins-code').innerText); const env = Object.fromEntries(instruction.split('\n').map(line => line.match(/^([A-Z][A-Z0-9_]*)=(.*)$/)).filter(Boolean).map(([, key, value]) => [key, value.trim()])); assert.equal(env.AGENT_ID, state.trial.agentId, '刷新提示词意外产生不同试用身份,停止操作'); assert.equal(env.MATRIX_USER_ID, state.trial.agentMxId); assert.equal(env.FMODE_SESSION_TOKEN, account.token); const bundle = JSON.parse(fs.readFileSync('cloud/onboarding/bundle.json')); assert.ok(instruction.includes(bundle.sha256) && instruction.includes(bundle.url), 'APK 未取得已回验的固定接入包'); const bindingAfter = await readBinding(); assert.equal(bindingAfter.objectId, bindingBefore.objectId, '提示词刷新改变了既有绑定'); const after = await accountApi('xlosi3m46q', { op: 'query', scope: 'mine' }); assert.deepEqual((after.agents || []).map(x => x.agentId).sort(), idsBefore, '提示词刷新新增了容器,停止后续动作'); fs.writeFileSync(path.join(privateDir, 'trial-instruction-updated.md'), instruction); fs.writeFileSync(path.join(privateDir, 'trial-env-updated.json'), JSON.stringify(env, null, 2)); 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 }; state.trial.updatedInstruction = receipt; save(); done('trialPromptRefresh', receipt); await c.screenshot(path.join(privateDir, 'trial-instruction-updated.png')); check('APK 取得新版真实提示词且未新增容器或绑定', true, receipt); console.log(JSON.stringify({ updatedInstructionCaptured: true, ...receipt })); } else if (stage === 'trial' || stage === 'capture-trial') { const account = JSON.parse(fs.readFileSync(accountFile, 'utf8')); assert.equal((await auth()).me?.id, account.userId, '真机当前身份不属于本轮账号'); if (stage === 'trial') { await navigate('/plans'); await c.waitFor(() => !!document.querySelector('.plans-trial-btn')); await shot('04-trial-before'); begin('trial', `${account.userId}/trial/我的试用容器`); await c.tap('.plans-trial-btn'); } else assert.ok(state.actions.trial?.attempted, '无试用创建记录,不能接管'); await c.waitFor(() => !!document.querySelector('app-provision-instruction .ins-code')?.innerText.includes('AGENT_ID='), undefined, 90000); const instruction = await c.evaluate(() => document.querySelector('app-provision-instruction .ins-code').innerText); const env = Object.fromEntries(instruction.split('\n').map(line => line.match(/^([A-Z][A-Z0-9_]*)=(.*)$/)).filter(Boolean).map(([, k, v]) => [k, v.trim()])); for (const key of ['AGENT_ID', 'MATRIX_USER_ID', 'MATRIX_PASSWORD', 'MATRIX_HOME_ROOM', 'FMODE_SESSION_TOKEN']) assert.ok(env[key], `提示词缺少 ${key}`); assert.equal(env.FMODE_SESSION_TOKEN, account.token, '提示词不是本账号当前登录态'); fs.writeFileSync(path.join(privateDir, 'trial-instruction.md'), instruction); fs.writeFileSync(path.join(privateDir, 'trial-env.json'), JSON.stringify(env, null, 2)); state.trial = { agentId: env.AGENT_ID, agentMxId: env.MATRIX_USER_ID, roomId: env.MATRIX_HOME_ROOM, instructionSha256: createHash('sha256').update(instruction).digest('hex') }; state.assets.push({ kind: 'trial-binding', ...state.trial, owner: account.userId }); done('trial', state.trial); await shot('05-trial-instruction'); check('APK 试用入口生成本账号真实接入参数', true, state.trial); console.log(JSON.stringify({ instructionSaved: true, ...state.trial })); } else throw Error('未知阶段:' + stage); } catch (error) { if (lock !== undefined && state) { state.lastFailure = { stage, message: error.message, at: new Date().toISOString() }; save(); note(`${stage} 未完成:${error.message}。先只读核实,不重复请求。`); if (c) await shot(`${stage}-failure`).catch(() => {}); } throw error; } finally { if (networkOverridden && c) { await c.send('Network.emulateNetworkConditions', { offline: false, latency: 0, downloadThroughput: -1, uploadThroughput: -1 }).catch(error => note('网络仿真恢复未确认:' + error.message + ';先检查设备网络,禁止重试发送。')); } c?.close(); if (lock !== undefined) { fs.closeSync(lock); fs.unlinkSync(lockFile); } }