Files
CyberGril/web/tests/hel898_agent_left.test.ts
T

138 lines
10 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { livekitTransport, type Livekit } from '../src/voice/livekit';
import { VoiceController, WORDS, type MicTrack, type RoomEvents, type VoiceRoom, type VoiceView } from '../src/voice/session';
// HEL-898 (f92a86f review): her worker leaving a room that stays open. Driven through the real transport adapter
// (src/voice/livekit.ts) with a scripted client that uses the vendored livekit-client 2.22.4 event names
// (RoomEvent.ParticipantDisconnected = 'participantDisconnected', emitted as (participant, reason)); no WebRTC.
const RoomEvent = { TrackSubscribed: 'trackSubscribed', TrackUnsubscribed: 'trackUnsubscribed', ParticipantConnected: 'participantConnected', ParticipantDisconnected: 'participantDisconnected', ParticipantAttributesChanged: 'participantAttributesChanged', DataReceived: 'dataReceived', Disconnected: 'disconnected', AudioPlaybackStatusChanged: 'audioPlaybackChanged' };
const AGENT = 4;
interface P { identity: string; kind?: number; attributes?: Record<string, string> }
class FakeRoom {
handlers: Record<string, ((...a: unknown[]) => void)[]> = {}; remoteParticipants = new Map<string, P>(); canPlaybackAudio = true; disconnects = 0; published: unknown[] = [];
localParticipant = { publishTrack: async (t: unknown) => { this.published.push(t); } };
constructor() { rooms.push(this); }
on(e: string, cb: (...a: unknown[]) => void) { (this.handlers[e] ||= []).push(cb); return this; }
emit(e: string, ...a: unknown[]) { (this.handlers[e] || []).forEach(cb => cb(...a)); }
async connect() {}
async disconnect() { this.disconnects++; [...this.remoteParticipants.values()].forEach(p => this.leave(p.identity)); this.emit(RoomEvent.Disconnected); }
async startAudio() {}
enter(p: P) { this.remoteParticipants.set(p.identity, p); this.emit(RoomEvent.ParticipantConnected, p); }
// As the SDK does: the participant is removed from the map, then the event carries it and a reason.
leave(identity: string) { const p = this.remoteParticipants.get(identity); if (!p) return; this.remoteParticipants.delete(identity); this.emit(RoomEvent.ParticipantDisconnected, p, 1); }
say(frame: unknown) { this.emit(RoomEvent.DataReceived, new TextEncoder().encode(JSON.stringify(frame)), undefined, 0, 'cg.subtitle'); }
}
let rooms: FakeRoom[] = [], mics: { stopped: number }[] = [];
const lk = {
Room: FakeRoom, RoomEvent, Track: { Source: { Microphone: 'microphone' } }, ParticipantKind: { AGENT },
async createLocalAudioTrack() { const m = { stopped: 0 }; mics.push(m); const mst = { stop: () => { m.stopped++; }, addEventListener() {} }; return { kind: 'audio', mediaStreamTrack: mst, attach: () => ({}), detach: () => [], stop: () => {} }; },
} as unknown as Livekit;
const worker: P = { identity: 'agent-AJ_1', kind: AGENT, attributes: { 'lk.agent.state': 'listening' } };
// The adapter keeps her audio in a hidden holder element; a node test has no DOM, so the few calls it makes are stubbed.
beforeEach(() => {
rooms = []; mics = [];
const el = () => ({ hidden: false, dataset: {}, querySelectorAll: () => [], remove() {}, append() {} });
vi.stubGlobal('document', { createElement: el, body: { append() {} } });
});
afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); });
function rig(deleteStatus = 200) {
const calls: string[] = [], views: VoiceView[] = [], record = vi.fn();
let status = deleteStatus, made = 0;
const f = vi.fn(async (url: string, init: RequestInit = {}) => {
const method = init.method || 'GET'; calls.push(`${method} ${url}`);
if (url === '/api/voice/status') return new Response(JSON.stringify({ configured: true, tts_ok: true }));
if (url === '/api/voice/session' && method === 'POST') { const id = `s${++made}`; return new Response(JSON.stringify({ url: 'wss://lk.test', token: `t-${id}`, room: `cg-voice-${id}`, session_id: id, epoch: 3, expires_at: 0 }), { status: 201 }); }
if (method === 'DELETE') return new Response('{}', { status });
return new Response('{}', { status: 404 });
});
const c = new VoiceController({ transport: async () => livekitTransport(lk), onView: v => views.push(v), onRecord: record, onSpoke: () => {}, fetch: f as unknown as typeof fetch, secure: () => true, agentWaitMs: 60000 });
return { c, calls, views, view: () => views.at(-1)!, setDelete: (s: number) => { status = s; } };
}
const flush = async () => { for (let i = 0; i < 8; i++) await Promise.resolve(); await new Promise(r => setTimeout(r, 0)); };
const deletes = (calls: string[]) => calls.filter(c => c.startsWith('DELETE'));
describe('her worker leaves while the room stays open (real adapter, SDK event names)', () => {
it('ends the call honestly: her line, microphone, audio, room and server room all go at once', async () => {
const r = rig(); await r.c.start(); const room = rooms[0];
room.enter(worker);
room.say({ v: 2, seq: 1, kind: 'user_final', role: 'user', text: '你在听吗' });
room.say({ v: 2, seq: 2, kind: 'turn_start', role: 'assistant', text: '', speech_id: 'sp' });
room.say({ v: 2, seq: 3, kind: 'assistant_interim', role: 'assistant', text: '在听呢。', speech_id: 'sp' });
expect(r.view()).toMatchObject({ phase: 'thinking', her: { speech: 'sp', text: '在听呢。', state: 'open' } });
room.leave(worker.identity); await flush();
expect(r.view()).toEqual({ phase: 'off', heard: '', spoken: '', her: null, notice: WORDS.agentLeft, blocked: false });
expect(mics[0].stopped).toBeGreaterThan(0);
expect(room.disconnects).toBe(1);
expect(deletes(r.calls)).toEqual(['DELETE /api/voice/session/s1']);
// Nothing of that room is heard from again (its own Disconnected, late frames): one notice, one cleanup.
room.say({ v: 2, seq: 9, kind: 'assistant_final', role: 'assistant', text: '晚到。', speech_id: 'sp', turn_id: 'T' });
room.emit(RoomEvent.ParticipantDisconnected, worker, 1); await flush();
expect(r.views.filter(v => v.notice === WORDS.agentLeft)).toHaveLength(1);
expect(r.view().her).toBeNull();
expect(deletes(r.calls)).toHaveLength(1);
});
it('a DELETE that could not get through is owed and sent again, as any failure', async () => {
const r = rig(503); await r.c.start(); const room = rooms[0];
room.enter(worker); room.leave(worker.identity); await flush();
expect(r.view().notice).toBe(WORDS.agentLeft);
r.setDelete(404); await r.c.settle();
expect(deletes(r.calls)).toEqual(['DELETE /api/voice/session/s1', 'DELETE /api/voice/session/s1']);
});
it('anyone else leaving does not hang up; nor does a second worker leaving while hers stays', async () => {
const r = rig(); await r.c.start(); const room = rooms[0];
room.enter(worker); room.enter({ identity: 'guest-1', kind: 0, attributes: {} });
room.leave('guest-1'); await flush();
expect(r.view()).toMatchObject({ phase: 'listening', notice: '' });
room.enter({ identity: 'agent-AJ_2', kind: AGENT, attributes: {} }); room.leave('agent-AJ_2'); await flush();
expect(r.view()).toMatchObject({ phase: 'listening', notice: '' });
expect(deletes(r.calls)).toHaveLength(0);
await r.c.end();
});
it('your own hang-up says nothing more: the room closing takes her worker with it silently', async () => {
const r = rig(); await r.c.start(); const room = rooms[0];
room.enter(worker);
await r.c.end(); await flush();
expect(room.disconnects).toBe(1);
expect(r.views.some(v => v.notice)).toBe(false);
expect(deletes(r.calls)).toHaveLength(1);
});
it('an old room\'s worker leaving late never ends the new call', async () => {
const r = rig(); await r.c.start(); const first = rooms[0]; first.enter(worker);
await r.c.start(); const second = rooms[1]; second.enter({ ...worker, identity: 'agent-AJ_new' });
// The first room was closed by the restart; its handlers stay registered, and fire late.
first.emit(RoomEvent.ParticipantDisconnected, worker, 1); await flush();
expect(r.view()).toMatchObject({ phase: 'listening', notice: '' });
expect(deletes(r.calls)).toEqual(['DELETE /api/voice/session/s1']);
await r.c.end();
});
});
describe('controller: agentLeft only for this call, only once she was there', () => {
class Room implements VoiceRoom { closed = 0; on!: RoomEvents; async publish(_m: MicTrack) {} hush() {} async resumeAudio() {} async close() { this.closed++; } }
const make = () => {
const list: Room[] = [], views: VoiceView[] = [];
const transport = { capture: async () => ({ stop() {}, onEnded() {} }), join: async (_u: string, _t: string, on: RoomEvents) => { const x = new Room(); x.on = on; list.push(x); return x; } };
const f = vi.fn(async (url: string, init: RequestInit = {}) => url === '/api/voice/status' ? new Response('{"configured":true,"tts_ok":true}') : init.method === 'POST' ? new Response(JSON.stringify({ url: 'u', token: 't', room: 'r', session_id: `s${list.length + 1}`, epoch: 1, expires_at: 0 }), { status: 201 }) : new Response('{}'));
const c = new VoiceController({ transport: async () => transport, onView: v => views.push(v), onRecord: () => {}, onSpoke: () => {}, fetch: f as unknown as typeof fetch, secure: () => true, agentWaitMs: 60000 });
return { c, list, views, view: () => views.at(-1)! };
};
it('before her worker ever joined, a leave is not hers to report (the join wait says it honestly)', async () => {
const r = make(); await r.c.start();
r.list[0].on.agentLeft(); await flush();
expect(r.view()).toMatchObject({ phase: 'joining', notice: '' });
await r.c.end();
});
it('a stale call\'s agentLeft changes nothing in the new call', async () => {
const r = make(); await r.c.start(); r.list[0].on.agentJoined();
await r.c.end(); await r.c.start(); r.list[1].on.agentJoined();
r.list[0].on.agentLeft(); await flush();
expect(r.view()).toMatchObject({ phase: 'listening', notice: '' });
expect(r.list[1].closed).toBe(0);
r.list[1].on.agentLeft(); await flush();
expect(r.view()).toMatchObject({ phase: 'off', notice: WORDS.agentLeft });
expect(r.list[1].closed).toBe(1);
});
});