Skip to content

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

feat(pipeline): per-shot start-frame renders inside storyboard scenes

[._.]/ Adam Eivyb7b9755b364f
diff --git a/client/src/components/pipeline/stages/StoryboardsStage.jsx b/client/src/components/pipeline/stages/StoryboardsStage.jsx
index 2ee76f3bba..cb6e66f588 100644
--- a/client/src/components/pipeline/stages/StoryboardsStage.jsx
+++ b/client/src/components/pipeline/stages/StoryboardsStage.jsx
@@ -22,6 +22,7 @@ import toast from '../../ui/Toast';
import {
generatePipelineVisualImage,
generatePipelineSceneVideo,
+ generatePipelineShotStartFrame,
refinePipelineSceneImagePrompt,
updatePipelineIssue,
updateIssueStageVisualStyle,
@@ -39,6 +40,10 @@ export default function StoryboardsStage({ issue, series, onStageUpdate, actions
const [savingIdx, setSavingIdx] = useState(null);
const [renderingVideoIdx, setRenderingVideoIdx] = useState(null);
const [refiningIdx, setRefiningIdx] = useState(null);
+ // Active per-shot renders keyed by `${sceneIdx}:${shotIdx}` so multiple
+ // shots can render concurrently with independent spinners. A single ref
+ // would race when the user starts a second render before the first settles.
+ const [renderingShots, setRenderingShots] = useState(() => new Set());
const [extractingFrom, setExtractingFrom] = useState(null);
// Holds the active arm-timer id so an unmount or a fresh arm clears the
// pending disarm — otherwise the 5s callback fires setExtractingFrom on
@@ -73,6 +78,63 @@ export default function StoryboardsStage({ issue, series, onStageUpdate, actions
setScenes(next);
};
+ // Shot id stable enough for React keys + filename-hook correlation. Local
+ // generation (vs server-assigned) is fine — every later persist round-trips
+ // through the server which keeps whatever id the client wrote.
+ const mintShotId = () => `shot-${Math.random().toString(36).slice(2, 10)}`;
+
+ const updateShots = (sceneIdx, transform) => {
+ const next = scenes.map((s, j) => {
+ if (j !== sceneIdx) return s;
+ const shots = Array.isArray(s.shots) ? s.shots : [];
+ return { ...s, shots: transform(shots) };
+ });
+ setScenes(next);
+ return next;
+ };
+
+ const addShot = (sceneIdx) => persist(updateShots(sceneIdx, (shots) =>
+ [...shots, { id: mintShotId(), description: '', durationSeconds: 4 }]));
+ const removeShot = (sceneIdx, shotIdx) => persist(updateShots(sceneIdx, (shots) =>
+ shots.filter((_, j) => j !== shotIdx)));
+ const updateShot = (sceneIdx, shotIdx, patch) => {
+ // Local edit only — caller flushes via onBlur → persist(scenes).
+ updateShots(sceneIdx, (shots) => shots.map((sh, j) => j === shotIdx ? { ...sh, ...patch } : sh));
+ };
+
+ const handleRenderShot = async (sceneIdx, shotIdx) => {
+ const shot = scenes[sceneIdx].shots[shotIdx];
+ const fallbackDesc = (scenes[sceneIdx].description || '').trim();
+ if (!(shot?.description || '').trim() && !fallbackDesc) {
+ toast.error('Add a shot or scene description first');
+ return;
+ }
+ // Flush any pending local edits to the server before rendering — otherwise
+ // the server reads the pre-edit shot.description (CLAUDE.md "In-flight
+ // saves must gate dependent actions"). persist() returns when the PATCH
+ // has settled, so the next read by the enqueue route sees the latest text.
+ await persist(scenes);
+ const key = `${sceneIdx}:${shotIdx}`;
+ setRenderingShots((prev) => new Set(prev).add(key));
+ const result = await generatePipelineShotStartFrame(issue.id, sceneIdx, shotIdx, {
+ ...genConfigToImageOptions(genConfig),
+ }).catch((err) => {
+ toast.error(err.message || 'Shot render failed');
+ return null;
+ });
+ setRenderingShots((prev) => {
+ const next = new Set(prev);
+ next.delete(key);
+ return next;
+ });
+ if (!result) return;
+ if (result.issue) {
+ setScenes(result.issue.stages.storyboards.scenes || []);
+ onStageUpdate?.('storyboards', result.issue.stages.storyboards, result.issue);
+ }
+ toast.success(`Queued shot ${shotIdx + 1} render (${result.jobId.slice(0, 8)})`);
+ };
+
// Replace-existing confirm uses a two-click arm pattern (no window.confirm
// per CLAUDE.md, no shared confirm-modal primitive in the pipeline yet).
// First click on a button when scenes is non-empty arms it (label flips to
@@ -324,6 +386,17 @@ export default function StoryboardsStage({ issue, series, onStageUpdate, actions
) : null}
</div>
</div>
+ <ShotList
+ sceneIdx={i}
+ shots={Array.isArray(scene.shots) ? scene.shots : []}
+ renderingShots={renderingShots}
+ actionsGated={actionsGated}
+ onAddShot={() => addShot(i)}
+ onRemoveShot={(j) => removeShot(i, j)}
+ onUpdateShot={(j, patch) => updateShot(i, j, patch)}
+ onBlurShot={() => persist(scenes)}
+ onRenderShot={(j) => handleRenderShot(i, j)}
+ />
</li>
))}
</ul>
@@ -331,3 +404,80 @@ export default function StoryboardsStage({ issue, series, onStageUpdate, actions
</div>
);
}
+
+function ShotList({
+ sceneIdx, shots, renderingShots, actionsGated,
+ onAddShot, onRemoveShot, onUpdateShot, onBlurShot, onRenderShot,
+}) {
+ const hasShots = shots.length > 0;
+ return (
+ <div className="mt-3 pt-3 border-t border-port-border/60">
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-[10px] uppercase tracking-wider text-gray-500">
+ Shots {hasShots ? `(${shots.length})` : '— optional breakdown'}
+ </span>
+ <button
+ type="button"
+ onClick={onAddShot}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded bg-port-card border border-port-border text-gray-300 text-[11px] hover:border-port-accent/50 hover:text-white"
+ >
+ <Plus size={11} /> Add shot
+ </button>
+ </div>
+ {hasShots ? (
+ <ul className="space-y-2">
+ {shots.map((shot, j) => {
+ const isRendering = renderingShots.has(`${sceneIdx}:${j}`);
+ return (
+ <li key={shot.id || j} className="flex items-start gap-2 p-2 bg-port-bg/40 border border-port-border/60 rounded">
+ <span className="text-[10px] text-gray-500 font-mono pt-1.5 w-6">{j + 1}</span>
+ <textarea
+ value={shot.description || ''}
+ onChange={(e) => onUpdateShot(j, { description: e.target.value })}
+ onBlur={onBlurShot}
+ placeholder="One camera setup. Subject + framing + motion + mood."
+ rows={2}
+ className="flex-1 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-xs"
+ maxLength={4000}
+ />
+ <div className="flex flex-col gap-1 w-24">
+ <input
+ type="number"
+ min={1}
+ max={30}
+ value={shot.durationSeconds ?? 4}
+ onChange={(e) => onUpdateShot(j, { durationSeconds: Number(e.target.value) || 4 })}
+ onBlur={onBlurShot}
+ title="Duration in seconds"
+ className="px-1 py-1 bg-port-bg border border-port-border rounded text-white text-[10px] text-center"
+ />
+ <button
+ type="button"
+ onClick={() => onRenderShot(j)}
+ disabled={isRendering || actionsGated}
+ title={actionsGated ? 'Saving settings…' : 'Render this shot as a start-frame image'}
+ className="inline-flex items-center justify-center gap-1 px-2 py-1 rounded bg-port-card border border-port-border text-white text-[11px] hover:border-port-accent/50 disabled:opacity-50"
+ >
+ {isRendering ? <Loader2 size={11} className="animate-spin" /> : <Sparkles size={11} />}
+ Render
+ </button>
+ {shot.startFrameJobId ? (
+ <MediaJobThumb jobId={shot.startFrameJobId} label={`Shot ${j + 1}`} size="sm" />
+ ) : null}
+ </div>
+ <button
+ type="button"
+ onClick={() => onRemoveShot(j)}
+ className="text-gray-500 hover:text-port-error p-1 mt-0.5"
+ aria-label="Remove shot"
+ >
+ <Trash2 size={12} />
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ ) : null}
+ </div>
+ );
+}
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index c6d2c976a2..1e7a830f63 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -203,6 +203,15 @@ export const generatePipelineSceneVideo = (issueId, sceneIndex, opts = {}) =>
body: JSON.stringify(opts),
});
+// Render the start-frame image for a single shot inside a storyboard scene.
+// Server persists the resulting jobId on
+// stages.storyboards.scenes[sceneIndex].shots[shotIndex].startFrameJobId.
+export const generatePipelineShotStartFrame = (issueId, sceneIndex, shotIndex, opts = {}) =>
+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/storyboards/scenes/${encodeURIComponent(sceneIndex)}/shots/${encodeURIComponent(shotIndex)}/render`, {
+ method: 'POST',
+ body: JSON.stringify(opts),
+ });
+
// LLM-driven refinement of a single comic panel's description into a
// richer image-gen prompt. Uses the pipeline-comic-panel-image-prompt
// stage with neighboring-panel continuity context. Server persists the
diff --git a/server/index.js b/server/index.js
index 42ca3a6e95..ed3e1416fc 100644
--- a/server/index.js
+++ b/server/index.js
@@ -91,6 +91,7 @@ import writersRoomRoutes from './routes/writersRoom.js';
import universeBuilderRoutes from './routes/universeBuilder.js';
import { initUniverseBuilderCollectionHook } from './services/universeBuilderCollectionHook.js';
import { initComicPagesFilenameHook } from './services/pipeline/comicPagesFilenameHook.js';
+import { initStoryboardsFilenameHook } from './services/pipeline/storyboardsFilenameHook.js';
import pipelineRoutes from './routes/pipeline.js';
import { initMediaJobQueue } from './services/mediaJobQueue/index.js';
import { recoverInFlightProjects } from './services/creativeDirector/recovery.js';
@@ -523,10 +524,11 @@ ensureSelf()
// Universe Builder needs the media job queue running before it can listen
// for `completed` events — so initialize the hook here.
initUniverseBuilderCollectionHook();
- // Pipeline comic-pages filename hook also subscribes to media-job
- // completion — stamps `filename` onto cover/page records so the UI can
- // still render them after the 24h media-job archive TTL elapses.
+ // Pipeline filename hooks — stamp `filename` onto stage records on
+ // media-job completion so the UI can still render them after the
+ // 24h media-job archive TTL elapses.
initComicPagesFilenameHook();
+ initStoryboardsFilenameHook();
})
.then(() => {
// Sharing: attach chokidar watchers to every registered share bucket so
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index af26bc2b51..8b723eae61 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -42,6 +42,7 @@ import {
enqueueVisualComicPage,
enqueueComicCover,
enqueueStoryboardSceneVideo,
+ enqueueStoryboardShotStartFrame,
refineComicPanelPrompt,
refineStoryboardScenePrompt,
} from '../services/pipeline/visualStages.js';
@@ -1099,6 +1100,29 @@ router.post('/issues/:id/stages/storyboards/scenes/:index/refine-prompt',
}),
);
+// Render the start-frame image for a single shot inside a storyboard scene.
+// Shot-level granularity sits parallel to the existing scene-level image
+// render: a scene either has shots[] (per-shot images) or doesn't (per-scene
+// image). Caller persists the jobId on `scene.shots[shotIndex].startFrameJobId`;
+// the storyboards filename hook later stamps `startFrameFilename` on
+// completion.
+router.post(
+ '/issues/:id/stages/storyboards/scenes/:sceneIndex/shots/:shotIndex/render',
+ asyncHandler(async (req, res) => {
+ const sceneIndex = Number(req.params.sceneIndex);
+ const shotIndex = Number(req.params.shotIndex);
+ if (!Number.isInteger(sceneIndex) || sceneIndex < 0 || !Number.isInteger(shotIndex) || shotIndex < 0) {
+ throw new ServerError('sceneIndex and shotIndex must be non-negative integers', {
+ status: 400, code: 'PIPELINE_SHOT_BAD_INDEX',
+ });
+ }
+ const body = validateRequest(comicPageRenderSchema, req.body ?? {});
+ const result = await enqueueStoryboardShotStartFrame(req.params.id, sceneIndex, shotIndex, body)
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+ }),
+);
+
// Render a single storyboard scene as a video clip, independent of the
// full episode-video stitch. Persists the resulting jobId on the scene's
// `sceneVideoJobId` so a reload still shows the in-flight render.
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index bd11c559f4..def19ab002 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -88,6 +88,15 @@ vi.mock('../services/pipeline/visualStages.js', () => ({
issue: { id: issueId, stages: { storyboards: { scenes: [] } } },
stage: { scenes: [] },
})),
+ enqueueStoryboardShotStartFrame: vi.fn(async (issueId, sceneIndex, shotIndex) => ({
+ jobId: `shot-img-${++uuidCounter}`,
+ mode: 'local',
+ prompt: `shot ${shotIndex} prompt`,
+ sceneIndex,
+ shotIndex,
+ issue: { id: issueId, stages: { storyboards: { scenes: [] } } },
+ stage: { scenes: [] },
+ })),
refineComicPanelPrompt: vi.fn(async (issueId, pi, ni) => ({
panel: { description: 'refined panel body' },
page: { panels: [] },
@@ -284,6 +293,29 @@ describe('pipeline routes', () => {
expect(r.status).toBe(400);
});
+ it('POST /issues/:id/stages/storyboards/scenes/:sceneIndex/shots/:shotIndex/render returns the enqueued jobId', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/storyboards/scenes/0/shots/2/render`)
+ .send({});
+ expect(r.status).toBe(200);
+ expect(r.body.jobId).toMatch(/^shot-img-/);
+ expect(r.body.sceneIndex).toBe(0);
+ expect(r.body.shotIndex).toBe(2);
+ });
+
+ it('POST /issues/:id/stages/storyboards/scenes/:sceneIndex/shots/:shotIndex/render rejects bad indices', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/stages/storyboards/scenes/nope/shots/0/render`)
+ .send({});
+ expect(r.status).toBe(400);
+ });
+
it('POST /issues/:id/stages/comicPages/pages/:p/panels/:n/refine-prompt returns the refined panel + changes', async () => {
const app = makeApp();
const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
diff --git a/server/services/pipeline/comicPagesFilenameHook.js b/server/services/pipeline/comicPagesFilenameHook.js
index 5389693260..c3d97bf809 100644
--- a/server/services/pipeline/comicPagesFilenameHook.js
+++ b/server/services/pipeline/comicPagesFilenameHook.js
@@ -1,83 +1,38 @@
/**
* Pipeline comic-pages — filename hook.
*
- * The pipeline previously stored only `imageJobId` on each cover/page.
- * `mediaJobQueue` prunes completed jobs after 24h, so the UI can no longer
- * resolve a filename to render even though the PNG is still on disk.
- * This listener stamps `filename` onto the record at completion time so
- * the client has a fallback that survives the queue's TTL.
- *
- * Panel renders are intentionally NOT handled here — `enqueueVisualImage`'s
- * owner string doesn't encode page/panel position, so we can't locate the
- * target record from the event alone. Encode position into that owner
+ * Stamps `filename` onto the matching cover/page record on media-job
+ * completion so the UI keeps rendering after mediaJobQueue's 24h archive
+ * TTL expires. Panel renders are intentionally NOT handled here —
+ * enqueueVisualImage's owner string doesn't encode page/panel position,
+ * so the hook can't locate the target. Encode position into that owner
* before extending this hook to panels.
- *
- * Failures are logged but never thrown — a bookkeeping miss must not
- * crash the server or fail the user's render.
*/
-import { mediaJobEvents } from '../mediaJobQueue/index.js';
-import { updateStageWithLatest } from './issues.js';
import { parseComicPagesOwner } from './owners.js';
+import { createFilenameHook } from './filenameHookFactory.js';
-let registeredHandler = null;
-
-export function initComicPagesFilenameHook() {
- if (registeredHandler) return;
-
- registeredHandler = (job) => {
- void (async () => {
- if (!job || job.kind !== 'image') return;
- const filename = job.result?.filename;
- if (typeof filename !== 'string' || !filename) return;
- const parsed = parseComicPagesOwner(job.owner);
- if (!parsed) return;
-
- const shortId = String(job.id || '').slice(0, 8);
- let stamped = false;
- await updateStageWithLatest(
- parsed.issueId,
- 'comicPages',
- (currentStage) => {
- if (parsed.target === 'cover') {
- const cover = currentStage?.cover;
- // Only stamp if THIS job is still the cover's active render —
- // a re-render that landed between enqueue and this event would
- // otherwise be overwritten with the older filename. Empty patch
- // is a no-op (updateStageWithLatest short-circuits on `{}`).
- if (!cover || cover.imageJobId !== job.id) return {};
- stamped = true;
- return { cover: { ...cover, filename } };
- }
- const pages = Array.isArray(currentStage?.pages) ? currentStage.pages : [];
- const page = pages[parsed.pageIndex];
- if (!page || page.imageJobId !== job.id) return {};
- const nextPages = [...pages];
- nextPages[parsed.pageIndex] = { ...page, filename };
- stamped = true;
- return { pages: nextPages };
- },
- ).catch((err) => {
- console.error(`❌ comicPages filename hook failed for job ${shortId}: ${err?.message || err}`);
- });
-
- if (stamped) {
- const where = parsed.target === 'cover' ? 'cover' : `page${parsed.pageIndex}`;
- console.log(`📎 comicPages filename stamped — issue=${parsed.issueId.slice(0, 8)} ${where} ← ${filename}`);
- }
- })().catch((err) => {
- console.error(`❌ comicPages filename hook crashed: ${err?.message || err}`);
- });
- };
- mediaJobEvents.on('completed', registeredHandler);
- console.log('📎 comicPages filename hook initialized');
-}
-
-export const __testing = {
- reset: () => {
- if (registeredHandler) {
- mediaJobEvents.off('completed', registeredHandler);
- registeredHandler = null;
+const hook = createFilenameHook({
+ name: 'comicPages',
+ stageId: 'comicPages',
+ parseOwner: parseComicPagesOwner,
+ applyFilename: (currentStage, parsed, job, filename) => {
+ if (parsed.target === 'cover') {
+ // Only stamp if THIS job is still the cover's active render — a
+ // re-render that landed between enqueue and this event would
+ // otherwise be overwritten with the older filename.
+ const cover = currentStage?.cover;
+ if (!cover || cover.imageJobId !== job.id) return null;
+ return { patch: { cover: { ...cover, filename } }, label: 'cover' };
}
+ const pages = Array.isArray(currentStage?.pages) ? currentStage.pages : [];
+ const page = pages[parsed.pageIndex];
+ if (!page || page.imageJobId !== job.id) return null;
+ const nextPages = [...pages];
+ nextPages[parsed.pageIndex] = { ...page, filename };
+ return { patch: { pages: nextPages }, label: `page${parsed.pageIndex}` };
},
-};
+});
+
+export const initComicPagesFilenameHook = hook.init;
+export const __testing = hook.__testing;
diff --git a/server/services/pipeline/filenameHookFactory.js b/server/services/pipeline/filenameHookFactory.js
new file mode 100644
index 0000000000..61f0bbbb32
--- /dev/null
+++ b/server/services/pipeline/filenameHookFactory.js
@@ -0,0 +1,70 @@
+/**
+ * Factory for pipeline media-job filename hooks.
+ *
+ * Stage-specific hooks (comicPages, storyboards, …) share the same skeleton:
+ * subscribe to mediaJobEvents 'completed', parse the job's owner string,
+ * stamp a `filename` onto the matching stage record so the path survives
+ * the mediaJobQueue's 24h archive TTL. The differences are the owner-parse
+ * function, the target stage id, and the per-shape reducer that applies
+ * the filename. Everything else — idempotent init, error logging, log
+ * narrative on success, test reset — is identical.
+ *
+ * `applyFilename(currentStage, parsed, job, filename)` returns either
+ * { patch, label } → stage gets the patch; label is logged
+ * or `null` to skip (e.g. stale jobId after a re-render — see CLAUDE.md
+ * "Pending socket-request tracking" for the same generation-aware idea).
+ */
+
+import { mediaJobEvents } from '../mediaJobQueue/index.js';
+import { updateStageWithLatest } from './issues.js';
+
+export function createFilenameHook({ name, stageId, kind = 'image', parseOwner, applyFilename }) {
+ let registeredHandler = null;
+
+ const handler = (job) => {
+ void (async () => {
+ if (!job || job.kind !== kind) return;
+ const filename = job.result?.filename;
+ if (typeof filename !== 'string' || !filename) return;
+ const parsed = parseOwner(job.owner);
+ if (!parsed) return;
+
+ const shortId = String(job.id || '').slice(0, 8);
+ let stampedLabel = null;
+ await updateStageWithLatest(
+ parsed.issueId,
+ stageId,
+ (currentStage) => {
+ const result = applyFilename(currentStage, parsed, job, filename);
+ if (!result) return {};
+ stampedLabel = result.label || null;
+ return result.patch || {};
+ },
+ ).catch((err) => {
+ console.error(`❌ ${name} filename hook failed for job ${shortId}: ${err?.message || err}`);
+ });
+
+ if (stampedLabel) {
+ console.log(`📎 ${name} filename stamped — issue=${parsed.issueId.slice(0, 8)} ${stampedLabel} ← ${filename}`);
+ }
+ })().catch((err) => {
+ console.error(`❌ ${name} filename hook crashed: ${err?.message || err}`);
+ });
+ };
+
+ function init() {
+ if (registeredHandler) return;
+ registeredHandler = handler;
+ mediaJobEvents.on('completed', registeredHandler);
+ console.log(`📎 ${name} filename hook initialized`);
+ }
+
+ function reset() {
+ if (registeredHandler) {
+ mediaJobEvents.off('completed', registeredHandler);
+ registeredHandler = null;
+ }
+ }
+
+ return { init, __testing: { reset } };
+}
diff --git a/server/services/pipeline/owners.js b/server/services/pipeline/owners.js
index 593062ba4d..ac1ffeb3fc 100644
--- a/server/services/pipeline/owners.js
+++ b/server/services/pipeline/owners.js
@@ -28,3 +28,26 @@ export function parseComicPagesOwner(owner) {
if (!Number.isInteger(pageIndex) || pageIndex < 0) return null;
return { issueId, target: 'page', pageIndex };
}
+
+// Per-shot start-frame renders inside the storyboards stage. Scene-level
+// owners (`pipeline:<id>:storyboards:scene<N>`) still exist for legacy
+// scene-image renders that don't decompose into shots — that string is
+// produced inline by `enqueueVisualImage` and intentionally falls outside
+// this parser (no filename hook needed for the scene-level path).
+export function buildStoryboardsShotOwner({ issueId, sceneIndex, shotIndex }) {
+ return `${PREFIX}:${issueId}:storyboards:scene${sceneIndex}:shot${shotIndex}`;
+}
+
+const STORYBOARDS_SHOT_RE = /^pipeline:([^:]+):storyboards:scene(\d+):shot(\d+)$/;
+
+export function parseStoryboardsShotOwner(owner) {
+ if (typeof owner !== 'string') return null;
+ const m = owner.match(STORYBOARDS_SHOT_RE);
+ if (!m) return null;
+ const [, issueId, sceneIdxStr, shotIdxStr] = m;
+ const sceneIndex = Number(sceneIdxStr);
+ const shotIndex = Number(shotIdxStr);
+ if (!Number.isInteger(sceneIndex) || sceneIndex < 0) return null;
+ if (!Number.isInteger(shotIndex) || shotIndex < 0) return null;
+ return { issueId, sceneIndex, shotIndex };
+}
diff --git a/server/services/pipeline/owners.test.js b/server/services/pipeline/owners.test.js
index 44a6227973..8aea4fb64d 100644
--- a/server/services/pipeline/owners.test.js
+++ b/server/services/pipeline/owners.test.js
@@ -1,5 +1,8 @@
import { describe, it, expect } from 'vitest';
-import { buildComicPagesOwner, parseComicPagesOwner } from './owners.js';
+import {
+ buildComicPagesOwner, parseComicPagesOwner,
+ buildStoryboardsShotOwner, parseStoryboardsShotOwner,
+} from './owners.js';
describe('pipeline owner strings', () => {
it('round-trips a cover owner', () => {
@@ -25,4 +28,22 @@ describe('pipeline owner strings', () => {
expect(parseComicPagesOwner('pipeline:iss:storyboards:scene0')).toBeNull();
expect(parseComicPagesOwner('pipeline:iss:comicPages:pageNaN')).toBeNull();
});
+
+ it('round-trips a storyboards shot owner', () => {
+ const owner = buildStoryboardsShotOwner({ issueId: 'iss-789', sceneIndex: 2, shotIndex: 5 });
+ expect(owner).toBe('pipeline:iss-789:storyboards:scene2:shot5');
+ expect(parseStoryboardsShotOwner(owner)).toEqual({ issueId: 'iss-789', sceneIndex: 2, shotIndex: 5 });
+ });
+
+ it('shot parser rejects non-shot owners and malformed indices', () => {
+ expect(parseStoryboardsShotOwner(null)).toBeNull();
+ expect(parseStoryboardsShotOwner('pipeline:iss:comicPages:cover')).toBeNull();
+ expect(parseStoryboardsShotOwner('pipeline:iss:storyboards:scene0')).toBeNull();
+ expect(parseStoryboardsShotOwner('pipeline:iss:storyboards:scene1:shotNaN')).toBeNull();
+ });
+
+ it('comic parser does not match shot owners and vice versa', () => {
+ expect(parseComicPagesOwner('pipeline:iss:storyboards:scene1:shot2')).toBeNull();
+ expect(parseStoryboardsShotOwner('pipeline:iss:comicPages:page3')).toBeNull();
+ });
});
diff --git a/server/services/pipeline/storyboardsFilenameHook.js b/server/services/pipeline/storyboardsFilenameHook.js
new file mode 100644
index 0000000000..1e7d39da45
--- /dev/null
+++ b/server/services/pipeline/storyboardsFilenameHook.js
@@ -0,0 +1,39 @@
+/**
+ * Storyboards — shot start-frame filename hook.
+ *
+ * Stamps `startFrameFilename` onto the matching shot record on media-job
+ * completion so the UI keeps rendering after mediaJobQueue's 24h archive
+ * TTL expires. Legacy scene-level renders (no shot decomposition) use the
+ * media-job record directly; only per-shot owners produced by
+ * `buildStoryboardsShotOwner` are handled here.
+ */
+
+import { parseStoryboardsShotOwner } from './owners.js';
+import { createFilenameHook } from './filenameHookFactory.js';
+
+const hook = createFilenameHook({
+ name: 'storyboards',
+ stageId: 'storyboards',
+ parseOwner: parseStoryboardsShotOwner,
+ applyFilename: (currentStage, parsed, job, filename) => {
+ const scenes = Array.isArray(currentStage?.scenes) ? currentStage.scenes : [];
+ const scene = scenes[parsed.sceneIndex];
+ const shots = Array.isArray(scene?.shots) ? scene.shots : [];
+ const shot = shots[parsed.shotIndex];
+ // Skip if THIS job isn't the shot's active render — a re-render that
+ // landed between enqueue and this event would otherwise be overwritten
+ // with the older filename.
+ if (!shot || shot.startFrameJobId !== job.id) return null;
+ const nextShots = [...shots];
+ nextShots[parsed.shotIndex] = { ...shot, startFrameFilename: filename };
+ const nextScenes = [...scenes];
+ nextScenes[parsed.sceneIndex] = { ...scene, shots: nextShots };
+ return {
+ patch: { scenes: nextScenes },
+ label: `scene${parsed.sceneIndex}/shot${parsed.shotIndex}`,
+ };
+ },
+});
+
+export const initStoryboardsFilenameHook = hook.init;
+export const __testing = hook.__testing;
diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.js
index 15b66dba54..19e35262ad 100644
--- a/server/services/pipeline/visualStages.js
+++ b/server/services/pipeline/visualStages.js
@@ -27,7 +27,7 @@ import { enqueueJob } from '../mediaJobQueue/index.js';
import { getSettings } from '../settings.js';
import { getSeries } from './series.js';
import { getIssue, updateStage, VISUAL_STAGE_IDS } from './issues.js';
-import { buildComicPagesOwner } from './owners.js';
+import { buildComicPagesOwner, buildStoryboardsShotOwner } from './owners.js';
import { getUniverse } from '../universeBuilder.js';
import { ServerError } from '../../lib/errorHandler.js';
import {
@@ -548,6 +548,76 @@ export async function enqueueStoryboardSceneVideo(issueId, sceneIndex, options =
return { jobId, prompt, sceneIndex: idx, issue: updatedIssue, stage };
}
+/**
+ * Enqueue an image render for a single shot inside a storyboard scene. Mirror
+ * of enqueueStoryboardSceneVideo but for IMAGE (start-frame), at shot
+ * granularity. Shot description is the primary anchor; falls back to the
+ * parent scene's description when the shot is sparse so a fresh shot still
+ * renders something coherent.
+ */
+export async function enqueueStoryboardShotStartFrame(issueId, sceneIndex, shotIndex, options = {}) {
+ const sIdx = Number(sceneIndex);
+ const tIdx = Number(shotIndex);
+ if (!Number.isInteger(sIdx) || sIdx < 0 || !Number.isInteger(tIdx) || tIdx < 0) {
+ throw new ServerError('sceneIndex and shotIndex must be non-negative integers', {
+ status: 400, code: 'PIPELINE_SHOT_BAD_INDEX',
+ });
+ }
+ const { issue, settings, series, world, canon } = await loadBibleContext(issueId);
+ const scenes = Array.isArray(issue.stages?.storyboards?.scenes)
+ ? [...issue.stages.storyboards.scenes]
+ : [];
+ const scene = scenes[sIdx];
+ if (!scene) {
+ throw new ServerError(`sceneIndex ${sIdx} out of range (have ${scenes.length})`, {
+ status: 404, code: 'PIPELINE_SCENE_NOT_FOUND',
+ });
+ }
+ const shots = Array.isArray(scene.shots) ? [...scene.shots] : [];
+ const shot = shots[tIdx];
+ if (!shot) {
+ throw new ServerError(`shotIndex ${tIdx} out of range (have ${shots.length})`, {
+ status: 404, code: 'PIPELINE_SHOT_NOT_FOUND',
+ });
+ }
+
+ const shotDescription = (shot.description || '').trim();
+ const description = shotDescription || (scene.description || '').trim();
+ if (!description) {
+ throw new ServerError('shot has no description (parent scene also empty) — add a description first', {
+ status: 400, code: 'PIPELINE_SHOT_EMPTY_DESCRIPTION',
+ });
+ }
+
+ const mode = resolveMode(options, settings);
+ const matchedCharacters = matchCharactersInText(
+ `${description} ${scene.slugline || ''}`,
+ canon.characters,
+ );
+ const prompt = composeVisualPrompt({
+ series,
+ description,
+ slugline: scene.slugline || '',
+ extraStyle: composeExtraStyle(series, issue, 'storyboards', options.extraStyle),
+ matchedCharacters,
+ world,
+ });
+
+ const jobId = enqueueImageJob({
+ prompt, world, settings, options, mode,
+ owner: buildStoryboardsShotOwner({ issueId, sceneIndex: sIdx, shotIndex: tIdx }),
+ logLine: `🎞️ Pipeline shot start-frame — issue=${issueId.slice(0, 8)} scene=${sIdx + 1} shot=${tIdx + 1}`,
+ });
+
+ shots[tIdx] = { ...shot, startFrameJobId: jobId };
+ scenes[sIdx] = { ...scene, shots };
+ const { issue: updatedIssue, stage } = await updateStage(issueId, 'storyboards', {
+ status: 'edited',
+ scenes,
+ });
+ return { jobId, mode, prompt, sceneIndex: sIdx, shotIndex: tIdx, issue: updatedIssue, stage };
+}
+
const seriesBibleCtx = (series) => ({
name: series.name || '',
styleNotes: series.styleNotes || '',
diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.js
index 48a81a4e08..ff393bbc02 100644
--- a/server/services/pipeline/visualStages.test.js
+++ b/server/services/pipeline/visualStages.test.js
@@ -69,6 +69,7 @@ const {
composeComicCoverPrompt,
enqueueComicCover,
enqueueStoryboardSceneVideo,
+ enqueueStoryboardShotStartFrame,
refineComicPanelPrompt,
refineStoryboardScenePrompt,
} = await import('./visualStages.js');
@@ -312,6 +313,67 @@ describe('enqueueStoryboardSceneVideo', () => {
});
});
+describe('enqueueStoryboardShotStartFrame', () => {
+ it('rejects non-integer indices', async () => {
+ await expect(enqueueStoryboardShotStartFrame('iss-test', 'nope', 0)).rejects.toThrow(/non-negative integers/);
+ await expect(enqueueStoryboardShotStartFrame('iss-test', 0, -1)).rejects.toThrow(/non-negative integers/);
+ });
+
+ it('404s when the scene index is out of range', async () => {
+ await expect(enqueueStoryboardShotStartFrame('iss-test', 99, 0)).rejects.toThrow(/scene.*out of range/i);
+ });
+
+ it('404s when the shot index is out of range', async () => {
+ getIssueMock.mockResolvedValueOnce({
+ ...structuredClone(mockIssue),
+ stages: { ...mockIssue.stages, storyboards: { scenes: [{ description: 'a', shots: [{ id: 's1', description: 'first' }] }] } },
+ });
+ await expect(enqueueStoryboardShotStartFrame('iss-test', 0, 5)).rejects.toThrow(/shot.*out of range/i);
+ });
+
+ it('rejects when the shot AND parent scene are both empty', async () => {
+ getIssueMock.mockResolvedValueOnce({
+ ...structuredClone(mockIssue),
+ stages: { ...mockIssue.stages, storyboards: { scenes: [{ description: ' ', shots: [{ id: 's1', description: ' ' }] }] } },
+ });
+ await expect(enqueueStoryboardShotStartFrame('iss-test', 0, 0)).rejects.toThrow(/no description/i);
+ });
+
+ it('happy path: enqueues image job, stamps startFrameJobId on the shot', async () => {
+ getIssueMock.mockResolvedValueOnce({
+ ...structuredClone(mockIssue),
+ stages: { ...mockIssue.stages, storyboards: { scenes: [{ description: 'wide', shots: [{ id: 's1', description: 'close on the lock' }] }] } },
+ });
+ const result = await enqueueStoryboardShotStartFrame('iss-test', 0, 0);
+ expect(result.jobId).toBe('job-fake-1234');
+ expect(result.sceneIndex).toBe(0);
+ expect(result.shotIndex).toBe(0);
+ expect(enqueueJobMock).toHaveBeenCalledWith(expect.objectContaining({
+ kind: 'image',
+ owner: 'pipeline:iss-test:storyboards:scene0:shot0',
+ }));
+ expect(updateStageMock).toHaveBeenCalledWith('iss-test', 'storyboards', expect.objectContaining({
+ status: 'edited',
+ scenes: expect.arrayContaining([
+ expect.objectContaining({
+ shots: expect.arrayContaining([
+ expect.objectContaining({ startFrameJobId: 'job-fake-1234' }),
+ ]),
+ }),
+ ]),
+ }));
+ });
+
+ it('falls back to the parent scene description when the shot description is empty', async () => {
+ getIssueMock.mockResolvedValueOnce({
+ ...structuredClone(mockIssue),
+ stages: { ...mockIssue.stages, storyboards: { scenes: [{ description: 'wide shot of the bridge at dawn', shots: [{ id: 's1', description: '' }] }] } },
+ });
+ const result = await enqueueStoryboardShotStartFrame('iss-test', 0, 0);
+ expect(result.prompt).toMatch(/bridge at dawn/i);
+ });
+});
+
describe('refineComicPanelPrompt', () => {
it('rejects a non-integer pageIndex / panelIndex', async () => {
await expect(refineComicPanelPrompt('iss-test', 'nope', 0)).rejects.toThrow(/non-negative integers/);