HEL-897: preserve visual author voice session race fixes

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
2026-10-27 02:52:08 +08:00
co-authored by multica-agent
parent f259bd34e1
commit 761a2331f5
6 changed files with 201 additions and 5 deletions
+15 -3
View File
@@ -124,13 +124,25 @@ export class VoiceController {
}
async start(): Promise<void> {
await this.end();
void this.settle();
// The generation is taken before anything is awaited, so a start that wakes up after a newer one never takes
// the call over; the call it replaces is released first, as end() would.
const prev = this.live;
const gen = ++this.gen, live: Live = { gen, abort: new AbortController(), agent: false, stated: false, hushed: false };
this.live = live;
this.view = { ...OFF, phase: 'opening' }; this.deps.onView(this.view);
const stale = () => gen !== this.gen;
const fail = async (notice: string) => { if (stale()) return; this.live = null; this.gen++; await this.teardown(live); this.view = { ...OFF, notice }; this.deps.onView(this.view); };
if (prev) { await this.teardown(prev); this.deps.onRecord(); }
if (stale()) return;
void this.settle();
// Everything a failure says is said while this call still owns the page; its cleanup goes on afterwards and,
// however late it answers, only releases this call's own microphone, room and server room.
const fail = (notice: string) => {
if (stale()) return Promise.resolve();
this.live = null; this.gen++;
const released = this.teardown(live);
this.view = { ...OFF, notice }; this.deps.onView(this.view);
return released;
};
const secure = (this.deps.secure ?? (() => window.isSecureContext && !!navigator.mediaDevices?.getUserMedia))();
if (!secure) return fail(WORDS.insecure);
+4 -2
View File
@@ -14,7 +14,8 @@ const dist = fileURLToPath(new URL('../dist/', import.meta.url)), fake = fileURL
const port = Number(process.argv[2] || 8878);
const T0 = Date.UTC(2026, 9, 26, 12, 0);
const identity = { id: '1', name: '栖', birth: '2000-03-14', hour: '子', relation: '朋友', nickname: '', boundary: '', color: { pillars: { year: '庚辰', month: '己卯', day: '丙午', hour: '戊子' }, traits: '合成测试档案' } };
const epoch = 3, log = [], rows = [], sessions = new Map();
// /__hold-delete?id=<session> keeps that DELETE unanswered (a slow server); /__hold-delete with no id answers them all.
const epoch = 3, log = [], rows = [], sessions = new Map(), held = new Map();
let voice = { configured: true, tts: true }, refuse = 0, made = 0, voiceTurn = 0, textStream = null;
const add = row => { const id = rows.length + 1; rows.push({ id, ts: T0 + id * 60e3, status: 'sent', lifeIds: [], ...row }); return id; };
add({ role: 'user', text: '下雨天的时候,你会想听什么?', turn_id: '00000000-0000-4000-8000-000000000001' });
@@ -62,7 +63,8 @@ createServer(async (req, res) => {
const id = `sess-${++made}`; sessions.set(id, { room: `cg-voice-${made}` });
return send(res, 201, { url: 'wss://lk.invalid', token: `token-${id}`, room: `cg-voice-${made}`, session_id: id, agent_name: 'cybergril-voice-agent', epoch, expires_at: Date.now() + 2 * 3600e3 });
}
if (p.startsWith('/api/voice/session/') && req.method === 'DELETE') { const id = decodeURIComponent(p.slice(19)); return sessions.delete(id) ? send(res, 200, { ended: true }) : send(res, 404, { detail: '这次通话已经不在了。' }); }
if (p === '/__hold-delete') { const id = url.searchParams.get('id'); if (id) { let open; held.set(id, { promise: new Promise(r => { open = r; }), open }); } else { held.forEach(h => h.open()); held.clear(); } return send(res, 200, { held: [...held.keys()] }); }
if (p.startsWith('/api/voice/session/') && req.method === 'DELETE') { const id = decodeURIComponent(p.slice(19)); if (held.has(id)) await held.get(id).promise; return sessions.delete(id) ? send(res, 200, { ended: true }) : send(res, 404, { detail: '这次通话已经不在了。' }); }
if (p === '/api/chat' && req.method === 'POST') {
let body = ''; for await (const chunk of req) body += chunk;
const { text: said, turn_id } = JSON.parse(body), reply = '我在。今天的雨停了没有?要是还在下,就慢点回家。';
+13
View File
@@ -182,6 +182,19 @@ await startVoice(); await lk('__lk.drop()');
await sleep(300);
check('room dropped: call ends, said so', (await status()).includes('通话断开了'), await status());
await cleanEnd('dropped');
// HEL-897: the dropped call's DELETE answers only after a new call is up; the late answer may not touch the new call.
await startVoice();
const firstSession = (await ctl('/__sessions')).open.at(-1);
await ctl(`/__hold-delete?id=${firstSession}`); await lk('__lk.drop()'); await sleep(300);
check('slow DELETE: dropped call says so and its microphone stops before the server answers', (await status()).includes('通话断开了') && await micsLive() === 0 && (await ctl('/__sessions')).open.includes(firstSession), await status());
await startVoice();
const secondSession = (await ctl('/__sessions')).open.find(s => s !== firstSession);
check('…a new call is up meanwhile: listening', (await phase()) === 'listening' && await micsLive() === 1);
await ctl('/__hold-delete'); await sleep(800);
const lateOpen = (await ctl('/__sessions')).open;
check('…the old DELETE answers late: the new call stays listening, no old notice, one live microphone, her audio, only the new room open', (await phase()) === 'listening' && !(await status()).includes('通话断开了') && await micsLive() === 1 && await herAudio() === 1 && lateOpen.length === 1 && lateOpen[0] === secondSession, `phase=${await phase()} status=${await status()} open=${lateOpen.join()}`);
await shot('12b-moon-desktop-voice-new-call-after-late-delete');
await click('.voice-row.real .voice-end'); await cleanEnd('new call after the late old DELETE');
await ctl('/__refuse/503'); await click('.voice-button'); await until(() => exists('.modal.open')); await click('.modal.open .btn-primary', '开始语音'); await sleep(900);
check('server refusal shows its detail; microphone released', (await status()).includes('她的声音服务这会儿不在') && await micsLive() === 0, await status());
await ctl('/__refuse/0');
+44
View File
@@ -0,0 +1,44 @@
import { expect, test } from 'vitest';
import { VoiceController, type RoomEvents, type VoiceView } from '../src/voice/session';
test('old room disconnect cleanup cannot overwrite a newly opened call', async () => {
const pendingDeletes: (() => void)[] = [];
const releaseOld = () => pendingDeletes.splice(0).forEach(resolve => resolve());
let grant = 0;
const events: RoomEvents[] = [];
let view: VoiceView | undefined;
const controller = new VoiceController({
secure: () => true,
onView: v => { view = v; },
onRecord: () => {}, onSpoke: () => {},
agentWaitMs: 60000,
fetch: (async (url, init) => {
if (String(url).endsWith('/status')) return Response.json({ configured: true, tts_ok: true });
if (init?.method === 'POST') return Response.json({ session_id: `s${++grant}`, token: 'token', url: 'wss://fake.invalid' });
if (String(url).endsWith('/s1')) await new Promise<void>(resolve => { pendingDeletes.push(resolve); });
return Response.json({ ended: true });
}) as typeof fetch,
transport: async () => ({
capture: async () => ({ stop() {}, onEnded() {} }),
join: async (_url, _token, callbacks) => {
events.push(callbacks);
return { publish: async () => {}, close: async () => {}, hush() {}, resumeAudio: async () => {} };
},
}),
});
try {
await controller.start();
events[0].agentJoined();
events[0].dropped(); // DELETE s1 is deliberately held in flight.
await controller.start();
events[1].agentJoined();
expect(view?.phase).toBe('listening');
releaseOld();
await new Promise(resolve => setTimeout(resolve, 0));
expect(controller.active).toBe(true);
expect(view?.phase).toBe('listening');
} finally {
releaseOld();
await controller.end();
}
});
+91
View File
@@ -26,6 +26,8 @@ class Server {
status: Record<string, unknown> | number = { configured: true, tts_ok: true, agent_name: 'cybergril-voice-agent', voice: false };
open = new Set<string>(); made = 0; calls: { method: string; url: string; keepalive?: boolean }[] = [];
postGate?: ReturnType<typeof gate>; refuse?: { status: number; detail: string };
// DELETEs of these sessions wait for the gate (a slow server answering for an older call).
deleteGate?: { ids: Set<string>; gate: ReturnType<typeof gate> };
fetch = vi.fn(async (url: string, init: RequestInit = {}) => {
const method = init.method || 'GET';
this.calls.push({ method, url, keepalive: init.keepalive });
@@ -37,6 +39,7 @@ class Server {
return new Response(JSON.stringify({ url: 'wss://lk.test', token: `tok-${id}`, room: `cg-voice-${id}`, session_id: id, agent_name: 'cybergril-voice-agent', epoch: 3, expires_at: 0 }), { status: 201 });
}
const m = /^\/api\/voice\/session\/(.+)$/u.exec(url);
if (m && method === 'DELETE' && this.deleteGate?.ids.has(decodeURIComponent(m[1]))) await this.deleteGate.gate.promise;
if (m && method === 'DELETE') return this.open.delete(decodeURIComponent(m[1])) ? new Response('{"ended":true}') : new Response('{"detail":"这次通话已经不在了。"}', { status: 404 });
return new Response('{"detail":"Not Found"}', { status: 404 });
});
@@ -247,6 +250,94 @@ describe('lifecycle', () => {
});
});
// An older call's cleanup may answer long after a new call is up (a slow DELETE, the settle retry for it, a late
// microphone): it may only release the older call's own things, never touch the new call's view, microphone or room.
describe('a late end of an older call', () => {
const hold = (r: ReturnType<typeof rig>, ...ids: string[]) => { const g = gate(); r.server.deleteGate = { ids: new Set(ids), gate: g }; return g; };
const reopened = async (r: ReturnType<typeof rig>, i: number) => { await r.c.start(); r.transport.rooms[i].on.agentJoined(); expect(r.view().phase).toBe('listening'); };
const stillNew = (r: ReturnType<typeof rig>, i: number) => {
expect(r.c.active).toBe(true);
expect(r.view()).toMatchObject({ phase: 'listening', notice: '' });
expect(r.transport.mics[i].stopped).toBe(0);
expect(r.transport.rooms[i].closed).toBe(0);
expect(r.transport.mics.slice(0, i).every(m => m.stopped > 0)).toBe(true);
expect(r.transport.rooms.slice(0, i).every(x => x.closed > 0)).toBe(true);
};
const failures: [string, (r: ReturnType<typeof rig>) => void][] = [
['the room dropped', r => r.transport.rooms[0].on.dropped()],
['the microphone was taken away', r => r.transport.mics[0].ended?.()],
];
for (const [what, cause] of failures) {
it(`${what}, its DELETE (and the settle retry) answering after a new call is up, leaves the new call alone`, async () => {
const r = await connected(), slow = hold(r, 's1');
cause(r); await flush();
expect(r.view()).toMatchObject({ phase: 'off' });
expect(r.transport.mics[0].stopped).toBeGreaterThan(0); // released at once, not after the server answers
expect(r.c.active).toBe(false);
await reopened(r, 1);
expect(r.server.calls.filter(c => c.method === 'DELETE' && c.url.endsWith('/s1')).length).toBe(2); // first try + settle
const seen = r.views.length;
slow.open(); await flush();
expect(r.views.length).toBe(seen);
stillNew(r, 1);
expect(r.server.open).toEqual(new Set(['s2']));
await r.c.end(); await flush();
expect(r.server.open.size).toBe(0);
expect(r.transport.mics.every(m => m.stopped)).toBe(true);
});
}
it('her worker never joined, the DELETE is slow, and a new call is started before it answers', async () => {
vi.useFakeTimers();
const r = rig(); await r.c.start(); const slow = hold(r, 's1');
await vi.advanceTimersByTimeAsync(1100);
expect(r.view()).toMatchObject({ phase: 'off', notice: WORDS.noAgent });
await reopened(r, 1);
slow.open(); await vi.advanceTimersByTimeAsync(0);
stillNew(r, 1);
await r.c.end();
});
it('a normal end whose DELETE is slow, then a new call, then the old answer arrives', async () => {
const r = await connected(), slow = hold(r, 's1');
const ending = r.c.end();
expect(r.view()).toMatchObject({ phase: 'off', notice: '' });
await reopened(r, 1);
slow.open(); await ending; await flush();
stillNew(r, 1);
expect(r.server.open).toEqual(new Set(['s2']));
await r.c.end();
});
it('starting again while the previous start still waits for the old room to be given back: only the newest call survives', async () => {
const r = await connected(), slow = hold(r, 's1');
const b = r.c.start(); await flush(); // B ends A; A's DELETE is held
const c = r.c.start(); await flush(); // C does not wait behind B
r.transport.rooms.at(-1)!.on.agentJoined();
slow.open(); await Promise.all([b, c]); await flush(); // B wakes up late: it must not take over
const last = r.transport.rooms.length - 1;
expect(r.transport.rooms.filter(x => !x.closed)).toEqual([r.transport.rooms[last]]);
expect(r.transport.mics.filter(m => !m.stopped)).toEqual([r.transport.mics[last]]);
expect(r.server.open.size).toBe(1);
stillNew(r, last);
await r.c.end(); await flush();
expect(r.server.open.size).toBe(0);
expect(r.transport.mics.every(m => m.stopped)).toBe(true);
expect(r.transport.rooms.every(x => x.closed)).toBe(true);
});
it('a microphone granted late to an older start is stopped without touching the new call', async () => {
const r = rig(); r.transport.micGate = gate(); const late = r.transport.micGate;
const a = r.c.start(); await flush();
r.transport.micGate = undefined;
await reopened(r, 0);
late.open(); await a; await flush();
expect(r.transport.mics).toHaveLength(2);
expect(r.transport.mics[1].stopped).toBeGreaterThan(0); // A's late microphone
expect(r.transport.mics[0].stopped).toBe(0); // the live call's own
expect(r.c.active).toBe(true);
expect(r.view()).toMatchObject({ phase: 'listening', notice: '' });
expect(r.server.made).toBe(1);
await r.c.end();
});
});
describe('subtitles and the two channels', () => {
it('interim is a draft; user_final cancels a text reply and asks for the record; φ is heard but not recorded', async () => {
const r = await connected(), room = r.transport.rooms[0];