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

feat(fableloom): guide series planning and review shot continuity before production (#6332)

[._.]/9333fe9d71eb
diff --git a/.env.example b/.env.example
index beef522bb8..6c3104fb55 100644
--- a/.env.example
+++ b/.env.example
@@ -119,6 +119,9 @@ PGPASSWORD=portos
# (videoGen/reactor.js; default: 1200000 / 20 minutes) — same reasoning as
# FAL_VIDEO_TIMEOUT_MS above.
# REACTOR_VIDEO_TIMEOUT_MS=1200000
+# Optional Python executable in an environment with reactor-sdk installed.
+# Defaults to data/venvs/reactor created by npm run setup:reactor.
+# REACTOR_PYTHON_PATH=
# Maximum Antigravity image-generation runtime in milliseconds (default: 1200000 / 20 minutes)
# AGY_IMAGEGEN_TIMEOUT_MS=1200000
diff --git a/client/src/components/fableloom/LoomEditorialAutomation.jsx b/client/src/components/fableloom/LoomEditorialAutomation.jsx
index 98111b1fe1..467f3547b4 100644
--- a/client/src/components/fableloom/LoomEditorialAutomation.jsx
+++ b/client/src/components/fableloom/LoomEditorialAutomation.jsx
@@ -81,6 +81,7 @@ function FindingLink({ loom, finding }) {
/** Whole-series one-pass editor, bounded editor/reviewer autopilot, and playthrough QA. */
export default function LoomEditorialAutomation({ loom, dirty, onLoomUpdate }) {
const [route, setRoute] = useState({ providerId: '', model: '', effort: '' });
+ const [mode, setMode] = useState(() => loom.episodes.some((episode) => episode.nodes?.length) ? 'series' : 'planning');
const [maxRounds, setMaxRounds] = useState(3);
const [selfImprove, setSelfImprove] = useState(false);
const [result, setResult] = useState(null);
@@ -104,7 +105,16 @@ export default function LoomEditorialAutomation({ loom, dirty, onLoomUpdate }) {
handledTerminalRunRef.current = null;
let ignore = false;
getLoomEditorialAutopilotStatus(loom.id, { silent: true })
- .then(({ run }) => { if (!ignore && run) setAutopilotRun(run); })
+ .then(({ run }) => {
+ if (ignore || !run) return;
+ setAutopilotRun(run);
+ if (ACTIVE_STATUSES.has(run.status)) {
+ setRoute({ providerId: run.route?.providerId || '', model: run.route?.model || '', effort: run.route?.effort || '' });
+ setMode(run.mode || 'series');
+ setMaxRounds(run.maxRounds);
+ setSelfImprove(run.selfImproveEnabled === true);
+ }
+ })
.catch(() => {});
return () => { ignore = true; };
}, [loom.id]);
@@ -173,6 +183,7 @@ export default function LoomEditorialAutomation({ loom, dirty, onLoomUpdate }) {
const run = await startLoomEditorialAutopilot(loom.id, {
...routeBody,
maxRounds,
+ ...(mode === 'planning' ? { mode } : {}),
...(selfImprove ? { selfImprove: true } : {}),
}, { silent: true });
handledTerminalRunRef.current = null;
@@ -208,7 +219,7 @@ export default function LoomEditorialAutomation({ loom, dirty, onLoomUpdate }) {
? response?.passed
: shownRun?.status === 'completed' || diagnostics?.passed;
const resultHeading = passed
- ? 'Series clears the current editorial gates'
+ ? (shownRun?.mode === 'planning' ? 'Series planning is ready for scene expansion' : 'Series clears the current editorial gates')
: shownRun?.status === 'failed'
? 'Editorial automation needs attention'
: shownRun?.status === 'canceled'
@@ -229,7 +240,9 @@ export default function LoomEditorialAutomation({ loom, dirty, onLoomUpdate }) {
<BrainCircuit size={16} className="text-port-accent" /> AI editor, reviewer & playtest
</h3>
<p className="mt-1 text-xs text-port-text-muted max-w-3xl">
- One editor can evaluate and safely repair the complete series. Autopilot alternates that editor with an independent review of every enumerated gameplay path until the story passes or reaches its bounded round limit. Rejected graph patches are corrected with validator feedback before a run can fail.
+ {mode === 'planning'
+ ? 'Review the series arc and challenges, then draft and check each episode’s camera-cut outline. Resolve planning problems before writing the teleplay or generating media.'
+ : 'Evaluate and repair the complete teleplay, then independently review every enumerated gameplay path. Autopilot repeats until the story passes or reaches its round limit.'}
</p>
</div>
{shownRun ? (
@@ -241,6 +254,14 @@ export default function LoomEditorialAutomation({ loom, dirty, onLoomUpdate }) {
) : null}
</div>
+ <div>
+ <label htmlFor="fableloom-autopilot-mode" className="block text-xs text-port-text-muted mb-1">Autopilot stage</label>
+ <select id="fableloom-autopilot-mode" value={mode} onChange={(event) => setMode(event.target.value)} disabled={busy} className="w-full min-h-11 rounded border border-port-border bg-port-bg px-3 text-sm">
+ <option value="planning">Plan the series before writing scenes</option>
+ <option value="series">Edit and playtest the complete teleplay</option>
+ </select>
+ <p className="mt-1 text-xs text-port-text-muted">Planning reviews the arc first, then drafts and reviews each episode outline in order. It stops before scene expansion or media generation.</p>
+ </div>
<div className="grid gap-3 lg:grid-cols-[minmax(0,1fr)_9rem]">
<ProviderModelSelector
providers={providers}
diff --git a/client/src/components/fableloom/LoomEditorialAutomation.test.jsx b/client/src/components/fableloom/LoomEditorialAutomation.test.jsx
index d42ea044bc..06e10a425f 100644
--- a/client/src/components/fableloom/LoomEditorialAutomation.test.jsx
+++ b/client/src/components/fableloom/LoomEditorialAutomation.test.jsx
@@ -146,6 +146,37 @@ describe('LoomEditorialAutomation', () => {
expect(screen.getByText(/safely rejected 3 invalid editor responses; no invalid changes were applied/i)).toBeInTheDocument();
});
+ it('restores the active run configuration when reopening the editor', async () => {
+ api.getLoomEditorialAutopilotStatus.mockResolvedValue({ run: {
+ id: 'active-planning-run', status: 'running', mode: 'planning', maxRounds: 2, round: 1,
+ route: { providerId: 'codex', model: 'gpt-5', effort: 'low' }, selfImproveEnabled: false,
+ } });
+ renderPanel();
+ await waitFor(() => expect(screen.getByLabelText('Autopilot stage')).toHaveValue('planning'));
+ expect(screen.getByLabelText('Editorial AI route')).toHaveValue('codex');
+ expect(screen.getByLabelText('Autopilot rounds')).toHaveValue('2');
+ expect(screen.getByLabelText('Thinking effort')).toHaveValue('low');
+ expect(screen.getByText('Runs will use Codex (gpt-5) at low effort.')).toBeInTheDocument();
+ });
+
+ it('starts an unexpanded series in planning mode without claiming production approval', async () => {
+ const user = userEvent.setup();
+ const planned = { ...loom, episodes: [{ ...loom.episodes[0], nodes: [] }] };
+ api.getLoom.mockResolvedValue(planned);
+ api.startLoomEditorialAutopilot.mockResolvedValue({
+ id: 'planning-run', loomId: loom.id, mode: 'planning', status: 'completed', round: 1, maxRounds: 3,
+ message: 'Outlines are ready.', rounds: [], residualFindings: [],
+ });
+ renderPanel({ loom: planned });
+ expect(await screen.findByLabelText('Autopilot stage')).toHaveValue('planning');
+ await user.click(screen.getByRole('button', { name: 'Start editor autopilot' }));
+ await waitFor(() => expect(api.startLoomEditorialAutopilot).toHaveBeenCalledWith(
+ loom.id, { maxRounds: 3, mode: 'planning' }, { silent: true },
+ ));
+ expect(await screen.findByText('Series planning is ready for scene expansion')).toBeInTheDocument();
+ expect(screen.queryByText('Series clears the current editorial gates')).not.toBeInTheDocument();
+ });
+
it('opts a run into approval-gated FableLoom workflow diagnosis', async () => {
const user = userEvent.setup();
api.startLoomEditorialAutopilot.mockResolvedValue({
diff --git a/client/src/components/fableloom/LoomEpisodeOutline.jsx b/client/src/components/fableloom/LoomEpisodeOutline.jsx
index c6cc1006ba..01d6c32da8 100644
--- a/client/src/components/fableloom/LoomEpisodeOutline.jsx
+++ b/client/src/components/fableloom/LoomEpisodeOutline.jsx
@@ -10,6 +10,7 @@
import { useMemo } from 'react';
import { ArrowRight, ChevronRight, Flag, Play, Waypoints } from 'lucide-react';
+import LoomReferenceReview from './LoomReferenceReview';
import { sceneProseClass } from './fieldStyles';
const asArray = (value) => (Array.isArray(value) ? value : []);
@@ -63,6 +64,7 @@ function SceneBlock({ node, number, episode, format, byId, onSelectNode }) {
/>
<div className="min-w-0">
<h3 className="font-semibold text-port-text break-words">{node.title || 'Untitled scene'}</h3>
+ {node.shot && <p className="text-xs text-port-accent">{node.shot.durationSeconds}s · {node.shot.framing}</p>}
<div className="mt-1 flex flex-wrap items-center gap-2 text-[11px] text-port-text-muted">
{isStart && <span className="inline-flex items-center gap-1 text-port-accent"><Play size={11} /> Opening</span>}
{node.isEnding && (
@@ -81,10 +83,12 @@ function SceneBlock({ node, number, episode, format, byId, onSelectNode }) {
</div>
</div>
</div>
- <span className="shrink-0 text-[11px] text-port-text-muted">Scene {number}</span>
+ <span className="shrink-0 text-[11px] text-port-text-muted">{node.shot ? 'Shot' : 'Scene'} {number}</span>
</summary>
<div className="space-y-3 border-t border-port-border p-4">
+ {onSelectNode && <button type="button" className="min-h-11 text-sm text-port-accent hover:underline" aria-label={`Edit ${node.shot ? 'shot' : 'scene'}: ${node.title || 'Untitled scene'}`} onClick={() => onSelectNode(node.id)}>Edit {node.shot ? 'shot' : 'scene'}</button>}
+ <LoomReferenceReview episode={episode} node={node} onSelectNode={onSelectNode} />
{node.prose?.trim() ? (
<div className={`${sceneProseClass(format)} text-port-text`}>
{node.prose}
@@ -170,6 +174,16 @@ export default function LoomEpisodeOutline({ loom, episode, onSelectNode }) {
const { reachable, unreachable, byId } = useMemo(() => orderEpisodeNodes(episode), [episode]);
const nodes = asArray(episode?.nodes);
const endingCount = nodes.filter((node) => node.isEnding).length;
+ const shotGroups = useMemo(() => {
+ if (!reachable.length || reachable.some((node) => !node.shot)) return null;
+ const groups = new Map();
+ for (const node of reachable) {
+ const key = node.shot.dramaticSceneId;
+ if (!groups.has(key)) groups.set(key, { id: key, title: node.shot.dramaticSceneTitle, nodes: [] });
+ groups.get(key).nodes.push(node);
+ }
+ return [...groups.values()];
+ }, [reachable]);
const numberedNodes = useMemo(() => {
const numbers = new Map();
[...reachable, ...unreachable].forEach((node, index) => numbers.set(node.id, index + 1));
@@ -205,30 +219,29 @@ export default function LoomEpisodeOutline({ loom, episode, onSelectNode }) {
<h2 className="mt-1 text-xl font-semibold">{episode.title || 'Untitled episode'}</h2>
</div>
<span className="shrink-0 text-xs text-port-text-muted">
- {nodes.length} scene{nodes.length === 1 ? '' : 's'} · {endingCount} ending{endingCount === 1 ? '' : 's'}
+ {nodes.length} {shotGroups ? 'shot' : 'scene'}{nodes.length === 1 ? '' : 's'} · {endingCount} ending{endingCount === 1 ? '' : 's'}
</span>
</div>
- {episode.synopsis && <p className="mt-2 max-w-3xl text-sm text-port-text-muted">{episode.synopsis}</p>}
+ {episode.synopsis && <details className="mt-2 text-sm text-port-text-muted" open={shotGroups ? undefined : true}><summary className="cursor-pointer">Episode synopsis</summary><p className="mt-2 max-w-3xl">{episode.synopsis}</p></details>}
</header>
- {episode.storyOutline?.scenes?.length ? <BeatOutline outline={episode.storyOutline} /> : null}
+ {!shotGroups && episode.storyOutline?.scenes?.length ? <BeatOutline outline={episode.storyOutline} /> : null}
{reachable.length || unreachable.length ? (
<>
- <p className="text-xs uppercase tracking-wide text-port-text-muted">Expanded teleplay scenes</p>
- <ol className="space-y-4 border-l border-port-border pl-0">
- {reachable.map((node) => (
- <SceneBlock
- key={node.id}
- node={node}
- number={numberedNodes.get(node.id)}
- episode={episode}
- format={loom.format}
- byId={numberedById}
- onSelectNode={onSelectNode}
- />
- ))}
- </ol>
+ <p className="text-xs uppercase tracking-wide text-port-text-muted">{shotGroups ? `${shotGroups.length} dramatic scenes · ${reachable.length} camera shots` : 'Expanded teleplay scenes'}</p>
+ {shotGroups ? <div className="space-y-2">{shotGroups.map((group) => (
+ <details key={group.id} className="rounded-lg border border-port-border bg-port-card p-2">
+ <summary className="cursor-pointer min-h-11 font-semibold text-sm">{group.title} · {group.nodes.length} shots · {group.nodes.reduce((seconds, node) => seconds + node.shot.durationSeconds, 0)}s</summary>
+ <ol className="space-y-3 mt-3">
+ {group.nodes.map((node) => <SceneBlock key={node.id} node={node} number={numberedNodes.get(node.id)} episode={episode} format={loom.format} byId={numberedById} onSelectNode={onSelectNode} />)}
+ </ol>
+ </details>
+ ))}</div> : (
+ <ol className="space-y-4 border-l border-port-border pl-0">
+ {reachable.map((node) => <SceneBlock key={node.id} node={node} number={numberedNodes.get(node.id)} episode={episode} format={loom.format} byId={numberedById} onSelectNode={onSelectNode} />)}
+ </ol>
+ )}
</>
) : (
<p className="rounded border border-port-border p-4 text-sm text-port-text-muted">No teleplay scenes yet. Expand the validated beat outline from Episode setup.</p>
diff --git a/client/src/components/fableloom/LoomEpisodeOutline.test.jsx b/client/src/components/fableloom/LoomEpisodeOutline.test.jsx
index 24f7dbd990..41db77d4f2 100644
--- a/client/src/components/fableloom/LoomEpisodeOutline.test.jsx
+++ b/client/src/components/fableloom/LoomEpisodeOutline.test.jsx
@@ -50,6 +50,8 @@ describe('LoomEpisodeOutline', () => {
const firstScene = screen.getByTestId('outline-scene-node-1');
await user.click(firstScene.querySelector('summary'));
+ await user.click(screen.getByRole('button', { name: 'Edit scene: Threshold' }));
+ expect(onSelectNode).toHaveBeenLastCalledWith('node-1');
await user.click(screen.getByRole('button', { name: /Scene 2: The Chamber/ }));
expect(onSelectNode).toHaveBeenCalledWith('node-2');
});
@@ -75,6 +77,18 @@ describe('LoomEpisodeOutline', () => {
expect(screen.getAllByText('Protagonist off-screen · side-device')).toHaveLength(3);
});
+ it('groups persisted cuts under their dramatic scene without repeating the expanded script as beats', async () => {
+ const timed = { ...episode, nodes: episode.nodes.slice(0, 2).map((node) => ({ ...node, shot: { dramaticSceneId: 'dramatic-1', dramaticSceneTitle: 'The encounter', durationSeconds: 8, framing: 'Close-up' } })), storyOutline: { scenes: [{ key: 'beat', title: 'Duplicate script', summary: 'Do not repeat this.' }] } };
+ render(<LoomEpisodeOutline loom={{ name: 'Example Loom' }} episode={timed} />);
+ expect(screen.getByText('1 dramatic scenes · 2 camera shots')).toBeInTheDocument();
+ expect(screen.queryByText('Duplicate script')).not.toBeInTheDocument();
+ const group = screen.getByText('The encounter · 2 shots · 16s');
+ expect(group.closest('details')).not.toHaveAttribute('open');
+ await userEvent.click(group);
+ expect(group.closest('details')).toHaveAttribute('open');
+ expect(screen.getAllByText('8s · Close-up')).toHaveLength(2);
+ });
+
it('explains when an episode has no scenes', () => {
render(<LoomEpisodeOutline loom={{ name: 'Example Loom', format: 'prose' }} episode={{ ...episode, nodes: [], startNodeId: null }} />);
diff --git a/client/src/components/fableloom/LoomEpisodeOutlinePlanner.jsx b/client/src/components/fableloom/LoomEpisodeOutlinePlanner.jsx
index b470a15c57..537407697f 100644
--- a/client/src/components/fableloom/LoomEpisodeOutlinePlanner.jsx
+++ b/client/src/components/fableloom/LoomEpisodeOutlinePlanner.jsx
@@ -1,3 +1,4 @@
+import LoomShotPlanner from './LoomShotPlanner';
import { useEffect, useMemo, useState } from 'react';
import { AlertTriangle, CheckCircle2, ChevronDown, ChevronUp, CircleAlert, Loader2, Save, Sparkles, Trash2 } from 'lucide-react';
import ProviderModelSelector from '../ProviderModelSelector';
@@ -240,6 +241,7 @@ export default function LoomEpisodeOutlinePlanner({
const [dirty, setDirty] = useState(false);
const [validation, setValidation] = useState(null);
const [review, setReview] = useState(null);
+ const [shotPlanning, setShotPlanning] = useState(false);
const [expandedKey, setExpandedKey] = useState(null);
const [route, setRoute] = useState({ providerId: '', model: '', effort: '' });
const generateRun = useFableLoomAiRun();
@@ -268,7 +270,7 @@ export default function LoomEpisodeOutlinePlanner({
const outlineStatus = validation?.stats
? (validation.stats.errorCount ? 'invalid' : 'valid')
: outline?.validation?.status || 'draft';
- const busy = disabled || providersLoading || generateRun.run?.phase === 'running' || reviewRun.run?.phase === 'running';
+ const busy = shotPlanning || disabled || providersLoading || generateRun.run?.phase === 'running' || reviewRun.run?.phase === 'running';
const hasScenes = episode.nodes.length > 0;
const activeValidation = validation || outline?.validation;
const activeValidationIssues = asArray(activeValidation?.issues);
@@ -378,7 +380,7 @@ export default function LoomEpisodeOutlinePlanner({
emptyModelOption="Default model"
alwaysShowModel={!!route.providerId}
/>
- {selectedProvider ? <p className="text-xs text-port-text-muted">Uses {selectedProvider.name}{effectiveModelFor(selectedProvider, route.model) ? ` (${effectiveModelFor(selectedProvider, route.model)})` : ''} for outline actions.</p> : null}
+ {selectedProvider ? <p className="text-xs text-port-text-muted">Uses {selectedProvider.name}{effectiveModelFor(selectedProvider, route.model) ? ` (${effectiveModelFor(selectedProvider, route.model)})` : ''}{route.effort ? ` at ${route.effort} effort` : ''} for outline and expansion actions.</p> : null}
{!outline ? (
<button
@@ -440,7 +442,7 @@ export default function LoomEpisodeOutlinePlanner({
{onExpand ? (
<button
type="button"
- onClick={onExpand}
+ onClick={() => onExpand(routeBody)}
disabled={busy || dirty || !canExpand || saving || generating || validating || reviewing || expanding}
className="flex w-full items-center justify-center gap-2 rounded bg-port-accent px-3 py-2 text-sm text-white disabled:opacity-50"
>
@@ -468,6 +470,7 @@ export default function LoomEpisodeOutlinePlanner({
) : null}
</>
)}
+ <LoomShotPlanner onRunningChange={setShotPlanning} key={episode.id} loom={loom} episode={episode} route={routeBody} guidance={guidance} disabled={busy || dirty || generating || saving || validating || reviewing || expanding} onLoomUpdate={(next) => { onLoomUpdate(next); setOutline(cloneOutline(next.episodes.find((item) => item.id === episode.id)?.storyOutline)); setValidation(null); }} />
<LoomAiRunStatus run={generateRun.run} />
<LoomAiRunStatus run={reviewRun.run} />
</section>
diff --git a/client/src/components/fableloom/LoomEpisodeOutlinePlanner.test.jsx b/client/src/components/fableloom/LoomEpisodeOutlinePlanner.test.jsx
index c450d10dce..583733ce62 100644
--- a/client/src/components/fableloom/LoomEpisodeOutlinePlanner.test.jsx
+++ b/client/src/components/fableloom/LoomEpisodeOutlinePlanner.test.jsx
@@ -8,10 +8,12 @@ vi.mock('../../hooks/useProviderModels', () => ({ default: () => ({ providers: [
vi.mock('../../hooks/useFableLoomAiRun', () => ({
default: () => ({ run: null, begin: () => '00000000-0000-4000-8000-000000000001', fail: vi.fn() }),
}));
-vi.mock('../ProviderModelSelector', () => ({ default: () => <div data-testid="outline-route">Outline AI route</div> }));
+vi.mock('../ProviderModelSelector', () => ({ default: ({ onProviderChange, onModelChange, onEffortChange }) => <button type="button" onClick={() => { onProviderChange('writer'); onModelChange('example-model'); onEffortChange('low'); }}>Select outline route</button> }));
vi.mock('../../services/api', () => ({
generateLoomEpisodeOutline: vi.fn(),
+ planLoomEpisodeShots: vi.fn(),
+ applyLoomEpisodeShots: vi.fn(),
reviewLoomEpisodeOutline: vi.fn(),
updateLoomEpisode: vi.fn(),
validateLoomEpisodeOutline: vi.fn(),
@@ -49,8 +51,9 @@ describe('LoomEpisodeOutlinePlanner', () => {
expect(screen.getByText('Signal')).toBeInTheDocument();
const expand = screen.getByRole('button', { name: 'Expand validated outline to teleplay' });
expect(expand).toBeEnabled();
+ await user.click(screen.getByRole('button', { name: 'Select outline route' }));
await user.click(expand);
- expect(onExpand).toHaveBeenCalledTimes(1);
+ expect(onExpand).toHaveBeenCalledWith({ providerId: 'writer', model: 'example-model', effort: 'low' });
});
it('saves edited log-lines before the deterministic validation request', async () => {
@@ -153,3 +156,15 @@ describe('LoomEpisodeOutlinePlanner', () => {
));
});
});
+
+it('blocks competing outline work until shot planning settles', async () => {
+ let finish;
+ api.planLoomEpisodeShots.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
+ render(<LoomEpisodeOutlinePlanner open loom={loom} episode={{ ...episode, nodes: [{ id: 'scene-1' }] }} onLoomUpdate={vi.fn()} onExpand={vi.fn()} />);
+ await userEvent.click(screen.getByRole('button', { name: 'Preview shot split' }));
+ expect(screen.getByRole('button', { name: 'Refresh with AI' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Validate outline' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Expand validated outline to teleplay' })).toBeDisabled();
+ finish({ review: { summary: 'Ready.' }, groups: [] });
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Expand validated outline to teleplay' })).toBeEnabled());
+});
diff --git a/client/src/components/fableloom/LoomNodeEditor.jsx b/client/src/components/fableloom/LoomNodeEditor.jsx
index 0179ad5ebc..61473f50c1 100644
--- a/client/src/components/fableloom/LoomNodeEditor.jsx
+++ b/client/src/components/fableloom/LoomNodeEditor.jsx
@@ -12,6 +12,7 @@
* gate on in-flight saves per the client save-gating convention.
*/
+import { estimatedShotSeconds } from '../../../../server/lib/fableLoomShots.js';
import { useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router';
import { GitBranch, Loader2, Trash2 } from 'lucide-react';
@@ -27,6 +28,8 @@ import {
import { fieldClass, labelClass, sceneFieldClass } from './fieldStyles';
import { isTeleplayFormat } from './loomFormats';
import LoomSceneMedia from './LoomSceneMedia';
+import LoomReferenceReview from './LoomReferenceReview';
+import GalleryImagePicker from '../imageGen/GalleryImagePicker';
import { FABLELOOM_CAMERA_MOVEMENTS } from '../../../../server/lib/fableLoomCameraMovements.js';
import {
FABLELOOM_HOLD_ROTATION_MODES,
@@ -73,6 +76,7 @@ export default function LoomNodeEditor({
generationDisabled = false, generationDisabledReason = '',
}) {
const [form, setForm] = useState(null);
+ const [referenceCharacterId, setReferenceCharacterId] = useState(null);
// In-flight blur-saves; the AI buttons (which read server-side state) stay
// disabled until every pending save settles.
const [pendingSaves, setPendingSaves] = useState(0);
@@ -90,6 +94,7 @@ export default function LoomNodeEditor({
useEffect(() => {
setForm({
title: node.title || '',
+ shot: node.shot || null,
prose: node.prose || '',
imagePrompt: node.imagePrompt || '',
videoPrompt: node.videoPrompt || '',
@@ -403,6 +408,14 @@ export default function LoomNodeEditor({
/>
</FormField>
+ {form.shot ? <div className="rounded border border-port-border p-3 space-y-2">
+ <p className="text-xs text-port-text-muted">Dramatic scene: {form.shot.dramaticSceneTitle}</p>
+ <label htmlFor="loom-shot-seconds" className="block text-xs">Shot duration (seconds)</label>
+ <input id="loom-shot-seconds" type="number" min={5} max={10} step={1} className={fieldClass} value={form.shot.durationSeconds} onChange={(event) => setForm((current) => ({ ...current, shot: { ...current.shot, durationSeconds: Number(event.target.value) } }))} onBlur={() => saveField('shot', form.shot)} />
+ <p className="text-xs">{form.shot.framing}</p>
+ <p className={`text-xs ${estimatedShotSeconds(form.prose) > form.shot.durationSeconds ? 'text-port-error' : 'text-port-text-muted'}`}>Estimated dialogue + pause: {estimatedShotSeconds(form.prose)}s. {estimatedShotSeconds(form.prose) > form.shot.durationSeconds ? 'Split or shorten before rendering.' : 'Timing estimate; validate the final voice delivery.'}</p>
+ </div> : null}
+
<FormField label={teleplay ? 'Scene (teleplay)' : 'Scene prose'} labelClassName={labelClass}>
<textarea
rows={teleplay ? 12 : 7}
@@ -693,6 +706,19 @@ export default function LoomNodeEditor({
</div>
</div>
+ <LoomReferenceReview episode={episode} node={{ ...node, shot: form.shot, visualCanon: form.visualCanon }} />
+ {form.visualCanon && node.image && (
+ <label className="flex items-center gap-2 text-xs" htmlFor="loom-node-storyboard-approved">
+ <input
+ id="loom-node-storyboard-approved"
+ aria-label="Approve storyboard image for video"
+ type="checkbox"
+ checked={form.visualCanon.storyboardImageApproved === true}
+ onChange={(event) => updateVisualCanon({ storyboardImageApproved: event.target.checked })}
+ />
+ Approve the current storyboard image as this shot's video first frame
+ </label>
+ )}
<div>
<span className="mb-1 block text-xs font-medium text-port-text-muted">Scene media</span>
<LoomSceneMedia
@@ -828,6 +854,12 @@ export default function LoomNodeEditor({
{appearance && canonicalWardrobeLocked && (
<p className="text-[11px] text-port-accent">Locked to the loom&apos;s canonical protagonist wardrobe.</p>
)}
+ {appearance && form.visualCanon.mode === 'draft' && (
+ <div className="flex items-center gap-2 text-xs">
+ {appearance.referenceImage && <img src={`/data/images/${appearance.referenceImage}`} alt={`${character.name} draft reference`} className="h-14 w-14 rounded object-cover" />}
+ <button type="button" className="min-h-11 text-port-accent hover:underline" onClick={() => setReferenceCharacterId(character.id)}>Choose draft character reference</button>
+ </div>
+ )}
{appearance && (
<div className="grid gap-2 sm:grid-cols-2">
<input
@@ -868,6 +900,11 @@ export default function LoomNodeEditor({
);
})}
</fieldset>
+ <GalleryImagePicker open={Boolean(referenceCharacterId)} onClose={() => setReferenceCharacterId(null)} onSelect={(image) => {
+ const visualCanon = { ...form.visualCanon, characterAppearances: form.visualCanon.characterAppearances.map((appearance) => appearance.characterId === referenceCharacterId ? { ...appearance, referenceImage: image.filename } : appearance) };
+ setForm((current) => ({ ...current, visualCanon }));
+ patchNode({ visualCanon });
+ }} />
<FormField label="Location" labelClassName={labelClass}>
<select
@@ -928,18 +965,7 @@ export default function LoomNodeEditor({
/>
</FormField>
- {node.image && (
- <label className="flex items-center gap-2 text-xs" htmlFor="loom-node-storyboard-approved">
- <input
- id="loom-node-storyboard-approved"
- aria-label="Approve storyboard image for video"
- type="checkbox"
- checked={form.visualCanon.storyboardImageApproved === true}
- onChange={(event) => updateVisualCanon({ storyboardImageApproved: event.target.checked })}
- />
- Approve the current storyboard image as this shot's video first frame
- </label>
- )}
+
</div>
)}
</div>
diff --git a/client/src/components/fableloom/LoomPlayPanel.jsx b/client/src/components/fableloom/LoomPlayPanel.jsx
index 697980669b..f63ad818b4 100644
--- a/client/src/components/fableloom/LoomPlayPanel.jsx
+++ b/client/src/components/fableloom/LoomPlayPanel.jsx
@@ -759,7 +759,9 @@ function SceneScriptCard({
)}
{!node.isEnding && node.protagonistPresence === 'offscreen' && (
<p className="mt-1 text-xs text-port-accent">
- Protagonist off-screen — keep this decision loop running while the audience conversation happens on the side device.
+ {automaticCut
+ ? 'Protagonist off-screen during this camera cut.'
+ : 'Protagonist off-screen — keep this decision loop running while the audience conversation happens on the side device.'}
</p>
)}
</article>
diff --git a/client/src/components/fableloom/LoomReferenceReview.jsx b/client/src/components/fableloom/LoomReferenceReview.jsx
new file mode 100644
index 0000000000..eea3ed92d0
--- /dev/null
+++ b/client/src/components/fableloom/LoomReferenceReview.jsx
@@ -0,0 +1,36 @@
+import MediaImage from '../MediaImage';
+
+function ReferenceFrame({ node, label, onSelectNode, paired = false }) {
+ return <figure className={paired ? "min-w-0 grid gap-2 sm:row-span-4 sm:grid-rows-subgrid" : "min-w-0 space-y-2"}>
+ <figcaption className="text-xs font-medium">
+ {label}: {node.title || 'Untitled shot'}
+ {onSelectNode && <button type="button" className="ml-2 min-h-11 text-port-accent hover:underline" onClick={() => onSelectNode(node.id)} aria-label={`Edit reference shot: ${node.title || 'Untitled shot'}`}>Edit shot</button>}
+ </figcaption>
+ {node.image
+ ? <a href={`/data/images/${encodeURIComponent(node.image)}`} target="_blank" rel="noreferrer" aria-label={`Open full reference: ${node.title || 'Untitled shot'}`} className="block rounded border border-port-border overflow-hidden">
+ <MediaImage src={`/data/images/${encodeURIComponent(node.image)}`} alt={`${label}: ${node.title || 'Untitled shot'}`} className="aspect-video w-full object-contain bg-port-bg" />
+ </a>
+ : <div className="aspect-video grid place-items-center rounded border border-dashed border-port-border p-3 text-xs text-port-text-muted">No reference image yet</div>}
+ <p className="text-xs text-port-text-muted">{node.shot?.framing || 'Framing not specified'}{node.shot?.durationSeconds ? ` · ${node.shot.durationSeconds}s` : ''}</p>
+ {node.visualCanon?.shotNotes && <p className="text-xs whitespace-pre-wrap">Continuity: {node.visualCanon.shotNotes}</p>}
+ </figure>;
+}
+
+/** Compare actual incoming graph shots, including every path at a branch merge. */
+export default function LoomReferenceReview({ episode, node, onSelectNode }) {
+ const predecessors = (episode.nodes || []).filter((candidate) => candidate.id !== node.id
+ && !candidate.isEnding && candidate.transitions?.some((transition) => transition.targetNodeId === node.id));
+ const preferred = node.visualCanon?.continuitySourceNodeId;
+ return <section className="rounded border border-port-accent/30 p-3 space-y-3" aria-label={`Reference image review: ${node.title || 'Untitled shot'}`}>
+ <h4 className="text-sm font-semibold">Review images before video</h4>
+ <p className="text-xs text-port-text-muted">Compare camera angle, room layout, lighting, wardrobe, and props across the cut. Open either image at full size to inspect details.</p>
+ {predecessors.length > 1 && <p className="text-xs text-port-warning">This shot follows {predecessors.length} incoming paths. Check continuity from each one.</p>}
+ {predecessors.length ? predecessors.map((previous) => <div key={previous.id} className="grid grid-cols-1 sm:grid-cols-2 gap-3 border-t border-port-border pt-3">
+ <ReferenceFrame paired node={previous} label={previous.id === preferred ? 'Previous · chosen continuity source' : 'Previous'} onSelectNode={onSelectNode} />
+ <ReferenceFrame paired node={node} label="Current" />
+ </div>) : <>
+ <p className="text-xs text-port-text-muted">{episode.startNodeId === node.id ? 'Opening shot — establishes the visual setting.' : 'No incoming graph shot to compare.'}</p>
+ <ReferenceFrame node={node} label="Current" />
+ </>}
+ </section>;
+}
diff --git a/client/src/components/fableloom/LoomReferenceReview.test.jsx b/client/src/components/fableloom/LoomReferenceReview.test.jsx
new file mode 100644
index 0000000000..3641f76ede
--- /dev/null
+++ b/client/src/components/fableloom/LoomReferenceReview.test.jsx
@@ -0,0 +1,33 @@
+import { render, screen, within } from '@testing-library/react';
+import { expect, it, vi } from 'vitest';
+import userEvent from '@testing-library/user-event';
+import LoomReferenceReview from './LoomReferenceReview';
+vi.mock('../MediaImage', () => ({ default: (props) => <img {...props} alt={props.alt} /> }));
+
+it('compares graph predecessors rather than array neighbors and includes each converging path', async () => {
+ const current = { id: 'current', title: 'Meeting', image: 'meeting.png', shot: { framing: 'Reverse close-up', durationSeconds: 8 }, visualCanon: { continuitySourceNodeId: 'left', shotNotes: 'Keep the window behind the desk.' } };
+ const episode = { nodes: [
+ { id: 'unrelated', title: 'Elsewhere', image: 'elsewhere.png' },
+ current,
+ { id: 'right', title: 'Right path', image: 'right.png', transitions: [{ targetNodeId: 'current' }] },
+ { id: 'left', title: 'Left path', image: 'left.png', transitions: [{ targetNodeId: 'current' }] },
+ ] };
+ const onSelectNode = vi.fn();
+ render(<LoomReferenceReview episode={episode} node={current} onSelectNode={onSelectNode} />);
+ expect(screen.queryByText(/Elsewhere/)).not.toBeInTheDocument();
+ expect(screen.getByText(/2 incoming paths/)).toBeInTheDocument();
+ expect(screen.getByAltText('Previous · chosen continuity source: Left path')).toHaveAttribute('src', '/data/images/left.png');
+ expect(screen.getAllByAltText('Current: Meeting')).toHaveLength(2);
+ expect(screen.getAllByText('Reverse close-up · 8s')).toHaveLength(2);
+ expect(screen.getAllByText('Continuity: Keep the window behind the desk.')).toHaveLength(2);
+ await userEvent.click(screen.getByRole('button', { name: 'Edit reference shot: Left path' }));
+ expect(onSelectNode).toHaveBeenCalledWith('left');
+});
+
+it('shows missing images explicitly and an opening without a fabricated previous shot', () => {
+ const opening = { id: 'opening', title: 'Arrival' };
+ render(<LoomReferenceReview episode={{ startNodeId: opening.id, nodes: [opening] }} node={opening} />);
+ expect(screen.getByText('Opening shot — establishes the visual setting.')).toBeInTheDocument();
+ expect(screen.getByText('No reference image yet')).toBeInTheDocument();
+ expect(within(screen.getByRole('region')).queryByRole('link')).not.toBeInTheDocument();
+});
diff --git a/client/src/components/fableloom/LoomSeriesPlan.jsx b/client/src/components/fableloom/LoomSeriesPlan.jsx
index 30103926c4..551b40b8a0 100644
--- a/client/src/components/fableloom/LoomSeriesPlan.jsx
+++ b/client/src/components/fableloom/LoomSeriesPlan.jsx
@@ -5,7 +5,9 @@
*/
import { useCallback, useEffect, useRef, useState } from 'react';
-import { Link, useSearchParams } from 'react-router';
+import { Link } from 'react-router';
+import TabPills from '../ui/TabPills';
+import useDrawerTab from '../../hooks/useDrawerTab';
import { BrainCircuit, CheckCircle2, ChevronDown, ChevronUp, Loader2, Plus, Save, Sparkles, Trash2 } from 'lucide-react';
import ConfirmButtonPair from '../ui/ConfirmButtonPair';
import toast from '../ui/Toast';
@@ -28,6 +30,15 @@ import LoomAiRunStatus from './LoomAiRunStatus';
import LoomEditorialAutomation from './LoomEditorialAutomation';
import { fableLoomPlotPointKind } from '../../../../server/lib/fableLoomOutline.js';
+const PLAN_SECTIONS = [
+ { id: 'arc', label: 'Story arc' },
+ { id: 'challenges', label: 'Plot & challenges' },
+ { id: 'quests', label: 'Side quests' },
+ { id: 'episodes', label: 'Episode outlines' },
+ { id: 'editorial', label: 'AI editor' },
+ { id: 'handoffs', label: 'Viewer handoffs' },
+];
+
const newItemId = (prefix) => `${prefix}-${uuidv4()}`;
const CHALLENGE_DESCRIPTION_TEMPLATE = 'SETUP: Establish the blockade and plant the clue. VIEWER DECISION LOOP: Offer 2–4 actionable options with escalating feedback. SUCCESS: Advance with an earned advantage. FAILURE: Continue with a visible cost. RECOVERY / PAYOFF: Converge without erasing the choice.';
@@ -67,8 +78,8 @@ const withVoicemailDrafts = (plan, episodes) => {
};
export default function LoomSeriesPlan({ loom, onLoomUpdate }) {
- const [searchParams] = useSearchParams();
- const requestedSection = searchParams.get('section');
+ const [requestedSection, setSection] = useDrawerTab('section', 'arc', PLAN_SECTIONS.map(({ id }) => id));
+ const contentRef = useRef(null);
const [plan, setPlan] = useState(() => normalizePlan(loom.seriesPlan));
const [dirty, setDirty] = useState(false);
const revisionRef = useRef(0);
@@ -77,20 +88,8 @@ export default function LoomSeriesPlan({ loom, onLoomUpdate }) {
const routeGuard = useUnsavedChangesGuard(dirty);
useEffect(() => {
- const targetId = {
- arc: 'fableloom-plan-arc',
- challenges: 'fableloom-plan-challenges',
- editorial: 'fableloom-plan-editorial',
- handoffs: 'fableloom-plan-handoffs',
- }[requestedSection];
- if (!targetId) return undefined;
- const frame = requestAnimationFrame(() => {
- const target = document.getElementById(targetId);
- target?.scrollIntoView?.({ behavior: 'smooth', block: 'start' });
- target?.focus?.({ preventScroll: true });
- });
- return () => cancelAnimationFrame(frame);
- }, [loom.id, requestedSection]);
+ contentRef.current?.scrollTo?.({ top: 0 });
+ }, [requestedSection]);
useEffect(() => {
if (loomIdRef.current !== loom.id) {
@@ -166,7 +165,7 @@ export default function LoomSeriesPlan({ loom, onLoomUpdate }) {
};
return (
- <section className="flex-1 overflow-y-auto p-4 md:p-6" aria-label="Series plan">
+ <section className="flex min-h-0 flex-1 flex-col" aria-label="Series plan">
<UnsavedChangesConfirm
guard={routeGuard}
when={!saving}
@@ -174,103 +173,85 @@ export default function LoomSeriesPlan({ loom, onLoomUpdate }) {
label={`Discard unsaved changes to ${loom.name}`}
onDiscard={discardAndExit}
/>
- <div className="max-w-7xl mx-auto">
- <div className="flex flex-col lg:flex-row items-start gap-6">
- <div className="flex-1 min-w-0 w-full space-y-6">
- <div>
- <h2 className="text-lg font-semibold">Series plan</h2>
- <p className="text-sm text-port-text-muted mt-1">
- Shape the full narrative before working inside individual episode graphs.
- </p>
- </div>
-
- <div id="fableloom-plan-arc" tabIndex={-1} className="rounded-lg border border-port-border bg-port-card p-4 focus:outline-none">
- <FormField
- label="Story arc"
- hint="The beginning-to-end dramatic movement, central conflict, and intended resolution."
- labelClassName={labelClass}
- >
- <textarea
- rows={7}
- className={fieldClass}
- value={plan.storyArc}
- placeholder="What changes across the series, why it matters, and where the story lands…"
- onChange={(event) => changePlan((current) => ({ ...current, storyArc: event.target.value }))}
- />
- </FormField>
- </div>
-
- <div id="fableloom-plan-challenges" tabIndex={-1} className="focus:outline-none">
- <PlanCollection
- title="Plot points"
- description="Order tentpoles and playable challenges, then assign each one to the episode where it must appear."
- items={plan.plotPoints}
- episodes={episodeOptions}
- onAdd={() => changePlan((current) => ({ ...current, plotPoints: [...current.plotPoints, {
- id: newItemId('plot'), kind: 'beat', title: '', description: '', episodeId: null,
- }] }))}
- onUpdate={(id, patch) => updateItem('plotPoints', id, patch)}
- onAddChallenge={() => changePlan((current) => ({ ...current, plotPoints: [...current.plotPoints, {
- id: newItemId('plot'), kind: 'challenge', title: '', description: CHALLENGE_DESCRIPTION_TEMPLATE, episodeId: null,
- }] }))}
- onRemove={(id) => removeItem('plotPoints', id)}
- onMove={(index, direction) => moveItem('plotPoints', index, direction)}
+ <div className="shrink-0 border-b border-port-border bg-port-bg p-3 space-y-3">
+ <div className="flex items-center justify-between gap-3">
+ <div><h2 className="font-semibold">Series plan</h2><p className="text-xs text-port-text-muted">{dirty ? 'Unsaved changes' : 'All changes saved'}</p></div>
+ <button type="button" onClick={save} disabled={!dirty || saving} className="flex min-h-[44px] items-center gap-2 rounded bg-port-accent px-3 text-sm text-white disabled:opacity-50">
+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}{saving ? 'Saving…' : 'Save plan'}
+ </button>
+ </div>
+ <TabPills tabs={PLAN_SECTIONS} activeTab={requestedSection} onChange={setSection} mobileDropdown ariaLabel="Series plan section" controlsIdPrefix="series-section" />
+ </div>
+ <div ref={contentRef} className="min-h-0 flex-1 overflow-y-auto p-4 md:p-6">
+ <div className="max-w-5xl mx-auto">
+ <div hidden={requestedSection !== 'arc'} role="tabpanel" aria-labelledby="tab-arc" id="series-section-arc" tabIndex={-1} className="rounded-lg border border-port-border bg-port-card p-4 focus:outline-none">
+ <FormField
+ label="Story arc"
+ hint="The beginning-to-end dramatic movement, central conflict, and intended resolution."
+ labelClassName={labelClass}
+ >
+ <textarea
+ rows={7}
+ className={fieldClass}
+ value={plan.storyArc}
+ placeholder="What changes across the series, why it matters, and where the story lands…"
+ onChange={(event) => changePlan((current) => ({ ...current, storyArc: event.target.value }))}
/>
- </div>
+ </FormField>
+ </div>
+ <div hidden={requestedSection !== 'challenges'} role="tabpanel" aria-labelledby="tab-challenges" id="series-section-challenges" tabIndex={-1} className="focus:outline-none">
<PlanCollection
- title="Side quests"
- description="Track supporting threads without letting them disappear inside a single episode."
- items={plan.sideQuests}
+ title="Plot points"
+ description="Order tentpoles and playable challenges, then assign each one to the episode where it must appear."
+ items={plan.plotPoints}
episodes={episodeOptions}
- sideQuests
- onAdd={() => changePlan((current) => ({ ...current, sideQuests: [...current.sideQuests, {
- id: newItemId('quest'), title: '', description: '', status: 'idea', startEpisodeId: null, endEpisodeId: null,
+ onAdd={() => changePlan((current) => ({ ...current, plotPoints: [...current.plotPoints, {
+ id: newItemId('plot'), kind: 'beat', title: '', description: '', episodeId: null,
+ }] }))}
+ onUpdate={(id, patch) => updateItem('plotPoints', id, patch)}
+ onAddChallenge={() => changePlan((current) => ({ ...current, plotPoints: [...current.plotPoints, {
+ id: newItemId('plot'), kind: 'challenge', title: '', description: CHALLENGE_DESCRIPTION_TEMPLATE, episodeId: null,
}] }))}
- onUpdate={(id, patch) => updateItem('sideQuests', id, patch)}
- onRemove={(id) => removeItem('sideQuests', id)}
- onMove={(index, direction) => moveItem('sideQuests', index, direction)}
+ onRemove={(id) => removeItem('plotPoints', id)}
+ onMove={(index, direction) => moveItem('plotPoints', index, direction)}
/>
+ </div>
- <EpisodeBeatReadiness loom={loom} />
-
- <div id="fableloom-plan-editorial" tabIndex={-1} className="focus:outline-none">
- <LoomEditorialAutomation loom={loom} dirty={dirty} onLoomUpdate={adoptServerPlan} />
- </div>
+ <div hidden={requestedSection !== 'quests'} role="tabpanel" aria-labelledby="tab-quests" id="series-section-quests">
+ <PlanCollection
+ title="Side quests"
+ description="Track supporting threads without letting them disappear inside a single episode."
+ items={plan.sideQuests}
+ episodes={episodeOptions}
+ sideQuests
+ onAdd={() => changePlan((current) => ({ ...current, sideQuests: [...current.sideQuests, {
+ id: newItemId('quest'), title: '', description: '', status: 'idea', startEpisodeId: null, endEpisodeId: null,
+ }] }))}
+ onUpdate={(id, patch) => updateItem('sideQuests', id, patch)}
+ onRemove={(id) => removeItem('sideQuests', id)}
+ onMove={(index, direction) => moveItem('sideQuests', index, direction)}
+ />
- <div id="fableloom-plan-handoffs" tabIndex={-1} className="focus:outline-none">
- <SeriesDeliveryPlan
- plan={plan}
- episodes={loom.episodes}
- onChange={changePlan}
- />
- </div>
+ </div>
+ <div hidden={requestedSection !== 'episodes'} role="tabpanel" aria-labelledby="tab-episodes" id="series-section-episodes">
+ <EpisodeBeatReadiness loom={loom} />
</div>
- <aside className="w-full lg:w-[380px] xl:w-[420px] shrink-0 space-y-6 lg:sticky lg:top-0 lg:max-h-[calc(100vh-3rem)] lg:overflow-y-auto" aria-label="AI tools and actions">
- <div className="rounded-lg border border-port-border bg-port-card p-4 space-y-3">
- <div className="flex items-center justify-between gap-3">
- <div>
- <h3 className="font-semibold text-sm">Series plan actions</h3>
- <p className="text-xs flex items-center gap-1.5 mt-0.5">
- <span className={`inline-block w-2 h-2 rounded-full ${dirty ? 'bg-amber-400' : 'bg-emerald-400'}`} />
- <span className="text-port-text-muted">{dirty ? 'Unsaved changes' : 'All changes saved'}</span>
- </p>
- </div>
- <button
- type="button"
- onClick={save}
- disabled={!dirty || saving}
- className="shrink-0 flex items-center gap-2 px-3 py-2 rounded bg-port-accent text-white text-sm disabled:opacity-50 font-medium"
- >
- {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
- {saving ? 'Saving…' : 'Save plan'}
- </button>
- </div>
- </div>
+ <div hidden={requestedSection !== 'editorial'} role="tabpanel" aria-labelledby="tab-editorial" id="series-section-editorial" tabIndex={-1} className="focus:outline-none">
+ <LoomEditorialAutomation loom={loom} dirty={dirty || saving} onLoomUpdate={adoptServerPlan} />
+ <details className="mt-4 rounded border border-port-border p-3"><summary className="min-h-11 cursor-pointer">Manual AI plan tools</summary>
+ <SeriesAiEditor loom={loom} dirty={dirty || saving} onLoomUpdate={adoptServerPlan} />
+ </details>
+ </div>
- <SeriesAiEditor loom={loom} dirty={dirty} onLoomUpdate={adoptServerPlan} />
- </aside>
+ <div hidden={requestedSection !== 'handoffs'} role="tabpanel" aria-labelledby="tab-handoffs" id="series-section-handoffs" tabIndex={-1} className="focus:outline-none">
+ <SeriesDeliveryPlan
+ plan={plan}
+ episodes={loom.episodes}
+ onChange={changePlan}
+ />
+ </div>
</div>
</div>
</section>
@@ -726,11 +707,23 @@ function PlanCollection({
title, description, items, episodes, sideQuests = false,
onAdd, onAddChallenge, onUpdate, onRemove, onMove,
}) {
+ const collectionRef = useRef(null);
+ const previousIds = useRef(new Set(items.map((item) => item.id)));
+ useEffect(() => {
+ const added = items.find((item) => !previousIds.current.has(item.id));
+ previousIds.current = new Set(items.map((item) => item.id));
+ if (!added) return;
+ const row = Array.from(collectionRef.current?.querySelectorAll('[data-plan-item]') || [])
+ .find((element) => element.dataset.planItem === added.id);
+ if (row) row.open = true;
+ row?.scrollIntoView?.({ block: 'nearest' });
+ row?.querySelector('input')?.focus({ preventScroll: true });
+ }, [items]);
const challenges = sideQuests ? [] : items.filter((item) => fableLoomPlotPointKind(item) === 'challenge');
const assignedChallenges = challenges.filter((item) => item.episodeId);
return (
- <div className="rounded-lg border border-port-border bg-port-card p-4 space-y-4">
- <div className="flex items-start justify-between gap-3">
+ <div ref={collectionRef} className="rounded-lg border border-port-border bg-port-card p-4 space-y-4">
+ <div className="flex flex-col sm:flex-row items-start justify-between gap-3">
<div>
<h3 className="font-semibold">{title}</h3>
<p className="text-xs text-port-text-muted mt-1">{description}</p>
@@ -758,17 +751,23 @@ function PlanCollection({
Add the first {sideQuests ? 'side quest' : 'plot point'}
</button>
) : items.map((item, index) => (
- <div key={item.id} className="rounded border border-port-border p-3 space-y-3">
+ <details key={item.id} data-plan-item={item.id} className="rounded border border-port-border p-3">
+ <summary className="min-h-[44px] cursor-pointer text-sm leading-6">
+ <span className="font-medium">{index + 1}. {item.title || (sideQuests ? 'New side quest' : 'New plot point')}</span>
+ <span className="ml-2 text-xs text-port-text-muted">{episodes.find((episode) => episode.id === (sideQuests ? item.startEpisodeId : item.episodeId))?.label || 'Unassigned'}</span>
+ {!sideQuests && fableLoomPlotPointKind(item) === 'challenge' ? <span className="ml-2 text-xs text-port-accent">Challenge</span> : null}
+ </summary>
+ <div className="space-y-3 pt-3">
{!sideQuests && fableLoomPlotPointKind(item) === 'challenge' ? (
<span className="inline-flex rounded bg-port-accent/10 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-port-accent">
Playable challenge
</span>
) : null}
- <div className="flex items-center gap-2">
+ <div className="flex flex-wrap items-center gap-2">
<span className="text-xs font-medium text-port-text-muted w-6">{index + 1}.</span>
<input
aria-label={`${title} ${index + 1} title`}
- className={fieldClass}
+ className={`${fieldClass} min-w-0 flex-1 basis-40`}
value={item.title}
placeholder={sideQuests ? 'Side quest title' : 'Plot point title'}
onChange={(event) => onUpdate(item.id, { title: event.target.value })}
@@ -797,7 +796,8 @@ function PlanCollection({
) : (
<PlanSelect label="Episode" value={item.episodeId || ''} onChange={(value) => onUpdate(item.id, { episodeId: value || null })} options={episodes} emptyLabel="Unassigned" />
)}
- </div>
+ </div>
+ </details>
))}
</div>
);
diff --git a/client/src/components/fableloom/LoomSeriesPlan.test.jsx b/client/src/components/fableloom/LoomSeriesPlan.test.jsx
index 7e7c0553b0..7425ccf462 100644
--- a/client/src/components/fableloom/LoomSeriesPlan.test.jsx
+++ b/client/src/components/fableloom/LoomSeriesPlan.test.jsx
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { createMemoryRouter, RouterProvider } from 'react-router';
import { useState } from 'react';
@@ -57,6 +57,8 @@ describe('LoomSeriesPlan', () => {
renderPlan({ loom: loom(), onLoomUpdate });
fireEvent.change(screen.getByRole('textbox', { name: /story arc/i }), { target: { value: 'A stronger arc.' } });
+ fireEvent.click(screen.getByRole('tab', { name: 'AI editor' }));
+ fireEvent.click(screen.getByText('Manual AI plan tools'));
expect(screen.getByRole('button', { name: /analyze series/i })).toBeDisabled();
fireEvent.click(screen.getByRole('button', { name: /save plan/i }));
@@ -71,25 +73,27 @@ describe('LoomSeriesPlan', () => {
api.updateLoom.mockResolvedValue(loom());
renderPlan({ loom: loom(), onLoomUpdate: vi.fn() });
+ await user.click(screen.getByRole('tab', { name: 'Plot & challenges' }));
await user.click(screen.getByRole('button', { name: 'Challenge' }));
const challengeTitle = screen.getByRole('textbox', { name: 'Plot points 2 title' });
expect(challengeTitle).toHaveValue('');
+ expect(challengeTitle).toHaveFocus();
expect(screen.getByRole('textbox', { name: 'Plot points 2 description' }).value)
.toContain('VIEWER DECISION LOOP');
expect(screen.getByText('0/1 playable challenges mapped to episodes')).toBeInTheDocument();
- await user.selectOptions(screen.getAllByRole('combobox', { name: 'Episode' })[1], 'ep-1');
+ await user.selectOptions(within(challengeTitle.closest('details')).getByRole('combobox', { name: 'Episode' }), 'ep-1');
expect(screen.getByText('1/1 playable challenges mapped to episodes')).toBeInTheDocument();
});
- it('presents challenge planning before outline readiness and editorial automation', () => {
+ it('keeps drafts across section changes and shows only the selected planning area', () => {
renderPlan({ loom: loom(), onLoomUpdate: vi.fn() });
-
- const plotPoints = screen.getByRole('heading', { name: 'Plot points' });
- const outlines = screen.getByRole('heading', { name: 'Episode beat outlines' });
- const editorial = screen.getByText('Editorial automation');
-
- expect(plotPoints.compareDocumentPosition(outlines) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
- expect(outlines.compareDocumentPosition(editorial) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ fireEvent.change(screen.getByRole('textbox', { name: /story arc/i }), { target: { value: 'Unsaved arc' } });
+ fireEvent.click(screen.getByRole('tab', { name: 'Plot & challenges' }));
+ expect(screen.queryByRole('textbox', { name: /story arc/i })).not.toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: 'Plot points' })).toBeVisible();
+ expect(screen.getByRole('button', { name: /save plan/i })).toBeVisible();
+ fireEvent.click(screen.getByRole('tab', { name: 'Story arc' }));
+ expect(screen.getByRole('textbox', { name: /story arc/i })).toHaveValue('Unsaved arc');
});
it('shows AI series analysis and recommendations for the outline', async () => {
@@ -103,6 +107,8 @@ describe('LoomSeriesPlan', () => {
});
renderPlan({ loom: loom(), onLoomUpdate: () => {} });
+ fireEvent.click(screen.getByRole('tab', { name: 'AI editor' }));
+ fireEvent.click(screen.getByText('Manual AI plan tools'));
fireEvent.click(screen.getByRole('button', { name: /analyze series/i }));
expect(await screen.findByText('The spine works.')).toBeInTheDocument();
expect(screen.getByText('Move the reversal into episode 3')).toBeInTheDocument();
@@ -120,6 +126,8 @@ describe('LoomSeriesPlan', () => {
api.feedbackLoomSeriesPlan.mockResolvedValue({ loom: updated, changes: ['Shifted plot point turn'] });
renderPlan({ loom: loom(), onLoomUpdate });
+ fireEvent.click(screen.getByRole('tab', { name: 'AI editor' }));
+ fireEvent.click(screen.getByText('Manual AI plan tools'));
fireEvent.change(screen.getByRole('textbox', { name: /edit outline & plot points/i }), {
target: { value: 'Move the turn to episode 1 and raise stakes.' },
});
@@ -148,6 +156,8 @@ describe('LoomSeriesPlan', () => {
api.generateLoomSeriesPlan.mockResolvedValue({ loom: generated, runId: 'run-draft' });
renderPlan({ loom: loom(), onLoomUpdate });
+ fireEvent.click(screen.getByRole('tab', { name: 'AI editor' }));
+ fireEvent.click(screen.getByText('Manual AI plan tools'));
fireEvent.click(screen.getByRole('button', { name: /regenerate full plan/i }));
expect(api.generateLoomSeriesPlan).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: /^regenerate$/i }));
@@ -165,8 +175,11 @@ describe('LoomSeriesPlan', () => {
{ path: '/', element: <StatefulPlan initial={loom()} /> },
], { initialEntries: ['/'] })} />);
+ fireEvent.click(screen.getByRole('tab', { name: 'AI editor' }));
+ fireEvent.click(screen.getByText('Manual AI plan tools'));
fireEvent.click(screen.getByRole('button', { name: /regenerate full plan/i }));
fireEvent.click(screen.getByRole('button', { name: /^regenerate$/i }));
+ fireEvent.click(screen.getByRole('tab', { name: 'Story arc' }));
fireEvent.change(screen.getByRole('textbox', { name: /story arc/i }), {
target: { value: 'Typing that should not undo the requested regeneration.' },
});
@@ -198,19 +211,6 @@ describe('LoomSeriesPlan', () => {
expect(screen.getByRole('button', { name: /save plan/i })).toBeEnabled();
});
- it('renders AI tools and save plan within the persistent desktop rail beside the story content', () => {
- renderPlan({ loom: loom(), onLoomUpdate: () => {} });
- const rightRail = screen.getByRole('complementary', { name: /ai tools and actions/i });
- expect(rightRail).toBeInTheDocument();
- expect(rightRail.className).toContain('lg:sticky');
- expect(rightRail.className).toContain('lg:top-0');
-
- // Confirm actions and AI tools reside within the right rail
- expect(rightRail).toContainElement(screen.getByRole('button', { name: /save plan/i }));
- expect(rightRail).toContainElement(screen.getByRole('button', { name: /analyze series/i }));
- expect(rightRail).toContainElement(screen.getByRole('button', { name: /(draft|regenerate) full plan/i }));
- });
-
it('reviews the complete expanded teleplay only when every episode has scenes', async () => {
api.reviewLoomTeleplay.mockResolvedValue({
analysis: {
@@ -228,6 +228,8 @@ describe('LoomSeriesPlan', () => {
});
renderPlan({ loom: fullLoom, onLoomUpdate: () => {} });
+ fireEvent.click(screen.getByRole('tab', { name: 'AI editor' }));
+ fireEvent.click(screen.getByText('Manual AI plan tools'));
expect(screen.getByRole('button', { name: 'Review full teleplay' })).toBeEnabled();
await userEvent.setup().click(screen.getByRole('button', { name: 'Review full teleplay' }));
expect(await screen.findByText('The full teleplay escalates cleanly.')).toBeInTheDocument();
@@ -242,6 +244,7 @@ describe('LoomSeriesPlan', () => {
const user = userEvent.setup();
renderPlan({ loom: loom(), onLoomUpdate: () => {} });
+ await user.click(screen.getByRole('tab', { name: 'Episode outlines' }));
await user.click(screen.getByRole('button', { name: 'Validate full beat arc' }));
expect(await screen.findByText(/Draft Episode 1 first\./)).toBeInTheDocument();
@@ -261,6 +264,7 @@ describe('LoomSeriesPlan', () => {
const onLoomUpdate = vi.fn();
renderPlan({ loom: threeEpisodeLoom, onLoomUpdate });
+ await user.click(screen.getByRole('tab', { name: 'Viewer handoffs' }));
await user.click(screen.getByLabelText(/overnight voicemail between episodes/i));
expect(screen.getAllByRole('textbox', { name: 'Voicemail transcript' })).toHaveLength(2);
await user.type(screen.getAllByRole('textbox', { name: 'Voicemail transcript' })[0], 'Stay awake. The beacon is listening.');
diff --git a/client/src/components/fableloom/LoomShotPlanner.jsx b/client/src/components/fableloom/LoomShotPlanner.jsx
new file mode 100644
index 0000000000..93c03bdddd
--- /dev/null
+++ b/client/src/components/fableloom/LoomShotPlanner.jsx
@@ -0,0 +1,54 @@
+import { useEffect, useState } from 'react';
+import { Loader2, Scissors } from 'lucide-react';
+import ConfirmButtonPair from '../ui/ConfirmButtonPair';
+import { useAsyncAction } from '../../hooks/useAsyncAction';
+import { applyLoomEpisodeShots, planLoomEpisodeShots } from '../../services/api';
+import { analyzeEpisodeShots } from '../../../../server/lib/fableLoomShots.js';
+
+export default function LoomShotPlanner({ loom, episode, route, guidance, disabled, onLoomUpdate, onRunningChange }) {
+ const [plan, setPlan] = useState(null);
+ const [confirmation, setConfirmation] = useState(null);
+ const [run, running] = useAsyncAction(async (apply = false) => {
+ const result = await planLoomEpisodeShots(loom.id, episode.id, { ...route, guidance, apply, maxRounds: 3 }, { silent: true });
+ setPlan(result);
+ if (result.loom) onLoomUpdate(result.loom);
+ }, { errorMessage: 'Shot planning failed' });
+ const [apply, applying] = useAsyncAction(async () => {
+ const result = await applyLoomEpisodeShots(loom.id, episode.id, { sourceFingerprint: plan.sourceFingerprint, groups: plan.groups }, { silent: true });
+ onLoomUpdate(result.loom);
+ setPlan({ ...plan, ...result });
+ }, { errorMessage: 'Could not apply shot plan' });
+ useEffect(() => { onRunningChange?.(running || applying); }, [running, applying, onRunningChange]);
+ const timing = analyzeEpisodeShots(episode);
+ const busy = disabled || running || applying;
+ return <section className="rounded border border-port-border p-3 space-y-3" aria-label="Timed shot planning">
+ <h4 className="font-semibold text-sm flex items-center gap-2"><Scissors size={15} /> Split dramatic scenes into shots</h4>
+ <p className="text-xs text-port-text-muted">One node becomes one 5–10 second render. The selected model drafts and reviews short shots before replacing scene nodes. Branches stay connected. Applying clears old scene media; preview first or let autopilot apply a passing plan.</p>
+ <div className="flex flex-wrap gap-2">
+ <button type="button" disabled={busy || !episode.nodes.length} onClick={() => run(false)} className="min-h-11 rounded border border-port-border px-3 text-sm disabled:opacity-50">{running ? <Loader2 size={14} className="inline animate-spin mr-2" /> : null}Preview shot split</button>
+ <button type="button" disabled={busy || !episode.nodes.length} onClick={() => setConfirmation('autopilot')} className="min-h-11 rounded bg-port-accent px-3 text-sm text-white disabled:opacity-50">Run shot autopilot</button>
+ </div>
+ {confirmation && <ConfirmButtonPair
+ prompt={`Replace ${episode.nodes.length} existing scene nodes and remove their rendered media bindings?`}
+ confirmText={confirmation === 'autopilot' ? 'Replace with shot autopilot' : 'Replace with reviewed shots'}
+ busy={busy}
+ onConfirm={() => { const action = confirmation; setConfirmation(null); if (action === 'autopilot') run(true); else apply(); }}
+ onCancel={() => setConfirmation(null)}
+ largeTouchTargets
+ className="flex-wrap"
+ />}
+ {timing.stats.shotCount > 0 ? <p className="text-xs">{timing.stats.dramaticSceneCount} dramatic scenes · {timing.stats.shotCount} shots · {timing.stats.totalAssetSeconds}s across all branches</p> : <p className="text-xs text-port-warning">This episode has not been planned as timed shots yet.</p>}
+ {timing.issues.map((issue) => <p key={`${issue.nodeId}-${issue.code}`} className="text-xs text-port-error">{issue.message}</p>)}
+ {plan ? <div className="space-y-2">
+ <p className="text-xs">{plan.review.summary}</p>
+ {!plan.loom ? <button type="button" disabled={busy} onClick={() => setConfirmation('apply')} className="min-h-11 rounded bg-port-accent px-3 text-sm text-white">Apply reviewed shots</button> : null}
+ {plan.groups.map((group) => <details key={group.sceneId} className="rounded border border-port-border p-2">
+ <summary className="cursor-pointer min-h-11 text-sm">{episode.nodes.find((node) => node.id === group.sceneId)?.shot?.dramaticSceneTitle || episode.nodes.find((node) => node.id === group.sceneId)?.title || 'Dramatic scene'} · {group.shots.length} shots</summary>
+ {group.shots.map((shot, index) => <div key={`${group.sceneId}-${index}`} className="border-t border-port-border py-2 text-xs space-y-1">
+ <p className="font-semibold">{index + 1}. {shot.title} · {shot.durationSeconds}s</p><p>{shot.framing}</p><p>{shot.action}</p>
+ {shot.dialogue.map((line, lineIndex) => <p key={`${index}-${lineIndex}`}>{line.speaker}: {line.text}</p>)}
+ </div>)}
+ </details>)}
+ </div> : null}
+ </section>;
+}
diff --git a/client/src/components/fableloom/LoomShotPlanner.test.jsx b/client/src/components/fableloom/LoomShotPlanner.test.jsx
new file mode 100644
index 0000000000..ff529fbed1
--- /dev/null
+++ b/client/src/components/fableloom/LoomShotPlanner.test.jsx
@@ -0,0 +1,40 @@
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { it, expect, vi } from 'vitest';
+import LoomShotPlanner from './LoomShotPlanner';
+const api = vi.hoisted(() => ({ planLoomEpisodeShots: vi.fn(), applyLoomEpisodeShots: vi.fn() }));
+vi.mock('../../services/api', () => api);
+vi.mock('../ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));
+it('previews with the selected route, then explicitly applies the reviewed fingerprint', async () => {
+ const episode = { id: 'ep-1', nodes: [{ id: 'scene-1', title: 'The gate' }] };
+ const groups = [{ sceneId: 'scene-1', shots: [{ title: 'A knock', durationSeconds: 8, framing: 'Close', action: 'A hand knocks.', dialogue: [] }] }];
+ api.planLoomEpisodeShots.mockResolvedValue({ sourceFingerprint: 'a'.repeat(64), groups, review: { summary: 'Ready.' } });
+ api.applyLoomEpisodeShots.mockResolvedValue({ loom: { id: 'loom-1', episodes: [episode] } });
+ const onLoomUpdate = vi.fn();
+ render(<LoomShotPlanner loom={{ id: 'loom-1' }} episode={episode} route={{ model: 'example-model', effort: 'low' }} onLoomUpdate={onLoomUpdate} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Preview shot split' }));
+ await screen.findByText('Ready.');
+ expect(api.planLoomEpisodeShots).toHaveBeenCalledWith('loom-1', 'ep-1', expect.objectContaining({ model: 'example-model', effort: 'low', apply: false }), { silent: true });
+ expect(onLoomUpdate).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'Apply reviewed shots' }));
+ expect(api.applyLoomEpisodeShots).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'Replace with reviewed shots' }));
+ await waitFor(() => expect(onLoomUpdate).toHaveBeenCalled());
+ expect(api.applyLoomEpisodeShots).toHaveBeenCalledWith('loom-1', 'ep-1', { sourceFingerprint: 'a'.repeat(64), groups }, { silent: true });
+});
+
+it('confirms destructive autopilot replacement and reports its active lifecycle', async () => {
+ let finish;
+ api.planLoomEpisodeShots.mockClear();
+ api.planLoomEpisodeShots.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
+ const onRunningChange = vi.fn();
+ render(<LoomShotPlanner loom={{ id: 'loom-1' }} episode={{ id: 'ep-1', nodes: [{ id: 'scene-1', image: 'example.png' }] }} onLoomUpdate={vi.fn()} onRunningChange={onRunningChange} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Run shot autopilot' }));
+ expect(api.planLoomEpisodeShots).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(api.planLoomEpisodeShots).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'Run shot autopilot' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Replace with shot autopilot' }));
+ await waitFor(() => expect(onRunningChange).toHaveBeenLastCalledWith(true));
+ finish({ review: { summary: 'Applied.' }, groups: [], loom: { id: 'loom-1' } });
+ await waitFor(() => expect(onRunningChange).toHaveBeenLastCalledWith(false));
+});
diff --git a/client/src/pages/FableLoomStory.jsx b/client/src/pages/FableLoomStory.jsx
index 535c1ab295..b600f9ed83 100644
--- a/client/src/pages/FableLoomStory.jsx
+++ b/client/src/pages/FableLoomStory.jsx
@@ -16,7 +16,7 @@
* content off-screen.
*/
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Link, Navigate, useNavigate, useParams, useSearchParams } from 'react-router';
import { ArrowLeft, BookOpenText, ListTree, PencilLine, Plus, Settings, Sparkles, Trash2, Waypoints, Workflow as WorkflowIcon, X } from 'lucide-react';
import toast from '../components/ui/Toast';
@@ -797,6 +797,7 @@ function EpisodeSetupDrawer({ open, onClose, loom, episode, onLoomUpdate, onFeed
const { run: aiRun, begin: beginAiRun, fail: failAiRun } = useFableLoomAiRun();
const del = useConfirmDelete();
const expansionConfirm = useConfirmDelete();
+ const expansionRouteRef = useRef({});
const hasScenes = episode.nodes.length > 0;
// Sync from the record on episode switch ONLY — re-syncing on every server
@@ -820,6 +821,7 @@ function EpisodeSetupDrawer({ open, onClose, loom, episode, onLoomUpdate, onFeed
const [runWeave, weaving] = useAsyncAction(async () => {
const operationId = beginAiRun();
const result = await weaveLoomEpisode(loom.id, episode.id, {
+ ...expansionRouteRef.current,
guidance: form.guidance,
replace: hasScenes,
expandFromOutline: true,
@@ -833,7 +835,8 @@ function EpisodeSetupDrawer({ open, onClose, loom, episode, onLoomUpdate, onFeed
onClose();
}, { errorMessage: 'Weave failed' });
- const requestWeave = () => {
+ const requestWeave = (route = {}) => {
+ expansionRouteRef.current = route;
if (hasScenes) {
expansionConfirm.requestDelete(episode.id);
return;
diff --git a/client/src/pages/FableLoomStory.test.jsx b/client/src/pages/FableLoomStory.test.jsx
index a9a5423db3..bd91535331 100644
--- a/client/src/pages/FableLoomStory.test.jsx
+++ b/client/src/pages/FableLoomStory.test.jsx
@@ -98,7 +98,7 @@ vi.mock('../components/fableloom/LoomMediaJobWatchers', () => ({
vi.mock('../components/fableloom/LoomEpisodeOutline', () => ({ default: ({ episode }) => <div data-testid="episode-outline">{episode.title}</div> }));
vi.mock('../components/fableloom/LoomEpisodeOutlinePlanner', () => ({
default: ({ onExpand }) => (
- <button type="button" onClick={onExpand}>Expand validated outline to teleplay</button>
+ <button type="button" onClick={() => onExpand({ providerId: 'writer', model: 'example-model', effort: 'low' })}>Expand validated outline to teleplay</button>
),
}));
vi.mock('../components/fableloom/LoomEpisodeFeedback', () => ({ default: () => null }));
@@ -306,7 +306,7 @@ describe('FableLoomStory episode expansion safety', () => {
await waitFor(() => expect(api.weaveLoomEpisode).toHaveBeenCalledWith(
'loom-1',
'ep-1',
- expect.objectContaining({ replace: true, expandFromOutline: true }),
+ expect.objectContaining({ replace: true, expandFromOutline: true, providerId: 'writer', model: 'example-model', effort: 'low' }),
{ silent: true },
));
});
diff --git a/client/src/services/apiFableLoom.js b/client/src/services/apiFableLoom.js
index 5c5603cc2b..e859fda232 100644
--- a/client/src/services/apiFableLoom.js
+++ b/client/src/services/apiFableLoom.js
@@ -187,3 +187,6 @@ export const reviewLoomEpisodeContinuity = (id, episodeId, body = {}, options =
request(episodePath(id, episodeId, '/continuity/review'), {
method: 'POST', body: JSON.stringify(body), ...options,
});
+
+export const planLoomEpisodeShots = (id, episodeId, body = {}, options = {}) => request(episodePath(id, episodeId, '/shots/plan'), { method: 'POST', body: JSON.stringify(body), ...options });
+export const applyLoomEpisodeShots = (id, episodeId, body, options = {}) => request(episodePath(id, episodeId, '/shots/apply'), { method: 'POST', body: JSON.stringify(body), ...options });
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 7ee8d4838f..1b6219e7d0 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -1093,6 +1093,27 @@
"model": "heavy",
"returnsJson": true,
"variables": []
+ },
+ "fableloom-plan-shots": {
+ "name": "FableLoom — Plan Timed Shots",
+ "description": "Episode-scoped short-shot production planning before media generation.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": [
+ "source",
+ "guidance",
+ "feedback"
+ ]
+ },
+ "fableloom-review-shots": {
+ "name": "FableLoom — Review Timed Shots",
+ "description": "Episode-scoped short-shot production planning before media generation.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": [
+ "source",
+ "shots"
+ ]
}
}
}
diff --git a/data.reference/prompts/stages/fableloom-feedback-series-plan.md b/data.reference/prompts/stages/fableloom-feedback-series-plan.md
index f8832bc1e6..ebcbdb6238 100644
--- a/data.reference/prompts/stages/fableloom-feedback-series-plan.md
+++ b/data.reference/prompts/stages/fableloom-feedback-series-plan.md
@@ -26,7 +26,8 @@ You are the story editor for an interactive branching series. Apply the author's
- Reordering is separate: include the existing ids to move in the desired relative order. Items omitted from an order array remain after the explicitly ordered items.
- Episode references must use an episode id from the supplied outline or `null`.
- Side-quest status is one of `idea`, `planned`, `active`, or `resolved`.
-- Do not change episode titles, synopses, scenes, paths, or ids in this pass.
+- Keep episode synopses consistent with the revised arc using sparse `episodeSynopsisEdits` for existing episode ids. Do not change episode titles, beat outlines, scenes, paths, or ids in this pass.
+- Keep plot-point descriptions under 4000 characters. Summarize their dramatic job; do not duplicate full episode beat outlines or put temporary workflow status in the story arc.
Return ONLY valid JSON matching this shape, omitting unchanged top-level fields:
@@ -34,6 +35,7 @@ Return ONLY valid JSON matching this shape, omitting unchanged top-level fields:
{
"storyArc": "complete revised arc",
"plotPointEdits": [{ "id": "existing id, or omit for new", "title": "only when changed", "description": "only when changed", "episodeId": "episode id or null, only when changed", "remove": false }],
+ "episodeSynopsisEdits": [{ "id": "existing episode id", "synopsis": "complete revised synopsis" }],
"plotPointOrder": ["existing plot-point id"],
"sideQuestEdits": [{ "id": "existing id, or omit for new", "title": "only when changed", "description": "only when changed", "status": "planned", "startEpisodeId": "episode id or null", "endEpisodeId": "episode id or null", "remove": false }],
"sideQuestOrder": ["existing side-quest id"],
diff --git a/data.reference/prompts/stages/fableloom-outline-episode.md b/data.reference/prompts/stages/fableloom-outline-episode.md
index 9c153bc4f6..fb8a850c94 100644
--- a/data.reference/prompts/stages/fableloom-outline-episode.md
+++ b/data.reference/prompts/stages/fableloom-outline-episode.md
@@ -32,6 +32,7 @@ You are the story architect for one episode of an interactive branching series.
## Planning contract
+- The first episode must establish a person before a puzzle: show the protagonist doing their everyday role, pursuing a concrete immediate want, and encountering a disruption with a legible personal cost. Put these observable actions in the opening summaries; the synopsis does not count as on-screen setup. Introduce unfamiliar systems through their effect on that person before naming their mechanisms. Do not spend the opening on evidence administration or future branch bookkeeping.
- Plan the complete dramatic job of this episode, including setup, escalation, a meaningful turn, branch consequences, and distinct endings that hand off cleanly to the next episode when one exists.
- Use one beat per eventual camera-cut scene. Keep each `summary` to 1–3 sentences describing what changes, what the protagonist wants, and why the beat matters.
- Use `playbackMode: "cut"` for setup/action beats that automatically advance and give them exactly one transition. Use `playbackMode: "decision"` only for genuine viewer choices and give them 2–4 clearly different paths.
diff --git a/data.reference/prompts/stages/fableloom-plan-shots.md b/data.reference/prompts/stages/fableloom-plan-shots.md
new file mode 100644
index 0000000000..a6dd67ebf9
--- /dev/null
+++ b/data.reference/prompts/stages/fableloom-plan-shots.md
@@ -0,0 +1,19 @@
+# FableLoom — Timed shot autopilot
+
+Turn the supplied dramatic scenes into individually renderable 5–10 second camera cuts. Preserve the story's emotional clarity, facts, promises, choices and consequences. You may compress repetitive dialogue, but never move a branch's facts into the shared continuation. The server preserves branch wiring; return exactly one group for EACH input scene id, in order. Never omit a scene. Do not write new episode material.
+
+{{source}}
+
+Author direction: {{guidance}}
+Prior blocking findings to repair: {{feedback}}
+
+- Each shot is ONE camera setup, ONE compact action, and at most a short line or exchange. Spoken dialogue must fit 2.2 words/second with 1.5 seconds reserved for reactions: at most 7 words in 5 seconds, 14 in 8 seconds, 18 in 10 seconds. Prefer fewer words and let looks/actions carry meaning. Do not pack 60 seconds of action into a silent 8-second cut.
+- Establish the protagonist's ordinary role, immediate want and emotional interruption before technical explanations. Continue a conversation through reaction shots instead of putting it all in one node. Make unfamiliar mechanisms legible with simple actions. Cut redundant procedural dialogue.
+- Choose as many shots as the episode needs; no fixed node-count target. Aim for an engaging short pilot, not exhaustive coverage. Never pad with duplicate shots just to reach a duration.
+- Each input decision scene must end with an EMPTY-DIALOGUE, open-ended environmental loop. Put its scripted question/explanation into earlier shots of that group. Preserve off-screen protagonist framing throughout off-screen source scenes. Live viewer conversation is not prerecorded dialogue and is not limited to ten seconds.
+- Include visibleCharacterIds for each shot: a subset of its source scene cast, only people actually visible in that composition. Include protagonistPresence as onscreen or offscreen for that exact shot. A voice-over or a person outside the frame is not visible.
+- All visible identities and wardrobe remain the same. Do not put the viewer on screen. Voice-only characters stay voice-only. For each imagePrompt describe exactly the visible shot; for videoPrompt describe only its short motion. No multi-location montages or camera cuts inside a shot.
+- Plan adjacent shots together, following transitions rather than array order. Within a dramatic scene preserve the same room geography, lighting direction/color, time, prop scale and placement, character positions, eyelines and screen direction unless a visible action changes them. Use source image/video prompts, framing, camera movement and visual bindings as continuity evidence. Choose a deliberate connecting angle (establishing view, matching close-up, reverse angle or insert); a tighter crop must still depict the same set. Repeat the relevant stable spatial details explicitly in each imagePrompt and the matching motion in videoPrompt, so independent renders connect. Branch reconvergence must use only the physical state common to all incoming paths.
+- Images and videos must have no subtitles, captions, dialogue text, speech bubbles, watermarks or title overlays. Keep spoken words only in dialogue; do not ask the renderer to print them. Story-required physical signage may remain only when established by the source. Include these exclusions explicitly in every imagePrompt and videoPrompt.
+- The resulting prompts are a plan, not visual approval. After stills are generated, the creator must review adjacent reference images together in playback order for visual continuity before requesting videos; never claim unseen image files have passed that review.
+- Output JSON only: {"groups":[{"sceneId":"exact input scene id","shots":[{"title":"short shot name","visibleCharacterIds":[],"protagonistPresence":"onscreen","durationSeconds":8,"framing":"medium shot, one fixed camera","action":"one brief visible action, no dialogue hidden here","dialogue":[{"speaker":"CHARACTER","text":"Short spoken line."}],"imagePrompt":"one composition","videoPrompt":"one short continuous action"}]}]}. Empty dialogue is []. Supply every field. Never write files except the requested response artifact.
diff --git a/data.reference/prompts/stages/fableloom-review-episode-outline.md b/data.reference/prompts/stages/fableloom-review-episode-outline.md
index d085c1074c..8e086ec519 100644
--- a/data.reference/prompts/stages/fableloom-review-episode-outline.md
+++ b/data.reference/prompts/stages/fableloom-review-episode-outline.md
@@ -22,7 +22,9 @@ You are a senior story editor reviewing the beat outline for one episode inside
{{structuralDigest}}
-Evaluate whether the episode has a clear dramatic job, escalation, protagonist agency, branch consequences, meaningful and distinct endings, continuity with adjacent episodes, side-quest movement, and a compelling handoff. Check that choices are legible from their preceding beat and that the audience connection rules are dramatized rather than merely technical. Check that off-screen protagonist beats are reserved for direct audience conversations and that visible beats keep the canonical wardrobe. Flag only concrete risks that a writer can fix before teleplay expansion.
+When Story requests a cold opening review, evaluate ONLY the supplied opening and do not demand absent later beats, canon, or endings. Treat missing orientation or personal motivation as blocking risks.
+
+For a full outline review, evaluate whether the episode has a clear dramatic job, escalation, protagonist agency, branch consequences, meaningful and distinct endings, continuity with adjacent episodes, side-quest movement, and a compelling handoff. Check that choices are legible from their preceding beat and that the audience connection rules are dramatized rather than merely technical. Check that off-screen protagonist beats are reserved for direct audience conversations and that visible beats keep the canonical wardrobe. Flag only concrete risks that a writer can fix before teleplay expansion.
Return ONLY valid JSON matching this shape — no prose, markdown fence, or commentary:
diff --git a/data.reference/prompts/stages/fableloom-review-shots.md b/data.reference/prompts/stages/fableloom-review-shots.md
new file mode 100644
index 0000000000..de06ad768a
--- /dev/null
+++ b/data.reference/prompts/stages/fableloom-review-shots.md
@@ -0,0 +1,12 @@
+# FableLoom — Shot-plan review
+
+Review the complete proposed short episode against its dramatic source before any images or videos are generated.
+
+Source dramatic scenes: {{source}}
+Proposed timed shots: {{shots}}
+
+Read each path in playback order as a first-time viewer. Check: a clear person/want/interruption before exposition; comprehensible stakes; dialogue and visible action fitting each 5–10 second shot; no new camera cut hidden within a shot; complete source groups; preserved choice information and meaningful costs; silent repeatable decision loops with live conversation separate; no branch-specific facts leaking into shared aftermath; and an earned emotional ending. Avoid multiplying technical explanations or adding paperwork. The timer check already validates spoken-word budgets; focus on actual filmability and story comprehension.
+
+Compare every adjacent cut along the actual paths, including shots already grouped by dramaticSceneId. Flag unexplained changes to room geography, lighting, prop placement/scale, character positions, eyelines or screen direction within one dramatic scene. Require a deliberate connecting camera angle/framing and self-contained continuity details in each render prompt; a generic character identity reference alone does not preserve the set. Check branch reconvergence against every incoming physical state. Reject instructions to render subtitles, captions, dialogue text, speech bubbles or title overlays; spoken words belong in the dialogue field. Source image filenames are context only: this text review cannot approve the pixels. Generated reference images must subsequently be viewed together in playback order before video rendering.
+
+Return JSON only: {"summary":"specific assessment","risks":["only concrete blocking omissions, contradictions, unfilmable action or incomprehensible stakes"],"recommendations":["optional polish"]}. Empty risks explicitly approves the text shot plan only, never generated reference images or video readiness. Do not invent new requirements or later-episode scenes. Do not demand dialogue repeat facts already shown in preceding shots. Do not ask for a full mystery solution in episode one.
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 55ec08a0aa..0b5c39a13e 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -224,3 +224,5 @@ Apply this checklist to **every new feature that persists data**, and require it
### Model comparison reference snapshot
`data/model-comparison.json` is `file-primary`: a bounded, externally researched reference snapshot, directly inspectable/importable as a portable JSON document, with no app-record foreign keys, cross-record queries, search index or accumulated history. It follows the local-assessment reference pattern, rather than representing app-native relational records. It is intentionally machine-local and never federated because configuration and quota interpretation can be install-specific. Schema version 1 is seeded for new installs and migration 351 preserves existing catalogs. Rsync backups include it; no backup exclusion, sync cursor or tombstone is added. Source dates and exact benchmark/configuration identities remain attached to metrics. The server rejects future/malformed versions and merges imports through a serialized last-good-preserving write. See [Models Comparison](MODEL-COMPARISON.md).
+
+Optional SDK environments under `data/venvs/` are machine-local, regenerable runtime files, not application records. Reactor installs its pinned SDK only through `npm run setup:reactor`; no seed, migration, database table, or peer synchronization is needed. Data Manager identifies these environments but does not purge them while render processes may use them.
diff --git a/docs/features/fableloom.md b/docs/features/fableloom.md
index 4c13239a85..7adb9c36ef 100644
--- a/docs/features/fableloom.md
+++ b/docs/features/fableloom.md
@@ -8,6 +8,33 @@ decision nodes loop while the viewer chooses a path or gives free-text
feedback—when that story's audience role permits it. A loom holds one or more ordered episodes, and the Play surface can
rehearse the same experience at any of those three production stages.
+## Planning a series
+
+The series editor has separate, linkable sections for the arc, plot points and
+challenges, side quests, episode outlines, AI editing, and viewer handoffs.
+Save remains visible while the selected section scrolls. Plot points and side
+quests show compact expandable summaries; adding an item opens it and focuses
+its title without changing the order of existing beats. Drafts survive section
+changes.
+
+Create the intended episode slots and assign plot points and playable challenges
+before starting **Plan the series before writing scenes** in the AI editor.
+This explicit autopilot mode reviews the plan first, repairs concrete findings,
+then drafts and reviews each episode outline in order with bounded retries.
+Plan edits can synchronize existing episode synopses while preserving episode
+titles and scene graphs. Advice for later prose expansion does not force another
+outline rewrite. The first episode also receives a cold opening review: only its
+first three dramatic groups are supplied (or three beats before shot splitting),
+stopping at the first decision, without synopsis, canon or later payoffs. Missing
+immediate motivation, orientation or understandable personal stakes blocks planning
+before the full contextual review. A missing verdict is not approval.
+Each outline scene represents one camera-cut beat, not a complete dramatic scene.
+Plot points assigned to another episode cannot be expanded into the current
+episode. Deterministic validation must pass across the complete arc. Planning does not
+expand scenes, render media, or set editorial production approval. Choose the
+episode to expand afterward; later episodes may remain outlines for human review.
+The complete-teleplay editor/playtest mode remains available separately.
+
## Concepts
| Term | Meaning |
@@ -327,3 +354,33 @@ as Games / Creative Director:
- The link is soft in both directions — deleting a series is never blocked by a
loom pointing at it, and the loom editor's series backlink renders **no chip**
(rather than a dead link) once the series is gone.
+
+### Timed shots before media
+
+In the episode outline editor, **Preview shot split** drafts and reviews a camera-cut plan without replacing the episode. **Run shot autopilot** applies the plan after deterministic timing/graph checks and an explicit editorial pass. Both use the selected provider, model, and effort. A changed source invalidates a preview; failed reviews leave the episode intact. Applying replaces that episode's scene media bindings, so finish this stage before generating images.
+
+A dramatic scene groups multiple shot nodes. Each shot records its framing and a 5–10 second intended duration. Dialogue is budgeted at 2.2 words per second with 1.5 seconds reserved for pauses/action. The editor shows overflow and production batches refuse oversized timed shots. This is a planning estimate; spoken delivery still needs review. A decision's question is staged before a quiet loop, which can repeat while the viewer chooses. The server preserves the existing branch targets and outcomes when splitting.
+
+Draft visual bindings can select a character image from the gallery. This fixed identity anchor accompanies subsequent shots and branches without changing the Universe's approved identity pack. Locked production continues to require approved canon; selecting a draft reference does not approve it. Draft anchors travel with the FableLoom asset manifest when sharing is enabled.
+
+### Reactor video previews
+
+Reactor FastH3 uses a live SDK session: upload the storyboard image, enqueue one
+shot, play it once, capture its video and native audio, then disconnect. Install
+the pinned SDK with `npm run setup:reactor` (Python 3.11+ and ffmpeg required).
+`REACTOR_PYTHON_PATH` can select an existing SDK environment. Installation is
+explicit; starting PortOS never installs or opens a Reactor session.
+
+The outline and shot editor show incoming reference images beside the current
+shot, including every incoming branch at a convergence. Review room geometry,
+lighting, props, wardrobe and camera direction together, then approve the current
+storyboard. FableLoom Reactor renders require that approved first frame even in
+draft mode. Prompt instructions exclude subtitles and dialogue overlays, but
+generated previews still need visual review.
+
+Keep preview batches small before authorizing an episode render. Each request
+uses its reference image and a prompt of at most 800 characters; longer prompts
+are rejected rather than silently losing dialogue. Reactor accepts 5.167–14.375
+seconds and snaps durations to its frame grid. Local interactive voice profiles
+are independent of Reactor's generated audio. Cross-request clip chaining is not
+supported because Reactor clip IDs belong to the session that generated them.
diff --git a/package.json b/package.json
index 7003551bdf..356dc28e6b 100644
--- a/package.json
+++ b/package.json
@@ -29,6 +29,7 @@
"migrations": "node scripts/run-migrations.js",
"setup": "node scripts/checkNodeVersion.js && node scripts/checkNpmVersion.js && git submodule update --init --recursive && npm install --no-save && npm install --no-save --prefix client && npm install --no-save --prefix server && npm install --no-save --prefix autofixer && node scripts/trusted-rebuilds.js server && node scripts/setup-data.js && node scripts/setup-db.js && node scripts/setup-llm.js && node scripts/setup-browser.js && node scripts/setup-cert.js && node scripts/setup-guide.js",
"setup:data": "node scripts/setup-data.js",
+ "setup:reactor": "node scripts/setup-reactor.js",
"setup:db": "node scripts/setup-db.js",
"setup:db:test": "npm run setup:db:test --prefix server",
"test:db": "npm run test:db --prefix server",
diff --git a/scripts/migrations/319-fableloom-protagonist-continuity.js b/scripts/migrations/319-fableloom-protagonist-continuity.js
index d1d9c7bb26..ca035a9fe6 100644
--- a/scripts/migrations/319-fableloom-protagonist-continuity.js
+++ b/scripts/migrations/319-fableloom-protagonist-continuity.js
@@ -13,8 +13,8 @@ export const ACCEPTED_OLD_MD5 = {
export const NEW_SHIPPED_MD5 = {
'fableloom-weave-episode.md': 'abea2442af2be2039b70deee4919c00e',
- 'fableloom-outline-episode.md': '820b8c157c1977b34eb317e44236519e',
- 'fableloom-review-episode-outline.md': '8154b4c289b10268df8fd3c625bcdac2',
+ 'fableloom-outline-episode.md': '2ff6fb72777ff0c6fc70f3afd0ddfd53',
+ 'fableloom-review-episode-outline.md': '0f549ed25dea8566ce2d3c515968783b',
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/324-fableloom-playable-challenge-contract.js b/scripts/migrations/324-fableloom-playable-challenge-contract.js
index 74d1b075ad..4a26bdafef 100644
--- a/scripts/migrations/324-fableloom-playable-challenge-contract.js
+++ b/scripts/migrations/324-fableloom-playable-challenge-contract.js
@@ -10,7 +10,7 @@ export const ACCEPTED_OLD_MD5 = {
export const NEW_SHIPPED_MD5 = {
'fableloom-generate-series-plan.md': '27336d8c64e6193aecd1ba697f52315e',
- 'fableloom-outline-episode.md': '820b8c157c1977b34eb317e44236519e',
+ 'fableloom-outline-episode.md': '2ff6fb72777ff0c6fc70f3afd0ddfd53',
'fableloom-weave-episode.md': 'abea2442af2be2039b70deee4919c00e',
};
diff --git a/scripts/migrations/349-fableloom-plan-synopsis-sync.js b/scripts/migrations/349-fableloom-plan-synopsis-sync.js
new file mode 100644
index 0000000000..e002ef891b
--- /dev/null
+++ b/scripts/migrations/349-fableloom-plan-synopsis-sync.js
@@ -0,0 +1,17 @@
+/** Keep episode summaries synchronized when the series plan changes. */
+import { makePromptReplaceMigration } from './_lib.js';
+
+export const ACCEPTED_OLD_MD5 = {
+ 'fableloom-feedback-series-plan.md': ['6c4f6c846acc6186eaa8da297080b9d9'],
+};
+export const NEW_SHIPPED_MD5 = {
+ 'fableloom-feedback-series-plan.md': '2d1b40041223baa02a1517a102f103c2',
+};
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'FableLoom episode synopsis synchronization',
+ customizedHint: (filename) => ` Merge episodeSynopsisEdits support from data.reference/prompts/stages/${filename}.`,
+});
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/349-fableloom-plan-synopsis-sync.test.js b/scripts/migrations/349-fableloom-plan-synopsis-sync.test.js
new file mode 100644
index 0000000000..f00d6228f2
--- /dev/null
+++ b/scripts/migrations/349-fableloom-plan-synopsis-sync.test.js
@@ -0,0 +1,6 @@
+import { describe } from 'vitest';
+import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './349-fableloom-plan-synopsis-sync.js';
+import { runPromptMigrationTests } from './_testHelpers.js';
+describe('migration 349 — FableLoom synopsis synchronization', () => {
+ runPromptMigrationTests({ migration, applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5, prefix: 'migration-349-' });
+});
diff --git a/scripts/migrations/350-fableloom-opening-comprehension.js b/scripts/migrations/350-fableloom-opening-comprehension.js
new file mode 100644
index 0000000000..a9935e6c83
--- /dev/null
+++ b/scripts/migrations/350-fableloom-opening-comprehension.js
@@ -0,0 +1,22 @@
+/** Teach existing installs to establish character stakes before mystery mechanics. */
+import { makePromptReplaceMigration } from './_lib.js';
+
+export const ACCEPTED_OLD_MD5 = {
+ "fableloom-outline-episode.md": [
+ "820b8c157c1977b34eb317e44236519e"
+ ],
+ "fableloom-review-episode-outline.md": [
+ "8154b4c289b10268df8fd3c625bcdac2"
+ ]
+};
+export const NEW_SHIPPED_MD5 = {
+ "fableloom-outline-episode.md": "2ff6fb72777ff0c6fc70f3afd0ddfd53",
+ "fableloom-review-episode-outline.md": "0f549ed25dea8566ce2d3c515968783b"
+};
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5, current: NEW_SHIPPED_MD5,
+ label: 'FableLoom opening comprehension',
+ customizedHint: (filename) => ` Merge opening comprehension guidance from data.reference/prompts/stages/${filename}.`,
+});
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/350-fableloom-opening-comprehension.test.js b/scripts/migrations/350-fableloom-opening-comprehension.test.js
new file mode 100644
index 0000000000..d0ae6b5fb5
--- /dev/null
+++ b/scripts/migrations/350-fableloom-opening-comprehension.test.js
@@ -0,0 +1,6 @@
+import { describe } from 'vitest';
+import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './350-fableloom-opening-comprehension.js';
+import { runPromptMigrationTests } from './_testHelpers.js';
+describe('migration 350 — opening comprehension', () => {
+ runPromptMigrationTests({ migration, applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5, prefix: 'migration-350-' });
+});
diff --git a/scripts/migrations/351-fableloom-timed-shots.js b/scripts/migrations/351-fableloom-timed-shots.js
new file mode 100644
index 0000000000..b83722d8c3
--- /dev/null
+++ b/scripts/migrations/351-fableloom-timed-shots.js
@@ -0,0 +1,3 @@
+/** Add opt-in timed-shot planning; existing episodes remain unchanged. */
+import { makeSeedMigrations } from './_seedStageHelpers.js';
+export default makeSeedMigrations(['fableloom-plan-shots', 'fableloom-review-shots']);
diff --git a/scripts/migrations/351-fableloom-timed-shots.test.js b/scripts/migrations/351-fableloom-timed-shots.test.js
new file mode 100644
index 0000000000..7227bc9adc
--- /dev/null
+++ b/scripts/migrations/351-fableloom-timed-shots.test.js
@@ -0,0 +1,4 @@
+import { describe } from 'vitest';
+import migration from './351-fableloom-timed-shots.js';
+import { runSeedStageMigrationTests } from './_seedStageTestHelpers.js';
+describe('timed shot stages', () => { runSeedStageMigrationTests({ migration, stages: ['fableloom-plan-shots', 'fableloom-review-shots'], prefix: 'migration-351-' }); });
diff --git a/scripts/migrations/352-fableloom-shot-visual-continuity.js b/scripts/migrations/352-fableloom-shot-visual-continuity.js
new file mode 100644
index 0000000000..4237588a73
--- /dev/null
+++ b/scripts/migrations/352-fableloom-shot-visual-continuity.js
@@ -0,0 +1,22 @@
+/** Upgrade shot direction and review before image-to-video production. */
+import { makePromptReplaceMigration } from './_lib.js';
+
+export const ACCEPTED_OLD_MD5 = {
+ "fableloom-plan-shots.md": [
+ "4cf0fb96d4e9a17a8ae8285ec134f37f"
+ ],
+ "fableloom-review-shots.md": [
+ "699ba1189f67338728b74834269759a9"
+ ]
+};
+export const NEW_SHIPPED_MD5 = {
+ "fableloom-plan-shots.md": "9b1cd4b406ee327d6dc3fcbd57b48483",
+ "fableloom-review-shots.md": "8cf5fe685cc5f75537caddea1d272a00"
+};
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5, current: NEW_SHIPPED_MD5,
+ label: 'FableLoom shot visual continuity',
+ customizedHint: (filename) => ` Merge shot continuity and no-subtitle direction from data.reference/prompts/stages/${filename}.`,
+});
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/352-fableloom-shot-visual-continuity.test.js b/scripts/migrations/352-fableloom-shot-visual-continuity.test.js
new file mode 100644
index 0000000000..dd0f867f5a
--- /dev/null
+++ b/scripts/migrations/352-fableloom-shot-visual-continuity.test.js
@@ -0,0 +1,6 @@
+import { describe } from 'vitest';
+import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './352-fableloom-shot-visual-continuity.js';
+import { runPromptMigrationTests } from './_testHelpers.js';
+describe('migration 352 — shot visual continuity', () => {
+ runPromptMigrationTests({ migration, applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5, prefix: 'migration-352-' });
+});
diff --git a/scripts/reactor-render.py b/scripts/reactor-render.py
new file mode 100644
index 0000000000..576ad0d48d
--- /dev/null
+++ b/scripts/reactor-render.py
@@ -0,0 +1,180 @@
+"""Render one FastH3 clip through Reactor's SDK; JSON input/output over stdio.
+
+Credentials arrive only over stdin. No session opens before an explicit render.
+The SDK's decoded video/audio tracks are captured while the clip plays, then
+muxed locally. See https://www.reactor.inc/models/fast-h3/api.
+"""
+import asyncio
+import json
+import math
+import signal
+import sys
+import shutil
+from pathlib import Path
+
+from reactor_sdk import Reactor
+
+
+def emit(kind, **fields):
+ print(json.dumps({"type": kind, **fields}), flush=True)
+
+
+def payload(reply):
+ return reply.get("data", reply) if isinstance(reply, dict) else {}
+
+
+async def render(params):
+ prompt = params.get("prompt", "").strip()
+ seconds = float(params.get("seconds", 8))
+ if not prompt or len(prompt) > 800 or not math.isfinite(seconds) or not 5.167 <= seconds <= 14.375:
+ raise ValueError("A prompt of 1–800 characters and duration of 5.167–14.375 seconds are required")
+ if not params.get("jwt") or not params.get("outputPath"):
+ raise ValueError("Session token and output path are required")
+ source = params.get("sourceImagePath")
+ if source and not Path(source).is_file():
+ raise ValueError("Starting frame is missing")
+ output = Path(params["outputPath"])
+ output.parent.mkdir(parents=True, exist_ok=True)
+ reactor = Reactor("reactor/fast-h3", jwt=params["jwt"])
+ generated = asyncio.Event()
+ finished = asyncio.Event()
+ state = {
+ "active": False, "frames": 0, "error": None, "size": None, "audio": None,
+ "videoBuffers": [], "audioBuffers": [], "timestamps": [],
+ }
+
+ def on_message(message):
+ kind = message.get("type")
+ if kind in ("command_error", "clip_failed"):
+ state["error"] = "Reactor rejected the clip or command"
+ generated.set()
+ finished.set()
+ elif kind == "clip_generated":
+ generated.set()
+ elif kind == "clip_started":
+ state["active"] = True
+ elif kind in ("clip_finished", "clip_stopped"):
+ finished.set()
+
+ reactor.on("message", on_message)
+ phase = "connecting"
+ try:
+ emit("status", message="Connecting to Reactor")
+ await asyncio.wait_for(reactor.connect(), 60)
+ scratch_path = Path(str(output) + ".capture")
+ scratch_path.mkdir(parents=True, exist_ok=True)
+ raw_video = scratch_path / "video.bgra"
+ raw_audio = scratch_path / "audio.pcm"
+ with raw_video.open("wb") as video, raw_audio.open("wb") as audio:
+ def on_video(bgra, width, height, frame_id, timestamp_us, user_data):
+ if state["active"] and len(state["videoBuffers"]) < 370:
+ state["timestamps"].append(timestamp_us)
+ state["size"] = (width, height)
+ state["videoBuffers"].append(bytes(bgra))
+ state["frames"] += 1
+
+ def on_audio(pcm, num_samples, sample_rate, num_channels):
+ if state["active"]:
+ state["audio"] = (sample_rate, num_channels)
+ state["audioBuffers"].append(bytes(pcm))
+
+ reactor.tracks.with_direction("recvonly").with_kind("video").one().on_raw_frame(on_video)
+ reactor.tracks.with_direction("recvonly").with_kind("audio").one().on_raw_frame(on_audio)
+ phase = "canvas"
+ await reactor.send_command("set_canvas", {"aspect": "16:9"})
+ request = {"prompt": prompt, "seconds": seconds}
+ if params.get("seed") is not None:
+ request["seed"] = int(params["seed"])
+ if source:
+ phase = "uploading"
+ request["starting_frame"] = await reactor.upload_file(source)
+ phase = "enqueue"
+ reply = payload(await reactor.send_command("enqueue", request))
+ clip = reply.get("clip")
+ if not clip or not clip.get("clip_id"):
+ raise RuntimeError("Reactor did not acknowledge the clip")
+ emit("status", message="Rendering clip", seconds=clip.get("seconds"))
+ phase = "generating"
+ await asyncio.wait_for(generated.wait(), 180)
+ if state["error"]:
+ raise RuntimeError(state["error"])
+ phase = "playing"
+ state["active"] = True
+ await reactor.send_command("play", {"clip_id": clip["clip_id"]})
+ await asyncio.wait_for(finished.wait(), seconds + 30)
+ await asyncio.sleep(0.5)
+ state["active"] = False
+ frames = state.pop("videoBuffers")
+ expected = int(clip.get("frames", round(seconds * 24)))
+ # WebRTC may skip decoded frames. Keep presentation time (and audio
+ # sync) by holding the previous frame across timestamp gaps.
+ if frames:
+ timestamps = state["timestamps"]
+ first = timestamps[0]
+ cursor = 0
+ for index in range(expected):
+ target = first + index * 1_000_000 / 24
+ while cursor + 1 < len(frames) and timestamps[cursor + 1] <= target:
+ cursor += 1
+ video.write(frames[cursor])
+ del frames
+ audio.writelines(state.pop("audioBuffers"))
+
+ if state["error"]:
+ raise RuntimeError(state["error"])
+ phase = "capture"
+ expected = clip.get("frames", round(seconds * 24))
+ (scratch_path / "capture.json").write_text(json.dumps({"frames": state["frames"], "expected": expected, "size": state["size"], "audio": state["audio"], "clipId": clip["clip_id"]}))
+ emit("status", message=f"Captured {state['frames']} of {expected} frames; audio={bool(state['audio'])}")
+ if state["frames"] < expected * 0.8 or not state["audio"]:
+ raise RuntimeError(f"Incomplete stream capture: {state['frames']} of {expected} video frames")
+ width, height = state["size"]
+ sample_rate, channels = state["audio"]
+ command = ["ffmpeg", "-y", "-v", "error", "-f", "rawvideo", "-pixel_format", "bgra",
+ "-video_size", f"{width}x{height}", "-framerate", "24", "-i", str(raw_video),
+ "-f", "s16le", "-ar", str(sample_rate), "-ac", str(channels), "-i", str(raw_audio),
+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "18", "-pix_fmt", "yuv420p",
+ "-c:a", "aac", "-af", "apad", "-t", str(expected / 24),
+ "-movflags", "+faststart", str(output)]
+ phase = "encoding"
+ encoder = await asyncio.create_subprocess_exec(*command, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL)
+ try:
+ await asyncio.wait_for(encoder.wait(), 60)
+ finally:
+ if encoder.returncode is None:
+ encoder.terminate()
+ try:
+ await asyncio.wait_for(encoder.wait(), 2)
+ except asyncio.TimeoutError:
+ encoder.kill()
+ await encoder.wait()
+ if encoder.returncode or not output.is_file() or output.stat().st_size == 0:
+ raise RuntimeError("Could not encode the captured Reactor clip")
+ shutil.rmtree(scratch_path)
+ emit("complete", clipId=clip["clip_id"], seconds=expected / 24)
+ except Exception as error:
+ emit("error", phase=phase, errorType=type(error).__name__)
+ raise
+ finally:
+ try:
+ await asyncio.wait_for(reactor.disconnect(), 10)
+ except Exception:
+ emit("status", message="Session cleanup did not acknowledge disconnect")
+
+
+async def main():
+ params = json.loads(sys.stdin.readline())
+ task = asyncio.create_task(render(params))
+ loop = asyncio.get_running_loop()
+ if sys.platform != "win32":
+ loop.add_signal_handler(signal.SIGTERM, task.cancel)
+ await task
+
+
+if __name__ == "__main__":
+ try:
+ asyncio.run(main())
+ except (Exception, asyncio.CancelledError) as error:
+ # SDK exceptions may carry remote response internals; never print credentials.
+ emit("error", message="Reactor render failed", errorType=type(error).__name__)
+ sys.exit(1)
diff --git a/scripts/reactor-render.test.js b/scripts/reactor-render.test.js
new file mode 100644
index 0000000000..311f492ce0
--- /dev/null
+++ b/scripts/reactor-render.test.js
@@ -0,0 +1,17 @@
+import { execFileSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, it } from 'vitest';
+import { resolveTestPython } from '../server/lib/testHelper.js';
+
+const python = resolveTestPython();
+const testScript = fileURLToPath(new URL('./reactor_render_test.py', import.meta.url));
+
+describe.skipIf(!python)('Reactor stream capture lifecycle', () => {
+ it('captures decoder tails, rejects incomplete streams, and reaps cancelled encoders offline', () => {
+ expect(() => execFileSync(python, [testScript], {
+ encoding: 'utf8', timeout: 10000,
+ env: { ...process.env, PYTHONIOENCODING: 'utf-8' },
+ stdio: 'pipe',
+ })).not.toThrow();
+ });
+});
diff --git a/scripts/reactor_render_test.py b/scripts/reactor_render_test.py
new file mode 100644
index 0000000000..65d57d6dad
--- /dev/null
+++ b/scripts/reactor_render_test.py
@@ -0,0 +1,152 @@
+"""Offline Reactor capture boundary tests; no SDK, network, or encoder required."""
+import asyncio
+import importlib.util
+import io
+import json
+import sys
+import tempfile
+import unittest
+from contextlib import redirect_stdout
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, patch
+
+
+def load_runner():
+ spec = importlib.util.spec_from_file_location("reactor_render_test_target", Path(__file__).with_name("reactor-render.py"))
+ module = importlib.util.module_from_spec(spec)
+ with patch.dict(sys.modules, {"reactor_sdk": SimpleNamespace(Reactor=None)}):
+ spec.loader.exec_module(module)
+ return module
+
+
+class FakeReactor:
+ def __init__(self, complete=True):
+ self.commands = []
+ self.callbacks = {}
+ self.tracks = self
+ self.skipped = set(range(2, 138, 5))
+ self.delivered = [index for index in range(144) if index not in self.skipped]
+ if not complete:
+ self.delivered.pop() # 115/144 is just below the 80% admission threshold.
+ self.disconnected = False
+
+ def on(self, kind, callback):
+ self.message = callback
+
+ async def connect(self):
+ pass
+
+ async def disconnect(self):
+ self.disconnected = True
+
+ def with_direction(self, direction):
+ return self
+
+ def with_kind(self, kind):
+ self.kind = kind
+ return self
+
+ def one(self):
+ return self
+
+ def on_raw_frame(self, callback):
+ self.callbacks[self.kind] = callback
+
+ def frame(self, index):
+ # Nonzero PTS origin, and integer microseconds like the decoded SDK track.
+ timestamp = 9_000_000 + int(index * 1_000_000 / 24)
+ self.callbacks["video"](bytes([index]) * 16, 2, 2, index, timestamp, None)
+
+ async def send_command(self, name, data):
+ self.commands.append((name, data))
+ if name == "enqueue":
+ self.frame(255) # Idle preview must not become a paid clip frame.
+ self.message({"type": "clip_generated"})
+ return {"data": {"clip": {"clip_id": "example-clip", "frames": 144.0, "seconds": 6}}}
+ if name == "play":
+ self.frame(0) # Track delivery may precede the clip_started message.
+ self.message({"type": "clip_started"})
+ self.frame(1)
+ self.callbacks["audio"](b"\x01\x00" * 144000, 144000, 24000, 1)
+ self.message({"type": "clip_finished"})
+ return {}
+
+ async def drain(self, delay):
+ for index in self.delivered[2:]:
+ self.frame(index) # Decoder output can trail clip_finished.
+
+
+class CaptureLifecycleTest(unittest.IsolatedAsyncioTestCase):
+ def setUp(self):
+ self.runner = load_runner()
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.output = Path(self.temp.name) / "render.mp4"
+ self.params = {"prompt": "A paper boat drifts.", "seconds": 6, "jwt": "example-token", "outputPath": str(self.output)}
+
+ async def run_capture(self, reactor, spawn):
+ log = io.StringIO()
+ with patch.object(self.runner, "Reactor", return_value=reactor), \
+ patch.object(self.runner.asyncio, "sleep", reactor.drain), \
+ patch.object(self.runner.asyncio, "create_subprocess_exec", spawn), redirect_stdout(log):
+ await self.runner.render(self.params)
+ return [json.loads(line) for line in log.getvalue().splitlines()]
+
+ async def test_timestamp_gaps_hold_previous_frame_without_shortening_video_or_audio(self):
+ reactor = FakeReactor()
+
+ async def encode(*command, **kwargs):
+ video = Path(command[command.index("-i") + 1]).read_bytes()
+ expected = [index - 1 if index in reactor.skipped else index for index in range(144)]
+ self.assertEqual(video, b"".join(bytes([index]) * 16 for index in expected))
+ self.assertEqual(Path(str(self.output) + ".capture/audio.pcm").read_bytes(), b"\x01\x00" * 144000)
+ self.assertEqual(command[command.index("-t") + 1], "6.0")
+ self.assertEqual(command[command.index("-framerate") + 1], "24")
+ capture = json.loads(Path(str(self.output) + ".capture/capture.json").read_text())
+ self.assertEqual(capture["frames"], 116)
+ self.assertEqual(capture["expected"], 144)
+ self.output.write_bytes(b"example-mp4")
+ return SimpleNamespace(returncode=0, wait=AsyncMock(return_value=0))
+
+ spawn = AsyncMock(side_effect=encode)
+ events = await self.run_capture(reactor, spawn)
+ self.assertEqual([name for name, _ in reactor.commands], ["set_canvas", "enqueue", "play"])
+ self.assertEqual(events[-1], {"type": "complete", "clipId": "example-clip", "seconds": 6.0})
+ self.assertTrue(reactor.disconnected)
+ self.assertFalse(Path(str(self.output) + ".capture").exists())
+ spawn.assert_awaited_once()
+
+ async def test_capture_just_below_eighty_percent_disconnects_without_encoding_or_retrying(self):
+ reactor = FakeReactor(complete=False)
+ spawn = AsyncMock()
+ with self.assertRaisesRegex(RuntimeError, "115 of 144"):
+ await self.run_capture(reactor, spawn)
+ self.assertTrue(reactor.disconnected)
+ self.assertEqual(sum(name == "enqueue" for name, _ in reactor.commands), 1)
+ spawn.assert_not_awaited()
+ self.assertTrue(Path(str(self.output) + ".capture/video.bgra").is_file())
+
+ async def test_cancelled_encoder_is_terminated_then_killed_and_reaped(self):
+ reactor = FakeReactor()
+ encoder = SimpleNamespace(returncode=None)
+ encoder.wait = AsyncMock(side_effect=[asyncio.CancelledError(), asyncio.TimeoutError(), -9])
+ encoder.terminate = unittest.mock.Mock()
+ encoder.kill = unittest.mock.Mock()
+ with self.assertRaises(asyncio.CancelledError):
+ await self.run_capture(reactor, AsyncMock(return_value=encoder))
+ encoder.terminate.assert_called_once()
+ encoder.kill.assert_called_once()
+ self.assertEqual(encoder.wait.await_count, 3)
+ self.assertTrue(reactor.disconnected)
+
+ async def test_invalid_request_never_constructs_a_session(self):
+ with patch.object(self.runner, "Reactor") as factory:
+ for change in ({"prompt": ""}, {"seconds": float("nan")}, {"sourceImagePath": str(Path(self.temp.name) / "missing.png")}):
+ with self.subTest(change=change), self.assertRaises(ValueError):
+ await self.runner.render({**self.params, **change})
+ factory.assert_not_called()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/requirements-reactor.txt b/scripts/requirements-reactor.txt
new file mode 100644
index 0000000000..54dc145537
--- /dev/null
+++ b/scripts/requirements-reactor.txt
@@ -0,0 +1 @@
+reactor-sdk==1.0.1
diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.js
index e4f4581982..1a504fe4dc 100644
--- a/scripts/setup-data-drift.test.js
+++ b/scripts/setup-data-drift.test.js
@@ -60,8 +60,11 @@ const EXPECTED_STAGE_OLD = {
'fableloom-play-turn.md': ['bb33dc9bc483668d88196ca972d5f364'],
'fableloom-feedback-episode.md': ['43d1525fcedce99b933ae5b003516a36', 'd09bb405478d24c294b0c658ef365cd1'],
'fableloom-review.md': ['2802f269f246e00ec5a8937637d42de6'],
- 'fableloom-outline-episode.md': ['3f5144103b2ab6203fa071ff5026251b', '513b2b5b8fa98766852cdde7b87198c9'],
- 'fableloom-review-episode-outline.md': ['96d631104155ff11be08bcc5144cca1c'],
+ 'fableloom-outline-episode.md': ['3f5144103b2ab6203fa071ff5026251b', '513b2b5b8fa98766852cdde7b87198c9', '820b8c157c1977b34eb317e44236519e'],
+ 'fableloom-review-episode-outline.md': ['96d631104155ff11be08bcc5144cca1c', '8154b4c289b10268df8fd3c625bcdac2'],
+ 'fableloom-feedback-series-plan.md': ['6c4f6c846acc6186eaa8da297080b9d9'],
+ 'fableloom-plan-shots.md': ['4cf0fb96d4e9a17a8ae8285ec134f37f'],
+ 'fableloom-review-shots.md': ['699ba1189f67338728b74834269759a9'],
'fableloom-generate-series-plan.md': ['2591cf4ca6cc160765f029fcc497dc35'],
};
const EXPECTED_STAGE_NEW = {
@@ -101,8 +104,11 @@ const EXPECTED_STAGE_NEW = {
'fableloom-play-turn.md': 'e35ad91aae263e3adf28d1e047a46661',
'fableloom-feedback-episode.md': '1aaa6f17acad6a3215e48dcce14e8670',
'fableloom-review.md': 'c26a641f6d0530caef7d1186c3b09937',
- 'fableloom-outline-episode.md': '820b8c157c1977b34eb317e44236519e',
- 'fableloom-review-episode-outline.md': '8154b4c289b10268df8fd3c625bcdac2',
+ 'fableloom-outline-episode.md': '2ff6fb72777ff0c6fc70f3afd0ddfd53',
+ 'fableloom-review-episode-outline.md': '0f549ed25dea8566ce2d3c515968783b',
+ 'fableloom-feedback-series-plan.md': '2d1b40041223baa02a1517a102f103c2',
+ 'fableloom-plan-shots.md': '9b1cd4b406ee327d6dc3fcbd57b48483',
+ 'fableloom-review-shots.md': '8cf5fe685cc5f75537caddea1d272a00',
'fableloom-generate-series-plan.md': '27336d8c64e6193aecd1ba697f52315e',
};
const EXPECTED_PARTIAL_OLD = {
diff --git a/scripts/setup-reactor.js b/scripts/setup-reactor.js
new file mode 100644
index 0000000000..5c315f81ab
--- /dev/null
+++ b/scripts/setup-reactor.js
@@ -0,0 +1,20 @@
+#!/usr/bin/env node
+// Explicit install only: the cloud adapter never installs dependencies at boot.
+import { spawnSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { join } from 'node:path';
+const root = fileURLToPath(new URL('..', import.meta.url));
+const venv = join(root, 'data', 'venvs', 'reactor');
+const bootstrap = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
+const python = join(venv, process.platform === 'win32' ? 'Scripts/python.exe' : 'bin/python');
+for (const [executable, args] of [
+ [bootstrap, ['-m', 'venv', venv]],
+ [python, ['-m', 'pip', 'install', '-r', join(root, 'scripts', 'requirements-reactor.txt')]],
+]) {
+ const result = spawnSync(executable, args, { stdio: 'inherit', shell: false });
+ if (result.error || result.status !== 0) {
+ console.error('❌ Reactor SDK setup failed. Install Python 3.11+ and retry.');
+ process.exit(1);
+ }
+}
+console.log('✅ Reactor SDK installed. Video generation also requires ffmpeg on PATH.');
diff --git a/server/lib/README.md b/server/lib/README.md
index 62fc926bd6..5451571ff8 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -547,3 +547,4 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `eidoverseCityLayout.js` | Portable native building components, curated furniture placement, visitor chambers, and ordered signal bays for PortOS Commons. |
| `eidoverseCitySurface.js` | Deterministic GLB pedestrian paths, gathering terraces, and physical district signs, generated without AI and stored through Eidoverse's content-addressed upload API. |
+| `fableLoomShots.js` | Short-shot grouping, spoken-dialogue timing estimates and 5–10 second render validation. |
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index 80b3249c3a..890d94b04d 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -6865,6 +6865,22 @@
"server/routes/fableLoom.js"
]
},
+ {
+ "method": "POST",
+ "path": "/api/fableloom/:id/episodes/:episodeId/shots/apply",
+ "mountPath": "/api/fableloom",
+ "sources": [
+ "server/routes/fableLoom.js"
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/fableloom/:id/episodes/:episodeId/shots/plan",
+ "mountPath": "/api/fableloom",
+ "sources": [
+ "server/routes/fableLoom.js"
+ ]
+ },
{
"method": "GET",
"path": "/api/fableloom/:id/episodes/:episodeId/validate",
@@ -17748,8 +17764,8 @@
],
"stats": {
"mounts": 150,
- "operations": 2198,
- "declarations": 2206,
+ "operations": 2200,
+ "declarations": 2208,
"sourceFiles": 233
}
}
diff --git a/server/lib/fableLoomOutline.js b/server/lib/fableLoomOutline.js
index f1ed014e36..5418fef268 100644
--- a/server/lib/fableLoomOutline.js
+++ b/server/lib/fableLoomOutline.js
@@ -18,6 +18,7 @@ const isText = (value) => typeof value === 'string' && value.trim().length > 0;
export const OUTLINE_ISSUE_CODES = Object.freeze({
NO_SCENES: 'NO_SCENES',
+ WRONG_EPISODE_PLOT_POINT: 'WRONG_EPISODE_PLOT_POINT',
MISSING_START: 'MISSING_START',
START_NOT_FOUND: 'START_NOT_FOUND',
NO_ENDINGS: 'NO_ENDINGS',
@@ -176,7 +177,7 @@ const outlineIssue = (issues, code, severity, message, extra = {}) => {
/** Deterministic validation for the log-line graph, independent of an LLM. */
export function analyzeStoryOutline(outline, {
- participationMode = 'protagonist', requireAudienceIntroduction = false, challenges = [],
+ participationMode = 'protagonist', requireAudienceIntroduction = false, challenges = [], plotPoints = [], episodeId = null, nodes = [],
} = {}) {
const scenes = asArray(outline?.scenes);
const byKey = new Map(scenes.map((scene) => [scene.key, scene]));
@@ -195,9 +196,12 @@ export function analyzeStoryOutline(outline, {
const reachable = new Set();
const depthByKey = new Map();
+ const dramaticDepthByKey = new Map();
+ const groupByKey = new Map(asArray(nodes).map((node) => [node.id, node.shot?.dramaticSceneId || node.id]));
if (byKey.has(startKey)) {
const queue = [startKey];
depthByKey.set(startKey, 0);
+ dramaticDepthByKey.set(startKey, 0);
let cursor = 0;
while (cursor < queue.length) {
const key = queue[cursor];
@@ -207,6 +211,9 @@ export function analyzeStoryOutline(outline, {
for (const transition of asArray(byKey.get(key)?.transitions)) {
if (byKey.has(transition.targetKey) && !depthByKey.has(transition.targetKey)) {
depthByKey.set(transition.targetKey, depthByKey.get(key) + 1);
+ // Extra camera cuts do not make the audience introduction narratively later.
+ const sameScene = groupByKey.has(key) && groupByKey.get(key) === groupByKey.get(transition.targetKey);
+ dramaticDepthByKey.set(transition.targetKey, dramaticDepthByKey.get(key) + (sameScene ? 0 : 1));
queue.push(transition.targetKey);
}
}
@@ -231,13 +238,13 @@ export function analyzeStoryOutline(outline, {
'The outline never activates the audience communication channel.',
);
} else {
- const firstDepth = Math.min(...connected.map((scene) => depthByKey.get(scene.key)));
+ const firstDepth = Math.min(...connected.map((scene) => dramaticDepthByKey.get(scene.key)));
if (firstDepth > 3) {
push(
OUTLINE_ISSUE_CODES.LATE_AUDIENCE_CONNECTION,
'warning',
'The audience communication channel is not activated until late in the opening sequence.',
- { sceneKey: connected.find((scene) => depthByKey.get(scene.key) === firstDepth)?.key },
+ { sceneKey: connected.find((scene) => dramaticDepthByKey.get(scene.key) === firstDepth)?.key },
);
}
}
@@ -246,6 +253,10 @@ export function analyzeStoryOutline(outline, {
for (const scene of scenes) {
const transitions = asArray(scene.transitions);
const label = scene.title || scene.key || 'Untitled beat';
+ const assignedPlot = asArray(plotPoints).find((item) => item.id === scene.plotPointId);
+ if (episodeId && assignedPlot?.episodeId && assignedPlot.episodeId !== episodeId) {
+ push(OUTLINE_ISSUE_CODES.WRONG_EPISODE_PLOT_POINT, 'error', `"${label}" uses a plot point assigned to another episode. Keep that payoff in its assigned episode.`, { sceneKey: scene.key });
+ }
if (!isText(scene.summary)) {
push(OUTLINE_ISSUE_CODES.EMPTY_SUMMARY, 'error', `"${label}" has no scene log-line.`, { sceneKey: scene.key });
}
@@ -496,9 +507,12 @@ export function analyzeSeriesStoryOutlines(loom, { replacingEpisodeId = null } =
return;
}
const validation = analyzeStoryOutline(episode.storyOutline, {
+ nodes: episode.nodes,
participationMode: loom?.participationMode,
requireAudienceIntroduction: index === 0,
challenges: fableLoomEpisodeChallenges(loom, episode.id),
+ plotPoints: loom?.seriesPlan?.plotPoints,
+ episodeId: episode.id,
});
validation.issues.forEach((issue) => {
push(issue.code, issue.severity, `Episode ${episode.number || index + 1}: ${issue.message}`, {
diff --git a/server/lib/fableLoomOutline.test.js b/server/lib/fableLoomOutline.test.js
index 8a43be8438..8755861745 100644
--- a/server/lib/fableLoomOutline.test.js
+++ b/server/lib/fableLoomOutline.test.js
@@ -264,3 +264,12 @@ describe('FableLoom story beat outlines', () => {
}));
});
});
+
+it('measures audience introduction in dramatic scenes after a shot split', () => {
+ const scenes = Array.from({ length: 6 }, (_, index) => ({ key: `shot-${index}`, title: `Shot ${index}`, summary: 'An opening action.', playbackMode: 'cut', audienceConnection: index >= 4 ? 'connected' : 'disconnected', isEnding: index === 5, transitions: index < 5 ? [{ targetKey: `shot-${index + 1}`, intent: 'continue' }] : [] }));
+ const outline = { startKey: 'shot-0', scenes };
+ const options = { participationMode: 'helper', requireAudienceIntroduction: true };
+ expect(analyzeStoryOutline(outline, options).issues.some((issue) => issue.code === 'LATE_AUDIENCE_CONNECTION')).toBe(true);
+ const nodes = scenes.map((scene, index) => ({ id: scene.key, shot: { dramaticSceneId: index < 4 ? 'opening' : 'invitation' } }));
+ expect(analyzeStoryOutline(outline, { ...options, nodes }).issues.some((issue) => issue.code === 'LATE_AUDIENCE_CONNECTION')).toBe(false);
+});
diff --git a/server/lib/fableLoomProduction.js b/server/lib/fableLoomProduction.js
index 8edd750675..55944253b5 100644
--- a/server/lib/fableLoomProduction.js
+++ b/server/lib/fableLoomProduction.js
@@ -6,6 +6,7 @@
* evaluating readiness gates, and verifying exact-input provenance.
*/
+import { analyzeEpisodeShots } from './fableLoomShots.js';
import { computeGraphLayers } from './fableLoomGraph.js';
import { EFFORT_LEVELS } from './providerModels.js';
import { validateAudioOccupancy } from './fableLoomPlayback.js';
@@ -578,7 +579,7 @@ export function buildEpisodeProductionPlan({
for (const node of orderedNodes) {
const depth = depthById.get(node.id) ?? 0;
const preds = predecessorsByNodeId.get(node.id) || [];
- const nodeBlockers = [];
+ const nodeBlockers = analyzeEpisodeShots({ nodes: [node] }).issues.map((issue) => issue.message);
const visualCanon = node.visualCanon || null;
const lockedCanon = isLockedCanon(node);
const universeCharacters = Array.isArray(universe?.characters) ? universe.characters : [];
diff --git a/server/lib/fableLoomShots.js b/server/lib/fableLoomShots.js
new file mode 100644
index 0000000000..026aea5b04
--- /dev/null
+++ b/server/lib/fableLoomShots.js
@@ -0,0 +1,44 @@
+/** Pure timing and grouping contracts for short, individually rendered shots. */
+export const FABLELOOM_SHOT_MIN_SECONDS = 5;
+export const FABLELOOM_SHOT_MAX_SECONDS = 10;
+
+export function sanitizeShot(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ return {
+ dramaticSceneId: String(raw.dramaticSceneId || '').slice(0, 80),
+ dramaticSceneTitle: String(raw.dramaticSceneTitle || '').slice(0, 300),
+ durationSeconds: Number.isFinite(raw.durationSeconds) ? raw.durationSeconds : 8,
+ framing: String(raw.framing || '').slice(0, 500),
+ };
+}
+
+// Shared with the structured shot schema so every accepted speaker is counted.
+export const isShotSpeakerCue = (text) => typeof text === 'string' && !/^(?:INT\.|EXT\.|INT\/EXT\.|EST\.|CUT TO|FADE|TELEPLAY)/.test(text) && /^[\p{Lu}\d][\p{Lu}\d .’'()—\-/:&]{0,69}$/u.test(text);
+
+/** Fountain-style cues; action and parentheticals consume no spoken-word budget. */
+export function shotDialogueWords(prose = '') {
+ let speaking = false;
+ let words = 0;
+ for (const line of prose.split('\n')) {
+ const text = line.trim();
+ if (!text) { speaking = false; continue; }
+ if (/^(?:INT\.|EXT\.|INT\/EXT\.|EST\.|CUT TO|FADE|TELEPLAY)/.test(text)) { speaking = false; continue; }
+ if (!speaking && isShotSpeakerCue(text)) { speaking = true; continue; }
+ if (speaking && !/^\([^)]*\)$/.test(text)) words += text.match(/[\p{L}\p{N}]+(?:['’][\p{L}\p{N}]+)*/gu)?.length || 0;
+ }
+ return words;
+}
+
+export const estimatedShotSeconds = (prose) => Math.ceil((1.5 + shotDialogueWords(prose) / 2.2) * 10) / 10;
+
+export function analyzeEpisodeShots(episode) {
+ const issues = [];
+ const shots = (episode?.nodes || []).filter((node) => node.shot);
+ for (const node of shots) {
+ const duration = node.shot.durationSeconds;
+ if (duration < 5 || duration > 10 || !Number.isFinite(duration)) issues.push({ nodeId: node.id, code: 'SHOT_DURATION', message: `${node.title}: choose a 5–10 second shot duration.` });
+ if (estimatedShotSeconds(node.prose) > duration) issues.push({ nodeId: node.id, code: 'SHOT_DIALOGUE_OVERFLOW', message: `${node.title}: dialogue needs about ${estimatedShotSeconds(node.prose)} seconds in a ${duration}-second shot. Split or shorten it.` });
+ if (node.playbackMode === 'decision' && shotDialogueWords(node.prose)) issues.push({ nodeId: node.id, code: 'SHOT_LOOP_DIALOGUE', message: `${node.title}: put scripted dialogue before the silent decision loop; live conversation is separate.` });
+ }
+ return { issues, stats: { shotCount: shots.length, dramaticSceneCount: new Set(shots.map((node) => node.shot.dramaticSceneId)).size, totalAssetSeconds: shots.reduce((sum, node) => sum + node.shot.durationSeconds, 0), ready: shots.length > 0 && shots.length === episode.nodes.length && !issues.length } };
+}
diff --git a/server/lib/fableLoomValidation.js b/server/lib/fableLoomValidation.js
index 1a8a1b4df3..cd7270d970 100644
--- a/server/lib/fableLoomValidation.js
+++ b/server/lib/fableLoomValidation.js
@@ -6,6 +6,7 @@
*/
import { z } from 'zod';
+import { isShotSpeakerCue } from './fableLoomShots.js';
import { LOOM_LIMITS } from './fableLoomLimits.js';
import { LOOM_FORMATS } from './fableLoomFormats.js';
import {
@@ -228,6 +229,7 @@ const visualCanonSchema = z.object({
characterAppearances: z.array(z.object({
characterId: refId.unwrap(),
wardrobeId: refId.unwrap().nullable().optional(),
+ referenceImage: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]*\.(png|jpg|jpeg|webp)$/i).nullable().optional(),
expression: z.string().max(LOOM_LIMITS.VISUAL_NOTE_MAX).optional(),
continuityNotes: z.string().max(LOOM_LIMITS.VISUAL_NOTE_MAX).optional(),
})).max(LOOM_LIMITS.VISUAL_BINDINGS_MAX).optional(),
@@ -291,7 +293,13 @@ export const interactionWindowSchema = z.object({
holdLoopRotation: z.enum(FABLELOOM_HOLD_ROTATION_MODES).optional(),
}).nullable();
+export const shotMetadataSchema = z.object({
+ dramaticSceneId: z.string().min(1).max(80), dramaticSceneTitle: z.string().max(300),
+ durationSeconds: z.number().min(5).max(10), framing: z.string().max(500),
+});
+
const nodeFields = {
+ shot: shotMetadataSchema.nullable().optional(),
title: z.string().max(LOOM_LIMITS.NODE_TITLE_MAX).optional(),
prose: z.string().max(LOOM_LIMITS.PROSE_MAX).optional(),
plotPointId: z.string().max(LOOM_LIMITS.OUTLINE_KEY_MAX).nullable().optional(),
@@ -404,6 +412,7 @@ export const playthroughReviewSchema = z.object({
});
export const editorialAutopilotStartSchema = z.object({
+ mode: z.enum(['series', 'planning']).optional(),
maxRounds: z.number().int().min(1).max(LOOM_LIMITS.EDITORIAL_AUTOPILOT_ROUNDS_MAX).optional(),
maxPaths: z.number().int().min(1).max(FABLELOOM_PLAYTEST_LIMITS.MAX_PATHS).optional(),
// Opt-in post-mortem over content-free run counters. A confident PortOS
@@ -447,3 +456,15 @@ export const productionBatchCreateSchema = z.object({
});
export const continuityReviewSchema = z.object({});
+
+export const shotDraftSchema = z.object({
+ visibleCharacterIds: z.array(z.string().min(1).max(80)).max(32).optional(),
+ protagonistPresence: z.enum(['onscreen', 'offscreen']).optional(),
+ title: z.string().min(1).max(300), durationSeconds: z.number().min(5).max(10),
+ action: z.string().min(1).max(1200), framing: z.string().min(1).max(500),
+ dialogue: z.array(z.object({ speaker: z.string().min(1).max(70).refine((value) => isShotSpeakerCue(value.toUpperCase()), 'Use a screenplay speaker cue without line breaks or unsupported punctuation'), text: z.string().min(1).max(500) })).max(6),
+ imagePrompt: z.string().min(1).max(2000), videoPrompt: z.string().min(1).max(4000),
+});
+export const shotGroupsSchema = z.array(z.object({ sceneId: z.string().min(1).max(80), shots: z.array(shotDraftSchema).min(1).max(40) })).min(1).max(200);
+export const shotAutopilotSchema = outlineGenerateSchema.extend({ maxRounds: z.number().int().min(1).max(3).optional(), apply: z.boolean().optional() });
+export const shotApplySchema = z.object({ sourceFingerprint: z.string().length(64), groups: shotGroupsSchema });
diff --git a/server/lib/index.js b/server/lib/index.js
index 5379b2960e..0cc386d9d2 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -522,3 +522,4 @@ export * from './videoFailure.js';
export * from './eidoverseCityLayout.js';
export * from './eidoverseCitySurface.js';
+export * from './fableLoomShots.js';
diff --git a/server/lib/promptStageCallSites.generated.json b/server/lib/promptStageCallSites.generated.json
index 2d015aee52..ed8260573b 100644
--- a/server/lib/promptStageCallSites.generated.json
+++ b/server/lib/promptStageCallSites.generated.json
@@ -52,6 +52,9 @@
"fableloom-outline-episode": [
"server/services/fableLoom/weave.js"
],
+ "fableloom-plan-shots": [
+ "server/services/fableLoom/shots.js"
+ ],
"fableloom-play-turn": [
"server/services/fableLoom/weave.js"
],
@@ -73,6 +76,9 @@
"fableloom-review-series-teleplay": [
"server/services/fableLoom/weave.js"
],
+ "fableloom-review-shots": [
+ "server/services/fableLoom/shots.js"
+ ],
"fableloom-weave-episode": [
"server/services/fableLoom/weave.js"
],
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index a197b6c480..3760d4eb77 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -378,7 +378,8 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// v6 = the loom-level render pin gained image/video backend, model, and
// effort preferences. A v5 peer would preserve the format but strip these
// additive preferences during an unrelated whole-record update.
- fableLoom: 6,
+ // v7 = shot duration and dramatic-scene grouping survive whole-record sync.
+ fableLoom: 7,
// v1 = Creative Director projects (PostgreSQL `creative_director_projects`)
// federated via the per-record peer-sync push pipeline (record kind
// `creativeDirectorProject`, sync category `creativeDirectorProjects`, #1564).
diff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.js
index dfa9e09a41..585fcaba66 100644
--- a/server/lib/schemaVersions.test.js
+++ b/server/lib/schemaVersions.test.js
@@ -42,11 +42,11 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {
expect(PORTOS_SCHEMA_VERSIONS.mediaCollections).toBe(1);
});
- it('version-gates the persisted FableLoom render-settings shape', () => {
- // v5 adds renderSettings; v6 adds its image/video provider preferences.
+ it('version-gates the persisted FableLoom shot and reference shape', () => {
+ // v7 adds timed shots and draft character image anchors.
// Older peers stay behind the full render contract until they advertise
// support for the additive fields.
- expect(PORTOS_SCHEMA_VERSIONS.fableLoom).toBe(6);
+ expect(PORTOS_SCHEMA_VERSIONS.fableLoom).toBe(7);
});
it('version-gates the additive Creative Commission taste brief shape', () => {
diff --git a/server/routes/fableLoom.js b/server/routes/fableLoom.js
index 5acde874e6..7ef1a67879 100644
--- a/server/routes/fableLoom.js
+++ b/server/routes/fableLoom.js
@@ -12,6 +12,8 @@ import { Router } from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import {
+ shotAutopilotSchema,
+ shotApplySchema,
branchSchema,
episodeCreateSchema,
episodePatchSchema,
@@ -51,6 +53,8 @@ import {
} from '../lib/fableLoomPlayback.js';
import { getUniverse } from '../services/universeBuilder.js';
import {
+ runEpisodeShotAutopilot,
+ applyEpisodeShots,
addEpisode,
addNode,
addNodeTransition,
@@ -321,6 +325,13 @@ router.post('/:id/episodes/:episodeId/weave', asyncHandler(async (req, res) => {
// Story-first authoring: draft and review the small beat outline before the
// full teleplay graph is expanded. Validation is deterministic and persisted
// so the expansion button can enforce the same gate from every client.
+router.post('/:id/episodes/:episodeId/shots/plan', asyncHandler(async (req, res) => {
+ res.json(await runEpisodeShotAutopilot(req.params.id, req.params.episodeId, validateRequest(shotAutopilotSchema, req.body)));
+}));
+router.post('/:id/episodes/:episodeId/shots/apply', asyncHandler(async (req, res) => {
+ res.json(await applyEpisodeShots(req.params.id, req.params.episodeId, validateRequest(shotApplySchema, req.body)));
+}));
+
router.post('/:id/episodes/:episodeId/outline/generate', asyncHandler(async (req, res) => {
const input = validateRequest(outlineGenerateSchema, req.body);
res.json(await generateEpisodeOutline(req.params.id, req.params.episodeId, input));
diff --git a/server/services/dataManager.js b/server/services/dataManager.js
index 5d19624b45..30fb45bda2 100644
--- a/server/services/dataManager.js
+++ b/server/services/dataManager.js
@@ -110,6 +110,7 @@ export const CATEGORIES = {
'pipeline-series-review': { label: 'Series Review', description: 'Cached series reviews — re-running them costs LLM calls', archivable: true, deletable: false },
'privacy': { label: 'Privacy', description: 'Data-broker opt-out records and request history', archivable: true, deletable: false },
'prompts': { label: 'Prompts', description: 'AI prompt templates', archivable: false, deletable: false },
+ 'venvs': { label: 'Optional SDK Runtimes', description: 'Explicitly installed Python environments for media SDKs; reinstall with the corresponding setup command', archivable: false, deletable: false },
'python': { label: 'Python Runtime', description: 'Managed virtualenv for local ML tooling — rebuilt on the next Python-backed run (re-downloads several GB of wheels)', archivable: false, deletable: true, purgeScope: 'category' },
// A pasted or URL-fetched book is the user's only copy — the shelf is not a
// cache of anything re-fetchable, so it is neither archivable nor deletable.
diff --git a/server/services/fableLoom/README.md b/server/services/fableLoom/README.md
index 8717335eef..c1f2a97106 100644
--- a/server/services/fableLoom/README.md
+++ b/server/services/fableLoom/README.md
@@ -11,7 +11,7 @@ intent to a transition and moves them through the graph until an ending.
| `visualConditioning.js` | Compiles stable scene canon bindings into capability-budgeted prompts, typed reference assets, local character adapters, and durable render provenance. |
| `weave.js` | AI ops via `runStagedLLM`: `generateSeriesPlan` (full arc / plot-point / side-quest scaffold), `generateEpisodeOutline` + `validateEpisodeOutline` + `reviewEpisodeOutline` (log-line beat planning before teleplay expansion), `weaveEpisode` (single-camera-cut graph with automatic cuts and looping decisions), `branchNode` (grow paths), `feedbackEpisode` (apply a conversational sparse patch to one episode), `reviewEpisode` + `reviewSeriesTeleplay` (episode or complete-series critique with 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). |
| `editorial.js` | Whole-series AI evaluate-and-remediate pass plus deterministic/AI playthrough review. Preserves episode/scene/path membership and IDs, validates generated outlines, rejects graph regressions, and applies story-aware convergence sources. |
-| `editorialAutopilot.js` | User-triggered bounded editor/reviewer loop: remediate, exercise every bounded branch variation, judge story quality, then complete, pause on residuals/plateau, fail, or cancel cooperatively. |
+| `editorialAutopilot.js` | User-triggered planning-only mode (plan review before sequential episode outlines, no teleplay/media) and bounded editor/reviewer loop: remediate, exercise every bounded branch variation, judge story quality, then complete, pause on residuals/plateau, fail, or cancel cooperatively. |
| `editorialSelfImprove.js` | Opt-in, budget-gated post-mortem for paused/failed editorial-autopilot runs. Sends only content-free counters to a diagnostic stage and queues a deduplicated, approval-gated PortOS CoS task for confident workflow defects. |
| `formats.js` | Scene formats (`prose` / `teleplay`) and the prompt contracts each generative stage renders for them. |
| `hostedSession.js` | Scoped QR-hosted play session lifecycle, HTTPS readiness preflight, token hashing, live voice gate revalidation, half-duplex turn taking (#5383), and the expired-session sweeper armed from bootstrap (#5660). |
@@ -23,3 +23,5 @@ intent to a transition and moves them through the graph until an ending.
Pure graph analysis (validation, BFS layering, prompt rendering) lives in
`server/lib/fableLoomGraph.js`. Federation uses the opt-in per-record
`fableLoom` category, conflict-journal recovery, and scene-media asset manifests.
+
+| `shots.js` | Episode-scoped shot autopilot, reviewable 5–10 second plans, deterministic branch-preserving application and stale-plan protection. |
diff --git a/server/services/fableLoom/editorialAutopilot.js b/server/services/fableLoom/editorialAutopilot.js
index b67bfe1ac3..b8349b868b 100644
--- a/server/services/fableLoom/editorialAutopilot.js
+++ b/server/services/fableLoom/editorialAutopilot.js
@@ -306,12 +306,78 @@ async function runRound(run, guidance) {
return runRound(run, guidanceFromFindings(residual, playtest.review?.summary));
}
+// Planning is an explicit, bounded phase: finish the series contract before
+// drafting any episode, and never expand a teleplay or approve production here.
+async function runPlanning(run) {
+ const { reviewSeriesPlan, feedbackSeriesPlan, generateEpisodeOutline, reviewEpisodeOutline, validateEpisodeOutline } = await import('./weave.js');
+ const { analyzeSeriesStoryOutlines } = await import('../../lib/fableLoomOutline.js');
+ const options = routeOptions(run);
+ const initial = await requireLoomForRun(run.loomId);
+ if (run.cancelRequested) return finishCanceled(run);
+ if (!initial.seriesPlan?.storyArc?.trim() || (initial.seriesPlan?.plotPoints || []).some((item) => !initial.episodes.some((episode) => episode.id === item.episodeId))) {
+ return finishPaused(run, 'planning-required', 'Save the story arc and assign every plot point and challenge to an episode before starting planning autopilot.');
+ }
+ touch(run, { round: 1, currentStep: 'review-plan', stepIndex: 1, stepLabel: 'Review series plan', message: 'Checking the series arc and challenge assignments before drafting episode outlines…' });
+ const review = await reviewSeriesPlan(run.loomId, { ...options, planningOnly: true });
+ if (run.cancelRequested) return finishCanceled(run);
+ let planFindings = review.analysis.risks;
+ for (let attempt = 1; planFindings.length && attempt <= run.maxRounds; attempt += 1) {
+ touch(run, { currentStep: 'repair-plan', stepLabel: 'Refine series plan', message: 'Resolving planning findings before episode outlines…' });
+ await feedbackSeriesPlan(run.loomId, { ...options, feedback: trimTo(`Resolve these planning findings before scene production. Preserve the episode count and ids. Map every challenge to its intended episode with setup, decision, success, failure and recovery. Do not expand scenes.\n${planFindings.join('\n')}`, 4000) });
+ if (run.cancelRequested) return finishCanceled(run);
+ touch(run, { round: attempt, currentStep: 'review-plan', stepLabel: 'Check repaired series plan', message: 'Confirming the series planning findings are resolved before drafting outlines…' });
+ const checked = await reviewSeriesPlan(run.loomId, { ...options, planningOnly: true });
+ if (run.cancelRequested) return finishCanceled(run);
+ planFindings = checked.analysis.risks;
+ }
+ if (planFindings.length) {
+ run.residualFindings = planFindings.map((problem) => ({ severity: 'high', category: 'structure', problem }));
+ return finishPaused(run, 'round-limit', 'The series plan still has review findings. No episode outlines, teleplay or media were generated.');
+ }
+ let loom = await requireLoomForRun(run.loomId);
+ const unmapped = (loom.seriesPlan?.plotPoints || []).filter((item) => item.kind === 'challenge' && !loom.episodes.some((episode) => episode.id === item.episodeId));
+ if (!loom.seriesPlan?.storyArc?.trim() || unmapped.length) {
+ return finishPaused(run, 'planning-required', 'Save a story arc and assign every challenge to an episode before drafting outlines.');
+ }
+ for (const [index, episode] of loom.episodes.entries()) {
+ let guidance = 'Follow the complete series plan. Each outline scene is a camera-cut beat, not a whole dramatic scene. Preserve each assigned challenge id and represent setup, decision, success, failure and recovery as separate beats. Keep branches purposeful and fail forward. Draft only the outline, never full scene prose.';
+ for (let attempt = 1; attempt <= run.maxRounds; attempt += 1) {
+ touch(run, { round: attempt, currentStep: 'outline-episode', stepIndex: index + 2, stepLabel: `Plan episode ${episode.number}`, message: `Planning episode ${episode.number} of ${loom.episodes.length} · attempt ${attempt}/${run.maxRounds}…` });
+ const current = await requireLoomForRun(run.loomId);
+ const existing = current.episodes.find((candidate) => candidate.id === episode.id);
+ const generated = attempt === 1 && existing?.storyOutline?.scenes?.length
+ ? await validateEpisodeOutline(run.loomId, episode.id)
+ : await generateEpisodeOutline(run.loomId, episode.id, { ...options, guidance });
+ if (run.cancelRequested) return finishCanceled(run);
+ const errors = generated.validation?.issues?.filter((issue) => issue.severity === 'error') || [];
+ const checked = errors.length ? null : await reviewEpisodeOutline(run.loomId, episode.id, { ...options, planningGate: true });
+ if (run.cancelRequested) return finishCanceled(run);
+ const findings = [...errors.map((issue) => issue.message), ...(checked?.analysis?.risks || [])];
+ run.residualFindings = findings.map((problem) => ({ severity: 'high', category: 'structure', episodeId: episode.id, problem }));
+ if (!findings.length) {
+ await validateEpisodeOutline(run.loomId, episode.id);
+ break;
+ }
+ if (attempt === run.maxRounds) return finishPaused(run, 'round-limit', `Episode ${episode.number} still has planning findings. No teleplay or media was generated.`);
+ guidance = trimTo(`Revise the outline to resolve these findings while preserving the series plan and challenge contracts:\n${findings.join('\n')}`, 4000);
+ }
+ }
+ loom = await requireLoomForRun(run.loomId);
+ const validation = analyzeSeriesStoryOutlines(loom);
+ run.residualFindings = validation.issues.filter((issue) => issue.severity === 'error').map((issue) => ({ ...issue, problem: issue.message }));
+ if (!validation.stats.ready) return finishPaused(run, 'planning-required', 'The complete beat arc still needs corrections before expansion. No teleplay or media was generated.');
+ return touch(run, { status: 'completed', currentStep: null, stepLabel: null, stepIndex: run.stepCount, message: 'Series planning complete. All episode outlines are ready; choose the episode to expand next.', completedAt: nowIso() });
+}
+
/** Start and detach a bounded editor/reviewer run. */
export async function startFableLoomEditorialAutopilot(loomId, {
- maxRounds, maxPaths, providerId, model, effort, selfImprove,
+ maxRounds, maxPaths, providerId, model, effort, selfImprove, mode = 'series',
} = {}) {
cleanStaleRuns();
- await requireLoomForRun(loomId);
+ const loom = await requireLoomForRun(loomId);
+ if (mode === 'planning' && (!loom.episodes?.length || loom.episodes.some((episode) => episode.nodes?.length))) {
+ throw new ServerError('Planning autopilot requires episode slots with no expanded scenes. Add the planned episodes first.', { status: 409, code: 'PLANNING_SCOPE_REQUIRED' });
+ }
const currentId = latestRunByLoom.get(loomId);
const current = currentId ? runs.get(currentId) : null;
if (current && ['running', 'canceling'].includes(current.status)) {
@@ -329,12 +395,13 @@ export async function startFableLoomEditorialAutopilot(loomId, {
const run = {
id: `editorial-${randomUUID()}`,
loomId,
+ mode,
status: 'running',
currentStep: 'starting',
round: 0,
maxRounds: boundedRounds(maxRounds),
stepIndex: 0,
- stepCount: boundedRounds(maxRounds) * 2,
+ stepCount: mode === 'planning' ? loom.episodes.length + 2 : boundedRounds(maxRounds) * 2,
stepLabel: 'Starting',
correctionAttempt: 0,
responseCorrections: 0,
@@ -364,7 +431,7 @@ export async function startFableLoomEditorialAutopilot(loomId, {
};
runs.set(run.id, run);
latestRunByLoom.set(loomId, run.id);
- void runRound(run, '')
+ void (mode === 'planning' ? runPlanning(run) : runRound(run, ''))
.catch((error) => (run.cancelRequested ? finishCanceled(run) : finishFailed(run, error)))
.catch((error) => {
console.error(`❌ FableLoom editorial autopilot terminal handling failed: ${error.message}`);
diff --git a/server/services/fableLoom/editorialAutopilot.test.js b/server/services/fableLoom/editorialAutopilot.test.js
index 34dc4e32f1..b84ed7ac00 100644
--- a/server/services/fableLoom/editorialAutopilot.test.js
+++ b/server/services/fableLoom/editorialAutopilot.test.js
@@ -16,6 +16,12 @@ const selfImproveMock = vi.hoisted(() => vi.fn(async () => ({
taskId: 'sys-example', filed: true, duplicate: false,
})));
+const planningMocks = vi.hoisted(() => ({
+ reviewSeriesPlan: vi.fn(), feedbackSeriesPlan: vi.fn(),
+ generateEpisodeOutline: vi.fn(), reviewEpisodeOutline: vi.fn(), validateEpisodeOutline: vi.fn(),
+}));
+vi.mock('./weave.js', () => planningMocks);
+
vi.mock('./records.js', () => ({ getLoom: getLoomMock, mutateLoom: mutateLoomMock }));
vi.mock('./editorial.js', () => ({
evaluateAndRemediateFableLoom: remediateMock,
@@ -79,6 +85,7 @@ beforeEach(() => {
_resetFableLoomEditorialAutopilots();
getLoomMock.mockClear().mockImplementation(async (id) => ({ id }));
mutateLoomMock.mockClear();
+ Object.values(planningMocks).forEach((mock) => mock.mockReset());
remediateMock.mockReset();
playtestMock.mockReset();
selfImproveMock.mockClear();
@@ -341,3 +348,76 @@ describe('FableLoom editorial autopilot', () => {
expect(publicFableLoomEditorialAutopilot(finished)).not.toHaveProperty('previousFindingSignature');
});
});
+
+
+describe('planning autopilot boundary', () => {
+ it('reviews and repairs the plan before sequential outlines, and never invokes teleplay editorial approval', async () => {
+ await import('../../lib/fableLoomOutline.js');
+ const planned = { id: 'loom-plan', participationMode: 'protagonist', seriesPlan: { storyArc: 'A complete arc.', plotPoints: [] }, episodes: [1, 2].map((number) => ({ id: `ep-${number}`, number, nodes: [] })) };
+ getLoomMock.mockImplementation(async () => planned);
+ const order = [];
+ planningMocks.reviewSeriesPlan.mockImplementation(async () => { order.push('review-plan'); return { analysis: { risks: order.includes('repair-plan') ? [] : ['Clarify the payoff'], recommendations: [] } }; });
+ planningMocks.feedbackSeriesPlan.mockImplementation(async () => { order.push('repair-plan'); });
+ planningMocks.generateEpisodeOutline.mockImplementation(async (_id, episodeId) => {
+ order.push(`draft-${episodeId}`);
+ planned.episodes.find((episode) => episode.id === episodeId).storyOutline = {
+ startKey: 'end', validation: { status: 'draft' }, scenes: [{ key: 'end', title: 'Arrival', summary: 'The traveler reaches the destination.', playbackMode: 'cut', protagonistPresence: 'present', audienceConnection: 'connected', isEnding: true, endingLabel: 'Home', transitions: [] }],
+ };
+ return { validation: { issues: [] } };
+ });
+ planningMocks.reviewEpisodeOutline.mockImplementation(async (_id, episodeId) => { order.push(`review-${episodeId}`); return { analysis: { risks: [] } }; });
+ planningMocks.validateEpisodeOutline.mockImplementation(async (_id, episodeId) => { planned.episodes.find((episode) => episode.id === episodeId).storyOutline.validation.status = 'valid'; });
+ const run = await startFableLoomEditorialAutopilot('loom-plan', { mode: 'planning', maxRounds: 1 });
+ const finished = await waitForTerminal(run.id);
+ expect(finished.status).toBe('completed');
+ expect(order).toEqual(['review-plan', 'repair-plan', 'review-plan', 'draft-ep-1', 'review-ep-1', 'draft-ep-2', 'review-ep-2']);
+ expect(remediateMock).not.toHaveBeenCalled();
+ expect(playtestMock).not.toHaveBeenCalled();
+ expect(mutateLoomMock).not.toHaveBeenCalled();
+ expect(planned.episodes.every((episode) => !episode.nodes.length)).toBe(true);
+ });
+
+ it('stops before drafting when the bounded plan repair did not resolve its findings', async () => {
+ getLoomMock.mockResolvedValue({ seriesPlan: { storyArc: 'An arc.', plotPoints: [] }, episodes: [{ id: 'ep-1', number: 1, nodes: [] }] });
+ planningMocks.reviewSeriesPlan.mockResolvedValue({ analysis: { risks: ['The payoff contradicts the premise.'] } });
+ planningMocks.feedbackSeriesPlan.mockResolvedValue({});
+ const run = await startFableLoomEditorialAutopilot('loom-plan', { mode: 'planning', maxRounds: 1 });
+ expect(await waitForTerminal(run.id)).toMatchObject({ status: 'paused', pauseReason: 'round-limit', residualFindings: [expect.objectContaining({ problem: 'The payoff contradicts the premise.' })] });
+ expect(planningMocks.reviewSeriesPlan).toHaveBeenCalledTimes(2);
+ expect(planningMocks.feedbackSeriesPlan).toHaveBeenCalledTimes(1);
+ expect(planningMocks.generateEpisodeOutline).not.toHaveBeenCalled();
+ });
+
+ it('stops at a broken outline within the retry budget before later episodes or media', async () => {
+ await import('../../lib/fableLoomOutline.js');
+ getLoomMock.mockResolvedValue({ seriesPlan: { storyArc: 'An arc.', plotPoints: [] }, episodes: [{ id: 'ep-1', number: 1, nodes: [] }, { id: 'ep-2', number: 2, nodes: [] }] });
+ planningMocks.reviewSeriesPlan.mockResolvedValue({ analysis: { risks: [], recommendations: [] } });
+ planningMocks.generateEpisodeOutline.mockResolvedValue({ validation: { issues: [{ severity: 'error', message: 'Missing recovery path.' }] } });
+ const run = await startFableLoomEditorialAutopilot('loom-plan', { mode: 'planning', maxRounds: 2 });
+ const finished = await waitForTerminal(run.id);
+ expect(finished).toMatchObject({ status: 'paused', pauseReason: 'round-limit' });
+ expect(planningMocks.generateEpisodeOutline.mock.calls.map((call) => call[1])).toEqual(['ep-1', 'ep-1']);
+ expect(planningMocks.generateEpisodeOutline.mock.calls[1][2].guidance).toContain('Missing recovery path.');
+ expect(planningMocks.reviewEpisodeOutline).not.toHaveBeenCalled();
+ expect(mutateLoomMock).not.toHaveBeenCalled();
+ });
+
+ it('blocks a structurally valid but confusing opening before planning later episodes', async () => {
+ getLoomMock.mockResolvedValue({ seriesPlan: { storyArc: 'An arc.', plotPoints: [] }, episodes: [{ id: 'ep-1', number: 1, nodes: [] }, { id: 'ep-2', number: 2, nodes: [] }] });
+ planningMocks.reviewSeriesPlan.mockResolvedValue({ analysis: { risks: [] } });
+ planningMocks.generateEpisodeOutline.mockResolvedValue({ validation: { issues: [] } });
+ planningMocks.reviewEpisodeOutline.mockResolvedValue({ analysis: { risks: ['The viewer cannot identify an immediate personal goal.'], recommendations: [] } });
+ const run = await startFableLoomEditorialAutopilot('loom-plan', { mode: 'planning', maxRounds: 1 });
+ const finished = await waitForTerminal(run.id);
+ expect(finished).toMatchObject({ status: 'paused', residualFindings: [expect.objectContaining({ problem: 'The viewer cannot identify an immediate personal goal.' })] });
+ expect(planningMocks.generateEpisodeOutline.mock.calls.map((call) => call[1])).toEqual(['ep-1']);
+ expect(planningMocks.validateEpisodeOutline).not.toHaveBeenCalled();
+ expect(remediateMock).not.toHaveBeenCalled();
+ });
+
+ it('refuses planning over expanded scenes before making provider calls', async () => {
+ getLoomMock.mockResolvedValue({ episodes: [{ id: 'ep-1', nodes: [{ id: 'scene-1' }] }] });
+ await expect(startFableLoomEditorialAutopilot('loom-plan', { mode: 'planning' })).rejects.toMatchObject({ code: 'PLANNING_SCOPE_REQUIRED' });
+ expect(planningMocks.reviewSeriesPlan).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/fableLoom/index.js b/server/services/fableLoom/index.js
index aa496053aa..b72644c5d4 100644
--- a/server/services/fableLoom/index.js
+++ b/server/services/fableLoom/index.js
@@ -121,3 +121,4 @@ export {
getFalVideoAutomation,
startFalVideoAutomation,
} from './falVideoAutomation.js';
+export { applyEpisodeShots, runEpisodeShotAutopilot } from './shots.js';
diff --git a/server/services/fableLoom/production.js b/server/services/fableLoom/production.js
index 549b20e2db..6c9bea80fd 100644
--- a/server/services/fableLoom/production.js
+++ b/server/services/fableLoom/production.js
@@ -29,6 +29,7 @@ import {
listVideoModels,
resolveVideoModel,
} from '../videoGen/local.js';
+import { validateReactorRequest } from '../videoGen/reactor.js';
import { loadHistory as loadVideoHistory } from '../videoGen/history.js';
import { VIDEO_GEN_MODE, VIDEO_GEN_MODES, resolveVideoMode } from '../videoGen/modes.js';
import {
@@ -63,7 +64,7 @@ const ACTIVE_ASSET_STATUSES = new Set(['preparing', 'queued', 'running']);
const EFFECTIVE_PARAMETER_KEYS = Object.freeze([
'width', 'height', 'numFrames', 'fps', 'steps', 'guidance', 'guidanceScale',
'seed', 'imageStrength', 'quantize', 'effort', 'mode', 'videoMode',
- 'aspectRatio', 'disableAudio', 'tiling',
+ 'aspectRatio', 'disableAudio', 'tiling', 'seconds',
]);
const nowIso = () => new Date().toISOString();
@@ -475,6 +476,9 @@ function resolveVideoBackend(settings, render, recordedConditioning = null) {
code: 'FAL_VIDEO_DISABLED',
});
}
+ if (requested === VIDEO_GEN_MODE.REACTOR && mode !== VIDEO_GEN_MODE.REACTOR) {
+ throw new ServerError('Reactor video is not configured — set an API key in Settings → Video Gen.', { status: 400, code: 'REACTOR_NOT_CONFIGURED' });
+ }
return mode;
}
@@ -614,7 +618,9 @@ async function prepareVideoJob(run, asset) {
? model
: backend === VIDEO_GEN_MODE.FAL
? { id: 'fal-video', supportedModes: ['text', 'image'] }
- : { id: 'grok-video', supportedModes: ['image'] },
+ : backend === VIDEO_GEN_MODE.REACTOR
+ ? { id: 'reactor-video', supportedModes: ['text', 'image'] }
+ : { id: 'grok-video', supportedModes: ['image'] },
});
const requestedSourceImagePath = imageInputForNode(run, asset);
const conditioned = await conditionRequest(run, asset, 'video', capability, requestedSourceImagePath);
@@ -661,6 +667,27 @@ async function prepareVideoJob(run, asset) {
};
}
+ if (backend === VIDEO_GEN_MODE.REACTOR) {
+ const loom = await loadRunLoom(run);
+ const node = findEpisode(loom, run.episodeId)?.nodes.find((candidate) => candidate.id === asset.nodeId);
+ // The compiler owns prompt compaction; never truncate dialogue at this boundary.
+ const request = validateReactorRequest({
+ prompt: conditioned?.prompt || asset.prompt,
+ seconds: replayParameters.seconds ?? node?.shot?.durationSeconds ?? 6,
+ seed: replayParameters.seed,
+ });
+ return {
+ kind: 'video', provider: backend, modelId: 'reactor:fast-h3',
+ modelRevision: capability.modelRevision || null,
+ params: {
+ mode: backend, videoMode: sourceImagePath ? 'image' : 'text',
+ ...request, sourceImagePath,
+ visualConditioning: conditioned?.visualConditioning || null,
+ fableLoom: productionTag(run, asset),
+ },
+ };
+ }
+
if (backend === VIDEO_GEN_MODE.FAL) {
return {
kind: 'video',
diff --git a/server/services/fableLoom/production.test.js b/server/services/fableLoom/production.test.js
index b57b1c030b..d338f45878 100644
--- a/server/services/fableLoom/production.test.js
+++ b/server/services/fableLoom/production.test.js
@@ -315,6 +315,36 @@ describe('fableLoom production service', () => {
expect(fetched).toEqual(run);
});
+ it('queues Reactor with its compact compiled script and fails oversized scripts before queueing', async () => {
+ const loom = structuredClone(sampleLoom);
+ loom.episodes[0].nodes.forEach((node) => { node.image = 'example-frame.png'; });
+ loom.episodes[0].nodes[0].shot = { durationSeconds: 8 };
+ records.getLoom.mockResolvedValue(loom);
+ settingsMocks.getSettings.mockResolvedValue({ videoGen: { reactor: { apiKey: 'example-key' } } });
+ const prompt = 'Preserve source identity. No subtitles. Static close-up. HERO: "The gate is open."';
+ visualConditioningMocks.compileFableLoomVisualRequest.mockResolvedValue({
+ prompt, sourceImagePath: '/example/frame.png', visualConditioning: { compiledPrompt: prompt },
+ });
+ const options = { videoMode: 'reactor', assetTypes: ['video_entry'], nodeIds: ['node-1'] };
+ await startEpisodeProductionBatch('loom-1', 'ep-1', options);
+ await vi.waitFor(() => expect(queueMocks.enqueueJob).toHaveBeenCalled());
+ expect(visualConditioningMocks.fableLoomVideoCapabilities).toHaveBeenCalledWith(expect.objectContaining({ backend: 'reactor', model: { id: 'reactor-video', supportedModes: ['text', 'image'] } }));
+ expect(queueMocks.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({
+ kind: 'video', params: expect.objectContaining({
+ mode: 'reactor', prompt, seconds: 8, sourceImagePath: '/example/frame.png',
+ visualConditioning: expect.objectContaining({ compiledPrompt: prompt, render: expect.objectContaining({ provider: 'reactor', parameters: expect.objectContaining({ seconds: 8 }) }) }),
+ }),
+ }));
+
+ _resetProductionBatchRuns();
+ queueMocks.enqueueJob.mockClear();
+ visualConditioningMocks.compileFableLoomVisualRequest.mockResolvedValue({ prompt: 'x'.repeat(801) });
+ const rejected = await startEpisodeProductionBatch('loom-1', 'ep-1', options);
+ await vi.waitFor(() => expect(getEpisodeProductionBatch(rejected.id).status).toBe('failed'));
+ expect(queueMocks.enqueueJob).not.toHaveBeenCalled();
+ expect(getEpisodeProductionBatch(rejected.id).error).toContain('1–800');
+ });
+
it('refuses a batch when its selected assets are blocked', async () => {
const blockedLoom = structuredClone(sampleLoom);
blockedLoom.episodes[0].nodes[0].prose = '';
diff --git a/server/services/fableLoom/records.js b/server/services/fableLoom/records.js
index 8607e61a5b..ee000aed70 100644
--- a/server/services/fableLoom/records.js
+++ b/server/services/fableLoom/records.js
@@ -11,6 +11,7 @@
* so a malformed mutation can never persist.
*/
+import { sanitizeShot } from '../../lib/fableLoomShots.js';
import { randomUUID } from 'crypto';
import { ServerError } from '../../lib/errorHandler.js';
import { isStr, trimTo } from '../../lib/storyBible.js';
@@ -90,6 +91,7 @@ const sanitizeVisualCanon = (raw) => {
.map((item) => ({
characterId: nullableRef(item.characterId),
wardrobeId: nullableRef(item.wardrobeId),
+ ...(isSafeImageFilename(item.referenceImage) ? { referenceImage: item.referenceImage } : {}),
expression: trimTo(item.expression, LOOM_LIMITS.VISUAL_NOTE_MAX),
continuityNotes: trimTo(item.continuityNotes, LOOM_LIMITS.VISUAL_NOTE_MAX),
}));
@@ -128,6 +130,7 @@ function sanitizeNode(raw) {
id: raw.id,
title: trimTo(raw.title, LOOM_LIMITS.NODE_TITLE_MAX),
prose: trimTo(raw.prose, LOOM_LIMITS.PROSE_MAX),
+ ...(raw.shot ? { shot: sanitizeShot(raw.shot) } : {}),
plotPointId: isStr(raw.plotPointId)
? raw.plotPointId.trim().slice(0, LOOM_LIMITS.OUTLINE_KEY_MAX)
: null,
@@ -386,6 +389,7 @@ const editorialContentSignature = (loom) => JSON.stringify({
id: node.id,
title: node.title,
prose: node.prose,
+ shot: node.shot,
plotPointId: node.plotPointId,
challengePhase: node.challengePhase,
imagePrompt: node.imagePrompt,
@@ -686,7 +690,7 @@ const preserveLegacyDeliveryPlan = (remotePlan, localPlan, senderVersion) => (
// them. A sender at the current schema version's present null remains an
// intentional clear.
const preserveLegacyVisualProduction = (remote, local, senderVersion) => {
- if (!local || senderVersion >= 6) return remote;
+ if (!local || senderVersion >= 7) return remote;
const localEpisodes = new Map(local.episodes.map((episode) => [episode.id, episode]));
const localPlotPoints = new Map((local.seriesPlan?.plotPoints || []).map((item) => [item.id, item]));
const legacyRenderSettings = senderVersion < 5
@@ -730,6 +734,18 @@ const preserveLegacyVisualProduction = (remote, local, senderVersion) => {
const localNode = localNodes.get(node.id);
return localNode ? {
...node,
+ ...(senderVersion < 7 ? {
+ ...(localNode.shot ? { shot: localNode.shot } : {}),
+ ...(senderVersion >= 3 && node.visualCanon ? {
+ visualCanon: {
+ ...node.visualCanon,
+ characterAppearances: node.visualCanon.characterAppearances.map((appearance) => {
+ const previous = localNode.visualCanon?.characterAppearances.find((item) => item.characterId === appearance.characterId);
+ return previous?.referenceImage ? { ...appearance, referenceImage: previous.referenceImage } : appearance;
+ }),
+ },
+ } : {}),
+ } : {}),
...(senderVersion < 5 ? {
plotPointId: localNode.plotPointId,
challengePhase: localNode.challengePhase,
@@ -761,7 +777,7 @@ export async function mergeLoomsFromSync(
remoteLooms,
{
source = { via: 'sync', peerId: null },
- senderSchemaVersions = { fableLoom: 6 },
+ senderSchemaVersions = { fableLoom: 7 },
} = {},
) {
if (!Array.isArray(remoteLooms)) return { applied: false, count: 0 };
@@ -898,6 +914,7 @@ export function deleteEpisode(loomId, episodeId) {
// --- Nodes & transitions ----------------------------------------------------
const NODE_PATCH_FIELDS = [
+ 'shot',
'title', 'prose', 'plotPointId', 'challengePhase', 'imagePrompt', 'videoPrompt', 'cameraMovement', 'playbackMode',
'audienceConnection', 'protagonistPresence', 'visualCanon', 'videoHistoryId', 'playbackAssets', 'interactionWindow',
'isEnding', 'endingLabel', 'pos', 'transitions',
diff --git a/server/services/fableLoom/records.test.js b/server/services/fableLoom/records.test.js
index 7af457150e..816e6876c6 100644
--- a/server/services/fableLoom/records.test.js
+++ b/server/services/fableLoom/records.test.js
@@ -431,6 +431,32 @@ describe('loom CRUD', () => {
});
});
+ it('preserves v7 shot and character references from older peers while accepting current explicit clears', async () => {
+ let loom = await makeLoom({ name: 'A timed episode' });
+ loom = await addEpisode(loom.id, { title: 'Pilot' });
+ const episodeId = loom.episodes[0].id;
+ loom = await addNode(loom.id, episodeId, {
+ title: 'Arrival', shot: { dramaticSceneId: 'arrival', dramaticSceneTitle: 'Arrival', durationSeconds: 8, framing: 'Wide' },
+ visualCanon: { mode: 'draft', characterAppearances: [{ characterId: 'courier', referenceImage: 'courier.png' }] },
+ });
+ const remote = structuredClone(loom);
+ remote.updatedAt = '2099-01-01T00:00:00.000Z';
+ remote.name = 'Renamed on older peer';
+ delete remote.episodes[0].nodes[0].shot;
+ delete remote.episodes[0].nodes[0].visualCanon.characterAppearances[0].referenceImage;
+ remote.episodes[0].nodes[0].visualCanon.characterAppearances[0].expression = 'smiling';
+ await mergeLoomsFromSync([remote], { senderSchemaVersions: { fableLoom: 6 } });
+ const saved = await getLoom(loom.id);
+ expect(saved.name).toBe(remote.name);
+ expect(saved.episodes[0].nodes[0].shot).toEqual(loom.episodes[0].nodes[0].shot);
+ expect(saved.episodes[0].nodes[0].visualCanon.characterAppearances[0]).toMatchObject({ referenceImage: 'courier.png', expression: 'smiling' });
+ remote.updatedAt = '2099-01-02T00:00:00.000Z';
+ await mergeLoomsFromSync([remote], { senderSchemaVersions: { fableLoom: 7 } });
+ const cleared = (await getLoom(loom.id)).episodes[0].nodes[0];
+ expect(cleared.shot).toBeUndefined();
+ expect(cleared.visualCanon.characterAppearances[0].referenceImage).toBeUndefined();
+ });
+
it('preserves playable challenge mappings when a v4 peer wins an unrelated edit', async () => {
let loom = await makeLoom({ name: 'Local challenge plan' });
loom = await addEpisode(loom.id, { title: 'Pilot' });
diff --git a/server/services/fableLoom/shots.js b/server/services/fableLoom/shots.js
new file mode 100644
index 0000000000..0d44a28d1f
--- /dev/null
+++ b/server/services/fableLoom/shots.js
@@ -0,0 +1,121 @@
+/** Draft/review timed shots; only apply a complete valid plan to the episode. */
+import { createHash, randomUUID } from 'node:crypto';
+import { ServerError } from '../../lib/errorHandler.js';
+import { shotGroupsSchema } from '../../lib/fableLoomValidation.js';
+import { analyzeEpisodeShots, estimatedShotSeconds } from '../../lib/fableLoomShots.js';
+import { analyzeEpisodeGraph } from '../../lib/fableLoomGraph.js';
+import { analyzeStoryOutline, fableLoomEpisodeChallenges } from '../../lib/fableLoomOutline.js';
+import { getUniverse } from '../universeBuilder.js';
+import { startAIOp } from '../aiStatusEvents.js';
+import { runStagedLLM } from '../stageRunner.js';
+import { getLoom, findEpisode, mutateLoom } from './records.js';
+
+const fingerprint = (loom, episode) => createHash('sha256').update(JSON.stringify({ episode, seriesPlan: loom.seriesPlan, protagonist: loom.protagonistCharacterId })).digest('hex');
+const requireSource = async (id, episodeId) => {
+ const loom = await getLoom(id);
+ if (!loom) throw new ServerError('Story not found', { status: 404 });
+ const episode = findEpisode(loom, episodeId);
+ if (!episode.nodes.length) throw new ServerError('Write the dramatic scenes before splitting them into shots.', { status: 409 });
+ return { loom, episode };
+};
+const script = (shot) => [shot.action, ...shot.dialogue.map((line) => `${line.speaker.toUpperCase()}\n${line.text.replace(/\s+/g, ' ').trim()}`)].join('\n\n');
+
+function compile(loom, episode, groups) {
+ const parsed = shotGroupsSchema.parse(groups).map((group) => ({ ...group, shots: group.shots.map((shot) => ({
+ ...shot, durationSeconds: Math.max(shot.durationSeconds, Math.min(10, Math.ceil(estimatedShotSeconds(script(shot))))),
+ })) }));
+ const byId = new Map(parsed.map((group) => [group.sceneId, group]));
+ if (byId.size !== parsed.length || byId.size !== episode.nodes.length || episode.nodes.some((node) => !byId.has(node.id))) {
+ throw new ServerError('Every existing scene must have exactly one shot group.', { status: 422 });
+ }
+ const ids = new Map(episode.nodes.map((node) => [node.id, byId.get(node.id).shots.map((_, i) => i === 0 ? node.id : `node-${randomUUID()}`)]));
+ const nodes = episode.nodes.flatMap((scene) => byId.get(scene.id).shots.map((shot, index, all) => {
+ const last = index === all.length - 1;
+ const decision = scene.playbackMode === 'decision';
+ const appearances = scene.visualCanon?.characterAppearances || [];
+ if (shot.visibleCharacterIds?.some((id) => !appearances.some((appearance) => appearance.characterId === id))) throw new ServerError('A shot names a character outside its source scene cast.', { status: 422 });
+ return {
+ ...scene, id: ids.get(scene.id)[index], title: shot.title, prose: script(shot),
+ shot: { dramaticSceneId: scene.shot?.dramaticSceneId || scene.id, dramaticSceneTitle: scene.shot?.dramaticSceneTitle || scene.title, durationSeconds: shot.durationSeconds, framing: shot.framing },
+ imagePrompt: shot.imagePrompt, videoPrompt: `${shot.durationSeconds}-second continuous shot. ${shot.videoPrompt}`, cameraMovement: 'static',
+ image: null, imageJobId: null, videoHistoryId: null, visualConditioning: null, playbackAssets: {}, pos: null,
+ protagonistPresence: shot.protagonistPresence || scene.protagonistPresence,
+ visualCanon: scene.visualCanon ? { ...scene.visualCanon, characterAppearances: shot.visibleCharacterIds ? appearances.filter((appearance) => shot.visibleCharacterIds.includes(appearance.characterId)) : appearances, storyboardImageApproved: false, continuitySourceNodeId: null } : null,
+ playbackMode: last ? scene.playbackMode : 'cut', isEnding: last && scene.isEnding,
+ endingLabel: last ? scene.endingLabel : '',
+ // Preparatory dialogue for a decision belongs to setup, not the loop.
+ challengePhase: decision && !last ? 'setup' : scene.challengePhase,
+ transitions: last ? scene.transitions.map((t) => ({ ...t, id: `tr-${randomUUID()}`, targetNodeId: ids.get(t.targetNodeId)?.[0] || t.targetNodeId }))
+ : [{ id: `tr-${randomUUID()}`, targetNodeId: ids.get(scene.id)[index + 1], intent: 'continue', triggers: [], description: '' }],
+ };
+ }));
+ if (nodes.length > 200) throw new ServerError('The shot plan exceeds the episode limit of 200 nodes.', { status: 422 });
+ const proposed = { ...episode, nodes, startNodeId: ids.get(episode.startNodeId)[0] };
+ const timing = analyzeEpisodeShots(proposed);
+ const graph = analyzeEpisodeGraph(proposed, { participationMode: loom.participationMode });
+ const outline = { version: 1, startKey: proposed.startNodeId, scenes: nodes.map((node) => ({
+ key: node.id, title: node.title, summary: node.prose.slice(0, 1200), plotPointId: node.plotPointId, challengePhase: node.challengePhase,
+ playbackMode: node.playbackMode, audienceConnection: node.audienceConnection, protagonistPresence: node.protagonistPresence,
+ isEnding: node.isEnding, endingLabel: node.endingLabel, transitions: node.transitions.map((t) => ({ targetKey: t.targetNodeId, intent: t.intent })),
+ })) };
+ const outlineCheck = analyzeStoryOutline(outline, { participationMode: loom.participationMode, challenges: fableLoomEpisodeChallenges(loom, episode.id), plotPoints: loom.seriesPlan.plotPoints, episodeId: episode.id });
+ const issues = [...timing.issues, ...graph.issues.filter((issue) => issue.severity === 'error'), ...outlineCheck.issues.filter((issue) => issue.severity === 'error')];
+ proposed.storyOutline = { ...outline, validation: { status: issues.length ? 'invalid' : 'valid', issues, validatedAt: new Date().toISOString() } };
+ return { groups: parsed, proposed, validation: { issues, stats: { ...timing.stats, ready: !issues.length } } };
+}
+
+export async function applyEpisodeShots(id, episodeId, { sourceFingerprint, groups }) {
+ const { loom, episode } = await requireSource(id, episodeId);
+ if (fingerprint(loom, episode) !== sourceFingerprint) throw new ServerError('The episode changed. Preview a fresh shot plan before applying.', { status: 409, code: 'SHOT_PLAN_STALE' });
+ const { proposed, validation } = compile(loom, episode, groups);
+ if (validation.issues.length) throw new ServerError(validation.issues.map((i) => i.message).join('\n'), { status: 422, code: 'SHOT_PLAN_INVALID' });
+ const updated = await mutateLoom(id, (current) => {
+ const target = findEpisode(current, episodeId);
+ if (fingerprint(current, target) !== sourceFingerprint) throw new ServerError('The episode changed during shot planning.', { status: 409, code: 'SHOT_PLAN_STALE' });
+ Object.assign(target, proposed, { updatedAt: new Date().toISOString() });
+ current.productionStatus.editorialApprovedAt = null;
+ current.productionStatus.editorialApprovalSource = null;
+ return current;
+ });
+ return { loom: updated, validation };
+}
+
+export async function runEpisodeShotAutopilot(id, episodeId, { providerId, model, effort, operationId, guidance = '', maxRounds = 3, apply = false } = {}) {
+ const { loom, episode } = await requireSource(id, episodeId);
+ const sourceFingerprint = fingerprint(loom, episode);
+ const status = operationId ? startAIOp({ op: 'fableloom-shots', label: 'Planning timed shots', operationId, localOnly: true, silent: true }) : null;
+ const universe = loom.universeId ? await getUniverse(loom.universeId) : null;
+ const cast = (universe?.characters || []).map(({ id, name, physicalDescription }) => ({ id, name, physicalDescription }));
+ const source = JSON.stringify({ cast, synopsis: episode.synopsis, startNodeId: episode.startNodeId, scenes: episode.nodes.map((node) => ({
+ id: node.id, title: node.title, prose: node.prose, playbackMode: node.playbackMode,
+ shot: node.shot, imagePrompt: node.imagePrompt, videoPrompt: node.videoPrompt, cameraMovement: node.cameraMovement,
+ referenceImage: node.image, visualCanon: node.visualCanon,
+ protagonistPresence: node.protagonistPresence,
+ visibleCharacterIds: (node.visualCanon?.characterAppearances || []).map((appearance) => appearance.characterId),
+ challengePhase: node.challengePhase, transitions: node.transitions.map(({ targetNodeId, intent }) => ({ targetNodeId, intent })),
+ })) });
+ const route = { returnsJson: true, ...(providerId ? { providerOverride: providerId } : {}), ...(model ? { modelOverride: model } : {}), ...(effort ? { effortOverride: effort } : {}) };
+ const execute = (stage, variables) => runStagedLLM(stage, variables, { ...route, source: stage,
+ onRunCreated: (runId) => status?.update('running', 'Planning and checking short shots…', { runId }),
+ onRunReady: (meta) => status?.update('ready', 'Shot autopilot is running', meta),
+ }).catch((error) => { status?.error(error.message); throw error; });
+ let feedback = '';
+ for (let attempt = 1; attempt <= maxRounds; attempt += 1) {
+ const draft = await execute('fableloom-plan-shots', { source, guidance, feedback });
+ const parsed = shotGroupsSchema.safeParse(draft.content?.groups);
+ if (!parsed.success) { feedback = `Return the required complete groups schema: ${parsed.error.message.slice(0, 3000)}`; continue; }
+ const compiled = await Promise.resolve().then(() => compile(loom, episode, parsed.data)).catch((error) => ({ validation: { issues: [{ message: error.message }] } }));
+ if (compiled.validation.issues.length) { feedback = compiled.validation.issues.map((i) => i.message).join('\n').slice(0, 5000); continue; }
+ const review = await execute('fableloom-review-shots', { source, shots: JSON.stringify(compiled.groups) });
+ if (!Array.isArray(review.content?.risks) || !review.content.risks.every((risk) => typeof risk === 'string') || typeof review.content?.summary !== 'string' || !review.content.summary.trim()) {
+ feedback = 'The shot reviewer returned no explicit verdict. Provide a clear self-contained episode, preserving the source stakes and consequences.'; continue;
+ }
+ if (review.content.risks.length) { feedback = review.content.risks.join('\n').slice(0, 5000); continue; }
+ const result = { sourceFingerprint, groups: compiled.groups, validation: compiled.validation, review: review.content, attempt };
+ const applied = apply ? await applyEpisodeShots(id, episodeId, result) : {};
+ status?.complete(apply ? 'Timed shots applied' : 'Shot plan ready to preview', { runId: review.runId, shellReady: false });
+ return { ...result, ...applied };
+ }
+ status?.error('Shot plan still needs revision; existing episode preserved.');
+ throw new ServerError(`Shot autopilot reached its ${maxRounds}-round limit. Existing episode preserved.\n${feedback}`, { status: 422, code: 'SHOT_PLAN_INVALID' });
+}
diff --git a/server/services/fableLoom/shots.test.js b/server/services/fableLoom/shots.test.js
new file mode 100644
index 0000000000..d0fd120b28
--- /dev/null
+++ b/server/services/fableLoom/shots.test.js
@@ -0,0 +1,94 @@
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'loom-shots-'));
+vi.mock('../../lib/fileUtils.js', async (original) => {
+ const actual = await original();
+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };
+});
+const runStagedLLM = vi.hoisted(() => vi.fn());
+vi.mock('../stageRunner.js', () => ({ runStagedLLM }));
+vi.mock('../universeBuilder.js', () => ({ getUniverse: async () => ({ id: 'example-universe' }) }));
+vi.mock('../pipeline/series.js', () => ({ getSeries: async () => null }));
+const { createLoom, addEpisode, addNode, updateNode, getLoom } = await import('./records.js');
+const { _resetFableLoomBackend } = await import('./store.js');
+const { runEpisodeShotAutopilot, applyEpisodeShots } = await import('./shots.js');
+beforeEach(() => { rmSync(join(TEST_DATA_ROOT, 'fableloom'), { recursive: true, force: true }); _resetFableLoomBackend(); runStagedLLM.mockReset(); });
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+const shot = (title, dialogue = []) => ({ title, durationSeconds: 8, action: 'A courier watches the gate.', framing: 'Medium static shot', dialogue, imagePrompt: 'Courier at the gate', videoPrompt: 'Courier waits.' });
+async function setup() {
+ let loom = await createLoom({ name: 'Example Story', universeId: 'example-universe' });
+ loom = await addEpisode(loom.id, { title: 'Pilot' });
+ const ep = loom.episodes[0].id;
+ loom = await addEpisode(loom.id, { title: 'Later' });
+ loom = await addNode(loom.id, ep, { title: 'Choice', playbackMode: 'decision' });
+ loom = await addNode(loom.id, ep, { title: 'North', isEnding: true });
+ loom = await addNode(loom.id, ep, { title: 'South', isEnding: true });
+ const [choice, north, south] = loom.episodes[0].nodes;
+ loom = await updateNode(loom.id, ep, choice.id, { transitions: [{ targetNodeId: north.id, intent: 'north' }, { targetNodeId: south.id, intent: 'south' }] });
+ const groups = [{ sceneId: choice.id, shots: [shot('Ask', [{ speaker: 'Courier', text: 'Which gate?' }]), shot('Wait')] }, { sceneId: north.id, shots: [shot('North')] }, { sceneId: south.id, shots: [shot('South')] }];
+ return { loom, ep, groups };
+}
+describe('timed shot autopilot', () => {
+ it('grounds both planning and review in existing shot geography and camera context', async () => {
+ const { loom, ep, groups } = await setup();
+ const visual = {
+ imagePrompt: 'A blue gate at screen left, courier beside a brass lamp at screen right.',
+ videoPrompt: 'The courier turns toward the blue gate; the lamp stays on the desk.',
+ cameraMovement: 'static',
+ shot: { dramaticSceneId: 'example-scene', dramaticSceneTitle: 'At the gate', durationSeconds: 8, framing: 'Wide from the courtyard' },
+ };
+ const updated = await updateNode(loom.id, ep, groups[0].sceneId, visual);
+ runStagedLLM.mockResolvedValueOnce({ content: { groups } }).mockResolvedValueOnce({ content: { summary: 'Connected shots.', risks: [] } });
+ await runEpisodeShotAutopilot(loom.id, ep);
+ for (const [, variables] of runStagedLLM.mock.calls) {
+ const source = JSON.parse(variables.source);
+ expect(source.startNodeId).toBe(updated.episodes[0].startNodeId);
+ expect(source.scenes[0]).toMatchObject(visual);
+ expect(source.scenes[0].transitions.map(t => t.targetNodeId)).toEqual(groups.slice(1).map(g => g.sceneId));
+ }
+ expect((await getLoom(loom.id)).episodes).toEqual(updated.episodes);
+ });
+ it('applies a reviewed split with preserved choices, quiet loop and untouched later episode', async () => {
+ const { loom, ep, groups } = await setup();
+ groups[0].shots[0].durationSeconds = 9;
+ groups[0].shots[0].dialogue = [{ speaker: 'Courier', text: 'We can open the northern gate now or take the long road around before the guards come back.' }];
+ runStagedLLM.mockResolvedValueOnce({ content: { groups } }).mockResolvedValueOnce({ content: { summary: 'Clear and filmable.', risks: [] } });
+ const result = await runEpisodeShotAutopilot(loom.id, ep, { apply: true });
+ const saved = await getLoom(loom.id);
+ expect(saved.episodes[1]).toEqual(loom.episodes[1]);
+ const nodes = saved.episodes[0].nodes;
+ expect(nodes).toHaveLength(4);
+ expect(nodes[0].id).toBe(loom.episodes[0].nodes[0].id);
+ expect(nodes[0].transitions[0].targetNodeId).toBe(nodes[1].id);
+ expect(nodes[1].transitions.map(t => t.targetNodeId)).toEqual(nodes.slice(2).map(n => n.id));
+ expect(nodes[1].playbackMode).toBe('decision');
+ expect(nodes[0].shot.durationSeconds).toBe(10);
+ expect(nodes[0].shot.dramaticSceneId).toBe(nodes[1].shot.dramaticSceneId);
+ expect(result.validation.stats.ready).toBe(true);
+ });
+ it('counts short and compound speaker cues before accepting a shot plan', async () => {
+ const { loom, ep, groups } = await setup();
+ groups[0].shots[0].dialogue = [{ speaker: 'Q', text: 'Too many spoken words. '.repeat(8) }, { speaker: 'RADIO/AI', text: '\n\nMore spoken words. '.repeat(8) }];
+ runStagedLLM.mockResolvedValueOnce({ content: { groups } });
+ await expect(runEpisodeShotAutopilot(loom.id, ep, { maxRounds: 1, apply: true })).rejects.toThrow('dialogue needs');
+ expect(runStagedLLM).toHaveBeenCalledTimes(1);
+ expect((await getLoom(loom.id)).episodes).toEqual(loom.episodes);
+ });
+
+ it('rejects oversized dialogue before editorial or mutation, and rejects stale previews', async () => {
+ const { loom, ep, groups } = await setup();
+ const bad = structuredClone(groups);
+ bad[0].shots[0].dialogue[0].text = 'too many words '.repeat(20);
+ runStagedLLM.mockResolvedValueOnce({ content: { groups: bad } });
+ await expect(runEpisodeShotAutopilot(loom.id, ep, { maxRounds: 1, apply: true })).rejects.toThrow('dialogue needs');
+ expect(runStagedLLM).toHaveBeenCalledTimes(1);
+ expect((await getLoom(loom.id)).episodes).toEqual(loom.episodes);
+ runStagedLLM.mockResolvedValueOnce({ content: { groups } }).mockResolvedValueOnce({ content: { summary: 'Clear.', risks: [] } });
+ const preview = await runEpisodeShotAutopilot(loom.id, ep);
+ await updateNode(loom.id, ep, groups[0].sceneId, { title: 'Revised choice' });
+ await expect(applyEpisodeShots(loom.id, ep, preview)).rejects.toThrow('episode changed');
+ expect((await getLoom(loom.id)).episodes[0].nodes).toHaveLength(3);
+ });
+});
diff --git a/server/services/fableLoom/visualConditioning.js b/server/services/fableLoom/visualConditioning.js
index 83cb5cee67..fbf1bd683e 100644
--- a/server/services/fableLoom/visualConditioning.js
+++ b/server/services/fableLoom/visualConditioning.js
@@ -24,7 +24,7 @@ import { resolveCharacterLoras } from '../characterLoraResolver.js';
import { getSeries } from '../pipeline/series.js';
import { getLoom } from './records.js';
-export const FABLELOOM_VISUAL_COMPILER_VERSION = '1.0.0';
+export const FABLELOOM_VISUAL_COMPILER_VERSION = '1.1.0';
const byId = (list) => new Map((Array.isArray(list) ? list : []).filter((item) => item?.id).map((item) => [item.id, item]));
const text = (value) => (typeof value === 'string' ? value.trim() : '');
@@ -304,11 +304,16 @@ export async function compileFableLoomVisualRequest({
: 'convergent scene needs an explicit incoming temporal source');
}
const characterAssets = [];
- for (const { character } of bindings.boundCharacters) {
+ for (const { character, appearance } of bindings.boundCharacters) {
+ const draftReference = !locked && appearance?.referenceImage ? resolveAsset(appearance.referenceImage) : null;
const resolved = imageAssetsForCharacter(character, locked, resolveAsset);
if (locked && resolved.readiness.status !== 'ready') failures.push(`${character.name} identity package is ${resolved.readiness.status}`);
if (locked && resolved.primary.length === 0) failures.push(`${character.name} approved identity assets are unavailable`);
omitted.push(...resolved.unavailable);
+ if (draftReference) {
+ resolved.primary = [publicAsset(draftReference, 'character-draft-reference', character.id)];
+ resolved.supplemental = [];
+ }
characterAssets.push(resolved);
}
// Guarantee each cast member's primary approved identity anchor is
@@ -355,20 +360,49 @@ export async function compileFableLoomVisualRequest({
// early-token weighting a diffusion model gives style.
const universeStyle = universeVisualStyleTokens(universe).embrace.join(', ');
const authoredBody = stripStyleClause(authoredPrompt, universeStyle);
+ const protagonistName = (universe.characters || []).find((character) => character.id === bindings.protagonistId)?.name || 'the canonical protagonist';
+ const visibleCast = bindings.boundCharacters.map(({ character }) => character.name).filter(Boolean);
const protagonistFraming = bindings.protagonistPresence === 'offscreen'
- ? 'Framing constraint: the canonical protagonist is speaking through the communicator off-screen. The camera is the remote witness: show the obstacle or environment the protagonist cannot see around a corner, beyond a bend, at a distance, or otherwise outside their sightline. The communicator stays on the protagonist\'s person and completely out of frame; never use a standalone comms device as the subject. Do not show their face, body, silhouette, or duplicate presence in this storyboard image.'
+ ? visibleCast.length
+ ? `Framing constraint: keep ${protagonistName} off-screen. Show the explicitly bound cast (${visibleCast.join(', ')}) in the authored composition. Their close-ups remain visible even while the protagonist speaks off-screen; do not replace them with an empty environment. Do not show ${protagonistName} or a standalone communicator.`
+ : `Framing constraint: ${protagonistName}, the canonical protagonist, is speaking through the communicator off-screen. The camera is the remote witness: show the obstacle or environment the protagonist cannot see around a corner, beyond a bend, at a distance, or otherwise outside their sightline. The communicator stays on the protagonist's person and completely out of frame; never use a standalone comms device as the subject. Do not show their face, body, silhouette, or duplicate presence in this storyboard image.`
: '';
- const positive = compact([
+ let positive = compact([
universeStyle && `Universe style: ${universeStyle}`,
placePrompt, ...characterPrompts, ...objectPrompts,
protagonistFraming,
+ 'Presentation: no subtitles, captions, dialogue lettering, speech balloons, or text overlays. Dialogue is spoken audio only; never draw the script into the image.',
+ node.shot?.framing && `Current camera framing: ${node.shot.framing}`,
+ kind === 'image' && allocation.accepted.some((asset) => asset.role === 'temporal-predecessor') && (
+ node.shot?.dramaticSceneId && node.shot.dramaticSceneId === temporal.node?.shot?.dramaticSceneId
+ ? `Same dramatic scene: use the preceding image as the set continuity reference. Preserve room geometry, window and doorway positions, furniture, props, lighting, wardrobe, character positions and screen direction. Apply the current camera framing with physically plausible parallax; do not redesign the room or copy the previous composition when a new angle is specified. Previous framing: ${temporal.node.shot.framing || 'see reference'}.`
+ : 'The preceding image is temporal context. Preserve recurring identities and props, but follow the current authored location and camera framing; do not copy the previous location across an intentional scene change.'
+ ),
+ allocation.accepted.filter((asset) => asset.role === 'character-draft-reference').map((asset) => {
+ const character = bindings.boundCharacters.find((binding) => binding.character.id === asset.bindingId)?.character;
+ return `Character reference ${asset.filename}: preserve ${character?.name || 'the bound character'} identity, face, hair or fur, clothing and accessories. Use the authored shot for staging; do not copy reference scene events or other figures.`;
+ }).join('\n'),
authoredBody || (kind === 'video' ? node.videoPrompt || node.prose : node.imagePrompt),
+ kind === 'video' && node.shot && `Shot duration: ${node.shot.durationSeconds} seconds. Play only this shot's current script, preserving each named speaker's voice: ${node.prose}`,
node.visualCanon?.shotNotes && `Shot continuity: ${node.visualCanon.shotNotes}`,
]).join('\n\n').slice(0, 8000);
+ if (kind === 'video' && capability.backend === 'reactor') {
+ if (!allocation.accepted.some((asset) => asset.role === 'storyboard-first-frame')) throw new ServerError('Review and approve the current storyboard reference before rendering with Reactor.', { status: 422, code: 'FABLELOOM_REACTOR_REFERENCE_REQUIRED' });
+ positive = compact([
+ 'Animate this reference as one continuous shot. Preserve its cast, room, props, lighting and screen direction. No subtitles, captions, speech balloons or text overlays. Dialogue is audio only.',
+ node.shot?.framing,
+ authoredBody || node.videoPrompt,
+ node.prose && `Script: ${node.prose}`,
+ node.visualCanon?.shotNotes,
+ bindings.protagonistPresence === 'offscreen' && `Keep ${protagonistName} off-screen.`,
+ ]).join('\n');
+ if (positive.length > 800) throw new ServerError('Reactor requires a complete shot prompt within 800 characters. Shorten the shot direction or split the dialogue; no render was queued.', { status: 422, code: 'FABLELOOM_REACTOR_PROMPT_TOO_LONG' });
+ }
const identityAvoid = bindings.boundCharacters.flatMap(({ character }) => character.identityPack?.avoid || []);
const negativePrompt = mergeNegativePromptTokens([
authoredNegativePrompt,
- bindings.protagonistPresence === 'offscreen' ? 'visible canonical protagonist, protagonist face, protagonist body, protagonist silhouette, standalone communicator, comms device close-up, radio prop hero shot' : '',
+ 'subtitles, captions, dialogue lettering, speech balloons, text overlays',
+ bindings.protagonistPresence === 'offscreen' ? `visible ${protagonistName}, ${protagonistName} face, ${protagonistName} body, ${protagonistName} silhouette, standalone communicator, comms device close-up, radio prop hero shot` : '',
universeVisualStyleTokens(universe).avoid,
identityAvoid,
]).join(', ').slice(0, 8000);
diff --git a/server/services/fableLoom/visualConditioning.test.js b/server/services/fableLoom/visualConditioning.test.js
index 0669bd6b03..80cd5ed24e 100644
--- a/server/services/fableLoom/visualConditioning.test.js
+++ b/server/services/fableLoom/visualConditioning.test.js
@@ -88,7 +88,7 @@ describe('FableLoom visual conditioning compiler', () => {
expect(result.prompt).toContain('ARIA_V2');
expect(result.negativePrompt).toContain('wrong aria face');
expect(result.visualConditioning).toMatchObject({
- status: 'locked', compilerVersion: '1.0.0', universeId: universe.id,
+ status: 'locked', compilerVersion: '1.1.0', universeId: universe.id,
temporalSourceNodeId: 'opening',
bindings: { inferred: false, placeId: 'place-1', objectIds: ['object-1'] },
adapters: [{ filename: 'aria-v2.safetensors', scale: 0.75, sha256: 'a'.repeat(64) }],
@@ -98,6 +98,68 @@ describe('FableLoom visual conditioning compiler', () => {
expect(JSON.stringify(result.visualConditioning)).not.toContain('/approved/');
});
+ it('keeps a shared set across camera cuts without carrying that room into another scene', async () => {
+ const loom = loomWith(lockedBinding);
+ const [previous, current] = loom.episodes[0].nodes;
+ previous.shot = { dramaticSceneId: 'scene-a', framing: 'Wide establishing view' };
+ current.shot = { dramaticSceneId: 'scene-a', framing: 'Close profile from the same side of the axis' };
+ const compile = () => compileFableLoomVisualRequest({
+ tag: { loomId: loom.id, episodeId: 'episode-1', nodeId: 'shot' }, kind: 'image',
+ capability: fableLoomImageCapabilities({ mode: 'codex', inputBudget: 6 }), ...deps(loom),
+ });
+ const result = await compile();
+ expect(result.prompt).toContain('Same dramatic scene:');
+ expect(result.prompt).toContain('room geometry');
+ expect(result.prompt).toContain(current.shot.framing);
+ expect(result.prompt).toContain('Dialogue is spoken audio only');
+ expect(result.negativePrompt).toContain('subtitles');
+ current.shot.dramaticSceneId = 'scene-b';
+ const changed = await compile();
+ expect(changed.prompt).not.toContain('Same dramatic scene:');
+ expect(changed.prompt).toContain('intentional scene change');
+ });
+
+ it('preserves complete Reactor dialogue and rejects oversize shots before rendering', async () => {
+ const loom = loomWith(lockedBinding);
+ const current = loom.episodes[0].nodes[1];
+ current.prose = 'ARIA\nThe last shuttle leaves tonight.';
+ current.videoPrompt = 'She folds the ticket.';
+ const compile = () => compileFableLoomVisualRequest({
+ tag: { loomId: loom.id, episodeId: 'episode-1', nodeId: 'shot' }, kind: 'video',
+ sourceImagePath: '/approved/storyboard.png',
+ capability: fableLoomVideoCapabilities({ backend: 'reactor', model: { supportedModes: ['image'] } }), ...deps(loom),
+ });
+ const result = await compile();
+ expect(result.prompt).toContain(current.prose);
+ expect(result.prompt).toContain('No subtitles');
+ expect(result.prompt.length).toBeLessThanOrEqual(800);
+ expect(result.visualConditioning.compiledPrompt).toBe(result.prompt);
+ current.visualCanon = { ...lockedBinding, mode: 'draft', storyboardImageApproved: false };
+ await expect(compile()).rejects.toMatchObject({ code: 'FABLELOOM_REACTOR_REFERENCE_REQUIRED' });
+ current.visualCanon = lockedBinding;
+ current.prose = 'x'.repeat(801);
+ await expect(compile()).rejects.toMatchObject({ code: 'FABLELOOM_REACTOR_PROMPT_TOO_LONG' });
+ });
+
+ it('uses the explicit draft character anchor without changing approved canon', async () => {
+ const loom = loomWith({ ...lockedBinding, mode: 'draft', characterAppearances: [{ characterId: 'char-a', referenceImage: 'draft-anchor.png' }] });
+ const result = await compileFableLoomVisualRequest({
+ tag: { loomId: loom.id, episodeId: 'episode-1', nodeId: 'shot' }, kind: 'image',
+ capability: fableLoomImageCapabilities({ mode: 'codex', inputBudget: 4 }),
+ authoredPrompt: 'A cautious arrival', ...deps(loom),
+ });
+ expect(result.referenceImagePaths).toContain('/approved/draft-anchor.png');
+ expect(result.visualConditioning.status).not.toBe('locked');
+ const locked = loomWith({ ...lockedBinding, characterAppearances: [{ characterId: 'char-a', referenceImage: 'draft-anchor.png' }] });
+ const approved = await compileFableLoomVisualRequest({
+ tag: { loomId: locked.id, episodeId: 'episode-1', nodeId: 'shot' }, kind: 'image',
+ capability: fableLoomImageCapabilities({ mode: 'codex', inputBudget: 6 }),
+ authoredPrompt: 'A cautious arrival', ...deps(locked),
+ });
+ expect(approved.referenceImagePaths).not.toContain('/approved/draft-anchor.png');
+ expect(approved.referenceImagePaths).toContain('/approved/aria-neutral.png');
+ });
+
it('renders curated style tokens once and never the writing-stage styleNotes', async () => {
const loom = loomWith(lockedBinding);
const result = await compileFableLoomVisualRequest({
@@ -183,10 +245,10 @@ describe('FableLoom visual conditioning compiler', () => {
});
expect(result.prompt).not.toContain('Character: Aria');
- expect(result.prompt).toContain('canonical protagonist is speaking through the communicator off-screen');
+ expect(result.prompt).toContain('Aria, the canonical protagonist, is speaking through the communicator off-screen');
expect(result.prompt).toContain('show the obstacle or environment the protagonist cannot see');
expect(result.prompt).toContain('never use a standalone comms device as the subject');
- expect(result.negativePrompt).toContain('visible canonical protagonist');
+ expect(result.negativePrompt).toContain('visible Aria');
expect(result.negativePrompt).toContain('standalone communicator');
expect(result.visualConditioning.bindings).toMatchObject({
protagonist: { characterId: 'char-a', wardrobeId: 'wardrobe-red', presence: 'offscreen' },
@@ -197,6 +259,23 @@ describe('FableLoom visual conditioning compiler', () => {
});
});
+ it('keeps another character visible while the canonical protagonist is off-screen', async () => {
+ const loom = loomWith({ mode: 'draft', characterAppearances: [{ characterId: 'char-b', referenceImage: 'bex-neutral.png' }] });
+ loom.protagonistCharacterId = 'char-a';
+ loom.episodes[0].nodes.at(-1).protagonistPresence = 'offscreen';
+ const result = await compileFableLoomVisualRequest({
+ tag: { loomId: loom.id, episodeId: 'episode-1', nodeId: 'shot' }, kind: 'image',
+ capability: fableLoomImageCapabilities({ mode: 'codex', inputBudget: 4 }),
+ authoredPrompt: 'Close-up of Bex telling a story.', ...deps(loom),
+ });
+ expect(result.prompt).toContain('keep Aria off-screen');
+ expect(result.prompt).toContain('Show the explicitly bound cast (Bex)');
+ expect(result.prompt).not.toContain('show the obstacle or environment');
+ expect(result.negativePrompt).toContain('visible Aria');
+ expect(result.negativePrompt).not.toContain('visible Bex');
+ expect(result.referenceImagePaths).toContain('/approved/bex-neutral.png');
+ });
+
it('fails a locked render when a backend cannot preserve the bound cast', async () => {
const loom = loomWith({
...lockedBinding,
diff --git a/server/services/fableLoom/weave.js b/server/services/fableLoom/weave.js
index 08f7738b08..f206b400be 100644
--- a/server/services/fableLoom/weave.js
+++ b/server/services/fableLoom/weave.js
@@ -144,7 +144,12 @@ const playRouting = (loom, perCall) => resolveLlmRoutePin(loom.playSettings, per
export async function buildCanonDigest(loom) {
if (!loom.universeId) return '';
const universe = await getUniverse(loom.universeId).catch(() => null);
- return universe ? renderCanonForPrompt(universe) : '';
+ if (!universe) return '';
+ const protagonist = universe.characters?.find((character) => character.id === loom.protagonistCharacterId);
+ return [
+ protagonist ? `Verified Universe protagonist: id=${protagonist.id}; name=${protagonist.name}.` : '',
+ renderCanonForPrompt(universe),
+ ].filter(Boolean).join('\n');
}
const seriesPlanContext = (loom, episode) => {
@@ -159,8 +164,8 @@ const seriesPlanContext = (loom, episode) => {
const assignment = item.episodeId ? ` [planned for ${episodeLabels.get(item.episodeId) || item.episodeId}]` : ' [unassigned]';
const challenge = fableLoomPlotPointKind(item) === 'challenge';
return [
- `Plot point ${index + 1} id=${item.id} kind=${challenge ? 'challenge' : 'beat'}${assignment}: ${item.title || 'Untitled'}${item.description ? ` — ${trimTo(item.description, 700)}` : ''}`,
- challenge
+ `Plot point ${index + 1} id=${item.id} kind=${challenge ? 'challenge' : 'beat'}${assignment}: ${item.title || 'Untitled'}${item.description ? ` — ${item.description}` : ''}`,
+ challenge && (!episode || item.episodeId === episode.id)
? 'PLAYABLE CHALLENGE CONTRACT: map this exact plot-point id onto separate outline/teleplay beats with challengePhase values setup, decision, success, failure, and recovery. The setup must lead to the decision loop; the decision must reach both success and failure; both outcomes must continue to recovery/payoff. Failure continues with a visible cost rather than resetting or dead-ending.'
: '',
].filter(Boolean).join('\n');
@@ -170,7 +175,7 @@ const seriesPlanContext = (loom, episode) => {
.map((item) => {
const start = item.startEpisodeId ? episodeLabels.get(item.startEpisodeId) || item.startEpisodeId : 'unassigned';
const end = item.endEpisodeId ? episodeLabels.get(item.endEpisodeId) || item.endEpisodeId : 'unassigned';
- return `Side quest (${item.status}; starts ${start}; ends ${end}): ${item.title || 'Untitled'}${item.description ? ` — ${trimTo(item.description, 300)}` : ''}`;
+ return `Side quest (${item.status}; starts ${start}; ends ${end}): ${item.title || 'Untitled'}${item.description ? ` — ${item.description}` : ''}`;
});
const delivery = plan.deliveryOptions || {};
const deliveryLines = [];
@@ -189,7 +194,7 @@ const seriesPlanContext = (loom, episode) => {
}
}
return [
- plan.storyArc ? `Series arc: ${trimTo(plan.storyArc, 4000)}` : '',
+ plan.storyArc ? `Series arc: ${plan.storyArc}` : '',
...plotPoints,
...sideQuests,
...deliveryLines,
@@ -214,32 +219,32 @@ const protagonistContinuityContext = (loom) => [
'Every scene must declare protagonist presence. Off-screen protagonist scenes are valid: use them for direct communicator conversations with the audience and keep the protagonist out of the storyboard image. For an off-screen helper scene, frame the obstacle or space the protagonist cannot see — around a corner, beyond a bend, at a distance, or otherwise outside their sightline. The communicator stays on the protagonist\'s person and out of frame; never make a standalone comms device the subject of the storyboard image.',
];
-const storyContext = (loom, episode) => [
+const storyContext = (loom, episode, { includeSeriesPlan = true } = {}) => [
`Story: ${loom.name}`,
`Scene format: ${loomFormatLabel(loom.format)}`,
`Audience participation: ${audienceContract(loom, episode)}`,
...protagonistContinuityContext(loom),
loom.logline ? `Logline: ${loom.logline}` : '',
loom.premise ? `Premise: ${loom.premise}` : '',
- ...seriesPlanContext(loom, episode),
- episode ? `Episode ${episode.number}: ${episode.title || 'Untitled'}` : '',
+ ...(includeSeriesPlan ? seriesPlanContext(loom, episode) : []),
+ episode ? `CURRENT EPISODE ONLY: Episode ${episode.number}: ${episode.title || 'Untitled'} (id=${episode.id}). Other episode assignments are continuity context, not scenes to write here. Stop at this episode's ending; do not dramatize later episode plot points or challenge payoffs.` : '',
episode?.synopsis ? `Synopsis: ${episode.synopsis}` : '',
].filter(Boolean).join('\n');
const seriesPlanDigest = (loom) => JSON.stringify({
- storyArc: trimTo(loom.seriesPlan?.storyArc, 6000),
+ storyArc: loom.seriesPlan?.storyArc || '',
plotPoints: (loom.seriesPlan?.plotPoints || []).map((item) => ({
- ...item, description: trimTo(item.description, 400),
+ ...item, description: item.description || '',
})),
sideQuests: (loom.seriesPlan?.sideQuests || []).map((item) => ({
- ...item, description: trimTo(item.description, 400),
+ ...item, description: item.description || '',
})),
deliveryOptions: loom.seriesPlan?.deliveryOptions || null,
interEpisodeVoicemails: (loom.seriesPlan?.interEpisodeVoicemails || []).map((item) => ({
- ...item, transcript: trimTo(item.transcript, 500),
+ ...item, transcript: item.transcript || '',
})),
nextSeasonTeaser: loom.seriesPlan?.nextSeasonTeaser
- ? { ...loom.seriesPlan.nextSeasonTeaser, transcript: trimTo(loom.seriesPlan.nextSeasonTeaser.transcript, 500) }
+ ? { ...loom.seriesPlan.nextSeasonTeaser, transcript: loom.seriesPlan.nextSeasonTeaser.transcript || '' }
: null,
protagonistCharacterId: loom.protagonistCharacterId || null,
protagonistWardrobeId: loom.protagonistWardrobeId || null,
@@ -248,7 +253,7 @@ const seriesPlanDigest = (loom) => JSON.stringify({
id,
number,
title,
- synopsis: trimTo(synopsis, 300),
+ synopsis: synopsis || '',
beatOutline: storyOutline ? describeStoryOutlineForPrompt(storyOutline) : '(missing)',
})),
}, null, 2);
@@ -366,9 +371,12 @@ const episodeOutlineFingerprint = (loom, episode) => JSON.stringify({
const outlineStructuralAnalysis = (loom, episode) => {
const structural = analyzeStoryOutline(episode.storyOutline, {
+ nodes: episode.nodes,
participationMode: loom.participationMode,
requireAudienceIntroduction: requiresAudienceIntroduction(loom, episode),
challenges: fableLoomEpisodeChallenges(loom, episode.id),
+ plotPoints: loom.seriesPlan?.plotPoints,
+ episodeId: episode.id,
});
const teleplaySync = analyzeStoryOutlineTeleplaySync(episode, episode.storyOutline, {
participationMode: loom.participationMode,
@@ -425,6 +433,8 @@ export async function generateEpisodeOutline(loomId, episodeId, {
participationMode: loom.participationMode,
requireAudienceIntroduction: requiresAudienceIntroduction(loom, episode),
challenges: fableLoomEpisodeChallenges(loom, episode.id),
+ plotPoints: loom.seriesPlan?.plotPoints,
+ episodeId: episode.id,
});
const draft = {
...outline,
@@ -494,6 +504,8 @@ export async function weaveEpisode(loomId, episodeId, {
participationMode: loom.participationMode,
requireAudienceIntroduction: requiresAudienceIntroduction(loom, episode),
challenges: fableLoomEpisodeChallenges(loom, episode.id),
+ plotPoints: loom.seriesPlan?.plotPoints,
+ episodeId: episode.id,
})
: null;
const currentOutlineErrors = expandFromOutline
@@ -560,8 +572,15 @@ export async function weaveEpisode(loomId, episodeId, {
const outlineScene = remappedOutlineByNodeId.get(node.id);
return outlineScene ? {
...node,
+ title: outlineScene.title,
+ endingLabel: outlineScene.endingLabel || '',
plotPointId: outlineScene.plotPointId || null,
challengePhase: outlineScene.challengePhase || null,
+ transitions: node.transitions.map((transition) => {
+ const paths = outlineScene.transitions.filter((path) => path.targetKey === transition.targetNodeId);
+ const planned = paths.find((path) => path.intent === transition.intent) || (paths.length === 1 ? paths[0] : null);
+ return { ...transition, intent: planned?.intent || transition.intent };
+ }),
} : node;
});
const remappedOutlineValidation = remappedOutline
@@ -569,6 +588,8 @@ export async function weaveEpisode(loomId, episodeId, {
participationMode: loom.participationMode,
requireAudienceIntroduction: requiresAudienceIntroduction(loom, episode),
challenges: fableLoomEpisodeChallenges(loom, episode.id),
+ plotPoints: loom.seriesPlan?.plotPoints,
+ episodeId: episode.id,
})
: null;
const expandedOutline = remappedOutline
@@ -892,17 +913,68 @@ const analysisStrings = (value) => (Array.isArray(value) ? value : [])
.filter(Boolean)
.slice(0, 12);
+const requirePlanningVerdict = (content) => {
+ if (typeof content?.summary !== 'string' || !content.summary.trim()
+ || !Array.isArray(content.risks) || !content.risks.every((risk) => typeof risk === 'string' && risk.trim())) {
+ throw aiShapeError('The planning review returned no explicit verdict');
+ }
+};
+
/** Read-only story-editor pass over one episode's beat outline. */
-export async function reviewEpisodeOutline(loomId, episodeId, { providerId, model, effort, operationId } = {}) {
+export async function reviewEpisodeOutline(loomId, episodeId, { providerId, model, effort, operationId, planningGate = false } = {}) {
const loom = await requireLoom(loomId);
const episode = findEpisode(loom, episodeId);
if (!episode.storyOutline) {
throw new ServerError('Draft an episode outline before reviewing it', { status: 409, code: 'OUTLINE_REQUIRED' });
}
const structural = outlineStructuralAnalysis(loom, episode);
+ const reviewStatus = createLoomAiStatus({ operationId }, { action: 'review-episode-outline', label: 'Reviewing episode outline' });
+ if (loom.episodes[0]?.id === episode.id) {
+ // A full bible gives the reviewer knowledge the audience has not earned.
+ // Follow the opening path, withholding synopsis, canon and later payoffs.
+ const opening = [];
+ const openingGroups = new Set();
+ const groupByKey = new Map(episode.nodes.map((node) => [node.id, node.shot?.dramaticSceneId || node.id]));
+ const byKey = new Map(episode.storyOutline.scenes.map((scene) => [scene.key, scene]));
+ let beat = byKey.get(episode.storyOutline.startKey);
+ while (beat && !opening.some((item) => item.key === beat.key)) {
+ const group = groupByKey.get(beat.key) || beat.key;
+ if (!openingGroups.has(group) && openingGroups.size >= 3) break;
+ openingGroups.add(group);
+ opening.push({ key: beat.key, title: beat.title, summary: beat.summary });
+ if (beat.playbackMode === 'decision') break;
+ beat = byKey.get(beat.transitions[0]?.targetKey);
+ }
+ const cold = await runLoomAi('fableloom-review-episode-outline', {
+ storyContext: 'COLD OPENING REVIEW ONLY. You are a first-time viewer with no synopsis or world bible. From the opening beats alone, explain who the protagonist is, what they want right now, what interrupts them, and why that matters emotionally. Cite observable actions for each answer. Do not infer missing motivation from genre or fill gaps using imagined dialogue. Mystery about the cause is welcome; confusion about the basic situation is a blocking risk. Put missing orientation, unearned emotional investment and unexplained terminology needed to follow the action in risks, not recommendations. Return the usual summary, strengths, risks and recommendations JSON; summary and risks are required. Evaluate only this opening, not absent later endings.',
+ canonDigest: '(withheld for first-time-viewer review)',
+ episodeSequence: '(withheld)',
+ outlineDigest: JSON.stringify(opening),
+ structuralDigest: '(not part of this cold read)',
+ }, { providerId, model, effort, operationId }, {
+ action: 'review-episode-outline', label: 'Checking first-time viewer understanding', source: 'fableloom-review-episode-outline', status: reviewStatus, complete: false,
+ });
+ if (typeof cold.content?.summary !== 'string' || !cold.content.summary.trim()
+ || !Array.isArray(cold.content?.risks) || !cold.content.risks.every((risk) => typeof risk === 'string' && risk.trim())) {
+ reviewStatus?.error('The opening review returned no explicit comprehension verdict');
+ throw aiShapeError('The opening review returned no explicit comprehension verdict');
+ }
+ if (cold.content.risks.length) {
+ reviewStatus?.complete('Opening needs revision', { runId: cold.runId, shellReady: false });
+ return {
+ structural, runId: cold.runId,
+ analysis: {
+ summary: trimTo(cold.content.summary, 2000),
+ strengths: analysisStrings(cold.content.strengths),
+ risks: analysisStrings(cold.content.risks),
+ recommendations: analysisStrings(cold.content.recommendations),
+ },
+ };
+ }
+ }
const canonDigest = await buildCanonDigest(loom);
const { content, runId } = await runLoomAi('fableloom-review-episode-outline', {
- storyContext: storyContext(loom, episode),
+ storyContext: [storyContext(loom, episode), planningGate ? 'PLANNING GATE: Put only present contradictions, missing required beats, missing opening orientation or emotional stakes, illegible choices, or unearned consequences that require changing this outline in risks. Put execution advice for the later teleplay (for example how to avoid too much dialogue) in recommendations. Do not require finished dialogue or images at outline stage. An outline with no remaining concrete blockers should return an empty risks array.' : ''].filter(Boolean).join('\n'),
canonDigest: canonDigest || '(none)',
episodeSequence: episodeSequenceDigest(loom, episode.id),
outlineDigest: describeStoryOutlineForPrompt(episode.storyOutline),
@@ -910,8 +982,9 @@ export async function reviewEpisodeOutline(loomId, episodeId, { providerId, mode
? structural.issues.map((issue) => `- [${issue.severity}] ${issue.message}`).join('\n')
: '(no structural issues)',
}, { providerId, model, effort, operationId }, {
- action: 'review-episode-outline', label: 'Reviewing episode outline', source: 'fableloom-review-episode-outline',
+ action: 'review-episode-outline', label: 'Reviewing episode outline', source: 'fableloom-review-episode-outline', status: reviewStatus,
});
+ if (planningGate) requirePlanningVerdict(content);
const analysis = {
summary: trimTo(content?.summary, 2000),
strengths: analysisStrings(content?.strengths),
@@ -935,7 +1008,7 @@ export async function generateSeriesPlan(loomId, { providerId, model, effort, op
const sourceFingerprint = seriesPlanGenerationFingerprint(loom);
const canonDigest = await buildCanonDigest(loom);
const { content, runId } = await runLoomAi('fableloom-generate-series-plan', {
- storyContext: storyContext(loom),
+ storyContext: storyContext(loom, undefined, { includeSeriesPlan: false }),
canonDigest: canonDigest || '(none — invent only what the premise needs)',
seriesPlanJson: seriesPlanDigest(loom),
}, { providerId, model, effort, operationId }, {
@@ -968,16 +1041,17 @@ export async function generateSeriesPlan(loomId, { providerId, model, effort, op
}
/** Read-only story-editor pass over the arc, tentpole beats, side quests, and episode outline. */
-export async function reviewSeriesPlan(loomId, { providerId, model, effort, operationId } = {}) {
+export async function reviewSeriesPlan(loomId, { providerId, model, effort, operationId, planningOnly = false } = {}) {
const loom = await requireLoom(loomId);
const canonDigest = await buildCanonDigest(loom);
const { content, runId } = await runLoomAi('fableloom-review-series-plan', {
- storyContext: storyContext(loom),
+ storyContext: [storyContext(loom, undefined, { includeSeriesPlan: false }), planningOnly ? 'PRE-OUTLINE REVIEW: Evaluate the arc, challenge design and episode assignments. Missing or stale episode outlines are expected at this stage and will be drafted or repaired next; do not report their absence as a plan defect. Keep plot-point notes concise; episode beat outlines have their own fields.' : ''].filter(Boolean).join('\n'),
canonDigest: canonDigest || '(none)',
seriesPlanJson: seriesPlanDigest(loom),
}, { providerId, model, effort, operationId }, {
action: 'review-series-plan', label: 'Reviewing series plan', source: 'fableloom-review-series-plan',
});
+ if (planningOnly) requirePlanningVerdict(content);
const analysis = {
summary: trimTo(content?.summary, 2000),
strengths: analysisStrings(content?.strengths),
@@ -1018,7 +1092,7 @@ export async function reviewSeriesTeleplay(loomId, { providerId, model, effort,
return `Episode ${episode.episodeNumber}:\n${issues}`;
}).join('\n');
const { content, runId } = await runLoomAi('fableloom-review-series-teleplay', {
- storyContext: storyContext(loom),
+ storyContext: storyContext(loom, undefined, { includeSeriesPlan: false }),
canonDigest: canonDigest || '(none)',
seriesPlanJson: seriesPlanDigest(loom),
teleplayDigest: seriesTeleplayDigest(loom),
@@ -1049,7 +1123,7 @@ export async function feedbackSeriesPlan(loomId, {
const loom = await requireLoom(loomId);
const canonDigest = await buildCanonDigest(loom);
const { content, runId } = await runLoomAi('fableloom-feedback-series-plan', {
- storyContext: storyContext(loom),
+ storyContext: storyContext(loom, undefined, { includeSeriesPlan: false }),
canonDigest: canonDigest || '(none)',
seriesPlanJson: seriesPlanDigest(loom),
feedback: instruction,
@@ -1062,7 +1136,8 @@ export async function feedbackSeriesPlan(loomId, {
}
const hasPlanEdit = (hasOwn(content, 'storyArc') && typeof content.storyArc === 'string')
|| Array.isArray(content.plotPointEdits) || Array.isArray(content.plotPointOrder)
- || Array.isArray(content.sideQuestEdits) || Array.isArray(content.sideQuestOrder);
+ || Array.isArray(content.sideQuestEdits) || Array.isArray(content.sideQuestOrder)
+ || Array.isArray(content.episodeSynopsisEdits);
if (!hasPlanEdit) throw aiShapeError('The model returned no usable series-plan edits');
const updated = await mutateLoom(loomId, (current) => {
@@ -1074,6 +1149,13 @@ export async function feedbackSeriesPlan(loomId, {
plan.sideQuests = applyPlanItemEdits(plan.sideQuests, content.sideQuestEdits, content.sideQuestOrder, {
prefix: 'quest', fields: ['title', 'description', 'status', 'startEpisodeId', 'endEpisodeId'],
});
+ for (const edit of (Array.isArray(content.episodeSynopsisEdits) ? content.episodeSynopsisEdits : [])) {
+ const episode = current.episodes.find((item) => item.id === edit?.id);
+ if (episode && typeof edit.synopsis === 'string') {
+ episode.synopsis = edit.synopsis;
+ episode.updatedAt = new Date().toISOString();
+ }
+ }
current.seriesPlan = plan;
return current;
});
@@ -1124,6 +1206,7 @@ export const publicNode = (node, loom = null) => ({
id: node.id,
title: node.title,
prose: node.prose,
+ ...(node.shot ? { shot: node.shot } : {}),
image: node.image,
videoHistoryId: node.videoHistoryId,
playbackAssets: node.playbackAssets || null,
diff --git a/server/services/fableLoom/weave.test.js b/server/services/fableLoom/weave.test.js
index 7c9fa8ca0d..52d05f77fe 100644
--- a/server/services/fableLoom/weave.test.js
+++ b/server/services/fableLoom/weave.test.js
@@ -269,11 +269,16 @@ describe('weaveEpisode', () => {
expect(checked.validation.issues).toEqual([]);
expect(checked.outline.validation.status).toBe('valid');
- runStagedLLM.mockResolvedValueOnce({ content: generatedGraphFromOutline(), runId: 'expand-run' });
+ const expandedDraft = generatedGraphFromOutline();
+ expandedDraft.nodes[0].title = 'A reworded title';
+ expandedDraft.nodes[0].transitions[0].intent = 'A reworded label';
+ runStagedLLM.mockResolvedValueOnce({ content: expandedDraft, runId: 'expand-run' });
const expanded = await weaveEpisode(loomId, episodeId, {
guidance: 'Write the full teleplay now.', replace: false, expandFromOutline: true,
});
expect(expanded.runId).toBe('expand-run');
+ expect(expanded.loom.episodes[0].nodes[0].title).toBe(drafted.outline.scenes[0].title);
+ expect(expanded.loom.episodes[0].nodes[0].transitions[0].intent).toBe(drafted.outline.scenes[0].transitions[0].intent);
expect(expanded.loom.episodes[0].nodes).toHaveLength(4);
expect(expanded.loom.episodes[0].storyOutline.scenes.map((scene) => scene.key))
.toEqual(expanded.loom.episodes[0].nodes.map((node) => node.id));
@@ -411,10 +416,61 @@ describe('weaveEpisode', () => {
});
describe('episode outline AI review', () => {
+ it('withholds author context and blocks an unmotivated opening before the full review', async () => {
+ const { loomId, episodeId } = await setup();
+ runStagedLLM.mockResolvedValueOnce({ content: generatedOutline(), runId: 'outline-run' });
+ await generateEpisodeOutline(loomId, episodeId, {});
+ runStagedLLM.mockClear();
+ runStagedLLM.mockResolvedValueOnce({ content: { summary: 'A puzzle appears, but no personal goal is shown.', risks: ['Establish what the protagonist wants before the clue.'] }, runId: 'cold-review' });
+ const result = await reviewEpisodeOutline(loomId, episodeId, { planningGate: true, providerId: 'writer', model: 'small', effort: 'low' });
+ expect(result.analysis.risks).toEqual(['Establish what the protagonist wants before the clue.']);
+ expect(runStagedLLM).toHaveBeenCalledTimes(1);
+ const prompt = JSON.stringify(runStagedLLM.mock.calls[0]);
+ expect(prompt).toContain('COLD OPENING REVIEW ONLY');
+ expect(prompt).toContain('(withheld for first-time-viewer review)');
+ expect(prompt).not.toContain('CURRENT EPISODE ONLY');
+ expect(prompt).not.toContain('Series arc:');
+ });
+
+ it('cold-reads complete dramatic groups after camera cuts are split', async () => {
+ const { loomId, episodeId } = await setup();
+ await mutateLoom(loomId, (loom) => {
+ const ep = loom.episodes[0];
+ ep.nodes = Array.from({ length: 9 }, (_, index) => ({ id: `shot-${index}`, title: `Shot ${index}`, prose: `Action ${index}`, playbackMode: 'cut', isEnding: index === 8, shot: { dramaticSceneId: index < 4 ? 'opening' : index < 6 ? 'interruption' : index < 8 ? 'consequence' : 'later', durationSeconds: 8 }, transitions: index < 8 ? [{ targetNodeId: `shot-${index + 1}`, intent: 'continue' }] : [] }));
+ ep.startNodeId = 'shot-0';
+ ep.storyOutline = { startKey: 'shot-0', scenes: ep.nodes.map((node) => ({ key: node.id, title: node.title, summary: node.prose, playbackMode: 'cut', isEnding: node.isEnding, transitions: node.transitions.map((t) => ({ targetKey: t.targetNodeId, intent: t.intent })) })) };
+ return loom;
+ });
+ runStagedLLM.mockResolvedValueOnce({ content: { summary: 'Opening reviewed.', risks: ['Clarify the consequence.'] } });
+ await reviewEpisodeOutline(loomId, episodeId);
+ const opening = JSON.parse(runStagedLLM.mock.calls[0][1].outlineDigest);
+ expect(opening.map((beat) => beat.key)).toEqual(Array.from({ length: 8 }, (_, index) => `shot-${index}`));
+ });
+
+ it('does not treat a missing opening verdict as approval', async () => {
+ const { loomId, episodeId } = await setup();
+ runStagedLLM.mockResolvedValueOnce({ content: generatedOutline(), runId: 'outline-run' });
+ await generateEpisodeOutline(loomId, episodeId, {});
+ runStagedLLM.mockResolvedValueOnce({ content: { summary: 'Looks fine.' }, runId: 'incomplete-review' });
+ await expect(reviewEpisodeOutline(loomId, episodeId, {})).rejects.toThrow('explicit comprehension verdict');
+ });
+
+ it('requires an explicit full review verdict before the planning gate can pass', async () => {
+ const { loomId, episodeId } = await setup();
+ runStagedLLM.mockResolvedValueOnce({ content: generatedOutline() });
+ await generateEpisodeOutline(loomId, episodeId, {});
+ runStagedLLM.mockResolvedValueOnce({ content: { summary: 'The opening is clear.', risks: [] } });
+ runStagedLLM.mockResolvedValueOnce({ content: { summary: 'Looks fine.' } });
+ await expect(reviewEpisodeOutline(loomId, episodeId, { planningGate: true })).rejects.toMatchObject({ code: 'AI_RESPONSE_INVALID' });
+ runStagedLLM.mockResolvedValueOnce({ content: { summary: 'Looks fine.', risks: 'No problems' } });
+ await expect(reviewSeriesPlan(loomId, { planningOnly: true })).rejects.toMatchObject({ code: 'AI_RESPONSE_INVALID' });
+ });
+
it('returns deterministic findings alongside editorial analysis', async () => {
const { loomId, episodeId } = await setup();
runStagedLLM.mockResolvedValueOnce({ content: generatedOutline(), runId: 'outline-run' });
await generateEpisodeOutline(loomId, episodeId, {});
+ runStagedLLM.mockResolvedValueOnce({ content: { summary: 'A courier wants to get home; a closed gate threatens that goal.', risks: [] }, runId: 'cold-read' });
runStagedLLM.mockResolvedValueOnce({
content: { summary: 'The turn lands.', strengths: ['The endings diverge.'], risks: ['The handoff needs a sharper hook.'], recommendations: ['Make the final beat reveal the next threat.'] },
runId: 'outline-review-run',
@@ -1015,11 +1071,12 @@ describe('reformatEpisodeScenes', () => {
describe('buildCanonDigest', () => {
it('renders linked-universe canon via the shared renderer and returns empty for unlinked looms', async () => {
getUniverseMock.mockResolvedValue({
- characters: [{ name: 'Mara', description: 'silver-eyed courier' }],
+ characters: [{ id: 'character-example', name: 'Mara', description: 'silver-eyed courier' }],
places: [{ name: 'The Hollow' }],
objects: [],
});
- const digest = await buildCanonDigest({ universeId: 'uni-1' });
+ const digest = await buildCanonDigest({ universeId: 'uni-1', protagonistCharacterId: 'character-example' });
+ expect(digest).toContain('Verified Universe protagonist: id=character-example; name=Mara.');
expect(digest).toContain('characters:');
expect(digest).toContain('- Mara');
expect(digest).toContain('places:');
@@ -1123,20 +1180,40 @@ describe('series plan AI', () => {
}), expect.objectContaining({ providerOverride: 'writer' }));
});
+ it('passes complete challenge outcomes and arc endings to review without duplicate plan context', async () => {
+ const { loomId, episodeId } = await setup();
+ const storyArc = `${'An established turn. '.repeat(340)}The final reconciliation.`;
+ const description = `${'A planted clue. '.repeat(60)}FAILURE: Lose the original. RECOVERY: Keep the proof.`;
+ await updateLoom(loomId, { seriesPlan: { storyArc, plotPoints: [{ title: 'The lock', kind: 'challenge', description, episodeId }], sideQuests: [] } });
+ runStagedLLM.mockResolvedValueOnce({ content: { summary: 'The complete contract is visible.', risks: [], recommendations: [] } });
+ await reviewSeriesPlan(loomId, { planningOnly: true });
+ const variables = runStagedLLM.mock.calls[0][1];
+ const plan = JSON.parse(variables.seriesPlanJson);
+ expect(plan.storyArc).toBe(storyArc);
+ expect(plan.plotPoints[0].description).toBe(description);
+ expect(variables.storyContext).not.toContain(storyArc);
+ expect(variables.storyContext).toContain('PRE-OUTLINE REVIEW');
+ });
+
it('applies sparse series-plan feedback and preserves omitted collections', async () => {
const { loomId, episodeId } = await setup();
+ await addNode(loomId, episodeId, { title: 'Keep this scene', prose: 'The gate opens.' });
+ const before = await getLoom(loomId);
await updateLoom(loomId, { seriesPlan: {
storyArc: 'Old arc',
plotPoints: [{ id: 'plot-1', title: 'Turn', description: 'Old', episodeId }],
sideQuests: [],
} });
runStagedLLM.mockResolvedValueOnce({
- content: { storyArc: 'New arc', changes: ['Raised the stakes'] },
+ content: { storyArc: 'New arc', episodeSynopsisEdits: [{ id: episodeId, synopsis: 'The new consequence.', title: 'Do not replace', nodes: [] }, { id: 'unknown', synopsis: 'Ignored' }], changes: ['Raised the stakes'] },
runId: 'run-feedback',
});
const result = await feedbackSeriesPlan(loomId, { feedback: 'Raise the stakes.' });
expect(result.loom.seriesPlan.storyArc).toBe('New arc');
expect(result.loom.seriesPlan.plotPoints).toHaveLength(1);
+ expect(result.loom.episodes[0]).toMatchObject({ id: episodeId, title: 'Pilot', synopsis: 'The new consequence.' });
+ expect(result.loom.episodes).toHaveLength(1);
+ expect(result.loom.episodes[0].nodes).toEqual(before.episodes[0].nodes);
expect(result.changes).toEqual(['Raised the stakes']);
});
@@ -1170,6 +1247,24 @@ describe('series plan AI', () => {
}), expect.anything());
});
+ it('rejects a later episode payoff before expanding the current episode', async () => {
+ const { loomId, episodeId } = await setup();
+ const withSecond = await addEpisode(loomId, { title: 'Second' });
+ await updateLoom(loomId, { seriesPlan: { storyArc: 'Two distinct acts.', plotPoints: [
+ { id: 'plot-later', kind: 'challenge', title: 'Later revelation', description: 'Reserved for the second act.', episodeId: withSecond.episodes[1].id },
+ ], sideQuests: [] } });
+ const outline = generatedChallengeOutline();
+ outline.scenes.forEach((scene) => { scene.plotPointId = 'plot-later'; });
+ runStagedLLM.mockResolvedValueOnce({ content: outline });
+ const draft = await generateEpisodeOutline(loomId, episodeId);
+ expect(draft.validation.issues).toContainEqual(expect.objectContaining({ code: 'WRONG_EPISODE_PLOT_POINT', severity: 'error' }));
+ expect(runStagedLLM.mock.calls[0][1].storyContext).toContain('CURRENT EPISODE ONLY');
+ expect(runStagedLLM.mock.calls[0][1].storyContext).not.toContain('PLAYABLE CHALLENGE CONTRACT');
+ expect((await validateEpisodeOutline(loomId, episodeId)).outline.validation.status).toBe('invalid');
+ await expect(weaveEpisode(loomId, episodeId, { expandFromOutline: true })).rejects.toThrow();
+ expect(runStagedLLM).toHaveBeenCalledTimes(1);
+ });
+
it('expands explicitly-authored challenges into a multi-scene interactive contract', async () => {
const { loomId, episodeId } = await setup();
await updateLoom(loomId, { seriesPlan: {
diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.js
index 2ded1ae8d2..4b5c9020bd 100644
--- a/server/services/sharing/peerSyncAssets.js
+++ b/server/services/sharing/peerSyncAssets.js
@@ -560,7 +560,7 @@ export async function buildFableLoomAssetManifest(loom) {
.flatMap((episode) => (Array.isArray(episode?.nodes) ? episode.nodes : []));
const dedup = new Map();
const imageNames = [...new Set(
- nodes.map((node) => (isStr(node?.image) ? node.image : null)).filter(Boolean),
+ nodes.flatMap((node) => [node?.image, ...(node?.visualCanon?.characterAppearances || []).map((appearance) => appearance.referenceImage)]).filter(isStr),
)];
for (const entry of await Promise.all(imageNames.map((name) => hashImageForManifest(name)))) {
if (entry) dedup.set(`${entry.kind}:${entry.filename}`, entry);
diff --git a/server/services/sharing/peerSyncAssets.test.js b/server/services/sharing/peerSyncAssets.test.js
index a2f56b1677..75cbadb74c 100644
--- a/server/services/sharing/peerSyncAssets.test.js
+++ b/server/services/sharing/peerSyncAssets.test.js
@@ -315,12 +315,13 @@ describe('buildFableLoomAssetManifest — scene renders', () => {
const imageBytes = Buffer.from('scene-image');
const videoBytes = Buffer.from('scene-video');
writeImage('scene.png', imageBytes);
+ writeImage('anchor.png', imageBytes);
writeVideo('video-1.mp4', videoBytes);
const manifest = await buildFableLoomAssetManifest({
episodes: [
{ nodes: [{ id: 'node-1', image: 'scene.png', videoHistoryId: 'video-1' }] },
- { nodes: [{ id: 'node-2', image: 'scene.png', videoHistoryId: 'video-1' }] },
+ { nodes: [{ id: 'node-2', image: 'scene.png', videoHistoryId: 'video-1', visualCanon: { characterAppearances: [{ referenceImage: 'anchor.png' }] } }] },
],
});
@@ -330,7 +331,8 @@ describe('buildFableLoomAssetManifest — scene renders', () => {
expect(manifest).toContainEqual({
filename: 'video-1.mp4', kind: 'video', sha256: sha(videoBytes),
});
- expect(manifest).toHaveLength(2);
+ expect(manifest).toContainEqual(expect.objectContaining({ filename: 'anchor.png', kind: 'image' }));
+ expect(manifest).toHaveLength(3);
});
it('includes typed playback assets — entry, hold loops, and transition exits (#6006)', async () => {
diff --git a/server/services/videoGen/reactor.js b/server/services/videoGen/reactor.js
index 43f91687fd..bece88c440 100644
--- a/server/services/videoGen/reactor.js
+++ b/server/services/videoGen/reactor.js
@@ -1,30 +1,11 @@
-/**
- * Video Gen — Reactor.inc `fast-h3` video generation API provider (#6214).
- *
- * A cloud-only, near-realtime (~1.0x) video backend with native
- * clip-to-clip chaining (`continue_from_clip_id`), unlike the local
- * runtimes or the fal.ai/grok queue backends. Mirrors `videoGen/fal.js`'s
- * job-map/SSE contract (cloud lane, no local child process) so
- * `mediaJobQueue` can dispatch to it the same way.
- *
- * Auth flow: PortOS never hands the caller the raw `REACTOR_API_KEY` — it
- * mints a short-lived, scoped session JWT server-side (`mintReactorToken`,
- * also exposed at `GET /api/video-gen/reactor/token`) and uses that JWT to
- * submit/poll/cancel. Flow: POST the prompt (plus optional
- * `continue_from_clip_id` and a base64-encoded starting frame) to
- * `api.reactor.inc/v1/fast-h3/generate`, poll the returned status URL until
- * COMPLETED, then download the resulting MP4 and hand it to the shared
- * `finalizeGeneratedVideo` helper — same streaming optimization, thumbnail,
- * and history entry as every other video backend.
- */
-
+/** Reactor FastH3 renders one bounded SDK/WebRTC session per job. */
import { randomUUID } from 'crypto';
-import { readFile, writeFile } from 'fs/promises';
+import { stat, rm } from 'fs/promises';
+import { spawn } from '../../lib/childProcess.js';
import { join } from 'path';
import { ensureDir, PATHS } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';
-import { detectImageFormat } from '../../lib/mimeTypes.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
import { videoGenEvents } from './events.js';
import { finalizeGeneratedVideo } from './generateVideoHelpers.js';
@@ -36,22 +17,14 @@ export const REACTOR_MODEL_ID = 'fast-h3';
export const REACTOR_MAX_PROMPT_LENGTH = 800;
const REACTOR_TOKEN_TIMEOUT_MS = 15_000;
-const REACTOR_SUBMIT_TIMEOUT_MS = 30_000;
-const REACTOR_POLL_TIMEOUT_MS = 15_000;
-const REACTOR_POLL_INTERVAL_MS = 3000;
-const REACTOR_DOWNLOAD_TIMEOUT_MS = 5 * 60 * 1000;
-// A cloud render can queue behind other tenants before it starts — generously
-// bounded, same order of magnitude as fal's and grok's render caps.
const REACTOR_RENDER_TIMEOUT_MS = (() => {
const n = Number(process.env.REACTOR_VIDEO_TIMEOUT_MS);
return Number.isFinite(n) && n > 0 ? n : 20 * 60 * 1000;
})();
-// Per-job state — keyed by jobId (cloud lane allows parallel renders). Same
-// client shape as videoGen/fal.js so attachSseClient/broadcastSse work.
+// Per-job state uses the common cloud-lane SSE contract.
const jobs = new Map();
-// Tracks the reactor.inc request so cancel() can both stop our poll loop and
-// ask reactor.inc to cancel the queued/running render.
+// Cancellation terminates the SDK session process and its remote connection.
const activeRequests = new Map();
const activeJobs = new Map();
@@ -85,14 +58,14 @@ export async function mintReactorToken(apiKey) {
}
const res = await fetchWithTimeout(`${REACTOR_API_BASE}/tokens`, {
method: 'POST',
- headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
+ headers: { 'Reactor-API-Key': apiKey, 'Content-Type': 'application/json' },
body: JSON.stringify({
- authorization_details: [{ type: `reactor/${REACTOR_MODEL_ID}`, max_sessions: 1 }],
+ authorization_details: [{ type: 'session', resources: { models: { match: [`reactor/${REACTOR_MODEL_ID}`] } }, constraints: { max_sessions: 1 } }],
}),
}, REACTOR_TOKEN_TIMEOUT_MS);
const payload = await res.json().catch(() => null);
if (!res.ok || !payload?.jwt) {
- const reason = payload?.detail ? JSON.stringify(payload.detail) : `HTTP ${res.status}`;
+ const reason = `HTTP ${res.status}`;
throw new ServerError(`reactor.inc token minting failed: ${reason}`, { status: 502, code: 'REACTOR_TOKEN_FAILED' });
}
return { jwt: payload.jwt, expiresAt: payload.expires_at || null };
@@ -105,12 +78,7 @@ export const cancel = (jobId) => {
const entry = activeRequests.get(jobId);
if (!entry) return false;
entry.aborted = true;
- if (entry.cancelUrl && entry.jwt) {
- fetchWithTimeout(entry.cancelUrl, {
- method: 'PUT',
- headers: { Authorization: `Bearer ${entry.jwt}` },
- }, REACTOR_POLL_TIMEOUT_MS).catch(() => {});
- }
+ entry.stop?.('Canceled');
return true;
};
@@ -121,45 +89,82 @@ export const cancelAll = () => {
return true;
};
-async function toDataUri(imagePath) {
- const buf = await readFile(imagePath);
- const detected = detectImageFormat(buf);
- const mime = detected?.mime || 'image/png';
- return `data:${mime};base64,${buf.toString('base64')}`;
-}
-
-function buildRequestBody({ prompt, continueFromClipId, startingFrameDataUri, seconds, seed }) {
- const body = { prompt: prompt.trim().slice(0, REACTOR_MAX_PROMPT_LENGTH) };
- if (continueFromClipId) body.continue_from_clip_id = continueFromClipId;
- if (startingFrameDataUri) body.starting_frame = startingFrameDataUri;
- if (seconds) body.seconds = Number(seconds);
- if (seed !== undefined && seed !== null && seed !== '') body.seed = Number(seed);
- return body;
-}
-
-async function submitReactorJob({ jwt, body }) {
- const res = await fetchWithTimeout(`${REACTOR_API_BASE}/v1/${REACTOR_MODEL_ID}/generate`, {
- method: 'POST',
- headers: { Authorization: `Bearer ${jwt}`, 'Content-Type': 'application/json' },
- body: JSON.stringify(body),
- }, REACTOR_SUBMIT_TIMEOUT_MS);
- const payload = await res.json().catch(() => null);
- if (!res.ok || !payload?.clip_id) {
- const reason = payload?.detail ? JSON.stringify(payload.detail) : `HTTP ${res.status}`;
- throw new ServerError(`reactor.inc rejected the request: ${reason}`, { status: 502, code: 'REACTOR_SUBMIT_FAILED' });
+export function validateReactorRequest({ prompt, continueFromClipId, seconds = 6, seed }) {
+ if (typeof prompt !== 'string' || !prompt.trim() || prompt.trim().length > REACTOR_MAX_PROMPT_LENGTH) {
+ throw new ServerError('Reactor prompts must contain 1–800 characters; shorten the shot prompt before rendering', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (continueFromClipId) throw new ServerError('Reactor clip continuity requires the same active session; use a starting image for independent renders', { status: 400, code: 'REACTOR_SESSION_CONTINUITY_UNSUPPORTED' });
+ if (!Number.isFinite(Number(seconds)) || Number(seconds) < 5.167 || Number(seconds) > 14.375) {
+ throw new ServerError('Reactor duration must be between 5.167 and 14.375 seconds', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (seed != null && seed !== '' && (!Number.isSafeInteger(Number(seed)) || Number(seed) < 0)) {
+ throw new ServerError('Reactor seed must be a non-negative integer', { status: 400, code: 'VALIDATION_ERROR' });
}
- return payload;
+ return { prompt: prompt.trim(), seconds: Number(seconds), ...(seed != null && seed !== '' ? { seed: Number(seed) } : {}) };
}
-async function pollReactorStatus({ statusUrl, jwt }) {
- const res = await fetchWithTimeout(statusUrl, {
- headers: { Authorization: `Bearer ${jwt}` },
- }, REACTOR_POLL_TIMEOUT_MS);
- if (res.status === 401) {
- throw new ServerError('reactor.inc session expired', { status: 401, code: 'REACTOR_TOKEN_EXPIRED' });
- }
- if (!res.ok) throw new ServerError(`reactor.inc status check failed: HTTP ${res.status}`, { status: 502, code: 'REACTOR_STATUS_FAILED' });
- return res.json();
+function captureClip(entry, input, pythonPath, job, jobId) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(pythonPath, [join(PATHS.root, 'scripts', 'reactor-render.py')], { stdio: ['pipe', 'pipe', 'pipe'] });
+ let buffer = '';
+ let outputBytes = 0;
+ let complete = null;
+ let failure = null;
+ let killTimer;
+ let stopping = false;
+ const stop = (reason) => {
+ if (stopping) return;
+ stopping = true;
+ failure ||= new Error(reason);
+ child.kill('SIGTERM');
+ killTimer = setTimeout(() => child.kill('SIGKILL'), 5000);
+ killTimer.unref?.();
+ };
+ entry.stop = stop;
+ const timeout = setTimeout(() => stop('Reactor render timed out'), REACTOR_RENDER_TIMEOUT_MS);
+ timeout.unref?.();
+ const countOutput = (chunk) => {
+ outputBytes += Buffer.byteLength(chunk);
+ if (outputBytes > 1024 * 1024) stop('Reactor renderer exceeded its output limit');
+ };
+ child.stdout.on('data', (chunk) => {
+ countOutput(chunk);
+ if (failure) return;
+ buffer += chunk.toString();
+ const lines = buffer.split('\n');
+ buffer = lines.pop();
+ for (const line of lines) {
+ if (!line.trim()) continue;
+ try {
+ const message = JSON.parse(line);
+ if (message.type === 'complete' && typeof message.clipId === 'string' && Number.isFinite(message.seconds)) complete = message;
+ if (message.type === 'error' && /^[a-z]+$/.test(message.phase) && /^[A-Za-z]+$/.test(message.errorType)) failure = new Error(`Reactor ${message.phase} failed (${message.errorType})`);
+ if (message.type === 'status') {
+ if (typeof message.message === 'string' && /^Captured [0-9.]+ of [0-9.]+ frames; audio=(True|False)$/.test(message.message)) console.log(`🎬 ${message.message}`);
+ broadcastSse(job, { type: 'status', message: 'Reactor session rendering…' });
+ videoGenEvents.emit('activity', { generationId: jobId });
+ }
+ } catch {
+ stop('Reactor renderer returned malformed output');
+ }
+ }
+ });
+ // SDK diagnostics can contain credentials or local paths. Bound and discard them.
+ child.stderr.on('data', countOutput);
+ child.stdin.on('error', () => stop('Could not send request to Reactor renderer'));
+ child.on('error', () => {
+ failure ||= new Error('Could not start Reactor renderer; run the Reactor runtime setup');
+ });
+ child.on('close', (code) => {
+ clearTimeout(timeout);
+ clearTimeout(killTimer);
+ entry.stop = null;
+ if (failure || code !== 0 || !complete) reject(failure || new Error('Reactor renderer failed before completing a clip; check the installed SDK runtime'));
+ else resolve(complete);
+ });
+ child.stdin.end(JSON.stringify(input));
+ if (entry.aborted) stop('Canceled');
+ });
}
export async function generateVideo({
@@ -167,6 +172,10 @@ export async function generateVideo({
continueFromClipId, seconds, seed,
sourceImagePath = null, jobId: providedJobId = null,
}) {
+ const request = validateReactorRequest({ prompt, continueFromClipId, seconds, seed });
+ const pythonPath = process.env.REACTOR_PYTHON_PATH || join(PATHS.data, 'venvs', 'reactor', ...(process.platform === 'win32' ? ['Scripts', 'python.exe'] : ['bin', 'python']));
+ const runtime = await stat(pythonPath).catch(() => null);
+ if (!runtime?.isFile()) { throw new ServerError('Reactor runtime is missing. Run npm run setup:reactor, or set REACTOR_PYTHON_PATH', { status: 400, code: 'REACTOR_RUNTIME_MISSING' }); }
await ensureDir(PATHS.videos);
const renderStartedAtMs = Date.now();
@@ -206,7 +215,7 @@ export async function generateVideo({
broadcastSse(job, { type: 'status', message: 'Minting reactor.inc session…' });
runReactorVideo(job, jobId, {
- apiKey, prompt, continueFromClipId, seconds, seed, sourceImagePath, outputPath, filename, meta,
+ apiKey, ...request, pythonPath, sourceImagePath, outputPath, filename, meta,
}).catch((err) => {
console.log(`❌ reactor video run failed [${jobId.slice(0, 8)}]: ${err?.message}`);
});
@@ -219,76 +228,26 @@ export async function generateVideo({
}
async function runReactorVideo(job, jobId, {
- apiKey, prompt, continueFromClipId, seconds, seed, sourceImagePath, outputPath, filename, meta,
+ apiKey, prompt, seconds, seed, pythonPath, sourceImagePath, outputPath, filename, meta,
}) {
- const entry = { jwt: null, aborted: false, cancelUrl: null };
+ const entry = { aborted: false, stop: null };
activeRequests.set(jobId, entry);
- const deadline = Date.now() + REACTOR_RENDER_TIMEOUT_MS;
try {
- let { jwt } = await mintReactorToken(apiKey);
- entry.jwt = jwt;
+ const { jwt } = await mintReactorToken(apiKey);
if (entry.aborted) return finalizeCanceled(job, jobId);
-
- const startingFrameDataUri = sourceImagePath ? await toDataUri(sourceImagePath) : null;
- const body = buildRequestBody({
- prompt, continueFromClipId, startingFrameDataUri, seconds, seed,
- });
- broadcastSse(job, { type: 'status', message: 'Submitting to reactor.inc…' });
- const submitted = await submitReactorJob({ jwt, body });
- entry.cancelUrl = submitted.cancel_url || `${REACTOR_API_BASE}/v1/${REACTOR_MODEL_ID}/clips/${submitted.clip_id}/cancel`;
- const statusUrl = submitted.status_url || `${REACTOR_API_BASE}/v1/${REACTOR_MODEL_ID}/clips/${submitted.clip_id}`;
-
- while (Date.now() < deadline) {
- if (entry.aborted) return finalizeCanceled(job, jobId);
- videoGenEvents.emit('activity', { generationId: jobId });
- // A 20-minute render can outlive a short-lived session JWT — re-mint
- // once and retry rather than failing a render that's still in flight.
- let status;
- try {
- status = await pollReactorStatus({ statusUrl, jwt });
- } catch (err) {
- if (err?.code !== 'REACTOR_TOKEN_EXPIRED') throw err;
- ({ jwt } = await mintReactorToken(apiKey));
- entry.jwt = jwt;
- status = await pollReactorStatus({ statusUrl, jwt });
- }
- if (status.status === 'completed') {
- const videoUrl = status.video_url || status.output?.video_url;
- if (!videoUrl) {
- return finalizeError(job, jobId, 'reactor.inc completed but returned no video URL');
- }
- broadcastSse(job, { type: 'status', message: 'Downloading video…' });
- const videoRes = await fetchWithTimeout(videoUrl, {}, REACTOR_DOWNLOAD_TIMEOUT_MS);
- if (!videoRes.ok) {
- return finalizeError(job, jobId, `reactor.inc video download failed: HTTP ${videoRes.status}`);
- }
- const buffer = Buffer.from(await videoRes.arrayBuffer());
- await writeFile(outputPath, buffer);
-
- activeRequests.delete(jobId);
- activeJobs.delete(jobId);
- await finalizeGeneratedVideo({
- job,
- jobId,
- outputPath,
- filename,
- meta: { ...meta, clipId: status.clip_id || null },
- actualSeed: seed ?? null,
- mutateHistory: mutateVideoHistory,
- });
- closeJobAfterDelay(jobs, jobId);
- return;
- }
- if (status.status === 'failed') {
- return finalizeError(job, jobId, `reactor.inc render failed: ${status.error || 'unknown error'}`);
- }
- broadcastSse(job, { type: 'status', message: status.status === 'processing' ? 'Rendering…' : 'Queued…' });
- await new Promise((r) => setTimeout(r, REACTOR_POLL_INTERVAL_MS));
- }
+ const result = await captureClip(entry, { jwt, prompt, seconds, seed, sourceImagePath, outputPath }, pythonPath, job, jobId);
if (entry.aborted) return finalizeCanceled(job, jobId);
- return finalizeError(job, jobId, `reactor.inc did not finish within ${Math.round(REACTOR_RENDER_TIMEOUT_MS / 1000)}s`);
+ const output = await stat(outputPath).catch(() => null);
+ if (!output?.isFile() || !output.size) throw new Error('Reactor completed without a playable output file');
+ await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta: { ...meta, clipId: result.clipId, seconds: result.seconds }, actualSeed: seed ?? null, mutateHistory: mutateVideoHistory });
+ closeJobAfterDelay(jobs, jobId);
} catch (err) {
- finalizeError(job, jobId, `reactor.inc video generation failed: ${err?.message || err}`);
+ await rm(outputPath, { force: true }).catch(() => {});
+ finalizeError(job, jobId, entry.aborted ? 'Canceled' : `Reactor video generation failed: ${err?.message || 'unknown error'}`, { force: true });
+ } finally {
+ if (entry.aborted) await rm(outputPath, { force: true }).catch(() => {});
+ activeRequests.delete(jobId);
+ activeJobs.delete(jobId);
}
}
@@ -306,7 +265,4 @@ const finalizeError = (job, jobId, reason, { force = false } = {}) => {
};
// Test-only handles.
-export const _internals = {
- buildRequestBody,
- toDataUri,
-};
+export const _internals = { validateRequest: validateReactorRequest };
diff --git a/server/services/videoGen/reactor.test.js b/server/services/videoGen/reactor.test.js
index 3d0c5cc021..900ea6b0e3 100644
--- a/server/services/videoGen/reactor.test.js
+++ b/server/services/videoGen/reactor.test.js
@@ -1,280 +1,134 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { mkdir, rm, readFile } from 'fs/promises';
+import { EventEmitter, once } from 'events';
+import { mkdir, rm, writeFile } from 'fs/promises';
import { join } from 'path';
import { tmpdir } from 'os';
-const TEST_ROOT = join(tmpdir(), `portos-reactor-video-test-${process.pid}-${Date.now()}`);
-const FAKE_VIDEOS_DIR = join(TEST_ROOT, 'data-videos');
-const FAKE_DATA_DIR = join(TEST_ROOT, 'data');
-
+const root = join(tmpdir(), `reactor-test-${process.pid}`);
+const mocks = vi.hoisted(() => ({ spawn: vi.fn(), finalize: vi.fn(), settings: vi.fn() }));
+vi.mock('../../lib/childProcess.js', async (importOriginal) => ({ ...await importOriginal(), spawn: mocks.spawn }));
+vi.mock('./generateVideoHelpers.js', () => ({ finalizeGeneratedVideo: mocks.finalize }));
+vi.mock('../settings.js', () => ({ getSettings: mocks.settings }));
vi.mock('../../lib/fileUtils.js', async () => {
const actual = await vi.importActual('../../lib/fileUtils.js');
- actual.PATHS.videos = FAKE_VIDEOS_DIR;
- actual.PATHS.data = FAKE_DATA_DIR;
- return {
- ...actual,
- ensureDir: vi.fn(async (dir) => mkdir(dir, { recursive: true })),
- };
-});
-
-vi.mock('../../lib/ffmpeg.js', async () => {
- const actual = await vi.importActual('../../lib/ffmpeg.js');
- return {
- ...actual,
- optimizeForStreaming: vi.fn(async () => {}),
- generateThumbnail: vi.fn(async (_p, jobId) => `${jobId}.jpg`),
- };
+ return { ...actual, PATHS: { ...actual.PATHS, videos: join(root, 'videos'), data: root }, ensureDir: (dir) => mkdir(dir, { recursive: true }) };
});
-
-const getSettingsMock = vi.fn();
-vi.mock('../settings.js', () => ({ getSettings: getSettingsMock }));
-
const reactor = await import('./reactor.js');
const { videoGenEvents } = await import('./events.js');
-const { loadHistory } = await import('./history.js');
-
-const flush = () => new Promise((r) => setTimeout(r, 10));
-
-const jsonResponse = (body, ok = true, status = 200) => ({
- ok, status,
- json: async () => body,
-});
-
-const TOKEN_URL = `${reactor.REACTOR_API_BASE}/tokens`;
-const GENERATE_URL = `${reactor.REACTOR_API_BASE}/v1/${reactor.REACTOR_MODEL_ID}/generate`;
-
+const settings = { videoGen: { reactor: { apiKey: 'example-key' } } };
+let child;
+let input;
beforeEach(async () => {
- videoGenEvents.removeAllListeners();
- await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});
- await mkdir(FAKE_DATA_DIR, { recursive: true });
- getSettingsMock.mockReset().mockResolvedValue({});
- vi.restoreAllMocks();
+ vi.clearAllMocks();
+ await mkdir(root, { recursive: true });
+ await writeFile(join(root, 'python'), 'placeholder');
+ vi.stubEnv('REACTOR_PYTHON_PATH', join(root, 'python'));
+ vi.stubEnv('REACTOR_API_KEY', '');
+ mocks.settings.mockResolvedValue(settings);
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({ jwt: 'example-jwt' }) })));
+ mocks.spawn.mockImplementation(() => {
+ child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.stdin = new EventEmitter();
+ child.stdin.end = vi.fn((body) => { input = JSON.parse(body); });
+ child.kill = vi.fn(() => { queueMicrotask(() => child.emit('close', null)); });
+ return child;
+ });
});
-
afterEach(async () => {
- await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});
-});
-
-describe('videoGen/reactor — resolveReactorApiKey', () => {
- it('prefers the settings-stored key over the REACTOR_API_KEY env var', () => {
- const prevEnv = process.env.REACTOR_API_KEY;
- process.env.REACTOR_API_KEY = 'env-key';
- expect(reactor.resolveReactorApiKey({ videoGen: { reactor: { apiKey: ' settings-key ' } } })).toBe('settings-key');
- if (prevEnv === undefined) delete process.env.REACTOR_API_KEY; else process.env.REACTOR_API_KEY = prevEnv;
- });
-
- it('falls back to REACTOR_API_KEY when settings carry no key', () => {
- const prevEnv = process.env.REACTOR_API_KEY;
- process.env.REACTOR_API_KEY = 'env-key';
- expect(reactor.resolveReactorApiKey({})).toBe('env-key');
- if (prevEnv === undefined) delete process.env.REACTOR_API_KEY; else process.env.REACTOR_API_KEY = prevEnv;
- });
-
- it('returns null when neither settings nor env carry a key', () => {
- const prevEnv = process.env.REACTOR_API_KEY;
- delete process.env.REACTOR_API_KEY;
- expect(reactor.resolveReactorApiKey({})).toBeNull();
- if (prevEnv !== undefined) process.env.REACTOR_API_KEY = prevEnv;
- });
+ reactor.cancelAll();
+ vi.useRealTimers();
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+ videoGenEvents.removeAllListeners();
+ await rm(root, { recursive: true, force: true });
});
-
-describe('videoGen/reactor — mintReactorToken', () => {
- it('rejects when no API key is supplied', async () => {
- await expect(reactor.mintReactorToken(null)).rejects.toThrow(/No reactor\.inc API key/);
+const started = async (options = {}) => {
+ const result = await reactor.generateVideo({ prompt: 'A camera holds on a quiet gate.', seconds: 6, ...options });
+ await vi.waitFor(() => expect(mocks.spawn).toHaveBeenCalled());
+ return result;
+};
+
+describe('Reactor SDK adapter', () => {
+ it('mints the official scoped token, pipes it privately, and finalizes only a captured file', async () => {
+ const job = await started({ sourceImagePath: '/example/first-frame.png', seed: 42 });
+ expect(fetch).toHaveBeenCalledWith('https://api.reactor.inc/tokens', expect.objectContaining({ headers: { 'Reactor-API-Key': 'example-key', 'Content-Type': 'application/json' }, body: JSON.stringify({ authorization_details: [{ type: 'session', resources: { models: { match: ['reactor/fast-h3'] } }, constraints: { max_sessions: 1 } }] }) }));
+ expect(input).toMatchObject({ jwt: 'example-jwt', seconds: 6, seed: 42, sourceImagePath: '/example/first-frame.png' });
+ expect(JSON.stringify(mocks.spawn.mock.calls)).not.toContain('example-jwt');
+ await writeFile(input.outputPath, 'example-video');
+ child.stdout.emit('data', Buffer.from('{"type":"complete","clipId":"clip-example","seconds":6}\n'));
+ expect(mocks.finalize).not.toHaveBeenCalled();
+ child.emit('close', 0);
+ await vi.waitFor(() => expect(mocks.finalize).toHaveBeenCalledWith(expect.objectContaining({ jobId: job.jobId, meta: expect.objectContaining({ clipId: 'clip-example', seconds: 6 }) })));
});
- it('mints a scoped session JWT from the API key', async () => {
- const fetchMock = vi.fn(async (url, opts) => {
- expect(url).toBe(TOKEN_URL);
- expect(opts.headers.Authorization).toBe('Bearer test-key');
- const body = JSON.parse(opts.body);
- expect(body.authorization_details).toEqual([{ type: 'reactor/fast-h3', max_sessions: 1 }]);
- return jsonResponse({ jwt: 'signed-jwt', expires_at: '2026-01-01T00:00:00Z' });
- });
- vi.stubGlobal('fetch', fetchMock);
- const result = await reactor.mintReactorToken('test-key');
- expect(result).toEqual({ jwt: 'signed-jwt', expiresAt: '2026-01-01T00:00:00Z' });
- vi.unstubAllGlobals();
- });
-
- it('throws when the token endpoint rejects the key', async () => {
- vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ detail: 'invalid key' }, false, 401)));
- await expect(reactor.mintReactorToken('bad-key')).rejects.toThrow(/token minting failed/);
- vi.unstubAllGlobals();
+ it('rejects unsupported requests before minting or spending', async () => {
+ for (const options of [{ prompt: 'x'.repeat(801) }, { seconds: 5 }, { seconds: 15 }, { continueFromClipId: 'old-session-clip' }]) {
+ await expect(reactor.generateVideo({ prompt: 'A gate', ...options })).rejects.toBeTruthy();
+ }
+ expect(fetch).not.toHaveBeenCalled();
+ expect(mocks.spawn).not.toHaveBeenCalled();
});
-});
-describe('videoGen/reactor — _internals.buildRequestBody', () => {
- it('includes only the fields that were actually supplied, truncating an oversized prompt', () => {
- expect(reactor._internals.buildRequestBody({ prompt: ' a fox running ' })).toEqual({ prompt: 'a fox running' });
- expect(reactor._internals.buildRequestBody({
- prompt: 'pan', continueFromClipId: 'clip-1', startingFrameDataUri: 'data:image/png;base64,AA==', seconds: 6, seed: 42,
- })).toEqual({
- prompt: 'pan', continue_from_clip_id: 'clip-1', starting_frame: 'data:image/png;base64,AA==', seconds: 6, seed: 42,
- });
- const longPrompt = 'x'.repeat(reactor.REACTOR_MAX_PROMPT_LENGTH + 50);
- expect(reactor._internals.buildRequestBody({ prompt: longPrompt }).prompt.length).toBe(reactor.REACTOR_MAX_PROMPT_LENGTH);
+ it('fails missing runtime before minting a token', async () => {
+ vi.stubEnv('REACTOR_PYTHON_PATH', join(root, 'missing-python'));
+ await expect(reactor.generateVideo({ prompt: 'A gate' })).rejects.toMatchObject({ code: 'REACTOR_RUNTIME_MISSING' });
+ expect(fetch).not.toHaveBeenCalled();
});
-});
-
-describe('videoGen/reactor — generateVideo', () => {
- it('mints a token, submits, polls to completion, downloads the result, and finalizes history', async () => {
- const clipId = 'clip-123';
- const statusUrl = `${reactor.REACTOR_API_BASE}/v1/fast-h3/clips/${clipId}`;
- const fetchMock = vi.fn(async (url, opts) => {
- if (url === TOKEN_URL) return jsonResponse({ jwt: 'session-jwt', expires_at: null });
- if (url === GENERATE_URL) {
- expect(opts.headers.Authorization).toBe('Bearer session-jwt');
- expect(JSON.parse(opts.body)).toEqual({ prompt: 'a fox running' });
- return jsonResponse({ clip_id: clipId, status_url: statusUrl });
- }
- if (url === statusUrl) return jsonResponse({ status: 'completed', video_url: 'https://cdn.reactor.inc/out.mp4', clip_id: clipId });
- if (url === 'https://cdn.reactor.inc/out.mp4') {
- return { ok: true, status: 200, arrayBuffer: async () => Uint8Array.from(Buffer.from('fake-mp4-bytes')).buffer };
- }
- throw new Error(`unexpected fetch: ${url}`);
- });
- vi.stubGlobal('fetch', fetchMock);
-
- const job = await reactor.generateVideo({ settings: { videoGen: { reactor: { apiKey: 'test-key' } } }, prompt: 'a fox running' });
- expect(job.mode).toBe('reactor');
- expect(job.status).toBe('running');
- expect(job.filename).toMatch(/^[0-9a-f-]{36}\.mp4$/);
-
- const outputPath = join(FAKE_VIDEOS_DIR, job.filename);
- let history = [];
- for (let i = 0; i < 50 && history.length === 0; i += 1) {
- await flush();
- history = await loadHistory();
- }
-
- const written = await readFile(outputPath);
- expect(written.toString()).toBe('fake-mp4-bytes');
- expect(history[0].id).toBe(job.jobId);
- expect(history[0].modelId).toBe('reactor:fast-h3');
- vi.unstubAllGlobals();
+ it('does not finalize a completion marker without its output file', async () => {
+ await started();
+ const failed = once(videoGenEvents, 'failed');
+ child.stdout.emit('data', Buffer.from('{"type":"complete","clipId":"clip-example","seconds":6}\n'));
+ child.emit('close', 0);
+ await failed;
+ expect(mocks.finalize).not.toHaveBeenCalled();
});
- it('resolves the API key from live settings when the caller supplies none (the mediaJobQueue dispatch shape)', async () => {
- getSettingsMock.mockResolvedValue({ videoGen: { reactor: { apiKey: 'live-key' } } });
- const fetchMock = vi.fn(async (url, opts) => {
- if (url === TOKEN_URL) {
- expect(opts.headers.Authorization).toBe('Bearer live-key');
- return jsonResponse({ jwt: 'jwt-1', expires_at: null });
- }
- if (url === GENERATE_URL) return jsonResponse({ clip_id: 'c1', status_url: `${reactor.REACTOR_API_BASE}/v1/fast-h3/clips/c1` });
- if (url === `${reactor.REACTOR_API_BASE}/v1/fast-h3/clips/c1`) {
- return jsonResponse({ status: 'completed', video_url: 'https://cdn.reactor.inc/out.mp4' });
- }
- if (url === 'https://cdn.reactor.inc/out.mp4') {
- return { ok: true, status: 200, arrayBuffer: async () => Uint8Array.from(Buffer.from('bytes')).buffer };
- }
- throw new Error(`unexpected fetch: ${url}`);
- });
- vi.stubGlobal('fetch', fetchMock);
-
- const job = await reactor.generateVideo({ prompt: 'x' });
- for (let i = 0; i < 50 && fetchMock.mock.calls.length < 1; i += 1) await flush();
- await flush();
- expect(getSettingsMock).toHaveBeenCalled();
- expect(job.status).toBe('running');
- vi.unstubAllGlobals();
+ it('cancels the child and never finalizes a canceled request', async () => {
+ const job = await started();
+ const failed = once(videoGenEvents, 'failed');
+ expect(reactor.cancel(job.jobId)).toBe(true);
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ await failed;
+ expect(mocks.finalize).not.toHaveBeenCalled();
});
- it('rejects when no API key is configured', async () => {
- const prevEnv = process.env.REACTOR_API_KEY;
- delete process.env.REACTOR_API_KEY;
- await expect(reactor.generateVideo({ prompt: 'x', settings: {} })).rejects.toThrow(/No reactor\.inc API key/);
- if (prevEnv !== undefined) process.env.REACTOR_API_KEY = prevEnv;
+ it('can still cancel and reap a renderer after it reports a failure', async () => {
+ vi.useFakeTimers();
+ const job = await started();
+ child.kill.mockImplementation((signal) => { if (signal === 'SIGKILL') child.emit('close', null); });
+ const failed = once(videoGenEvents, 'failed');
+ child.stdout.emit('data', Buffer.from('{"type":"error","phase":"capture","errorType":"RuntimeError"}\n'));
+ expect(reactor.cancel(job.jobId)).toBe(true);
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(child.kill).toHaveBeenCalledWith('SIGKILL');
+ await failed;
+ expect(reactor.getActiveJob()).toBeNull();
+ expect(mocks.finalize).not.toHaveBeenCalled();
});
- it('emits failed and does not write output when reactor.inc reports a failed status', async () => {
- const fetchMock = vi.fn(async (url) => {
- if (url === TOKEN_URL) return jsonResponse({ jwt: 'jwt-2', expires_at: null });
- if (url === GENERATE_URL) return jsonResponse({ clip_id: 'c2', status_url: `${reactor.REACTOR_API_BASE}/v1/fast-h3/clips/c2` });
- if (url === `${reactor.REACTOR_API_BASE}/v1/fast-h3/clips/c2`) {
- return jsonResponse({ status: 'failed', error: 'model overloaded' });
- }
- throw new Error(`unexpected fetch: ${url}`);
- });
- vi.stubGlobal('fetch', fetchMock);
-
- const failed = vi.fn();
- videoGenEvents.on('failed', failed);
- const job = await reactor.generateVideo({ settings: { videoGen: { reactor: { apiKey: 'test-key' } } }, prompt: 'x' });
- for (let i = 0; i < 20 && failed.mock.calls.length < 1; i += 1) await flush();
-
- expect(failed).toHaveBeenCalledWith(expect.objectContaining({ generationId: job.jobId, error: expect.stringContaining('model overloaded') }));
- vi.unstubAllGlobals();
+ it('bounds process output instead of publishing success', async () => {
+ await started();
+ const failed = once(videoGenEvents, 'failed');
+ child.stderr.emit('data', Buffer.alloc(1024 * 1024 + 1));
+ await failed;
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ expect(mocks.finalize).not.toHaveBeenCalled();
});
-
- it('threads continue_from_clip_id, seconds, and seed onto the submit body', async () => {
- const fetchMock = vi.fn(async (url, opts) => {
- if (url === TOKEN_URL) return jsonResponse({ jwt: 'jwt-3', expires_at: null });
- if (url === GENERATE_URL) {
- expect(JSON.parse(opts.body)).toEqual({
- prompt: 'continued shot', continue_from_clip_id: 'clip-9', seconds: 6, seed: 7,
- });
- return jsonResponse({ clip_id: 'c3', status_url: `${reactor.REACTOR_API_BASE}/v1/fast-h3/clips/c3` });
- }
- if (url === `${reactor.REACTOR_API_BASE}/v1/fast-h3/clips/c3`) {
- return jsonResponse({ status: 'completed', video_url: 'https://cdn.reactor.inc/out.mp4' });
- }
- if (url === 'https://cdn.reactor.inc/out.mp4') {
- return { ok: true, status: 200, arrayBuffer: async () => Uint8Array.from(Buffer.from('bytes')).buffer };
- }
- throw new Error(`unexpected fetch: ${url}`);
- });
- vi.stubGlobal('fetch', fetchMock);
-
- await reactor.generateVideo({
- settings: { videoGen: { reactor: { apiKey: 'test-key' } } },
- prompt: 'continued shot',
- continueFromClipId: 'clip-9',
- seconds: 6,
- seed: 7,
- });
- for (let i = 0; i < 50 && fetchMock.mock.calls.length < 2; i += 1) await flush();
- expect(fetchMock).toHaveBeenCalled();
- vi.unstubAllGlobals();
+ it('terminates timed-out sessions and escalates when graceful termination is ignored', async () => {
+ vi.useFakeTimers();
+ await started();
+ child.kill.mockImplementation((signal) => { if (signal === 'SIGKILL') child.emit('close', null); });
+ const failed = once(videoGenEvents, 'failed');
+ await vi.advanceTimersByTimeAsync(20 * 60 * 1000);
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(child.kill).toHaveBeenCalledWith('SIGKILL');
+ await failed;
+ expect(mocks.finalize).not.toHaveBeenCalled();
});
- it('re-mints the session token and retries once when a poll returns 401', async () => {
- const statusUrl = `${reactor.REACTOR_API_BASE}/v1/fast-h3/clips/c4`;
- let tokenMints = 0;
- let statusCalls = 0;
- const fetchMock = vi.fn(async (url, opts) => {
- if (url === TOKEN_URL) {
- tokenMints += 1;
- return jsonResponse({ jwt: `jwt-${tokenMints}`, expires_at: null });
- }
- if (url === GENERATE_URL) return jsonResponse({ clip_id: 'c4', status_url: statusUrl });
- if (url === statusUrl) {
- statusCalls += 1;
- if (statusCalls === 1) {
- expect(opts.headers.Authorization).toBe('Bearer jwt-1');
- return { ok: false, status: 401, json: async () => ({}) };
- }
- expect(opts.headers.Authorization).toBe('Bearer jwt-2');
- return jsonResponse({ status: 'completed', video_url: 'https://cdn.reactor.inc/out.mp4' });
- }
- if (url === 'https://cdn.reactor.inc/out.mp4') {
- return { ok: true, status: 200, arrayBuffer: async () => Uint8Array.from(Buffer.from('bytes')).buffer };
- }
- throw new Error(`unexpected fetch: ${url}`);
- });
- vi.stubGlobal('fetch', fetchMock);
-
- const job = await reactor.generateVideo({ settings: { videoGen: { reactor: { apiKey: 'test-key' } } }, prompt: 'x' });
- const outputPath = join(FAKE_VIDEOS_DIR, job.filename);
- let history = [];
- for (let i = 0; i < 50 && history.length === 0; i += 1) {
- await flush();
- history = await loadHistory();
- }
- expect(await readFile(outputPath)).toBeTruthy();
- expect(tokenMints).toBe(2);
- vi.unstubAllGlobals();
- });
});