test-dual-channel-diagnostic.mjs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. import test from 'node:test';
  2. import assert from 'node:assert/strict';
  3. import fs from 'node:fs';
  4. import os from 'node:os';
  5. import path from 'node:path';
  6. import { spawn } from 'node:child_process';
  7. import { once } from 'node:events';
  8. import { runDiagnostic } from './diagnose-dual-channels.mjs';
  9. const diagnosticUrl = new URL('./diagnose-dual-channels.mjs', import.meta.url).href;
  10. function fixture(t, state = { actions: {}, checks: [] }) {
  11. const root = fs.mkdtempSync(path.join(os.tmpdir(), 'fmode-dual-diagnostic-test-'));
  12. t.after(() => fs.rmSync(root, { recursive: true, force: true }));
  13. const dir = path.join(root, 'test-results/dual-channel-20261201');
  14. fs.mkdirSync(dir, { recursive: true });
  15. const file = path.join(dir, 'state.json');
  16. fs.writeFileSync(file, JSON.stringify(state));
  17. fs.writeFileSync(path.join(dir, 'master-question.md'), 'fixture question');
  18. const read = () => JSON.parse(fs.readFileSync(file, 'utf8'));
  19. const run = (command, request) => runDiagnostic({ root, command,
  20. client: { MASTER_MXID: '@master:fixture', USER_MXID: '@user:fixture', request },
  21. recordProgress() {}, print() {} });
  22. return { root, dir, file, read, run };
  23. }
  24. const existing = () => ({ actions: { room: { attempted: true, roomId: '!fixture' },
  25. send: { attempted: true, eventId: '$question', since: 0 },
  26. followup: { attempted: true, eventId: '$followup', txnId: 'existing-txn' } }, checks: [] });
  27. const event = (id, type = 'm.room.message', content = { body: 'fixture reply' }) => ({
  28. event_id: id, origin_server_ts: 1, sender: '@master:fixture', type, content });
  29. test('two independent processes can create and send only once', async t => {
  30. const f = fixture(t);
  31. const calls = path.join(f.root, 'calls.log');
  32. const code = `import fs from 'node:fs';
  33. import {runDiagnostic} from ${JSON.stringify(diagnosticUrl)};
  34. const waitForRelease=process.argv[1]==='hold';
  35. try {await runDiagnostic({root:${JSON.stringify(f.root)},command:'send',print(){},recordProgress(){},
  36. client:{MASTER_MXID:'@master:fixture',USER_MXID:'@user:fixture',request:async p=>{
  37. if(p==='/account/whoami') {if(waitForRelease){process.stdout.write('locked\\n');await new Promise(r=>process.stdin.once('data',r));}return {user_id:'@user:fixture'};}
  38. if(p==='/createRoom'){fs.appendFileSync(${JSON.stringify(calls)},'room\\n');return {room_id:'!fixture'};}
  39. if(p.includes('/send/')){fs.appendFileSync(${JSON.stringify(calls)},'send\\n');return {event_id:'$question'};}
  40. throw Error('unexpected mock request');
  41. }}});process.stdin.pause();process.exitCode=0;
  42. }catch(e){process.stdout.write(e.code||e.message);process.exitCode=2;}`;
  43. const first = spawn(process.execPath, ['--input-type=module', '-e', code, 'hold'], { windowsHide: true });
  44. t.after(() => { if (first.exitCode === null) first.kill(); });
  45. await once(first.stdout, 'data');
  46. const firstDone = once(first, 'exit');
  47. const second = spawn(process.execPath, ['--input-type=module', '-e', code, 'now'], { windowsHide: true });
  48. let output = '';
  49. second.stdout.on('data', value => { output += value; });
  50. const [secondExit] = await once(second, 'exit');
  51. assert.equal(secondExit, 2);
  52. assert.match(output, /EEXIST/);
  53. first.stdin.write('release');
  54. const [firstExit] = await firstDone;
  55. assert.equal(firstExit, 0);
  56. assert.equal(fs.readFileSync(calls, 'utf8'), 'room\nsend\n');
  57. assert.equal(f.read().actions.send.eventId, '$question');
  58. });
  59. test('read preserves actions and accumulates event evidence by ID', async t => {
  60. const f = fixture(t, existing());
  61. fs.writeFileSync(path.join(f.dir, 'master-events.json'), JSON.stringify({ events: [event('$old')] }));
  62. await f.run('read', async p => p.endsWith('/joined_members') ? { joined: { '@master:fixture': {} } } : {
  63. chunk: [event('$new'), event('$question'), event('$unrelated-reaction', 'm.reaction', {
  64. 'm.relates_to': { event_id: '$other-task', key: '✅' } })], end: 'next' });
  65. assert.equal(f.read().actions.followup.txnId, 'existing-txn');
  66. assert.equal(f.read().lastReadCoverage.complete, true);
  67. assert.equal(f.read().completionReactions.length, 0);
  68. const ids = JSON.parse(fs.readFileSync(path.join(f.dir, 'master-events.json'))).events.map(e => e.event_id);
  69. assert.ok(ids.includes('$old') && ids.includes('$new'));
  70. assert.equal(fs.readdirSync(path.join(f.dir, 'observations')).length, 1);
  71. });
  72. test('read and followup cannot race over action state', async t => {
  73. const state = existing();
  74. delete state.actions.followup;
  75. const f = fixture(t, state);
  76. let entered;
  77. const ready = new Promise(resolve => { entered = resolve; });
  78. let release;
  79. const gate = new Promise(resolve => { release = resolve; });
  80. const reading = f.run('read', async p => {
  81. if (p.endsWith('/joined_members')) { entered(); await gate; return { joined: {} }; }
  82. return { chunk: [event('$question')] };
  83. });
  84. await ready;
  85. await assert.rejects(f.run('followup', async () => { throw Error('must not call network'); }), { code: 'EEXIST' });
  86. release();
  87. await reading;
  88. await f.run('followup', async () => ({ event_id: '$followup-new' }));
  89. await f.run('read', async p => p.endsWith('/joined_members') ? { joined: {} } : { chunk: [event('$question')] });
  90. assert.equal(f.read().actions.followup.eventId, '$followup-new');
  91. });
  92. test('bounded pagination marks truncation and keeps prior successful evidence', async t => {
  93. const f = fixture(t, existing());
  94. fs.writeFileSync(path.join(f.dir, 'master-events.json'), JSON.stringify({ events: [event('$retained')] }));
  95. let pages = 0;
  96. await f.run('read', async p => p.endsWith('/joined_members') ? { joined: {} } :
  97. { chunk: [event('$page-' + ++pages)], end: 'token-' + pages });
  98. assert.equal(pages, 6);
  99. assert.equal(f.read().lastReadCoverage.truncated, true);
  100. assert.equal(f.read().lastReadCoverage.startEventFound, false);
  101. assert.equal(f.read().lastReadCoverage.nextToken, 'token-6');
  102. assert.ok(f.read().replyEventIds.includes('$retained'));
  103. });
  104. test('failed observation records failure without overwriting the prior response', async t => {
  105. const f = fixture(t, existing());
  106. const file = path.join(f.dir, 'master-events.json');
  107. const previous = JSON.stringify({ events: [event('$retained')] });
  108. fs.writeFileSync(file, previous);
  109. await assert.rejects(f.run('read', async () => { throw Error('fixture timeout'); }), /fixture timeout/);
  110. assert.equal(fs.readFileSync(file, 'utf8'), previous);
  111. assert.equal(f.read().failures.at(-1).status, 'observation_failed_previous_evidence_retained');
  112. assert.equal(f.read().actions.followup.eventId, '$followup');
  113. });
  114. test('existing locks remain untouched and no remote call occurs', async t => {
  115. const f = fixture(t);
  116. const lock = path.join(f.dir, 'runner.lock');
  117. fs.writeFileSync(lock, 'external owner');
  118. await assert.rejects(f.run('send', async () => { throw Error('must not call network'); }), { code: 'EEXIST' });
  119. assert.equal(fs.readFileSync(lock, 'utf8'), 'external owner');
  120. });
  121. test('unknown room creation outcome remains blocked against another send', async t => {
  122. const f = fixture(t);
  123. let created = 0;
  124. const request = async p => {
  125. if (p === '/account/whoami') return { user_id: '@user:fixture' };
  126. created++;
  127. throw Error('fixture timeout after remote create');
  128. };
  129. await assert.rejects(f.run('send', request), /timeout after remote create/);
  130. await assert.rejects(f.run('send', request), /已有动作意图/);
  131. assert.equal(created, 1);
  132. assert.equal(f.read().actions.room.attempted, true);
  133. assert.equal(f.read().failures.length, 2);
  134. });