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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(pipeline): scene-video render + AI prompt refine + live thumbs + voice stage nav + dynamic sidebar (#224)
[._.]/ Adam Eivy6c8c62f46464
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex fb40c7a70b..420117cb94 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -193,7 +193,7 @@ const navItems = [defaultTo: '/media',children: [{ to: '/media', label: 'Media Gen', icon: Layers },- { to: '/pipeline', label: 'Pipeline', icon: WorkflowIcon },+ { to: '/pipeline', label: 'Pipeline', icon: WorkflowIcon, dynamic: 'pipelineRecent' },{ to: '/world-builder', label: 'World Builder', icon: Globe },{ to: '/writers-room', label: 'Writers Room', icon: NotebookPen }]@@ -383,26 +383,88 @@ export default function Layout() {return () => socket.off('apps:changed', fetchApps);}, []);+ // Fetch recent pipeline issues for the Create > Pipeline grandchildren.+ // Refresh on focus so freshly-created/updated issues show up without a+ // full reload — but debounced: alt-tabbing back after 2s shouldn't refetch.+ // Signature guard on setState avoids re-rendering the whole sidebar tree+ // when the items haven't actually changed.+ const [recentPipelineIssues, setRecentPipelineIssues] = useState([]);+ useEffect(() => {+ // Track successful fetches only — a failed fetch shouldn't lock out the+ // next focus retry for 30 seconds.+ let lastSuccessAt = 0;+ // Include EVERY rendered field — id/updatedAt alone misses cases like+ // a series rename (which doesn't bump the issue's updatedAt) where the+ // sidebar label would stay stale because `sigOf(prev) === sigOf(next)`+ // suppresses the state update.+ const sigOf = (items) => items+ .map((i) => `${i.id}@${i.updatedAt}|${i.number}|${i.title}|${i.seriesName}`)+ .join('||');+ const loadRecent = () => {+ api.listRecentPipelineIssues(10)+ .then((items) => {+ lastSuccessAt = Date.now();+ const next = Array.isArray(items) ? items : [];+ setRecentPipelineIssues((prev) => sigOf(prev) === sigOf(next) ? prev : next);+ })+ .catch((err) => {+ console.warn(`⚠️ Sidebar pipeline-recent fetch failed: ${err?.message || err}`);+ });+ };+ loadRecent();+ const onFocus = () => {+ if (Date.now() - lastSuccessAt < 30_000) return;+ loadRecent();+ };+ window.addEventListener('focus', onFocus);+ return () => window.removeEventListener('focus', onFocus);+ }, []);+useEffect(() => {localStorage.setItem(SIDEBAR_KEY, String(collapsed));}, [collapsed]);- // Build dynamic nav items with app children- const resolvedNavItems = useMemo(() => navItems.map(item => {- if (item.dynamic !== 'apps') return item;- return {- ...item,- children: [- { to: '/apps', label: 'Dashboard', icon: LayoutDashboard, end: true },- { separator: true },- ...sidebarApps.map(app => ({- to: `/apps/${app.id}`,- label: app.name,- icon: Package- }))- ]+ // Build dynamic nav items with app children + recent pipeline issues.+ // `decoratePipelineChild` is defined inside the memo so its closure over+ // `recentPipelineIssues` doesn't require an eslint-disable, and so it+ // isn't reallocated on every render.+ const resolvedNavItems = useMemo(() => {+ const decoratePipelineChild = (child) => {+ if (child.dynamic !== 'pipelineRecent') return child;+ return {+ ...child,+ grandChildren: recentPipelineIssues.map((iss) => ({+ to: `/pipeline/issues/${iss.id}/idea`,+ label: `#${iss.number} ${iss.title}`.slice(0, 60),+ title: `${iss.seriesName} — #${iss.number} ${iss.title}`,+ // Active-detection prefix — the actual to-link points at /idea+ // for a clean default, but the sidebar should highlight when the+ // user is on ANY stage of this issue.+ activePathPrefix: `/pipeline/issues/${iss.id}`,+ })),+ };};- }), [sidebarApps]);+ return navItems.map((item) => {+ if (item.dynamic === 'apps') {+ return {+ ...item,+ children: [+ { to: '/apps', label: 'Dashboard', icon: LayoutDashboard, end: true },+ { separator: true },+ ...sidebarApps.map((app) => ({+ to: `/apps/${app.id}`,+ label: app.name,+ icon: Package,+ })),+ ],+ };+ }+ if (Array.isArray(item.children)) {+ return { ...item, children: item.children.map(decoratePipelineChild) };+ }+ return item;+ });+ }, [sidebarApps, recentPipelineIssues]);// Auto-expand sections when on a child pageuseEffect(() => {@@ -632,21 +694,51 @@ export default function Layout() {const childActive = child.end? location.pathname === child.to: isActive(child.to);+ const grandChildren = Array.isArray(child.grandChildren) ? child.grandChildren : [];return (- <NavLink- key={child.to}- to={child.to}- end={child.end}- onClick={() => setMobileOpen(false)}- className={`flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors min-w-0 ${- childActive- ? 'bg-port-accent/10 text-port-accent'- : 'text-gray-500 hover:text-white hover:bg-port-border/50'- }`}- >- <ChildIcon size={16} className="shrink-0" />- <span className="min-w-0 truncate">{child.label}</span>- </NavLink>+ <div key={child.to} className="min-w-0">+ <NavLink+ to={child.to}+ end={child.end}+ onClick={() => setMobileOpen(false)}+ className={`flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors min-w-0 ${+ childActive+ ? 'bg-port-accent/10 text-port-accent'+ : 'text-gray-500 hover:text-white hover:bg-port-border/50'+ }`}+ >+ <ChildIcon size={16} className="shrink-0" />+ <span className="min-w-0 truncate">{child.label}</span>+ </NavLink>+ {grandChildren.length > 0 && (+ <div className="ml-6 mt-0.5 mb-1 border-l border-port-border/50 pl-2 min-w-0">+ {grandChildren.map((gc) => {+ // Prefer the explicit prefix (e.g. `/pipeline/issues/<id>`)+ // so the row stays highlighted across stage tabs — the+ // `to` link points at a specific default stage but the+ // user may navigate to siblings.+ const prefix = gc.activePathPrefix || gc.to;+ const gcActive = location.pathname === prefix+ || location.pathname.startsWith(prefix + '/');+ return (+ <NavLink+ key={gc.to}+ to={gc.to}+ onClick={() => setMobileOpen(false)}+ title={gc.title || gc.label}+ className={`block px-2 py-1 rounded text-xs transition-colors min-w-0 truncate ${+ gcActive+ ? 'text-port-accent'+ : 'text-gray-600 hover:text-gray-300 hover:bg-port-border/30'+ }`}+ >+ {gc.label}+ </NavLink>+ );+ })}+ </div>+ )}+ </div>);})}</div>diff --git a/client/src/components/pipeline/MediaJobThumb.jsx b/client/src/components/pipeline/MediaJobThumb.jsxnew file mode 100644index 0000000000..be7dd68d80--- /dev/null+++ b/client/src/components/pipeline/MediaJobThumb.jsx@@ -0,0 +1,144 @@+import { useEffect, useState } from 'react';+import { AlertCircle, Ban, Loader2 } from 'lucide-react';+import useMediaJobProgress from '../../hooks/useMediaJobProgress';++/**+ * Small thumbnail strip for a single mediaJobQueue job. Used by the+ * Pipeline ComicPages and Storyboards stages so each panel/scene shows its+ * render's live preview (currentImage during diffusion) and the final+ * artifact once the job completes.+ *+ * kind='image' — completed render served from /data/images/<filename>.+ * kind='video' — completed render served as <video> from /data/videos/<jobId>.mp4+ * with /data/video-thumbnails/<jobId>.jpg as poster (matches ScenePreview).+ *+ * Handles the same "media file deleted out from under us" case ScenePreview+ * does — flips to a "missing" badge with a Retry button (re-arms the+ * <video>/<img> via a cache-busting key) when the file 404s.+ */+export default function MediaJobThumb({ jobId, label = 'Render', size = 'sm', kind = 'image' }) {+ const { status, progress, step, totalSteps, currentImage, filename, error } =+ useMediaJobProgress(jobId, { kind });+ // Local missing-media state. Reset when jobId changes so a fresh render+ // doesn't inherit the prior render's failure flag.+ const [missing, setMissing] = useState(false);+ const [attempt, setAttempt] = useState(0);+ useEffect(() => { setMissing(false); setAttempt(0); }, [jobId]);++ if (!jobId) return null;++ const dims = size === 'lg'+ ? 'w-32 h-32'+ : size === 'md' ? 'w-24 h-24' : 'w-16 h-16';++ if (missing) {+ return (+ <div+ title="Media file missing (deleted from disk)"+ className={`${dims} bg-port-bg rounded border border-port-border flex flex-col items-center justify-center gap-1 text-[10px] text-port-text-muted`}+ >+ <span>missing</span>+ <button+ type="button"+ onClick={() => { setMissing(false); setAttempt((a) => a + 1); }}+ className="px-1.5 py-0 rounded border border-port-border hover:bg-port-card text-port-text"+ >+ Retry+ </button>+ </div>+ );+ }++ const cacheBust = attempt > 0 ? `?retry=${attempt}` : '';++ if (status === 'completed' && kind === 'video') {+ return (+ <video+ key={attempt}+ src={`/data/videos/${jobId}.mp4${cacheBust}`}+ poster={`/data/video-thumbnails/${jobId}.jpg${cacheBust}`}+ controls+ preload="none"+ playsInline+ aria-label={label}+ onError={() => setMissing(true)}+ className={`${dims} object-cover bg-port-bg rounded border border-port-border`}+ />+ );+ }+ if (status === 'completed' && filename) {+ return (+ <a+ href={`/data/images/${filename}${cacheBust}`}+ target="_blank"+ rel="noopener noreferrer"+ title="Open full image in a new tab"+ className={`block ${dims} bg-port-bg rounded overflow-hidden border border-port-border hover:border-port-accent/50 transition-colors`}+ >+ <img+ key={attempt}+ src={`/data/images/${filename}${cacheBust}`}+ alt={label}+ onError={() => setMissing(true)}+ className="w-full h-full object-cover"+ loading="lazy"+ />+ </a>+ );+ }++ if (status === 'failed') {+ // No client-side retry — re-enqueue lives on the parent stage's button+ // since the job's params (mode, model, image source) are owned there.+ // Surface the error message so the user knows what to fix.+ return (+ <div+ title={error || 'Render failed'}+ className={`${dims} bg-port-bg rounded border border-port-error/40 flex flex-col items-center justify-center gap-1 text-[10px] text-port-error`}+ >+ <AlertCircle size={14} />+ <span>failed</span>+ </div>+ );+ }++ if (status === 'canceled') {+ // Canceled by the user via the queue cancel route. Without an explicit+ // branch the row would fall through to the running/queued spinner and+ // look stuck forever — re-enqueue lives on the parent stage button.+ return (+ <div+ title="Render canceled"+ className={`${dims} bg-port-bg rounded border border-port-border flex flex-col items-center justify-center gap-1 text-[10px] text-port-text-muted`}+ >+ <Ban size={14} />+ <span>canceled</span>+ </div>+ );+ }++ // running/queued/unknown — show currentImage preview if we have one,+ // otherwise a spinner with step counter. The base64 currentImage is the+ // freshly-decoded latent frame from the diffusion loop.+ const pct = totalSteps ? Math.round((step / totalSteps) * 100) : Math.round((progress || 0) * 100);+ return (+ <div className={`relative ${dims} bg-port-bg rounded overflow-hidden border border-port-border`}>+ {currentImage ? (+ <img+ src={`data:image/png;base64,${currentImage}`}+ alt={`${label} preview`}+ className="w-full h-full object-cover opacity-70"+ />+ ) : (+ <div className="w-full h-full flex items-center justify-center">+ <Loader2 size={14} className="animate-spin text-port-accent" />+ </div>+ )}+ {pct > 0 && (+ <div className="absolute bottom-0 left-0 right-0 bg-black/60 text-[9px] text-white text-center py-0.5 font-mono">+ {pct}%+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/pipeline/stages/ComicPagesStage.jsx b/client/src/components/pipeline/stages/ComicPagesStage.jsxindex 7dbb629bb3..3e7a933384 100644--- a/client/src/components/pipeline/stages/ComicPagesStage.jsx+++ b/client/src/components/pipeline/stages/ComicPagesStage.jsx@@ -1,18 +1,21 @@import { useRef, useState } from 'react';-import { Plus, Trash2, Sparkles, Loader2, Wand2, ImagePlus } from 'lucide-react';+import { Plus, Trash2, Sparkles, Loader2, Wand2, WandSparkles, ImagePlus } from 'lucide-react';import toast from '../../ui/Toast';import { useArmedAction } from '../../../hooks/useArmedAction';import {generatePipelineVisualImage,generatePipelineComicPage,+ refinePipelineComicPanelPrompt,updatePipelineIssue,extractPipelineComicPages,} from '../../../services/api';+import MediaJobThumb from '../MediaJobThumb';export default function ComicPagesStage({ issue, onStageUpdate }) {const stage = issue.stages?.comicPages || { status: 'empty', pages: [] };const [pages, setPages] = useState(stage.pages || []);const [savingIdx, setSavingIdx] = useState(null);+ const [refiningKey, setRefiningKey] = useState(null);// Per-page in-flight state. Codex can render multiple pages in parallel, so// tracking a single index would flip the spinner off the wrong button when// the first request finished while a second was still pending.@@ -114,6 +117,32 @@ export default function ComicPagesStage({ issue, onStageUpdate }) {toast.success(`Queued ${result.mode} page render (${result.jobId.slice(0, 8)})`);};+ // LLM-driven refinement of a single panel's description into a richer+ // image-gen prompt. Server replaces the persisted description with the+ // refined version and returns the updated issue.+ const handleRefinePanel = async (pi, ni) => {+ const panel = pages[pi]?.panels?.[ni];+ if (!panel?.description?.trim()) {+ toast.error('Add a description first');+ return;+ }+ const key = `${pi}:${ni}`;+ setRefiningKey(key);+ const result = await refinePipelineComicPanelPrompt(issue.id, pi, ni, {})+ .catch((err) => {+ toast.error(err.message || 'Refine failed');+ return null;+ });+ setRefiningKey(null);+ if (!result) return;+ if (result.issue) {+ setPages(result.issue.stages?.comicPages?.pages || []);+ onStageUpdate?.('comicPages', result.issue.stages.comicPages, result.issue);+ }+ const summary = result.changes?.[0] ? ` — ${result.changes[0]}` : '';+ toast.success(`Refined panel ${pi + 1}.${ni + 1}${summary}`);+ };+const handleGeneratePanel = async (pi, ni) => {const panel = pages[pi].panels[ni];if (!panel.description?.trim()) {@@ -189,9 +218,12 @@ export default function ComicPagesStage({ issue, onStageUpdate }) {Generate page</button>{page.imageJobId ? (- <span className="text-[10px] text-gray-500 font-mono break-all" title="Last page render job">- page job {page.imageJobId.slice(0, 8)}- </span>+ <div className="flex items-center gap-2">+ <MediaJobThumb jobId={page.imageJobId} label={`Page ${pi + 1}`} size="md" />+ <span className="text-[10px] text-gray-500 font-mono break-all" title="Last page render job">+ {page.imageJobId.slice(0, 8)}+ </span>+ </div>) : null}<buttontype="button"@@ -217,6 +249,16 @@ export default function ComicPagesStage({ issue, onStageUpdate }) {maxLength={8000}/><div className="flex flex-col gap-1 items-stretch w-32">+ <button+ type="button"+ onClick={() => handleRefinePanel(pi, ni)}+ disabled={refiningKey !== null}+ title="Elaborate this panel description into a richer image-gen prompt (LLM call — replaces the current text)"+ className="inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded bg-port-card border border-port-border text-white text-xs hover:border-port-accent/50 disabled:opacity-50"+ >+ {refiningKey === `${pi}:${ni}` ? <Loader2 size={12} className="animate-spin" /> : <WandSparkles size={12} />}+ AI: refine+ </button><buttontype="button"onClick={() => handleGeneratePanel(pi, ni)}@@ -227,7 +269,10 @@ export default function ComicPagesStage({ issue, onStageUpdate }) {Image</button>{panel.imageJobId ? (- <span className="text-[10px] text-gray-500 font-mono break-all">job {panel.imageJobId.slice(0, 8)}</span>+ <>+ <MediaJobThumb jobId={panel.imageJobId} label={`Panel ${ni + 1}`} size="sm" />+ <span className="text-[10px] text-gray-500 font-mono break-all">job {panel.imageJobId.slice(0, 8)}</span>+ </>) : null}</div><buttondiff --git a/client/src/components/pipeline/stages/StoryboardsStage.jsx b/client/src/components/pipeline/stages/StoryboardsStage.jsxindex 21832b9787..ea7ab80d16 100644--- a/client/src/components/pipeline/stages/StoryboardsStage.jsx+++ b/client/src/components/pipeline/stages/StoryboardsStage.jsx@@ -1,25 +1,39 @@/**- * Storyboards stage — one storyboard image per TV-script scene.+ * Storyboards stage — one storyboard image per TV-script scene, plus+ * single-scene video preview and AI-driven prompt refinement.*- * MVP: flat list of scenes. Each scene has its own description and a- * "Generate storyboard image" button that hands off to image-gen via the- * pipeline visual endpoint. Per-scene video rendering via Creative Director- * is deferred — see PLAN.md "Pipeline — Deferred".+ * Each scene row exposes four actions:+ * - **AI: refine** — rewrites the description via the storyboard prompt+ * template (see server/services/pipeline/visualStages.js#refineStoryboardScenePrompt).+ * - **Storyboard** — enqueues an image-gen job for the scene; jobId+ * lands on `scene.imageJobId`, surfaced via `<MediaJobThumb>`.+ * - **Scene video** — enqueues a t2v video render; jobId lands on+ * `scene.sceneVideoJobId`. Independent of the full episode-video+ * stitch in `episodeVideo.js`.+ * - **Trash** — removes the scene from the list.+ *+ * Auto-fill: "From TV script" / "From prose" buttons run the scene+ * extractor against the corresponding text stage and replace the list.*/import { useEffect, useRef, useState } from 'react';-import { Plus, Trash2, Sparkles, Loader2, Wand2 } from 'lucide-react';+import { Plus, Trash2, Sparkles, Loader2, Wand2, Film, WandSparkles } from 'lucide-react';import toast from '../../ui/Toast';import {generatePipelineVisualImage,+ generatePipelineSceneVideo,+ refinePipelineSceneImagePrompt,updatePipelineIssue,extractPipelineStoryboardScenes,} from '../../../services/api';+import MediaJobThumb from '../MediaJobThumb';export default function StoryboardsStage({ issue, onStageUpdate }) {const stage = issue.stages?.storyboards || { status: 'empty', scenes: [] };const [scenes, setScenes] = useState(stage.scenes || []);const [savingIdx, setSavingIdx] = useState(null);+ const [renderingVideoIdx, setRenderingVideoIdx] = useState(null);+ const [refiningIdx, setRefiningIdx] = useState(null);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@@ -113,6 +127,59 @@ export default function StoryboardsStage({ issue, onStageUpdate }) {toast.success(`Queued ${result.mode} image (${result.jobId.slice(0, 8)})`);};+ // LLM-driven refinement of the scene description into a richer image+ // prompt. Server replaces the persisted description with the refined+ // version and returns the updated issue.+ const handleRefinePrompt = async (i) => {+ const scene = scenes[i];+ if (!scene.description?.trim()) {+ toast.error('Add a description first');+ return;+ }+ setRefiningIdx(i);+ const result = await refinePipelineSceneImagePrompt(issue.id, i, {})+ .catch((err) => {+ toast.error(err.message || 'Refine failed');+ return null;+ });+ setRefiningIdx(null);+ if (!result) return;+ if (result.issue) {+ setScenes(result.issue.stages?.storyboards?.scenes || []);+ onStageUpdate?.('storyboards', result.issue.stages.storyboards, result.issue);+ }+ const summary = result.changes?.[0] ? ` — ${result.changes[0]}` : '';+ toast.success(`Refined scene ${i + 1}${summary}`);+ };++ // Render this one scene as a video clip — independent of the full+ // episode-video stitch. Server persists sceneVideoJobId on the scene.+ const handleGenerateVideo = async (i) => {+ const scene = scenes[i];+ if (!scene.description?.trim()) {+ toast.error('Add a description first');+ return;+ }+ setRenderingVideoIdx(i);+ const result = await generatePipelineSceneVideo(issue.id, i, {})+ .catch((err) => {+ toast.error(err.message || 'Failed to enqueue scene video');+ return null;+ });+ setRenderingVideoIdx(null);+ if (!result) return;+ // Server returned the updated issue — adopt its scenes list rather than+ // patching locally so any sanitizer drift stays a server-side concern.+ if (result.issue) {+ setScenes(result.issue.stages?.storyboards?.scenes || []);+ onStageUpdate?.('storyboards', result.issue.stages.storyboards, result.issue);+ } else {+ const next = scenes.map((s, j) => j === i ? { ...s, sceneVideoJobId: result.jobId } : s);+ setScenes(next);+ }+ toast.success(`Queued scene video (${result.jobId.slice(0, 8)})`);+ };+return (<div className="space-y-4"><div className="flex items-center justify-between gap-3 flex-wrap">@@ -192,6 +259,16 @@ export default function StoryboardsStage({ issue, onStageUpdate }) {maxLength={8000}/><div className="flex flex-col gap-1 w-32">+ <button+ type="button"+ onClick={() => handleRefinePrompt(i)}+ disabled={refiningIdx !== null}+ title="Elaborate this description into a richer image-gen prompt (LLM call — replaces the current text)"+ className="inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded bg-port-card border border-port-border text-white text-xs hover:border-port-accent/50 disabled:opacity-50"+ >+ {refiningIdx === i ? <Loader2 size={12} className="animate-spin" /> : <WandSparkles size={12} />}+ AI: refine+ </button><buttontype="button"onClick={() => handleGenerate(i)}@@ -201,8 +278,27 @@ export default function StoryboardsStage({ issue, onStageUpdate }) {{savingIdx === i ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}Storyboard</button>+ <button+ type="button"+ onClick={() => handleGenerateVideo(i)}+ disabled={renderingVideoIdx !== null}+ title="Render this scene as a video clip (independent of the full episode-video stitch)"+ className="inline-flex items-center justify-center gap-1 px-2 py-1.5 rounded bg-port-card border border-port-border text-white text-xs hover:border-port-accent/50 disabled:opacity-50"+ >+ {renderingVideoIdx === i ? <Loader2 size={12} className="animate-spin" /> : <Film size={12} />}+ Scene video+ </button>{scene.imageJobId ? (- <span className="text-[10px] text-gray-500 font-mono break-all">job {scene.imageJobId.slice(0, 8)}</span>+ <>+ <MediaJobThumb jobId={scene.imageJobId} label={`Scene ${i + 1}`} size="md" />+ <span className="text-[10px] text-gray-500 font-mono break-all">img {scene.imageJobId.slice(0, 8)}</span>+ </>+ ) : null}+ {scene.sceneVideoJobId ? (+ <>+ <MediaJobThumb jobId={scene.sceneVideoJobId} label={`Scene ${i + 1} video`} size="md" kind="video" />+ <span className="text-[10px] text-gray-500 font-mono break-all">vid {scene.sceneVideoJobId.slice(0, 8)}</span>+ </>) : null}</div></div>diff --git a/client/src/hooks/useMediaJobProgress.js b/client/src/hooks/useMediaJobProgress.jsnew file mode 100644index 0000000000..cdfa2ce83b--- /dev/null+++ b/client/src/hooks/useMediaJobProgress.js@@ -0,0 +1,148 @@+import { useEffect, useRef, useState } from 'react';+import socket from '../services/socket';+import { getMediaJob } from '../services/apiMediaJobs';++/**+ * Subscribe to live progress for a single mediaJobQueue job (image-gen+ * today, video-gen once a caller passes kind='video'). Filters socket+ * events by jobId so multiple instances of this hook coexist (one per+ * comic panel / storyboard scene) without cross-talk.+ *+ * Returns:+ * {+ * status: 'unknown' | 'queued' | 'running' | 'completed' | 'failed' | 'canceled',+ * progress, step, totalSteps, currentImage,+ * filename, path, error,+ * }+ *+ * Initial state is hydrated from GET /api/media-jobs/:id so navigating+ * back to a page mid-render picks up the in-flight job's snapshot+ * instead of showing an empty preview until the next event lands.+ */+export default function useMediaJobProgress(jobId, { kind = 'image' } = {}) {+ const [state, setState] = useState(() => ({+ status: 'unknown',+ progress: 0,+ step: 0,+ totalSteps: null,+ currentImage: null,+ filename: null,+ path: null,+ error: null,+ }));+ // Track mount so the initial fetch's setState doesn't fire after unmount+ // (the panel could be removed while the GET is in flight).+ //+ // The set-in-effect-setup pattern (NOT relying on `useRef(true)`'s initial+ // value alone) is required: React 18 StrictMode in dev fires+ // mount → cleanup → mount, but the ref is preserved across the simulated+ // remount. Without re-setting `true` in setup, cleanup flips it to false+ // and it never goes back up — the initial fetch's `.then` permanently+ // no-ops for every dev render.+ const mountedRef = useRef(true);+ useEffect(() => {+ mountedRef.current = true;+ return () => { mountedRef.current = false; };+ }, []);++ useEffect(() => {+ // Reset state on every jobId change so the previous job's filename /+ // currentImage doesn't briefly leak into the new job's render window+ // (between the listener attach and the new fetch resolving).+ setState({+ status: 'unknown', progress: 0, step: 0, totalSteps: null,+ currentImage: null, filename: null, path: null, error: null,+ });+ if (!jobId) return undefined;++ // Hydrate from the server. The job may already be completed (the user+ // reloaded after the render finished) — without this fetch the UI+ // would never reflect that.+ let canceled = false;+ getMediaJob(jobId).then((job) => {+ if (canceled || !mountedRef.current) return;+ setState((prev) => ({+ ...prev,+ status: job.status || 'unknown',+ filename: job.result?.filename || prev.filename,+ path: job.result?.path || prev.path,+ error: job.error || prev.error,+ }));+ }).catch(() => {+ // 404 just means the job archive expired — keep `status: unknown`.+ });++ const evtPrefix = kind === 'video' ? 'video-gen' : 'image-gen';+ const onStarted = (data) => {+ if (data.generationId !== jobId) return;+ setState((prev) => {+ const totalSteps = data.totalSteps ?? prev.totalSteps;+ if (prev.status === 'running' && totalSteps === prev.totalSteps) return prev;+ return { ...prev, status: 'running', totalSteps };+ });+ };+ // Diffusion runners throttle `currentImage` but still emit identical+ // step/progress between frames. Return prev unchanged on a no-op tick so+ // each panel doesn't re-render unnecessarily — N panels × every tick+ // adds up across a comic page.+ const onProgress = (data) => {+ if (data.generationId !== jobId) return;+ setState((prev) => {+ const next = {+ ...prev,+ status: 'running',+ progress: data.progress ?? prev.progress,+ step: data.step ?? prev.step,+ totalSteps: data.totalSteps ?? prev.totalSteps,+ currentImage: data.currentImage ?? prev.currentImage,+ };+ if (+ next.status === prev.status+ && next.progress === prev.progress+ && next.step === prev.step+ && next.totalSteps === prev.totalSteps+ && next.currentImage === prev.currentImage+ ) return prev;+ return next;+ });+ };+ const onCompleted = (data) => {+ if (data.generationId !== jobId) return;+ setState((prev) => ({+ ...prev,+ status: 'completed',+ filename: data.filename ?? prev.filename,+ path: data.path ?? prev.path,+ }));+ };+ const onFailed = (data) => {+ if (data.generationId !== jobId) return;+ // The mediaJobQueue collapses user-canceled jobs into a *:failed+ // socket event (SIGTERM looks like a failure to the underlying gen+ // module) while the persisted job.status is actually 'canceled'.+ // Re-fetch the authoritative state so MediaJobThumb's canceled UI+ // is reachable in live sessions, not just on reload.+ setState((prev) => ({ ...prev, status: 'failed', error: data.error || 'failed' }));+ getMediaJob(jobId).then((job) => {+ if (canceled || !mountedRef.current) return;+ if (job?.status === 'canceled') {+ setState((prev) => ({ ...prev, status: 'canceled', error: job.error || prev.error }));+ }+ }).catch(() => {});+ };++ socket.on(`${evtPrefix}:started`, onStarted);+ socket.on(`${evtPrefix}:progress`, onProgress);+ socket.on(`${evtPrefix}:completed`, onCompleted);+ socket.on(`${evtPrefix}:failed`, onFailed);+ return () => {+ canceled = true;+ socket.off(`${evtPrefix}:started`, onStarted);+ socket.off(`${evtPrefix}:progress`, onProgress);+ socket.off(`${evtPrefix}:completed`, onCompleted);+ socket.off(`${evtPrefix}:failed`, onFailed);+ };+ }, [jobId, kind]);++ return state;+}diff --git a/client/src/services/apiMediaJobs.js b/client/src/services/apiMediaJobs.jsindex 2e5142e9d7..eba838cb9d 100644--- a/client/src/services/apiMediaJobs.js+++ b/client/src/services/apiMediaJobs.js@@ -7,7 +7,11 @@ export const listMediaJobs = (filters = {}) => {return request(`/media-jobs${qs ? `?${qs}` : ''}`);};-export const getMediaJob = (id) => request(`/media-jobs/${encodeURIComponent(id)}`);+// `silent` so speculative lookups (e.g. MediaJobThumb hydration for old+// panel/scene jobIds past the queue's 24h archive TTL) don't surface a+// global toast on the routine 404 — the caller's own .catch handles the+// missing-job case as a cache miss.+export const getMediaJob = (id) => request(`/media-jobs/${encodeURIComponent(id)}`, { silent: true });export const cancelMediaJob = (id) => request(`/media-jobs/${encodeURIComponent(id)}/cancel`, { method: 'POST' });diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex 2100be45fa..37ba759eaa 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -49,6 +49,11 @@ export const extractPipelineBibles = (seriesId, { issueId, corpus, kinds, providexport const listPipelineIssues = (seriesId) =>request(`/pipeline/series/${encodeURIComponent(seriesId)}/issues`);+// Recently-updated issues across all series. Used by the sidebar to surface+// in-flight pipeline work without forcing the user to drill in.+export const listRecentPipelineIssues = (limit = 10) =>+ request(`/pipeline/issues/recent?limit=${encodeURIComponent(limit)}`);+export const createPipelineIssue = (seriesId, data) =>request(`/pipeline/series/${encodeURIComponent(seriesId)}/issues`, {method: 'POST',@@ -107,6 +112,37 @@ export const generatePipelineComicPage = (issueId, pageIndex, opts = {}) =>body: JSON.stringify(opts),});+// Render a single storyboard scene as a video clip (one t2v call against+// the scene's existing description + style). Independent of the+// episode-video stitch — use this when you want to preview a scene before+// committing the whole episode render.+// Server persists the resulting jobId on stages.storyboards.scenes[index]+// .sceneVideoJobId. Returns { jobId, prompt, sceneIndex, issue, stage }.+export const generatePipelineSceneVideo = (issueId, sceneIndex, opts = {}) =>+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/storyboards/scenes/${encodeURIComponent(sceneIndex)}/video`, {+ 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+// refined description on the panel and returns { panel, page, issue,+// stage, runId, changes, providerId }.+export const refinePipelineComicPanelPrompt = (issueId, pageIndex, panelIndex, opts = {}) =>+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/comicPages/pages/${encodeURIComponent(pageIndex)}/panels/${encodeURIComponent(panelIndex)}/refine-prompt`, {+ method: 'POST',+ body: JSON.stringify(opts),+ });++// LLM-driven refinement of a single storyboard scene's description into a+// richer image-gen prompt. Mirror of refinePipelineComicPanelPrompt.+export const refinePipelineSceneImagePrompt = (issueId, sceneIndex, opts = {}) =>+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/storyboards/scenes/${encodeURIComponent(sceneIndex)}/refine-prompt`, {+ method: 'POST',+ body: JSON.stringify(opts),+ });+// ---- Seasons (Phase 2 of Story Arc Planning) ----export const listPipelineSeasons = (seriesId) =>request(`/pipeline/series/${encodeURIComponent(seriesId)}/seasons`);diff --git a/data.sample/prompts/stage-config.json b/data.sample/prompts/stage-config.jsonindex d7be903525..0e95c7dd31 100644--- a/data.sample/prompts/stage-config.json+++ b/data.sample/prompts/stage-config.json@@ -241,6 +241,20 @@"model": "heavy","returnsJson": true,"variables": []+ },+ "pipeline-comic-panel-image-prompt": {+ "name": "Pipeline — Comic Panel Image Prompt",+ "description": "Refine a single comic panel's description into a richer image-gen-ready prompt. Uses caption / dialogue / sfx context + neighboring-panel continuity to elaborate without re-imagining the scene.",+ "model": "default",+ "returnsJson": true,+ "variables": []+ },+ "pipeline-storyboard-image-prompt": {+ "name": "Pipeline — Storyboard Scene Image Prompt",+ "description": "Refine a single storyboard scene's description into a richer image-gen-ready prompt. Uses slugline + neighboring-scene continuity to elaborate without contradicting location or time of day.",+ "model": "default",+ "returnsJson": true,+ "variables": []}}}diff --git a/data.sample/prompts/stages/pipeline-comic-panel-image-prompt.md b/data.sample/prompts/stages/pipeline-comic-panel-image-prompt.mdnew file mode 100644index 0000000000..c93c7a45ab--- /dev/null+++ b/data.sample/prompts/stages/pipeline-comic-panel-image-prompt.md@@ -0,0 +1,71 @@+# Pipeline — Comic Panel Image Prompt++You are an image prompt engineer. Take the comic panel below and rewrite its `description` into a richer, single-image-gen-ready visual prompt that a diffusion model can render directly. The series' style notes are prepended at render time — your job is the **panel-specific** visuals only.++## Series++- **Title:** {{series.name}}+- **Tone / style:** {{series.styleNotes}}++{{> bible-deference }}++## Episode++- **Number:** {{issue.number}}+- **Title:** {{issue.title}}++## Page context++This is **Page {{pageNumber}}, Panel {{panelNumber}}** of {{panelCount}} on this page.++{{#hasNeighbors}}+For visual continuity, here's the panel **before** and **after** this one (do not re-render either — just use as continuity context):++- **Previous panel:** {{previousPanel}}+- **Next panel:** {{nextPanel}}+{{/hasNeighbors}}++## Current panel content++- **Description (what to refine):**+ ```+ {{description}}+ ```+{{#hasCaption}}+- **Caption text:** "{{caption}}"+{{/hasCaption}}+{{#hasDialogue}}+- **Dialogue:** {{dialogue}}+{{/hasDialogue}}+{{#hasSfx}}+- **SFX:** {{sfx}}+{{/hasSfx}}++## What to write++A single paragraph (~40–80 words) that an image diffusion model can read top-to-bottom:++1. **Subject** — who/what is in frame and what they're doing.+2. **Framing** — wide / medium / close-up / extreme close-up; bird's-eye / low angle / over-the-shoulder.+3. **Composition** — lead lines, foreground/midground/background, focal point, panel-shape feel (vertical / horizontal / square).+4. **Lighting + mood** — palette, key/fill, time of day, weather, atmosphere (smoke, dust, rain), shadow contrast.+5. **Texture / details** — material call-outs that pay off the genre (rivets, ozone, scrollwork, neon, oil sheen).++## Rules++- Do **not** repeat the series style notes or character physical descriptions — those are prepended automatically.+- Do **not** describe the speech balloons / captions themselves — the page-level layout pass adds those. Only describe the **drawn** content.+- Do **not** invent characters, locations, or props that aren't in the panel description, dialogue, caption, or sfx fields.+- Keep characters anonymous (visual description only) — image models without story context can't resolve names.+- Lean into the visual genre cues from the series' tone/style; assume an experienced comic artist + colorist is rendering.++## Output++Return ONLY valid JSON. The `prompt` field is the refined description that will replace the panel's current description.++```json+{+ "prompt": "<refined image-gen prompt, single paragraph>",+ "changes": ["<short bullet of what changed>", "..."]+}+```diff --git a/data.sample/prompts/stages/pipeline-storyboard-image-prompt.md b/data.sample/prompts/stages/pipeline-storyboard-image-prompt.mdnew file mode 100644index 0000000000..b018b0ddb8--- /dev/null+++ b/data.sample/prompts/stages/pipeline-storyboard-image-prompt.md@@ -0,0 +1,66 @@+# Pipeline — Storyboard Scene Image Prompt++You are an image prompt engineer. Take the storyboard scene below and rewrite its `description` into a richer, single-image-gen-ready visual prompt that a diffusion model can render directly. The series' style notes and any matched setting/character bible entries are prepended at render time — your job is the **scene-specific** visuals only.++## Series++- **Title:** {{series.name}}+- **Tone / style:** {{series.styleNotes}}++{{> bible-deference }}++## Episode++- **Number:** {{issue.number}}+- **Title:** {{issue.title}}++## Scene context++This is **Scene {{sceneNumber}} of {{sceneCount}}** in the storyboard.++{{#hasSlugline}}+- **Slugline:** `{{slugline}}`+{{/hasSlugline}}++{{#hasNeighbors}}+For visual continuity, here are the scenes **before** and **after** this one (do not re-render either — just use as continuity context):++- **Previous scene:** {{previousScene}}+- **Next scene:** {{nextScene}}+{{/hasNeighbors}}++## Current scene content++- **Description (what to refine):**+ ```+ {{description}}+ ```++## What to write++A single paragraph (~40–80 words) that an image diffusion model can read top-to-bottom:++1. **Subject** — who/what is in frame and what they're doing. Anonymous characters (visual description only).+2. **Framing** — wide / medium / close-up; lens feel (anamorphic, 35mm, macro); camera height + angle.+3. **Composition** — foreground / midground / background, focal point, lead lines.+4. **Lighting + mood** — palette, key/fill, time of day, weather, atmosphere (haze, dust, rain), shadow contrast.+5. **Texture / details** — material call-outs that pay off the genre (rivets, ozone, scrollwork, neon, oil sheen, fabric weave).++## Rules++- Do **not** repeat the series style notes or character physical descriptions — those are prepended automatically.+- Do **not** invent characters, locations, or props the scene doesn't already imply.+- Keep characters anonymous (visual description only) — image models without story context can't resolve names.+- The slugline (`INT. KITCHEN — NIGHT`) is hard truth: don't contradict location, interior/exterior, or time of day.+- Lean into the visual genre cues from the series' tone/style; assume an experienced cinematographer + colorist is rendering a still.++## Output++Return ONLY valid JSON. The `prompt` field is the refined description that will replace the scene's current description.++```json+{+ "prompt": "<refined image-gen prompt, single paragraph>",+ "changes": ["<short bullet of what changed>", "..."]+}+```diff --git a/server/routes/mediaJobs.js b/server/routes/mediaJobs.jsindex 47ef4d98da..9455b7e850 100644--- a/server/routes/mediaJobs.js+++ b/server/routes/mediaJobs.js@@ -123,7 +123,14 @@ router.post('/refine-prompt', asyncHandler(async (req, res) => {router.get('/:id', asyncHandler(async (req, res) => {const job = getJob(req.params.id);- if (!job) throw new ServerError('Not found', { status: 404, code: 'NOT_FOUND' });+ if (!job) {+ // Speculative lookups (Pipeline `MediaJobThumb` hydration for old+ // panel/scene jobIds that are past the queue's 24h archive TTL) hit+ // this path constantly. Mark as `warning` so it doesn't surface as a+ // global toast/console.error via useErrorNotifications — the body is+ // unchanged, callers still get a 404 + NOT_FOUND code.+ throw new ServerError('Not found', { status: 404, code: 'NOT_FOUND', severity: 'warning' });+ }res.json(sanitizeJob(job));}));diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex b215172a14..415e8ae078 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -37,7 +37,13 @@ import * as seasonsSvc from '../services/pipeline/seasons.js';import * as arcPlanner from '../services/pipeline/arcPlanner.js';import { generateStage } from '../services/pipeline/textStages.js';import * as autoRunner from '../services/pipeline/autoRunner.js';-import { enqueueVisualImage, enqueueVisualComicPage } from '../services/pipeline/visualStages.js';+import {+ enqueueVisualImage,+ enqueueVisualComicPage,+ enqueueStoryboardSceneVideo,+ refineComicPanelPrompt,+ refineStoryboardScenePrompt,+} from '../services/pipeline/visualStages.js';import { startEpisodeVideoForIssue, ERR_NO_STORYBOARDS } from '../services/pipeline/episodeVideo.js';import { ASPECT_RATIOS, QUALITIES } from '../lib/creativeDirectorPresets.js';import { extractScenes, SOURCE_KIND } from '../lib/sceneExtractor.js';@@ -252,6 +258,23 @@ const episodeVideoSchema = z.object({force: z.boolean().optional(),});+// Single-scene video render. Lighter schema than episodeVideo because there+// is no stitch step — just one t2v render against the scene's existing+// description.+const sceneVideoSchema = z.object({+ aspectRatio: z.enum(ASPECT_RATIOS).optional(),+ modelId: z.string().trim().max(64).optional(),+ negativePrompt: z.string().trim().max(2000).optional(),+ extraStyle: z.string().trim().max(2000).optional(),+});++// Provider/model picker for the LLM-driven panel/scene prompt refine. Both+// are optional — server falls back to the active provider + stage default.+const promptRefineSchema = z.object({+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+});+// Source for scene extraction: which text stage to read from (`prose` →// granular paragraph-grain breakdown via `writers-room-script`; `tvScript`// → slugline-grain parse via `pipeline-extract-scenes`). `force` overrides@@ -509,6 +532,32 @@ router.post('/series/:id/arc/verify', asyncHandler(async (req, res) => {// Issue routes// =====================+// Recent issues across all series — used by the sidebar's dynamic Pipeline+// child list. Routes through `listRecentIssues` which sorts the FULL issue+// set by `updatedAt` desc before applying limit; `listIssues` would+// silently miss the most-recent items once the dataset grows past+// `ISSUES_PER_RESPONSE_MAX` (1000).+router.get('/issues/recent', asyncHandler(async (req, res) => {+ // Forward the raw query value to the service — it owns clamping ++ // non-finite handling, and applying our own `Number(...) || 10` here+ // would silently disagree with the service (e.g. limit=0 ends up as 10+ // via the route but clamps to 1 in the service). Pass through and let+ // listRecentIssues coerce.+ const [issues, series] = await Promise.all([+ issuesSvc.listRecentIssues({ limit: req.query.limit }),+ seriesSvc.listSeries(),+ ]);+ const seriesById = new Map(series.map((s) => [s.id, s.name]));+ res.json(issues.map((i) => ({+ id: i.id,+ title: i.title,+ number: i.number,+ seriesId: i.seriesId,+ seriesName: seriesById.get(i.seriesId) || '(unknown series)',+ updatedAt: i.updatedAt,+ })));+}));+router.get('/issues/:id', asyncHandler(async (req, res) => {const issue = await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });res.json(issue);@@ -686,6 +735,53 @@ router.post('/issues/:id/stages/comicPages/pages/:pageIndex/render', asyncHandleres.json({ ...result, issue: updatedIssue, stage });}));+// AI-driven prompt refinement for a single comic panel. Uses+// pipeline-comic-panel-image-prompt stage to elaborate the panel's existing+// description into a richer image-gen prompt, then persists the result on+// the panel.+router.post('/issues/:id/stages/comicPages/pages/:pageIndex/panels/:panelIndex/refine-prompt',+ asyncHandler(async (req, res) => {+ const body = validateRequest(promptRefineSchema, req.body ?? {});+ const result = await refineComicPanelPrompt(+ req.params.id,+ Number(req.params.pageIndex),+ Number(req.params.panelIndex),+ body,+ ).catch((err) => { throw mapServiceError(err); });+ res.json(result);+ }),+);++// AI-driven prompt refinement for a single storyboard scene. Mirror of the+// comic-panel refine but uses pipeline-storyboard-image-prompt.+router.post('/issues/:id/stages/storyboards/scenes/:index/refine-prompt',+ asyncHandler(async (req, res) => {+ const body = validateRequest(promptRefineSchema, req.body ?? {});+ const result = await refineStoryboardScenePrompt(+ req.params.id,+ Number(req.params.index),+ 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.+router.post('/issues/:id/stages/storyboards/scenes/:index/video', asyncHandler(async (req, res) => {+ const idx = Number(req.params.index);+ if (!Number.isInteger(idx) || idx < 0) {+ throw new ServerError('scene index must be a non-negative integer', {+ status: 400, code: 'PIPELINE_SCENE_BAD_INDEX',+ });+ }+ const body = validateRequest(sceneVideoSchema, req.body ?? {});+ const result = await enqueueStoryboardSceneVideo(req.params.id, idx, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));+router.post('/issues/:id/stages/:stageId/visual', asyncHandler(async (req, res) => {const { id, stageId } = req.params;if (!issuesSvc.VISUAL_STAGE_IDS.includes(stageId)) {diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.jsindex ca868462c9..aa717b3fdb 100644--- a/server/routes/pipeline.test.js+++ b/server/routes/pipeline.test.js@@ -69,6 +69,32 @@ vi.mock('../services/pipeline/visualStages.js', () => ({prompt: `comic-page prompt for page ${opts.pageIndex + 1}`,pageIndex: opts.pageIndex,})),+ // Single-scene video render. Returns the shape the route forwards verbatim+ // to clients: { jobId, prompt, sceneIndex, issue, stage }.+ enqueueStoryboardSceneVideo: vi.fn(async (issueId, sceneIndex) => ({+ jobId: `scene-vid-${++uuidCounter}`,+ prompt: `scene video prompt ${sceneIndex}`,+ sceneIndex,+ issue: { id: issueId, stages: { storyboards: { scenes: [] } } },+ stage: { scenes: [] },+ })),+ refineComicPanelPrompt: vi.fn(async (issueId, pi, ni) => ({+ panel: { description: 'refined panel body' },+ page: { panels: [] },+ issue: { id: issueId, stages: { comicPages: { pages: [] } } },+ stage: { pages: [] },+ runId: 'run-mock-comic',+ changes: ['mock change'],+ providerId: 'mock-provider',+ })),+ refineStoryboardScenePrompt: vi.fn(async (issueId, idx) => ({+ scene: { description: 'refined scene body' },+ issue: { id: issueId, stages: { storyboards: { scenes: [] } } },+ stage: { scenes: [] },+ runId: 'run-mock-scene',+ changes: ['mock change'],+ providerId: 'mock-provider',+ })),}));// The episode-video handoff creates a CD project; stub it so the route test@@ -198,6 +224,81 @@ describe('pipeline routes', () => {expect(r.status).toBe(400);});+ it('GET /issues/recent?limit=0 clamps to 1 (route forwards to service which owns coercion)', async () => {+ const app = makeApp();+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });+ await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'A' });+ await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'B' });+ const r = await request(app).get('/api/pipeline/issues/recent?limit=0');+ expect(r.status).toBe(200);+ // Without alignment, the route's `Number(...) || 10` would return up+ // to 10 issues even when the caller explicitly passed 0.+ expect(r.body).toHaveLength(1);+ });++ it('GET /issues/recent returns the most-recently-updated issues with denormalized seriesName', async () => {+ const app = makeApp();+ const ser1 = await request(app).post('/api/pipeline/series').send({ name: 'Alpha' });+ const ser2 = await request(app).post('/api/pipeline/series').send({ name: 'Beta' });+ const iss1 = await request(app).post(`/api/pipeline/series/${ser1.body.id}/issues`).send({ title: 'Old' });+ // Bump iss1's updatedAt back so iss2 is unambiguously the most recent.+ await new Promise((r) => setTimeout(r, 10));+ const iss2 = await request(app).post(`/api/pipeline/series/${ser2.body.id}/issues`).send({ title: 'Newer' });+ const r = await request(app).get('/api/pipeline/issues/recent?limit=10');+ expect(r.status).toBe(200);+ expect(Array.isArray(r.body)).toBe(true);+ expect(r.body[0].id).toBe(iss2.body.id);+ expect(r.body[0].seriesName).toBe('Beta');+ expect(r.body.find((i) => i.id === iss1.body.id)?.seriesName).toBe('Alpha');+ });++ it('POST /issues/:id/stages/storyboards/scenes/:index/video 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/video`)+ .send({ aspectRatio: '16:9' });+ expect(r.status).toBe(200);+ expect(r.body.jobId).toMatch(/^scene-vid-/);+ expect(r.body.sceneIndex).toBe(0);+ });++ it('POST /issues/:id/stages/storyboards/scenes/:index/video rejects a non-integer index', 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/video`)+ .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' });+ 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/comicPages/pages/0/panels/0/refine-prompt`)+ .send({});+ expect(r.status).toBe(200);+ expect(r.body.runId).toBe('run-mock-comic');+ expect(r.body.panel.description).toBe('refined panel body');+ expect(r.body.changes).toEqual(['mock change']);+ });++ it('POST /issues/:id/stages/storyboards/scenes/:index/refine-prompt returns the refined scene', 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/refine-prompt`)+ .send({ providerId: 'codex', model: 'gpt-4o' });+ expect(r.status).toBe(200);+ expect(r.body.runId).toBe('run-mock-scene');+ expect(r.body.scene.description).toBe('refined scene body');+ });+it('POST /issues/:id/auto-run-text returns runId + sseUrl', async () => {const app = makeApp();const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex a68ab29613..c6dd8d4137 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -160,6 +160,27 @@ export async function listIssues({ seriesId = null } = {}) {.slice(0, ISSUES_PER_RESPONSE_MAX);}+/**+ * Recently-updated issues across all series. Sorts the FULL issue set by+ * `updatedAt` desc before applying `limit` — unlike `listIssues`, which+ * sorts by `seriesId/number` then caps at `ISSUES_PER_RESPONSE_MAX`. That+ * cap would silently miss the most-recent issues once the dataset grows+ * beyond 1000, so the sidebar's recent-issues view needs this dedicated+ * helper.+ */+export async function listRecentIssues({ limit = 10 } = {}) {+ const { issues } = await readState();+ // Coerce in two passes so non-finite inputs ('abc', undefined) fall to+ // the default rather than letting JS's `0 || 10` short-circuit return+ // 10 for an explicit limit=0.+ const raw = Number(limit);+ const fallback = Number.isFinite(raw) ? Math.floor(raw) : 10;+ const clamped = Math.max(1, Math.min(50, fallback));+ return [...issues]+ .sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''))+ .slice(0, clamped);+}+export async function getIssue(id) {const { issues } = await readState();const found = issues.find((i) => i.id === id);diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.jsindex e90315aa20..fa727dc445 100644--- a/server/services/pipeline/issues.test.js+++ b/server/services/pipeline/issues.test.js@@ -86,6 +86,49 @@ describe('pipeline issues service', () => {expect(list1.every((i) => i.seriesId === 'ser-1')).toBe(true);});+ describe('listRecentIssues', () => {+ it('orders descending by updatedAt across all series', async () => {+ const a = await svc.createIssue({ seriesId: 'ser-1', title: 'A' });+ const b = await svc.createIssue({ seriesId: 'ser-2', title: 'B' });+ const c = await svc.createIssue({ seriesId: 'ser-3', title: 'C' });+ // Bump A so it becomes unambiguously the most recent — its update+ // timestamp will be 10ms later than B and C's creates, which may+ // share the same ms-resolution timestamp with each other.+ await new Promise((r) => setTimeout(r, 10));+ await svc.updateStage(a.id, 'idea', { status: 'ready', output: 'fresh' });+ const recent = await svc.listRecentIssues({ limit: 10 });+ expect(recent[0].id).toBe(a.id);+ expect(recent).toHaveLength(3);+ // B and C may tie on ms-resolution timestamps; only assert their+ // membership in the remaining positions, not the order between them.+ expect(new Set(recent.slice(1).map((i) => i.id))).toEqual(new Set([b.id, c.id]));+ });++ it('clamps limit: < 1 → 1, > 50 → 50, non-numeric → default 10', async () => {+ for (let i = 0; i < 12; i += 1) {+ // Stagger to keep updatedAt monotonic.+ await svc.createIssue({ seriesId: 'ser-1', title: `T${i}` });+ await new Promise((r) => setTimeout(r, 2));+ }+ expect((await svc.listRecentIssues({ limit: 0 })).length).toBe(1);+ expect((await svc.listRecentIssues({ limit: -5 })).length).toBe(1);+ expect((await svc.listRecentIssues({ limit: 999 })).length).toBe(12);+ expect((await svc.listRecentIssues({ limit: 'abc' })).length).toBe(10);+ expect((await svc.listRecentIssues({})).length).toBe(10);+ });++ it('respects the upper clamp of 50', async () => {+ // Verifying the cap without creating 51 issues — pass an explicit+ // huge limit and confirm it clamps to 50 (one of the bounds), and+ // a limit of 50 returns up to 50.+ for (let i = 0; i < 3; i += 1) {+ await svc.createIssue({ seriesId: 'ser-1', title: `Y${i}` });+ }+ const r = await svc.listRecentIssues({ limit: 9999 });+ expect(r.length).toBeLessThanOrEqual(50);+ });+ });+it('updateIssue partial patch preserves other fields', async () => {const i = await svc.createIssue({ seriesId: 'ser-1', title: 'First' });await svc.updateStage(i.id, 'idea', { status: 'ready', output: 'Beats here' });diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.jsindex a038aef424..89ea90aa6c 100644--- a/server/services/pipeline/visualStages.js+++ b/server/services/pipeline/visualStages.js@@ -1,26 +1,39 @@/*** Pipeline — Visual stage handoff helpers*- * Thin wrappers that enqueue image-gen jobs on behalf of the Pipeline's- * comicPages and storyboards stages. The route layer is responsible for- * persisting the returned jobIds into the issue's stage record — this module- * just owns the "build the right params, hand to mediaJobQueue" mechanic so- * the pipeline doesn't have to duplicate Image-Gen's mode-resolution code.+ * Responsibilities, in order of how they evolved:*- * MVP scope: image jobs only. Scene video / episode-video stitching is- * deferred — the storyboards and episodeVideo stages currently expose- * read/write of their structured fields but don't yet drive the Creative- * Director scene runner. See PLAN.md "Pipeline — Deferred" for the follow-up.+ * 1. **Image enqueue** (`enqueueVisualImage`, `enqueueVisualComicPage`) —+ * build the right diffusion params for a comicPages panel / page or a+ * storyboards scene and hand off to `mediaJobQueue`. The route layer+ * persists the returned jobId into the issue's stage record.+ *+ * 2. **Single-scene video enqueue** (`enqueueStoryboardSceneVideo`) —+ * render one storyboard scene as a t2v clip without committing to the+ * full episode-video stitch. Persists `sceneVideoJobId` on the scene+ * so a reload still surfaces the in-flight render.+ *+ * 3. **LLM-driven prompt refinement** (`refineComicPanelPrompt`,+ * `refineStoryboardScenePrompt`) — elaborate a panel/scene description+ * into a richer image-gen prompt via `runStagedLLM`, then persist the+ * refined text back on the source record. Shared `runPromptRefine`+ * helper + slim `loadRefineContext` keep the two surfaces DRY.+ *+ * Full episode-video stitching still lives in `episodeVideo.js` — that+ * path drives the Creative Director scene runner end-to-end.*/import { enqueueJob } from '../mediaJobQueue/index.js';import { getSettings } from '../settings.js';import { getSeries } from './series.js';-import { getIssue, VISUAL_STAGE_IDS } from './issues.js';+import { getIssue, updateStage, VISUAL_STAGE_IDS } from './issues.js';import { getWorld } from '../worldBuilder.js';import { ServerError } from '../../lib/errorHandler.js';import { buildScenePrompt, buildSettingByKey, matchSceneSetting } from '../../lib/scenePrompt.js';import { composeStyledPrompt } from '../../lib/composeStyledPrompt.js';+import { getDefaultVideoModelId, getVideoModels } from '../../lib/mediaModels.js';+import { runStagedLLM } from '../../lib/stageRunner.js';+import { ASPECT_PRESETS } from '../../lib/creativeDirectorPresets.js';const SUPPORTED_MODES = new Set(['local', 'codex']);@@ -211,3 +224,276 @@ export async function enqueueVisualImage(issueId, stageId, options = {}) {});return { jobId, mode, prompt };}++/**+ * Enqueue a single-scene video render for a storyboard scene. Builds the+ * same prompt the episode-video CD treatment would build for this scene+ * (composeVisualPrompt with style notes + world style), then enqueues a+ * video job through the shared mediaJobQueue.+ *+ * Persists the resulting jobId on `stages.storyboards.scenes[index]+ * .sceneVideoJobId` so the UI can reflect it on reload.+ *+ * Returns { jobId, prompt, sceneIndex }.+ */+export async function enqueueStoryboardSceneVideo(issueId, sceneIndex, options = {}) {+ const idx = Number(sceneIndex);+ if (!Number.isInteger(idx) || idx < 0) {+ throw new ServerError('sceneIndex must be a non-negative integer', {+ status: 400, code: 'PIPELINE_SCENE_BAD_INDEX',+ });+ }+ const { issue, settings, series, world } = await loadBibleContext(issueId);+ const pythonPath = settings.imageGen?.local?.pythonPath || null;+ if (!pythonPath) {+ throw new ServerError(+ 'Local video generation is not configured (settings.imageGen.local.pythonPath is missing).',+ { status: 400, code: 'VIDEO_GEN_NOT_CONFIGURED' },+ );+ }+ const scenes = Array.isArray(issue.stages?.storyboards?.scenes)+ ? [...issue.stages.storyboards.scenes]+ : [];+ const scene = scenes[idx];+ if (!scene) {+ throw new ServerError(`sceneIndex ${idx} out of range (have ${scenes.length})`, {+ status: 404, code: 'PIPELINE_SCENE_NOT_FOUND',+ });+ }+ if (!(scene.description || '').trim()) {+ throw new ServerError('scene has no description — add a description before rendering', {+ status: 400, code: 'PIPELINE_SCENE_EMPTY_DESCRIPTION',+ });+ }++ const prompt = composeVisualPrompt({+ series,+ description: scene.description,+ slugline: scene.slugline || '',+ extraStyle: options.extraStyle,+ world,+ });++ const aspectRatio = ASPECT_PRESETS[options.aspectRatio] ? options.aspectRatio : '16:9';+ const { width, height } = ASPECT_PRESETS[aspectRatio];+ const modelId = options.modelId || settings.videoGen?.defaultModelId || getDefaultVideoModelId();+ // Validate the model exists for this platform before enqueueing — otherwise+ // the worker will fail with "Unknown video model" and leave a persisted+ // doomed entry in the queue. Mirrors the same fail-fast pattern as+ // /api/video-gen's route validation.+ if (!getVideoModels().some((m) => m.id === modelId)) {+ throw new ServerError(`Unknown video model "${modelId}"`, {+ status: 400, code: 'PIPELINE_UNKNOWN_VIDEO_MODEL',+ });+ }+ const negativePrompt = options.negativePrompt || 'text, watermark, blur, motion blur, low quality';++ const { jobId } = enqueueJob({+ kind: 'video',+ params: {+ pythonPath,+ prompt,+ negativePrompt,+ modelId,+ width,+ height,+ mode: 't2v',+ disableAudio: true,+ tiling: 'auto',+ chunks: 1,+ },+ owner: `pipeline:${issueId}:storyboards:scene${idx}`,+ });++ scenes[idx] = { ...scene, sceneVideoJobId: jobId };+ const { issue: updatedIssue, stage } = await updateStage(issueId, 'storyboards', {+ status: 'edited',+ scenes,+ });+ console.log(`🎥 Pipeline scene video — issue=${issueId.slice(0, 8)} scene=${idx + 1} jobId=${jobId.slice(0, 8)}`);+ return { jobId, prompt, sceneIndex: idx, issue: updatedIssue, stage };+}++const seriesBibleCtx = (series) => ({+ name: series.name || '',+ styleNotes: series.styleNotes || '',+ logline: series.logline || '',+ premise: series.premise || '',+});++const issueCtx = (issue) => ({ number: issue.number || 0, title: issue.title || '' });++const neighborText = (item) => (item?.description || '').trim().slice(0, 240) || '(empty)';++// Refine path needs issue + series only — skip the settings + world reads+// that loadBibleContext does for the image/video enqueue path.+async function loadRefineContext(issueId) {+ const issue = await getIssue(issueId);+ const series = await getSeries(issue.seriesId);+ return { issue, series };+}++// Shared scaffolding for both the comic-panel and storyboard-scene refine+// paths. The caller supplies the per-stage variables/persist details; this+// helper owns the runStagedLLM call + result parsing + empty-prompt guard ++// changes shaping.+async function runPromptRefine({ templateName, variables, options, source, logTag }) {+ const result = await runStagedLLM(templateName, variables, {+ providerOverride: options.providerId,+ modelOverride: options.model,+ returnsJson: true,+ source,+ });+ const refined = (result.content?.prompt || '').trim();+ if (!refined) {+ throw new ServerError('LLM returned an empty refined prompt', {+ status: 502, code: 'PIPELINE_PROMPT_REFINE_EMPTY',+ });+ }+ const changes = Array.isArray(result.content?.changes)+ ? result.content.changes.map((c) => String(c).slice(0, 240)).filter(Boolean).slice(0, 8)+ : [];+ console.log(`✨ ${logTag} runId=${(result.runId || '').slice(0, 8)}`);+ return { refined, changes, runId: result.runId, providerId: result.providerId };+}++/**+ * Run the `pipeline-comic-panel-image-prompt` template against the current+ * panel + surrounding context, then persist the refined description on the+ * panel. Returns { panel, page, issue, stage, runId, changes, providerId }.+ */+export async function refineComicPanelPrompt(issueId, pageIndex, panelIndex, options = {}) {+ const pi = Number(pageIndex);+ const ni = Number(panelIndex);+ if (!Number.isInteger(pi) || pi < 0 || !Number.isInteger(ni) || ni < 0) {+ throw new ServerError('pageIndex and panelIndex must be non-negative integers', {+ status: 400, code: 'PIPELINE_PANEL_BAD_INDEX',+ });+ }+ const { issue, series } = await loadRefineContext(issueId);+ const pages = Array.isArray(issue.stages?.comicPages?.pages) ? [...issue.stages.comicPages.pages] : [];+ const page = pages[pi];+ if (!page) {+ throw new ServerError(`pageIndex ${pi} out of range (have ${pages.length})`, {+ status: 404, code: 'PIPELINE_COMIC_PAGE_NOT_FOUND',+ });+ }+ const panels = Array.isArray(page.panels) ? [...page.panels] : [];+ const panel = panels[ni];+ if (!panel) {+ throw new ServerError(`panelIndex ${ni} out of range (have ${panels.length})`, {+ status: 404, code: 'PIPELINE_COMIC_PANEL_NOT_FOUND',+ });+ }+ if (!(panel.description || '').trim()) {+ throw new ServerError('panel has no description to refine', {+ status: 400, code: 'PIPELINE_PANEL_EMPTY_DESCRIPTION',+ });+ }++ const prev = panels[ni - 1];+ const next = panels[ni + 1];+ // Drop dialogue rows whose line is empty/whitespace — matches the same+ // filter `composeComicPagePrompt` applies, so the refine template doesn't+ // get fed noisy `CHAR: ""` fragments that would confuse the LLM.+ const dialogue = Array.isArray(panel.dialogue) && panel.dialogue.length+ ? panel.dialogue+ .map((d) => {+ const character = (d.character || 'CHAR').trim() || 'CHAR';+ const line = (d.line || '').trim();+ return line ? `${character}: "${line}"` : null;+ })+ .filter(Boolean)+ .join(' / ')+ : '';++ const { refined, changes, runId, providerId } = await runPromptRefine({+ templateName: 'pipeline-comic-panel-image-prompt',+ variables: {+ series: seriesBibleCtx(series),+ issue: issueCtx(issue),+ pageNumber: pi + 1,+ panelNumber: ni + 1,+ panelCount: panels.length,+ description: (panel.description || '').slice(0, 4000),+ caption: (panel.caption || '').slice(0, 1000),+ hasCaption: !!(panel.caption || '').trim(),+ dialogue,+ hasDialogue: !!dialogue,+ sfx: (panel.sfx || '').slice(0, 500),+ hasSfx: !!(panel.sfx || '').trim(),+ hasNeighbors: !!(prev || next),+ previousPanel: neighborText(prev),+ nextPanel: neighborText(next),+ },+ options,+ source: 'pipeline-comic-panel-prompt-refine',+ logTag: `Pipeline comic panel refine — issue=${issueId.slice(0, 8)} p=${pi + 1} panel=${ni + 1}`,+ });++ panels[ni] = { ...panel, description: refined };+ pages[pi] = { ...page, panels };+ const { issue: updatedIssue, stage } = await updateStage(issueId, 'comicPages', {+ status: 'edited',+ pages,+ });+ return { panel: panels[ni], page: pages[pi], issue: updatedIssue, stage, runId, changes, providerId };+}++/**+ * Run the `pipeline-storyboard-image-prompt` template against the current+ * storyboard scene + surrounding context, then persist the refined+ * description on the scene. Returns { scene, issue, stage, runId, changes, providerId }.+ */+export async function refineStoryboardScenePrompt(issueId, sceneIndex, options = {}) {+ const idx = Number(sceneIndex);+ if (!Number.isInteger(idx) || idx < 0) {+ throw new ServerError('sceneIndex must be a non-negative integer', {+ status: 400, code: 'PIPELINE_SCENE_BAD_INDEX',+ });+ }+ const { issue, series } = await loadRefineContext(issueId);+ const scenes = Array.isArray(issue.stages?.storyboards?.scenes)+ ? [...issue.stages.storyboards.scenes]+ : [];+ const scene = scenes[idx];+ if (!scene) {+ throw new ServerError(`sceneIndex ${idx} out of range (have ${scenes.length})`, {+ status: 404, code: 'PIPELINE_SCENE_NOT_FOUND',+ });+ }+ if (!(scene.description || '').trim()) {+ throw new ServerError('scene has no description to refine', {+ status: 400, code: 'PIPELINE_SCENE_EMPTY_DESCRIPTION',+ });+ }++ const prev = scenes[idx - 1];+ const next = scenes[idx + 1];++ const { refined, changes, runId, providerId } = await runPromptRefine({+ templateName: 'pipeline-storyboard-image-prompt',+ variables: {+ series: seriesBibleCtx(series),+ issue: issueCtx(issue),+ sceneNumber: idx + 1,+ sceneCount: scenes.length,+ slugline: (scene.slugline || '').slice(0, 200),+ hasSlugline: !!(scene.slugline || '').trim(),+ description: (scene.description || '').slice(0, 4000),+ hasNeighbors: !!(prev || next),+ previousScene: neighborText(prev),+ nextScene: neighborText(next),+ },+ options,+ source: 'pipeline-storyboard-prompt-refine',+ logTag: `Pipeline scene refine — issue=${issueId.slice(0, 8)} scene=${idx + 1}`,+ });++ scenes[idx] = { ...scene, description: refined };+ const { issue: updatedIssue, stage } = await updateStage(issueId, 'storyboards', {+ status: 'edited',+ scenes,+ });+ return { scene: scenes[idx], issue: updatedIssue, stage, runId, changes, providerId };+}diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.jsindex 4492541e63..5b22a3c4c6 100644--- a/server/services/pipeline/visualStages.test.js+++ b/server/services/pipeline/visualStages.test.js@@ -1,5 +1,82 @@-import { describe, expect, it } from 'vitest';-import { composeComicPagePrompt } from './visualStages.js';+import { describe, expect, it, vi, beforeEach } from 'vitest';++// Mock the persistence + LLM + queue surface so the new function tests+// exercise pure orchestration without hitting disk or providers. Mocks+// must register before the SUT is imported (vi.mock hoists).+const mockIssue = {+ id: 'iss-test',+ seriesId: 'ser-test',+ stages: {+ storyboards: {+ scenes: [+ { slugline: 'INT. LAB — NIGHT', description: 'Scene 1 baseline.', imageJobId: null },+ { slugline: 'EXT. STREET — DAY', description: 'Scene 2 baseline.', imageJobId: null },+ ],+ },+ comicPages: {+ pages: [+ {+ panels: [+ { description: 'Panel 1 baseline.', dialogue: [], caption: '', sfx: '' },+ { description: 'Panel 2 baseline.', dialogue: [{ character: 'X', line: 'line' }], caption: 'c', sfx: 's' },+ ],+ },+ ],+ },+ },+};++const getIssueMock = vi.fn(async () => structuredClone(mockIssue));+const updateStageMock = vi.fn(async (issueId, stageId, patch) => ({+ issue: { ...mockIssue, stages: { ...mockIssue.stages, [stageId]: { ...mockIssue.stages[stageId], ...patch } } },+ stage: { ...mockIssue.stages[stageId], ...patch },+}));+vi.mock('./issues.js', () => ({+ getIssue: (...a) => getIssueMock(...a),+ updateStage: (...a) => updateStageMock(...a),+ VISUAL_STAGE_IDS: ['comicPages', 'storyboards', 'episodeVideo'],+ STAGE_IDS: ['idea', 'prose', 'comicScript', 'tvScript', 'comicPages', 'storyboards', 'episodeVideo'],+}));++vi.mock('./series.js', () => ({+ getSeries: vi.fn(async () => ({ id: 'ser-test', name: 'Test', styleNotes: 'noir', characters: [], settings: [] })),+}));++vi.mock('../settings.js', () => ({+ getSettings: vi.fn(async () => ({ imageGen: { local: { pythonPath: '/usr/bin/python3' }, mode: 'local' }, videoGen: {} })),+}));++vi.mock('../worldBuilder.js', () => ({ getWorld: vi.fn(async () => null) }));++const enqueueJobMock = vi.fn(() => ({ jobId: 'job-fake-1234' }));+vi.mock('../mediaJobQueue/index.js', () => ({ enqueueJob: (...a) => enqueueJobMock(...a) }));++const runStagedLLMMock = vi.fn(async () => ({+ content: { prompt: 'refined prompt body', changes: ['tightened the framing'] },+ runId: 'run-abc12345',+ providerId: 'codex',+ model: 'gpt-4o',+}));+vi.mock('../../lib/stageRunner.js', () => ({ runStagedLLM: (...a) => runStagedLLMMock(...a) }));++vi.mock('../../lib/mediaModels.js', () => ({+ getDefaultVideoModelId: () => 'ltx-default',+ getVideoModels: () => [{ id: 'ltx-default' }, { id: 'ltx-extra' }],+}));++const {+ composeComicPagePrompt,+ enqueueStoryboardSceneVideo,+ refineComicPanelPrompt,+ refineStoryboardScenePrompt,+} = await import('./visualStages.js');++beforeEach(() => {+ getIssueMock.mockClear();+ updateStageMock.mockClear();+ enqueueJobMock.mockClear();+ runStagedLLMMock.mockClear();+});const SERIES = {name: 'Bone Walker',@@ -109,3 +186,145 @@ describe('composeComicPagePrompt', () => {expect(prompt).toMatch(/SFX: fmp\./);});});++describe('enqueueStoryboardSceneVideo', () => {+ it('rejects a non-integer sceneIndex', async () => {+ await expect(enqueueStoryboardSceneVideo('iss-test', 'nope')).rejects.toThrow(/non-negative integer/);+ });++ it('rejects when sceneIndex is out of range', async () => {+ await expect(enqueueStoryboardSceneVideo('iss-test', 99)).rejects.toThrow(/out of range/);+ });++ it('rejects when the scene has no description', async () => {+ getIssueMock.mockResolvedValueOnce({+ ...structuredClone(mockIssue),+ stages: { ...mockIssue.stages, storyboards: { scenes: [{ description: ' ' }] } },+ });+ await expect(enqueueStoryboardSceneVideo('iss-test', 0)).rejects.toThrow(/no description/);+ });++ it('rejects when modelId is unknown for this platform', async () => {+ await expect(enqueueStoryboardSceneVideo('iss-test', 0, { modelId: 'ltx-typo' }))+ .rejects.toThrow(/Unknown video model/);+ });++ it('rejects when local python is not configured', async () => {+ const settingsMod = await import('../settings.js');+ settingsMod.getSettings.mockResolvedValueOnce({ imageGen: { local: { pythonPath: null }, mode: 'local' }, videoGen: {} });+ await expect(enqueueStoryboardSceneVideo('iss-test', 0)).rejects.toThrow(/VIDEO_GEN_NOT_CONFIGURED|is not configured/);+ });++ it('happy path: enqueues a t2v video job and persists sceneVideoJobId on the scene', async () => {+ const result = await enqueueStoryboardSceneVideo('iss-test', 0, { aspectRatio: '9:16' });+ expect(result.jobId).toBe('job-fake-1234');+ expect(result.sceneIndex).toBe(0);+ expect(enqueueJobMock).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'video',+ params: expect.objectContaining({ mode: 't2v', disableAudio: true, width: 432, height: 768 }),+ }));+ expect(updateStageMock).toHaveBeenCalledWith('iss-test', 'storyboards', expect.objectContaining({+ status: 'edited',+ scenes: expect.arrayContaining([+ expect.objectContaining({ sceneVideoJobId: 'job-fake-1234' }),+ ]),+ }));+ });+});++describe('refineComicPanelPrompt', () => {+ it('rejects a non-integer pageIndex / panelIndex', async () => {+ await expect(refineComicPanelPrompt('iss-test', 'nope', 0)).rejects.toThrow(/non-negative integers/);+ await expect(refineComicPanelPrompt('iss-test', 0, -1)).rejects.toThrow(/non-negative integers/);+ });++ it('returns 404 when the page does not exist', async () => {+ await expect(refineComicPanelPrompt('iss-test', 99, 0)).rejects.toThrow(/page.*out of range|PIPELINE_COMIC_PAGE_NOT_FOUND/);+ });++ it('returns 404 when the panel does not exist', async () => {+ await expect(refineComicPanelPrompt('iss-test', 0, 99)).rejects.toThrow(/panel.*out of range|PIPELINE_COMIC_PANEL_NOT_FOUND/);+ });++ it('rejects when the panel has no description', async () => {+ getIssueMock.mockResolvedValueOnce({+ ...structuredClone(mockIssue),+ stages: { ...mockIssue.stages, comicPages: { pages: [{ panels: [{ description: ' ' }] }] } },+ });+ await expect(refineComicPanelPrompt('iss-test', 0, 0)).rejects.toThrow(/no description to refine/);+ });++ it('rejects when the LLM returns an empty refined prompt', async () => {+ runStagedLLMMock.mockResolvedValueOnce({+ content: { prompt: ' ', changes: [] }, runId: 'r', providerId: 'p', model: 'm',+ });+ await expect(refineComicPanelPrompt('iss-test', 0, 0)).rejects.toThrow(/empty refined prompt/);+ });++ it('happy path: replaces the panel description and returns changes + runId', async () => {+ const result = await refineComicPanelPrompt('iss-test', 0, 0);+ expect(result.runId).toBe('run-abc12345');+ expect(result.changes).toEqual(['tightened the framing']);+ expect(runStagedLLMMock).toHaveBeenCalledWith(+ 'pipeline-comic-panel-image-prompt',+ expect.objectContaining({ description: expect.stringContaining('Panel 1 baseline.') }),+ expect.objectContaining({ returnsJson: true }),+ );+ expect(updateStageMock).toHaveBeenCalledWith('iss-test', 'comicPages', expect.objectContaining({+ status: 'edited',+ pages: expect.arrayContaining([+ expect.objectContaining({+ panels: expect.arrayContaining([+ expect.objectContaining({ description: 'refined prompt body' }),+ ]),+ }),+ ]),+ }));+ });+});++describe('refineStoryboardScenePrompt', () => {+ it('rejects a non-integer sceneIndex', async () => {+ await expect(refineStoryboardScenePrompt('iss-test', 'nope')).rejects.toThrow(/non-negative integer/);+ });++ it('returns 404 when the scene does not exist', async () => {+ await expect(refineStoryboardScenePrompt('iss-test', 99)).rejects.toThrow(/out of range/);+ });++ it('rejects when the scene has no description', async () => {+ getIssueMock.mockResolvedValueOnce({+ ...structuredClone(mockIssue),+ stages: { ...mockIssue.stages, storyboards: { scenes: [{ description: ' ' }] } },+ });+ await expect(refineStoryboardScenePrompt('iss-test', 0)).rejects.toThrow(/no description to refine/);+ });++ it('rejects when the LLM returns an empty refined prompt', async () => {+ runStagedLLMMock.mockResolvedValueOnce({+ content: { prompt: '', changes: [] }, runId: 'r', providerId: 'p', model: 'm',+ });+ await expect(refineStoryboardScenePrompt('iss-test', 0)).rejects.toThrow(/empty refined prompt/);+ });++ it('happy path: replaces the scene description and uses the storyboard template', async () => {+ const result = await refineStoryboardScenePrompt('iss-test', 1);+ expect(result.runId).toBe('run-abc12345');+ expect(runStagedLLMMock).toHaveBeenCalledWith(+ 'pipeline-storyboard-image-prompt',+ expect.objectContaining({+ sceneNumber: 2,+ slugline: 'EXT. STREET — DAY',+ hasSlugline: true,+ description: expect.stringContaining('Scene 2 baseline.'),+ }),+ expect.objectContaining({ returnsJson: true }),+ );+ expect(updateStageMock).toHaveBeenCalledWith('iss-test', 'storyboards', expect.objectContaining({+ status: 'edited',+ scenes: expect.arrayContaining([+ expect.objectContaining({ description: 'refined prompt body' }),+ ]),+ }));+ });+});diff --git a/server/services/voice/tools.js b/server/services/voice/tools.jsindex 87841d311b..5eaf017eb9 100644--- a/server/services/voice/tools.js+++ b/server/services/voice/tools.js@@ -3,6 +3,7 @@// Add a new tool by pushing another entry onto TOOLS.import { captureThought, getInboxLog } from '../brain.js';+import { STAGE_IDS as PIPELINE_STAGE_IDS } from '../pipeline/issues.js';import { logDrink, getAlcoholSummary } from '../meatspaceAlcohol.js';import { logNicotine, getNicotineSummary } from '../meatspaceNicotine.js';import { addBodyEntry } from '../meatspaceHealth.js';@@ -19,6 +20,112 @@ import { getSettings } from '../settings.js';const DAILY_LOG_PATH = '/brain/daily-log';+// ----- Pipeline stage navigation helpers (used by pipeline_next_stage etc) -----+const PIPELINE_STAGE_LABELS = {+ idea: 'Idea',+ prose: 'Prose',+ comicScript: 'Comic Script',+ tvScript: 'TV Script',+ comicPages: 'Comic Pages',+ storyboards: 'Storyboards',+ episodeVideo: 'Episode Video',+};+// Spoken aliases → canonical stage ids. `resolveNavCommand` covers top-level+// pages but not in-route stage names, so this is a dedicated table.+const PIPELINE_STAGE_ALIASES = {+ idea: 'idea',+ prose: 'prose', story: 'prose',+ 'comic script': 'comicScript', comicscript: 'comicScript', comics: 'comicScript',+ 'tv script': 'tvScript', tvscript: 'tvScript', teleplay: 'tvScript',+ 'comic pages': 'comicPages', 'comic page': 'comicPages', comicpages: 'comicPages', pages: 'comicPages', page: 'comicPages',+ storyboards: 'storyboards', storyboard: 'storyboards', scenes: 'storyboards',+ 'episode video': 'episodeVideo', episodevideo: 'episodeVideo', episode: 'episodeVideo', video: 'episodeVideo',+};+const parsePipelineIssuePath = (path) => {+ if (typeof path !== 'string') return null;+ // Strip query/hash before matching — `[^/]+` would otherwise greedily+ // absorb `?foo=bar` or `#anchor` into the captured id/stage segments+ // (the path "/pipeline/issues/abc?x" would parse as id="abc?x").+ const clean = path.split(/[?#]/)[0];+ const m = clean.match(/^\/pipeline\/issues\/([^/]+)(?:\/([^/]+))?/);+ if (!m) return null;+ const stage = PIPELINE_STAGE_IDS.includes(m[2]) ? m[2] : 'idea';+ return { issueId: m[1], stage };+};+const NOT_ON_PIPELINE_ISSUE_PAGE = {+ ok: false,+ error: 'Not on a pipeline issue page',+ summary: 'I can only switch stages from a /pipeline/issues/... page. Open an issue first.',+};+const navigateToPipelineStage = (issueId, stage, ctx) => {+ const path = `/pipeline/issues/${issueId}/${stage}`;+ ctx.sideEffects?.push({ type: 'navigate', path });+ return { ok: true, path, stage, label: PIPELINE_STAGE_LABELS[stage], summary: `Opened ${PIPELINE_STAGE_LABELS[stage]}.` };+};+const PIPELINE_STAGE_TOOLS = [+ {+ name: 'pipeline_next_stage',+ description: 'Advance to the next stage of the current pipeline issue (Idea → Prose → Comic Script → TV Script → Comic Pages → Storyboards → Episode Video). Only works on a /pipeline/issues/... page.',+ parameters: { type: 'object', properties: {} },+ execute: async (_args, ctx = {}) => {+ const cur = parsePipelineIssuePath(ctx.state?.ui?.path);+ if (!cur) return NOT_ON_PIPELINE_ISSUE_PAGE;+ const idx = PIPELINE_STAGE_IDS.indexOf(cur.stage);+ if (idx === PIPELINE_STAGE_IDS.length - 1) {+ return { ok: false, error: 'Already on last stage', summary: `Already on ${PIPELINE_STAGE_LABELS[cur.stage]} — that's the last stage.` };+ }+ return navigateToPipelineStage(cur.issueId, PIPELINE_STAGE_IDS[idx + 1], ctx);+ },+ },+ {+ name: 'pipeline_prev_stage',+ description: 'Go back to the previous stage of the current pipeline issue. Only works on a /pipeline/issues/... page.',+ parameters: { type: 'object', properties: {} },+ execute: async (_args, ctx = {}) => {+ const cur = parsePipelineIssuePath(ctx.state?.ui?.path);+ if (!cur) return NOT_ON_PIPELINE_ISSUE_PAGE;+ const idx = PIPELINE_STAGE_IDS.indexOf(cur.stage);+ if (idx === 0) {+ return { ok: false, error: 'Already on first stage', summary: `Already on ${PIPELINE_STAGE_LABELS[cur.stage]} — that's the first stage.` };+ }+ return navigateToPipelineStage(cur.issueId, PIPELINE_STAGE_IDS[idx - 1], ctx);+ },+ },+ {+ name: 'pipeline_open_stage',+ description: 'Open a specific stage of the current pipeline issue by name. Pass `stage` as the user spoke it: "prose", "comic script", "storyboards", "episode video", etc. Only works on a /pipeline/issues/... page.',+ parameters: {+ type: 'object',+ properties: {+ stage: {+ type: 'string',+ description: 'Stage name (idea, prose, comic script, tv script, comic pages, storyboards, episode video).',+ },+ },+ required: ['stage'],+ },+ execute: async ({ stage } = {}, ctx = {}) => {+ const cur = parsePipelineIssuePath(ctx.state?.ui?.path);+ if (!cur) return NOT_ON_PIPELINE_ISSUE_PAGE;+ const key = String(stage || '').trim().toLowerCase();+ // Build a case-insensitive canonical lookup so "Prose", "PROSE",+ // "prose" all resolve. PIPELINE_STAGE_IDS is mixed-case ('idea',+ // 'comicScript', ...) so a direct .includes(key) wouldn't match;+ // compare lowercased forms instead.+ const canonicalById = PIPELINE_STAGE_IDS.find((id) => id.toLowerCase() === key);+ const canonical = PIPELINE_STAGE_ALIASES[key] || canonicalById || null;+ if (!canonical) {+ return {+ ok: false,+ error: `Unknown stage "${stage}"`,+ summary: `I don't know a stage named "${stage}". Try: idea, prose, comic script, tv script, comic pages, storyboards, or episode video.`,+ };+ }+ return navigateToPipelineStage(cur.issueId, canonical, ctx);+ },+ },+];+// Shorthand presets for voice logging. A user saying "I had a beer" should// not need to recite oz + ABV — these defaults match typical US servings.const DRINK_PRESETS = {@@ -70,6 +177,9 @@ const TOOL_GROUPS = {ui_check: 'ui',ui_ask: 'ask',image_generate: 'media',+ pipeline_next_stage: 'pipeline',+ pipeline_prev_stage: 'pipeline',+ pipeline_open_stage: 'pipeline',// UNGROUPED = always-on: time_now, daily_log_append, ui_navigate.// brain_capture used to be always-on, but that caused form-fill turns// ("fill description with X") to be misrouted to brain_capture because@@ -116,6 +226,18 @@ const GROUP_INTENT = {// common false positives like "imagine if" or "show me a picture of the// page" by anchoring on creation verbs paired with visual nouns.media: /\b(?:generate|render|create|draw|sketch|paint|illustrate|make|design|produce)\b[^.!?\n]{0,30}\b(?:image|picture|photo|illustration|art(?:work)?|render|drawing|sketch|portrait|wallpaper|scene|asset|graphic|logo|icon)\b|\bimagegen\b/i,+ // Pipeline stage navigation — fires on "next stage", "previous stage",+ // "back to prose", "open the storyboards", "open prose", "open teleplay",+ // and the stage names + their spoken aliases (idea, prose, story,+ // comic script, teleplay, comic pages, pages, storyboards, scenes,+ // episode video, episode, video). The stage-name alternation is shared+ // across open/go-to/back-to so users don't need to say "stage" as a+ // suffix. The leading anchors keep "take me to pipeline" out of this+ // group — that still routes to ui_navigate.+ //+ // Alias list must mirror PIPELINE_STAGE_ALIASES below so any alias+ // accepted by pipeline_open_stage actually triggers the group.+ pipeline: /\b(?:next stage|previous stage|prev stage|stage (?:advance|forward|back)|(?:open|go to|back to)(?: the)? (?:idea|prose|story|comic ?script|comicscript|comics|tv ?script|tvscript|teleplay|comic ?pages?|comicpages|pages?|storyboards?|scenes|episode ?video|episodevideo|episode|video)(?: stage)?)\b/i,ui: UI_INTENT_RE,};@@ -1199,6 +1321,8 @@ const TOOLS = [},},+ ...PIPELINE_STAGE_TOOLS,+{name: 'time_now',description:diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.jsindex 81809a7ede..b94fb5df01 100644--- a/server/services/voice/tools.test.js+++ b/server/services/voice/tools.test.js@@ -583,3 +583,164 @@ describe("image_generate", () => {codexEnabledRef.value = false;});});++// Pipeline stage navigation tools — parsePipelineIssuePath, pipeline_next_stage,+// pipeline_prev_stage, pipeline_open_stage, plus the GROUP_INTENT.pipeline regex.+describe('pipeline stage navigation tools', () => {+ // Each dispatch needs a ctx with `state.ui.path` (current page) and a+ // `sideEffects` array (where navigate intents land). The helper builds+ // a fresh ctx so per-test mutations don't bleed.+ const makeCtx = (path) => ({+ state: { ui: path === undefined ? undefined : { path } },+ sideEffects: [],+ });++ describe('pipeline_next_stage', () => {+ it('advances from idea → prose', async () => {+ const ctx = makeCtx('/pipeline/issues/iss-abc/idea');+ const r = await dispatchTool('pipeline_next_stage', {}, ctx);+ expect(r.ok).toBe(true);+ expect(r.stage).toBe('prose');+ expect(ctx.sideEffects).toEqual([{ type: 'navigate', path: '/pipeline/issues/iss-abc/prose' }]);+ });++ it('refuses to advance past episodeVideo (last stage)', async () => {+ const r = await dispatchTool('pipeline_next_stage', {}, makeCtx('/pipeline/issues/x/episodeVideo'));+ expect(r.ok).toBe(false);+ expect(r.summary).toMatch(/last stage/);+ });++ it('refuses when not on a pipeline issue page', async () => {+ const r = await dispatchTool('pipeline_next_stage', {}, makeCtx('/brain/inbox'));+ expect(r.ok).toBe(false);+ expect(r.summary).toMatch(/\/pipeline\/issues\//);+ });++ it('defaults the parsed stage to idea when the path omits the stage segment', async () => {+ const ctx = makeCtx('/pipeline/issues/iss-zzz');+ const r = await dispatchTool('pipeline_next_stage', {}, ctx);+ expect(r.ok).toBe(true);+ expect(r.stage).toBe('prose');+ });+ });++ describe('pipeline_prev_stage', () => {+ it('rewinds from prose → idea', async () => {+ const ctx = makeCtx('/pipeline/issues/iss-abc/prose');+ const r = await dispatchTool('pipeline_prev_stage', {}, ctx);+ expect(r.ok).toBe(true);+ expect(r.stage).toBe('idea');+ expect(ctx.sideEffects).toEqual([{ type: 'navigate', path: '/pipeline/issues/iss-abc/idea' }]);+ });++ it('refuses to rewind past idea (first stage)', async () => {+ const r = await dispatchTool('pipeline_prev_stage', {}, makeCtx('/pipeline/issues/x/idea'));+ expect(r.ok).toBe(false);+ expect(r.summary).toMatch(/first stage/);+ });+ });++ describe('pipeline_open_stage', () => {+ it('opens a canonical stage id directly', async () => {+ const ctx = makeCtx('/pipeline/issues/iss-x/idea');+ const r = await dispatchTool('pipeline_open_stage', { stage: 'storyboards' }, ctx);+ expect(r.ok).toBe(true);+ expect(r.stage).toBe('storyboards');+ expect(ctx.sideEffects).toEqual([{ type: 'navigate', path: '/pipeline/issues/iss-x/storyboards' }]);+ });++ it('resolves spoken aliases (teleplay → tvScript, pages → comicPages, video → episodeVideo)', async () => {+ const ctx = makeCtx('/pipeline/issues/iss-x/idea');+ const r1 = await dispatchTool('pipeline_open_stage', { stage: 'teleplay' }, ctx);+ expect(r1.stage).toBe('tvScript');+ const r2 = await dispatchTool('pipeline_open_stage', { stage: 'pages' }, ctx);+ expect(r2.stage).toBe('comicPages');+ const r3 = await dispatchTool('pipeline_open_stage', { stage: 'video' }, ctx);+ expect(r3.stage).toBe('episodeVideo');+ });++ it('resolves canonical ids case-insensitively (e.g. "Prose" → prose, "ComicScript" → comicScript)', async () => {+ const ctx = makeCtx('/pipeline/issues/iss-x/idea');+ const r1 = await dispatchTool('pipeline_open_stage', { stage: 'Prose' }, ctx);+ expect(r1.stage).toBe('prose');+ const r2 = await dispatchTool('pipeline_open_stage', { stage: 'COMICSCRIPT' }, ctx);+ // 'COMICSCRIPT' lowercased ('comicscript') hits the alias table.+ expect(r2.stage).toBe('comicScript');+ });++ it('resolves singular "comic page" / "page" so the regex and alias table agree', async () => {+ // The regex matches `comic ?pages?` (singular OR plural). The alias+ // table now mirrors that so a matched utterance never bottoms out+ // at "Unknown stage" with the user staring at a working group.+ const ctx = makeCtx('/pipeline/issues/iss-x/idea');+ const r1 = await dispatchTool('pipeline_open_stage', { stage: 'comic page' }, ctx);+ expect(r1.stage).toBe('comicPages');+ const r2 = await dispatchTool('pipeline_open_stage', { stage: 'page' }, ctx);+ expect(r2.stage).toBe('comicPages');+ });++ it('rejects an unknown stage with a suggestion list', async () => {+ const ctx = makeCtx('/pipeline/issues/iss-x/idea');+ const r = await dispatchTool('pipeline_open_stage', { stage: 'whatever' }, ctx);+ expect(r.ok).toBe(false);+ expect(r.summary).toMatch(/storyboards/);+ });+ });++ describe('parsePipelineIssuePath (via dispatch)', () => {+ // The parser isn't exported directly — exercise it through the public+ // tools so regressions show up where users would actually feel them.+ it('strips a query string from the path before parsing the id', async () => {+ const ctx = makeCtx('/pipeline/issues/iss-abc/prose?foo=bar');+ const r = await dispatchTool('pipeline_next_stage', {}, ctx);+ expect(r.ok).toBe(true);+ // If the query bled into the issueId or stage, the navigate path+ // would carry "?foo=bar" or fall back to 'idea' as the current stage.+ expect(ctx.sideEffects[0].path).toBe('/pipeline/issues/iss-abc/comicScript');+ });++ it('strips a hash anchor from the path before parsing the id', async () => {+ const ctx = makeCtx('/pipeline/issues/iss-abc/prose#anchor');+ const r = await dispatchTool('pipeline_next_stage', {}, ctx);+ expect(r.ok).toBe(true);+ expect(ctx.sideEffects[0].path).toBe('/pipeline/issues/iss-abc/comicScript');+ });++ it('tolerates a missing UI state', async () => {+ const r = await dispatchTool('pipeline_next_stage', {}, makeCtx(undefined));+ expect(r.ok).toBe(false);+ });+ });++ describe('classifyIntent — pipeline group', () => {+ it('matches explicit stage-advance phrasings', () => {+ expect(classifyIntent('next stage').has('pipeline')).toBe(true);+ expect(classifyIntent('previous stage').has('pipeline')).toBe(true);+ expect(classifyIntent('stage forward').has('pipeline')).toBe(true);+ });++ it('matches "open <stage>" without requiring the trailing word "stage"', () => {+ expect(classifyIntent('open prose').has('pipeline')).toBe(true);+ expect(classifyIntent('open the storyboards').has('pipeline')).toBe(true);+ expect(classifyIntent('back to prose').has('pipeline')).toBe(true);+ expect(classifyIntent('go to storyboards').has('pipeline')).toBe(true);+ });++ it('does not steal generic "open pipeline" / "take me to pipeline" — those belong to ui_navigate', () => {+ expect(classifyIntent('take me to the pipeline').has('pipeline')).toBe(false);+ });++ it('matches spoken aliases so PIPELINE_STAGE_ALIASES resolution actually runs', () => {+ // Aliases that were dropped from the original narrow regex — without+ // these the alias table below was unreachable for these utterances.+ expect(classifyIntent('open teleplay').has('pipeline')).toBe(true);+ expect(classifyIntent('open comics').has('pipeline')).toBe(true);+ expect(classifyIntent('open the pages').has('pipeline')).toBe(true);+ expect(classifyIntent('open page').has('pipeline')).toBe(true);+ expect(classifyIntent('go to scenes').has('pipeline')).toBe(true);+ expect(classifyIntent('open episode').has('pipeline')).toBe(true);+ expect(classifyIntent('open video').has('pipeline')).toBe(true);+ expect(classifyIntent('back to story').has('pipeline')).toBe(true);+ });+ });+});