test-onboarding-runners.mjs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /** Execute trusted runner code with fake I/O to reproduce stale-ledger competition. */
  2. import fs from 'node:fs';
  3. import path from 'node:path';
  4. import assert from 'node:assert/strict';
  5. import { createHash } from 'node:crypto';
  6. import { test } from 'node:test';
  7. const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
  8. async function compete(file, stage, key) {
  9. const source = fs.readFileSync(new URL(file, import.meta.url), 'utf8').replace(/^import[^\n]*\n/gm, '');
  10. let shared = { run: 'fixture', phone: '18100000000', actions: {}, checks: [], assets: [], trial: { agentId: 'agent-fixture' } };
  11. let pending;
  12. const calls = [];
  13. const fakeFs = {
  14. existsSync: () => true,
  15. mkdirSync() {},
  16. openSync() {
  17. calls.push('lock');
  18. // Another process completed after this process started but before it acquired the lock.
  19. shared.actions[key] = { attempted: true, confirmedAt: 'concurrent-completion', proof: 'must-preserve' };
  20. return 7;
  21. },
  22. readFileSync(file) {
  23. if (String(file).endsWith('state.json')) { calls.push('read-state'); return JSON.stringify(shared); }
  24. return JSON.stringify({ AGENT_ID: 'agent-fixture', MATRIX_PASSWORD: 'fixture-password', FMODE_SESSION_TOKEN: 'fixture-token' });
  25. },
  26. writeFileSync(file, data) { if (String(file).endsWith('state.json.next')) pending = JSON.parse(data); },
  27. renameSync() { shared = pending; },
  28. appendFileSync() {}, closeSync() {}, unlinkSync() {},
  29. };
  30. const c = {
  31. async evaluate(fn) {
  32. if (String(fn).includes('fmode_session_token')) return { token: null, me: null };
  33. return true;
  34. },
  35. async waitFor() {}, async fill() {}, async screenshot() {}, close() {},
  36. async tap() { calls.push('external-action'); },
  37. };
  38. const fakeProcess = { argv: ['node', 'runner', '--stage=' + stage, '--phone=18100000000'], pid: 1, cwd: () => '/project' };
  39. const execute = new AsyncFunction('fs', 'path', 'assert', 'createHash', 'connectWebView', 'spawnSync', 'process', 'console', 'recordProgress', source);
  40. await assert.rejects(() => execute(fakeFs, path, assert, createHash, async () => c,
  41. () => { calls.push('external-action'); throw Error('Docker must not be called'); }, fakeProcess, { log() {} }, () => {}), /已有.*记录|已.*动作记录|已登记/);
  42. assert.ok(calls.indexOf('lock') < calls.indexOf('read-state'), 'the fresh ledger must be read only after locking');
  43. assert.equal(calls.filter(x => x === 'external-action').length, 0, 'no SMS, trial or Docker action may be repeated');
  44. assert.equal(shared.actions[key].proof, 'must-preserve', 'do not overwrite the competing process receipt');
  45. }
  46. test('SMS runner reloads concurrent completed action after acquiring lock', () => compete('./verify-new-account.mjs', 'request-code', 'sms'));
  47. test('Docker runner reloads concurrent completed action after acquiring lock', () => compete('./verify-trial-local.mjs', 'raw', 'localRaw'));
  48. test('cold-start runner never stops the app again when its action is already recorded', () => compete('./verify-new-account.mjs', 'trial-cold-start', 'trialColdStart'));
  49. 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'));
  50. test('isolation runner does not navigate after its action is recorded', () => compete('./verify-new-account.mjs', 'trial-isolation', 'trialIsolation'));
  51. test('copy runner does not change clipboard after its action is recorded', () => compete('./verify-new-account.mjs', 'trial-links-refresh', 'trialLinksRefresh'));
  52. test('offline runner does not send after its action is recorded', () => compete('./verify-new-account.mjs', 'trial-offline', 'trialOffline'));
  53. test('offline retry runner never clicks retry twice', () => compete('./verify-new-account.mjs', 'trial-offline-retry', 'trialOfflineRetry'));
  54. test('isolation seed runner never creates or sends twice', () => compete('./verify-new-account.mjs', 'trial-isolation-send', 'trialIsolationSeed'));
  55. test('isolation verification never repeats a recorded verification action', () => compete('./verify-new-account.mjs', 'trial-isolation-verify', 'trialIsolationVerified'));
  56. test('clean-output runner never repeats an existing real send', () => compete('./verify-new-account.mjs', 'trial-clean-output', 'trialCleanOutput'));
  57. test('real-prompt fresh install never recreates a recorded volume or container', () => compete('./verify-trial-local.mjs', 'prompt-fresh', 'localPromptFresh'));
  58. test('document fixture task never repeats an existing real send', () => compete('./verify-new-account.mjs', 'trial-documents', 'trialDocuments'));
  59. test('fresh-prompt roundtrip never repeats an existing real send', () => compete('./verify-new-account.mjs', 'trial-fresh-chat', 'trialFreshChat'));
  60. test('advanced creation reloads concurrent receipt and never clicks another plan', () => compete('./verify-new-account.mjs', 'advanced-start', 'advancedCreate'));
  61. async function routeCheck(actual, requested) {
  62. const source = fs.readFileSync(new URL('./verify-new-account.mjs', import.meta.url), 'utf8');
  63. const navigate = source.match(/const navigate = async route => \{[\s\S]*?\n\};/)[0];
  64. const c = { async evaluate() {}, async waitFor(fn, arg) { assert.ok(fn(arg), '目标会话必须匹配'); } };
  65. await new AsyncFunction('c', 'location', 'target', navigate + '\nawait navigate(target);')(c, { pathname: actual }, requested);
  66. }
  67. 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'));
  68. test('navigation still rejects a different thread root', () => assert.rejects(() => routeCheck('/mobile/chat/agent/$other:fmode.cn', '/mobile/chat/agent/%24root%3Afmode.cn'), /目标会话必须匹配/));
  69. async function chosenPackage(stage) {
  70. const source = fs.readFileSync(new URL('./verify-trial-local.mjs', import.meta.url), 'utf8').replace(/^import[^\n]*\n/gm, '');
  71. const selected = path.resolve('test-results/isolated-package-v101');
  72. let shared = { run: 'fixture', phone: '18100000000', actions: { localRaw: { target: 'raw' } }, assets: [], checks: [], trial: { agentId: 'agent-fixture' } }, pending;
  73. if (stage === 'update-candidate') shared.actions.localCandidate = { target: 'candidate', containerId: 'candidate-id', volume: 'fixture-volume' };
  74. if (stage === 'status') shared.actions.localPromptFresh = { attempted: true, kind: 'trial-local', target: 'fresh-prompt-instance' };
  75. const reads = [], dockerCalls = [];
  76. const fakeFs = {
  77. existsSync: () => true, openSync: () => 7, closeSync() {}, unlinkSync() {},
  78. readFileSync(file) {
  79. reads.push(file);
  80. if (String(file).endsWith('state.json')) return JSON.stringify(shared);
  81. if (String(file).endsWith('receipt.json')) return JSON.stringify({ sha256: 'a'.repeat(64) });
  82. return JSON.stringify({ AGENT_ID: 'agent-fixture', MATRIX_PASSWORD: 'fixture-password', FMODE_SESSION_TOKEN: 'fixture-token' });
  83. },
  84. writeFileSync(file, data) { if (String(file).endsWith('state.json.next')) pending = JSON.parse(data); },
  85. renameSync() { shared = pending; },
  86. };
  87. const spawn = (command, args) => {
  88. assert.equal(command, 'docker'); dockerCalls.push(args);
  89. if (args[0] === 'volume' && args[1] === 'inspect') return { status: 1, stdout: '', stderr: '' };
  90. 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: [] } }]) };
  91. return { status: 0, stdout: args[0] === 'run' && args.includes('-d') ? 'candidate-id' : '', stderr: '' };
  92. };
  93. const proc = { argv: ['node', 'runner', '--stage=' + stage, '--package-dir=' + selected], pid: 1, cwd: () => '/project' };
  94. const run = new AsyncFunction('fs', 'path', 'assert', 'spawnSync', 'process', 'console', 'recordProgress', 'setTimeout', source);
  95. await run(fakeFs, path, assert, spawn, proc, { log() {} }, () => {}, fn => fn());
  96. if (stage === 'status') {
  97. 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');
  98. return;
  99. }
  100. assert.ok(reads.includes(path.join(selected, 'receipt.json')), 'must read selected receipt rather than old default');
  101. const install = dockerCalls.find(args => args[0] === 'run' && args.includes('--network') && args.some(value => value.endsWith('target=/candidate,readonly')));
  102. assert.ok(install?.includes(`type=bind,source=${path.join(selected, 'package')},target=/candidate,readonly`), 'must install selected package rather than old default');
  103. }
  104. test('fresh candidate honors explicitly selected package directory', () => chosenPackage('candidate'));
  105. test('candidate update honors explicitly selected package directory', () => chosenPackage('update-candidate'));
  106. test('read-only Docker status includes recorded fresh-prompt instances', () => chosenPackage('status'));