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 hosted guest text admission and preserve accepted input (#11731)
[._.]/76e88bbeef5b
diff --git a/client/src/pages/FableLoomHostedJoin.jsx b/client/src/pages/FableLoomHostedJoin.jsxindex 4d2036c004..d88e924147 100644--- a/client/src/pages/FableLoomHostedJoin.jsx+++ b/client/src/pages/FableLoomHostedJoin.jsx@@ -10,6 +10,7 @@ import { useEffect, useRef, useState } from 'react';import { io } from 'socket.io-client';import { MAX_VOICE_AUDIO_BYTES, RECORDING_TOO_LONG_MESSAGE } from '../lib/audioRecorder.js';import useMounted from '../hooks/useMounted.js';+import { formatCount } from '../utils/formatters.js';import {AlertCircle,Loader2,@@ -28,6 +29,7 @@ const HOSTED_ERROR_MESSAGES = {TURN_IN_PROGRESS: 'A reply is already in progress — wait a moment, then try again.',EPISODE_SWITCH_IN_PROGRESS: 'The host is switching episodes — try again in a moment.',};+const MAX_TEXT_CHARACTERS = 1000;export default function FableLoomHostedJoin() {const [sessionId, setSessionId] = useState(null);@@ -253,8 +255,8 @@ export default function FableLoomHostedJoin() {const handleSendText = (e) => {e?.preventDefault();- if (!textInput.trim() || !socket) return;- socket.emit('hosted:turn:text', { text: textInput.trim() });+ if (!textInput.trim() || textInput.length > MAX_TEXT_CHARACTERS || !socket) return;+ socket.emit('hosted:turn:text', { text: textInput });setTextInput('');};@@ -387,18 +389,28 @@ export default function FableLoomHostedJoin() {onChange={(e) => setTextInput(e.target.value)}placeholder="Or type a message…"aria-label="Message protagonist"+ aria-describedby={textInput.length > MAX_TEXT_CHARACTERS ? 'hosted-text-count hosted-text-limit-error' : 'hosted-text-count'}+ aria-invalid={textInput.length > MAX_TEXT_CHARACTERS}disabled={turnPhase === 'thinking' || turnPhase === 'speaking'}className="flex-1 bg-slate-800/80 border border-slate-700 rounded-lg px-3 py-2 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-indigo-500"/><buttontype="submit"aria-label="Send message"- disabled={!textInput.trim() || turnPhase === 'thinking' || turnPhase === 'speaking'}+ disabled={!textInput.trim() || textInput.length > MAX_TEXT_CHARACTERS || turnPhase === 'thinking' || turnPhase === 'speaking'}className="min-w-[44px] min-h-[44px] p-2 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-40 disabled:cursor-not-allowed rounded-lg text-white transition-colors flex items-center justify-center"><Send className="w-4 h-4" /></button></form>+ <p id="hosted-text-count" className="mt-1 text-right text-[11px] text-slate-400">+ {formatCount(textInput.length)} / {formatCount(MAX_TEXT_CHARACTERS)} characters+ </p>+ {textInput.length > MAX_TEXT_CHARACTERS && (+ <p id="hosted-text-limit-error" role="alert" className="text-xs text-red-400">+ Message exceeds {formatCount(MAX_TEXT_CHARACTERS)} characters. Shorten it before sending.+ </p>+ )}</div></main>);diff --git a/client/src/pages/FableLoomHostedJoin.test.jsx b/client/src/pages/FableLoomHostedJoin.test.jsxindex d6f139bcff..bdf2be1f58 100644--- a/client/src/pages/FableLoomHostedJoin.test.jsx+++ b/client/src/pages/FableLoomHostedJoin.test.jsx@@ -1,5 +1,6 @@import { describe, it, expect, beforeEach, vi } from 'vitest';import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';+import userEvent from '@testing-library/user-event';import FableLoomHostedJoin from './FableLoomHostedJoin';// Mock socket.io-client@@ -68,7 +69,7 @@ describe('FableLoomHostedJoin', () => {render(<FableLoomHostedJoin />);const input = screen.getByPlaceholderText('Or type a message…');- fireEvent.change(input, { target: { value: 'Look around the room' } });+ fireEvent.change(input, { target: { value: ' Look around the room ' } });const sendButton = screen.getByRole('button', { name: 'Send message' });expect(sendButton).toBeInTheDocument();@@ -81,7 +82,45 @@ describe('FableLoomHostedJoin', () => {);fireEvent.submit(input.closest('form'));- expect(mockSocket.emit).toHaveBeenCalledWith('hosted:turn:text', { text: 'Look around the room' });+ expect(mockSocket.emit).toHaveBeenCalledWith('hosted:turn:text', { text: ' Look around the room ' });+ });++ it('preserves an over-limit paste, refuses to send, and lets the guest shorten the message', async () => {+ window.location.hash = '#session=sess-123&token=tok-abc';+ const user = userEvent.setup();+ render(<FableLoomHostedJoin />);+ const input = screen.getByRole('textbox', { name: 'Message protagonist' });+ expect(input).not.toHaveAttribute('maxlength');+ expect(input).toHaveAccessibleDescription('0 / 1,000 characters');+ await user.click(input);+ await user.paste('x'.repeat(1001));+ expect(input).toHaveValue('x'.repeat(1001));+ expect(input).toHaveAccessibleDescription('1,001 / 1,000 characters Message exceeds 1,000 characters. Shorten it before sending.');+ expect(screen.getByRole('alert')).toHaveTextContent('Shorten it before sending.');+ expect(screen.getByRole('button', { name: 'Send message' })).toBeDisabled();+ fireEvent.submit(input.closest('form'));+ expect(mockSocket.emit).not.toHaveBeenCalled();++ input.setSelectionRange(1000, 1001);+ await user.keyboard('{Backspace}');+ expect(input).toHaveValue('x'.repeat(1000));+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ expect(input).toHaveAccessibleDescription('1,000 / 1,000 characters');+ await user.click(screen.getByRole('button', { name: 'Send message' }));+ expect(mockSocket.emit).toHaveBeenCalledWith('hosted:turn:text', { text: 'x'.repeat(1000) });+ expect(input).toHaveAccessibleDescription('0 / 1,000 characters');+ });++ it('refuses over-limit typed input without cutting or clearing it', () => {+ window.location.hash = '#session=sess-123&token=tok-abc';+ render(<FableLoomHostedJoin />);+ const input = screen.getByRole('textbox', { name: 'Message protagonist' });+ const text = 'x'.repeat(1001);+ fireEvent.change(input, { target: { value: text } });+ fireEvent.submit(input.closest('form'));+ expect(mockSocket.emit).not.toHaveBeenCalled();+ expect(input).toHaveValue(text);+ expect(input).toHaveAccessibleDescription('1,001 / 1,000 characters Message exceeds 1,000 characters. Shorten it before sending.');});it('releases a mic opened after push-to-talk was released', async () => {diff --git a/server/lib/fableLoomValidation.js b/server/lib/fableLoomValidation.jsindex 62fb5b042e..4379f6c5c5 100644--- a/server/lib/fableLoomValidation.js+++ b/server/lib/fableLoomValidation.js@@ -378,9 +378,11 @@ export const reviewSchema = z.object({ ...aiRunFields });// A turn is EITHER a reader's free text (matched to a path by the play stage)// or a path the reader took outright — a tapped choice needs no intent// mapping, so it carries the transition id and no LLM call happens at all.+const playMessageSchema = z.string().min(1).max(1000);+export const playTurnSchema = z.object({nodeId: nodeIdStr,- message: z.string().min(1).max(1000).optional(),+ message: playMessageSchema.optional(),transitionId: z.string().min(1).max(80).optional(),transcript: z.array(z.object({role: z.enum(['reader', 'narrator']),@@ -392,6 +394,8 @@ export const playTurnSchema = z.object({path: ['message'],});+export const hostedTextTurnSchema = z.object({ text: playMessageSchema });+export const reformatSchema = z.object({format,...aiRunFields,@@ -446,6 +450,12 @@ export const hostedSessionPatchSchema = z.object({activeHoldIndex: z.number().int().min(0).max(10).optional(),});+export const hostedPlaybackUpdateSchema = z.object({+ nodeId: hostedSessionPatchSchema.shape.currentNodeId,+ phase: hostedSessionPatchSchema.shape.playbackPhase,+ activeHoldIndex: hostedSessionPatchSchema.shape.activeHoldIndex,+});+export const productionPlanSchema = z.object({mode: z.enum(FABLELOOM_PRODUCTION_MODES).optional(),imageMode: z.enum(QUEUEABLE_IMAGE_MODES).optional(),diff --git a/server/services/cosAgentLifecycle.test.js b/server/services/cosAgentLifecycle.test.jsindex 30701ee850..8aaa6d6230 100644--- a/server/services/cosAgentLifecycle.test.js+++ b/server/services/cosAgentLifecycle.test.js@@ -37,11 +37,15 @@ const fsFailures = vi.hoisted(() => ({ dateBucketWritesFail: false, rmFailsFor:vi.mock('fs/promises', async (importOriginal) => {const actual = await importOriginal();+ const { relative } = await import('node:path');// Accept either separator: the archive path is composed with path.join, so on// Windows the date bucket reads '\2026-08-14\' and a '/'-only pattern never// matched — the injected failure never fired and completeAgent RESOLVED,// making this rollback test assert nothing.- const failsFor = (p) => fsFailures.dateBucketWritesFail && /[\\/]\d{4}-\d{2}-\d{2}[\\/]/.test(String(p));+ const failsFor = (p) => {+ const target = relative(mockCosState.agentsDir, String(p));+ return fsFailures.dateBucketWritesFail && /^\d{4}-\d{2}-\d{2}[\\/]/.test(target);+ };return {...actual,rename: async (from, to, ...rest) => {diff --git a/server/services/fableLoom/hostedSession.js b/server/services/fableLoom/hostedSession.jsindex fbb2605038..fd879b4fa0 100644--- a/server/services/fableLoom/hostedSession.js+++ b/server/services/fableLoom/hostedSession.js@@ -607,52 +607,62 @@ export async function startHostedListening(sessionId, { io } = {}) {throw new ServerError('An episode switch is in progress', { status: 409, code: 'EPISODE_SWITCH_IN_PROGRESS' });}- const episodeId = session.episodeId;- const switchGeneration = session.episodeSwitchGeneration;- const loom = await getLoom(session.loomId);- if (activeSessions.get(sessionId) !== session || session.status !== 'active') {- throw new ServerError('Session is not active', { status: 400, code: 'SESSION_INACTIVE' });- }- if (session.switchingEpisode || session.episodeSwitchGeneration !== switchGeneration || session.episodeId !== episodeId) {- throw new ServerError('Session changed while starting the listening turn', { status: 409, code: 'EPISODE_SWITCH_IN_PROGRESS' });+ // Reserve admission before the loom read so simultaneous mic/text starts+ // cannot replace each other's active turn while their gate checks await.+ if (session.startingListening) {+ throw new ServerError('A turn is already starting', { status: 409, code: 'TURN_IN_PROGRESS' });}+ session.startingListening = true;+ try {+ const episodeId = session.episodeId;+ const switchGeneration = session.episodeSwitchGeneration;+ const loom = await getLoom(session.loomId);+ if (activeSessions.get(sessionId) !== session || session.status !== 'active') {+ throw new ServerError('Session is not active', { status: 400, code: 'SESSION_INACTIVE' });+ }+ if (session.switchingEpisode || session.episodeSwitchGeneration !== switchGeneration || session.episodeId !== episodeId) {+ throw new ServerError('Session changed while starting the listening turn', { status: 409, code: 'EPISODE_SWITCH_IN_PROGRESS' });+ }- const episode = loom.episodes?.find((e) => e.id === episodeId) || null;- const node = episode?.nodes?.find((n) => n.id === session.currentNodeId) || null;- const asset = resolvePlaybackPhaseAsset({- node,- phase: session.playbackPhase,- activeHoldIndex: session.activeHoldIndex,- });-- const gate = revalidateLiveConversationGate({ session, node, asset });- if (!gate.allowed) {- throw new ServerError(`Live voice conversation is not permitted: ${gate.reason}`, {- status: 409,- code: gate.reason,+ const episode = loom.episodes?.find((e) => e.id === episodeId) || null;+ const node = episode?.nodes?.find((n) => n.id === session.currentNodeId) || null;+ const asset = resolvePlaybackPhaseAsset({+ node,+ phase: session.playbackPhase,+ activeHoldIndex: session.activeHoldIndex,});- }- if (session.turnPhase === 'speaking' || session.turnPhase === 'thinking') {- throw new ServerError('A turn is already in progress', { status: 409, code: 'TURN_IN_PROGRESS' });- }+ const gate = revalidateLiveConversationGate({ session, node, asset });+ if (!gate.allowed) {+ throw new ServerError(`Live voice conversation is not permitted: ${gate.reason}`, {+ status: 409,+ code: gate.reason,+ });+ }- const turnId = randomUUID();- session.turnPhase = 'listening';- session.activeTurn = {- id: turnId,- abortController: new AbortController(),- startedAt: Date.now(),- };+ if (session.turnPhase === 'speaking' || session.turnPhase === 'thinking') {+ throw new ServerError('A turn is already in progress', { status: 409, code: 'TURN_IN_PROGRESS' });+ }- if (io) {- io.of('/fableloom-hosted').to(`session:${sessionId}`).emit('hosted:turn:phase', {- phase: 'listening',- turnId,- });- }+ const turnId = randomUUID();+ session.turnPhase = 'listening';+ session.activeTurn = {+ id: turnId,+ abortController: new AbortController(),+ startedAt: Date.now(),+ };- return { ok: true, turnId };+ if (io) {+ io.of('/fableloom-hosted').to(`session:${sessionId}`).emit('hosted:turn:phase', {+ phase: 'listening',+ turnId,+ });+ }++ return { ok: true, turnId };+ } finally {+ session.startingListening = false;+ }}/**@@ -700,10 +710,10 @@ export async function processHostedUtterance(sessionId, {emitIfLive('hosted:turn:phase', { phase: 'thinking', turnId: turn.id });try {- let message = (textMessage || '').trim();+ let message = textMessage || '';// 1. Transcribe audio if supplied- if (audioBuffer && !message) {+ if (audioBuffer && !message.trim()) {let wavPayload = audioBuffer;if (audioBuffer instanceof Int16Array || (ArrayBuffer.isView(audioBuffer) && !(audioBuffer instanceof Buffer))) {const floatPcm = pcmToFloat(audioBuffer);@@ -721,7 +731,7 @@ export async function processHostedUtterance(sessionId, {}// Check for echo / empty message- if (!message || isEchoOfRecentTts(message, session.recentTts)) {+ if (!message.trim() || isEchoOfRecentTts(message, session.recentTts)) {session.turnPhase = 'listening';emitIfLive('hosted:turn:phase', {phase: 'listening',diff --git a/server/services/fableLoom/weave.js b/server/services/fableLoom/weave.jsindex 134c77a29a..1e71baf8ba 100644--- a/server/services/fableLoom/weave.js+++ b/server/services/fableLoom/weave.js@@ -1329,7 +1329,7 @@ export async function playTurn(loomId, episodeId, {sceneProse: node.prose || node.title || '',choicesDigest,transcriptDigest: transcriptDigest(transcript) || '(start of the read-through)',- readerMessage: trimTo(message, 1000),+ readerMessage: isStr(message) && message.length <= 1000 ? message : trimTo(message, 1000),narrationFormatContract: narrationFormatContract(loom.format),}, { ...llmOptions(playRouting(loom, { providerId, model, effort }), 'fableloom-play'), callerPolicy });diff --git a/server/sockets/fableLoomHosted.js b/server/sockets/fableLoomHosted.jsindex 9d64fb8d3f..601dbf46fb 100644--- a/server/sockets/fableLoomHosted.js+++ b/server/sockets/fableLoomHosted.js@@ -7,6 +7,7 @@*/import { SOCKET_MEDIA_MAX_BYTES } from '../lib/socketPayloadLimits.js';+import { hostedPlaybackUpdateSchema, hostedTextTurnSchema } from '../lib/fableLoomValidation.js';import {_getInternalSession,abortHostedTurn,@@ -161,10 +162,18 @@ export function registerFableLoomHostedNamespace(io) {socket.on('hosted:playback:update', async (data) => {if (socket.hostedRole !== 'host') return;try {+ const parsed = hostedPlaybackUpdateSchema.safeParse(data);+ if (!parsed.success) {+ socket.emit('hosted:error', {+ code: 'VALIDATION_ERROR',+ message: parsed.error.issues.map((issue) => `${issue.path.join('.')}: ${issue.message}`).join('; '),+ });+ return;+ }const updated = await updateHostedSession(sessionId, {- playbackPhase: data?.phase,- activeHoldIndex: data?.activeHoldIndex,- currentNodeId: data?.nodeId,+ playbackPhase: parsed.data.phase,+ activeHoldIndex: parsed.data.activeHoldIndex,+ currentNodeId: parsed.data.nodeId,}, { io });ns.to(room).emit('hosted:playback:sync', {phase: updated.playbackPhase,@@ -284,9 +293,28 @@ export function registerFableLoomHostedNamespace(io) {socket.on('hosted:turn:text', async (data) => {if (socket.hostedRole !== 'audience') return;const live = liveSession();- if (!live || live.turnPhase !== 'listening') return;+ if (!live) return;try {- await processHostedUtterance(sessionId, { textMessage: data?.text, io });+ const parsed = hostedTextTurnSchema.safeParse(data);+ if (!parsed.success) {+ const count = typeof data?.text === 'string' ? data.text.length : null;+ const maxLength = hostedTextTurnSchema.shape.text.maxLength;+ socket.emit('hosted:error', {+ code: 'VALIDATION_ERROR',+ message: count === null+ ? 'Text must be a string.'+ : `Text has ${count} characters; send between 1 and ${maxLength} characters.`,+ count,+ maxLength,+ });+ return;+ }+ if (live.turnPhase === 'thinking' || live.turnPhase === 'speaking') {+ socket.emit('hosted:error', { code: 'TURN_IN_PROGRESS', message: 'A turn is already in progress' });+ return;+ }+ if (live.turnPhase === 'idle') await startHostedListening(sessionId, { io });+ await processHostedUtterance(sessionId, { textMessage: parsed.data.text, io });} catch (err) {if (!err?.hostedReported) socket.emit('hosted:error', { code: err.code || 'TEXT_FAILED', message: err.message });}diff --git a/server/sockets/fableLoomHosted.test.js b/server/sockets/fableLoomHosted.test.jsindex 10d202985a..e160d8fc2c 100644--- a/server/sockets/fableLoomHosted.test.js+++ b/server/sockets/fableLoomHosted.test.js@@ -181,7 +181,7 @@ describe('fableLoomHosted Socket.IO namespace', () => {}});- async function guestTurn(input) {+ async function guestTurn(input, text = 'go next') {const { session, token, preflight } = await createHostedSession('loom-1', 'ep-1');const audience = makeSocket({ role: 'audience', sessionId: session.id });audience.handshake = { auth: { role: 'audience', sessionId: session.id, token } };@@ -191,7 +191,7 @@ describe('fableLoomHosted Socket.IO namespace', () => {connectionHandler(audience);await audience.listeners['hosted:mic:start']();if (input === 'audio') await audience.listeners['hosted:mic:stop'](Buffer.from('synthetic audio'));- else await audience.listeners['hosted:turn:text']({ text: 'go next', callerPolicy: 'any-text', providerId: cli.id });+ else await audience.listeners['hosted:turn:text']({ text, callerPolicy: 'any-text', providerId: cli.id });expect(runner.executeCliRun).not.toHaveBeenCalled();expect(tuiRunner.executeTuiRun).not.toHaveBeenCalled();return { preflight, session: getHostedSession(session.id) };@@ -221,6 +221,13 @@ describe('fableLoomHosted Socket.IO namespace', () => {expect(runner.executeApiRun).toHaveBeenCalledTimes(1);});+ it('preserves the full accepted guest text through the real play prompt boundary', async () => {+ const text = ` ${'x'.repeat(996)} `;+ const { session } = await guestTurn('text', text);+ expect(prompts.buildPrompt).toHaveBeenCalledWith('fableloom-play-turn', expect.objectContaining({ readerMessage: text }));+ expect(session.transcript.find((item) => item.role === 'audience')?.text).toBe(text);+ });+it('refuses proactive process substitution and retains authored narration', async () => {selected = { ...api, fallbackProvider: cli.id };runner.createRun.mockImplementation(async ({ requestCapabilities }) => {@@ -470,14 +477,115 @@ describe('fableLoomHosted Socket.IO namespace', () => {expect(getHostedSession(session.id).turnPhase).toBe('idle');});- it('ignores hosted:turn:text when the session is not listening', async () => {+ it('opens a text turn from the initial idle session without a microphone start', async () => {await audience.listeners['hosted:turn:text']({ text: 'go next' });- expect(weave.playTurn).not.toHaveBeenCalled();+ expect(weave.playTurn).toHaveBeenCalledWith('loom-1', 'ep-1', expect.objectContaining({ message: 'go next' }));expect(getHostedSession(session.id).currentNodeId).toBe('node-1');expect(audience.emitted.find((e) => e.event === 'hosted:error')).toBeUndefined();});+ it('opens another typed turn after a scene transition returns the session to idle', async () => {+ weave.playTurn.mockResolvedValueOnce({+ action: 'move', transitionId: 'tr-1', narration: 'Onward.', node: { id: 'node-2' }, ended: false,+ });+ await audience.listeners['hosted:turn:text']({ text: 'go next' });+ expect(getHostedSession(session.id)).toMatchObject({ turnPhase: 'idle', currentNodeId: 'node-2' });++ await audience.listeners['hosted:turn:text']({ text: 'look around' });+ expect(weave.playTurn).toHaveBeenLastCalledWith('loom-1', 'ep-1', expect.objectContaining({+ nodeId: 'node-2', message: 'look around',+ }));+ expect(weave.playTurn).toHaveBeenCalledTimes(2);+ });++ it('reports the live gate refusal and permits a new text turn after playback returns to hold', async () => {+ const host = connectHost();+ await host.listeners['hosted:playback:update']({ phase: 'entry' });+ await audience.listeners['hosted:turn:text']({ text: 'go next' });+ expect(audience.emitted.find((e) => e.event === 'hosted:error')?.data)+ .toMatchObject({ code: 'PLAYBACK_NOT_IN_HOLD_PHASE' });+ expect(weave.playTurn).not.toHaveBeenCalled();+ expect(getHostedSession(session.id).turnPhase).toBe('idle');++ await host.listeners['hosted:playback:update']({ phase: 'hold' });+ await audience.listeners['hosted:turn:text']({ text: 'go next' });+ expect(weave.playTurn).toHaveBeenCalledOnce();+ });++ it.each(['thinking', 'speaking'])('refuses typed turns while %s', async (phase) => {+ _getInternalSession(session.id).turnPhase = phase;+ await audience.listeners['hosted:turn:text']({ text: 'go next' });+ expect(audience.emitted.find((e) => e.event === 'hosted:error')?.data)+ .toMatchObject({ code: 'TURN_IN_PROGRESS' });+ expect(weave.playTurn).not.toHaveBeenCalled();+ expect(getHostedSession(session.id).turnPhase).toBe(phase);+ });++ it.each(['text', 'mic'])('refuses a concurrent idle %s admission without replacing the first text turn', async (second) => {+ let resolveLoom;+ records.getLoom.mockImplementationOnce(() => new Promise((resolve) => { resolveLoom = resolve; }));+ const pending = audience.listeners['hosted:turn:text']({ text: 'first request' });+ if (second === 'text') await audience.listeners['hosted:turn:text']({ text: 'second request' });+ else await audience.listeners['hosted:mic:start']();+ expect(audience.emitted.find((e) => e.event === 'hosted:error')?.data)+ .toMatchObject({ code: 'TURN_IN_PROGRESS' });+ resolveLoom(mockLoom);+ await pending;+ expect(weave.playTurn).toHaveBeenCalledOnce();+ expect(weave.playTurn).toHaveBeenCalledWith('loom-1', 'ep-1', expect.objectContaining({ message: 'first request' }));+ expect(getHostedSession(session.id).transcript.filter((item) => item.role === 'audience'))+ .toMatchObject([{ text: 'first request' }]);+ });++ it('releases text admission after a failed loom read so a retry can succeed', async () => {+ records.getLoom.mockRejectedValueOnce(new Error('loom read failed'));+ await audience.listeners['hosted:turn:text']({ text: 'first request' });+ expect(audience.emitted.find((e) => e.event === 'hosted:error')?.data)+ .toMatchObject({ code: 'TEXT_FAILED', message: 'loom read failed' });+ expect(weave.playTurn).not.toHaveBeenCalled();+ await audience.listeners['hosted:turn:text']({ text: 'retry request' });+ expect(weave.playTurn).toHaveBeenCalledOnce();+ });++ it('reports an episode-switch refusal and accepts text after the switch completes', async () => {+ const host = connectHost();+ let resolveLoom;+ records.getLoom.mockImplementationOnce(() => new Promise((resolve) => { resolveLoom = resolve; }));+ const pending = host.listeners['hosted:episode:switch']({ episodeId: 'ep-2' });+ await audience.listeners['hosted:turn:text']({ text: 'go next' });+ expect(audience.emitted.find((e) => e.event === 'hosted:error')?.data)+ .toMatchObject({ code: 'EPISODE_SWITCH_IN_PROGRESS' });+ expect(weave.playTurn).not.toHaveBeenCalled();+ resolveLoom(mockLoom);+ await pending;+ await audience.listeners['hosted:turn:text']({ text: 'new episode request' });+ expect(weave.playTurn).toHaveBeenCalledWith('loom-1', 'ep-2', expect.objectContaining({+ nodeId: 'node-ep2-1', message: 'new episode request',+ }));+ });++ it.each([{}, { text: 42 }, { text: { message: 'go next' } }, { text: null }, { text: '' }, { text: 'x'.repeat(1001) }])(+ 'rejects invalid text payload %# before opening a turn or publishing a transcript', async (payload) => {+ await audience.listeners['hosted:turn:text'](payload);+ const error = audience.emitted.find((e) => e.event === 'hosted:error')?.data;+ expect(error).toMatchObject({ code: 'VALIDATION_ERROR', maxLength: 1000 });+ expect(error.count).toBe(typeof payload.text === 'string' ? payload.text.length : null);+ if (typeof payload.text === 'string') expect(error.message).toContain(String(payload.text.length));+ expect(weave.playTurn).not.toHaveBeenCalled();+ expect(getHostedSession(session.id)).toMatchObject({ turnPhase: 'idle' });+ expect(getHostedSession(session.id).transcript).toHaveLength(1);+ expect(roomEvent('hosted:turn:transcript')).toBeUndefined();+ },+ );++ it('passes a text message at the REST limit through without cutting it', async () => {+ const text = 'x'.repeat(1000);+ await audience.listeners['hosted:turn:text']({ text });+ expect(weave.playTurn).toHaveBeenCalledWith('loom-1', 'ep-1', expect.objectContaining({ message: text }));+ expect(roomEvent('hosted:turn:transcript')?.data).toMatchObject({ text });+ });+it('buffers mic frames while listening and transcribes them on mic:stop', async () => {await audience.listeners['hosted:mic:start']();audience.listeners['hosted:mic:frame'](Buffer.from('aa'));@@ -627,6 +735,23 @@ describe('fableLoomHosted Socket.IO namespace', () => {});});+ it.each([+ { phase: 'not-a-phase' }, { activeHoldIndex: -1 }, { activeHoldIndex: 11 },+ { activeHoldIndex: 1.5 }, { activeHoldIndex: '1' }, { nodeId: 42 },+ ])('rejects playback payload %# outside the REST schema without changing state', async (payload) => {+ const host = connectHost();+ await host.listeners['hosted:playback:update'](payload);+ expect(host.emitted.find((e) => e.event === 'hosted:error')?.data).toMatchObject({ code: 'VALIDATION_ERROR' });+ expect(getHostedSession(session.id)).toMatchObject({ playbackPhase: 'hold', activeHoldIndex: 0, currentNodeId: 'node-1' });+ expect(roomEvent('hosted:playback:sync')).toBeUndefined();+ });++ it.each([0, 10])('accepts the REST playback hold-index boundary %s', async (activeHoldIndex) => {+ const host = connectHost();+ await host.listeners['hosted:playback:update']({ phase: 'hold', activeHoldIndex, nodeId: 'node-2' });+ expect(roomEvent('hosted:playback:sync')?.data).toEqual({ phase: 'hold', activeHoldIndex, nodeId: 'node-2' });+ });+// #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.