Skip to content

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

fix: re-bind hosted FableLoom sessions when the host advances episodes (#8112)

[._.]/ Adam Eivy1b3afa7de610
diff --git a/client/src/components/fableloom/LoomPlayPanel.jsx b/client/src/components/fableloom/LoomPlayPanel.jsx
index f63ad818b4..c000470692 100644
--- a/client/src/components/fableloom/LoomPlayPanel.jsx
+++ b/client/src/components/fableloom/LoomPlayPanel.jsx
@@ -20,6 +20,7 @@ import MediaImage from '../MediaImage';
import { useAsyncAction } from '../../hooks/useAsyncAction';
import { playLoomTurn } from '../../services/api';
import { sceneProseClass } from './fieldStyles';
+import toast from '../ui/Toast';
import LoomHostedSessionModal from './LoomHostedSessionModal';
import { audienceCanParticipate } from '../../../../server/lib/fableLoomParticipation.js';
import {
@@ -110,6 +111,14 @@ export default function LoomPlayPanel({ loom, episode: initialEpisode, onClose }
const hostAudioPlayerRef = useRef(null);
const scrollRef = useRef(null);
const hostedSocketRef = useRef(null);
+ // The episode id the server-side hosted session is currently bound to —
+ // null while no session is active, otherwise re-armed to the current
+ // episode the moment a session connects (it was created for THAT episode).
+ const hostedEpisodeIdRef = useRef(null);
+ // Names the episode a pending `hosted:episode:switch` targeted, so a
+ // resulting `hosted:session:ended{reason:'episode_not_ready'}` can name it
+ // in the toast even though the server payload carries only the reason.
+ const pendingHostedEpisodeSwitchRef = useRef(null);
// Socket connection when hosted session is active
useEffect(() => {
@@ -151,10 +160,15 @@ export default function LoomPlayPanel({ loom, episode: initialEpisode, onClose }
}
});
- socket.on('hosted:session:ended', () => {
+ socket.on('hosted:session:ended', (data) => {
setHostedSession(null);
setHostedAudienceConnected(false);
setHostedTurnPhase('idle');
+ if (data?.reason === 'episode_not_ready') {
+ const label = pendingHostedEpisodeSwitchRef.current?.label || 'The next episode';
+ toast.error(`Hosted session ended — ${label} isn't ready for hosted play.`);
+ }
+ pendingHostedEpisodeSwitchRef.current = null;
});
return () => {
@@ -163,6 +177,34 @@ export default function LoomPlayPanel({ loom, episode: initialEpisode, onClose }
};
}, [hostedSession?.id, hostedSession?.token]);
+ // Re-bind the server-side hosted session when the host advances to a
+ // different episode (e.g. the "Next: Episode N" button). Without this the
+ // server keeps resolving audience turns against the OLD episode's graph —
+ // `findNode` throws, and every turn silently falls back to canned
+ // narration while the UI still claims the session is connected (#8112).
+ // Runs in the commit BEFORE the scene/playback-sync effect below re-points
+ // `scene` at the new episode's opening node, so the switch always reaches
+ // the server ahead of the first `hosted:playback:update` for that node.
+ useEffect(() => {
+ if (!hostedSession?.id) {
+ hostedEpisodeIdRef.current = null;
+ return;
+ }
+ if (hostedEpisodeIdRef.current === null) {
+ // A session that just connected/was created is already bound to the
+ // episode that was active when it was created — nothing to switch.
+ hostedEpisodeIdRef.current = episode.id;
+ return;
+ }
+ if (hostedEpisodeIdRef.current === episode.id) return;
+ hostedEpisodeIdRef.current = episode.id;
+ pendingHostedEpisodeSwitchRef.current = {
+ id: episode.id,
+ label: `Episode ${episode.number || episodeIndex + 1}`,
+ };
+ hostedSocketRef.current?.emit('hosted:episode:switch', { episodeId: episode.id });
+ }, [episode.id, episode.number, episodeIndex, hostedSession?.id]);
+
// Sync playback phase & scene updates to hosted audience
useEffect(() => {
if (hostedSocketRef.current && hostedSession?.id && scene?.id) {
diff --git a/client/src/components/fableloom/LoomPlayPanel.test.jsx b/client/src/components/fableloom/LoomPlayPanel.test.jsx
index 23d7de964a..a8823c6a0e 100644
--- a/client/src/components/fableloom/LoomPlayPanel.test.jsx
+++ b/client/src/components/fableloom/LoomPlayPanel.test.jsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
vi.mock('../../services/api', () => ({ playLoomTurn: vi.fn() }));
@@ -16,9 +16,11 @@ vi.mock('./LoomHostedSessionModal', () => ({
</button>
),
}));
+vi.mock('../ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));
import { playLoomTurn } from '../../services/api';
import { io } from 'socket.io-client';
+import toast from '../ui/Toast';
import LoomPlayPanel from './LoomPlayPanel';
const loom = { id: 'loom-1', name: 'The Hollow Crown', episodes: [] };
@@ -387,6 +389,68 @@ describe('LoomPlayPanel', () => {
expect(screen.queryByText('Episode one ends.')).not.toBeInTheDocument();
});
+ // #8112: without this, the server-side hosted session keeps resolving
+ // audience turns against episode 1's graph after the host advances — every
+ // turn throws "Scene not found" and silently falls back to canned
+ // narration while the UI still claims the session is connected.
+ it('re-binds the hosted session before syncing playback when advancing episodes during a hosted session', async () => {
+ const user = userEvent.setup();
+ const first = {
+ id: 'ep-1', number: 1, title: 'One', startNodeId: 'end-1',
+ nodes: [{ id: 'end-1', title: 'First ending', prose: 'Episode one ends.', isEnding: true, transitions: [] }],
+ };
+ const second = {
+ id: 'ep-2', number: 2, title: 'Two', startNodeId: 'start-2',
+ nodes: [{ id: 'start-2', title: 'Second opening', prose: 'Episode two begins.', transitions: [] }],
+ };
+ render(<LoomPlayPanel loom={{ ...loom, episodes: [first, second] }} episode={first} />);
+
+ await user.click(screen.getByRole('button', { name: 'Host (QR)' }));
+ await user.click(screen.getByRole('button', { name: 'Start hosted session' }));
+
+ const hostedSocket = io.mock.results.at(-1).value;
+ hostedSocket.emit.mockClear();
+
+ await user.click(screen.getByRole('button', { name: 'Next: Episode 2' }));
+
+ await waitFor(() => expect(hostedSocket.emit).toHaveBeenCalledWith(
+ 'hosted:episode:switch', { episodeId: 'ep-2' },
+ ));
+
+ const calls = hostedSocket.emit.mock.calls;
+ const switchIndex = calls.findIndex(([event]) => event === 'hosted:episode:switch');
+ const playbackIndex = calls.findIndex(
+ ([event, payload]) => event === 'hosted:playback:update' && payload?.nodeId === 'start-2',
+ );
+ expect(switchIndex).toBeGreaterThanOrEqual(0);
+ expect(playbackIndex).toBeGreaterThan(switchIndex);
+ });
+
+ it('clears the hosted session and toasts naming the episode when the switch target fails preflight', async () => {
+ const user = userEvent.setup();
+ const first = {
+ id: 'ep-1', number: 1, title: 'One', startNodeId: 'end-1',
+ nodes: [{ id: 'end-1', title: 'First ending', prose: 'Episode one ends.', isEnding: true, transitions: [] }],
+ };
+ const second = {
+ id: 'ep-2', number: 2, title: 'Two', startNodeId: 'start-2',
+ nodes: [{ id: 'start-2', title: 'Second opening', prose: 'Episode two begins.', transitions: [] }],
+ };
+ render(<LoomPlayPanel loom={{ ...loom, episodes: [first, second] }} episode={first} />);
+
+ await user.click(screen.getByRole('button', { name: 'Host (QR)' }));
+ await user.click(screen.getByRole('button', { name: 'Start hosted session' }));
+
+ await user.click(screen.getByRole('button', { name: 'Next: Episode 2' }));
+
+ const hostedSocket = io.mock.results.at(-1).value;
+ const endedHandler = hostedSocket.on.mock.calls.find(([event]) => event === 'hosted:session:ended')?.[1];
+ act(() => { endedHandler({ sessionId: 'host-session', reason: 'episode_not_ready' }); });
+
+ expect(await screen.findByRole('button', { name: 'Host (QR)' })).toBeInTheDocument();
+ expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('Episode 2'));
+ });
+
it('shows an authored overnight voicemail at an episode boundary', async () => {
const first = {
id: 'ep-1', number: 1, title: 'One', startNodeId: 'end-1',
diff --git a/server/routes/fableLoom.js b/server/routes/fableLoom.js
index 7ef1a67879..203e558bb0 100644
--- a/server/routes/fableLoom.js
+++ b/server/routes/fableLoom.js
@@ -400,7 +400,7 @@ router.get('/sessions/:sessionId', asyncHandler(async (req, res) => {
router.patch('/sessions/:sessionId', asyncHandler(async (req, res) => {
const patch = validateRequest(hostedSessionPatchSchema, req.body);
- res.json(updateHostedSession(req.params.sessionId, patch));
+ res.json(await updateHostedSession(req.params.sessionId, patch));
}));
router.delete('/sessions/:sessionId', asyncHandler(async (req, res) => {
diff --git a/server/services/fableLoom/hostedSession.js b/server/services/fableLoom/hostedSession.js
index c4384ce3ec..847cf7c94c 100644
--- a/server/services/fableLoom/hostedSession.js
+++ b/server/services/fableLoom/hostedSession.js
@@ -376,8 +376,18 @@ export function _getInternalSession(sessionId) {
/**
* Update hosted session state (e.g. audio target, playback phase, current node).
+ *
+ * `currentNodeId` is validated against the session's CURRENT `episodeId` (only
+ * when it actually changes — a phase/hold-index-only update skips the lookup).
+ * Without this, a client that drifted from the server's episode (the host
+ * advanced an episode without the server learning about it, #8112) would push
+ * a node id that belongs to a different episode's graph; the audience's next
+ * turn then resolves `findNode` against the WRONG episode, throws "Scene not
+ * found", and silently falls back to canned narration with no visible error.
+ * Rejecting here fails loudly instead, so a future client bug can't degrade
+ * the same way in silence.
*/
-export function updateHostedSession(sessionId, patch = {}, { io } = {}) {
+export async function updateHostedSession(sessionId, patch = {}, { io } = {}) {
const session = activeSessions.get(sessionId);
if (!session || session.status !== 'active') {
throw new ServerError('Hosted session not found or ended', { status: 404, code: 'SESSION_NOT_FOUND' });
@@ -386,7 +396,16 @@ export function updateHostedSession(sessionId, patch = {}, { io } = {}) {
if (patch.audioTarget && FABLELOOM_AUDIO_TARGETS.includes(patch.audioTarget)) {
session.audioTarget = patch.audioTarget;
}
- if (patch.currentNodeId) {
+ if (patch.currentNodeId && patch.currentNodeId !== session.currentNodeId) {
+ const loom = await getLoom(session.loomId);
+ const episode = loom?.episodes?.find((e) => e.id === session.episodeId) || null;
+ const nodeBelongsToEpisode = !!episode?.nodes?.some((n) => n.id === patch.currentNodeId);
+ if (!nodeBelongsToEpisode) {
+ throw new ServerError('currentNodeId does not belong to the hosted session\'s current episode', {
+ status: 400,
+ code: 'NODE_NOT_IN_EPISODE',
+ });
+ }
session.currentNodeId = patch.currentNodeId;
}
if (patch.playbackPhase) {
@@ -403,6 +422,66 @@ export function updateHostedSession(sessionId, patch = {}, { io } = {}) {
return sanitized;
}
+/**
+ * Re-bind a hosted session to a different episode of the same loom, so the
+ * audience's phone stays connected across an episode transition instead of
+ * being silently stranded on the old episode's graph (#8112).
+ *
+ * Aborts any in-flight turn against the OLD episode first (a turn that
+ * resolves mid-switch must not land narration/a transition against the new
+ * one), re-runs the same readiness preflight `createHostedSession` requires,
+ * and — on failure — ends the session outright via `endHostedSession` rather
+ * than leaving it half-bound to an episode that can't play. Resets
+ * `currentNodeId` to the new episode's opening node and clears the
+ * transcript/turnPhase so the audience view starts clean.
+ */
+export async function switchHostedEpisode(sessionId, episodeId, { io } = {}) {
+ const session = activeSessions.get(sessionId);
+ if (!session || session.status !== 'active') {
+ throw new ServerError('Hosted session not found or ended', { status: 404, code: 'SESSION_NOT_FOUND' });
+ }
+
+ const loom = await getLoom(session.loomId);
+ if (!loom) {
+ throw new ServerError('Loom not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ const episode = findEpisode(loom, episodeId);
+
+ if (session.activeTurn?.abortController) {
+ session.activeTurn.abortController.abort('episode_switch');
+ session.activeTurn = null;
+ }
+
+ const preflight = await checkHostedSessionReadiness({ loomId: session.loomId, episodeId, loom, episode });
+ const startNode = preflight.ready
+ ? episode.nodes?.find((n) => n.id === episode.startNodeId) || null
+ : null;
+ if (!preflight.ready || !startNode) {
+ endHostedSession(sessionId, { reason: 'episode_not_ready', io });
+ return { ok: false, ended: true, reason: 'episode_not_ready', preflight };
+ }
+
+ const now = new Date();
+ session.episodeId = episodeId;
+ session.currentNodeId = startNode.id;
+ session.playbackPhase = initialPhaseForNode(startNode);
+ session.activeHoldIndex = 0;
+ session.turnPhase = 'idle';
+ session.transcript = [{
+ id: randomUUID(),
+ role: 'narrator',
+ text: startNode.prose || startNode.title || '',
+ timestamp: now.toISOString(),
+ }];
+ session.recentTts = [];
+
+ const sanitized = sanitizeHostedSession(session);
+ if (io) {
+ io.of('/fableloom-hosted').to(`session:${sessionId}`).emit('hosted:session:sync', sanitized);
+ }
+ return { ok: true, session: sanitized };
+}
+
/**
* End a hosted session and notify connected clients.
*/
diff --git a/server/services/fableLoom/hostedSession.test.js b/server/services/fableLoom/hostedSession.test.js
index 885fc2e6c1..da9115d29b 100644
--- a/server/services/fableLoom/hostedSession.test.js
+++ b/server/services/fableLoom/hostedSession.test.js
@@ -14,6 +14,7 @@ import {
startHostedListening,
startHostedSessionSweep,
stopHostedSessionSweep,
+ switchHostedEpisode,
updateHostedSession,
verifyHostedToken,
} from './hostedSession.js';
@@ -64,6 +65,27 @@ describe('fableLoom hostedSession', () => {
transitions: [],
},
],
+ }, {
+ id: 'ep-2',
+ title: 'Episode 2',
+ startNodeId: 'node-ep2-start',
+ nodes: [
+ {
+ id: 'node-ep2-start',
+ title: 'Mountain Pass',
+ prose: 'Snow crunches underfoot as you climb.',
+ playbackMode: 'decision',
+ audienceConnection: 'connected',
+ protagonistPresence: 'offscreen',
+ isEnding: false,
+ transitions: [{ id: 'tr-ep2-1', targetNodeId: 'node-ep2-start', intent: 'keep climbing', triggers: ['climb'] }],
+ },
+ ],
+ }, {
+ id: 'ep-3-not-ready',
+ title: 'Episode 3',
+ startNodeId: 'missing-start-node',
+ nodes: [],
}],
};
@@ -431,6 +453,98 @@ describe('fableLoom hostedSession', () => {
});
});
+ // #8112: the host can advance episodes without the server ever learning
+ // about it, so a hosted session used to keep resolving audience turns
+ // against the OLD episode's graph — findNode throws "Scene not found" and
+ // every turn silently falls back to canned narration.
+ describe('updateHostedSession — currentNodeId episode validation', () => {
+ it('accepts a currentNodeId that belongs to the session episode', async () => {
+ const { session } = await createHostedSession('loom-1', 'ep-1');
+ const updated = await updateHostedSession(session.id, { currentNodeId: 'node-2' });
+ expect(updated.currentNodeId).toBe('node-2');
+ });
+
+ it('rejects a currentNodeId from another episode and leaves the session unchanged', async () => {
+ const { session } = await createHostedSession('loom-1', 'ep-1');
+ await expect(updateHostedSession(session.id, { currentNodeId: 'node-ep2-start' }))
+ .rejects.toMatchObject({ status: 400, code: 'NODE_NOT_IN_EPISODE' });
+ expect(getHostedSession(session.id).currentNodeId).toBe('node-start');
+ });
+
+ it('skips the episode lookup when currentNodeId is unchanged', async () => {
+ const { session } = await createHostedSession('loom-1', 'ep-1');
+ records.getLoom.mockClear();
+ const updated = await updateHostedSession(session.id, { currentNodeId: 'node-start', playbackPhase: 'hold' });
+ expect(updated.playbackPhase).toBe('hold');
+ expect(records.getLoom).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('switchHostedEpisode', () => {
+ it('re-binds the session to the new episode, resets to its opening node, and clears the transcript', async () => {
+ const io = makeIo();
+ const { session } = await createHostedSession('loom-1', 'ep-1');
+
+ const result = await switchHostedEpisode(session.id, 'ep-2', { io });
+ expect(result.ok).toBe(true);
+ expect(result.session.currentNodeId).toBe('node-ep2-start');
+
+ const updated = getHostedSession(session.id);
+ expect(updated.currentNodeId).toBe('node-ep2-start');
+ expect(updated.playbackPhase).toBe('hold');
+ expect(updated.turnPhase).toBe('idle');
+ expect(updated.transcript).toHaveLength(1);
+ expect(updated.transcript[0].role).toBe('narrator');
+
+ // A subsequent audience turn resolves against episode 2's graph rather
+ // than throwing "Scene not found" against the old episode.
+ vi.spyOn(weave, 'playTurn').mockResolvedValue({
+ action: 'stay',
+ narration: 'The pass stretches on.',
+ node: { id: 'node-ep2-start' },
+ });
+ await startHostedListening(session.id, { io });
+ const turnResult = await processHostedUtterance(session.id, { textMessage: 'keep climbing', io });
+ expect(turnResult.playResult.narration).toBe('The pass stretches on.');
+ expect(weave.playTurn).toHaveBeenCalledWith('loom-1', 'ep-2', expect.objectContaining({ nodeId: 'node-ep2-start' }));
+
+ expect(io.emits.some((e) => e.event === 'hosted:session:sync')).toBe(true);
+ });
+
+ it('aborts an in-flight turn against the old episode before switching', 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: 'enter the forest', io });
+ await vi.waitFor(() => expect(weave.playTurn).toHaveBeenCalled());
+
+ await switchHostedEpisode(session.id, 'ep-2', { io });
+ storyTurn.resolve({ action: 'stay', narration: 'too late', node: { id: 'node-start' } });
+
+ await expect(pending).resolves.toMatchObject({ aborted: true });
+ expect(getHostedSession(session.id).currentNodeId).toBe('node-ep2-start');
+ });
+
+ it('ends the session with reason episode_not_ready when the target episode fails preflight', async () => {
+ const io = makeIo();
+ const { session } = await createHostedSession('loom-1', 'ep-1');
+
+ const result = await switchHostedEpisode(session.id, 'ep-3-not-ready', { io });
+ expect(result.ok).toBe(false);
+ expect(result.reason).toBe('episode_not_ready');
+ expect(getHostedSession(session.id)).toBeNull();
+ expect(io.emits.at(-1)).toMatchObject({ event: 'hosted:session:ended', payload: { reason: 'episode_not_ready' } });
+ });
+
+ it('throws when the target episode does not belong to the session loom', async () => {
+ const { session } = await createHostedSession('loom-1', 'ep-1');
+ await expect(switchHostedEpisode(session.id, 'not-an-episode')).rejects.toMatchObject({ status: 404 });
+ });
+ });
+
describe('expired-session sweep', () => {
// Age a session past its TTL without waiting out 30 real minutes.
const expire = (sessionId) => {
diff --git a/server/services/fableLoom/index.js b/server/services/fableLoom/index.js
index e66e92bb68..7606627e72 100644
--- a/server/services/fableLoom/index.js
+++ b/server/services/fableLoom/index.js
@@ -106,6 +106,7 @@ export {
startHostedSessionSweep,
stopHostedSessionSweep,
sweepExpiredHostedSessions,
+ switchHostedEpisode,
updateHostedSession,
verifyHostedToken,
} from './hostedSession.js';
diff --git a/server/sockets/fableLoomHosted.js b/server/sockets/fableLoomHosted.js
index e2fff429c7..e7fd3fe25f 100644
--- a/server/sockets/fableLoomHosted.js
+++ b/server/sockets/fableLoomHosted.js
@@ -14,6 +14,7 @@ import {
processHostedUtterance,
sanitizeHostedSession,
startHostedListening,
+ switchHostedEpisode,
updateHostedSession,
verifyHostedToken,
} from '../services/fableLoom/hostedSession.js';
@@ -130,10 +131,10 @@ export function registerFableLoomHostedNamespace(io) {
const liveSession = () => _getInternalSession(sessionId);
// --- Host actions ---
- socket.on('hosted:playback:update', (data) => {
+ socket.on('hosted:playback:update', async (data) => {
if (socket.hostedRole !== 'host') return;
try {
- const updated = updateHostedSession(sessionId, {
+ const updated = await updateHostedSession(sessionId, {
playbackPhase: data?.phase,
activeHoldIndex: data?.activeHoldIndex,
currentNodeId: data?.nodeId,
@@ -144,20 +145,40 @@ export function registerFableLoomHostedNamespace(io) {
nodeId: updated.currentNodeId,
});
} catch (err) {
- socket.emit('hosted:error', { code: 'UPDATE_FAILED', message: err.message });
+ socket.emit('hosted:error', { code: err.code || 'UPDATE_FAILED', message: err.message });
}
});
- socket.on('hosted:audio:target', (data) => {
+ socket.on('hosted:audio:target', async (data) => {
if (socket.hostedRole !== 'host') return;
try {
- const updated = updateHostedSession(sessionId, { audioTarget: data?.target }, { io });
+ const updated = await updateHostedSession(sessionId, { audioTarget: data?.target }, { io });
ns.to(room).emit('hosted:audio:target:updated', { audioTarget: updated.audioTarget });
} catch (err) {
socket.emit('hosted:error', { code: 'TARGET_UPDATE_FAILED', message: err.message });
}
});
+ // Host advanced to a different episode ("Next: Episode N") — re-bind THIS
+ // hosted session to it rather than letting the server keep resolving
+ // audience turns against the old episode's graph (#8112). On preflight
+ // failure `switchHostedEpisode` already ends the session and broadcasts
+ // `hosted:session:ended` with reason `episode_not_ready`; there is no live
+ // room left to answer with a second error frame.
+ socket.on('hosted:episode:switch', async (data) => {
+ if (socket.hostedRole !== 'host') return;
+ const episodeId = typeof data?.episodeId === 'string' ? data.episodeId : null;
+ if (!episodeId) {
+ socket.emit('hosted:error', { code: 'EPISODE_ID_REQUIRED', message: 'episodeId is required' });
+ return;
+ }
+ try {
+ await switchHostedEpisode(sessionId, episodeId, { io });
+ } catch (err) {
+ socket.emit('hosted:error', { code: err.code || 'EPISODE_SWITCH_FAILED', message: err.message });
+ }
+ });
+
socket.on('hosted:session:end', () => {
if (socket.hostedRole !== 'host') return;
endHostedSession(sessionId, { reason: 'host_ended', io });
diff --git a/server/sockets/fableLoomHosted.test.js b/server/sockets/fableLoomHosted.test.js
index 88403e2a99..692d5a998f 100644
--- a/server/sockets/fableLoomHosted.test.js
+++ b/server/sockets/fableLoomHosted.test.js
@@ -48,6 +48,20 @@ describe('fableLoomHosted Socket.IO namespace', () => {
playbackAssets: { holdLoopVideoHistoryIds: ['vid-2'] },
transitions: [],
}],
+ }, {
+ id: 'ep-2',
+ title: 'Episode 2',
+ startNodeId: 'node-ep2-1',
+ nodes: [{
+ id: 'node-ep2-1',
+ title: 'Episode 2 opener',
+ prose: 'Episode two opening prose',
+ playbackMode: 'decision',
+ audienceConnection: 'connected',
+ protagonistPresence: 'offscreen',
+ isEnding: false,
+ transitions: [],
+ }],
}],
};
@@ -377,10 +391,10 @@ describe('fableLoomHosted Socket.IO namespace', () => {
expect(getHostedSession(session.id).turnPhase).toBe('idle');
});
- it('lets a host drive hosted:playback:update', () => {
+ it('lets a host drive hosted:playback:update', async () => {
const host = connectHost();
- host.listeners['hosted:playback:update']({ phase: 'entry', activeHoldIndex: 1, nodeId: 'node-2' });
+ await host.listeners['hosted:playback:update']({ phase: 'entry', activeHoldIndex: 1, nodeId: 'node-2' });
expect(roomEvent('hosted:playback:sync')?.data).toEqual({
phase: 'entry',
@@ -405,6 +419,51 @@ describe('fableLoomHosted Socket.IO namespace', () => {
});
});
+ // #8112: only the host may re-bind this hosted session's episode. An
+ // audience socket triggering this would let a guest device rewrite the
+ // story the host is presenting.
+ it('lets a host switch episodes and re-syncs the room', async () => {
+ const host = connectHost();
+
+ await host.listeners['hosted:episode:switch']({ episodeId: 'ep-2' });
+
+ expect(getHostedSession(session.id)).toMatchObject({
+ episodeId: 'ep-2',
+ currentNodeId: 'node-ep2-1',
+ turnPhase: 'idle',
+ });
+ const sync = roomEvent('hosted:session:sync');
+ expect(sync?.data).toMatchObject({ episodeId: 'ep-2', currentNodeId: 'node-ep2-1' });
+ expect(sync?.data.transcript).toHaveLength(1);
+ });
+
+ it('refuses hosted:episode:switch from an audience socket', async () => {
+ await audience.listeners['hosted:episode:switch']({ episodeId: 'ep-2' });
+
+ expect(getHostedSession(session.id)).toMatchObject({ episodeId: 'ep-1', currentNodeId: 'node-1' });
+ expect(roomEvent('hosted:session:sync')).toBeUndefined();
+ });
+
+ it('emits hosted:error when hosted:episode:switch is sent with no episodeId', async () => {
+ const host = connectHost();
+
+ await host.listeners['hosted:episode:switch']({});
+
+ expect(host.emitted.find((e) => e.event === 'hosted:error')?.data)
+ .toMatchObject({ code: 'EPISODE_ID_REQUIRED' });
+ expect(getHostedSession(session.id).episodeId).toBe('ep-1');
+ });
+
+ it('emits hosted:error to the host when the target episode does not exist', async () => {
+ const host = connectHost();
+
+ await host.listeners['hosted:episode:switch']({ episodeId: 'no-such-episode' });
+
+ expect(host.emitted.find((e) => e.event === 'hosted:error')?.data)
+ .toMatchObject({ code: 'NOT_FOUND' });
+ expect(getHostedSession(session.id).episodeId).toBe('ep-1');
+ });
+
it('returns the turn to listening on hosted:speech:done', () => {
_getInternalSession(session.id).turnPhase = 'speaking';