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 saved recipe library and Make empty panels (#12925)

[._.]/f0d97e40f2f8
diff --git a/client/src/components/storyboards/MakeEmptyPanels.jsx b/client/src/components/storyboards/MakeEmptyPanels.jsx
new file mode 100644
index 0000000000..0b8f7826d3
--- /dev/null
+++ b/client/src/components/storyboards/MakeEmptyPanels.jsx
@@ -0,0 +1,91 @@
+import { useEffect, useState } from 'react';
+import { Loader2, Wand2 } from 'lucide-react';
+import InlineConfirmRow from '../ui/InlineConfirmRow';
+import ProgressBar from '../ui/ProgressBar';
+import toast from '../ui/Toast';
+import socket from '../../services/socket';
+import { getStoryboardMakeEmpty, startStoryboardMakeEmpty } from '../../services/api';
+import { formatCount } from '../../utils/formatters';
+
+const plural = (n, word) => `${formatCount(n)} ${word}${n === 1 ? '' : 's'}`;
+
+function planQuestion({ panelCount, steps }) {
+ const parts = steps.map((step) => (step.type === 'image'
+ ? `${step.title} makes ${plural(step.frames, 'frame')} each with ${step.model}`
+ : `${step.title} runs on ${step.model}`));
+ return `Make ${plural(panelCount, 'empty panel')}? ${parts.join('; ')}. Prompts already written are kept.`;
+}
+
+/**
+ * "Make empty panels": runs the board's recipe on every panel with no art.
+ * The confirm names each model and the panel count before anything runs;
+ * progress arrives on `storyboard:make-batch` (the panels' own frames still
+ * arrive on `storyboard:make`, which the page already follows).
+ */
+export default function MakeEmptyPanels({ boardId }) {
+ const [batch, setBatch] = useState(null);
+ const [plan, setPlan] = useState(null);
+ const [loading, setLoading] = useState(false);
+ const [note, setNote] = useState('');
+
+ useEffect(() => {
+ let active = true;
+ // A batch started in another tab, or before a reload, is still shown.
+ getStoryboardMakeEmpty(boardId, { silent: true })
+ .then((res) => { if (active) setBatch(res?.batch || null); })
+ .catch(() => {});
+ const onBatch = (evt) => {
+ if (evt?.storyboardId !== boardId) return;
+ if (evt.status !== 'done') { setBatch(evt); return; }
+ setBatch(null);
+ const made = evt.done - evt.failed;
+ if (evt.failed) toast.error(`Made ${plural(made, 'panel')}; ${plural(evt.failed, 'panel')} could not be made. Open one to see why.`);
+ else toast.success(`Made ${plural(made, 'panel')}.`);
+ };
+ socket.on('storyboard:make-batch', onBatch);
+ return () => {
+ active = false;
+ socket.off('storyboard:make-batch', onBatch);
+ };
+ }, [boardId]);
+
+ const openConfirm = async () => {
+ setLoading(true);
+ setNote('');
+ const next = await getStoryboardMakeEmpty(boardId).catch(() => null);
+ setLoading(false);
+ if (!next) return;
+ if (next.batch) { setBatch(next.batch); return; }
+ if (!next.panelCount) { setNote('Every panel already has art.'); return; }
+ if (!next.steps.some((step) => step.type === 'image')) { setNote('The recipe has no Image node, so there is nothing to make.'); return; }
+ setPlan(next);
+ };
+
+ const start = async () => {
+ setPlan(null);
+ const res = await startStoryboardMakeEmpty(boardId).catch(() => null);
+ if (res?.batch) setBatch(res.batch);
+ };
+
+ if (batch) {
+ return (
+ <div className="flex min-h-[44px] min-w-[12rem] flex-1 items-center gap-2 sm:flex-none">
+ <ProgressBar percent={(batch.done / batch.total) * 100} label="Making empty panels" className="flex-1" />
+ <span className="text-xs text-gray-400 tabular-nums shrink-0">{formatCount(batch.done)} of {formatCount(batch.total)}</span>
+ </div>
+ );
+ }
+ return (
+ <>
+ <button type="button" onClick={openConfirm} disabled={loading}
+ className="min-h-[44px] inline-flex items-center gap-1.5 rounded border border-port-border px-3 text-sm text-gray-200 hover:border-port-accent/60 hover:text-white disabled:opacity-40">
+ {loading ? <Loader2 size={16} className="animate-spin" aria-hidden="true" /> : <Wand2 size={16} aria-hidden="true" />} Make empty panels
+ </button>
+ {note && <p role="status" className="basis-full text-xs text-gray-400">{note}</p>}
+ {plan && (
+ <InlineConfirmRow autoFocus aria-label="Make empty panels" className="basis-full" tone="warning" confirmText="Make"
+ question={planQuestion(plan)} onConfirm={start} onCancel={() => setPlan(null)} />
+ )}
+ </>
+ );
+}
diff --git a/client/src/components/storyboards/PanelMakeTab.jsx b/client/src/components/storyboards/PanelMakeTab.jsx
index d49673fcc4..49adbb0761 100644
--- a/client/src/components/storyboards/PanelMakeTab.jsx
+++ b/client/src/components/storyboards/PanelMakeTab.jsx
@@ -16,6 +16,7 @@ import TabPills from '../ui/TabPills';
import useUrlParams from '../../hooks/useUrlParams';
import CommitField from './CommitField';
import RecipeCanvas from './RecipeCanvas';
+import RecipeLibrary from './RecipeLibrary';
import RecipeNodeCard, { NODE_ICONS } from './RecipeNodeCard';
import { takeSrc } from './storyboardArt';
@@ -369,6 +370,7 @@ export default function PanelMakeTab({ board, found, sketchNonce, handlers }) {
question="Restore the default recipe? This board's node edits and wiring are replaced."
onConfirm={() => { setConfirmReset(false); saveRecipe(null); }} onCancel={() => setConfirmReset(false)} />
)}
+ <RecipeLibrary recipe={recipe} onLoad={saveRecipe} />
<p className="text-[11px] text-gray-500">The recipe is shared by every panel on this board. Each node runs only when you tap it.</p>
<div className="hidden lg:block">
<TabPills tabs={VIEW_TABS} activeTab={canvas ? 'canvas' : 'chain'} variant="pills" size="sm" ariaLabel="Recipe view"
diff --git a/client/src/components/storyboards/RecipeLibrary.jsx b/client/src/components/storyboards/RecipeLibrary.jsx
new file mode 100644
index 0000000000..d09a51c599
--- /dev/null
+++ b/client/src/components/storyboards/RecipeLibrary.jsx
@@ -0,0 +1,127 @@
+import { useState } from 'react';
+import { BookmarkPlus, FolderOpen, Trash2 } from 'lucide-react';
+import InlineConfirmRow from '../ui/InlineConfirmRow';
+import toast from '../ui/Toast';
+import { deleteStoryboardRecipe, listStoryboardRecipes, saveStoryboardRecipe } from '../../services/api';
+import { RECIPE_LIMITS } from '../../../../server/lib/storyboardRecipe.js';
+
+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 fieldClass = 'min-h-[44px] w-full bg-port-bg border border-port-border rounded px-2 text-sm text-white';
+
+/**
+ * The saved recipe library on the Make tab: "Save as…" keeps a named copy of
+ * this board's recipe; "Load…" copies a saved one onto the board (the saved
+ * copy never changes when the board's recipe is edited afterwards).
+ */
+export default function RecipeLibrary({ recipe, onLoad }) {
+ const [mode, setMode] = useState(null);
+ const [name, setName] = useState('');
+ const [saving, setSaving] = useState(false);
+ const [saved, setSaved] = useState(null);
+ const [loadError, setLoadError] = useState(false);
+ const [pickedId, setPickedId] = useState('');
+ const [confirm, setConfirm] = useState(null);
+ const picked = saved?.find((item) => item.id === pickedId) || null;
+
+ const close = () => { setMode(null); setConfirm(null); };
+
+ const openLoad = () => {
+ setMode('load');
+ setLoadError(false);
+ listStoryboardRecipes({ silent: true })
+ .then((rows) => {
+ const list = Array.isArray(rows) ? rows : [];
+ setSaved(list);
+ setPickedId((prev) => (list.some((item) => item.id === prev) ? prev : list[0]?.id || ''));
+ })
+ // A failed read says so; it must not look like an empty library.
+ .catch(() => setLoadError(true));
+ };
+
+ const save = async (event) => {
+ event.preventDefault();
+ const trimmed = name.trim();
+ if (!trimmed) return;
+ setSaving(true);
+ const record = await saveStoryboardRecipe(trimmed, { nodes: recipe.nodes, edges: recipe.edges }).catch(() => null);
+ setSaving(false);
+ if (!record) return;
+ setSaved((prev) => (prev ? [record, ...prev] : prev));
+ setName('');
+ close();
+ toast.success(`Saved "${record.name}".`);
+ };
+
+ const remove = async () => {
+ const target = picked;
+ setConfirm(null);
+ if (!target || !(await deleteStoryboardRecipe(target.id).catch(() => null))) return;
+ const rest = saved.filter((item) => item.id !== target.id);
+ setSaved(rest);
+ setPickedId(rest[0]?.id || '');
+ };
+
+ const load = () => {
+ const target = picked;
+ close();
+ if (target) onLoad(structuredClone(target.recipe));
+ };
+
+ return (
+ <div className="space-y-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <button type="button" onClick={() => (mode === 'save' ? close() : setMode('save'))} aria-expanded={mode === 'save'} className={actionButton}>
+ <BookmarkPlus size={16} aria-hidden="true" /> Save as…
+ </button>
+ <button type="button" onClick={() => (mode === 'load' ? close() : openLoad())} aria-expanded={mode === 'load'} className={actionButton}>
+ <FolderOpen size={16} aria-hidden="true" /> Load…
+ </button>
+ </div>
+ {mode === 'save' && (
+ <form onSubmit={save} className="flex flex-wrap items-end gap-2 rounded-lg border border-port-border p-2">
+ <div className="flex-1 min-w-[12rem]">
+ <label htmlFor="recipe-save-name" className="block text-[11px] text-gray-500 mb-0.5">Recipe name</label>
+ <input id="recipe-save-name" autoFocus value={name} maxLength={RECIPE_LIMITS.title} onChange={(e) => setName(e.target.value)}
+ placeholder="Pencil frames, two references" className={fieldClass} />
+ </div>
+ <button type="submit" disabled={saving || !name.trim()} className={`${actionButton} bg-port-accent/20 border-port-accent/50`}>Save</button>
+ <button type="button" onClick={close} className={actionButton}>Cancel</button>
+ </form>
+ )}
+ {mode === 'load' && (
+ <div className="space-y-2 rounded-lg border border-port-border p-2">
+ {loadError ? (
+ <p role="status" className="text-xs text-port-warning">Saved recipes could not be read. Try Load… again.</p>
+ ) : !saved ? (
+ <p role="status" className="text-xs text-gray-500">Reading saved recipes…</p>
+ ) : !saved.length ? (
+ <p className="text-xs text-gray-500">No saved recipes yet. Save as… keeps this one.</p>
+ ) : (
+ <div className="flex flex-wrap items-end gap-2">
+ <div className="flex-1 min-w-[12rem]">
+ <label htmlFor="recipe-load-pick" className="block text-[11px] text-gray-500 mb-0.5">Saved recipe</label>
+ <select id="recipe-load-pick" value={pickedId} onChange={(e) => { setPickedId(e.target.value); setConfirm(null); }} className={fieldClass}>
+ {saved.map((item) => <option key={item.id} value={item.id}>{item.name} ({item.recipe.nodes.length} nodes)</option>)}
+ </select>
+ </div>
+ <button type="button" onClick={() => setConfirm('load')} disabled={!picked} className={`${actionButton} bg-port-accent/20 border-port-accent/50`}>Load</button>
+ <button type="button" onClick={() => setConfirm('delete')} disabled={!picked} aria-label={picked ? `Delete ${picked.name}` : 'Delete saved recipe'} className={actionButton}>
+ <Trash2 size={16} aria-hidden="true" />
+ </button>
+ </div>
+ )}
+ {confirm === 'load' && picked && (
+ <InlineConfirmRow autoFocus aria-label={`Load ${picked.name}`} confirmText="Load" tone="warning"
+ question={`Load "${picked.name}"? This board's recipe is replaced by a copy; the saved recipe stays as it is.`}
+ onConfirm={load} onCancel={() => setConfirm(null)} />
+ )}
+ {confirm === 'delete' && picked && (
+ <InlineConfirmRow autoFocus aria-label={`Delete ${picked.name}`}
+ question={`Delete "${picked.name}" from saved recipes? Boards that loaded it keep their copy.`}
+ onConfirm={remove} onCancel={() => setConfirm(null)} />
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/StoryboardDetail.jsx b/client/src/pages/StoryboardDetail.jsx
index 6d798b7e2c..27c7174eb2 100644
--- a/client/src/pages/StoryboardDetail.jsx
+++ b/client/src/pages/StoryboardDetail.jsx
@@ -25,6 +25,7 @@ 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 MakeEmptyPanels from '../components/storyboards/MakeEmptyPanels';
import PanelCard from '../components/storyboards/PanelCard';
import PanelDrawer from '../components/storyboards/PanelDrawer';
import { beatSeconds, findPanel } from '../components/storyboards/storyboardArt';
@@ -225,6 +226,7 @@ export default function StoryboardDetail() {
{missingMoodBoard ? <option value={board.moodBoardId}>Missing mood board</option> : null}
{moodBoards.map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}
</select>
+ {board.beats.some((beat) => beat.panels.length) && <MakeEmptyPanels boardId={id} />}
</div>
</header>
diff --git a/client/src/pages/StoryboardDetail.test.jsx b/client/src/pages/StoryboardDetail.test.jsx
index d3f62c9014..1a26bc7120 100644
--- a/client/src/pages/StoryboardDetail.test.jsx
+++ b/client/src/pages/StoryboardDetail.test.jsx
@@ -14,6 +14,11 @@ const api = vi.hoisted(() => ({
createBlankSketch: vi.fn(),
runStoryboardPanelNode: vi.fn(),
updateStoryboardRecipe: vi.fn(),
+ getStoryboardMakeEmpty: vi.fn(),
+ startStoryboardMakeEmpty: vi.fn(),
+ listStoryboardRecipes: vi.fn(),
+ saveStoryboardRecipe: vi.fn(),
+ deleteStoryboardRecipe: vi.fn(),
}));
vi.mock('../services/api', () => {
const rest = ['deleteStoryboardBeat', 'deleteStoryboardPanel', 'moveStoryboardBeat', 'moveStoryboardPanel',
@@ -21,7 +26,8 @@ vi.mock('../services/api', () => {
'updateStoryboardPanelNode', 'getStoryboardPanelMake'];
return { ...api, ...Object.fromEntries(rest.map((name) => [name, vi.fn(() => Promise.resolve([]))])) };
});
-vi.mock('../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } }));
+const socketMock = vi.hoisted(() => ({ on: vi.fn(), off: vi.fn() }));
+vi.mock('../services/socket', () => ({ default: socketMock }));
vi.mock('../components/imageGen/GalleryImagePicker', () => ({ default: () => null }));
vi.mock('../components/IngredientPicker', () => ({ default: () => null }));
vi.mock('../components/musicVideo/MusicVideoLlmPicker', () => ({ default: () => null }));
@@ -58,6 +64,7 @@ const renderAt = (path) => render(
beforeEach(() => {
for (const fn of Object.values(api)) fn.mockReset();
api.listMoodBoardNames.mockResolvedValue([]);
+ api.getStoryboardMakeEmpty.mockResolvedValue({ batch: null, panelCount: 0, steps: [] });
});
describe('StoryboardDetail', () => {
@@ -200,4 +207,58 @@ describe('StoryboardDetail', () => {
{ from: 'node-a', to: 'node-c', toPort: 'prompt' },
]);
});
+
+ it('names the models and panel count before making empty panels, then shows progress', async () => {
+ api.getStoryboard.mockResolvedValue(board());
+ api.getStoryboardMakeEmpty.mockResolvedValue({
+ batch: null,
+ panelCount: 2,
+ steps: [
+ { nodeId: 'node-writer', title: 'Prompt writer', type: 'llm', model: 'Example · example-model', frames: 0 },
+ { nodeId: 'node-image', title: 'Image', type: 'image', model: 'Default image model', frames: 4 },
+ ],
+ });
+ api.startStoryboardMakeEmpty.mockResolvedValue({ batch: { storyboardId: 'sb-1', status: 'running', total: 2, done: 0, failed: 0 } });
+ renderAt('/storyboards/sb-1');
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Make empty panels' }));
+ const confirm = await screen.findByLabelText('Make empty panels');
+ expect(confirm.textContent).toContain('Make 2 empty panels? Prompt writer runs on Example · example-model; Image makes 4 frames each with Default image model.');
+ expect(api.startStoryboardMakeEmpty).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Make' }));
+ await waitFor(() => expect(api.startStoryboardMakeEmpty).toHaveBeenCalledWith('sb-1'));
+ expect(await screen.findByText('0 of 2')).toBeInTheDocument();
+
+ const onBatch = socketMock.on.mock.calls.findLast(([event]) => event === 'storyboard:make-batch')[1];
+ act(() => onBatch({ storyboardId: 'sb-1', status: 'running', total: 2, done: 1, failed: 0 }));
+ expect(screen.getByText('1 of 2')).toBeInTheDocument();
+ act(() => onBatch({ storyboardId: 'sb-1', status: 'done', total: 2, done: 2, failed: 0 }));
+ expect(await screen.findByRole('button', { name: 'Make empty panels' })).toBeInTheDocument();
+ });
+
+ it('saves the recipe to the library and loads a saved one onto the board as a copy', async () => {
+ api.getStoryboard.mockResolvedValue(board());
+ const savedRecipe = { nodes: [{ id: 'node-a', type: 'text', title: 'Words', settings: { source: 'panel' }, x: 0, y: 0 }], edges: [] };
+ api.saveStoryboardRecipe.mockImplementation(async (name, recipe) => ({ id: 'sbr-1', name, recipe, createdAt: '', updatedAt: '' }));
+ api.listStoryboardRecipes.mockResolvedValue([{ id: 'sbr-2', name: 'Words only', recipe: savedRecipe, createdAt: '', updatedAt: '' }]);
+ api.updateStoryboardRecipe.mockImplementation(async (_id, recipe) => board({ recipe, updatedAt: '2026-10-22T00:00:03.000Z' }));
+ renderAt('/storyboards/sb-1/panel/panel-1?panelTab=make');
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Save as…' }));
+ fireEvent.change(screen.getByLabelText('Recipe name'), { target: { value: 'Pencil frames' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(api.saveStoryboardRecipe).toHaveBeenCalled());
+ const [name, sent] = api.saveStoryboardRecipe.mock.calls[0];
+ expect(name).toBe('Pencil frames');
+ expect(sent.nodes.map((n) => n.id)).toEqual(['node-text', 'node-system', 'node-writer', 'node-refs', 'node-image', 'node-panel']);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Load…' }));
+ expect(await screen.findByLabelText('Saved recipe')).toHaveValue('sbr-2');
+ fireEvent.click(screen.getByRole('button', { name: 'Load' }));
+ expect(api.updateStoryboardRecipe).not.toHaveBeenCalled();
+ fireEvent.click(screen.getAllByRole('button', { name: 'Load' }).at(-1));
+ await waitFor(() => expect(api.updateStoryboardRecipe).toHaveBeenCalledWith('sb-1', savedRecipe));
+ expect(await screen.findByRole('region', { name: 'Words node' })).toBeInTheDocument();
+ });
});
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 53201754e9..73dcdee3cb 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -87,7 +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), the panel maker (board recipe, per-panel node values, node runs); every write returns the whole board. |
+| `apiStoryboards.js` | Storyboards (Create › Storyboards): board/beat/panel CRUD and moves, panel art takes (add, select, remove), the panel maker (board recipe, per-panel node values, node runs, Make empty panels) and the saved recipe library; every board 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/apiStoryboards.js b/client/src/services/apiStoryboards.js
index 0e85500695..7a21dc62e8 100644
--- a/client/src/services/apiStoryboards.js
+++ b/client/src/services/apiStoryboards.js
@@ -54,3 +54,16 @@ export const updateStoryboardPanelNode = (id, panelId, nodeId, patch, options) =
request(`/storyboards/${enc(id)}/panels/${enc(panelId)}/make/${enc(nodeId)}`, { ...json('PATCH', patch), ...options });
export const runStoryboardPanelNode = (id, panelId, nodeId, options) =>
request(`/storyboards/${enc(id)}/panels/${enc(panelId)}/make/${enc(nodeId)}/run`, { method: 'POST', ...options });
+
+// Make empty panels. GET → { batch, panelCount, steps: [{ nodeId, title, type, model, frames }] }.
+export const getStoryboardMakeEmpty = (id, options) => request(`/storyboards/${enc(id)}/make-empty`, options);
+// → { batch } at once; `storyboard:make-batch` reports progress.
+export const startStoryboardMakeEmpty = (id, options) =>
+ request(`/storyboards/${enc(id)}/make-empty`, { method: 'POST', ...options });
+
+// The saved recipe library, shared by every board. A load copies the graph onto a board.
+export const listStoryboardRecipes = (options) => request('/storyboards/recipes', options);
+export const saveStoryboardRecipe = (name, recipe, options) =>
+ request('/storyboards/recipes', { ...json('POST', { name, recipe }), ...options });
+export const deleteStoryboardRecipe = (recipeId, options) =>
+ request(`/storyboards/recipes/${enc(recipeId)}`, { method: 'DELETE', ...options });
diff --git a/docs/API.md b/docs/API.md
index dba50063f3..0c096aa4a3 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -808,7 +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`); the panel maker at `PUT /:id/recipe` (`{ recipe \| null }`, null = default), `GET /:id/panels/:panelId/make` (linked catalog reference images), `PATCH /:id/panels/:panelId/make/:nodeId` (`{ text?, excludedRefs?, extraRefs? }`) and `POST /:id/panels/:panelId/make/:nodeId/run` (an LLM node answers when done; an image node once its frames are queued, with `storyboard:make` socket events after). Every write returns the whole board; over-limit text is refused. |
+| `/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`); the panel maker at `PUT /:id/recipe` (`{ recipe \| null }`, null = default), `GET /:id/panels/:panelId/make` (linked catalog reference images), `PATCH /:id/panels/:panelId/make/:nodeId` (`{ text?, excludedRefs?, extraRefs? }`) and `POST /:id/panels/:panelId/make/:nodeId/run` (an LLM node answers when done; an image node once its frames are queued, with `storyboard:make` socket events after). Make empty panels: `GET /:id/make-empty` (`{ batch, panelCount, steps }`: the panels with no art and each node it runs with its model) and `POST /:id/make-empty` (202, one batch per board, `storyboard:make-batch` progress). The saved recipe library: `GET`/`POST /recipes` (`{ name, recipe }`) and `DELETE /recipes/:recipeId`. 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 cdcfc0c6c7..23f4c5173c 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -149,6 +149,7 @@ does not recover nonempty output or general failed saves; those still require th
- `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. Federated as record kind `storyboard` / sync category `storyboards` (schema version-gated): one whole-board LWW unit on `updatedAt`, deletes travel as the tombstone pair, gallery-image takes ride the push asset manifest. Machine-local limits: a `sketch:` take syncs as its key only (the `data/media-sketches` sidecars do not travel, so a peer shows no drawing for it), and in-flight panel-maker runs ship as idle. 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.
+- `storyboard_recipes` — the panel maker's saved recipe library (Create › Storyboards, Make tab): one named node graph per row in `data` JSONB, with `name`/`updated_at` mirrored for the list sort. `db-primary` beside `storyboards`: any board loads a saved recipe as a copy (`board.recipe`), so the row is a template, never a live link, and per-panel run state never travels with it. Not federated yet; the tombstone pair and `updatedAt` keep a later sync category additive. No seed. Adapter: `server/services/storyboards/recipeDb.js`, selected pg-vs-collectionStore by `server/services/storyboards/recipeLibrary.js`. Migration 436 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/436-storyboard-recipes-table.js b/scripts/migrations/436-storyboard-recipes-table.js
new file mode 100644
index 0000000000..ac854a0893
--- /dev/null
+++ b/scripts/migrations/436-storyboard-recipes-table.js
@@ -0,0 +1,12 @@
+/**
+ * Registration stub for the storyboard_recipes table (the Make tab's saved
+ * recipe library). 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 435-storyboards-table.js.
+ */
+
+export default {
+ async up() {
+ console.log('🧩 storyboard recipes: table created idempotently by ensureSchema at boot; nothing to do in the file runner');
+ },
+};
diff --git a/server/lib/README.md b/server/lib/README.md
index f42232cfb5..0ea0334623 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -194,8 +194,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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. |
| `storyboardRecipe.js` | Storyboard panel maker recipes: node types and ports (`RECIPE_NODE_PORTS`: text, system, llm, references, image, panel), `defaultPanelRecipe` (Text → Prompt writer + System prompt → Image + References → Panel), `sanitizeRecipe` (edges join matching ports, no cycles), `recipeRunOrder`, `nodeInputValue` / `nodeOutputValue` (what flows into a node for one panel), `sanitizePanelMake` (per-panel run state), `STORYBOARD_RENDER_SIZES`. Browser-safe. |
-| `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. |
+| `storyboardRecord.js` | Shared Storyboard record (Create › Storyboards): `sanitizeStoryboard` (beats → panels → art takes, catalog refs by id), `sanitizeTake`, `summarizeStoryboard` (with runtime), `sanitizeSavedRecipe` (a saved recipe library entry). |
+| `storyboardVocabulary.js` | Storyboard ids (`isValidStoryboardId`, `newStoryboardId`, `isValidStoryboardRecipeId`), 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 f1cb4c3e81..ab7bca21e2 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', 'storyboards',
+ 'catalog_user_types', 'creative_director_projects', 'threejs_models', 'image_to_3d_models', 'sprite_records', 'games', 'code_animation_jobs', 'mood_boards', 'fableloom_stories', 'storyboards', 'storyboard_recipes',
'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 750b255952..9bd5fa35c6 100644
--- a/server/lib/db/schema/media.js
+++ b/server/lib/db/schema/media.js
@@ -141,6 +141,18 @@ export const mediaDdl = [
)`,
`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`,
+ // Saved storyboard recipes (the Make tab's library): one named node graph
+ // per row in `data` JSONB, loaded onto any board as a copy. Mirrors init-db.sql.
+ `CREATE TABLE IF NOT EXISTS storyboard_recipes (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ 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_storyboard_recipes_updated ON storyboard_recipes (updated_at DESC)`,
// Sprite records (issue #2895, phase 1). One row per sprite subject — a
// character or a props atlas family; the full record (spec, chromaKey,
diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.js
index a89ebb1bd8..90d224801f 100644
--- a/server/lib/socketEventContracts.js
+++ b/server/lib/socketEventContracts.js
@@ -485,6 +485,23 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({
additionalProperties: false,
},
},
+ 'storyboard:make-batch': {
+ direction: 'server-to-client',
+ summary: 'Make empty panels progress on a storyboard: panels finished of the total, and when the batch is done.',
+ payloadSchema: {
+ type: 'object',
+ properties: {
+ storyboardId: { type: 'string' },
+ status: { type: 'string', enum: ['running', 'done'] },
+ total: { type: 'number' },
+ done: { type: 'number' },
+ failed: { type: 'number' },
+ startedAt: { type: 'string' },
+ },
+ required: ['storyboardId', 'status', 'total', 'done', 'failed'],
+ additionalProperties: false,
+ },
+ },
'mood-board:item-render': {
direction: 'server-to-client',
summary: 'A mood board text note render was queued, finished (the note is now an image item) or failed; reload the board.',
diff --git a/server/lib/storyboardRecord.js b/server/lib/storyboardRecord.js
index 2fb9e40610..143f29cb02 100644
--- a/server/lib/storyboardRecord.js
+++ b/server/lib/storyboardRecord.js
@@ -23,10 +23,10 @@ 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,
+ isValidStoryboardId, isValidStoryboardRecipeId, newStoryboardEntityId, STORYBOARD_ART_STYLES, STORYBOARD_ASPECT_RATIOS, STORYBOARD_LIMITS,
STORYBOARD_MUSICAL_ROLES, STORYBOARD_PANEL_FRAMINGS, STORYBOARD_TAKE_SOURCES,
} from './storyboardVocabulary.js';
-import { sanitizePanelMake, sanitizeRecipe } from './storyboardRecipe.js';
+import { RECIPE_LIMITS, sanitizePanelMake, sanitizeRecipe } from './storyboardRecipe.js';
const SKETCH_KEY_PATTERN = /^sketch:[A-Za-z0-9-]{1,80}$/;
const ENTITY_ID_PATTERN = /^[a-z]+-[A-Za-z0-9-]{1,80}$/;
@@ -166,6 +166,25 @@ export function sanitizeStoryboard(raw) {
};
}
+/**
+ * A saved recipe in the Make tab's library: a named copy of a board's node
+ * graph that any board can load. Per-panel run state never travels with it.
+ */
+export function sanitizeSavedRecipe(raw) {
+ if (!raw || typeof raw !== 'object' || !isValidStoryboardRecipeId(raw.id)) return null;
+ const recipe = sanitizeRecipe(raw.recipe);
+ if (!recipe) return null;
+ const createdAt = isoOr(raw.createdAt, new Date().toISOString());
+ return {
+ id: raw.id,
+ name: trimTo(raw.name, RECIPE_LIMITS.title) || 'Untitled recipe',
+ recipe,
+ 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(
diff --git a/server/lib/storyboardValidation.js b/server/lib/storyboardValidation.js
index db564e02db..106961d687 100644
--- a/server/lib/storyboardValidation.js
+++ b/server/lib/storyboardValidation.js
@@ -88,11 +88,17 @@ const recipeEdge = z.object({
toPort: z.enum(Object.keys(RECIPE_PORT_LABELS)),
}).strict();
-export const storyboardRecipeSchema = z.object({
- recipe: z.object({
- nodes: z.array(recipeNode).max(R.nodes),
- edges: z.array(recipeEdge).max(R.nodes * 3),
- }).strict().nullable(),
+const recipeGraph = z.object({
+ nodes: z.array(recipeNode).max(R.nodes),
+ edges: z.array(recipeEdge).max(R.nodes * 3),
+}).strict();
+
+export const storyboardRecipeSchema = z.object({ recipe: recipeGraph.nullable() }).strict();
+
+// A library entry: a named copy of a board's graph.
+export const storyboardSavedRecipeSchema = z.object({
+ name: z.string().trim().min(1).max(R.title),
+ recipe: recipeGraph.extend({ nodes: z.array(recipeNode).min(1).max(R.nodes) }),
}).strict();
export const storyboardPanelNodeUpdateSchema = z.object({
diff --git a/server/lib/storyboardVocabulary.js b/server/lib/storyboardVocabulary.js
index daf112b631..370446871b 100644
--- a/server/lib/storyboardVocabulary.js
+++ b/server/lib/storyboardVocabulary.js
@@ -12,6 +12,9 @@ export const isValidStoryboardId = (id) => typeof id === 'string' && STORYBOARD_
// 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()}`;
+// Saved panel maker recipes (the Make tab's library), shared across boards.
+export const STORYBOARD_RECIPE_ID_PATTERN = /^sbr-[A-Za-z0-9-]{1,80}$/;
+export const isValidStoryboardRecipeId = (id) => typeof id === 'string' && STORYBOARD_RECIPE_ID_PATTERN.test(id);
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']);
diff --git a/server/routes/storyboards.js b/server/routes/storyboards.js
index b528499c57..f021c16cda 100644
--- a/server/routes/storyboards.js
+++ b/server/routes/storyboards.js
@@ -10,14 +10,17 @@ import { validateRequest } from '../lib/validation.js';
import {
storyboardBeatCreateSchema, storyboardBeatUpdateSchema, storyboardCreateSchema, storyboardMoveSchema,
storyboardPanelCreateSchema, storyboardPanelMoveSchema, storyboardPanelNodeUpdateSchema, storyboardPanelUpdateSchema,
- storyboardRecipeSchema, storyboardTakeCreateSchema, storyboardUpdateSchema,
+ storyboardRecipeSchema, storyboardSavedRecipeSchema, 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';
-import { getPanelMake, runPanelNode, updatePanelNode, updateRecipe } from '../services/storyboards/make.js';
+import {
+ getMakeEmptyPlan, getPanelMake, runPanelNode, startMakeEmpty, updatePanelNode, updateRecipe,
+} from '../services/storyboards/make.js';
+import { deleteSavedRecipe, listSavedRecipes, saveRecipe } from '../services/storyboards/recipeLibrary.js';
const router = Router();
@@ -29,6 +32,19 @@ router.post('/', asyncHandler(async (req, res) => {
res.status(201).json(await createStoryboard(validateRequest(storyboardCreateSchema, req.body ?? {})));
}));
+// The saved recipe library sits before /:id; a board id always starts "sb-".
+router.get('/recipes', asyncHandler(async (_req, res) => {
+ res.json(await listSavedRecipes());
+}));
+
+router.post('/recipes', asyncHandler(async (req, res) => {
+ res.status(201).json(await saveRecipe(validateRequest(storyboardSavedRecipeSchema, req.body ?? {})));
+}));
+
+router.delete('/recipes/:recipeId', asyncHandler(async (req, res) => {
+ res.json(await deleteSavedRecipe(req.params.recipeId));
+}));
+
router.get('/:id', asyncHandler(async (req, res) => {
res.json(await getStoryboard(req.params.id));
}));
@@ -108,4 +124,14 @@ router.post('/:id/panels/:panelId/make/:nodeId/run', asyncHandler(async (req, re
res.json(await runPanelNode(req.params.id, req.params.panelId, req.params.nodeId));
}));
+// Make empty panels: GET names what a run would do (panels, nodes, models);
+// POST starts it and answers at once, with storyboard:make-batch after.
+router.get('/:id/make-empty', asyncHandler(async (req, res) => {
+ res.json(await getMakeEmptyPlan(req.params.id));
+}));
+
+router.post('/:id/make-empty', asyncHandler(async (req, res) => {
+ res.status(202).json(await startMakeEmpty(req.params.id));
+}));
+
export default router;
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 4b907f239e..bec6951c19 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -1101,6 +1101,19 @@ CREATE TABLE IF NOT EXISTS storyboards (
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;
+-- Saved storyboard recipes (the Make tab's library). Mirrors the
+-- storyboard_recipes block in db/schema/media.js.
+CREATE TABLE IF NOT EXISTS storyboard_recipes (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ 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_storyboard_recipes_updated ON storyboard_recipes (updated_at DESC);
+
-- 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
@@ -2299,6 +2312,8 @@ 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_storyboard_recipes_audit ON storyboard_recipes;
+CREATE TRIGGER trg_storyboard_recipes_audit AFTER UPDATE OR DELETE ON storyboard_recipes 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 01d3b2d619..15d0898ed7 100644
--- a/server/services/dataManager.js
+++ b/server/services/dataManager.js
@@ -196,6 +196,7 @@ export const CATEGORIES = {
'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 },
+ 'storyboard-recipes': { label: 'Storyboard recipes', description: 'Saved panel maker recipes (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/make.js b/server/services/storyboards/make.js
index 89aae2f512..a9ae374faa 100644
--- a/server/services/storyboards/make.js
+++ b/server/services/storyboards/make.js
@@ -20,7 +20,8 @@ import { resolveImageInputPath } from '../../lib/fileUtils.js';
import { promptAddition } from '../../lib/modelInput.js';
import { CREATIVE_LATITUDE_ADDITION, withCreativeLatitude } from '../../lib/creativeLatitude.js';
import {
- effectiveRecipe, nodeInputValue, panelNodeState, RECIPE_LIMITS, sanitizeRecipe, STORYBOARD_RENDER_SIZES, upstreamNode,
+ effectiveRecipe, nodeInputValue, panelNodeState, RECIPE_LIMITS, recipeRunOrder, sanitizeRecipe, STORYBOARD_RENDER_SIZES,
+ upstreamNode,
} from '../../lib/storyboardRecipe.js';
import { newStoryboardEntityId, STORYBOARD_LIMITS } from '../../lib/storyboardVocabulary.js';
import { getStoryboard, mutateStoryboard } from './index.js';
@@ -41,6 +42,9 @@ const deps = {
emit: (payload) => import('../socket.js')
.then(({ getIo }) => getIo()?.emit('storyboard:make', payload))
.catch((err) => console.error(`❌ storyboard:make emit failed: ${err.message}`)),
+ emitBatch: (payload) => import('../socket.js')
+ .then(({ getIo }) => getIo()?.emit('storyboard:make-batch', payload))
+ .catch((err) => console.error(`❌ storyboard:make-batch emit failed: ${err.message}`)),
};
export const __setDepsForTests = (overrides) => Object.assign(deps, overrides);
@@ -282,3 +286,98 @@ export async function failPanelFrame({ storyboardId, panelId, nodeId, runId, job
});
announce(storyboardId, panelId, nodeId, 'failed', reason);
}
+
+// Make empty panels: one batch per board at a time, in memory only (a restart
+// ends it; nothing resumes on its own at boot).
+const batches = new Map();
+const RUNNABLE_TYPES = new Set(['llm', 'image']);
+const IN_FLIGHT = new Set(['running', 'queued']);
+
+const runnableSteps = (board) => recipeRunOrder(effectiveRecipe(board)).filter((node) => RUNNABLE_TYPES.has(node.type));
+// A panel with no art and no frames on the way.
+const isEmptyPanel = (panel, steps) => !panel.takes.length && !steps.some((node) => IN_FLIGHT.has(panelNodeState(panel, node.id).status));
+const emptyPanelIds = (board, steps) => board.beats.flatMap((beat) => beat.panels).filter((panel) => isEmptyPanel(panel, steps)).map((p) => p.id);
+const batchView = (storyboardId, batch) => (batch ? { storyboardId, ...batch } : null);
+
+async function stepLabel(node) {
+ if (node.type === 'image') {
+ return { nodeId: node.id, title: node.title, type: node.type, model: node.settings.imageModelId || 'Default image model', frames: node.settings.count };
+ }
+ const { provider, selectedModel } = await deps.resolveProvider({ providerId: node.settings.providerId || null, model: node.settings.model || null })
+ .catch(() => ({ provider: null }));
+ const model = provider ? [provider.name || provider.id, selectedModel].filter(Boolean).join(' · ') : 'No AI provider set up';
+ return { nodeId: node.id, title: node.title, type: node.type, model, frames: 0 };
+}
+
+/**
+ * What "Make empty panels" would do, for the confirm that names it: how many
+ * panels have no art, and each node it runs with the model it uses.
+ */
+export async function getMakeEmptyPlan(storyboardId) {
+ const board = await getStoryboard(storyboardId);
+ const steps = runnableSteps(board);
+ return {
+ batch: batchView(storyboardId, batches.get(storyboardId)),
+ panelCount: emptyPanelIds(board, steps).length,
+ steps: await Promise.all(steps.map(stepLabel)),
+ };
+}
+
+/**
+ * Run the recipe on every panel with no art, one panel after another. A
+ * prompt already written for a panel is kept (it may be the user's edit); an
+ * LLM failure skips that panel's image so no frame is made from no prompt.
+ * Answers at once; `storyboard:make-batch` reports progress.
+ */
+export async function startMakeEmpty(storyboardId) {
+ if (batches.has(storyboardId)) throw refuse('This board is already making its empty panels.', 'STORYBOARD_BATCH_RUNNING', 409);
+ const board = await getStoryboard(storyboardId);
+ const steps = runnableSteps(board);
+ if (!steps.some((node) => node.type === 'image')) throw refuse('The recipe has no Image node, so there is nothing to make.');
+ const panelIds = emptyPanelIds(board, steps);
+ if (!panelIds.length) throw refuse('Every panel already has art.');
+ // Re-checked after the read: two quick taps (or two tabs) both passed the first check.
+ if (batches.has(storyboardId)) throw refuse('This board is already making its empty panels.', 'STORYBOARD_BATCH_RUNNING', 409);
+ const batch = { status: 'running', total: panelIds.length, done: 0, failed: 0, startedAt: new Date().toISOString() };
+ batches.set(storyboardId, batch);
+ deps.emitBatch(batchView(storyboardId, batch));
+ console.log(`🎬 Storyboard ${storyboardId.slice(0, 11)} making ${panelIds.length} empty panel(s)`);
+ runBatch(storyboardId, panelIds, batch)
+ .catch((err) => console.error(`❌ Storyboard ${storyboardId.slice(0, 11)} empty-panel batch stopped: ${err.message}`))
+ .finally(() => {
+ batches.delete(storyboardId);
+ deps.emitBatch(batchView(storyboardId, { ...batch, status: 'done' }));
+ });
+ return { batch: batchView(storyboardId, batch) };
+}
+
+async function runBatch(storyboardId, panelIds, batch) {
+ for (const panelId of panelIds) {
+ const ok = await makePanel(storyboardId, panelId);
+ batch.done += 1;
+ if (!ok) batch.failed += 1;
+ deps.emitBatch(batchView(storyboardId, batch));
+ }
+}
+
+/** One panel's run; false when it was skipped or a node failed. A deleted board ends the batch. */
+async function makePanel(storyboardId, panelId) {
+ const board = await getStoryboard(storyboardId);
+ const steps = runnableSteps(board);
+ const panel = board.beats.flatMap((beat) => beat.panels).find((p) => p.id === panelId);
+ // Removed, or given art since the batch started.
+ if (!panel || !isEmptyPanel(panel, steps)) return false;
+ for (const node of steps) {
+ if (node.type === 'llm' && panelNodeState(panel, node.id).text.trim()) continue;
+ try {
+ const next = await runPanelNode(storyboardId, panelId, node.id);
+ const state = panelNodeState(locate(next, panelId).panel, node.id);
+ if (state.status === 'failed') return false;
+ } catch (err) {
+ if (err?.code === 'NOT_FOUND' && err.message.startsWith('Storyboard')) throw err;
+ console.log(`🚫 Storyboard ${storyboardId.slice(0, 11)} panel ${panelId.slice(0, 12)} ${node.title} skipped: ${err.message}`);
+ return false;
+ }
+ }
+ return true;
+}
diff --git a/server/services/storyboards/make.test.js b/server/services/storyboards/make.test.js
index f9b403840f..add6de2106 100644
--- a/server/services/storyboards/make.test.js
+++ b/server/services/storyboards/make.test.js
@@ -21,12 +21,14 @@ const provider = { id: 'example-api', name: 'Example', type: 'api', enabled: tru
let runPrompt;
let enqueue;
let emitted;
+let batchEvents;
beforeEach(() => {
runPrompt = vi.fn(async () => ({ text: ' A wide pencil frame of gym doors ' }));
let n = 0;
enqueue = vi.fn(async () => ({ jobId: `job-${(n += 1)}` }));
emitted = [];
+ batchEvents = [];
__setDepsForTests({
resolveProvider: async () => ({ provider, selectedModel: 'example-model' }),
runPrompt,
@@ -36,6 +38,7 @@ beforeEach(() => {
linkedMedia: async (ids) => new Map(ids.map((id) => [id, [{ kind: 'portrait', mediaKey: `${id}.png` }]])),
ingredient: async (id) => ({ id, name: `Name of ${id}` }),
emit: (payload) => { emitted.push(payload); },
+ emitBatch: (payload) => { batchEvents.push(payload); },
});
});
@@ -157,4 +160,53 @@ describe('storyboard panel maker', () => {
expect(nodeState(board, 'node-image')).toMatchObject({ status: 'done', failedJobIds: ['job-1'] });
expect(nodeState(board, 'node-image').error).toContain('panel is full');
});
+
+ it('makes only the empty panels, keeping a prompt already written, and runs one batch per board at a time', async () => {
+ const { id, panelId: withArt } = await boardWithPanel({ action: 'Doors' });
+ const beatId = (await api('get', `/${id}`)).body.beats[0].id;
+ await api('post', `/${id}/panels/${withArt}/takes`, { source: 'upload', image: 'mine.png' });
+ const written = (await api('post', `/${id}/beats/${beatId}/panels`, { action: 'Hallway' })).body.panelId;
+ await api('patch', `/${id}/panels/${written}/make/node-writer`, { text: 'My hallway prompt' });
+ const blank = (await api('post', `/${id}/beats/${beatId}/panels`, { action: 'Gym floor' })).body.panelId;
+
+ const plan = await api('get', `/${id}/make-empty`);
+ expect(plan.body).toMatchObject({ batch: null, panelCount: 2 });
+ expect(plan.body.steps.map((step) => [step.nodeId, step.model, step.frames])).toEqual([
+ ['node-writer', 'Example · example-model', 0], ['node-image', 'Default image model', 4],
+ ]);
+
+ let answer;
+ runPrompt.mockImplementationOnce(() => new Promise((resolve) => { answer = resolve; }));
+ // Two taps at once: only one batch starts.
+ const both = await Promise.all([api('post', `/${id}/make-empty`), api('post', `/${id}/make-empty`)]);
+ expect(both.map((res) => res.status).sort()).toEqual([202, 409]);
+ const start = both.find((res) => res.status === 202);
+ expect(start.body.batch).toMatchObject({ status: 'running', total: 2, done: 0 });
+ await vi.waitFor(() => expect(answer).toBeTypeOf('function'));
+ expect((await api('post', `/${id}/make-empty`)).status).toBe(409);
+
+ answer({ text: 'A gym floor frame' });
+ await vi.waitFor(() => expect(batchEvents.at(-1)).toMatchObject({ status: 'done', done: 2, failed: 0 }));
+ // The kept prompt was not rewritten; the blank panel got one; the panel with art was left alone.
+ expect(runPrompt).toHaveBeenCalledTimes(1);
+ expect(runPrompt.mock.calls[0][0].prompt).toContain('Gym floor');
+ expect(enqueue.mock.calls.map((call) => [call[0].params.prompt, call[0].params.storyboardPanelRender.panelId])).toEqual([
+ ...Array(4).fill(['My hallway prompt', written]), ...Array(4).fill(['A gym floor frame', blank]),
+ ]);
+ expect((await api('get', `/${id}/make-empty`)).body.batch).toBeNull();
+ });
+
+ it('keeps a library of named recipes any board can load as a copy', async () => {
+ const recipe = { nodes: [{ id: 'node-a', type: 'text', settings: { source: 'panel' } }, { id: 'node-b', type: 'image', settings: { count: 2 } }],
+ edges: [{ from: 'node-a', to: 'node-b', toPort: 'prompt' }] };
+ const saved = await api('post', '/recipes', { name: 'Straight to image', recipe });
+ expect(saved.status).toBe(201);
+ expect(saved.body).toMatchObject({ name: 'Straight to image', recipe: { edges: recipe.edges } });
+ expect((await api('post', '/recipes', { name: 'Empty', recipe: { nodes: [], edges: [] } })).status).toBe(400);
+
+ expect((await api('get', '/recipes')).body.map((r) => r.id)).toEqual([saved.body.id]);
+ expect((await api('delete', `/recipes/${saved.body.id}`)).status).toBe(200);
+ expect((await api('get', '/recipes')).body).toEqual([]);
+ expect((await api('delete', `/recipes/${saved.body.id}`)).status).toBe(404);
+ });
});
diff --git a/server/services/storyboards/recipeDb.js b/server/services/storyboards/recipeDb.js
new file mode 100644
index 0000000000..b61cac4497
--- /dev/null
+++ b/server/services/storyboards/recipeDb.js
@@ -0,0 +1,44 @@
+/**
+ * PostgreSQL leaf I/O for saved storyboard recipes (the Make tab's library).
+ * The sanitized record lives in `data` JSONB; name/updated_at are mirrored for
+ * the list sort, 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 storyboard_recipes WHERE id = $1', [id]);
+ return rows[0]?.data ?? null;
+}
+
+export async function listRaw() {
+ const { rows } = await query('SELECT data FROM storyboard_recipes 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 storyboard_recipes (id, name, data, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7)
+ ON CONFLICT (id) DO UPDATE SET
+ name = EXCLUDED.name,
+ data = EXCLUDED.data,
+ updated_at = EXCLUDED.updated_at,
+ deleted = EXCLUDED.deleted,
+ deleted_at = EXCLUDED.deleted_at`,
+ [
+ id,
+ record.name,
+ toPgJson(record),
+ createdAt,
+ mirrorTimestamp(record?.updatedAt, createdAt),
+ record.deleted === true,
+ mirrorTimestamp(record.deletedAt, null),
+ ],
+ );
+ return record;
+}
diff --git a/server/services/storyboards/recipeLibrary.js b/server/services/storyboards/recipeLibrary.js
new file mode 100644
index 0000000000..aaa7e1e03c
--- /dev/null
+++ b/server/services/storyboards/recipeLibrary.js
@@ -0,0 +1,91 @@
+/**
+ * Saved storyboard recipes — the Make tab's library of named node graphs.
+ *
+ * db-primary (`storyboard_recipes`); collectionStore keeps it runnable in
+ * tests and under the unsupported MEMORY_BACKEND=file escape hatch, the same
+ * split as the boards themselves (store.js). Loading a saved recipe copies its
+ * graph onto a board, so editing the board never changes the saved copy.
+ */
+
+import { join } from 'path';
+import { PATHS } from '../../lib/fileUtils.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { createCollectionStore } from '../../lib/collectionStore.js';
+import { createRecordWriteQueue } from '../../lib/fileWriteQueue.js';
+import { createPgFileFacade, resolvePgBackend } from '../../lib/pgFileFacade.js';
+import { sanitizeSavedRecipe } from '../../lib/storyboardRecord.js';
+import {
+ isValidStoryboardRecipeId, newStoryboardEntityId, STORYBOARD_RECIPE_ID_PATTERN,
+} from '../../lib/storyboardVocabulary.js';
+
+const TYPE_SCHEMA_VERSION = 1;
+// A library, not an archive: past this the user deletes one first.
+const SAVED_RECIPE_LIMIT = 100;
+
+function assertId(id) {
+ if (!isValidStoryboardRecipeId(id)) throw new Error(`storyboard recipes: invalid record id "${id}"`);
+}
+
+function makeFileBackend() {
+ const collection = createCollectionStore({
+ dir: join(PATHS.data, 'storyboard-recipes'),
+ type: 'storyboard-recipes',
+ schemaVersion: TYPE_SCHEMA_VERSION,
+ idPattern: STORYBOARD_RECIPE_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: 'Storyboard recipes require PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the unsupported file backend)',
+ loadDb: () => import('./recipeDb.js'),
+ makePg: (db) => ({ name: 'postgres', readRaw: db.readRaw, listRaw: db.listRaw, writeRaw: db.writeRaw }),
+ }),
+});
+
+const queueRecordWrite = createRecordWriteQueue(assertId);
+const backend = () => facade.getBackend();
+const notFound = () => new ServerError('Saved recipe not found', { status: 404, code: 'NOT_FOUND' });
+
+export async function listSavedRecipes() {
+ const rows = await (await backend()).listRaw();
+ return rows
+ .map(sanitizeSavedRecipe)
+ .filter((record) => record && !record.deleted)
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
+}
+
+async function getSavedRecipe(id) {
+ if (!isValidStoryboardRecipeId(id)) throw notFound();
+ const record = sanitizeSavedRecipe(await (await backend()).readRaw(id));
+ if (!record || record.deleted) throw notFound();
+ return record;
+}
+
+export async function saveRecipe({ name, recipe }) {
+ if ((await listSavedRecipes()).length >= SAVED_RECIPE_LIMIT) {
+ throw new ServerError(`The library keeps at most ${SAVED_RECIPE_LIMIT} recipes; delete one first.`, { status: 409, code: 'STORYBOARD_LIMIT' });
+ }
+ const now = new Date().toISOString();
+ const record = sanitizeSavedRecipe({ id: newStoryboardEntityId('sbr'), name, recipe, createdAt: now, updatedAt: now });
+ await (await backend()).writeRaw(record.id, record);
+ console.log(`🧩 Saved storyboard recipe ${record.id}`);
+ return record;
+}
+
+export async function deleteSavedRecipe(id) {
+ if (!isValidStoryboardRecipeId(id)) throw notFound();
+ return queueRecordWrite(id, async () => {
+ const current = await getSavedRecipe(id);
+ const now = new Date().toISOString();
+ await (await backend()).writeRaw(id, { ...current, updatedAt: now, deleted: true, deletedAt: now });
+ return { id };
+ });
+}