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
address review (round 2): fix the seam count, the temp-file guard, and the chain's numFrames default
[._.]/ Adam Eivy1b6d6a18e8e8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e342e1c20f..92e073ec84 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -272,4 +272,4 @@- **Image Gen's agy model picker lists models again, instead of reporting an empty catalog against a healthy one.** Choosing `agy` as the Image Gen provider showed "agy models returned no model ids — renders will use the model saved in Settings → Image Gen", with `agy models` printing a full eleven-model catalog on stdout the whole time. The parser dated from a build that printed one bare model id per line; agy now prints `<id>\t<Label>` rows (`gemini-3.6-flash-high⇥Gemini 3.6 Flash (High)`), so every row failed the bare-id test and the list came back empty — which the picker correctly refuses to present as a real fetch. Both the id-only and the tab-labelled shapes are now accepted, since other installs run older builds and every previously-persisted catalog was parsed under the old rule. The label is anchored on the tab rather than split on first whitespace on purpose: agy's own banner prose ("Fetching available models…") leads with a word that passes the id pattern, and a whitespace split would have persisted "Fetching" as a model. The same stale parse sat in the provider-catalog refresh behind Settings → Providers → Refresh models, whose failure was louder (it throws rather than falling back to the shipped seed) but has the identical cause; both now share one definition — `parseAntigravityModelList` in `server/lib/antigravity.js`, mirrored into the vendored toolkit copy — with a test that fails if the two ever disagree on any output shape.-- **[issue-3761] A chained video render no longer re-encodes a single chunk, and archives each one exactly as the model rendered it.** Windowed continuation conditions chunk N+1 on the tail of chunk N, and LTX-2's extend pipeline returns `source + extension` — so every chunk after the first opens with an echo of that window, which the stitched timeline already holds. Cutting the echo used to mean rewriting each chunk file in place, and a frame-index cut can't be stream-copied: an N-chunk chain spent `(N−1)` full x264 crf-18 passes whose only product was a frame offset, then knocked the trimmed chunks out of codec lockstep with the never-trimmed chunk 0 and forced the concat to re-encode the whole timeline on top. The offsets now ride into the stitch instead of into the files: `stitchVideos` takes a `trims` map and applies the cuts inside its concat's own `filter_complex` graph (`buildTrimConcatArgs` in `server/lib/ffmpeg.js`, mirroring the normalization the video-timeline renderer already proved out — `scale`/`pad`/`setsar`/`fps` on the video leg and `aresample`/`aformat` on the audio leg are what keep ffmpeg from aborting with "Input link parameters do not match"). Total cost drops to the single timeline encode that was always going to happen (each hop still encodes its own ~1s conditioning window, which is unrelated), the trimmed chunks stop being graded one generation lossier than chunk 0, and the archived per-chunk gallery entries stay byte-identical to the render — carrying their echo, which is invisible since those entries are hidden by default. Audio legs are emitted only when *every* input has an audio stream, because `concat=a=1` needs one from each and referencing `[k:a]` on a silent clip aborts the run; a chain of silent renders takes the video-only graph. The old `reencode` and `frameCounts` options collapse into `trims`, and the hand-stitch path from Media History — which passes no offsets — keeps its demuxer stream-copy fast path untouched. A filter graph that fails to build no longer discards the chain: it falls back to the stream-copy concat over the untrimmed chunks (which were never re-encoded, so they are still in lockstep), replaying the context at each seam rather than losing every chunk already rendered.+- **[issue-3761] A chained video render no longer re-encodes a single chunk, and archives each one exactly as the model rendered it.** Windowed continuation conditions chunk N+1 on the tail of chunk N, and LTX-2's extend pipeline returns `source + extension` — so every chunk after the first opens with an echo of that window, which the stitched timeline already holds. Cutting the echo used to mean rewriting each chunk file in place, and a frame-index cut can't be stream-copied: an N-chunk chain spent `(N−1)` full x264 crf-18 passes whose only product was a frame offset, then knocked the trimmed chunks out of codec lockstep with the never-trimmed chunk 0 and forced the concat to re-encode the whole timeline on top. The offsets now ride into the stitch instead of into the files: `stitchVideos` takes a `trims` map and applies the cuts inside its concat's own `filter_complex` graph (`buildTrimConcatArgs` in `server/lib/ffmpeg.js`, mirroring the normalization the video-timeline renderer already proved out — `scale`/`pad`/`setsar`/`fps` on the video leg and `aresample`/`aformat` on the audio leg are what keep ffmpeg from aborting with "Input link parameters do not match"). Total cost drops to the single timeline encode that was always going to happen (each hop still encodes its own ~1s conditioning window, which is unrelated), the trimmed chunks stop being graded one generation lossier than chunk 0, and the archived per-chunk gallery entries stay byte-identical to the render — carrying their echo, which is invisible since those entries are hidden by default. Audio legs are emitted only when *every* input has an audio stream, because `concat=a=1` needs one from each and referencing `[k:a]` on a silent clip aborts the run; a chain of silent renders takes the video-only graph. The old `reencode` and `frameCounts` options collapse into `trims`, and the hand-stitch path from Media History — which passes no offsets — keeps its demuxer stream-copy fast path untouched. One latent bug in the echo arithmetic closes along the way: `numFrames` is optional on the render route, and `generateVideo` resolves the model default before deriving `--extend-frames` — but the chain orchestrator read the raw request. A chained request that omitted `numFrames` therefore measured a ~120-frame extension against an assumed 8-frame one and called all but 8 frames of every hop "echo", which the old in-place trim then destroyed on disk. Both sides resolve the default now. A filter graph that fails to build no longer discards the chain: it falls back to the stream-copy concat over the untrimmed chunks (which were never re-encoded, so they are still in lockstep), replaying the context at each seam rather than losing every chunk already rendered.diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex 1d2f2bf05c..bbc484187d 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -1678,8 +1678,15 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFramesconst 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);+ // the pixel frames they decode to, so the two have to stay in step —+ // INCLUDING when the caller omitted numFrames. `numFrames` is optional on+ // the route, and generateVideo resolves the same default before deriving+ // `--extend-frames`; resolving it there but not here made the orchestrator+ // assume an 8-frame extension against a ~120-frame one, so the prefix trim+ // would have kept 8 frames of each hop and thrown the rest away.+ const chunkExtendLatents = extendLatentFrames(+ rest.numFrames ?? chainModel.defaultFrames ?? DEFAULT_NUM_FRAMES,+ );const chainState = { stopped: false };activeChain = chainState;@@ -2178,6 +2185,9 @@ export async function stitchVideos(videoIds, opts = {}) {});const listFile = join(tmpdir(), `concat-${id}.txt`);+ // Set before the write, not after: `writeFile` creates and truncates the+ // file before it writes, so a failure partway through still leaves one on+ // disk to clean up. Unlinking a file that was never created is a no-op here.let listFileWritten = false;const writeConcatList = async () => {// ffmpeg concat-demuxer escape: per its docs, single quotes in filenames@@ -2186,8 +2196,8 @@ export async function stitchVideos(videoIds, opts = {}) {// `C:\foo\bar.mp4`, that corrupts the path. Normalize to forward slashes// (which ffmpeg accepts on Windows just fine) before quoting.const escapeForConcat = (p) => p.replace(/\\/g, '/').replace(/'/g, "'\\''");- await writeFile(listFile, videoPaths.map((p) => `file '${escapeForConcat(p)}'`).join('\n'));listFileWritten = true;+ await writeFile(listFile, videoPaths.map((p) => `file '${escapeForConcat(p)}'`).join('\n'));};const outFilename = `${filenamePrefix}-${id}.mp4`;@@ -2206,9 +2216,12 @@ export async function stitchVideos(videoIds, opts = {}) {proc.on('error', (err) => reject(new ServerError(`ffmpeg failed to spawn: ${err.message}`, { status: 500, code: 'FFMPEG_FAILED' })));});+ // Inputs with a real cut, as opposed to the measurement-only entries. Zero+ // means the demuxer can do the job.+ const cutCount = trimPlan.filter((t) => t?.startFrame > 0).length;// Tracks whether the cuts actually made it into the output, so `numFrames`// below reports the timeline that exists rather than the one we asked for.- let trimsApplied = trimPlan.some((t) => t?.startFrame > 0);+ let trimsApplied = cutCount > 0;// Use a try/finally so the concat list temp file is cleaned up even when// ffmpeg rejects — otherwise it leaks one file per failed stitch.try {@@ -2234,13 +2247,15 @@ export async function stitchVideos(videoIds, opts = {}) {// inputs were never re-encoded, so they're still in codec lockstep and// the stream-copy concat below can salvage the clip. The cost is the// echoed context replaying at each trimmed seam.- console.log(`⚠️ Trimmed concat failed (${failure.message}) — falling back to a stream copy; ${trimPlan.filter(Boolean).length} seam(s) will repeat their context`);+ console.log(`⚠️ Trimmed concat failed (${failure.message}) — falling back to a stream copy; ${cutCount} seam(s) will repeat their context`);trimsApplied = false;}}if (!trimsApplied) {await writeConcatList();- await runFfmpeg(['-f', 'concat', '-safe', '0', '-i', listFile, '-c', 'copy', '-y', outPath]);+ // This one is fatal — its rejection is what the caller surfaces — so it+ // needs the cause even more than the survivable run above does.+ await runFfmpeg(['-f', 'concat', '-safe', '0', '-i', listFile, '-c', 'copy', '-y', outPath], { captureStderr: true });}await optimizeForStreaming(outPath);} finally {diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex 0a45aa229b..f452e431d5 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -561,6 +561,20 @@ describe('generateChainedVideo — continuation strategy (context window vs lastexpect(stitched?.numFrames).toBe(FIRST_FILE_FRAMES + (HOP_FILE_FRAMES - EXPECTED_PREFIX_START));});+ it('resolves the default frame count before sizing the echo, like the render does', async () => {+ // numFrames is optional on the route, and generateVideo falls back to+ // DEFAULT_NUM_FRAMES (121 → 15 latents → 120 new pixel frames) before it+ // derives --extend-frames. The orchestrator has to fall back identically:+ // reading the raw request instead makes it assume a 1-latent, 8-frame+ // extension, so it would call all but 8 frames of every hop "echo" and+ // cut the hop's actual footage out of the timeline.+ const DEFAULT_HOP_FILE_FRAMES = 145; // a 25-frame echo + 120 new frames+ const { renders, concat } = await runChain({ numFrames: undefined }, 2, [121, DEFAULT_HOP_FILE_FRAMES]);+ expect(flagValue(renders[1], '--extend-frames')).toBe('15');+ const graph = concat[concat.indexOf('-filter_complex') + 1];+ expect(graph).toMatch(/\[1:v\]trim=start_frame=25,/);+ });+it('never conditions the next hop on the echo the stitch is about to drop', async () => {// A window bigger than the chunk's own new footage (121 requested vs 24// rendered) clamps to the start of the file — which, now that the file