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(creative-director): autonomous long-form video projects + media job queue (#191)
[._.]/ Adam Eivy9b36b9000004
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e9e4b1691e..3c02a8debb 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -3,7 +3,8 @@## Added- **FLUX.2-klein image generation on macOS (Apple Silicon).** Three quantized variants ship: 4B SDNQ-4bit (~8 GB @ 512px, recommended), 9B SDNQ-4bit (~12 GB, needs 32+ GB RAM), and 4B Int8 (~16 GB). Runs through PyTorch + diffusers + MPS in a separate `~/.portos/venv-flux2` to avoid colliding with mflux's older torch. `INSTALL_FLUX2=1 bash scripts/setup-image-video.sh` bootstraps the venv (idempotent — skips re-install when `Flux2KleinPipeline` already imports). The runner (`scripts/flux2_macos.py`) mirrors `mflux-generate`'s CLI surface so the existing local-image dispatcher just swaps the binary path; live preview frames, metadata sidecar, gallery, and Remix all work unchanged. Stepwise preview decodes latents on a `@torch.no_grad()` callback and writes capped 512-px PNGs so fs.watch + base64 stays cheap. Models are gated on HuggingFace — accept the license at https://huggingface.co/black-forest-labs/FLUX.2-klein-4B and export `HF_TOKEN`; the Image Gen page surfaces a yellow banner when the venv is missing or the token isn't set. The legacy `flux2-klein-{4b,9b}` registry entries (which had `broken: 'macos'`) auto-upgrade in place — user customizations like a custom name or steps are preserved.-+- **Creative Director — autonomous long-form video projects** (`/media/creative-director`). Configure a project with a fixed aspect ratio, quality, model, target duration (up to 10 min), style spec, and optional starting image or user-supplied story. A CoS-driven agent writes a scene-by-scene treatment, kicks off 1–10s segment renders one at a time (continuing from each prior segment's last frame or starting fresh from a new image), evaluates output thumbnails against the style spec via its own multimodal review, and self-perpetuates until the episode is complete. On completion the server auto-creates a video-timeline project and renders the final concat into a single mp4. All segments + the final cut are grouped in an auto-created media collection. New routes (`/api/creative-director/*`), data file (`data/creative-director-projects.json`), preset tables (`server/lib/creativeDirectorPresets.js`), agent prompts (`server/lib/creativeDirectorPrompts.js`), and UI tabs (Overview / Treatment / Segments / Runs).+- **Unified media job queue** (`server/services/mediaJobQueue/`) for image and video gen. Replaces the per-provider 409 BUSY error with a FIFO that accepts every submission immediately and returns `{ jobId, status: 'queued', position }`. A single worker drains serially (image and video share Metal/MLX runtime, so parallelism would OOM anyway). Persists to `data/media-jobs.json`; on boot any job stuck in `running` is reclassified `failed (interrupted by restart)`. SSE on `/api/{video,image}-gen/:jobId/events` covers the full `queued → started → progress → complete/failed` lifecycle so existing UIs keep working without changes. New `/api/media-jobs` lets the UI inspect and cancel queued/running renders.- **Media model registry at `data/media-models.json`** — single source of truth for video and image model definitions, the LTX text encoder, and per-platform defaults. Replaces hardcoded model catalogs in `videoGen/local.js`, `imageGen/local.js`, and `imageVideoModels.js`. Seeded automatically on first run; edit + restart the server to swap models. New `gemma-bf16` (now default, best output quality), `gemma-qat-4bit` (auto-detected if LM Studio installed it), and `gemma-4bit` text-encoder options. Loader resolves `~/...` and prefers a local `localPath` when it exists.- **`+faststart` mp4 post-processing** — every video render is remuxed (no re-encoding, ~hundreds of ms) to move the moov atom to the front of the file. Gallery tiles with `preload="metadata"` now render their poster frame on page load instead of flashing black until clicked.- **`caffeinate -i -w <pid>`** spawned alongside the LTX Python child on macOS so a 90s+ render isn't aborted by display/system sleep on a laptop. `-w` makes it self-exit when our pid does — no manual lifecycle management.@@ -23,6 +24,11 @@## Fixed+- **Creative Director stuck projects now self-recover** — `completionHook` always re-evaluates project state after any CD task completes (regardless of task kind), so legacy `scene`-kind tasks from before the treatment/evaluate split no longer leave a project frozen. PATCHing a scene to a terminal status (`accepted` or `failed`) also nudges the orchestrator to start the next scene immediately.+- **Creative Director projects auto-resume on server restart.** New `recoverInFlightProjects()` runs at boot (after `initMediaJobQueue` reclassifies running jobs as `failed (interrupted by restart)`): for every project in `planning`/`rendering`/`stitching`, it resets any scenes stuck in `rendering` or `evaluating` (whose in-memory listeners died with the previous process) back to `pending` and fires `advanceAfterSceneSettled` so the orchestrator picks up where it left off. Without this, a pm2 reload mid-render left the project frozen — scene status pointed at a dead job, no listener to advance.+- **Creative Director smoke-test fixture** — `POST /api/creative-director/smoke-test` (or the "Run smoke test" button on the CD list page) creates a deterministic 3-scene colored-ball project: scene 1 generates a red ball bouncing on white (text-to-video), scene 2 continues from scene 1's last frame with a "blue ball" prompt to verify the i2v honors a prompt-driven color change while preserving motion, scene 3 continues from scene 2 with the same prompt to verify pure i2v continuity. The fixture sets `disableAudio: true` (skips the mlx_video audio pass to roughly halve wall-clock per scene) and `autoAcceptScenes: true` (sceneRunner short-circuits the cognitive evaluator with a synthetic `accepted` evaluation, so a smoke run completes in render time only — no Claude in the loop). Adds `disableAudio` and `autoAcceptScenes` as CD project fields and plumbs them through to the queue params.+- **Creative Director scene-retry path unblocked.** `creativeDirectorSceneUpdateSchema` previously stripped `pending` from the agent-callable status enum, but the evaluator-agent prompt template (`creativeDirectorPrompts.js`) and `advanceAfterSceneSettled` (`completionHook.js`) both depend on the agent flipping a scene back to `pending` (with a refined prompt and bumped `retryCount`) to request a re-render. The validation rejected every retry PATCH with `Invalid enum value` and stranded scenes in `evaluating` forever. Schema now accepts the full `SCENE_STATUSES` set and the misleading "agents shouldn't be allowed to flip back to pending" comment is corrected.+- **Image-to-video on macOS now actually preserves the source image as the first frame.** Root cause: PortOS was on `mlx-video-with-audio` 0.1.33, which had a known bug where the VAE encoder failed to load for split-format unified models (LTX-2.3 distilled-Q4) and silently produced gray-fog conditioned frames. Pinned `>=0.1.35` in `scripts/setup-image-video.sh`. The setup script also installed the wrong PyPI package: `mlx_video` (a different unrelated "video loading utilities" package) instead of `mlx-video-with-audio` (the LTX generation backend). Both provide an `import mlx_video` module so the wrong install was silent. Verified end-to-end through the API: pixel-perfect first-frame preservation with coherent motion across all frames.- **FFLF last-frame conditioning silently produced no output.** PortOS was passing `numFrames - 1` (= 24 for 25 frames) as `--image-frame-idx`, but mlx_video expects a *latent* frame index — for LTX that's `floor((videoFrames - 1) / 8)`, max 3 for 25 frames. ffmpeg-conditioning shape check failed and the python child exited 0 with no output mp4. Now computes `lastLatentIdx` correctly.- **"Continue" / extract-last-frame produced phantom-success logs but no file**, leaving a broken image preview in Video Gen. Two compounded bugs: (1) `-sseof -0.1` was too narrow a seek window — for videos with audio (B-frames + AV mux), the last keyframe sits earlier than 100ms before EOF, so ffmpeg returned zero frames while sometimes still exiting 0. Widened to `-sseof -1.0` and added `-update 1`. (2) The success path resolved on exit-code without verifying the output file existed. Now requires `existsSync(framePath)` too.@@ -34,6 +40,7 @@- **`caffeinate` sleep-prevention is now strictly macOS-only.** Previous gate (`!IS_WIN`) would also fire on Linux and emit a pointless ENOENT every render. Tightened to `process.platform === 'darwin'`.- **`scripts/setup-image-video.sh` removes the wrong package before install.** The PyPI package `mlx_video` (unrelated video-loading utility) shadows the LTX backend's `import mlx_video` if previously installed. The script now `pip uninstall --yes mlx_video` before installing `mlx-video-with-audio>=0.1.35`, so upgraders aren't left in an ambiguous state.- **Form fields stay editable during a video render.** Previously every input was `disabled={generating}`, blocking the user from queueing a different config while a render was in flight. The queue worker captures payloads at enqueue time, so live editing is safe.+- **"Add to collection" popover on media cards no longer gets clipped at the card edge.** `MediaCard`'s outer wrapper had `overflow-hidden` (to clip the image into the card's `rounded-xl`), which was creating a clipping context that swallowed the `AddToCollectionMenu` popover regardless of its `z-index`. Moved the corner-clipping onto the image button itself (`rounded-t-xl overflow-hidden`) so the outer card no longer clips its absolutely-positioned children.- **Morse Send drill** no longer reveals the answer or competes with itself for spacebar input: the morse pattern under each prompt is gone (the reference tabs on the right are still available for hints), the global spacebar keying listener only attaches in Send mode (so it doesn't fire on the trainer landing page or during Copy drills), the side widget's "Practice Key" panel is hidden outside Send mode and no longer duplicates the live decoded letter, and the "Your sending" box starts blank with a "waiting for your first key…" hint instead of a misleading "—" placeholder.- **CoS agents now reliably open PRs and request Copilot reviews when configured.** Previously, when both `openPR` and `reviewLoop` were enabled on a task, the worktree-cleanup logic's gate (`taskOpenPR && !taskReviewLoop`) skipped PR creation — falling through to auto-merge the agent's branch into main with no PR, no review, and contradictory wording in the agent prompt about whether it should open the PR itself. The cleanup now always opens the PR when `openPR` is set; when `reviewLoop` is also set, it requests a Copilot review on the new PR via the new `git.requestCopilotReview()` helper. The agent prompt is updated to consistently tell the agent the system handles PR creation and review requests.diff --git a/client/src/App.jsx b/client/src/App.jsxindex d75ae2be19..d641f21548 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -54,6 +54,9 @@ const MediaCollectionDetail = lazyWithReload(() => import('./pages/MediaCollecticonst MediaModels = lazyWithReload(() => import('./pages/MediaModels'));const VideoTimeline = lazyWithReload(() => import('./pages/VideoTimeline'));const VideoTimelineEditor = lazyWithReload(() => import('./pages/VideoTimelineEditor'));+const CreativeDirector = lazyWithReload(() => import('./pages/CreativeDirector'));+const CreativeDirectorDetail = lazyWithReload(() => import('./pages/CreativeDirectorDetail'));+const RenderQueue = lazyWithReload(() => import('./pages/RenderQueue'));const CreateApp = lazyWithReload(() => import('./pages/CreateApp'));const Templates = lazyWithReload(() => import('./pages/Templates'));const PromptManager = lazyWithReload(() => import('./pages/PromptManager'));@@ -191,6 +194,10 @@ export default function App() {<Route path="history" element={<MediaHistory />} /><Route path="collections" element={<MediaCollections />} /><Route path="collections/:id" element={<MediaCollectionDetail />} />+ <Route path="creative-director" element={<CreativeDirector />} />+ <Route path="creative-director/:id" element={<Navigate to="overview" replace />} />+ <Route path="creative-director/:id/:tab" element={<CreativeDirectorDetail />} />+ <Route path="queue" element={<RenderQueue />} /><Route path="timeline" element={<VideoTimeline />} /><Route path="timeline/:projectId" element={<VideoTimelineEditor />} /><Route path="models" element={<MediaModels />} />diff --git a/client/src/components/creative-director/ActiveAgentsBanner.jsx b/client/src/components/creative-director/ActiveAgentsBanner.jsxnew file mode 100644index 0000000000..09c0341f23--- /dev/null+++ b/client/src/components/creative-director/ActiveAgentsBanner.jsx@@ -0,0 +1,49 @@+import { Link } from 'react-router-dom';+import { Bot, ExternalLink } from 'lucide-react';++/**+ * Banner shown at the top of the project detail page whenever there are+ * CoS agents running for this project. The parent (CreativeDirectorDetail)+ * polls /api/cos/agents and passes the filtered list down — keeping the+ * fetch in one place so the banner and SegmentsTab share state.+ */+export default function ActiveAgentsBanner({ agents }) {+ if (!agents?.length) return null;++ return (+ <div className="mb-4 bg-port-card border border-port-accent/40 rounded p-3 flex items-start justify-between gap-3">+ <div className="flex items-start gap-2 min-w-0">+ <Bot className="w-4 h-4 text-port-accent shrink-0 mt-0.5" />+ <div className="min-w-0">+ <div className="text-sm">+ <span className="font-medium text-port-accent">{agents.length} agent{agents.length === 1 ? '' : 's'} running</span>+ <span className="text-port-text-muted"> for this project</span>+ </div>+ <div className="text-xs text-port-text-muted truncate mt-0.5 font-mono">+ {agents.map((a) => `${a.id?.slice(0, 14) || 'agent'} · ${extractKind(a.taskId)}`).join(' • ')}+ </div>+ </div>+ </div>+ <Link+ to="/cos/agents"+ className="shrink-0 inline-flex items-center gap-1 text-xs text-port-accent hover:underline whitespace-nowrap"+ >+ Live progress <ExternalLink className="w-3 h-3" />+ </Link>+ </div>+ );+}++// Pull the task kind (treatment / evaluate) out of the+// cd-<projectId>-<kind>-<ts> task id. Project UUIDs contain hex segments,+// so a token-includes match is more reliable than counting separators.+// Only `treatment` and `evaluate` reach the CoS task queue today; scene+// rendering and final stitching run server-side and never appear here.+export function extractKind(taskId) {+ if (!taskId) return 'task';+ const parts = taskId.split('-');+ for (const k of ['treatment', 'evaluate']) {+ if (parts.includes(k)) return k;+ }+ return 'task';+}diff --git a/client/src/components/creative-director/OverviewTab.jsx b/client/src/components/creative-director/OverviewTab.jsxnew file mode 100644index 0000000000..6721efaa52--- /dev/null+++ b/client/src/components/creative-director/OverviewTab.jsx@@ -0,0 +1,56 @@+import { Link } from 'react-router-dom';++export default function OverviewTab({ project }) {+ const collectionLink = `/media/collections/${project.collectionId}`;+ const final = project.finalVideoId+ ? <Link to={`/media/history?selected=${project.finalVideoId}`} className="text-port-accent">{project.finalVideoId}</Link>+ : <span className="text-port-text-muted">not yet rendered</span>;++ return (+ <div className="space-y-4 max-w-3xl">+ <section className="bg-port-card border border-port-border rounded p-4 space-y-2">+ <h2 className="text-sm font-semibold text-port-text-muted uppercase tracking-wide">Configuration</h2>+ <Field label="Aspect ratio" value={project.aspectRatio} />+ <Field label="Quality" value={project.quality} />+ <Field label="Model" value={project.modelId} />+ <Field label="Target duration" value={`${project.targetDurationSeconds}s (~${Math.round(project.targetDurationSeconds / 60)} min)`} />+ <Field label="Starting image" value={project.startingImageFile || '—'} />+ <Field label="Collection" value={<Link to={collectionLink} className="text-port-accent">{project.collectionId}</Link>} />+ <Field label="Final video" value={final} />+ {project.timelineProjectId && (+ <Field label="Timeline" value={<Link to={`/media/timeline/${project.timelineProjectId}`} className="text-port-accent">{project.timelineProjectId}</Link>} />+ )}+ </section>++ {project.styleSpec && (+ <section className="bg-port-card border border-port-border rounded p-4">+ <h2 className="text-sm font-semibold text-port-text-muted uppercase tracking-wide mb-2">Style spec</h2>+ <pre className="whitespace-pre-wrap text-sm text-port-text font-mono">{project.styleSpec}</pre>+ </section>+ )}++ {project.userStory && (+ <section className="bg-port-card border border-port-border rounded p-4">+ <h2 className="text-sm font-semibold text-port-text-muted uppercase tracking-wide mb-2">User-supplied story</h2>+ <pre className="whitespace-pre-wrap text-sm text-port-text font-mono">{project.userStory}</pre>+ </section>+ )}++ {project.failureReason && (+ <section className="bg-port-card border border-port-error rounded p-4">+ <h2 className="text-sm font-semibold text-port-error uppercase tracking-wide mb-2">Failure reason</h2>+ <p className="text-sm text-port-text break-all">{project.failureReason}</p>+ </section>+ )}+ </div>+ );+}++function Field({ label, value }) {+ return (+ <div className="grid grid-cols-3 gap-2 text-sm">+ <div className="text-port-text-muted">{label}</div>+ <div className="col-span-2 text-port-text break-all">{value}</div>+ </div>+ );+}diff --git a/client/src/components/creative-director/RunsTab.jsx b/client/src/components/creative-director/RunsTab.jsxnew file mode 100644index 0000000000..41e290841d--- /dev/null+++ b/client/src/components/creative-director/RunsTab.jsx@@ -0,0 +1,44 @@+import { Link } from 'react-router-dom';++const STATUS_BADGE = {+ running: 'bg-port-accent/30 text-port-accent',+ completed: 'bg-port-success/30 text-port-success',+ failed: 'bg-port-error/30 text-port-error',+};++export default function RunsTab({ project }) {+ const runs = project.runs || [];+ if (!runs.length) {+ return <div className="text-port-text-muted text-sm">No runs yet — start the project to spawn the first agent task.</div>;+ }+ const sorted = runs.slice().sort((a, b) => new Date(b.startedAt || 0) - new Date(a.startedAt || 0));+ return (+ <div className="space-y-2 max-w-4xl">+ {sorted.map((r) => (+ <div key={r.runId} className="bg-port-card border border-port-border rounded p-3 text-sm">+ <div className="flex items-center justify-between gap-2">+ <div className="font-medium">+ {r.kind} {r.sceneId ? `· ${r.sceneId}` : ''}+ </div>+ <span className={`text-xs px-2 py-0.5 rounded ${STATUS_BADGE[r.status] || ''}`}>{r.status}</span>+ </div>+ <div className="text-xs text-port-text-muted mt-1">+ {r.startedAt && new Date(r.startedAt).toLocaleString()}+ {r.completedAt && ` → ${new Date(r.completedAt).toLocaleString()}`}+ </div>+ {r.taskId && (+ <div className="text-xs text-port-text-muted mt-1">+ Task: <span className="font-mono">{r.taskId}</span>+ </div>+ )}+ {r.agentId && (+ <div className="text-xs text-port-text-muted">+ Agent: <Link to={`/cos/agents?id=${encodeURIComponent(r.agentId)}`} className="text-port-accent font-mono">{r.agentId.slice(0, 8)}…</Link>+ </div>+ )}+ {r.error && <div className="text-xs text-port-error mt-1">{r.error}</div>}+ </div>+ ))}+ </div>+ );+}diff --git a/client/src/components/creative-director/SegmentsTab.jsx b/client/src/components/creative-director/SegmentsTab.jsxnew file mode 100644index 0000000000..6a9b8084a8--- /dev/null+++ b/client/src/components/creative-director/SegmentsTab.jsx@@ -0,0 +1,108 @@+import { Link } from 'react-router-dom';+import { Bot } from 'lucide-react';+import { extractKind } from './ActiveAgentsBanner.jsx';++const STATUS_BADGE = {+ pending: 'bg-port-border text-port-text-muted',+ rendering: 'bg-port-accent/30 text-port-accent',+ evaluating: 'bg-port-warning/30 text-port-warning',+ accepted: 'bg-port-success/30 text-port-success',+ failed: 'bg-port-error/30 text-port-error',+};++export default function SegmentsTab({ project, activeAgents = [] }) {+ const scenes = project.treatment?.scenes;+ if (!scenes?.length) {+ return <div className="text-port-text-muted text-sm">No scenes yet — the treatment hasn't been generated.</div>;+ }+ const sorted = scenes.slice().sort((a, b) => a.order - b.order);++ // Scene rendering runs server-side now (no `scene` CoS task), so the only+ // CD agent we'd see attached to a specific scene is `evaluate` — it reads+ // the rendered thumbnail and judges it against the project's style spec.+ // Use the explicit sceneId from the agent's task metadata (set by+ // agentBridge#enqueueEvaluateTask) when available — that pins the active+ // agent to the exact scene being judged. Fall back to the orchestrator's+ // "next non-terminal scene" guess only when metadata is missing.+ const sceneAgents = activeAgents.filter((a) => extractKind(a.taskId) === 'evaluate');+ const inflightScene = sorted.find((s) => s.status === 'pending' || s.status === 'rendering' || s.status === 'evaluating');+ const agentSceneIds = new Set(+ sceneAgents+ .map((a) => a.task?.metadata?.creativeDirector?.sceneId)+ .filter(Boolean),+ );+ const fallbackInflightSceneId = sceneAgents.length ? inflightScene?.sceneId : null;+ const isSceneInflight = (sceneId) =>+ agentSceneIds.has(sceneId) || (agentSceneIds.size === 0 && sceneId === fallbackInflightSceneId);+ // Pick out only the agents whose task metadata names this exact scene.+ // Without this filter the row would render every evaluate agent in the+ // project — confusing if multiple evaluates run concurrently or if an+ // earlier agent's metadata is stale. When metadata is missing for all+ // agents (older runs / queued pre-spawn), fall back to the orchestrator's+ // single inflight guess so the row still shows *something*.+ const agentsForScene = (sceneId) => {+ const tagged = sceneAgents.filter((a) => a.task?.metadata?.creativeDirector?.sceneId === sceneId);+ if (tagged.length) return tagged;+ if (agentSceneIds.size === 0 && sceneId === fallbackInflightSceneId) return sceneAgents;+ return [];+ };++ return (+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">+ {sorted.map((s) => {+ const isInflight = isSceneInflight(s.sceneId);+ const decoratedStatus = isInflight && s.status === 'pending' ? 'rendering' : s.status;+ return (+ <div key={s.sceneId} className={`bg-port-card border rounded overflow-hidden ${isInflight ? 'border-port-accent/60' : 'border-port-border'}`}>+ {s.renderedJobId ? (+ <a href={`/data/videos/${s.renderedJobId}.mp4`} target="_blank" rel="noopener noreferrer" className="block bg-port-bg aspect-video">+ <img+ src={`/data/video-thumbnails/${s.renderedJobId}.jpg`}+ alt={`Scene ${s.order + 1}`}+ className="w-full h-full object-cover"+ onError={(e) => { e.currentTarget.style.display = 'none'; }}+ />+ </a>+ ) : (+ <div className="bg-port-bg aspect-video flex items-center justify-center text-port-text-muted text-xs">+ {isInflight ? (+ <span className="text-port-accent flex items-center gap-1">+ <Bot className="w-3 h-3 animate-pulse" /> agent working…+ </span>+ ) : decoratedStatus === 'rendering' || decoratedStatus === 'evaluating' ? 'rendering…' : 'no render yet'}+ </div>+ )}+ <div className="p-2 space-y-1">+ <div className="flex items-center justify-between gap-2">+ <div className="text-sm font-medium">Scene {s.order + 1}</div>+ <span className={`text-xs px-2 py-0.5 rounded ${STATUS_BADGE[decoratedStatus] || ''}`}>{decoratedStatus}</span>+ </div>+ <div className="text-xs text-port-text-muted truncate" title={s.intent}>{s.intent}</div>+ <div className="text-xs text-port-text-muted">+ {s.durationSeconds}s • retries: {s.retryCount || 0}+ </div>+ {isInflight && (() => {+ const myAgents = agentsForScene(s.sceneId);+ if (!myAgents.length) return null;+ return (+ <div className="text-xs text-port-accent font-mono mt-1 flex flex-wrap gap-x-2">+ {myAgents.map((a) => (+ <Link key={a.id} to={`/cos/agents?id=${encodeURIComponent(a.id)}`} className="hover:underline">+ {a.id?.slice(0, 14) || 'agent'}+ </Link>+ ))}+ </div>+ );+ })()}+ {s.evaluation?.notes && (+ <div className="text-xs text-port-text-muted italic truncate" title={s.evaluation.notes}>+ {s.evaluation.notes}+ </div>+ )}+ </div>+ </div>+ );+ })}+ </div>+ );+}diff --git a/client/src/components/creative-director/TreatmentTab.jsx b/client/src/components/creative-director/TreatmentTab.jsxnew file mode 100644index 0000000000..87d2f0b396--- /dev/null+++ b/client/src/components/creative-director/TreatmentTab.jsx@@ -0,0 +1,51 @@+export default function TreatmentTab({ project }) {+ const t = project.treatment;+ if (!t) {+ return (+ <div className="text-port-text-muted text-sm max-w-2xl">+ No treatment yet. The agent will write one when you start the project.+ Once written, scenes appear here read-only — regenerating the+ treatment is a future enhancement.+ </div>+ );+ }+ return (+ <div className="space-y-4 max-w-4xl">+ <section className="bg-port-card border border-port-border rounded p-4 space-y-2">+ <div>+ <div className="text-xs uppercase tracking-wide text-port-text-muted">Logline</div>+ <div className="text-sm">{t.logline}</div>+ </div>+ <div>+ <div className="text-xs uppercase tracking-wide text-port-text-muted">Synopsis</div>+ <div className="text-sm whitespace-pre-wrap">{t.synopsis}</div>+ </div>+ </section>++ <section className="space-y-2">+ <h2 className="text-sm font-semibold text-port-text-muted uppercase tracking-wide">+ Scenes ({t.scenes.length})+ </h2>+ {t.scenes+ .slice()+ .sort((a, b) => a.order - b.order)+ .map((s) => (+ <div key={s.sceneId} className="bg-port-card border border-port-border rounded p-3 text-sm">+ <div className="flex items-center justify-between gap-2">+ <div className="font-medium">+ Scene {s.order + 1}: {s.intent}+ </div>+ <span className="text-xs text-port-text-muted">+ {s.durationSeconds}s {s.useContinuationFromPrior ? '· continues' : s.sourceImageFile ? '· from image' : '· text-to-video'}+ </span>+ </div>+ <pre className="whitespace-pre-wrap text-xs text-port-text-muted font-mono mt-2">{s.prompt}</pre>+ {s.negativePrompt && (+ <pre className="whitespace-pre-wrap text-xs text-port-error/70 font-mono mt-1">neg: {s.negativePrompt}</pre>+ )}+ </div>+ ))}+ </section>+ </div>+ );+}diff --git a/client/src/components/media/MediaCard.jsx b/client/src/components/media/MediaCard.jsxindex eee1e99064..1439f6892b 100644--- a/client/src/components/media/MediaCard.jsx+++ b/client/src/components/media/MediaCard.jsx@@ -26,12 +26,12 @@ export default function MediaCard({const handleTileClick = onClick || (() => onPreview?.(item));return (- <div className={`bg-port-card border rounded-xl overflow-hidden ${selected ? 'border-port-accent' : 'border-port-border'}`}>+ <div className={`bg-port-card border rounded-xl ${selected ? 'border-port-accent' : 'border-port-border'}`}><buttontype="button"onClick={() => handleTileClick(item)}disabled={disabled}- className="block w-full aspect-square bg-port-bg relative disabled:cursor-not-allowed disabled:opacity-40"+ className="block w-full aspect-square bg-port-bg relative rounded-t-xl overflow-hidden disabled:cursor-not-allowed disabled:opacity-40">{previewUrl ? (<img src={previewUrl} alt={prompt} className="w-full h-full object-cover" loading="lazy" />diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsxindex 04a01a129e..e6eced6faf 100644--- a/client/src/components/settings/ImageGenTab.jsx+++ b/client/src/components/settings/ImageGenTab.jsx@@ -226,6 +226,9 @@ export function ImageGenTab() {} else if (msg.type === 'error') {closeEs();reject(new Error(msg.error || 'Generation failed'));+ } else if (msg.type === 'canceled') {+ closeEs();+ reject(new Error(msg.reason || 'Canceled'));}};es.onerror = () => { closeEs(); reject(new Error('Lost connection during test render')); };diff --git a/client/src/pages/CreativeDirector.jsx b/client/src/pages/CreativeDirector.jsxnew file mode 100644index 0000000000..baebb924a3--- /dev/null+++ b/client/src/pages/CreativeDirector.jsx@@ -0,0 +1,306 @@+import { useEffect, useState, useCallback } from 'react';+import { Link } from 'react-router-dom';+import { Plus, Film, Trash2, Play, Pause, FlaskConical } from 'lucide-react';+import toast from '../components/ui/Toast';+import {+ listCreativeDirectorProjects,+ createCreativeDirectorProject,+ createSmokeTestCreativeDirectorProject,+ deleteCreativeDirectorProject,+ startCreativeDirectorProject,+ pauseCreativeDirectorProject,+} from '../services/apiCreativeDirector.js';+import { listVideoModels } from '../services/apiImageVideo.js';++const ASPECT_RATIOS = ['16:9', '9:16', '1:1'];+const QUALITIES = ['draft', 'standard', 'high'];++const STATUS_COLORS = {+ draft: 'bg-port-border text-port-text',+ planning: 'bg-port-accent/30 text-port-accent',+ rendering: 'bg-port-accent/30 text-port-accent',+ stitching: 'bg-port-warning/30 text-port-warning',+ complete: 'bg-port-success/30 text-port-success',+ paused: 'bg-port-warning/30 text-port-warning',+ failed: 'bg-port-error/30 text-port-error',+};++export default function CreativeDirector() {+ const [projects, setProjects] = useState([]);+ const [loading, setLoading] = useState(true);+ const [showForm, setShowForm] = useState(false);+ const [models, setModels] = useState([]);+ const [form, setForm] = useState({+ name: '',+ aspectRatio: '16:9',+ quality: 'standard',+ modelId: '',+ targetDurationSeconds: 60,+ styleSpec: '',+ userStory: '',+ startingImageFile: '',+ });++ const fetchProjects = useCallback(() => {+ listCreativeDirectorProjects()+ .then((data) => { setProjects(data || []); setLoading(false); })+ .catch(() => setLoading(false));+ }, []);++ useEffect(() => {+ fetchProjects();+ listVideoModels().then((m) => {+ setModels(m || []);+ if (m?.length && !form.modelId) setForm((f) => ({ ...f, modelId: m[0].id }));+ }).catch(() => {});+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [fetchProjects]);++ const handleCreate = async (e) => {+ e.preventDefault();+ if (!form.name.trim() || !form.modelId) {+ toast.error('Name and model are required');+ return;+ }+ const payload = {+ name: form.name.trim(),+ aspectRatio: form.aspectRatio,+ quality: form.quality,+ modelId: form.modelId,+ targetDurationSeconds: Number(form.targetDurationSeconds),+ styleSpec: form.styleSpec,+ userStory: form.userStory || null,+ startingImageFile: form.startingImageFile || null,+ };+ try {+ const created = await createCreativeDirectorProject(payload);+ setProjects((prev) => [...prev, created]);+ setShowForm(false);+ setForm((f) => ({ ...f, name: '', styleSpec: '', userStory: '', startingImageFile: '' }));+ toast.success(`Created "${created.name}"`);+ } catch (err) {+ toast.error(err.message || 'Failed to create project');+ }+ };++ // Optimistic-update the row in place rather than refetching the whole list+ // (per CLAUDE.md "Reactive UI updates"). The detail page's poll picks up the+ // server's authoritative status within 5s if anything diverges.+ const handleStart = async (id) => {+ try {+ await startCreativeDirectorProject(id);+ setProjects((prev) => prev.map((p) => p.id === id ? { ...p, status: p.treatment ? 'rendering' : 'planning' } : p));+ toast.success('Pipeline started');+ } catch (err) {+ toast.error(err.message || 'Failed to start');+ }+ };++ const handlePause = async (id) => {+ try {+ await pauseCreativeDirectorProject(id);+ setProjects((prev) => prev.map((p) => p.id === id ? { ...p, status: 'paused' } : p));+ toast.success('Paused');+ } catch (err) {+ toast.error(err.message || 'Failed to pause');+ }+ };++ const handleDelete = async (id) => {+ // No confirmation modal yet — destructive but reversible if you re-create.+ // Future: inline two-click confirm pattern.+ try {+ await deleteCreativeDirectorProject(id);+ setProjects((prev) => prev.filter((p) => p.id !== id));+ toast.success('Deleted');+ } catch (err) {+ toast.error(err.message || 'Failed to delete');+ }+ };++ if (loading) {+ return <div className="p-6 text-port-text-muted">Loading projects…</div>;+ }++ return (+ <div className="flex flex-col h-full">+ <div className="shrink-0 px-6 pt-6 pb-4 border-b border-port-border">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-3">+ <Film className="w-6 h-6 text-port-accent" />+ <div>+ <h1 className="text-xl font-semibold">Creative Director</h1>+ <p className="text-sm text-port-text-muted">Long-form video projects driven by an autonomous CoS agent</p>+ </div>+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={async () => {+ const created = await createSmokeTestCreativeDirectorProject().catch((e) => {+ toast.error(e?.message || 'Smoke test failed to start');+ return null;+ });+ if (!created) return;+ toast.success('Smoke test project started');+ setProjects((prev) => [created, ...prev]);+ }}+ className="flex items-center gap-2 bg-port-card border border-port-border hover:bg-port-card/60 text-port-text px-3 py-2 rounded text-sm"+ title="Create + start a deterministic 3-scene colored-ball project (auto-accept, no audio)"+ >+ <FlaskConical className="w-4 h-4" />+ Run smoke test+ </button>+ <button+ onClick={() => setShowForm((s) => !s)}+ className="flex items-center gap-2 bg-port-accent hover:bg-port-accent/80 text-white px-3 py-2 rounded text-sm"+ >+ <Plus className="w-4 h-4" />+ New project+ </button>+ </div>+ </div>+ </div>++ {showForm && (+ <form onSubmit={handleCreate} className="shrink-0 p-6 border-b border-port-border bg-port-card/40 space-y-3">+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3">+ <label className="block text-sm">+ <span className="text-port-text-muted">Name</span>+ <input+ value={form.name}+ onChange={(e) => setForm({ ...form, name: e.target.value })}+ placeholder="My Episode"+ className="w-full mt-1 bg-port-bg border border-port-border rounded px-2 py-1 text-sm"+ maxLength={200}+ />+ </label>+ <label className="block text-sm">+ <span className="text-port-text-muted">Model</span>+ <select+ value={form.modelId}+ onChange={(e) => setForm({ ...form, modelId: e.target.value })}+ className="w-full mt-1 bg-port-bg border border-port-border rounded px-2 py-1 text-sm"+ >+ {models.map((m) => <option key={m.id} value={m.id}>{m.name || m.id}</option>)}+ </select>+ </label>+ <label className="block text-sm">+ <span className="text-port-text-muted">Aspect ratio</span>+ <select+ value={form.aspectRatio}+ onChange={(e) => setForm({ ...form, aspectRatio: e.target.value })}+ className="w-full mt-1 bg-port-bg border border-port-border rounded px-2 py-1 text-sm"+ >+ {ASPECT_RATIOS.map((r) => <option key={r} value={r}>{r}</option>)}+ </select>+ </label>+ <label className="block text-sm">+ <span className="text-port-text-muted">Quality</span>+ <select+ value={form.quality}+ onChange={(e) => setForm({ ...form, quality: e.target.value })}+ className="w-full mt-1 bg-port-bg border border-port-border rounded px-2 py-1 text-sm"+ >+ {QUALITIES.map((q) => <option key={q} value={q}>{q}</option>)}+ </select>+ </label>+ <label className="block text-sm">+ <span className="text-port-text-muted">Target duration (seconds, max 600)</span>+ <input+ type="number"+ min={5}+ max={600}+ value={form.targetDurationSeconds}+ onChange={(e) => setForm({ ...form, targetDurationSeconds: e.target.value })}+ className="w-full mt-1 bg-port-bg border border-port-border rounded px-2 py-1 text-sm"+ />+ </label>+ <label className="block text-sm">+ <span className="text-port-text-muted">Starting image filename (optional)</span>+ <input+ value={form.startingImageFile}+ onChange={(e) => setForm({ ...form, startingImageFile: e.target.value })}+ placeholder="my-image.png (basename in /data/images)"+ className="w-full mt-1 bg-port-bg border border-port-border rounded px-2 py-1 text-sm"+ maxLength={256}+ />+ </label>+ </div>+ <label className="block text-sm">+ <span className="text-port-text-muted">Style spec</span>+ <textarea+ value={form.styleSpec}+ onChange={(e) => setForm({ ...form, styleSpec: e.target.value })}+ placeholder="Cinematic, painterly, warm color palette, slow camera dolly…"+ className="w-full mt-1 bg-port-bg border border-port-border rounded px-2 py-1 text-sm h-24 font-mono"+ maxLength={5000}+ />+ </label>+ <label className="block text-sm">+ <span className="text-port-text-muted">User-supplied story (optional — leave blank to let the agent invent one)</span>+ <textarea+ value={form.userStory}+ onChange={(e) => setForm({ ...form, userStory: e.target.value })}+ placeholder="Open on a foggy mountain. A traveler descends into the valley below…"+ className="w-full mt-1 bg-port-bg border border-port-border rounded px-2 py-1 text-sm h-24 font-mono"+ maxLength={10000}+ />+ </label>+ <div className="flex gap-2">+ <button type="submit" className="bg-port-accent hover:bg-port-accent/80 text-white px-3 py-1.5 rounded text-sm">+ Create+ </button>+ <button type="button" onClick={() => setShowForm(false)} className="bg-port-card border border-port-border px-3 py-1.5 rounded text-sm">+ Cancel+ </button>+ </div>+ </form>+ )}++ <div className="flex-1 overflow-auto p-6">+ {projects.length === 0 && !showForm && (+ <div className="text-port-text-muted text-sm">+ No projects yet. Click <span className="text-port-text">New project</span> to start one.+ </div>+ )}+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">+ {projects.map((p) => (+ <div key={p.id} className="bg-port-card border border-port-border rounded p-3 flex flex-col gap-2">+ <div className="flex items-start justify-between gap-2">+ <Link to={`/media/creative-director/${p.id}/overview`} className="flex-1 min-w-0">+ <div className="font-medium truncate">{p.name}</div>+ <div className="text-xs text-port-text-muted truncate">{p.id}</div>+ </Link>+ <span className={`text-xs px-2 py-0.5 rounded ${STATUS_COLORS[p.status] || ''}`}>{p.status}</span>+ </div>+ <div className="text-xs text-port-text-muted">+ {p.aspectRatio} • {p.quality} • {p.modelId} • {p.targetDurationSeconds}s target+ </div>+ <div className="text-xs text-port-text-muted">+ {p.treatment?.scenes?.length ? `${p.treatment.scenes.filter((s) => s.status === 'accepted').length}/${p.treatment.scenes.length} scenes accepted` : 'No treatment yet'}+ </div>+ <div className="flex gap-1 mt-1">+ {/* Pause is meaningful only when the agent could be in flight.+ `draft` has nothing running yet, and the terminal states are+ obviously inert — match the detail page's gating. */}+ {!['paused', 'complete', 'failed', 'draft'].includes(p.status) && (+ <button onClick={() => handlePause(p.id)} className="flex items-center gap-1 px-2 py-1 bg-port-bg border border-port-border rounded text-xs">+ <Pause className="w-3 h-3" /> Pause+ </button>+ )}+ {(p.status === 'paused' || p.status === 'draft' || p.status === 'failed') && (+ <button onClick={() => handleStart(p.id)} className="flex items-center gap-1 px-2 py-1 bg-port-accent/30 text-port-accent rounded text-xs">+ <Play className="w-3 h-3" /> Start+ </button>+ )}+ <button onClick={() => handleDelete(p.id)} className="ml-auto flex items-center gap-1 px-2 py-1 bg-port-bg border border-port-border rounded text-xs hover:bg-port-error/20 hover:text-port-error">+ <Trash2 className="w-3 h-3" />+ </button>+ </div>+ </div>+ ))}+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/pages/CreativeDirectorDetail.jsx b/client/src/pages/CreativeDirectorDetail.jsxnew file mode 100644index 0000000000..7b6ed545a6--- /dev/null+++ b/client/src/pages/CreativeDirectorDetail.jsx@@ -0,0 +1,158 @@+import { useEffect, useState, useCallback } from 'react';+import { useParams, useNavigate, Link } from 'react-router-dom';+import { ArrowLeft, Play, Pause, RefreshCw } from 'lucide-react';+import toast from '../components/ui/Toast';+import {+ getCreativeDirectorProject,+ startCreativeDirectorProject,+ pauseCreativeDirectorProject,+ resumeCreativeDirectorProject,+} from '../services/apiCreativeDirector.js';+import OverviewTab from '../components/creative-director/OverviewTab.jsx';+import TreatmentTab from '../components/creative-director/TreatmentTab.jsx';+import SegmentsTab from '../components/creative-director/SegmentsTab.jsx';+import RunsTab from '../components/creative-director/RunsTab.jsx';+import ActiveAgentsBanner from '../components/creative-director/ActiveAgentsBanner.jsx';+import { getCosAgents } from '../services/apiAgents.js';++const TABS = [+ { id: 'overview', label: 'Overview' },+ { id: 'treatment', label: 'Treatment' },+ { id: 'segments', label: 'Segments' },+ { id: 'runs', label: 'Runs' },+];++const VALID_TAB_IDS = new Set(TABS.map((t) => t.id));++export default function CreativeDirectorDetail() {+ const { id, tab } = useParams();+ const navigate = useNavigate();+ const activeTab = VALID_TAB_IDS.has(tab) ? tab : 'overview';+ const [project, setProject] = useState(null);+ const [loading, setLoading] = useState(true);+ const [activeAgents, setActiveAgents] = useState([]);++ const fetchProject = useCallback(() => {+ getCreativeDirectorProject(id)+ .then((p) => { setProject(p); setLoading(false); })+ .catch(() => { setProject(null); setLoading(false); });+ }, [id]);++ // Reset state ONLY when the route id changes, so navigating between+ // projects (or hitting an error fetch) clears the prior project — but+ // the 5s poll interval below doesn't keep nulling-and-re-setting the+ // same project (which previously coupled with the `project?.status`+ // dep on the polling effect to produce a tight refetch loop).+ useEffect(() => {+ setLoading(true);+ setProject(null);+ }, [id]);++ // Poll CoS agents in parallel so the Segments tab can flag the scene that's+ // currently being worked on, even before the agent PATCHes its status.+ // Filter by `taskId` prefix `cd-<projectId>-` (agentBridge's id scheme).+ const fetchAgents = useCallback(() => {+ getCosAgents()+ .then((data) => {+ const prefix = `cd-${id}-`;+ const mine = (data || []).filter((a) => a.status === 'running' && (a.taskId || '').startsWith(prefix));+ setActiveAgents(mine);+ })+ .catch(() => setActiveAgents([]));+ }, [id]);++ useEffect(() => {+ fetchProject();+ fetchAgents();+ // Only poll while the agent could still mutate the project. Once the+ // status reaches a terminal state, skip the interval entirely so we're+ // not constantly tearing down and rebuilding it on every refetch.+ const status = project?.status;+ if (status && ['complete', 'failed', 'paused', 'draft'].includes(status)) return;+ const interval = setInterval(() => { fetchProject(); fetchAgents(); }, 5000);+ return () => clearInterval(interval);+ }, [fetchProject, fetchAgents, project?.status]);++ const handleAction = async (kind) => {+ // Map action → past-tense label and optimistic status up-front.+ const successMessages = { start: 'Started', pause: 'Paused', resume: 'Resumed' };+ // Optimistic status: start kicks off planning or rendering depending on+ // whether a treatment exists; the 5s poll will correct it if the server+ // resolves to a different status (e.g. planning → rendering).+ const optimisticStatus = kind === 'pause' ? 'paused'+ : kind === 'resume' ? (project?.treatment ? 'rendering' : 'planning')+ : kind === 'start' ? (project?.treatment ? 'rendering' : 'planning')+ : null;+ try {+ if (kind === 'start') await startCreativeDirectorProject(id);+ else if (kind === 'pause') await pauseCreativeDirectorProject(id);+ else if (kind === 'resume') await resumeCreativeDirectorProject(id);+ toast.success(successMessages[kind] || kind);+ if (optimisticStatus) setProject((p) => p ? { ...p, status: optimisticStatus } : p);+ } catch (err) {+ toast.error(err.message || `Failed to ${kind}`);+ }+ };++ if (loading) return <div className="p-6 text-port-text-muted">Loading…</div>;+ if (!project) return <div className="p-6 text-port-error">Project not found.</div>;++ const goTo = (tabId) => navigate(`/media/creative-director/${id}/${tabId}`);++ return (+ <div className="flex flex-col h-full">+ <div className="shrink-0 px-6 pt-6 pb-3 border-b border-port-border">+ <div className="flex items-center justify-between gap-3">+ <div className="flex items-center gap-3 min-w-0">+ <Link to="/media/creative-director" className="text-port-text-muted hover:text-port-text"><ArrowLeft className="w-4 h-4" /></Link>+ <div className="min-w-0">+ <h1 className="text-xl font-semibold truncate">{project.name}</h1>+ <div className="text-xs text-port-text-muted truncate">+ {project.id} • status: <span className="text-port-text">{project.status}</span>+ </div>+ </div>+ </div>+ <div className="flex gap-1">+ <button onClick={fetchProject} className="flex items-center gap-1 px-2 py-1 bg-port-card border border-port-border rounded text-xs">+ <RefreshCw className="w-3 h-3" /> Refresh+ </button>+ {(project.status === 'draft' || project.status === 'failed') && (+ <button onClick={() => handleAction('start')} className="flex items-center gap-1 px-2 py-1 bg-port-accent/30 text-port-accent rounded text-xs">+ <Play className="w-3 h-3" /> Start+ </button>+ )}+ {project.status === 'paused' && (+ <button onClick={() => handleAction('resume')} className="flex items-center gap-1 px-2 py-1 bg-port-accent/30 text-port-accent rounded text-xs">+ <Play className="w-3 h-3" /> Resume+ </button>+ )}+ {!['paused', 'complete', 'failed', 'draft'].includes(project.status) && (+ <button onClick={() => handleAction('pause')} className="flex items-center gap-1 px-2 py-1 bg-port-card border border-port-border rounded text-xs">+ <Pause className="w-3 h-3" /> Pause+ </button>+ )}+ </div>+ </div>+ <div className="flex gap-1 mt-3">+ {TABS.map((t) => (+ <button+ key={t.id}+ onClick={() => goTo(t.id)}+ className={`px-3 py-1.5 text-sm rounded ${activeTab === t.id ? 'bg-port-accent/30 text-port-accent' : 'text-port-text-muted hover:text-port-text'}`}+ >+ {t.label}+ </button>+ ))}+ </div>+ </div>++ <div className="flex-1 overflow-auto p-6">+ <ActiveAgentsBanner agents={activeAgents} />+ {activeTab === 'overview' && <OverviewTab project={project} />}+ {activeTab === 'treatment' && <TreatmentTab project={project} />}+ {activeTab === 'segments' && <SegmentsTab project={project} activeAgents={activeAgents} />}+ {activeTab === 'runs' && <RunsTab project={project} />}+ </div>+ </div>+ );+}diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex 23a6fc1c13..4eace0daf2 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -196,7 +196,7 @@ export default function ImageGen() {if (!msg) return;if (msg.type === 'status') setStatusMsg(msg.message);if (msg.type === 'progress') setLocalProgress({ progress: msg.progress });- if (msg.type === 'complete' || msg.type === 'error') {+ if (msg.type === 'complete' || msg.type === 'error' || msg.type === 'canceled') {setGenerating(false);es.close();}@@ -390,6 +390,10 @@ export default function ImageGen() {es.close();reject(new Error(msg.error));}+ if (msg.type === 'canceled') {+ es.close();+ reject(new Error(msg.reason || 'Canceled'));+ }};es.onerror = () => {es.close();diff --git a/client/src/pages/MediaGen.jsx b/client/src/pages/MediaGen.jsxindex e6192b4596..1d2a29683c 100644--- a/client/src/pages/MediaGen.jsx+++ b/client/src/pages/MediaGen.jsx@@ -1,10 +1,12 @@import { useNavigate, useLocation, Outlet } from 'react-router-dom';-import { Layers, Image as ImageIcon, Film, History, HardDrive, Scissors, FolderOpen } from 'lucide-react';+import { Layers, Image as ImageIcon, Film, History, HardDrive, Scissors, FolderOpen, Clapperboard, ListOrdered } from 'lucide-react';const TABS = [{ id: 'image', label: 'Image', icon: ImageIcon },{ id: 'video', label: 'Video', icon: Film },{ id: 'timeline', label: 'Timeline', icon: Scissors },+ { id: 'creative-director', label: 'Creative Director', icon: Clapperboard },+ { id: 'queue', label: 'Render Queue', icon: ListOrdered },{ id: 'history', label: 'History', icon: History },{ id: 'collections', label: 'Collections', icon: FolderOpen },{ id: 'models', label: 'Models', icon: HardDrive }diff --git a/client/src/pages/RenderQueue.jsx b/client/src/pages/RenderQueue.jsxnew file mode 100644index 0000000000..b91e2cb6df--- /dev/null+++ b/client/src/pages/RenderQueue.jsx@@ -0,0 +1,146 @@+import { useEffect, useState, useCallback } from 'react';+import { ListOrdered, Image as ImageIcon, Film, X, RefreshCw } from 'lucide-react';+import toast from '../components/ui/Toast';+import { listMediaJobs, cancelMediaJob } from '../services/apiMediaJobs.js';++const STATUS_BADGE = {+ queued: 'bg-port-border text-port-text-muted',+ running: 'bg-port-accent/30 text-port-accent',+ completed: 'bg-port-success/30 text-port-success',+ failed: 'bg-port-error/30 text-port-error',+ canceled: 'bg-port-warning/30 text-port-warning',+};++const KIND_ICON = {+ video: Film,+ image: ImageIcon,+};++export default function RenderQueue() {+ const [jobs, setJobs] = useState([]);+ const [loading, setLoading] = useState(true);++ const fetchJobs = useCallback(() => {+ listMediaJobs()+ .then((data) => { setJobs(data || []); setLoading(false); })+ .catch(() => setLoading(false));+ }, []);++ useEffect(() => {+ fetchJobs();+ const t = setInterval(fetchJobs, 3000);+ return () => clearInterval(t);+ }, [fetchJobs]);++ const handleCancel = async (id) => {+ try {+ await cancelMediaJob(id);+ // Optimistic update: queued jobs flip straight to 'canceled' (the worker+ // never picks them up so the next poll will show the same). For running+ // jobs we leave the server status as-is and track a UI-only+ // `cancelRequested` flag so the badge stays valid (the server status+ // model only knows queued|running|completed|failed|canceled — using a+ // synthetic 'canceling' here would render an unstyled badge until the+ // next poll). The next /jobs poll resolves the row to 'canceled' once+ // the worker observes the cancellation.+ setJobs((prev) => prev.map((j) => {+ if (j.id !== id) return j;+ if (j.status === 'queued') return { ...j, status: 'canceled', cancelRequested: false };+ return { ...j, cancelRequested: true };+ }));+ toast.success('Cancel requested');+ } catch (err) {+ toast.error(err.message || 'Cancel failed');+ }+ };++ if (loading) return <div className="text-port-text-muted text-sm">Loading…</div>;++ const live = jobs.filter((j) => j.status === 'queued' || j.status === 'running');+ const recent = jobs.filter((j) => j.status !== 'queued' && j.status !== 'running').slice(0, 30);++ return (+ <div className="space-y-4">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ <ListOrdered className="w-5 h-5 text-port-accent" />+ <h2 className="text-lg font-semibold">Render Queue</h2>+ <span className="text-xs text-port-text-muted">+ {live.length} active • {recent.length} recent+ </span>+ </div>+ <button onClick={fetchJobs} className="flex items-center gap-1 px-2 py-1 bg-port-card border border-port-border rounded text-xs">+ <RefreshCw className="w-3 h-3" /> Refresh+ </button>+ </div>++ {live.length === 0 && (+ <div className="text-port-text-muted text-sm">No image or video renders in flight.</div>+ )}++ {live.length > 0 && (+ <section className="space-y-2">+ <h3 className="text-xs font-semibold text-port-text-muted uppercase tracking-wide">Active</h3>+ {live.map((j) => <JobRow key={j.id} job={j} onCancel={handleCancel} />)}+ </section>+ )}++ {recent.length > 0 && (+ <section className="space-y-2">+ <h3 className="text-xs font-semibold text-port-text-muted uppercase tracking-wide">Recent (last 24h)</h3>+ {recent.map((j) => <JobRow key={j.id} job={j} onCancel={handleCancel} />)}+ </section>+ )}+ </div>+ );+}++function JobRow({ job, onCancel }) {+ const Icon = KIND_ICON[job.kind] || Film;+ const canCancel = job.status === 'queued' || job.status === 'running';+ return (+ <div className="bg-port-card border border-port-border rounded p-3">+ <div className="flex items-center justify-between gap-3">+ <div className="flex items-center gap-2 min-w-0">+ <Icon className="w-4 h-4 text-port-accent shrink-0" />+ <div className="min-w-0">+ <div className="text-sm font-medium truncate">+ <span className="font-mono">{job.id.slice(0, 8)}</span>+ <span className="text-port-text-muted"> · {job.kind}</span>+ {job.position && job.status === 'queued' && (+ <span className="text-port-text-muted"> · #{job.position} in queue</span>+ )}+ </div>+ <div className="text-xs text-port-text-muted truncate">+ {job.params?.prompt ? `"${job.params.prompt.slice(0, 80)}${job.params.prompt.length > 80 ? '…' : ''}"` : 'no prompt'}+ {job.owner && <span> · {job.owner}</span>}+ </div>+ </div>+ </div>+ <div className="flex items-center gap-2 shrink-0">+ <span className={`text-xs px-2 py-0.5 rounded ${STATUS_BADGE[job.status] || ''}`}>{job.status}</span>+ {job.cancelRequested && (+ <span className="text-xs text-port-warning" title="Cancellation requested — waiting for worker">cancelling…</span>+ )}+ {canCancel && !job.cancelRequested && (+ <button+ onClick={() => onCancel(job.id)}+ className="flex items-center gap-1 px-2 py-1 bg-port-bg border border-port-border rounded text-xs hover:bg-port-error/20 hover:text-port-error"+ title="Cancel"+ >+ <X className="w-3 h-3" />+ </button>+ )}+ </div>+ </div>+ {job.status === 'failed' && job.error && (+ <div className="text-xs text-port-error mt-2 truncate" title={job.error}>{job.error}</div>+ )}+ <div className="text-xs text-port-text-muted mt-1">+ {job.queuedAt && `queued ${new Date(job.queuedAt).toLocaleTimeString()}`}+ {job.startedAt && ` · started ${new Date(job.startedAt).toLocaleTimeString()}`}+ {job.completedAt && ` · finished ${new Date(job.completedAt).toLocaleTimeString()}`}+ </div>+ </div>+ );+}diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex cb9252fa01..71c929acc5 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -412,6 +412,15 @@ export default function VideoGen() {toast.error(msg.error);settleReject(new Error(msg.error));}+ if (msg.type === 'canceled') {+ // Queue-driven cancellation (different from gen-side error). Mark+ // the UI terminal so the spinner clears and the user can resubmit.+ setGenerating(false);+ setStatusMsg(msg.reason || 'Canceled');+ es.close();+ toast.info?.(msg.reason || 'Render canceled');+ settleReject(new Error(msg.reason || 'Canceled'));+ }};es.onerror = () => {if (!isCurrent()) { es.close(); return; }diff --git a/client/src/services/apiCreativeDirector.js b/client/src/services/apiCreativeDirector.jsnew file mode 100644index 0000000000..45cf48b6c7--- /dev/null+++ b/client/src/services/apiCreativeDirector.js@@ -0,0 +1,27 @@+import { request } from './apiCore.js';++export const listCreativeDirectorProjects = () => request('/creative-director');+export const getCreativeDirectorProject = (id) => request(`/creative-director/${encodeURIComponent(id)}`);+export const createCreativeDirectorProject = (data) => request('/creative-director', {+ method: 'POST',+ body: JSON.stringify(data),+});+export const updateCreativeDirectorProject = (id, patch) => request(`/creative-director/${encodeURIComponent(id)}`, {+ method: 'PATCH',+ body: JSON.stringify(patch),+});+export const deleteCreativeDirectorProject = (id) => request(`/creative-director/${encodeURIComponent(id)}`, {+ method: 'DELETE',+});+export const startCreativeDirectorProject = (id) => request(`/creative-director/${encodeURIComponent(id)}/start`, {+ method: 'POST',+});+export const pauseCreativeDirectorProject = (id) => request(`/creative-director/${encodeURIComponent(id)}/pause`, {+ method: 'POST',+});+export const resumeCreativeDirectorProject = (id) => request(`/creative-director/${encodeURIComponent(id)}/resume`, {+ method: 'POST',+});+export const createSmokeTestCreativeDirectorProject = () => request('/creative-director/smoke-test', {+ method: 'POST',+});diff --git a/client/src/services/apiMediaJobs.js b/client/src/services/apiMediaJobs.jsnew file mode 100644index 0000000000..3940ccc6fa--- /dev/null+++ b/client/src/services/apiMediaJobs.js@@ -0,0 +1,12 @@+import { request } from './apiCore.js';++export const listMediaJobs = (filters = {}) => {+ const qs = new URLSearchParams(+ Object.entries(filters).filter(([, v]) => v != null && v !== ''),+ ).toString();+ return request(`/media-jobs${qs ? `?${qs}` : ''}`);+};++export const getMediaJob = (id) => request(`/media-jobs/${encodeURIComponent(id)}`);++export const cancelMediaJob = (id) => request(`/media-jobs/${encodeURIComponent(id)}/cancel`, { method: 'POST' });diff --git a/server/index.js b/server/index.jsindex a2ba9eb42a..cd8ed83201 100644--- a/server/index.js+++ b/server/index.js@@ -81,6 +81,10 @@ import toolsRoutes from './routes/tools.js';import imageGenRoutes from './routes/imageGen.js';import videoGenRoutes from './routes/videoGen.js';import videoTimelineRoutes from './routes/videoTimeline.js';+import mediaJobsRoutes from './routes/mediaJobs.js';+import creativeDirectorRoutes from './routes/creativeDirector.js';+import { initMediaJobQueue } from './services/mediaJobQueue/index.js';+import { recoverInFlightProjects } from './services/creativeDirector/recovery.js';import imageVideoModelsRoutes from './routes/imageVideoModels.js';import sdapiRoutes from './routes/sdapi.js';import openclawRoutes from './routes/openclaw.js';@@ -314,6 +318,8 @@ app.use('/api/tools', toolsRoutes);app.use('/api/image-gen', imageGenRoutes);app.use('/api/video-gen', videoGenRoutes);app.use('/api/video-timeline', videoTimelineRoutes);+app.use('/api/media-jobs', mediaJobsRoutes);+app.use('/api/creative-director', creativeDirectorRoutes);app.use('/api/image-video/models', imageVideoModelsRoutes);// AUTOMATIC1111-compatible surface for tailnet clients — gated by// settings.imageGen.expose.a1111 so it returns 403 unless the user opted in.@@ -321,6 +327,10 @@ app.use('/sdapi/v1', sdapiRoutes);app.use('/api/openclaw', openclawRoutes);app.use('/api/ask', askRoutes);+// initMediaJobQueue is awaited as part of the startup chain below so that+// data/ exists and the worker loop is running before /api/video-gen or+// /api/image-gen can enqueue (otherwise persist() can race with ensureDir).+// Initialize agent automation scheduler and action executorautomationScheduler.init().catch(err => console.error(`❌ Agent scheduler init failed: ${err.message}`));// agentActionExecutor.init() is synchronous — guard with try/catch so a thrown@@ -439,8 +449,22 @@ app.use(errorMiddleware);// race conditions where brain mutations arrive before the sync log is readyensureSelf().then(() => initSyncLog())+ .then(() => initMediaJobQueue())+ .then(() => {+ // Fire-and-forget — resume any Creative Director projects that were mid-+ // flight when the server died. The queue reload above just reclassified+ // their renders as 'failed (interrupted by restart)'; this nudges the+ // orchestrator so projects don't sit frozen waiting for listeners that+ // no longer exist. Doesn't block startup.+ recoverInFlightProjects().catch((e) => console.log(`⚠️ CD boot recovery failed: ${e.message}`));+ }).then(() => {- // Start server only after sync log is initialized+ // Start server only after sync log + media job queue are initialized.+ // initMediaJobQueue failure is fatal: the queue owns persistence + SSE+ // + temp-file cleanup for /api/video-gen and local /api/image-gen, and+ // accepting requests with a half-init queue silently corrupts state+ // (persist() throws, SSE streams degrade). Catch + crash via the+ // outer .catch(...process.exit) below.httpServer.listen(PORT, HOST, () => {// One canonical "where do I open this" banner — :5555 is always user-facing// (HTTP or HTTPS), :PORTOS_HTTP_PORT (default 5553) is the loopback HTTPdiff --git a/server/lib/creativeDirectorPresets.js b/server/lib/creativeDirectorPresets.jsnew file mode 100644index 0000000000..20e47ee23e--- /dev/null+++ b/server/lib/creativeDirectorPresets.js@@ -0,0 +1,69 @@+/**+ * Creative Director presets — locked-at-creation aspect ratio + quality+ * settings that map onto the render-API params the LTX/mlx_video pipeline+ * actually consumes.+ *+ * The contract: a project picks an aspectRatio + quality + modelId once;+ * every scene render uses these. Tweaking is intentionally not allowed+ * mid-project — segment-to-segment continuity needs identical resolution+ * and frame budgets.+ */++// Width/height pairs are 64-aligned (videoGen rounds down to multiples of+// 64 anyway) and chosen for sensible LTX defaults.+export const ASPECT_PRESETS = Object.freeze({+ '16:9': { width: 768, height: 432 },+ '9:16': { width: 432, height: 768 },+ '1:1': { width: 512, height: 512 },+});++// `steps` and `guidance` are mlx_video knobs. `fps` is the render frame+// rate. Higher quality = more denoising steps + slightly higher guidance,+// trading wall-clock time for fidelity.+export const QUALITY_PRESETS = Object.freeze({+ draft: { steps: 8, guidance: 2.5, fps: 24 },+ standard: { steps: 20, guidance: 3.0, fps: 24 },+ high: { steps: 30, guidance: 3.5, fps: 30 },+});++export const ASPECT_RATIOS = Object.freeze(['16:9', '9:16', '1:1']);+export const QUALITIES = Object.freeze(['draft', 'standard', 'high']);++// Project lifecycle states. Single source of truth for both validation+// (Zod enum) and runtime guards in the service layer.+export const PROJECT_STATUSES = Object.freeze([+ 'draft', 'planning', 'rendering', 'stitching', 'complete', 'paused', 'failed',+]);++// Per-scene lifecycle states. Used by the validation schemas + the+// orchestrator's "next pending scene" logic.+export const SCENE_STATUSES = Object.freeze([+ 'pending', 'rendering', 'evaluating', 'accepted', 'failed',+]);++/**+ * Map a project's aspectRatio + quality + scene durationSeconds to the+ * concrete render-API body.+ *+ * numFrames is rounded to a multiple of 8 because LTX latent compression+ * is `1 + (frames - 1) / 8` — non-multiples silently break the+ * conditioning shape check on i2v renders. Floor to 8 frames minimum so+ * a 0.3s scene still produces something coherent.+ */+export function presetToRenderParams({ aspectRatio, quality, durationSeconds }) {+ const aspect = ASPECT_PRESETS[aspectRatio];+ if (!aspect) throw new Error(`Unknown aspectRatio '${aspectRatio}'`);+ const q = QUALITY_PRESETS[quality];+ if (!q) throw new Error(`Unknown quality '${quality}'`);+ const requested = Math.max(0.1, Number(durationSeconds) || 1) * q.fps;+ // Round to nearest multiple of 8, with an 8-frame floor.+ const numFrames = Math.max(8, Math.round(requested / 8) * 8);+ return {+ width: aspect.width,+ height: aspect.height,+ fps: q.fps,+ steps: q.steps,+ guidanceScale: q.guidance,+ numFrames,+ };+}diff --git a/server/lib/creativeDirectorPrompts.js b/server/lib/creativeDirectorPrompts.jsnew file mode 100644index 0000000000..4d2920e289--- /dev/null+++ b/server/lib/creativeDirectorPrompts.js@@ -0,0 +1,183 @@+/**+ * Creative Director — agent prompt templates.+ *+ * Only two cognitive steps require an agent:+ * - `treatment`: write the story + scene plan+ * - `evaluate` : judge a single rendered scene against the style spec+ *+ * Programmatic steps (per-scene render orchestration, final stitch) live+ * server-side in services/creativeDirector/{sceneRunner,stitchRunner}.js+ * and never spawn an agent.+ */++import { ASPECT_PRESETS, QUALITY_PRESETS, presetToRenderParams } from './creativeDirectorPresets.js';+import { PORTOS_API_URL } from './ports.js';++// Common header. Project context the agent always needs to know.+function projectBlock(project) {+ const aspect = ASPECT_PRESETS[project.aspectRatio];+ const q = QUALITY_PRESETS[project.quality];+ return [+ `## Project: "${project.name}" (id: ${project.id})`,+ ``,+ `- Aspect ratio: ${project.aspectRatio} (${aspect.width}×${aspect.height})`,+ `- Quality: ${project.quality} (${q.steps} denoising steps, guidance ${q.guidance}, ${q.fps}fps)`,+ `- Model: ${project.modelId}`,+ `- Target episode duration: ${project.targetDurationSeconds}s (~${Math.round(project.targetDurationSeconds / 60)} min)`,+ `- Collection id (group all rendered segments here): ${project.collectionId}`,+ project.startingImageFile ? `- Starting image: /data/images/${project.startingImageFile}` : `- Starting image: none`,+ ``,+ `## Style spec (apply to every prompt)`,+ project.styleSpec || '(none — derive a coherent visual language from the project name + first scene intent)',+ ``,+ ].join('\n');+}++export function buildTreatmentPrompt(project) {+ const userStoryBlock = project.userStory+ ? `## User-supplied story\n\nThe user provided this outline. Honor it; expand/refine but don't contradict.\n\n${project.userStory}\n\n`+ : `## Story\n\nThe user did not supply a story. Invent one that suits the style spec and target duration.\n\n`;++ return [+ `# Creative Director — Treatment task`,+ ``,+ `You are the Creative Director for a long-form generated-video project. Your job in this task is to produce a TREATMENT — a complete scene-by-scene plan that the server will then render scene-by-scene (no further agent task is needed for rendering — the server orchestrates that). After each render lands, a separate short evaluation task will judge it.`,+ ``,+ projectBlock(project),+ userStoryBlock,+ `## Task`,+ ``,+ `1. Design a story arc that fits ~${project.targetDurationSeconds}s of total runtime. Think in scenes that are 1–10 seconds each (most should be 4–6s; reserve short ones for cuts and long ones for held shots).`,+ `2. Each scene should have a clear visual intent and a render prompt that incorporates the style spec.`,+ `3. Decide for each scene whether it continues from the previous scene's last frame (\`useContinuationFromPrior: true\`) or starts from a new image (\`useContinuationFromPrior: false\`, optionally with a \`sourceImageFile\` basename if you want to seed from a specific gallery image). Scene 1 either uses the project starting image (if provided — copy its filename into \`sourceImageFile\`) or starts as text-to-video.`,+ `4. Don't pad with filler; if the natural arc is shorter than the target, that's fine — produce fewer scenes.`,+ ``,+ `## Output contract`,+ ``,+ `Issue ONE HTTP request to update the project with the treatment, then exit:`,+ ``,+ `\`\`\``,+ `PATCH ${PORTOS_API_URL}/api/creative-director/${project.id}/treatment`,+ `Content-Type: application/json`,+ ``,+ `{`,+ ` "logline": "<one-sentence high-concept>",`,+ ` "synopsis": "<short paragraph synopsis>",`,+ ` "scenes": [`,+ ` {`,+ ` "sceneId": "scene-1",`,+ ` "order": 0,`,+ ` "intent": "<what this scene does narratively/visually>",`,+ ` "prompt": "<full render prompt with style spec inlined>",`,+ ` "negativePrompt": "<optional>",`,+ ` "durationSeconds": 5,`,+ ` "useContinuationFromPrior": false,`,+ ` "sourceImageFile": ${project.startingImageFile ? `"${project.startingImageFile}"` : 'null'}`,+ ` },`,+ ` { "sceneId": "scene-2", "order": 1, ..., "useContinuationFromPrior": true }`,+ ` ]`,+ `}`,+ `\`\`\``,+ ``,+ `On a 200 response your task is complete. The server will automatically begin rendering scene 1 — do not create any additional tasks yourself.`,+ ``,+ `If the PATCH returns 4xx, fix the validation issue (read the error body) and retry. Do not retry on 5xx more than twice.`,+ ].join('\n');+}++export function buildEvaluatePrompt(project, scene) {+ const renderParams = presetToRenderParams({+ aspectRatio: project.aspectRatio,+ quality: project.quality,+ durationSeconds: scene.durationSeconds,+ });+ const renderedId = scene.renderedJobId || '<unknown>';+ return [+ `# Creative Director — Scene evaluation task`,+ ``,+ `Your ONLY job is to evaluate a freshly-rendered scene and decide whether it works. The render itself was done by the server (no upstream task to do); the rendered video and its thumbnail are already on disk.`,+ ``,+ projectBlock(project),+ `## Scene to evaluate`,+ ``,+ `- Scene id: \`${scene.sceneId}\` (${scene.order + 1}/${project.treatment?.scenes?.length || '?'})`,+ `- Intent: ${scene.intent}`,+ `- Render prompt: ${JSON.stringify(scene.prompt)}`,+ `- Render: \`${renderParams.width}×${renderParams.height}\`, ${renderParams.numFrames} frames @ ${renderParams.fps}fps`,+ `- Strategy: ${scene.useContinuationFromPrior ? 'continued from prior scene last-frame' : (scene.sourceImageFile ? `seeded from image \`${scene.sourceImageFile}\`` : 'text-to-video')}`,+ `- Retry count: ${scene.retryCount || 0} (max 3)`,+ `- Rendered video: \`/data/videos/${renderedId}.mp4\``,+ `- Thumbnail (use this for evaluation): \`/data/video-thumbnails/${renderedId}.jpg\``,+ ``,+ `## Step 1 — Read the thumbnail using your vision capability`,+ ``,+ `Open the thumbnail file (Read tool) and inspect the frame.`,+ ``,+ `## Step 2 — Score against three dimensions`,+ ``,+ `1. **Style adherence**: does it match the project style spec?`,+ `2. **Continuity**: does it flow from the prior accepted scene's tone, color, characters? (If this is scene 1, just check it stands on its own.)`,+ `3. **Scene intent**: does it actually depict "${scene.intent}"?`,+ ``,+ `## Step 3 — Decide`,+ ``,+ `Issue ONE PATCH to record your verdict, then exit. Do not request renders, do not call last-frame, do not create follow-up tasks — the server handles all of that.`,+ ``,+ `\`\`\``,+ `PATCH ${PORTOS_API_URL}/api/creative-director/${project.id}/scene/${scene.sceneId}`,+ `Content-Type: application/json`,+ `\`\`\``,+ ``,+ `**If the render is acceptable** (good enough — perfect is the enemy of done):`,+ `\`\`\`json`,+ `{`,+ ` "status": "accepted",`,+ ` "evaluation": {`,+ ` "accepted": true,`,+ ` "score": 0.0–1.0,`,+ ` "notes": "<one-sentence reason>",`,+ ` "sampledAt": "<ISO 8601 timestamp>"`,+ ` }`,+ `}`,+ `\`\`\``,+ ``,+ `Then (and ONLY in the accepted case) add the rendered video to the project's collection:`,+ `\`\`\``,+ `POST ${PORTOS_API_URL}/api/media/collections/${project.collectionId}/items`,+ `Content-Type: application/json`,+ ``,+ `{ "kind": "video", "ref": "${renderedId}" }`,+ `\`\`\``,+ `Do NOT issue this POST for the retry or failed branches below — rejected renders should not enter the collection.`,+ ``,+ `**If the render misses the mark and retries are still available** (\`retryCount < 3\`): tweak the prompt and request a re-render. The server will run the new render and then send you back here for another evaluation.`,+ `\`\`\`json`,+ `{`,+ ` "status": "pending",`,+ ` "prompt": "<refined render prompt>",`,+ ` "retryCount": ${(scene.retryCount || 0) + 1},`,+ ` "evaluation": {`,+ ` "accepted": false,`,+ ` "score": 0.0–1.0,`,+ ` "notes": "<what to fix>",`,+ ` "sampledAt": "<ISO 8601 timestamp>"`,+ ` }`,+ `}`,+ `\`\`\``,+ ``,+ `**If retries are exhausted** (\`retryCount >= 3\`) and the render is still not acceptable, give up on this scene:`,+ `\`\`\`json`,+ `{`,+ ` "status": "failed",`,+ ` "evaluation": {`,+ ` "accepted": false,`,+ ` "score": 0.0–1.0,`,+ ` "notes": "<why no further retry helps>",`,+ ` "sampledAt": "<ISO 8601 timestamp>"`,+ ` }`,+ `}`,+ `\`\`\``,+ ``,+ `Then exit. The server picks up from there.`,+ ].join('\n');+}diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 02305e11e6..96c8af7b7f 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -14,6 +14,8 @@ export const NAV_COMMANDS = [{ id: 'nav.media.video', path: '/media/video', label: 'Video', section: 'AI', aliases: ['video-gen', 'videogen', 'generate-video', 'ltx'], keywords: ['video', 'animate', 'movie', 'clip', 'ltx'] },{ id: 'nav.media.history', path: '/media/history', label: 'Media History', section: 'AI', aliases: ['media-history', 'video-history'], keywords: ['videos', 'gallery', 'stitch'] },{ id: 'nav.media.collections', path: '/media/collections', label: 'Collections', section: 'AI', aliases: ['collections', 'media-collections', 'stacks', 'projects'], keywords: ['bucket', 'group', 'project', 'album', 'organize'] },+ { id: 'nav.media.creative-director', path: '/media/creative-director', label: 'Creative Director', section: 'AI', aliases: ['creative-director', 'creative', 'director', 'long-form', 'episode'], keywords: ['story', 'episode', 'narrative', 'agent', 'auto-video', 'long-form'] },+ { id: 'nav.media.queue', path: '/media/queue', label: 'Render Queue', section: 'AI', aliases: ['render-queue', 'queue', 'media-queue', 'media-jobs'], keywords: ['render', 'queue', 'pending', 'jobs', 'pipeline'] },{ id: 'nav.media.timeline', path: '/media/timeline', label: 'Timeline', section: 'AI', aliases: ['timeline', 'video-timeline', 'editor'], keywords: ['edit', 'trim', 'composite', 'stitch', 'cut', 'compose'] },{ id: 'nav.media.models', path: '/media/models', label: 'Media Models', section: 'AI', aliases: ['media-models', 'image-models', 'video-models', 'huggingface', 'loras'], keywords: ['hf cache', 'lora', 'model storage', 'disk'] },{ id: 'nav.media.settings', path: '/media/image?settings=1', label: 'Media Gen Settings', section: 'AI', aliases: ['media-settings', 'image-gen-settings', 'sd-settings', 'video-gen-settings'] },diff --git a/server/lib/taskParser.js b/server/lib/taskParser.jsindex 43b520118f..f6e3bc33d8 100644--- a/server/lib/taskParser.js+++ b/server/lib/taskParser.js@@ -29,7 +29,7 @@*/// Canonical prefix lists — add new prefixes here, not in scattered startsWith checks-const INTERNAL_PREFIXES = ['sys-', 'app-improve-'];+const INTERNAL_PREFIXES = ['sys-', 'app-improve-', 'cd-'];const ALL_KNOWN_PREFIXES = ['task-', ...INTERNAL_PREFIXES];export const hasKnownPrefix = (id) => ALL_KNOWN_PREFIXES.some(p => id?.startsWith(p));diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 95d4a37ab0..03685746ba 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1,5 +1,6 @@import { z } from 'zod';import { ServerError } from './errorHandler.js';+import { ASPECT_RATIOS, QUALITIES, PROJECT_STATUSES, SCENE_STATUSES } from './creativeDirectorPresets.js';// =============================================================================// AGENT PERSONALITY SCHEMAS@@ -598,3 +599,102 @@ export function sanitizeTaskMetadata(raw) {}return hasKeys ? { ...clean } : null;}+++// =============================================================================+// CREATIVE DIRECTOR SCHEMAS+// =============================================================================++export const creativeDirectorAspectRatioSchema = z.enum(ASPECT_RATIOS);+export const creativeDirectorQualitySchema = z.enum(QUALITIES);++// Top-level project create. modelId is required because each LTX variant+// has a different speed/VRAM/quality profile and the project locks it at+// creation. targetDurationSeconds is capped at 600 (10 min) per the v1 plan+// — much beyond that and the agent's treatment quality drifts hard.+// Strict basename: rejects path separators and the exact `.`/`..` segments.+// Used for both startingImageFile (project create) and sourceImageFile+// (per-scene) since both feed into `join(PATHS.images, ...)` later. The+// downstream consumers also do a resolve+prefix-check against PATHS.images+// (sceneRunner.js) — that's the real traversal guard; this validator just+// catches the obvious bad values at the route boundary. Note: a substring+// check on `..` would over-reject legitimate names like `my..image.png`,+// so we only reject the exact dot segments and rely on prefix-checks for+// the actual escape protection.+const safeBasename = z.string()+ .max(256)+ .regex(/^[^/\\]+$/, 'must be a basename (no path separators)')+ .refine((v) => v !== '.' && v !== '..',+ 'must not be `.` or `..`');++export const creativeDirectorProjectCreateSchema = z.object({+ name: z.string().min(1).max(200),+ aspectRatio: creativeDirectorAspectRatioSchema,+ quality: creativeDirectorQualitySchema,+ modelId: z.string().min(1).max(64),+ targetDurationSeconds: z.number().int().min(5).max(600),+ styleSpec: z.string().max(5000).default(''),+ startingImageFile: safeBasename.nullable().optional(),+ userStory: z.string().max(10000).nullable().optional(),+ // Test/dev knobs. Both default false. Smoke-test fixtures set these.+ disableAudio: z.boolean().optional().default(false),+ autoAcceptScenes: z.boolean().optional().default(false),+});++// Update is restricted to a few editable fields. modelId / aspectRatio /+// quality / targetDurationSeconds are locked at creation — changing them+// mid-project would invalidate already-rendered segments.+export const creativeDirectorProjectUpdateSchema = z.object({+ name: z.string().min(1).max(200).optional(),+ styleSpec: z.string().max(5000).optional(),+ userStory: z.string().max(10000).nullable().optional(),+ status: z.enum(PROJECT_STATUSES).optional(),+ finalVideoId: z.string().max(64).nullable().optional(),+ timelineProjectId: z.string().max(64).nullable().optional(),+ failureReason: z.string().max(500).nullable().optional(),+}).strict();++// One scene in the treatment, written by the agent on the treatment task.+export const creativeDirectorSceneSchema = z.object({+ sceneId: z.string().min(1).max(64),+ order: z.number().int().min(0),+ intent: z.string().min(1).max(1000),+ prompt: z.string().min(1).max(2000),+ negativePrompt: z.string().max(2000).optional().default(''),+ durationSeconds: z.number().min(1).max(10),+ useContinuationFromPrior: z.boolean().default(false),+ sourceImageFile: safeBasename.nullable().optional(),+ status: z.enum(SCENE_STATUSES).default('pending'),+ retryCount: z.number().int().min(0).max(10).default(0),+ renderedJobId: z.string().max(64).nullable().optional(),+ evaluation: z.object({+ score: z.number().min(0).max(1).optional(),+ notes: z.string().max(2000).optional(),+ accepted: z.boolean(),+ sampledAt: z.string().optional(),+ }).nullable().optional(),+});++// The full treatment doc the agent writes after the planning task.+export const creativeDirectorTreatmentSchema = z.object({+ logline: z.string().min(1).max(500),+ synopsis: z.string().min(1).max(5000),+ scenes: z.array(creativeDirectorSceneSchema).min(1).max(120),+});++// Used by the agent when finishing a scene render.+export const creativeDirectorSceneUpdateSchema = z.object({+ // Full SCENE_STATUSES — the evaluator agent flips a scene back to 'pending'+ // (with an updated prompt + bumped retryCount) to request a re-render; see+ // creativeDirectorPrompts.js and completionHook.js's advanceAfterSceneSettled.+ status: z.enum(SCENE_STATUSES).optional(),+ retryCount: z.number().int().min(0).max(10).optional(),+ renderedJobId: z.string().max(64).nullable().optional(),+ prompt: z.string().min(1).max(2000).optional(),+ evaluation: z.object({+ score: z.number().min(0).max(1).optional(),+ notes: z.string().max(2000).optional(),+ accepted: z.boolean(),+ sampledAt: z.string().optional(),+ }).nullable().optional(),+}).strict();diff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.jsnew file mode 100644index 0000000000..a741bca13b--- /dev/null+++ b/server/routes/creativeDirector.js@@ -0,0 +1,146 @@+/**+ * Creative Director Routes — REST surface for project CRUD + agent bridge.+ *+ * The agent (running as a CoS task) calls into here to: read a project's+ * state, write a treatment, mark a scene accepted/failed, and update the+ * project status. The user's UI calls in to: list/create/delete projects+ * and start/pause/resume the agent pipeline.+ */++import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import {+ validateRequest,+ creativeDirectorProjectCreateSchema,+ creativeDirectorProjectUpdateSchema,+ creativeDirectorTreatmentSchema,+ creativeDirectorSceneUpdateSchema,+} from '../lib/validation.js';+import {+ listProjects,+ getProject,+ createProject,+ updateProject,+ deleteProject,+ setTreatment,+ updateScene,+} from '../services/creativeDirector/local.js';+import { startCreativeDirectorProject } from '../services/creativeDirector/completionHook.js';+import { createSmokeTestProject } from '../services/creativeDirector/smokeTest.js';++const router = Router();++router.get('/', asyncHandler(async (_req, res) => {+ res.json(await listProjects());+}));++router.get('/:id', asyncHandler(async (req, res) => {+ const p = await getProject(req.params.id);+ if (!p) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ res.json(p);+}));++router.post('/', asyncHandler(async (req, res) => {+ const data = validateRequest(creativeDirectorProjectCreateSchema, req.body);+ const project = await createProject(data);+ res.status(201).json(project);+}));++router.patch('/:id', asyncHandler(async (req, res) => {+ const data = validateRequest(creativeDirectorProjectUpdateSchema, req.body);+ const updated = await updateProject(req.params.id, data);+ res.json(updated);+}));++router.delete('/:id', asyncHandler(async (req, res) => {+ await deleteProject(req.params.id);+ res.json({ ok: true });+}));++// Agent-callable: write the treatment doc.+router.patch('/:id/treatment', asyncHandler(async (req, res) => {+ const treatment = validateRequest(creativeDirectorTreatmentSchema, req.body);+ const updated = await setTreatment(req.params.id, treatment);+ res.json(updated);+}));++// Agent-callable: update a single scene's status / evaluation / retry count.+router.patch('/:id/scene/:sceneId', asyncHandler(async (req, res) => {+ const data = validateRequest(creativeDirectorSceneUpdateSchema, req.body);+ const updated = await updateScene(req.params.id, req.params.sceneId, data);+ if (data.status === 'accepted' || data.status === 'failed') {+ // Fire-and-forget — agent or user just settled a scene; nudge the+ // orchestrator so the next scene (or stitch) starts.+ const { advanceAfterSceneSettled } = await import('../services/creativeDirector/completionHook.js');+ advanceAfterSceneSettled(req.params.id).catch((e) => console.log(`⚠️ CD scene advance failed: ${e.message}`));+ }+ res.json(updated);+}));++// User-callable: kick off (or resume) the agent pipeline. Server inspects+// project state, decides what kind of task is next, and enqueues it via the+// CoS task queue. Idempotent — calling start on an already-running project+// just enqueues whatever the next-task-kind is, which may be nothing.+//+// Failed projects are recoverable: any failed scenes are reset to pending so+// the orchestrator can retry them, and the project status flips back to+// planning/rendering. This matches the PR's "you can resume from the UI"+// promise — without it, a single failed scene would leave Start a no-op.+router.post('/:id/start', asyncHandler(async (req, res) => {+ const project = await getProject(req.params.id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ if (project.status === 'failed') {+ // Reset every failed scene back to pending so the orchestrator picks+ // them up. Without this, a single failed scene would leave Start a no-op.+ const scenes = project.treatment?.scenes || [];+ for (const s of scenes) {+ if (s.status === 'failed') {+ await updateScene(project.id, s.sceneId, { status: 'pending', retryCount: 0 });+ }+ }+ // Clear the prior failure banner — restart implies the user has+ // accepted the previous failure and wants a fresh attempt.+ await updateProject(project.id, { status: project.treatment ? 'rendering' : 'planning', failureReason: null });+ } else if (project.status === 'paused') {+ await updateProject(project.id, { status: project.treatment ? 'rendering' : 'planning' });+ } else if (project.status === 'draft') {+ await updateProject(project.id, { status: 'planning' });+ }+ // Fire-and-forget — the orchestrator runs server-side and may spawn an+ // agent (treatment / evaluate) or kick off a render directly. The route+ // returns immediately; the UI's polling reflects state changes.+ startCreativeDirectorProject(project.id).catch((e) => console.log(`⚠️ CD start failed: ${e.message}`));+ res.json({ ok: true });+}));++// User-callable: pause. Stops the server from auto-enqueueing follow-up+// work. The currently running render (if any) keeps going to completion —+// canceling that is a separate gesture (POST /api/media-jobs/:id/cancel).+router.post('/:id/pause', asyncHandler(async (req, res) => {+ const updated = await updateProject(req.params.id, { status: 'paused' });+ res.json(updated);+}));++// Dev/test fixture: create a deterministic 3-scene "colored ball" project+// (autoAcceptScenes + disableAudio) and immediately kick it off. Used as+// the fast E2E health check after pipeline changes — completes in render+// time only, no Claude in the loop.+router.post('/smoke-test', asyncHandler(async (_req, res) => {+ const project = await createSmokeTestProject();+ startCreativeDirectorProject(project.id).catch((e) => console.log(`⚠️ CD smoke start failed: ${e.message}`));+ res.status(201).json(project);+}));++router.post('/:id/resume', asyncHandler(async (req, res) => {+ const project = await getProject(req.params.id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ if (project.status !== 'paused') {+ throw new ServerError('Project is not paused', { status: 400, code: 'INVALID_STATE' });+ }+ const restored = project.treatment ? 'rendering' : 'planning';+ await updateProject(project.id, { status: restored });+ startCreativeDirectorProject(project.id).catch((e) => console.log(`⚠️ CD resume failed: ${e.message}`));+ res.json({ ok: true });+}));++export default router;diff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.jsnew file mode 100644index 0000000000..203aeeca12--- /dev/null+++ b/server/routes/creativeDirector.test.js@@ -0,0 +1,197 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';++vi.mock('../services/creativeDirector/local.js', () => ({+ listProjects: vi.fn(async () => [{ id: 'cd-1', name: 'A' }]),+ getProject: vi.fn(),+ createProject: vi.fn(),+ updateProject: vi.fn(),+ deleteProject: vi.fn(async () => ({ ok: true })),+ setTreatment: vi.fn(),+ updateScene: vi.fn(),+}));++vi.mock('../services/creativeDirector/completionHook.js', () => ({+ startCreativeDirectorProject: vi.fn(async () => undefined),+ advanceAfterSceneSettled: vi.fn(async () => undefined),+}));++import * as cdService from '../services/creativeDirector/local.js';+import * as hook from '../services/creativeDirector/completionHook.js';+import creativeDirectorRoutes from './creativeDirector.js';++describe('creativeDirector routes', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/creative-director', creativeDirectorRoutes);+ vi.clearAllMocks();+ });++ describe('GET /', () => {+ it('returns all projects', async () => {+ const r = await request(app).get('/api/creative-director');+ expect(r.status).toBe(200);+ expect(r.body).toEqual([{ id: 'cd-1', name: 'A' }]);+ });+ });++ describe('GET /:id', () => {+ it('returns 404 when project missing', async () => {+ cdService.getProject.mockResolvedValue(null);+ const r = await request(app).get('/api/creative-director/cd-missing');+ expect(r.status).toBe(404);+ });++ it('returns the project when found', async () => {+ cdService.getProject.mockResolvedValue({ id: 'cd-1', name: 'A' });+ const r = await request(app).get('/api/creative-director/cd-1');+ expect(r.status).toBe(200);+ expect(r.body.id).toBe('cd-1');+ });+ });++ describe('POST /', () => {+ it('rejects body missing required fields', async () => {+ const r = await request(app).post('/api/creative-director').send({ name: 'x' });+ expect(r.status).toBe(400);+ });++ it('creates a project on a complete payload', async () => {+ cdService.createProject.mockResolvedValue({ id: 'cd-new', name: 'New' });+ const r = await request(app).post('/api/creative-director').send({+ name: 'New',+ aspectRatio: '16:9',+ quality: 'standard',+ modelId: 'ltx2_unified',+ targetDurationSeconds: 60,+ });+ expect(r.status).toBe(201);+ expect(r.body.id).toBe('cd-new');+ });++ it('rejects an invalid aspect ratio', async () => {+ const r = await request(app).post('/api/creative-director').send({+ name: 'New',+ aspectRatio: '4:3',+ quality: 'standard',+ modelId: 'ltx2_unified',+ targetDurationSeconds: 60,+ });+ expect(r.status).toBe(400);+ });+ });++ describe('PATCH /:id/treatment', () => {+ it('writes the treatment when shape is valid', async () => {+ cdService.setTreatment.mockResolvedValue({ id: 'cd-1', treatment: { scenes: [] } });+ const r = await request(app).patch('/api/creative-director/cd-1/treatment').send({+ logline: 'A cat finds a hat.',+ synopsis: 'Then puts it on.',+ scenes: [{+ sceneId: 'scene-1',+ order: 0,+ intent: 'Cat enters frame',+ prompt: 'A cat walks into view',+ durationSeconds: 4,+ }],+ });+ expect(r.status).toBe(200);+ expect(cdService.setTreatment).toHaveBeenCalled();+ });+ });++ describe('POST /:id/start', () => {+ it('flips draft → planning and triggers the orchestrator', async () => {+ cdService.getProject.mockResolvedValueOnce({ id: 'cd-1', name: 'A', status: 'draft' });+ cdService.updateProject.mockResolvedValue({});+ const r = await request(app).post('/api/creative-director/cd-1/start');+ expect(r.status).toBe(200);+ expect(r.body.ok).toBe(true);+ expect(cdService.updateProject).toHaveBeenCalledWith('cd-1', { status: 'planning' });+ expect(hook.startCreativeDirectorProject).toHaveBeenCalledWith('cd-1');+ });++ it('resets failed scenes back to pending and re-fires orchestrator', async () => {+ cdService.getProject.mockResolvedValueOnce({+ id: 'cd-1',+ status: 'failed',+ treatment: { scenes: [+ { sceneId: 'scene-1', status: 'failed', retryCount: 3 },+ { sceneId: 'scene-2', status: 'accepted', retryCount: 0 },+ ] },+ });+ cdService.updateProject.mockResolvedValue({});+ cdService.updateScene.mockResolvedValue({});+ const r = await request(app).post('/api/creative-director/cd-1/start');+ expect(r.status).toBe(200);+ expect(cdService.updateScene).toHaveBeenCalledWith('cd-1', 'scene-1', { status: 'pending', retryCount: 0 });+ expect(cdService.updateScene).not.toHaveBeenCalledWith('cd-1', 'scene-2', expect.anything());+ expect(hook.startCreativeDirectorProject).toHaveBeenCalledWith('cd-1');+ });+ });++ describe('POST /:id/pause', () => {+ it('marks paused', async () => {+ cdService.updateProject.mockResolvedValue({ id: 'cd-1', status: 'paused' });+ const r = await request(app).post('/api/creative-director/cd-1/pause');+ expect(r.status).toBe(200);+ expect(cdService.updateProject).toHaveBeenCalledWith('cd-1', { status: 'paused' });+ });+ });++ describe('POST /:id/resume', () => {+ it('rejects when not paused', async () => {+ cdService.getProject.mockResolvedValue({ id: 'cd-1', status: 'rendering' });+ const r = await request(app).post('/api/creative-director/cd-1/resume');+ expect(r.status).toBe(400);+ });++ it('flips paused → rendering and triggers the orchestrator', async () => {+ cdService.getProject.mockResolvedValueOnce({+ id: 'cd-1',+ status: 'paused',+ treatment: { scenes: [{ status: 'pending' }] },+ });+ cdService.updateProject.mockResolvedValue({});+ const r = await request(app).post('/api/creative-director/cd-1/resume');+ expect(r.status).toBe(200);+ expect(r.body.ok).toBe(true);+ expect(cdService.updateProject).toHaveBeenCalledWith('cd-1', { status: 'rendering' });+ expect(hook.startCreativeDirectorProject).toHaveBeenCalledWith('cd-1');+ });+ });++ describe('PATCH /:id/scene/:sceneId', () => {+ it('returns the updated scene and does not nudge orchestrator for non-terminal status', async () => {+ cdService.updateScene.mockResolvedValue({ sceneId: 'scene-1', status: 'rendering' });+ const r = await request(app)+ .patch('/api/creative-director/cd-1/scene/scene-1')+ .send({ status: 'rendering' });+ expect(r.status).toBe(200);+ expect(cdService.updateScene).toHaveBeenCalledWith('cd-1', 'scene-1', { status: 'rendering' });+ expect(hook.advanceAfterSceneSettled).not.toHaveBeenCalled();+ });++ it('nudges the orchestrator when a scene is accepted', async () => {+ cdService.updateScene.mockResolvedValue({ sceneId: 'scene-1', status: 'accepted' });+ const r = await request(app)+ .patch('/api/creative-director/cd-1/scene/scene-1')+ .send({ status: 'accepted' });+ expect(r.status).toBe(200);+ expect(hook.advanceAfterSceneSettled).toHaveBeenCalledWith('cd-1');+ });++ it('nudges the orchestrator when a scene is failed', async () => {+ cdService.updateScene.mockResolvedValue({ sceneId: 'scene-1', status: 'failed' });+ const r = await request(app)+ .patch('/api/creative-director/cd-1/scene/scene-1')+ .send({ status: 'failed' });+ expect(r.status).toBe(200);+ expect(hook.advanceAfterSceneSettled).toHaveBeenCalledWith('cd-1');+ });+ });+});diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex e0e31bc83d..28260d6560 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -19,6 +19,9 @@ import { validateRequest } from '../lib/validation.js';import { optionalUpload } from '../lib/multipart.js';import * as imageGen from '../services/imageGen/index.js';import { local, IMAGE_GEN_MODES } from '../services/imageGen/index.js';+import { enqueueJob, attachSseClient as attachQueueSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';+import { getSettings } from '../services/settings.js';+import { getImageModels, isFlux2 } from '../lib/mediaModels.js';import {REQUIRED_PACKAGES, detectPython, checkPackages, installPackages,isExternallyManaged, createVenv, isAllowedPython, pipNameFor,@@ -139,6 +142,56 @@ router.post('/generate', initImageUpload, asyncHandler(async (req, res) => {if (uploadedInitTempPath) {res.on('close', () => { unlink(uploadedInitTempPath).catch(() => {}); });}+ // Mode resolution: explicit per-request override > settings default. Only+ // local-mode goes through the mediaJobQueue (it's the GPU-bound backend that+ // used to throw BUSY). External and Codex backends remain synchronous —+ // they don't share Metal/MLX resources so no queue is needed.+ const settings = await getSettings();+ const mode = data.mode || settings.imageGen?.mode || 'external';+ if (mode === 'local') {+ const py = settings.imageGen?.local?.pythonPath || null;+ // Pre-validate config: mflux models need pythonPath, FLUX.2 doesn't+ // (it uses its own bundled venv). Without this guard, the queue would+ // accept the job and only surface the failure async over SSE.+ const allModels = getImageModels();+ // Reject a typo'd modelId synchronously rather than enqueueing a doomed+ // job. When omitted, fall through to the default ('dev'-ish) — the+ // worker does the same lookup so behavior stays consistent.+ if (data.modelId && !allModels.some((m) => m.id === data.modelId)) {+ throw new ServerError(+ `Unknown modelId: ${data.modelId}`,+ { status: 400, code: 'IMAGE_GEN_UNKNOWN_MODEL' },+ );+ }+ const selectedModel = allModels.find((m) => m.id === data.modelId)+ ?? allModels.find((m) => m.id === 'dev')+ ?? allModels[0];+ if (selectedModel && !isFlux2(selectedModel) && !py) {+ throw new ServerError(+ 'Local image generation is not configured (settings.imageGen.local.pythonPath is missing).',+ { status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' },+ );+ }+ const { jobId, position, status } = enqueueJob({+ kind: 'image',+ params: { pythonPath: py, ...data },+ });+ // Surface the effective model so the response matches the+ // non-queued path's `model` field. Use the same `selectedModel`+ // resolution as the validation block above so the response reflects+ // the actual fallback chain (caller modelId → 'dev' → allModels[0])+ // rather than just the requested id.+ return res.json({+ jobId,+ generationId: jobId,+ filename: `${jobId}.png`,+ path: `/data/images/${jobId}.png`,+ mode: 'local',+ model: selectedModel?.id || data.modelId || 'dev',+ status,+ position,+ });+ }res.json(await imageGen.generateImage(data));}));@@ -160,17 +213,39 @@ router.get('/gallery', asyncHandler(async (_req, res) => {res.json(await local.listGallery());}));-// SSE progress stream. Local + Codex both produce job-keyed SSE; the-// dispatcher picks the right provider for whichever owns the job.+// SSE progress stream. Local renders run via the mediaJobQueue and emit+// `queued` → `started` → `progress` → `complete` events; the queue owns the+// SSE attachment for those. Codex still produces job-keyed SSE through its+// own provider — fall through to the dispatcher when the queue doesn't know+// the job. External backend has no SSE (it's blocking).router.get('/:jobId/events', (req, res) => {- const ok = imageGen.attachSseClient(req.params.jobId, res);- if (!ok) res.status(404).json({ error: 'Job not found or expired' });+ if (attachQueueSseClient(req.params.jobId, res)) return;+ if (imageGen.attachSseClient(req.params.jobId, res)) return;+ res.status(404).json({ error: 'Job not found or expired' });});-router.post('/cancel', (_req, res) => {+router.post('/cancel', asyncHandler(async (req, res) => {+ // Cancel selection rules, in priority order:+ // 1. Explicit body.jobId — cancel that queued/running local image job.+ // Required for users with multiple in-flight renders.+ // 2. No jobId — cancel the newest queued/running local image job (most+ // recent activity wins, matching the user's last "submit" gesture).+ // 3. No queue match — fall through to the codex-mode cancel.+ const requestedJobId = typeof req.body?.jobId === 'string' && req.body.jobId.trim()+ ? req.body.jobId.trim()+ : undefined;+ const cancellable = listJobs({ kind: 'image' })+ .filter((j) => j.status === 'queued' || j.status === 'running');+ if (requestedJobId) {+ const target = cancellable.find((j) => j.id === requestedJobId);+ if (target) return res.json(await cancelJob(target.id));+ // jobId not in our queue — fall through (could be a codex job).+ } else if (cancellable.length) {+ return res.json(await cancelJob(cancellable[cancellable.length - 1].id));+ }const cancelled = imageGen.cancel();res.json({ ok: cancelled });-});+}));router.delete('/:filename', asyncHandler(async (req, res) => {res.json(await local.deleteImage(req.params.filename));diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex cfd189fae7..fe5fa91e37 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -18,7 +18,22 @@ vi.mock('../services/imageGen/index.js', () => ({},}));+// Default to external mode in tests so /generate goes through the dispatcher.+// Local-mode tests below override the settings mock to flip into queue mode.+vi.mock('../services/settings.js', () => ({+ getSettings: vi.fn(async () => ({ imageGen: { mode: 'external' } })),+}));++vi.mock('../services/mediaJobQueue/index.js', () => ({+ enqueueJob: vi.fn(({ kind }) => ({ jobId: `mock-${kind}-job`, position: 1, status: 'queued' })),+ attachSseClient: vi.fn(() => false),+ cancelJob: vi.fn(async () => ({ ok: true, status: 'canceling' })),+ listJobs: vi.fn(() => []),+}));+import * as imageGen from '../services/imageGen/index.js';+import * as mediaJobQueue from '../services/mediaJobQueue/index.js';+import { getSettings } from '../services/settings.js';describe('Image Gen Routes', () => {let app;@@ -121,6 +136,69 @@ describe('Image Gen Routes', () => {expect.objectContaining({ prompt: 'test', width: 512, height: 768, steps: 30, cfgScale: 7, seed: 42 }));});++ // Local mode goes through the mediaJobQueue rather than calling+ // generateImage synchronously; the route returns immediately with+ // { jobId, status: 'queued', position } so the UI can attach SSE.+ it('local mode enqueues through mediaJobQueue and returns queued status', async () => {+ getSettings.mockResolvedValueOnce({ imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3' } } });+ mediaJobQueue.enqueueJob.mockReturnValueOnce({ jobId: 'queued-job-001', position: 1, status: 'queued' });++ const response = await request(app)+ .post('/api/image-gen/generate')+ .send({ prompt: 'a fox in a forest' });++ expect(response.status).toBe(200);+ expect(response.body.status).toBe('queued');+ expect(response.body.position).toBe(1);+ expect(response.body.mode).toBe('local');+ expect(response.body.jobId).toBe('queued-job-001');+ expect(response.body.generationId).toBe('queued-job-001');+ expect(response.body.path).toBe('/data/images/queued-job-001.png');+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'image',+ params: expect.objectContaining({ prompt: 'a fox in a forest', pythonPath: '/usr/bin/python3' }),+ }));+ // Synchronous generateImage MUST NOT be called in local mode — the+ // queue takes ownership of the job lifecycle.+ expect(imageGen.generateImage).not.toHaveBeenCalled();+ });++ // The per-request `mode` override flips into queue mode even when the+ // saved default is external — protects against future regressions where+ // someone hard-codes settings.imageGen.mode as the only mode source.+ it('per-request mode=local override enqueues even when settings default is external', async () => {+ // Local mode now validates pythonPath up-front (mflux model needs it),+ // so the test must supply a configured local section. The override+ // contract — explicit `mode: 'local'` flips into queue mode regardless+ // of the saved default — is still what's being asserted here.+ getSettings.mockResolvedValueOnce({ imageGen: { mode: 'external', local: { pythonPath: '/usr/bin/python3' } } });+ mediaJobQueue.enqueueJob.mockReturnValueOnce({ jobId: 'queued-job-002', position: 2, status: 'queued' });++ const response = await request(app)+ .post('/api/image-gen/generate')+ .send({ prompt: 'a wizard tower', mode: 'local' });++ expect(response.status).toBe(200);+ expect(response.body.status).toBe('queued');+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({ kind: 'image' }));+ expect(imageGen.generateImage).not.toHaveBeenCalled();+ });++ // Local mode without a configured pythonPath now rejects up-front (400)+ // rather than enqueueing a job that can never run. The queue is meant to+ // serialize concurrent renders, not to absorb hard configuration errors.+ it('local mode with missing pythonPath returns 400 IMAGE_GEN_NOT_CONFIGURED', async () => {+ getSettings.mockResolvedValueOnce({ imageGen: { mode: 'local' } }); // no `local.pythonPath`++ const response = await request(app)+ .post('/api/image-gen/generate')+ .send({ prompt: 'a fox in a forest' });++ expect(response.status).toBe(400);+ expect(response.body.error).toMatch(/not configured/i);+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();+ });});describe('POST /api/image-gen/avatar', () => {diff --git a/server/routes/mediaJobs.js b/server/routes/mediaJobs.jsnew file mode 100644index 0000000000..db307f9d13--- /dev/null+++ b/server/routes/mediaJobs.js@@ -0,0 +1,88 @@+/**+ * Media Job Queue Routes — read + cancel access to the unified image/video+ * render queue. The actual enqueueing happens in /api/video-gen and+ * /api/image-gen routes; this surface lets the UI show what's pending and+ * cancel something without going through provider-specific endpoints.+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import { listJobs, getJob, cancelJob, JOB_KINDS, JOB_STATUSES } from '../services/mediaJobQueue/index.js';++const router = Router();++const listQuerySchema = z.object({+ status: z.enum(JOB_STATUSES).optional(),+ kind: z.enum(JOB_KINDS).optional(),+ owner: z.string().max(256).optional(),+});++// Sanitize a job before serialization. The internal job record carries+// worker-only data (the python interpreter path, absolute filesystem paths+// to multipart uploads / source images) that the UI doesn't need and that+// shouldn't ride out over the API. Only surface the user-visible params+// the Render Queue UI actually renders (prompt, owner-supplied settings).+const PARAM_ALLOWLIST = new Set([+ 'prompt', 'negativePrompt', 'modelId',+ 'width', 'height', 'numFrames', 'fps', 'steps', 'guidanceScale',+ 'seed', 'tiling', 'disableAudio', 'mode', 'imageStrength',+ 'cfgScale', 'guidance', 'quantize',+]);+function sanitizeJob(job) {+ if (!job) return job;+ const safeParams = job.params+ ? Object.fromEntries(Object.entries(job.params).filter(([k]) => PARAM_ALLOWLIST.has(k)))+ : undefined;+ return {+ id: job.id,+ kind: job.kind,+ owner: job.owner,+ status: job.status,+ queuedAt: job.queuedAt,+ startedAt: job.startedAt,+ completedAt: job.completedAt,+ position: job.position,+ error: job.error,+ result: job.result,+ params: safeParams,+ };+}++router.get('/', asyncHandler(async (req, res) => {+ const filters = validateRequest(listQuerySchema, req.query);+ // Most-recent activity first across all statuses. Live (queued/running)+ // jobs land at the top by virtue of having the freshest `startedAt` /+ // `queuedAt`. The fallback chain is `startedAt → completedAt → queuedAt`+ // so terminal jobs that never started (queued→canceled, or failed by+ // boot recovery) sort by their cancel/finish time, not the original+ // enqueue time.+ const sorted = [...listJobs(filters)].sort((a, b) => {+ const ta = new Date(a.startedAt || a.completedAt || a.queuedAt || 0).getTime();+ const tb = new Date(b.startedAt || b.completedAt || b.queuedAt || 0).getTime();+ return tb - ta;+ });+ res.json(sorted.map(sanitizeJob));+}));++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' });+ res.json(sanitizeJob(job));+}));++router.post('/:id/cancel', asyncHandler(async (req, res) => {+ const result = await cancelJob(req.params.id);+ if (!result.ok) {+ // Distinguish "no such id" (404) from "exists but already terminal"+ // (409) so consumers can react appropriately — e.g. the UI doesn't+ // need to display "Not found" when the user just clicked Cancel+ // again on a job that already finished.+ const status = result.code === 'ALREADY_TERMINAL' ? 409 : 404;+ throw new ServerError(result.error || 'Cancel failed', { status, code: result.code || 'NOT_FOUND' });+ }+ res.json(result);+}));++export default router;diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex f57fe0491d..e5b68c898b 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -8,25 +8,24 @@import { Router } from 'express';import { existsSync, statSync } from 'fs';-import { unlink } from 'fs/promises';-import { join, basename, resolve as resolvePath, sep as PATH_SEP } from 'path';+import { copyFile, unlink } from 'fs/promises';+import { randomUUID } from 'crypto';+import { join, basename, resolve as resolvePath, sep as PATH_SEP, extname } from 'path';import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { uploadSingle } from '../lib/multipart.js';-import { PATHS } from '../lib/fileUtils.js';+import { PATHS, ensureDir } from '../lib/fileUtils.js';import { getSettings } from '../services/settings.js';import {listVideoModels,defaultVideoModelId,- generateVideo,- attachSseClient,- cancel,loadHistory,deleteHistoryItem,setHistoryItemHidden,extractLastFrame,stitchVideos,} from '../services/videoGen/local.js';+import { enqueueJob, attachSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';const router = Router();@@ -114,23 +113,74 @@ const resolveGalleryImage = (name) => {};router.post('/', sourceImageUpload, asyncHandler(async (req, res) => {+ // Pre-enqueue cleanup hook: every throw path below MUST drop the multipart+ // temp upload (Multer wrote it before this handler ran). Without this a+ // configuration/validation error leaks the upload in the OS temp dir.+ const cleanupTempUpload = async () => {+ if (req.file?.path) await unlink(req.file.path).catch(() => {});+ };const parsed = generateBodySchema.safeParse(req.body);if (!parsed.success) {+ await cleanupTempUpload();throw new ServerError(`Validation failed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ')}`, { status: 400, code: 'VALIDATION_ERROR' });}const body = parsed.data;const s = await getSettings();const pythonPath = s.imageGen?.local?.pythonPath || null;+ // Reject up-front when the local python isn't configured. Without this,+ // the queue would happily accept the job, return 200/queued, and only+ // surface the failure asynchronously on SSE — which then pollutes the+ // persisted queue with a doomed entry.+ if (!pythonPath) {+ await cleanupTempUpload();+ throw new ServerError(+ 'Local video generation is not configured (settings.imageGen.local.pythonPath is missing).',+ { status: 400, code: 'VIDEO_GEN_NOT_CONFIGURED' },+ );+ }+ // Validate modelId synchronously (when supplied). Without this the queue+ // would happily accept a typo'd modelId and fail asynchronously inside+ // the worker — leaving a persisted, doomed queue entry.+ if (body.modelId) {+ const known = listVideoModels();+ if (!known.some((m) => m.id === body.modelId)) {+ await cleanupTempUpload();+ throw new ServerError(+ `Unknown modelId: ${body.modelId}`,+ { status: 400, code: 'VIDEO_GEN_UNKNOWN_MODEL' },+ );+ }+ }let sourceImagePath = null;let uploadedTempPath = null;if (req.file) {- sourceImagePath = req.file.path;- // Hand the multipart upload's temp path to the service so it can unlink- // it in the proc.on('close') cleanup — covers both the success path- // (after ffmpeg consumed it for resize) and the no-ffmpeg fallback path- // (where the python child reads it directly and we can't unlink earlier).- uploadedTempPath = req.file.path;+ // Copy the multipart upload into a durable location under data/uploads+ // before enqueueing. The Multer temp file lives in the OS temp dir —+ // which gets reaped by macOS on reboot, and might be missing entirely+ // when the queue replays a persisted `queued` job after a server+ // restart. Copying here gives the worker a stable path that survives+ // restarts; the worker unlinks it on completion or cancel.+ await ensureDir(PATHS.uploads);+ const ext = extname(req.file.originalname || req.file.path) || '.bin';+ const durablePath = join(PATHS.uploads, `video-source-${randomUUID()}${ext}`);+ // copyFile can throw on disk-full / permission errors. If it does we+ // need to clean up: drop the multipart temp upload AND the half-written+ // durablePath (copyFile may have created a zero-byte sentinel before+ // bailing). Without this, a failed POST leaks files in /tmp + data/uploads.+ try {+ await copyFile(req.file.path, durablePath);+ } catch (err) {+ await unlink(durablePath).catch(() => {});+ await cleanupTempUpload();+ throw new ServerError(+ `Failed to stage upload to durable location: ${err.message}`,+ { status: 500, code: 'VIDEO_GEN_UPLOAD_STAGE_FAILED' },+ );+ }+ await unlink(req.file.path).catch(() => {});+ sourceImagePath = durablePath;+ uploadedTempPath = durablePath;} else if (body.sourceImageFile) {sourceImagePath = resolveGalleryImage(body.sourceImageFile);}@@ -138,8 +188,11 @@ router.post('/', sourceImageUpload, asyncHandler(async (req, res) => {// FFLF end-frame: gallery-pick only. Same path-traversal guard.const lastImagePath = body.lastImageFile ? resolveGalleryImage(body.lastImageFile) : null;- try {- const result = await generateVideo({+ // Enqueue rather than spawn synchronously — the mediaJobQueue worker will+ // run this when no other render is in flight. Caller never sees BUSY.+ const { jobId, position, status } = enqueueJob({+ kind: 'video',+ params: {pythonPath,prompt: body.prompt,negativePrompt: body.negativePrompt || '',@@ -158,14 +211,15 @@ router.post('/', sourceImageUpload, asyncHandler(async (req, res) => {lastImagePath,mode: body.mode,imageStrength: body.imageStrength,- });- res.json(result);- } catch (err) {- // generateVideo threw before scheduling the proc.on('close') cleanup- // (e.g. PYTHON not configured, BUSY, validation) — drop the upload now.- if (uploadedTempPath) await unlink(uploadedTempPath).catch(() => {});- throw err;- }+ },+ });+ // Match the legacy response shape (jobId, generationId, filename, model,+ // mode) so existing client code keeps working; add status+position for+ // the queue. Resolve the effective model NOW — when modelId is omitted+ // the worker will default it inside generateVideo, but the response+ // needs to surface what the gallery / history will record.+ const effectiveModel = body.modelId || defaultVideoModelId();+ res.json({ jobId, generationId: jobId, filename: `${jobId}.mp4`, model: effectiveModel, mode: 'local', status, position });}));router.get('/:jobId/events', (req, res) => {@@ -173,10 +227,34 @@ router.get('/:jobId/events', (req, res) => {if (!ok) res.status(404).json({ error: 'Job not found or expired' });});-router.post('/cancel', (_req, res) => {- const cancelled = cancel();- res.json({ ok: cancelled });-});+router.post('/cancel', asyncHandler(async (req, res) => {+ // Cancel selection rules, in priority order:+ // 1. Explicit body.jobId — cancel exactly that job (queued or running).+ // Required for users with multiple in-flight renders.+ // 2. No jobId — cancel the currently-running video job (legacy behavior).+ // 3. No running job — cancel the newest queued video job so the user can+ // take back a submission they regret while it's still in line.+ const requestedJobId = typeof req.body?.jobId === 'string' && req.body.jobId.trim()+ ? req.body.jobId.trim()+ : undefined;+ if (requestedJobId) {+ // Validate that the jobId is a video job before cancelling, so a stray+ // image jobId from another tab doesn't accidentally cancel here.+ const job = listJobs({ kind: 'video' }).find((j) => j.id === requestedJobId);+ if (!job) return res.json({ ok: false, reason: 'video job not found' });+ if (job.status !== 'queued' && job.status !== 'running') {+ return res.json({ ok: false, reason: `job already ${job.status}` });+ }+ return res.json(await cancelJob(job.id));+ }+ const running = listJobs({ kind: 'video', status: 'running' });+ if (running.length) return res.json(await cancelJob(running[0].id));+ // No running render — cancel the newest queued video instead so the user+ // can pull back a submission before it starts.+ const queued = listJobs({ kind: 'video', status: 'queued' });+ if (queued.length) return res.json(await cancelJob(queued[queued.length - 1].id));+ res.json({ ok: false, reason: 'no active or queued video render' });+}));router.get('/history', asyncHandler(async (_req, res) => {res.json(await loadHistory());diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex ee044dbc3c..06933cf721 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -9,15 +9,24 @@ vi.mock('../services/settings.js', () => ({vi.mock('../services/videoGen/local.js', () => ({listVideoModels: vi.fn(() => [{ id: 'ltx2_unified', name: 'LTX-2 Unified' }]),defaultVideoModelId: vi.fn(() => 'ltx2_unified'),- generateVideo: vi.fn(),- attachSseClient: vi.fn(() => false),- cancel: vi.fn(() => true),loadHistory: vi.fn(async () => []),deleteHistoryItem: vi.fn(async (id) => ({ ok: true, id })),+ // The route imports setHistoryItemHidden too — without this entry, ESM+ // module linking fails when the route is loaded inside the test process.+ setHistoryItemHidden: vi.fn(async (id, hidden) => ({ ok: true, id, hidden })),extractLastFrame: vi.fn(),stitchVideos: vi.fn(),}));+// Render submissions go through the mediaJobQueue. Mock its surface so the+// route tests stay synchronous and don't kick off the worker loop.+vi.mock('../services/mediaJobQueue/index.js', () => ({+ enqueueJob: vi.fn(({ kind, params }) => ({ jobId: `mock-${kind}-job`, position: 1, status: 'queued' })),+ attachSseClient: vi.fn(() => false),+ cancelJob: vi.fn(async () => ({ ok: true, status: 'canceling' })),+ listJobs: vi.fn(() => []),+}));+vi.mock('../lib/multipart.js', () => ({// Bypass the multipart parser for unit tests — handler treats req.file as// optional, and we exercise the no-upload path here.@@ -38,6 +47,7 @@ vi.mock('fs', () => ({vi.mock('fs/promises', () => ({ unlink: vi.fn(async () => {}) }));import * as videoGenService from '../services/videoGen/local.js';+import * as mediaJobQueue from '../services/mediaJobQueue/index.js';import videoGenRoutes from './videoGen.js';describe('videoGen routes', () => {@@ -87,7 +97,6 @@ describe('videoGen routes', () => {});it('accepts empty-string numerics as undefined (multipart preprocess fix)', async () => {- videoGenService.generateVideo.mockResolvedValue({ jobId: 'j1', filename: 'j1.mp4' });const r = await request(app).post('/api/video-gen/').send({prompt: 'a cat',width: '',@@ -95,16 +104,19 @@ describe('videoGen routes', () => {seed: '',});expect(r.status).toBe(200);- expect(videoGenService.generateVideo).toHaveBeenCalledWith(expect.objectContaining({- prompt: 'a cat',- width: undefined,- height: undefined,- seed: undefined,+ expect(r.body.status).toBe('queued');+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'video',+ params: expect.objectContaining({+ prompt: 'a cat',+ width: undefined,+ height: undefined,+ seed: undefined,+ }),}));});it('strips path-traversal segments from sourceImageFile via basename + prefix-check', async () => {- videoGenService.generateVideo.mockResolvedValue({ jobId: 'j2', filename: 'j2.mp4' });const r = await request(app).post('/api/video-gen/').send({prompt: 'a cat',sourceImageFile: '../../etc/passwd',@@ -113,15 +125,15 @@ describe('videoGen routes', () => {// path is `/mock/images/passwd` (under PATHS.images). The route does// NOT 400 — it just consumes whatever's safely under the images root.// What this test really locks in: the request succeeds + the route- // never reads outside PATHS.images.+ // never enqueues a job that points outside PATHS.images.expect(r.status).toBe(200);- expect(videoGenService.generateVideo).toHaveBeenCalledWith(expect.objectContaining({- prompt: 'a cat',+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'video',+ params: expect.objectContaining({ prompt: 'a cat' }),}));});it('forwards lastImageFile + mode for FFLF', async () => {- videoGenService.generateVideo.mockResolvedValue({ jobId: 'j3', filename: 'j3.mp4' });const r = await request(app).post('/api/video-gen/').send({prompt: 'morph between two scenes',sourceImageFile: 'first.png',@@ -129,15 +141,14 @@ describe('videoGen routes', () => {mode: 'fflf',});expect(r.status).toBe(200);- // Locks in the new request-field plumbing: lastImageFile becomes- // lastImagePath resolved under PATHS.images, and the mode hint flows- // through to the service. existsSync + PATHS.images are mocked so the- // resolver returns deterministic paths.- expect(videoGenService.generateVideo).toHaveBeenCalledWith(expect.objectContaining({- prompt: 'morph between two scenes',- sourceImagePath: '/mock/images/first.png',- lastImagePath: '/mock/images/last.png',- mode: 'fflf',+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'video',+ params: expect.objectContaining({+ prompt: 'morph between two scenes',+ sourceImagePath: '/mock/images/first.png',+ lastImagePath: '/mock/images/last.png',+ mode: 'fflf',+ }),}));});@@ -149,11 +160,23 @@ describe('videoGen routes', () => {expect(r.status).toBe(400);expect(r.body.error).toMatch(/mode/i);});++ // Pre-enqueue config validation: without pythonPath the queue would+ // accept the job, return 200/queued, then fail asynchronously over SSE+ // and pollute the persisted queue with a doomed entry.+ it('rejects 400 VIDEO_GEN_NOT_CONFIGURED when pythonPath is missing', async () => {+ const settingsMock = await import('../services/settings.js');+ settingsMock.getSettings.mockResolvedValueOnce({ imageGen: { local: {} } });+ const r = await request(app).post('/api/video-gen/').send({ prompt: 'a cat' });+ expect(r.status).toBe(400);+ expect(r.body.error).toMatch(/not configured/i);+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();+ });});describe('GET /:jobId/events', () => {it('returns 404 when the job is unknown', async () => {- videoGenService.attachSseClient.mockReturnValue(false);+ mediaJobQueue.attachSseClient.mockReturnValue(false);const r = await request(app).get('/api/video-gen/unknown-job/events');expect(r.status).toBe(404);expect(r.body.error).toMatch(/not found/i);@@ -161,11 +184,59 @@ describe('videoGen routes', () => {});describe('POST /cancel', () => {- it('returns the cancel result', async () => {- videoGenService.cancel.mockReturnValue(true);+ it('reports nothing to cancel when no video render is running', async () => {+ mediaJobQueue.listJobs.mockReturnValue([]);+ const r = await request(app).post('/api/video-gen/cancel').send({});+ expect(r.status).toBe(200);+ expect(r.body.ok).toBe(false);+ });++ it('cancels the running video render through the queue', async () => {+ mediaJobQueue.listJobs.mockReturnValue([{ id: 'running-job', kind: 'video', status: 'running' }]);+ mediaJobQueue.cancelJob.mockResolvedValue({ ok: true, status: 'canceling' });+ const r = await request(app).post('/api/video-gen/cancel').send({});+ expect(r.status).toBe(200);+ expect(r.body.ok).toBe(true);+ expect(mediaJobQueue.cancelJob).toHaveBeenCalledWith('running-job');+ });++ // jobId in the body cancels a specific job, even if it's still queued.+ it('cancels a specific queued job when jobId is supplied', async () => {+ const jobs = [+ { id: 'running-1', kind: 'video', status: 'running' },+ { id: 'queued-2', kind: 'video', status: 'queued' },+ ];+ // The route calls listJobs({ kind: 'video' }) — replicate the production+ // queue's filter semantics (status filter is optional).+ mediaJobQueue.listJobs.mockImplementation(({ status, kind } = {}) => jobs.filter((j) => {+ if (status && j.status !== status) return false;+ if (kind && j.kind !== kind) return false;+ return true;+ }));+ mediaJobQueue.cancelJob.mockResolvedValue({ ok: true, status: 'canceled' });+ const r = await request(app).post('/api/video-gen/cancel').send({ jobId: 'queued-2' });+ expect(r.status).toBe(200);+ expect(r.body.ok).toBe(true);+ expect(mediaJobQueue.cancelJob).toHaveBeenCalledWith('queued-2');+ });++ // No running job and no jobId — fall back to newest queued so the user+ // can pull back a recent submission before it starts.+ it('falls back to newest queued video when no jobId and nothing is running', async () => {+ const jobs = [+ { id: 'queued-old', kind: 'video', status: 'queued' },+ { id: 'queued-new', kind: 'video', status: 'queued' },+ ];+ mediaJobQueue.listJobs.mockImplementation(({ status, kind } = {}) => jobs.filter((j) => {+ if (status && j.status !== status) return false;+ if (kind && j.kind !== kind) return false;+ return true;+ }));+ mediaJobQueue.cancelJob.mockResolvedValue({ ok: true, status: 'canceled' });const r = await request(app).post('/api/video-gen/cancel').send({});expect(r.status).toBe(200);expect(r.body.ok).toBe(true);+ expect(mediaJobQueue.cancelJob).toHaveBeenCalledWith('queued-new');});});diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 361cda36bd..aa4bcae597 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -1068,6 +1068,18 @@ export async function handleAgentCompletion(agentId, exitCode, success, durationawait handlePipelineProgression(task, agentId, effectiveSuccess);}+ // Advance Creative Director task chain if applicable. After a Creative+ // Director agent task (treatment or evaluate) finishes, the orchestrator+ // decides what comes next and enqueues it. Scene rendering and final+ // stitching run server-side rather than as separate CoS tasks, so they+ // never reach this hook directly. Failure marks the project failed; the+ // user can resume from the UI.+ if (task?.metadata?.creativeDirector) {+ const { handleCreativeDirectorCompletion } = await import('./creativeDirector/completionHook.js');+ handleCreativeDirectorCompletion(task, agentId, effectiveSuccess)+ .catch((err) => console.log(`⚠️ creativeDirector completion hook failed: ${err.message}`));+ }+// Clean up ephemeral BTW.md before worktree removalawait cleanupBtwFile(agentState?.metadata?.workspacePath);diff --git a/server/services/creativeDirector/agentBridge.js b/server/services/creativeDirector/agentBridge.jsnew file mode 100644index 0000000000..b57d47449e--- /dev/null+++ b/server/services/creativeDirector/agentBridge.js@@ -0,0 +1,91 @@+/**+ * Creative Director — CoS agent task bridge.+ *+ * Only spawns agents for the COGNITIVE steps in the pipeline:+ * - `treatment`: write the story + scene plan (one per project)+ * - `evaluate` : read a rendered scene's thumbnail and judge it against+ * the style spec + scene intent (one per scene render)+ *+ * The mechanical steps (per-scene render orchestration, concat stitch) run+ * server-side via sceneRunner / stitchRunner — they don't need an LLM.+ * That cuts agent runtime from ~3 minutes per scene down to ~30 seconds.+ *+ * Tasks set `useWorktree: false` because render evaluation is file-based,+ * not git-based.+ */++import { randomUUID } from 'crypto';+import { addTask, cosEvents } from '../cos.js';+import { buildTreatmentPrompt, buildEvaluatePrompt } from '../../lib/creativeDirectorPrompts.js';+import { recordRun } from './local.js';++function buildTaskRecord(project, kind, scene, context) {+ const taskId = `cd-${project.id}-${kind}-${Date.now().toString(36)}`;+ const runId = randomUUID();+ return {+ id: taskId,+ runId,+ record: {+ id: taskId,+ status: 'pending',+ priority: 'MEDIUM',+ priorityValue: 2,+ description: buildDescription(project, kind, scene),+ metadata: {+ creativeDirector: {+ projectId: project.id,+ kind,+ sceneId: scene?.sceneId || null,+ runId,+ },+ context,+ useWorktree: false,+ readOnly: false,+ },+ approvalRequired: false,+ autoApproved: true,+ section: 'pending',+ },+ };+}++function buildDescription(project, kind, scene) {+ if (kind === 'treatment') {+ return `Creative Director — Treatment for "${project.name}"`;+ }+ if (kind === 'evaluate' && scene) {+ const total = project.treatment?.scenes?.length || '?';+ const intent = (scene.intent || '').slice(0, 60);+ return `Creative Director — Evaluate Scene ${scene.order + 1}/${total}: "${intent}" (${project.name})`;+ }+ return `Creative Director — ${kind} for "${project.name}"`;+}++async function persistAndEmit({ id, runId, record }, project, kind, sceneId) {+ // Record the run as `running` up-front so the Runs tab shows in-flight+ // state immediately. completionHook updates the same runId on finish.+ await recordRun(project.id, {+ runId,+ taskId: id,+ kind,+ sceneId: sceneId || null,+ status: 'running',+ }).catch((err) => console.log(`⚠️ CD recordRun(running) failed: ${err.message}`));+ await addTask(record, 'internal', { raw: true });+ cosEvents.emit('task:ready', record);+ console.log(`📤 CD task enqueued: ${id} (${kind}${sceneId ? ` for ${sceneId}` : ''} on ${project.id})`);+ return record;+}++export async function enqueueTreatmentTask(project) {+ const context = buildTreatmentPrompt(project);+ const built = buildTaskRecord(project, 'treatment', null, context);+ return persistAndEmit(built, project, 'treatment', null);+}++export async function enqueueEvaluateTask(project, scene) {+ if (!scene) throw new Error('enqueueEvaluateTask: scene is required');+ const context = buildEvaluatePrompt(project, scene);+ const built = buildTaskRecord(project, 'evaluate', scene, context);+ return persistAndEmit(built, project, 'evaluate', scene.sceneId);+}diff --git a/server/services/creativeDirector/completionHook.js b/server/services/creativeDirector/completionHook.jsnew file mode 100644index 0000000000..a6ca822d5a--- /dev/null+++ b/server/services/creativeDirector/completionHook.js@@ -0,0 +1,186 @@+/**+ * Creative Director — task-completion hook.+ *+ * Called from agentLifecycle.handleAgentCompletion when a finished agent+ * task carries `metadata.creativeDirector`. The hook decides what (if+ * anything) happens next based on the project's current state.+ *+ * Flow under the new architecture:+ * - treatment task done → kick off render for scene 1 (server-side, no+ * agent task) via sceneRunner.runSceneRender.+ * - evaluate task done → look at the scene's verdict:+ * * `accepted` → run the next pending scene, OR if all done, run+ * the stitch (server-side, no agent task).+ * * `pending` → the agent requested a re-render with a new+ * prompt; run scene render again.+ * * `failed` → continue on to the next scene (one bad render+ * shouldn't kill the whole project) OR mark project+ * failed if NO scene was ever accepted.+ *+ * `advanceAfterSceneSettled` is also exported for sceneRunner to call+ * directly when a render fails terminally (no evaluate task is spawned in+ * that case).+ */++import { getProject, updateProject, updateRun, recordRun } from './local.js';+import { enqueueTreatmentTask } from './agentBridge.js';+import { runSceneRender } from './sceneRunner.js';+import { runStitch } from './stitchRunner.js';++export async function handleCreativeDirectorCompletion(task, agentId, success) {+ const meta = task?.metadata?.creativeDirector;+ if (!meta?.projectId) return;+ const project = await getProject(meta.projectId).catch(() => null);+ if (!project) {+ console.log(`⚠️ CD completion hook: project ${meta.projectId} not found`);+ return;+ }++ // Update / create the run record so the Runs tab reflects this agent run.+ const completedAt = new Date().toISOString();+ const runId = meta.runId;+ const updatedExisting = runId+ ? await updateRun(project.id, runId, {+ agentId,+ status: success ? 'completed' : 'failed',+ completedAt,+ kind: meta.kind,+ sceneId: meta.sceneId || null,+ taskId: task.id,+ })+ : null;+ if (!updatedExisting) {+ await recordRun(project.id, {+ runId: runId || undefined,+ agentId,+ taskId: task.id,+ kind: meta.kind,+ sceneId: meta.sceneId || null,+ status: success ? 'completed' : 'failed',+ completedAt,+ }).catch((err) => console.log(`⚠️ CD recordRun failed: ${err.message}`));+ }++ if (!success) {+ // Surface a concrete reason on the project so the UI's failure banner+ // has actionable context. Without this, a project flips to 'failed'+ // with whatever stale failureReason it had before (often null), and+ // the user has no idea what happened.+ const reason = `${meta.kind} agent task failed (taskId=${task.id || '?'}, agent=${agentId || '?'})`;+ await updateProject(project.id, { status: 'failed', failureReason: reason })+ .catch((e) => console.log(`⚠️ CD updateProject(failed) for ${project.id} failed: ${e.message}`));+ console.log(`❌ CD project ${project.id} marked failed (task ${meta.kind} failed)`);+ return;+ }++ const fresh = await getProject(project.id);+ if (!fresh) return;+ if (fresh.status === 'paused' || fresh.status === 'failed') return;++ // Always advance — advanceAfterSceneSettled is idempotent and inspects+ // project state to decide what comes next. Calling it for unknown kinds+ // (e.g. legacy 'scene' tasks from before the treatment/evaluate split)+ // makes the system self-healing rather than silently getting stuck.+ return advanceAfterSceneSettled(fresh.id);+}++/**+ * Look at the project's scene state and decide what to do next.+ * Called from:+ * - completionHook on `treatment` and `evaluate` task completion.+ * - sceneRunner when a render fails terminally (no evaluate task spawned).+ */+// In-memory dedup. The status field doesn't fully cover this — `planning`+// gets set just before enqueueing the treatment task, and `stitching` just+// before runStitch starts the timeline render. A second concurrent+// invocation between updateProject and enqueue/runStitch would bypass the+// status guard. These per-projectId Sets close the window. Cleared after+// the corresponding async work returns or on failure.+const inflightTreatment = new Set();+const inflightStitch = new Set();++export async function advanceAfterSceneSettled(projectId) {+ const project = await getProject(projectId);+ if (!project) return;+ if (project.status === 'paused' || project.status === 'failed') return;++ // No treatment yet → enqueue treatment task.+ if (!project.treatment) {+ // Skip if status is already `planning` (a treatment task is in flight)+ // OR our in-memory dedup set has this project (covers the+ // updateProject→enqueueTreatmentTask window between two concurrent+ // advance calls).+ if (project.status === 'planning' || inflightTreatment.has(projectId)) return;+ inflightTreatment.add(projectId);+ await updateProject(project.id, { status: 'planning' })+ .catch((e) => { inflightTreatment.delete(projectId); throw e; });+ const fresh = await getProject(project.id);+ await enqueueTreatmentTask(fresh)+ .finally(() => inflightTreatment.delete(projectId));+ return;+ }++ // Find next pending scene. nextPendingScene returns the lowest-order+ // scene whose status is pending/rendering/evaluating — but since+ // sceneRunner sets status='rendering' the moment it kicks off, and+ // 'evaluating' once the render completes, we want the lowest-order scene+ // whose status is exactly 'pending' (i.e. not yet started OR+ // re-requested by the evaluator).+ const scenes = (project.treatment.scenes || []).slice().sort((a, b) => a.order - b.order);+ const nextPending = scenes.find((s) => s.status === 'pending');+ if (nextPending) {+ if (project.status !== 'rendering') {+ await updateProject(project.id, { status: 'rendering' });+ }+ const updated = await getProject(project.id);+ // Re-read may return null if the project was deleted between calls,+ // or sceneFresh may be undefined if the treatment was rewritten+ // concurrently. Bail rather than passing null/undefined into+ // runSceneRender (which would crash on the first .property access).+ const sceneFresh = updated?.treatment?.scenes?.find((s) => s.sceneId === nextPending.sceneId);+ if (!updated || !sceneFresh) {+ console.log(`⚠️ CD advance: project ${projectId} or scene ${nextPending.sceneId} disappeared between reads — bailing`);+ return;+ }+ await runSceneRender(updated, sceneFresh);+ return;+ }++ // No pending scenes — but maybe one is mid-flight (rendering / evaluating)?+ // Don't double-trigger; just wait for it to settle and re-fire this hook.+ const inflight = scenes.find((s) => s.status === 'rendering' || s.status === 'evaluating');+ if (inflight) {+ console.log(`⏳ CD project ${projectId}: scene ${inflight.sceneId} is ${inflight.status} — waiting for it to settle`);+ return;+ }++ // All scenes terminal. If at least one was accepted, stitch; else fail.+ const accepted = scenes.filter((s) => s.status === 'accepted');+ if (!accepted.length) {+ await updateProject(project.id, { status: 'failed' })+ .catch((e) => console.log(`⚠️ CD updateProject(failed) for ${projectId} failed: ${e.message}`));+ console.log(`❌ CD project ${projectId}: every scene failed — marking project failed`);+ return;+ }+ if (project.finalVideoId) {+ if (project.status !== 'complete') {+ await updateProject(project.id, { status: 'complete' });+ }+ return;+ }+ // Run stitch (programmatic, no agent task). Skip if already stitching+ // OR if a stitch is in flight from a concurrent advance call (the+ // status flip to 'stitching' happens inside runStitch, leaving a window+ // where two callers could both reach this line).+ if (project.status === 'stitching' || inflightStitch.has(projectId)) return;+ inflightStitch.add(projectId);+ await runStitch(projectId).finally(() => inflightStitch.delete(projectId));+}++/**+ * Convenience: kick off the project from the user's "Start" button. Skips+ * straight to advancing.+ */+export async function startCreativeDirectorProject(projectId) {+ return advanceAfterSceneSettled(projectId);+}diff --git a/server/services/creativeDirector/local.js b/server/services/creativeDirector/local.jsnew file mode 100644index 0000000000..407f7cdc31--- /dev/null+++ b/server/services/creativeDirector/local.js@@ -0,0 +1,177 @@+/**+ * Creative Director — project state CRUD.+ *+ * Persists to data/creative-director-projects.json (array, atomicWrite).+ * Mirrors the shape of services/videoTimeline/local.js but stores a richer+ * model — every project has a treatment (logline + scene list) the agent+ * fills in during the planning task.+ *+ * The treatment + scene + run fields are mutated by the agent via the+ * /api/creative-director/:id/* routes. This module is the only writer to+ * the JSON file; the orchestrator and routes call into here.+ */++import { join } from 'path';+import { randomUUID } from 'crypto';+import { PATHS, readJSONFile, atomicWrite, ensureDir } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { creativeDirectorTreatmentSchema } from '../../lib/validation.js';+import { PROJECT_STATUSES } from '../../lib/creativeDirectorPresets.js';+import { createCollection } from '../mediaCollections.js';++const PROJECTS_FILE = join(PATHS.data, 'creative-director-projects.json');++async function loadAll() {+ const raw = await readJSONFile(PROJECTS_FILE, []);+ return Array.isArray(raw) ? raw : [];+}++async function saveAll(projects) {+ // Defense for first-run on a fresh checkout where data/ may not exist yet.+ // Mirrors videoTimeline/local.js#saveProjects.+ await ensureDir(PATHS.data);+ await atomicWrite(PROJECTS_FILE, projects);+}++export async function listProjects() {+ return loadAll();+}++export async function getProject(id) {+ const all = await loadAll();+ return all.find((p) => p.id === id) || null;+}++export async function createProject({ name, aspectRatio, quality, modelId, targetDurationSeconds, styleSpec = '', startingImageFile = null, userStory = null, disableAudio = false, autoAcceptScenes = false }) {+ const id = `cd-${randomUUID()}`;+ const now = new Date().toISOString();++ // Auto-create a media collection scoped to this project. All segment+ // renders + the final stitched output land in here.+ const collection = await createCollection({ name: `Creative Director: ${name}`, description: `Auto-created for project ${id}` });++ const project = {+ id,+ name,+ status: 'draft',+ createdAt: now,+ updatedAt: now,+ aspectRatio,+ quality,+ modelId,+ targetDurationSeconds,+ styleSpec,+ startingImageFile,+ userStory,+ disableAudio,+ autoAcceptScenes,+ collectionId: collection.id,+ timelineProjectId: null,+ finalVideoId: null,+ treatment: null,+ runs: [],+ };+ const all = await loadAll();+ all.push(project);+ await saveAll(all);+ console.log(`🎬 Created Creative Director project: ${id} (${name})`);+ return project;+}++export async function updateProject(id, patch) {+ const all = await loadAll();+ const idx = all.findIndex((p) => p.id === id);+ if (idx < 0) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ if (patch.status && !PROJECT_STATUSES.includes(patch.status)) {+ throw new ServerError(`Invalid status: ${patch.status}`, { status: 400, code: 'VALIDATION_ERROR' });+ }+ const updated = { ...all[idx], ...patch, updatedAt: new Date().toISOString() };+ all[idx] = updated;+ await saveAll(all);+ return updated;+}++export async function deleteProject(id) {+ const all = await loadAll();+ const next = all.filter((p) => p.id !== id);+ if (next.length === all.length) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ await saveAll(next);+ return { ok: true };+}++export async function setTreatment(id, treatmentInput) {+ const parsed = creativeDirectorTreatmentSchema.safeParse(treatmentInput);+ if (!parsed.success) {+ throw new ServerError(+ `Treatment validation failed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ')}`,+ { status: 400, code: 'VALIDATION_ERROR' },+ );+ }+ const all = await loadAll();+ const idx = all.findIndex((p) => p.id === id);+ if (idx < 0) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ // Initialize each scene's runtime fields if the agent didn't supply them.+ const scenes = parsed.data.scenes.map((s) => ({+ ...s,+ status: s.status || 'pending',+ retryCount: s.retryCount ?? 0,+ renderedJobId: s.renderedJobId ?? null,+ evaluation: s.evaluation ?? null,+ }));+ const nextStatus = (all[idx].status === 'paused' || all[idx].status === 'failed')+ ? all[idx].status+ : 'rendering';+ all[idx] = {+ ...all[idx],+ treatment: { logline: parsed.data.logline, synopsis: parsed.data.synopsis, scenes },+ status: nextStatus,+ updatedAt: new Date().toISOString(),+ };+ await saveAll(all);+ return all[idx];+}++export async function updateScene(id, sceneId, patch) {+ const all = await loadAll();+ const idx = all.findIndex((p) => p.id === id);+ if (idx < 0) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = all[idx];+ if (!project.treatment?.scenes?.length) {+ throw new ServerError('Project has no treatment yet', { status: 400, code: 'NO_TREATMENT' });+ }+ const sceneIdx = project.treatment.scenes.findIndex((s) => s.sceneId === sceneId);+ if (sceneIdx < 0) throw new ServerError('Scene not found', { status: 404, code: 'NOT_FOUND' });+ const updated = { ...project.treatment.scenes[sceneIdx], ...patch };+ project.treatment.scenes[sceneIdx] = updated;+ project.updatedAt = new Date().toISOString();+ all[idx] = project;+ await saveAll(all);+ return updated;+}++export async function recordRun(id, runEntry) {+ const all = await loadAll();+ const idx = all.findIndex((p) => p.id === id);+ if (idx < 0) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = all[idx];+ const run = { startedAt: new Date().toISOString(), ...runEntry, runId: runEntry.runId || randomUUID() };+ project.runs = [...(project.runs || []), run];+ project.updatedAt = new Date().toISOString();+ all[idx] = project;+ await saveAll(all);+ return run;+}++export async function updateRun(id, runId, patch) {+ const all = await loadAll();+ const idx = all.findIndex((p) => p.id === id);+ if (idx < 0) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const project = all[idx];+ const runIdx = (project.runs || []).findIndex((r) => r.runId === runId);+ if (runIdx < 0) return null;+ project.runs[runIdx] = { ...project.runs[runIdx], ...patch };+ project.updatedAt = new Date().toISOString();+ all[idx] = project;+ await saveAll(all);+ return project.runs[runIdx];+}diff --git a/server/services/creativeDirector/local.test.js b/server/services/creativeDirector/local.test.jsnew file mode 100644index 0000000000..e0dec012ef--- /dev/null+++ b/server/services/creativeDirector/local.test.js@@ -0,0 +1,71 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mocks declared before importing the module under test.+const mockReadJSONFile = vi.fn();+const mockAtomicWrite = vi.fn();+const mockEnsureDir = vi.fn();++vi.mock('../../lib/fileUtils.js', () => ({+ PATHS: { data: '/fake/data' },+ readJSONFile: (...args) => mockReadJSONFile(...args),+ atomicWrite: (...args) => mockAtomicWrite(...args),+ ensureDir: (...args) => mockEnsureDir(...args),+}));++vi.mock('../mediaCollections.js', () => ({+ createCollection: vi.fn(async () => ({ id: 'col-1' })),+}));++const { setTreatment } = await import('./local.js');++const VALID_TREATMENT = {+ logline: 'A cat finds a hat.',+ synopsis: 'Then puts it on.',+ scenes: [+ {+ sceneId: 'scene-1',+ order: 0,+ intent: 'Cat enters frame',+ prompt: 'A cat walks into view',+ durationSeconds: 4,+ },+ ],+};++beforeEach(() => {+ mockReadJSONFile.mockReset();+ mockAtomicWrite.mockReset().mockResolvedValue(undefined);+ mockEnsureDir.mockReset().mockResolvedValue(undefined);+});++describe('setTreatment — status preservation', () => {+ it('preserves paused status when agent PATCHes treatment on a paused project', async () => {+ mockReadJSONFile.mockResolvedValue([{ id: 'cd-1', status: 'paused', name: 'Test' }]);+ const result = await setTreatment('cd-1', VALID_TREATMENT);+ expect(result.status).toBe('paused');+ const saved = mockAtomicWrite.mock.calls[0][1];+ expect(saved[0].status).toBe('paused');+ });++ it('preserves failed status when agent PATCHes treatment on a failed project', async () => {+ mockReadJSONFile.mockResolvedValue([{ id: 'cd-1', status: 'failed', name: 'Test' }]);+ const result = await setTreatment('cd-1', VALID_TREATMENT);+ expect(result.status).toBe('failed');+ const saved = mockAtomicWrite.mock.calls[0][1];+ expect(saved[0].status).toBe('failed');+ });++ it('flips planning → rendering when agent PATCHes treatment on a planning project', async () => {+ mockReadJSONFile.mockResolvedValue([{ id: 'cd-1', status: 'planning', name: 'Test' }]);+ const result = await setTreatment('cd-1', VALID_TREATMENT);+ expect(result.status).toBe('rendering');+ const saved = mockAtomicWrite.mock.calls[0][1];+ expect(saved[0].status).toBe('rendering');+ });++ it('flips draft → rendering when agent PATCHes treatment on a draft project', async () => {+ mockReadJSONFile.mockResolvedValue([{ id: 'cd-1', status: 'draft', name: 'Test' }]);+ const result = await setTreatment('cd-1', VALID_TREATMENT);+ expect(result.status).toBe('rendering');+ });+});diff --git a/server/services/creativeDirector/orchestrator.js b/server/services/creativeDirector/orchestrator.jsnew file mode 100644index 0000000000..f514a8ae33--- /dev/null+++ b/server/services/creativeDirector/orchestrator.js@@ -0,0 +1,58 @@+/**+ * Creative Director — pure orchestration helpers.+ *+ * No HTTP, no I/O, no CoS coupling. These functions decide what comes next+ * given a project's state, so the routes + agentBridge can stay thin and+ * the logic stays unit-testable.+ */++/**+ * Pick the next non-terminal scene by `order`. Returns the lowest-order+ * scene that's `pending`, `rendering`, or `evaluating` (i.e. not yet in a+ * terminal `accepted`/`failed` state). Returns null when every scene is+ * terminal.+ *+ * The caller treats `rendering`/`evaluating` as "currently in flight" —+ * surfacing them here lets a re-enqueue pick up where work left off+ * rather than skip ahead. `advanceAfterSceneSettled` separately filters+ * to status === 'pending' before kicking off a fresh render.+ */+export function nextPendingScene(project) {+ if (!project?.treatment?.scenes?.length) return null;+ const sorted = [...project.treatment.scenes].sort((a, b) => a.order - b.order);+ return sorted.find((s) => s.status === 'pending' || s.status === 'rendering' || s.status === 'evaluating') || null;+}++/**+ * What kind of follow-up task should the server enqueue next?+ * - 'treatment' — no treatment yet+ * - 'scene' — at least one scene still pending+ * - 'stitch' — every scene accepted, no final video yet+ * - null — project is fully done (or failed terminally)+ */+export function nextTaskKind(project) {+ if (!project) return null;+ if (project.status === 'failed' || project.status === 'paused') return null;+ if (!project.treatment) return 'treatment';+ const scenes = project.treatment.scenes || [];+ if (!scenes.length) return null;+ const remaining = scenes.find((s) => s.status === 'pending' || s.status === 'rendering' || s.status === 'evaluating');+ if (remaining) return 'scene';+ // All scenes terminal — if at least one accepted and no final video yet,+ // stitch. If none accepted, the project failed.+ const acceptedCount = scenes.filter((s) => s.status === 'accepted').length;+ if (!acceptedCount) return null;+ if (project.finalVideoId) return null;+ return 'stitch';+}++/**+ * Build the timeline-project clip list from accepted scenes. Used by the+ * stitch task prompt and could be used by a server-side auto-stitch path.+ */+export function buildTimelineClips(project) {+ return (project?.treatment?.scenes || [])+ .filter((s) => s.status === 'accepted' && s.renderedJobId)+ .sort((a, b) => a.order - b.order)+ .map((s) => ({ clipId: s.renderedJobId, inSec: 0, outSec: s.durationSeconds }));+}diff --git a/server/services/creativeDirector/orchestrator.test.js b/server/services/creativeDirector/orchestrator.test.jsnew file mode 100644index 0000000000..71ffddeeda--- /dev/null+++ b/server/services/creativeDirector/orchestrator.test.js@@ -0,0 +1,240 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { nextPendingScene, nextTaskKind, buildTimelineClips } from './orchestrator.js';+import { presetToRenderParams } from '../../lib/creativeDirectorPresets.js';++// Mocks for advanceAfterSceneSettled integration test.+const mockRunSceneRender = vi.fn(async () => undefined);+const mockUpdateProject = vi.fn(async () => undefined);++vi.mock('./local.js', () => ({+ getProject: vi.fn(),+ updateProject: (...args) => mockUpdateProject(...args),+}));++vi.mock('./sceneRunner.js', () => ({+ runSceneRender: (...args) => mockRunSceneRender(...args),+}));++vi.mock('./stitchRunner.js', () => ({+ runStitch: vi.fn(async () => undefined),+}));++vi.mock('./agentBridge.js', () => ({+ enqueueTreatmentTask: vi.fn(async () => undefined),+}));++import * as localMod from './local.js';+import { advanceAfterSceneSettled } from './completionHook.js';++const baseProject = {+ id: 'cd-1',+ name: 'Test',+ status: 'rendering',+ aspectRatio: '16:9',+ quality: 'standard',+ modelId: 'ltx2_unified',+ collectionId: 'mc-1',+ finalVideoId: null,+ treatment: null,+};++describe('orchestrator', () => {+ describe('nextPendingScene', () => {+ it('returns null when no treatment', () => {+ expect(nextPendingScene({ ...baseProject, treatment: null })).toBeNull();+ });++ it('returns the lowest-order non-terminal scene', () => {+ const project = {+ ...baseProject,+ treatment: {+ scenes: [+ { sceneId: 's1', order: 0, status: 'accepted' },+ { sceneId: 's2', order: 1, status: 'pending' },+ { sceneId: 's3', order: 2, status: 'pending' },+ ],+ },+ };+ expect(nextPendingScene(project).sceneId).toBe('s2');+ });++ it('considers rendering / evaluating as in-flight (not next)', () => {+ // The currently running scene IS the "next" scene from the queue+ // perspective — the orchestrator returns it so a re-enqueue picks+ // up where it left off rather than skipping ahead.+ const project = {+ ...baseProject,+ treatment: {+ scenes: [+ { sceneId: 's1', order: 0, status: 'accepted' },+ { sceneId: 's2', order: 1, status: 'rendering' },+ { sceneId: 's3', order: 2, status: 'pending' },+ ],+ },+ };+ expect(nextPendingScene(project).sceneId).toBe('s2');+ });++ it('returns null when every scene is terminal', () => {+ const project = {+ ...baseProject,+ treatment: {+ scenes: [+ { sceneId: 's1', order: 0, status: 'accepted' },+ { sceneId: 's2', order: 1, status: 'failed' },+ ],+ },+ };+ expect(nextPendingScene(project)).toBeNull();+ });+ });++ describe('nextTaskKind', () => {+ it('returns "treatment" when no treatment exists', () => {+ expect(nextTaskKind({ ...baseProject, treatment: null })).toBe('treatment');+ });++ it('returns "scene" when at least one scene is pending', () => {+ const project = {+ ...baseProject,+ treatment: { scenes: [{ sceneId: 's1', order: 0, status: 'pending' }] },+ };+ expect(nextTaskKind(project)).toBe('scene');+ });++ it('returns "stitch" when every scene accepted and no final video', () => {+ const project = {+ ...baseProject,+ treatment: {+ scenes: [+ { sceneId: 's1', order: 0, status: 'accepted' },+ { sceneId: 's2', order: 1, status: 'accepted' },+ ],+ },+ };+ expect(nextTaskKind(project)).toBe('stitch');+ });++ it('returns null when finalVideoId is already set', () => {+ const project = {+ ...baseProject,+ finalVideoId: 'final-uuid',+ treatment: { scenes: [{ sceneId: 's1', order: 0, status: 'accepted' }] },+ };+ expect(nextTaskKind(project)).toBeNull();+ });++ it('returns null when project is paused or failed', () => {+ const paused = { ...baseProject, status: 'paused', treatment: null };+ const failed = { ...baseProject, status: 'failed', treatment: null };+ expect(nextTaskKind(paused)).toBeNull();+ expect(nextTaskKind(failed)).toBeNull();+ });++ it('returns null when no scenes were ever accepted (full failure)', () => {+ const project = {+ ...baseProject,+ treatment: {+ scenes: [+ { sceneId: 's1', order: 0, status: 'failed' },+ { sceneId: 's2', order: 1, status: 'failed' },+ ],+ },+ };+ expect(nextTaskKind(project)).toBeNull();+ });+ });++ describe('buildTimelineClips', () => {+ it('orders accepted scenes by order field', () => {+ const project = {+ ...baseProject,+ treatment: {+ scenes: [+ { sceneId: 's2', order: 1, status: 'accepted', renderedJobId: 'job-2', durationSeconds: 4 },+ { sceneId: 's1', order: 0, status: 'accepted', renderedJobId: 'job-1', durationSeconds: 5 },+ { sceneId: 's3', order: 2, status: 'failed', renderedJobId: 'job-3', durationSeconds: 3 },+ ],+ },+ };+ const clips = buildTimelineClips(project);+ expect(clips).toEqual([+ { clipId: 'job-1', inSec: 0, outSec: 5 },+ { clipId: 'job-2', inSec: 0, outSec: 4 },+ ]);+ });+ });+});++describe('presetToRenderParams', () => {+ it('maps 16:9 + standard at 5s into the LTX-friendly numbers', () => {+ const r = presetToRenderParams({ aspectRatio: '16:9', quality: 'standard', durationSeconds: 5 });+ expect(r.width).toBe(768);+ expect(r.height).toBe(432);+ expect(r.fps).toBe(24);+ expect(r.steps).toBe(20);+ expect(r.guidanceScale).toBe(3.0);+ // 5s × 24fps = 120 → rounds to 120 (multiple of 8).+ expect(r.numFrames).toBe(120);+ });++ it('rounds frame count to multiple of 8 (LTX latent compression requires it)', () => {+ // 1.3s × 24fps = 31.2 — rounds to nearest 8 → 32.+ const r = presetToRenderParams({ aspectRatio: '1:1', quality: 'draft', durationSeconds: 1.3 });+ expect(r.numFrames % 8).toBe(0);+ expect(r.numFrames).toBe(32);+ });++ it('floors at 8 frames so a tiny scene still renders', () => {+ const r = presetToRenderParams({ aspectRatio: '16:9', quality: 'draft', durationSeconds: 0.1 });+ expect(r.numFrames).toBe(8);+ });++ it('throws on unknown aspect ratio', () => {+ expect(() => presetToRenderParams({ aspectRatio: '4:3', quality: 'standard', durationSeconds: 1 }))+ .toThrow(/aspectRatio/);+ });++ it('throws on unknown quality preset', () => {+ expect(() => presetToRenderParams({ aspectRatio: '16:9', quality: 'ultra', durationSeconds: 1 }))+ .toThrow(/quality/);+ });+});++describe('advanceAfterSceneSettled', () => {+ const makeProject = (overrides = {}) => ({+ id: 'cd-test',+ status: 'rendering',+ finalVideoId: null,+ treatment: {+ scenes: [+ { sceneId: 'scene-1', order: 0, status: 'accepted', renderedJobId: 'job-1' },+ { sceneId: 'scene-2', order: 1, status: 'pending' },+ { sceneId: 'scene-3', order: 2, status: 'pending' },+ { sceneId: 'scene-4', order: 3, status: 'pending' },+ { sceneId: 'scene-5', order: 4, status: 'pending' },+ { sceneId: 'scene-6', order: 5, status: 'pending' },+ ],+ },+ ...overrides,+ });++ beforeEach(() => {+ mockRunSceneRender.mockClear();+ mockUpdateProject.mockClear();+ });++ it('picks scene-2 (lowest-order pending) when scene-1 is accepted and scenes 2-6 are pending', async () => {+ const project = makeProject();+ // getProject called twice: initial fetch + fresh fetch before runSceneRender.+ localMod.getProject+ .mockResolvedValueOnce(project)+ .mockResolvedValueOnce(project);++ await advanceAfterSceneSettled(project.id);++ expect(mockRunSceneRender).toHaveBeenCalledTimes(1);+ const [, sceneArg] = mockRunSceneRender.mock.calls[0];+ expect(sceneArg.sceneId).toBe('scene-2');+ });+});diff --git a/server/services/creativeDirector/recovery.js b/server/services/creativeDirector/recovery.jsnew file mode 100644index 0000000000..2801aa8700--- /dev/null+++ b/server/services/creativeDirector/recovery.js@@ -0,0 +1,50 @@+/**+ * Creative Director — boot-time recovery.+ *+ * Server restarts (deploys, watchers, OOM kills) abort any in-flight render+ * and tear down the in-memory listeners that runSceneRender attaches. Without+ * recovery the project sits in `rendering` / `stitching` forever — its scene+ * status fields point at jobs that the queue already reclassified as+ * 'failed (interrupted by restart)' but nothing fires advanceAfterSceneSettled+ * to push the project forward.+ *+ * On boot, after the media-job queue reloads its persisted state, we:+ * 1. Find every project that's mid-flight (status in planning/rendering/+ * stitching).+ * 2. Reset any scenes stuck in `rendering` or `evaluating` back to `pending`+ * — their listeners are gone, the render is dead, the only sane next+ * action is to redo them.+ * 3. Call `advanceAfterSceneSettled` to resume each project. It picks up+ * from wherever the project stopped: re-renders pending scenes, fires a+ * fresh evaluate task, runs the stitch, etc.+ */++import { listProjects, updateScene } from './local.js';++const RECOVERABLE_STATUSES = new Set(['planning', 'rendering', 'stitching']);+const STUCK_SCENE_STATUSES = new Set(['rendering', 'evaluating']);++export async function recoverInFlightProjects() {+ const projects = await listProjects();+ const recoverable = projects.filter((p) => RECOVERABLE_STATUSES.has(p.status));+ if (!recoverable.length) return { resumed: 0 };++ const { advanceAfterSceneSettled } = await import('./completionHook.js');+ let resumed = 0;+ for (const project of recoverable) {+ const scenes = project.treatment?.scenes || [];+ const stuck = scenes.filter((s) => STUCK_SCENE_STATUSES.has(s.status));+ for (const scene of stuck) {+ await updateScene(project.id, scene.sceneId, { status: 'pending' })+ .catch((e) => console.log(`⚠️ CD recovery: reset scene ${scene.sceneId} of ${project.id} failed: ${e.message}`));+ }+ if (stuck.length) {+ console.log(`🔄 CD recovery: ${project.id} reset ${stuck.length} stuck scene(s) to pending`);+ }+ advanceAfterSceneSettled(project.id)+ .catch((e) => console.log(`⚠️ CD recovery: advance for ${project.id} failed: ${e.message}`));+ resumed += 1;+ }+ console.log(`🔄 CD recovery: resumed ${resumed} in-flight project(s)`);+ return { resumed };+}diff --git a/server/services/creativeDirector/recovery.test.js b/server/services/creativeDirector/recovery.test.jsnew file mode 100644index 0000000000..dcfc593842--- /dev/null+++ b/server/services/creativeDirector/recovery.test.js@@ -0,0 +1,104 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mocks must be declared before importing the module under test.+const mockListProjects = vi.fn();+const mockUpdateScene = vi.fn();+const mockAdvance = vi.fn();++vi.mock('./local.js', () => ({+ listProjects: (...args) => mockListProjects(...args),+ updateScene: (...args) => mockUpdateScene(...args),+}));++vi.mock('./completionHook.js', () => ({+ advanceAfterSceneSettled: (...args) => mockAdvance(...args),+}));++const { recoverInFlightProjects } = await import('./recovery.js');++beforeEach(() => {+ mockListProjects.mockReset();+ mockUpdateScene.mockReset().mockResolvedValue(undefined);+ mockAdvance.mockReset().mockResolvedValue(undefined);+});++describe('recoverInFlightProjects', () => {+ it('skips terminal and draft projects', async () => {+ mockListProjects.mockResolvedValue([+ { id: 'cd-1', status: 'complete', treatment: { scenes: [{ sceneId: 's1', status: 'accepted' }] } },+ { id: 'cd-2', status: 'failed', treatment: { scenes: [{ sceneId: 's1', status: 'failed' }] } },+ { id: 'cd-3', status: 'draft', treatment: null },+ { id: 'cd-4', status: 'paused', treatment: null },+ ]);+ const result = await recoverInFlightProjects();+ expect(result.resumed).toBe(0);+ expect(mockAdvance).not.toHaveBeenCalled();+ expect(mockUpdateScene).not.toHaveBeenCalled();+ });++ it('resets stuck rendering/evaluating scenes to pending and advances', async () => {+ mockListProjects.mockResolvedValue([+ {+ id: 'cd-1',+ status: 'rendering',+ treatment: {+ scenes: [+ { sceneId: 's1', status: 'accepted' },+ { sceneId: 's2', status: 'rendering' },+ { sceneId: 's3', status: 'evaluating' },+ { sceneId: 's4', status: 'pending' },+ ],+ },+ },+ ]);+ const result = await recoverInFlightProjects();+ expect(result.resumed).toBe(1);+ expect(mockUpdateScene).toHaveBeenCalledTimes(2);+ expect(mockUpdateScene).toHaveBeenCalledWith('cd-1', 's2', { status: 'pending' });+ expect(mockUpdateScene).toHaveBeenCalledWith('cd-1', 's3', { status: 'pending' });+ expect(mockAdvance).toHaveBeenCalledWith('cd-1');+ });++ it('resumes planning-state projects (treatment task interrupted)', async () => {+ mockListProjects.mockResolvedValue([+ { id: 'cd-1', status: 'planning', treatment: null },+ ]);+ const result = await recoverInFlightProjects();+ expect(result.resumed).toBe(1);+ expect(mockUpdateScene).not.toHaveBeenCalled();+ expect(mockAdvance).toHaveBeenCalledWith('cd-1');+ });++ it('resumes stitching-state projects (final concat interrupted)', async () => {+ mockListProjects.mockResolvedValue([+ {+ id: 'cd-1',+ status: 'stitching',+ treatment: { scenes: [{ sceneId: 's1', status: 'accepted', renderedJobId: 'job-1' }] },+ },+ ]);+ const result = await recoverInFlightProjects();+ expect(result.resumed).toBe(1);+ expect(mockAdvance).toHaveBeenCalledWith('cd-1');+ });++ it('handles multiple projects independently', async () => {+ mockListProjects.mockResolvedValue([+ {+ id: 'cd-1',+ status: 'rendering',+ treatment: { scenes: [{ sceneId: 's1', status: 'rendering' }] },+ },+ {+ id: 'cd-2',+ status: 'rendering',+ treatment: { scenes: [{ sceneId: 's1', status: 'evaluating' }] },+ },+ ]);+ const result = await recoverInFlightProjects();+ expect(result.resumed).toBe(2);+ expect(mockAdvance).toHaveBeenCalledTimes(2);+ expect(mockAdvance).toHaveBeenCalledWith('cd-1');+ expect(mockAdvance).toHaveBeenCalledWith('cd-2');+ });+});diff --git a/server/services/creativeDirector/sceneRunner.js b/server/services/creativeDirector/sceneRunner.jsnew file mode 100644index 0000000000..40ed40537d--- /dev/null+++ b/server/services/creativeDirector/sceneRunner.js@@ -0,0 +1,275 @@+/**+ * Creative Director — server-side scene render orchestrator.+ *+ * Render submission, last-frame extraction, and queue-completion handling+ * are all mechanical operations — no LLM cognition required. We do them+ * directly here instead of paying for a Claude task that would just shell+ * out to the same HTTP endpoints. Once the render lands, we hand off to+ * an `evaluate` agent task whose ONLY job is the cognitive step (read the+ * thumbnail, score it against the style spec + scene intent, accept or+ * request a re-render).+ *+ * Lifecycle for a single scene:+ * 1. updateScene(status='rendering', renderedJobId=null)+ * 2. resolve sourceImageFile (extract last-frame of prior scene if+ * `useContinuationFromPrior`; else use scene.sourceImageFile if any;+ * else text-to-video).+ * 3. enqueueJob into mediaJobQueue with owner=`cd:<projectId>:<sceneId>`.+ * 4. listen for mediaJobEvents 'completed'/'failed' for that jobId.+ * 5a. on 'completed': updateScene(renderedJobId, status='evaluating')+ * and enqueue evaluate agent task.+ * 5b. on 'failed': bump retryCount; if < 3, retry with same prompt; else+ * updateScene(status='failed') and let completionHook decide what to+ * do next.+ *+ * Each call sets up its own event listeners and detaches them on settle.+ * Multiple concurrent runners are not expected (the queue serializes+ * renders) but the listener is jobId-scoped so concurrent calls would be+ * isolated anyway.+ */++import { join, basename, resolve as resolvePath, sep as PATH_SEP } from 'path';+import { existsSync } from 'fs';+import { PATHS } from '../../lib/fileUtils.js';+import { presetToRenderParams } from '../../lib/creativeDirectorPresets.js';+import { extractLastFrame } from '../videoGen/local.js';+import { enqueueJob, mediaJobEvents } from '../mediaJobQueue/index.js';+import { getSettings } from '../settings.js';+import { updateScene, getProject } from './local.js';+import { enqueueEvaluateTask } from './agentBridge.js';++const MAX_SCENE_RETRIES = 3;++/**+ * Kick off a render for a single scene. Returns the jobId; the caller does+ * not need to await completion — the listener installed here will spawn+ * the evaluate task or schedule a retry.+ */+export async function runSceneRender(project, scene) {+ console.log(`🎞️ CD scene render starting: ${project.id} / ${scene.sceneId} (order ${scene.order}, attempt ${(scene.retryCount || 0) + 1}/${MAX_SCENE_RETRIES + 1})`);++ await updateScene(project.id, scene.sceneId, {+ status: 'rendering',+ renderedJobId: null,+ });++ const settings = await getSettings();+ const pythonPath = settings.imageGen?.local?.pythonPath || null;+ // Fail fast when local video gen isn't configured. Without this guard the+ // job would be enqueued, fail inside `generateVideo`, retry up to+ // MAX_SCENE_RETRIES, and pollute the persisted queue with N doomed entries+ // — none of which can ever succeed without operator intervention. Mark+ // the scene failed and let advanceAfterSceneSettled flag the project so+ // the user can configure pythonPath and Resume from the UI.+ if (!pythonPath) {+ console.log(`❌ CD scene ${scene.sceneId}: local video gen not configured (settings.imageGen.local.pythonPath missing)`);+ await updateScene(project.id, scene.sceneId, {+ status: 'failed',+ evaluation: {+ accepted: false,+ notes: 'Local video generation is not configured — set settings.imageGen.local.pythonPath in Settings > Image Gen.',+ sampledAt: new Date().toISOString(),+ },+ });+ const { advanceAfterSceneSettled } = await import('./completionHook.js');+ await advanceAfterSceneSettled(project.id);+ return null;+ }++ // Resolve the source image:+ // - useContinuationFromPrior=true → extract the prior accepted scene's+ // last frame and use that as the source.+ // - else if scene.sourceImageFile set → use that file.+ // - else → text-to-video (no source).+ let sourceImageFile = scene.sourceImageFile || null;+ if (scene.useContinuationFromPrior) {+ const fresh = await getProject(project.id);+ const priorScene = (fresh?.treatment?.scenes || [])+ .filter((s) => s.order < scene.order && s.status === 'accepted')+ .sort((a, b) => b.order - a.order)[0];+ if (priorScene?.renderedJobId) {+ const lf = await extractLastFrame(priorScene.renderedJobId).catch((e) => {+ console.log(`⚠️ CD last-frame for ${priorScene.renderedJobId} failed: ${e.message}`);+ return null;+ });+ if (lf?.filename) {+ sourceImageFile = lf.filename;+ } else {+ console.log(`⚠️ CD scene ${scene.sceneId} requested continuation but last-frame extract failed — falling back to text-to-video`);+ }+ } else {+ console.log(`⚠️ CD scene ${scene.sceneId} requested continuation but no prior accepted scene exists — falling back`);+ }+ }++ // Resolve sourceImageFile to an absolute path if it's a basename in the+ // gallery. Two-layer guard:+ // 1. basename() strips any path segments (so `../../etc/passwd` →+ // `passwd`); reject `.`/`..` outright.+ // 2. resolve + prefix-check against the images root so a unicode trick+ // can't escape PATHS.images.+ // Without these, `sourceImageFile: '..'` from a malicious / mistaken+ // payload could resolve to PATHS.images's parent and feed an arbitrary+ // local path into the renderer.+ let sourceImagePath = null;+ if (sourceImageFile) {+ const safe = basename(sourceImageFile);+ if (!safe || safe === '.' || safe === '..') {+ console.log(`⚠️ CD scene ${scene.sceneId} sourceImageFile rejected (dot segment): ${sourceImageFile}`);+ } else {+ const imagesRoot = resolvePath(PATHS.images) + PATH_SEP;+ const localPath = resolvePath(join(PATHS.images, safe));+ if (localPath.startsWith(imagesRoot) && existsSync(localPath)) {+ sourceImagePath = localPath;+ } else {+ console.log(`⚠️ CD scene ${scene.sceneId} sourceImageFile not found on disk: ${sourceImageFile}`);+ }+ }+ }++ const renderParams = presetToRenderParams({+ aspectRatio: project.aspectRatio,+ quality: project.quality,+ durationSeconds: scene.durationSeconds,+ });++ const params = {+ pythonPath,+ prompt: scene.prompt,+ negativePrompt: scene.negativePrompt || '',+ modelId: project.modelId,+ width: renderParams.width,+ height: renderParams.height,+ numFrames: renderParams.numFrames,+ fps: renderParams.fps,+ steps: renderParams.steps,+ guidanceScale: renderParams.guidanceScale,+ tiling: 'auto',+ sourceImagePath,+ mode: sourceImagePath ? 'image' : 'text',+ // Smoke-test / dev knob: skips the mlx_video audio-gen pass to cut+ // wall-clock per scene roughly in half. Project-level so every scene+ // in the project inherits the same setting.+ disableAudio: project.disableAudio === true,+ };++ const owner = `cd:${project.id}:${scene.sceneId}`;+ const { jobId } = enqueueJob({ kind: 'video', params, owner });++ // Wire one-shot listeners scoped to this jobId so we can hand off to the+ // evaluator on success or schedule a retry on failure. mediaJobEvents+ // fires `completed`, `failed`, and `canceled` from the queue's runJob /+ // cancelJob handlers — we MUST listen for all three or a user-initiated+ // cancel via the Render Queue UI would leave the scene stuck in+ // `rendering` forever and leak listeners.+ const onCompleted = async (job) => {+ if (job.id !== jobId) return;+ cleanup();+ await handleRenderCompleted(project.id, scene.sceneId, jobId);+ };+ const onFailed = async (job) => {+ if (job.id !== jobId) return;+ cleanup();+ await handleRenderFailed(project.id, scene.sceneId, job.error || 'render failed');+ };+ const onCanceled = async (job) => {+ if (job.id !== jobId) return;+ cleanup();+ // Treat user-initiated cancel as a terminal stop for this scene — do+ // NOT route through handleRenderFailed (which would retry up to+ // MAX_SCENE_RETRIES); the user explicitly stopped this. Mark the scene+ // failed and let the completionHook flag the project so the user can+ // resume from the UI.+ await handleRenderCanceled(project.id, scene.sceneId);+ };+ function cleanup() {+ mediaJobEvents.off('completed', onCompleted);+ mediaJobEvents.off('failed', onFailed);+ mediaJobEvents.off('canceled', onCanceled);+ }+ mediaJobEvents.on('completed', onCompleted);+ mediaJobEvents.on('failed', onFailed);+ mediaJobEvents.on('canceled', onCanceled);++ return jobId;+}++async function handleRenderCompleted(projectId, sceneId, jobId) {+ console.log(`✅ CD scene render done: ${projectId} / ${sceneId} → ${jobId.slice(0, 8)}`);+ const fresh = await getProject(projectId);+ if (!fresh) return;+ const scene = fresh.treatment?.scenes?.find((s) => s.sceneId === sceneId);+ if (!scene) return;+ // autoAcceptScenes — smoke-test path that bypasses the cognitive evaluator.+ // Mark the scene accepted with a synthetic evaluation, drop the rendered+ // video into the project's collection, and let the orchestrator advance.+ // No Claude task spawned, so a smoke run completes in render time only.+ if (fresh.autoAcceptScenes === true) {+ await updateScene(projectId, sceneId, {+ status: 'accepted',+ renderedJobId: jobId,+ evaluation: {+ accepted: true,+ score: 1,+ notes: 'auto-accepted (autoAcceptScenes)',+ sampledAt: new Date().toISOString(),+ },+ });+ if (fresh.collectionId) {+ const { addItem } = await import('../mediaCollections.js');+ await addItem(fresh.collectionId, { kind: 'video', ref: jobId })+ .catch((e) => console.log(`⚠️ CD auto-accept addItem failed: ${e.message}`));+ }+ const { advanceAfterSceneSettled } = await import('./completionHook.js');+ await advanceAfterSceneSettled(projectId);+ return;+ }+ await updateScene(projectId, sceneId, {+ status: 'evaluating',+ renderedJobId: jobId,+ });+ await enqueueEvaluateTask(fresh, scene);+}++async function handleRenderCanceled(projectId, sceneId) {+ console.log(`🛑 CD scene ${sceneId} render canceled by user`);+ await updateScene(projectId, sceneId, {+ status: 'failed',+ evaluation: {+ accepted: false,+ notes: 'Render canceled by user',+ sampledAt: new Date().toISOString(),+ },+ });+ const { advanceAfterSceneSettled } = await import('./completionHook.js');+ await advanceAfterSceneSettled(projectId);+}++async function handleRenderFailed(projectId, sceneId, errorMsg) {+ const fresh = await getProject(projectId);+ if (!fresh) return;+ const scene = fresh.treatment?.scenes?.find((s) => s.sceneId === sceneId);+ if (!scene) return;+ const nextRetry = (scene.retryCount || 0) + 1;+ if (nextRetry <= MAX_SCENE_RETRIES) {+ console.log(`🔁 CD scene ${sceneId} render failed (${errorMsg}) — retry ${nextRetry}/${MAX_SCENE_RETRIES}`);+ await updateScene(projectId, sceneId, { status: 'pending', retryCount: nextRetry });+ const updated = { ...scene, retryCount: nextRetry };+ await runSceneRender(fresh, updated);+ return;+ }+ console.log(`❌ CD scene ${sceneId} render failed terminally: ${errorMsg}`);+ await updateScene(projectId, sceneId, {+ status: 'failed',+ evaluation: {+ accepted: false,+ notes: `Render failed: ${errorMsg}`,+ sampledAt: new Date().toISOString(),+ },+ });+ // The completionHook will be triggered when the evaluate-step is skipped;+ // here we delegate by directly invoking the hook's logic via a synthetic+ // re-evaluation of project state. Simplest: import and call.+ const { advanceAfterSceneSettled } = await import('./completionHook.js');+ await advanceAfterSceneSettled(projectId);+}diff --git a/server/services/creativeDirector/smokeTest.js b/server/services/creativeDirector/smokeTest.jsnew file mode 100644index 0000000000..d2cffa31c0--- /dev/null+++ b/server/services/creativeDirector/smokeTest.js@@ -0,0 +1,94 @@+/**+ * Creative Director — deterministic smoke-test fixture.+ *+ * Spins up a 3-scene "colored ball" project with `disableAudio: true` and+ * `autoAcceptScenes: true` so the run proves the i2v chaining mechanics+ * end-to-end without the variance of the cognitive evaluator. The scenes+ * are intentionally trivial:+ *+ * 1. Red ball bouncing on white background (text-to-video baseline)+ * 2. Blue ball bouncing on white background (continuation from scene 1+ * — verifies the scene+ * transition + color change+ * is driven by the prompt+ * while motion carries+ * forward from the seed+ * frame)+ * 3. Blue ball bouncing on white background (continuation from scene 2+ * — verifies pure i2v+ * continuation doesn't+ * drift)+ *+ * Result: ~9s total runtime, no LLM in the loop after the project is+ * created, audio rendering disabled. Use as a fast E2E health check after+ * touching anything in the CD pipeline (sceneRunner, mediaJobQueue,+ * completionHook, stitchRunner).+ */++import { createProject, setTreatment } from './local.js';++const SMOKE_SCENES = [+ {+ sceneId: 'scene-1',+ order: 0,+ intent: 'Establish: a red ball bouncing on a plain white background.',+ prompt: 'A red rubber ball bouncing up and down on a plain white background. Simple flat lighting, centered framing, slow gentle bounce, no other objects.',+ negativePrompt: 'text, watermark, blur, motion blur, multiple balls, complex background, shadows, people',+ durationSeconds: 3,+ useContinuationFromPrior: false,+ sourceImageFile: null,+ },+ {+ sceneId: 'scene-2',+ order: 1,+ intent: 'Color change: the same bouncing ball is now blue. Tests that the i2v render honors a prompt-driven color change while preserving the bouncing motion seeded by scene 1\'s last frame.',+ prompt: 'A blue rubber ball bouncing up and down on a plain white background. Simple flat lighting, centered framing, slow gentle bounce, no other objects.',+ negativePrompt: 'text, watermark, blur, motion blur, multiple balls, complex background, shadows, people, red',+ durationSeconds: 3,+ useContinuationFromPrior: true,+ sourceImageFile: null,+ },+ {+ sceneId: 'scene-3',+ order: 2,+ intent: 'Pure continuation: same blue ball, same scene. Tests that i2v chaining holds visual identity across a same-prompt continuation step.',+ prompt: 'A blue rubber ball bouncing up and down on a plain white background. Simple flat lighting, centered framing, slow gentle bounce, no other objects.',+ negativePrompt: 'text, watermark, blur, motion blur, multiple balls, complex background, shadows, people, red',+ durationSeconds: 3,+ useContinuationFromPrior: true,+ sourceImageFile: null,+ },+];++const SMOKE_TREATMENT = {+ logline: 'A red rubber ball changes color to blue and keeps bouncing.',+ synopsis: 'Three short clips that exercise the core mechanics of the Creative Director pipeline: text-to-video for the opening scene, continuation-with-prompt-change for the second, and pure continuation for the third. No characters, no story, no audio — just deterministic geometry against a uniform background so a human can verify the transitions worked at a glance.',+ scenes: SMOKE_SCENES,+};++const SMOKE_DEFAULTS = {+ name: 'CD smoke test (colored ball)',+ aspectRatio: '1:1',+ quality: 'draft',+ modelId: 'ltx23_distilled_q4',+ targetDurationSeconds: 9,+ styleSpec: 'Plain white background, single rubber ball, no text, no people. Flat lighting, centered framing.',+ startingImageFile: null,+ userStory: null,+ disableAudio: true,+ autoAcceptScenes: true,+};++/**+ * Create a fresh smoke-test project with a pre-filled treatment. The+ * caller is expected to POST /:id/start (or call advanceAfterSceneSettled)+ * to kick off the renders. Returns the created project record.+ *+ * Pure orchestration — no HTTP, no UI, no agent spawns.+ */+export async function createSmokeTestProject(overrides = {}) {+ const project = await createProject({ ...SMOKE_DEFAULTS, ...overrides });+ const withTreatment = await setTreatment(project.id, SMOKE_TREATMENT);+ console.log(`🧪 CD smoke project ready: ${withTreatment.id} (${withTreatment.scenes?.length ?? withTreatment.treatment?.scenes?.length ?? 0} scenes, autoAcceptScenes=${withTreatment.autoAcceptScenes ?? SMOKE_DEFAULTS.autoAcceptScenes}, disableAudio=${withTreatment.disableAudio ?? SMOKE_DEFAULTS.disableAudio})`);+ return withTreatment;+}diff --git a/server/services/creativeDirector/smokeTest.test.js b/server/services/creativeDirector/smokeTest.test.jsnew file mode 100644index 0000000000..979199718c--- /dev/null+++ b/server/services/creativeDirector/smokeTest.test.js@@ -0,0 +1,73 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++const mockReadJSONFile = vi.fn();+const mockAtomicWrite = vi.fn();+const mockEnsureDir = vi.fn();++vi.mock('../../lib/fileUtils.js', () => ({+ PATHS: { data: '/fake/data' },+ readJSONFile: (...args) => mockReadJSONFile(...args),+ atomicWrite: (...args) => mockAtomicWrite(...args),+ ensureDir: (...args) => mockEnsureDir(...args),+}));++vi.mock('../mediaCollections.js', () => ({+ createCollection: vi.fn(async () => ({ id: 'col-smoke' })),+}));++const { createSmokeTestProject } = await import('./smokeTest.js');++beforeEach(() => {+ // Persisted file starts empty; each save returns the latest snapshot.+ let snapshot = [];+ mockReadJSONFile.mockReset().mockImplementation(async () => snapshot);+ mockAtomicWrite.mockReset().mockImplementation(async (_path, data) => {+ snapshot = data;+ });+ mockEnsureDir.mockReset().mockResolvedValue(undefined);+});++describe('createSmokeTestProject', () => {+ it('creates a deterministic 3-scene project with disableAudio=true and autoAcceptScenes=true', async () => {+ const project = await createSmokeTestProject();+ expect(project.disableAudio).toBe(true);+ expect(project.autoAcceptScenes).toBe(true);+ expect(project.aspectRatio).toBe('1:1');+ expect(project.quality).toBe('draft');+ expect(project.targetDurationSeconds).toBe(9);+ expect(project.treatment.scenes).toHaveLength(3);+ });++ it('scene 1 is text-to-video (no continuation, no source image)', async () => {+ const project = await createSmokeTestProject();+ const scene1 = project.treatment.scenes.find((s) => s.sceneId === 'scene-1');+ expect(scene1.useContinuationFromPrior).toBe(false);+ expect(scene1.sourceImageFile).toBeNull();+ expect(scene1.prompt.toLowerCase()).toContain('red');+ });++ it('scene 2 continues from scene 1 with a color-change prompt', async () => {+ const project = await createSmokeTestProject();+ const scene2 = project.treatment.scenes.find((s) => s.sceneId === 'scene-2');+ expect(scene2.useContinuationFromPrior).toBe(true);+ expect(scene2.prompt.toLowerCase()).toContain('blue');+ // Negative prompt should explicitly reject the prior color so the i2v+ // doesn't drift back to red.+ expect(scene2.negativePrompt.toLowerCase()).toContain('red');+ });++ it('scene 3 is a pure continuation of scene 2 (same prompt)', async () => {+ const project = await createSmokeTestProject();+ const scene2 = project.treatment.scenes.find((s) => s.sceneId === 'scene-2');+ const scene3 = project.treatment.scenes.find((s) => s.sceneId === 'scene-3');+ expect(scene3.useContinuationFromPrior).toBe(true);+ expect(scene3.prompt).toBe(scene2.prompt);+ });++ it('respects overrides (e.g. flip autoAcceptScenes off for a real-evaluator dry run)', async () => {+ const project = await createSmokeTestProject({ autoAcceptScenes: false });+ expect(project.autoAcceptScenes).toBe(false);+ // Other defaults still applied.+ expect(project.disableAudio).toBe(true);+ });+});diff --git a/server/services/creativeDirector/stitchRunner.js b/server/services/creativeDirector/stitchRunner.jsnew file mode 100644index 0000000000..7b6157fdbf--- /dev/null+++ b/server/services/creativeDirector/stitchRunner.js@@ -0,0 +1,103 @@+/**+ * Creative Director — server-side stitch (final cut) orchestrator.+ *+ * The stitch step is purely mechanical: build a video-timeline project with+ * the accepted scenes' clips, kick off the timeline render, wait for the+ * resulting mp4 to land in `data/video-history.json` (the timeline service+ * appends to it on success), and update the CD project with the final+ * video id + status='complete'.+ *+ * No agent/LLM cognition needed at this stage — there's no decision to+ * make. We removed the previous `stitch` agent task entirely.+ */++import {+ createProject as createTimelineProject,+ updateProject as updateTimelineProject,+ renderProject as renderTimelineProject,+ getRenderJobStatus,+} from '../videoTimeline/local.js';+import { loadHistory } from '../videoGen/local.js';+import { addItem as addCollectionItem } from '../mediaCollections.js';+import { buildTimelineClips } from './orchestrator.js';+import { getProject, updateProject } from './local.js';++const FINAL_RENDER_POLL_MS = 3000;+const FINAL_RENDER_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes — concat is fast but be generous on big projects.++export async function runStitch(projectId) {+ const project = await getProject(projectId);+ if (!project) {+ console.log(`⚠️ CD stitch: project ${projectId} not found`);+ return;+ }+ const clips = buildTimelineClips(project);+ if (!clips.length) {+ console.log(`⚠️ CD stitch: project ${projectId} has no accepted scenes — marking failed`);+ await updateProject(projectId, { status: 'failed', failureReason: 'No accepted scenes to stitch' }).catch(() => {});+ return;+ }++ await updateProject(projectId, { status: 'stitching', failureReason: null });+ console.log(`🎬 CD stitch starting: ${projectId} (${clips.length} clips)`);++ try {+ const timeline = await createTimelineProject(`${project.name} — Final Cut`);+ await updateTimelineProject(timeline.id, { clips });+ await updateProject(projectId, { timelineProjectId: timeline.id });++ const { jobId } = await renderTimelineProject(timeline.id);++ // Poll video-history.json for an entry tagged with our timelineProjectId.+ // The timeline service appends a history entry at the end of a successful+ // render with `timelineProjectId` set, so when we see it the mp4 is on+ // disk. In parallel, check the job's in-memory status so an ffmpeg failure+ // breaks out of the loop within seconds instead of waiting 30 minutes.+ const deadline = Date.now() + FINAL_RENDER_TIMEOUT_MS;+ let finalEntry = null;+ while (Date.now() < deadline) {+ // Fast-fail: if the render job itself has entered an error/cancelled+ // state, there will never be a history entry — bail immediately.+ const jobStatus = getRenderJobStatus(jobId);+ if (jobStatus && (jobStatus.status === 'error' || jobStatus.status === 'cancelled')) {+ const reason = jobStatus.error ?? `Render ${jobStatus.status}`;+ console.log(`❌ CD stitch: timeline render ${jobStatus.status} for ${timeline.id}: ${reason}`);+ await updateProject(projectId, { status: 'failed', failureReason: reason });+ return;+ }++ const history = await loadHistory().catch(() => []);+ finalEntry = history.find((h) => h.id === jobId || h.timelineProjectId === timeline.id);+ if (finalEntry) break;+ await sleep(FINAL_RENDER_POLL_MS);+ }++ if (!finalEntry) {+ const reason = 'Timeline render timed out';+ console.log(`⚠️ CD stitch: ${reason} for ${timeline.id}`);+ await updateProject(projectId, { status: 'failed', failureReason: reason });+ return;+ }++ await updateProject(projectId, {+ finalVideoId: finalEntry.id,+ status: 'complete',+ failureReason: null,+ });+ // Best-effort: append the final cut to the project's collection so it sits+ // alongside the segment renders.+ if (project.collectionId) {+ await addCollectionItem(project.collectionId, { kind: 'video', ref: finalEntry.id })+ .catch((e) => console.log(`⚠️ CD stitch addCollectionItem failed: ${e.message}`));+ }+ console.log(`✅ CD stitch complete: ${projectId} → ${finalEntry.id.slice(0, 8)}`);+ } catch (err) {+ const reason = err?.message ?? String(err);+ console.log(`❌ CD stitch error for ${projectId}: ${reason}`);+ await updateProject(projectId, { status: 'failed', failureReason: reason }).catch(() => {});+ }+}++function sleep(ms) {+ return new Promise((r) => setTimeout(r, ms));+}diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex b5068cc241..764538b5af 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -156,12 +156,12 @@ export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, hereturn { bin, args };};-export async function generateImage({ pythonPath, prompt, negativePrompt = '', modelId = 'dev', width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [], initImagePath = null, initImageStrength = null }) {+export async function generateImage({ pythonPath, prompt, negativePrompt = '', modelId = 'dev', width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [], initImagePath = null, initImageStrength = null, jobId: providedJobId = null }) {if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });- // Enforce the single-activeProcess invariant the rest of this module relies- // on — without this, a double-click on Generate would orphan the first- // child (cancel() can only kill the one stored in activeProcess).- if (activeProcess) throw new ServerError('A generation is already in progress — cancel it before starting another', { status: 409, code: 'IMAGE_GEN_BUSY' });+ // Single-flight is enforced by the mediaJobQueue worker upstream. Direct+ // callers that bypass the queue must not run two concurrent renders — the+ // activeProcess handle below would be clobbered and cancel() would orphan+ // the first child.// Use the registry cache view (which applies the per-platform `broken`// filter via getImageModels) rather than the module-load IMAGE_MODELS// snapshot. Note: loadMediaModels memoizes on first read — on-disk edits@@ -187,7 +187,7 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', mawait ensureDir(PATHS.images);await ensureDir(PATHS.loras);- const jobId = randomUUID();+ const jobId = providedJobId || randomUUID();const filename = `${jobId}.png`;const outputPath = join(PATHS.images, filename);const actualSeed = seed != null && seed !== '' ? Number(seed) : Math.floor(Math.random() * 2147483647);diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsnew file mode 100644index 0000000000..b336c55ad7--- /dev/null+++ b/server/services/mediaJobQueue/index.js@@ -0,0 +1,649 @@+/**+ * Media Job Queue — single-worker FIFO for image + video gen jobs.+ *+ * Why this exists: video gen (mlx_video) and image gen (mflux/diffusers) both+ * spawn heavy GPU/Metal child processes. Running two simultaneously OOMs the+ * machine, so the gen modules used to throw 409 BUSY when one was already in+ * flight. That made any agent-driven pipeline (e.g. Creative Director) need+ * to retry/backoff. This queue serializes submissions so callers always get+ * an immediate `queued` ack and watch progress via SSE.+ *+ * Scope: gates `videoGen/local#generateVideo` (always) and+ * `imageGen/local#generateImage` (only when imageGen mode === 'local'). The+ * external/codex image-gen backends bypass the queue — they don't share the+ * MLX runtime so they can run concurrently with anything in the queue.+ *+ * Persistence: data/media-jobs.json holds queued + running + recently-finished+ * jobs. On boot, any 'running' is reclassified as 'failed (interrupted by+ * restart)' since the spawned child died with the previous server process.+ * Completed/failed/canceled entries older than 24h or beyond the 500-most-+ * recent are pruned to keep the file small.+ */++import { EventEmitter } from 'events';+import { randomUUID } from 'crypto';+import { unlink } from 'fs/promises';+import { join, resolve as pathResolve, sep as PATH_SEP } from 'path';+import { PATHS, readJSONFile, atomicWrite, ensureDir } from '../../lib/fileUtils.js';+import {+ broadcastSse,+ attachSseClient as attachSse,+ closeJobAfterDelay,+} from '../../lib/sseUtils.js';+import { videoGenEvents } from '../videoGen/events.js';+import { imageGenEvents } from '../imageGenEvents.js';++const JOBS_FILE = join(PATHS.data, 'media-jobs.json');+const COMPLETED_TTL_MS = 24 * 60 * 60 * 1000;+const MAX_PERSISTED_ARCHIVE = 500;+// Defaults (env-overridable). `Number(non-numeric)` → NaN, and+// `setTimeout(NaN)` fires immediately — that would fail every job at boot+// if MEDIA_JOB_WATCHDOG_*_MS were set to garbage. Fall back to the default+// when the parsed value isn't a positive finite number.+const watchdogMs = (envValue, defaultMs) => {+ const n = Number(envValue);+ return Number.isFinite(n) && n > 0 ? n : defaultMs;+};+const WATCHDOG_VIDEO_MS = watchdogMs(process.env.MEDIA_JOB_WATCHDOG_VIDEO_MS, 30 * 60 * 1000);+const WATCHDOG_IMAGE_MS = watchdogMs(process.env.MEDIA_JOB_WATCHDOG_IMAGE_MS, 5 * 60 * 1000);++// Returns true if `p` resolves strictly under PATHS.uploads. Shared by+// safeUnlinkUpload (cleanup) and the pre-gen sanitizer (Thread #1 guard).+function isUnderUploadsRoot(p) {+ if (typeof p !== 'string') return false;+ const uploadsRoot = `${pathResolve(PATHS.uploads)}${PATH_SEP}`;+ return pathResolve(p).startsWith(uploadsRoot);+}++// Defense-in-depth helper for cleaning up staged multipart uploads. Job+// params are persisted (and replayed on boot), so a corrupted media-jobs.json+// or a buggy caller could otherwise feed an arbitrary path into unlink().+// Confine deletion to PATHS.uploads — the routes (videoGen.js, imageGen.js)+// always copy multipart uploads into that directory before enqueueing, so+// any legitimate `uploadedTempPath` is under that root.+async function safeUnlinkUpload(path) {+ if (!path || typeof path !== 'string') return;+ if (!isUnderUploadsRoot(path)) {+ console.log(`⚠️ mediaJobQueue refused to unlink path outside PATHS.uploads: ${path}`);+ return;+ }+ await unlink(path).catch(() => {});+}++export const JOB_KINDS = Object.freeze(['video', 'image']);+export const JOB_STATUSES = Object.freeze(['queued', 'running', 'completed', 'failed', 'canceled']);++export const mediaJobEvents = new EventEmitter();++// Live state. Single worker → at most one job in `running` at a time. `queue`+// holds pending jobs in submission order. `archive` holds recently-finished+// jobs (visible for ~24h via /api/media-jobs?status=completed).+const queue = [];+let running = null;+const archive = [];++// jobId → entry consumed by lib/sseUtils.js#{broadcastSse,attachSseClient,+// closeJobAfterDelay}. Each entry carries `clients: []` and `lastPayload`,+// so we can hand it directly to those helpers. Survives the queued→running+// transition so a client that attached during queue keeps its stream open+// through the render and final completion. Entries are removed after+// SSE_CLEANUP_DELAY_MS by closeJobAfterDelay on terminal events.+const sseJobs = new Map();++let workerStarted = false;+let initPromise = null;++function findJob(jobId) {+ if (running && running.id === jobId) return running;+ const inQueue = queue.find((j) => j.id === jobId);+ if (inQueue) return inQueue;+ return archive.find((j) => j.id === jobId) || null;+}++export function getJob(jobId) {+ return findJob(jobId);+}++export function listJobs({ status, kind, owner } = {}) {+ const all = [+ ...(running ? [running] : []),+ ...queue,+ ...archive,+ ];+ return all.filter((j) => {+ if (status && j.status !== status) return false;+ if (kind && j.kind !== kind) return false;+ if (owner && j.owner !== owner) return false;+ return true;+ });+}++// Serialize persist() calls through a single chain. atomicWrite rename can+// finish out-of-order under concurrent calls, so a slow "start" persist+// landing after a fast "done" persist would regress the on-disk snapshot+// (e.g. completed→running). Chaining ensures every snapshot reflects the+// state at its enqueue time, in submission order.+let persistChain = Promise.resolve();+function persist() {+ persistChain = persistChain.then(persistImpl, persistImpl);+ return persistChain;+}+async function persistImpl() {+ const cutoff = Date.now() - COMPLETED_TTL_MS;+ const trimmedArchive = archive+ .filter((j) => {+ const ts = j.completedAt ? new Date(j.completedAt).getTime() : Date.now();+ return ts > cutoff;+ })+ .slice(-MAX_PERSISTED_ARCHIVE);+ // Mutate `archive` in place so subsequent reads see the trim too.+ archive.length = 0;+ archive.push(...trimmedArchive);+ const live = [+ ...(running ? [running] : []),+ ...queue,+ ...archive,+ ];+ // Strip non-serializable bits.+ const serializable = live.map(({ id, kind, owner, status, queuedAt, startedAt, completedAt, params, result, error, position }) =>+ ({ id, kind, owner, status, queuedAt, startedAt, completedAt, params, result, error, position }),+ );+ await atomicWrite(JOBS_FILE, { jobs: serializable });+}++export async function initMediaJobQueue() {+ if (initPromise) return initPromise;+ initPromise = (async () => {+ // Once-at-boot: subsequent persist() calls assume the data dir exists.+ await ensureDir(PATHS.data);+ const data = await readJSONFile(JOBS_FILE, { jobs: [] });+ const persistedJobs = Array.isArray(data?.jobs) ? data.jobs : [];+ const restartedFailedIds = [];+ for (const j of persistedJobs) {+ if (j.status === 'running') {+ const failed = {+ ...j,+ status: 'failed',+ error: 'interrupted by restart',+ completedAt: new Date().toISOString(),+ };+ archive.push(failed);+ restartedFailedIds.push(failed.id);+ // The failed job will never reach the worker's cleanup, so any+ // multipart upload it staged into data/uploads would leak forever.+ // safeUnlinkUpload constrains the delete to PATHS.uploads so we+ // never delete a file the job merely referenced (gallery image,+ // prior render, etc).+ safeUnlinkUpload(j.params?.uploadedTempPath);+ } else if (j.status === 'queued') {+ queue.push({ ...j });+ } else {+ archive.push(j);+ }+ }+ // The persisted `position` reflects the previous process' queue layout+ // (which may have included a now-failed running job). Recompute against+ // the current queue so /api/media-jobs and the initial SSE `queued`+ // event report accurate slots.+ queue.forEach((q, i) => { q.position = i + 1; });+ if (persistedJobs.length) {+ console.log(`📦 mediaJobQueue restored: ${queue.length} queued, ${archive.length} archived`);+ }+ // Pre-seed terminal SSE payloads for each restart-failed job so that any+ // client that reconnects to /:jobId/events after a restart (the route+ // attaches via attachSseClient → attachSse, which replays lastPayload)+ // gets an immediate error event instead of a silent stream.+ for (const id of restartedFailedIds) {+ const entry = ensureSseEntry(id);+ broadcastSse(entry, { type: 'error', error: 'interrupted by restart' });+ closeJobAfterDelay(sseJobs, id);+ }+ // Pre-seed SSE entries for recovered queued jobs too. Without this, a+ // client reconnecting to /:jobId/events between boot and the worker+ // dequeueing the job would hit attachSseClient's "no sse entry" branch+ // and synthesize a terminal `error` frame from a still-`queued` archive+ // miss (since the job is in `queue`, not `archive`). The pre-seeded+ // payload also gives the client an immediate `queued` heartbeat with the+ // recomputed position.+ for (const j of queue) {+ const entry = ensureSseEntry(j.id);+ broadcastSse(entry, { type: 'queued', position: j.position });+ }+ await persist();+ startWorker();+ })();+ return initPromise;+}++function startWorker() {+ if (workerStarted) return;+ workerStarted = true;+ // Detach from awaiting so init can return; the loop runs forever.+ drainLoop().catch((err) => {+ console.log(`❌ mediaJobQueue worker crashed: ${err.message}`);+ workerStarted = false;+ });+}++async function drainLoop() {+ while (true) {+ if (running || queue.length === 0) {+ await sleep(150);+ continue;+ }+ const job = queue.shift();+ job.status = 'running';+ job.startedAt = new Date().toISOString();+ // The running job is always slot 1 in the overall pipeline. Without+ // this, a job dequeued from position 2 (queued behind another job that+ // just finished) would keep its old position=2 even while running, and+ // /api/media-jobs would show "running, 2 in queue" when it's really 1.+ job.position = 1;+ running = job;+ // Recompute positions for everyone still queued AND broadcast the new+ // position over SSE so clients listening to /:jobId/events see "you are+ // now #2" instead of staying frozen at the original enqueue-time slot.+ recomputeQueuePositions();+ persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on start failed: ${e.message}`));+ broadcastSse(ensureSseEntry(job.id), { type: 'started', kind: job.kind });+ mediaJobEvents.emit('started', job);+ console.log(`▶️ media-job [${job.id.slice(0, 8)}] ${job.kind} started`);+ // The worker loop is a top-level fire-and-forget — if runJob throws+ // unexpectedly (an unhandled emitter / listener edge case, etc.), an+ // uncaught error here would terminate the loop and freeze the queue+ // until the next enqueueJob re-armed startWorker. Catch + recover so a+ // single bad job can't kill the worker.+ try {+ await runJob(job);+ } catch (err) {+ console.log(`❌ media-job [${job.id.slice(0, 8)}] runJob threw: ${err.message}`);+ if (job.status === 'running') {+ job.status = 'failed';+ job.error = `runJob threw: ${err.message}`;+ job.completedAt = new Date().toISOString();+ broadcastSse(ensureSseEntry(job.id), { type: 'error', error: job.error });+ // Mirror the in-job failed path: schedule SSE cleanup so this rare+ // recovery doesn't leak the sseJobs entry + open clients forever.+ closeJobAfterDelay(sseJobs, job.id);+ mediaJobEvents.emit('failed', job);+ }+ }+ running = null;+ archive.push(job);+ // Now that running is cleared, every queued job has shifted up one slot.+ // Recompute immediately so /api/media-jobs and any subsequent persist()+ // see accurate positions even before the next dequeue, and broadcast+ // the new position to each waiting client.+ recomputeQueuePositions();+ persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on done failed: ${e.message}`));+ }+}++// Recompute queue positions and notify each waiting SSE client of its new+// slot. Called whenever the queue layout shifts (job dequeued, finished, or+// canceled mid-queue). Without the broadcast, a client connected to+// /:jobId/events would keep showing the position from its original enqueue+// frame even after the line ahead of it cleared.+function recomputeQueuePositions() {+ queue.forEach((q, i) => {+ const newPosition = i + 1 + (running ? 1 : 0);+ if (q.position !== newPosition) {+ q.position = newPosition;+ const entry = sseJobs.get(q.id);+ if (entry) broadcastSse(entry, { type: 'queued', position: newPosition });+ }+ });+}++// Filter videoGenEvents/imageGenEvents down to a single jobId and translate+// them into SSE-wire payloads + queue-status transitions. Returns+// `{ attach, detach }` so runJob can deterministically clean up listeners+// even on the throw path.+//+// Event shapes (match the underlying gens):+// videoGen.progress → { generationId, progress: number, step?, totalSteps? }+// imageGen.progress → { generationId, progress: number, step?, totalSteps? }+// imageGen.progress → { generationId, currentImage } (preview-only frames)+// `message` is synthesized from `step` / `totalSteps` so the existing UIs+// (which display `msg.message` as the status line) keep working through+// the queue, even though the underlying emitters don't supply one.+function synthesizeMessage(e, kind) {+ if (typeof e.step === 'number' && typeof e.totalSteps === 'number' && e.totalSteps > 0) {+ const verb = kind === 'video' ? 'Rendering' : 'Generating';+ return `${verb} step ${e.step}/${e.totalSteps}`;+ }+ return undefined;+}+function makeGenDispatcher(emitter, job, handlers) {+ const onProgress = (e) => {+ if (e.generationId !== job.id) return;+ const hasProgress = typeof e.progress === 'number' && Number.isFinite(e.progress);+ const hasCurrentImage = typeof e.currentImage === 'string' && e.currentImage.length > 0;+ const message = e.message !== undefined ? e.message : synthesizeMessage(e, job.kind);+ if (hasProgress) {+ const payload = { type: 'progress', progress: e.progress };+ if (hasCurrentImage) payload.currentImage = e.currentImage;+ if (message !== undefined) payload.message = message;+ handlers.progress(payload);+ return;+ }+ if (hasCurrentImage) {+ // Preview-only frame (imageGen step thumbnail) — distinct SSE type so+ // existing consumers can keep their progress-bar value untouched.+ const payload = { type: 'preview', currentImage: e.currentImage };+ if (message !== undefined) payload.message = message;+ handlers.progress(payload);+ }+ };+ const onStatus = (e) => {+ // Optional explicit `status` event for gens that want to push a status+ // line independent of progress. Unused today; here so a future emitter+ // can call `videoGenEvents.emit('status', { generationId, message })`.+ if (e.generationId !== job.id) return;+ if (typeof e.message === 'string' && e.message.length > 0) {+ handlers.progress({ type: 'status', message: e.message });+ }+ };+ const onCompleted = (e) => { if (e.generationId === job.id) handlers.completed(e); };+ const onFailed = (e) => { if (e.generationId === job.id) handlers.failed({ error: e.error }); };+ return {+ attach() {+ emitter.on('progress', onProgress);+ emitter.on('status', onStatus);+ emitter.on('completed', onCompleted);+ emitter.on('failed', onFailed);+ },+ detach() {+ emitter.off('progress', onProgress);+ emitter.off('status', onStatus);+ emitter.off('completed', onCompleted);+ emitter.off('failed', onFailed);+ },+ };+}++async function runJob(job) {+ const sseEntry = ensureSseEntry(job.id);++ // Single idempotent terminal sink. All terminal paths (completed, failed,+ // canceled, watchdog) funnel through here. The status check at the top+ // ensures only the first caller wins; any subsequent call (e.g. watchdog+ // fired and then the gen emits 'completed') is a no-op.+ let watchdogTimer;+ function terminate(state, apply) {+ if (job.status !== 'running') return;+ clearTimeout(watchdogTimer);+ apply(job);+ job.status = state;+ job.completedAt = new Date().toISOString();+ const logPrefix = state === 'completed' ? '✅' : state === 'canceled' ? '🛑' : '❌';+ const logSuffix = state === 'failed' ? `: ${job.error}` : state === 'canceled' ? ' (was running)' : '';+ console.log(`${logPrefix} media-job [${job.id.slice(0, 8)}] ${state}${logSuffix}`);+ const ssePayload =+ state === 'completed' ? { type: 'complete', result: job.result }+ : state === 'canceled' ? { type: 'canceled', reason: job.error }+ : { type: 'error', error: job.error };+ broadcastSse(sseEntry, ssePayload);+ closeJobAfterDelay(sseJobs, job.id);+ mediaJobEvents.emit(state, job);+ }++ const handlers = {+ progress: (payload) => {+ broadcastSse(sseEntry, payload);+ },+ completed: (payload) => {+ terminate('completed', (j) => { j.result = payload; });+ },+ failed: (payload) => {+ // If cancelJob() flagged this job before the underlying gen reported+ // failure, treat the SIGTERM-induced failure as a clean cancel rather+ // than an error so /api/media-jobs?status=canceled works.+ if (job.cancelRequested) {+ terminate('canceled', (j) => {+ // Persist the reason so a late SSE reconnect after the live entry+ // is cleaned up still gets a meaningful terminal frame from the+ // archived state, rather than the generic "Canceled" fallback.+ j.error = 'Canceled while running';+ });+ return;+ }+ terminate('failed', (j) => { j.error = payload.error || 'unknown error'; });+ },+ };++ // Thread #1: sanitize uploadedTempPath before passing params to the gen+ // module. Even though safeUnlinkUpload guards the *delete* path, the gen+ // module receives the raw job.params spread and could itself act on a+ // corrupted path from a hand-edited media-jobs.json. Null it out here if+ // it doesn't resolve under PATHS.uploads so the constraint holds end-to-end.+ const safeParams = { ...job.params };+ if (safeParams.uploadedTempPath && (typeof safeParams.uploadedTempPath !== 'string' || !isUnderUploadsRoot(safeParams.uploadedTempPath))) {+ console.log(`⚠️ media-job [${job.id.slice(0, 8)}] uploadedTempPath outside PATHS.uploads — nulled before gen invoke: ${safeParams.uploadedTempPath}`);+ safeParams.uploadedTempPath = null;+ }++ const emitter = job.kind === 'video' ? videoGenEvents : imageGenEvents;+ const dispatcher = makeGenDispatcher(emitter, job, handlers);+ dispatcher.attach();++ // Thread #2: per-job watchdog — fires if the gen never emits a terminal+ // event (hung child process or emitter regression). On trigger it marks+ // the job failed via the normal handlers path (SSE + mediaJobEvents ++ // persistence all fire) and best-effort cancels the underlying process+ // so the queue can make forward progress.+ // Renamed from `watchdogMs` to avoid shadowing the top-level+ // `watchdogMs(envValue, defaultMs)` helper that parses the env-var+ // overrides. Both lived as `watchdogMs` previously and made the call+ // site easy to misread.+ const watchdogTimeoutMs = job.kind === 'video' ? WATCHDOG_VIDEO_MS : WATCHDOG_IMAGE_MS;+ watchdogTimer = setTimeout(async () => {+ // Two-stage status guard: first check stops us if the gen settled+ // before the timer fired. The await on the dynamic import below opens+ // a window during which a natural completion / failure could land —+ // re-check after the await so we don't fire `handlers.failed` and+ // SIGTERM the *next* job's child (cancel() targets the gen module's+ // current activeProcess; once handlers.failed marks this job+ // terminal, runJob's await exits and the worker advances).+ if (job.status !== 'running') return;+ const importer = job.kind === 'video'+ ? import('../videoGen/local.js')+ : job.kind === 'image' ? import('../imageGen/local.js') : null;+ const mod = importer ? await importer : null;+ if (job.status !== 'running') return;+ console.log(`⏱️ media-job [${job.id.slice(0, 8)}] watchdog fired after ${watchdogTimeoutMs}ms — marking failed`);+ // Cancel BEFORE marking failed — that ordering keeps the SIGTERM+ // pointed at *this* job's child. The gen module will then emit its+ // own 'failed' event, but the terminate() guard makes it a no-op.+ if (mod?.cancel) mod.cancel();+ handlers.failed({ error: `watchdog timeout: job exceeded ${watchdogTimeoutMs}ms` });+ }, watchdogTimeoutMs);+ // Ensure the timer doesn't keep Node alive after the job settles.+ watchdogTimer.unref?.();++ try {+ if (job.kind === 'video') {+ const { generateVideo } = await import('../videoGen/local.js');+ await generateVideo({ ...safeParams, jobId: job.id });+ } else if (job.kind === 'image') {+ const { generateImage } = await import('../imageGen/local.js');+ await generateImage({ ...safeParams, jobId: job.id });+ } else {+ throw new Error(`Unknown job kind: ${job.kind}`);+ }+ } catch (err) {+ // generateVideo / generateImage threw before reaching their proc.on+ // cleanup hooks (e.g. PYTHON not configured, validation fail). Clean up+ // multipart upload temp files the route handed us so they don't leak+ // under data/uploads. safeUnlinkUpload constrains the delete to+ // PATHS.uploads as defense-in-depth against corrupted persisted params.+ await safeUnlinkUpload(job.params?.uploadedTempPath);+ handlers.failed({ error: err.message });+ }++ // Wait for the underlying gen to settle (the gen modules emit completed/+ // failed asynchronously after the proc closes — runJob's await above only+ // gates the spawn, not the render finish). Handlers flip job.status to a+ // terminal state; short-sleep poll so we don't busy-spin.+ while (job.status === 'running') await sleep(100);+ dispatcher.detach();+}++export function enqueueJob({ kind, params, owner = null }) {+ if (!JOB_KINDS.includes(kind)) {+ throw new Error(`enqueueJob: invalid kind '${kind}'`);+ }+ const id = randomUUID();+ const job = {+ id,+ kind,+ owner,+ status: 'queued',+ queuedAt: new Date().toISOString(),+ params,+ // position counts "where you sit in the overall pipeline" — the running+ // job (if any) occupies slot 1, then queued jobs follow. So the second+ // submission while one is running sits at position 2.+ position: queue.length + (running ? 1 : 0) + 1,+ };+ queue.push(job);+ const sseEntry = ensureSseEntry(id);+ broadcastSse(sseEntry, { type: 'queued', position: job.position });+ mediaJobEvents.emit('enqueued', job);+ persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on enqueue failed: ${e.message}`));+ startWorker();+ console.log(`📥 media-job [${id.slice(0, 8)}] ${kind} queued (position ${job.position})`);+ return { jobId: id, position: job.position, status: 'queued' };+}++// Cancel: drops a queued job, or sends SIGTERM to a running gen process.+export async function cancelJob(jobId) {+ const queueIdx = queue.findIndex((j) => j.id === jobId);+ if (queueIdx >= 0) {+ const [job] = queue.splice(queueIdx, 1);+ // Multipart uploads (e.g. /api/video-gen with an image) hand us a path+ // staged under PATHS.uploads. If we drop the job before it starts,+ // runJob never gets a chance to delete it — clean up here so the+ // uploads dir doesn't accumulate. safeUnlinkUpload constrains the+ // delete to PATHS.uploads.+ await safeUnlinkUpload(job.params?.uploadedTempPath);+ job.status = 'canceled';+ // Persist the cancel reason on the job so a late SSE reconnect (after+ // the live SSE entry was cleaned up) can synthesize the same terminal+ // payload from the archived state — without this, attachSseClient's+ // post-cleanup terminal frame would just say "Canceled" and lose the+ // more specific "Canceled before start" reason we just broadcast.+ job.error = 'Canceled before start';+ job.completedAt = new Date().toISOString();+ archive.push(job);+ // Removing a queued job shifts everyone behind it up one slot. Recompute+ // + broadcast so clients still attached to those SSE streams see the new+ // position immediately, instead of waiting for the next dequeue.+ recomputeQueuePositions();+ const sseEntry = ensureSseEntry(jobId);+ // Emit `canceled` (not `error`) so clients can distinguish a user-+ // initiated cancellation from a real failure. Mirror the event type+ // emitted for running-job cancellation in runJob's failed handler.+ broadcastSse(sseEntry, { type: 'canceled', reason: job.error });+ closeJobAfterDelay(sseJobs, jobId);+ mediaJobEvents.emit('canceled', job);+ persist().catch(() => {});+ console.log(`🛑 media-job [${jobId.slice(0, 8)}] canceled (was queued)`);+ return { ok: true, status: 'canceled' };+ }+ if (running && running.id === jobId) {+ // Flag the job so the dispatcher's `failed` handler treats the SIGTERM-+ // induced failure as `canceled` rather than `failed`. Without this the+ // job would land in archive with status='failed' and listing by+ // status='canceled' would be empty for running cancels.+ running.cancelRequested = true;+ if (running.kind === 'video') {+ const { cancel } = await import('../videoGen/local.js');+ cancel();+ } else if (running.kind === 'image') {+ const { cancel } = await import('../imageGen/local.js');+ cancel();+ }+ console.log(`🛑 media-job [${jobId.slice(0, 8)}] cancel signal sent (was running)`);+ return { ok: true, status: 'canceling' };+ }+ // Distinguish "no such id" from "id exists but is already terminal" so+ // the route layer can map the right HTTP status (404 vs 409).+ const archived = archive.find((j) => j.id === jobId);+ if (archived) {+ return { ok: false, code: 'ALREADY_TERMINAL', status: archived.status, error: `Job is already ${archived.status}` };+ }+ return { ok: false, code: 'NOT_FOUND', error: 'Job not found' };+}++function ensureSseEntry(jobId) {+ if (!sseJobs.has(jobId)) {+ // Shape required by lib/sseUtils.js#{broadcastSse,attachSseClient}.+ sseJobs.set(jobId, { clients: [], lastPayload: null });+ }+ return sseJobs.get(jobId);+}++// Routes call this. Returns false when the jobId is unknown to the queue.+//+// Three cases:+// 1. Live job (queued/running) — sseJobs already has an entry created by+// enqueueJob; attach replays lastPayload (queued/started/progress).+// 2. Terminal job within the SSE_CLEANUP_DELAY_MS grace window — entry is+// still around with the terminal lastPayload (complete/error/canceled),+// so attach immediately replays + the deferred close ends the stream.+// 3. Terminal job after the grace window — entry is gone; we synthesize a+// one-shot terminal frame from the archived job and end the stream so+// a late client doesn't hang on an empty SSE stream forever.+export function attachSseClient(jobId, res) {+ const job = findJob(jobId);+ if (!job) return false;+ if (sseJobs.has(jobId)) {+ return attachSse(sseJobs, jobId, res);+ }+ // No SSE entry but the job is still live (queued/running) — the entry was+ // dropped or never created (e.g. crash recovery). Create one on the fly+ // and attach so the client receives subsequent progress/terminal events+ // rather than a synthetic `error` frame for a job that is still running.+ if (job.status === 'queued' || job.status === 'running') {+ const entry = ensureSseEntry(jobId);+ // Seed a heartbeat so the freshly-attached client sees the current+ // status immediately instead of waiting for the next worker emit.+ const heartbeat = job.status === 'queued'+ ? { type: 'queued', position: job.position }+ : { type: 'started', kind: job.kind };+ broadcastSse(entry, heartbeat);+ return attachSse(sseJobs, jobId, res);+ }+ // Terminal job whose SSE entry was already cleaned up. Synthesize the+ // expected terminal payload from the archived state and end immediately.+ const terminal =+ job.status === 'completed' ? { type: 'complete', result: job.result }+ : job.status === 'canceled' ? { type: 'canceled', reason: job.error || 'Canceled' }+ : { type: 'error', error: job.error || `Job ${job.status}` };+ res.writeHead(200, {+ 'Content-Type': 'text/event-stream',+ 'Cache-Control': 'no-cache',+ Connection: 'keep-alive',+ });+ res.write(`data: ${JSON.stringify(terminal)}\n\n`);+ res.end();+ return true;+}++function sleep(ms) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++// Test-only reset hook. Real callers go through enqueueJob/cancelJob.+export function __resetForTests() {+ queue.length = 0;+ running = null;+ archive.length = 0;+ sseJobs.clear();+ workerStarted = false;+ initPromise = null;+ // Reset the persist chain so a leftover rejection from a previous test's+ // ENOENT writes doesn't poison subsequent persist() calls.+ persistChain = Promise.resolve();+}diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsnew file mode 100644index 0000000000..22ae428d76--- /dev/null+++ b/server/services/mediaJobQueue/index.test.js@@ -0,0 +1,428 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, existsSync, readFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++// The queue persists to data/media-jobs.json. Steer it at a temp dir so each+// test gets a clean slate without scribbling over the real data dir.+let tempDataDir;++vi.mock('../../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../../lib/fileUtils.js');+ return {+ ...actual,+ // Override PATHS so JOBS_FILE lands in the temp dir. We can't read the+ // temp path here at module-load time (vi.mock is hoisted before the test+ // creates the dir), so expose a setter the tests use.+ PATHS: new Proxy({}, {+ get(_, key) {+ if (key === 'data') return tempDataDir;+ return actual.PATHS[key];+ },+ }),+ };+});++// Mock the gen modules so the worker's dynamic imports return controllable+// stubs. The dispatcher relies on videoGenEvents / imageGenEvents to fire+// 'completed' or 'failed' for the worker to advance — we drive those events+// directly from each test.+const stubs = {+ generateVideo: vi.fn(async () => ({ jobId: 'whatever' })),+ generateImage: vi.fn(async () => ({ jobId: 'whatever' })),+ cancelVideo: vi.fn(),+ cancelImage: vi.fn(),+};++vi.mock('../videoGen/local.js', () => ({+ generateVideo: (...args) => stubs.generateVideo(...args),+ cancel: (...args) => stubs.cancelVideo(...args),+}));++vi.mock('../imageGen/local.js', () => ({+ generateImage: (...args) => stubs.generateImage(...args),+ cancel: (...args) => stubs.cancelImage(...args),+}));++// Import the queue + the gen-event emitters AFTER the mocks above are+// registered. Static imports would race with vi.mock hoisting on a real+// dependency cycle, so dynamic-import this in beforeEach.+let mediaJobQueue;+let videoGenEvents;+let imageGenEvents;++async function importFresh() {+ vi.resetModules();+ mediaJobQueue = await import('./index.js');+ videoGenEvents = (await import('../videoGen/events.js')).videoGenEvents;+ imageGenEvents = (await import('../imageGenEvents.js')).imageGenEvents;+}++const flush = () => new Promise((r) => setTimeout(r, 250));++beforeEach(async () => {+ tempDataDir = mkdtempSync(join(tmpdir(), 'mediaJobQueue-test-'));+ Object.values(stubs).forEach((fn) => fn.mockReset());+ await importFresh();+});++afterEach(() => {+ if (tempDataDir && existsSync(tempDataDir)) {+ rmSync(tempDataDir, { recursive: true, force: true });+ }+});++describe('mediaJobQueue', () => {+ it('enqueueJob returns jobId + queued status + position', () => {+ // Block the worker so the second enqueue lands behind the first in the+ // pipeline rather than entering an empty queue after the first ran.+ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));+ const r1 = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'a' } });+ const r2 = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'b' } });+ expect(r1.status).toBe('queued');+ expect(r1.jobId).toMatch(/^[0-9a-f-]{36}$/);+ expect(r1.position).toBe(1);+ expect(r2.position).toBe(2);+ });++ it('rejects unknown kinds', () => {+ expect(() => mediaJobQueue.enqueueJob({ kind: 'audio', params: {} })).toThrow(/invalid kind/);+ });++ it('listJobs filters by kind / status / owner', async () => {+ // Pin the first dequeued job in 'running' indefinitely so the rest of+ // the assertions see the queue + running set we expect.+ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));+ stubs.generateImage.mockImplementation(() => new Promise(() => {}));+ mediaJobQueue.enqueueJob({ kind: 'video', params: {}, owner: 'creative-director:cd-1' });+ mediaJobQueue.enqueueJob({ kind: 'image', params: {}, owner: 'voice' });+ mediaJobQueue.enqueueJob({ kind: 'video', params: {}, owner: 'creative-director:cd-2' });+ expect(mediaJobQueue.listJobs({ kind: 'video' })).toHaveLength(2);+ expect(mediaJobQueue.listJobs({ kind: 'image' })).toHaveLength(1);+ expect(mediaJobQueue.listJobs({ owner: 'voice' })).toHaveLength(1);+ // One job is 'running' (worker dequeued it), the other two are still 'queued'.+ expect(mediaJobQueue.listJobs({ status: 'queued' })).toHaveLength(2);+ expect(mediaJobQueue.listJobs({ status: 'running' })).toHaveLength(1);+ });++ it('cancelJob drops a queued job before it starts', async () => {+ // Block the worker by making the first job hang — generateVideo never+ // resolves, so subsequent enqueues stay queued for cancellation.+ let resolveBlocker;+ stubs.generateVideo.mockImplementation(() => new Promise((r) => { resolveBlocker = r; }));+ const blocker = mediaJobQueue.enqueueJob({ kind: 'video', params: {} });+ const target = mediaJobQueue.enqueueJob({ kind: 'video', params: {} });++ await flush();++ const result = await mediaJobQueue.cancelJob(target.jobId);+ expect(result.ok).toBe(true);+ expect(result.status).toBe('canceled');+ const job = mediaJobQueue.getJob(target.jobId);+ expect(job.status).toBe('canceled');++ // Unblock the first one for cleanup.+ videoGenEvents.emit('failed', { generationId: blocker.jobId, error: 'cleanup' });+ if (resolveBlocker) resolveBlocker();+ await flush();+ });++ it('worker drains a queued video job and marks it completed on the gen completed event', async () => {+ const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'hi' } });+ // Wait until the worker invokes generateVideo. The stub records the call.+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);+ // The queue passed our jobId through so the gen module would write to+ // a deterministic file.+ expect(stubs.generateVideo).toHaveBeenCalledWith(expect.objectContaining({ jobId: job.jobId, prompt: 'hi' }));++ // Simulate the gen module finishing. The dispatcher attached a listener+ // on videoGenEvents 'completed' for our jobId and flips the queue's job+ // status.+ videoGenEvents.emit('completed', {+ generationId: job.jobId,+ filename: `${job.jobId}.mp4`,+ path: `/data/videos/${job.jobId}.mp4`,+ });+ await waitFor(() => mediaJobQueue.getJob(job.jobId).status === 'completed');++ const finished = mediaJobQueue.getJob(job.jobId);+ expect(finished.status).toBe('completed');+ expect(finished.completedAt).toBeTruthy();+ expect(finished.result?.path).toBe(`/data/videos/${job.jobId}.mp4`);+ });++ it('boot recovery: persisted "running" jobs are reclassified as failed', async () => {+ const interruptedId = '00000000-0000-4000-8000-000000000001';+ const persisted = {+ jobs: [+ {+ id: interruptedId,+ kind: 'video',+ status: 'running',+ queuedAt: '2026-04-30T10:00:00.000Z',+ startedAt: '2026-04-30T10:00:01.000Z',+ params: {},+ },+ ],+ };+ writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify(persisted, null, 2));++ await importFresh();+ await mediaJobQueue.initMediaJobQueue();++ const recovered = mediaJobQueue.getJob(interruptedId);+ expect(recovered).toBeTruthy();+ expect(recovered.status).toBe('failed');+ expect(recovered.error).toMatch(/interrupted by restart/);+ });++ it('boot recovery: persisted "queued" jobs are re-enqueued for the worker', async () => {+ const queuedId = '00000000-0000-4000-8000-000000000002';+ const persisted = {+ jobs: [+ {+ id: queuedId,+ kind: 'video',+ status: 'queued',+ queuedAt: '2026-04-30T10:00:00.000Z',+ params: { prompt: 'restart-me' },+ },+ ],+ };+ writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify(persisted, null, 2));++ await importFresh();+ await mediaJobQueue.initMediaJobQueue();++ // Worker should pick the recovered job and call generateVideo with the+ // original jobId so SSE clients keyed off it still resolve.+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);+ expect(stubs.generateVideo).toHaveBeenCalledWith(expect.objectContaining({+ jobId: queuedId,+ prompt: 'restart-me',+ }));+ });++ it('persists state to media-jobs.json on enqueue / completion', async () => {+ const file = join(tempDataDir, 'media-jobs.json');+ const job = mediaJobQueue.enqueueJob({ kind: 'video', params: {} });+ await waitFor(() => existsSync(file));+ const initial = JSON.parse(readFileSync(file, 'utf-8'));+ expect(initial.jobs.find((j) => j.id === job.jobId)).toBeTruthy();++ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);+ videoGenEvents.emit('completed', { generationId: job.jobId, filename: `${job.jobId}.mp4` });+ // After completion the worker calls persist() fire-and-forget, so wait+ // for the file to actually reflect the new status before asserting.+ await waitFor(() => {+ const data = JSON.parse(readFileSync(file, 'utf-8'));+ const j = data.jobs.find((x) => x.id === job.jobId);+ return j?.status === 'completed';+ });+ });++ it('failed gen events propagate to job status', async () => {+ const job = mediaJobQueue.enqueueJob({ kind: 'image', params: { prompt: 'hi' } });+ await waitFor(() => stubs.generateImage.mock.calls.length === 1);+ imageGenEvents.emit('failed', { generationId: job.jobId, error: 'OOM' });+ await waitFor(() => mediaJobQueue.getJob(job.jobId).status === 'failed');++ const failed = mediaJobQueue.getJob(job.jobId);+ expect(failed.status).toBe('failed');+ expect(failed.error).toBe('OOM');+ });++ it('pre-gen sanitizer nulls uploadedTempPath that resolves outside PATHS.uploads', async () => {+ // Any path that is not under the uploads root should be nulled out so the+ // gen module never sees it (defense-in-depth against corrupted job params).+ const job = mediaJobQueue.enqueueJob({+ kind: 'video',+ params: { prompt: 'x', uploadedTempPath: '/etc/passwd' },+ });+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);+ const callArgs = stubs.generateVideo.mock.calls[0][0];+ // The gen module must receive a nulled path, not the original dangerous one.+ expect(callArgs.uploadedTempPath).toBeNull();++ videoGenEvents.emit('completed', { generationId: job.jobId, filename: `${job.jobId}.mp4` });+ await waitFor(() => mediaJobQueue.getJob(job.jobId).status === 'completed');+ });++ it('watchdog fires and marks the job failed when gen never emits a terminal event', async () => {+ // Use a very short watchdog for this test by overriding the env var before+ // the module is loaded. Re-import the module with MEDIA_JOB_WATCHDOG_VIDEO_MS=50.+ process.env.MEDIA_JOB_WATCHDOG_VIDEO_MS = '50';+ await importFresh();+ // generateVideo hangs forever — never emits completed/failed.+ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));++ const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'hang' } });+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);++ // The watchdog should fire within 50 ms and fail the job.+ await waitFor(() => mediaJobQueue.getJob(job.jobId)?.status === 'failed', { timeoutMs: 2000 });++ const failed = mediaJobQueue.getJob(job.jobId);+ expect(failed.status).toBe('failed');+ expect(failed.error).toMatch(/watchdog timeout/);++ delete process.env.MEDIA_JOB_WATCHDOG_VIDEO_MS;+ });++ it('terminal handlers are idempotent: watchdog then gen emit causes only one mediaJobEvents.failed', async () => {+ // Short watchdog so we can trigger it quickly in tests.+ process.env.MEDIA_JOB_WATCHDOG_VIDEO_MS = '50';+ await importFresh();++ // generateVideo hangs so watchdog fires first.+ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));++ const failedEmits = [];+ const completedEmits = [];+ mediaJobQueue.mediaJobEvents.on('failed', (j) => failedEmits.push(j.id));+ mediaJobQueue.mediaJobEvents.on('completed', (j) => completedEmits.push(j.id));++ const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'double-terminal' } });+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);++ // Let the watchdog fire and confirm the job lands as failed.+ await waitFor(() => mediaJobQueue.getJob(job.jobId)?.status === 'failed', { timeoutMs: 2000 });+ expect(failedEmits).toHaveLength(1);++ // Now the underlying gen (late) emits completed — must be a no-op.+ videoGenEvents.emit('completed', { generationId: job.jobId, filename: `${job.jobId}.mp4` });+ await flush();++ // Still only one failed emit, zero completed emits, status unchanged.+ expect(failedEmits).toHaveLength(1);+ expect(completedEmits).toHaveLength(0);+ expect(mediaJobQueue.getJob(job.jobId).status).toBe('failed');++ delete process.env.MEDIA_JOB_WATCHDOG_VIDEO_MS;+ });++ // Regression: a client that reconnects to /:jobId/events for a queued job+ // recovered from media-jobs.json (or one that never had an SSE entry for+ // any reason) must NOT receive a synthetic terminal `error` frame just+ // because no SSE entry exists yet. The fix pre-seeds an entry on boot and+ // attachSseClient creates one on the fly for live (queued/running) jobs.+ it('attachSseClient on a recovered queued job seeds an SSE entry instead of terminating', async () => {+ // Block the worker so the recovered queued job stays queued for the+ // duration of the test (we want to assert the queued-attach path, not+ // the running-attach path).+ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));+ const queuedId = '00000000-0000-4000-8000-000000000003';+ const persisted = {+ jobs: [+ {+ id: queuedId,+ kind: 'video',+ status: 'queued',+ queuedAt: '2026-04-30T10:00:00.000Z',+ params: { prompt: 'hi' },+ },+ ],+ };+ writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify(persisted, null, 2));+ await importFresh();+ await mediaJobQueue.initMediaJobQueue();++ // Fake response that captures writeHead/write/end calls so we can assert+ // the route did NOT short-circuit with a terminal `error` frame. `req.on`+ // is required by lib/sseUtils.js#attachSseClient (it wires a 'close'+ // listener to clean up the client list).+ const writes = [];+ const fakeRes = {+ writeHead: vi.fn(),+ write: vi.fn((s) => writes.push(s)),+ end: vi.fn(),+ req: { on: vi.fn() },+ };+ const ok = mediaJobQueue.attachSseClient(queuedId, fakeRes);+ expect(ok).toBe(true);+ // The seeded payload is `queued`, OR `started` if the worker raced ahead+ // and picked the job before we attached. Either way is a valid replay of+ // real lifecycle state — the regression we're guarding against is the+ // pre-fix path that terminated the response with .end() and emitted no+ // payload at all.+ const written = writes.join('');+ expect(written).toMatch(/"type":"(queued|started)"/);+ expect(written).not.toMatch(/"type":"error"/);+ expect(fakeRes.end).not.toHaveBeenCalled();+ });++ it('non-string uploadedTempPath (number) on a persisted job does not throw on enqueue', async () => {+ const jobId = '00000000-0000-4000-8000-000000000010';+ const persisted = {+ jobs: [+ {+ id: jobId,+ kind: 'video',+ status: 'queued',+ queuedAt: '2026-04-30T10:00:00.000Z',+ params: { prompt: 'corrupted', uploadedTempPath: 12345 },+ },+ ],+ };+ writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify(persisted, null, 2));+ await importFresh();+ await expect(mediaJobQueue.initMediaJobQueue()).resolves.not.toThrow();+ // Worker should call generateVideo with uploadedTempPath nulled out (sanitizer fired).+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);+ const callArgs = stubs.generateVideo.mock.calls[0][0];+ expect(callArgs.uploadedTempPath).toBeNull();+ videoGenEvents.emit('completed', { generationId: jobId, filename: `${jobId}.mp4` });+ await waitFor(() => mediaJobQueue.getJob(jobId)?.status === 'completed');+ });++ it('non-string uploadedTempPath (object) on a persisted job does not throw on enqueue', async () => {+ const jobId = '00000000-0000-4000-8000-000000000011';+ const persisted = {+ jobs: [+ {+ id: jobId,+ kind: 'video',+ status: 'queued',+ queuedAt: '2026-04-30T10:00:00.000Z',+ params: { prompt: 'corrupted', uploadedTempPath: { evil: true } },+ },+ ],+ };+ writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify(persisted, null, 2));+ await importFresh();+ await expect(mediaJobQueue.initMediaJobQueue()).resolves.not.toThrow();+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);+ const callArgs = stubs.generateVideo.mock.calls[0][0];+ expect(callArgs.uploadedTempPath).toBeNull();+ videoGenEvents.emit('completed', { generationId: jobId, filename: `${jobId}.mp4` });+ await waitFor(() => mediaJobQueue.getJob(jobId)?.status === 'completed');+ });++ it('watchdog falls back to default when env var is non-numeric (does not fire immediately)', async () => {+ // setTimeout(NaN) effectively fires synchronously, which would fail every+ // job at boot. Confirm the parser rejects non-numeric strings and falls+ // back to the default — by checking the job is still 'running' shortly+ // after enqueue, despite the deliberately bogus env var.+ process.env.MEDIA_JOB_WATCHDOG_VIDEO_MS = 'not-a-number';+ await importFresh();+ stubs.generateVideo.mockImplementation(() => new Promise(() => {})); // hang forever++ const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'guard' } });+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);++ // Wait a beat — long enough that a NaN-driven watchdog would have fired.+ await new Promise((r) => setTimeout(r, 100));+ expect(mediaJobQueue.getJob(job.jobId)?.status).toBe('running');++ delete process.env.MEDIA_JOB_WATCHDOG_VIDEO_MS;+ });+});++async function waitFor(predicate, { timeoutMs = 3000, intervalMs = 30 } = {}) {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ if (predicate()) return;+ await new Promise((r) => setTimeout(r, intervalMs));+ }+ throw new Error('waitFor: predicate never became true within timeout');+}diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex edcd780a74..d659df4756 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -119,12 +119,13 @@ const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width,return { bin: pythonPath, args };};-export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = 768, height = 512, numFrames = 121, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, lastImagePath = null, mode = null, imageStrength = null }) {+export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = 768, height = 512, numFrames = 121, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, lastImagePath = null, mode = null, imageStrength = null, jobId: providedJobId = null }) {if (!pythonPath) throw new ServerError('Python path not configured — set it in Settings > Image Gen', { status: 400, code: 'VIDEO_GEN_NOT_CONFIGURED' });if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });- // Enforce the single-activeProcess invariant — without this a double-submit- // would orphan the first child (cancel() only kills the one in activeProcess).- if (activeProcess) throw new ServerError('A video generation is already in progress — cancel it before starting another', { status: 409, code: 'VIDEO_GEN_BUSY' });+ // Single-flight is now enforced by the mediaJobQueue worker upstream — only+ // one job is dequeued at a time, so we don't need a BUSY guard here. Direct+ // callers (legacy / tests) bypass the queue and would clobber activeProcess+ // on concurrent calls; that's an explicit "don't do that" contract.const model = VIDEO_MODELS[modelId];if (!model) throw new ServerError(`Unknown video model: ${modelId}`, { status: 400, code: 'VALIDATION_ERROR' });@@ -138,7 +139,9 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', mawait ensureDir(PATHS.videos);await ensureDir(PATHS.videoThumbnails);- const jobId = randomUUID();+ // jobId may be supplied by the queue so SSE clients (which attached against+ // the queue's id) reach the same generation events.+ const jobId = providedJobId || randomUUID();const filename = `${jobId}.mp4`;const outputPath = join(PATHS.videos, filename);const w = Math.floor(Number(width) / 64) * 64;diff --git a/server/services/videoTimeline/local.js b/server/services/videoTimeline/local.jsindex 98074b46e2..e6ed312623 100644--- a/server/services/videoTimeline/local.js+++ b/server/services/videoTimeline/local.js@@ -34,6 +34,19 @@ const projectRenders = new Map(); // projectId → jobIdexport const attachSseClient = (jobId, res) => attachSse(jobs, jobId, res);+/**+ * Return the current status of a render job, or null if unknown.+ * Lets external callers (e.g. stitchRunner) detect ffmpeg failures fast+ * instead of waiting for a polling timeout.+ * @param {string} jobId+ * @returns {{ status: string, error?: string } | null}+ */+export function getRenderJobStatus(jobId) {+ const job = jobs.get(jobId);+ if (!job) return null;+ return { status: job.status, error: job.lastError };+}+// =====================================================================// Project CRUD// =====================================================================@@ -394,6 +407,7 @@ export async function renderProject(projectId) {proc.on('error', (err) => {job.status = 'error';const reason = `Failed to spawn ffmpeg: ${err.message}`;+ job.lastError = reason;console.log(`❌ Timeline render spawn error [${jobId.slice(0, 8)}]: ${reason}`);broadcastSse(job, { type: 'error', error: reason });projectRenders.delete(projectId);@@ -408,6 +422,7 @@ export async function renderProject(projectId) {const reason = cancelled? 'Render cancelled': signal ? `Killed by signal ${signal}` : `ffmpeg exit ${code}`;+ job.lastError = reason;console.log(`${cancelled ? '🛑' : '❌'} Timeline render ${cancelled ? 'cancelled' : 'failed'} [${jobId.slice(0, 8)}]: ${reason}`);await unlink(outputPath).catch(() => {});broadcastSse(job, { type: cancelled ? 'cancelled' : 'error', error: reason });