From 73fa93445c8cf9e45f7f87a0ab8418f2e0fa872d Mon Sep 17 00:00:00 2001 From: Phil Leggetter Date: Tue, 24 Nov 2026 16:24:59 +0000 Subject: [PATCH] fix(livekit): stop a late ingress_ended restarting the wrong scene, and close the room when the last player leaves Soundtrack race: ensure() deleted the old scene's ingress and then spent a few hundred ms creating the new one, and only set the wanted scene at the end. The ingress_ended webhook for the deleted ingress could arrive in that window, see the old scene as still wanted, and restart it, which deleted the new scene's ingress seconds after it started. ensure(), stop() and onEnded() now run one at a time per room, so a late webhook is judged against the scene the story is in. Room never finished: the story agent stays in the room after a player leaves (closeOnDisconnect is false) and the app keeps the soundtrack playing, so the room was never empty and LiveKit never sent room_finished. When the last human leaves, and nobody comes back within 10 s, the agent marks the story ended, asks the app to delete the soundtrack ingress, and leaves 10 s later (so a bot player sees the ended state and leaves too). Co-Authored-By: Claude Opus 5.5 --- .../voice-adventure/agent/src/empty-room.ts | 20 +++++ livekit/voice-adventure/agent/src/main.ts | 14 ++++ .../agent/test/empty-room.test.ts | 36 +++++++++ .../voice-adventure/src/soundtrack-keeper.ts | 74 +++++++++++-------- .../test/soundtrack-keeper.test.ts | 24 ++++++ 5 files changed, 137 insertions(+), 31 deletions(-) create mode 100644 livekit/voice-adventure/agent/src/empty-room.ts create mode 100644 livekit/voice-adventure/agent/test/empty-room.test.ts diff --git a/livekit/voice-adventure/agent/src/empty-room.ts b/livekit/voice-adventure/agent/src/empty-room.ts new file mode 100644 index 0000000..44ced1d --- /dev/null +++ b/livekit/voice-adventure/agent/src/empty-room.ts @@ -0,0 +1,20 @@ +/** + * Closes the story when the last human has left. The agent stays in the room on purpose (closeOnDisconnect is false, so a player + * who leaves doesn't end the story for the others), and the app keeps a soundtrack playing: both are participants, so LiveKit never + * sees an empty room and never sends room_finished. After a short grace period (a refreshed page rejoins within it) the watcher + * calls `onEmpty`, which stops the soundtrack and has the agent leave; LiveKit then closes the room after its departure timeout. + */ +export function createEmptyRoomWatcher(onEmpty: () => void, grace_ms = 10000, timers = { set: setTimeout, clear: clearTimeout }) { + let timer: ReturnType | undefined; + return { + /** Call whenever a participant connects or disconnects, with how many humans are in the room now. */ + update(humans_here: number): void { + if (humans_here > 0) { + if (timer) timers.clear(timer); + timer = undefined; + } else if (!timer) { + timer = timers.set(() => { timer = undefined; onEmpty(); }, grace_ms); + } + }, + }; +} diff --git a/livekit/voice-adventure/agent/src/main.ts b/livekit/voice-adventure/agent/src/main.ts index a6459be..2c8e675 100644 --- a/livekit/voice-adventure/agent/src/main.ts +++ b/livekit/voice-adventure/agent/src/main.ts @@ -26,6 +26,7 @@ import { botName, fetchLine, planLedger, shouldFetchBram } from './names.ts'; import { chooseGesture, respondLine } from './pixel-lines.ts'; import { addSummaryLine, buildState, decodeState, encodeState, recapInstructions, resumePlayers, shouldResume, type StoryState } from './resume.ts'; import { BREVITY, CLOSING_LINE, GOAL_LINE, bramInstructions, createEndWatcher, onBramReply, onPlayerInput, onPlayout, onSceneStart, speechFilter, createLlmWatchdog, createTurnRecovery, stallLine } from './story.ts'; +import { createEmptyRoomWatcher } from './empty-room.ts'; dotenv.config({ path: fileURLToPath(new URL('../../.env', import.meta.url)) }); @@ -464,6 +465,17 @@ export default defineAgent({ .catch(() => undefined) .finally(() => setTimeout(() => job_ctx.shutdown('the story is over'), 3000)); }); + // The last human left: the agent and the soundtrack are the only things keeping the room open, so stop the music and leave + // (after a few seconds, so a silent bot player sees the story has ended and leaves too). LiveKit then finishes the room. + const empty_room = createEmptyRoomWatcher(() => { + console.log(`the last player left at ${new Date().toISOString()}: stopping the soundtrack and leaving`); + session.userData.ending = true; + publish(job_ctx, { 'story.state': 'ended', 'story.turn': '', 'story.turn_name': '' }); + fetch(`${APP_URL}/api/scene/end`, { method: 'POST', headers: APP_HEADERS, body: JSON.stringify({ room: job_ctx.room.name }), signal: AbortSignal.timeout(10000) }) + .catch(() => undefined) + .finally(() => setTimeout(() => job_ctx.shutdown('everyone left'), 10000)); + }); + const humans_after = (leaving?: RemoteParticipant) => humans(job_ctx).filter((h) => h.identity !== leaving?.identity).length; session.on(voice.AgentSessionEventTypes.AgentStateChanged, (e: any) => session.userData.end_watcher?.onAgentState(e.oldState, e.newState)); // Who is still in the room: a player who left never gets the turn const here = (p: Player) => ctx.room.remoteParticipants.has(p.identity); @@ -543,6 +555,7 @@ export default defineAgent({ // and take them out of Bram's roster so he doesn't address them ctx.room.on('participantDisconnected', (p: RemoteParticipant) => { const data = session.userData; + if (!is_bot(p) && is_player(p)) empty_room.update(humans_after(p)); const had_turn = ctx.room.localParticipant?.attributes?.['story.turn'] === p.identity; if (listening_to(session) === p.identity || had_turn) { const next = data.players.find((x) => !x.bot && x.identity !== p.identity && here(x)) ?? humans(ctx)[0]; @@ -576,6 +589,7 @@ export default defineAgent({ // ledger, so without this it would never get a turn. Bram's roster is updated and he acknowledges the arrival once. ctx.room.on('participantConnected', (p: RemoteParticipant) => { const data = session.userData; + if (!is_bot(p) && is_player(p)) empty_room.update(humans_after()); if (!data.handed_off || !is_player(p) || data.players.some((x) => x.identity === p.identity)) return; const bot = is_bot(p); // A late joiner who gave no name still joins, as "Traveller": otherwise they would never be heard. They can say their name ("I'm Priya"). diff --git a/livekit/voice-adventure/agent/test/empty-room.test.ts b/livekit/voice-adventure/agent/test/empty-room.test.ts new file mode 100644 index 0000000..2388afd --- /dev/null +++ b/livekit/voice-adventure/agent/test/empty-room.test.ts @@ -0,0 +1,36 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createEmptyRoomWatcher } from '../src/empty-room.ts'; + +function fake() { + const pending = new Map void>(); + let n = 0; + return { + timers: { set: ((fn: () => void) => { pending.set(++n, fn); return n; }) as any, clear: ((id: number) => { pending.delete(id); }) as any }, + fire: () => { for (const [id, fn] of [...pending]) { pending.delete(id); fn(); } }, + pending, + }; +} + +test('the last human leaving ends the story once the grace period has passed', () => { + const f = fake(); + let ended = 0; + const watcher = createEmptyRoomWatcher(() => { ended += 1; }, 10000, f.timers); + watcher.update(1); + assert.equal(f.pending.size, 0); + watcher.update(0); + watcher.update(0); // a second event doesn't arm a second timer + assert.equal(f.pending.size, 1); + f.fire(); + assert.equal(ended, 1); +}); + +test('a human who comes back within the grace period cancels it', () => { + const f = fake(); + let ended = 0; + const watcher = createEmptyRoomWatcher(() => { ended += 1; }, 10000, f.timers); + watcher.update(0); + watcher.update(1); + f.fire(); + assert.equal(ended, 0); +}); diff --git a/livekit/voice-adventure/src/soundtrack-keeper.ts b/livekit/voice-adventure/src/soundtrack-keeper.ts index 20d219f..c4f9b48 100644 --- a/livekit/voice-adventure/src/soundtrack-keeper.ts +++ b/livekit/voice-adventure/src/soundtrack-keeper.ts @@ -32,41 +32,53 @@ export function createSoundtrackKeeper(deps: { ingresses: IngressApi; reachable: return ours.length; } + // One change at a time per room. A late ingress_ended webhook (for example the one for the scene ingress the last scene change + // deleted) must not run in the middle of a scene change: it would restart the old scene's soundtrack and delete the new one. + const queues = new Map>(); + function serial(room: string, work: () => Promise): Promise { + const run = (queues.get(room) ?? Promise.resolve()).then(work); + const tail = run.catch(() => undefined); + queues.set(room, tail); + tail.then(() => { if (queues.get(room) === tail) queues.delete(room); }); + return run; + } + + async function ensureNow(room: string, scene: SceneName): Promise { + const here = (await deps.ingresses.list(room)).filter((i) => i.name.startsWith('scene:')); + const playing = here.find((i) => i.name === `scene:${scene}` && isPlaying(i)); + if (playing) { + wanted.set(room, { scene, since: wanted.get(room)?.scene === scene ? wanted.get(room)!.since : now() }); + return { ok: true, kept: true, ingress_id: playing.ingressId }; + } + // One soundtrack at a time: the previous scene's stops before the next starts + await removeScenes(room); + const url = url_of(scene); + if (!(await deps.reachable(url))) { + wanted.delete(room); + return { ok: false, reason: `the soundtrack at ${url} can't be fetched` }; + } + const ingress = await deps.ingresses.create({ name: `scene:${scene}`, room, identity: `soundtrack-${scene}`, participant_name: `Soundtrack: ${scene}`, url }); + wanted.set(room, { scene, since: now() }); + return { ok: true, ingress_id: ingress.ingressId }; + } + return { wanted, /** Makes sure `scene`'s soundtrack is playing in `room`: kept if it already is, otherwise the room's scene ingresses are replaced by a fresh one. */ - async ensure(room: string, scene: SceneName): Promise { - const here = (await deps.ingresses.list(room)).filter((i) => i.name.startsWith('scene:')); - const playing = here.find((i) => i.name === `scene:${scene}` && isPlaying(i)); - if (playing) { - wanted.set(room, { scene, since: wanted.get(room)?.scene === scene ? wanted.get(room)!.since : now() }); - return { ok: true, kept: true, ingress_id: playing.ingressId }; - } - // One soundtrack at a time: the previous scene's stops before the next starts - await removeScenes(room); - const url = url_of(scene); - if (!(await deps.reachable(url))) { - wanted.delete(room); - return { ok: false, reason: `the soundtrack at ${url} can't be fetched` }; - } - const ingress = await deps.ingresses.create({ name: `scene:${scene}`, room, identity: `soundtrack-${scene}`, participant_name: `Soundtrack: ${scene}`, url }); - wanted.set(room, { scene, since: now() }); - return { ok: true, ingress_id: ingress.ingressId }; - }, + ensure: (room: string, scene: SceneName): Promise => serial(room, () => ensureNow(room, scene)), /** The story ended or the room finished: delete the room's soundtracks and stop wanting one. Returns how many were deleted. */ - async stop(room: string): Promise { - wanted.delete(room); - return removeScenes(room); - }, + stop: (room: string): Promise => serial(room, async () => { wanted.delete(room); return removeScenes(room); }), /** An `ingress_ended` webhook for a scene ingress: start the same soundtrack again if the room is still in that scene. */ - async onEnded(room: string, ingress_name: string): Promise<'restarted' | 'ignored'> { - const scene = ingress_name.replace(/^scene:/, ''); - const want = wanted.get(room); - if (!isScene(scene) || !want || want.scene !== scene) return 'ignored'; - if (now() - want.since < MIN_PLAY_MS) return 'ignored'; - if (!(await deps.room_open(room))) { wanted.delete(room); return 'ignored'; } - const result = await this.ensure(room, scene); - return result.ok && !result.kept ? 'restarted' : 'ignored'; - }, + onEnded: (room: string, ingress_name: string): Promise<'restarted' | 'ignored'> => + // Decided inside the queue: when a late webhook gets its turn, the wanted scene is already the new one + serial(room, async () => { + const scene = ingress_name.replace(/^scene:/, ''); + const want = wanted.get(room); + if (!isScene(scene) || !want || want.scene !== scene) return 'ignored'; + if (now() - want.since < MIN_PLAY_MS) return 'ignored'; + if (!(await deps.room_open(room))) { wanted.delete(room); return 'ignored'; } + const result = await ensureNow(room, scene); + return result.ok && !result.kept ? 'restarted' : 'ignored'; + }), }; } diff --git a/livekit/voice-adventure/test/soundtrack-keeper.test.ts b/livekit/voice-adventure/test/soundtrack-keeper.test.ts index 15626e8..faa235c 100644 --- a/livekit/voice-adventure/test/soundtrack-keeper.test.ts +++ b/livekit/voice-adventure/test/soundtrack-keeper.test.ts @@ -76,3 +76,27 @@ test('the reachability check is a HEAD request, falls back to a ranged GET, and assert.equal(await soundtrackReachable('https://x.test/a.ogg', (async (_u: any, init: any) => new Response(null, { status: init?.method === 'HEAD' ? 405 : 206 })) as any), true); assert.deepEqual(seen, ['HEAD:200', 'HEAD:404']); }); + +test('a late ingress_ended for the scene just replaced does not restart it or delete the new scene', async () => { + const store: IngressLike[] = []; + const calls: string[] = []; + let n = 0; + let clock = 1000; + const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + const ingresses: IngressApi = { + async list(room) { return store.filter((i) => i.roomName === room); }, + async create(o) { await sleep(30); calls.push(`create ${o.name}`); const i = { ingressId: `IN_${++n}`, name: o.name, roomName: o.room, state: { status: 2 } }; store.push(i); return i; }, + async remove(id) { calls.push(`remove ${id}`); store.splice(store.findIndex((i) => i.ingressId === id), 1); }, + }; + const keeper = createSoundtrackKeeper({ ingresses, reachable: async () => true, room_open: async () => true, url_of: (s) => `https://x.test/${s}.ogg`, now: () => clock }); + await keeper.ensure('story-aaaaaa', 'tavern'); + clock += 69000; + // The scene changes; the webhook for the deleted tavern ingress arrives while the forest ingress is still being created + const change = keeper.ensure('story-aaaaaa', 'forest'); + await sleep(10); + const late = keeper.onEnded('story-aaaaaa', 'scene:tavern'); + assert.equal(await late, 'ignored'); + assert.equal((await change).ok, true); + assert.deepEqual(calls, ['create scene:tavern', 'remove IN_1', 'create scene:forest']); + assert.deepEqual(store.map((i) => i.name), ['scene:forest']); +});