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
carry motion across chunk seams with a tail-window continuation, and stop extend chains repeating themselves
[._.]/ Adam Eivy503782bbac53
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2b205d1dcb..1e869dbd6d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,6 +8,10 @@- Internal: retiring a built-in video model now has a `RETIRED_VIDEO_MODELS` table in `server/lib/mediaModels.js` rather than living only in a migration. The migration alone would have been undone by the boot that applied it — the registry is cached at import time, before `bootstrapServices()` reaches the migration runner, and the next registry edit writes that stale cached object back to disk. The table is the load-time twin (same arrangement `applyVideoDisclosures`/migration 237 and `backfillKvRepo`/migration 064 already use), carries the successor id so a default naming a retired model repoints instead of falling through to whatever happens to be first, and shares the fork-preservation guard with the migration — asserted equal across the two copies so a typo in either can't silently no-op one half. `scripts/migrations/_lib.js` also gained `readMediaRegistry`/`writeMediaRegistry`, the strict-read → skip → platform-array shell that migration 244 and the new 247 were carrying verbatim.+- **Chunked video renders now carry motion across the joins — and an Extend chain no longer repeats itself.** Chaining several chunks into one longer clip used to seed each new chunk from a single extracted still, so the model got a pose with no velocity and the movement visibly stalled and restarted at every seam. Chunks now condition on a *window* of the previous chunk (about a second of footage by default) through LTX-2's extend pipeline, which carries the scene's motion and its current lighting across the join instead of just its last frame. There's a new **Continuity** control under Advanced to size that window — larger windows hold motion better but add render time per chunk, and "Last frame only" returns to the old behavior. Models without an extend pipeline (MiniMax H3, Wan, Hunyuan) keep seeding from the last frame, which is all they can do, and the control stays hidden for them rather than offering a setting that does nothing.++ This also fixes a real defect in multi-chunk **Extend** renders. Extending a video returns the source *plus* the new footage, and each chunk was being handed the whole clip before it — so chunk 2 re-contained chunk 1, chunk 3 re-contained both, and the stitched result replayed the same footage once per chunk while every chunk took longer to render than the last. A chunk now sees only a bounded window, and the part of its render that merely echoes that window is measured and cut back off before the chunks are joined, so the finished clip holds each frame exactly once and per-chunk render time stays flat however long the chain runs.+- **Picking a source image on Video Gen now shows you the images.** Every gallery slot on the Video Gen form — the image-to-video source frame, the FFLF first/last pair, each multi-keyframe row, and each IC-LoRA reference row — used to be a dropdown of bare filenames capped at the 50 newest renders, which meant choosing a frame by guessing at `ltx-1754...png`. Those dropdowns are now the same searchable thumbnail-grid picker the Image Gen image-to-image form uses: your whole gallery, with previews, full-text search across prompt/model/seed/LoRA, and universe/collection and type filters. Uploading a frame from disk works exactly as before.- **Accepting a restricted model's license now counts everywhere, and the acceptance appears where you're blocked.** Generating a music video scene with MiniMax H3 failed with "requires acknowledgement of its territory restrictions, Community License, and Acceptable Use Policy" — even for someone who had already ticked exactly that box on the Video Gen page, because the acknowledgement was only remembered in that page's browser storage and no other screen had a way to show it. The acknowledgement is now a property of the install: accept it once, on any screen, and every render path is authorized — the Video Gen page, the music video scene board, and background producers like pipeline stages and scheduled agent runs that have no way to ask you. The music video board also shows the acknowledgement panel inline next to its renderer picker, so the terms are readable and acceptable on the screen that triggers the render; when a render is refused anyway, the message now says where the acceptance is made instead of naming rules with no way to reach them. Acceptance is keyed to the exact reviewed license version, so a future revision asks again rather than inheriting an old approval. And because the recorded acknowledgement is the *only* thing that authorizes a render — a request can no longer assert its own — withdrawing it takes effect everywhere at once, including on work already sitting in the render queue.diff --git a/client/src/components/videoGen/AdvancedParamsPanel.jsx b/client/src/components/videoGen/AdvancedParamsPanel.jsxindex 63a4f6c15a..a6fe92b788 100644--- a/client/src/components/videoGen/AdvancedParamsPanel.jsx+++ b/client/src/components/videoGen/AdvancedParamsPanel.jsx@@ -23,6 +23,7 @@ import { FormField } from '../ui/FormField';import {frameOptionsForModel, fpsOptionsForModel, CHUNK_OPTIONS,isModelAllowedForMode, supportsVideoAudioControls,+ CONTEXT_FRAME_OPTIONS, supportsContextWindow,} from '../../lib/videoGenParams.js';import { VIDEO_TILING_OPTIONS } from '../../lib/videoTilingOptions';@@ -34,6 +35,7 @@ export default function AdvancedParamsPanel({numFrames, onNumFramesChange,chunks, onChunksChange, keyframesActive,chunkPrompts = [], onChunkPromptChange, chainingActive = false,+ contextFrames, onContextFramesChange,fps, onFpsChange,seed, onSeedChange, onRandomSeed,steps, onStepsChange,@@ -113,6 +115,34 @@ export default function AdvancedParamsPanel({</div>)}+ {/* Continuation context window. Only meaningful once the request+ really chains AND the runtime has an extend pipeline to feed the+ window to — everywhere else the server seeds the next chunk from+ a single last frame regardless, so showing the control would be+ offering a knob that does nothing. */}+ {chainingActive && supportsContextWindow(currentModel) && (+ <div>+ <label htmlFor="context-frames-select" className="block text-xs font-medium text-gray-400 mb-1" title="How much of the previous chunk each new chunk sees. A window carries the scene's motion across the seam; a single last frame gives the model a pose with no velocity, so movement stalls and restarts at every join.">+ Continuity+ </label>+ <select+ id="context-frames-select"+ value={contextFrames}+ onChange={(e) => onContextFramesChange(Number(e.target.value))}+ className={inputCls}+ >+ {CONTEXT_FRAME_OPTIONS.map((n) => (+ <option key={n} value={n}>+ {n === 0 ? 'Last frame only' : `${n} frames (~${(n / fps).toFixed(1)}s)`}+ </option>+ ))}+ </select>+ <p className="text-[10px] text-gray-500 leading-snug mt-1">+ Bigger windows hold motion better across joins but add render time per chunk.+ </p>+ </div>+ )}+{/* Per-chunk prompt beats (#3695). Only shown when the request reallychains — the parent derives `chainingActive` from the samepredicate that decides whether `chunks` is submitted at all, sodiff --git a/client/src/components/videoGen/AdvancedParamsPanel.test.jsx b/client/src/components/videoGen/AdvancedParamsPanel.test.jsxindex e752478c40..a8982bc003 100644--- a/client/src/components/videoGen/AdvancedParamsPanel.test.jsx+++ b/client/src/components/videoGen/AdvancedParamsPanel.test.jsx@@ -12,6 +12,7 @@ const baseProps = {numFrames: 121, onNumFramesChange: vi.fn(),chunks: 1, onChunksChange: vi.fn(), keyframesActive: false,chunkPrompts: [], onChunkPromptChange: vi.fn(), chainingActive: false,+ contextFrames: 22, onContextFramesChange: vi.fn(),fps: 24, onFpsChange: vi.fn(),seed: '', onSeedChange: vi.fn(), onRandomSeed: vi.fn(),steps: '', onStepsChange: vi.fn(),@@ -201,4 +202,43 @@ describe('AdvancedParamsPanel', () => {expect(onChunkPromptChange).toHaveBeenCalledWith(1, 'the storm breaks');});});++ describe('continuation context window', () => {+ // ltx2 is the only runtime with an extend pipeline to feed a window to.+ const LTX2 = { steps: 30, guidance: 3.0, runtime: 'ltx2' };++ it('stays hidden while the request is not chaining', () => {+ renderPanel({ currentModel: LTX2, chunks: 1, chainingActive: false });+ fireEvent.click(toggle());+ expect(screen.queryByLabelText('Continuity')).toBeNull();+ });++ it('stays hidden on a runtime that ignores the window', () => {+ // Offering the control where the server discards the value would be a+ // knob that silently does nothing.+ renderPanel({ currentModel: { runtime: 'minimax_h3' }, chunks: 3, chainingActive: true });+ fireEvent.click(toggle());+ expect(screen.queryByLabelText('Continuity')).toBeNull();+ });++ it('shows the selected window on a chaining ltx2 render', () => {+ renderPanel({ currentModel: LTX2, chunks: 3, chainingActive: true, contextFrames: 45 });+ fireEvent.click(toggle());+ expect(screen.getByLabelText('Continuity').value).toBe('45');+ });++ it('offers last-frame chaining as an explicit choice', () => {+ renderPanel({ currentModel: LTX2, chunks: 3, chainingActive: true });+ fireEvent.click(toggle());+ expect(screen.getByRole('option', { name: /Last frame only/ })).toBeTruthy();+ });++ it('reports the choice as a number, so a selected 0 is not sent as a string', () => {+ const onContextFramesChange = vi.fn();+ renderPanel({ currentModel: LTX2, chunks: 3, chainingActive: true, onContextFramesChange });+ fireEvent.click(toggle());+ fireEvent.change(screen.getByLabelText('Continuity'), { target: { value: '0' } });+ expect(onContextFramesChange).toHaveBeenCalledWith(0);+ });+ });});diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.jsindex 3476e1f8df..7f2de34198 100644--- a/client/src/hooks/useVideoGenForm.js+++ b/client/src/hooks/useVideoGenForm.js@@ -10,7 +10,7 @@ import { clampImageEdge } from '../lib/imageGenResolutions';import { GROK_VIDEO_DEFAULT_DURATION } from '../lib/grokVideoClip.js';import { VIDEO_TILING_ENUM_SET } from '../lib/videoTilingOptions';import {- VIDEO_EDGE_BOUNDS, MAX_CHUNKS,+ VIDEO_EDGE_BOUNDS, MAX_CHUNKS, DEFAULT_CONTEXT_FRAMES,videoModelMemoryGb, computeFflfSafeFrames, isModelAllowedForMode,supportsVideoAudioControls,normalizeFramesForModel, normalizeFpsForModel,@@ -73,6 +73,10 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })// `setChunkPromptAt` rather than eagerly resized on every chunk change, so// lowering then raising the count doesn't lose typed text.const [chunkPrompts, setChunkPrompts] = useState([]);+ // Continuation context window — how many of the previous chunk's frames each+ // chained chunk conditions on. 0 means "last frame only"; the server clamps+ // and ignores it on a runtime with no extend pipeline.+ const [contextFrames, setContextFrames] = useState(DEFAULT_CONTEXT_FRAMES);const [steps, setSteps] = useState('');const [guidanceScale, setGuidanceScale] = useState('');const [imageStrength, setImageStrength] = useState('');@@ -898,6 +902,10 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })if (p.duration) setGrokDuration(p.duration);} else if (p.mode) setMode(p.mode);if (p.chunks && p.chunks > 1) setChunks(p.chunks);+ // 0 is a real restored value ("last frame only"), so this can't gate on+ // truthiness the way `chunks` does — that would silently upgrade a render+ // the user deliberately put on last-frame chaining back to a window.+ if (Number.isFinite(p.contextFrames)) setContextFrames(p.contextFrames);// Per-chunk beats (#3695). The server normalizes an absent beat to null;// the editor's shape is '' for the same thing, so map back on restore.if (Array.isArray(p.chunkPrompts) && p.chunkPrompts.length) {@@ -1118,6 +1126,10 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })// POSITION of a blank middle beat. Omitted entirely when chaining is off// or every beat is blank, so a non-chained submit sends nothing.chunkPrompts: beats.some((p) => p.trim()) ? JSON.stringify(beats) : '',+ // Rides only when the request actually chains — same rule as `chunks`.+ // String()'d rather than sent raw so a deliberate 0 survives buildFormData+ // (which drops falsy values); '' is what "not sent" looks like here.+ contextFrames: chainingActive ? String(contextFrames) : '',};};@@ -1140,6 +1152,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })fps, setFps,chunks, setChunks,chunkPrompts, setChunkPromptAt, chainingActive,+ contextFrames, setContextFrames,steps, setSteps,guidanceScale, setGuidanceScale,imageStrength, setImageStrength,diff --git a/client/src/hooks/useVideoGenForm.test.jsx b/client/src/hooks/useVideoGenForm.test.jsxindex 0023f2150e..fbbf34d22f 100644--- a/client/src/hooks/useVideoGenForm.test.jsx+++ b/client/src/hooks/useVideoGenForm.test.jsx@@ -365,6 +365,34 @@ describe('useVideoGenForm', () => {expect(result.current.buildGeneratePayload().chunkPrompts).toBe('');});+ it('submits the continuation window only while chaining', async () => {+ const result = await chained(3);+ expect(result.current.buildGeneratePayload().contextFrames).toBe('22');+ act(() => result.current.setChunks(1));+ // A single-chunk render has nothing to continue from, so the knob must+ // not ride along and be persisted into that job's params.+ expect(result.current.buildGeneratePayload().contextFrames).toBe('');+ });++ it('submits a chosen 0 rather than dropping it as falsy', async () => {+ // buildFormData skips '' — sending the number 0 raw would be skipped too,+ // and the server would default the user straight back to a window.+ const result = await chained(2);+ act(() => result.current.setContextFrames(0));+ expect(result.current.buildGeneratePayload().contextFrames).toBe('0');+ });++ it('restores a resumed 0 instead of treating it as unset', async () => {+ const { result } = render();+ await waitFor(() => expect(result.current.modelId).toBe(MLX.id));+ act(() => result.current.applyResumedParams({+ prompt: 'a long shot',+ chunks: 2,+ contextFrames: 0,+ }));+ expect(result.current.contextFrames).toBe(0);+ });+it('restores beats from a resumed job, mapping the server null back to blank', async () => {const { result } = render();await waitFor(() => expect(result.current.modelId).toBe(MLX.id));diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex c8eaebd787..5296f7e2e5 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -64,7 +64,7 @@ grep -i "what you want to do" client/src/lib/README.md| `importerDeepLink.js` | The Importer deep-link contract both ways: `buildImporterLink({ universeId, seriesId, seriesName })` builds the `/importer?…` URL a Series Pipeline page navigates to; `resolveImporterDeepLink(...)` reads those params back into the universe + series names the importer matches on. || `muscriptorModels.js` | `MUSCRIPTOR_MODELS` (audio → MIDI size tiers `small`/`medium`/`large`) + `DEFAULT_MUSCRIPTOR_MODEL`. Single source consumed by the transcribe `<select>`s in `MusicVideo.jsx` and `ReferenceAnalysis.jsx`. Mirrors the server's `MUSCRIPTOR_MODELS` in `server/services/audioMidiTranscription.js`. || `videoFinish.js` | Finish-a-draft gate (#3696). `isReproducibleTextToVideo(record)` is true only for a single text-to-video render whose history record already carries everything a re-render needs — `renderInputsVersion` (the positive marker that its conditioning inventory is trustworthy, so legacy records degrade to not-finishable rather than reading as unconditioned), an empty `conditioning` array, a resolved seed, a real prompt, and no stitched/chained/upscaled provenance. `finishTargetForRecord(record, models)` additionally resolves the draft model's server-declared `finishModelId` against the models this install can actually run, returning the delivery model entry or `null`. Mirrors `finishTargetForModel` in `server/lib/videoFinishProfiles.js`; the pair table itself stays server-side. |-| `videoGenParams.js` | Pure VideoGen param helpers: `FRAME_OPTIONS`/`FPS_OPTIONS`/`VIDEO_EDGE_BOUNDS`/`MAX_CHUNKS`/`CHUNK_OPTIONS` constants, `videoModelMemoryGb()` (model memory footprint), `computeFflfSafeFrames()` (FFLF/ltx2 pixel-budget back-solve, mirrors `server/services/videoGen/local.js`), and `isModelAllowedForMode()` (a2v + IC-remix → ltx2 gate). Also mirrors the IC-LoRA remix registry (`IC_LORA_MODES`/`IC_LORA_MODE_VALUES`/`isIcLoraMode()`/`icLoraSpecForMode()`/`icResolutionIssue()`) from `server/lib/icLoraWeights.js` so the form validates a reference render pre-submit — pinned by `server/lib/icLoraWeights.parity.test.js`. |+| `videoGenParams.js` | Pure VideoGen param helpers: `FRAME_OPTIONS`/`FPS_OPTIONS`/`VIDEO_EDGE_BOUNDS`/`MAX_CHUNKS`/`CHUNK_OPTIONS`/`DEFAULT_CONTEXT_FRAMES`/`CONTEXT_FRAME_OPTIONS` constants, `supportsContextWindow(model)` (does this runtime have an extend pipeline to feed a continuation window to — display mirror of `server/lib/videoContinuity.js`, pinned by `server/lib/videoContinuity.parity.test.js`), `videoModelMemoryGb()` (model memory footprint), `computeFflfSafeFrames()` (FFLF/ltx2 pixel-budget back-solve, mirrors `server/services/videoGen/local.js`), and `isModelAllowedForMode()` (a2v + IC-remix → ltx2 gate). Also mirrors the IC-LoRA remix registry (`IC_LORA_MODES`/`IC_LORA_MODE_VALUES`/`isIcLoraMode()`/`icLoraSpecForMode()`/`icResolutionIssue()`) from `server/lib/icLoraWeights.js` so the form validates a reference render pre-submit — pinned by `server/lib/icLoraWeights.parity.test.js`. || `videoGenResolutions.js` | Shared resolution presets for video generation (companion to image side; LTX-2 latent-friendly sizes) + `snapAspectToImage()` to pick the closest-aspect preset for an I2V source. || `videoTilingOptions.js` | `VIDEO_TILING_OPTIONS` (the `<select>` rows) + `VIDEO_TILING_ENUM_SET` (the value-only Set). Single source consumed by `VideoGen.jsx` and the Remix URL builder in `useMediaPreviewActions`. Mirrors the server's `z.enum` in `server/routes/videoGen.js`. |diff --git a/client/src/lib/videoGenParams.js b/client/src/lib/videoGenParams.jsindex 88843bef2a..c532f50a08 100644--- a/client/src/lib/videoGenParams.js+++ b/client/src/lib/videoGenParams.js@@ -17,6 +17,22 @@ export const FPS_OPTIONS = [16, 24, 30];// Exported so the Chunks picker and the Remix restore can't drift from it.export const MAX_CHUNKS = 8;export const CHUNK_OPTIONS = Array.from({ length: MAX_CHUNKS }, (_, i) => i + 1);++// Continuation context window — how many of the prior chunk's frames each+// subsequent chunk conditions on. Display-side mirror of+// `server/lib/videoContinuity.js` (which stays the authority: it defaults,+// clamps, and picks the strategy). Pinned against drift by the parity block in+// `videoGenParams.test.js`.+//+// `0` is a real option, not "unset" — it opts back into seeding the next chunk+// from a single extracted last frame, which is what every runtime without an+// extend pipeline does anyway.+export const DEFAULT_CONTEXT_FRAMES = 22;+export const CONTEXT_FRAME_OPTIONS = [0, 11, 22, 45, 73];+// Only a runtime with a video-conditioned extend pipeline can use a window;+// elsewhere the server ignores the value, so the control stays hidden rather+// than offering a knob that does nothing.+export const supportsContextWindow = (model) => model?.runtime === 'ltx2';export const WAN_FRAME_OPTIONS = [...new Set([...FRAME_OPTIONS,41, 61, 81, 101, 161, 201, 321,diff --git a/client/src/lib/videoGenParams.test.js b/client/src/lib/videoGenParams.test.jsindex d604f5fd6d..e20b557bd0 100644--- a/client/src/lib/videoGenParams.test.js+++ b/client/src/lib/videoGenParams.test.js@@ -182,3 +182,4 @@ describe('IC-LoRA remix modes (#3100)', () => {expect(icLoraSpecForMode('ic-colorize').uploadLabel).toMatch(/B&W/);});});+diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex d75c3cd472..8ba7110211 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -149,6 +149,7 @@ export default function VideoGen() {width, height, handleResolutionChange,numFrames, setNumFrames, fps, setFps, chunks, setChunks,chunkPrompts, setChunkPromptAt, chainingActive,+ contextFrames, setContextFrames,steps, setSteps, guidanceScale, setGuidanceScale, imageStrength, setImageStrength,seed, setSeed, handleRandomSeed, tiling, setTiling,disableAudio, setDisableAudio, noMusic, setNoMusic,@@ -1132,6 +1133,7 @@ export default function VideoGen() {numFrames={numFrames} onNumFramesChange={setNumFrames}chunks={chunks} onChunksChange={setChunks} keyframesActive={keyframesActive}chunkPrompts={chunkPrompts} onChunkPromptChange={setChunkPromptAt} chainingActive={chainingActive}+ contextFrames={contextFrames} onContextFramesChange={setContextFrames}fps={fps} onFpsChange={setFps}seed={seed} onSeedChange={setSeed} onRandomSeed={handleRandomSeed}steps={steps} onStepsChange={setSteps}diff --git a/server/lib/README.md b/server/lib/README.mdindex d1e14dd382..7161430b22 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -109,6 +109,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `promptTemplate.js` | Mustache-flavored, dot-notation-aware prompt template engine. || `promptPartials.js` | Mustache-style partial expansion. || `mediaModels.js` | Single source of truth for image/video model metadata. |+| `videoContinuity.js` | How chunk N+1 of a chained video render is conditioned on chunk N. `resolveContextFrames(requested)` normalizes the tail-window size (absent → `DEFAULT_CONTEXT_FRAMES` = 22 ≈ 1s @ 24fps; an explicit `0` is preserved as "last frame only", NOT collapsed into the default) and clamps to `MIN_CONTEXT_FRAMES`..`MAX_CONTEXT_FRAMES`. `resolveContinuityStrategy({model, contextFrames})` picks `'window'` (LTX-2 `extend_from_video` conditioned on the prior chunk's last N frames — motion, not just a pose) or `'frame'` (extract the last frame, run i2v), degrading to `'frame'` on any runtime outside `CONTEXT_WINDOW_RUNTIMES` rather than rejecting. `extendLatentFrames` / `extendedPixelFrames` convert across the VAE's `LATENT_FRAME_STRIDE` (8 pixel frames per latent), `contextPrefixFrames({totalFrames, extendLatents})` measures how much of an extend render is echoed context to trim back off before stitching (0 = leave it alone), and `tailWindowStartFrame` gives the cut index for the window itself. Pure — importable from `prepareParams.js` without dragging in `local.js`. Mirrored for the picker in `client/src/lib/videoGenParams.js`, pinned by `videoContinuity.parity.test.js`. || `videoDisclosure.js` | Video Gen provenance/licensing + backend policy-scope facts (#3674). `VIDEO_MODEL_DISCLOSURES` maps each shipped video model id to `{ shippedRepo, disclosure }` (model card URL, weights license, runtime license, pinned-snapshot download size in decimal GB, review date) — every value checked against a primary upstream source, and any fact that could not be established is OMITTED so the UI renders "Unknown" instead of guessing. `applyVideoDisclosures(list)` is the load-time backfill (twin of migration 237) with the same preservation guards: an existing `disclosure` key wins, a custom id is skipped, and a `repo` pointed at a fork keeps Unknown. `VIDEO_BACKEND_DISCLOSURES` / `videoBackendDisclosure(id)` state where inference runs (`execution: local or hosted`) and whose policy applies — execution facts only, never a restrictiveness ranking. || `videoFinishProfiles.js` | Draft → delivery ("Finish") relationships between video models (#3696). `VIDEO_FINISH_PROFILES` declares each fast draft entry id → `{ shippedRepo, finishModelId }`, only for pairs that share a runtime, base repo and supported modes (the same weights at a different step budget), so re-rendering the draft's seed reproduces its composition instead of re-rolling it. `applyVideoFinishProfiles(list)` is the load-time backfill (twin of migration 238) with the usual preservation guards (existing key wins, custom id skipped, forked `repo` skipped); `validateFinishProfileGraph(list)` returns the graph problems (missing / self-referencing / chained target, runtime / repo / supportedModes mismatch) and `sanitizeFinishProfiles(list)` warns + strips them at load so a typo can never surface a Finish button targeting nothing. `finishTargetForModel(model, availableModels)` resolves the delivery entry scoped to what this install can run. || `videoModeProfiles.js` | The shipped `supportedModes` fact per video runtime (#3737), so "which modes does this model support?" has one answer on the registry entry instead of 25+ `runtime === '…'` comparisons. `VIDEO_RUNTIME_MODES` maps each runtime to the base semantic modes its helper's argv can actually render (`mlx_video`/`ltx2` text+image+fflf+extend, `wan22` text+image, `minimax_h3` text+image+fflf — also the mode ceiling in `videoGen/modeContract.js` — `hunyuan` text only, replacing the legacy unread `mode: 't2v'` field); `VIDEO_BASE_MODES` is the fallback for an unknown (user-added or peer-synced) runtime, deliberately the full base set so a custom model doesn't vanish from every picker. `resolveVideoSupportedModes(entry)` (declared non-empty list always wins) and `applyVideoSupportedModes(list)` — the read-time decoration `mediaModels.js#getVideoModels` applies, so the derived list never lands in `data/media-models.json` where it would read back as a *declared* list no later correction could reach. a2v and the IC-LoRA remix ids are NOT enumerated here: they're ltx2 pipeline capabilities, gated by runtime (`A2V_REQUIRES_LTX2` / `IC_LORA_REQUIRES_LTX2`). |@@ -183,7 +184,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart (boot re-attach, #1332) and `reapDetached` to checkpoint-kill one when re-attach isn't possible. || `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing; `shouldAbandonForHostShutdown({sentinelPresent,terminatedByUser,paused})` keeps every spawn path on the same preserve-vs-finalize policy. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. || `execGit.js` | `execGit` utility imported by `git.js` + worktree manager. |-| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). |+| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. || `ffmpegRenderGuard.js` | `attachFfmpegRenderGuard(proc, {label, onSpawnError, onProcessError, onClose})` — shared spawn-state tracking + exactly-once `terminal` guard + pre-vs-post-spawn dispatch for the SSE ffmpeg render runners (musicVideo/render + videoTimeline/local). Owns the 'spawn'/'error'/'close' wiring (only the pre-spawn 'error' or 'close' finalizes; a post-spawn 'error' records only) and takes the service-specific finalize bodies as callbacks so each renderer keeps its own project-status/history behavior. || `gitArgs.js` | `PROTECTED_BRANCHES`, `validateFilePaths(files)` — pure command-arg builders/validators for `git.js` (reject injection/traversal in staged paths). || `gitCommitProbe.js` | `commitsSince(workspacePath, sinceMs)` / `committedDuringRun(workspacePath, sinceMs)` — the run-window commit probe: how many commits landed with a COMMITTER date inside a run's window (so a rebase/commit by the agent counts, a merely-pulled remote commit does not). The single machine-checkable "did this run commit anything?" primitive shared by finalize's success-criteria evaluation, run completion, runner completion, and orphan recovery — it replaced the unsatisfiable task-id commit-marker grep (#3637). Non-throwing: a non-repo, empty repo, or git timeout is 0. |diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.jsindex efeb7fddbc..f605f5768d 100644--- a/server/lib/ffmpeg.js+++ b/server/lib/ffmpeg.js@@ -228,7 +228,7 @@ export const generateThumbnail = async (videoPath, jobId) => {// (`-count_frames stream=nb_read_frames`) for containers that don't expose// nb_frames in their header. Returns null when both paths fail or the// reported count is unusable.-const probeFrameCount = async (videoPath) => {+export const probeFrameCount = async (videoPath) => {const run = async (countFrames) => {const stdout = await runFfprobe(['-v', 'error',@@ -340,6 +340,113 @@ export const extractEvaluationFrames = async (videoPath, jobId, count = 5) => {return frameIndices.map((_, i) => `${jobId}-f${i + 1}.jpg`);};+// The one H.264 encode profile every re-encoding path here shares. Visually+// lossless to most viewers and plays everywhere — but the reason it's a+// constant rather than three inlined copies is that clips encoded by DIFFERENT+// paths get concatenated together (a chained render's trimmed chunks join its+// untrimmed ones), and a mismatch there shows up as one segment being graded+// differently from its neighbours. Callers append their own `-c:a`.+export const H264_ENCODE_ARGS = Object.freeze([+ '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-crf', '18', '-preset', 'medium',+]);+export const AAC_ENCODE_ARGS = Object.freeze(['-c:a', 'aac', '-b:a', '192k']);++// Move a freshly-encoded temp file over the file it replaces.+//+// POSIX rename atomically replaces an existing destination in one syscall. On+// Windows, fs.rename fails when the destination already exists — but a simple+// unlink-first would destroy the original if the subsequent rename failed+// (locked file, AV scan, transient permissions). Move the original aside to a+// .bak first, install the new file, and restore the backup on any failure, so+// the worst case is "the operation was skipped", never "the video is gone".+//+// Extracted because three callers (`trimVideoFromFrame`, `upscaleVideo2x`,+// `optimizeForStreaming`) need this identical rollback, and a data-loss-+// sensitive path with three copies is one that eventually gets fixed in only+// two of them. `label` names the operation for the failure message.+//+// Returns `{ ok: true, outPath }` or `{ ok: false, reason }`.+const installEncodedVideo = async (tmpPath, targetPath, label) => {+ let backupPath = null;+ try {+ if (IS_WIN) {+ backupPath = `${targetPath}.bak.${randomUUID()}`;+ await rename(targetPath, backupPath).catch((err) => {+ if (err?.code === 'ENOENT') { backupPath = null; return; }+ throw err;+ });+ }+ await rename(tmpPath, targetPath);+ if (backupPath) await unlink(backupPath).catch(() => {});+ return { ok: true, outPath: targetPath };+ } catch (err) {+ if (backupPath) await rename(backupPath, targetPath).catch(() => {});+ await unlink(tmpPath).catch(() => {});+ return { ok: false, reason: `Failed to install ${label} video: ${err.message}` };+ }+};++// Keep frames [startFrame, end) of a clip, dropping everything before it.+//+// Both halves of the chained-render context window need exactly this cut: the+// tail window handed to LTX-2's extend pipeline is "keep the last N frames"+// (startFrame = total - N), and trimming the echoed context back off an extend+// render is "keep everything after the echo" (startFrame = prefix length). See+// `lib/videoContinuity.js` for how those indices are derived.+//+// Frame-exact by construction: the `trim` filter cuts on a frame INDEX rather+// than a timestamp, so the seam can't drift by a frame the way an `-ss` seek+// can — and a one-frame drift here is a visible stutter or a repeated frame in+// the stitched clip. `atrim` cuts the audio at the matching timestamp so LTX's+// jointly-generated soundtrack stays in sync; a silent clip takes `-an`+// instead, because referencing a missing audio stream aborts the whole run.+//+// Re-encodes (a frame-index cut can't be stream-copied — the new first frame+// is almost never a keyframe). Callers that then concat the result must+// re-encode at concat time too rather than relying on `-c copy`.+//+// `outPath` may be the input path: the encode goes to a sibling temp file and+// is renamed into place, so a failure leaves the original untouched.+//+// Returns `{ ok: true, outPath }` or `{ ok: false, reason }`.+export const trimVideoFromFrame = async (videoPath, outPath, { startFrame, fps } = {}) => {+ if (typeof videoPath !== 'string' || !videoPath) return { ok: false, reason: 'invalid video path' };+ if (typeof outPath !== 'string' || !outPath) return { ok: false, reason: 'invalid output path' };+ if (!existsSync(videoPath)) return { ok: false, reason: 'video file missing' };+ const start = Math.max(0, Math.floor(Number(startFrame) || 0));+ const rate = Number(fps);+ if (!Number.isFinite(rate) || rate <= 0) return { ok: false, reason: `invalid fps: ${fps}` };+ const ffmpeg = await findFfmpeg();+ if (!ffmpeg) return { ok: false, reason: 'ffmpeg not found' };++ const inPlace = resolvePath(videoPath) === resolvePath(outPath);+ const encodePath = inPlace ? `${videoPath}.trim.mp4` : outPath;+ if (!inPlace) await ensureDir(dirname(outPath));++ const audio = await hasAudioStream(videoPath);+ const result = await runFfmpegProcess({+ bin: ffmpeg,+ args: [+ '-i', videoPath,+ '-vf', `trim=start_frame=${start},setpts=PTS-STARTPTS`,+ ...(audio+ // atrim takes seconds; the frame index converts exactly because the+ // clips this runs on are CFR renders straight out of the model.+ ? ['-af', `atrim=start=${(start / rate).toFixed(6)},asetpts=PTS-STARTPTS`, ...AAC_ENCODE_ARGS]+ : ['-an']),+ ...H264_ENCODE_ARGS,+ '-movflags', '+faststart',+ '-y', encodePath,+ ],+ });+ if (!result.ok) {+ await unlink(encodePath).catch(() => {});+ return { ok: false, reason: `ffmpeg trim failed: ${result.reason}` };+ }+ if (!inPlace) return { ok: true, outPath };+ return installEncodedVideo(encodePath, videoPath, 'trimmed');+};+// 2× Lanczos upscale of an MP4 in place. Doubles width and height while// preserving the exact aspect ratio and the audio track. Used as a quick// post-render export option for LTX renders that come out at sub-720p@@ -378,10 +485,7 @@ export const upscaleVideo2x = async (videoPath) => {args: ['-i', videoPath,'-vf', 'scale=iw*2:-2:flags=lanczos',- '-c:v', 'libx264',- '-pix_fmt', 'yuv420p',- '-crf', '18',- '-preset', 'medium',+ ...H264_ENCODE_ARGS,'-c:a', 'copy','-movflags', '+faststart','-y', tmpPath,@@ -391,23 +495,7 @@ export const upscaleVideo2x = async (videoPath) => {await unlink(tmpPath).catch(() => {});return { ok: false, reason: 'ffmpeg upscale failed' };}- let backupPath = null;- try {- if (IS_WIN) {- backupPath = `${videoPath}.bak.${randomUUID()}`;- await rename(videoPath, backupPath).catch((err) => {- if (err?.code === 'ENOENT') { backupPath = null; return; }- throw err;- });- }- await rename(tmpPath, videoPath);- if (backupPath) await unlink(backupPath).catch(() => {});- return { ok: true, outPath: videoPath };- } catch (err) {- if (backupPath) await rename(backupPath, videoPath).catch(() => {});- await unlink(tmpPath).catch(() => {});- return { ok: false, reason: `Failed to install upscaled video: ${err.message}` };- }+ return installEncodedVideo(tmpPath, videoPath, 'upscaled');};// MP4s with the moov atom at the END require browsers to download the entire@@ -423,27 +511,8 @@ export const optimizeForStreaming = async (videoPath) => {args: ['-i', videoPath, '-c', 'copy', '-movflags', '+faststart', '-y', tmpPath],});if (!result.ok) { await unlink(tmpPath).catch(() => {}); return; }- // POSIX rename atomically replaces an existing dest in one syscall. On- // Windows, fs.rename fails when the destination already exists — but a- // simple unlink-first would destroy the rendered video if the subsequent- // rename failed (locked file, AV scan, transient permissions). Move the- // original aside to a .bak first, then install the optimized file, and- // restore the backup on any failure so the worst case is "faststart- // skipped", not "rendered video lost".- let backupPath = null;- try {- if (IS_WIN) {- backupPath = `${videoPath}.bak.${randomUUID()}`;- await rename(videoPath, backupPath).catch((err) => {- if (err?.code === 'ENOENT') { backupPath = null; return; }- throw err;- });- }- await rename(tmpPath, videoPath);- if (backupPath) await unlink(backupPath).catch(() => {});- } catch (err) {- if (backupPath) await rename(backupPath, videoPath).catch(() => {});- await unlink(tmpPath).catch(() => {});- console.log(`⚠️ Failed to install streaming-optimized video at ${videoPath}: ${err.message}`);- }+ // Best-effort: faststart is a nicety, so a failed install is logged and+ // swallowed rather than surfaced — the original clip is already restored.+ const installed = await installEncodedVideo(tmpPath, videoPath, 'streaming-optimized');+ if (!installed.ok) console.log(`⚠️ ${installed.reason} (at ${videoPath})`);};diff --git a/server/lib/index.js b/server/lib/index.jsindex df964aa8c5..bcf3096a32 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -110,6 +110,7 @@ export * from './sseHeaders.js';export * from './installLogger.js';export * from './kimi.js';export * from './mediaModels.js';+export * from './videoContinuity.js';export * from './videoDisclosure.js';export * from './videoFinishProfiles.js';export * from './videoModeProfiles.js';diff --git a/server/lib/videoContinuity.js b/server/lib/videoContinuity.jsnew file mode 100644index 0000000000..0c31397fac--- /dev/null+++ b/server/lib/videoContinuity.js@@ -0,0 +1,167 @@+/**+ * Video Gen — how chunk N+1 of a chained render is conditioned on chunk N.+ *+ * Two strategies exist, and which one a request gets is decided here so the+ * route, `prepareParams.js` and the chain orchestrator in `local.js` can't+ * drift on the rule:+ *+ * 'frame' — extract the prior chunk's LAST FRAME and run chunk N+1 as+ * image-to-video off that still. Works on every runtime, but the+ * model gets a pose with no velocity, so motion visibly stalls+ * and restarts at every seam.+ * 'window' — hand the prior chunk's LAST N FRAMES to LTX-2's+ * ExtendPipeline.extend_from_video, which conditions on that+ * window's latent (motion AND appearance) instead of a still.+ * Only the `ltx2` runtime has the pipeline, so every other+ * runtime degrades to 'frame'.+ *+ * Why a WINDOW and not the whole prior clip. `extend_from_video` returns+ * `source + extension` (see `retake.py`: `F_total = F_source + extend_frames`),+ * so feeding it the previous chunk's full output makes chunk N+1 contain+ * everything chunk N did, and stitching the chunks then repeats that content+ * once per hop while per-chunk cost grows with every hop. A fixed-size tail+ * window makes the conditioning cost constant, keeps only the most recent+ * appearance state (so exposure/color drift doesn't compound from the clip's+ * opening frames), and — because we know how much of the output is echoed+ * context — lets the orchestrator trim the echo back off before stitching.+ *+ * Pure and dependency-free: `prepareParams.js` imports it without dragging in+ * `local.js`, which the module suites mock wholesale.+ */++/**+ * Default tail-window size, in pixel frames.+ *+ * ~1 second at 24fps, and just under 3 LTX latent frames (the VAE compresses+ * 8 pixel frames per latent), which is enough for the model to read a motion+ * vector out of the context rather than a single pose. Community reports on+ * long-form LTX chaining converge on roughly this size: smaller windows read+ * as a still and reintroduce the seam, larger ones cost more per hop without+ * visibly improving continuity.+ */+export const DEFAULT_CONTEXT_FRAMES = 22;++/**+ * `0` is a real, supported value — "condition on the last frame only", i.e.+ * opt back into the 'frame' strategy on a runtime that could do better. It is+ * NOT the same as an absent value, which takes DEFAULT_CONTEXT_FRAMES.+ */+export const MIN_CONTEXT_FRAMES = 0;++/**+ * Ceiling on the tail window. 121 frames is ~5s at 24fps and 16 LTX latent+ * frames — past that the context costs more to encode and denoise than the+ * extension itself, and LTX's own extend API caps context + extension at 505+ * frames total, which a chained render can reach from both ends at once.+ */+export const MAX_CONTEXT_FRAMES = 121;++/**+ * The LTX-2 VAE's temporal compression: one latent frame decodes to 8 pixel+ * frames (the first latent carries the extra anchor frame, which is why a+ * clip's pixel length is 8k+1 rather than 8k).+ *+ * This is a property of LTX-2's VAE, not a general one — everything derived+ * from it below is only valid for the runtime in CONTEXT_WINDOW_RUNTIMES. A+ * second runtime joining that set has to bring its own stride, and the failure+ * mode if it doesn't is a wrongly-sized trim rather than an error, so make the+ * stride per-runtime at that point instead of reusing this constant.+ */+export const LATENT_FRAME_STRIDE = 8;++/**+ * Runtimes whose helper can condition on a source *video* rather than a still.+ * `ltx2` routes to ExtendPipeline.extend_from_video; `minimax_h3`, `wan22`,+ * `hunyuan` and `mlx_video` have no equivalent and take the 'frame' path.+ *+ * Kept here rather than in `videoGen/modeContract.js` — that module's "declare+ * every runtime gate in one table" rule is about mode/source pairings that+ * REJECT a request at two boundaries, which is what had drifted. This never+ * rejects: an unsupported runtime silently gets the 'frame' path.+ *+ * And deliberately NOT derived from the registry's `supportedModes` (#3737),+ * even though every entry now resolves one: `mlx_video` declares `'extend'`+ * too, but implements it by extracting a last frame and running i2v — there is+ * no pipeline there to hand a video to. `supportedModes.includes('extend')`+ * would therefore route mlx_video chains down a path its helper cannot honor.+ * The two questions genuinely differ: "can the user pick Extend mode?" vs "can+ * this runtime condition on a source VIDEO?", and only the latter belongs here.+ */+export const CONTEXT_WINDOW_RUNTIMES = new Set(['ltx2']);++/** True when the model's runtime exposes a video-conditioned extend path. */+export const supportsContextWindow = (model) => CONTEXT_WINDOW_RUNTIMES.has(model?.runtime);++/**+ * Normalize a caller-supplied context-frame count.+ *+ * Absent (`null`/`undefined`/`''`) → the default. An explicit `0` → 0, which+ * the strategy resolver reads as "last frame only" — conflating the two would+ * make it impossible to opt out of windowed continuation once it's the+ * default. Anything non-finite falls back to the default rather than+ * poisoning the arithmetic downstream; finite values clamp into range.+ */+export const resolveContextFrames = (requested) => {+ if (requested == null || requested === '') return DEFAULT_CONTEXT_FRAMES;+ const n = Number(requested);+ if (!Number.isFinite(n)) return DEFAULT_CONTEXT_FRAMES;+ return Math.min(MAX_CONTEXT_FRAMES, Math.max(MIN_CONTEXT_FRAMES, Math.floor(n)));+};++/**+ * The strategy a chained render will actually use.+ *+ * `contextFrames` is the already-resolved count (call `resolveContextFrames`+ * first). A model whose runtime has no extend pipeline always gets 'frame',+ * whatever the caller asked for — the count is simply ignored rather than+ * rejected, so switching models mid-form can't strand the request.+ */+export const resolveContinuityStrategy = ({ model, contextFrames }) => (+ contextFrames > 0 && supportsContextWindow(model) ? 'window' : 'frame'+);++/**+ * Latent frames to request from ExtendPipeline for a chunk that should add+ * `numFrames` pixel frames. No leading +1: the context window already supplies+ * the anchor frame. Floors at 1 so a too-small request still renders something.+ */+export const extendLatentFrames = (numFrames) => {+ const n = Number(numFrames);+ if (!Number.isFinite(n)) return 1;+ return Math.max(1, Math.floor(n / LATENT_FRAME_STRIDE));+};++/** Pixel frames an `extendLatents`-latent extension contributes to the output. */+export const extendedPixelFrames = (extendLatents) => Math.max(0, Math.floor(Number(extendLatents) || 0)) * LATENT_FRAME_STRIDE;++/**+ * How many leading frames of an extend render are echoed context that the+ * stitched timeline already contains.+ *+ * Derived from the RENDERED output rather than from the context clip we fed+ * in, because the VAE snaps the encoded source to a latent boundary — the+ * echo is generally a few frames longer than the window we supplied. Since+ * `extend()` appends exactly `extend_frames` latents, everything before the+ * last `extendLatents × 8` frames is echo.+ *+ * Returns 0 when the numbers don't support a trim (unprobeable output, an+ * output no longer than the extension, a nonsensical count) — the caller must+ * treat 0 as "leave the chunk alone", never as "trim everything".+ */+export const contextPrefixFrames = ({ totalFrames, extendLatents }) => {+ const total = Number(totalFrames);+ const newFrames = extendedPixelFrames(extendLatents);+ if (!Number.isFinite(total) || total <= 0 || newFrames <= 0) return 0;+ return Math.max(0, total - newFrames);+};++/**+ * First frame index of an `frames`-long tail window in a `totalFrames` clip.+ * Clamps at 0 so a window larger than the clip just keeps the whole clip.+ */+export const tailWindowStartFrame = ({ totalFrames, frames }) => {+ const total = Number(totalFrames);+ const want = Number(frames);+ if (!Number.isFinite(total) || !Number.isFinite(want)) return 0;+ return Math.max(0, Math.floor(total) - Math.floor(want));+};diff --git a/server/lib/videoContinuity.parity.test.js b/server/lib/videoContinuity.parity.test.jsnew file mode 100644index 0000000000..a91a66c3cb--- /dev/null+++ b/server/lib/videoContinuity.parity.test.js@@ -0,0 +1,60 @@+/**+ * Cross-package parity for the chained-render continuation contract.+ *+ * `server/lib/videoContinuity.js` is the source of truth — it defaults, clamps,+ * and picks the strategy. `client/src/lib/videoGenParams.js` carries a small+ * mirror of the parts the Continuity picker has to display: the default window+ * size, the option list, and which runtimes can use a window at all.+ *+ * This suite imports BOTH and asserts they agree, so an unmirrored server-side+ * change fails CI here rather than surfacing as a UI that quietly disagrees+ * with what renders. The concrete failures it prevents: the picker preselecting+ * one window while the server renders another (the user never sees which they+ * got), an option outside the route's accepted range 400ing only after Generate+ * is pressed, and the control appearing for a runtime whose renders ignore it.+ *+ * It lives server-side, matching `icLoraWeights.parity.test.js`, because the+ * pure client mirror loads fine under the node runner while the reverse isn't+ * guaranteed.+ */++import { describe, it, expect } from 'vitest';+import {+ DEFAULT_CONTEXT_FRAMES, MIN_CONTEXT_FRAMES, MAX_CONTEXT_FRAMES,+ supportsContextWindow as serverSupportsContextWindow,+} from './videoContinuity.js';+import {+ DEFAULT_CONTEXT_FRAMES as CLIENT_DEFAULT_CONTEXT_FRAMES,+ CONTEXT_FRAME_OPTIONS,+ supportsContextWindow as clientSupportsContextWindow,+} from '../../client/src/lib/videoGenParams.js';++describe('continuation context window — server/client parity', () => {+ it('mirrors the default window size', () => {+ expect(CLIENT_DEFAULT_CONTEXT_FRAMES).toBe(DEFAULT_CONTEXT_FRAMES);+ });++ it('offers the default as a selectable option', () => {+ // A default the picker can't display leaves the select with no matching+ // <option>, which renders as a blank control.+ expect(CONTEXT_FRAME_OPTIONS).toContain(DEFAULT_CONTEXT_FRAMES);+ });++ it('keeps every option inside the range the route accepts', () => {+ for (const n of CONTEXT_FRAME_OPTIONS) {+ expect(n).toBeGreaterThanOrEqual(MIN_CONTEXT_FRAMES);+ expect(n).toBeLessThanOrEqual(MAX_CONTEXT_FRAMES);+ }+ });++ it('offers 0 — last-frame chaining is a real choice, not "unset"', () => {+ expect(CONTEXT_FRAME_OPTIONS).toContain(0);+ });++ it('agrees on which runtimes can use a window', () => {+ for (const runtime of ['ltx2', 'mlx_video', 'minimax_h3', 'wan22', 'hunyuan', undefined]) {+ expect(clientSupportsContextWindow({ runtime })).toBe(serverSupportsContextWindow({ runtime }));+ }+ expect(clientSupportsContextWindow(null)).toBe(serverSupportsContextWindow(null));+ });+});diff --git a/server/lib/videoContinuity.test.js b/server/lib/videoContinuity.test.jsnew file mode 100644index 0000000000..8c9879e2df--- /dev/null+++ b/server/lib/videoContinuity.test.js@@ -0,0 +1,130 @@+import { describe, it, expect } from 'vitest';+import {+ DEFAULT_CONTEXT_FRAMES, MIN_CONTEXT_FRAMES, MAX_CONTEXT_FRAMES, LATENT_FRAME_STRIDE,+ resolveContextFrames, resolveContinuityStrategy, supportsContextWindow,+ extendLatentFrames, extendedPixelFrames, contextPrefixFrames, tailWindowStartFrame,+} from './videoContinuity.js';++describe('resolveContextFrames', () => {+ it('defaults when the value is absent', () => {+ for (const absent of [null, undefined, '']) {+ expect(resolveContextFrames(absent)).toBe(DEFAULT_CONTEXT_FRAMES);+ }+ });++ it('preserves an explicit 0 instead of collapsing it into the default', () => {+ // This is the whole sentinel discipline: 0 means "last frame only", and+ // treating it as absent would make windowed continuation impossible to+ // turn off once it became the default.+ expect(resolveContextFrames(0)).toBe(0);+ expect(resolveContextFrames('0')).toBe(0);+ });++ it('clamps into range rather than rejecting', () => {+ expect(resolveContextFrames(-5)).toBe(MIN_CONTEXT_FRAMES);+ expect(resolveContextFrames(MAX_CONTEXT_FRAMES + 500)).toBe(MAX_CONTEXT_FRAMES);+ });++ it('floors a fractional value', () => {+ expect(resolveContextFrames(22.9)).toBe(22);+ });++ it('falls back to the default for a non-numeric value', () => {+ // NaN would otherwise poison every frame index derived from it.+ expect(resolveContextFrames('lots')).toBe(DEFAULT_CONTEXT_FRAMES);+ expect(resolveContextFrames(Infinity)).toBe(DEFAULT_CONTEXT_FRAMES);+ });+});++describe('supportsContextWindow / resolveContinuityStrategy', () => {+ it('only ltx2 has an extend pipeline to feed a window to', () => {+ expect(supportsContextWindow({ runtime: 'ltx2' })).toBe(true);+ for (const runtime of ['mlx_video', 'minimax_h3', 'wan22', 'hunyuan']) {+ expect(supportsContextWindow({ runtime })).toBe(false);+ }+ expect(supportsContextWindow(null)).toBe(false);+ expect(supportsContextWindow({})).toBe(false);+ });++ it('is not the same question as "declares the extend mode"', () => {+ // #3737 resolves a supportedModes list for every entry, and mlx_video's+ // includes 'extend' — but it implements that by extracting a last frame and+ // running i2v, with no pipeline to hand a video to. Deriving this from+ // supportedModes would route mlx_video chains into a window path its helper+ // cannot honor, so the runtime check has to stay a separate fact.+ const mlx = { runtime: 'mlx_video', supportedModes: ['text', 'image', 'fflf', 'extend'] };+ expect(mlx.supportedModes).toContain('extend');+ expect(supportsContextWindow(mlx)).toBe(false);+ });++ it('windows when the runtime supports it and a window was asked for', () => {+ expect(resolveContinuityStrategy({ model: { runtime: 'ltx2' }, contextFrames: 22 })).toBe('window');+ });++ it('falls back to last-frame chaining, never an error, on an unsupported runtime', () => {+ // Silently degrading is deliberate — switching models mid-form must not+ // strand a request that was legal a moment ago.+ expect(resolveContinuityStrategy({ model: { runtime: 'minimax_h3' }, contextFrames: 22 })).toBe('frame');+ expect(resolveContinuityStrategy({ model: null, contextFrames: 22 })).toBe('frame');+ });++ it('honors an explicit 0 as an opt-out on a supported runtime', () => {+ expect(resolveContinuityStrategy({ model: { runtime: 'ltx2' }, contextFrames: 0 })).toBe('frame');+ });+});++describe('extend latent arithmetic', () => {+ it('converts a pixel-frame request to latents with no leading +1', () => {+ // The context window already supplies the anchor frame, so this is a plain+ // divide — an off-by-one here desyncs the trim from what was rendered.+ expect(extendLatentFrames(97)).toBe(12);+ expect(extendLatentFrames(25)).toBe(3);+ });++ it('floors at one latent so a tiny request still renders something', () => {+ expect(extendLatentFrames(4)).toBe(1);+ expect(extendLatentFrames(0)).toBe(1);+ expect(extendLatentFrames(null)).toBe(1);+ expect(extendLatentFrames('nope')).toBe(1);+ });++ it('round-trips back to pixel frames at the VAE stride', () => {+ expect(extendedPixelFrames(3)).toBe(3 * LATENT_FRAME_STRIDE);+ expect(extendedPixelFrames(0)).toBe(0);+ expect(extendedPixelFrames(-4)).toBe(0);+ });+});++describe('contextPrefixFrames', () => {+ it('measures the echo as everything before the newly-generated frames', () => {+ // A 25-frame render that appended 3 latents (24 frames) opens with 1 frame+ // of echoed context.+ expect(contextPrefixFrames({ totalFrames: 25, extendLatents: 3 })).toBe(1);+ expect(contextPrefixFrames({ totalFrames: 120, extendLatents: 12 })).toBe(24);+ });++ it('returns 0 — "leave it alone" — when the numbers do not support a trim', () => {+ // An unprobeable output must never be read as "trim everything", which+ // would delete the chunk's real content.+ expect(contextPrefixFrames({ totalFrames: null, extendLatents: 3 })).toBe(0);+ expect(contextPrefixFrames({ totalFrames: 0, extendLatents: 3 })).toBe(0);+ expect(contextPrefixFrames({ totalFrames: 24, extendLatents: 3 })).toBe(0);+ expect(contextPrefixFrames({ totalFrames: 10, extendLatents: 3 })).toBe(0);+ expect(contextPrefixFrames({ totalFrames: 100, extendLatents: 0 })).toBe(0);+ });+});++describe('tailWindowStartFrame', () => {+ it('starts the window `frames` back from the end', () => {+ expect(tailWindowStartFrame({ totalFrames: 97, frames: 22 })).toBe(75);+ });++ it('keeps the whole clip when the window is longer than it', () => {+ expect(tailWindowStartFrame({ totalFrames: 16, frames: 22 })).toBe(0);+ });++ it('falls back to frame 0 on unusable inputs', () => {+ expect(tailWindowStartFrame({ totalFrames: null, frames: 22 })).toBe(0);+ expect(tailWindowStartFrame({ totalFrames: 97, frames: NaN })).toBe(0);+ });+});diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex fdccc4b467..c8f467cb7e 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -16,6 +16,7 @@ import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.jimport { uploadFields } from '../lib/multipart.js';import { PATHS } from '../lib/fileUtils.js';import { grokVideoDurationSchema, videoModelTermsSchema } from '../lib/validation.js';+import { MIN_CONTEXT_FRAMES, MAX_CONTEXT_FRAMES } from '../lib/videoContinuity.js';import {VIDEO_BACKEND_DISCLOSURES, isVideoModelTermsAccepted, acceptedVideoModelTerms,videoModelTermsGateId, videoModelTermsError,@@ -204,6 +205,12 @@ const generateBodySchema = z.object({// string multipart sends for a single repeated key — a bare string is still// accepted as a one-entry list for hand-rolled/JSON clients.chunkPrompts: z.preprocess(listPreprocess, z.array(z.string().max(8000)).max(MAX_VIDEO_CHUNKS).optional()),+ // How many of the prior chunk's frames each subsequent chunk conditions on.+ // A window carries motion across the seam where a single still can't; `0`+ // opts back into last-frame chaining, and absence takes the default. Only+ // meaningful on a runtime with an extend pipeline — elsewhere it's ignored,+ // not rejected. See lib/videoContinuity.js.+ contextFrames: optionalInt(MIN_CONTEXT_FRAMES, MAX_CONTEXT_FRAMES, 'contextFrames'),// History id of a prior render to extend natively (ltx2 runtime only —// routes through ExtendPipeline.extend_from_video which conditions on// the entire source video's latent rather than a single last frame).@@ -923,7 +930,7 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {pythonPath, effectiveModelId, mode,sourceImagePath, lastImagePath, audioFilePath, icReferencePaths,resolvedKeyframes, extendFromVideoPath,- uploadedTempPath, uploadedTempPaths, loras, effectiveChunks, effectiveChunkPrompts,+ uploadedTempPath, uploadedTempPaths, loras, effectiveChunks, effectiveChunkPrompts, effectiveContextFrames,} = prepared;// Enqueue rather than spawn synchronously — the mediaJobQueue worker will@@ -957,6 +964,10 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {// key is simply absent from job.params then, so a resumed form restores no// stale beats. See prepareVideoGenParams for the normalization....(effectiveChunkPrompts ? { chunkPrompts: effectiveChunkPrompts } : {}),+ // Undefined for a non-chained request, so job.params doesn't carry a knob+ // that couldn't have applied. `0` is a real value here (last-frame+ // chaining) and must survive — see resolveContextFrames.+ ...(effectiveContextFrames != null ? { contextFrames: effectiveContextFrames } : {}),loras,icReferencePaths,icStrength: body.icStrength,@@ -991,7 +1002,7 @@ const ACTIVE_JOB_PARAM_FIELDS = ['prompt', 'negativePrompt', 'modelId','width', 'height', 'numFrames', 'fps','steps', 'guidanceScale', 'seed',- 'tiling', 'disableAudio', 'mode', 'chunks', 'chunkPrompts', 'imageStrength',+ 'tiling', 'disableAudio', 'mode', 'chunks', 'chunkPrompts', 'contextFrames', 'imageStrength','audioStartSec',// Grok jobs (#2859 phase 2): the semantic t2v/i2v mode ('mode' holds the// 'grok' discriminator for them) and the clip duration — both plaindiff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex c357f1ccb4..d8ea372f4b 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import express from 'express';import { request } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';+import { DEFAULT_CONTEXT_FRAMES, MAX_CONTEXT_FRAMES } from '../lib/videoContinuity.js';const installProcess = vi.hoisted(() => {const spawn = vi.fn();@@ -1105,6 +1106,66 @@ describe('videoGen routes', () => {expect(r.body.error).toMatch(/chunks/i);});+ it('defaults the continuation context window on a chained request', async () => {+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'a long shot',+ chunks: 3,+ });+ expect(r.status).toBe(200);+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ params: expect.objectContaining({ chunks: 3, contextFrames: DEFAULT_CONTEXT_FRAMES }),+ }));+ });++ it('forwards an explicit context window', async () => {+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'a long shot',+ chunks: 2,+ contextFrames: 45,+ });+ expect(r.status).toBe(200);+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ params: expect.objectContaining({ contextFrames: 45 }),+ }));+ });++ it('preserves contextFrames: 0 — last-frame chaining, not "unset"', async () => {+ // Dropping the 0 would silently upgrade the render back to a window and+ // give the user a materially different clip than they asked for.+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'a long shot',+ chunks: 2,+ contextFrames: 0,+ });+ expect(r.status).toBe(200);+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ params: expect.objectContaining({ contextFrames: 0 }),+ }));+ });++ it('omits contextFrames entirely when the request does not chain', async () => {+ // Persisting a knob that could never have applied would replay into the+ // form on resume as if the user had chosen it.+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'a single render',+ contextFrames: 45,+ });+ expect(r.status).toBe(200);+ const { params } = mediaJobQueue.enqueueJob.mock.calls.at(-1)[0];+ expect(params.chunks).toBe(1);+ expect(params).not.toHaveProperty('contextFrames');+ });++ it('rejects a context window past the cap', async () => {+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'a long shot',+ chunks: 2,+ contextFrames: MAX_CONTEXT_FRAMES + 1,+ });+ expect(r.status).toBe(400);+ expect(r.body.error).toMatch(/contextFrames/i);+ });+it('forwards per-chunk prompt beats, keeping a blank entry as a fallback marker', async () => {const r = await request(app).post('/api/video-gen/').send({prompt: 'a long shot',diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex 4286f66e66..799bc4b8f6 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -25,7 +25,15 @@ 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, extractEvaluationFrames } from '../../lib/ffmpeg.js';+import {+ findFfmpeg, safeUnder, generateThumbnail, optimizeForStreaming, upscaleVideo2x,+ extractEvaluationFrames, probeFrameCount, trimVideoFromFrame,+ H264_ENCODE_ARGS, AAC_ENCODE_ARGS,+} from '../../lib/ffmpeg.js';+import {+ resolveContextFrames, resolveContinuityStrategy, extendLatentFrames,+ contextPrefixFrames, tailWindowStartFrame,+} from '../../lib/videoContinuity.js';import { hfChildEnv } from '../../lib/hfToken.js';import { inspectModelCache, findCachedRepoFile } from '../../lib/hfCache.js';import { safeChildProcessEnv } from '../../lib/processEnv.js';@@ -507,12 +515,11 @@ const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames}if (helperMode === 'extend') {args.push('--extend-from-video', extendFromVideoPath);- // Translate the user's requested numFrames into a latent-frame count- // for ExtendPipeline. 1 latent ≈ 8 pixel frames, with no leading +1- // because the source already supplies the anchor frame. Floor at 1- // so a too-small numFrames still produces something.- const extendLatents = Math.max(1, Math.floor(Number(numFrames) / 8));- args.push('--extend-frames', String(extendLatents));+ // Translate the user's requested numFrames into a latent-frame count for+ // ExtendPipeline. Shared with the chain orchestrator, which needs the same+ // number to work out how much of the render is echoed source (see+ // `lib/videoContinuity.js`) — the two MUST agree or the trim is wrong.+ args.push('--extend-frames', String(extendLatentFrames(numFrames)));args.push('--extend-direction', 'after');}if (helperMode === 'a2v') {@@ -1614,11 +1621,25 @@ 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.+// Generate a chain of N video chunks, each conditioned on the one before it,+// 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.+//+// Continuation strategy (`lib/videoContinuity.js`, tunable via+// `contextFrames`):+//+// 'window' — chunk N+1 is an `extend` render conditioned on a clip cut from+// the last `contextFrames` frames of chunk N, so the model inherits the+// scene's MOTION, not just its final pose. Requires a runtime with an+// extend pipeline (ltx2 today) and applies whatever mode the chain started+// in. Because extend returns `source + extension`, each windowed chunk+// opens with an echo of the window; that echo is measured and cut back off+// before the stitch, so the timeline holds each frame exactly once.+// 'frame' — the historical hop: extract chunk N's last frame and run chunk+// N+1 as image-to-video off that still. What every other runtime gets, and+// what `contextFrames: 0` opts back into.//// 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@@ -1633,7 +1654,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// chunk i's prompt, and a null/blank/missing entry falls back to the main// `prompt`. It is destructured out of `rest` on purpose so the per-chunk// generateVideo() calls below never receive the whole list.-export async function generateChainedVideo({ chunks, chunkPrompts, jobId: outerJobId, ...rest }) {+export async function generateChainedVideo({ chunks, chunkPrompts, contextFrames, jobId: outerJobId, ...rest }) {const totalChunks = Number(chunks) || 1;if (totalChunks === 1) {return generateVideo({ jobId: outerJobId, ...rest });@@ -1644,6 +1665,20 @@ export async function generateChainedVideo({ chunks, chunkPrompts, jobId: outerJconst chainError = videoChainUnsupportedError(chainModel);if (chainError) throw chainError;+ // How chunk N+1 sees chunk N. 'window' hands LTX-2's extend pipeline the+ // prior chunk's last `windowFrames` frames (motion + appearance); 'frame'+ // is the historical single-still i2v hop, and is what every runtime without+ // an extend pipeline resolves to. See lib/videoContinuity.js.+ const windowFrames = resolveContextFrames(contextFrames);+ const continuity = resolveContinuityStrategy({ model: chainModel, contextFrames: windowFrames });+ // Mirrors generateVideo's own default — the trim math converts frame indices+ // to audio timestamps, so it can't run on an undefined rate.+ const chainFps = Number(rest.fps) > 0 ? Number(rest.fps) : 24;+ // Latents each chained chunk asks ExtendPipeline to append. buildLtx2Args+ // derives the same number from the same numFrames; the trim below subtracts+ // the pixel frames they decode to, so the two have to stay in step.+ const chunkExtendLatents = extendLatentFrames(rest.numFrames);+const chainState = { stopped: false };activeChain = chainState;@@ -1655,14 +1690,24 @@ export async function generateChainedVideo({ chunks, chunkPrompts, jobId: outerJconst chunkIds = [];let currentSource = rest.sourceImagePath;- // For extend mode, track the prior chunk's full video path so ExtendPipeline- // can condition on the entire clip (motion + visual content) rather than just- // a single last frame.- let currentExtendFromVideo = rest.extendFromVideoPath ?? null;- // First chunk preserves the user's mode (text, image, or extend). Subsequent- // chunks are conditioned differently depending on the original mode:- // - extend: keep mode='extend', pass prior chunk's full video as extendFromVideoPath- // - all others: image-conditioned on the previous chunk's extracted last frame+ // 'window' continuation: the tail slice of the prior chunk that the next one+ // conditions on. A fresh short clip per hop, NOT the prior chunk's whole+ // output — extend_from_video returns `source + extension`, so conditioning+ // on the full clip would make every chunk re-contain the one before it (the+ // stitch then repeats that content once per hop) while the conditioning cost+ // grew with the chain. Written under tmpdir and deleted when the chain ends.+ let currentContextClip = null;+ const contextClipPaths = [];+ // Post-trim frame count for each chunk we cut a context prefix off. Two jobs:+ // a non-empty map means at least one chunk was re-encoded (so the concat can+ // no longer stream-copy), and it tells stitchVideos the real lengths — the+ // chunks' own history entries record the frame count that was RENDERED, which+ // is a render parameter Remix reuses, not a measurement of the trimmed file.+ const trimmedFrameCounts = new Map();+ // First chunk always preserves the user's mode (text, image, fflf or extend)+ // and is never trimmed: in an extend chain its output is `source clip ++ // extension`, and the source clip belongs in the result exactly once — here.+ // Chunks 1+ take the resolved continuity path instead.const firstMode = rest.mode || (currentSource ? 'image' : 'text');const runChunk = (i) => new Promise((resolve, reject) => {@@ -1712,7 +1757,11 @@ export async function generateChainedVideo({ chunks, chunkPrompts, jobId: outerJ? Number(rest.seed) + i: undefined;- const isExtendChain = firstMode === 'extend' && i > 0;+ // Chunks 1+ on a window-continuity chain re-enter as extend renders+ // conditioned on the tail clip built after the previous chunk, whatever+ // mode the chain STARTED in — a text or i2v chain gets the same motion+ // carry-over an extend chain does, instead of restarting from a still.+ const isWindowHop = continuity === 'window' && i > 0;// Per-chunk beat (#3695). `chunkPrompts` is already normalized (blank →// null) by prepareVideoGenParams, but re-guard on emptiness here too so a// direct service caller can't hand a chunk an empty prompt — an absent beat@@ -1725,22 +1774,21 @@ export async function generateChainedVideo({ chunks, chunkPrompts, jobId: outerJprompt: chunkPrompt,seed: chunkSeed,jobId: innerJobId,- // extend chain: subsequent chunks condition on the prior clip's full- // video — ExtendPipeline.extend_from_video needs the entire video, not- // just the last frame, to avoid reintroducing seams.- // image/text chain: condition on the extracted last frame as before.- sourceImagePath: isExtendChain ? null : currentSource,- extendFromVideoPath: isExtendChain ? currentExtendFromVideo : (i === 0 ? rest.extendFromVideoPath : null),+ // window hop: condition on the tail clip cut from the prior chunk, so+ // the model reads motion out of it rather than a single static pose.+ // frame hop: condition on the prior chunk's extracted last frame.+ sourceImagePath: isWindowHop ? null : currentSource,+ extendFromVideoPath: isWindowHop ? currentContextClip : (i === 0 ? rest.extendFromVideoPath : null),// Only the first chunk consumes the user's uploadedTempPath (durable- // copy under data/uploads). Later chunks use a frame extracted from a- // prior render (image chain) or the prior chunk's video (extend chain).+ // copy under data/uploads). Later chunks condition on the prior chunk+ // instead — a tail window (window hop) or an extracted frame (frame hop).uploadedTempPath: i === 0 ? rest.uploadedTempPath : null,uploadedTempPaths: i === 0 ? (rest.uploadedTempPaths || []) : [],hidden: true,- mode: isExtendChain ? 'extend' : (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 (or full video- // for extend mode).+ mode: isWindowHop ? 'extend' : (i === 0 ? firstMode : 'image'),+ // After the first chunk, drop FFLF-style last image — chained+ // continuation conditions on one thing, the tail of the chunk before it,+ // and has no second anchor to pin an end frame to.lastImagePath: i === 0 ? rest.lastImagePath : null,// Multi-keyframe interpolation only makes sense for the first chunk// (the user pinned specific frame indices in a single clip). Subsequent@@ -1753,14 +1801,24 @@ export async function generateChainedVideo({ chunks, chunkPrompts, jobId: outerJ});});+ // The conditioning windows are scratch input to the next chunk, never+ // output — drop them on every terminal path (both of which always run) so a+ // long chain doesn't leave a trail of clips in tmpdir. Best-effort and+ // fire-and-forget: a leftover temp file must never fail a finished render.+ const cleanupContextClips = () => {+ for (const p of contextClipPaths) unlink(p).catch(() => {});+ contextClipPaths.length = 0;+ };const finishOk = (payload) => {if (activeChain === chainState) activeChain = null;+ cleanupContextClips();videoGenEvents.emit('completed', { generationId: outerJobId, ...payload });broadcastSse(outerJob, { type: 'complete', result: payload });closeJobAfterDelay(jobs, outerJobId);};const finishFail = (error) => {if (activeChain === chainState) activeChain = null;+ cleanupContextClips();videoGenEvents.emit('failed', { generationId: outerJobId, error });broadcastSse(outerJob, { type: 'error', error });closeJobAfterDelay(jobs, outerJobId);@@ -1782,27 +1840,76 @@ export async function generateChainedVideo({ chunks, chunkPrompts, jobId: outerJfinishFail(completed.error);return;}- if (i < totalChunks - 1) {- if (firstMode === 'extend') {- // For extend chains, subsequent chunks condition on the entire prior- // clip via ExtendPipeline.extend_from_video — no frame extraction- // needed. The chunk's output file is always <innerJobId>.mp4 under- // PATHS.videos (see generateVideo: filename = `${jobId}.mp4`).- currentExtendFromVideo = join(PATHS.videos, `${chunkIds[chunkIds.length - 1]}.mp4`);- } else {- // extractLastFrame caches by id, so re-clicks (e.g. from gallery- // "Continue") don't re-spawn ffmpeg.+ // The chunk's output file is always <innerJobId>.mp4 under PATHS.videos+ // (see generateVideo: filename = `${jobId}.mp4`).+ const chunkId = chunkIds[chunkIds.length - 1];+ const chunkPath = join(PATHS.videos, `${chunkId}.mp4`);++ if (continuity === 'window') {+ // One probe serves both cuts below. The trim rewrites chunkPath, so+ // `frames` is decremented rather than re-probed — `ffmpeg trim` keeps+ // exactly [prefix, total), which makes the new length arithmetic, and+ // probeFrameCount can fall back to a full decode pass.+ // eslint-disable-next-line no-await-in-loop+ let frames = await probeFrameCount(chunkPath);++ // A window hop's render is `context window + new frames`. The window is+ // the tail of the chunk before it, which the stitched timeline already+ // holds, so cut it back off before this chunk joins the concat. Measured+ // from the RENDERED length rather than from the window we supplied: the+ // VAE snaps the encoded context up to a latent boundary, so the echo is+ // usually a few frames longer than what we handed in.+ if (i > 0) {+ const prefix = contextPrefixFrames({ totalFrames: frames, extendLatents: chunkExtendLatents });+ if (prefix > 0) {+ // eslint-disable-next-line no-await-in-loop+ const trim = await trimVideoFromFrame(chunkPath, chunkPath, { startFrame: prefix, fps: chainFps });+ if (trim.ok) {+ frames -= prefix;+ trimmedFrameCounts.set(chunkId, frames);+ } else {+ // Degrade rather than throw away the whole chain: an untrimmed+ // chunk costs the viewer a ~1s repeat at one seam, where failing+ // here would discard every chunk already rendered.+ console.log(`⚠️ Chunk ${i + 1}/${totalChunks} context trim failed, seam will repeat ${prefix} frames: ${trim.reason}`);+ }+ } else {+ console.log(`⚠️ Chunk ${i + 1}/${totalChunks} context prefix unmeasurable (frames=${frames ?? 'unknown'}), leaving it untrimmed`);+ }+ }++ if (i < totalChunks - 1) {+ // Cut the next hop's conditioning window off this chunk's tail. Both+ // the count and the cut clamp: a window longer than the chunk simply+ // conditions on all of it.+ const contextPath = join(tmpdir(), `chaincontext-${chunkId}.mp4`);// eslint-disable-next-line no-await-in-loop- const frame = await extractLastFrame(chunkIds[chunkIds.length - 1]).catch((err) => ({ error: err.message }));- if (frame?.error) {+ const cut = await trimVideoFromFrame(chunkPath, contextPath, {+ startFrame: tailWindowStartFrame({ totalFrames: frames, frames: windowFrames }),+ fps: chainFps,+ });+ if (!cut.ok) {await setHistoryItemsHidden(chunkIds, true);- finishFail(`Failed to extract frame between chunks: ${frame.error}`);+ finishFail(`Failed to build the continuation context window between chunks: ${cut.reason}`);return;}- currentSource = join(PATHS.images, frame.filename);+ contextClipPaths.push(contextPath);+ currentContextClip = contextPath;+ }+ } else 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(chunkId).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',@@ -1813,6 +1920,13 @@ export async function generateChainedVideo({ chunks, chunkPrompts, jobId: outerJ// from — the individual chunk entries only ever hold their own resolved// prompt, which loses which of them were explicit beats vs. fallbacks.chunkPrompts: chunkPrompts?.some(Boolean) ? chunkPrompts : null,+ // A trimmed chunk was re-encoded, so it no longer shares an identical+ // codec/parameter set with its untrimmed siblings and the concat+ // demuxer's `-c copy` fast path can't be trusted across the mix.+ reencode: trimmedFrameCounts.size > 0,+ // Trimmed chunks are shorter on disk than the frame count they were+ // rendered at, so the stitched duration can't just sum the chunk records.+ frameCounts: trimmedFrameCounts.size ? trimmedFrameCounts : null,}).catch((err) => ({ error: err.message }));if (stitched?.error) {await setHistoryItemsHidden(chunkIds, true);@@ -1982,9 +2096,10 @@ export async function sampleEvaluationFrames(jobId, count = 5) {}// 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-// lets users stitch from a single model so this holds in practice.+// concat demuxer, stream-copy by default, so it's fast and lossless — but the+// inputs must then share codec/resolution. The Media History page already only+// lets users stitch from a single model so this holds in practice; a caller+// whose inputs have been re-encoded out of lockstep passes `reencode: true`.//// `opts` lets the chained-render code reuse the same ffmpeg path with a// different identity (id, filename prefix, history-link key, prompt, per-chunk@@ -1998,6 +2113,18 @@ export async function stitchVideos(videoIds, opts = {}) {// Per-chunk prompt beats to record on the stitched entry (#3695) — chained// renders only; a hand-stitched clip has no beats.chunkPrompts = null,+ // Normalize every input through one encoder instead of stream-copying.+ // Required when the inputs no longer share identical codec parameters —+ // the chained-render context trim re-encodes the chunks it cuts, and the+ // concat demuxer's `-c copy` needs its inputs to match exactly. Costs an+ // encode pass over the whole timeline, so it stays opt-in.+ reencode = false,+ // Optional `Map<videoId, frames>` overriding what an input contributes to+ // the stitched entry's `numFrames`. A history entry's `numFrames` is the+ // count the clip was RENDERED at — a render parameter Remix reuses — so a+ // caller that shortened a file on disk reports the real length here instead+ // of rewriting that record and changing what a Remix of it would produce.+ frameCounts = null,} = opts;if (!Array.isArray(videoIds) || videoIds.length < 2) {throw new ServerError('Need at least 2 videos to stitch', { status: 400, code: 'VALIDATION_ERROR' });@@ -2036,7 +2163,15 @@ export async function stitchVideos(videoIds, opts = {}) {// ffmpeg rejects — otherwise it leaks one file per failed stitch.try {await new Promise((resolve, reject) => {- const proc = spawn(ffmpeg, ['-f', 'concat', '-safe', '0', '-i', listFile, '-c', 'copy', '-y', outPath], { env: safeChildProcessEnv(), stdio: 'ignore' });+ const codecArgs = reencode+ // Matches trimVideoFromFrame's encoder so a trimmed chunk isn't+ // re-graded relative to its untrimmed siblings. `-c:a` is safe to pass+ // unconditionally — ffmpeg ignores it when the concatenated inputs+ // carry no audio stream at all (every chunk in a chain shares one+ // model and one audio setting, so they're never mixed).+ ? [...H264_ENCODE_ARGS, ...AAC_ENCODE_ARGS]+ : ['-c', 'copy'];+ const proc = spawn(ffmpeg, ['-f', 'concat', '-safe', '0', '-i', listFile, ...codecArgs, '-y', outPath], { env: safeChildProcessEnv(), stdio: 'ignore' });proc.on('close', (code) => code === 0 ? resolve() : reject(new ServerError('Stitch failed', { status: 500, code: 'FFMPEG_FAILED' })));proc.on('error', (err) => reject(new ServerError(`ffmpeg failed to spawn: ${err.message}`, { status: 500, code: 'FFMPEG_FAILED' })));});@@ -2055,7 +2190,7 @@ export async function stitchVideos(videoIds, opts = {}) {seed: videos[0].seed ?? 0,width: videos[0].width,height: videos[0].height,- numFrames: videos.reduce((sum, v) => sum + (v.numFrames || 0), 0),+ numFrames: videos.reduce((sum, v) => sum + (frameCounts?.get(v.id) ?? v.numFrames ?? 0), 0),fps: videos[0].fps,filename: outFilename,thumbnail: thumb,diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex 8b301b3177..2bc19f9a98 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -123,6 +123,14 @@ vi.mock('../../lib/ffmpeg.js', () => ({optimizeForStreaming: vi.fn(async () => {}),upscaleVideo2x: vi.fn(async () => ({ ok: true })),extractEvaluationFrames: vi.fn(async () => []),+ // Chained renders on a window-continuity runtime probe each chunk's length+ // and cut two clips from it (the echoed-context trim and the next hop's+ // conditioning window). 25 matches the numFrames the chain tests render, so+ // the prefix math below lands on a realistic value.+ H264_ENCODE_ARGS: ['-c:v', 'libx264'],+ AAC_ENCODE_ARGS: ['-c:a', 'aac'],+ probeFrameCount: vi.fn(async () => 25),+ trimVideoFromFrame: vi.fn(async (_videoPath, outPath) => ({ ok: true, outPath })),}));// hfChildEnv() carries the resolved token over the inherited child env; mocking here@@ -285,51 +293,66 @@ async function runChainAndCaptureArgs(chainParams, totalChunks) {// ─── tests ───────────────────────────────────────────────────────────────────-describe('generateChainedVideo — extend chain arg routing', () => {- it('chunks 2+ receive mode=extend with extendFromVideoPath pointing to the prior chunk output', async () => {- // Provide an initial extendFromVideoPath (the source clip the user wants to extend)- const sourceVideoPath = join(MOCK_PATHS.videos, 'original-video.mp4');+describe('generateChainedVideo — continuation strategy (context window vs last frame)', () => {+ // numFrames=25 → extendLatentFrames(25) = 3 latents = 24 new pixel frames,+ // and probeFrameCount is mocked at 25. So for each rendered chunk:+ // echoed context prefix = 25 − 24 = 1 frame (chunk 0 is never trimmed)+ // chunk 0's 22-frame window starts at 25 − 22 = 3+ // a TRIMMED chunk is 24 frames, so its window starts at 24 − 22 = 2+ // The 2-vs-3 difference is the point: the orchestrator probes each chunk+ // once and subtracts the trim, so it can't cut the window from a stale+ // pre-trim length (which would hand the next hop a short window).+ const CHUNK_FRAMES = 25;+ const EXPECTED_EXTEND_LATENTS = 3;+ const EXPECTED_PREFIX_START = 1;+ const WINDOW_START_UNTRIMMED = 3;+ const WINDOW_START_TRIMMED = 2;++ const flagValue = (args, flag) => (Array.isArray(args) && args.includes(flag)+ ? args[args.indexOf(flag) + 1] : null);- // We can't intercept generateVideo's exact params directly from outside- // the module (same-module calls), but we CAN assert the emitted 'started'- // event's metadata and the chain's internal state by tracking the chunk- // job ids and verifying the expected file paths.- //- // The real assertion is that the chain does NOT call extractLastFrame for- // extend mode. We verify this by ensuring ffmpeg's spawn is never called- // with the last-frame extraction arguments (only the video render spawn- // is called, not a frame-extract spawn).+ /**+ * Drive a chain and return everything the continuation path touches: the+ * argv of each chunk's render child, every trim the orchestrator asked for,+ * and the raw child_process spawns (which is where both extractLastFrame's+ * `-sseof` seek and the final concat show up).+ */+ async function runChain(chainParams, totalChunks) {+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');+ const { trimVideoFromFrame, probeFrameCount } = await import('../../lib/ffmpeg.js');const { spawn } = await import('child_process');- const spawnMock = vi.mocked(spawn);- spawnMock.mockClear();+ const { readJSONFile } = await import('../../lib/fileUtils.js');+ vi.mocked(spawnDetached).mockClear();+ vi.mocked(trimVideoFromFrame).mockClear();+ vi.mocked(probeFrameCount).mockClear();+ vi.mocked(spawn).mockClear();- const outerJobId = randomUUID();+ // extractLastFrame and stitchVideos both look their inputs up in history;+ // feed the chunk ids back as they start so the chain can advance.const innerJobIds = [];- const startedEvents = [];-- videoGenEvents.on('started', (e) => {- innerJobIds.push(e.generationId);- startedEvents.push(e);- });+ vi.mocked(readJSONFile).mockImplementation(async () =>+ innerJobIds.map((id) => ({ id, filename: `${id}.mp4` })),+ );+ videoGenEvents.on('started', (e) => innerJobIds.push(e.generationId));generateChainedVideo({- chunks: 3,- jobId: outerJobId,+ chunks: totalChunks,+ jobId: randomUUID(),pythonPath: '/usr/bin/python3',modelId: 'ltx2_unified',prompt: 'test prompt',width: 512,height: 512,- numFrames: 25,+ numFrames: CHUNK_FRAMES,fps: 24,- mode: 'extend',- extendFromVideoPath: sourceVideoPath,+ mode: 'text',sourceImagePath: null,+ extendFromVideoPath: null,lastImagePath: null,+ ...chainParams,});- // Drive all 3 chunks through the chain- for (let i = 0; i < 3; i++) {+ for (let i = 0; i < totalChunks; i++) {// eslint-disable-next-line no-await-in-loopawait new Promise((resolve) => {const check = () => {@@ -341,105 +364,125 @@ describe('generateChainedVideo — extend chain arg routing', () => {const id = innerJobIds[i];videoGenEvents.emit('completed', { generationId: id, filename: `${id}.mp4`, path: `/data/videos/${id}.mp4` });}-- // Wait for outer chain to settleawait new Promise((r) => setTimeout(r, 100));-videoGenEvents.removeAllListeners('started');- // All 3 chunks must have been started- expect(innerJobIds).toHaveLength(3);-- // Verify ffmpeg was NOT called with last-frame extraction args between chunks.- // extractLastFrame uses spawn(ffmpeg, ['-sseof', '-1.0', ...]) — the chain- // loop must skip this entirely for extend mode.- const ffmpegFrameExtractCalls = spawnMock.mock.calls.filter(- (args) => Array.isArray(args[1]) && args[1].includes('-sseof'),- );- expect(ffmpegFrameExtractCalls).toHaveLength(0);-- // Verify the expected per-chunk video output paths are resolvable:- // chunk i's output is PATHS.videos/<innerJobIds[i]>.mp4- const chunk0Output = join(MOCK_PATHS.videos, `${innerJobIds[0]}.mp4`);- const chunk1Output = join(MOCK_PATHS.videos, `${innerJobIds[1]}.mp4`);+ return {+ innerJobIds,+ renders: vi.mocked(spawnDetached).mock.calls.map(([, args]) => args),+ trims: vi.mocked(trimVideoFromFrame).mock.calls,+ spawns: vi.mocked(spawn).mock.calls,+ };+ }- // Chunk 1 should extend from chunk 0's video, chunk 2 from chunk 1's video.- // We verify this by checking that the path the chain would have computed- // (PATHS.videos/<id>.mp4) matches the known inner job ids.- expect(chunk0Output).toBe(join(MOCK_PATHS.videos, `${innerJobIds[0]}.mp4`));- expect(chunk1Output).toBe(join(MOCK_PATHS.videos, `${innerJobIds[1]}.mp4`));+ it('chains an ltx2 text render as extend hops conditioned on the prior chunk tail, not on a still', async () => {+ const { innerJobIds, renders, spawns } = await runChain({}, 3);++ expect(renders).toHaveLength(3);+ // Chunk 0 keeps the mode the user asked for.+ expect(flagValue(renders[0], '--mode')).toBe('text');+ // Chunks 1+ re-enter as extend renders reading the tail clip cut from the+ // chunk before them — a text chain now inherits motion across the seam+ // exactly the way an explicit extend chain does.+ for (const i of [1, 2]) {+ expect(flagValue(renders[i], '--mode')).toBe('extend');+ expect(flagValue(renders[i], '--extend-from-video'))+ .toBe(join(tmpdir(), `chaincontext-${innerJobIds[i - 1]}.mp4`));+ expect(flagValue(renders[i], '--extend-frames')).toBe(String(EXPECTED_EXTEND_LATENTS));+ }+ // The window replaces last-frame extraction entirely — no `-sseof` seek.+ expect(spawns.filter(([, args]) => Array.isArray(args) && args.includes('-sseof'))).toHaveLength(0);+ });++ it('cuts the echoed context back off each windowed chunk before stitching', async () => {+ // extend_from_video returns `source + extension`, so every hop after the+ // first opens with a replay of its conditioning window. Left in, the+ // stitched clip repeats ~1s of footage at every seam.+ const { innerJobIds, trims } = await runChain({}, 3);++ const chunkPath = (i) => join(MOCK_PATHS.videos, `${innerJobIds[i]}.mp4`);+ const trimFor = (src, dest) => trims.find(([from, to]) => from === src && to === dest);++ // Chunk 0 is never trimmed — nothing precedes it in the timeline.+ expect(trims.some(([, to]) => to === chunkPath(0))).toBe(false);+ // Chunks 1 and 2 are trimmed in place, dropping only the echoed prefix.+ for (const i of [1, 2]) {+ const trim = trimFor(chunkPath(i), chunkPath(i));+ expect(trim).toBeTruthy();+ expect(trim[2]).toMatchObject({ startFrame: EXPECTED_PREFIX_START });+ }+ // And each hop's conditioning window is cut from the tail into tmpdir —+ // off the chunk's post-trim length, not the length it was probed at.+ const windowStart = (i) => trimFor(chunkPath(i), join(tmpdir(), `chaincontext-${innerJobIds[i]}.mp4`))?.[2]?.startFrame;+ expect(windowStart(0)).toBe(WINDOW_START_UNTRIMMED);+ expect(windowStart(1)).toBe(WINDOW_START_TRIMMED);});- it('non-extend chains still call extractLastFrame (frame extraction path unchanged)', async () => {- const { spawn } = await import('child_process');- const spawnMock = vi.mocked(spawn);- spawnMock.mockClear();-- // For image-conditioned chain (non-extend), extractLastFrame calls ffmpeg- // with -sseof. Mock existsSync to return true (frame file present) so the- // cache-hit path triggers and we avoid needing a real ffmpeg call.- const { existsSync } = await import('fs');- vi.mocked(existsSync).mockReturnValue(true);-- const { statSync } = await import('fs');- vi.mocked(statSync).mockReturnValue({ size: 1000 });+ it('re-encodes the concat once a chunk has been trimmed', async () => {+ // A trimmed chunk was re-encoded, so it no longer shares codec parameters+ // with its untrimmed siblings and the demuxer's `-c copy` can't be trusted.+ const { spawns } = await runChain({}, 2);+ const concat = spawns.find(([, args]) => Array.isArray(args) && args.includes('-f') && args.includes('concat'));+ expect(concat).toBeTruthy();+ expect(concat[1]).toContain('libx264');+ expect(concat[1].join(' ')).not.toContain('-c copy');+ });- const { readJSONFile } = await import('../../lib/fileUtils.js');- // extractLastFrame reads history to find the item — return a stub entry- // so it can resolve the video path.- vi.mocked(readJSONFile).mockImplementation(async () => [- { id: 'placeholder', filename: 'placeholder.mp4' },- ]);+ it('probes each chunk once rather than re-reading it after the trim', async () => {+ // probeFrameCount falls back to a full -count_frames decode when the+ // container header carries no nb_frames, so a redundant probe per hop can+ // cost an entire extra decode of the clip.+ const { probeFrameCount } = await import('../../lib/ffmpeg.js');+ const { innerJobIds } = await runChain({}, 3);+ expect(vi.mocked(probeFrameCount).mock.calls).toHaveLength(innerJobIds.length);+ });- const outerJobId = randomUUID();- const innerJobIds = [];+ it('honors a smaller context window', async () => {+ // 8 frames instead of the 22-frame default → the window starts 8 back.+ const { innerJobIds, trims } = await runChain({ contextFrames: 8 }, 2);+ const cut = trims.find(([, to]) => to === join(tmpdir(), `chaincontext-${innerJobIds[0]}.mp4`));+ expect(cut[2]).toMatchObject({ startFrame: CHUNK_FRAMES - 8 });+ });- videoGenEvents.on('started', (e) => {- innerJobIds.push(e.generationId);- // Once history has the chunk id, subsequent extractLastFrame calls work- vi.mocked(readJSONFile).mockImplementation(async () =>- innerJobIds.map((id) => ({ id, filename: `${id}.mp4` })),- );- });+ it('contextFrames: 0 opts back into last-frame chaining', async () => {+ // 0 is a real value, distinct from "unset" — it's how a user gets the+ // historical single-still hop back on a runtime that could do better.+ const { renders, trims, spawns } = await runChain({ contextFrames: 0 }, 2);- generateChainedVideo({- chunks: 2,- jobId: outerJobId,- pythonPath: '/usr/bin/python3',- modelId: 'ltx2_unified',- prompt: 'image chain test',- width: 512,- height: 512,- numFrames: 25,- fps: 24,- mode: 'image',- sourceImagePath: '/mock/source.png',- extendFromVideoPath: null,- lastImagePath: null,- });+ expect(flagValue(renders[1], '--mode')).toBe('image');+ expect(flagValue(renders[1], '--extend-from-video')).toBeNull();+ // Nothing is trimmed, so the concat keeps the stream-copy fast path.+ expect(trims).toHaveLength(0);+ const concat = spawns.find(([, args]) => Array.isArray(args) && args.includes('concat'));+ expect(concat[1]).toContain('copy');+ });- for (let i = 0; i < 2; i++) {- // eslint-disable-next-line no-await-in-loop- await new Promise((resolve) => {- const check = () => {- if (innerJobIds.length > i) { resolve(); return; }- setTimeout(check, 10);- };- check();- });- const id = innerJobIds[i];- videoGenEvents.emit('completed', { generationId: id, filename: `${id}.mp4`, path: `/data/videos/${id}.mp4` });- }+ it('falls back to last-frame chaining on a runtime with no extend pipeline', async () => {+ // mlx_video has no extend_from_video, so the window is silently ignored+ // rather than rejected — switching models mid-form can't strand a request.+ const { renders, trims } = await runChain({ modelId: 'ltx23_unified', contextFrames: 22 }, 2);- await new Promise((r) => setTimeout(r, 100));- videoGenEvents.removeAllListeners('started');+ expect(flagValue(renders[1], '--mode')).not.toBe('extend');+ expect(trims).toHaveLength(0);+ });- expect(innerJobIds).toHaveLength(2);- // For non-extend chains the frame-extraction path is exercised OR the cache-- // hit (existsSync returning true) skips the ffmpeg spawn. Either way,- // extractLastFrame was called — we confirm no extend-mode bypass happened- // by asserting the chain completed its 2 chunks.- expect(innerJobIds).toHaveLength(2);+ it('keeps the first chunk of an extend chain whole, conditioned on the user source clip', async () => {+ // In an extend chain chunk 0's output is `user clip + extension`, and the+ // user clip belongs in the result exactly once — here. Trimming it would+ // drop the very footage the user asked to extend.+ const sourceVideoPath = join(MOCK_PATHS.videos, 'original-video.mp4');+ const { innerJobIds, renders, trims } = await runChain({+ mode: 'extend',+ extendFromVideoPath: sourceVideoPath,+ }, 2);++ expect(flagValue(renders[0], '--mode')).toBe('extend');+ expect(flagValue(renders[0], '--extend-from-video')).toBe(sourceVideoPath);+ expect(trims.some(([, to]) => to === join(MOCK_PATHS.videos, `${innerJobIds[0]}.mp4`))).toBe(false);+ // Chunk 1 conditions on a bounded window, NOT on chunk 0's whole output —+ // that's what kept the chain from growing a copy of itself per hop.+ expect(flagValue(renders[1], '--extend-from-video'))+ .toBe(join(tmpdir(), `chaincontext-${innerJobIds[0]}.mp4`));});});diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.jsindex 1f316218ae..4b43f24c7f 100644--- a/server/services/videoGen/prepareParams.js+++ b/server/services/videoGen/prepareParams.js@@ -35,6 +35,7 @@ import { safeUnder } from '../../lib/ffmpeg.js';import { RENDER_TARGET } from '../../lib/renderTargets.js';import { isVideoModelTermsAccepted, acceptedVideoModelTerms, videoModelTermsError } from '../../lib/videoDisclosure.js';import { videoLoraFamily } from '../../lib/runners.js';+import { resolveContextFrames } from '../../lib/videoContinuity.js';import {IC_LORA_MODE_VALUES, icLoraSpecForMode,assertIcReferenceCount, describeIcReferenceRange,@@ -828,6 +829,16 @@ async function resolvePreparedParams({? normalizedChunkPrompts: undefined;+ // Continuation context window — same "only meaningful once the request+ // really chains" rule as the beats above, so a single-chunk render doesn't+ // persist a knob that never applied and a resume can't replay it into the+ // form. Resolved (defaulted + clamped) here rather than at render time so+ // the persisted job records what the chain will actually do; note `0` is a+ // real value (last-frame chaining) and must not be dropped as falsy.+ const effectiveContextFrames = effectiveChunks > 1+ ? resolveContextFrames(body.contextFrames)+ : undefined;+return {backend,pythonPath,@@ -844,6 +855,7 @@ async function resolvePreparedParams({loras,effectiveChunks,effectiveChunkPrompts,+ effectiveContextFrames,cleanupStaged,};}