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
feat: add interactive FableLoom playback modes
Adam Eivyb4388e140008
diff --git a/client/src/components/fableloom/LoomCanvas.jsx b/client/src/components/fableloom/LoomCanvas.jsxindex c10faecc38..c75d9c7e63 100644--- a/client/src/components/fableloom/LoomCanvas.jsx+++ b/client/src/components/fableloom/LoomCanvas.jsx@@ -282,6 +282,18 @@ export default function LoomCanvas({</g>)}</g>+ {!node.isEnding && (+ <text+ x={nodeW - 10}+ y={nodeH - 15}+ textAnchor="end"+ className={node.playbackMode === 'cut'+ ? 'fill-port-accent text-[9px] font-medium pointer-events-none'+ : 'fill-port-warning text-[9px] font-medium pointer-events-none'}+ >+ {node.playbackMode === 'cut' ? 'Auto cut' : 'Decision loop'}+ </text>+ )}</g>);})}diff --git a/client/src/components/fableloom/LoomCanvas.test.jsx b/client/src/components/fableloom/LoomCanvas.test.jsxindex 9b03ed1a18..3c1b5dfcc8 100644--- a/client/src/components/fableloom/LoomCanvas.test.jsx+++ b/client/src/components/fableloom/LoomCanvas.test.jsx@@ -29,6 +29,7 @@ describe('LoomCanvas', () => {expect(screen.getByLabelText('Scene: The Gate')).toBeInTheDocument();expect(screen.getByLabelText('Scene: Inside')).toBeInTheDocument();expect(screen.getByText('Opening')).toBeInTheDocument();+ expect(screen.getByText('Decision loop')).toBeInTheDocument();expect(screen.getByText('Within')).toBeInTheDocument();expect(screen.getByText('enter the gate')).toBeInTheDocument();});diff --git a/client/src/components/fableloom/LoomEpisodeOutline.jsx b/client/src/components/fableloom/LoomEpisodeOutline.jsxindex 27d9a6af7e..e14943cf42 100644--- a/client/src/components/fableloom/LoomEpisodeOutline.jsx+++ b/client/src/components/fableloom/LoomEpisodeOutline.jsx@@ -63,6 +63,9 @@ function SceneBlock({ node, number, episode, format, byId, onSelectNode }) {<Flag size={11} /> {node.endingLabel || 'Ending'}</span>)}+ {!node.isEnding && (+ <span>{node.playbackMode === 'cut' ? 'Automatic cut' : 'Decision loop'}</span>+ )}</div></div><span className="shrink-0 text-[11px] text-port-text-muted">Scene {number}</span>@@ -78,7 +81,9 @@ function SceneBlock({ node, number, episode, format, byId, onSelectNode }) {{transitions.length > 0 && (<div className="border-t border-port-border pt-3">- <h4 className="mb-2 text-[11px] font-semibold uppercase tracking-wide text-port-text-muted">Reader paths</h4>+ <h4 className="mb-2 text-[11px] font-semibold uppercase tracking-wide text-port-text-muted">+ {node.playbackMode === 'cut' ? 'Next cut' : 'Viewer paths'}+ </h4><ul className="space-y-1.5">{transitions.map((transition) => {const target = byId.get(transition.targetNodeId);diff --git a/client/src/components/fableloom/LoomNodeEditor.jsx b/client/src/components/fableloom/LoomNodeEditor.jsxindex 6954e4d7d5..70214ab7fe 100644--- a/client/src/components/fableloom/LoomNodeEditor.jsx+++ b/client/src/components/fableloom/LoomNodeEditor.jsx@@ -27,6 +27,7 @@ import {import { fieldClass, labelClass, sceneFieldClass } from './fieldStyles';import { isTeleplayFormat } from './loomFormats';import { FABLELOOM_CAMERA_MOVEMENTS } from '../../../../server/lib/fableLoomCameraMovements.js';+import { FABLELOOM_PLAYBACK_MODES } from '../../../../server/lib/fableLoomPlayback.js';const toRow = (t) => ({ ...t, triggersText: (t.triggers || []).join('; ') });const rowToPatch = ({ targetNodeId, intent, triggersText, description }) => ({@@ -59,6 +60,7 @@ export default function LoomNodeEditor({ loom, episode, node, onLoomUpdate, onClimagePrompt: node.imagePrompt || '',videoPrompt: node.videoPrompt || '',cameraMovement: node.cameraMovement || '',+ playbackMode: node.playbackMode || 'decision',isEnding: !!node.isEnding,endingLabel: node.endingLabel || '',transitions: (node.transitions || []).map(toRow),@@ -148,9 +150,15 @@ export default function LoomNodeEditor({ loom, episode, node, onLoomUpdate, onClonLoomUpdate(result.loom);// The AI writes new paths straight onto the record; this panel is keyed by// node.id so it never remounts to pick them up.- const woven = result.loom?.episodes.find((e) => e.id === episode.id)- ?.nodes.find((n) => n.id === node.id)?.transitions;- if (woven) setForm((prev) => ({ ...prev, transitions: woven.map(toRow) }));+ const wovenNode = result.loom?.episodes.find((e) => e.id === episode.id)+ ?.nodes.find((n) => n.id === node.id);+ if (wovenNode) {+ setForm((prev) => ({+ ...prev,+ playbackMode: wovenNode.playbackMode || 'decision',+ transitions: (wovenNode.transitions || []).map(toRow),+ }));+ }toast.success('New branches woven');}, { errorMessage: 'Branching failed' });@@ -254,6 +262,24 @@ export default function LoomNodeEditor({ loom, episode, node, onLoomUpdate, onCl/></FormField>+ <FormField label="Playback behavior" labelClassName={labelClass}>+ <select+ className={fieldClass}+ aria-label="Playback behavior"+ value={form.playbackMode}+ onChange={(e) => {+ setForm((p) => ({ ...p, playbackMode: e.target.value }));+ patchNode({ playbackMode: e.target.value });+ }}+ >+ {FABLELOOM_PLAYBACK_MODES.map((mode) => (+ <option key={mode} value={mode}>+ {mode === 'cut' ? 'Automatic cut — play once, then advance' : 'Decision point — loop while awaiting input'}+ </option>+ ))}+ </select>+ </FormField>+<div className="flex items-center gap-3"><label className="flex items-center gap-2 text-sm" htmlFor="loom-node-ending"><input@@ -369,7 +395,7 @@ export default function LoomNodeEditor({ loom, episode, node, onLoomUpdate, onCl<div><div className="flex items-center justify-between mb-1"><span className="text-xs font-medium text-port-text-muted">- Paths out ({form.transitions.length})+ {form.playbackMode === 'cut' ? 'Next cut' : 'Viewer paths'} ({form.transitions.length})</span><div className="flex items-center gap-3"><button@@ -394,6 +420,9 @@ export default function LoomNodeEditor({ loom, episode, node, onLoomUpdate, onCl{form.isEnding && form.transitions.length > 0 && (<p className="text-xs text-port-warning mb-2">Endings never fire their outgoing paths.</p>)}+ {!form.isEnding && form.playbackMode === 'cut' && form.transitions.length !== 1 && (+ <p className="text-xs text-port-error mb-2">Automatic cuts need exactly one path to the next cut.</p>+ )}<div className="space-y-3">{form.transitions.map((tr, index) => (<div key={tr.id} className="border border-port-border rounded p-2 space-y-2">diff --git a/client/src/components/fableloom/LoomNodeEditor.test.jsx b/client/src/components/fableloom/LoomNodeEditor.test.jsxindex 39048b2b5b..984b6b7f5f 100644--- a/client/src/components/fableloom/LoomNodeEditor.test.jsx+++ b/client/src/components/fableloom/LoomNodeEditor.test.jsx@@ -15,7 +15,7 @@ vi.mock('../../services/api', () => ({vi.mock('../MediaImage', () => ({ default: () => null }));import {- addLoomTransition, deleteLoomTransition, generateVideo, updateLoomNode, updateLoomTransition,+ addLoomTransition, branchLoomNode, deleteLoomTransition, generateVideo, updateLoomNode, updateLoomTransition,} from '../../services/api';import LoomNodeEditor from './LoomNodeEditor';@@ -28,6 +28,7 @@ const makeNodes = (transitions) => ([id: 'n1', title: 'The Gate', prose: scene, image: 'scene.png',imagePrompt: 'an ancient gate', videoPrompt: 'The gate opens in one continuous shot.',cameraMovement: 'slow-dolly-in', transitions,+ playbackMode: 'decision',},{ id: 'n2', title: 'Inside', prose: 'Torchlight.', transitions: [] },]);@@ -66,7 +67,7 @@ describe('LoomNodeEditor paths', () => {'loom-1', 'ep-1', 'n1', { targetNodeId: 'n2', intent: '' }, { silent: true },);expect(onLoomUpdate).toHaveBeenCalledWith({ id: 'loom-1' });- await waitFor(() => expect(screen.getByText('Paths out (1)')).toBeInTheDocument());+ await waitFor(() => expect(screen.getByText('Viewer paths (1)')).toBeInTheDocument());// The whole-array node PATCH is not how a path is added any more.expect(updateLoomNode).not.toHaveBeenCalled();});@@ -108,7 +109,7 @@ describe('LoomNodeEditor paths', () => {await waitFor(() => expect(deleteLoomTransition).toHaveBeenCalledTimes(1));expect(deleteLoomTransition).toHaveBeenCalledWith('loom-1', 'ep-1', 'n1', 'tr-1', { silent: true });expect(onLoomUpdate).toHaveBeenCalledWith({ id: 'loom-1' });- expect(screen.getByText('Paths out (0)')).toBeInTheDocument();+ expect(screen.getByText('Viewer paths (0)')).toBeInTheDocument();});});@@ -169,4 +170,38 @@ describe('LoomNodeEditor scene media', () => {'loom-1', 'ep-1', 'n1', { cameraMovement: 'orbit-180' }, { silent: true },));});++ it('marks a scene as an automatic cut', async () => {+ const user = userEvent.setup();+ updateLoomNode.mockResolvedValue({ id: 'loom-1' });+ renderEditor();++ await user.selectOptions(screen.getByLabelText('Playback behavior'), 'cut');++ await waitFor(() => expect(updateLoomNode).toHaveBeenCalledWith(+ 'loom-1', 'ep-1', 'n1', { playbackMode: 'cut' }, { silent: true },+ ));+ });++ it('reflects the decision mode applied when AI adds branches', async () => {+ const user = userEvent.setup();+ const nodes = makeNodes([existingPath]);+ nodes[0].playbackMode = 'cut';+ branchLoomNode.mockResolvedValue({+ loom: { ...loom, episodes: [{ id: 'ep-1', nodes: [{ ...nodes[0], playbackMode: 'decision' }] }] },+ });+ render(+ <LoomNodeEditor+ loom={loom}+ episode={{ id: 'ep-1', nodes }}+ node={nodes[0]}+ onLoomUpdate={vi.fn()}+ onClearSelection={() => {}}+ />,+ );++ await user.click(screen.getByRole('button', { name: 'Branch with AI' }));++ await waitFor(() => expect(screen.getByLabelText('Playback behavior')).toHaveValue('decision'));+ });});diff --git a/client/src/components/fableloom/LoomPlayPanel.jsx b/client/src/components/fableloom/LoomPlayPanel.jsxindex 1df717de62..02c320b28c 100644--- a/client/src/components/fableloom/LoomPlayPanel.jsx+++ b/client/src/components/fableloom/LoomPlayPanel.jsx@@ -1,11 +1,10 @@/*** FableLoom play panel — the reader-side chat for one episode.*- * The reader types what they want to do; the play stage matches it against- * the current scene's intent paths and either moves them (new scene prose +- * image) or answers in-world without leaving the scene. The session lives in- * this panel's state (current scene + transcript) — restarting is free, and- * nothing persists server-side.+ * Automatic-cut nodes play once and follow their single transition. Decision+ * nodes loop their video while the reader chooses a path or types feedback.+ * Text, storyboard-image, and rendered-video previews share the same graph+ * traversal so authors can rehearse the experience at every production stage.** TAPPING a path costs nothing: the turn carries the transition id, and the* server resolves the move straight off the authored graph — same endpoint,@@ -31,12 +30,18 @@ const asPublic = (node) => (node ? {title: node.title,prose: node.prose,image: node.image,+ videoHistoryId: node.videoHistoryId,+ playbackMode: node.playbackMode || 'decision',isEnding: !!node.isEnding,endingLabel: node.endingLabel,choices: (node.transitions || []).map((t) => ({ id: t.id, intent: t.intent })),} : null);-export default function LoomPlayPanel({ loom, episode }) {+export default function LoomPlayPanel({ loom, episode: initialEpisode }) {+ const [playEpisodeId, setPlayEpisodeId] = useState(initialEpisode.id);+ const episode = loom.episodes?.find((item) => item.id === playEpisodeId) || initialEpisode;+ const episodeIndex = loom.episodes?.findIndex((item) => item.id === episode.id) ?? -1;+ const nextEpisode = episodeIndex >= 0 ? loom.episodes?.[episodeIndex + 1] : null;// Anchored on scalars so an authoring echo elsewhere in the loom (a node// PATCH, a drag) doesn't mint a new `start` identity and wipe an// in-progress read-through. The trade: mid-session edits to the opening@@ -48,10 +53,12 @@ export default function LoomPlayPanel({ loom, episode }) {const [scene, setScene] = useState(start);const [transcript, setTranscript] = useState([]);const [message, setMessage] = useState('');+ const [previewMode, setPreviewMode] = useState('text');const scrollRef = useRef(null);// Mirrors the server's terminal rule: an ending, or a dead-end scene with// no paths out, ends the read-through.const ended = !!scene && (scene.isEnding || !scene.choices?.length);+ const automaticCut = !!scene && scene.playbackMode === 'cut' && scene.choices?.length === 1;const restart = () => {setScene(start);@@ -59,6 +66,8 @@ export default function LoomPlayPanel({ loom, episode }) {setMessage('');};+ useEffect(() => { setPlayEpisodeId(initialEpisode.id); }, [initialEpisode.id]);+// An episode switch (or a changed opening scene) re-anchors the session.useEffect(() => { restart(); }, [start]);@@ -107,6 +116,11 @@ export default function LoomPlayPanel({ loom, episode }) {runTurn({ transitionId: choice.id }, history);};+ const advanceCut = () => {+ if (sending || !automaticCut) return;+ runTurn({ transitionId: scene.choices[0].id }, transcript);+ };+const send = () => {const text = message.trim();if (!text || sending || !scene) return;@@ -126,10 +140,33 @@ export default function LoomPlayPanel({ loom, episode }) {return (<div className="flex flex-col h-full">+ <div className="border-b border-port-border p-3 flex items-center justify-between gap-3">+ <div>+ <p className="text-xs font-medium">Episode {episode.number || episodeIndex + 1 || 1}: {episode.title || 'Untitled'}</p>+ <label htmlFor="loom-preview-mode" className="text-xs text-port-text-muted">Preview stage</label>+ </div>+ <select+ id="loom-preview-mode"+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs"+ value={previewMode}+ onChange={(event) => setPreviewMode(event.target.value)}+ >+ <option value="text">Text</option>+ <option value="image">Storyboard images</option>+ <option value="video">Rendered video</option>+ </select>+ </div><div ref={scrollRef} className="flex-1 overflow-y-auto p-4 space-y-4">- <SceneCard node={start} isOpening format={loom.format} />+ <SceneCard+ node={scene}+ isOpening={scene?.id === start.id}+ format={loom.format}+ previewMode={previewMode}+ onCutEnded={advanceCut}+ automaticCut={automaticCut}+ />{transcript.map((turn, i) => {- if (turn.role === 'scene') return <SceneCard key={i} node={turn.node} format={loom.format} />;+ if (turn.role === 'scene') return null;return (<div key={i} className={turn.role === 'reader' ? 'text-right' : ''}><div@@ -152,7 +189,7 @@ export default function LoomPlayPanel({ loom, episode }) {)}</div><div className="border-t border-port-border p-3 space-y-2">- {!ended && scene?.choices?.length > 0 && (+ {!ended && !automaticCut && scene?.choices?.length > 0 && (<div className="flex flex-wrap gap-1.5">{scene.choices.filter((c) => c.intent).map((c) => (<button@@ -167,7 +204,17 @@ export default function LoomPlayPanel({ loom, episode }) {))}</div>)}- <div className="flex gap-2">+ {automaticCut && (+ <button+ type="button"+ onClick={advanceCut}+ disabled={sending}+ className="w-full px-3 py-2 rounded bg-port-accent text-white text-sm disabled:opacity-50"+ >+ {sending ? 'Loading next cut…' : previewMode === 'video' && scene.videoHistoryId ? 'Video advances automatically' : 'Next cut'}+ </button>+ )}+ {!automaticCut && <div className="flex gap-2"><inputclassName="flex-1 bg-port-bg border border-port-border rounded px-3 py-2 text-sm"placeholder={ended ? 'The story has ended' : 'What do you do?'}@@ -180,10 +227,10 @@ export default function LoomPlayPanel({ loom, episode }) {{ended ? (<buttontype="button"- onClick={restart}+ onClick={() => (nextEpisode ? setPlayEpisodeId(nextEpisode.id) : restart())}className="flex items-center gap-1.5 px-3 py-2 rounded bg-port-accent/15 text-port-accent text-sm">- <RotateCcw size={14} /> Read again+ <RotateCcw size={14} /> {nextEpisode ? `Next: Episode ${nextEpisode.number || episodeIndex + 2}` : 'Play again'}</button>) : (<button@@ -196,24 +243,47 @@ export default function LoomPlayPanel({ loom, episode }) {{sending ? <Loader2 size={16} className="animate-spin" /> : <Send size={16} />}</button>)}- </div>+ </div>}</div></div>);}-function SceneCard({ node, isOpening = false, format }) {+function SceneCard({ node, isOpening = false, format, previewMode, onCutEnded, automaticCut }) {if (!node) return null;+ const showVideo = previewMode === 'video' && node.videoHistoryId;+ const showImage = previewMode === 'image' && node.image;return (<div className="border border-port-border rounded-lg overflow-hidden bg-port-card">- {node.image && (+ {showVideo && (+ <video+ key={node.videoHistoryId}+ controls+ autoPlay+ muted+ playsInline+ loop={!automaticCut && !node.isEnding}+ onEnded={automaticCut ? onCutEnded : undefined}+ src={`/data/videos/${encodeURIComponent(node.videoHistoryId)}.mp4`}+ aria-label={node.title || 'Scene video'}+ className="w-full max-h-[60vh] bg-black object-contain"+ />+ )}+ {showImage && (<MediaImage src={`/data/images/${node.image}`} alt={node.title || 'Scene'} className="w-full max-h-56 object-cover" />)}<div className="p-3"><div className="text-xs uppercase tracking-wide text-port-text-muted mb-1">{isOpening ? 'Opening' : node.isEnding ? (node.endingLabel || 'Ending') : node.title || 'Scene'}</div>- <p className={sceneProseClass(format)}>{node.prose}</p>+ {previewMode === 'text' && <p className={sceneProseClass(format)}>{node.prose}</p>}+ {previewMode === 'image' && !node.image && <p className="text-sm text-port-text-muted">No storyboard image rendered for this cut yet.</p>}+ {previewMode === 'video' && !node.videoHistoryId && <p className="text-sm text-port-text-muted">No video rendered for this cut yet.</p>}+ {!node.isEnding && (+ <p className="mt-2 text-xs text-port-text-muted">+ {automaticCut ? 'Automatic cut' : 'Decision loop — waits for viewer input'}+ </p>+ )}</div></div>);diff --git a/client/src/components/fableloom/LoomPlayPanel.test.jsx b/client/src/components/fableloom/LoomPlayPanel.test.jsxindex 98b813d254..8c578ebf4b 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 { render, screen, waitFor } from '@testing-library/react';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';vi.mock('../../services/api', () => ({ playLoomTurn: vi.fn() }));@@ -8,7 +8,7 @@ vi.mock('../MediaImage', () => ({ default: () => null }));import { playLoomTurn } from '../../services/api';import LoomPlayPanel from './LoomPlayPanel';-const loom = { id: 'loom-1', name: 'The Hollow Crown' };+const loom = { id: 'loom-1', name: 'The Hollow Crown', episodes: [] };const episode = {id: 'ep-1',startNodeId: 'n1',@@ -118,4 +118,44 @@ describe('LoomPlayPanel', () => {await waitFor(() => expect(playLoomTurn).toHaveBeenCalledTimes(1));await waitFor(() => expect(screen.getByText('Nothing comes of it.')).toBeInTheDocument());});++ it('auto-advances a rendered cut when its video ends', async () => {+ const cutEpisode = {+ id: 'ep-cut', number: 1, title: 'Pilot', startNodeId: 'cut-1', nodes: [{+ id: 'cut-1', title: 'Setup', prose: 'A door opens.', playbackMode: 'cut', videoHistoryId: 'video-1',+ transitions: [{ id: 'continue-1', targetNodeId: 'decision-1', intent: 'Continue' }],+ }, {+ id: 'decision-1', title: 'Wait', prose: 'A guard paces.', playbackMode: 'decision', transitions: [],+ }],+ };+ playLoomTurn.mockResolvedValue({+ action: 'move', narration: '', ended: true,+ node: { id: 'decision-1', title: 'Wait', prose: 'A guard paces.', playbackMode: 'decision', choices: [] },+ });+ const user = userEvent.setup();+ render(<LoomPlayPanel loom={{ ...loom, episodes: [cutEpisode] }} episode={cutEpisode} />);+ await user.selectOptions(screen.getByLabelText('Preview stage'), 'video');++ fireEvent.ended(screen.getByLabelText('Setup'));++ await waitFor(() => expect(playLoomTurn).toHaveBeenCalledWith(+ 'loom-1', 'ep-cut', expect.objectContaining({ nodeId: 'cut-1', transitionId: 'continue-1' }), { silent: true },+ ));+ await waitFor(() => expect(screen.getByText('Wait')).toBeInTheDocument());+ });++ it('loops rendered decision video while waiting for input', async () => {+ const decisionEpisode = {+ id: 'ep-loop', number: 1, title: 'Pilot', startNodeId: 'decision-1', nodes: [{+ id: 'decision-1', title: 'Guard patrol', prose: 'A guard paces.', playbackMode: 'decision', videoHistoryId: 'video-loop',+ transitions: [{ id: 'go', targetNodeId: 'end', intent: 'cross now' }],+ }, { id: 'end', title: 'Across', isEnding: true, transitions: [] }],+ };+ const user = userEvent.setup();+ render(<LoomPlayPanel loom={{ ...loom, episodes: [decisionEpisode] }} episode={decisionEpisode} />);+ await user.selectOptions(screen.getByLabelText('Preview stage'), 'video');++ expect(screen.getByLabelText('Guard patrol')).toHaveProperty('loop', true);+ expect(screen.getByRole('button', { name: 'Take path: cross now' })).toBeInTheDocument();+ });});diff --git a/client/src/components/fableloom/LoomValidationPanel.jsx b/client/src/components/fableloom/LoomValidationPanel.jsxindex 8136694c11..e1563ab796 100644--- a/client/src/components/fableloom/LoomValidationPanel.jsx+++ b/client/src/components/fableloom/LoomValidationPanel.jsx@@ -26,7 +26,7 @@ export default function LoomValidationPanel({ loom, episode, onSelectNode }) {() => [episode.startNodeId,...episode.nodes.map((n) =>- `${n.id}|${n.isEnding ? 1 : 0}|${(n.transitions || []).map((t) => `${t.targetNodeId}:${t.intent}`).join(',')}`),+ `${n.id}|${n.isEnding ? 1 : 0}|${n.playbackMode || 'decision'}|${(n.transitions || []).map((t) => `${t.targetNodeId}:${t.intent}`).join(',')}`),].join(';'),[episode.startNodeId, episode.nodes],);@@ -68,6 +68,7 @@ export default function LoomValidationPanel({ loom, episode, onSelectNode }) {<h3 className="text-sm font-semibold">Structure</h3>{structural?.stats && (<span className="text-xs text-port-text-muted">+ {structural.stats.automaticCutCount} cuts · {structural.stats.decisionCount} decisions ·{' '}{structural.stats.reachableEndingCount}/{structural.stats.endingCount} endings reachable· depth {structural.stats.maxDepth}</span>diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex dd84a12a44..af471e9ba5 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -991,14 +991,14 @@},"fableloom-weave-episode": {"name": "FableLoom — Weave Episode Graph",- "description": "Generates a complete branching-narrative episode as a directed graph of single-camera-cut nodes, choosing its own node and ending counts from the story. Consecutive coverage uses Continue paths; genuine decisions use distinct intent paths. Each node includes image, video, and camera-movement direction.",+ "description": "Generates a complete interactive-video episode as single-camera-cut nodes, choosing its own node and ending counts from the story. Automatic cuts use one Continue path; decision nodes loop while waiting on viewer intent. Each node includes image, video, and camera-movement direction.","model": "heavy","returnsJson": true,"variables": []},"fableloom-branch-node": {"name": "FableLoom — Branch a Scene",- "description": "Grows new paths out of ONE camera-cut node: each branch is a new single-shot node plus the reader intent that leads to it, including image, video, and camera-movement direction. Returns { branches[] }.",+ "description": "Turns one camera-cut node into an interactive decision and grows new intent paths from it. Each branch is a new single-shot node with playback, image, video, and camera-movement direction. Returns { branches[] }.","model": "default","returnsJson": true,"variables": []diff --git a/data.reference/prompts/stages/fableloom-branch-node.md b/data.reference/prompts/stages/fableloom-branch-node.mdindex ced7747c80..d9a34f01d9 100644--- a/data.reference/prompts/stages/fableloom-branch-node.md+++ b/data.reference/prompts/stages/fableloom-branch-node.md@@ -32,6 +32,7 @@ You are a branching-narrative designer growing new paths out of ONE scene of an- A new scene may be an ending (`isEnding: true` + `endingLabel`) when the branch naturally concludes the story; otherwise write it as one continuous camera cut that ends at a decision point (its own paths will be authored later).- Each new scene's `imagePrompt` is one sentence of concrete visual description.- Each new scene's `videoPrompt` directs one renderable clip: visible action, one primary camera movement, pace, atmosphere, and final beat. Never put a cut or angle change inside it.+- Set `playbackMode` to `cut` for a one-pass node with exactly one future Continue path, or `decision` for a seamlessly looping node that waits for viewer choice/feedback. A decision loop must depict repeatable ongoing action, not an irreversible beat.- Choose `cameraMovement` from this vocabulary (the stable id before the parentheses):{{cameraMovementCatalog}}@@ -58,6 +59,7 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c"imagePrompt": "string","videoPrompt": "string","cameraMovement": "slow-dolly-in",+ "playbackMode": "decision","isEnding": false,"endingLabel": ""}diff --git a/data.reference/prompts/stages/fableloom-feedback-episode.md b/data.reference/prompts/stages/fableloom-feedback-episode.mdindex 0bbb2ada08..ccd5cb1ed4 100644--- a/data.reference/prompts/stages/fableloom-feedback-episode.md+++ b/data.reference/prompts/stages/fableloom-feedback-episode.md@@ -25,11 +25,13 @@ The bracketed values are stable scene and path ids. They are the only records yo- Interpret the feedback as an actionable revision, not as a request for critique or an explanation.- Return only the fields that need to change. An omitted field is preserved. A present empty string intentionally clears that field.- You may revise the episode `title` and `synopsis`.-- You may revise existing scenes' `title`, complete `prose`, `imagePrompt`, `videoPrompt`, `cameraMovement`, `isEnding`, and `endingLabel`.+- You may revise existing scenes' `title`, complete `prose`, `imagePrompt`, `videoPrompt`, `cameraMovement`, `playbackMode`, `isEnding`, and `endingLabel`.- You may revise the `intent`, `triggers`, `description`, or `targetNodeId` of an existing path, using its existing path id.- Do not add or remove scenes or paths. Keep every id exactly as shown. Keep any changed `targetNodeId` pointed at an existing scene id.- A prose edit must be a complete replacement for that scene, not a summary, placeholder, or editorial note. Preserve the episode's scene format and continuity.-- Each scene is one continuous camera cut and one separately rendered video clip. A revised `videoPrompt` must contain visible action, one primary move, pace, atmosphere, and final beat—never an edit or second setup. Choose `cameraMovement` from this vocabulary:+- Each scene is one continuous camera cut and one separately rendered video clip. A revised `videoPrompt` must contain visible action, one primary move, pace, atmosphere, and final beat—never an edit or second setup.+- `playbackMode: "cut"` plays once and advances through its one Continue path. `playbackMode: "decision"` loops seamlessly while awaiting viewer choice or feedback; its action must be repeatable rather than irreversible.+- Choose `cameraMovement` from this vocabulary:{{cameraMovementCatalog}}- If the feedback asks for a new or deleted scene/path, make the closest useful edit to the existing records and leave graph membership unchanged.@@ -51,6 +53,7 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c"imagePrompt": "new image prompt, only when changed","videoPrompt": "new single-clip video prompt, only when changed","cameraMovement": "slow-dolly-in, only when changed",+ "playbackMode": "cut or decision, only when changed","isEnding": false,"endingLabel": "new ending label, only when changed","transitions": [diff --git a/data.reference/prompts/stages/fableloom-weave-episode.md b/data.reference/prompts/stages/fableloom-weave-episode.mdindex 36e7576fce..5f7b42cd31 100644--- a/data.reference/prompts/stages/fableloom-weave-episode.md+++ b/data.reference/prompts/stages/fableloom-weave-episode.md@@ -24,7 +24,9 @@ When an existing graph is present, this is a reweave: preserve its story events,- Choose the node count and ending count yourself from the story's pacing, dramatic coverage, and branching needs. Never compress multiple camera cuts into one node to hit an arbitrary count.- Each node is exactly ONE continuous shot with one primary framing and one camera movement. Split every change of angle, framing, location, time, or camera movement into another node.-- Use a single `Continue` transition for consecutive coverage inside the same narrative path. Reserve 2–4 distinct intent paths for genuine reader decisions. Endings must differ meaningfully in outcome and tone.+- Set `playbackMode: "cut"` on setup/action nodes that play once and automatically feed the next camera cut. They must have exactly one `Continue` transition.+- Set `playbackMode: "decision"` on choice or feedback nodes. Their video is designed to loop seamlessly while the experience waits for the viewer; give them 1–4 distinct intent paths. The loop must show an ongoing, repeatable situation rather than irreversible action (for example, a guard pacing a hallway while the viewer decides when to move).+- Reserve multiple paths for genuine viewer decisions. Endings must differ meaningfully in outcome and tone.- Exactly one scene is the opening (`startKey`). Every scene must be reachable from it.- Every non-ending node needs either one `Continue` path for consecutive coverage or 2–4 outgoing paths at a genuine decision. Each path gets: an `intent` (a short imperative label, ≤10 words), 2–4 `triggers` (example free-text phrasings a reader might type), and a one-sentence `description` of where it leads (spoiler-safe).- Intents on the same scene must be clearly distinguishable from each other — no two paths a reader could mean with the same sentence.@@ -55,6 +57,7 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c"imagePrompt": "string","videoPrompt": "string","cameraMovement": "slow-dolly-in",+ "playbackMode": "cut","isEnding": false,"transitions": [{ "targetKey": "s2", "intent": "string", "triggers": ["string"], "description": "string" }@@ -67,6 +70,7 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c"imagePrompt": "string","videoPrompt": "string","cameraMovement": "locked-off",+ "playbackMode": "cut","isEnding": true,"endingLabel": "string","transitions": []diff --git a/docs/features/fableloom.md b/docs/features/fableloom.mdindex aeabdeb007..d2825fda17 100644--- a/docs/features/fableloom.md+++ b/docs/features/fableloom.md@@ -1,13 +1,12 @@# FableLoom — Branching Narratives-FableLoom is the Create-section workspace for branching narratives: stories a-reader plays through by *chatting their intent* rather than picking from a-fixed menu. A loom holds one or more episodes (like a series holds episodes);-each episode is a directed graph of scene nodes with multiple endings. Every-transition out of a scene is labeled with a reader **intent** ("sneak past the-guard") plus example phrasings — at read time an LLM matches the reader's-free-text message against those intents and moves them through the graph, or-answers in-world without leaving the scene when nothing matches.+FableLoom is the Create-section workspace for interactive video narratives.+A loom progresses from a text teleplay, through storyboard stills, to rendered+video clips without changing its graph. Each node is one comic-panel-like+camera cut and one eventual video file. Automatic cuts play once and continue;+decision nodes loop while the viewer chooses a path or gives free-text+feedback. A loom holds one or more ordered episodes, and the Play surface can+rehearse the same experience at any of those three production stages.## Concepts@@ -15,9 +14,28 @@ answers in-world without leaving the scene when nothing matches.|---|---|| **Loom** | A branching-narrative story (`loom-*`): name/logline/premise, scene `format`, optional `playSettings` pin, optional `universeId` + `seriesId` links, episodes. || **Episode** | One playable graph (`ep-*`): title, synopsis (feeds generation), `startNodeId`, nodes. |-| **Scene node** | One story beat (`node-*`): prose, image prompt + rendered image, ending flag/label, transitions. |+| **Scene node** | One camera cut (`node-*`): teleplay/prose, image prompt/render, single-clip video prompt/render, camera movement, `playbackMode`, ending state, transitions. || **Transition** | An intent-labeled edge (`tr-*`): `intent`, `triggers` (example phrasings), spoiler-safe `description`, `targetNodeId`. |+## Playback contract++`playbackMode` is the explicit difference between editing a graph and playing+an interactive video:++| Mode | Graph contract | Runtime behavior | Video direction |+|---|---|---|---|+| **`cut`** | Exactly one outgoing `Continue` transition unless it is an ending. | Video plays once and follows that transition automatically. Text/image previews expose **Next cut** because they have no media duration. | One irreversible setup/action/reaction beat is fine; the clip ends where the next camera setup begins. |+| **`decision`** | One or more intent paths (or an ending). | Video loops while path chips and free-text input remain available. | The visible situation must loop seamlessly and remain unresolved: pacing, watching, waiting, searching, holding position—not an action that completes once. |++For example, `A → B → C`: A and B are automatic setup cuts. C is a decision+node showing a guard pacing a hallway in a repeatable loop while the viewer+tells the unseen character when to cross. The response resolves one of C's+transitions, playback leaves the loop, and automatic cuts can resume.++The deterministic validator rejects an automatic cut without exactly one next+path. Legacy nodes default to `decision`; an upgrade therefore never starts+auto-advancing an existing choice story without an author edit or reweave.+## Surfaces- **`/fableloom`** — index: create/delete looms, link a universe (canon +@@ -34,8 +52,12 @@ answers in-world without leaving the scene when nothing matches.reachable scenes appear in story order with their authored prose, endings,and reader paths. Unreachable scenes remain visible in a separate section,and path destinations return to the matching scene in the visual editor.-- **Play drawer** — the reader chat. Sessions are client-side state- (restart is free; nothing persists server-side).+- **Play drawer** — an interactive production preview with **Text**,+ **Storyboard images**, and **Rendered video** modes. All three traverse the+ same graph. Rendered automatic cuts advance on the video's `ended` event;+ rendered decision nodes loop. At an episode ending the player continues to+ the next ordered episode, allowing a full loom/series read-through. Sessions+ are client-side state (restart is free; nothing persists server-side).- **Story settings drawer** — scene format (plus the rewrite pass), and thenarrator's provider/model/effort pin.- **Series detail page** (`/pipeline/series/:seriesId`) — a "Branching@@ -94,14 +116,15 @@ Two properties survive that split:mid-walk can't leave the loom claiming a format half its story isn't in.Until then the run reports what remains and the drawer says to run it again.-## Playing: what costs an LLM call+## Playing: traversal and LLM cost`POST …/play` takes EITHER `message` (free text the play stage matches to apath) or `transitionId` (a path the reader named outright). The second laneresolves straight off the authored graph — no provider call, no wait — and-answers `resolvedBy: 'choice'`. Tapping a chip in the play drawer sends that-lane, so the common case of "the reader picked one of the offered paths" costs-nothing; only typed free text reaches `fableloom-play-turn`.+answers `resolvedBy: 'choice'`. Tapping a chip and automatic cut advancement+both send that cheap lane, so neither costs an LLM call. Only typed free text+at a decision loop reaches `fableloom-play-turn`. Automatic nodes do not expose+the text box: their one path is production sequencing, not a viewer decision.Which provider maps typed input is the loom's own `playSettings`(`{ providerId, model, effort }`, set in Story settings). It beats the stage@@ -113,15 +136,16 @@ in the request body beats both.| Stage | What it does ||---|---|| `fableloom-generate-series-plan` | Drafts the full series arc, ordered plot points, and side quests from the loom metadata, linked-universe canon, and episode outline. |-| `fableloom-weave-episode` | Generates a full episode graph (scenes, intents, triggers, endings) from the loom premise + episode synopsis + linked-universe canon. |-| `fableloom-branch-node` | Grows N new intent-labeled branches out of one scene. |+| `fableloom-weave-episode` | Generates or reweaves a full episode as single-camera-cut nodes. The story writer/creative director chooses node and ending counts, marks automatic cuts vs decision loops, and assigns camera/video direction. A reweave sees and preserves the existing story graph while splitting multi-cut scenes. |+| `fableloom-branch-node` | Grows N new intent-labeled single-cut branches with playback and camera direction. || `fableloom-play-turn` | Resolves one reader message: `move` through a matched transition or `stay` with in-world narration. || `fableloom-review` | Story-editor critique (intent clarity, branch coherence, ending payoff) layered over the deterministic checks. || `fableloom-reformat-scenes` | Rewrites existing scenes into the loom's other format (prose ⇄ teleplay), preserving every beat and decision point. |Deterministic graph validation (no LLM) lives in`server/lib/fableLoomGraph.js` — reachability from the opening scene, dead-ends, dangling transitions, unreachable endings, duplicate/empty intents —+ends, dangling transitions, unreachable endings, duplicate/empty intents, and+the exactly-one-next-path contract for automatic cuts —and renders in the editor's Structure panel via`GET /api/fableloom/:id/episodes/:episodeId/validate`.@@ -135,14 +159,17 @@ the node durably — even if the editor unmounted mid-render — withnewest-render-wins per node. The loom's `styleNotes` are appended to theprompt for a consistent look.-**Generate video** uses the authored scene text itself as the prompt and posts-to the shared local `/api/video-gen` queue with the same destination tag. If the-node already has a rendered image, it is sent as the video's first-frame-conditioning image; otherwise the render is text-to-video. The completion hook+**Generate video** prefers the node's dedicated single-clip `videoPrompt`, adds+the selected movement's production direction from the shared camera registry,+and falls back to scene text for legacy nodes. The registry includes dolly,+truck, pan/tilt, crane, orbit, tracking, handheld, drone, focus, roll, parallax,+body-mounted, bullet-time, hyperlapse, and locked-off setups. If the node has a+rendered image, it becomes the video's first-frame conditioning image;+otherwise the render is text-to-video. The completion hook(`server/services/fableLoomSceneVideoHook.js`) files the finished-`videoHistoryId` onto the node durably, with newest-render-wins per node. The-legacy `videoPrompt` record field remains accepted for compatibility with older-clients, but the editor no longer asks authors to maintain a duplicate prompt.+`videoHistoryId` onto the node durably, with newest-render-wins per node.+Decision videos are authored as seamless loops; automatic-cut videos land on+a final beat that hands cleanly to the next node.## Storagediff --git a/scripts/migrations/288-fableloom-scene-format.js b/scripts/migrations/288-fableloom-scene-format.jsindex 4fc053befe..90cc2d54e6 100644--- a/scripts/migrations/288-fableloom-scene-format.js+++ b/scripts/migrations/288-fableloom-scene-format.js@@ -25,8 +25,8 @@ export const ACCEPTED_OLD_MD5 = {// Post-change shipped hashes (format contract rendered from the loom record).export const NEW_SHIPPED_MD5 = {- 'fableloom-weave-episode.md': '990cdecf9e46fa049ae4aae27e3b172d',- 'fableloom-branch-node.md': 'e5005826c4577623ba362a0292741c7c',+ 'fableloom-weave-episode.md': '4c9454d1537c4ebb3becbfa04fae3ed8',+ 'fableloom-branch-node.md': 'ff5d40b3090c775fc9c1f48c2ea96bbd','fableloom-play-turn.md': 'e35ad91aae263e3adf28d1e047a46661',};diff --git a/scripts/migrations/310-fableloom-camera-cuts.js b/scripts/migrations/310-fableloom-camera-cuts.jsindex 0e79e4c883..e66b2523c6 100644--- a/scripts/migrations/310-fableloom-camera-cuts.js+++ b/scripts/migrations/310-fableloom-camera-cuts.js@@ -12,17 +12,17 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'fableloom-weave-episode.md': '990cdecf9e46fa049ae4aae27e3b172d',- 'fableloom-branch-node.md': 'e5005826c4577623ba362a0292741c7c',- 'fableloom-feedback-episode.md': '9ff21b47c4251585da9500c306d91a28',+ 'fableloom-weave-episode.md': '4c9454d1537c4ebb3becbfa04fae3ed8',+ 'fableloom-branch-node.md': 'ff5d40b3090c775fc9c1f48c2ea96bbd',+ 'fableloom-feedback-episode.md': 'd09bb405478d24c294b0c658ef365cd1',};const { applyMigration, up } = makePromptReplaceMigration({accepted: ACCEPTED_OLD_MD5,current: NEW_SHIPPED_MD5,- label: 'FableLoom camera cuts',+ label: 'FableLoom camera cuts and interactive playback',customizedHint: (filename) =>- ` Merge the one-camera-cut contract and {{cameraMovementCatalog}} from\n`+ ` Merge the one-camera-cut and playback-mode contracts plus {{cameraMovementCatalog}} from\n`+ ` data.reference/prompts/stages/${filename} into the installed template.`,});diff --git a/server/lib/README.md b/server/lib/README.mdindex 6a32e4d9a5..ff3231b1cf 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -33,6 +33,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `generationModes.js` | Shared immutable image/video render-backend alphabets (`IMAGE_GEN_MODE[S]`, `QUEUEABLE_IMAGE_MODES`, `VIDEO_GEN_MODE[S]`, and cloud subsets), kept below both validation and generation services so schemas never import orchestration modules. || `fableLoomLimits.js` | FableLoom record caps (`LOOM_LIMITS`) — the single source of truth shared by the route schemas and the record sanitizer. A leaf module, below both. || `fableLoomCameraMovements.js` | Shared FableLoom camera-movement registry for generated cut direction and the manual scene editor selector. |+| `fableLoomPlayback.js` | FableLoom node playback modes (`cut` auto-advances; `decision` loops while awaiting input), with the backward-compatible default. || `fableLoomFormats.js` | FableLoom scene formats (`LOOM_FORMATS`, `asLoomFormat`, `sceneFormatContract`, …) — how a loom writes scene text, read by validation, the sanitizer, and every generative stage. || `postDrillTypes.js` | MeatSpace POST drill vocabularies (`CACHEABLE_TYPES`, `COGNITIVE_DRILL_TYPES`), kept below validation so a route schema never pulls in the POST services (and, through them, the LLM drill generator). || `spriteVocabulary.js` | Sprite id pattern, record kinds, the canonical 8-direction order + derived anchor set, `TURNAROUND_ID`, and the animation provider ids — the alphabets the sprite route schemas enumerate, kept below the sprite services. |diff --git a/server/lib/fableLoomGraph.js b/server/lib/fableLoomGraph.jsindex c88b5c17ac..d8ad6b2089 100644--- a/server/lib/fableLoomGraph.js+++ b/server/lib/fableLoomGraph.js@@ -29,6 +29,7 @@ export const GRAPH_ISSUE_CODES = Object.freeze({DUPLICATE_INTENT: 'DUPLICATE_INTENT',ENDING_UNREACHABLE: 'ENDING_UNREACHABLE',SELF_LOOP: 'SELF_LOOP',+ CUT_TRANSITION_COUNT: 'CUT_TRANSITION_COUNT',});/**@@ -109,6 +110,14 @@ export function analyzeEpisodeGraph(episode) {if (node?.isEnding && transitions.length) {push(GRAPH_ISSUE_CODES.ENDING_WITH_TRANSITIONS, 'warning', `Ending "${label}" still has outgoing paths — they will never fire.`, { nodeId: node.id });}+ if (!node?.isEnding && node?.playbackMode === 'cut' && transitions.length !== 1) {+ push(+ GRAPH_ISSUE_CODES.CUT_TRANSITION_COUNT,+ 'error',+ `Automatic cut "${label}" must have exactly one path to the next camera cut.`,+ { nodeId: node.id },+ );+ }const seenIntents = new Set();for (const tr of transitions) {@@ -130,6 +139,8 @@ export function analyzeEpisodeGraph(episode) {const stats = {nodeCount: nodes.length,+ automaticCutCount: nodes.filter((node) => !node?.isEnding && node?.playbackMode === 'cut').length,+ decisionCount: nodes.filter((node) => !node?.isEnding && node?.playbackMode !== 'cut').length,endingCount: endings.length,reachableCount: depthById.size,reachableEndingCount: reachableEndings.length,@@ -158,10 +169,13 @@ export function describeGraphForPrompt(episode, { proseLimit = 400 } = {}) {const flags = [node.id === episode?.startNodeId ? 'START' : null,node?.isEnding ? `ENDING${isStr(node?.endingLabel) ? `: ${node.endingLabel}` : ''}` : null,+ node?.playbackMode === 'cut' ? 'AUTO CUT' : 'DECISION LOOP',].filter(Boolean);lines.push(`[${node.id}] ${node.title || 'Untitled scene'}${flags.length ? ` (${flags.join(') (')})` : ''}`);const prose = typeof node.prose === 'string' ? node.prose.trim() : '';if (prose) lines.push(prose.length > proseLimit ? `${prose.slice(0, proseLimit)}…` : prose);+ if (isStr(node.videoPrompt)) lines.push(`Video: ${node.videoPrompt}`);+ if (isStr(node.cameraMovement)) lines.push(`Camera movement: ${node.cameraMovement}`);for (const tr of asArray(node.transitions)) {const triggers = asArray(tr?.triggers).filter(isStr);lines.push(`-> [${tr?.targetNodeId}] intent "${tr?.intent || ''}"${triggers.length ? ` (triggers: ${triggers.join('; ')})` : ''}`);diff --git a/server/lib/fableLoomGraph.test.js b/server/lib/fableLoomGraph.test.jsindex 612f4eb237..05c9be0cc6 100644--- a/server/lib/fableLoomGraph.test.js+++ b/server/lib/fableLoomGraph.test.js@@ -54,6 +54,8 @@ describe('analyzeEpisodeGraph', () => {expect(issues).toEqual([]);expect(stats).toMatchObject({nodeCount: 4,+ automaticCutCount: 0,+ decisionCount: 2,endingCount: 2,reachableCount: 4,reachableEndingCount: 2,@@ -93,6 +95,22 @@ describe('analyzeEpisodeGraph', () => {expect(deadEnd).toMatchObject({ severity: 'error', nodeId: 'n4' });});+ it('requires an automatic cut to have exactly one next path', () => {+ const none = soundEpisode();+ none.nodes[0].playbackMode = 'cut';+ none.nodes[0].transitions = [];+ expect(issueCodes(none)).toContain(GRAPH_ISSUE_CODES.CUT_TRANSITION_COUNT);++ const many = soundEpisode();+ many.nodes[0].playbackMode = 'cut';+ expect(issueCodes(many)).toContain(GRAPH_ISSUE_CODES.CUT_TRANSITION_COUNT);++ const one = soundEpisode();+ one.nodes[0].playbackMode = 'cut';+ one.nodes[0].transitions = [tr('t1', 'n2', 'Continue')];+ expect(issueCodes(one)).not.toContain(GRAPH_ISSUE_CODES.CUT_TRANSITION_COUNT);+ });+it('warns on unreachable nodes and errors when no ending is reachable', () => {const ep = soundEpisode();ep.nodes.push({ id: 'n9', title: 'Orphan', transitions: [tr('t9', 'n4', 'onward')] });diff --git a/server/lib/fableLoomPlayback.js b/server/lib/fableLoomPlayback.jsnew file mode 100644index 0000000000..495e2d22b0--- /dev/null+++ b/server/lib/fableLoomPlayback.js@@ -0,0 +1,13 @@+/**+ * FableLoom node playback semantics shared by persistence, prompts, and UI.+ * Legacy nodes default to decision mode so upgrades never start auto-advancing+ * an authored choice graph without the author explicitly reweaving/editing it.+ */++export const FABLELOOM_PLAYBACK_MODES = Object.freeze(['cut', 'decision']);+export const FABLELOOM_PLAYBACK_MODE_DEFAULT = 'decision';++export const isFableLoomPlaybackMode = (value) => FABLELOOM_PLAYBACK_MODES.includes(value);+export const asFableLoomPlaybackMode = (value) => (+ isFableLoomPlaybackMode(value) ? value : FABLELOOM_PLAYBACK_MODE_DEFAULT+);diff --git a/server/lib/fableLoomPlayback.test.js b/server/lib/fableLoomPlayback.test.jsnew file mode 100644index 0000000000..f2bb4366db--- /dev/null+++ b/server/lib/fableLoomPlayback.test.js@@ -0,0 +1,15 @@+import { describe, expect, it } from 'vitest';+import {+ FABLELOOM_PLAYBACK_MODES, asFableLoomPlaybackMode, isFableLoomPlaybackMode,+} from './fableLoomPlayback.js';++describe('FableLoom playback modes', () => {+ it('recognizes the persisted vocabulary and defaults old or invalid nodes to decisions', () => {+ expect(FABLELOOM_PLAYBACK_MODES).toEqual(['cut', 'decision']);+ expect(isFableLoomPlaybackMode('cut')).toBe(true);+ expect(isFableLoomPlaybackMode('loop')).toBe(false);+ expect(asFableLoomPlaybackMode('cut')).toBe('cut');+ expect(asFableLoomPlaybackMode(undefined)).toBe('decision');+ expect(asFableLoomPlaybackMode('loop')).toBe('decision');+ });+});diff --git a/server/lib/fableLoomValidation.js b/server/lib/fableLoomValidation.jsindex fb04f261cb..46314d56b0 100644--- a/server/lib/fableLoomValidation.js+++ b/server/lib/fableLoomValidation.js@@ -8,6 +8,7 @@import { z } from 'zod';import { LOOM_LIMITS } from './fableLoomLimits.js';import { LOOM_FORMATS } from './fableLoomFormats.js';+import { FABLELOOM_PLAYBACK_MODES } from './fableLoomPlayback.js';import { llmRoutePinSchema } from './llmRoutePin.js';const name = z.string().trim().min(1).max(LOOM_LIMITS.NAME_MAX);@@ -124,6 +125,7 @@ const nodeFields = {imagePrompt: z.string().max(LOOM_LIMITS.IMAGE_PROMPT_MAX).optional(),videoPrompt: z.string().max(LOOM_LIMITS.VIDEO_PROMPT_MAX).optional(),cameraMovement: z.string().max(LOOM_LIMITS.CAMERA_MOVEMENT_MAX).optional(),+ playbackMode: z.enum(FABLELOOM_PLAYBACK_MODES).optional(),isEnding: z.boolean().optional(),endingLabel: z.string().max(LOOM_LIMITS.ENDING_LABEL_MAX).optional(),pos: z.object({ x: z.number(), y: z.number() }).nullable().optional(),diff --git a/server/lib/index.js b/server/lib/index.jsindex 63726e887f..b22d71d1c1 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -82,6 +82,7 @@ export * from './creativeLatitude.js';export * as editorial from './editorial/index.js';export * from './fableLoomGraph.js';export * from './fableLoomCameraMovements.js';+export * from './fableLoomPlayback.js';export * from './fableLoomLimits.js';export * from './fableLoomFormats.js';export * from './scenePrompt.js';diff --git a/server/services/fableLoom/README.md b/server/services/fableLoom/README.mdindex 6e9b88e11c..e1057df41e 100644--- a/server/services/fableLoom/README.md+++ b/server/services/fableLoom/README.md@@ -1,6 +1,6 @@# server/services/fableLoom-FableLoom — branching narratives. A loom holds episodes; each episode is a+FableLoom — interactive video narratives. A loom holds ordered episodes; each episode is adirected graph of scene nodes with intent-triggered transitions. Readers playan episode through a chat conversation: the play stage matches their free-textintent to a transition and moves them through the graph until an ending.@@ -8,7 +8,7 @@ intent to a transition and moves them through the graph until an ending.| Module | Purpose ||---|---|| `records.js` | Sanitizer + CRUD for looms/episodes/nodes; transitions are addressable one at a time (`addNodeTransition` / `updateNodeTransition` / `deleteNodeTransition`) as well as replaceable as a whole array via the node patch; `attachNodeImage` and `attachNodeVideo` for media-job hooks. |-| `weave.js` | AI ops via `runStagedLLM`: `generateSeriesPlan` (full arc / plot-point / side-quest scaffold), `weaveEpisode` (full graph), `branchNode` (grow paths), `feedbackEpisode` (apply a conversational sparse patch to one episode), `reviewEpisode` (critique + deterministic analysis), `playTurn` (reader intent → transition; a tapped path resolves off the graph with NO LLM call), `reformatEpisodeScenes` (rewrite ONE episode's scenes into another format; the loom's format pin lands only once every episode is converted). |+| `weave.js` | AI ops via `runStagedLLM`: `generateSeriesPlan` (full arc / plot-point / side-quest scaffold), `weaveEpisode` (single-camera-cut graph with automatic cuts and looping decisions), `branchNode` (grow paths), `feedbackEpisode` (apply a conversational sparse patch to one episode), `reviewEpisode` (critique + deterministic analysis), `playTurn` (reader intent → transition; tapped/automatic paths resolve with NO LLM call), `reformatEpisodeScenes` (rewrite ONE episode's scenes into another format; the loom's format pin lands only once every episode is converted). || `formats.js` | Scene formats (`prose` / `teleplay`) and the prompt contracts each generative stage renders for them. || `store.js` | PostgreSQL/file backend facade (`fableloom_stories`; collectionStore escape hatch for tests). || `db.js` | PostgreSQL leaf I/O. |diff --git a/server/services/fableLoom/records.js b/server/services/fableLoom/records.jsindex ca8de1da81..80d7e0123c 100644--- a/server/services/fableLoom/records.js+++ b/server/services/fableLoom/records.js@@ -27,6 +27,7 @@ import {} from './store.js';import { LOOM_LIMITS } from './limits.js';import { asLoomFormat, isLoomFormat } from './formats.js';+import { asFableLoomPlaybackMode } from '../../lib/fableLoomPlayback.js';export { LOOM_LIMITS };@@ -70,6 +71,7 @@ function sanitizeNode(raw) {imageJobId: isStr(raw.imageJobId) && raw.imageJobId ? raw.imageJobId.slice(0, 200) : null,videoPrompt: trimTo(raw.videoPrompt, LOOM_LIMITS.VIDEO_PROMPT_MAX),cameraMovement: trimTo(raw.cameraMovement, LOOM_LIMITS.CAMERA_MOVEMENT_MAX),+ playbackMode: asFableLoomPlaybackMode(raw.playbackMode),videoHistoryId: isSafeVideoHistoryId(raw.videoHistoryId) ? raw.videoHistoryId : null,isEnding: raw.isEnding === true,// The format this scene's text is actually WRITTEN in — server-set, not@@ -371,7 +373,7 @@ export function deleteEpisode(loomId, episodeId) {// --- Nodes & transitions -----------------------------------------------------const NODE_PATCH_FIELDS = ['title', 'prose', 'imagePrompt', 'videoPrompt', 'cameraMovement', 'isEnding', 'endingLabel', 'pos', 'transitions'];+const NODE_PATCH_FIELDS = ['title', 'prose', 'imagePrompt', 'videoPrompt', 'cameraMovement', 'playbackMode', 'isEnding', 'endingLabel', 'pos', 'transitions'];export function addNode(loomId, episodeId, fields = {}) {return mutateLoom(loomId, (loom) => {diff --git a/server/services/fableLoom/records.test.js b/server/services/fableLoom/records.test.jsindex addd06c7db..ab03377f5f 100644--- a/server/services/fableLoom/records.test.js+++ b/server/services/fableLoom/records.test.js@@ -91,10 +91,21 @@ describe('sanitizeLoom', () => {}] }],});expect(loom.episodes[0].nodes[0]).toMatchObject({- videoPrompt: 'A figure turns as the camera arcs.', cameraMovement: 'cinematic-arc',+ videoPrompt: 'A figure turns as the camera arcs.', cameraMovement: 'cinematic-arc', playbackMode: 'decision',});});+ it('keeps known playback modes and defaults legacy or invalid nodes to decision', () => {+ const loom = sanitizeLoom({+ id: 'loom-1', name: 'X', episodes: [{ id: 'ep-1', nodes: [+ { id: 'n1', playbackMode: 'cut' },+ { id: 'n2', playbackMode: 'unknown' },+ { id: 'n3' },+ ] }],+ });+ expect(loom.episodes[0].nodes.map((node) => node.playbackMode)).toEqual(['cut', 'decision', 'decision']);+ });+it('defaults the scene format and keeps only a known one', () => {expect(sanitizeLoom({ id: 'loom-1', name: 'X' }).format).toBe('prose');expect(sanitizeLoom({ id: 'loom-1', name: 'X', format: 'teleplay' }).format).toBe('teleplay');diff --git a/server/services/fableLoom/weave.js b/server/services/fableLoom/weave.jsindex d5f3e5b70a..211f3f0efd 100644--- a/server/services/fableLoom/weave.js+++ b/server/services/fableLoom/weave.js@@ -142,6 +142,7 @@ const generatedNodeFields = (raw) => ({imagePrompt: raw.imagePrompt,videoPrompt: raw.videoPrompt,cameraMovement: raw.cameraMovement,+ playbackMode: raw.playbackMode,isEnding: raw.isEnding === true,endingLabel: raw.endingLabel,});@@ -243,6 +244,9 @@ export async function branchNode(loomId, episodeId, nodeId, {const updated = await mutateLoom(loomId, (current) => {const ep = findEpisode(current, episodeId);const source = findNode(ep, nodeId);+ // Asking for branches turns the source into an interactive choice point.+ // This prevents an automatic cut from retaining ambiguous outgoing paths.+ source.playbackMode = 'decision';for (const branch of branches) {if (ep.nodes.length >= LOOM_LIMITS.NODES_MAX) break;const newNode = { id: `node-${randomUUID()}`, ...generatedNodeFields(branch.node), format: asLoomFormat(loom.format), transitions: [], pos: null };@@ -294,9 +298,9 @@ export async function reviewEpisode(loomId, episodeId, { providerId, model, effo// --- Feedback: apply a conversational episode edit ---------------------------const FEEDBACK_NODE_FIELDS = ['title', 'prose', 'imagePrompt', 'videoPrompt', 'cameraMovement', 'isEnding', 'endingLabel'];+const FEEDBACK_NODE_FIELDS = ['title', 'prose', 'imagePrompt', 'videoPrompt', 'cameraMovement', 'playbackMode', 'isEnding', 'endingLabel'];const FEEDBACK_TRANSITION_FIELDS = ['targetNodeId', 'intent', 'triggers', 'description'];-const FEEDBACK_STRING_NODE_FIELDS = new Set(['title', 'prose', 'imagePrompt', 'videoPrompt', 'cameraMovement', 'endingLabel']);+const FEEDBACK_STRING_NODE_FIELDS = new Set(['title', 'prose', 'imagePrompt', 'videoPrompt', 'cameraMovement', 'playbackMode', 'endingLabel']);const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);@@ -570,6 +574,8 @@ export const publicNode = (node) => ({title: node.title,prose: node.prose,image: node.image,+ videoHistoryId: node.videoHistoryId,+ playbackMode: node.playbackMode,isEnding: node.isEnding,endingLabel: node.endingLabel,choices: (node.transitions || []).map((t) => ({ id: t.id, intent: t.intent })),diff --git a/server/services/fableLoom/weave.test.js b/server/services/fableLoom/weave.test.jsindex cabbb1f668..8f0a9f0fd7 100644--- a/server/services/fableLoom/weave.test.js+++ b/server/services/fableLoom/weave.test.js@@ -143,6 +143,7 @@ describe('branchNode', () => {const ep = loom.episodes[0];expect(ep.nodes).toHaveLength(3);const source = ep.nodes.find((n) => n.id === nodeId);+ expect(source.playbackMode).toBe('decision');expect(source.transitions.map((t) => t.intent)).toEqual(['scale the wall', 'bribe the guard']);const ending = ep.nodes.find((n) => n.title === 'A Deal');expect(ending).toMatchObject({ isEnding: true, endingLabel: 'Bought passage' });