Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: checkpoint scene-scoped FableLoom shot autopilot (#13204)

[._.]/ Adam Eivyf51f3df6fe8c
diff --git a/client/src/components/fableloom/LoomShotPlanner.jsx b/client/src/components/fableloom/LoomShotPlanner.jsx
index 93c03bdddd..179581b0ca 100644
--- a/client/src/components/fableloom/LoomShotPlanner.jsx
+++ b/client/src/components/fableloom/LoomShotPlanner.jsx
@@ -1,26 +1,42 @@
import { useEffect, useState } from 'react';
import { Loader2, Scissors } from 'lucide-react';
+import { useFableLoomRun } from '../../hooks/useFableLoomRun';
+import toast from '../ui/Toast';
import ConfirmButtonPair from '../ui/ConfirmButtonPair';
import { useAsyncAction } from '../../hooks/useAsyncAction';
-import { applyLoomEpisodeShots, planLoomEpisodeShots } from '../../services/api';
+import { applyLoomEpisodeShots, startLoomEpisodeShotRun, getLoomEpisodeShotRun, cancelLoomEpisodeShotRun, getLoom } 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);
+ const { run: shotRun, applyRun } = useFableLoomRun({
+ loomId: loom.id, episodeId: episode.id, event: 'fableloom:shots:run',
+ loadRun: () => getLoomEpisodeShotRun(loom.id, episode.id, { silent: true }),
+ onTerminal: (finished, isCurrent) => {
+ if (finished.status === 'completed') {
+ setPlan(finished.result);
+ if (finished.result?.loom) getLoom(loom.id, { silent: true }).then(current => { if (isCurrent()) onLoomUpdate(current); }).catch(() => toast.error('Shot plan applied, but the story could not be refreshed. Reload to see it.'));
+ }
+ },
+ });
+ const active = ['running', 'canceling'].includes(shotRun?.status);
+ const [run, running] = useAsyncAction(async (apply = false, resume = false) => {
+ const result = await startLoomEpisodeShotRun(loom.id, episode.id, { ...route, guidance, apply, maxRounds: 3, resume }, { silent: true });
+ applyRun(result);
}, { 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 [cancel, canceling] = useAsyncAction(async () => {
+ applyRun(await cancelLoomEpisodeShotRun(loom.id, episode.id, { silent: true }));
+ }, { errorMessage: 'Could not stop shot planning' });
+ useEffect(() => { setPlan(null); }, [loom.id, episode.id]);
+ useEffect(() => { onRunningChange?.(active || running || applying); }, [active, running, applying, onRunningChange]);
const timing = analyzeEpisodeShots(episode);
- const busy = disabled || running || applying;
+ const busy = disabled || active || 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>
@@ -28,6 +44,11 @@ export default function LoomShotPlanner({ loom, episode, route, guidance, disabl
<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>
+ {shotRun && <div role="status" className="text-xs space-y-2">
+ <p>{shotRun.message}</p>
+ {active ? <button type="button" disabled={canceling || shotRun.status === 'canceling'} onClick={cancel} className="min-h-11 rounded border border-port-border px-3">Stop shot planning</button> : null}
+ {['failed', 'canceled'].includes(shotRun.status) ? <button type="button" disabled={busy} onClick={() => run(false, true)} className="min-h-11 rounded border border-port-border px-3">Resume saved shot plan</button> : null}
+ </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'}
diff --git a/client/src/components/fableloom/LoomShotPlanner.test.jsx b/client/src/components/fableloom/LoomShotPlanner.test.jsx
index ff529fbed1..9047098cea 100644
--- a/client/src/components/fableloom/LoomShotPlanner.test.jsx
+++ b/client/src/components/fableloom/LoomShotPlanner.test.jsx
@@ -1,19 +1,19 @@
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() }));
+const api = vi.hoisted(() => ({ getLoom: vi.fn(async () => ({ id: 'loom-1' })), getLoomEpisodeShotRun: vi.fn(async () => null), cancelLoomEpisodeShotRun: vi.fn(), startLoomEpisodeShotRun: 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.startLoomEpisodeShotRun.mockResolvedValue({ id: 'run-1', loomId: 'loom-1', episodeId: 'ep-1', status: 'completed', createdAt: '2026-01-01', revision: 1, result: { 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(api.startLoomEpisodeShotRun).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();
@@ -24,17 +24,28 @@ it('previews with the selected route, then explicitly applies the reviewed finge
it('confirms destructive autopilot replacement and reports its active lifecycle', async () => {
let finish;
- api.planLoomEpisodeShots.mockClear();
- api.planLoomEpisodeShots.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
+ api.startLoomEpisodeShotRun.mockClear();
+ api.startLoomEpisodeShotRun.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();
+ expect(api.startLoomEpisodeShotRun).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
- expect(api.planLoomEpisodeShots).not.toHaveBeenCalled();
+ expect(api.startLoomEpisodeShotRun).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' } });
+ finish({ id: 'run-2', loomId: 'loom-1', episodeId: 'ep-1', createdAt: '2026-01-02', revision: 1, status: 'completed', result: { review: { summary: 'Applied.' }, groups: [], loom: { id: 'loom-1' } } });
await waitFor(() => expect(onRunningChange).toHaveBeenLastCalledWith(false));
});
+
+it('reattaches to an interrupted run and resumes its saved options', async () => {
+ const interrupted = { id: 'run-saved', loomId: 'loom-1', episodeId: 'ep-1', revision: 2, attempt: 1, createdAt: '2026-01-03', status: 'failed', message: 'Interrupted; saved draft preserved.' };
+ api.getLoomEpisodeShotRun.mockResolvedValueOnce(interrupted);
+ api.startLoomEpisodeShotRun.mockResolvedValue({ ...interrupted, revision: 3, attempt: 2, status: 'running', message: 'Resuming saved draft' });
+ render(<LoomShotPlanner loom={{ id: 'loom-1' }} episode={{ id: 'ep-1', nodes: [] }} onLoomUpdate={vi.fn()} />);
+ await screen.findByText('Interrupted; saved draft preserved.');
+ fireEvent.click(screen.getByRole('button', { name: 'Resume saved shot plan' }));
+ await screen.findByRole('button', { name: 'Stop shot planning' });
+ expect(api.startLoomEpisodeShotRun).toHaveBeenLastCalledWith('loom-1', 'ep-1', expect.objectContaining({ resume: true }), { silent: true });
+});
diff --git a/client/src/services/apiFableLoom.js b/client/src/services/apiFableLoom.js
index 370b9c34ca..1f47a814db 100644
--- a/client/src/services/apiFableLoom.js
+++ b/client/src/services/apiFableLoom.js
@@ -188,3 +188,7 @@ export const reviewLoomEpisodeContinuity = (id, episodeId, 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 });
+
+export const startLoomEpisodeShotRun = (id, episodeId, body = {}, options = {}) => request(episodePath(id, episodeId, '/shots/start'), { method: 'POST', body: JSON.stringify(body), ...options });
+export const getLoomEpisodeShotRun = (id, episodeId, options = {}) => request(episodePath(id, episodeId, '/shots/status'), options);
+export const cancelLoomEpisodeShotRun = (id, episodeId, options = {}) => request(episodePath(id, episodeId, '/shots/cancel'), { method: 'POST', ...options });
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 86c4cd7132..4c6cf4c967 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -1100,3 +1100,5 @@ recent-retirements display list. Its keys hash the exact archive path and releas
identity; values preserve the original receipt timestamp. This operational
recovery evidence prevents an interrupted journal replay from becoming fresh
retirement evidence after the display row has aged out. It has no TTL purge.
+
+FableLoom shot-planning run checkpoints live in machine-local `data/fableloom-shot-runs/` JSON journals (atomic writes, one latest run per story/episode). They preserve drafts, review verdicts and feedback across restarts; they do not federate. Reading an interrupted run marks it failed without starting a provider call. Explicit resume uses the saved provider/guidance and rejects changed source revisions. Story records remain PostgreSQL-primary.
diff --git a/docs/features/fableloom.md b/docs/features/fableloom.md
index 21ef2b2ee1..0a37638eaf 100644
--- a/docs/features/fableloom.md
+++ b/docs/features/fableloom.md
@@ -418,3 +418,14 @@ opens its own session, so whether an earlier clip is still addressable is
Reactor's decision: a rejected ID fails that render with a message naming the
continuation (episodes re-establish the shot fresh instead). A continuation and
a starting image are mutually exclusive.
+
+
+### Recoverable timed-shot planning
+
+The shot planner starts a background run with `POST /api/fableloom/:id/episodes/:episodeId/shots/start`.
+`GET .../shots/status` reattaches to its latest state; `POST .../shots/cancel` stops after the active provider call.
+The UI receives `fableloom:shots:run` snapshots and reloads status on reconnect. The legacy `POST .../shots/plan` remains synchronous for existing callers.
+
+Draft and review run on one source scene at a time with the episode's compact graph digest. A final text consistency review receives the complete shot plan and graph, without the complete teleplay. Provider timeout settings remain authoritative; large inputs show a warning. Stage failures name the stage, round, scene and provider.
+
+Each draft and review is saved before the next call. After a restart the run is reported failed with those steps preserved; no AI work starts at boot. Resume sends `{ "resume": true }` to the start endpoint, retaining the original route, direction and apply choice, and reuses completed steps. Changed episodes require a fresh plan. New previews explicitly start a fresh run. Applying still requires a complete, validated, reviewed plan matching the episode revision; cancellation prevents application after an in-flight call.
diff --git a/server/hostControlCoverage.test.js b/server/hostControlCoverage.test.js
index 884deccd97..a248353e9b 100644
--- a/server/hostControlCoverage.test.js
+++ b/server/hostControlCoverage.test.js
@@ -492,6 +492,7 @@ const REVIEWED_OPEN_MUTATIONS = [
['POST /api/fableloom/:id/episodes/:episodeId/sessions/host', TOOL_FREE_INFERENCE],
['POST /api/fableloom/:id/episodes/:episodeId/sessions/preflight', READ_OVER_POST],
['POST /api/fableloom/:id/episodes/:episodeId/shots/apply', RECORDS],
+ ['POST /api/fableloom/:id/episodes/:episodeId/shots/cancel', REDUCES_EXECUTION],
['DELETE /api/fableloom/sessions/:sessionId', REMOVES_RECORD],
['PATCH /api/fableloom/sessions/:sessionId', RECORDS],
// /api/feature-agents
diff --git a/server/lib/fableLoomValidation.js b/server/lib/fableLoomValidation.js
index 4379f6c5c5..b9dac5b2e3 100644
--- a/server/lib/fableLoomValidation.js
+++ b/server/lib/fableLoomValidation.js
@@ -488,4 +488,5 @@ export const shotDraftSchema = z.object({
});
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 shotRunStartSchema = shotAutopilotSchema.extend({ resume: z.boolean().optional() });
export const shotApplySchema = z.object({ sourceFingerprint: z.string().length(64), groups: shotGroupsSchema });
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.js
index 2bd779ad23..23c3c2f74b 100644
--- a/server/lib/hostControlRoutes.js
+++ b/server/lib/hostControlRoutes.js
@@ -1027,6 +1027,7 @@ export const HOST_CONTROL_ROUTES = Object.freeze([
'POST /api/fableloom/:id/playtest',
'POST /api/fableloom/:id/episodes/:episodeId/weave',
'POST /api/fableloom/:id/episodes/:episodeId/shots/plan',
+ 'POST /api/fableloom/:id/episodes/:episodeId/shots/start',
'POST /api/fableloom/:id/episodes/:episodeId/outline/generate',
'POST /api/fableloom/:id/episodes/:episodeId/outline/review',
'POST /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId/branch',
diff --git a/server/lib/hostControlRoutes.test.js b/server/lib/hostControlRoutes.test.js
index 18ceb87c41..f821666801 100644
--- a/server/lib/hostControlRoutes.test.js
+++ b/server/lib/hostControlRoutes.test.js
@@ -675,6 +675,7 @@ describe('FableLoom mutation inventory (#10668)', () => {
'PATCH /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId/transitions/:transitionId',
'DELETE /api/fableloom/:id/episodes/:episodeId/nodes/:nodeId/transitions/:transitionId',
'POST /api/fableloom/:id/episodes/:episodeId/shots/apply',
+ 'POST /api/fableloom/:id/episodes/:episodeId/shots/cancel',
'POST /api/fableloom/:id/episodes/:episodeId/outline/validate',
'POST /api/fableloom/:id/episodes/:episodeId/sessions/preflight',
'POST /api/fableloom/:id/episodes/:episodeId/sessions/host',
diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.js
index 90d224801f..38c9641e1c 100644
--- a/server/lib/socketEventContracts.js
+++ b/server/lib/socketEventContracts.js
@@ -540,6 +540,7 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({
}),
'fableloom:editorial:run': loomRunSnapshot(false),
'fableloom:production:run': loomRunSnapshot(true),
+ 'fableloom:shots:run': loomRunSnapshot(false),
'app:deploy': input(appDeploySchema, 'Deploy a managed app with allowlisted flags.'),
'app:standardize': input(appStandardizeSchema, 'Standardize one registered app.'),
'app:update': input(appUpdateSchema, 'Run the update lifecycle for one registered app.'),
diff --git a/server/routes/fableLoom.js b/server/routes/fableLoom.js
index 1441d1838b..74228b8dd6 100644
--- a/server/routes/fableLoom.js
+++ b/server/routes/fableLoom.js
@@ -9,10 +9,12 @@
*/
import { Router } from 'express';
+import { startEpisodeShotRun, getEpisodeShotRun, cancelEpisodeShotRun } from '../services/fableLoom/shotRuns.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import {
shotAutopilotSchema,
+ shotRunStartSchema,
shotApplySchema,
branchSchema,
episodeCreateSchema,
@@ -326,6 +328,15 @@ 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/start', asyncHandler(async (req, res) => {
+ res.status(202).json(await startEpisodeShotRun(req.params.id, req.params.episodeId, validateRequest(shotRunStartSchema, req.body ?? {})));
+}));
+router.get('/:id/episodes/:episodeId/shots/status', asyncHandler(async (req, res) => {
+ res.json(await getEpisodeShotRun(req.params.id, req.params.episodeId));
+}));
+router.post('/:id/episodes/:episodeId/shots/cancel', asyncHandler(async (req, res) => {
+ res.json(await cancelEpisodeShotRun(req.params.id, req.params.episodeId));
+}));
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)));
}));
diff --git a/server/routes/fableLoom.test.js b/server/routes/fableLoom.test.js
index 5c456994c2..817a579a09 100644
--- a/server/routes/fableLoom.test.js
+++ b/server/routes/fableLoom.test.js
@@ -54,6 +54,8 @@ vi.mock('../services/fableLoom/index.js', () => ({
reviewEpisodeContinuity: vi.fn(),
}));
+vi.mock('../services/fableLoom/shotRuns.js', () => ({ startEpisodeShotRun: vi.fn(), getEpisodeShotRun: vi.fn(), cancelEpisodeShotRun: vi.fn() }));
+import * as shotRuns from '../services/fableLoom/shotRuns.js';
import * as fableLoom from '../services/fableLoom/index.js';
import routes from './fableLoom.js';
@@ -615,3 +617,18 @@ describe('FableLoom routes', () => {
});
});
});
+
+it('starts detached shot planning, validates resume, and exposes reattach/cancel', async () => {
+ const run = { id: 'shots-example', status: 'running' };
+ shotRuns.startEpisodeShotRun.mockResolvedValue(run);
+ shotRuns.getEpisodeShotRun.mockResolvedValue(run);
+ shotRuns.cancelEpisodeShotRun.mockResolvedValue({ ...run, status: 'canceling' });
+ const base = '/api/fableloom/loom-1/episodes/ep-1/shots';
+ const started = await request(makeApp()).post(`${base}/start`).send({ resume: true });
+ expect(started.status).toBe(202);
+ expect(started.body).toEqual(run);
+ expect(shotRuns.startEpisodeShotRun).toHaveBeenCalledWith('loom-1', 'ep-1', expect.objectContaining({ resume: true }));
+ expect((await request(makeApp()).post(`${base}/start`).send({ resume: 'yes' })).status).toBe(400);
+ expect((await request(makeApp()).get(`${base}/status`)).body).toEqual(run);
+ expect((await request(makeApp()).post(`${base}/cancel`)).body.status).toBe('canceling');
+});
diff --git a/server/services/fableLoom/shotRuns.js b/server/services/fableLoom/shotRuns.js
new file mode 100644
index 0000000000..5f4c23d1ef
--- /dev/null
+++ b/server/services/fableLoom/shotRuns.js
@@ -0,0 +1,113 @@
+/** Machine-local, durable shot-planning checkpoints. Never restart provider work at boot. */
+import { createHash, randomUUID } from 'node:crypto';
+import { readFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { PATHS, atomicWrite, ensureDir } from '../../lib/fileUtils.js';
+import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { getLoom, findEpisode } from './records.js';
+import { runEpisodeShotAutopilot } from './shots.js';
+import { fableLoomRunEvents } from './runEvents.js';
+
+const active = new Map();
+const queue = createFileWriteQueue();
+const keyFor = (loomId, episodeId) => createHash('sha256').update(JSON.stringify([loomId, episodeId])).digest('hex');
+const directory = () => join(PATHS.data, 'fableloom-shot-runs');
+const pathFor = (key) => join(directory(), `${key}.json`);
+const now = () => new Date().toISOString();
+const snapshot = (run) => {
+ if (!run) return null;
+ const { checkpoint, ...publicRun } = run;
+ return structuredClone({ ...publicRun, progress: {
+ current: checkpoint.current || null,
+ completedScenes: Object.values(checkpoint.scenes || {}).filter(scene => scene.group).length,
+ rounds: Object.entries(checkpoint.scenes || {}).map(([sceneId, scene]) => ({ sceneId, rounds: scene.rounds.length, completed: !!scene.group })),
+ } });
+};
+const publish = async (run) => {
+ run.updatedAt = now();
+ run.revision += 1;
+ await ensureDir(directory());
+ await atomicWrite(pathFor(keyFor(run.loomId, run.episodeId)), run);
+ fableLoomRunEvents.emit('shots', snapshot(run));
+ return snapshot(run);
+};
+const read = async (key) => JSON.parse(await readFile(pathFor(key), 'utf8').catch(error => {
+ if (error.code === 'ENOENT') return 'null';
+ throw error;
+}));
+const requireEpisode = async (loomId, episodeId) => {
+ const loom = await getLoom(loomId);
+ if (!loom) throw new ServerError('Story not found', { status: 404 });
+ return findEpisode(loom, episodeId);
+};
+async function load(loomId, episodeId) {
+ const key = keyFor(loomId, episodeId);
+ const run = active.get(key) || await read(key);
+ if (run && !active.has(key) && ['running', 'canceling'].includes(run.status)) {
+ run.status = 'failed';
+ run.message = 'Shot planning was interrupted by a restart. Completed steps are preserved; resume explicitly.';
+ await publish(run);
+ }
+ return run;
+}
+export async function getEpisodeShotRun(loomId, episodeId) {
+ await requireEpisode(loomId, episodeId);
+ return queue(async () => snapshot(await load(loomId, episodeId)));
+}
+async function execute(run) {
+ const key = keyFor(run.loomId, run.episodeId);
+ await runEpisodeShotAutopilot(run.loomId, run.episodeId, {
+ ...run.options,
+ checkpoint: run.checkpoint,
+ isCanceled: () => run.cancelRequested,
+ saveCheckpoint: () => queue(async () => {
+ run.message = `${run.checkpoint.current?.stage || 'Planning shots'} · round ${run.checkpoint.current?.round || 1}${run.checkpoint.current?.warning ? ` · ${run.checkpoint.current.warning}` : ''}`;
+ await publish(run);
+ }),
+ }).then(result => queue(async () => {
+ run.status = 'completed';
+ run.result = result;
+ run.message = 'Shot plan completed.';
+ await publish(run);
+ })).catch(error => queue(async () => {
+ run.status = run.cancelRequested ? 'canceled' : 'failed';
+ run.message = error.message;
+ await publish(run);
+ })).finally(() => active.delete(key));
+}
+export async function startEpisodeShotRun(loomId, episodeId, { resume = false, ...options } = {}) {
+ const episode = await requireEpisode(loomId, episodeId);
+ if (!episode.nodes.length) throw new ServerError('Write dramatic scenes before planning shots.', { status: 409 });
+ return queue(async () => {
+ const key = keyFor(loomId, episodeId);
+ if (active.has(key)) return { ...snapshot(active.get(key)), alreadyRunning: true };
+ const previous = resume ? await load(loomId, episodeId) : null;
+ if (resume && !previous) throw new ServerError('No shot run to resume.', { status: 404 });
+ if (previous?.status === 'completed') return snapshot(previous);
+ const run = previous || { id: `shots-${randomUUID()}`, loomId, episodeId, createdAt: now(), revision: 0, attempt: 0, options, checkpoint: {} };
+ // Resume retains the original provider, guidance and apply choice.
+ run.attempt += 1;
+ run.status = 'running';
+ run.cancelRequested = false;
+ run.message = resume ? 'Resuming shot planning…' : 'Starting shot planning…';
+ await publish(run);
+ active.set(key, run);
+ void execute(run).catch(error => console.error(`❌ Shot run persistence failed: ${error.message}`));
+ return snapshot(run);
+ });
+}
+export async function cancelEpisodeShotRun(loomId, episodeId) {
+ await requireEpisode(loomId, episodeId);
+ return queue(async () => {
+ const run = await load(loomId, episodeId);
+ if (!run) throw new ServerError('No shot run found.', { status: 404 });
+ if (run.status === 'running') {
+ run.cancelRequested = true;
+ run.status = 'canceling';
+ run.message = 'Stopping after the active provider call; completed steps will be preserved.';
+ await publish(run);
+ }
+ return snapshot(run);
+ });
+}
diff --git a/server/services/fableLoom/shots.js b/server/services/fableLoom/shots.js
index 0d44a28d1f..8d743e0ef4 100644
--- a/server/services/fableLoom/shots.js
+++ b/server/services/fableLoom/shots.js
@@ -7,7 +7,7 @@ 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 { runStagedLLM, resolveStageRoute } 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');
@@ -80,42 +80,129 @@ export async function applyEpisodeShots(id, episodeId, { sourceFingerprint, grou
return { loom: updated, validation };
}
-export async function runEpisodeShotAutopilot(id, episodeId, { providerId, model, effort, operationId, guidance = '', maxRounds = 3, apply = false } = {}) {
+/** Checkpoints are supplied only by the local run service, never by HTTP callers. */
+export async function runEpisodeShotAutopilot(id, episodeId, {
+ providerId, model, effort, operationId, guidance = '', maxRounds = 3, apply = false,
+ checkpoint = {}, saveCheckpoint = async () => {}, isCanceled = () => false,
+} = {}) {
const { loom, episode } = await requireSource(id, episodeId);
const sourceFingerprint = fingerprint(loom, episode);
+ if (checkpoint.sourceFingerprint && checkpoint.sourceFingerprint !== sourceFingerprint) {
+ throw new ServerError('The episode changed. Start a fresh shot plan.', { status: 409, code: 'SHOT_PLAN_STALE' });
+ }
+ checkpoint.sourceFingerprint = sourceFingerprint;
+ checkpoint.scenes ||= {};
+ checkpoint.consistency ||= [];
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 })),
- })) });
+ // The rest of the episode supplies graph context, never another scene's teleplay.
+ const context = { cast, synopsis: episode.synopsis, startNodeId: episode.startNodeId,
+ sceneDigest: episode.nodes.map(({ id, title, playbackMode, transitions }) => ({ id, title, playbackMode, transitions: 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;
+ const checkCanceled = () => {
+ if (isCanceled()) throw new ServerError('Shot planning canceled; completed steps preserved.', { status: 409, code: 'SHOT_PLAN_CANCELED' });
+ };
+ const persist = async () => { await saveCheckpoint(checkpoint); checkCanceled(); };
+ const execute = async (stage, variables, round, sceneId) => {
+ checkCanceled();
+ const resolved = await resolveStageRoute(stage, route);
+ const selectedProvider = resolved.provider;
+ const inputCharacters = Object.values(variables).reduce((total, value) => total + String(value).length, 0);
+ checkpoint.current = { stage, round, sceneId, providerId: selectedProvider.id,
+ inputCharacters, timeoutMs: selectedProvider.timeout,
+ warning: inputCharacters > 12000 && (selectedProvider.timeout || 300000) <= 300000
+ ? 'Large shot-planning input; this provider timeout may be too short. Completed steps will be preserved on failure.' : null };
+
+ await persist();
+ return 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) => {
+ const message = `${stage} round ${round}${sceneId ? ` scene ${sceneId}` : ''} on provider ${selectedProvider.id}: ${error.message}`;
+ status?.error(message);
+ throw new ServerError(message, { status: error.status || 502, code: error.code || 'SHOT_STAGE_FAILED' });
+ });
+ };
+ const validReview = (review) => Array.isArray(review?.risks) && review.risks.every((risk) => typeof risk === 'string') && typeof review?.summary === 'string' && review.summary.trim();
+ const groups = [];
+ for (const node of episode.nodes) {
+ const state = checkpoint.scenes[node.id] ||= { rounds: [] };
+ const { id: sceneId, title, prose, playbackMode, shot, imagePrompt, videoPrompt,
+ cameraMovement, image: referenceImage, visualCanon, protagonistPresence, challengePhase } = node;
+ const source = JSON.stringify({ ...context, scenes: [{ id: sceneId, title, prose, playbackMode, shot, imagePrompt, videoPrompt,
+ cameraMovement, referenceImage, visualCanon, protagonistPresence, challengePhase,
+ visibleCharacterIds: (visualCanon?.characterAppearances || []).map((appearance) => appearance.characterId),
+ transitions: context.sceneDigest.find((scene) => scene.id === node.id).transitions }] });
+ for (let round = Math.max(1, state.rounds.length + (state.rounds.at(-1)?.feedback ? 1 : 0)); !state.group && round <= maxRounds; round += 1) {
+ checkCanceled();
+ const entry = state.rounds[round - 1] ||= {};
+ const feedback = state.rounds[round - 2]?.feedback || '';
+ if (!entry.draft) {
+ const draft = await execute('fableloom-plan-shots', { source, guidance, feedback }, round, node.id);
+ entry.draft = draft.content;
+ await persist();
+ }
+ const parsed = shotGroupsSchema.safeParse(entry.draft?.groups);
+ if (!parsed.success || parsed.data.length !== 1 || parsed.data[0].sceneId !== node.id) {
+ entry.feedback = 'Return exactly one valid group for the supplied scene id.';
+ await persist();
+ continue;
+ }
+ // Timing can be checked locally; full graph/outline validation runs on the assembled plan.
+ const group = parsed.data[0];
+ const timing = analyzeEpisodeShots({ nodes: group.shots.map((shot, index) => ({ id: String(index), title: shot.title, playbackMode: index === group.shots.length - 1 ? node.playbackMode : 'cut', prose: script(shot), shot: { ...shot, durationSeconds: Math.max(shot.durationSeconds, Math.min(10, Math.ceil(estimatedShotSeconds(script(shot))))) } })) });
+ const sceneCast = (node.visualCanon?.characterAppearances || []).map((appearance) => appearance.characterId);
+ const invalidCast = group.shots.some((shot) => shot.visibleCharacterIds?.some((id) => !sceneCast.includes(id)));
+ if (timing.issues.length || invalidCast) {
+ entry.feedback = [...timing.issues.map((issue) => issue.message), ...(invalidCast ? ['A shot names a character outside its source scene cast.'] : [])].join('\n');
+ await persist();
+ continue;
+ }
+ if (!entry.review) {
+ const review = await execute('fableloom-review-shots', { source, shots: JSON.stringify([group]) }, round, node.id);
+ entry.review = review.content;
+ await persist();
+ }
+ if (!validReview(entry.review) || entry.review.risks.length) {
+ entry.feedback = validReview(entry.review) ? entry.review.risks.join('\n') : 'The reviewer returned no explicit verdict.';
+ } else {
+ state.group = group;
+ }
+ await persist();
+ }
+ if (!state.group) throw new ServerError(`Shot planning exhausted ${maxRounds} rounds for scene ${node.id}. Completed steps preserved.\n${state.rounds.at(-1)?.feedback || ''}`, { status: 422, code: 'SHOT_PLAN_INVALID' });
+ groups.push(state.group);
+ }
+ const compiled = compile(loom, episode, groups);
+ if (compiled.validation.issues.length) throw new ServerError(compiled.validation.issues.map((i) => i.message).join('\n'), { status: 422, code: 'SHOT_PLAN_INVALID' });
+ // One whole-plan review, without the episode teleplay. It checks connections
+ // between the scene plans already reviewed against their full dramatic source.
+ const planHash = createHash('sha256').update(JSON.stringify(compiled.groups)).digest('hex');
+ let review = checkpoint.consistency.findLast((entry) => entry.planHash === planHash)?.review;
+ if (!review) {
+ const result = await execute('fableloom-review-shots', { source: JSON.stringify({ ...context, scenes: context.sceneDigest }), shots: JSON.stringify(compiled.groups) }, checkpoint.consistency.length + 1, null);
+ review = result.content;
+ checkpoint.consistency.push({ planHash, review });
+ await persist();
+ }
+ if (!validReview(review) || review.risks.length) {
+ const feedback = validReview(review) ? review.risks.join('\n') : 'The consistency reviewer returned no explicit verdict.';
+ if (checkpoint.consistency.length < maxRounds && Object.values(checkpoint.scenes).every((scene) => scene.rounds.length < maxRounds)) {
+ // Cross-scene findings need a coordinated repair, using each scene's
+ // full source again while preserving the rejected drafts and verdict.
+ for (const scene of Object.values(checkpoint.scenes)) {
+ scene.rounds.at(-1).feedback = feedback;
+ delete scene.group;
+ }
+ await persist();
+ return runEpisodeShotAutopilot(id, episodeId, { providerId, model, effort, operationId, guidance, maxRounds, apply, checkpoint, saveCheckpoint, isCanceled });
}
- 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 };
+ throw new ServerError(`Shot consistency review needs revision. Completed steps preserved.\n${feedback}`, { status: 422, code: 'SHOT_PLAN_INVALID' });
}
- 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' });
+ const result = { sourceFingerprint, groups: compiled.groups, validation: compiled.validation, review, attempt: Math.max(...Object.values(checkpoint.scenes).map((scene) => scene.rounds.length)) };
+ checkCanceled();
+ const applied = apply ? await applyEpisodeShots(id, episodeId, result) : {};
+ status?.complete(apply ? 'Timed shots applied' : 'Shot plan ready to preview', { shellReady: false });
+ return { ...result, ...applied };
}
diff --git a/server/services/fableLoom/shots.test.js b/server/services/fableLoom/shots.test.js
index d0fd120b28..1323a6797d 100644
--- a/server/services/fableLoom/shots.test.js
+++ b/server/services/fableLoom/shots.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
-import { mkdtempSync, rmSync } from 'node:fs';
+import { mkdtempSync, rmSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'loom-shots-'));
@@ -8,7 +8,7 @@ vi.mock('../../lib/fileUtils.js', async (original) => {
return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };
});
const runStagedLLM = vi.hoisted(() => vi.fn());
-vi.mock('../stageRunner.js', () => ({ runStagedLLM }));
+vi.mock('../stageRunner.js', () => ({ runStagedLLM, resolveStageRoute: async () => ({ provider: { id: 'test-provider', timeout: 300000 } }) }));
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');
@@ -30,6 +30,11 @@ async function setup() {
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 };
}
+function mockPlan(groups) {
+ runStagedLLM.mockImplementation(async (stage, variables) => stage === 'fableloom-plan-shots'
+ ? { content: { groups: groups.filter(group => group.sceneId === JSON.parse(variables.source).scenes[0].id) } }
+ : { content: { summary: 'Clear and filmable.', risks: [] } });
+}
describe('timed shot autopilot', () => {
it('grounds both planning and review in existing shot geography and camera context', async () => {
const { loom, ep, groups } = await setup();
@@ -40,13 +45,13 @@ describe('timed shot autopilot', () => {
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: [] } });
+ mockPlan(groups);
await runEpisodeShotAutopilot(loom.id, ep);
- for (const [, variables] of runStagedLLM.mock.calls) {
+ for (const [, variables] of runStagedLLM.mock.calls.filter(([, variables]) => JSON.parse(variables.source).scenes[0]?.shot)) {
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));
+ if (source.scenes[0].id === groups[0].sceneId) expect(source.scenes[0]).toMatchObject(visual);
+ if (source.scenes[0].id === groups[0].sceneId) 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);
});
@@ -54,7 +59,7 @@ describe('timed shot autopilot', () => {
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: [] } });
+ mockPlan(groups);
const result = await runEpisodeShotAutopilot(loom.id, ep, { apply: true });
const saved = await getLoom(loom.id);
expect(saved.episodes[1]).toEqual(loom.episodes[1]);
@@ -71,7 +76,7 @@ describe('timed shot autopilot', () => {
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 } });
+ mockPlan(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);
@@ -81,14 +86,119 @@ describe('timed shot autopilot', () => {
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 } });
+ mockPlan(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: [] } });
+ mockPlan(groups);
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);
});
});
+
+
+describe('shot checkpoints and bounded inputs', () => {
+ it('preserves a draft across a review timeout and resumes without redrafting', async () => {
+ const { loom, ep, groups } = await setup();
+ const checkpoint = {};
+ let durable;
+ mockPlan(groups);
+ const implementation = runStagedLLM.getMockImplementation();
+ runStagedLLM.mockImplementation(async (stage, variables) => {
+ if (stage === 'fableloom-review-shots') throw new Error('CLI run timed out after 300000ms');
+ return implementation(stage, variables);
+ });
+ await expect(runEpisodeShotAutopilot(loom.id, ep, { checkpoint, saveCheckpoint: async value => { durable = structuredClone(value); } }))
+ .rejects.toThrow('fableloom-review-shots round 1 scene');
+ expect(durable.current.providerId).toBe('test-provider');
+ expect(durable.scenes[groups[0].sceneId].rounds[0].draft.groups).toEqual([groups[0]]);
+ runStagedLLM.mockClear();
+ mockPlan(groups);
+ const result = await runEpisodeShotAutopilot(loom.id, ep, { checkpoint: durable });
+ expect(result.validation.stats.ready).toBe(true);
+ expect(runStagedLLM.mock.calls[0][0]).toBe('fableloom-review-shots');
+ expect(runStagedLLM.mock.calls.filter(([stage]) => stage === 'fableloom-plan-shots')).toHaveLength(2);
+ });
+ it('keeps 20 normal-size scene teleplays out of other scene calls and the consistency pass', async () => {
+ let loom = await createLoom({ name: 'Example Long Story', universeId: 'example-universe' });
+ loom = await addEpisode(loom.id, { title: 'Twenty scenes' });
+ const ep = loom.episodes[0].id;
+ for (let i = 0; i < 20; i += 1) loom = await addNode(loom.id, ep, { title: `Scene ${i}`, playbackMode: 'cut', prose: `UNIQUE_${i}_` + 'A courier waits. '.repeat(65), isEnding: i === 19 });
+ const nodes = loom.episodes[0].nodes;
+ for (let i = 0; i < 19; i += 1) loom = await updateNode(loom.id, ep, nodes[i].id, { transitions: [{ targetNodeId: nodes[i + 1].id, intent: 'continue' }] });
+ const groups = nodes.map(node => ({ sceneId: node.id, shots: [shot(node.title)] }));
+ mockPlan(groups);
+ await expect(runEpisodeShotAutopilot(loom.id, ep)).resolves.toMatchObject({ validation: { stats: { ready: true } } });
+ expect(runStagedLLM).toHaveBeenCalledTimes(41);
+ const calls = runStagedLLM.mock.calls;
+ for (const [, variables] of calls.slice(0, -1)) {
+ const source = JSON.parse(variables.source);
+ expect(source.scenes).toHaveLength(1);
+ expect(variables.source.match(/UNIQUE_\d+_/g)).toHaveLength(1);
+ expect(variables.source.length).toBeLessThan(9000);
+ }
+ expect(calls.at(-1)[1].source).not.toContain('UNIQUE_');
+ });
+ it('reports a durable interrupted run without calling a provider, then resumes explicitly', async () => {
+ const { startEpisodeShotRun, getEpisodeShotRun } = await import('./shotRuns.js');
+ const { fableLoomRunEvents } = await import('./runEvents.js');
+ const { loom, ep, groups } = await setup();
+ let rejectCall;
+ let callStarted;
+ const startedCall = new Promise(resolve => { callStarted = resolve; });
+ runStagedLLM.mockImplementation(() => new Promise((resolve, reject) => { rejectCall = reject; callStarted(); }));
+ const started = await startEpisodeShotRun(loom.id, ep);
+ expect(started.status).toBe('running');
+ const terminal = new Promise(resolve => {
+ const handler = run => { if (run.id === started.id && run.status === 'failed') { fableLoomRunEvents.off('shots', handler); resolve(run); } };
+ fableLoomRunEvents.on('shots', handler);
+ });
+ await startedCall;
+ rejectCall(new Error('CLI run timed out after 300000ms'));
+ const failed = await terminal;
+ expect(failed.message).toContain('provider test-provider');
+ const { createHash } = await import('node:crypto');
+ const path = join(TEST_DATA_ROOT, 'fableloom-shot-runs', createHash('sha256').update(JSON.stringify([loom.id, ep])).digest('hex') + '.json');
+ const saved = JSON.parse(readFileSync(path, 'utf8'));
+ // Reproduce the bytes a process death leaves, without starting work at boot.
+ saved.status = 'running';
+ writeFileSync(path, JSON.stringify(saved));
+ const count = runStagedLLM.mock.calls.length;
+ const interrupted = await getEpisodeShotRun(loom.id, ep);
+ expect(interrupted.status).toBe('failed');
+ expect(interrupted.message).toContain('restart');
+ expect(runStagedLLM).toHaveBeenCalledTimes(count);
+ mockPlan(groups);
+ const completed = new Promise(resolve => {
+ const handler = run => { if (run.id === started.id && run.status === 'completed') { fableLoomRunEvents.off('shots', handler); resolve(run); } };
+ fableLoomRunEvents.on('shots', handler);
+ });
+ const resumed = await startEpisodeShotRun(loom.id, ep, { resume: true });
+ expect(resumed.id).toBe(started.id);
+ expect((await completed).result.validation.stats.ready).toBe(true);
+ });
+});
+
+it('deduplicates starts and preserves the last draft when canceled during a provider call', async () => {
+ const { startEpisodeShotRun, cancelEpisodeShotRun, getEpisodeShotRun } = await import('./shotRuns.js');
+ const { fableLoomRunEvents } = await import('./runEvents.js');
+ const { loom, ep, groups } = await setup();
+ let finishCall, callStarted;
+ const ready = new Promise(resolve => { callStarted = resolve; });
+ runStagedLLM.mockImplementation(() => new Promise(resolve => { finishCall = resolve; callStarted(); }));
+ const started = await startEpisodeShotRun(loom.id, ep, { apply: true });
+ await ready;
+ expect(await startEpisodeShotRun(loom.id, ep)).toMatchObject({ id: started.id, alreadyRunning: true });
+ const terminal = new Promise(resolve => {
+ const handler = run => { if (run.id === started.id && run.status === 'canceled') { fableLoomRunEvents.off('shots', handler); resolve(run); } };
+ fableLoomRunEvents.on('shots', handler);
+ });
+ expect((await cancelEpisodeShotRun(loom.id, ep)).status).toBe('canceling');
+ finishCall({ content: { groups: [groups[0]] } });
+ await terminal;
+ expect(runStagedLLM).toHaveBeenCalledTimes(1);
+ expect((await getLoom(loom.id)).episodes).toEqual(loom.episodes);
+ expect((await getEpisodeShotRun(loom.id, ep)).progress.rounds).toEqual([{ sceneId: groups[0].sceneId, rounds: 1, completed: false }]);
+});
diff --git a/server/services/socket.js b/server/services/socket.js
index a7fe7ed751..9242ba4c22 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -930,6 +930,9 @@ function setupFableLoomRunForwarding() {
fableLoomRunEvents.on('editorial', run => {
broadcastToSet(fableLoomSubscribers, 'fableloom:editorial:run', run);
});
+ fableLoomRunEvents.on('shots', run => {
+ broadcastToSet(fableLoomSubscribers, 'fableloom:shots:run', run);
+ });
fableLoomRunEvents.on('production', run => {
broadcastToSet(fableLoomSubscribers, 'fableloom:production:run', run);
});
diff --git a/server/services/socket.test.js b/server/services/socket.test.js
index f9981a9ee9..abc41eacef 100644
--- a/server/services/socket.test.js
+++ b/server/services/socket.test.js
@@ -438,8 +438,10 @@ describe('socket.js — initSocket', () => {
const run = { id: 'run-example', loomId: 'loom-example', revision: 1 };
fableLoomRunEvents.emit('editorial', run);
fableLoomRunEvents.emit('production', run);
+ fableLoomRunEvents.emit('shots', run);
expect(viewer.emitted).toContainEqual(['fableloom:editorial:run', run]);
expect(viewer.emitted).toContainEqual(['fableloom:production:run', run]);
+ expect(viewer.emitted).toContainEqual(['fableloom:shots:run', run]);
expect(peer.emitted.some(([name]) => name.startsWith('fableloom:'))).toBe(false);
expect(io.emitted.some(([name]) => name.startsWith('fableloom:'))).toBe(false);
viewer.handlers['fableloom:unsubscribe']();