Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: stop a FableLoom hosted turn from emitting after its session ends (#5786)
Adam Eivy1a4d7b877cc9
diff --git a/server/services/fableLoom/hostedSession.js b/server/services/fableLoom/hostedSession.jsindex 23c27a56d8..c4384ce3ec 100644--- a/server/services/fableLoom/hostedSession.js+++ b/server/services/fableLoom/hostedSession.js@@ -497,40 +497,57 @@ export async function processHostedUtterance(sessionId, {session.activeTurn = turn;session.turnPhase = 'thinking';- if (io) {- io.of('/fableloom-hosted').to(`session:${sessionId}`).emit('hosted:turn:phase', {- phase: 'thinking',- turnId: turn.id,- });- }+ // This function holds `session` and `turn` across every provider await, but a+ // teardown landing mid-turn (host "end", DELETE /sessions/:id, or the TTL+ // sweep) aborts the controller, clears `activeTurn` and drops the map entry.+ // Re-derive liveness at each boundary so no provider work starts — and no+ // frame is emitted — after the terminal `hosted:session:ended` (#5786).+ const isLive = () => !turn.abortController.signal.aborted+ && activeSessions.get(sessionId) === session+ && session.status === 'active'+ && session.activeTurn === turn;++ const emitIfLive = (event, payload) => {+ if (io && isLive()) io.of('/fableloom-hosted').to(`session:${sessionId}`).emit(event, payload);+ };++ const abandonedResult = { ok: true, aborted: true, turnId: turn.id };+ const abandonTurn = (stage) => {+ console.log(`🛑 Hosted turn ${turn.id} abandoned during ${stage} — session no longer live`);+ return abandonedResult;+ };++ emitIfLive('hosted:turn:phase', { phase: 'thinking', turnId: turn.id });try {let message = (textMessage || '').trim();// 1. Transcribe audio if supplied- if (audioBuffer && (!message || !message.length)) {+ if (audioBuffer && !message) {let wavPayload = audioBuffer;if (audioBuffer instanceof Int16Array || (ArrayBuffer.isView(audioBuffer) && !(audioBuffer instanceof Buffer))) {const floatPcm = pcmToFloat(audioBuffer);wavPayload = pcmToWavBuffer(floatPcm, { sampleRate: 16000 });}const sttResult = await transcribe(wavPayload, { signal: turn.abortController.signal }).catch((err) => {+ // A torn-down turn aborts this signal. That is a cancellation, not a+ // successful empty transcription, and must not fall through as one.+ if (turn.abortController.signal.aborted) return null;console.warn(`[HostedPlay] STT transcription failed: ${err.message}`);return { text: '' };});+ if (!sttResult || !isLive()) return abandonTurn('transcription');message = (sttResult.text || '').trim();}// Check for echo / empty messageif (!message || isEchoOfRecentTts(message, session.recentTts)) {session.turnPhase = 'listening';- if (io) {- io.of('/fableloom-hosted').to(`session:${sessionId}`).emit('hosted:turn:phase', {- phase: 'listening',- turnId: turn.id,- note: 'ignored-echo-or-empty',- });- }+ emitIfLive('hosted:turn:phase', {+ phase: 'listening',+ turnId: turn.id,+ note: 'ignored-echo-or-empty',+ });return { ok: true, ignored: true };}@@ -544,12 +561,11 @@ export async function processHostedUtterance(sessionId, {session.transcript.push(audienceItem);if (session.transcript.length > 50) session.transcript.shift();- if (io) {- io.of('/fableloom-hosted').to(`session:${sessionId}`).emit('hosted:turn:transcript', audienceItem);- }+ emitIfLive('hosted:turn:transcript', audienceItem);// 2. Run LLM Play Turnconst loom = await getLoom(session.loomId);+ if (!isLive()) return abandonTurn('loom load');const episode = loom.episodes?.find((e) => e.id === session.episodeId) || null;const node = episode?.nodes?.find((n) => n.id === session.currentNodeId) || null;@@ -558,12 +574,16 @@ export async function processHostedUtterance(sessionId, {playResult = await playTurn(session.loomId, session.episodeId, {nodeId: session.currentNodeId,message,+ signal: turn.abortController.signal,transcript: session.transcript.map((t) => ({role: t.role === 'audience' ? 'reader' : 'narrator',text: t.text,})),});} catch (err) {+ // A cancelled turn has no one left to narrate to — the authored fallback+ // would only produce a reply for a room that already saw `ended`.+ if (!isLive()) return abandonTurn('story turn');console.warn(`[HostedPlay] LLM turn error, using authored fallback: ${err?.message}`);playResult = {action: 'stay',@@ -572,6 +592,7 @@ export async function processHostedUtterance(sessionId, {ended: false,};}+ if (!isLive()) return abandonTurn('story turn');const narration = (playResult?.narration || '').trim() || "Let's continue.";@@ -590,14 +611,8 @@ export async function processHostedUtterance(sessionId, {session.turnPhase = 'speaking';rememberTtsSentence(session.recentTts, narration);- if (io) {- io.of('/fableloom-hosted').to(`session:${sessionId}`).emit('hosted:turn:phase', {- phase: 'speaking',- turnId: turn.id,- text: narration,- });- io.of('/fableloom-hosted').to(`session:${sessionId}`).emit('hosted:turn:transcript', protagonistItem);- }+ emitIfLive('hosted:turn:phase', { phase: 'speaking', turnId: turn.id, text: narration });+ emitIfLive('hosted:turn:transcript', protagonistItem);// Resolve character voicelet ttsAudio = null;@@ -613,14 +628,17 @@ export async function processHostedUtterance(sessionId, {characterVoiceId: char?.voiceId,route: 'interactive',}).catch(() => null);+ if (!isLive()) return abandonTurn('voice resolution');const { engine, voice } = parseVoiceId(resolved?.voiceId);const synth = await synthesize(narration, {engine: engine || undefined,profileId: resolved?.profileId || undefined,route: 'interactive',+ signal: turn.abortController.signal,voice: voice || undefined,}).catch((err) => {+ if (turn.abortController.signal.aborted) return null;console.warn(`[HostedPlay] Protagonist TTS synthesis failed: ${err.message}`);return null;});@@ -630,10 +648,11 @@ export async function processHostedUtterance(sessionId, {} catch (err) {console.warn(`[HostedPlay] Protagonist TTS synthesis failed: ${err.message}`);}+ if (!isLive()) return abandonTurn('speech synthesis');// 4. Dispatch Audio to designated Audio Target- if (io && ttsAudio) {- io.of('/fableloom-hosted').to(`session:${sessionId}`).emit('hosted:turn:tts', {+ if (ttsAudio) {+ emitIfLive('hosted:turn:tts', {audio: Buffer.isBuffer(ttsAudio) ? ttsAudio.toString('base64') : Buffer.from(ttsAudio).toString('base64'),mimeType: 'audio/wav',target: session.audioTarget,@@ -650,36 +669,36 @@ export async function processHostedUtterance(sessionId, {session.activeHoldIndex = 0;session.turnPhase = 'idle';- if (io) {- io.of('/fableloom-hosted').to(`session:${sessionId}`).emit('hosted:story:transition', {- node: publicNode(targetNode, loom),- transitionId: playResult.transitionId,- playbackPhase: session.playbackPhase,- });- }+ emitIfLive('hosted:story:transition', {+ node: publicNode(targetNode, loom),+ transitionId: playResult.transitionId,+ playbackPhase: session.playbackPhase,+ });}} else {// Stay on current nodesession.turnPhase = 'listening';- if (io) {- io.of('/fableloom-hosted').to(`session:${sessionId}`).emit('hosted:turn:phase', {- phase: 'listening',- turnId: turn.id,- });- }+ emitIfLive('hosted:turn:phase', { phase: 'listening', turnId: turn.id });}session.activeTurn = null;return { ok: true, playResult };} catch (err) {+ // A failure that lands after teardown has no room left to tell: the session+ // already emitted its terminal frame, so log and swallow rather than+ // emitting `hosted:error` behind it.+ if (!isLive()) {+ console.warn(`[HostedPlay] Hosted turn ${turn.id} failed after teardown: ${err?.message || err}`);+ return abandonedResult;+ }+ // Emit BEFORE clearing `activeTurn` — clearing it first makes the turn+ // non-live and would suppress the very error frame the client needs.+ emitIfLive('hosted:error', {+ code: err?.code || 'TURN_FAILED',+ message: err?.message || String(err),+ });session.turnPhase = 'idle';session.activeTurn = null;- if (io) {- io.of('/fableloom-hosted').to(`session:${sessionId}`).emit('hosted:error', {- code: err?.code || 'TURN_FAILED',- message: err?.message || String(err),- });- }throw err;}}diff --git a/server/services/fableLoom/hostedSession.test.js b/server/services/fableLoom/hostedSession.test.jsindex 2f5784a3ac..885fc2e6c1 100644--- a/server/services/fableLoom/hostedSession.test.js+++ b/server/services/fableLoom/hostedSession.test.js@@ -84,6 +84,27 @@ describe('fableLoom hostedSession', () => {httpsEnabled: false,});+ // A stub Socket.IO surface that records every namespace emit.+ const makeIo = () => {+ const emits = [];+ return {+ emits,+ of: () => ({+ to: (room) => ({+ emit: (event, payload) => emits.push({ room, event, payload }),+ }),+ }),+ };+ };++ // A promise the test resolves by hand, so one provider stage can be held+ // pending across a teardown without any real timing.+ const deferred = () => {+ let settle;+ const promise = new Promise((resolve, reject) => { settle = { resolve, reject }; });+ return { promise, ...settle };+ };+beforeEach(() => {_resetHostedSessions();vi.restoreAllMocks();@@ -281,6 +302,7 @@ describe('fableLoom hostedSession', () => {engine: 'qwen3-tts',profileId: 'voice-profile-1',route: 'interactive',+ signal: expect.any(AbortSignal),voice: 'character-1',});});@@ -311,6 +333,7 @@ describe('fableLoom hostedSession', () => {engine: 'kokoro',profileId: undefined,route: 'interactive',+ signal: expect.any(AbortSignal),voice: 'af_heart',});});@@ -343,22 +366,72 @@ describe('fableLoom hostedSession', () => {endHostedSession(session.id, { reason: 'user_ended' });expect(getHostedSession(session.id)).toBeNull();});++ // #5786: the turn holds `session`/`turn` across every provider await, so a+ // teardown landing mid-flight used to let the LLM and TTS run to completion+ // and emit turn frames AFTER the room's terminal `hosted:session:ended`.+ it('abandons a turn whose session is torn down mid story turn, emitting nothing after ended', async () => {+ const io = makeIo();+ const { session } = await createHostedSession('loom-1', 'ep-1');+ await startHostedListening(session.id, { io });++ const storyTurn = deferred();+ vi.spyOn(weave, 'playTurn').mockImplementation(() => storyTurn.promise);++ const pending = processHostedUtterance(session.id, {+ textMessage: 'What is behind the trees?',+ io,+ });+ await vi.waitFor(() => expect(weave.playTurn).toHaveBeenCalled());++ endHostedSession(session.id, { reason: 'user_ended', io });+ storyTurn.resolve({+ action: 'move',+ transitionId: 'tr-1',+ narration: 'We shall enter the dark woods together.',+ node: { id: 'node-2', title: 'Deep Woods' },+ });++ await expect(pending).resolves.toMatchObject({ aborted: true });+ // The provider work downstream of the abandoned stage never ran…+ expect(tts.synthesize).not.toHaveBeenCalled();+ // …and `hosted:session:ended` is the last thing the room ever saw.+ expect(io.emits.at(-1).event).toBe('hosted:session:ended');+ });++ it('treats an aborted transcription as a cancellation, not an empty utterance', async () => {+ const io = makeIo();+ const { session } = await createHostedSession('loom-1', 'ep-1');+ await startHostedListening(session.id, { io });++ const transcription = deferred();+ stt.transcribe.mockImplementation((_audio, opts) => {+ opts.signal.addEventListener('abort', () => transcription.reject(new Error('transcribe aborted')));+ return transcription.promise;+ });+ vi.spyOn(weave, 'playTurn').mockResolvedValue({+ action: 'stay',+ narration: 'Still here.',+ node: { id: 'node-start' },+ });++ const pending = processHostedUtterance(session.id, {+ audioBuffer: Buffer.from('fake-audio-bytes'),+ io,+ });+ await vi.waitFor(() => expect(stt.transcribe).toHaveBeenCalled());++ endHostedSession(session.id, { reason: 'expired', io });++ await expect(pending).resolves.toMatchObject({ aborted: true });+ // An abort used to fall through the STT catch as `{ text: '' }`, which+ // reads as a successfully-empty utterance rather than a cancellation.+ expect(weave.playTurn).not.toHaveBeenCalled();+ expect(io.emits.at(-1).event).toBe('hosted:session:ended');+ });});describe('expired-session sweep', () => {- // A stub Socket.IO surface that records every namespace emit.- const makeIo = () => {- const emits = [];- return {- emits,- of: () => ({- to: (room) => ({- emit: (event, payload) => emits.push({ room, event, payload }),- }),- }),- };- };-// Age a session past its TTL without waiting out 30 real minutes.const expire = (sessionId) => {const internal = _getInternalSession(sessionId);diff --git a/server/services/fableLoom/weave.js b/server/services/fableLoom/weave.jsindex 0fe2d68bac..08f7738b08 100644--- a/server/services/fableLoom/weave.js+++ b/server/services/fableLoom/weave.js@@ -1150,9 +1150,15 @@ const transcriptDigest = (transcript) =>* (`transitionId`), there is no intent to map, so the move resolves straight* off the graph — no provider call, no latency, no spend. Free text goes* through the play stage, which either matches a path or answers in-world.+ *+ * `signal` lets a caller whose turn can be torn down mid-flight (the hosted QR+ * session, #5786) stop the turn from SPENDING on a reader nobody is listening+ * to any more. The stage runner has no mid-call cancellation, so this is a+ * boundary guard, not a mid-flight abort: the record load above is a real await,+ * and an abort landing inside it means the provider call is never made.*/export async function playTurn(loomId, episodeId, {- nodeId, message, transitionId, transcript = [], providerId, model, effort,+ nodeId, message, transitionId, transcript = [], providerId, model, effort, signal,} = {}) {const loom = await requireLoom(loomId);const episode = findEpisode(loom, episodeId);@@ -1190,6 +1196,13 @@ export async function playTurn(loomId, episodeId, {t.description ? ` leads to: ${t.description}` : null,].filter(Boolean).join('\n')).join('\n');+ if (signal?.aborted) {+ throw new ServerError('Play turn was cancelled before the provider call', {+ status: 499,+ code: 'TURN_ABORTED',+ });+ }+const { content, runId } = await runStagedLLM('fableloom-play-turn', {storyContext: storyContext(loom, episode),sceneProse: node.prose || node.title || '',