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

Storyboards: a shared planning board under Create (#12903)

[._.]/560dd41a246a
diff --git a/client/src/App.jsx b/client/src/App.jsx
index e893e68e9a..692499a0c4 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -85,6 +85,8 @@ const Sprites = lazyWithReload(() => import('./pages/Sprites'));
const MoodBoards = lazyWithReload(() => import('./pages/MoodBoards'));
const CodeAnimation = lazyWithReload(() => import('./pages/CodeAnimation'));
const MoodBoardDetail = lazyWithReload(() => import('./pages/MoodBoardDetail'));
+const Storyboards = lazyWithReload(() => import('./pages/Storyboards'));
+const StoryboardDetail = lazyWithReload(() => import('./pages/StoryboardDetail'));
const Decks = lazyWithReload(() => import('./pages/Decks'));
const DeckDetail = lazyWithReload(() => import('./pages/DeckDetail'));
const CreateApp = lazyWithReload(() => import('./pages/CreateApp'));
@@ -632,6 +634,9 @@ export default function App() {
<Route path="code-animation/production/:projectId" element={<CodeAnimation />} />
<Route path="mood-boards" element={<MoodBoards />} />
<Route path="mood-boards/:id" element={<MoodBoardDetail />} />
+ <Route path="storyboards" element={<Storyboards />} />
+ <Route path="storyboards/:id" element={<StoryboardDetail />} />
+ <Route path="storyboards/:id/panel/:panelId" element={<StoryboardDetail />} />
<Route path="decks" element={<Decks />} />
<Route path="decks/:id" element={<DeckDetail />} />
<Route path="universes" element={<Universes />} />
diff --git a/client/src/components/IngredientPicker.jsx b/client/src/components/IngredientPicker.jsx
index ac24c60495..4412e6459c 100644
--- a/client/src/components/IngredientPicker.jsx
+++ b/client/src/components/IngredientPicker.jsx
@@ -124,6 +124,10 @@ export default function IngredientPicker({
onClose={onClose}
size="xl"
closeOnBackdrop
+ // Portal to <body>, as GalleryImagePicker does: opened from inside a
+ // drawer or a glass-theme card, an inline fixed overlay is trapped in
+ // that ancestor's stacking context.
+ usePortal
panelClassName="bg-port-card border border-port-border rounded-xl flex flex-col"
ariaLabelledBy="ingredient-picker-title"
>
diff --git a/client/src/components/storyboards/BeatSection.jsx b/client/src/components/storyboards/BeatSection.jsx
new file mode 100644
index 0000000000..b3bf04d32a
--- /dev/null
+++ b/client/src/components/storyboards/BeatSection.jsx
@@ -0,0 +1,126 @@
+import { useState } from 'react';
+import { ChevronDown, ChevronUp, Plus, SlidersHorizontal, Trash2 } from 'lucide-react';
+import InlineConfirmRow from '../ui/InlineConfirmRow';
+import { STORYBOARD_LIMITS, STORYBOARD_MUSICAL_ROLES } from '../../../../server/lib/storyboardVocabulary.js';
+import { formatTimecode } from '../../utils/formatters';
+import CommitField from './CommitField';
+import PanelCard from './PanelCard';
+import { beatSeconds, MUSICAL_ROLE_LABELS } from './storyboardArt';
+
+const iconButton = 'min-h-[44px] min-w-[44px] inline-flex items-center justify-center rounded text-gray-400 hover:text-white hover:bg-port-border/50 disabled:opacity-30 disabled:pointer-events-none';
+
+/**
+ * One story beat: its title and musical role, a horizontal strip of panels,
+ * and (behind the sliders toggle) what happens, why it matters, and the
+ * emotion — the brief the song gets written from.
+ */
+export default function BeatSection({
+ beat, beatIndex, beatCount, firstPanelNumber, aspectRatio, selectedPanelId, sketchNonce,
+ onUpdate, onMove, onDelete, onAddPanel, onOpenPanel, addingPanel = false,
+}) {
+ const [showDetails, setShowDetails] = useState(false);
+ const [confirmDelete, setConfirmDelete] = useState(false);
+ const seconds = beatSeconds(beat);
+ const fieldId = (name) => `beat-${beat.id}-${name}`;
+
+ return (
+ <section className="rounded-xl border border-port-border bg-port-card/60" aria-label={beat.title || `Beat ${beatIndex + 1}`}>
+ {confirmDelete ? (
+ <InlineConfirmRow
+ variant="separator"
+ question={`Delete this beat and its ${beat.panels.length} panel${beat.panels.length === 1 ? '' : 's'}?`}
+ onConfirm={() => { setConfirmDelete(false); onDelete(); }}
+ onCancel={() => setConfirmDelete(false)}
+ autoFocus
+ />
+ ) : null}
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 px-2 pt-2">
+ <span className="text-xs font-semibold text-gray-500 tabular-nums w-6 text-center">{beatIndex + 1}</span>
+ <div className="flex-1 min-w-[10rem]">
+ <CommitField
+ id={fieldId('title')}
+ value={beat.title}
+ maxLength={STORYBOARD_LIMITS.beatTitle}
+ placeholder="Beat title"
+ ariaLabel="Beat title"
+ onCommit={(title) => onUpdate({ title })}
+ className="font-medium"
+ />
+ </div>
+ <label htmlFor={fieldId('role')} className="sr-only">Musical role</label>
+ <select
+ id={fieldId('role')}
+ value={beat.musicalRole || ''}
+ onChange={(event) => onUpdate({ musicalRole: event.target.value || null })}
+ className="min-h-[44px] bg-port-bg border border-port-border rounded px-2 text-sm text-white"
+ >
+ <option value="">No section</option>
+ {STORYBOARD_MUSICAL_ROLES.map((role) => <option key={role} value={role}>{MUSICAL_ROLE_LABELS[role] || role}</option>)}
+ </select>
+ <span className="text-xs text-gray-500 tabular-nums" title="Estimated length of this beat">{formatTimecode(seconds)}</span>
+ <div className="flex items-center ml-auto">
+ <button type="button" className={`${iconButton} ${showDetails ? 'text-port-accent' : ''}`} onClick={() => setShowDetails((v) => !v)}
+ aria-expanded={showDetails} aria-controls={fieldId('details')} aria-label="Beat details">
+ <SlidersHorizontal size={16} />
+ </button>
+ <button type="button" className={iconButton} onClick={() => onMove(beatIndex - 1)} disabled={beatIndex === 0} aria-label="Move beat up">
+ <ChevronUp size={16} />
+ </button>
+ <button type="button" className={iconButton} onClick={() => onMove(beatIndex + 1)} disabled={beatIndex >= beatCount - 1} aria-label="Move beat down">
+ <ChevronDown size={16} />
+ </button>
+ <button type="button" className={`${iconButton} hover:text-port-error`} onClick={() => setConfirmDelete(true)} aria-label="Delete beat">
+ <Trash2 size={16} />
+ </button>
+ </div>
+ </div>
+
+ {showDetails ? (
+ <div id={fieldId('details')} className="grid gap-2 px-2 pt-2 sm:grid-cols-2">
+ <div>
+ <label htmlFor={fieldId('what')} className="block text-[11px] text-gray-500 mb-0.5">What happens</label>
+ <CommitField id={fieldId('what')} multiline value={beat.what} maxLength={STORYBOARD_LIMITS.beatText} onCommit={(what) => onUpdate({ what })} />
+ </div>
+ <div>
+ <label htmlFor={fieldId('why')} className="block text-[11px] text-gray-500 mb-0.5">Why it matters</label>
+ <CommitField id={fieldId('why')} multiline value={beat.why} maxLength={STORYBOARD_LIMITS.beatText} onCommit={(why) => onUpdate({ why })} />
+ </div>
+ <div>
+ <label htmlFor={fieldId('emotion')} className="block text-[11px] text-gray-500 mb-0.5">Emotion</label>
+ <CommitField id={fieldId('emotion')} value={beat.emotion} maxLength={STORYBOARD_LIMITS.emotion} onCommit={(emotion) => onUpdate({ emotion })} />
+ </div>
+ <div>
+ <label htmlFor={fieldId('section')} className="block text-[11px] text-gray-500 mb-0.5">Song section note</label>
+ <CommitField id={fieldId('section')} value={beat.sectionHint} maxLength={STORYBOARD_LIMITS.sectionHint} placeholder="e.g. first chorus, half-time" onCommit={(sectionHint) => onUpdate({ sectionHint })} />
+ </div>
+ </div>
+ ) : null}
+
+ <ol className="flex gap-2 overflow-x-auto overscroll-x-contain snap-x p-2" aria-label="Panels">
+ {beat.panels.map((panel, index) => (
+ <li key={panel.id} className="snap-start shrink-0 w-36 sm:w-44">
+ <PanelCard
+ panel={panel}
+ number={firstPanelNumber + index}
+ aspectRatio={aspectRatio}
+ selected={panel.id === selectedPanelId}
+ sketchNonce={sketchNonce}
+ onOpen={() => onOpenPanel(panel.id)}
+ />
+ </li>
+ ))}
+ <li className="snap-start shrink-0 w-36 sm:w-44">
+ <button
+ type="button"
+ onClick={onAddPanel}
+ disabled={addingPanel}
+ className="w-full h-full min-h-[5rem] rounded-lg border border-dashed border-port-border text-gray-400 hover:text-white hover:border-port-accent/60 inline-flex flex-col items-center justify-center gap-1 text-xs disabled:opacity-50"
+ >
+ <Plus size={18} aria-hidden="true" />
+ Panel
+ </button>
+ </li>
+ </ol>
+ </section>
+ );
+}
diff --git a/client/src/components/storyboards/CommitField.jsx b/client/src/components/storyboards/CommitField.jsx
new file mode 100644
index 0000000000..637a7d6234
--- /dev/null
+++ b/client/src/components/storyboards/CommitField.jsx
@@ -0,0 +1,52 @@
+import { useEffect, useRef, useState } from 'react';
+import AutoSizeTextarea from '../ui/AutoSizeTextarea';
+
+/**
+ * A text field that saves on blur (and on Enter for a single line), so typing
+ * never fires a request per keystroke. It follows `value` from the server
+ * until the user starts editing, then keeps their draft until it commits.
+ * `maxLength` is shown as a count and refused at the input — text is never cut.
+ */
+export default function CommitField({
+ id, value, onCommit, multiline = false, maxLength, placeholder, className = '', ariaLabel, minHeightClass = 'min-h-[2.5rem]',
+}) {
+ const [draft, setDraft] = useState(value ?? '');
+ const editingRef = useRef(false);
+
+ useEffect(() => {
+ if (!editingRef.current) setDraft(value ?? '');
+ }, [value]);
+
+ const commit = () => {
+ editingRef.current = false;
+ if (draft !== (value ?? '')) onCommit(draft);
+ };
+
+ const shared = {
+ id,
+ value: draft,
+ placeholder,
+ maxLength,
+ onFocus: () => { editingRef.current = true; },
+ onChange: (event) => { editingRef.current = true; setDraft(event.target.value); },
+ onBlur: commit,
+ className: `w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white placeholder:text-gray-600 focus:border-port-accent focus:outline-none ${className}`,
+ };
+ const nearLimit = maxLength && draft.length > maxLength * 0.9;
+
+ return (
+ <>
+ {multiline ? (
+ <AutoSizeTextarea {...shared} aria-label={ariaLabel} rows={2} className={`${shared.className} ${minHeightClass}`} />
+ ) : (
+ <input
+ type="text"
+ {...shared}
+ aria-label={ariaLabel}
+ onKeyDown={(event) => { if (event.key === 'Enter') event.currentTarget.blur(); }}
+ />
+ )}
+ {nearLimit ? <p className="mt-0.5 text-[11px] text-port-warning tabular-nums">{draft.length} / {maxLength}</p> : null}
+ </>
+ );
+}
diff --git a/client/src/components/storyboards/MoodBoardPinPicker.jsx b/client/src/components/storyboards/MoodBoardPinPicker.jsx
new file mode 100644
index 0000000000..49b011486a
--- /dev/null
+++ b/client/src/components/storyboards/MoodBoardPinPicker.jsx
@@ -0,0 +1,58 @@
+import { useCallback } from 'react';
+import { Loader2, X } from 'lucide-react';
+import Modal from '../ui/Modal';
+import ListLoadError from '../ui/ListLoadError';
+import useListResource from '../../hooks/useListResource';
+import { getMoodBoard } from '../../services/api';
+import { moodBoardItemAnalysisSource, moodBoardItemSrc } from '../../lib/moodBoardItemSrc';
+
+/**
+ * Pick one image pin from the storyboard's linked mood board. Only pins that
+ * are local gallery images are offered: a panel take stores a gallery filename.
+ */
+export default function MoodBoardPinPicker({ open, moodBoardId, onClose, onSelect }) {
+ const fetchPins = useCallback(async () => {
+ const board = await getMoodBoard(moodBoardId, { silent: true });
+ const items = Array.isArray(board?.items) ? board.items : [];
+ return items.flatMap((item) => {
+ if (item?.type !== 'image') return [];
+ const source = moodBoardItemAnalysisSource(item);
+ return source?.filename ? [{ id: item.id, filename: source.filename, src: moodBoardItemSrc(item), caption: item.caption || '' }] : [];
+ });
+ }, [moodBoardId]);
+ const { items: pins, state, error, retry } = useListResource(fetchPins, { enabled: open && !!moodBoardId });
+
+ return (
+ <Modal open={open} onClose={onClose} size="xl" usePortal ariaLabel="Pick a mood board pin"
+ panelClassName="bg-port-card border border-port-border rounded-xl flex flex-col">
+ <div className="flex items-center justify-between gap-2 p-3 border-b border-port-border">
+ <h2 className="text-sm font-medium text-white">Pick from the mood board</h2>
+ <button type="button" onClick={onClose} aria-label="Close"
+ className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center rounded text-gray-400 hover:text-white">
+ <X size={16} />
+ </button>
+ </div>
+ <div className="p-3 overflow-y-auto">
+ {state === 'error' ? (
+ <ListLoadError what="the mood board" error={error} onRetry={retry} />
+ ) : state === 'loading' ? (
+ <div className="flex justify-center py-8"><Loader2 className="w-5 h-5 animate-spin text-gray-500" aria-label="Loading pins" /></div>
+ ) : pins.length === 0 ? (
+ <p className="py-6 text-center text-sm text-gray-500">This mood board has no gallery image pins.</p>
+ ) : (
+ <ul className="grid grid-cols-3 sm:grid-cols-4 lg:grid-cols-5 gap-2">
+ {pins.map((pin) => (
+ <li key={pin.id}>
+ <button type="button" onClick={() => { onSelect(pin); onClose(); }}
+ className="block w-full aspect-square rounded overflow-hidden border border-port-border hover:border-port-accent"
+ aria-label={pin.caption || 'Mood board pin'}>
+ <img src={pin.src} alt="" loading="lazy" className="w-full h-full object-cover" />
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ </Modal>
+ );
+}
diff --git a/client/src/components/storyboards/PanelCard.jsx b/client/src/components/storyboards/PanelCard.jsx
new file mode 100644
index 0000000000..07296e79f7
--- /dev/null
+++ b/client/src/components/storyboards/PanelCard.jsx
@@ -0,0 +1,39 @@
+import { ImageIcon } from 'lucide-react';
+import { SHOT_TYPE_LABELS } from '../../lib/shotGrammar';
+import { aspectClass, formatPanelSeconds, selectedTake, takeSrc } from './storyboardArt';
+
+/** One panel thumbnail: its selected art (or its action as text) and a footer line. */
+export default function PanelCard({ panel, number, aspectRatio, selected = false, sketchNonce, onOpen, caption }) {
+ const take = selectedTake(panel);
+ const src = takeSrc(take, sketchNonce?.(take?.sketchKey));
+ const seconds = formatPanelSeconds(panel.seconds);
+ const framing = panel.framing ? SHOT_TYPE_LABELS[panel.framing] : null;
+
+ return (
+ <button
+ type="button"
+ onClick={onOpen}
+ aria-label={`Open panel ${number}${panel.action ? `: ${panel.action}` : ''}`}
+ aria-current={selected ? 'true' : undefined}
+ className={`group block w-full text-left rounded-lg border bg-port-card overflow-hidden transition-colors ${selected ? 'border-port-accent ring-1 ring-port-accent' : 'border-port-border hover:border-port-accent/50'}`}
+ >
+ <div className={`${aspectClass(aspectRatio)} w-full bg-port-bg flex items-center justify-center overflow-hidden relative`}>
+ {src ? (
+ <img src={src} alt="" loading="lazy" className="w-full h-full object-cover" />
+ ) : panel.action ? (
+ <p className="p-2 text-xs text-gray-400 line-clamp-4">{panel.action}</p>
+ ) : (
+ <ImageIcon className="w-6 h-6 text-gray-600" aria-hidden="true" />
+ )}
+ {caption ? (
+ <span className="port-media-overlay-strong absolute left-1 top-1 rounded px-1 text-[10px] max-w-[90%] truncate">{caption}</span>
+ ) : null}
+ </div>
+ <div className="flex items-center gap-1.5 px-2 py-1 text-[11px] text-gray-400 min-w-0">
+ <span className="font-semibold text-gray-300 tabular-nums">{number}</span>
+ {framing ? <span className="truncate">{framing}</span> : null}
+ {seconds ? <span className="ml-auto tabular-nums shrink-0">{seconds}</span> : null}
+ </div>
+ </button>
+ );
+}
diff --git a/client/src/components/storyboards/PanelDrawer.jsx b/client/src/components/storyboards/PanelDrawer.jsx
new file mode 100644
index 0000000000..c5c2cd1a65
--- /dev/null
+++ b/client/src/components/storyboards/PanelDrawer.jsx
@@ -0,0 +1,312 @@
+import { useEffect, useMemo, useState } from 'react';
+import {
+ ChevronLeft, ChevronRight, Clapperboard, Drama, ImagePlus, Loader2, Mountain, Package, Palette, PenLine, Plus,
+ StickyNote, Trash2, Users, X,
+} from 'lucide-react';
+import Drawer from '../Drawer';
+import InlineConfirmRow from '../ui/InlineConfirmRow';
+import GalleryImagePicker from '../imageGen/GalleryImagePicker';
+import IngredientPicker from '../IngredientPicker';
+import useDrawerTab from '../../hooks/useDrawerTab';
+import { listCatalogIngredientsByIds } from '../../services/api';
+import { SHOT_TYPES, SHOT_TYPE_LABELS } from '../../lib/shotGrammar';
+import { STORYBOARD_LIMITS } from '../../../../server/lib/storyboardVocabulary.js';
+import CommitField from './CommitField';
+import MoodBoardPinPicker from './MoodBoardPinPicker';
+import { aspectClass, selectedTake, takeSrc } from './storyboardArt';
+
+const TABS = [
+ { id: 'shot', label: 'Shot', icon: Clapperboard },
+ { id: 'cast', label: 'Cast & sets', icon: Users },
+ { id: 'notes', label: 'Notes', icon: StickyNote },
+];
+const TAB_IDS = TABS.map((tab) => tab.id);
+
+const REF_GROUPS = [
+ { field: 'castIds', label: 'Cast', type: 'character', icon: Drama },
+ { field: 'environmentIds', label: 'Environments', type: 'place', icon: Mountain },
+ { field: 'objectIds', label: 'Objects', type: 'object', icon: Package },
+];
+
+const actionButton = 'min-h-[44px] inline-flex items-center justify-center gap-1.5 rounded-lg border border-port-border px-3 text-sm text-gray-200 hover:border-port-accent/60 hover:text-white disabled:opacity-40';
+const iconButton = 'min-h-[44px] min-w-[44px] inline-flex items-center justify-center rounded text-gray-400 hover:text-white hover:bg-port-border/50 disabled:opacity-30 disabled:pointer-events-none';
+const labelClass = 'block text-[11px] text-gray-500 mb-0.5';
+
+function ArtSection({ panel, aspectRatio, sketchNonce, moodBoardId, busy, onAddTake, onSelectTake, onRemoveTake, onSketch }) {
+ const [galleryOpen, setGalleryOpen] = useState(false);
+ const [pinsOpen, setPinsOpen] = useState(false);
+ const [confirmRemove, setConfirmRemove] = useState(false);
+ const take = selectedTake(panel);
+ const src = takeSrc(take, sketchNonce(take?.sketchKey));
+
+ return (
+ <div className="space-y-2">
+ <div className={`${aspectClass(aspectRatio)} w-full rounded-lg border border-port-border bg-port-bg overflow-hidden flex items-center justify-center`}>
+ {src ? (
+ <img src={src} alt="Selected panel art" className="w-full h-full object-contain" />
+ ) : (
+ <p className="text-xs text-gray-500">No art yet</p>
+ )}
+ </div>
+ {panel.takes.length > 1 ? (
+ <ul className="flex gap-1.5 overflow-x-auto pb-1" aria-label="Takes">
+ {panel.takes.map((item, index) => (
+ <li key={item.id} className="shrink-0">
+ <button type="button" onClick={() => onSelectTake(item.id)}
+ aria-label={`Take ${index + 1}`} aria-pressed={item.id === panel.selectedTakeId}
+ className={`block w-16 h-11 rounded overflow-hidden border ${item.id === panel.selectedTakeId ? 'border-port-accent ring-1 ring-port-accent' : 'border-port-border'}`}>
+ <img src={takeSrc(item, sketchNonce(item.sketchKey))} alt="" loading="lazy" className="w-full h-full object-cover" />
+ </button>
+ </li>
+ ))}
+ </ul>
+ ) : null}
+ {confirmRemove && take ? (
+ <InlineConfirmRow
+ question="Remove this take from the panel? The image stays in your gallery."
+ confirmText="Remove"
+ onConfirm={() => { setConfirmRemove(false); onRemoveTake(take.id); }}
+ onCancel={() => setConfirmRemove(false)}
+ autoFocus
+ />
+ ) : null}
+ <div className="flex flex-wrap gap-2">
+ <button type="button" className={actionButton} onClick={() => setGalleryOpen(true)} disabled={busy}>
+ <ImagePlus size={16} aria-hidden="true" /> Pick or upload
+ </button>
+ <button type="button" className={actionButton} onClick={onSketch} disabled={busy}>
+ {busy ? <Loader2 size={16} className="animate-spin" aria-hidden="true" /> : <PenLine size={16} aria-hidden="true" />} Sketch
+ </button>
+ {moodBoardId ? (
+ <button type="button" className={actionButton} onClick={() => setPinsOpen(true)} disabled={busy}>
+ <Palette size={16} aria-hidden="true" /> Mood board
+ </button>
+ ) : null}
+ {take ? (
+ <button type="button" className={`${actionButton} ml-auto hover:text-port-error`} onClick={() => setConfirmRemove(true)}>
+ <Trash2 size={16} aria-hidden="true" /> Take
+ </button>
+ ) : null}
+ </div>
+ <GalleryImagePicker
+ open={galleryOpen}
+ allowUpload
+ onClose={() => setGalleryOpen(false)}
+ onSelect={(image) => { if (image?.filename) onAddTake({ source: 'gallery', image: image.filename }); }}
+ />
+ <MoodBoardPinPicker
+ open={pinsOpen}
+ moodBoardId={moodBoardId}
+ onClose={() => setPinsOpen(false)}
+ onSelect={(pin) => onAddTake({ source: 'moodBoard', image: pin.filename, refId: moodBoardId })}
+ />
+ </div>
+ );
+}
+
+function ShotTab({ board, found, panelNumber, sketchNonce, busy, handlers }) {
+ const { panel, beat, beatIndex, index } = found;
+ const [confirmDelete, setConfirmDelete] = useState(false);
+ const fieldId = (name) => `panel-${panel.id}-${name}`;
+ const [secondsDraft, setSecondsDraft] = useState(panel.seconds ?? '');
+ useEffect(() => { setSecondsDraft(panel.seconds ?? ''); }, [panel.seconds]);
+
+ const commitSeconds = () => {
+ const raw = String(secondsDraft).trim();
+ const next = raw === '' ? null : Number(raw);
+ if (next !== null && (!Number.isFinite(next) || next <= 0 || next > STORYBOARD_LIMITS.panelSecondsMax)) {
+ setSecondsDraft(panel.seconds ?? '');
+ return;
+ }
+ if (next !== panel.seconds) handlers.onPatch({ seconds: next });
+ };
+
+ return (
+ <div className="space-y-3">
+ <ArtSection
+ panel={panel}
+ aspectRatio={board.aspectRatio}
+ sketchNonce={sketchNonce}
+ moodBoardId={board.moodBoardId}
+ busy={busy}
+ onAddTake={handlers.onAddTake}
+ onSelectTake={handlers.onSelectTake}
+ onRemoveTake={handlers.onRemoveTake}
+ onSketch={handlers.onSketch}
+ />
+ <div>
+ <label htmlFor={fieldId('action')} className={labelClass}>Action</label>
+ <CommitField id={fieldId('action')} multiline value={panel.action} maxLength={STORYBOARD_LIMITS.panelText}
+ placeholder="What we see" onCommit={(action) => handlers.onPatch({ action })} />
+ </div>
+ <div>
+ <label htmlFor={fieldId('dialogue')} className={labelClass}>Dialogue or lyric</label>
+ <CommitField id={fieldId('dialogue')} multiline value={panel.dialogue} maxLength={STORYBOARD_LIMITS.panelText}
+ onCommit={(dialogue) => handlers.onPatch({ dialogue })} />
+ </div>
+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
+ <div>
+ <label htmlFor={fieldId('framing')} className={labelClass}>Framing</label>
+ <select id={fieldId('framing')} value={panel.framing || ''}
+ onChange={(event) => handlers.onPatch({ framing: event.target.value || null })}
+ className="w-full min-h-[44px] bg-port-bg border border-port-border rounded px-2 text-sm text-white">
+ <option value="">Not set</option>
+ {SHOT_TYPES.map((type) => <option key={type} value={type}>{SHOT_TYPE_LABELS[type] || type}</option>)}
+ </select>
+ </div>
+ <div>
+ <label htmlFor={fieldId('seconds')} className={labelClass}>Seconds (estimate)</label>
+ <input id={fieldId('seconds')} type="number" inputMode="decimal" min="0.01" step="0.01" max={STORYBOARD_LIMITS.panelSecondsMax}
+ value={secondsDraft} onChange={(event) => setSecondsDraft(event.target.value)} onBlur={commitSeconds}
+ onKeyDown={(event) => { if (event.key === 'Enter') event.currentTarget.blur(); }}
+ className="w-full min-h-[44px] bg-port-bg border border-port-border rounded px-2 text-sm text-white tabular-nums" />
+ </div>
+ <div className="col-span-2 sm:col-span-1">
+ <label htmlFor={fieldId('camera')} className={labelClass}>Camera</label>
+ <CommitField id={fieldId('camera')} value={panel.camera} maxLength={STORYBOARD_LIMITS.camera}
+ placeholder="e.g. slow push in" onCommit={(camera) => handlers.onPatch({ camera })} />
+ </div>
+ </div>
+ <div className="flex flex-wrap items-center gap-2 border-t border-port-border pt-3">
+ <button type="button" className={iconButton} onClick={() => handlers.onMove({ index: index - 1 })} disabled={index === 0} aria-label="Move panel earlier">
+ <ChevronLeft size={18} />
+ </button>
+ <span className="text-xs text-gray-500 tabular-nums">Panel {panelNumber}</span>
+ <button type="button" className={iconButton} onClick={() => handlers.onMove({ index: index + 1 })} disabled={index >= beat.panels.length - 1} aria-label="Move panel later">
+ <ChevronRight size={18} />
+ </button>
+ {board.beats.length > 1 ? (
+ <>
+ <label htmlFor={fieldId('beat')} className="sr-only">Beat</label>
+ <select id={fieldId('beat')} value={beat.id}
+ onChange={(event) => handlers.onMove({ beatId: event.target.value, index: 10_000 })}
+ className="min-h-[44px] max-w-[12rem] bg-port-bg border border-port-border rounded px-2 text-sm text-white">
+ {board.beats.map((b, i) => <option key={b.id} value={b.id}>{`Beat ${i + 1}${b.title ? ` · ${b.title}` : ''}`}</option>)}
+ </select>
+ </>
+ ) : null}
+ <button type="button" className={`${iconButton} ml-auto hover:text-port-error`} onClick={() => setConfirmDelete(true)} aria-label="Delete panel">
+ <Trash2 size={18} />
+ </button>
+ </div>
+ {confirmDelete ? (
+ <InlineConfirmRow
+ question={`Delete panel ${panelNumber} from beat ${beatIndex + 1}?`}
+ onConfirm={() => { setConfirmDelete(false); handlers.onDelete(); }}
+ onCancel={() => setConfirmDelete(false)}
+ autoFocus
+ />
+ ) : null}
+ </div>
+ );
+}
+
+function CastTab({ panel, onPatch }) {
+ const [names, setNames] = useState({});
+ const [picking, setPicking] = useState(null);
+ const allIds = useMemo(() => REF_GROUPS.flatMap(({ field }) => panel[field]), [panel]);
+ const idsKey = allIds.join('|');
+
+ useEffect(() => {
+ const missing = idsKey ? idsKey.split('|').filter((id) => !(id in names)) : [];
+ if (!missing.length) return undefined;
+ let active = true;
+ listCatalogIngredientsByIds(missing, { silent: true })
+ .then((items) => {
+ if (!active) return;
+ setNames((prev) => {
+ const next = { ...prev };
+ for (const id of missing) next[id] = null;
+ for (const item of items) next[item.id] = item.name || null;
+ return next;
+ });
+ })
+ .catch(() => {});
+ return () => { active = false; };
+ }, [idsKey]); // `names` is the cache this effect fills, so it is not a dependency
+
+ const group = REF_GROUPS.find((g) => g.field === picking);
+
+ return (
+ <div className="space-y-4">
+ {REF_GROUPS.map(({ field, label, icon: Icon }) => (
+ <section key={field} aria-label={label}>
+ <div className="flex items-center gap-2 mb-1">
+ <Icon size={14} className="text-gray-500" aria-hidden="true" />
+ <h3 className="text-xs font-medium text-gray-300">{label}</h3>
+ <button type="button" className={`${iconButton} ml-auto`} onClick={() => setPicking(field)} aria-label={`Add ${label.toLowerCase()}`}>
+ <Plus size={16} />
+ </button>
+ </div>
+ {panel[field].length ? (
+ <ul className="flex flex-wrap gap-1.5">
+ {panel[field].map((id) => (
+ <li key={id} className="inline-flex items-center gap-1 rounded-full border border-port-border bg-port-bg pl-3 text-sm text-gray-200">
+ <span className="truncate max-w-[12rem]">{names[id] || (id in names ? 'Missing record' : '…')}</span>
+ <button type="button" onClick={() => onPatch({ [field]: panel[field].filter((x) => x !== id) })}
+ className="min-h-[36px] min-w-[36px] inline-flex items-center justify-center rounded-full text-gray-500 hover:text-port-error"
+ aria-label={`Remove ${names[id] || 'record'}`}>
+ <X size={14} />
+ </button>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="text-xs text-gray-600">None</p>
+ )}
+ </section>
+ ))}
+ <IngredientPicker
+ open={!!group}
+ type={group?.type}
+ multi
+ excludeIds={group ? panel[group.field] : []}
+ onClose={() => setPicking(null)}
+ onSelect={(items) => {
+ if (!group) return;
+ const picked = (Array.isArray(items) ? items : [items]).filter(Boolean);
+ setNames((prev) => ({ ...prev, ...Object.fromEntries(picked.map((item) => [item.id, item.name || null])) }));
+ onPatch({ [group.field]: [...panel[group.field], ...picked.map((item) => item.id)].slice(0, STORYBOARD_LIMITS.refs) });
+ setPicking(null);
+ }}
+ />
+ </div>
+ );
+}
+
+/**
+ * The open panel, deep-linked at `/storyboards/:id/panel/:panelId` with the
+ * tab in `?panelTab=`. Every field saves on its own; the parent applies the
+ * board each write returns.
+ */
+export default function PanelDrawer({ open, board, found, panelNumber, sketchNonce, busy, onClose, handlers }) {
+ const [activeTab, setActiveTab] = useDrawerTab('panelTab', 'shot', TAB_IDS);
+
+ return (
+ <Drawer
+ open={open}
+ onClose={onClose}
+ title={found ? `Panel ${panelNumber}` : 'Panel'}
+ subtitle={found ? (found.beat.title || `Beat ${found.beatIndex + 1}`) : undefined}
+ size="md"
+ tabs={found ? TABS : null}
+ activeTab={activeTab}
+ onTabChange={setActiveTab}
+ closeLabel="Close panel"
+ >
+ {!found ? (
+ <p className="text-sm text-gray-400">This panel is no longer on the storyboard.</p>
+ ) : activeTab === 'cast' ? (
+ <CastTab panel={found.panel} onPatch={handlers.onPatch} />
+ ) : activeTab === 'notes' ? (
+ <div>
+ <label htmlFor={`panel-${found.panel.id}-notes`} className={labelClass}>Notes</label>
+ <CommitField id={`panel-${found.panel.id}-notes`} multiline minHeightClass="min-h-[10rem]" value={found.panel.notes}
+ maxLength={STORYBOARD_LIMITS.notes} onCommit={(notes) => handlers.onPatch({ notes })} />
+ </div>
+ ) : (
+ <ShotTab board={board} found={found} panelNumber={panelNumber} sketchNonce={sketchNonce} busy={busy} handlers={handlers} />
+ )}
+ </Drawer>
+ );
+}
diff --git a/client/src/components/storyboards/storyboardArt.js b/client/src/components/storyboards/storyboardArt.js
new file mode 100644
index 0000000000..b236f2b98e
--- /dev/null
+++ b/client/src/components/storyboards/storyboardArt.js
@@ -0,0 +1,50 @@
+// Display helpers shared by the Storyboards index, editor and panel drawer.
+
+const enc = encodeURIComponent;
+
+export const selectedTake = (panel) => panel?.takes?.find((take) => take.id === panel.selectedTakeId) || null;
+
+// A sketch's flattened PNG is served by the media sketch service; `nonce`
+// busts the browser cache after a save (bumped on `media:sketch:updated`).
+export function takeSrc(take, nonce = 0) {
+ if (take?.sketchKey) return `/api/media/sketches/${enc(take.sketchKey)}/png?v=${nonce}`;
+ if (take?.image) return `/data/images/${enc(take.image)}`;
+ return null;
+}
+
+export const ASPECT_CLASS = Object.freeze({
+ '16:9': 'aspect-video',
+ '9:16': 'aspect-[9/16]',
+ '1:1': 'aspect-square',
+ '4:5': 'aspect-[4/5]',
+ '2.39:1': 'aspect-[239/100]',
+});
+
+export const aspectClass = (ratio) => ASPECT_CLASS[ratio] || ASPECT_CLASS['16:9'];
+
+// Panel seconds are hundredths (the sanitizer rounds them).
+export const formatPanelSeconds = (sec) => (Number.isFinite(sec) && sec > 0 ? `${sec.toFixed(2)}s` : null);
+
+export const beatSeconds = (beat) => (beat?.panels || []).reduce((sum, panel) => sum + (panel.seconds || 0), 0);
+
+export const MUSICAL_ROLE_LABELS = Object.freeze({
+ intro: 'Intro',
+ verse: 'Verse',
+ 'pre-chorus': 'Pre-chorus',
+ chorus: 'Chorus',
+ bridge: 'Bridge',
+ build: 'Build',
+ drop: 'Drop',
+ breakdown: 'Breakdown',
+ instrumental: 'Instrumental',
+ outro: 'Outro',
+});
+
+/** Find a panel and its beat by id, or null. */
+export function findPanel(board, panelId) {
+ for (const [beatIndex, beat] of (board?.beats || []).entries()) {
+ const index = beat.panels.findIndex((panel) => panel.id === panelId);
+ if (index >= 0) return { beat, beatIndex, panel: beat.panels[index], index };
+ }
+ return null;
+}
diff --git a/client/src/lib/layoutRoutes.js b/client/src/lib/layoutRoutes.js
index 4da3cf9ccc..a507ad0e4f 100644
--- a/client/src/lib/layoutRoutes.js
+++ b/client/src/lib/layoutRoutes.js
@@ -55,6 +55,7 @@ const EXACT_FULL_WIDTH_PATHS = [
'/decks',
'/fableloom',
'/mood-boards',
+ '/storyboards',
'/creative-commission',
'/creative-commission/new',
'/importer',
@@ -68,6 +69,8 @@ const FULL_WIDTH_PATH_PREFIXES = [
'/x/',
'/privacy/',
'/code-animation/',
+ // The storyboard editor owns its scroll (header over a flex-1 overflow-auto body).
+ '/storyboards/',
'/ask/',
'/calendar',
// Catalog detail (/catalog/{type}/{id}) and Ingest (/catalog/ingest)
diff --git a/client/src/lib/navPresentation.js b/client/src/lib/navPresentation.js
index 4df253035d..a8003f5da8 100644
--- a/client/src/lib/navPresentation.js
+++ b/client/src/lib/navPresentation.js
@@ -26,6 +26,7 @@ import { AudioLines,
Film,
MessageSquare,
Palette,
+ LayoutPanelLeft,
Spade,
PenLine,
Sparkles,
@@ -187,6 +188,7 @@ export const NAV_PRESENTATION = {
'/media': { icon: Layers },
'/decks': { icon: Spade },
'/mood-boards': { icon: Palette },
+ '/storyboards': { icon: LayoutPanelLeft },
'/music': { icon: Mic },
'/music-video': { icon: Music },
'/rounds': { icon: Music },
diff --git a/client/src/pages/StoryboardDetail.jsx b/client/src/pages/StoryboardDetail.jsx
new file mode 100644
index 0000000000..e9c8ed6fc9
--- /dev/null
+++ b/client/src/pages/StoryboardDetail.jsx
@@ -0,0 +1,271 @@
+/**
+ * Storyboard editor — `/storyboards/:id`, with the open panel deep-linked at
+ * `/storyboards/:id/panel/:panelId` and the view in `?view=board`.
+ *
+ * Beats view: one row per beat (title, musical role, estimated length) with a
+ * strip of panels. Board view: every panel as one sheet, the classic
+ * storyboard page. Each write returns the whole board, and the page keeps the
+ * newest one it has seen (`updatedAt`), so two quick edits can't land out of
+ * order.
+ */
+
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
+import { ArrowLeft, LayoutGrid, LayoutPanelLeft, Loader2, Plus, Rows3 } from 'lucide-react';
+import TabPills from '../components/ui/TabPills';
+import toast from '../components/ui/Toast';
+import socket from '../services/socket';
+import {
+ addStoryboardBeat, addStoryboardPanel, addStoryboardPanelTake, createBlankSketch, deleteStoryboardBeat,
+ deleteStoryboardPanel, getStoryboard, listMoodBoardNames, moveStoryboardBeat, moveStoryboardPanel,
+ removeStoryboardPanelTake, selectStoryboardPanelTake, updateStoryboard, updateStoryboardBeat, updateStoryboardPanel,
+} from '../services/api';
+import { formatTimecode } from '../utils/formatters';
+import { STORYBOARD_ASPECT_RATIOS, STORYBOARD_LIMITS } from '../../../server/lib/storyboardVocabulary.js';
+import BeatSection from '../components/storyboards/BeatSection';
+import CommitField from '../components/storyboards/CommitField';
+import PanelCard from '../components/storyboards/PanelCard';
+import PanelDrawer from '../components/storyboards/PanelDrawer';
+import { beatSeconds, findPanel } from '../components/storyboards/storyboardArt';
+
+const VIEW_TABS = [
+ { id: 'beats', label: 'Beats', icon: Rows3 },
+ { id: 'board', label: 'Board', icon: LayoutGrid },
+];
+
+const selectClass = 'min-h-[44px] bg-port-bg border border-port-border rounded px-2 text-sm text-white';
+
+export default function StoryboardDetail() {
+ const { id, panelId } = useParams();
+ const navigate = useNavigate();
+ const [searchParams] = useSearchParams();
+ const view = searchParams.get('view') === 'board' ? 'board' : 'beats';
+ const viewSuffix = view === 'board' ? '?view=board' : '';
+ // undefined = loading, null = missing.
+ const [board, setBoard] = useState(undefined);
+ const [pending, setPending] = useState(null);
+ const [moodBoards, setMoodBoards] = useState([]);
+ const [sketchNonces, setSketchNonces] = useState({});
+ const mountNonceRef = useRef(Date.now());
+
+ useEffect(() => {
+ let active = true;
+ setBoard(undefined);
+ getStoryboard(id, { silent: true })
+ .then((next) => { if (active) setBoard(next); })
+ .catch(() => { if (active) setBoard(null); });
+ return () => { active = false; };
+ }, [id]);
+
+ useEffect(() => {
+ let active = true;
+ listMoodBoardNames({ silent: true })
+ .then((rows) => { if (active) setMoodBoards(Array.isArray(rows) ? rows : []); })
+ .catch(() => {});
+ return () => { active = false; };
+ }, []);
+
+ useEffect(() => {
+ const onSketchUpdated = ({ key } = {}) => {
+ if (key) setSketchNonces((prev) => ({ ...prev, [key]: (prev[key] || mountNonceRef.current) + 1 }));
+ };
+ socket.on('media:sketch:updated', onSketchUpdated);
+ return () => socket.off('media:sketch:updated', onSketchUpdated);
+ }, []);
+ const sketchNonce = useCallback((key) => (key ? sketchNonces[key] || mountNonceRef.current : 0), [sketchNonces]);
+
+ // Keep the newest board: a slower earlier write must not undo a later one.
+ const apply = useCallback((res) => {
+ const next = res?.board ?? res;
+ if (next?.id !== id) return res;
+ setBoard((prev) => (prev && prev.updatedAt > next.updatedAt ? prev : next));
+ return res;
+ }, [id]);
+
+ // The request helper toasts a failure; null tells the caller it failed.
+ const write = useCallback((call) => call().then(apply).catch(() => null), [apply]);
+
+ const panelNumbers = useMemo(() => {
+ const numbers = new Map();
+ let n = 1;
+ for (const beat of board?.beats || []) for (const panel of beat.panels) numbers.set(panel.id, n++);
+ return numbers;
+ }, [board]);
+
+ const openPanel = (pid) => navigate(`/storyboards/${id}/panel/${pid}${viewSuffix}`);
+ const closePanel = () => navigate(`/storyboards/${id}${viewSuffix}`);
+ const setView = (next) => navigate(`/storyboards/${id}${panelId ? `/panel/${panelId}` : ''}${next === 'board' ? '?view=board' : ''}`, { replace: true });
+
+ const addBeat = async () => {
+ setPending('beat');
+ await write(() => addStoryboardBeat(id, {}));
+ setPending(null);
+ };
+
+ const addPanel = async (beatId) => {
+ setPending(`panel:${beatId}`);
+ const res = await write(() => addStoryboardPanel(id, beatId, {}));
+ setPending(null);
+ if (res?.panelId) openPanel(res.panelId);
+ };
+
+ const found = board && panelId ? findPanel(board, panelId) : null;
+
+ const panelHandlers = {
+ onPatch: (patch) => write(() => updateStoryboardPanel(id, panelId, patch)),
+ onAddTake: (take) => write(() => addStoryboardPanelTake(id, panelId, take)),
+ onSelectTake: (takeId) => write(() => selectStoryboardPanelTake(id, panelId, takeId)),
+ onRemoveTake: (takeId) => write(() => removeStoryboardPanelTake(id, panelId, takeId)),
+ onMove: (target) => write(() => moveStoryboardPanel(id, panelId, target)),
+ onDelete: async () => {
+ const res = await write(() => deleteStoryboardPanel(id, panelId));
+ if (res) closePanel();
+ },
+ // A blank sketch is minted server-side, added as the panel's take, then
+ // drawn on the annotate page, which returns here.
+ onSketch: async () => {
+ setPending('sketch');
+ const minted = await createBlankSketch({ silent: true }).catch(() => null);
+ if (!minted?.key) {
+ setPending(null);
+ toast.error('Could not start a sketch');
+ return;
+ }
+ const res = await write(() => addStoryboardPanelTake(id, panelId, { source: 'sketch', sketchKey: minted.key }));
+ setPending(null);
+ if (!res) return;
+ const returnTo = `/storyboards/${id}/panel/${panelId}${viewSuffix}`;
+ navigate(`/media/annotate/${encodeURIComponent(minted.key)}?returnTo=${encodeURIComponent(returnTo)}`);
+ },
+ };
+
+ if (board === undefined) {
+ return (
+ <div className="flex h-full items-center justify-center text-gray-500">
+ <Loader2 className="w-5 h-5 animate-spin" aria-label="Loading storyboard" />
+ </div>
+ );
+ }
+
+ if (board === null) {
+ return (
+ <div className="p-6 text-center space-y-3">
+ <p className="text-gray-300">This storyboard doesn't exist or was deleted.</p>
+ <Link to="/storyboards" className="text-port-accent hover:underline">All storyboards</Link>
+ </div>
+ );
+ }
+
+ const runtime = board.beats.reduce((sum, beat) => sum + beatSeconds(beat), 0);
+ const missingMoodBoard = board.moodBoardId && !moodBoards.some((m) => m.id === board.moodBoardId);
+ let firstPanelNumber = 1;
+
+ return (
+ <div className="flex h-full min-h-0 flex-col">
+ <header className="shrink-0 border-b border-port-border px-2 py-2 sm:px-4 space-y-2">
+ {/* The name is edited in place, so the page heading is for screen readers. */}
+ <h1 className="sr-only">{board.name}</h1>
+ <div className="flex items-center gap-1 sm:gap-2">
+ <Link to="/storyboards" aria-label="All storyboards"
+ className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center rounded text-gray-400 hover:text-white">
+ <ArrowLeft size={18} />
+ </Link>
+ <LayoutPanelLeft className="hidden sm:block w-6 h-6 shrink-0 text-port-accent" aria-hidden="true" />
+ <div className="flex-1 min-w-0">
+ <CommitField id="storyboard-name" value={board.name} maxLength={STORYBOARD_LIMITS.name} ariaLabel="Storyboard name"
+ onCommit={(name) => write(() => updateStoryboard(id, { name }))} className="text-base font-semibold" />
+ </div>
+ <span className="text-sm text-gray-400 tabular-nums shrink-0" title="Estimated runtime">{formatTimecode(runtime)}</span>
+ <TabPills tabs={VIEW_TABS} activeTab={view} onChange={setView} variant="pills" size="sm" mobileCompact ariaLabel="Storyboard view" />
+ </div>
+ <div className="flex flex-wrap items-start gap-2">
+ <div className="flex-1 min-w-[14rem]">
+ <CommitField id="storyboard-logline" multiline value={board.logline} maxLength={STORYBOARD_LIMITS.logline}
+ placeholder="Logline: the story in a sentence" ariaLabel="Logline" minHeightClass="min-h-[2.75rem]"
+ onCommit={(logline) => write(() => updateStoryboard(id, { logline }))} />
+ </div>
+ <label htmlFor="storyboard-aspect" className="sr-only">Aspect ratio</label>
+ <select id="storyboard-aspect" value={board.aspectRatio} className={selectClass}
+ onChange={(event) => write(() => updateStoryboard(id, { aspectRatio: event.target.value }))}>
+ {STORYBOARD_ASPECT_RATIOS.map((ratio) => <option key={ratio} value={ratio}>{ratio}</option>)}
+ </select>
+ <label htmlFor="storyboard-mood-board" className="sr-only">Mood board</label>
+ <select id="storyboard-mood-board" value={board.moodBoardId || ''} className={`${selectClass} max-w-[12rem]`}
+ onChange={(event) => write(() => updateStoryboard(id, { moodBoardId: event.target.value || null }))}>
+ <option value="">No mood board</option>
+ {missingMoodBoard ? <option value={board.moodBoardId}>Missing mood board</option> : null}
+ {moodBoards.map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}
+ </select>
+ </div>
+ </header>
+
+ <div className="flex-1 min-h-0 overflow-auto p-2 sm:p-4">
+ {board.beats.length === 0 ? (
+ <div className="py-10 text-center space-y-3">
+ <p className="text-sm text-gray-400">Start with the first story beat.</p>
+ <button type="button" onClick={addBeat} disabled={pending === 'beat'}
+ className="min-h-[44px] inline-flex items-center gap-1.5 px-4 rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50">
+ <Plus size={16} aria-hidden="true" /> Beat
+ </button>
+ </div>
+ ) : view === 'board' ? (
+ <ol className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-2" aria-label="All panels">
+ {board.beats.flatMap((beat, beatIndex) => beat.panels.map((panel, index) => (
+ <li key={panel.id}>
+ <PanelCard
+ panel={panel}
+ number={panelNumbers.get(panel.id)}
+ aspectRatio={board.aspectRatio}
+ selected={panel.id === panelId}
+ sketchNonce={sketchNonce}
+ caption={index === 0 ? (beat.title || `Beat ${beatIndex + 1}`) : null}
+ onOpen={() => openPanel(panel.id)}
+ />
+ </li>
+ )))}
+ </ol>
+ ) : (
+ <div className="space-y-3">
+ {board.beats.map((beat, beatIndex) => {
+ const first = firstPanelNumber;
+ firstPanelNumber += beat.panels.length;
+ return (
+ <BeatSection
+ key={beat.id}
+ beat={beat}
+ beatIndex={beatIndex}
+ beatCount={board.beats.length}
+ firstPanelNumber={first}
+ aspectRatio={board.aspectRatio}
+ selectedPanelId={panelId}
+ sketchNonce={sketchNonce}
+ addingPanel={pending === `panel:${beat.id}`}
+ onUpdate={(patch) => write(() => updateStoryboardBeat(id, beat.id, patch))}
+ onMove={(index) => write(() => moveStoryboardBeat(id, beat.id, index))}
+ onDelete={() => write(() => deleteStoryboardBeat(id, beat.id))}
+ onAddPanel={() => addPanel(beat.id)}
+ onOpenPanel={openPanel}
+ />
+ );
+ })}
+ <button type="button" onClick={addBeat} disabled={pending === 'beat'}
+ className="w-full min-h-[44px] rounded-xl border border-dashed border-port-border text-sm text-gray-400 hover:text-white hover:border-port-accent/60 inline-flex items-center justify-center gap-1.5 disabled:opacity-50">
+ <Plus size={16} aria-hidden="true" /> Beat
+ </button>
+ </div>
+ )}
+ </div>
+
+ <PanelDrawer
+ open={!!panelId}
+ board={board}
+ found={found}
+ panelNumber={found ? panelNumbers.get(found.panel.id) : null}
+ sketchNonce={sketchNonce}
+ busy={pending === 'sketch'}
+ onClose={closePanel}
+ handlers={panelHandlers}
+ />
+ </div>
+ );
+}
diff --git a/client/src/pages/StoryboardDetail.test.jsx b/client/src/pages/StoryboardDetail.test.jsx
new file mode 100644
index 0000000000..c496497d89
--- /dev/null
+++ b/client/src/pages/StoryboardDetail.test.jsx
@@ -0,0 +1,119 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter, Route, Routes, useLocation } from 'react-router';
+import StoryboardDetail from './StoryboardDetail';
+
+const api = vi.hoisted(() => ({
+ getStoryboard: vi.fn(),
+ listMoodBoardNames: vi.fn(),
+ updateStoryboard: vi.fn(),
+ addStoryboardBeat: vi.fn(),
+ addStoryboardPanel: vi.fn(),
+ updateStoryboardPanel: vi.fn(),
+ addStoryboardPanelTake: vi.fn(),
+ createBlankSketch: vi.fn(),
+}));
+vi.mock('../services/api', () => {
+ const rest = ['deleteStoryboardBeat', 'deleteStoryboardPanel', 'moveStoryboardBeat', 'moveStoryboardPanel',
+ 'removeStoryboardPanelTake', 'selectStoryboardPanelTake', 'updateStoryboardBeat', 'listCatalogIngredientsByIds', 'getMoodBoard'];
+ return { ...api, ...Object.fromEntries(rest.map((name) => [name, vi.fn(() => Promise.resolve([]))])) };
+});
+vi.mock('../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } }));
+vi.mock('../components/imageGen/GalleryImagePicker', () => ({ default: () => null }));
+vi.mock('../components/IngredientPicker', () => ({ default: () => null }));
+vi.mock('../components/ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
+
+const panel = (id, extra = {}) => ({
+ id, action: '', dialogue: '', framing: null, camera: '', seconds: null,
+ castIds: [], environmentIds: [], objectIds: [], notes: '', takes: [], selectedTakeId: null, ...extra,
+});
+const board = (extra = {}) => ({
+ id: 'sb-1', name: 'Here to Dance', logline: '', aspectRatio: '16:9', artStyle: 'pencil',
+ universeId: null, moodBoardId: null, createdAt: '2026-10-22T00:00:00.000Z', updatedAt: '2026-10-22T00:00:01.000Z',
+ beats: [{ id: 'beat-1', title: 'Opening', what: '', why: '', emotion: '', musicalRole: 'intro', sectionHint: '', panels: [panel('panel-1')] }],
+ ...extra,
+});
+
+function LocationProbe() {
+ const location = useLocation();
+ return <div data-testid="location">{location.pathname}{location.search}</div>;
+}
+
+const renderAt = (path) => render(
+ <MemoryRouter initialEntries={[path]}>
+ <Routes>
+ <Route path="/storyboards/:id" element={<StoryboardDetail />} />
+ <Route path="/storyboards/:id/panel/:panelId" element={<StoryboardDetail />} />
+ <Route path="*" element={null} />
+ </Routes>
+ <LocationProbe />
+ </MemoryRouter>,
+);
+
+beforeEach(() => {
+ for (const fn of Object.values(api)) fn.mockReset();
+ api.listMoodBoardNames.mockResolvedValue([]);
+});
+
+describe('StoryboardDetail', () => {
+ it('keeps the newest board when an earlier save answers last', async () => {
+ api.getStoryboard.mockResolvedValue(board());
+ let resolveOlder;
+ api.updateStoryboard
+ .mockImplementationOnce(() => new Promise((resolve) => { resolveOlder = resolve; }))
+ .mockImplementationOnce(() => Promise.resolve(board({ name: 'Second', updatedAt: '2026-10-22T00:00:03.000Z' })));
+ renderAt('/storyboards/sb-1');
+
+ const name = await screen.findByLabelText('Storyboard name');
+ fireEvent.change(name, { target: { value: 'First' } });
+ fireEvent.blur(name);
+ fireEvent.change(name, { target: { value: 'Second' } });
+ fireEvent.blur(name);
+ await waitFor(() => expect(name.value).toBe('Second'));
+
+ await act(async () => { resolveOlder(board({ name: 'First', updatedAt: '2026-10-22T00:00:02.000Z' })); });
+ expect(name.value).toBe('Second');
+ });
+
+ it('opens a new panel at its deep link and saves its action on blur', async () => {
+ api.getStoryboard.mockResolvedValue(board());
+ const withPanel = board({
+ updatedAt: '2026-10-22T00:00:02.000Z',
+ beats: [{ ...board().beats[0], panels: [panel('panel-1'), panel('panel-2')] }],
+ });
+ api.addStoryboardPanel.mockResolvedValue({ board: withPanel, panelId: 'panel-2' });
+ api.updateStoryboardPanel.mockImplementation((_id, _panelId, patch) => Promise.resolve(board({
+ updatedAt: '2026-10-22T00:00:03.000Z',
+ beats: [{ ...board().beats[0], panels: [panel('panel-1'), panel('panel-2', patch)] }],
+ })));
+ renderAt('/storyboards/sb-1');
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Panel' }));
+ await waitFor(() => expect(screen.getByTestId('location').textContent).toBe('/storyboards/sb-1/panel/panel-2'));
+ expect(api.addStoryboardPanel).toHaveBeenCalledWith('sb-1', 'beat-1', {});
+
+ const action = await screen.findByLabelText('Action');
+ fireEvent.change(action, { target: { value: 'She laces her skates' } });
+ fireEvent.blur(action);
+ await waitFor(() => expect(api.updateStoryboardPanel).toHaveBeenCalledWith('sb-1', 'panel-2', { action: 'She laces her skates' }));
+ expect(await screen.findByRole('button', { name: 'Open panel 2: She laces her skates' })).toBeTruthy();
+ });
+
+ it('starts a sketch as a panel take and returns to the panel after drawing', async () => {
+ api.getStoryboard.mockResolvedValue(board());
+ api.createBlankSketch.mockResolvedValue({ key: 'sketch:abc-123' });
+ api.addStoryboardPanelTake.mockResolvedValue({ board: board({ updatedAt: '2026-10-22T00:00:02.000Z' }), takeId: 'take-1' });
+ renderAt('/storyboards/sb-1/panel/panel-1');
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Sketch' }));
+ await waitFor(() => expect(screen.getByTestId('location').textContent)
+ .toBe(`/media/annotate/sketch%3Aabc-123?returnTo=${encodeURIComponent('/storyboards/sb-1/panel/panel-1')}`));
+ expect(api.addStoryboardPanelTake).toHaveBeenCalledWith('sb-1', 'panel-1', { source: 'sketch', sketchKey: 'sketch:abc-123' });
+ });
+
+ it('says so when the linked panel is gone', async () => {
+ api.getStoryboard.mockResolvedValue(board());
+ renderAt('/storyboards/sb-1/panel/panel-missing');
+ expect(await screen.findByText('This panel is no longer on the storyboard.')).toBeTruthy();
+ });
+});
diff --git a/client/src/pages/Storyboards.jsx b/client/src/pages/Storyboards.jsx
new file mode 100644
index 0000000000..bebd31ccb3
--- /dev/null
+++ b/client/src/pages/Storyboards.jsx
@@ -0,0 +1,135 @@
+/**
+ * Storyboards index — Create › Storyboards.
+ *
+ * A storyboard plans a production as beats of panels before (or without) a
+ * song or an edit; Music Video, Video, FableLoom and Series Pipeline link one
+ * rather than keeping a private plan. "New" creates a blank board and opens it.
+ */
+
+import { useRef, useState } from 'react';
+import { Link, useNavigate } from 'react-router';
+import { LayoutPanelLeft, Plus, Trash2 } from 'lucide-react';
+import PageHeader from '../components/PageHeader';
+import PageSkeleton from '../components/ui/PageSkeleton';
+import EmptyState from '../components/EmptyState';
+import InlineConfirmRow from '../components/ui/InlineConfirmRow';
+import CollapsibleListItem from '../components/ui/CollapsibleListItem';
+import ListLoadError from '../components/ui/ListLoadError';
+import toast from '../components/ui/Toast';
+import useListResource from '../hooks/useListResource';
+import { createStoryboard, deleteStoryboard, listStoryboards } from '../services/api';
+import { formatCount, formatTimecode, timeAgo } from '../utils/formatters';
+import { aspectClass, takeSrc } from '../components/storyboards/storyboardArt';
+
+const fetchStoryboards = () => listStoryboards({ silent: true });
+
+function StoryboardCard({ board, mountNonce, confirming, onAskDelete, onCancelDelete, onDelete }) {
+ const cover = takeSrc(board.cover, mountNonce);
+ return (
+ <div className="h-full bg-port-card border border-port-border rounded-xl overflow-hidden flex flex-col hover:border-port-accent/40 transition-colors">
+ {confirming ? (
+ <InlineConfirmRow
+ variant="separator"
+ question={`Delete "${board.name}"?`}
+ onConfirm={() => onDelete(board.id)}
+ onCancel={onCancelDelete}
+ autoFocus
+ />
+ ) : null}
+ <Link to={`/storyboards/${board.id}`} className={`block ${aspectClass(board.aspectRatio)} max-h-56 w-full bg-port-bg overflow-hidden`}>
+ {cover ? (
+ <img src={cover} alt="" loading="lazy" className="w-full h-full object-cover" />
+ ) : (
+ <span className="w-full h-full flex items-center justify-center">
+ <LayoutPanelLeft className="w-10 h-10 text-gray-600 stroke-[1.5]" aria-hidden="true" />
+ </span>
+ )}
+ </Link>
+ <div className="p-3 flex-1 flex flex-col gap-1.5">
+ <Link to={`/storyboards/${board.id}`} className="text-white font-medium hover:text-port-accent line-clamp-1">{board.name}</Link>
+ {board.logline ? <p className="text-xs text-gray-400 line-clamp-2">{board.logline}</p> : null}
+ <div className="mt-auto flex items-center gap-2 pt-1 text-xs text-gray-500">
+ <span className="tabular-nums">{formatCount(board.beatCount, { fallback: '0' })} beats · {formatCount(board.panelCount, { fallback: '0' })} panels · {formatTimecode(board.runtimeSec)}</span>
+ <span className="truncate">· {timeAgo(board.updatedAt)}</span>
+ <button type="button" onClick={() => onAskDelete(board.id)} aria-label={`Delete ${board.name}`}
+ className="ml-auto min-h-[44px] min-w-[44px] inline-flex items-center justify-center rounded text-gray-500 hover:text-port-error">
+ <Trash2 className="w-4 h-4" aria-hidden="true" />
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export default function Storyboards() {
+ const navigate = useNavigate();
+ const { items: boards, state, error, retry, setItems: setBoards } = useListResource(fetchStoryboards);
+ const [creating, setCreating] = useState(false);
+ const [confirmingId, setConfirmingId] = useState(null);
+ const [removingIds, setRemovingIds] = useState(() => new Set());
+ const mountNonceRef = useRef(Date.now());
+
+ const handleCreate = async () => {
+ if (creating) return;
+ setCreating(true);
+ const board = await createStoryboard({}, { silent: true }).catch(() => null);
+ setCreating(false);
+ if (!board) { toast.error('Failed to create storyboard'); return; }
+ navigate(`/storyboards/${board.id}`);
+ };
+
+ const handleDelete = async (id) => {
+ setConfirmingId(null);
+ const ok = await deleteStoryboard(id, { silent: true }).then(() => true).catch(() => false);
+ if (!ok) { toast.error('Failed to delete storyboard'); return; }
+ setRemovingIds((prev) => new Set(prev).add(id));
+ };
+
+ const newButton = (
+ <button type="button" onClick={handleCreate} disabled={creating}
+ className="min-h-[44px] flex items-center gap-1.5 px-3 text-sm rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50">
+ <Plus className="w-4 h-4" aria-hidden="true" /> New
+ </button>
+ );
+
+ return (
+ <div className="flex h-full min-h-0 flex-col">
+ <PageHeader icon={LayoutPanelLeft} title="Storyboards" subtitle="Plan story beats and panels before the song or the edit." actions={newButton} />
+ <div className="flex-1 min-h-0 overflow-auto p-3 sm:p-4">
+ {state === 'error' ? (
+ <ListLoadError what="storyboards" error={error} onRetry={retry} />
+ ) : state === 'loading' ? (
+ <PageSkeleton header="none" label="Loading storyboards" cards={4} sidebar={false} />
+ ) : boards.length === 0 ? (
+ <EmptyState
+ icon={LayoutPanelLeft}
+ title="No storyboards yet"
+ message="Lay out the beats of a story as panels, then link the board to a music video or video."
+ actionLabel="New storyboard"
+ onAction={handleCreate}
+ />
+ ) : (
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-4">
+ {boards.map((board) => (
+ <CollapsibleListItem
+ key={board.id}
+ removing={removingIds.has(board.id)}
+ spacing="1rem"
+ onExited={() => setBoards((prev) => prev.filter((b) => b.id !== board.id))}
+ >
+ <StoryboardCard
+ board={board}
+ mountNonce={mountNonceRef.current}
+ confirming={confirmingId === board.id}
+ onAskDelete={setConfirmingId}
+ onCancelDelete={() => setConfirmingId(null)}
+ onDelete={handleDelete}
+ />
+ </CollapsibleListItem>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 5829bdd129..a44f176339 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -87,6 +87,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiMeatspace.js` | MeatSpace health, genome, POST, memory-practice, and atomic POST training-run APIs. |
| `apiMortalLoom.js` | Mortality tracking. |
| `apiMoodBoard.js` | Mood boards (inspiration canvas + items), `listMoodBoardNames()` for pickers, `composeMoodBoardPrompt()` which stores the board's composite style prompt. |
+| `apiStoryboards.js` | Storyboards (Create › Storyboards): board/beat/panel CRUD and moves, panel art takes (add, select, remove); every write returns the whole board. |
| `apiTribe.js` | Tribe people (relationship rings + contacts), plus `getTribeDuplicateIdentifiers()` (`GET /tribe/duplicate-identifiers`): a non-blocking report of emails/phones shared by more than one person. |
| `apiTimeline.js` | Human-activity timeline: `/timeline/day`. |
| `apiCalendar.js` | Calendar events. |
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 82a29a3887..bef1be4217 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -87,6 +87,7 @@ export * from './apiContinuousVideo.js';
export * from './apiSprites.js';
export * from './apiShell.js';
export * from './apiMoodBoard.js';
+export * from './apiStoryboards.js';
export * from './apiDecks.js';
export * from './apiThreejsModels.js';
export * from './apiCodeAnimation.js';
diff --git a/client/src/services/apiStoryboards.js b/client/src/services/apiStoryboards.js
new file mode 100644
index 0000000000..9696c922bb
--- /dev/null
+++ b/client/src/services/apiStoryboards.js
@@ -0,0 +1,44 @@
+import { request } from './apiCore.js';
+
+// Storyboards — the shared Create › Storyboards planning board (beats → panels,
+// panel art as takes). Every write returns the whole sanitized board, so callers
+// replace their local copy with the response instead of patching it.
+
+const enc = encodeURIComponent;
+const json = (method, body) => ({ method, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
+
+export const listStoryboards = (options) => request('/storyboards', options);
+export const getStoryboard = (id, options) => request(`/storyboards/${enc(id)}`, options);
+export const createStoryboard = (data, options) => request('/storyboards', { ...json('POST', data), ...options });
+export const updateStoryboard = (id, patch, options) =>
+ request(`/storyboards/${enc(id)}`, { ...json('PATCH', patch), ...options });
+export const deleteStoryboard = (id, options) => request(`/storyboards/${enc(id)}`, { method: 'DELETE', ...options });
+
+// → { board, beatId }
+export const addStoryboardBeat = (id, data, options) =>
+ request(`/storyboards/${enc(id)}/beats`, { ...json('POST', data), ...options });
+export const updateStoryboardBeat = (id, beatId, patch, options) =>
+ request(`/storyboards/${enc(id)}/beats/${enc(beatId)}`, { ...json('PATCH', patch), ...options });
+export const deleteStoryboardBeat = (id, beatId, options) =>
+ request(`/storyboards/${enc(id)}/beats/${enc(beatId)}`, { method: 'DELETE', ...options });
+export const moveStoryboardBeat = (id, beatId, index, options) =>
+ request(`/storyboards/${enc(id)}/beats/${enc(beatId)}/move`, { ...json('POST', { index }), ...options });
+
+// → { board, panelId }
+export const addStoryboardPanel = (id, beatId, data, options) =>
+ request(`/storyboards/${enc(id)}/beats/${enc(beatId)}/panels`, { ...json('POST', data), ...options });
+export const updateStoryboardPanel = (id, panelId, patch, options) =>
+ request(`/storyboards/${enc(id)}/panels/${enc(panelId)}`, { ...json('PATCH', patch), ...options });
+export const deleteStoryboardPanel = (id, panelId, options) =>
+ request(`/storyboards/${enc(id)}/panels/${enc(panelId)}`, { method: 'DELETE', ...options });
+// `{ index }` within its own beat, or `{ beatId, index }` to move across beats.
+export const moveStoryboardPanel = (id, panelId, target, options) =>
+ request(`/storyboards/${enc(id)}/panels/${enc(panelId)}/move`, { ...json('POST', target), ...options });
+
+// take: `{ source, image }` for a gallery image or `{ source: 'sketch', sketchKey }`. → { board, takeId }
+export const addStoryboardPanelTake = (id, panelId, take, options) =>
+ request(`/storyboards/${enc(id)}/panels/${enc(panelId)}/takes`, { ...json('POST', take), ...options });
+export const selectStoryboardPanelTake = (id, panelId, takeId, options) =>
+ request(`/storyboards/${enc(id)}/panels/${enc(panelId)}/takes/${enc(takeId)}/select`, { method: 'POST', ...options });
+export const removeStoryboardPanelTake = (id, panelId, takeId, options) =>
+ request(`/storyboards/${enc(id)}/panels/${enc(panelId)}/takes/${enc(takeId)}`, { method: 'DELETE', ...options });
diff --git a/docs/API.md b/docs/API.md
index 6dd9179a77..86deb5f2dd 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -808,6 +808,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom
| `/api/music-video` | Music video projects; [one-prompt autonomous runs](./features/music-video-autonomous.md) at `/api/music-video/autonomous` |
| `/api/music-video/character-styles` | Built-in character styles a project loads via `concept.characterStyleId`: list with each style's sheet prompt and this install's sheet (`GET /`), full style (`GET /:id`), set or clear the install's character sheet (`PUT /:id/reference` `{ imageId }`) |
| `/api/mood-boards` | Mood boards; `POST /:id/generate` writes 1–4 prompts with the chosen LLM and queues new image items using saved imagegen settings (1024×576 default). Body: `requestId` (UUID), `providerId`, optional `model`, `effort`, `direction`, `count`, `render` (`mode`, `model`, `width`, `height`), `retry`. `GET /:id/generate` restores transient status; `mood-board:generate` pushes progress. Retry reuses the original batch and only queues unfinished slots. Prompt writing uses stored text, not pixels; saved prompts and references survive navigation and server restart, while transient batch status and recent request receipts reset on restart. |
+| `/api/storyboards` | Storyboards (Create › Storyboards): `GET`/`POST /`, `GET`/`PATCH`/`DELETE /:id`; beats at `/:id/beats` (`POST`, `PATCH`/`DELETE /:beatId`, `POST /:beatId/move`); panels at `/:id/beats/:beatId/panels` (`POST`) and `/:id/panels/:panelId` (`PATCH`, `DELETE`, `POST /move` with `{ beatId?, index }`); panel art takes at `/:id/panels/:panelId/takes` (`POST` `{ source, image \| sketchKey }`, `POST /:takeId/select`, `DELETE /:takeId`). Every write returns the whole board; over-limit text is refused. |
| `/api/decks` | Decks (playing-card / tarot designer) |
| `/api/writers-room` | Writers Room |
| `/api/universe-builder` | Universe Builder |
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 811cd8ae2d..ddc13c5547 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -148,6 +148,7 @@ does not recover nonempty output or general failed saves; those still require th
- `creative_commissions` — Creative Commissions (Autonomous Creation Engine, #2657/#2686): standing recurring creative briefs that fire on a cron cadence and drive the Creative Director directive pipeline unattended. One row per commission, the full sanitized record in `data` JSONB with `name`/`enabled`/`created_at`/`updated_at` mirrored into columns for the scheduler's "arm every enabled commission" query. The brief/identity federates as `creativeCommission` so synced feedback can attach to the same commission; `schedule`, `runs`, `assignment`, `enabled`, and feedback view stay machine-local (the per-reaction `commissionFeedback` records federate separately). The opt-in Digital Twin music-taste configuration is bounded brief metadata; raw taste sources and per-run recipes never cross the wire. The file backend is the `NODE_ENV=test`/`MEMORY_BACKEND=file` escape hatch only. Adapter: `server/services/creativeCommissions/db.js`, selected pg-vs-file by `server/services/creativeCommissions/store.js` (file backend is the `NODE_ENV=test`/`MEMORY_BACKEND=file` escape hatch only).
- `games` — Game studio workspaces (#3177): one row per managed-app asset plan, with the full reusable sprite/music binding set, current compiled-manifest pointer, compile history, and user-requested AI feedback history in `data` JSONB; `app_id`/`name`/`updated_at` are mirrored for list and relationship queries. The record is **machine-local** because managed-app registration, sprite atlases, and music-library bytes are machine-local; there is no peer-sync cursor or tombstone, and deletes are hard deletes. Compiled manifests are immutable, SHA-256-addressed artifacts under `data/games/{id}/manifests/`; their pointers and hashes live in the DB record. Adapter: `server/services/games/db.js`, selected pg-vs-collectionStore by `server/services/games/store.js` (collectionStore is test/unsupported file escape hatch only).
- `fableloom_stories` — FableLoom branching narratives: one row per loom (a branching-narrative story), with episodes, scene-node graphs, and intent transitions in `data` JSONB; `name`/`universe_id`/`series_id`/`updated_at` are mirrored for list and relationship queries (both refs are soft — no FK). `db-primary` because looms relate to universes and series and the index queries by recency. Federates through the opt-in per-record `fableLoom` category: whole-record LWW merges carry soft-delete tombstones, conflict-journal recovery, and hashed manifests for scene images/videos; there is no snapshot cursor or `sync_sequence`. Adapter: `server/services/fableLoom/db.js`, selected pg-vs-collectionStore by `server/services/fableLoom/store.js` (collectionStore is the test/unsupported file escape hatch only). Feature doc: [FableLoom](./features/fableloom.md).
+- `storyboards` — shared Storyboards (Create › Storyboards): one row per board, with beats → panels → art takes in `data` JSONB (a board is read and written whole, so no child tables); `name`/`universe_id`/`updated_at` are mirrored for the list sort and universe filter. `db-primary` because productions (music videos, Creative Director videos, FableLoom, Series Pipeline) link boards by id and later phases query those links. Panels reference catalog records by id only; panel art bytes stay in the gallery (`data/images`) and `data/media-sketches`, so the row holds filenames and sketch keys, never image bytes. Not federated yet: the tombstone pair and `updatedAt` keep a later sync category additive. No seed. Adapter: `server/services/storyboards/db.js`, selected pg-vs-collectionStore by `server/services/storyboards/store.js` (collectionStore is the test/unsupported file escape hatch only). Migration 435 is a ledger stub; boot DDL creates the table.
- `threejs_models` — generated procedural 3D-model workspaces: one row per model with gallery-image lineage, provider/model attribution, generation/refinement status, and the validated declarative scene spec in `data` JSONB. The referenced image bytes remain under `data/images/`; deterministic Three.js source is derived from the stored spec rather than persisted as a second mutable artifact. The table is local-only in this first slice, with soft-delete columns retained so federation can be added without a record-shape migration.
- `code_animation_jobs` — Code Animation generation history (`db-primary` record with a managed HTML output asset): job status/title and the generation brief/provider details are stored in PostgreSQL so the gallery can list and reopen jobs after navigation or restart. The generated HTML is kept as a managed file at `data/code-animations/<id>.html`, with its derived gallery poster beside it at `data/code-animations/<id>.jpg` (drawn from the page in the jailed preview browser when the job completes, or on first gallery view for older jobs; a missing poster is simply redrawn, so it needs no row of its own); PostgreSQL stores only its job record, not the output bytes. Jobs are machine-local and never federated. The database dump covers records and the normal filesystem backup includes the HTML assets.
- `code_animation_projects`, `code_animation_project_revisions`, `code_animation_project_runs` — opt-in Code Animation Production settings, accepted/candidate source pointers, immutable source/package hashes, portable manifest metadata and bounded import history. PostgreSQL owns metadata; source/asset bytes are write-once files under `data/code-animations/projects/<project-id>/revisions/<revision-id>/`. Settings, reference IDs, execution snapshots, managed paths and run IDs are machine-local and never federate. Budgets independently record iterations, elapsed time, tokens, render time and total retained disk bytes; imports consume disk only and never execute or install dependencies. Every attempted import has its own UUID-owned destination; failed/interrupted staging stays attributable to its run and never replaces accepted source. Boot DDL and migration 420 install empty tables without a seed. The PostgreSQL dump covers all three tables, and normal filesystem backup includes the entire project directory (no new excludes). Brief handoff omits local settings/IDs/paths; revision packages export only the validated portable contract. Source acceptance is explicit and does not assert visual, motion, sound or render evidence. Contained production workers stage each run in its own `data/code-animation-workspaces/<uuid>/` (excluded from backups, removed when the run ends); their operator-chosen tool paths are the machine-local `codeAnimationExecution` slice of `data/settings.json`.
diff --git a/scripts/migrations/435-storyboards-table.js b/scripts/migrations/435-storyboards-table.js
new file mode 100644
index 0000000000..b5aabfc562
--- /dev/null
+++ b/scripts/migrations/435-storyboards-table.js
@@ -0,0 +1,12 @@
+/**
+ * Registration stub for the storyboards table (Create › Storyboards). The
+ * table itself is created idempotently by ensureSchema at boot
+ * (server/lib/db/schema/media.js) — this stub records when the domain arrived
+ * on an install. Mirrors 287-fableloom-table.js.
+ */
+
+export default {
+ async up() {
+ console.log('🎬 storyboards: table created idempotently by ensureSchema at boot; nothing to do in the file runner');
+ },
+};
diff --git a/server/index.js b/server/index.js
index f2646a38b8..98042f5e45 100644
--- a/server/index.js
+++ b/server/index.js
@@ -154,6 +154,7 @@ import musicVideoCharacterStyleRoutes from './routes/musicVideoCharacterStyles.j
import humanActionRoutes from './routes/humanActions.js';
import spriteRoutes from './routes/sprites.js';
import moodBoardRoutes from './routes/moodBoard.js';
+import storyboardRoutes from './routes/storyboards.js';
import deckRoutes from './routes/decks.js';
import threejsModelsRoutes from './routes/threejsModels.js';
import filmStylesRoutes from './routes/filmStyles.js';
@@ -474,6 +475,7 @@ app.use('/api/music-video/character-styles', musicVideoCharacterStyleRoutes);
app.use('/api/music-video', musicVideoRoutes);
app.use('/api/sprites', spriteRoutes);
app.use('/api/mood-boards', moodBoardRoutes);
+app.use('/api/storyboards', storyboardRoutes);
app.use('/api/decks', deckRoutes);
app.use('/api/threejs-models', threejsModelsRoutes);
app.use('/api/film-styles', filmStylesRoutes);
diff --git a/server/lib/README.md b/server/lib/README.md
index 2134b37b56..cbf1a381a4 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -169,6 +169,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `spriteValidation.js` | Sprite Manager Zod schemas — record import/create/update, reference generate/lock/unlock + fork, walk-cycle generate/approve/reopen/trim, per-track generate/approve schemas built from the animation-track registry, publish binding + runtime contract, atlas publish/compile, and user-defined animation-track create/update. Split out of `validation.js` (#3873), which re-exports it. |
| `styleSourcePrompt.js` | `universeStyleLines(universe)` / `moodBoardSection(board)` — a resolved universe style guide or mood board (`services/creativeStyleSources.js`) as prompt text; shared by Code Animation and Creative Commissions. |
| `storyBuilderValidation.js` | Unified Story Builder session/step schemas. |
+| `storyboardValidation.js` | Storyboards route schemas (board, beat, panel, move, take) built from `storyboardVocabulary.js` caps; over-limit text is refused, never cut. |
| `telegramValidation.js` | Telegram bot config + test schemas. |
| `terminalReplay.js` | `stripTerminalQueries(text)` — remove response-soliciting terminal sequences (DSR `ESC[6n`, DA, DECRQM, DECRQSS, OSC colour queries) from the re-attach replay buffer a PTY session hands a newly attached client. A TUI emits `ESC[6n` on nearly every render and the 50KB ring buffer stores PTY output verbatim, so replaying it makes the attaching xterm ANSWER every historical query as input — landing cursor-position reports (`56;3R56;3R…`) on the shell prompt the dead TUI left behind, which then echo back into the same buffer and re-flood on every later attach. Applied on the way out, over the joined buffer, so a sequence split across two stored chunks still matches; live output is untouched because a running TUI must still get its replies. Stateful sequences the replay needs (mouse tracking, bracketed paste, alternate screen, SGR) are deliberately preserved — this is NOT `ansiStrip.js`, which removes every sequence to recover plain text. `createTerminalModeTracker()` — `observe(chunk)` follows the same stream’s DEC private modes (alternate screen, mouse tracking and encoding, bracketed paste, DECCKM, cursor visibility) and `preamble()` re-asserts the ones still in force, prepended to the replay: a TUI declares them ONCE at startup, so a session that overflows the 50KB window would otherwise replay as a normal-buffer, mouse-less terminal and become unscrollable. **`createReplayBuffer({ maxBytes })` is the export callers want** — the ring buffer that owns the bytes and applies both corrections to them (`push(chunk)` records and evicts, `render()` returns what an attaching client is handed); `services/shell.js` holds one per PTY session. The two helpers above are its internals, exported for their own direct tests — reach for the buffer rather than re-composing them by hand. |
| `brainLinkLocalFields.js` | `BRAIN_LINK_MACHINE_LOCAL_FIELDS` / `stripLinkMachineLocalFields(record)` / `mergeIncomingLinkRecord(incoming, existing)` — the Brain link fields (`localPath`, clone state, `repoIntake`, scan/study state) that stay on the machine that wrote them: stripped from synced links, kept from the local copy when a peer record lands. |
@@ -192,6 +193,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `characterIntegrity.js` | The shared cast-integrity contract (#6415), stated in `characterIntegrityVocabulary.js`'s terms: `characterIntegrityDepth` (minor roles / flat arcs / an explained `unknown` psychology get lighter requirements), the no-provider `characterCompletenessFindings` / `buildCastIntegrityReport`, the validating `mergeSemanticFindings`, and `characterFingerprint` (reports are derived, never persisted — the fingerprint is what makes a stale one detectable). |
| `castIntegrityPrompt.js` | The prompt-facing render of a `characterIntegrity.js` report (#6415): `renderCastIntegrity` (gap rows first, header always kept, so a budget-truncated block can never read as a clean cast) and `INTEGRITY_DEPTH_NOTES` (the `explained` / `light` / `full` rulings in the reviewer's own words). Shared by the Series foundation judge and the FableLoom whole-series editor so the two cannot drift on what a `light` character owes. |
| `bibleLimits.js` | `BIBLE_LIMITS` — the canon field length/count caps every story-bible sanitizer, Zod schema, and catalog payload upgrade measures against. A pure leaf split out of `storyBible.js` (which pulls `crypto` + `fileUtils`) so `catalogTypes.js` and the browser bundle can read the numbers alone. |
+| `storyboardRecord.js` | Shared Storyboard record (Create › Storyboards): `sanitizeStoryboard` (beats → panels → art takes, catalog refs by id), `sanitizeTake`, `summarizeStoryboard` (with runtime). |
+| `storyboardVocabulary.js` | Storyboard ids (`isValidStoryboardId`, `newStoryboardId`), vocab (`STORYBOARD_MUSICAL_ROLES`, aspect ratios, art styles, framings, take sources) and `STORYBOARD_LIMITS`. Browser-safe: the client editor imports it. |
| `storyArc.js` | Canonical Arc + Season + Reader-Map shapes, plus sanitizeSeriesDesign/renderSeriesDesign for author-owned series intent. |
| `storyArcLimits.js` | Pure canonical length/count caps and series-design field/mode contract shared by sanitizers, schemas and browser editors. |
| `styleGuide.js` | Per-series house style (tense/POV/audience/rating/reading-level/tone/conventions): `sanitizeStyleGuide` + `renderStyleGuide` generation block + enums. |
diff --git a/server/lib/db/schema/audit.js b/server/lib/db/schema/audit.js
index 430fd02af3..f1cb4c3e81 100644
--- a/server/lib/db/schema/audit.js
+++ b/server/lib/db/schema/audit.js
@@ -89,7 +89,7 @@ export const auditedTables = [
'universes', 'universe_runs', 'pipeline_series', 'pipeline_issues',
'story_builder_sessions', 'writers_room_works', 'writers_room_folders',
'writers_room_draft_versions', 'catalog_ingredients', 'catalog_scraps',
- 'catalog_user_types', 'creative_director_projects', 'threejs_models', 'image_to_3d_models', 'sprite_records', 'games', 'code_animation_jobs', 'mood_boards', 'fableloom_stories',
+ 'catalog_user_types', 'creative_director_projects', 'threejs_models', 'image_to_3d_models', 'sprite_records', 'games', 'code_animation_jobs', 'mood_boards', 'fableloom_stories', 'storyboards',
'lora_training_runs', 'authors', 'artists', 'albums', 'tracks', 'tribe_people', 'tribe_touchpoints',
'tribe_identities',
];
diff --git a/server/lib/db/schema/media.js b/server/lib/db/schema/media.js
index 13ec06c6bc..ac8dcb0c1a 100644
--- a/server/lib/db/schema/media.js
+++ b/server/lib/db/schema/media.js
@@ -124,6 +124,24 @@ export const mediaDdl = [
// Partial index for the live-list filter (deleted = FALSE).
`CREATE INDEX IF NOT EXISTS idx_mood_boards_live ON mood_boards (deleted) WHERE deleted = FALSE`,
+ // Storyboards (Create › Storyboards): one row per board, beats → panels →
+ // art takes inline in `data` JSONB (a board is read and written whole).
+ // name/universe_id/updated_at mirror for the list sort and universe filter;
+ // the tombstone pair keeps a later peer-sync category additive. Panel art
+ // bytes stay in data/images and data/media-sketches. Mirrors init-db.sql.
+ `CREATE TABLE IF NOT EXISTS storyboards (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ universe_id TEXT,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_storyboards_updated ON storyboards (updated_at DESC)`,
+ `CREATE INDEX IF NOT EXISTS idx_storyboards_live ON storyboards (deleted) WHERE deleted = FALSE`,
+
// Sprite records (issue #2895, phase 1). One row per sprite subject — a
// character or a props atlas family; the full record (spec, chromaKey,
// publishBinding, importedFrom) in `data` JSONB with kind/status mirrored
diff --git a/server/lib/index.js b/server/lib/index.js
index 463b90b814..01b6262646 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -87,6 +87,7 @@ export * from './socketEventContracts.js';
export * from './socketEventInventory.js';
export * as spriteValidation from './spriteValidation.js';
export * as storyBuilderValidation from './storyBuilderValidation.js';
+export * as storyboardValidation from './storyboardValidation.js';
export * as telegramValidation from './telegramValidation.js';
export * from './terminalReplay.js';
export * from './validation.js';
@@ -143,6 +144,8 @@ export * from './scenePrompt.js';
export * from './proseExportSettings.js';
export * from './shotGrammar.js';
export * from './storyboardScenes.js';
+export * from './storyboardRecord.js';
+export * from './storyboardVocabulary.js';
export * from './seasonStructure.js';
export * from './seriesAutopilotDefaults.js';
export * from './seriesCharacterArc.js';
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 2af2be09aa..b19c3e1715 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -78,6 +78,7 @@ const RAW_NAV_COMMANDS = [
{ id: 'nav.create.music-video-cleanup', path: '/music-video/cleanup', label: 'Music Video Cleanup', section: 'Create', aliases: ['music-video-cleanup', 'mv-cleanup', 'music video cleanup'], keywords: ['superseded', 'renders', 'film looks', 'disk', 'cleanup'] },
{ id: 'nav.create.decks', path: '/decks', label: 'Decks', section: 'Create', aliases: ['decks', 'deck', 'card-deck', 'playing-cards', 'tarot', 'tarot-deck', 'cards'], keywords: ['playing cards', 'tarot', 'card deck', 'card design', 'suits', 'arcana', 'style guide', 'batch render', 'card art'] },
{ id: 'nav.create.mood-boards', path: '/mood-boards', label: 'Mood Boards', section: 'Create', aliases: ['mood-boards', 'mood-board', 'moodboard', 'mood', 'inspiration', 'references'], keywords: ['inspiration', 'reference', 'pin', 'visual', 'canvas', 'collect', 'pinboard', 'palette', 'ideas'] },
+ { id: 'nav.create.storyboards', path: '/storyboards', label: 'Storyboards', section: 'Create', aliases: ['storyboards', 'storyboard', 'story-board', 'shot-planner', 'beat-board'], keywords: ['story beats', 'panels', 'shots', 'animatic', 'plan', 'film', 'music video', 'sketch', 'shot list', 'previs'] },
// Promoted out of the Media Gen tabs to a top-level Create page (#2930).
// The id stays `nav.media.sprites` — it's opaque and stored in palette
// history, so renaming it would orphan those entries.
diff --git a/server/lib/storyboardRecord.js b/server/lib/storyboardRecord.js
new file mode 100644
index 0000000000..6f20a2b0dc
--- /dev/null
+++ b/server/lib/storyboardRecord.js
@@ -0,0 +1,189 @@
+/**
+ * Storyboard records — the shared planning board under Create › Storyboards.
+ *
+ * A storyboard holds beats, and a beat holds panels; a panel is one planned
+ * shot. Productions (music videos, Creative Director videos, FableLoom,
+ * Series Pipeline) link a board rather than keeping a private plan, so the
+ * board is written to work before a song or edit exists: each panel carries
+ * estimated seconds and each beat a musical role, both optional.
+ *
+ * Panels point at catalog records (cast, environments, objects) by id only;
+ * the catalog stays the store for those. Panel art is a list of takes, each a
+ * gallery image filename (upload, catalog image, mood board pin, generated
+ * frame) or a blank-canvas sketch key (`sketch:<uuid>`, owned by
+ * services/mediaSketches.js); `selectedTakeId` names the one shown.
+ *
+ * Vocabulary and caps live in storyboardVocabulary.js (browser-safe).
+ * `sanitizeStoryboard` is the single normalizer every write passes through:
+ * it never invents content, drops malformed entries, and keeps a stale
+ * `selectedTakeId` from pointing at a removed take.
+ */
+
+import { isNonBlankStr, trimTo } from './textUtils.js';
+import { localImageFilename } from './localImageFilename.js';
+import { sanitizeSoftDeleteFields } from './syncWire.js';
+import {
+ isValidStoryboardId, newStoryboardEntityId, STORYBOARD_ART_STYLES, STORYBOARD_ASPECT_RATIOS, STORYBOARD_LIMITS,
+ STORYBOARD_MUSICAL_ROLES, STORYBOARD_PANEL_FRAMINGS, STORYBOARD_TAKE_SOURCES,
+} from './storyboardVocabulary.js';
+
+const SKETCH_KEY_PATTERN = /^sketch:[A-Za-z0-9-]{1,80}$/;
+const ENTITY_ID_PATTERN = /^[a-z]+-[A-Za-z0-9-]{1,80}$/;
+
+const ASPECT_SET = new Set(STORYBOARD_ASPECT_RATIOS);
+const ART_STYLE_SET = new Set(STORYBOARD_ART_STYLES);
+const ROLE_SET = new Set(STORYBOARD_MUSICAL_ROLES);
+const FRAMING_SET = new Set(STORYBOARD_PANEL_FRAMINGS);
+const SOURCE_SET = new Set(STORYBOARD_TAKE_SOURCES);
+
+const pick = (value, set, fallback = null) => (set.has(value) ? value : fallback);
+const isoOr = (value, fallback) => (isNonBlankStr(value) && Number.isFinite(Date.parse(value)) ? value : fallback);
+const entityId = (value, prefix) => (typeof value === 'string' && ENTITY_ID_PATTERN.test(value) ? value : newStoryboardEntityId(prefix));
+
+function refList(value) {
+ if (!Array.isArray(value)) return [];
+ const seen = new Set();
+ const out = [];
+ for (const item of value) {
+ const id = trimTo(item, STORYBOARD_LIMITS.refId);
+ if (!id || seen.has(id)) continue;
+ seen.add(id);
+ out.push(id);
+ if (out.length >= STORYBOARD_LIMITS.refs) break;
+ }
+ return out;
+}
+
+/** Seconds as a positive number rounded to hundredths, or null when unset. */
+function sanitizePanelSeconds(value) {
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return null;
+ return Math.round(Math.min(value, STORYBOARD_LIMITS.panelSecondsMax) * 100) / 100;
+}
+
+/** A take is a gallery image or a sketch key; anything else is dropped. */
+export function sanitizeTake(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const source = pick(raw.source, SOURCE_SET);
+ if (!source) return null;
+ if (source === 'sketch') {
+ if (typeof raw.sketchKey !== 'string' || !SKETCH_KEY_PATTERN.test(raw.sketchKey)) return null;
+ return { id: entityId(raw.id, 'take'), source, image: null, sketchKey: raw.sketchKey, refId: null, addedAt: isoOr(raw.addedAt, new Date().toISOString()) };
+ }
+ const image = localImageFilename(raw.image);
+ if (!image) return null;
+ return {
+ id: entityId(raw.id, 'take'),
+ source,
+ image,
+ sketchKey: null,
+ refId: trimTo(raw.refId, STORYBOARD_LIMITS.refId) || null,
+ addedAt: isoOr(raw.addedAt, new Date().toISOString()),
+ };
+}
+
+function sanitizePanel(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const takes = [];
+ const takeIds = new Set();
+ for (const item of Array.isArray(raw.takes) ? raw.takes : []) {
+ const take = sanitizeTake(item);
+ if (!take || takeIds.has(take.id)) continue;
+ takeIds.add(take.id);
+ takes.push(take);
+ if (takes.length >= STORYBOARD_LIMITS.takes) break;
+ }
+ const selectedTakeId = takeIds.has(raw.selectedTakeId) ? raw.selectedTakeId : (takes.at(-1)?.id ?? null);
+ return {
+ id: entityId(raw.id, 'panel'),
+ action: trimTo(raw.action, STORYBOARD_LIMITS.panelText),
+ dialogue: trimTo(raw.dialogue, STORYBOARD_LIMITS.panelText),
+ framing: pick(raw.framing, FRAMING_SET),
+ camera: trimTo(raw.camera, STORYBOARD_LIMITS.camera),
+ seconds: sanitizePanelSeconds(raw.seconds),
+ castIds: refList(raw.castIds),
+ environmentIds: refList(raw.environmentIds),
+ objectIds: refList(raw.objectIds),
+ notes: trimTo(raw.notes, STORYBOARD_LIMITS.notes),
+ takes,
+ selectedTakeId,
+ };
+}
+
+function sanitizeBeat(raw, budget = { panels: STORYBOARD_LIMITS.panelsTotal }) {
+ if (!raw || typeof raw !== 'object') return null;
+ const panels = [];
+ const ids = new Set();
+ for (const item of Array.isArray(raw.panels) ? raw.panels : []) {
+ if (panels.length >= STORYBOARD_LIMITS.panelsPerBeat || budget.panels <= 0) break;
+ const panel = sanitizePanel(item);
+ if (!panel || ids.has(panel.id)) continue;
+ ids.add(panel.id);
+ panels.push(panel);
+ budget.panels -= 1;
+ }
+ return {
+ id: entityId(raw.id, 'beat'),
+ title: trimTo(raw.title, STORYBOARD_LIMITS.beatTitle),
+ what: trimTo(raw.what, STORYBOARD_LIMITS.beatText),
+ why: trimTo(raw.why, STORYBOARD_LIMITS.beatText),
+ emotion: trimTo(raw.emotion, STORYBOARD_LIMITS.emotion),
+ musicalRole: pick(raw.musicalRole, ROLE_SET),
+ sectionHint: trimTo(raw.sectionHint, STORYBOARD_LIMITS.sectionHint),
+ panels,
+ };
+}
+
+/** Normalize a whole storyboard record, or null when it has no valid id. */
+export function sanitizeStoryboard(raw) {
+ if (!raw || typeof raw !== 'object' || !isValidStoryboardId(raw.id)) return null;
+ const now = new Date().toISOString();
+ const budget = { panels: STORYBOARD_LIMITS.panelsTotal };
+ const beats = [];
+ const ids = new Set();
+ for (const item of Array.isArray(raw.beats) ? raw.beats : []) {
+ if (beats.length >= STORYBOARD_LIMITS.beats) break;
+ const beat = sanitizeBeat(item, budget);
+ if (!beat || ids.has(beat.id)) continue;
+ ids.add(beat.id);
+ beats.push(beat);
+ }
+ const createdAt = isoOr(raw.createdAt, now);
+ return {
+ id: raw.id,
+ name: trimTo(raw.name, STORYBOARD_LIMITS.name) || 'Untitled storyboard',
+ logline: trimTo(raw.logline, STORYBOARD_LIMITS.logline),
+ aspectRatio: pick(raw.aspectRatio, ASPECT_SET, '16:9'),
+ artStyle: pick(raw.artStyle, ART_STYLE_SET, 'pencil'),
+ universeId: trimTo(raw.universeId, STORYBOARD_LIMITS.refId) || null,
+ moodBoardId: trimTo(raw.moodBoardId, STORYBOARD_LIMITS.refId) || null,
+ beats,
+ createdAt,
+ updatedAt: isoOr(raw.updatedAt, createdAt),
+ ...sanitizeSoftDeleteFields(raw),
+ };
+}
+
+/** Estimated runtime of a board in seconds (panels without seconds count 0). */
+function storyboardRuntime(board) {
+ return (board?.beats || []).reduce(
+ (sum, beat) => sum + (beat.panels || []).reduce((s, panel) => s + (panel.seconds || 0), 0),
+ 0,
+ );
+}
+
+/** List-row projection: no panels or takes, just what the index shows. */
+export function summarizeStoryboard(board) {
+ const panels = (board.beats || []).flatMap((beat) => beat.panels || []);
+ const cover = panels.map((panel) => panel.takes.find((take) => take.id === panel.selectedTakeId)).find(Boolean) || null;
+ return {
+ id: board.id,
+ name: board.name,
+ logline: board.logline,
+ aspectRatio: board.aspectRatio,
+ beatCount: board.beats.length,
+ panelCount: panels.length,
+ runtimeSec: storyboardRuntime(board),
+ cover: cover ? { image: cover.image, sketchKey: cover.sketchKey } : null,
+ updatedAt: board.updatedAt,
+ };
+}
diff --git a/server/lib/storyboardValidation.js b/server/lib/storyboardValidation.js
new file mode 100644
index 0000000000..c6cee28c23
--- /dev/null
+++ b/server/lib/storyboardValidation.js
@@ -0,0 +1,69 @@
+/**
+ * Zod schemas for the Storyboards routes. Caps and vocabularies come from
+ * storyboardRecord.js (the sanitizer's constants) so the route check and the
+ * normalizer cannot drift. Over-limit text is refused here, never cut.
+ */
+
+import { z } from 'zod';
+import {
+ STORYBOARD_ART_STYLES, STORYBOARD_ASPECT_RATIOS, STORYBOARD_LIMITS as L, STORYBOARD_MUSICAL_ROLES,
+ STORYBOARD_PANEL_FRAMINGS, STORYBOARD_TAKE_SOURCES,
+} from './storyboardVocabulary.js';
+
+const text = (max) => z.string().max(max);
+const ref = z.string().trim().min(1).max(L.refId);
+const nullableRef = ref.nullable();
+const refs = z.array(ref).max(L.refs);
+const entityId = z.string().trim().min(1).max(120);
+const position = z.number().int().min(0).max(10_000);
+
+export const storyboardCreateSchema = z.object({
+ name: text(L.name).optional(),
+ logline: text(L.logline).optional(),
+ aspectRatio: z.enum(STORYBOARD_ASPECT_RATIOS).optional(),
+ artStyle: z.enum(STORYBOARD_ART_STYLES).optional(),
+ universeId: nullableRef.optional(),
+ moodBoardId: nullableRef.optional(),
+}).strict();
+
+export const storyboardUpdateSchema = storyboardCreateSchema;
+
+const beatFields = {
+ title: text(L.beatTitle).optional(),
+ what: text(L.beatText).optional(),
+ why: text(L.beatText).optional(),
+ emotion: text(L.emotion).optional(),
+ musicalRole: z.enum(STORYBOARD_MUSICAL_ROLES).nullable().optional(),
+ sectionHint: text(L.sectionHint).optional(),
+};
+
+export const storyboardBeatCreateSchema = z.object({ ...beatFields, index: position.optional() }).strict();
+export const storyboardBeatUpdateSchema = z.object(beatFields).strict();
+export const storyboardMoveSchema = z.object({ index: position }).strict();
+
+const panelFields = {
+ action: text(L.panelText).optional(),
+ dialogue: text(L.panelText).optional(),
+ framing: z.enum(STORYBOARD_PANEL_FRAMINGS).nullable().optional(),
+ camera: text(L.camera).optional(),
+ seconds: z.number().positive().max(L.panelSecondsMax).nullable().optional(),
+ castIds: refs.optional(),
+ environmentIds: refs.optional(),
+ objectIds: refs.optional(),
+ notes: text(L.notes).optional(),
+};
+
+export const storyboardPanelCreateSchema = z.object({ ...panelFields, index: position.optional() }).strict();
+export const storyboardPanelUpdateSchema = z.object(panelFields).strict();
+export const storyboardPanelMoveSchema = z.object({ beatId: entityId.optional(), index: position }).strict();
+
+// A take names a gallery image (any source but sketch) or a sketch key.
+export const storyboardTakeCreateSchema = z.object({
+ source: z.enum(STORYBOARD_TAKE_SOURCES),
+ image: z.string().trim().min(1).max(300).optional(),
+ sketchKey: z.string().trim().regex(/^sketch:[A-Za-z0-9-]{1,80}$/).optional(),
+ refId: ref.optional(),
+}).strict().refine(
+ (take) => (take.source === 'sketch' ? !!take.sketchKey && !take.image : !!take.image && !take.sketchKey),
+ { message: 'A sketch take needs sketchKey; every other take needs image' },
+);
diff --git a/server/lib/storyboardVocabulary.js b/server/lib/storyboardVocabulary.js
new file mode 100644
index 0000000000..daf112b631
--- /dev/null
+++ b/server/lib/storyboardVocabulary.js
@@ -0,0 +1,43 @@
+/**
+ * Storyboard vocabulary — ids, enums and caps shared by the server record
+ * normalizer (storyboardRecord.js), the route schemas and the client editor.
+ * Kept free of node-only imports so the client can import it directly.
+ */
+
+import { SHOT_TYPES } from './shotGrammar.js';
+
+export const STORYBOARD_ID_PATTERN = /^sb-[A-Za-z0-9-]{1,80}$/;
+export const isValidStoryboardId = (id) => typeof id === 'string' && STORYBOARD_ID_PATTERN.test(id);
+// globalThis.crypto (not node:crypto) keeps this module importable by the
+// client for its vocabulary; only the server ever mints ids.
+export const newStoryboardId = () => `sb-${globalThis.crypto.randomUUID()}`;
+export const newStoryboardEntityId = (prefix) => `${prefix}-${globalThis.crypto.randomUUID()}`;
+
+export const STORYBOARD_ASPECT_RATIOS = Object.freeze(['16:9', '9:16', '1:1', '4:5', '2.39:1']);
+export const STORYBOARD_ART_STYLES = Object.freeze(['pencil', 'clean-line', 'grey-marker', 'color']);
+// Song-structure vocabulary for a beat before (or without) a song. Matches how
+// a songwriter names sections, not the music-video treatment's arc roles.
+export const STORYBOARD_MUSICAL_ROLES = Object.freeze([
+ 'intro', 'verse', 'pre-chorus', 'chorus', 'bridge', 'build', 'drop', 'breakdown', 'instrumental', 'outro',
+]);
+export const STORYBOARD_PANEL_FRAMINGS = SHOT_TYPES;
+export const STORYBOARD_TAKE_SOURCES = Object.freeze(['upload', 'gallery', 'catalog', 'moodBoard', 'sketch', 'generated']);
+
+export const STORYBOARD_LIMITS = Object.freeze({
+ name: 120,
+ logline: 500,
+ beats: 200,
+ panelsPerBeat: 60,
+ panelsTotal: 1000,
+ beatTitle: 120,
+ beatText: 2000,
+ emotion: 120,
+ sectionHint: 120,
+ panelText: 2000,
+ camera: 200,
+ refs: 40,
+ refId: 128,
+ takes: 30,
+ panelSecondsMax: 600,
+ notes: 4000,
+});
diff --git a/server/routes/storyboards.js b/server/routes/storyboards.js
new file mode 100644
index 0000000000..704216ecca
--- /dev/null
+++ b/server/routes/storyboards.js
@@ -0,0 +1,90 @@
+/**
+ * Storyboards routes — boards, beats, panels and panel art takes
+ * (Create › Storyboards). Every mutation answers with the whole board so the
+ * client applies its own write at once; no list re-fetch.
+ */
+
+import { Router } from 'express';
+import { asyncHandler } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import {
+ storyboardBeatCreateSchema, storyboardBeatUpdateSchema, storyboardCreateSchema, storyboardMoveSchema,
+ storyboardPanelCreateSchema, storyboardPanelMoveSchema, storyboardPanelUpdateSchema, storyboardTakeCreateSchema,
+ storyboardUpdateSchema,
+} from '../lib/storyboardValidation.js';
+import {
+ addBeat, addPanel, addPanelTake, createStoryboard, deleteBeat, deletePanel, deleteStoryboard, getStoryboard,
+ listStoryboards, moveBeat, movePanel, removePanelTake, selectPanelTake, updateBeat, updatePanel,
+ updateStoryboard,
+} from '../services/storyboards/index.js';
+
+const router = Router();
+
+router.get('/', asyncHandler(async (_req, res) => {
+ res.json(await listStoryboards());
+}));
+
+router.post('/', asyncHandler(async (req, res) => {
+ res.status(201).json(await createStoryboard(validateRequest(storyboardCreateSchema, req.body ?? {})));
+}));
+
+router.get('/:id', asyncHandler(async (req, res) => {
+ res.json(await getStoryboard(req.params.id));
+}));
+
+router.patch('/:id', asyncHandler(async (req, res) => {
+ res.json(await updateStoryboard(req.params.id, validateRequest(storyboardUpdateSchema, req.body ?? {})));
+}));
+
+router.delete('/:id', asyncHandler(async (req, res) => {
+ res.json(await deleteStoryboard(req.params.id));
+}));
+
+router.post('/:id/beats', asyncHandler(async (req, res) => {
+ const { index, ...fields } = validateRequest(storyboardBeatCreateSchema, req.body ?? {});
+ res.status(201).json(await addBeat(req.params.id, fields, { index }));
+}));
+
+router.patch('/:id/beats/:beatId', asyncHandler(async (req, res) => {
+ res.json(await updateBeat(req.params.id, req.params.beatId, validateRequest(storyboardBeatUpdateSchema, req.body ?? {})));
+}));
+
+router.delete('/:id/beats/:beatId', asyncHandler(async (req, res) => {
+ res.json(await deleteBeat(req.params.id, req.params.beatId));
+}));
+
+router.post('/:id/beats/:beatId/move', asyncHandler(async (req, res) => {
+ const { index } = validateRequest(storyboardMoveSchema, req.body ?? {});
+ res.json(await moveBeat(req.params.id, req.params.beatId, index));
+}));
+
+router.post('/:id/beats/:beatId/panels', asyncHandler(async (req, res) => {
+ const { index, ...fields } = validateRequest(storyboardPanelCreateSchema, req.body ?? {});
+ res.status(201).json(await addPanel(req.params.id, req.params.beatId, fields, { index }));
+}));
+
+router.patch('/:id/panels/:panelId', asyncHandler(async (req, res) => {
+ res.json(await updatePanel(req.params.id, req.params.panelId, validateRequest(storyboardPanelUpdateSchema, req.body ?? {})));
+}));
+
+router.delete('/:id/panels/:panelId', asyncHandler(async (req, res) => {
+ res.json(await deletePanel(req.params.id, req.params.panelId));
+}));
+
+router.post('/:id/panels/:panelId/move', asyncHandler(async (req, res) => {
+ res.json(await movePanel(req.params.id, req.params.panelId, validateRequest(storyboardPanelMoveSchema, req.body ?? {})));
+}));
+
+router.post('/:id/panels/:panelId/takes', asyncHandler(async (req, res) => {
+ res.status(201).json(await addPanelTake(req.params.id, req.params.panelId, validateRequest(storyboardTakeCreateSchema, req.body ?? {})));
+}));
+
+router.post('/:id/panels/:panelId/takes/:takeId/select', asyncHandler(async (req, res) => {
+ res.json(await selectPanelTake(req.params.id, req.params.panelId, req.params.takeId));
+}));
+
+router.delete('/:id/panels/:panelId/takes/:takeId', asyncHandler(async (req, res) => {
+ res.json(await removePanelTake(req.params.id, req.params.panelId, req.params.takeId));
+}));
+
+export default router;
diff --git a/server/routes/storyboards.test.js b/server/routes/storyboards.test.js
new file mode 100644
index 0000000000..223b490eb2
--- /dev/null
+++ b/server/routes/storyboards.test.js
@@ -0,0 +1,84 @@
+import { afterAll, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { request } from '../lib/testHelper.js';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-storyboards-') }));
+afterAll(cleanupTempDataRoots);
+
+const { default: routes } = await import('./storyboards.js');
+
+const app = express();
+app.use(express.json());
+app.use('/api/storyboards', routes);
+app.use(errorMiddleware);
+
+const api = (method, path, body) => request(app)[method](`/api/storyboards${path}`).send(body);
+
+describe('storyboards routes', () => {
+ it('plans a story with no song: beats, panels with estimated seconds, catalog links, art takes', async () => {
+ const created = await api('post', '/', { name: 'Example Story', aspectRatio: '9:16' });
+ expect(created.status).toBe(201);
+ const id = created.body.id;
+ expect(created.body).toMatchObject({ name: 'Example Story', aspectRatio: '9:16', artStyle: 'pencil', beats: [] });
+
+ const opening = await api('post', `/${id}/beats`, { title: 'Arrival', what: 'She steps into the empty gym', musicalRole: 'intro' });
+ const beatId = opening.body.beatId;
+ const chorus = await api('post', `/${id}/beats`, { title: 'First dance', musicalRole: 'chorus', index: 0 });
+ expect(chorus.body.board.beats.map((b) => b.title)).toEqual(['First dance', 'Arrival']);
+
+ const p1 = await api('post', `/${id}/beats/${beatId}/panels`, { action: 'Wide of the gym doors', framing: 'wide', seconds: 3.456, castIds: ['cat-example-1'] });
+ expect(p1.status).toBe(201);
+ const panelId = p1.body.panelId;
+ const panel = p1.body.board.beats[1].panels[0];
+ expect(panel).toMatchObject({ seconds: 3.46, framing: 'wide', castIds: ['cat-example-1'], takes: [], selectedTakeId: null });
+
+ const take = await api('post', `/${id}/panels/${panelId}/takes`, { source: 'upload', image: '/data/images/example.png' });
+ expect(take.status).toBe(201);
+ const sketch = await api('post', `/${id}/panels/${panelId}/takes`, { source: 'sketch', sketchKey: 'sketch:abc-123' });
+ const art = sketch.body.board.beats[1].panels[0];
+ expect(art.takes.map((t) => t.image ?? t.sketchKey)).toEqual(['example.png', 'sketch:abc-123']);
+ expect(art.selectedTakeId).toBe(sketch.body.takeId);
+
+ // Removing the selected take falls back to the newest remaining one.
+ const removed = await api('delete', `/${id}/panels/${panelId}/takes/${sketch.body.takeId}`);
+ expect(removed.body.beats[1].panels[0].selectedTakeId).toBe(take.body.takeId);
+
+ const list = await api('get', '/');
+ expect(list.body).toEqual([expect.objectContaining({ id, beatCount: 2, panelCount: 1, runtimeSec: 3.46, cover: { image: 'example.png', sketchKey: null } })]);
+ });
+
+ it('moves a panel to another beat and keeps the order', async () => {
+ const { body: board } = await api('post', '/', { name: 'Moves' });
+ const a = (await api('post', `/${board.id}/beats`, { title: 'A' })).body.beatId;
+ const b = (await api('post', `/${board.id}/beats`, { title: 'B' })).body.beatId;
+ const p1 = (await api('post', `/${board.id}/beats/${a}/panels`, { action: 'one' })).body.panelId;
+ await api('post', `/${board.id}/beats/${b}/panels`, { action: 'two' });
+ const moved = await api('post', `/${board.id}/panels/${p1}/move`, { beatId: b, index: 0 });
+ expect(moved.body.beats[0].panels).toEqual([]);
+ expect(moved.body.beats[1].panels.map((p) => p.action)).toEqual(['one', 'two']);
+ });
+
+ it('refuses over-limit text and malformed art instead of cutting or keeping it', async () => {
+ const { body: board } = await api('post', '/', {});
+ expect(board.name).toBe('Untitled storyboard');
+ const beat = (await api('post', `/${board.id}/beats`, {})).body.beatId;
+ const tooLong = await api('patch', `/${board.id}/beats/${beat}`, { what: 'x'.repeat(2001) });
+ expect(tooLong.status).toBe(400);
+ const panel = (await api('post', `/${board.id}/beats/${beat}/panels`, {})).body.panelId;
+ const external = await api('post', `/${board.id}/panels/${panel}/takes`, { source: 'upload', image: 'https://example.com/a.png' });
+ expect(external.status).toBe(400);
+ const mixed = await api('post', `/${board.id}/panels/${panel}/takes`, { source: 'sketch', image: 'a.png' });
+ expect(mixed.status).toBe(400);
+ });
+
+ it('treats a deleted board as gone', async () => {
+ const { body: board } = await api('post', '/', { name: 'Gone' });
+ expect((await api('delete', `/${board.id}`)).body).toEqual({ ok: true });
+ expect((await api('get', `/${board.id}`)).status).toBe(404);
+ expect((await api('patch', `/${board.id}`, { name: 'Back' })).status).toBe(404);
+ expect((await api('get', '/')).body.some((row) => row.id === board.id)).toBe(false);
+ });
+});
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 2b214b6935..22b106f1ab 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -1086,6 +1086,21 @@ CREATE INDEX IF NOT EXISTS idx_mood_boards_updated ON mood_boards (updated_at DE
-- Partial index for the live-list filter (deleted = FALSE).
CREATE INDEX IF NOT EXISTS idx_mood_boards_live ON mood_boards (deleted) WHERE deleted = FALSE;
+-- Storyboards (Create › Storyboards): beats → panels → art takes inline in
+-- `data` JSONB. Mirrors the storyboards block in db/schema/media.js.
+CREATE TABLE IF NOT EXISTS storyboards (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ universe_id TEXT,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+);
+CREATE INDEX IF NOT EXISTS idx_storyboards_updated ON storyboards (updated_at DESC);
+CREATE INDEX IF NOT EXISTS idx_storyboards_live ON storyboards (deleted) WHERE deleted = FALSE;
+
-- Media asset index (Phase 3.2, issue #1000). One row per generated image or
-- video. The bytes stay on disk (data/images, data/videos) and the image
-- sidecars + data/video-history.json remain authoritative — this table is a
@@ -2276,6 +2291,8 @@ DROP TRIGGER IF EXISTS trg_fableloom_stories_audit ON fableloom_stories;
CREATE TRIGGER trg_fableloom_stories_audit AFTER UPDATE OR DELETE ON fableloom_stories FOR EACH ROW EXECUTE FUNCTION record_audit_log();
DROP TRIGGER IF EXISTS trg_mood_boards_audit ON mood_boards;
CREATE TRIGGER trg_mood_boards_audit AFTER UPDATE OR DELETE ON mood_boards FOR EACH ROW EXECUTE FUNCTION record_audit_log();
+DROP TRIGGER IF EXISTS trg_storyboards_audit ON storyboards;
+CREATE TRIGGER trg_storyboards_audit AFTER UPDATE OR DELETE ON storyboards FOR EACH ROW EXECUTE FUNCTION record_audit_log();
DROP TRIGGER IF EXISTS trg_lora_training_runs_audit ON lora_training_runs;
CREATE TRIGGER trg_lora_training_runs_audit AFTER UPDATE OR DELETE ON lora_training_runs FOR EACH ROW EXECUTE FUNCTION record_audit_log();
DROP TRIGGER IF EXISTS trg_authors_audit ON authors;
diff --git a/server/services/dataManager.js b/server/services/dataManager.js
index bf6249d42c..01d3b2d619 100644
--- a/server/services/dataManager.js
+++ b/server/services/dataManager.js
@@ -195,6 +195,7 @@ export const CATEGORIES = {
'spotify': { label: 'Spotify Sync', description: 'Machine-local Spotify sync cursor and cache — purging resets the cursor and can leave a gap in imported history', archivable: true, deletable: false },
'sprites': { label: 'Sprites', description: 'Sprite reference art, walk frames, and runtime atlases — the only copy of the generated art; records live in Postgres', archivable: false, deletable: false },
'story-builder': { label: 'Story Builder', description: 'Story Builder project records', archivable: true, deletable: false },
+ 'storyboards': { label: 'Storyboards', description: 'Storyboard beats and panels (file mirror of the Postgres store)', archivable: true, deletable: false },
'supercollider': { label: 'SuperCollider Runtime', description: 'Machine-local readiness evidence for the managed SuperCollider image, in-flight render scratch and 24-hour render previews — re-created by npm run setup:supercollider, safe to purge', archivable: false, deletable: true, purgeScope: 'category' },
'telegram': { label: 'Telegram', description: 'Telegram bot data', archivable: true, deletable: true, purgeScope: 'category' },
'templates': { label: 'Visual Templates', description: 'Shipped layout assets used as render anchors', archivable: false, deletable: false },
diff --git a/server/services/storyboards/db.js b/server/services/storyboards/db.js
new file mode 100644
index 0000000000..a5132e307a
--- /dev/null
+++ b/server/services/storyboards/db.js
@@ -0,0 +1,46 @@
+/**
+ * PostgreSQL leaf I/O for storyboards. The full sanitized record lives in
+ * `data` JSONB; name/universe_id/updated_at are mirrored for the list sort and
+ * universe filter, and the tombstone pair keeps a later federation additive.
+ */
+
+import { query } from '../../lib/db.js';
+import { mirrorTimestamp } from '../../lib/pgTimestamp.js';
+import { toPgJson } from '../../lib/pgJson.js';
+
+export async function readRaw(id) {
+ const { rows } = await query('SELECT data FROM storyboards WHERE id = $1', [id]);
+ return rows[0]?.data ?? null;
+}
+
+export async function listRaw() {
+ const { rows } = await query('SELECT data FROM storyboards ORDER BY updated_at DESC, id ASC');
+ return rows.map((row) => row.data);
+}
+
+export async function writeRaw(id, record) {
+ const now = new Date().toISOString();
+ const createdAt = mirrorTimestamp(record?.createdAt, now);
+ await query(
+ `INSERT INTO storyboards (id, name, universe_id, data, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7, $8)
+ ON CONFLICT (id) DO UPDATE SET
+ name = EXCLUDED.name,
+ universe_id = EXCLUDED.universe_id,
+ data = EXCLUDED.data,
+ updated_at = EXCLUDED.updated_at,
+ deleted = EXCLUDED.deleted,
+ deleted_at = EXCLUDED.deleted_at`,
+ [
+ id,
+ record.name,
+ record.universeId ?? null,
+ toPgJson(record),
+ createdAt,
+ mirrorTimestamp(record?.updatedAt, createdAt),
+ record.deleted === true,
+ mirrorTimestamp(record.deletedAt, null),
+ ],
+ );
+ return record;
+}
diff --git a/server/services/storyboards/index.js b/server/services/storyboards/index.js
new file mode 100644
index 0000000000..cb266943aa
--- /dev/null
+++ b/server/services/storyboards/index.js
@@ -0,0 +1,209 @@
+/**
+ * Storyboards service — CRUD over boards, beats, panels and panel art takes.
+ *
+ * Every write funnels through `mutateStoryboard` (per-record write queue, then
+ * a full re-sanitize), so concurrent edits from two open tabs or a beat edit
+ * racing a panel add merge against the freshest record and a malformed
+ * mutation never persists. A tombstoned board reads as missing.
+ *
+ * Not federated yet: the tombstone pair and `updatedAt` stamping keep adding
+ * a peer-sync category later additive (same posture as sprite records).
+ */
+
+import { ServerError } from '../../lib/errorHandler.js';
+import { sanitizeStoryboard, sanitizeTake, summarizeStoryboard } from '../../lib/storyboardRecord.js';
+import {
+ isValidStoryboardId, newStoryboardEntityId, newStoryboardId, STORYBOARD_LIMITS,
+} from '../../lib/storyboardVocabulary.js';
+import { listRaw, queueStoryboardWrite, readRaw, writeRaw } from './store.js';
+
+const notFound = (what = 'Storyboard') => new ServerError(`${what} not found`, { status: 404, code: 'NOT_FOUND' });
+const tooMany = (message) => new ServerError(message, { status: 409, code: 'STORYBOARD_LIMIT' });
+
+const BOARD_FIELDS = ['name', 'logline', 'aspectRatio', 'artStyle', 'universeId', 'moodBoardId'];
+const BEAT_FIELDS = ['title', 'what', 'why', 'emotion', 'musicalRole', 'sectionHint'];
+const PANEL_FIELDS = ['action', 'dialogue', 'framing', 'camera', 'seconds', 'castIds', 'environmentIds', 'objectIds', 'notes'];
+
+const pickFields = (patch, fields) => Object.fromEntries(
+ fields.filter((key) => Object.hasOwn(patch || {}, key)).map((key) => [key, patch[key]]),
+);
+
+const clampIndex = (index, length) => (Number.isInteger(index) ? Math.max(0, Math.min(index, length)) : length);
+
+async function readLive(id) {
+ if (!isValidStoryboardId(id)) return null;
+ const raw = await readRaw(id);
+ const board = sanitizeStoryboard(raw);
+ return board && !board.deleted ? board : null;
+}
+
+export async function listStoryboards() {
+ const rows = await listRaw();
+ return rows
+ .map(sanitizeStoryboard)
+ .filter((board) => board && !board.deleted)
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
+ .map(summarizeStoryboard);
+}
+
+export async function getStoryboard(id) {
+ const board = await readLive(id);
+ if (!board) throw notFound();
+ return board;
+}
+
+export async function createStoryboard(input = {}) {
+ const now = new Date().toISOString();
+ const board = sanitizeStoryboard({ ...pickFields(input, BOARD_FIELDS), id: newStoryboardId(), beats: [], createdAt: now, updatedAt: now });
+ await writeRaw(board.id, board);
+ console.log(`🎬 Created storyboard ${board.id}`);
+ return board;
+}
+
+/**
+ * Run `mutate(board)` against the freshest live record under the per-record
+ * queue. The mutator edits the draft in place and may return a value for the
+ * caller; the sanitized board is persisted with a fresh `updatedAt`.
+ */
+async function mutateStoryboard(id, mutate) {
+ if (!isValidStoryboardId(id)) throw notFound();
+ return queueStoryboardWrite(id, async () => {
+ const current = await readLive(id);
+ if (!current) throw notFound();
+ const draft = structuredClone(current);
+ const result = mutate(draft);
+ const next = sanitizeStoryboard({ ...draft, id, updatedAt: new Date().toISOString() });
+ await writeRaw(id, next);
+ return { board: next, result };
+ });
+}
+
+export async function updateStoryboard(id, patch) {
+ const { board } = await mutateStoryboard(id, (draft) => { Object.assign(draft, pickFields(patch, BOARD_FIELDS)); });
+ return board;
+}
+
+export async function deleteStoryboard(id) {
+ await mutateStoryboard(id, (draft) => {
+ draft.deleted = true;
+ draft.deletedAt = new Date().toISOString();
+ });
+ return { ok: true };
+}
+
+const findBeat = (board, beatId) => {
+ const beat = board.beats.find((b) => b.id === beatId);
+ if (!beat) throw notFound('Beat');
+ return beat;
+};
+
+const findPanel = (board, panelId) => {
+ for (const beat of board.beats) {
+ const index = beat.panels.findIndex((p) => p.id === panelId);
+ if (index >= 0) return { beat, panel: beat.panels[index], index };
+ }
+ throw notFound('Panel');
+};
+
+const panelCount = (board) => board.beats.reduce((sum, beat) => sum + beat.panels.length, 0);
+
+export async function addBeat(id, fields = {}, { index } = {}) {
+ const { board, result } = await mutateStoryboard(id, (draft) => {
+ if (draft.beats.length >= STORYBOARD_LIMITS.beats) throw tooMany(`A storyboard holds at most ${STORYBOARD_LIMITS.beats} beats.`);
+ const beat = { ...pickFields(fields, BEAT_FIELDS), id: newStoryboardEntityId('beat'), panels: [] };
+ draft.beats.splice(clampIndex(index, draft.beats.length), 0, beat);
+ return beat.id;
+ });
+ return { board, beatId: result };
+}
+
+export async function updateBeat(id, beatId, patch) {
+ const { board } = await mutateStoryboard(id, (draft) => { Object.assign(findBeat(draft, beatId), pickFields(patch, BEAT_FIELDS)); });
+ return board;
+}
+
+export async function deleteBeat(id, beatId) {
+ const { board } = await mutateStoryboard(id, (draft) => {
+ findBeat(draft, beatId);
+ draft.beats = draft.beats.filter((b) => b.id !== beatId);
+ });
+ return board;
+}
+
+export async function moveBeat(id, beatId, toIndex) {
+ const { board } = await mutateStoryboard(id, (draft) => {
+ const beat = findBeat(draft, beatId);
+ draft.beats = draft.beats.filter((b) => b.id !== beatId);
+ draft.beats.splice(clampIndex(toIndex, draft.beats.length), 0, beat);
+ });
+ return board;
+}
+
+export async function addPanel(id, beatId, fields = {}, { index } = {}) {
+ const { board, result } = await mutateStoryboard(id, (draft) => {
+ const beat = findBeat(draft, beatId);
+ if (beat.panels.length >= STORYBOARD_LIMITS.panelsPerBeat) throw tooMany(`A beat holds at most ${STORYBOARD_LIMITS.panelsPerBeat} panels.`);
+ if (panelCount(draft) >= STORYBOARD_LIMITS.panelsTotal) throw tooMany(`A storyboard holds at most ${STORYBOARD_LIMITS.panelsTotal} panels.`);
+ const panel = { ...pickFields(fields, PANEL_FIELDS), id: newStoryboardEntityId('panel'), takes: [], selectedTakeId: null };
+ beat.panels.splice(clampIndex(index, beat.panels.length), 0, panel);
+ return panel.id;
+ });
+ return { board, panelId: result };
+}
+
+export async function updatePanel(id, panelId, patch) {
+ const { board } = await mutateStoryboard(id, (draft) => { Object.assign(findPanel(draft, panelId).panel, pickFields(patch, PANEL_FIELDS)); });
+ return board;
+}
+
+export async function deletePanel(id, panelId) {
+ const { board } = await mutateStoryboard(id, (draft) => {
+ const { beat } = findPanel(draft, panelId);
+ beat.panels = beat.panels.filter((p) => p.id !== panelId);
+ });
+ return board;
+}
+
+/** Move a panel to `index` within `beatId` (its own beat when omitted). */
+export async function movePanel(id, panelId, { beatId, index } = {}) {
+ const { board } = await mutateStoryboard(id, (draft) => {
+ const { beat: from, panel } = findPanel(draft, panelId);
+ const to = beatId ? findBeat(draft, beatId) : from;
+ if (to !== from && to.panels.length >= STORYBOARD_LIMITS.panelsPerBeat) throw tooMany(`A beat holds at most ${STORYBOARD_LIMITS.panelsPerBeat} panels.`);
+ from.panels = from.panels.filter((p) => p.id !== panelId);
+ to.panels.splice(clampIndex(index, to.panels.length), 0, panel);
+ });
+ return board;
+}
+
+/** Add a take to a panel's art and make it the selected one. */
+export async function addPanelTake(id, panelId, take) {
+ const entry = sanitizeTake({ ...take, id: newStoryboardEntityId('take'), addedAt: new Date().toISOString() });
+ if (!entry) throw new ServerError('Panel art must be a gallery image or a sketch.', { status: 400, code: 'VALIDATION_ERROR' });
+ const { board } = await mutateStoryboard(id, (draft) => {
+ const { panel } = findPanel(draft, panelId);
+ if (panel.takes.length >= STORYBOARD_LIMITS.takes) throw tooMany(`A panel keeps at most ${STORYBOARD_LIMITS.takes} takes; remove one first.`);
+ panel.takes.push(entry);
+ panel.selectedTakeId = entry.id;
+ });
+ return { board, takeId: entry.id };
+}
+
+export async function selectPanelTake(id, panelId, takeId) {
+ const { board } = await mutateStoryboard(id, (draft) => {
+ const { panel } = findPanel(draft, panelId);
+ if (!panel.takes.some((t) => t.id === takeId)) throw notFound('Take');
+ panel.selectedTakeId = takeId;
+ });
+ return board;
+}
+
+export async function removePanelTake(id, panelId, takeId) {
+ const { board } = await mutateStoryboard(id, (draft) => {
+ const { panel } = findPanel(draft, panelId);
+ if (!panel.takes.some((t) => t.id === takeId)) throw notFound('Take');
+ panel.takes = panel.takes.filter((t) => t.id !== takeId);
+ if (panel.selectedTakeId === takeId) panel.selectedTakeId = panel.takes.at(-1)?.id ?? null;
+ });
+ return board;
+}
diff --git a/server/services/storyboards/store.js b/server/services/storyboards/store.js
new file mode 100644
index 0000000000..80d8924b92
--- /dev/null
+++ b/server/services/storyboards/store.js
@@ -0,0 +1,65 @@
+/**
+ * Storyboard records — PostgreSQL/file backend facade.
+ *
+ * Storyboards are db-primary (`storyboards`). The collectionStore backend
+ * keeps the domain runnable in tests and under the unsupported
+ * MEMORY_BACKEND=file development escape hatch — the same split as FableLoom
+ * (services/fableLoom/store.js).
+ */
+
+import { join } from 'path';
+import { PATHS } from '../../lib/fileUtils.js';
+import { createCollectionStore } from '../../lib/collectionStore.js';
+import { createRecordWriteQueue } from '../../lib/fileWriteQueue.js';
+import { createPgFileFacade, resolvePgBackend } from '../../lib/pgFileFacade.js';
+import { isValidStoryboardId, STORYBOARD_ID_PATTERN } from '../../lib/storyboardVocabulary.js';
+
+const TYPE_SCHEMA_VERSION = 1;
+
+function assertId(id) {
+ if (!isValidStoryboardId(id)) throw new Error(`storyboards: invalid record id "${id}"`);
+}
+
+function makeFileBackend() {
+ const collection = createCollectionStore({
+ dir: join(PATHS.data, 'storyboards'),
+ type: 'storyboards',
+ schemaVersion: TYPE_SCHEMA_VERSION,
+ idPattern: STORYBOARD_ID_PATTERN,
+ });
+ return {
+ name: 'file',
+ readRaw: (id) => collection.loadOneRaw(id),
+ listRaw: () => collection.loadAll(),
+ writeRaw: (id, record) => collection.saveOneNow(id, record),
+ };
+}
+
+const facade = createPgFileFacade({
+ makeFile: makeFileBackend,
+ makePg: () => resolvePgBackend({
+ requirement: 'Storyboards require PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the unsupported file backend)',
+ loadDb: () => import('./db.js'),
+ makePg: (db) => ({ name: 'postgres', readRaw: db.readRaw, listRaw: db.listRaw, writeRaw: db.writeRaw }),
+ }),
+});
+
+const queueRecordWrite = createRecordWriteQueue(assertId);
+
+export const readRaw = async (id) => {
+ assertId(id);
+ return (await facade.getBackend()).readRaw(id);
+};
+
+export const listRaw = async () => (await facade.getBackend()).listRaw();
+
+export const writeRaw = async (id, record) => {
+ assertId(id);
+ return (await facade.getBackend()).writeRaw(id, record);
+};
+
+export const queueStoryboardWrite = (id, fn) => queueRecordWrite(id, fn);
+
+export function _resetStoryboardBackend() {
+ facade.reset();
+}