| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- /** Execute trusted runner code with fake I/O to reproduce stale-ledger competition. */
- import fs from 'node:fs';
- import path from 'node:path';
- import assert from 'node:assert/strict';
- import { createHash } from 'node:crypto';
- import { test } from 'node:test';
- const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
- async function compete(file, stage, key) {
- const source = fs.readFileSync(new URL(file, import.meta.url), 'utf8').replace(/^import[^\n]*\n/gm, '');
- let shared = { run: 'fixture', phone: '18100000000', actions: {}, checks: [], assets: [], trial: { agentId: 'agent-fixture' } };
- let pending;
- const calls = [];
- const fakeFs = {
- existsSync: () => true,
- mkdirSync() {},
- openSync() {
- calls.push('lock');
- // Another process completed after this process started but before it acquired the lock.
- shared.actions[key] = { attempted: true, confirmedAt: 'concurrent-completion', proof: 'must-preserve' };
- return 7;
- },
- readFileSync(file) {
- if (String(file).endsWith('state.json')) { calls.push('read-state'); return JSON.stringify(shared); }
- return JSON.stringify({ AGENT_ID: 'agent-fixture', MATRIX_PASSWORD: 'fixture-password', FMODE_SESSION_TOKEN: 'fixture-token' });
- },
- writeFileSync(file, data) { if (String(file).endsWith('state.json.next')) pending = JSON.parse(data); },
- renameSync() { shared = pending; },
- appendFileSync() {}, closeSync() {}, unlinkSync() {},
- };
- const c = {
- async evaluate(fn) {
- if (String(fn).includes('fmode_session_token')) return { token: null, me: null };
- return true;
- },
- async waitFor() {}, async fill() {}, async screenshot() {}, close() {},
- async tap() { calls.push('external-action'); },
- };
- const fakeProcess = { argv: ['node', 'runner', '--stage=' + stage, '--phone=18100000000'], pid: 1, cwd: () => '/project' };
- const execute = new AsyncFunction('fs', 'path', 'assert', 'createHash', 'connectWebView', 'spawnSync', 'process', 'console', 'recordProgress', source);
- await assert.rejects(() => execute(fakeFs, path, assert, createHash, async () => c,
- () => { calls.push('external-action'); throw Error('Docker must not be called'); }, fakeProcess, { log() {} }, () => {}), /已有.*记录|已.*动作记录|已登记/);
- assert.ok(calls.indexOf('lock') < calls.indexOf('read-state'), 'the fresh ledger must be read only after locking');
- assert.equal(calls.filter(x => x === 'external-action').length, 0, 'no SMS, trial or Docker action may be repeated');
- assert.equal(shared.actions[key].proof, 'must-preserve', 'do not overwrite the competing process receipt');
- }
- test('SMS runner reloads concurrent completed action after acquiring lock', () => compete('./verify-new-account.mjs', 'request-code', 'sms'));
- test('Docker runner reloads concurrent completed action after acquiring lock', () => compete('./verify-trial-local.mjs', 'raw', 'localRaw'));
- test('cold-start runner never stops the app again when its action is already recorded', () => compete('./verify-new-account.mjs', 'trial-cold-start', 'trialColdStart'));
- test('relogin SMS runner does not log out or request another code after a recorded request', () => compete('./verify-new-account.mjs', 'request-relogin-code', 'smsRelogin'));
- test('isolation runner does not navigate after its action is recorded', () => compete('./verify-new-account.mjs', 'trial-isolation', 'trialIsolation'));
- test('copy runner does not change clipboard after its action is recorded', () => compete('./verify-new-account.mjs', 'trial-links-refresh', 'trialLinksRefresh'));
- test('offline runner does not send after its action is recorded', () => compete('./verify-new-account.mjs', 'trial-offline', 'trialOffline'));
- test('offline retry runner never clicks retry twice', () => compete('./verify-new-account.mjs', 'trial-offline-retry', 'trialOfflineRetry'));
- test('isolation seed runner never creates or sends twice', () => compete('./verify-new-account.mjs', 'trial-isolation-send', 'trialIsolationSeed'));
- test('isolation verification never repeats a recorded verification action', () => compete('./verify-new-account.mjs', 'trial-isolation-verify', 'trialIsolationVerified'));
- test('clean-output runner never repeats an existing real send', () => compete('./verify-new-account.mjs', 'trial-clean-output', 'trialCleanOutput'));
- test('real-prompt fresh install never recreates a recorded volume or container', () => compete('./verify-trial-local.mjs', 'prompt-fresh', 'localPromptFresh'));
- test('document fixture task never repeats an existing real send', () => compete('./verify-new-account.mjs', 'trial-documents', 'trialDocuments'));
- test('fresh-prompt roundtrip never repeats an existing real send', () => compete('./verify-new-account.mjs', 'trial-fresh-chat', 'trialFreshChat'));
- test('advanced creation reloads concurrent receipt and never clicks another plan', () => compete('./verify-new-account.mjs', 'advanced-start', 'advancedCreate'));
- async function routeCheck(actual, requested) {
- const source = fs.readFileSync(new URL('./verify-new-account.mjs', import.meta.url), 'utf8');
- const navigate = source.match(/const navigate = async route => \{[\s\S]*?\n\};/)[0];
- const c = { async evaluate() {}, async waitFor(fn, arg) { assert.ok(fn(arg), '目标会话必须匹配'); } };
- await new AsyncFunction('c', 'location', 'target', navigate + '\nawait navigate(target);')(c, { pathname: actual }, requested);
- }
- test('navigation accepts Angular-normalized encoding of the same Matrix thread root', () => routeCheck('/mobile/chat/agent/$root:fmode.cn', '/mobile/chat/agent/%24root%3Afmode.cn'));
- test('navigation still rejects a different thread root', () => assert.rejects(() => routeCheck('/mobile/chat/agent/$other:fmode.cn', '/mobile/chat/agent/%24root%3Afmode.cn'), /目标会话必须匹配/));
- async function chosenPackage(stage) {
- const source = fs.readFileSync(new URL('./verify-trial-local.mjs', import.meta.url), 'utf8').replace(/^import[^\n]*\n/gm, '');
- const selected = path.resolve('test-results/isolated-package-v101');
- let shared = { run: 'fixture', phone: '18100000000', actions: { localRaw: { target: 'raw' } }, assets: [], checks: [], trial: { agentId: 'agent-fixture' } }, pending;
- if (stage === 'update-candidate') shared.actions.localCandidate = { target: 'candidate', containerId: 'candidate-id', volume: 'fixture-volume' };
- if (stage === 'status') shared.actions.localPromptFresh = { attempted: true, kind: 'trial-local', target: 'fresh-prompt-instance' };
- const reads = [], dockerCalls = [];
- const fakeFs = {
- existsSync: () => true, openSync: () => 7, closeSync() {}, unlinkSync() {},
- readFileSync(file) {
- reads.push(file);
- if (String(file).endsWith('state.json')) return JSON.stringify(shared);
- if (String(file).endsWith('receipt.json')) return JSON.stringify({ sha256: 'a'.repeat(64) });
- return JSON.stringify({ AGENT_ID: 'agent-fixture', MATRIX_PASSWORD: 'fixture-password', FMODE_SESSION_TOKEN: 'fixture-token' });
- },
- writeFileSync(file, data) { if (String(file).endsWith('state.json.next')) pending = JSON.parse(data); },
- renameSync() { shared = pending; },
- };
- const spawn = (command, args) => {
- assert.equal(command, 'docker'); dockerCalls.push(args);
- if (args[0] === 'volume' && args[1] === 'inspect') return { status: 1, stdout: '', stderr: '' };
- if (args[0] === 'inspect') return { status: 0, stdout: JSON.stringify([{ Id: args[1] === 'raw' ? 'raw-id' : 'candidate-id', State: { Running: args[1] !== 'raw', Status: args[1] === 'raw' ? 'exited' : 'running' }, Mounts: [], Config: { Env: [] } }]) };
- return { status: 0, stdout: args[0] === 'run' && args.includes('-d') ? 'candidate-id' : '', stderr: '' };
- };
- const proc = { argv: ['node', 'runner', '--stage=' + stage, '--package-dir=' + selected], pid: 1, cwd: () => '/project' };
- const run = new AsyncFunction('fs', 'path', 'assert', 'spawnSync', 'process', 'console', 'recordProgress', 'setTimeout', source);
- await run(fakeFs, path, assert, spawn, proc, { log() {} }, () => {}, fn => fn());
- if (stage === 'status') {
- assert.ok(dockerCalls.some(args => args[0] === 'inspect' && args[1] === 'fresh-prompt-instance'), 'read-only status must inspect the new prompt instance, including uncertain starts');
- return;
- }
- assert.ok(reads.includes(path.join(selected, 'receipt.json')), 'must read selected receipt rather than old default');
- const install = dockerCalls.find(args => args[0] === 'run' && args.includes('--network') && args.some(value => value.endsWith('target=/candidate,readonly')));
- assert.ok(install?.includes(`type=bind,source=${path.join(selected, 'package')},target=/candidate,readonly`), 'must install selected package rather than old default');
- }
- test('fresh candidate honors explicitly selected package directory', () => chosenPackage('candidate'));
- test('candidate update honors explicitly selected package directory', () => chosenPackage('update-candidate'));
- test('read-only Docker status includes recorded fresh-prompt instances', () => chosenPackage('status'));
|