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: add Episode Composer UI for continuous multi-scene video (#6228)

[._.]/ Adam Eivycfcaa8129706
diff --git a/client/src/components/fableloom/LoomSettingsDrawer.jsx b/client/src/components/fableloom/LoomSettingsDrawer.jsx
index 196b951a2f..261b8a5359 100644
--- a/client/src/components/fableloom/LoomSettingsDrawer.jsx
+++ b/client/src/components/fableloom/LoomSettingsDrawer.jsx
@@ -19,7 +19,7 @@
*/
import { useEffect, useRef, useState } from 'react';
-import { CheckCircle2, Cloud, Cpu, Layers, Loader2, Sparkles } from 'lucide-react';
+import { CheckCircle2, Cloud, Cpu, Film, Layers, Loader2, Sparkles } from 'lucide-react';
import { Link } from 'react-router';
import Drawer from '../Drawer';
import BackendChipStrip from '../media/BackendChipStrip';
@@ -85,7 +85,7 @@ const rewriteProgressLabel = ({ index, total, title, scenesLeft }) => [
scenesLeft ? ` ${scenesLeft} scene${scenesLeft === 1 ? '' : 's'} left in it.` : '',
].join('');
-export default function LoomSettingsDrawer({ open, onClose, loom, universe, onLoomUpdate, onRewritten }) {
+export default function LoomSettingsDrawer({ open, onClose, loom, universe, onLoomUpdate, onRewritten, episodeId }) {
const { providers } = useProviderModels({ allowDefault: true, silent: true, withEffort: true });
// Which episode the rewrite is on. The walk is one request per episode, so
@@ -621,6 +621,20 @@ export default function LoomSettingsDrawer({ open, onClose, loom, universe, onLo
)}
</div>
+ {episodeId && (
+ <div className="rounded border border-port-border p-2.5">
+ <Link
+ to={`/media/video?episode=1&loomId=${encodeURIComponent(loom.id)}&episodeId=${encodeURIComponent(episodeId)}`}
+ className="flex items-center gap-1.5 text-xs text-port-accent hover:underline"
+ >
+ <Film className="w-3.5 h-3.5" /> Open Episode Composer for this episode
+ </Link>
+ <p className="text-[11px] text-port-text-muted mt-1">
+ Draft a chained multi-scene continuous-video render in MediaGen, importing this episode's scenes as a starting point.
+ </p>
+ </div>
+ )}
+
<FormField
label="Codex image effort"
labelClassName={labelClass}
diff --git a/client/src/components/videoGen/EpisodeComposer.jsx b/client/src/components/videoGen/EpisodeComposer.jsx
new file mode 100644
index 0000000000..9803dbfb98
--- /dev/null
+++ b/client/src/components/videoGen/EpisodeComposer.jsx
@@ -0,0 +1,354 @@
+/**
+ * Episode Composer (#6228) — write or import a rough multi-scene episode
+ * script, preview it as chained continuous-video clips with live lint status
+ * (#6226's hard-cut/slot-lock rules), then queue it for generation over the
+ * continuous-video orchestrator (#6227).
+ *
+ * The live preview is a debounced POST to `/api/continuous-video/lint` —
+ * compose+lint without submitting — rather than a client-side port of the
+ * compiler/linter, since `composeEpisodeClips` pulls in server-only imports
+ * (fs paths, SSE registry) that can't ship to the browser.
+ */
+import { useEffect, useMemo, useRef, useState } from 'react';
+import {
+ CheckCircle2, XCircle, Loader2, Plus, Trash2, Sparkles, Film,
+} from 'lucide-react';
+import {
+ lintContinuousVideoEpisode, generateContinuousVideoEpisode, continuousVideoEpisodeEventsUrl,
+} from '../../services/api';
+import { useSseProgress } from '../../hooks/useSseProgress';
+import { useAsyncAction } from '../../hooks/useAsyncAction';
+import toast from '../ui/Toast';
+import { uuidv4 } from '../../lib/uuid.js';
+
+const CONTINUOUS_VIDEO_BACKENDS = ['local', 'reactor', 'fal'];
+const PREVIEW_DEBOUNCE_MS = 500;
+
+// `sceneIndex:beatIndex` is a stable clip identity across recompiles — the
+// raw array index is not: editing an earlier scene's beat count reflows
+// every downstream clip's position, which would silently reattach an
+// already-entered camera framing to the wrong beat.
+const clipFramingKey = (clip) => `${clip.sceneIndex}:${clip.beatIndex}`;
+const framingsArrayFor = (clips, framings) => (clips || []).map((clip) => framings[clipFramingKey(clip)] || null);
+
+const emptyLine = () => ({ key: uuidv4(), type: 'action', speaker: '', voice: '', text: '' });
+const emptyScene = () => ({ key: uuidv4(), sceneId: uuidv4(), location: '', lines: [emptyLine()] });
+
+/** Strip UI-only keys and empty lines/scenes before this goes over the wire. */
+function sanitizeScenesForRequest(scenes) {
+ return scenes
+ .map((scene) => ({
+ sceneId: scene.sceneId || undefined,
+ location: scene.location.trim() || undefined,
+ lines: scene.lines
+ .filter((l) => l.text.trim())
+ .map((l) => ({
+ type: l.type,
+ ...(l.type === 'dialogue' && l.speaker.trim() ? { speaker: l.speaker.trim() } : {}),
+ ...(l.type === 'dialogue' && l.voice.trim() ? { voice: l.voice.trim() } : {}),
+ text: l.text.trim(),
+ })),
+ }))
+ .filter((scene) => scene.lines.length > 0);
+}
+
+function buildBible(styleDescriptor, castEntries, locationEntries) {
+ const bible = {};
+ if (styleDescriptor.trim()) bible.styleDescriptor = styleDescriptor.trim();
+ const cast = {};
+ castEntries.forEach((e) => { if (e.id.trim() && e.descriptor.trim()) cast[e.id.trim()] = { descriptor: e.descriptor.trim() }; });
+ if (Object.keys(cast).length) bible.cast = cast;
+ const locations = {};
+ locationEntries.forEach((e) => { if (e.id.trim() && e.descriptor.trim()) locations[e.id.trim()] = { descriptor: e.descriptor.trim() }; });
+ if (Object.keys(locations).length) bible.locations = locations;
+ return bible;
+}
+
+function BibleEntryEditor({ label, entries, onChange, idPlaceholder }) {
+ const update = (i, patch) => onChange(entries.map((e, idx) => (idx === i ? { ...e, ...patch } : e)));
+ const remove = (i) => onChange(entries.filter((_, idx) => idx !== i));
+ return (
+ <div className="space-y-1.5">
+ <div className="flex items-center justify-between">
+ <span className="text-[11px] font-medium text-gray-400">{label}</span>
+ <button type="button" onClick={() => onChange([...entries, { id: uuidv4(), descriptor: '' }])} className="inline-flex items-center gap-1 text-[11px] text-port-accent hover:underline">
+ <Plus className="w-3 h-3" /> Add
+ </button>
+ </div>
+ {entries.map((entry, i) => (
+ <div key={entry.id} className="flex gap-1.5 items-start">
+ <input
+ type="text" value={entry.id} onChange={(e) => update(i, { id: e.target.value })}
+ placeholder={idPlaceholder} aria-label={`${label} id`}
+ className="w-28 shrink-0 bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white focus:outline-none focus:border-port-accent"
+ />
+ <input
+ type="text" value={entry.descriptor} onChange={(e) => update(i, { descriptor: e.target.value })}
+ placeholder="byte-stable visual descriptor" aria-label={`${label} descriptor`}
+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white focus:outline-none focus:border-port-accent"
+ />
+ <button type="button" onClick={() => remove(i)} aria-label={`Remove ${label} entry`} className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-gray-500 hover:text-port-error">
+ <Trash2 className="w-3.5 h-3.5" />
+ </button>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+function SceneEditor({ scene, onChange, onRemove, busy }) {
+ const updateLine = (i, patch) => onChange({ ...scene, lines: scene.lines.map((l, idx) => (idx === i ? { ...l, ...patch } : l)) });
+ const addLine = () => onChange({ ...scene, lines: [...scene.lines, emptyLine()] });
+ const removeLine = (i) => onChange({ ...scene, lines: scene.lines.filter((_, idx) => idx !== i) });
+ return (
+ <div className="border border-port-border/50 rounded-lg p-2.5 space-y-2">
+ <div className="flex items-center gap-1.5">
+ <label htmlFor={`scene-location-${scene.key}`} className="sr-only">Scene location id</label>
+ <input
+ id={`scene-location-${scene.key}`} type="text" value={scene.location}
+ onChange={(e) => onChange({ ...scene, location: e.target.value })}
+ disabled={busy} placeholder="location id (matches a Locations bible entry)"
+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
+ />
+ <button type="button" onClick={onRemove} disabled={busy} aria-label="Remove scene" className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-gray-500 hover:text-port-error disabled:opacity-50">
+ <Trash2 className="w-3.5 h-3.5" />
+ </button>
+ </div>
+ <div className="space-y-1.5">
+ {scene.lines.map((line, i) => (
+ <div key={line.key} className="flex gap-1.5 items-start">
+ <select
+ value={line.type} onChange={(e) => updateLine(i, { type: e.target.value })} disabled={busy}
+ aria-label="Line type"
+ className="w-20 shrink-0 bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
+ >
+ <option value="action">Action</option>
+ <option value="dialogue">Dialogue</option>
+ </select>
+ {line.type === 'dialogue' && (
+ <input
+ type="text" value={line.speaker} onChange={(e) => updateLine(i, { speaker: e.target.value })}
+ disabled={busy} placeholder="speaker id" aria-label="Speaker id"
+ className="w-24 shrink-0 bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
+ />
+ )}
+ <input
+ type="text" value={line.text} onChange={(e) => updateLine(i, { text: e.target.value })}
+ disabled={busy} placeholder={line.type === 'dialogue' ? 'what they say' : 'what happens'} aria-label="Line text"
+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
+ />
+ <button type="button" onClick={() => removeLine(i)} disabled={busy} aria-label="Remove line" className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-gray-500 hover:text-port-error disabled:opacity-50">
+ <Trash2 className="w-3.5 h-3.5" />
+ </button>
+ </div>
+ ))}
+ </div>
+ <button type="button" onClick={addLine} disabled={busy} className="inline-flex items-center gap-1 text-[11px] text-port-accent hover:underline disabled:opacity-50">
+ <Plus className="w-3 h-3" /> Add line
+ </button>
+ </div>
+ );
+}
+
+function ClipPreviewCard({ clip, result, framing, onFramingChange, busy }) {
+ const pass = result?.pass !== false;
+ return (
+ <div className={`border rounded-lg p-2.5 space-y-1.5 ${pass ? 'border-port-border/50' : 'border-port-error/60'}`}>
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex items-center gap-1.5 flex-wrap">
+ <span className="text-[10px] font-mono text-gray-500">#{result?.index ?? 0}</span>
+ <span className={`text-[10px] px-1.5 py-0.5 rounded ${clip.cutType === 'continue' ? 'bg-purple-500/20 text-purple-300' : 'bg-blue-500/20 text-blue-300'}`}>
+ {clip.cutType === 'continue' ? 'continue' : 'fresh cut'}
+ </span>
+ {clip.speakers?.map((s) => (
+ <span key={s} className="text-[10px] px-1.5 py-0.5 rounded bg-port-border/50 text-gray-300">{s}</span>
+ ))}
+ </div>
+ {pass ? (
+ <CheckCircle2 className="w-4 h-4 text-port-success shrink-0" aria-label="Lint passed" />
+ ) : (
+ <XCircle className="w-4 h-4 text-port-error shrink-0" aria-label="Lint failed" />
+ )}
+ </div>
+ <p className="text-[11px] text-gray-400 line-clamp-3">{clip.prompt}</p>
+ {clip.references?.length > 0 && (
+ <div className="flex items-center gap-1 flex-wrap text-[10px] text-gray-500">
+ <span>slot locks:</span>
+ {clip.references.map((r) => <span key={`${r.kind}/${r.id}`} className="font-mono">{r.kind}/{r.id}</span>)}
+ </div>
+ )}
+ {clip.cutType === 'continue' && (
+ <div className="flex items-center gap-1.5">
+ <label htmlFor={`framing-${clipFramingKey(clip)}`} className="text-[11px] text-gray-400 shrink-0">Camera framing</label>
+ <input
+ id={`framing-${clipFramingKey(clip)}`} type="text" value={framing} disabled={busy}
+ onChange={(e) => onFramingChange(e.target.value)}
+ placeholder="e.g. close-up on Mara's face"
+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
+ />
+ </div>
+ )}
+ {!pass && (
+ <ul className="text-[10px] text-port-error space-y-0.5 list-disc list-inside">
+ {result.reasons.map((r) => <li key={r}>{r}</li>)}
+ </ul>
+ )}
+ </div>
+ );
+}
+
+export default function EpisodeComposer({ initialScenes, onQueued }) {
+ const [scenes, setScenes] = useState(() => (initialScenes?.length ? initialScenes.map((s) => ({
+ key: uuidv4(), sceneId: s.sceneId || uuidv4(), location: s.location || '',
+ lines: s.lines.map((l) => ({ key: uuidv4(), type: l.type, speaker: l.speaker || '', voice: l.voice || '', text: l.text || '' })),
+ })) : [emptyScene()]));
+ const [styleDescriptor, setStyleDescriptor] = useState('');
+ const [castEntries, setCastEntries] = useState([]);
+ const [locationEntries, setLocationEntries] = useState([]);
+ const [backend, setBackend] = useState('local');
+ const [framings, setFramings] = useState({}); // { [`${sceneIndex}:${beatIndex}`]: string }
+ const [preview, setPreview] = useState(null); // { clips, lint }
+ const [previewLoading, setPreviewLoading] = useState(false);
+ const [queuedJobId, setQueuedJobId] = useState(null);
+ const debounceRef = useRef(null);
+
+ const bible = useMemo(() => buildBible(styleDescriptor, castEntries, locationEntries), [styleDescriptor, castEntries, locationEntries]);
+ const sanitizedScenes = useMemo(() => sanitizeScenesForRequest(scenes), [scenes]);
+ const hasContent = sanitizedScenes.length > 0;
+
+ const sse = useSseProgress(queuedJobId ? continuousVideoEpisodeEventsUrl(queuedJobId) : null);
+
+ // Debounced live preview — recompiles + relints on every scene/bible/framing
+ // edit. Skipped once queued: the composer is read-only during generation.
+ // `sanitizedScenes`/`bible` are already fresh-only-on-change via useMemo, so
+ // depending on them directly (no JSON.stringify) is both cheaper and correct.
+ useEffect(() => {
+ if (queuedJobId) return undefined;
+ if (!hasContent) { setPreview(null); setPreviewLoading(false); return undefined; }
+ setPreviewLoading(true);
+ debounceRef.current = setTimeout(async () => {
+ const result = await lintContinuousVideoEpisode({
+ scenes: sanitizedScenes, bible, framings: framingsArrayFor(preview?.clips, framings),
+ }).catch(() => null);
+ setPreview(result);
+ setPreviewLoading(false);
+ }, PREVIEW_DEBOUNCE_MS);
+ return () => clearTimeout(debounceRef.current);
+ // Re-runs on any scene/bible/framing edit; `preview` itself is excluded to
+ // avoid retriggering off its own write.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [sanitizedScenes, bible, framings, queuedJobId]);
+
+ useEffect(() => {
+ if (sse.latest?.type === 'complete') {
+ toast.success('Episode generated');
+ onQueued?.(sse.latest.result);
+ } else if (sse.latest?.type === 'error') {
+ toast.error(sse.latest.error?.message || sse.latest.error || 'Episode generation failed');
+ }
+ }, [sse.latest, onQueued]);
+
+ const [handleQueue, queuing] = useAsyncAction(async () => {
+ const result = await generateContinuousVideoEpisode({
+ scenes: sanitizedScenes, bible, framings: framingsArrayFor(preview.clips, framings), backend,
+ }, { silent: true }); // useAsyncAction owns the error toast
+ setQueuedJobId(result.jobId);
+ }, { errorMessage: 'Failed to queue episode' });
+
+ const canQueue = hasContent && preview?.lint?.pass === true && !queuing && !queuedJobId;
+
+ const resetForNewEpisode = () => {
+ setQueuedJobId(null);
+ setScenes([emptyScene()]);
+ setFramings({});
+ setPreview(null);
+ };
+
+ const streaming = !!queuedJobId && !sse.closed;
+ const busy = queuing || streaming;
+
+ return (
+ <div className="space-y-4">
+ <div className="space-y-2">
+ <label htmlFor="episode-style-descriptor" className="text-[11px] font-medium text-gray-400 block">Style descriptor</label>
+ <input
+ id="episode-style-descriptor" type="text" value={styleDescriptor} disabled={busy}
+ onChange={(e) => setStyleDescriptor(e.target.value)}
+ placeholder="e.g. gritty 35mm noir, high contrast"
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-xs text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
+ />
+ </div>
+
+ <BibleEntryEditor label="Cast" entries={castEntries} onChange={setCastEntries} idPlaceholder="mara" />
+ <BibleEntryEditor label="Locations" entries={locationEntries} onChange={setLocationEntries} idPlaceholder="cell-block" />
+
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <span className="text-[11px] font-medium text-gray-400">Scenes</span>
+ <button type="button" disabled={busy} onClick={() => setScenes((prev) => [...prev, emptyScene()])} className="inline-flex items-center gap-1 text-[11px] text-port-accent hover:underline disabled:opacity-50">
+ <Plus className="w-3 h-3" /> Add scene
+ </button>
+ </div>
+ {scenes.map((scene, i) => (
+ <SceneEditor
+ key={scene.key} scene={scene} busy={busy}
+ onChange={(next) => setScenes((prev) => prev.map((s, idx) => (idx === i ? next : s)))}
+ onRemove={() => setScenes((prev) => prev.filter((_, idx) => idx !== i))}
+ />
+ ))}
+ </div>
+
+ <div className="flex items-center gap-2">
+ <label htmlFor="episode-backend" className="text-[11px] font-medium text-gray-400 shrink-0">Backend</label>
+ <select
+ id="episode-backend" value={backend} disabled={busy} onChange={(e) => setBackend(e.target.value)}
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
+ >
+ {CONTINUOUS_VIDEO_BACKENDS.map((b) => <option key={b} value={b}>{b}</option>)}
+ </select>
+ </div>
+
+ <div className="space-y-2">
+ <div className="flex items-center gap-1.5 text-[11px] font-medium text-gray-400">
+ <Sparkles className="w-3.5 h-3.5" /> Beat preview
+ {previewLoading && <Loader2 className="w-3 h-3 animate-spin" />}
+ </div>
+ {!hasContent && <p className="text-[11px] text-gray-500">Write at least one scene to see a beat preview.</p>}
+ {preview?.clips?.map((clip, i) => (
+ <ClipPreviewCard
+ key={clipFramingKey(clip)} clip={clip} result={preview.lint?.results?.[i]} busy={busy}
+ framing={framings[clipFramingKey(clip)] || ''}
+ onFramingChange={(v) => setFramings((prev) => ({ ...prev, [clipFramingKey(clip)]: v }))}
+ />
+ ))}
+ </div>
+
+ {queuedJobId ? (
+ <div className="border border-port-border/50 rounded-lg p-2.5 space-y-1.5">
+ <div className="flex items-center gap-1.5 text-xs text-gray-300">
+ <Film className="w-3.5 h-3.5" />
+ {streaming ? (sse.latest?.message || 'Generating…') : 'Episode generation finished'}
+ </div>
+ {typeof sse.latest?.progress === 'number' && (
+ <div className="w-full h-1.5 bg-port-border rounded overflow-hidden">
+ <div className="h-full bg-port-accent" style={{ width: `${Math.round(sse.latest.progress * 100)}%` }} />
+ </div>
+ )}
+ {!streaming && (
+ <button type="button" onClick={resetForNewEpisode} className="text-[11px] text-port-accent hover:underline">
+ Compose another episode
+ </button>
+ )}
+ </div>
+ ) : (
+ <button
+ type="button" onClick={handleQueue} disabled={!canQueue}
+ className="w-full min-h-[44px] inline-flex items-center justify-center gap-1.5 px-3 py-2 rounded bg-port-accent text-white text-sm font-medium disabled:opacity-40"
+ >
+ {queuing ? <Loader2 className="w-4 h-4 animate-spin" /> : <Film className="w-4 h-4" />}
+ Queue episode
+ </button>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/videoGen/EpisodeComposer.test.jsx b/client/src/components/videoGen/EpisodeComposer.test.jsx
new file mode 100644
index 0000000000..1c7d164964
--- /dev/null
+++ b/client/src/components/videoGen/EpisodeComposer.test.jsx
@@ -0,0 +1,90 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
+import EpisodeComposer from './EpisodeComposer';
+import { MockEventSource, lastEventSource } from '../../test/mockEventSource';
+
+vi.mock('../../services/api', () => ({
+ lintContinuousVideoEpisode: vi.fn(),
+ generateContinuousVideoEpisode: vi.fn(),
+ continuousVideoEpisodeEventsUrl: (jobId) => `/api/continuous-video/${jobId}/events`,
+}));
+
+import {
+ lintContinuousVideoEpisode, generateContinuousVideoEpisode,
+} from '../../services/api';
+
+const FAILING_PREVIEW = {
+ clips: [{
+ cutType: 'fresh', speakers: ['mara'], prompt: 'Mara paces.', references: [{ kind: 'cast', id: 'mara' }],
+ }],
+ lint: { pass: false, results: [{ index: 0, pass: false, reasons: ['no bible descriptor found for cast/mara'] }] },
+};
+
+const PASSING_PREVIEW = {
+ clips: [{
+ cutType: 'fresh', speakers: ['mara'], prompt: 'gritty noir. a cell. Mara paces.', references: [{ kind: 'cast', id: 'mara' }],
+ }],
+ lint: { pass: true, results: [{ index: 0, pass: true, reasons: [] }] },
+};
+
+async function writeScene() {
+ const [textInput] = screen.getAllByPlaceholderText('what happens');
+ fireEvent.change(textInput, { target: { value: 'Mara paces the cell.' } });
+}
+
+describe('EpisodeComposer', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ MockEventSource.reset();
+ global.EventSource = MockEventSource;
+ });
+ afterEach(() => {
+ delete global.EventSource;
+ });
+
+ it('renders a beat preview with camera-cut and slot-lock info once scenes have content', async () => {
+ lintContinuousVideoEpisode.mockResolvedValue(PASSING_PREVIEW);
+ render(<EpisodeComposer />);
+ await writeScene();
+ await waitFor(() => expect(lintContinuousVideoEpisode).toHaveBeenCalled(), { timeout: 2000 });
+ expect(await screen.findByText('fresh cut')).toBeTruthy();
+ expect(screen.getByText('mara')).toBeTruthy();
+ expect(screen.getByText('cast/mara')).toBeTruthy();
+ });
+
+ it('shows lint failure reasons for a failing beat and keeps Queue disabled', async () => {
+ lintContinuousVideoEpisode.mockResolvedValue(FAILING_PREVIEW);
+ render(<EpisodeComposer />);
+ await writeScene();
+ await waitFor(() => expect(lintContinuousVideoEpisode).toHaveBeenCalled(), { timeout: 2000 });
+ expect(await screen.findByText(/no bible descriptor found for cast\/mara/)).toBeTruthy();
+ expect(screen.getByRole('button', { name: /Queue episode/i })).toBeDisabled();
+ });
+
+ it('gates Queue episode on a passing lint, then streams progress and disables the form while queuing', async () => {
+ lintContinuousVideoEpisode.mockResolvedValue(PASSING_PREVIEW);
+ generateContinuousVideoEpisode.mockResolvedValue({ jobId: 'job-1', generationId: 'job-1', status: 'running' });
+ render(<EpisodeComposer />);
+ await writeScene();
+ await waitFor(() => expect(lintContinuousVideoEpisode).toHaveBeenCalled(), { timeout: 2000 });
+
+ const queueButton = await screen.findByRole('button', { name: /Queue episode/i });
+ await waitFor(() => expect(queueButton).not.toBeDisabled());
+ fireEvent.click(queueButton);
+
+ await waitFor(() => expect(generateContinuousVideoEpisode).toHaveBeenCalled());
+ await waitFor(() => expect(lastEventSource()).toBeTruthy());
+
+ // Streaming — the scene text input is disabled (save-gating: no editing mid-generation).
+ await waitFor(() => {
+ const [textInput] = screen.getAllByPlaceholderText('what happens');
+ expect(textInput.disabled).toBe(true);
+ });
+
+ act(() => lastEventSource().emit({ type: 'progress', progress: 0.5, message: 'Rendering clip 1/1' }));
+ expect(await screen.findByText('Rendering clip 1/1')).toBeTruthy();
+
+ act(() => lastEventSource().emit({ type: 'complete', result: { jobId: 'job-1' } }));
+ expect(await screen.findByText(/Compose another episode/i)).toBeTruthy();
+ });
+});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index d7e1cd4fe3..e617d6fee8 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -168,6 +168,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |
| `editorialChecks.js` | Pure helpers for the Editorial Checks page (`/pipeline/editorial-checks`, #1285): `groupChecksByScope(checks)` buckets catalog rows into ordered Noun/Scene/Issue/Series sections; `groupFindingsByCheck(comments, rowsById)` groups check-sourced review comments per check with open/total + severity counts; `openFindingsTotal(groups)` sums open findings; `findingManuscriptLink(seriesId, comment)` builds the `?comment=` deep-link into the manuscript editor; the triage filter/sort helpers (#1600) `deriveFindingFacets(groups)` (enumerate present severities/statuses/scopes/checks/issues), `applyFindingsView(groups, filters, sort)` (filter + recount + sort findings and groups), `normalizeFindingSort`, `findingIssueKey`, and the `FINDING_SORT_OPTIONS` table; the per-check maturity/quality helpers (#1629) `checkDismissalRate(group)` and `checkMaturity(group)` (→ `{ findings, dismissalRate, falsePositiveRate, level }`, `level` ∈ new/unproven/noisy/reliable) plus the `CHECK_MATURITY_MIN_SAMPLE`/`CHECK_NOISY_DISMISSAL_RATE` thresholds; plus `scopeLabel` and the `CHECK_SCOPE_ORDER`/`CHECK_SCOPE_LABELS` tables. No React/window — the page and its tests share them. |
| `editorialHealth.js` | Pure presentation helpers for the editorial health panel (`/pipeline/editorial-checks`, #1316): `scoreBand(score)` bands a 0–100 health score into a label + Tailwind tone; `deltaDisplay(delta)` formats the revision-to-revision score change (arrow + tone); `sparklineGeometry(points, box)` projects the trend's score points into SVG polyline coords; `orderedCategories(openByCategory)` sorts the per-category open-finding breakdown; `orderedChecks(openByCheck, labelFor)` sorts the per-check breakdown resolving each id to its catalog label (#1597); `checkCountSeries(points, checkId)` extracts one check's count series across the trend points; `countSparklineGeometry(values, box)` projects a non-negative count series into SVG polyline coords normalized to its own max (per-check finding-count sparkline); `diffCountMaps(current, previous)` lists the buckets whose open-finding count changed between two snapshots (#1630); `snapshotDiff(point, previous)` builds a trend snapshot's drill-down (its own breakdown + per-severity/category/check diff vs the prior revision, null-aware for pre-#1597 per-check telemetry, #1630); plus the `SEVERITY_ORDER`/`SEVERITY_LABELS` and `READINESS_GATE_LABELS`/`READINESS_GATE_ORDER` tables. No React/window — the panel and its tests share them. |
+| `episodeSceneImport.js` | Best-effort mapping of a FableLoom episode's scene nodes into the Episode Composer's draft `scenes` shape (#6228): `parseNodeTextToLines(text, { format })` splits prose into a single action line, or (for `teleplay`) picks out ALL-CAPS character cues + following dialogue lines and drops sluglines; `loomEpisodeToDraftScenes(episode, { format })` maps every node to one draft scene. Lossy on purpose — the composer always leaves the import user-editable. |
| `seriesReviewProgress.js` | Pure helpers for the "Review this series" SSE progress stream (`SeriesReviewPanel.jsx`, #4108): `REVIEW_STEP_LABELS` + `reviewFrameLabel(frame)` label a single frame, and `summarizeReviewProgress(frames)` folds the whole stream into `{ headline, alsoRunning }`. Since the review runs the foundation judge and canon readiness concurrently with the editorial-checks pass, frames interleave — labelling only the newest frame made the headline flicker between a background step that just settled and the current check. The summarizer tracks which steps are still in flight, gives the headline to the editorial-checks pass while it runs, and reports the other in-flight steps alongside it. No React/window. |
| `drumKits.js` | The three selectable synth kits for the SongBook drum play-along — `DRUM_KIT_LIST` (the one ordered source of truth, first entry = default; the picker renders it directly) plus the derived `DRUM_KITS` / `DRUM_KIT_IDS` / `DEFAULT_DRUM_KIT` (`909` punchy, `808` deep-sub, `acoustic`), `resolveDrumKit(id)` (unknown/stale id → the default, never silence), `kitVoiceLayers(kit, sound)` (unmapped piece → the snare, never silence) and the kit-independent `CLICK_VOICE`. Pure DATA: each voice is a list of LAYERS — `tone` (`wave, from, to, pitchDecay, drive`), `noise` (`filter`), or `metal` (N square `partials` summed into one filter+envelope) — that `drumPlayback.js` realizes in Web Audio. Three properties carry the kit's punch and are easy to undo by accident: `pitchDecay` is INDEPENDENT of the amplitude `decay` (a membrane snaps to its fundamental in ~30–60ms then holds while the tail runs on — coupling the two is what made the original kick sound weak), `drive` tanh-saturates a layer so a sub-50 Hz kick generates the harmonics a phone/laptop speaker can actually reproduce, and a `metal` layer's high-pass cutoffs are far LOWER (and gains far higher) than the noise voices beside them because a square's harmonics fall off 6 dB/octave — see the calibration warning in the file before "harmonizing" those numbers. |
| `drumNotation.js` | Parser for the PortOS drum-kit notation (#3115) — a dependency-free GRID DSL (`HH: x x x x`) for the SongBook `drum` content format, drawn by `<DrumSheetView>` (hand-rolled SVG, no engraving lib). `parseDrumChart(text)` → `{ time, tempo, subdivision, stepsPerBar, bars:[{index,label,repeat,repeatPass,rows:[{piece,cells}]}], pieces, errors }` — `key: value` headers (`time`/`tempo`/`subdivision`/`kit` row-order override), blank-line-separated bar blocks with a `# label x2` repeat suffix expanded into real bars, nine kit pieces (`CR RD HH T1 T2 S FT K HF`, long aliases accepted), six cell glyphs (`-` rest, `x` normal, `X` accent, `o` open, `g` ghost, `f` flam) with spacing optional. Forgiving: short rows pad with rests, over-long rows truncate, unknown pieces/cells collect into `errors` — never throws. Plus `KIT_PIECES` (label / GM `midi` / synth `sound` / `glyph`), `kitPiece(id)`, `CELL_GLYPHS` (per-glyph velocity + flags), `isDrumNotation(text)` (import-page format sniff, runs BEFORE `tabNotation.detectFormat`), `drumChartHasMusic(text)` and its already-parsed twin `chartHasMusic(chart)`. Also the plain-language explainers the sheet's tap-a-note readout and Legend panel read — `describeDrumCell(pieceId, cell)` → `{ pieceLabel, char, articulation, detail, technique, velocityPercent, rest }` (piece-aware: `o` is "Open" on a hi-hat/cymbal but a normal hit on a drum; a null/unknown cell describes as a rest, an unknown piece returns null), `describeDrumPosition(bar, step, subdivision)` → `bar 6, count “2 e”` (count-along syllables, exact `+n/N` fallback for an unconventional subdivision), `drumGlyphLegend(pieceIds)` (all six cell characters, with the `o` row resolved for the pieces a chart uses — a fixed row would tell a crash-only chart to work the hi-hat pedal; a mixed kit gets every applicable reading) and each `KIT_PIECES` row's `technique` (how that piece is struck). Only the hi-hat voice sustains an `o` in playback, so the `open` wording follows the piece's `sound`, not its glyph shape. NOT the lead-sheet parser (`scoreNotation.js`). |
diff --git a/client/src/lib/episodeSceneImport.js b/client/src/lib/episodeSceneImport.js
new file mode 100644
index 0000000000..ebe1392dd2
--- /dev/null
+++ b/client/src/lib/episodeSceneImport.js
@@ -0,0 +1,74 @@
+// Best-effort mapping from a FableLoom scene node's authored text into the
+// `{ lines: [{ type, speaker, text }] }` shape /api/continuous-video expects
+// (#6228). There is no existing FableLoom→continuous-video scene export, and
+// prose/teleplay text is free-form — this is a lossy starting draft the
+// Episode Composer always leaves user-editable, not a round-trip parser.
+
+const CUE_RE = /^[A-Z][A-Z0-9 .,'()-]{1,60}$/;
+
+/** True for a short all-caps line that reads as a teleplay character cue. */
+const looksLikeCue = (line) => {
+ const trimmed = line.trim();
+ if (!trimmed || trimmed.length > 60) return false;
+ if (!CUE_RE.test(trimmed)) return false;
+ return /[A-Z]/.test(trimmed) && trimmed === trimmed.toUpperCase();
+};
+
+/**
+ * Parse one FableLoom node's text into continuous-video scene lines.
+ * `format` 'teleplay' looks for ALL-CAPS character cues followed by dialogue;
+ * anything else (including 'prose') is imported as a single action line.
+ * Blank lines and slugline-looking lines (`INT. ...` / `EXT. ...`) are dropped.
+ */
+export function parseNodeTextToLines(text, { format = 'prose' } = {}) {
+ const raw = typeof text === 'string' ? text : '';
+ if (!raw.trim()) return [];
+ const rawLines = raw.split('\n').map((l) => l.trim()).filter(Boolean);
+
+ if (format !== 'teleplay') {
+ return [{ type: 'action', text: raw.trim() }];
+ }
+
+ const lines = [];
+ let actionBuffer = [];
+ const flushAction = () => {
+ if (actionBuffer.length) {
+ lines.push({ type: 'action', text: actionBuffer.join(' ') });
+ actionBuffer = [];
+ }
+ };
+
+ for (let i = 0; i < rawLines.length; i += 1) {
+ const line = rawLines[i];
+ if (/^(INT\.|EXT\.)/.test(line)) continue; // slugline — not a spoken/action line
+ if (looksLikeCue(line)) {
+ flushAction();
+ const speaker = line.replace(/\(.*\)$/, '').trim();
+ const next = rawLines[i + 1];
+ if (next && !looksLikeCue(next) && !/^(INT\.|EXT\.)/.test(next)) {
+ lines.push({ type: 'dialogue', speaker, text: next });
+ i += 1;
+ }
+ continue;
+ }
+ actionBuffer.push(line);
+ }
+ flushAction();
+ return lines;
+}
+
+/**
+ * Map a FableLoom loom's episode nodes into draft continuous-video scenes —
+ * one scene per node, in node order. Nodes with no importable lines are
+ * skipped.
+ */
+export function loomEpisodeToDraftScenes(episode, { format = 'prose' } = {}) {
+ const nodes = Array.isArray(episode?.nodes) ? episode.nodes : [];
+ return nodes
+ .map((node) => ({
+ sceneId: node.id,
+ location: node.title || undefined,
+ lines: parseNodeTextToLines(node.prose, { format }),
+ }))
+ .filter((scene) => scene.lines.length > 0);
+}
diff --git a/client/src/lib/episodeSceneImport.test.js b/client/src/lib/episodeSceneImport.test.js
new file mode 100644
index 0000000000..3cac8b3949
--- /dev/null
+++ b/client/src/lib/episodeSceneImport.test.js
@@ -0,0 +1,49 @@
+import { describe, it, expect } from 'vitest';
+import { parseNodeTextToLines, loomEpisodeToDraftScenes } from './episodeSceneImport.js';
+
+describe('parseNodeTextToLines', () => {
+ it('imports prose as a single action line', () => {
+ expect(parseNodeTextToLines('You step into the hall. It is dark.', { format: 'prose' })).toEqual([
+ { type: 'action', text: 'You step into the hall. It is dark.' },
+ ]);
+ });
+
+ it('returns an empty array for blank/missing text', () => {
+ expect(parseNodeTextToLines('', { format: 'prose' })).toEqual([]);
+ expect(parseNodeTextToLines(undefined, { format: 'prose' })).toEqual([]);
+ });
+
+ it('extracts teleplay cues + dialogue and drops sluglines', () => {
+ const text = [
+ 'INT. HOLDING CELL - NIGHT',
+ 'Mara paces the cell.',
+ 'MARA',
+ "We're out of time.",
+ 'She looks at the door.',
+ ].join('\n');
+ expect(parseNodeTextToLines(text, { format: 'teleplay' })).toEqual([
+ { type: 'action', text: 'Mara paces the cell.' },
+ { type: 'dialogue', speaker: 'MARA', text: "We're out of time." },
+ { type: 'action', text: 'She looks at the door.' },
+ ]);
+ });
+});
+
+describe('loomEpisodeToDraftScenes', () => {
+ it('maps each node to a scene and skips nodes with no importable lines', () => {
+ const episode = {
+ nodes: [
+ { id: 'n1', title: 'Cell Block', prose: 'You wake up.' },
+ { id: 'n2', title: 'Empty', prose: '' },
+ ],
+ };
+ expect(loomEpisodeToDraftScenes(episode)).toEqual([
+ { sceneId: 'n1', location: 'Cell Block', lines: [{ type: 'action', text: 'You wake up.' }] },
+ ]);
+ });
+
+ it('handles a missing/empty node list', () => {
+ expect(loomEpisodeToDraftScenes(null)).toEqual([]);
+ expect(loomEpisodeToDraftScenes({ nodes: [] })).toEqual([]);
+ });
+});
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index a730dd9e5b..b379555d19 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -137,6 +137,7 @@ export * from './drumNotation.js';
export * from './drumPlayback.js';
export * from './editorialChecks.js';
export * from './editorialHealth.js';
+export * from './episodeSceneImport.js';
export * from './lookaheadTransport.js';
export * from './lossSparkline.js';
export * from './metronome.js';
diff --git a/client/src/pages/FableLoomStory.jsx b/client/src/pages/FableLoomStory.jsx
index 9e55650756..535c1ab295 100644
--- a/client/src/pages/FableLoomStory.jsx
+++ b/client/src/pages/FableLoomStory.jsx
@@ -761,6 +761,7 @@ export default function FableLoomStory({ view = 'graph' }) {
universe={linkedUniverse}
onLoomUpdate={setLoom}
onRewritten={handleRewritten}
+ episodeId={seriesPlanOpen ? null : episodeId}
/>
{episode && (
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index e53c59e69e..2dab94fd38 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -54,6 +54,7 @@ import ModelDisclosure from '../components/videoGen/ModelDisclosure';
import ModelRepairBanner from '../components/videoGen/ModelRepairBanner';
import RenderStatusCard from '../components/videoGen/RenderStatusCard';
import VideoGenGallery from '../components/videoGen/VideoGenGallery';
+import EpisodeComposer from '../components/videoGen/EpisodeComposer';
import GalleryImagePicker from '../components/imageGen/GalleryImagePicker';
import MediaPreview from '../components/media/MediaPreview';
import StylePresetPicker from '../components/media/StylePresetPicker';
@@ -90,7 +91,9 @@ import {
getSettings,
getVideoGenRuntimeStatus,
listLorasFull,
+ getLoom,
} from '../services/api';
+import { loomEpisodeToDraftScenes } from '../lib/episodeSceneImport.js';
import LoraPicker from '../components/imageGen/LoraPicker';
import { VIDEO_RESOLUTIONS, resolutionOptionsForModel } from '../lib/videoGenResolutions';
import { GROK_VIDEO_DURATIONS } from '../lib/grokVideoClip.js';
@@ -120,6 +123,30 @@ export default function VideoGen() {
refreshGrokEnabled();
};
+ // Episode Composer (#6228) — multi-scene continuous-video authoring, opened
+ // either directly or as a FableLoom entry point carrying loomId/episodeId
+ // (LoomSettingsDrawer's "Open Episode Composer" link).
+ const episodeOpen = searchParams.get('episode') === '1';
+ const episodeLoomId = searchParams.get('loomId');
+ const episodeEpisodeId = searchParams.get('episodeId');
+ const openEpisodeComposer = () => setSearchParams(prev => { const n = new URLSearchParams(prev); n.set('episode', '1'); return n; });
+ const closeEpisodeComposer = () => setSearchParams(prev => {
+ const n = new URLSearchParams(prev);
+ n.delete('episode'); n.delete('loomId'); n.delete('episodeId');
+ return n;
+ });
+ const [episodeImportScenes, setEpisodeImportScenes] = useState(null);
+ useEffect(() => {
+ if (!episodeOpen || !episodeLoomId || !episodeEpisodeId) return;
+ getLoom(episodeLoomId, { silent: true }).then((loom) => {
+ const episode = loom?.episodes?.find((e) => e.id === episodeEpisodeId);
+ const draftScenes = loomEpisodeToDraftScenes(episode, { format: loom?.format });
+ if (draftScenes.length) setEpisodeImportScenes(draftScenes);
+ }).catch(() => {});
+ // Only re-run when a fresh loom/episode is targeted, not on every render.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [episodeOpen, episodeLoomId, episodeEpisodeId]);
+
// `/status` owns connectivity ONLY. It shells out to python on every call
// (~1-2s), so nothing the form needs to render may wait on it.
const [status, setStatus] = useState(null);
@@ -887,6 +914,14 @@ export default function VideoGen() {
>
<RefreshCw className={`w-3.5 h-3.5 ${statusLoading ? 'animate-spin' : ''}`} />
</button>
+ <button
+ type="button"
+ onClick={openEpisodeComposer}
+ className="flex items-center gap-1.5 px-2 py-1 text-gray-300 hover:text-white border border-port-border rounded hover:bg-port-border/50"
+ title="Compose a multi-scene continuous-video episode"
+ >
+ <Film className="w-3.5 h-3.5" /> Episode
+ </button>
<button
type="button"
onClick={openSettings}
@@ -1652,6 +1687,10 @@ export default function VideoGen() {
<ImageGenTab />
</Drawer>
+ <Drawer open={episodeOpen} onClose={closeEpisodeComposer} title="Episode Composer" size="xl" closeOnBackdrop={false}>
+ {episodeOpen && <EpisodeComposer initialScenes={episodeImportScenes} onQueued={refreshHistory} />}
+ </Drawer>
+
<RuntimeInstallModal
open={installModalOpen}
runtime={byovRuntime}
diff --git a/client/src/services/README.md b/client/src/services/README.md
index bc6598a3fb..512fe09f0d 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -107,6 +107,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiFableLoom.js` | FableLoom branching narratives — loom/episode/scene-node/transition CRUD, deterministic graph validation, AI authoring lanes, and the bounded editorial/playthrough autopilot lifecycle. |
| `apiGames.js` | Game studio records, managed-app binding, reusable sprite/music bindings, deterministic asset-bundle compilation/integrity preflight, and AI feedback history. |
| `apiMusicVideo.js` | Music Video projects + scene board + audio analysis. |
+| `apiContinuousVideo.js` | Continuous-video episode generation: client-side-callable lint preview of a scene draft, queue-episode submit, and the SSE progress-events URL. |
| `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), directional walk and per-track generation/approval, animation-type definition CRUD (#3153), trim/postprocess, and per-run source-frame listing for the Loop Trimmer's re-derive (#2980), and animation render-provider readiness (#4876). |
| `apiShell.js` | Shell sessions over HTTP: hand a photo (plus a message) to the agent TUI running in a session. Keystrokes/output stay on the `shell:*` socket protocol. |
| `apiThreejsModels.js` | Procedural Three.js model workspaces: gallery-image generation, refinement, source export, deletion, and the subject-family checklist options. |
diff --git a/client/src/services/api.js b/client/src/services/api.js
index d99caf089e..8cd66e4710 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -78,6 +78,7 @@ export * from './apiCreativeCommission.js';
export * from './apiFableLoom.js';
export * from './apiGames.js';
export * from './apiMusicVideo.js';
+export * from './apiContinuousVideo.js';
export * from './apiSprites.js';
export * from './apiShell.js';
export * from './apiMoodBoard.js';
diff --git a/client/src/services/apiContinuousVideo.js b/client/src/services/apiContinuousVideo.js
new file mode 100644
index 0000000000..79ea9c1bbd
--- /dev/null
+++ b/client/src/services/apiContinuousVideo.js
@@ -0,0 +1,23 @@
+import { request } from './apiCore.js';
+
+// Continuous-video episode generation (#6227) — submit a multi-scene script +
+// bible for chained clip generation, or lint a draft before submitting it
+// (Episode Composer, #6228). `options` lets a caller suppress request()'s
+// auto-toast with `{ silent: true }` when it owns its own error UI.
+
+// Compose the scenes into clips and lint them WITHOUT submitting anything.
+// Resolves to `{ clips, lint: { pass, results: [{ index, pass, reasons }] } }`.
+export const lintContinuousVideoEpisode = (body, options = {}) => request('/continuous-video/lint', {
+ method: 'POST', body: JSON.stringify(body), silent: true, ...options,
+});
+
+// Queue the episode for generation. Resolves to `{ jobId, generationId, status }`.
+// A 422 VIDEO_PROMPT_LINT_FAILED means the server-side lint rejected a clip —
+// the caller should already have surfaced this via lintContinuousVideoEpisode.
+export const generateContinuousVideoEpisode = (body, options = {}) => request('/continuous-video', {
+ method: 'POST', body: JSON.stringify(body), ...options,
+});
+
+// EventSource URL for an episode job's progress stream (consumed by useSseProgress).
+export const continuousVideoEpisodeEventsUrl = (jobId) =>
+ `/api/continuous-video/${encodeURIComponent(jobId)}/events`;
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index e8fd0e216c..57099ca24a 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -3511,6 +3511,14 @@
"server/routes/continuousVideoEpisode.js"
]
},
+ {
+ "method": "POST",
+ "path": "/api/continuous-video/lint",
+ "mountPath": "/api/continuous-video",
+ "sources": [
+ "server/routes/continuousVideoEpisode.js"
+ ]
+ },
{
"method": "GET",
"path": "/api/cos",
@@ -17570,8 +17578,8 @@
],
"stats": {
"mounts": 148,
- "operations": 2176,
- "declarations": 2184,
+ "operations": 2177,
+ "declarations": 2185,
"sourceFiles": 231
}
}
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 19b2b69a1b..88ee78c029 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -44,7 +44,7 @@ const RAW_NAV_COMMANDS = [
{ id: 'nav.catalog.settings', path: '/catalog?settings=1', label: 'Catalog Types', section: 'Create', previousPaths: ['/settings/catalog'], aliases: ['catalog settings', 'catalog-settings', 'settings-catalog', 'catalog-types'], keywords: ['catalog', 'types', 'labels', 'character', 'place', 'object', 'taxonomy'] },
{ id: 'nav.media', path: '/media', label: 'Media Gen', section: 'Create', aliases: ['media', 'media-gen', 'mediagen', 'generate'], keywords: ['image', 'video', 'render', 'art', 'movie'] },
{ id: 'nav.media.image', path: '/media/image', label: 'Image', section: 'Create', previousPaths: ['/image-gen'], aliases: ['image-gen', 'imagegen', 'generate-image', 'sd', 'stable-diffusion'], keywords: ['stable diffusion', 'render', 'art', 'picture', 'photo', 'draw', 'flux', 'mflux'] },
- { id: 'nav.media.video', path: '/media/video', label: 'Video', section: 'Create', previousPaths: ['/video-gen'], aliases: ['video-gen', 'videogen', 'generate-video', 'ltx'], keywords: ['video', 'animate', 'movie', 'clip', 'ltx'] },
+ { id: 'nav.media.video', path: '/media/video', label: 'Video', section: 'Create', previousPaths: ['/video-gen'], aliases: ['video-gen', 'videogen', 'generate-video', 'ltx'], keywords: ['video', 'animate', 'movie', 'clip', 'ltx', 'episode composer', 'continuous video', 'multi-scene'] },
{ id: 'nav.media.history', path: '/media/history', label: 'Media History', section: 'Create', previousPaths: ['/media-history'], aliases: ['media-history', 'video-history'], keywords: ['videos', 'gallery', 'stitch'] },
{ id: 'nav.media.annotate', path: '/media/annotate', label: 'Annotate', section: 'Create', previousPaths: ['/annotate', '/annotate/:mediaKey'], aliases: ['annotate', 'media-annotate', 'sketch', 'draw-over', 'markup'], keywords: ['annotation', 'sketch', 'draw', 'markup', 'scribble', 'label', 'canvas', 'overlay', 'stroke'] },
{ id: 'nav.media.collections', path: '/media/collections', label: 'Collections', section: 'Create', aliases: ['collections', 'media-collections', 'stacks', 'projects'], keywords: ['bucket', 'group', 'project', 'album', 'organize'] },
diff --git a/server/routes/continuousVideoEpisode.js b/server/routes/continuousVideoEpisode.js
index da4d41ed2e..287624ab3b 100644
--- a/server/routes/continuousVideoEpisode.js
+++ b/server/routes/continuousVideoEpisode.js
@@ -61,15 +61,34 @@ const compilerOptionsSchema = z.object({
frameGrid: z.enum(['uniform', '17n+5']).optional(),
});
-const submitBodySchema = z.object({
+const previewBodySchema = z.object({
scenes: z.array(sceneSchema).min(1).max(200),
bible: bibleSchema,
framings: z.array(z.string().max(200).nullable()).max(2000).optional(),
+ compilerOptions: compilerOptionsSchema.optional(),
+});
+
+const submitBodySchema = previewBodySchema.extend({
backend: z.enum(CONTINUOUS_VIDEO_BACKENDS).optional(),
renderOptions: renderOptionsSchema.optional(),
- compilerOptions: compilerOptionsSchema.optional(),
});
+// Compose+lint without submitting anything — the Episode Composer UI calls
+// this on every scene edit to render a live beat/lint preview before the
+// user queues generation. Never touches a backend or settings.
+router.post('/lint', asyncHandler(async (req, res) => {
+ const parsed = previewBodySchema.safeParse(req.body || {});
+ if (!parsed.success) failValidation(parsed);
+ const {
+ scenes, bible, framings, compilerOptions,
+ } = parsed.data;
+ const clips = composeEpisodeClips({
+ scenes, bible, framings, compilerOptions,
+ });
+ const lint = lintClips(clips, { bible });
+ res.json({ clips, lint });
+}));
+
router.post('/', asyncHandler(async (req, res) => {
const parsed = submitBodySchema.safeParse(req.body || {});
if (!parsed.success) failValidation(parsed);
diff --git a/server/routes/continuousVideoEpisode.test.js b/server/routes/continuousVideoEpisode.test.js
index b1e401907b..c1c8825132 100644
--- a/server/routes/continuousVideoEpisode.test.js
+++ b/server/routes/continuousVideoEpisode.test.js
@@ -76,6 +76,34 @@ describe('continuousVideoEpisode routes', () => {
});
});
+ describe('POST /lint', () => {
+ it('composes and lints without starting generation', async () => {
+ lintClips.mockReturnValue({ pass: false, results: [{ index: 0, pass: false, reasons: ['banned term'] }] });
+ const r = await request(app).post('/api/continuous-video/lint').send({ scenes, bible });
+ expect(r.status).toBe(200);
+ expect(r.body.lint.pass).toBe(false);
+ expect(r.body.clips).toEqual([{ prompt: 'A quiet street.', cutType: 'fresh' }]);
+ expect(continuousVideo.generateContinuousVideoEpisode).not.toHaveBeenCalled();
+ });
+
+ it('rejects a request missing scenes/bible', async () => {
+ const r = await request(app).post('/api/continuous-video/lint').send({});
+ expect(r.status).toBe(400);
+ expect(continuousVideo.composeEpisodeClips).not.toHaveBeenCalled();
+ });
+
+ it('does not accept backend/renderOptions — only compose+lint fields', async () => {
+ const r = await request(app).post('/api/continuous-video/lint').send({
+ scenes, bible, backend: 'reactor', renderOptions: { modelId: 'ltx2' },
+ });
+ expect(r.status).toBe(200);
+ // composeEpisodeClips is only ever called with the compose-relevant fields.
+ const call = continuousVideo.composeEpisodeClips.mock.calls[0][0];
+ expect(call).not.toHaveProperty('backend');
+ expect(call).not.toHaveProperty('renderOptions');
+ });
+ });
+
describe('GET /:jobId/events', () => {
it('404s when the job is not found', async () => {
const r = await request(app).get('/api/continuous-video/missing/events');