| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142 |
- import test from 'node:test';
- import assert from 'node:assert/strict';
- import fs from 'node:fs';
- import os from 'node:os';
- import path from 'node:path';
- import { spawn } from 'node:child_process';
- import { once } from 'node:events';
- import { runDiagnostic } from './diagnose-dual-channels.mjs';
- const diagnosticUrl = new URL('./diagnose-dual-channels.mjs', import.meta.url).href;
- function fixture(t, state = { actions: {}, checks: [] }) {
- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'fmode-dual-diagnostic-test-'));
- t.after(() => fs.rmSync(root, { recursive: true, force: true }));
- const dir = path.join(root, 'test-results/dual-channel-20261201');
- fs.mkdirSync(dir, { recursive: true });
- const file = path.join(dir, 'state.json');
- fs.writeFileSync(file, JSON.stringify(state));
- fs.writeFileSync(path.join(dir, 'master-question.md'), 'fixture question');
- const read = () => JSON.parse(fs.readFileSync(file, 'utf8'));
- const run = (command, request) => runDiagnostic({ root, command,
- client: { MASTER_MXID: '@master:fixture', USER_MXID: '@user:fixture', request },
- recordProgress() {}, print() {} });
- return { root, dir, file, read, run };
- }
- const existing = () => ({ actions: { room: { attempted: true, roomId: '!fixture' },
- send: { attempted: true, eventId: '$question', since: 0 },
- followup: { attempted: true, eventId: '$followup', txnId: 'existing-txn' } }, checks: [] });
- const event = (id, type = 'm.room.message', content = { body: 'fixture reply' }) => ({
- event_id: id, origin_server_ts: 1, sender: '@master:fixture', type, content });
- test('two independent processes can create and send only once', async t => {
- const f = fixture(t);
- const calls = path.join(f.root, 'calls.log');
- const code = `import fs from 'node:fs';
- import {runDiagnostic} from ${JSON.stringify(diagnosticUrl)};
- const waitForRelease=process.argv[1]==='hold';
- try {await runDiagnostic({root:${JSON.stringify(f.root)},command:'send',print(){},recordProgress(){},
- client:{MASTER_MXID:'@master:fixture',USER_MXID:'@user:fixture',request:async p=>{
- 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'};}
- if(p==='/createRoom'){fs.appendFileSync(${JSON.stringify(calls)},'room\\n');return {room_id:'!fixture'};}
- if(p.includes('/send/')){fs.appendFileSync(${JSON.stringify(calls)},'send\\n');return {event_id:'$question'};}
- throw Error('unexpected mock request');
- }}});process.stdin.pause();process.exitCode=0;
- }catch(e){process.stdout.write(e.code||e.message);process.exitCode=2;}`;
- const first = spawn(process.execPath, ['--input-type=module', '-e', code, 'hold'], { windowsHide: true });
- t.after(() => { if (first.exitCode === null) first.kill(); });
- await once(first.stdout, 'data');
- const firstDone = once(first, 'exit');
- const second = spawn(process.execPath, ['--input-type=module', '-e', code, 'now'], { windowsHide: true });
- let output = '';
- second.stdout.on('data', value => { output += value; });
- const [secondExit] = await once(second, 'exit');
- assert.equal(secondExit, 2);
- assert.match(output, /EEXIST/);
- first.stdin.write('release');
- const [firstExit] = await firstDone;
- assert.equal(firstExit, 0);
- assert.equal(fs.readFileSync(calls, 'utf8'), 'room\nsend\n');
- assert.equal(f.read().actions.send.eventId, '$question');
- });
- test('read preserves actions and accumulates event evidence by ID', async t => {
- const f = fixture(t, existing());
- fs.writeFileSync(path.join(f.dir, 'master-events.json'), JSON.stringify({ events: [event('$old')] }));
- await f.run('read', async p => p.endsWith('/joined_members') ? { joined: { '@master:fixture': {} } } : {
- chunk: [event('$new'), event('$question'), event('$unrelated-reaction', 'm.reaction', {
- 'm.relates_to': { event_id: '$other-task', key: '✅' } })], end: 'next' });
- assert.equal(f.read().actions.followup.txnId, 'existing-txn');
- assert.equal(f.read().lastReadCoverage.complete, true);
- assert.equal(f.read().completionReactions.length, 0);
- const ids = JSON.parse(fs.readFileSync(path.join(f.dir, 'master-events.json'))).events.map(e => e.event_id);
- assert.ok(ids.includes('$old') && ids.includes('$new'));
- assert.equal(fs.readdirSync(path.join(f.dir, 'observations')).length, 1);
- });
- test('read and followup cannot race over action state', async t => {
- const state = existing();
- delete state.actions.followup;
- const f = fixture(t, state);
- let entered;
- const ready = new Promise(resolve => { entered = resolve; });
- let release;
- const gate = new Promise(resolve => { release = resolve; });
- const reading = f.run('read', async p => {
- if (p.endsWith('/joined_members')) { entered(); await gate; return { joined: {} }; }
- return { chunk: [event('$question')] };
- });
- await ready;
- await assert.rejects(f.run('followup', async () => { throw Error('must not call network'); }), { code: 'EEXIST' });
- release();
- await reading;
- await f.run('followup', async () => ({ event_id: '$followup-new' }));
- await f.run('read', async p => p.endsWith('/joined_members') ? { joined: {} } : { chunk: [event('$question')] });
- assert.equal(f.read().actions.followup.eventId, '$followup-new');
- });
- test('bounded pagination marks truncation and keeps prior successful evidence', async t => {
- const f = fixture(t, existing());
- fs.writeFileSync(path.join(f.dir, 'master-events.json'), JSON.stringify({ events: [event('$retained')] }));
- let pages = 0;
- await f.run('read', async p => p.endsWith('/joined_members') ? { joined: {} } :
- { chunk: [event('$page-' + ++pages)], end: 'token-' + pages });
- assert.equal(pages, 6);
- assert.equal(f.read().lastReadCoverage.truncated, true);
- assert.equal(f.read().lastReadCoverage.startEventFound, false);
- assert.equal(f.read().lastReadCoverage.nextToken, 'token-6');
- assert.ok(f.read().replyEventIds.includes('$retained'));
- });
- test('failed observation records failure without overwriting the prior response', async t => {
- const f = fixture(t, existing());
- const file = path.join(f.dir, 'master-events.json');
- const previous = JSON.stringify({ events: [event('$retained')] });
- fs.writeFileSync(file, previous);
- await assert.rejects(f.run('read', async () => { throw Error('fixture timeout'); }), /fixture timeout/);
- assert.equal(fs.readFileSync(file, 'utf8'), previous);
- assert.equal(f.read().failures.at(-1).status, 'observation_failed_previous_evidence_retained');
- assert.equal(f.read().actions.followup.eventId, '$followup');
- });
- test('existing locks remain untouched and no remote call occurs', async t => {
- const f = fixture(t);
- const lock = path.join(f.dir, 'runner.lock');
- fs.writeFileSync(lock, 'external owner');
- await assert.rejects(f.run('send', async () => { throw Error('must not call network'); }), { code: 'EEXIST' });
- assert.equal(fs.readFileSync(lock, 'utf8'), 'external owner');
- });
- test('unknown room creation outcome remains blocked against another send', async t => {
- const f = fixture(t);
- let created = 0;
- const request = async p => {
- if (p === '/account/whoami') return { user_id: '@user:fixture' };
- created++;
- throw Error('fixture timeout after remote create');
- };
- await assert.rejects(f.run('send', request), /timeout after remote create/);
- await assert.rejects(f.run('send', request), /已有动作意图/);
- assert.equal(created, 1);
- assert.equal(f.read().actions.room.attempted, true);
- assert.equal(f.read().failures.length, 2);
- });
|