/** 离线执行真实验收分支;文件、云端、CDP、ADB 均由内存夹具替换。 */ import fs from 'node:fs'; import path from 'node:path'; import vm from 'node:vm'; import assert from 'node:assert/strict'; import { createHash } from 'node:crypto'; import { test } from 'node:test'; const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; const runnerSource = fs.readFileSync(new URL('./verify-new-account.mjs', import.meta.url), 'utf8') .replace(/^import[^\n]*\n/gm, ''); const oldIds = ['agent-node-app-trial', 'agent-node-app-original']; const originalRestore = { attempted: true, at: '2026-11-29T06:00:00.000Z', target: 'new-job/原恢复动作', restartedAt: '2026-11-29T06:00:01.000Z' }; const originalRestoreFailure = { stage: 'advanced-restore', message: '原进度按钮定位等待超时,保留首次失败', at: '2026-11-29T06:01:00.000Z' }; function fixture({ stage = 'advanced-status', unavailableCdp = false, page = 'valid', terminal = false, source = runnerSource, alter = () => {} } = {}) { const job = { jobId: 'new-job', agentId: 'NewAgent', planCode: 'advanced', status: 'provisioning', stage: 'prepare', steps: [{ stage: 'prepare', status: 'running' }], currentStep: { stage: 'prepare', status: 'running' } }; const oldJob = { jobId: 'old-job', agentId: 'original', planCode: 'advanced', status: 'ready' }; const data = { job, jobs: [job, oldJob], agents: [...oldIds, 'agent-node-app-newagent'].map(agentId => ({ agentId })), state: { phone: '18100000000', userId: 'fixture', run: 'offline-advanced', checks: [], assets: [], trial: { agentId: oldIds[0] }, actions: { originalProof: { attempted: true, proof: { completion: 'retained-original-reaction' } }, advancedCreate: { attempted: true, jobId: job.jobId, jobsBefore: [oldJob], agentIdsBefore: [...oldIds], latestStatus: { ...job }, statusObservations: ['old-observation.json'] }, }, }, }; if (terminal) { data.job.status = 'ready'; data.jobs[0].status = 'ready'; } alter(data); let state = structuredClone(data.state), pending; const calls = [], writes = new Map(); const fakeFs = { existsSync: () => true, openSync() { calls.push({ type: 'lock' }); return 7; }, closeSync() { calls.push({ type: 'close-lock' }); }, unlinkSync() { calls.push({ type: 'unlock' }); }, readFileSync(file) { if (String(file).endsWith('state.json')) { calls.push({ type: 'read-ledger' }); return JSON.stringify(state); } return JSON.stringify({ token: 'offline-only', userId: 'fixture' }); }, writeFileSync(file, value) { if (String(file).endsWith('state.json.next')) pending = JSON.parse(value); else if (typeof file === 'string') writes.set(file, value); }, renameSync() { assert.ok(pending, '内存账本需先写后替换'); state = pending; pending = undefined; }, }; const fetchImpl = async (_url, options) => { const { id, params } = JSON.parse(options.body); calls.push({ type: 'api', id, params }); let response; if (id === 'VtW1GT93Ax' && params.op === 'list') response = { items: data.jobs }; else if (id === 'VtW1GT93Ax' && params.op === 'status') response = data.job; else if (id === 'xlosi3m46q' && params.op === 'query') response = { agents: data.agents }; else throw Error('离线夹具禁止申请、重试或其他业务接口:' + id + '/' + params.op); return { ok: true, json: async () => ({ code: 200, ...structuredClone(response) }) }; }; const location = { pathname: '/mobile/messages', search: '' }; const events = []; const changeRoute = url => { const parsed = new URL(url, 'https://localhost'); location.pathname = parsed.pathname; location.search = parsed.search; if (location.pathname === '/provision') events.push({ method: 'Network.responseReceived', params: { requestId: 'page-status', response: { url: 'https://server.fmode.cn/api/functions' } } }); }; const button = { innerText: terminal ? '查看我的容器' : '查看开通进度', disabled: false, getClientRects: () => [{}], scrollIntoView() {}, getBoundingClientRect: () => ({ x: 0, y: 0, width: 100, height: 40 }) }; // 与 MbPlansPage 模板一致:section.plans-job 与 div.plans-job-actions 是兄弟。 const plansSection = { innerText: terminal ? '已就绪\n容器创建由平台自动完成' : '正在开通\n容器创建由平台自动完成', querySelector: () => null, querySelectorAll: () => [] }; const plansActions = { get innerText() { return button.innerText; }, querySelector: selector => selector === 'button' ? button : null, querySelectorAll: selector => selector === 'button' ? [button] : [] }; const pageText = () => location.pathname === '/plans' ? plansSection.innerText + '\n' + plansActions.innerText : location.pathname !== '/provision' ? '消息 我的容器' : page === 'blank' ? '' : page === 'error' ? '加载开通状态失败\n重新加载\n返回套餐' : terminal ? '容器已就绪' : '正在创建容器\n准备环境\n开通在服务器上进行'; const element = { get innerText() { return pageText(); }, getClientRects: () => [{}] }; const document = { body: { get innerText() { return pageText(); } }, documentElement: { scrollWidth: 360 }, querySelector(selector) { if (/app-mobile-shell|app-m-tab-bar|app-m-drawer/.test(selector)) return null; if (location.pathname === '/plans' && selector === '.plans-job') return plansSection; if (location.pathname === '/plans' && selector === '.plans-job-actions') return plansActions; if (location.pathname === '/plans' && selector === '.plans-job-actions button') return button; if (location.pathname === '/plans' && selector === '.plans-job button') return null; if (location.pathname === '/provision' && page !== 'blank' && /app-dk-provision-page|app-mb-provision-page|\.prov/.test(selector)) return element; if (location.pathname === '/provision' && page === 'valid' && /progressbar|prov-stage|prov-title|prov-step/.test(selector)) return element; return null; }, querySelectorAll(selector) { if (selector === 'input') return []; if (selector === 'button' || selector === '.plans-job-actions button') return location.pathname === '/plans' ? [button] : []; if (selector === '.plans-job button') return []; if (/prov-stage/.test(selector)) return page === 'valid' ? Array(6).fill(element) : []; return []; }, }; const context = vm.createContext({ location, document, innerWidth: 360, innerHeight: 780, URLSearchParams, localStorage: { getItem: key => key === 'fmode_me' ? JSON.stringify({ id: 'fixture' }) : key === 'fmode_active_provision_job' ? 'new-job' : 'offline-only' }, history: { pushState: (_state, _title, url) => changeRoute(url) }, dispatchEvent() {}, PopStateEvent: class {}, }); const c = { events, async evaluate(fn, value) { calls.push({ type: 'evaluate', source: fn.toString() }); return vm.runInContext('(' + fn.toString() + ')', context)(value); }, async waitFor(fn, value) { assert.ok(await this.evaluate(fn, value), '离线页面等待条件未满足:' + fn.toString()); }, async send(method) { calls.push({ type: 'cdp', method }); if (method === 'Network.getResponseBody') return { body: JSON.stringify({ code: 200, ...data.job }), base64Encoded: false }; if (method === 'Input.dispatchTouchEvent' && location.pathname === '/plans') changeRoute('/provision?jobId=new-job'); return {}; }, async screenshot() {}, close() { calls.push({ type: 'close-cdp' }); }, }; const connect = async () => { calls.push({ type: 'connect-cdp' }); if (unavailableCdp) throw Error('CDP unavailable'); return c; }; const spawn = (command, args) => { assert.equal(command, 'adb', '不得运行其他子进程'); calls.push({ type: 'adb', args }); return { status: 0, stdout: args.includes('pidof') ? '1234' : '', stderr: '' }; }; const execute = new AsyncFunction('fs', 'path', 'assert', 'createHash', 'connectWebView', 'spawnSync', 'process', 'console', 'recordProgress', 'fetch', 'captureNativeScreenshot', source); return { calls, writes, data, get state() { return state; }, async run() { try { await execute(fakeFs, path, assert, createHash, connect, spawn, { argv: ['node', 'runner', '--stage=' + stage, '--phone=18100000000'], pid: 7, cwd: () => process.cwd() }, { log() {} }, () => {}, fetchImpl, () => {}); } finally { assert.ok(calls.find(x => x.type === 'unlock'), '成功和错误均需释放自己持有的账本锁'); assert.deepEqual(state.actions.originalProof, data.state.actions.originalProof, '历史回执应保持不变'); } }, }; } test('恢复夹具任务说明区和操作区与真实移动模板保持兄弟层级', () => { const template = fs.readFileSync(new URL('../src/app/mobile/pages/plans/plans.ts', import.meta.url), 'utf8'); assert.match(template, /
\s*
/); }); test('恢复夹具能够拒绝把操作按钮错定位到任务说明区', async () => { const source = runnerSource.replaceAll('.plans-job-actions button', '.plans-job button'); assert.notEqual(source, runnerSource, '需实际模拟错误的子元素定位'); const run = fixture({ stage: 'advanced-restore', source }); await assert.rejects(() => run.run(), /离线页面等待条件未满足/); assert.notEqual(run.state.actions.advancedRestore?.receipt?.restored, true); }); test('advanced-restore-readback 沿用原重启回执且不再执行任何 ADB 动作', async () => { const run = fixture({ stage: 'advanced-restore-readback', alter(data) { data.state.actions.advancedRestore = { ...originalRestore }; data.state.lastFailure = { ...originalRestoreFailure }; } }); await run.run(); assert.equal(run.calls.filter(x => x.type === 'adb').length, 0); assert.equal(run.state.actions.advancedRestore.at, originalRestore.at); assert.equal(run.state.actions.advancedRestore.restartedAt, originalRestore.restartedAt); assert.equal(run.state.actions.advancedRestore.receipt.restored, true); assert.equal(run.state.actions.advancedRestore.receipt.jobId, 'new-job'); assert.deepEqual(run.state.lastFailure, originalRestoreFailure, '补查成功不能抹掉首次失败'); assert.ok(run.calls.some(x => x.type === 'cdp' && x.method === 'Network.getResponseBody')); }); for (const [label, original] of [ ['缺少原恢复动作', undefined], ['缺少重启回执', { attempted: true, at: originalRestore.at, target: originalRestore.target }], ['原恢复已确认', { ...originalRestore, confirmedAt: '2026-11-29T06:02:00.000Z', receipt: { restored: true, jobId: 'new-job' } }], ]) { test('advanced-restore-readback 拒绝' + label + '并且不执行 ADB 或接口查询', async () => { const run = fixture({ stage: 'advanced-restore-readback', alter(data) { if (original) data.state.actions.advancedRestore = structuredClone(original); } }); await assert.rejects(() => run.run(), /原恢复|重启|未完成|回执/); assert.equal(run.calls.filter(x => x.type === 'adb' || x.type === 'api').length, 0); assert.deepEqual(run.state.actions.advancedRestore, original); }); } test('advanced-status 在 CDP 不可用时仍只读回验原 job 和独立新资产', async () => { const run = fixture({ unavailableCdp: true }); await run.run(); assert.equal(run.calls.filter(x => x.type === 'connect-cdp').length, 0); assert.ok(run.calls.some(x => x.type === 'api' && x.params.op === 'status' && x.params.jobId === 'new-job')); assert.equal(run.state.actions.advancedCreate.latestStatus.jobId, 'new-job'); assert.ok(run.state.actions.advancedCreate.statusObservations.includes('old-observation.json')); assert.ok(run.calls.findIndex(x => x.type === 'lock') < run.calls.findIndex(x => x.type === 'read-ledger')); }); for (const [label, alter] of [ ['错误套餐', data => { data.job.planCode = 'enterprise'; }], ['状态回包错 job', data => { data.job = { ...data.job, jobId: 'other-job' }; }], ['复用旧 agent', data => { data.job.agentId = 'Original'; }], ['原资产丢失', data => { data.agents = data.agents.filter(x => x.agentId !== oldIds[0]); }], ]) { test('advanced-status 拒绝' + label, async () => { const run = fixture({ unavailableCdp: true, alter }); await assert.rejects(() => run.run(), error => error.code === 'ERR_ASSERTION' && !/CDP|离线夹具/.test(error.message)); assert.equal(run.state.actions.advancedCreate.statusObservations.length, 1, '失败不得追加通过回执'); assert.ok(run.state.lastFailure, '失败原因需保留到账本'); }); } for (const page of ['blank', 'error']) { test('advanced-restore 不将' + (page === 'blank' ? '空白页' : '加载失败页') + '记为恢复成功', async () => { const run = fixture({ stage: 'advanced-restore', page }); await assert.rejects(() => run.run(), /离线页面等待条件未满足|进阶|等待|恢复|加载/); assert.ok(run.calls.some(x => x.type === 'adb' && x.args.includes('force-stop')), '需实际进入内存模拟的强停恢复分支'); assert.ok(run.calls.some(x => x.type === 'evaluate' && x.source.includes('app-dk-provision-page')), '负例应走到实际等待页核对处'); assert.notEqual(run.state.actions.advancedRestore?.receipt?.restored, true); assert.ok(run.state.lastFailure, '恢复失败需保留原因'); }); } for (const terminal of [false, true]) { test('advanced-restore 可恢复原任务' + (terminal ? '恰好终结的真实终态' : '真实在途进度'), async () => { const run = fixture({ stage: 'advanced-restore', terminal }); await run.run(); assert.equal(run.state.actions.advancedRestore.receipt.restored, true); assert.equal(run.state.actions.advancedRestore.receipt.jobId, 'new-job'); assert.equal(run.state.actions.advancedRestore.receipt.status, terminal ? 'ready' : 'provisioning'); assert.ok(run.calls.some(x => x.type === 'cdp' && x.method === 'Network.getResponseBody'), '恢复必须依赖页面真实状态回包'); assert.equal(run.state.actions.advancedRestore.receipt.creates, 0); }); }