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: video render chains + codex lane queue separation
Adam Eivyaa0e3b4e28dc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 20e02d6a02..6539fe1a8d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,13 @@# Unreleased Changes+## Fixed++- 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.++## 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.+## Changed- Release workflow no longer silently skips creating the GitHub Release when something else pushed the version tag before the workflow ran.diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex 3ba9df7b32..a0c9406dbc 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -109,6 +109,7 @@ export default function VideoGen() {const [height, setHeight] = useState(512);const [numFrames, setNumFrames] = useState(121);const [fps, setFps] = useState(24);+ const [chunks, setChunks] = useState(1);const [steps, setSteps] = useState('');const [guidanceScale, setGuidanceScale] = useState('');const [seed, setSeed] = useState('');@@ -384,6 +385,7 @@ export default function VideoGen() {sourceImageFile: (mode === 'image' || mode === 'fflf' || mode === 'extend') ? (sourceImageFile || '') : '',sourceImage: (mode === 'image' || mode === 'fflf') ? (sourceImageUpload || '') : '',lastImageFile: mode === 'fflf' ? (lastImageFile || '') : '',+ chunks: chunks > 1 ? chunks : '',};};@@ -838,6 +840,23 @@ export default function VideoGen() {</select></div>+ <div>+ <label className="block text-xs font-medium text-gray-400 mb-1" title="Chain N renders end-to-end. Each chunk's last frame seeds the next, then they're stitched into one clip. Wall time scales linearly with chunks.">+ Chunks+ </label>+ <select+ value={chunks}+ onChange={(e) => setChunks(Number(e.target.value))}+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"+ >+ {[1, 2, 3, 4, 5, 6, 7, 8].map((n) => (+ <option key={n} value={n}>+ {n === 1 ? '1 (single)' : `${n} (~${((n * numFrames) / fps).toFixed(0)}s total)`}+ </option>+ ))}+ </select>+ </div>+<div><label className="block text-xs font-medium text-gray-400 mb-1">FPS</label><selectdiff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 4bc430b219..b9885ee0e2 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -110,6 +110,20 @@ router.get('/active', asyncHandler(async (_req, res) => {res.json({ activeJob: await imageGen.getActiveJob() });}));+// Shape returned for any image-gen job that goes through the mediaJobQueue+// (local + codex). Kept in one place so the two enqueue branches below stay+// in sync — the client's polling/SSE hooks key off these fields.+const queuedImageResponse = ({ jobId, position, status, mode, model }) => ({+ jobId,+ generationId: jobId,+ filename: `${jobId}.png`,+ path: `/data/images/${jobId}.png`,+ mode,+ model,+ status,+ position,+});+router.post('/generate', initImageUpload, asyncHandler(async (req, res) => {const data = validateRequest(generateSchema, coerceFormFields(req.body));// Resolve init image source: uploaded file > gallery filename. The local@@ -146,12 +160,36 @@ router.post('/generate', initImageUpload, asyncHandler(async (req, res) => {if (uploadedInitTempPath) {res.on('close', () => { unlink(uploadedInitTempPath).catch(() => {}); });}- // Mode resolution: explicit per-request override > settings default. Only- // local-mode goes through the mediaJobQueue (it's the GPU-bound backend that- // used to throw BUSY). External and Codex backends remain synchronous —- // they don't share Metal/MLX resources so no queue is needed.+ // Local + codex both go through mediaJobQueue (separate lanes — codex+ // doesn't share MLX). External SD-API stays synchronous: it's a remote+ // call with no local single-flight constraint to absorb.const settings = await getSettings();const mode = data.mode || settings.imageGen?.mode || 'external';+ if (mode === 'codex') {+ // Reject up-front rather than enqueueing a doomed job — codex is gated+ // behind an explicit toggle since not every Codex account has access to+ // the image_gen tool.+ const c = settings.imageGen?.codex || {};+ if (!c.enabled) {+ throw new ServerError(+ 'Codex Imagegen is disabled — enable it in Settings → Image Gen first',+ { status: 400, code: 'CODEX_IMAGEGEN_DISABLED' },+ );+ }+ const queued = enqueueJob({+ kind: 'image',+ // `mode: 'codex'` is the queue's discriminator — laneForJob() routes+ // codex jobs to the codex lane, and runJob's image branch dispatches+ // to imageGen/codex.js when it sees this flag.+ params: {+ mode: 'codex',+ codexPath: c.codexPath,+ model: c.model,+ ...data,+ },+ });+ return res.json(queuedImageResponse({ ...queued, mode: 'codex', model: c.model || null }));+ }if (mode === 'local') {const py = settings.imageGen?.local?.pythonPath || null;// Pre-validate config: mflux models need pythonPath, FLUX.2 doesn't@@ -176,25 +214,18 @@ router.post('/generate', initImageUpload, asyncHandler(async (req, res) => {{ status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' },);}- const { jobId, position, status } = enqueueJob({+ const queued = enqueueJob({kind: 'image',params: { pythonPath: py, ...data },});- // Surface the effective model so the response matches the- // non-queued path's `model` field. Use the same `selectedModel`- // resolution as the validation block above so the response reflects- // the actual fallback chain (caller modelId → 'dev' → allModels[0])- // rather than just the requested id.- return res.json({- jobId,- generationId: jobId,- filename: `${jobId}.png`,- path: `/data/images/${jobId}.png`,+ // Resolve the effective model the same way the validation block above+ // does so the response reflects the actual fallback chain (caller+ // modelId → 'dev' → allModels[0]) rather than just the requested id.+ return res.json(queuedImageResponse({+ ...queued,mode: 'local',model: selectedModel?.id || data.modelId || 'dev',- status,- position,- });+ }));}res.json(await imageGen.generateImage(data));}));diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex 35ed40f012..4abdc5f757 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -199,6 +199,78 @@ describe('Image Gen Routes', () => {expect(response.body.error).toMatch(/not configured/i);expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();});++ // Codex mode now goes through the mediaJobQueue (codex lane), so a+ // burst of writers-room storyboard renders queues against itself+ // instead of failing the second-and-onwards calls with 409+ // IMAGE_GEN_BUSY.+ it('codex mode enqueues through mediaJobQueue and returns queued status', async () => {+ getSettings.mockResolvedValueOnce({+ imageGen: { mode: 'codex', codex: { enabled: true, codexPath: '/usr/local/bin/codex', model: 'gpt-5.4' } },+ });+ mediaJobQueue.enqueueJob.mockReturnValueOnce({ jobId: 'queued-codex-001', position: 1, status: 'queued' });++ const response = await request(app)+ .post('/api/image-gen/generate')+ .send({ prompt: 'a tavern at dusk' });++ expect(response.status).toBe(200);+ expect(response.body.status).toBe('queued');+ expect(response.body.mode).toBe('codex');+ expect(response.body.model).toBe('gpt-5.4');+ expect(response.body.jobId).toBe('queued-codex-001');+ expect(response.body.path).toBe('/data/images/queued-codex-001.png');+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'image',+ params: expect.objectContaining({+ mode: 'codex',+ codexPath: '/usr/local/bin/codex',+ model: 'gpt-5.4',+ prompt: 'a tavern at dusk',+ }),+ }));+ // Synchronous generateImage MUST NOT be called in codex mode either —+ // the queue takes ownership.+ expect(imageGen.generateImage).not.toHaveBeenCalled();+ });++ // Per-request codex override: even when the saved default is external,+ // an explicit `mode: 'codex'` on the payload (e.g. the writers-room+ // storyboard chip strip) flips into queue mode so renders serialize.+ it('per-request mode=codex override enqueues even when settings default is external', async () => {+ getSettings.mockResolvedValueOnce({+ imageGen: { mode: 'external', codex: { enabled: true, model: 'gpt-5.4' } },+ });+ mediaJobQueue.enqueueJob.mockReturnValueOnce({ jobId: 'queued-codex-002', position: 2, status: 'queued' });++ const response = await request(app)+ .post('/api/image-gen/generate')+ .send({ prompt: 'a wizard tower', mode: 'codex' });++ expect(response.status).toBe(200);+ expect(response.body.status).toBe('queued');+ expect(response.body.mode).toBe('codex');+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'image',+ params: expect.objectContaining({ mode: 'codex' }),+ }));+ expect(imageGen.generateImage).not.toHaveBeenCalled();+ });++ // Codex with the toggle off rejects up-front rather than enqueueing.+ it('codex mode with disabled toggle returns 400 CODEX_IMAGEGEN_DISABLED', async () => {+ getSettings.mockResolvedValueOnce({+ imageGen: { mode: 'codex', codex: { enabled: false } },+ });++ const response = await request(app)+ .post('/api/image-gen/generate')+ .send({ prompt: 'a fox' });++ expect(response.status).toBe(400);+ expect(response.body.error).toMatch(/disabled/i);+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();+ });});describe('POST /api/image-gen/avatar', () => {diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex ed0548e427..c9565ce86a 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -71,6 +71,10 @@ const generateBodySchema = z.object({// UI mode hint — backend only uses it for logging/branching; absence// falls back to inferring (sourceImage→i2v, no source→t2v).mode: z.enum(['text', 'image', 'fflf', 'extend']).optional(),+ // Chain N renders end-to-end: each chunk's last frame becomes the next+ // chunk's start frame, then ffmpeg concats them into one clip. 1..8 to+ // keep the worst-case wall time bounded (8 × ~5min ≈ 40min on M3 Max).+ chunks: optionalNum(1, 8, 'chunks'),});router.get('/status', asyncHandler(async (_req, res) => {@@ -212,6 +216,7 @@ router.post('/', sourceImageUpload, asyncHandler(async (req, res) => {lastImagePath,mode: body.mode,imageStrength: body.imageStrength,+ chunks: body.chunks ?? 1,},});// Match the legacy response shape (jobId, generationId, filename, model,diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex f67ed6ad32..72b552a63a 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -153,6 +153,38 @@ describe('videoGen routes', () => {}));});+ it('forwards chunks > 1 so the queue dispatches the chain orchestrator', async () => {+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'a long shot',+ chunks: 4,+ });+ expect(r.status).toBe(200);+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'video',+ params: expect.objectContaining({ chunks: 4 }),+ }));+ });++ it('coerces chunks=1 (and missing) to 1 — the non-chained path', async () => {+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'a single render',+ });+ expect(r.status).toBe(200);+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'video',+ params: expect.objectContaining({ chunks: 1 }),+ }));+ });++ it('rejects chunks above the 1..8 cap', async () => {+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'too long',+ chunks: 99,+ });+ expect(r.status).toBe(400);+ expect(r.body.error).toMatch(/chunks/i);+ });+it('rejects an unknown mode value', async () => {const r = await request(app).post('/api/video-gen/').send({prompt: 'a cat',diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.jsindex 4d74994f8e..3e902fae73 100644--- a/server/services/imageGen/codex.js+++ b/server/services/imageGen/codex.js@@ -83,17 +83,22 @@ export async function checkConnection({ codexPath } = {}) {const SESSION_ID_RE = /^session id:\s*([0-9a-f-]{36})/im;-export async function generateImage({ codexPath, model, prompt, width, height, negativePrompt }) {+export async function generateImage({ codexPath, model, prompt, width, height, negativePrompt, jobId: providedJobId = null }) {if (!prompt?.trim()) {throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });}+ // The mediaJobQueue serializes codex jobs in their own lane and passes+ // its job id in via `providedJobId`, so concurrent queued calls never reach+ // here while activeProcess is set. The 409 below is defense-in-depth for+ // legacy direct callers (voice tool, avatar route) that still bypass the+ // queue.if (activeProcess) {throw new ServerError('A Codex generation is already in progress — cancel it before starting another', { status: 409, code: 'IMAGE_GEN_BUSY' });}await ensureDir(PATHS.images);- const jobId = randomUUID();+ const jobId = providedJobId || randomUUID();const filename = `${jobId}.png`;const outputPath = join(PATHS.images, filename);diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex b336c55ad7..7003e0789f 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -1,17 +1,27 @@/**- * Media Job Queue — single-worker FIFO for image + video gen jobs.+ * Media Job Queue — lane-aware FIFO for image + video gen jobs.** Why this exists: video gen (mlx_video) and image gen (mflux/diffusers) both* spawn heavy GPU/Metal child processes. Running two simultaneously OOMs the* machine, so the gen modules used to throw 409 BUSY when one was already in- * flight. That made any agent-driven pipeline (e.g. Creative Director) need- * to retry/backoff. This queue serializes submissions so callers always get- * an immediate `queued` ack and watch progress via SSE.+ * 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.*- * Scope: gates `videoGen/local#generateVideo` (always) and- * `imageGen/local#generateImage` (only when imageGen mode === 'local'). The- * external/codex image-gen backends bypass the queue — they don't share the- * MLX runtime so they can run concurrently with anything in the queue.+ * 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.+ *+ * 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.** Persistence: data/media-jobs.json holds queued + running + recently-finished* jobs. On boot, any 'running' is reclassified as 'failed (interrupted by@@ -75,13 +85,53 @@ export const JOB_STATUSES = Object.freeze(['queued', 'running', 'completed', 'faexport const mediaJobEvents = new EventEmitter();-// Live state. Single worker → at most one job in `running` at a time. `queue`-// holds pending jobs in submission order. `archive` holds recently-finished-// jobs (visible for ~24h via /api/media-jobs?status=completed).+// 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) {+ 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;+}++// 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).const queue = [];-let running = null;+const running = new Map();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@@ -94,7 +144,9 @@ let workerStarted = false;let initPromise = null;function findJob(jobId) {- if (running && running.id === jobId) return running;+ for (const r of running.values()) {+ if (r.id === jobId) return r;+ }const inQueue = queue.find((j) => j.id === jobId);if (inQueue) return inQueue;return archive.find((j) => j.id === jobId) || null;@@ -106,7 +158,7 @@ export function getJob(jobId) {export function listJobs({ status, kind, owner } = {}) {const all = [- ...(running ? [running] : []),+ ...runningArray(),...queue,...archive,];@@ -140,7 +192,7 @@ async function persistImpl() {archive.length = 0;archive.push(...trimmedArchive);const live = [- ...(running ? [running] : []),+ ...runningArray(),...queue,...archive,];@@ -227,56 +279,71 @@ function startWorker() {async function drainLoop() {while (true) {- if (running || queue.length === 0) {- await sleep(150);- continue;+ // 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;}- const job = queue.shift();- job.status = 'running';- job.startedAt = new Date().toISOString();- // The running job is always slot 1 in the overall pipeline. Without- // this, a job dequeued from position 2 (queued behind another job that- // just finished) would keep its old position=2 even while running, and- // /api/media-jobs would show "running, 2 in queue" when it's really 1.- job.position = 1;- running = job;- // Recompute positions for everyone still queued AND broadcast the new- // position over SSE so clients listening to /:jobId/events see "you are- // now #2" instead of staying frozen at the original enqueue-time slot.- recomputeQueuePositions();- persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on start failed: ${e.message}`));- broadcastSse(ensureSseEntry(job.id), { type: 'started', kind: job.kind });- mediaJobEvents.emit('started', job);- console.log(`▶️ media-job [${job.id.slice(0, 8)}] ${job.kind} started`);- // The worker loop is a top-level fire-and-forget — if runJob throws- // unexpectedly (an unhandled emitter / listener edge case, etc.), an- // uncaught error here would terminate the loop and freeze the queue- // until the next enqueueJob re-armed startWorker. Catch + recover so a- // single bad job can't kill the worker.- try {- await runJob(job);- } catch (err) {- console.log(`❌ media-job [${job.id.slice(0, 8)}] runJob threw: ${err.message}`);- if (job.status === 'running') {- job.status = 'failed';- job.error = `runJob threw: ${err.message}`;- job.completedAt = new Date().toISOString();- broadcastSse(ensureSseEntry(job.id), { type: 'error', error: job.error });- // Mirror the in-job failed path: schedule SSE cleanup so this rare- // recovery doesn't leak the sseJobs entry + open clients forever.- closeJobAfterDelay(sseJobs, job.id);- mediaJobEvents.emit('failed', job);- }+ 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);}- running = null;- archive.push(job);- // Now that running is cleared, every queued job has shifted up one slot.- // Recompute immediately so /api/media-jobs and any subsequent persist()- // see accurate positions even before the next dequeue, and broadcast- // the new position to each waiting client.- recomputeQueuePositions();- persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on done failed: ${e.message}`));}+ 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@@ -284,15 +351,27 @@ async function drainLoop() {// 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() {- queue.forEach((q, i) => {- const newPosition = i + 1 + (running ? 1 : 0);+ 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);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@@ -436,7 +515,14 @@ 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.- const watchdogTimeoutMs = job.kind === 'video' ? WATCHDOG_VIDEO_MS : WATCHDOG_IMAGE_MS;+ // 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_IMAGE_MS;watchdogTimer = setTimeout(async () => {// Two-stage status guard: first check stops us if the gen settled// before the timer fired. The await on the dynamic import below opens@@ -446,10 +532,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 importer = job.kind === 'video'- ? import('../videoGen/local.js')- : job.kind === 'image' ? import('../imageGen/local.js') : null;- const mod = importer ? await importer : null;+ const mod = await importGenModuleForJob(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@@ -463,10 +546,18 @@ async function runJob(job) {try {if (job.kind === 'video') {- const { generateVideo } = await import('../videoGen/local.js');- await generateVideo({ ...safeParams, jobId: job.id });+ // 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 } = await import('../imageGen/local.js');+ const { generateImage } = isCodexJob(job)+ ? await import('../imageGen/codex.js')+ : await import('../imageGen/local.js');await generateImage({ ...safeParams, jobId: job.id });} else {throw new Error(`Unknown job kind: ${job.kind}`);@@ -494,6 +585,12 @@ 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,@@ -501,10 +598,7 @@ export function enqueueJob({ kind, params, owner = null }) {status: 'queued',queuedAt: new Date().toISOString(),params,- // position counts "where you sit in the overall pipeline" — the running- // job (if any) occupies slot 1, then queued jobs follow. So the second- // submission while one is running sits at position 2.- position: queue.length + (running ? 1 : 0) + 1,+ position,};queue.push(job);const sseEntry = ensureSseEntry(id);@@ -551,19 +645,15 @@ export async function cancelJob(jobId) {console.log(`🛑 media-job [${jobId.slice(0, 8)}] canceled (was queued)`);return { ok: true, status: 'canceled' };}- if (running && running.id === jobId) {+ for (const r of running.values()) {+ if (r.id !== jobId) continue;// Flag the job so the dispatcher's `failed` handler treats the SIGTERM-// induced failure as `canceled` rather than `failed`. Without this the// job would land in archive with status='failed' and listing by// status='canceled' would be empty for running cancels.- running.cancelRequested = true;- if (running.kind === 'video') {- const { cancel } = await import('../videoGen/local.js');- cancel();- } else if (running.kind === 'image') {- const { cancel } = await import('../imageGen/local.js');- cancel();- }+ r.cancelRequested = true;+ const mod = await importGenModuleForJob(r);+ mod?.cancel?.();console.log(`🛑 media-job [${jobId.slice(0, 8)}] cancel signal sent (was running)`);return { ok: true, status: 'canceling' };}@@ -638,7 +728,7 @@ function sleep(ms) {// Test-only reset hook. Real callers go through enqueueJob/cancelJob.export function __resetForTests() {queue.length = 0;- running = null;+ running.clear();archive.length = 0;sseJobs.clear();workerStarted = false;diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex 22ae428d76..2982294d27 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -30,8 +30,10 @@ vi.mock('../../lib/fileUtils.js', async () => {const stubs = {generateVideo: vi.fn(async () => ({ jobId: 'whatever' })),generateImage: vi.fn(async () => ({ jobId: 'whatever' })),+ generateCodexImage: vi.fn(async () => ({ jobId: 'whatever' })),cancelVideo: vi.fn(),cancelImage: vi.fn(),+ cancelCodexImage: vi.fn(),};vi.mock('../videoGen/local.js', () => ({@@ -44,6 +46,11 @@ vi.mock('../imageGen/local.js', () => ({cancel: (...args) => stubs.cancelImage(...args),}));+vi.mock('../imageGen/codex.js', () => ({+ generateImage: (...args) => stubs.generateCodexImage(...args),+ cancel: (...args) => stubs.cancelCodexImage(...args),+}));+// Import the queue + the gen-event emitters AFTER the mocks above are// registered. Static imports would race with vi.mock hoisting on a real// dependency cycle, so dynamic-import this in beforeEach.@@ -398,6 +405,89 @@ 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(() => {}));++ mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'gpu-job' } });+ mediaJobQueue.enqueueJob({+ kind: 'image',+ params: { mode: 'codex', prompt: 'codex-job' },+ });++ // 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);+ });++ // 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({+ kind: 'image',+ params: { mode: 'codex', prompt: 'first' },+ });+ const second = mediaJobQueue.enqueueJob({+ kind: 'image',+ params: { mode: 'codex', prompt: 'second' },+ });++ 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);+ });++ // 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({+ kind: 'image',+ params: { mode: 'codex', codexPath: '/usr/local/bin/codex', prompt: 'a fox' },+ });++ 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}$/);+ });++ // 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(() => {}));+ const job = mediaJobQueue.enqueueJob({+ kind: 'image',+ params: { mode: 'codex', prompt: 'cancel-me' },+ });+ await waitFor(() => stubs.generateCodexImage.mock.calls.length === 1);++ await mediaJobQueue.cancelJob(job.jobId);+ expect(stubs.cancelCodexImage).toHaveBeenCalled();+ expect(stubs.cancelImage).not.toHaveBeenCalled();+ });+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 fallsdiff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex dd0090c110..cf28ba70d8 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -40,11 +40,20 @@ const HISTORY_FILE = join(PATHS.data, 'video-history.json');const jobs = new Map();let activeProcess = null;+// Chain state for multi-chunk renders. cancel() flips `stopped` so the chain+// loop bails before kicking off the next chunk; the in-flight chunk's child+// is killed via the existing activeProcess SIGTERM path. There is at most+// one chain in flight at a time (mediaJobQueue serializes the gpu lane).+let activeChain = null;export const attachSseClient = (jobId, res) => attachSse(jobs, jobId, res);export const cancel = () => {- if (!activeProcess) return false;+ // Flag the chain (if any) so the loop stops between chunks. We still+ // kill the in-flight child below — without that the current chunk would+ // run to completion before the chain saw the stop flag.+ if (activeChain) activeChain.stopped = true;+ if (!activeProcess) return !!activeChain;const proc = activeProcess;proc.kill('SIGTERM');// KEEP activeProcess set until proc.on('close') clears it. Without this,@@ -329,6 +338,200 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', mreturn { jobId, generationId: jobId, filename, mode: 'local', model: modelId };}+// Generate a chain of N video chunks where each chunk's last frame seeds+// the next, then stitch them into a single longer clip. Reports progress ++// terminal events against the OUTER jobId (so the mediaJobQueue's dispatcher+// sees one logical job through the chain) while each inner chunk runs as a+// normal generateVideo() with its own inner jobId, file, and history entry.+//+// On completion the inner chunk entries are hidden so only the stitched clip+// is visible by default; the user can toggle hidden in the gallery to+// inspect individual chunks.+//+// On cancel the chain stops before the next chunk; the in-flight chunk's+// child is SIGTERM'd by cancel() and surfaces a 'failed' event we translate+// into a chain-level failure. Already-completed inner chunks are hidden but+// not deleted (the partial output is still on disk if the user wants it).+export async function generateChainedVideo({ chunks, jobId: outerJobId, ...rest }) {+ const totalChunks = Number(chunks) || 1;+ if (totalChunks === 1) {+ return generateVideo({ jobId: outerJobId, ...rest });+ }+ if (!outerJobId) throw new ServerError('generateChainedVideo requires jobId', { status: 500, code: 'INTERNAL' });++ const chainState = { stopped: false };+ activeChain = chainState;++ // Hold an outer job entry so attachSseClient(outerJobId) wires up against+ // the same SSE stream the queue sees. Without this, /api/video-gen/:id/events+ // attached at the outer id would 404 because no `jobs` map entry exists.+ const outerJob = { id: outerJobId, clients: [], status: 'running' };+ jobs.set(outerJobId, outerJob);++ const chunkIds = [];+ let currentSource = rest.sourceImagePath;+ // First chunk preserves the user's mode (text or image). Subsequent chunks+ // are always image-conditioned on the previous chunk's last frame.+ const firstMode = rest.mode || (currentSource ? 'image' : 'text');++ const runChunk = (i) => new Promise((resolve, reject) => {+ const innerJobId = randomUUID();+ chunkIds.push(innerJobId);+ const onProgress = (e) => {+ if (e.generationId !== innerJobId) return;+ const innerProg = typeof e.progress === 'number' ? e.progress : 0;+ const aggregate = (i + Math.max(0, Math.min(1, innerProg))) / totalChunks;+ videoGenEvents.emit('progress', {+ generationId: outerJobId,+ progress: aggregate,+ step: typeof e.step === 'number' ? e.step : undefined,+ totalSteps: typeof e.totalSteps === 'number' ? e.totalSteps : undefined,+ message: `Chunk ${i + 1}/${totalChunks}${e.message ? ` — ${e.message}` : ''}`,+ });+ broadcastSse(outerJob, {+ type: 'progress',+ progress: aggregate,+ message: `Chunk ${i + 1}/${totalChunks}`,+ });+ };+ const detach = () => {+ videoGenEvents.off('progress', onProgress);+ videoGenEvents.off('completed', onCompleted);+ videoGenEvents.off('failed', onFailed);+ };+ const onCompleted = (e) => {+ if (e.generationId !== innerJobId) return;+ detach();+ resolve(e);+ };+ const onFailed = (e) => {+ if (e.generationId !== innerJobId) return;+ detach();+ reject(new Error(e.error || 'chunk failed'));+ };+ videoGenEvents.on('progress', onProgress);+ videoGenEvents.on('completed', onCompleted);+ videoGenEvents.on('failed', onFailed);++ // Bump the seed by chunk index when the user supplied one — keeps each+ // chunk visually varied while remaining reproducible from the user's+ // chosen seed. When seed is unset, generateVideo picks one randomly+ // per chunk (existing behavior).+ const chunkSeed = rest.seed != null && rest.seed !== ''+ ? Number(rest.seed) + i+ : undefined;+ generateVideo({+ ...rest,+ seed: chunkSeed,+ jobId: innerJobId,+ sourceImagePath: currentSource,+ // Only the first chunk consumes the user's uploadedTempPath (durable+ // copy under data/uploads). Later chunks use a frame extracted from a+ // prior render, which lives under data/images.+ uploadedTempPath: i === 0 ? rest.uploadedTempPath : null,+ mode: i === 0 ? firstMode : 'image',+ // After the first chunk, drop FFLF-style last image — chained continuation+ // is single-conditioned on the previous chunk's tail frame.+ lastImagePath: i === 0 ? rest.lastImagePath : null,+ }).catch((err) => {+ detach();+ reject(err);+ });+ });++ const finishOk = (payload) => {+ if (activeChain === chainState) activeChain = null;+ videoGenEvents.emit('completed', { generationId: outerJobId, ...payload });+ broadcastSse(outerJob, { type: 'complete', result: payload });+ closeJobAfterDelay(jobs, outerJobId);+ };+ const finishFail = (error) => {+ if (activeChain === chainState) activeChain = null;+ videoGenEvents.emit('failed', { generationId: outerJobId, error });+ broadcastSse(outerJob, { type: 'error', error });+ closeJobAfterDelay(jobs, outerJobId);+ };++ // Schedule the chain on the next tick and return the descriptor+ // synchronously — matches generateVideo's spawn-then-emit contract.+ (async () => {+ for (let i = 0; i < totalChunks; i++) {+ if (chainState.stopped) {+ await setHistoryItemsHidden(chunkIds, true);+ finishFail('Canceled mid-chain');+ return;+ }+ // eslint-disable-next-line no-await-in-loop+ const completed = await runChunk(i).catch((err) => ({ error: err.message }));+ if (completed?.error) {+ await setHistoryItemsHidden(chunkIds, true);+ finishFail(completed.error);+ return;+ }+ if (i < totalChunks - 1) {+ // extractLastFrame caches by id, so re-clicks (e.g. from gallery+ // "Continue") don't re-spawn ffmpeg.+ // eslint-disable-next-line no-await-in-loop+ const frame = await extractLastFrame(chunkIds[chunkIds.length - 1]).catch((err) => ({ error: err.message }));+ if (frame?.error) {+ await setHistoryItemsHidden(chunkIds, true);+ finishFail(`Failed to extract frame between chunks: ${frame.error}`);+ return;+ }+ currentSource = join(PATHS.images, frame.filename);+ }+ }+ const stitched = await stitchVideos(chunkIds, {+ id: outerJobId,+ filenamePrefix: 'chained',+ historyKey: 'chainedFrom',+ promptOverride: rest.prompt || null,+ }).catch((err) => ({ error: err.message }));+ if (stitched?.error) {+ await setHistoryItemsHidden(chunkIds, true);+ finishFail(`Stitch failed: ${stitched.error}`);+ return;+ }+ await setHistoryItemsHidden(chunkIds, true);+ finishOk({+ filename: stitched.filename,+ thumbnail: stitched.thumbnail,+ path: `/data/videos/${stitched.filename}`,+ chainedFrom: chunkIds,+ });+ })().catch((err) => {+ console.log(`❌ chain orchestration crashed [${outerJobId.slice(0, 8)}]: ${err.message}`);+ finishFail(err.message);+ });++ // Match the synchronous shape of generateVideo so the route's response+ // assembly doesn't need a chain-specific branch. The actual filename is+ // delivered via SSE 'complete' once the chain settles.+ return {+ jobId: outerJobId,+ generationId: outerJobId,+ filename: `chained-${outerJobId}.mp4`,+ mode: 'local',+ model: rest.modelId,+ };+}++// Hide many history entries in one load+save. The per-id setHistoryItemHidden+// would re-read + atomic-write the entire history file once per id; for an+// 8-chunk chain that's 16 file ops on every terminal path. Best-effort —+// errors are swallowed because the stitched clip is more important than+// the visibility flag.+async function setHistoryItemsHidden(ids, hidden) {+ if (!ids?.length) return;+ const wanted = new Set(ids);+ const history = await loadHistory().catch(() => null);+ if (!Array.isArray(history)) return;+ for (const item of history) {+ if (wanted.has(item.id)) item.hidden = !!hidden;+ }+ await saveHistory(history).catch(() => {});+}+// Extract the last frame of a video as a PNG into data/images/ — used to// chain a clip into Imagine for "continue from last frame" remixing.export async function extractLastFrame(historyId) {@@ -408,7 +611,17 @@ export async function extractLastFrame(historyId) {// 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// lets users stitch from a single model so this holds in practice.-export async function stitchVideos(videoIds) {+//+// `opts` lets the chained-render code reuse the same ffmpeg path with a+// different identity (id, filename prefix, history-link key, prompt) without+// duplicating the validation + concat-manifest plumbing.+export async function stitchVideos(videoIds, opts = {}) {+ const {+ id = randomUUID(),+ filenamePrefix = 'stitched',+ historyKey = 'stitchedFrom',+ promptOverride = null,+ } = opts;if (!Array.isArray(videoIds) || videoIds.length < 2) {throw new ServerError('Need at least 2 videos to stitch', { status: 400, code: 'VALIDATION_ERROR' });}@@ -416,7 +629,7 @@ export async function stitchVideos(videoIds) {if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });const history = await loadHistory();- const videos = videoIds.map((id) => history.find((h) => h.id === id)).filter(Boolean);+ const videos = videoIds.map((vid) => history.find((h) => h.id === vid)).filter(Boolean);if (videos.length < 2) throw new ServerError('Some videos not found', { status: 400, code: 'VALIDATION_ERROR' });// Validate every history-supplied filename through safeUnder before@@ -430,8 +643,7 @@ export async function stitchVideos(videoIds) {if (!existsSync(p)) throw new ServerError(`Missing: ${basename(p)}`, { status: 404, code: 'NOT_FOUND' });}- const jobId = randomUUID();- const listFile = join(tmpdir(), `concat-${jobId}.txt`);+ const listFile = join(tmpdir(), `concat-${id}.txt`);// ffmpeg concat-demuxer escape: per its docs, single quotes in filenames// must be replaced with `'\''`. Inside quoted strings ffmpeg also treats// backslash as an escape character — on Windows where paths are@@ -440,7 +652,7 @@ export async function stitchVideos(videoIds) {const escapeForConcat = (p) => p.replace(/\\/g, '/').replace(/'/g, "'\\''");await writeFile(listFile, videoPaths.map((p) => `file '${escapeForConcat(p)}'`).join('\n'));- const outFilename = `stitched-${jobId}.mp4`;+ const outFilename = `${filenamePrefix}-${id}.mp4`;const outPath = join(PATHS.videos, outFilename);// Use a try/finally so the concat list temp file is cleaned up even when@@ -455,12 +667,14 @@ export async function stitchVideos(videoIds) {await unlink(listFile).catch(() => {});}- const thumb = await generateThumbnail(outPath, jobId);+ const thumb = await generateThumbnail(outPath, id);const stitchedMeta = {- id: jobId,- prompt: `Stitched: ${videos.map((v) => v.prompt).join(' + ')}`,+ id,+ prompt: promptOverride != null+ ? promptOverride+ : `Stitched: ${videos.map((v) => v.prompt).join(' + ')}`,modelId: videos[0].modelId,- seed: 0,+ seed: videos[0].seed ?? 0,width: videos[0].width,height: videos[0].height,numFrames: videos.reduce((sum, v) => sum + (v.numFrames || 0), 0),@@ -468,12 +682,12 @@ export async function stitchVideos(videoIds) {filename: outFilename,thumbnail: thumb,createdAt: new Date().toISOString(),- stitchedFrom: videoIds,+ [historyKey]: videoIds,};const h = await loadHistory();h.unshift(stitchedMeta);await saveHistory(h);- console.log(`🎬 Stitched ${videos.length} videos: ${outFilename}`);+ console.log(`🎬 Stitched ${videos.length} videos → ${outFilename}`);return stitchedMeta;}