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 + 24 rounds of fixes (#199)
[._.]/ Adam Eivy0a1c7e5f5e62
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 036e7536e2..45e584cc3b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,27 +1,58 @@-# Unreleased Changes--## Fixed--- Video Gen audio uploads (a2v mode) were rejected with "File type not allowed" even for valid MP3/WAV files — the multipart parser was missing `fieldname` on the file metadata it passed to the upload filter, so every per-field MIME check silently evaluated to false. Fixed by including `fieldname` in the parser's file metadata, matching multer's API contract.-- `update.sh` no longer hangs after "PortOS restarted" — the browser-open script now exits explicitly instead of waiting for Node's undici connection pool to drain.-- `update.sh` now kills the PM2 daemon (not just stops apps) before restarting, fixing crashes where a stale daemon cached a `ProcessContainerFork.js` path from a different project's Yarn PnP zip cache.-- Writers-room storyboard renders queued through Codex now wait their turn instead of erroring with "A Codex generation is already in progress" when you fire a second render before the first finishes. Codex jobs run on their own queue lane, so they don't block (and aren't blocked by) local image or video renders.+# Next Release## Added-- Video Gen "Chunks" control (1–8) chains multiple LTX renders into a single longer clip. Each chunk's last frame seeds the next, then ffmpeg stitches them into one output. The individual chunks land in history hidden by default, so the gallery shows just the stitched result.-- Two new LTX-2.3 video models — "dgrauet Q4" and "dgrauet Q8" — running on a more capable runtime that supports true keyframe interpolation (proper FFLF that respects both start AND end frames), native video extend, and audio-to-video. Install with `INSTALL_LTX2=1 bash scripts/setup-image-video.sh`. The existing notapalindrome models keep working unchanged; pick the new "dgrauet" entries from the model dropdown to use the new pipeline. FFLF on these models has a stage-2 OOM ceiling — the server auto-clamps frame count to a memory-safe budget (override via `FFLF_LTX2_PIXEL_BUDGET` env var if you have more RAM than 48 GB).-- "Extend" mode on the new dgrauet runtime now uses a true latent video extension (conditions on the entire source video's motion + visual content) instead of last-frame i2v conditioning. The visible motion stall at scene boundaries is gone — extensions continue movement naturally from the source. Legacy notapalindrome models keep using the old chained-i2v workaround.-- New "Audio" mode in Video Gen renders a clip whose motion and on-screen audio sync to an uploaded audio track (WAV / MP3 / M4A). Pick the new mode tile, drop in a 4–8 second clip, write a directive prompt ("a person dancing to this track in a studio"), and the dgrauet runtime drives the video to the audio. Requires one of the new dgrauet models — legacy LTX models don't expose an audio-conditioned pipeline.+- **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). The setup script bootstraps a dedicated virtual environment automatically — existing mflux installs are unaffected. Live step-by-step previews, the metadata sidecar, gallery, and Remix all work unchanged. Models are gated on HuggingFace — accept the license at https://huggingface.co/black-forest-labs/FLUX.2-klein-4B and set your HF token; the Image Gen page surfaces a yellow banner when setup is incomplete or the token isn't set. Any existing FLUX.2-klein model entries auto-upgrade in place, preserving customizations like a custom name or step count.+- **Unified media job queue for image and video generation.** Image and video render requests are now accepted immediately and placed in a FIFO queue instead of returning a "busy" error when the GPU is occupied. GPU renders (video + local image) drain one at a time since they share the same hardware runtime; Codex image jobs run in a parallel lane so a long video render never blocks a storyboard generation. Jobs interrupted by a server restart are automatically reclassified as failed on next boot. A new media jobs panel lets you inspect and cancel queued or running renders.+- **Editable media model registry** — video and image model definitions are now stored in a single editable file rather than being hardcoded. Edit the registry and restart the server to swap models without touching source code. Three new text-encoder quality tiers ship out of the box: a BF16 full-precision option (new default, best output quality), a QAT 4-bit option (auto-detected when LM Studio has it installed), and a 4-bit option for lower-memory setups. The registry is seeded automatically on first run.+- **Streaming-ready mp4 output** — every video render is lightly post-processed (no re-encoding, ~hundreds of ms) so gallery tiles display their poster frame on page load instead of flashing black until clicked.+- **Sleep prevention during long renders on macOS** — the system display and sleep are held off for the duration of any video render, so a 90-second+ generation on a laptop isn't aborted mid-run by the screen going dark.+- **Full diagnostic output from the video generation process is now logged.** Previously only structured progress markers were captured and the rest was silently dropped, hiding upstream errors like "VAE encoder failed to load" until you ran the generator manually from the command line.+- **Image strength control for video generation** — a new parameter lets you tune how strongly an input image conditions the video. The default preserves the source image; lower values allow the model to diverge more freely. The model's actual behavior is the inverse of its own documentation, which is noted in the UI.+- **1:1 square resolutions** (512×512, 768×768) added to the Video Gen resolution dropdown.+- **Image upload preview + larger reference-image previews** in Video Gen — uploads show a preview immediately so you can confirm what you uploaded before submitting; source image, FFLF last-frame, and extend-mode previews are displayed at a much larger size instead of small thumbnails.++- **Morse code trainer** in POST — Koch-method Copy mode (listen → type, 90% accuracy unlocks the next letter) and a Send mode that decodes spacebar/touch keying into text. Native Web Audio, Farnsworth timing, configurable WPM/tone. Reachable from the POST launcher header, the sidebar, ⌘K, and voice.+- **Morse trainer side widget** with a binary tree visualization that highlights the live keying path (DAH-left, DIT-right), three reference views (Tree / Length / List), a tap-anywhere practice key, and a real-time decoded log. Spacebar keying is intercepted in capture phase so it doesn't trigger the voice FAB push-to-talk hotkey while on the morse page.+- **Video Gen mode switch + batch queue** — a segmented control selects Text / Image / FFLF (first-frame + last-frame) / Extend (continue from a prior render). Mode-specific input panels (start image, end image, prior-video picker) replace the always-on source image upload. A new "Add to queue" button enqueues the current configuration; the batch-queue panel runs jobs serially with per-item status (pending / running / complete / error), inline error messages, and a clear-finished action that removes completed and errored items.+- **Video Gen "Chunks" control (1–8)** chains multiple renders into a single longer clip. Each chunk's last frame seeds the next, and the final output is stitched into one file. Intermediate chunks are hidden in history by default so the gallery shows only the finished result.+- **Two new high-capability video models** ("dgrauet Q4" and "dgrauet Q8") on a more capable runtime that supports true keyframe interpolation (FFLF that respects both start AND end frames), native video extend, and audio-to-video. Install them from the Setup screen — the existing models keep working unchanged; pick the new "dgrauet" entries from the model dropdown to use the new pipeline. On systems with 48 GB of RAM or less, the server automatically clamps FFLF frame counts to a memory-safe budget.+- **"Extend" mode on the new dgrauet models** uses true latent video extension — conditioned on the entire source video's motion and visual content — instead of just continuing from the last frame. The visible motion stall at scene boundaries is gone; extensions continue naturally from the source. Legacy models keep using the previous last-frame method.+- **New "Audio" mode in Video Gen** renders a clip whose motion and on-screen audio sync to an uploaded audio track (WAV / MP3 / M4A). Drop in a 4–8 second clip, write a directive prompt, and the model drives the video to match the audio. Requires one of the new dgrauet models.## Changed+- **Image Gen and Video Gen layouts tightened for above-the-fold density.** Form and preview now render side-by-side on wider screens instead of stacking, so more of the page is usable without scrolling. Previews are capped so they no longer dominate the viewport, the prompt and negative-prompt fields sit in two columns on medium+ screens, and section headers are more compact. Status text is hoisted into the Generate button row; video Download moved into the preview header for parity with Image Gen.+- **Worktree policy clarified** in developer documentation: TUI sessions edit the main repo directly; worktrees are reserved for unattended CoS sub-agents.- Video Gen frame picker now goes up to 481 frames (~20s at 24fps); options past 241 frames (~10s) show a hint recommending Extend mode for reliable long renders at 48 GB.-- Switching to Audio mode now automatically selects the smallest dgrauet model (Q4) when the current model doesn't support a2v, instead of landing on a blocked state with a warning. The warning still appears if you manually pick a non-ltx2 model while in Audio mode.+- Switching to Audio mode now automatically selects the smallest compatible model when the current model doesn't support audio-to-video, instead of landing on a blocked state with a warning. The warning still appears if you manually pick an incompatible model while in Audio mode.- "Disable audio" and "No music" checkboxes are hidden in Audio mode and their state is reset on entry — both are irrelevant when audio comes from an uploaded file rather than being generated.- Video Gen FFLF mode now offers the same dual control on both the first-frame and last-frame slots — pick from your image gallery or upload a fresh image — instead of the previous upload-only first frame and gallery-only last frame.- Release workflow no longer silently skips creating the GitHub Release when something else pushed the version tag before the workflow ran.-- Release-notes style guide tightened — entries should be one sentence per change in user-facing language, not code-review prose with file paths and internal symbols.- Chief of Staff 3D avatars (Cyber, Sigil, Esoteric, Nexus, Muse) now fill the agent panel as a full-bleed background, with the title, status, and controls overlaying the scene instead of sharing a column with it.- Autonomy level buttons in the CoS Config tab now use higher-contrast active states so the selected level is obvious at a glance.- Quick Task form checkboxes (Enhance, Worktree, Open PR, Simplify, Review Loop, JIRA) are tighter — vertical padding around each checkbox is reduced so the form fits more comfortably in the dashboard widget without dead whitespace.++## Fixed++- **Creative Director stuck projects now self-recover** — the orchestrator re-evaluates project state after every task completes, so projects that were started before the treatment/evaluate workflow split no longer get frozen. Manually accepting or failing a scene also immediately triggers the next scene to start.+- **Creative Director projects auto-resume on server restart.** Previously a server restart mid-render left a project frozen — the scene appeared to be rendering but had no active job behind it, and the orchestrator wouldn't kick off a replacement because of bookkeeping left behind by the dead worker. On boot, any in-progress Creative Director project now detects interrupted scenes, clears the stale bookkeeping, and resumes from exactly where it left off.+- **Creative Director smoke test** — a "Run smoke test" button on the Creative Director list page creates a deterministic 3-scene project (red ball → blue ball continuation → pure continuity) to verify the full pipeline end-to-end without needing a real story or AI evaluation. The smoke test skips audio generation and auto-accepts every scene so it completes in render time only, making it a fast sanity check after setup or after a model swap.+- **Creative Director scene-retry path unblocked.** When the AI evaluator decided a scene needed a re-render with a refined prompt, the retry was silently rejected by a validation rule that shouldn't have been there — leaving the scene stuck in "evaluating" forever. The evaluator can now correctly request a re-render, and the project advances as expected.++- **Image-to-video on macOS now actually preserves the source image as the first frame.** A bug in an older version of the video generation backend caused the VAE encoder to fail silently, producing gray-fog frames instead of conditioning on the uploaded image. The setup script also had a package name collision that caused it to install the wrong library — both packages share the same Python import name, so the wrong install was invisible. Updated to a patched version and fixed the installer. Verified end-to-end: pixel-perfect first-frame preservation with coherent motion across all frames.+- **FFLF (first-frame + last-frame) conditioning silently produced no output.** An incorrect frame index was passed to the generation backend — the model's internal latent frame count is much smaller than the raw video frame count, and passing the raw frame number caused a shape mismatch that caused the render to exit without producing an mp4. Fixed by computing the correct latent index.+- **"Continue" / last-frame extraction produced phantom-success logs but no file**, leaving a broken image preview in Video Gen. Two compounded bugs: the seek window used to grab the last frame was too narrow for videos with audio tracks (where the final keyframe sits earlier than expected), causing the frame extractor to return zero frames while still reporting success; and the success path only checked the process exit code without verifying the output file actually existed. Both are now fixed.+- **Last-frame extraction now caches** — repeated "Continue" clicks reuse the previously extracted frame instead of re-running the extraction every time. Cuts ~1–2s per click.+- **Delete operations now log** for both image and video gallery actions. Previously a delete was silent on the server side, making it impossible to confirm from the logs that the click registered.+- **Media model registry is resilient to partial or malformed edits.** A partially filled registry (missing sections, wrong field types, or an unreadable file) no longer crashes the server on startup — the loader merges user edits over built-in defaults and falls back gracefully. Typos in the configured default video model now fall back to the first available model with a warning instead of showing "Unknown video model" in the UI. Missing or invalid text encoder configuration also surfaces a clear error rather than silently passing bad values into the generation pipeline.+- **Last-frame cache recovers from a prior crashed extraction.** A crashed ffmpeg run could leave a zero-byte placeholder that was served forever as a broken image in Video Gen. The cache now validates that the extracted file has content before trusting it, and falls through to re-extract when it doesn't — so a previously stuck "Continue" preview heals itself on the next click.+- **Streaming-optimized mp4 remux works on Windows without risking the rendered video.** On Windows, an atomic file-replace fails when the destination already exists. The replace strategy now moves the original aside first, installs the optimized file, and restores the backup on any failure — so a transient lock or permissions issue skips the optimization step instead of destroying the rendered video.+- **Sleep prevention during renders is now strictly macOS-only.** The system sleep guard was also firing on Linux, emitting a harmless but noisy error on every render. It now runs only on macOS where the caffeinate utility exists.+- **Setup script cleans up a conflicting package before install.** An unrelated package with the same Python import name as the LTX video backend was shadowing it silently if previously installed. The setup script now removes the conflicting package before installing the correct one, so upgraders aren't left with an ambiguous environment.+- **Form fields stay editable during a video render.** Previously every input was locked while a render was in flight, blocking you from queueing a different configuration. Since the queue captures your settings at submit time, live editing is now safe and the fields are no longer disabled.+- **"Add to collection" popover on media cards no longer gets clipped at the card edge.** The card's rounded-corner styling was creating an invisible clipping boundary that swallowed the popover regardless of its stacking order. The clipping is now scoped only to the image area, so the popover floats freely above the card as intended.+- **Video Gen audio uploads (Audio mode) were rejected with "File type not allowed" even for valid MP3/WAV files.** A missing field in the upload handler's file metadata caused every MIME-type check to silently fail. Fixed.+- **`update.sh` no longer hangs after "PortOS restarted"** — the browser-open step now exits immediately rather than waiting for an internal connection pool to drain.+- **`update.sh` now fully resets the process manager before restarting**, fixing crashes where a stale daemon retained a cached path from a different project that no longer existed.+- Writers-room storyboard renders queued through Codex now wait their turn instead of erroring with "A Codex generation is already in progress" when you fire a second render before the first finishes. Codex jobs run on their own queue lane, so they don't block (and aren't blocked by) local image or video renders.diff --git a/client/src/components/creative-director/OverviewTab.jsx b/client/src/components/creative-director/OverviewTab.jsxindex 46bf4069ad..602408ef22 100644--- a/client/src/components/creative-director/OverviewTab.jsx+++ b/client/src/components/creative-director/OverviewTab.jsx@@ -1,22 +1,66 @@import { Link } from 'react-router-dom';-import toast from '../ui/Toast';-import ToggleSwitch from '../ToggleSwitch.jsx';+import { useState, useEffect, useRef } from 'react';import { updateCreativeDirectorProject } from '../../services/apiCreativeDirector.js';+import toast from '../ui/Toast';export default function OverviewTab({ project, onProjectUpdate }) {+ const [disableAudio, setDisableAudio] = useState(project.disableAudio === true);+ const [saving, setSaving] = useState(false);+ // Track the project id this tab is currently mounted for. If the user+ // toggles audio and navigates to a different CD project before the PATCH+ // resolves, the late `.then()` would otherwise call onProjectUpdate on+ // the now-different project and silently overwrite its local state.+ // We also reset `saving` on project switch — otherwise the new project+ // inherits the stuck-true flag (the prior project's PATCH cleanup is+ // gated on the old id and never runs the .finally for this instance),+ // leaving the new project's audio checkbox permanently disabled.+ const projectIdRef = useRef(project.id);+ // Guards prop-driven resets while a PATCH is in flight. A stale poll+ // response arriving before the PATCH resolves would otherwise call+ // setSaving(false) and roll back the optimistic toggle.+ const savingRef = useRef(false);+ useEffect(() => {+ projectIdRef.current = project.id;+ setDisableAudio(project.disableAudio === true);+ setSaving(false);+ savingRef.current = false;+ }, [project.id]);+ useEffect(() => {+ if (!savingRef.current) {+ setDisableAudio(project.disableAudio === true);+ }+ }, [project.disableAudio]);++ const handleAudioToggle = (e) => {+ const next = e.target.checked;+ setDisableAudio(next);+ setSaving(true);+ savingRef.current = true;+ const requestProjectId = project.id;+ updateCreativeDirectorProject(requestProjectId, { disableAudio: next })+ .then(() => {+ if (projectIdRef.current === requestProjectId) {+ onProjectUpdate?.({ disableAudio: next });+ }+ })+ .catch((err) => {+ if (projectIdRef.current === requestProjectId) {+ setDisableAudio(!next);+ }+ toast.error(err.message || 'Failed to update audio setting');+ })+ .finally(() => {+ savingRef.current = false;+ if (projectIdRef.current === requestProjectId) {+ setSaving(false);+ }+ });+ };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>;- const setDisableAudio = async (next) => {- const updated = await updateCreativeDirectorProject(project.id, { disableAudio: next })- .catch((err) => { toast.error(err.message || 'Failed to update audio setting'); return null; });- if (!updated) return;- onProjectUpdate?.(updated);- toast.success(next ? 'Audio disabled for future scenes' : 'Audio enabled for future scenes');- };-return (<div className="space-y-4 max-w-3xl"><section className="bg-port-card border border-port-border rounded p-4 space-y-2">@@ -26,25 +70,29 @@ export default function OverviewTab({ project, onProjectUpdate }) {<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 || '—'} />+ <div className="grid grid-cols-3 gap-2 text-sm">+ <div className="text-port-text-muted">Audio</div>+ <div className="col-span-2">+ <label className="flex items-center gap-2 cursor-pointer">+ <input+ type="checkbox"+ checked={disableAudio}+ onChange={handleAudioToggle}+ disabled={saving}+ className="accent-port-accent"+ />+ <span className="text-port-text">Disable audio</span>+ </label>+ <div className="text-xs text-port-text-muted mt-1">+ Applies to future scene renders only — already-rendered scenes keep their original audio.+ </div>+ </div>+ </div><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>} />)}- <Field- label="Audio"- value={- <div className="inline-flex items-center gap-2 text-port-text">- <ToggleSwitch- size="sm"- enabled={!project.disableAudio}- onChange={() => setDisableAudio(!project.disableAudio)}- ariaLabel="Toggle audio for future scene renders"- />- <span>{project.disableAudio ? 'Disabled' : 'Enabled'} <span className="text-port-text-muted">(applies to future scene renders)</span></span>- </div>- }- /></section>{project.styleSpec && (diff --git a/client/src/components/creative-director/SegmentsTab.jsx b/client/src/components/creative-director/SegmentsTab.jsxindex 6449509999..1e337ef465 100644--- a/client/src/components/creative-director/SegmentsTab.jsx+++ b/client/src/components/creative-director/SegmentsTab.jsx@@ -1,5 +1,6 @@+import { useState, useEffect } from 'react';import { Link } from 'react-router-dom';-import { Bot } from 'lucide-react';+import { Bot, ExternalLink } from 'lucide-react';import { extractKind } from './ActiveAgentsBanner.jsx';const STATUS_BADGE = {@@ -10,6 +11,76 @@ const STATUS_BADGE = {failed: 'bg-port-error/30 text-port-error',};+// Renders the preview area for a scene that has a rendered video.+// Uses <video controls poster> so the thumbnail is shown when idle and the+// user can play the clip in-tab without leaving the page. The browser handles+// a missing poster (ffmpeg/thumbnail not generated) by showing its own blank+// poster — controls remain fully accessible either way.+//+// `renderedJobId` survives even after the underlying mp4 is deleted from+// history, so the <video> can fail to load. We track that with onError and+// fall back to a "missing media" placeholder (matches the prior <a><img>+// onError-hides-tile behavior) instead of leaving a broken control.+function ScenePreview({ jobId, label }) {+ const [missing, setMissing] = useState(false);+ // `attempt` is bumped manually by the user-clickable Retry button below+ // (and indirectly by the jobId reset effect — a re-render with the same+ // jobId would otherwise leave a transient load error stuck for the rest+ // of the session). Each bump remounts <video> via the keyed `?retry=N`+ // suffix so the browser re-fetches instead of using its cached error.+ const [attempt, setAttempt] = useState(0);+ // Reset the missing flag when jobId changes so a re-rendered scene gets+ // a fresh load attempt instead of inheriting the prior scene's "media+ // missing" state. attempt resets too so the cache-busting param starts+ // fresh per scene.+ useEffect(() => {+ setMissing(false);+ setAttempt(0);+ }, [jobId]);+ const cacheBust = attempt > 0 ? `?retry=${attempt}` : '';+ const videoSrc = `/data/videos/${jobId}.mp4${cacheBust}`;+ const posterSrc = `/data/video-thumbnails/${jobId}.jpg${cacheBust}`;+ if (missing) {+ return (+ <div className="bg-port-bg aspect-video flex flex-col items-center justify-center text-port-text-muted text-xs gap-2">+ <span>media missing</span>+ <button+ type="button"+ onClick={() => { setMissing(false); setAttempt((a) => a + 1); }}+ className="px-2 py-0.5 rounded border border-port-border hover:bg-port-card text-port-text"+ >+ Retry+ </button>+ </div>+ );+ }+ return (+ <div className="relative bg-port-bg aspect-video">+ <video+ key={attempt}+ src={videoSrc}+ poster={posterSrc}+ controls+ preload="none"+ playsInline+ aria-label={label}+ onError={() => setMissing(true)}+ className="w-full h-full object-cover"+ />+ <a+ href={videoSrc}+ target="_blank"+ rel="noopener noreferrer"+ aria-label={`Open ${label} in new tab`}+ title="Open video in new tab"+ className="absolute top-1 right-1 p-1 rounded bg-black/50 text-white hover:bg-black/80"+ >+ <ExternalLink className="w-3 h-3" />+ </a>+ </div>+ );+}+export default function SegmentsTab({ project, activeAgents = [] }) {const scenes = project.treatment?.scenes;if (!scenes?.length) {@@ -55,15 +126,7 @@ export default function SegmentsTab({ project, activeAgents = [] }) {return (<div key={s.sceneId} className={`bg-port-card border rounded overflow-hidden ${isInflight ? 'border-port-accent/60' : 'border-port-border'}`}>{s.renderedJobId ? (- <video- src={`/data/videos/${s.renderedJobId}.mp4`}- poster={`/data/video-thumbnails/${s.renderedJobId}.jpg`}- controls- preload="none"- playsInline- onError={(e) => { e.currentTarget.style.display = 'none'; }}- className="block w-full bg-port-bg aspect-video object-cover"- />+ <ScenePreview jobId={s.renderedJobId} label={`Scene ${s.order + 1}`} />) : (<div className="bg-port-bg aspect-video flex items-center justify-center text-port-text-muted text-xs">{isInflight ? (diff --git a/client/src/pages/CreativeDirector.jsx b/client/src/pages/CreativeDirector.jsxindex 0db191fbbb..eb2ff449d0 100644--- a/client/src/pages/CreativeDirector.jsx+++ b/client/src/pages/CreativeDirector.jsx@@ -227,18 +227,16 @@ export default function CreativeDirector() {maxLength={256}/></label>- <label className="flex items-center gap-2 text-sm md:col-span-2">- <input- type="checkbox"- checked={!form.disableAudio}- onChange={(e) => setForm({ ...form, disableAudio: !e.target.checked })}- />- <span className="text-port-text-muted">- Generate audio for each scene- <span className="text-port-text-muted/70"> (off by default — current models produce inconsistent audio)</span>- </span>- </label></div>+ <label className="flex items-center gap-2 text-sm cursor-pointer">+ <input+ type="checkbox"+ checked={form.disableAudio}+ onChange={(e) => setForm({ ...form, disableAudio: e.target.checked })}+ className="accent-port-accent"+ />+ <span className="text-port-text-muted">Disable audio</span>+ </label><label className="block text-sm"><span className="text-port-text-muted">Style spec</span><textareadiff --git a/client/src/pages/CreativeDirectorDetail.jsx b/client/src/pages/CreativeDirectorDetail.jsxindex 7d633aaf3d..81a2df28af 100644--- a/client/src/pages/CreativeDirectorDetail.jsx+++ b/client/src/pages/CreativeDirectorDetail.jsx@@ -148,7 +148,7 @@ export default function CreativeDirectorDetail() {<div className="flex-1 overflow-auto p-6"><ActiveAgentsBanner agents={activeAgents} />- {activeTab === 'overview' && <OverviewTab project={project} onProjectUpdate={setProject} />}+ {activeTab === 'overview' && <OverviewTab project={project} onProjectUpdate={(updates) => setProject((p) => p ? { ...p, ...updates } : p)} />}{activeTab === 'treatment' && <TreatmentTab project={project} />}{activeTab === 'segments' && <SegmentsTab project={project} activeAgents={activeAgents} />}{activeTab === 'runs' && <RunsTab project={project} />}diff --git a/server/index.js b/server/index.jsindex 0320af744e..5c65ed268d 100644--- a/server/index.js+++ b/server/index.js@@ -460,7 +460,14 @@ ensureSelf()// 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}`));+ // recoverInFlightProjects resolves cdRecoveryDone on success. On any+ // failure path here, explicitly resolve it so cos.init's gate doesn't+ // hit the 5s timeout fallback for nothing.+ recoverInFlightProjects().catch(async (e) => {+ console.log(`⚠️ CD boot recovery failed: ${e.message}`);+ const { markRecoveryDone } = await import('./services/creativeDirector/recovery.js');+ markRecoveryDone();+ });}).then(() => {// Start server only after sync log + media job queue are initialized.diff --git a/server/lib/creativeDirectorPresets.js b/server/lib/creativeDirectorPresets.jsindex 9fcddc8a2f..f2a67e0d0e 100644--- a/server/lib/creativeDirectorPresets.js+++ b/server/lib/creativeDirectorPresets.js@@ -11,18 +11,11 @@// Width/height pairs are 64-aligned (videoGen rounds down to multiples of// 64 anyway) and chosen for sensible LTX defaults.-//-// `1:1-small` is intentionally NOT exported in ASPECT_RATIOS — it's a-// hidden preset used only by the smoke-test fixture (cuts pixel count by-// ~44% vs 1:1 to keep the CI/dev health-check render time low). The smoke-// route bypasses the route-level enum validation (it calls createProject-// directly), so the smaller dimensions land in the render queue without-// the user-facing dropdown ever seeing it.export const ASPECT_PRESETS = Object.freeze({- '16:9': { width: 768, height: 432 },- '9:16': { width: 432, height: 768 },- '1:1': { width: 512, height: 512 },- '1:1-small': { width: 384, height: 384 },+ '16:9': { width: 768, height: 432 },+ '9:16': { width: 432, height: 768 },+ '1:1': { width: 512, height: 512 },+ '1:1-small': { width: 384, height: 384 }, // Legacy alias — pre-removal smoke-test fixture});// `steps` and `guidance` are mlx_video knobs. `fps` is the render framediff --git a/server/lib/creativeDirectorPresets.test.js b/server/lib/creativeDirectorPresets.test.jsnew file mode 100644index 0000000000..2d75060096--- /dev/null+++ b/server/lib/creativeDirectorPresets.test.js@@ -0,0 +1,35 @@+import { describe, it, expect } from 'vitest';+import { presetToRenderParams, ASPECT_PRESETS, QUALITY_PRESETS, ASPECT_RATIOS } from './creativeDirectorPresets.js';++describe('presetToRenderParams', () => {+ it('returns valid params for all current aspect ratios', () => {+ // Iterate the exported enum so a newly added ratio is automatically+ // covered without having to remember to update this test.+ expect(ASPECT_RATIOS.length).toBeGreaterThan(0);+ for (const aspectRatio of ASPECT_RATIOS) {+ const params = presetToRenderParams({ aspectRatio, quality: 'standard', durationSeconds: 3 });+ expect(params).toMatchObject({ width: expect.any(Number), height: expect.any(Number), fps: expect.any(Number) });+ expect(params.numFrames % 8).toBe(0);+ expect(params.numFrames).toBeGreaterThanOrEqual(8);+ }+ });++ it('does not throw for legacy 1:1-small and returns original 384×384 dims', () => {+ const legacy = presetToRenderParams({ aspectRatio: '1:1-small', quality: 'draft', durationSeconds: 3 });+ expect(legacy.width).toBe(384);+ expect(legacy.height).toBe(384);+ });++ it('throws for truly unknown aspectRatio', () => {+ expect(() => presetToRenderParams({ aspectRatio: 'bogus', quality: 'draft', durationSeconds: 1 })).toThrow("Unknown aspectRatio 'bogus'");+ });++ it('throws for unknown quality', () => {+ expect(() => presetToRenderParams({ aspectRatio: '1:1', quality: 'ultra', durationSeconds: 1 })).toThrow("Unknown quality 'ultra'");+ });++ it('rounds numFrames to a multiple of 8 and floors at 8', () => {+ const params = presetToRenderParams({ aspectRatio: '1:1', quality: 'draft', durationSeconds: 0.1 });+ expect(params.numFrames).toBe(8);+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 8e27599061..777de4ae6f 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -764,13 +764,18 @@ export const creativeDirectorProjectCreateSchema = z.object({// 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.+//+// Server-managed fields (timelineProjectId, runs, treatment) are+// intentionally NOT in this schema. timelineProjectId is set only by+// stitchRunner.js — accepting it in PATCH payloads would let a client+// point a CD project at an unrelated user timeline project, which the+// next stitch would silently overwrite via updateTimelineProject.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(),// Toggleable post-creation — only affects future scene renders.disableAudio: z.boolean().optional(),diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex b9885ee0e2..07e510b713 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -293,7 +293,18 @@ router.post('/cancel', asyncHandler(async (req, res) => {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));+ // "Most recent submit" — explicitly sort by queuedAt DESC instead of+ // relying on listJobs() ordering (which puts gpuRunning before+ // codexRunning, then queue, then archive). queuedAt is the user's+ // actual submit timestamp; startedAt would mis-order an older queued+ // job that just dequeued ahead of a more-recently-submitted job+ // still waiting in queue.+ const latestSubmitFirst = [...cancellable].sort((a, b) => {+ const ta = new Date(a.queuedAt || 0).getTime();+ const tb = new Date(b.queuedAt || 0).getTime();+ return tb - ta;+ });+ return res.json(await cancelJob(latestSubmitFirst[0].id));}const cancelled = imageGen.cancel();res.json({ ok: cancelled });diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex 4abdc5f757..934330b67a 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -346,5 +346,44 @@ describe('Image Gen Routes', () => {// Belt-and-braces: legacy single-process cancel also poked.expect(imageGen.cancel).toHaveBeenCalled();});++ it('POST /cancel (no jobId) picks the most-recently-submitted job by queuedAt — NOT the listJobs() ordering', async () => {+ // listJobs() returns jobs in queue-internal order: gpuRunning first,+ // then codexRunning, then queue. Without explicit queuedAt sorting, a+ // bare `/cancel` (the user's "stop the last thing I submitted" gesture)+ // would target the gpuRunning job — even when the user just queued a+ // newer Codex job that should be the cancel target. The route must+ // tie-break by queuedAt DESC so the newest submit always wins.+ mediaJobQueue.listJobs.mockReturnValueOnce([+ // listJobs ordering: gpu-running first (oldest submit, started long ago).+ { id: 'gpu-running', status: 'running', queuedAt: '2026-05-05T08:00:00Z' },+ // Codex job queued AFTER the GPU job started — this is the "most+ // recent submit" and should be the cancel target.+ { id: 'codex-newest', status: 'queued', queuedAt: '2026-05-05T08:30:00Z' },+ // Older queued job, should NOT be picked.+ { id: 'queued-older', status: 'queued', queuedAt: '2026-05-05T08:15:00Z' },+ ]);+ const response = await request(app).post('/api/image-gen/cancel').send({});+ expect(response.status).toBe(200);+ // The newest-submit (codex-newest at 08:30) wins — not 'gpu-running'+ // (which appeared first in listJobs) and not 'queued-older'.+ expect(mediaJobQueue.cancelJob).toHaveBeenCalledTimes(1);+ expect(mediaJobQueue.cancelJob.mock.calls[0][0]).toBe('codex-newest');+ });++ it('POST /cancel (explicit jobId) cancels exactly that job and skips queuedAt selection', async () => {+ // When a jobId is provided, the route must cancel THAT job — even if a+ // newer queued job exists. This locks in that explicit selection wins+ // over the queuedAt fallback (writers-room "cancel this scene").+ mediaJobQueue.listJobs.mockReturnValueOnce([+ { id: 'newest', status: 'queued', queuedAt: '2026-05-05T08:30:00Z' },+ { id: 'middle', status: 'queued', queuedAt: '2026-05-05T08:20:00Z' },+ { id: 'oldest', status: 'running', queuedAt: '2026-05-05T08:00:00Z' },+ ]);+ const response = await request(app).post('/api/image-gen/cancel').send({ jobId: 'middle' });+ expect(response.status).toBe(200);+ expect(mediaJobQueue.cancelJob).toHaveBeenCalledTimes(1);+ expect(mediaJobQueue.cancelJob.mock.calls[0][0]).toBe('middle');+ });});});diff --git a/server/services/cos.js b/server/services/cos.jsindex 665005a218..afc76a28dc 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -158,6 +158,22 @@ export async function start() {emitLog('info', `Cleaned up ${cleanedAgents} orphaned agent(s)`);}+ // Wait for Creative Director boot recovery to finish retiring stale CD+ // tasks before we reset orphans. Without this gate, resetOrphanedTasks+ // would respawn stale CD treatment/evaluate tasks before recovery can+ // mark them `completed`, racing two agents on the same project. The+ // promise resolves whether recovery ran successfully, was a no-op (no+ // mid-flight projects), or wasn't called at all (markRecoveryDone is+ // exposed for that case). 60s ceiling — recovery on a healthy boot+ // resolves in <100ms, but we'd rather pay a slow-boot tax than reopen+ // the duplicate-agent race when initMediaJobQueue or earlier startup+ // steps stall.+ const { cdRecoveryDone } = await import('./creativeDirector/recovery.js');+ await Promise.race([+ cdRecoveryDone,+ new Promise((resolve) => setTimeout(resolve, 60000)),+ ]);+// Then reset any orphaned in_progress tasks (no running agent)await resetOrphanedTasks();diff --git a/server/services/creativeDirector/completionHook.js b/server/services/creativeDirector/completionHook.jsindex b494c4b233..0ffadff7d8 100644--- a/server/services/creativeDirector/completionHook.js+++ b/server/services/creativeDirector/completionHook.js@@ -22,10 +22,14 @@* that case).*/-import { getProject, updateProject, updateRun, recordRun } from './local.js';-import { enqueueTreatmentTask } from './agentBridge.js';+import { existsSync } from 'fs';+import { join } from 'path';+import { getProject, updateProject, updateScene, updateRun, recordRun } from './local.js';+import { enqueueTreatmentTask, enqueueEvaluateTask } from './agentBridge.js';import { runSceneRender } from './sceneRunner.js';import { runStitch } from './stitchRunner.js';+import { sampleEvaluationFrames } from '../videoGen/local.js';+import { PATHS } from '../../lib/fileUtils.js';export async function handleCreativeDirectorCompletion(task, agentId, success) {const meta = task?.metadata?.creativeDirector;@@ -98,6 +102,13 @@ export async function handleCreativeDirectorCompletion(task, agentId, success) {// the corresponding async work returns or on failure.const inflightTreatment = new Set();const inflightStitch = new Set();+// Resume-after-pause path enqueues an evaluator for an orphaned+// 'evaluating' scene. recordRun isn't persisted until the agentBridge+// writes the run row, so two concurrent advance() calls (e.g. user+// clicks Resume + a stale completionHook fires) could both observe the+// scene as orphaned and double-enqueue. Per-projectId+sceneId set+// closes that window in the same way inflightTreatment/inflightStitch do.+const inflightEvaluator = new Set();export async function advanceAfterSceneSettled(projectId) {const project = await getProject(projectId);@@ -106,19 +117,16 @@ export async function advanceAfterSceneSettled(projectId) {// No treatment yet → enqueue treatment task.if (!project.treatment) {- // Skip if a treatment run is already mid-flight (its run row stays- // 'running' until the agent's completion hook fires) OR our in-memory- // dedup set has this project (covers the updateProject→enqueueTreatmentTask- // window between two concurrent advance calls in this process).- //- // Note: we deliberately do NOT bail just because status === 'planning'.- // The route pre-flips `draft`/`paused`/`failed` projects to 'planning'- // before calling start, so a status check would short-circuit the very- // first Start click and leave the project stuck with no runs and no task.- const runningTreatment = (project.runs || []).some(- (r) => r.kind === 'treatment' && r.status === 'running',+ // Skip if our in-memory dedup set has this project — covers the+ // updateProject→enqueueTreatmentTask window between two concurrent+ // advance calls. The `planning` status check is intentionally omitted:+ // the start route pre-flips new projects to `planning` before calling+ // startCreativeDirectorProject, so checking status here would cause+ // brand-new projects to get stuck (treatment task never enqueued).+ const hasInflightTreatmentRun = (project.runs || []).some(+ (r) => r.kind === 'treatment' && r.status !== 'completed' && r.status !== 'failed');- if (runningTreatment || inflightTreatment.has(projectId)) return;+ if (hasInflightTreatmentRun || inflightTreatment.has(projectId)) return;inflightTreatment.add(projectId);await updateProject(project.id, { status: 'planning' }).catch((e) => { inflightTreatment.delete(projectId); throw e; });@@ -128,13 +136,163 @@ export async function advanceAfterSceneSettled(projectId) {return;}+ let scenes = (project.treatment.scenes || []).slice().sort((a, b) => a.order - b.order);++ // Resume-after-pause path: a scene left in `evaluating` with a+ // renderedJobId set means handleRenderCompleted persisted the render+ // (the user paused before the evaluator could be enqueued, or recovery+ // reaped the live evaluate task on restart). Re-fire the evaluator+ // here so the existing rendered clip isn't wasted on a pointless+ // re-render. Skip if a fresh evaluate run is already in flight (don't+ // double-enqueue mid-resume).+ // jobIds in the queue are crypto.randomUUID(); accept the lowercase-hex+ // UUID v4 shape and reject anything else. Persisted scene.renderedJobId+ // is editable via PATCH /:id/scenes/:sceneId so a crafted payload could+ // otherwise make ffmpeg/ffprobe read+write outside PATHS.videos /+ // PATHS.video-thumbnails. (sampleEvaluationFrames builds paths via+ // string concat, not via PATHS.join + safety check.)+ const isSafeJobId = (id) => typeof id === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id);+ const noLiveEvaluateRun = (s) => !(project.runs || []).some(+ (r) => r.kind === 'evaluate' && r.sceneId === s.sceneId && r.status !== 'completed' && r.status !== 'failed',+ );+ // Reset any 'evaluating' scenes whose renderedJobId is unsafe (tampered+ // PATCH, missing, etc.) — without this they'd stay 'evaluating' forever+ // and the inflight check at the bottom of the function would block+ // every future advance() call, wedging the project. Mark them failed+ // so the orchestrator can either fall through to the next scene or+ // mark the whole project failed if no scene was ever accepted.+ const wedged = scenes.filter((s) =>+ s.status === 'evaluating' && !isSafeJobId(s.renderedJobId) && noLiveEvaluateRun(s),+ );+ for (const w of wedged) {+ console.log(`❌ CD scene ${w.sceneId} on ${project.id} is 'evaluating' with an unsafe renderedJobId (${JSON.stringify(w.renderedJobId)}) — marking failed to prevent project wedge.`);+ await updateScene(project.id, w.sceneId, {+ status: 'failed',+ evaluation: {+ accepted: false,+ notes: 'Scene wedged: invalid renderedJobId in persisted state. Re-render to recover.',+ sampledAt: new Date().toISOString(),+ },+ }).catch((e) => console.log(`⚠️ CD wedge-reset for ${w.sceneId} failed: ${e.message}`));+ }+ // Re-read scenes so the subsequent orphan/pending/inflight checks see the+ // updated statuses — the wedge-reset writes above are not reflected in the+ // in-memory `scenes` slice we sorted at the top of this function.+ if (wedged.length > 0) {+ const refreshed = await getProject(project.id);+ if (!refreshed) return;+ scenes = (refreshed.treatment?.scenes || []).slice().sort((a, b) => a.order - b.order);+ }+ const orphanedEvaluating = scenes.find((s) =>+ s.status === 'evaluating' &&+ isSafeJobId(s.renderedJobId) &&+ noLiveEvaluateRun(s),+ );+ if (orphanedEvaluating) {+ const evalKey = `${project.id}:${orphanedEvaluating.sceneId}`;+ if (inflightEvaluator.has(evalKey)) return;+ inflightEvaluator.add(evalKey);+ try {+ if (project.status !== 'rendering') {+ await updateProject(project.id, { status: 'rendering' });+ }+ // Verify the rendered .mp4 file is still on disk BEFORE deciding what+ // to do about frames. The video file is the prerequisite for every+ // evaluator branch: the multi-frame path reads the sampled frames+ // (which only exist because the video does), and the+ // single-thumbnail fallback (`{{^multiFrame}}` in cd-evaluate.md)+ // reads `/data/video-thumbnails/{renderedJobId}.jpg`. If the user+ // deleted the rendered video while the project was paused, all+ // three artifacts are gone (videoGen/local#deleteHistoryItem unlinks+ // the .mp4, its thumbnail, AND every `${jobId}-fN.jpg` evaluation+ // frame in one shot). If we don't catch this here — even when the+ // CACHED `evaluationFrames` array still happens to be on disk — the+ // evaluator may accept the scene, only for the later stitch to+ // crash on a missing input file.+ const videoStillExists = existsSync(join(PATHS.videos, `${orphanedEvaluating.renderedJobId}.mp4`));+ if (!videoStillExists) {+ console.log(`❌ CD resume: rendered video missing for scene ${orphanedEvaluating.sceneId} on ${project.id} — video deleted while paused, marking scene failed`);+ let sceneFailed = false;+ await updateScene(project.id, orphanedEvaluating.sceneId, {+ status: 'failed',+ evaluation: {+ accepted: false,+ notes: 'Evaluation frames unavailable: rendered video was deleted while project was paused.',+ sampledAt: new Date().toISOString(),+ },+ })+ .then(() => { sceneFailed = true; })+ .catch((e) => console.log(`⚠️ CD scene fail-deleted-video for ${orphanedEvaluating.sceneId} failed: ${e.message}`));+ if (!sceneFailed) {+ // updateScene errored; don't recurse, otherwise the same orphan+ // would be re-detected next pass with no progress.+ return;+ }+ // Release the per-scene evaluator lock manually so the recursive+ // advance below isn't short-circuited by the inflightEvaluator+ // guard at the top of this branch. The `finally` will delete()+ // it a second time, which is a no-op on Set. The recursion+ // re-fetches the project; since the scene is now 'failed', the+ // orphan check won't re-match and the function falls through to+ // nextPending / project-failure / stitch logic.+ inflightEvaluator.delete(evalKey);+ return advanceAfterSceneSettled(project.id);+ }+ // Re-sample evaluation frames if they weren't captured during the+ // original completion path (pause landed before frame sampling) OR+ // if any of the persisted frame files is missing on disk. Frames+ // can disappear if the user deleted the underlying video from+ // history while the project was paused — videoGen/local#deleteVideo+ // unlinks `${jobId}-fN.jpg` thumbnails as part of its cleanup.+ // Without this on-disk check, the evaluator would receive broken+ // image paths and reject every render with "frame not found".+ let frames = orphanedEvaluating.evaluationFrames || [];+ const allFramesExist = frames.length > 0 && frames.every((f) => existsSync(join(PATHS.videoThumbnails, f)));+ if (!allFramesExist) {+ frames = await sampleEvaluationFrames(orphanedEvaluating.renderedJobId)+ .catch((err) => {+ console.error(`❌ CD resume sampleEvaluationFrames failed for ${orphanedEvaluating.renderedJobId.slice(0, 8)}: ${err.message}`);+ return [];+ });+ // sampleEvaluationFrames can return [] for non-fatal reasons+ // (ffmpeg missing on PATH, ffprobe miscount, transient I/O). The+ // video file is still on disk (we checked above), so the+ // evaluator template's single-thumbnail fallback path+ // (`{{^multiFrame}}` in cd-evaluate.md) can still produce a+ // verdict against `/data/video-thumbnails/{renderedJobId}.jpg`.+ // Mirror the normal render-completion path (sceneRunner.js): hand+ // off whatever frames we got, even an empty array, rather than+ // bailing here and leaving the project wedged in `rendering`.+ await updateScene(project.id, orphanedEvaluating.sceneId, { evaluationFrames: frames });+ }+ // Pause race re-check after the expensive frame-sampling step. The+ // user could re-pause the project mid-resume; without this the+ // evaluator would fire against a now-paused project, which is+ // exactly the race the render-completion path already guards+ // against. Bail without enqueueing — the next Resume click will+ // pick up the freshly-sampled frames since we just persisted them.+ const recheck = await getProject(project.id);+ if (recheck?.status === 'paused' || recheck?.status === 'failed') {+ console.log(`⏸️ CD resume: project ${project.id} flipped to ${recheck.status} during frame sampling — skipping evaluator enqueue (next resume will reuse the sampled frames).`);+ return;+ }+ console.log(`▶️ CD resume: re-firing evaluator for orphaned 'evaluating' scene ${orphanedEvaluating.sceneId} on project ${project.id} (renderedJobId preserved from pre-pause render).`);+ const sceneRefreshed = recheck?.treatment?.scenes?.find((s) => s.sceneId === orphanedEvaluating.sceneId);+ if (recheck && sceneRefreshed) {+ await enqueueEvaluateTask(recheck, { ...sceneRefreshed, evaluationFrames: frames });+ }+ return;+ } finally {+ inflightEvaluator.delete(evalKey);+ }+ }+// 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') {diff --git a/server/services/creativeDirector/orchestrator.test.js b/server/services/creativeDirector/orchestrator.test.jsindex e5ad3cc9d3..d51558873f 100644--- a/server/services/creativeDirector/orchestrator.test.js+++ b/server/services/creativeDirector/orchestrator.test.js@@ -5,10 +5,20 @@ import { presetToRenderParams } from '../../lib/creativeDirectorPresets.js';// Mocks for advanceAfterSceneSettled integration test.const mockRunSceneRender = vi.fn(async () => undefined);const mockUpdateProject = vi.fn(async () => undefined);+const mockUpdateScene = vi.fn(async () => undefined);+const mockEnqueueTreatmentTask = vi.fn(async () => undefined);+const mockEnqueueEvaluateTask = vi.fn(async () => undefined);+const mockSampleEvaluationFrames = vi.fn(async () => []);+// fs.existsSync is consulted on (a) every persisted evaluationFrame to detect+// frames deleted under us, and (b) the rendered .mp4 itself to differentiate+// "video deleted while paused" (fail scene) from "transient ffmpeg failure"+// (bail and retry). Tests override per-call with mockReturnValueOnce.+const mockExistsSync = vi.fn(() => false);vi.mock('./local.js', () => ({getProject: vi.fn(),updateProject: (...args) => mockUpdateProject(...args),+ updateScene: (...args) => mockUpdateScene(...args),}));vi.mock('./sceneRunner.js', () => ({@@ -20,11 +30,20 @@ vi.mock('./stitchRunner.js', () => ({}));vi.mock('./agentBridge.js', () => ({- enqueueTreatmentTask: vi.fn(async () => undefined),+ enqueueTreatmentTask: (...args) => mockEnqueueTreatmentTask(...args),+ enqueueEvaluateTask: (...args) => mockEnqueueEvaluateTask(...args),}));+vi.mock('../videoGen/local.js', () => ({+ sampleEvaluationFrames: (...args) => mockSampleEvaluationFrames(...args),+}));++vi.mock('fs', async () => {+ const actual = await vi.importActual('fs');+ return { ...actual, existsSync: (...args) => mockExistsSync(...args) };+});+import * as localMod from './local.js';-import * as agentBridge from './agentBridge.js';import { advanceAfterSceneSettled } from './completionHook.js';const baseProject = {@@ -223,6 +242,11 @@ describe('advanceAfterSceneSettled', () => {beforeEach(() => {mockRunSceneRender.mockClear();mockUpdateProject.mockClear();+ mockUpdateScene.mockClear();+ mockEnqueueTreatmentTask.mockClear();+ mockEnqueueEvaluateTask.mockClear();+ mockSampleEvaluationFrames.mockReset().mockResolvedValue([]);+ mockExistsSync.mockReset().mockReturnValue(false);});it('picks scene-2 (lowest-order pending) when scene-1 is accepted and scenes 2-6 are pending', async () => {@@ -239,40 +263,337 @@ describe('advanceAfterSceneSettled', () => {expect(sceneArg.sceneId).toBe('scene-2');});- it('enqueues treatment when project has no treatment, even if route already pre-flipped status to planning', async () => {- // Regression: the route's `draft → planning` pre-flip used to short-- // circuit advance via a `status === 'planning'` early-return, leaving- // brand-new projects stuck in planning with no runs and no agent task.+ it('enqueues treatment when project.treatment is null and status is "planning" (start route pre-flip)', async () => {+ // The start route sets status='planning' before calling+ // startCreativeDirectorProject, so advanceAfterSceneSettled must NOT+ // skip treatment enqueue just because status is already 'planning'.+ const project = { id: 'cd-planning', status: 'planning', finalVideoId: null, treatment: null, runs: [] };+ // getProject called twice: initial fetch + fresh fetch inside the treatment branch.+ localMod.getProject+ .mockResolvedValueOnce(project)+ .mockResolvedValueOnce(project);++ await advanceAfterSceneSettled(project.id);++ expect(mockEnqueueTreatmentTask).toHaveBeenCalledTimes(1);+ });++ it('does NOT enqueue a second treatment when a treatment run is already in-flight (persisted runs[] check, live worker)', async () => {+ // Covers the LIVE concurrent-worker case: a treatment task is genuinely+ // running in another agent. The post-restart case where this row is+ // stale is handled separately by recovery.js, which reaps stale+ // `running` rows before calling advanceAfterSceneSettled — so by the+ // time advance runs after a restart, this guard sees `failed` instead+ // of `running` and proceeds to enqueue. See recovery.test.js for that+ // path.const project = {- id: 'cd-stuck',+ id: 'cd-inflight',status: 'planning',finalVideoId: null,treatment: null,- runs: [],+ runs: [{ kind: 'treatment', status: 'running' }],+ };+ localMod.getProject.mockResolvedValueOnce(project);++ await advanceAfterSceneSettled(project.id);++ expect(mockEnqueueTreatmentTask).not.toHaveBeenCalled();+ });++ it('skips treatment when inflightTreatment in-memory set already has the projectId (concurrent call dedup)', async () => {+ // Simulate a concurrent call by firing two advances in parallel.+ // The first resolves slowly so the second enters while the first holds+ // the inflightTreatment lock. Both calls see treatment=null, but only+ // one should enqueue.+ let firstEnqueueResolve;+ mockEnqueueTreatmentTask.mockImplementationOnce(+ () => new Promise((resolve) => { firstEnqueueResolve = resolve; })+ );++ const project = { id: 'cd-concurrent', status: 'rendering', finalVideoId: null, treatment: null, runs: [] };+ // Each call to getProject returns the same base project (no inflight run).+ localMod.getProject.mockResolvedValue(project);++ const first = advanceAfterSceneSettled(project.id);+ // Let the first call fully reach enqueueTreatmentTask before starting the+ // second. There are 3 awaits (getProject, updateProject, getProject) before+ // the enqueue call, so we drain via a macrotask which flushes all pending+ // microtask chains regardless of how many levels deep they are.+ await new Promise((r) => setTimeout(r, 10));++ const second = advanceAfterSceneSettled(project.id);++ // Unblock the first enqueue so both promises can settle.+ firstEnqueueResolve();+ await Promise.all([first, second]);++ expect(mockEnqueueTreatmentTask).toHaveBeenCalledTimes(1);+ });++ it('re-fires the evaluator for an orphaned `evaluating` scene with renderedJobId set (resume-after-pause path)', async () => {+ // The render-completion path persists renderedJobId + status='evaluating'+ // when a pause lands during frame sampling, then bails without enqueuing+ // the evaluator. On resume, advanceAfterSceneSettled must detect the+ // orphan (renderedJobId set, no live evaluate run in runs[]) and re-fire+ // the evaluator instead of falling through to runSceneRender — otherwise+ // the user pays for a full re-render of work that already completed.+ const project = {+ id: 'cd-orphan-eval',+ status: 'rendering',+ finalVideoId: null,+ treatment: {+ scenes: [+ { sceneId: 'scene-1', order: 0, status: 'accepted', renderedJobId: '11111111-1111-4111-8111-111111111111' },+ { sceneId: 'scene-2', order: 1, status: 'evaluating', renderedJobId: '22222222-2222-4222-8222-222222222222', evaluationFrames: ['f1.jpg'] },+ { sceneId: 'scene-3', order: 2, status: 'pending' },+ ],+ },+ runs: [+ // Prior evaluate run was reaped by recovery (status='completed') —+ // there is no LIVE evaluate run, so the resume path should fire.+ { kind: 'evaluate', sceneId: 'scene-2', status: 'completed' },+ ],+ };+ // getProject called twice in this branch: initial fetch + post-sample re-check.+ localMod.getProject.mockResolvedValue(project);+ // The resume path now verifies the rendered .mp4 is still on disk+ // BEFORE deciding to re-sample; let it through. The persisted frame+ // (f1.jpg) is intentionally NOT on disk (existsSync defaults to+ // false for everything else), so sampleEvaluationFrames runs.+ // Simulate a successful re-sample so the evaluator is enqueued.+ mockExistsSync.mockImplementation((p) => typeof p === 'string' && p.endsWith('.mp4'));+ mockSampleEvaluationFrames.mockResolvedValueOnce(['f1.jpg']);++ await advanceAfterSceneSettled(project.id);++ expect(mockEnqueueEvaluateTask).toHaveBeenCalledTimes(1);+ const [, sceneArg] = mockEnqueueEvaluateTask.mock.calls[0];+ expect(sceneArg.sceneId).toBe('scene-2');+ expect(sceneArg.renderedJobId).toBe('22222222-2222-4222-8222-222222222222');+ // Should NOT fall through to runSceneRender for the next pending scene —+ // resume must finish the orphaned evaluate first.+ expect(mockRunSceneRender).not.toHaveBeenCalled();+ });++ it('fails the orphan scene AND advances to the next pending scene when the rendered .mp4 is missing (deleted-while-paused)', async () => {+ // The deleted-video branch in resume must do TWO things:+ // 1. Mark the orphaned scene `failed` (the evaluator's+ // multi-frame and single-thumbnail fallback BOTH need the .mp4+ // and its thumbnail, all of which are unlinked together by+ // videoGen/local#deleteHistoryItem — none can recover).+ // 2. Nudge the orchestrator forward — otherwise the project sits in+ // `rendering` forever because updateScene goes through local.js+ // directly, not the route handler that auto-calls advance.+ const project = {+ id: 'cd-deleted-video',+ status: 'rendering',+ finalVideoId: null,+ treatment: {+ scenes: [+ { sceneId: 'scene-1', order: 0, status: 'evaluating', renderedJobId: '11111111-1111-4111-8111-111111111111', evaluationFrames: [] },+ { sceneId: 'scene-2', order: 1, status: 'pending' },+ ],+ },+ runs: [+ { kind: 'evaluate', sceneId: 'scene-1', status: 'completed' },+ ],+ };+ // After the deleted-video branch fails the orphan scene, the+ // implementation tail-recurses into advanceAfterSceneSettled. Reflect the+ // failure in the mock so the recursive call sees scene-1 as 'failed'+ // (not 'evaluating') and falls through to the nextPending branch instead+ // of re-entering the orphan branch indefinitely. The third+ call serves+ // the runSceneRender re-read.+ const projectAfterFail = {+ ...project,+ treatment: {+ ...project.treatment,+ scenes: [+ { ...project.treatment.scenes[0], status: 'failed' },+ project.treatment.scenes[1],+ ],+ },};localMod.getProject.mockResolvedValueOnce(project)- .mockResolvedValueOnce({ ...project });- agentBridge.enqueueTreatmentTask.mockClear();+ .mockResolvedValue(projectAfterFail);+ // sampleEvaluationFrames returns [] (deleted video / extraction failure).+ mockSampleEvaluationFrames.mockResolvedValue([]);+ // existsSync returns false for every check — simulating that the .mp4+ // is gone from disk (the deleted-video case).+ mockExistsSync.mockReturnValue(false);await advanceAfterSceneSettled(project.id);- expect(agentBridge.enqueueTreatmentTask).toHaveBeenCalledTimes(1);+ // Scene-1 was failed with the right notes.+ expect(mockUpdateScene).toHaveBeenCalledWith(+ 'cd-deleted-video',+ 'scene-1',+ expect.objectContaining({+ status: 'failed',+ evaluation: expect.objectContaining({+ accepted: false,+ notes: expect.stringContaining('rendered video was deleted'),+ }),+ }),+ );+ // Evaluator must NOT be enqueued — there are no frames.+ expect(mockEnqueueEvaluateTask).not.toHaveBeenCalled();+ // After the tail-recursion, the orchestrator advanced to scene-2 (the+ // next pending scene) instead of leaving the project stuck.+ expect(mockRunSceneRender).toHaveBeenCalled();+ const renderedScene = mockRunSceneRender.mock.calls.at(-1)[1];+ expect(renderedScene.sceneId).toBe('scene-2');});- it('does NOT enqueue a duplicate treatment when one is already running', async () => {+ it('enqueues the evaluator with empty frames (single-thumbnail fallback) when frame sampling returns 0 but the rendered video is still on disk', async () => {+ // sampleEvaluationFrames returns [] for non-fatal failures: ffmpeg+ // missing on PATH, ffprobe miscount, transient I/O. The cd-evaluate+ // template has a `{{^multiFrame}}` branch that falls back to the+ // single thumbnail at /data/video-thumbnails/{renderedJobId}.jpg —+ // the same fallback the normal render-completion path relies on. The+ // resume path must mirror that behavior (hand off whatever frames it+ // got, even an empty array) instead of bailing, otherwise the+ // project sits in `rendering` with an orphaned `evaluating` scene+ // and no automatic way back to progress from the UI.const project = {- id: 'cd-dup',- status: 'planning',+ id: 'cd-transient-ffmpeg',+ status: 'rendering',finalVideoId: null,- treatment: null,- runs: [{ runId: 'r1', kind: 'treatment', status: 'running' }],+ treatment: {+ scenes: [+ { sceneId: 'scene-1', order: 0, status: 'evaluating', renderedJobId: '22222222-2222-4222-8222-222222222222', evaluationFrames: [] },+ { sceneId: 'scene-2', order: 1, status: 'pending' },+ ],+ },+ runs: [+ { kind: 'evaluate', sceneId: 'scene-1', status: 'completed' },+ ],};- localMod.getProject.mockResolvedValueOnce(project);- agentBridge.enqueueTreatmentTask.mockClear();+ localMod.getProject.mockResolvedValue(project);+ // Sampling returns [] (failure of some kind).+ mockSampleEvaluationFrames.mockResolvedValue([]);+ // existsSync(videoPath) → true: the rendered .mp4 is still on disk, so+ // the empty frames must be a transient ffmpeg/ffprobe failure.+ mockExistsSync.mockImplementation((p) => typeof p === 'string' && p.endsWith('.mp4'));++ await advanceAfterSceneSettled(project.id);++ // Scene must NOT be marked failed — the render is recoverable.+ expect(mockUpdateScene).not.toHaveBeenCalledWith(+ 'cd-transient-ffmpeg',+ 'scene-1',+ expect.objectContaining({ status: 'failed' }),+ );+ // Evaluator IS enqueued — empty frames go through the+ // single-thumbnail fallback path in the prompt template.+ expect(mockEnqueueEvaluateTask).toHaveBeenCalledTimes(1);+ const [, sceneArg] = mockEnqueueEvaluateTask.mock.calls[0];+ expect(sceneArg.sceneId).toBe('scene-1');+ expect(sceneArg.evaluationFrames).toEqual([]);+ // Resume must not skip past scene-1 to render scene-2 — the orphan+ // evaluator is owning that slot.+ expect(mockRunSceneRender).not.toHaveBeenCalled();+ });++ it('fails the orphan scene when the cached evaluationFrames are still on disk but the rendered .mp4 is gone (video-deleted-while-paused, frames-survive)', async () => {+ // The MP4 existence check must run BEFORE the frame-cache check,+ // because the evaluator (multi-frame OR single-thumbnail fallback)+ // both reference the .mp4 by its renderedJobId. If the user deleted+ // the rendered video while the project was paused but the cached+ // evaluationFrames thumbnails happened to survive (deleteHistoryItem+ // swallows unlink errors), the old code would happily enqueue the+ // evaluator and the scene could be accepted — only for the later+ // stitch step to fail on the missing input file.+ const project = {+ id: 'cd-mp4-gone-frames-stay',+ status: 'rendering',+ finalVideoId: null,+ treatment: {+ scenes: [+ { sceneId: 'scene-1', order: 0, status: 'evaluating', renderedJobId: '33333333-3333-4333-8333-333333333333', evaluationFrames: ['f1.jpg', 'f2.jpg', 'f3.jpg'] },+ { sceneId: 'scene-2', order: 1, status: 'pending' },+ ],+ },+ runs: [+ { kind: 'evaluate', sceneId: 'scene-1', status: 'completed' },+ ],+ };+ const projectAfterFail = {+ ...project,+ treatment: {+ ...project.treatment,+ scenes: [+ { ...project.treatment.scenes[0], status: 'failed' },+ project.treatment.scenes[1],+ ],+ },+ };+ localMod.getProject+ .mockResolvedValueOnce(project)+ .mockResolvedValue(projectAfterFail);+ // Frame thumbnails are on disk (allFramesExist would return true), but+ // the .mp4 is gone — only existsSync calls for the frame .jpg paths+ // return true; the .mp4 check returns false.+ mockExistsSync.mockImplementation((p) => typeof p === 'string' && p.endsWith('.jpg'));await advanceAfterSceneSettled(project.id);- expect(agentBridge.enqueueTreatmentTask).not.toHaveBeenCalled();+ // Scene-1 was failed because the .mp4 is gone, even though the+ // cached frames were still on disk.+ expect(mockUpdateScene).toHaveBeenCalledWith(+ 'cd-mp4-gone-frames-stay',+ 'scene-1',+ expect.objectContaining({+ status: 'failed',+ evaluation: expect.objectContaining({+ accepted: false,+ notes: expect.stringContaining('rendered video was deleted'),+ }),+ }),+ );+ // Evaluator must NOT fire — its inputs (.mp4 and the thumbnail) are+ // gone, regardless of whether the cached frames survived.+ expect(mockEnqueueEvaluateTask).not.toHaveBeenCalled();+ // Sampling is also skipped — we bailed before that step.+ expect(mockSampleEvaluationFrames).not.toHaveBeenCalled();+ // Tail-advance moves the orchestrator forward to scene-2.+ expect(mockRunSceneRender).toHaveBeenCalled();+ expect(mockRunSceneRender.mock.calls.at(-1)[1].sceneId).toBe('scene-2');+ });++ it('rejects + fails orphaned-evaluating scenes whose renderedJobId is not a UUID (path-traversal guard, wedge prevention)', async () => {+ // scene.renderedJobId is editable via PATCH; a tampered value must NOT+ // be accepted into the resume path because sampleEvaluationFrames builds+ // ffmpeg paths via string concat. The scene must also be MARKED FAILED+ // — silently skipping it would leave it `evaluating` forever, and the+ // inflight check at the bottom of advanceAfterSceneSettled would+ // block every future advance call, wedging the whole project.+ const project = {+ id: 'cd-tamper',+ status: 'rendering',+ finalVideoId: null,+ treatment: {+ scenes: [+ { sceneId: 'scene-2', order: 1, status: 'evaluating', renderedJobId: '../../../etc/passwd' },+ { sceneId: 'scene-3', order: 2, status: 'pending' },+ ],+ },+ runs: [],+ };+ localMod.getProject.mockResolvedValue(project);+ await advanceAfterSceneSettled(project.id);+ expect(mockEnqueueEvaluateTask).not.toHaveBeenCalled();+ // The wedged scene must be reset to `failed` so it doesn't block+ // future advances.+ expect(mockUpdateScene).toHaveBeenCalledWith(+ 'cd-tamper',+ 'scene-2',+ expect.objectContaining({ status: 'failed' }),+ );+ // After failing the wedged scene, advance still falls through to+ // render the next pending scene.+ expect(mockRunSceneRender).toHaveBeenCalledTimes(1);+ expect(mockRunSceneRender.mock.calls[0][1].sceneId).toBe('scene-3');});});diff --git a/server/services/creativeDirector/recovery.js b/server/services/creativeDirector/recovery.jsindex 2801aa8700..5ba7b32c54 100644--- a/server/services/creativeDirector/recovery.js+++ b/server/services/creativeDirector/recovery.js@@ -14,24 +14,69 @@* 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+ * 3. Mark any persisted `runs[]` row in `running` state as failed —+ * the agent task behind it died with the previous process. Without+ * this, advanceAfterSceneSettled's persisted-runs guard (which treats+ * any non-terminal `treatment` run as "another worker is on it")+ * would silently refuse to enqueue a replacement and the project+ * would stay stuck in `planning` forever.+ * 4. 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';+import { listProjects, updateScene, updateRun, updateProject } from './local.js';+import { listJobs, cancelJob } from '../mediaJobQueue/index.js';+import { updateTask } from '../cos.js';+// Boot-time coordination: cos.js eagerly calls resetOrphanedTasks() during+// module import, which would respawn stale CD treatment/evaluate tasks+// BEFORE recoverInFlightProjects() has had a chance to retire them via+// updateTask. Two concurrent agents would then race on the same project.+// Expose a promise that cos.init() awaits before its first+// resetOrphanedTasks call, so the order is always:+// 1. recoverInFlightProjects retires stale CD tasks (status='completed').+// 2. cos.resetOrphanedTasks runs and finds nothing CD-related to respawn.+let resolveRecoveryDone;+export const cdRecoveryDone = new Promise((resolve) => {+ resolveRecoveryDone = resolve;+});++// Projects that should be auto-advanced on boot — the user expects them to+// keep running.const RECOVERABLE_STATUSES = new Set(['planning', 'rendering', 'stitching']);+// Projects whose stale state still needs cleanup but should NOT auto-advance+// on boot. `paused` is here because the user pressed Pause; we still need to+// wipe the dead in-flight state behind the pause so Resume picks up cleanly,+// but we don't want to fire a fresh agent task before the user clicks+// Resume themselves.+const CLEANUP_ONLY_STATUSES = new Set(['paused']);const STUCK_SCENE_STATUSES = new Set(['rendering', 'evaluating']);export async function recoverInFlightProjects() {+ // Stamp the recovery start so we can distinguish boot-snapshot jobs+ // (queued by the dead worker before restart, must be canceled) from+ // jobs the user enqueued AFTER recovery began (e.g. clicked Resume+ // mid-recovery — the new job must NOT be canceled as an "orphan").+ // recoverInFlightProjects runs fire-and-forget from index.js and the+ // user can interact during that window.+ const recoveryStartedAt = Date.now();const projects = await listProjects();- const recoverable = projects.filter((p) => RECOVERABLE_STATUSES.has(p.status));- if (!recoverable.length) return { resumed: 0 };+ const needsCleanup = projects.filter(+ (p) => RECOVERABLE_STATUSES.has(p.status) || CLEANUP_ONLY_STATUSES.has(p.status),+ );+ if (!needsCleanup.length) {+ // Must resolve the gate even on the no-op path or cos.init's+ // resetOrphanedTasks await would sit on its 5s timeout for nothing+ // every daemon start/auto-start.+ resolveRecoveryDone();+ return { resumed: 0 };+ }const { advanceAfterSceneSettled } = await import('./completionHook.js');let resumed = 0;- for (const project of recoverable) {+ const completedAt = new Date().toISOString();+ for (const project of needsCleanup) {const scenes = project.treatment?.scenes || [];const stuck = scenes.filter((s) => STUCK_SCENE_STATUSES.has(s.status));for (const scene of stuck) {@@ -41,10 +86,112 @@ export async function recoverInFlightProjects() {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;+ // Reap stale `running` agent-run rows AND retire the underlying CoS+ // task. The agent task behind each run died with the previous process,+ // but cos.js#resetOrphanedTasks would otherwise see `in_progress` task+ // rows on boot and respawn them — racing the fresh treatment/evaluate+ // task this recovery path will cause to enqueue. Mark the task failed+ // first so the orphan-task reset finds nothing to retry.+ //+ // taskType MUST be 'internal' here — CD treatment/evaluate tasks are+ // added by agentBridge#persistAndEmit via `addTask(record, 'internal',+ // …)`. Passing 'cos' would write to the wrong file AND, per+ // cos.js#updateTask, strip approval flags from internal task entries+ // (only 'internal' preserves them), silently auto-approving unrelated+ // internal tasks across a CD recovery cycle.+ //+ // status MUST be one of generateTasksMarkdown's supported terminal+ // values (pending/in_progress/blocked/completed) — writing 'failed'+ // would make the parser drop the task from COS-TASKS.md entirely on+ // the next write. Use 'completed' with a metadata audit note so the+ // task is properly retired (preventing orphan re-spawn) without+ // being silently deleted.+ const staleRuns = (project.runs || []).filter((r) => r.status === 'running');+ for (const run of staleRuns) {+ if (run.taskId) {+ await updateTask(run.taskId, {+ status: 'completed',+ metadata: { interruptedByRestart: 'true', recoveredAt: completedAt },+ }, 'internal')+ .catch((e) => console.log(`⚠️ CD recovery: retire internal task ${run.taskId} for ${project.id} failed: ${e.message}`));+ }+ await updateRun(project.id, run.runId, {+ status: 'failed',+ completedAt,+ failureReason: 'interrupted by restart',+ }).catch((e) => console.log(`⚠️ CD recovery: reap run ${run.runId} of ${project.id} failed: ${e.message}`));+ }+ if (staleRuns.length) {+ console.log(`🔄 CD recovery: ${project.id} reaped ${staleRuns.length} stale running run(s)`);+ }+ // Cancel any media-queue jobs owned by this project that+ // initMediaJobQueue() restored from disk. Two reasons: (1) For paused+ // projects the user explicitly stopped, the queued render shouldn't+ // burn GPU on resume. (2) For recovering projects (planning/rendering/+ // stitching) the recovery path resets their scenes to `pending` and+ // advance() will enqueue a fresh render — leaving the prior job alive+ // would race two completions for the same `cd:<projectId>:<sceneId>`+ // owner.+ //+ // We must cancel BOTH queued AND running, not just queued. The queue+ // worker is started by initMediaJobQueue() (see server/index.js boot+ // order) and dequeues restored jobs immediately — by the time this+ // recovery path runs, what was `queued` on disk may already have+ // transitioned to `running` in memory. Cancelling running CD jobs+ // here SIGTERMs the gen process so the freshly-enqueued render+ // doesn't have to compete for GPU memory with a doomed sibling.+ // (Jobs reclassified `failed (interrupted by restart)` by the queue's+ // own boot recovery are already terminal and listJobs returns them+ // archived — they won't match either filter.)+ //+ // Filter to jobs queued BEFORE recovery started — recoverInFlightProjects+ // runs fire-and-forget from index.js, so the user can have already+ // clicked Resume on a paused project and enqueued a fresh render+ // while we're iterating projects here. queuedAt > recoveryStartedAt+ // means it's a brand-new user-initiated job, not a stale snapshot+ // entry, and canceling it would silently kill the user's action.+ const orphaned = listJobs()+ .filter((j) => typeof j.owner === 'string' && j.owner.startsWith(`cd:${project.id}:`))+ .filter((j) => j.status === 'queued' || j.status === 'running')+ .filter((j) => {+ const qa = new Date(j.queuedAt || 0).getTime();+ return qa > 0 && qa < recoveryStartedAt;+ });+ for (const job of orphaned) {+ await cancelJob(job.id)+ .catch((e) => console.log(`⚠️ CD recovery: cancel orphaned ${job.status} job ${job.id} for ${project.id} failed: ${e.message}`));+ }+ if (orphaned.length) {+ console.log(`🔄 CD recovery: ${project.id} canceled ${orphaned.length} orphaned job(s) (mix of queued + already-dequeued, all from pre-recovery snapshot)`);+ }+ // Only auto-advance projects the user expects to still be running.+ // `paused` projects skip this — the cleanup above is enough to make a+ // future Resume click work.+ if (RECOVERABLE_STATUSES.has(project.status)) {+ // Special case: a project that was mid-stitch when the server died+ // still has status='stitching'. advanceAfterSceneSettled exits+ // early when it sees that status (its stitch dedup guard), so it+ // would never re-fire runStitch. Flip back to 'rendering' so the+ // function re-evaluates from scratch — it'll find all scenes+ // accepted, no inflight, no finalVideoId, and call runStitch+ // (which sets status back to 'stitching' itself before starting).+ if (project.status === 'stitching' && !project.finalVideoId) {+ await updateProject(project.id, { status: 'rendering' })+ .catch((e) => console.log(`⚠️ CD recovery: reset stitching→rendering for ${project.id} failed: ${e.message}`));+ }+ 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)`);+ resolveRecoveryDone();return { resumed };}++// Test/resume helper: callers that don't run recoverInFlightProjects (unit+// tests, scripts) should still resolve the gate so any await on+// cdRecoveryDone in cos.init doesn't hang forever. Idempotent.+export function markRecoveryDone() {+ resolveRecoveryDone();+}diff --git a/server/services/creativeDirector/recovery.test.js b/server/services/creativeDirector/recovery.test.jsindex dcfc593842..41bb0e83c4 100644--- a/server/services/creativeDirector/recovery.test.js+++ b/server/services/creativeDirector/recovery.test.js@@ -3,32 +3,52 @@ 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 mockUpdateRun = vi.fn();+const mockUpdateProject = vi.fn();const mockAdvance = vi.fn();+const mockListJobs = vi.fn();+const mockCancelJob = vi.fn();+const mockUpdateTask = vi.fn();vi.mock('./local.js', () => ({listProjects: (...args) => mockListProjects(...args),updateScene: (...args) => mockUpdateScene(...args),+ updateRun: (...args) => mockUpdateRun(...args),+ updateProject: (...args) => mockUpdateProject(...args),}));vi.mock('./completionHook.js', () => ({advanceAfterSceneSettled: (...args) => mockAdvance(...args),}));+vi.mock('../mediaJobQueue/index.js', () => ({+ listJobs: (...args) => mockListJobs(...args),+ cancelJob: (...args) => mockCancelJob(...args),+}));++vi.mock('../cos.js', () => ({+ updateTask: (...args) => mockUpdateTask(...args),+}));+const { recoverInFlightProjects } = await import('./recovery.js');beforeEach(() => {mockListProjects.mockReset();mockUpdateScene.mockReset().mockResolvedValue(undefined);+ mockUpdateRun.mockReset().mockResolvedValue(undefined);mockAdvance.mockReset().mockResolvedValue(undefined);+ mockListJobs.mockReset().mockReturnValue([]);+ mockCancelJob.mockReset().mockResolvedValue({ ok: true, status: 'canceled' });+ mockUpdateTask.mockReset().mockResolvedValue({ ok: true });+ mockUpdateProject.mockReset().mockResolvedValue({ ok: true });});describe('recoverInFlightProjects', () => {- it('skips terminal and draft projects', async () => {+ it('skips terminal and draft projects entirely', 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);@@ -36,6 +56,142 @@ describe('recoverInFlightProjects', () => {expect(mockUpdateScene).not.toHaveBeenCalled();});+ it('cancels orphaned queued media-jobs owned by paused projects', async () => {+ // Without this, initMediaJobQueue() would happily restart a queued+ // render whose owner=cd:<projectId>:<sceneId> belongs to a paused+ // project, burning GPU on work the user explicitly stopped.+ // Use a queuedAt well in the past so the recovery-window filter+ // treats them as pre-recovery snapshot entries.+ const longAgo = new Date(Date.now() - 600000).toISOString();+ mockListProjects.mockResolvedValue([+ { id: 'cd-paused', status: 'paused', treatment: { scenes: [] }, runs: [] },+ ]);+ mockListJobs.mockReturnValue([+ { id: 'job-orphan-1', status: 'queued', owner: 'cd:cd-paused:scene-2', queuedAt: longAgo },+ { id: 'job-orphan-2', status: 'queued', owner: 'cd:cd-paused:scene-3', queuedAt: longAgo },+ { id: 'job-other', status: 'queued', owner: 'cd:cd-other:scene-1', queuedAt: longAgo },+ { id: 'job-no-owner', status: 'queued', owner: null, queuedAt: longAgo },+ ]);+ await recoverInFlightProjects();+ expect(mockCancelJob).toHaveBeenCalledTimes(2);+ expect(mockCancelJob).toHaveBeenCalledWith('job-orphan-1');+ expect(mockCancelJob).toHaveBeenCalledWith('job-orphan-2');+ });++ it('skips orphan-cancel for jobs queued AFTER recovery started (user resumed mid-recovery)', async () => {+ // recoverInFlightProjects is fire-and-forget — the user can click+ // Resume on a paused project and enqueue a fresh render between the+ // listProjects() snapshot and this orphan-cancel loop. That fresh+ // job has queuedAt > recoveryStartedAt and must NOT be canceled.+ const veryRecentFuture = new Date(Date.now() + 60000).toISOString(); // queued "after" recovery start+ const longAgo = new Date(Date.now() - 600000).toISOString();+ mockListProjects.mockResolvedValue([+ { id: 'cd-paused', status: 'paused', treatment: { scenes: [] }, runs: [] },+ ]);+ mockListJobs.mockReturnValue([+ { id: 'job-stale', status: 'queued', owner: 'cd:cd-paused:scene-1', queuedAt: longAgo },+ { id: 'job-fresh', status: 'queued', owner: 'cd:cd-paused:scene-2', queuedAt: veryRecentFuture },+ ]);+ await recoverInFlightProjects();+ expect(mockCancelJob).toHaveBeenCalledTimes(1);+ expect(mockCancelJob).toHaveBeenCalledWith('job-stale');+ expect(mockCancelJob).not.toHaveBeenCalledWith('job-fresh');+ });++ it('also cancels queued jobs for recovering (non-paused) projects to prevent double-render races', async () => {+ // Recovery resets stuck scenes to `pending` and advance() will enqueue+ // a fresh render — leaving the prior queued job alive would race two+ // completions for the same `cd:<projectId>:<sceneId>` owner.+ const longAgo = new Date(Date.now() - 600000).toISOString();+ mockListProjects.mockResolvedValue([+ { id: 'cd-rendering', status: 'rendering', treatment: { scenes: [] }, runs: [] },+ ]);+ mockListJobs.mockReturnValue([+ { id: 'job-orphan', status: 'queued', owner: 'cd:cd-rendering:scene-1', queuedAt: longAgo },+ ]);+ await recoverInFlightProjects();+ expect(mockCancelJob).toHaveBeenCalledWith('job-orphan');+ });++ it('cancels orphaned jobs that have already moved from queued → running by the time recovery runs', async () => {+ // initMediaJobQueue() starts the worker before recovery executes, so+ // restored queued jobs may already be running when listJobs() is+ // called here. Recovery must SIGTERM those too via cancelJob — not+ // just queued — otherwise the dead-listener render keeps burning GPU+ // and the freshly-enqueued sibling fights it for memory.+ const longAgo = new Date(Date.now() - 600000).toISOString();+ mockListProjects.mockResolvedValue([+ { id: 'cd-rendering', status: 'rendering', treatment: { scenes: [] }, runs: [] },+ ]);+ mockListJobs.mockReturnValue([+ { id: 'job-running', status: 'running', owner: 'cd:cd-rendering:scene-1', queuedAt: longAgo },+ { id: 'job-completed', status: 'completed', owner: 'cd:cd-rendering:scene-2', queuedAt: longAgo }, // terminal — must NOT cancel+ { id: 'job-failed', status: 'failed', owner: 'cd:cd-rendering:scene-3', queuedAt: longAgo }, // terminal — must NOT cancel+ ]);+ await recoverInFlightProjects();+ expect(mockCancelJob).toHaveBeenCalledTimes(1);+ expect(mockCancelJob).toHaveBeenCalledWith('job-running');+ });++ it('retires the underlying CoS task for each stale run so cos.js#resetOrphanedTasks does not respawn it', async () => {+ // Without retiring the CoS task, cos.js sees `in_progress` task rows+ // on boot and respawns them — racing the fresh treatment/evaluate task+ // recovery's advance() will enqueue.+ mockListProjects.mockResolvedValue([+ {+ id: 'cd-1',+ status: 'planning',+ treatment: null,+ runs: [+ { runId: 'run-1', taskId: 'task-treatment-abc', kind: 'treatment', status: 'running' },+ { runId: 'run-2', taskId: 'task-eval-def', kind: 'evaluate', sceneId: 's1', status: 'running' },+ { runId: 'run-3', taskId: null, kind: 'evaluate', sceneId: 's2', status: 'running' }, // missing taskId — skip+ ],+ },+ ]);+ await recoverInFlightProjects();+ expect(mockUpdateTask).toHaveBeenCalledTimes(2);+ // taskType MUST be 'internal' — CD tasks are added via addTask(record, 'internal').+ // Passing 'cos' would write to the wrong file and silently strip approval flags.+ // status MUST be 'completed' — generateTasksMarkdown only serializes+ // pending/in_progress/blocked/completed; writing 'failed' would drop+ // the task from COS-TASKS.md entirely. Metadata audit-trails the+ // restart so the orphan-task reset still finds nothing to retry.+ expect(mockUpdateTask).toHaveBeenCalledWith(+ 'task-treatment-abc',+ expect.objectContaining({ status: 'completed', metadata: expect.objectContaining({ interruptedByRestart: 'true' }) }),+ 'internal',+ );+ expect(mockUpdateTask).toHaveBeenCalledWith(+ 'task-eval-def',+ expect.objectContaining({ status: 'completed', metadata: expect.objectContaining({ interruptedByRestart: 'true' }) }),+ 'internal',+ );+ });++ it('cleans up paused projects but does NOT auto-advance them', async () => {+ // The user pressed Pause; we still need to wipe dead in-flight scene+ // state and stale running runs so a future Resume click finds a clean+ // slate. But we must NOT fire advance — that would burn agent time+ // before the user explicitly clicks Resume.+ mockListProjects.mockResolvedValue([+ {+ id: 'cd-paused',+ status: 'paused',+ treatment: { scenes: [{ sceneId: 's1', status: 'evaluating' }] },+ runs: [{ runId: 'run-stale', kind: 'evaluate', sceneId: 's1', status: 'running' }],+ },+ ]);+ const result = await recoverInFlightProjects();+ expect(result.resumed).toBe(0);+ expect(mockUpdateScene).toHaveBeenCalledWith('cd-paused', 's1', { status: 'pending' });+ expect(mockUpdateRun).toHaveBeenCalledWith('cd-paused', 'run-stale', expect.objectContaining({+ status: 'failed',+ failureReason: 'interrupted by restart',+ }));+ expect(mockAdvance).not.toHaveBeenCalled();+ });+it('resets stuck rendering/evaluating scenes to pending and advances', async () => {mockListProjects.mockResolvedValue([{@@ -69,16 +225,69 @@ describe('recoverInFlightProjects', () => {expect(mockAdvance).toHaveBeenCalledWith('cd-1');});- it('resumes stitching-state projects (final concat interrupted)', async () => {+ it('resumes stitching-state projects (final concat interrupted) by flipping back to rendering first', async () => {+ // advanceAfterSceneSettled bails out early when status === 'stitching'+ // (its in-flight stitch dedup guard), so without flipping the status+ // back to 'rendering' here the recovery would silently leave the+ // project frozen at "all scenes accepted, no finalVideoId, never+ // re-stitched" — needing manual JSON edits to escape.+ mockListProjects.mockResolvedValue([+ {+ id: 'cd-1',+ status: 'stitching',+ finalVideoId: null,+ treatment: { scenes: [{ sceneId: 's1', status: 'accepted', renderedJobId: 'job-1' }] },+ },+ ]);+ const result = await recoverInFlightProjects();+ expect(result.resumed).toBe(1);+ expect(mockUpdateProject).toHaveBeenCalledWith('cd-1', { status: 'rendering' });+ expect(mockAdvance).toHaveBeenCalledWith('cd-1');+ });++ it('does NOT flip stitching → rendering when finalVideoId is already set (stitch already finished, just status not flipped)', async () => {mockListProjects.mockResolvedValue([{id: 'cd-1',status: 'stitching',+ finalVideoId: 'final-job-1',treatment: { scenes: [{ sceneId: 's1', status: 'accepted', renderedJobId: 'job-1' }] },},]);+ await recoverInFlightProjects();+ expect(mockUpdateProject).not.toHaveBeenCalled();+ expect(mockAdvance).toHaveBeenCalledWith('cd-1');+ });++ it('reaps stale running runs[] rows so the persisted-runs guard does not block re-enqueue', async () => {+ // Regression: a project that restarted mid-treatment still has a+ // persisted `runs: [{ kind: 'treatment', status: 'running' }]` from+ // before the crash. Without reaping, advanceAfterSceneSettled's+ // hasInflightTreatmentRun guard would treat this as another worker on+ // it and refuse to enqueue a replacement, leaving the project frozen.+ mockListProjects.mockResolvedValue([+ {+ id: 'cd-1',+ status: 'planning',+ treatment: null,+ runs: [+ { runId: 'run-completed', kind: 'treatment', status: 'completed' },+ { runId: 'run-stale-1', kind: 'treatment', status: 'running' },+ { runId: 'run-stale-2', kind: 'evaluate', sceneId: 's1', status: 'running' },+ ],+ },+ ]);const result = await recoverInFlightProjects();expect(result.resumed).toBe(1);+ expect(mockUpdateRun).toHaveBeenCalledTimes(2);+ expect(mockUpdateRun).toHaveBeenCalledWith('cd-1', 'run-stale-1', expect.objectContaining({+ status: 'failed',+ failureReason: 'interrupted by restart',+ }));+ expect(mockUpdateRun).toHaveBeenCalledWith('cd-1', 'run-stale-2', expect.objectContaining({+ status: 'failed',+ failureReason: 'interrupted by restart',+ }));expect(mockAdvance).toHaveBeenCalledWith('cd-1');});diff --git a/server/services/creativeDirector/sceneRunner.js b/server/services/creativeDirector/sceneRunner.jsindex d402cf9f90..bffcc4945a 100644--- a/server/services/creativeDirector/sceneRunner.js+++ b/server/services/creativeDirector/sceneRunner.js@@ -31,12 +31,12 @@import { join, basename, resolve as resolvePath, sep as PATH_SEP } from 'path';import { existsSync } from 'fs';import { PATHS } from '../../lib/fileUtils.js';+import { verifyVideoPlayable } from '../../lib/ffmpeg.js';import { presetToRenderParams } from '../../lib/creativeDirectorPresets.js';-import { extractEvaluationFrames, safeUnder, verifyVideoPlayable } from '../../lib/ffmpeg.js';-import { extractLastFrame } from '../videoGen/local.js';+import { extractLastFrame, sampleEvaluationFrames } from '../videoGen/local.js';import { enqueueJob, mediaJobEvents } from '../mediaJobQueue/index.js';import { getSettings } from '../settings.js';-import { updateScene, getProject } from './local.js';+import { updateScene, updateProject, getProject } from './local.js';import { enqueueEvaluateTask } from './agentBridge.js';const MAX_SCENE_RETRIES = 3;@@ -82,7 +82,23 @@ export async function runSceneRender(project, scene) {// last frame and use that as the source.// - else if scene.sourceImageFile set → use that file.// - else → text-to-video (no source).+ //+ // `continuationFellBack` records that the scene asked for i2v continuation+ // but we couldn't honor it (prior scene's last frame missing/unextractable+ // or no accepted prior scene at all) and silently degraded to text-to-+ // video. The autoAccept path uses this to fail the scene instead of+ // accepting a render that proves nothing about the i2v chaining mechanics+ // — otherwise the smoke test would report green even when continuation is+ // broken.let sourceImageFile = scene.sourceImageFile || null;+ let continuationFellBack = false;+ // Track whether `sourceImageFile` was assigned via the continuation+ // branch (vs. being a user-supplied scene.sourceImageFile). If it+ // was, and the path-resolution step below later drops it as missing+ // or invalid, we need to flag continuationFellBack — otherwise the+ // smoke-test autoAccept path silently reports a green render even+ // though the actual i2v chaining never engaged.+ let continuationSourceFromExtract = false;if (scene.useContinuationFromPrior) {const fresh = await getProject(project.id);const priorScene = (fresh?.treatment?.scenes || [])@@ -95,11 +111,14 @@ export async function runSceneRender(project, scene) {});if (lf?.filename) {sourceImageFile = lf.filename;+ continuationSourceFromExtract = true;} else {console.log(`⚠️ CD scene ${scene.sceneId} requested continuation but last-frame extract failed — falling back to text-to-video`);+ continuationFellBack = true;}} else {console.log(`⚠️ CD scene ${scene.sceneId} requested continuation but no prior accepted scene exists — falling back`);+ continuationFellBack = true;}}@@ -127,6 +146,16 @@ export async function runSceneRender(project, scene) {}}}+ // If the continuation branch above produced a sourceImageFile but the+ // path-resolution step just dropped it (file missing, dot-segment, or+ // outside PATHS.images), the render will silently fall through to+ // text-to-video. Surface that as a continuation fallback so the+ // smoke-test autoAccept guard still catches it — otherwise the test+ // could report a green render that proves nothing about i2v chaining.+ if (continuationSourceFromExtract && !sourceImagePath) {+ console.log(`⚠️ CD scene ${scene.sceneId} continuation last-frame resolved to no file — flagging as fallback`);+ continuationFellBack = true;+ }const renderParams = presetToRenderParams({aspectRatio: project.aspectRatio,@@ -166,7 +195,7 @@ export async function runSceneRender(project, scene) {const onCompleted = async (job) => {if (job.id !== jobId) return;cleanup();- await handleRenderCompleted(project.id, scene.sceneId, jobId);+ await handleRenderCompleted(project.id, scene.sceneId, jobId, { continuationFellBack });};const onFailed = async (job) => {if (job.id !== jobId) return;@@ -195,7 +224,7 @@ export async function runSceneRender(project, scene) {return jobId;}-async function handleRenderCompleted(projectId, sceneId, jobId) {+async function handleRenderCompleted(projectId, sceneId, jobId, opts = {}) {console.log(`✅ CD scene render done: ${projectId} / ${sceneId} → ${jobId.slice(0, 8)}`);const fresh = await getProject(projectId);if (!fresh) return;@@ -206,17 +235,56 @@ async function handleRenderCompleted(projectId, sceneId, jobId) {// 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) {- // Sanity-check the rendered file BEFORE marking accepted: a black /- // zero-byte / unreadable render exits the queue with code 0 in some- // ffmpeg+mlx_video failure modes, which would otherwise sail through- // auto-accept and pollute the collection with broken videos.- const videoPath = safeUnder(PATHS.videos, `${jobId}.mp4`);- const sanity = videoPath- ? await verifyVideoPlayable(videoPath)- : { ok: false, reason: `unsafe video path for jobId ${jobId}` };- if (!sanity.ok) {- console.log(`⚠️ CD auto-accept sanity check failed for ${sceneId} (${jobId.slice(0, 8)}): ${sanity.reason}`);- await handleRenderFailed(projectId, sceneId, `auto-accept sanity check failed: ${sanity.reason}`);+ // If the scene asked for i2v continuation but the runner silently fell+ // back to text-to-video (prior render's last frame was missing or+ // unextractable), we MUST fail here. Otherwise the smoke test would+ // report green even when continuation chaining is broken — exactly the+ // regression this fixture is supposed to catch.+ //+ // Bypass handleRenderFailed: that function retries up to+ // MAX_SCENE_RETRIES, and a broken last-frame extraction will fail the+ // same way every retry — burning three more full renders before+ // surfacing the regression. Mark terminal directly and let the+ // completion hook decide what to do next.+ if (opts.continuationFellBack && scene.useContinuationFromPrior) {+ const reason = `scene ${sceneId} requested continuation but fell back to text-to-video`;+ console.log(`❌ CD auto-accept: ${reason} — failing the entire smoke project so the regression is visible immediately (one accepted scene + later failures would still stitch + complete and hide this).`);+ // Failing only the scene isn't enough: advanceAfterSceneSettled keeps+ // going as long as at least one scene was accepted, which would then+ // stitch the surviving clips into a `complete` project and report the+ // smoke run as green even though i2v chaining is provably broken.+ // Fail the whole project so the smoke fixture goes red.+ await updateScene(projectId, sceneId, {+ status: 'failed',+ evaluation: {+ accepted: false,+ notes: `Render failed: ${reason}`,+ sampledAt: new Date().toISOString(),+ },+ });+ await updateProject(projectId, {+ status: 'failed',+ failureReason: `i2v continuation regression detected: ${reason}`,+ }).catch((e) => console.log(`⚠️ CD updateProject(failed) for ${projectId} failed: ${e.message}`));+ return;+ }+ const videoPath = join(PATHS.videos, `${jobId}.mp4`);+ const playable = await verifyVideoPlayable(videoPath);+ if (!playable.ok) {+ const reason = playable.reason || 'video file unplayable';+ console.log(`❌ CD auto-accept: video unplayable for ${jobId.slice(0, 8)}: ${reason} — failing smoke project directly (retrying would waste renders; a broken render must not produce a green smoke result).`);+ await updateScene(projectId, sceneId, {+ status: 'failed',+ evaluation: {+ accepted: false,+ notes: `Render failed: ${reason}`,+ sampledAt: new Date().toISOString(),+ },+ });+ await updateProject(projectId, {+ status: 'failed',+ failureReason: `unplayable render detected: ${reason}`,+ }).catch((e) => console.log(`⚠️ CD updateProject(failed) for ${projectId} failed: ${e.message}`));return;}await updateScene(projectId, sceneId, {@@ -238,32 +306,59 @@ async function handleRenderCompleted(projectId, sceneId, jobId) {await advanceAfterSceneSettled(projectId);return;}- // Sample 5 evenly-spaced frames so the evaluator can judge intent across- // the full timeline rather than only the opening pose. i2v scenes whose- // payoff lands mid- or late-clip (archway appearing, light bloom) were- // getting rejected when the agent only saw frame 0.- const videoPath = safeUnder(PATHS.videos, `${jobId}.mp4`);- const evaluationFrames = videoPath- ? await extractEvaluationFrames(videoPath, jobId, 5).catch((e) => {- console.log(`⚠️ CD multi-frame extract failed for ${jobId.slice(0, 8)}: ${e.message}`);- return [];- })- : [];- if (evaluationFrames.length > 0) {- console.log(`🎞️ CD sampled ${evaluationFrames.length} evaluator frames for ${sceneId} (${jobId.slice(0, 8)})`);+ // Helper: persist the completed render and skip the evaluator. The+ // pause/fail-aware path keeps the scene in `evaluating` with the+ // renderedJobId set so resume can pick up evaluation directly without+ // re-rendering. completionHook#advanceAfterSceneSettled detects+ // orphaned `evaluating` scenes (renderedJobId set, no live evaluate+ // run in runs[]) and re-fires the evaluator — closing the loop without+ // wasting the rendered clip.+ const skipEvaluatorForPause = async (statusLabel, frames) => {+ await updateScene(projectId, sceneId, {+ status: 'evaluating',+ renderedJobId: jobId,+ evaluationFrames: frames,+ });+ console.log(`⏸️ CD project ${projectId} is ${statusLabel} — render landed during pause; persisting renderedJobId on scene ${sceneId} and deferring evaluator to resume.`);+ };+ // Pre-frame-sample status check: a user pause that landed while the+ // render was in flight should short-circuit BEFORE we burn ffprobe ++ // ffmpeg cycles writing throwaway thumbnails. Frames will be sampled+ // on resume by advanceAfterSceneSettled instead.+ const preFrames = await getProject(projectId);+ if (preFrames?.status === 'paused' || preFrames?.status === 'failed') {+ await skipEvaluatorForPause(preFrames.status, []);+ return;+ }+ const evaluationFrames = await sampleEvaluationFrames(jobId).catch((err) => {+ console.error(`❌ CD sampleEvaluationFrames failed for ${jobId.slice(0, 8)}: ${err.message}`);+ return [];+ });+ // Re-check immediately before the agent-task enqueue. Single-user+ // single-instance app per CLAUDE.md, but pause IS a real user action+ // and the API roundtrip can land between this read and the enqueue+ // below. The cost of one extra read is trivial vs. spending an agent+ // run on work the user explicitly canceled.+ const postFrames = await getProject(projectId);+ if (postFrames?.status === 'paused' || postFrames?.status === 'failed') {+ await skipEvaluatorForPause(postFrames.status, evaluationFrames);+ return;}-await updateScene(projectId, sceneId, {status: 'evaluating',renderedJobId: jobId,evaluationFrames,});- await enqueueEvaluateTask(fresh, {- ...scene,- status: 'evaluating',- renderedJobId: jobId,- evaluationFrames,- });+ // Final pause guard: close the async gap between the postFrames check above+ // and the enqueue below. The scene is already persisted in 'evaluating' with+ // renderedJobId set, so advanceAfterSceneSettled's resume path will pick it+ // up correctly on the next Resume click — no further action needed here.+ const postUpdate = await getProject(projectId);+ if (postUpdate?.status === 'paused' || postUpdate?.status === 'failed') {+ console.log(`⏸️ CD project ${projectId} is ${postUpdate.status} — paused during updateScene; renderedJobId persisted on scene ${sceneId}, deferring evaluator to resume.`);+ return;+ }+ await enqueueEvaluateTask(fresh, { ...scene, renderedJobId: jobId, status: 'evaluating', evaluationFrames });}async function handleRenderCanceled(projectId, sceneId) {diff --git a/server/services/creativeDirector/smokeTest.js b/server/services/creativeDirector/smokeTest.jsindex 18348b6679..ab36c42112 100644--- a/server/services/creativeDirector/smokeTest.js+++ b/server/services/creativeDirector/smokeTest.js@@ -19,23 +19,14 @@* continuation doesn't* drift)*- * Result: ~6s total runtime at 384×384 (1:1-small hidden preset), 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).- *- * Cost knobs the smoke test deliberately picks:- * - aspectRatio '1:1-small' (384×384, ~44% fewer pixels than 1:1's- * 512×512) — hidden from the user-facing dropdown via ASPECT_RATIOS,- * valid in ASPECT_PRESETS so render params resolve.- * - quality 'draft' (8 denoising steps, 24fps).- * - durationSeconds 2 per scene → numFrames rounds to 48 per scene.- * - 3 scenes (T2V baseline, color-change continuation, pure- * continuation) — all three earn their keep verifying distinct- * pipeline behaviors.+ * Result: ~6s of generated video, 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';+import { getDefaultVideoModelId } from '../../lib/mediaModels.js';const SMOKE_SCENES = [{@@ -76,18 +67,26 @@ const SMOKE_TREATMENT = {scenes: SMOKE_SCENES,};-const SMOKE_DEFAULTS = {+// Resolve at call time, not at module load — getDefaultVideoModelId reads+// the per-platform registry (data/media-models.json) and returns the+// active default for the current OS. Hardcoding `ltx23_distilled_q4`+// (macOS-only) made the smoke run fail with "Unknown video model" on+// Windows. Callers can still override modelId via the overrides arg.+const buildSmokeDefaults = () => ({name: 'CD smoke test (colored ball)',+ // Use the 384×384 legacy preset (kept in ASPECT_PRESETS specifically for+ // this fixture) — at 3 × 2s scenes that's roughly 63% fewer pixel-frames+ // than 1:1 (512×512) × 3s, keeping the health check cheap to run.aspectRatio: '1:1-small',quality: 'draft',- modelId: 'ltx23_distilled_q4',+ modelId: getDefaultVideoModelId(),targetDurationSeconds: 6,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@@ -97,8 +96,9 @@ const SMOKE_DEFAULTS = {* Pure orchestration — no HTTP, no UI, no agent spawns.*/export async function createSmokeTestProject(overrides = {}) {- const project = await createProject({ ...SMOKE_DEFAULTS, ...overrides });+ const defaults = buildSmokeDefaults();+ const project = await createProject({ ...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})`);+ console.log(`🧪 CD smoke project ready: ${withTreatment.id} (${withTreatment.scenes?.length ?? withTreatment.treatment?.scenes?.length ?? 0} scenes, model=${withTreatment.modelId}, autoAcceptScenes=${withTreatment.autoAcceptScenes ?? defaults.autoAcceptScenes}, disableAudio=${withTreatment.disableAudio ?? defaults.disableAudio})`);return withTreatment;}diff --git a/server/services/creativeDirector/smokeTest.test.js b/server/services/creativeDirector/smokeTest.test.jsindex ca8d5dea93..872e37a752 100644--- a/server/services/creativeDirector/smokeTest.test.js+++ b/server/services/creativeDirector/smokeTest.test.js@@ -15,6 +15,12 @@ vi.mock('../mediaCollections.js', () => ({createCollection: vi.fn(async () => ({ id: 'col-smoke' })),}));+// Mock the platform-default model resolver — real one reads+// data/media-models.json which doesn't exist in tests.+vi.mock('../../lib/mediaModels.js', () => ({+ getDefaultVideoModelId: () => 'ltx23_distilled_q4',+}));+const { createSmokeTestProject } = await import('./smokeTest.js');beforeEach(() => {@@ -32,13 +38,13 @@ describe('createSmokeTestProject', () => {const project = await createSmokeTestProject();expect(project.disableAudio).toBe(true);expect(project.autoAcceptScenes).toBe(true);- // Hidden small preset (384×384) keeps smoke renders fast — present in- // ASPECT_PRESETS but intentionally absent from ASPECT_RATIOS so the UI- // doesn't expose it.expect(project.aspectRatio).toBe('1:1-small');expect(project.quality).toBe('draft');expect(project.targetDurationSeconds).toBe(6);expect(project.treatment.scenes).toHaveLength(3);+ // Lock per-scene durations so a future tweak (e.g. 2s → 3s) gets caught.+ // Smoke run total compute is O(scenes × duration² × resolution²) — drift+ // here makes the health check silently expensive without anyone noticing.for (const scene of project.treatment.scenes) {expect(scene.durationSeconds).toBe(2);}diff --git a/server/services/creativeDirector/stitchRunner.js b/server/services/creativeDirector/stitchRunner.jsindex 7b6157fdbf..d630dd1ac2 100644--- a/server/services/creativeDirector/stitchRunner.js+++ b/server/services/creativeDirector/stitchRunner.js@@ -15,6 +15,7 @@ import {createProject as createTimelineProject,updateProject as updateTimelineProject,renderProject as renderTimelineProject,+ getProject as getTimelineProject,getRenderJobStatus,} from '../videoTimeline/local.js';import { loadHistory } from '../videoGen/local.js';@@ -42,17 +43,40 @@ export async function runStitch(projectId) {console.log(`🎬 CD stitch starting: ${projectId} (${clips.length} clips)`);try {- const timeline = await createTimelineProject(`${project.name} — Final Cut`);+ // Reuse the previously-created timeline project if one exists. Without+ // this, a server crash or restart between createTimelineProject and the+ // final render's history landing would create a fresh timeline project+ // every recovery cycle, leaking orphaned entries into video-projects.json+ // and the Timeline UI. We still re-write the clips list (scenes may have+ // been re-rendered between attempts) before re-rendering. If the+ // persisted timelineProjectId points to a deleted/missing project, fall+ // through and create a new one.+ let timeline = null;+ if (project.timelineProjectId) {+ timeline = await getTimelineProject(project.timelineProjectId).catch(() => null);+ if (timeline) {+ console.log(`🔁 CD stitch: reusing timeline project ${timeline.id.slice(0, 8)} from prior attempt for ${projectId}`);+ } else {+ console.log(`🆕 CD stitch: persisted timelineProjectId for ${projectId} is missing — creating a fresh timeline project`);+ }+ }+ if (!timeline) {+ timeline = await createTimelineProject(`${project.name} — Final Cut`);+ await updateProject(projectId, { timelineProjectId: timeline.id });+ }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.+ // Poll video-history.json for an entry whose id matches THIS render's+ // jobId. Match strictly on jobId — not on timelineProjectId — because+ // when we reuse an existing timeline project (recovery path), an older+ // successful render from a previous attempt could still be in history+ // tagged with the same timelineProjectId. Picking that up here would+ // mark the CD project complete with a stale finalVideoId while the+ // fresh render is still running. The timeline service writes its+ // history entry with `id: jobId` (videoTimeline/local.js), so jobId+ // alone uniquely identifies the current render's output.const deadline = Date.now() + FINAL_RENDER_TIMEOUT_MS;let finalEntry = null;while (Date.now() < deadline) {@@ -67,7 +91,7 @@ export async function runStitch(projectId) {}const history = await loadHistory().catch(() => []);- finalEntry = history.find((h) => h.id === jobId || h.timelineProjectId === timeline.id);+ finalEntry = history.find((h) => h.id === jobId);if (finalEntry) break;await sleep(FINAL_RENDER_POLL_MS);}diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex d79e73934f..550c23ac75 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -1,27 +1,25 @@/**- * Media Job Queue — lane-aware FIFO for image + video gen jobs.+ * Media Job Queue — two-lane 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. The codex image provider had the same single-flight constraint at- * the provider level. That made any agent-driven pipeline (Creative Director,- * writers-room storyboard) need to retry/backoff. This queue serializes- * submissions so callers always get an immediate `queued` ack and watch- * progress via SSE.+ * Why this exists: video gen (mlx_video) and local 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.*- * Lanes: jobs run concurrently across lanes but serialize within a lane.- * - `gpu` lane: videoGen/local + imageGen/local — share the MLX/Metal- * runtime and OOM together, so they all share a single slot.- * - `codex` lane: imageGen/codex — runs the external `codex` CLI, doesn't- * touch the MLX runtime, gets its own slot so a writers-room storyboard- * burst doesn't sit behind unrelated video work.+ * Lanes: GPU jobs (video + local image) drain serially through `running` since+ * they share the MLX runtime. Codex image jobs run in a parallel `codexRunning`+ * lane — they shell out to an external CLI and don't compete for GPU memory,+ * so a long video render never blocks a Codex storyboard generation.** Scope: gates `videoGen/local#generateVideo` (always),* `imageGen/local#generateImage` (when imageGen mode === 'local'), and- * `imageGen/codex#generateImage` (when imageGen mode === 'codex'). The- * external SD-API backend bypasses the queue — it's a remote call with no- * shared local state.+ * `imageGen/codex#generateImage` (when mode === 'codex') in a separate+ * concurrent lane — Codex doesn't share the MLX runtime so it runs alongside+ * GPU jobs without OOMing the machine. External SD-API mode bypasses the+ * queue entirely — it's a remote call with no local single-flight+ * constraint to absorb.** Persistence: data/media-jobs.json holds queued + running + recently-finished* jobs. On boot, any 'running' is reclassified as 'failed (interrupted by@@ -65,6 +63,17 @@ function isUnderUploadsRoot(p) {return pathResolve(p).startsWith(uploadsRoot);}+// Normalize `uploadedTempPaths` to an array regardless of how it arrived+// in persisted params. Handles three cases:+// - Array → use as-is (normal path)+// - string → wrap in array (legacy/corrupt single-string serialization)+// - other → treat as empty (null, undefined, corrupt non-string)+function normalizeTempPaths(p) {+ if (Array.isArray(p)) return p;+ if (typeof p === 'string' && p.length > 0) return [p];+ return [];+}+// 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().@@ -80,75 +89,32 @@ async function safeUnlinkUpload(path) {await unlink(path).catch(() => {});}-// Walks both `uploadedTempPath` (single, start-frame upload) and-// `uploadedTempPaths` (array, additional staged uploads such as the FFLF-// lastImage) so cleanup paths stay agnostic to which fields contributed.-// Also handles the corrupted-JSON case where `uploadedTempPaths` arrives as-// a single string (treats it as a one-entry array) — defense-in-depth so a-// hand-edited media-jobs.json still gets its staged file unlinked.-async function safeUnlinkAllUploads(params) {- if (!params) return;- await safeUnlinkUpload(params.uploadedTempPath);- const paths = params.uploadedTempPaths;- if (Array.isArray(paths)) {- for (const p of paths) await safeUnlinkUpload(p);- } else if (typeof paths === 'string') {- await safeUnlinkUpload(paths);- }-}-export const JOB_KINDS = Object.freeze(['video', 'image']);export const JOB_STATUSES = Object.freeze(['queued', 'running', 'completed', 'failed', 'canceled']);-export const mediaJobEvents = new EventEmitter();--// Lane keying — controls which jobs share a single in-flight slot.-//-// `gpu` lane: video gen (mlx_video) + local image gen (mflux/diffusers/flux2)-// share the Metal/MLX runtime and OOM the box if they run together, so only-// one runs at a time across both kinds.-//-// `codex` lane: codex CLI image gen runs externally (it shells out to the-// user's locally-installed `codex` binary, which doesn't touch our GPU/MLX-// runtime). It needs its own slot so a queued storyboard render doesn't sit-// behind a video render that has nothing to do with it. Multiple codex jobs-// still serialize against EACH OTHER on this lane (the codex provider only-// holds one child process at a time).-const LANE_GPU = 'gpu';-const LANE_CODEX = 'codex';--const isCodexJob = (job) => job.kind === 'image' && job.params?.mode === 'codex';--function laneForJob(job) {- return isCodexJob(job) ? LANE_CODEX : LANE_GPU;-}--// Resolve the gen module that owns the job's process so cancel() and the-// watchdog know which provider's `cancel()` to call. Codex image jobs route-// through a separate provider from local image jobs even though they share-// the kind='image' bucket, so dispatching by kind alone wouldn't suffice.-async function importGenModuleForJob(job) {+// Returns a Promise that resolves to the gen module for the given job's+// provider (video/local, imageGen/local, or imageGen/codex). Single source+// of provider-dispatch truth — used by the watchdog, runJob, and cancelJob+// so a new provider addition is one edit instead of three.+function getGenModuleForJob(job) {if (job.kind === 'video') return import('../videoGen/local.js');- if (job.kind === 'image') {- return isCodexJob(job)- ? import('../imageGen/codex.js')- : import('../imageGen/local.js');- }- return null;+ if (job.kind === 'image' && job.params?.mode === 'codex') return import('../imageGen/codex.js');+ if (job.kind === 'image') return import('../imageGen/local.js');+ return Promise.resolve(null);}-// Live state. `queue` holds pending jobs in submission order. `running` maps-// lane → job (at most one job per lane at any time). `archive` holds-// recently-finished jobs (visible for ~24h via /api/media-jobs?status=completed).+export const mediaJobEvents = new EventEmitter();++// Live state. GPU jobs: at most one in `running` at a time. Codex image jobs+// (`kind === 'image' && params.mode === 'codex'`) run in a separate concurrent+// lane (`codexRunning`) because they don't share the MLX runtime. `queue`+// holds pending jobs in submission order. `archive` holds recently-finished+// jobs (visible for ~24h via /api/media-jobs?status=completed).const queue = [];-const running = new Map();+let running = null;+let codexRunning = null;const archive = [];-// Snapshot of all currently-running jobs as an array, in lane-insertion order.-// Convenience for the persistence + listing paths that previously did-// `running ? [running] : []`.-const runningArray = () => Array.from(running.values());-// 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@@ -161,9 +127,8 @@ let workerStarted = false;let initPromise = null;function findJob(jobId) {- for (const r of running.values()) {- if (r.id === jobId) return r;- }+ if (running && running.id === jobId) return running;+ if (codexRunning && codexRunning.id === jobId) return codexRunning;const inQueue = queue.find((j) => j.id === jobId);if (inQueue) return inQueue;return archive.find((j) => j.id === jobId) || null;@@ -175,7 +140,8 @@ export function getJob(jobId) {export function listJobs({ status, kind, owner } = {}) {const all = [- ...runningArray(),+ ...(running ? [running] : []),+ ...(codexRunning ? [codexRunning] : []),...queue,...archive,];@@ -209,7 +175,8 @@ async function persistImpl() {archive.length = 0;archive.push(...trimmedArchive);const live = [- ...runningArray(),+ ...(running ? [running] : []),+ ...(codexRunning ? [codexRunning] : []),...queue,...archive,];@@ -239,11 +206,14 @@ export async function initMediaJobQueue() {archive.push(failed);restartedFailedIds.push(failed.id);// The failed job will never reach the worker's cleanup, so any- // multipart uploads it staged into data/uploads would leak forever.- // safeUnlinkAllUploads constrains each delete to PATHS.uploads so we+ // 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).- safeUnlinkAllUploads(j.params);+ safeUnlinkUpload(j.params?.uploadedTempPath);+ for (const p of normalizeTempPaths(j.params?.uploadedTempPaths)) {+ safeUnlinkUpload(p);+ }} else if (j.status === 'queued') {queue.push({ ...j });} else {@@ -253,8 +223,19 @@ export async function initMediaJobQueue() {// 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; });+ // event report accurate slots. Positions are lane-scoped: Codex image+ // jobs and GPU jobs each get their own counter so a queued Codex job+ // behind a running GPU job is restored as position 1 (not position 2).+ const isCodexJob = (j) => j.kind === 'image' && j.params?.mode === 'codex';+ let codexCounter = 0;+ let gpuCounter = 0;+ for (const q of queue) {+ if (isCodexJob(q)) {+ q.position = ++codexCounter;+ } else {+ q.position = ++gpuCounter;+ }+ }if (persistedJobs.length) {console.log(`📦 mediaJobQueue restored: ${queue.length} queued, ${archive.length} archived`);}@@ -294,73 +275,70 @@ function startWorker() {});}+// Both lanes use fire-and-forget so the poll loop is never blocked by a+// running job. This lets a Codex job that arrives while a GPU render is in+// flight be picked up immediately on the next 150 ms tick instead of having+// to wait for the entire GPU job to finish first.+function startLaneJob(job, { isCodex }) {+ queue.splice(queue.indexOf(job), 1);+ job.status = 'running';+ job.startedAt = new Date().toISOString();+ job.position = 1;+ if (isCodex) {+ codexRunning = job;+ } else {+ running = job;+ }+ recomputeQueuePositions();+ persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on ${isCodex ? 'codex' : 'gpu'} 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)}] ${isCodex ? 'codex' : job.kind} started`);++ const label = isCodex ? 'codex' : job.kind;+ (async () => {+ try {+ await runJob(job);+ } catch (err) {+ // runJob threw before its own terminal handlers ran (e.g. PYTHON+ // not configured). Recover so a single bad job can't freeze its lane.+ console.log(`❌ media-job [${job.id.slice(0, 8)}] ${label} 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 });+ closeJobAfterDelay(sseJobs, job.id);+ mediaJobEvents.emit('failed', job);+ }+ }+ if (isCodex) {+ codexRunning = null;+ } else {+ running = null;+ }+ archive.push(job);+ recomputeQueuePositions();+ persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on ${label} done failed: ${e.message}`));+ })();+}+async function drainLoop() {while (true) {- // Walk the queue in submission order and start the first job in each- // currently-free lane. Lanes run concurrently — a codex render and a- // video render can be in flight at the same time without sharing a- // single global slot. Within a lane, jobs serialize FIFO.- let started = false;- for (let i = 0; i < queue.length; i++) {- const j = queue[i];- const lane = laneForJob(j);- if (running.has(lane)) continue;- const [job] = queue.splice(i, 1);- i--;- job.status = 'running';- job.startedAt = new Date().toISOString();- // The running job is always slot 1 in its lane. Without this, a job- // dequeued from position 2 (queued behind another lane-mate that just- // finished) would keep its old position=2 even while running.- job.position = 1;- running.set(lane, job);- // Recompute positions for everyone still queued AND broadcast the new- // position over SSE so clients listening to /:jobId/events see their- // updated slot instead of staying frozen at the original enqueue-time- // value.- 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 (lane=${lane})`);- // Detach: each lane runs its own job concurrently. runJobInLane wraps- // runJob with the lane cleanup (release the lane, archive, recompute,- // persist) so when this iteration of the drainLoop continues we can- // start the next free-lane job without waiting for the in-flight one.- runJobInLane(job, lane);- started = true;+ // Codex lane: concurrent with GPU lane.+ if (!codexRunning) {+ const nextCodex = queue.find((j) => j.kind === 'image' && j.params?.mode === 'codex');+ if (nextCodex) startLaneJob(nextCodex, { isCodex: true });}- if (!started) await sleep(150);- }-}-async function runJobInLane(job, lane) {- // The worker is a top-level fire-and-forget — if runJob throws unexpectedly- // (an unhandled emitter / listener edge case, etc.), an uncaught error here- // would orphan the lane (running.has(lane) would stay true forever and- // freeze that lane's queue). Catch + recover so a single bad job can't kill- // the lane.- 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 });- closeJobAfterDelay(sseJobs, job.id);- mediaJobEvents.emit('failed', job);+ // GPU lane: serialized — at most one video or local-image job at a time.+ if (!running) {+ const nextGpu = queue.find((j) => !(j.kind === 'image' && j.params?.mode === 'codex'));+ if (nextGpu) startLaneJob(nextGpu, { isCodex: false });}++ await sleep(150);}- running.delete(lane);- archive.push(job);- // Now that the lane is free, every same-lane 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@@ -368,27 +346,28 @@ async function runJobInLane(job, lane) {// 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.-//-// Position is per-lane: a queued GPU job sits behind only the running GPU-// job + other queued GPU jobs, ignoring codex jobs entirely (and vice versa).-// Without this, a writers-room storyboard with 5 codex renders queued behind-// one running video would show position 6, which is misleading — the codex-// jobs have nothing to wait on except each other.function recomputeQueuePositions() {- const counters = new Map();- for (const lane of running.keys()) {- counters.set(lane, 1); // running occupies slot 1 in its lane- }- for (const q of queue) {- const lane = laneForJob(q);- const newPosition = (counters.get(lane) ?? 0) + 1;- counters.set(lane, newPosition);+ const isCodexJob = (j) => j.kind === 'image' && j.params?.mode === 'codex';+ const codexJobs = queue.filter(isCodexJob);+ const gpuJobs = queue.filter((j) => !isCodexJob(j));++ codexJobs.forEach((q, i) => {+ const newPosition = i + 1 + (codexRunning ? 1 : 0);if (q.position !== newPosition) {q.position = newPosition;const entry = sseJobs.get(q.id);if (entry) broadcastSse(entry, { type: 'queued', position: newPosition });}- }+ });++ gpuJobs.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@@ -508,46 +487,29 @@ async function runJob(job) {},};- // Thread #1: sanitize uploadedTempPath(s) before passing params to the gen+ // 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/strip anything- // that doesn't resolve under PATHS.uploads so the constraint holds end-to-end.+ // 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;}- // a2v: audioFilePath is fed straight to the python helper as --audio, so- // a corrupted/hand-edited persisted job that points it at /etc/secrets- // could make the worker open arbitrary local files. Same constraint as- // uploadedTempPath — null it if it doesn't resolve under PATHS.uploads.if (safeParams.audioFilePath && (typeof safeParams.audioFilePath !== 'string' || !isUnderUploadsRoot(safeParams.audioFilePath))) {console.log(`⚠️ media-job [${job.id.slice(0, 8)}] audioFilePath outside PATHS.uploads — nulled before gen invoke: ${safeParams.audioFilePath}`);safeParams.audioFilePath = null;}- if (Array.isArray(safeParams.uploadedTempPaths)) {- const filtered = safeParams.uploadedTempPaths.filter((p) => {- if (typeof p === 'string' && isUnderUploadsRoot(p)) return true;- console.log(`⚠️ media-job [${job.id.slice(0, 8)}] uploadedTempPaths entry outside PATHS.uploads — dropped before gen invoke: ${p}`);- return false;- });- safeParams.uploadedTempPaths = filtered;- } else if (typeof safeParams.uploadedTempPaths === 'string') {- // Persisted as a string (corrupted JSON or older shape) — normalize to a- // single-entry array if the path is safe so generateVideo's cleanup loop- // still unlinks it on completion. Drop otherwise.- if (isUnderUploadsRoot(safeParams.uploadedTempPaths)) {- safeParams.uploadedTempPaths = [safeParams.uploadedTempPaths];- } else {- console.log(`⚠️ media-job [${job.id.slice(0, 8)}] uploadedTempPaths string outside PATHS.uploads — dropped before gen invoke: ${safeParams.uploadedTempPaths}`);- safeParams.uploadedTempPaths = [];- }- } else if (safeParams.uploadedTempPaths != null) {- // Any other non-array, non-string value — drop it rather than feed a- // non-iterable into the worker's cleanup loop.- safeParams.uploadedTempPaths = [];- }+ safeParams.uploadedTempPaths = normalizeTempPaths(safeParams.uploadedTempPaths).filter((p) => {+ if (isUnderUploadsRoot(p)) return true;+ console.log(`⚠️ media-job [${job.id.slice(0, 8)}] uploadedTempPaths entry outside PATHS.uploads — rejected before gen invoke: ${p}`);+ return false;+ });+ // Clamp chunks to the same 1-8 bound the route enforces on new submissions.+ // Replayed jobs read params from media-jobs.json which could be hand-edited+ // to an out-of-range value, bypassing the route-layer Zod validation.+ safeParams.chunks = Math.min(8, Math.max(1, Math.trunc(Number(safeParams.chunks) || 1)));const emitter = job.kind === 'video' ? videoGenEvents : imageGenEvents;const dispatcher = makeGenDispatcher(emitter, job, handlers);@@ -562,13 +524,8 @@ async function runJob(job) {// `watchdogMs(envValue, defaultMs)` helper that parses the env-var// overrides. Both lived as `watchdogMs` previously and made the call// site easy to misread.- // Multi-chunk video chains run N renders end-to-end, so the wall time- // scales linearly with chunks. Without this the watchdog would SIGTERM- // the chain mid-stream on a healthy 4-chunk render. Route-side Zod has- // already validated chunks ∈ 1..8.- const chunks = Number(job.params?.chunks) || 1;const watchdogTimeoutMs = job.kind === 'video'- ? WATCHDOG_VIDEO_MS * chunks+ ? WATCHDOG_VIDEO_MS * Math.max(1, Number(safeParams.chunks) || 1): WATCHDOG_IMAGE_MS;watchdogTimer = setTimeout(async () => {// Two-stage status guard: first check stops us if the gen settled@@ -579,7 +536,7 @@ async function runJob(job) {// current activeProcess; once handlers.failed marks this job// terminal, runJob's await exits and the worker advances).if (job.status !== 'running') return;- const mod = await importGenModuleForJob(job);+ const mod = await getGenModuleForJob(job);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@@ -592,30 +549,26 @@ async function runJob(job) {watchdogTimer.unref?.();try {- if (job.kind === 'video') {- // Route to the chain orchestrator when chunks > 1. The chain function- // delegates to generateVideo for chunks=1, so we could always call it,- // but keeping the chunks=1 path on plain generateVideo means the simple- // case never carries chain bookkeeping or the activeChain global.- const wantsChain = Number(safeParams.chunks) > 1;- const mod = await import('../videoGen/local.js');- const fn = wantsChain ? mod.generateChainedVideo : mod.generateVideo;- await fn({ ...safeParams, jobId: job.id });- } else if (job.kind === 'image') {- const { generateImage } = isCodexJob(job)- ? await import('../imageGen/codex.js')- : await import('../imageGen/local.js');- await generateImage({ ...safeParams, jobId: job.id });+ const mod = await getGenModuleForJob(job);+ if (!mod) throw new Error(`Unknown job kind: ${job.kind}`);+ if (job.kind === 'video' && safeParams.chunks > 1) {+ await mod.generateChainedVideo({ ...safeParams, jobId: job.id });+ } else if (job.kind === 'video') {+ await mod.generateVideo({ ...safeParams, jobId: job.id });} else {- throw new Error(`Unknown job kind: ${job.kind}`);+ await mod.generateImage({ ...safeParams, jobId: job.id });}} catch (err) {- // generateVideo / generateImage threw before reaching their proc.on- // cleanup hooks (e.g. PYTHON not configured, validation fail). Clean up- // every multipart upload temp file the route handed us so they don't- // leak under data/uploads. safeUnlinkAllUploads constrains each delete- // to PATHS.uploads as defense-in-depth against corrupted persisted params.- await safeUnlinkAllUploads(job.params);+ // generateVideo / generateChainedVideo / 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);+ for (const p of normalizeTempPaths(job.params?.uploadedTempPaths)) {+ await safeUnlinkUpload(p);+ }handlers.failed({ error: err.message });}@@ -632,12 +585,6 @@ export function enqueueJob({ kind, params, owner = null }) {throw new Error(`enqueueJob: invalid kind '${kind}'`);}const id = randomUUID();- const probe = { kind, params };- const lane = laneForJob(probe);- // Per-lane position: running same-lane job (if any) occupies slot 1, then- // queued same-lane jobs follow. Cross-lane jobs don't add to this count.- const sameLaneQueued = queue.filter((j) => laneForJob(j) === lane).length;- const position = sameLaneQueued + (running.has(lane) ? 1 : 0) + 1;const job = {id,kind,@@ -645,7 +592,14 @@ export function enqueueJob({ kind, params, owner = null }) {status: 'queued',queuedAt: new Date().toISOString(),params,- position,+ // position counts "where you sit in your lane" — a running job in the+ // same lane occupies slot 1, then same-lane queued jobs follow. Codex+ // jobs only count Codex ahead-of-them; GPU jobs only count GPU jobs.+ position: (() => {+ const isCodex = kind === 'image' && params?.mode === 'codex';+ const laneQueue = queue.filter((j) => (j.kind === 'image' && j.params?.mode === 'codex') === isCodex);+ return laneQueue.length + (isCodex ? (codexRunning ? 1 : 0) : (running ? 1 : 0)) + 1;+ })(),};queue.push(job);const sseEntry = ensureSseEntry(id);@@ -662,12 +616,15 @@ 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 — start frame,- // end frame, or both) are staged under PATHS.uploads. If we drop the- // job before it starts, runJob never gets a chance to delete them —- // clean up here so the uploads dir doesn't accumulate. Each delete is- // constrained to PATHS.uploads.- await safeUnlinkAllUploads(job.params);+ // 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);+ for (const p of normalizeTempPaths(job.params?.uploadedTempPaths)) {+ await safeUnlinkUpload(p);+ }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@@ -692,15 +649,16 @@ export async function cancelJob(jobId) {console.log(`🛑 media-job [${jobId.slice(0, 8)}] canceled (was queued)`);return { ok: true, status: 'canceled' };}- for (const r of running.values()) {- if (r.id !== jobId) continue;+ // Check both the GPU slot and the Codex slot for a running-cancel.+ const runningJob = (running?.id === jobId ? running : null) ?? (codexRunning?.id === jobId ? codexRunning : null);+ if (runningJob) {// 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.- r.cancelRequested = true;- const mod = await importGenModuleForJob(r);- mod?.cancel?.();+ runningJob.cancelRequested = true;+ const mod = await getGenModuleForJob(runningJob);+ if (mod?.cancel) mod.cancel();console.log(`🛑 media-job [${jobId.slice(0, 8)}] cancel signal sent (was running)`);return { ok: true, status: 'canceling' };}@@ -775,7 +733,8 @@ function sleep(ms) {// Test-only reset hook. Real callers go through enqueueJob/cancelJob.export function __resetForTests() {queue.length = 0;- running.clear();+ running = null;+ codexRunning = null;archive.length = 0;sseJobs.clear();workerStarted = false;diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex 67eb743680..6e2383b3cc 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -29,15 +29,17 @@ vi.mock('../../lib/fileUtils.js', async () => {// directly from each test.const stubs = {generateVideo: vi.fn(async () => ({ jobId: 'whatever' })),+ generateChainedVideo: vi.fn(async () => ({ jobId: 'whatever' })),generateImage: vi.fn(async () => ({ jobId: 'whatever' })),- generateCodexImage: vi.fn(async () => ({ jobId: 'whatever' })),+ generateImageCodex: vi.fn(async () => ({ jobId: 'whatever' })),cancelVideo: vi.fn(),cancelImage: vi.fn(),- cancelCodexImage: vi.fn(),+ cancelImageCodex: vi.fn(),};vi.mock('../videoGen/local.js', () => ({generateVideo: (...args) => stubs.generateVideo(...args),+ generateChainedVideo: (...args) => stubs.generateChainedVideo(...args),cancel: (...args) => stubs.cancelVideo(...args),}));@@ -47,8 +49,8 @@ vi.mock('../imageGen/local.js', () => ({}));vi.mock('../imageGen/codex.js', () => ({- generateImage: (...args) => stubs.generateCodexImage(...args),- cancel: (...args) => stubs.cancelCodexImage(...args),+ generateImage: (...args) => stubs.generateImageCodex(...args),+ cancel: (...args) => stubs.cancelImageCodex(...args),}));// Import the queue + the gen-event emitters AFTER the mocks above are@@ -70,10 +72,14 @@ const flush = () => new Promise((r) => setTimeout(r, 250));beforeEach(async () => {tempDataDir = mkdtempSync(join(tmpdir(), 'mediaJobQueue-test-'));Object.values(stubs).forEach((fn) => fn.mockReset());+ // Default codex stub: hang (matches video/local defaults so tests that+ // don't care about codex don't accidentally complete too fast).+ stubs.generateImageCodex.mockImplementation(() => new Promise(() => {}));await importFresh();});-afterEach(() => {+afterEach(async () => {+ await flush();if (tempDataDir && existsSync(tempDataDir)) {rmSync(tempDataDir, { recursive: true, force: true });}@@ -255,23 +261,6 @@ describe('mediaJobQueue', () => {await waitFor(() => mediaJobQueue.getJob(job.jobId).status === 'completed');});- it('pre-gen sanitizer nulls audioFilePath that resolves outside PATHS.uploads', async () => {- // a2v: audioFilePath flows directly into the python helper as --audio.- // A hand-edited persisted job pointing it at /etc/secrets would otherwise- // make the worker open arbitrary local files; the same uploads-root- // guard applied to uploadedTempPath must apply here too.- const job = mediaJobQueue.enqueueJob({- kind: 'video',- params: { prompt: 'beats', mode: 'a2v', audioFilePath: '/etc/passwd' },- });- await waitFor(() => stubs.generateVideo.mock.calls.length === 1);- const callArgs = stubs.generateVideo.mock.calls[0][0];- expect(callArgs.audioFilePath).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.@@ -422,106 +411,193 @@ describe('mediaJobQueue', () => {await waitFor(() => mediaJobQueue.getJob(jobId)?.status === 'completed');});- // Lane separation: codex image jobs run on their own lane so they- // don't sit behind GPU-bound video / local-image renders. Without this,- // the writers-room storyboard's burst of codex calls would be serialized- // behind whatever GPU work is in flight, defeating the point of routing- // them through the queue.- it('codex image jobs run concurrently with GPU jobs (separate lane)', async () => {- // Pin video on the GPU lane forever so any cross-lane blocking would- // strand the codex job.- stubs.generateVideo.mockImplementation(() => new Promise(() => {}));- stubs.generateCodexImage.mockImplementation(() => new Promise(() => {}));+ 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;+ });+});- mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'gpu-job' } });- mediaJobQueue.enqueueJob({+describe('Codex lane', () => {+ it('dispatches a Codex job to imageGen/codex.js#generateImage, not local', async () => {+ // Allow the codex job to resolve immediately so the worker can settle.+ stubs.generateImageCodex.mockResolvedValue({ jobId: 'whatever' });++ const job = mediaJobQueue.enqueueJob({kind: 'image',- params: { mode: 'codex', prompt: 'codex-job' },+ params: { prompt: 'codex test', mode: 'codex' },});+ await waitFor(() => stubs.generateImageCodex.mock.calls.length === 1);++ expect(stubs.generateImageCodex).toHaveBeenCalledWith(+ expect.objectContaining({ jobId: job.jobId, prompt: 'codex test', mode: 'codex' }),+ );+ // The GPU local image gen must NOT have been called.+ expect(stubs.generateImage).not.toHaveBeenCalled();- // Both gen modules should have been invoked — one on each lane —- // despite the video stub never resolving.- await waitFor(() => stubs.generateVideo.mock.calls.length === 1- && stubs.generateCodexImage.mock.calls.length === 1);- expect(mediaJobQueue.listJobs({ status: 'running' })).toHaveLength(2);+ imageGenEvents.emit('completed', { generationId: job.jobId, filename: `${job.jobId}.png` });+ await waitFor(() => mediaJobQueue.getJob(job.jobId).status === 'completed');});- // Multiple codex jobs in a row queue against EACH OTHER (single codex- // lane) so codex.activeProcess never gets clobbered. This is the case- // that previously surfaced 409 IMAGE_GEN_BUSY.- it('back-to-back codex image jobs serialize on the codex lane', async () => {- stubs.generateCodexImage.mockImplementation(() => new Promise(() => {}));- const first = mediaJobQueue.enqueueJob({+ it('Codex job and a GPU video job run concurrently — both dispatch functions are called', async () => {+ // Both stubs hang indefinitely so neither completes before we assert.+ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));+ stubs.generateImageCodex.mockImplementation(() => new Promise(() => {}));++ const videoJob = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'video' } });+ const codexJob = mediaJobQueue.enqueueJob({kind: 'image',- params: { mode: 'codex', prompt: 'first' },+ params: { prompt: 'codex concurrent', mode: 'codex' },});- const second = mediaJobQueue.enqueueJob({++ // Both dispatch functions should be called without either blocking the other.+ await waitFor(+ () => stubs.generateVideo.mock.calls.length === 1 && stubs.generateImageCodex.mock.calls.length === 1,+ );++ expect(stubs.generateVideo).toHaveBeenCalledWith(expect.objectContaining({ jobId: videoJob.jobId }));+ expect(stubs.generateImageCodex).toHaveBeenCalledWith(expect.objectContaining({ jobId: codexJob.jobId }));++ // Clean up: emit failures so the worker can settle.+ videoGenEvents.emit('failed', { generationId: videoJob.jobId, error: 'cleanup' });+ imageGenEvents.emit('failed', { generationId: codexJob.jobId, error: 'cleanup' });+ await waitFor(+ () =>+ mediaJobQueue.getJob(videoJob.jobId).status !== 'running' &&+ mediaJobQueue.getJob(codexJob.jobId).status !== 'running',+ );+ });++ it('queued Codex job reports position within the Codex lane (not counting GPU jobs)', async () => {+ // GPU job hangs so the GPU slot is occupied but separate from the Codex lane.+ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));+ // First Codex job hangs so a second Codex job lands in the queue.+ stubs.generateImageCodex.mockImplementation(() => new Promise(() => {}));++ // Enqueue one GPU video job (occupies the GPU lane, should not affect Codex positions).+ const videoJob = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'video blocker' } });++ // First Codex job: worker picks it up immediately (codexRunning slot).+ const codex1 = mediaJobQueue.enqueueJob({kind: 'image',- params: { mode: 'codex', prompt: 'second' },+ params: { prompt: 'codex first', mode: 'codex' },});- await waitFor(() => stubs.generateCodexImage.mock.calls.length === 1);- // First is running on the codex lane; second sits queued behind it.- expect(mediaJobQueue.getJob(first.jobId).status).toBe('running');- expect(mediaJobQueue.getJob(second.jobId).status).toBe('queued');- // Same-lane position counts only same-lane jobs — the codex queue's- // second slot is "behind one running codex job", regardless of any- // GPU jobs in flight.- expect(mediaJobQueue.getJob(second.jobId).position).toBe(2);- });+ // Wait until the first Codex job is actually running so codexRunning is set.+ await waitFor(() => stubs.generateImageCodex.mock.calls.length === 1);- // The runJob dispatcher routes by params.mode — codex image jobs hit the- // codex provider, not the local one. Without this dispatch, the queue- // would call mflux for a codex job and silently break the storyboard.- it('runJob dispatches codex image jobs to the codex provider', async () => {- stubs.generateCodexImage.mockImplementation(() => new Promise(() => {}));- mediaJobQueue.enqueueJob({+ // Second Codex job: lands in queue behind the running Codex job (position 2 in Codex lane).+ const codex2 = mediaJobQueue.enqueueJob({kind: 'image',- params: { mode: 'codex', codexPath: '/usr/local/bin/codex', prompt: 'a fox' },+ params: { prompt: 'codex second', mode: 'codex' },});- await waitFor(() => stubs.generateCodexImage.mock.calls.length === 1);- expect(stubs.generateImage).not.toHaveBeenCalled();- const callArgs = stubs.generateCodexImage.mock.calls[0][0];- expect(callArgs.codexPath).toBe('/usr/local/bin/codex');- expect(callArgs.prompt).toBe('a fox');- expect(callArgs.jobId).toMatch(/^[0-9a-f-]{36}$/);+ // The second Codex job's position should be 2 (1 running Codex + 1 queue slot),+ // not inflated by the GPU video job also being in flight.+ expect(codex2.position).toBe(2);+ expect(mediaJobQueue.getJob(codex2.jobId).position).toBe(2);++ // Clean up.+ videoGenEvents.emit('failed', { generationId: videoJob.jobId, error: 'cleanup' });+ imageGenEvents.emit('failed', { generationId: codex1.jobId, error: 'cleanup' });+ imageGenEvents.emit('failed', { generationId: codex2.jobId, error: 'cleanup' });+ await flush();});+});- // Cancel of a running codex job must SIGTERM the codex provider, not- // the local one. Without per-job dispatch in cancelJob, cancelImage- // would be called against the wrong provider and the codex child- // would orphan.- it('cancelJob targets the codex provider for running codex jobs', async () => {- stubs.generateCodexImage.mockImplementation(() => new Promise(() => {}));+describe('audioFilePath sanitization', () => {+ it('pre-gen sanitizer nulls audioFilePath that resolves outside PATHS.uploads', async () => {+ // audioFilePath must be treated identically to uploadedTempPath: if it+ // doesn't resolve under PATHS.uploads, the gen module must never see it.const job = mediaJobQueue.enqueueJob({- kind: 'image',- params: { mode: 'codex', prompt: 'cancel-me' },+ kind: 'video',+ params: { prompt: 'x', audioFilePath: '/etc/shadow' },});- await waitFor(() => stubs.generateCodexImage.mock.calls.length === 1);+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);+ const callArgs = stubs.generateVideo.mock.calls[0][0];+ expect(callArgs.audioFilePath).toBeNull();- await mediaJobQueue.cancelJob(job.jobId);- expect(stubs.cancelCodexImage).toHaveBeenCalled();- expect(stubs.cancelImage).not.toHaveBeenCalled();+ videoGenEvents.emit('completed', { generationId: job.jobId, filename: `${job.jobId}.mp4` });+ await waitFor(() => mediaJobQueue.getJob(job.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+describe('chunks dispatch', () => {+ it('video job with chunks > 1 calls generateChainedVideo instead of generateVideo', async () => {+ const job = mediaJobQueue.enqueueJob({+ kind: 'video',+ params: { prompt: 'chained', chunks: 3 },+ });+ await waitFor(() => stubs.generateChainedVideo.mock.calls.length === 1);- const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'guard' } });+ expect(stubs.generateChainedVideo).toHaveBeenCalledWith(+ expect.objectContaining({ jobId: job.jobId, prompt: 'chained', chunks: 3 }),+ );+ // The single-chunk path must NOT have been called.+ expect(stubs.generateVideo).not.toHaveBeenCalled();++ videoGenEvents.emit('completed', { generationId: job.jobId, filename: `${job.jobId}.mp4` });+ await waitFor(() => mediaJobQueue.getJob(job.jobId).status === 'completed');+ });++ it('video job with chunks === 1 calls generateVideo (not generateChainedVideo)', async () => {+ const job = mediaJobQueue.enqueueJob({+ kind: 'video',+ params: { prompt: 'single', chunks: 1 },+ });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');+ expect(stubs.generateVideo).toHaveBeenCalledWith(+ expect.objectContaining({ jobId: job.jobId, prompt: 'single', chunks: 1 }),+ );+ expect(stubs.generateChainedVideo).not.toHaveBeenCalled();- delete process.env.MEDIA_JOB_WATCHDOG_VIDEO_MS;+ videoGenEvents.emit('completed', { generationId: job.jobId, filename: `${job.jobId}.mp4` });+ await waitFor(() => mediaJobQueue.getJob(job.jobId).status === 'completed');+ });+});++describe('cancelJob running-Codex branch', () => {+ it('canceling a running Codex job calls imageGen/codex.js#cancel, not the local cancel', async () => {+ // Codex job hangs indefinitely so it stays in 'running' for the cancel.+ stubs.generateImageCodex.mockImplementation(() => new Promise(() => {}));++ const job = mediaJobQueue.enqueueJob({+ kind: 'image',+ params: { prompt: 'codex running cancel', mode: 'codex' },+ });++ // Wait until the Codex job is actually running (worker picked it up).+ await waitFor(() => stubs.generateImageCodex.mock.calls.length === 1);+ expect(mediaJobQueue.getJob(job.jobId).status).toBe('running');++ const result = await mediaJobQueue.cancelJob(job.jobId);+ expect(result.ok).toBe(true);+ expect(result.status).toBe('canceling');++ // Codex cancel must have fired.+ expect(stubs.cancelImageCodex).toHaveBeenCalled();+ // The GPU/local image cancel must NOT have fired.+ expect(stubs.cancelImage).not.toHaveBeenCalled();+ expect(stubs.cancelVideo).not.toHaveBeenCalled();++ // Simulate the codex gen acknowledging the cancel with a failure event+ // so the worker settles cleanly.+ imageGenEvents.emit('failed', { generationId: job.jobId, error: 'canceled' });+ await waitFor(() => mediaJobQueue.getJob(job.jobId).status !== 'running');});});diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex 3f63f03c1c..464e74b594 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -22,7 +22,7 @@ import { ServerError } from '../../lib/errorHandler.js';import { videoGenEvents } from './events.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';import { getVideoModels, getDefaultVideoModelId, getTextEncoderRepo } from '../../lib/mediaModels.js';-import { findFfmpeg, safeUnder, generateThumbnail, optimizeForStreaming, upscaleVideo2x } from '../../lib/ffmpeg.js';+import { findFfmpeg, safeUnder, generateThumbnail, optimizeForStreaming, upscaleVideo2x, extractEvaluationFrames } from '../../lib/ffmpeg.js';// Path to the dgrauet/ltx-2-mlx venv populated by `INSTALL_LTX2=1// scripts/setup-image-video.sh`. Used when a model entry has@@ -263,6 +263,7 @@ const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width,};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, uploadedTempPaths = [], lastImagePath = null, extendFromVideoPath = null, audioFilePath = null, mode = null, imageStrength = null, jobId: providedJobId = null }) {+ uploadedTempPaths = Array.isArray(uploadedTempPaths) ? uploadedTempPaths : [];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' });// Single-flight is now enforced by the mediaJobQueue worker upstream — only@@ -756,6 +757,19 @@ export async function extractLastFrame(historyId) {});}+// Sample N evenly-spaced frames from a video for multi-frame LLM evaluation.+// Thin wrapper around the canonical lib/ffmpeg.js helper `extractEvaluationFrames`+// that derives the video path from the jobId so call-sites don't need to know+// the storage layout. Returns [] on any failure — callers fall back to the+// single-thumbnail prompt path.+export async function sampleEvaluationFrames(jobId, count = 5) {+ const videoPath = join(PATHS.videos, `${jobId}.mp4`);+ if (!existsSync(videoPath)) return [];+ const filenames = await extractEvaluationFrames(videoPath, jobId, count);+ if (filenames.length) console.log(`🎞️ CD sampled ${filenames.length} evaluation frames for ${jobId.slice(0, 8)}`);+ return filenames;+}+// Concat selected videos (preserving order) into a single MP4. Uses ffmpeg's// concat demuxer which is stream-copy, so it's fast and lossless — but the// inputs must share codec/resolution. The Media History page already only@@ -926,6 +940,13 @@ export async function deleteHistoryItem(id) {const thumbFile = safeUnder(PATHS.videoThumbnails, item.thumbnail);if (thumbFile) await unlink(thumbFile).catch(() => {});}+ // Delete evaluation frame thumbnails written by sampleEvaluationFrames:+ // `${jobId}-f1.jpg` … `${jobId}-f9.jpg` (max count in sampleEvaluationFrames is 5,+ // but 9 is a safe upper bound to catch any future increase).+ for (let i = 1; i <= 9; i++) {+ const frameFile = safeUnder(PATHS.videoThumbnails, `${id}-f${i}.jpg`);+ if (frameFile) await unlink(frameFile).catch(() => {});+ }await saveHistory(history.filter((h) => h.id !== id));console.log(`🗑️ Deleted video: ${item.filename}`);return { ok: true };