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: report the real length when a stitch falls back, and cut before normalizing
[._.]/ Adam Eivy387961ed479c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ae82731e03..e342e1c20f 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 now pays exactly one encode pass, and archives each chunk 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, 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. 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/lib/ffmpeg.js b/server/lib/ffmpeg.jsindex b4cbb65d78..348b3b1987 100644--- a/server/lib/ffmpeg.js+++ b/server/lib/ffmpeg.js@@ -489,20 +489,25 @@ export const buildTrimConcatArgs = ({ inputs, outPath, width, height, fps, withAconst concatStreams = [];clips.forEach((clip, i) => {const startFrame = Math.max(0, Math.floor(Number(clip?.startFrame) || 0));+ // `trim` leads the chain on purpose. `start_frame` is an index into the+ // frames the filter SEES, so cutting before `fps=` resamples keeps it an+ // index into the source — which is what the caller measured with+ // `probeFrameCount`. It also means the discarded frames never get scaled+ // or padded, which on a windowed chain is roughly half of every chunk.const video = [- ...(hasDims ? [`scale=${canonW}:${canonH}:force_original_aspect_ratio=decrease,pad=${canonW}:${canonH}:(ow-iw)/2:(oh-ih)/2,setsar=1`] : []),- ...(hasRate ? [`fps=${rate}`] : []),...(startFrame > 0 ? [`trim=start_frame=${startFrame}`] : []),'setpts=PTS-STARTPTS',+ ...(hasDims ? [`scale=${canonW}:${canonH}:force_original_aspect_ratio=decrease,pad=${canonW}:${canonH}:(ow-iw)/2:(oh-ih)/2,setsar=1`] : []),+ ...(hasRate ? [`fps=${rate}`] : []),];filters.push(`[${i}:v]${video.join(',')}[v${i}]`);if (audio) {const track = [- 'aresample=48000',- 'aformat=sample_fmts=fltp:channel_layouts=stereo',// The frame index converts exactly because these are CFR renders....(startFrame > 0 ? [`atrim=start=${(startFrame / rate).toFixed(6)}`] : []),'asetpts=PTS-STARTPTS',+ 'aresample=48000',+ 'aformat=sample_fmts=fltp:channel_layouts=stereo',];filters.push(`[${i}:a]${track.join(',')}[a${i}]`);}diff --git a/server/lib/ffmpeg.test.js b/server/lib/ffmpeg.test.jsindex 25c0f13ed1..0dd2eb8228 100644--- a/server/lib/ffmpeg.test.js+++ b/server/lib/ffmpeg.test.js@@ -188,8 +188,10 @@ describe('buildTrimConcatArgs', () => {expect(args.slice(0, 4)).toEqual(['-i', '/v/a.mp4', '-i', '/v/b.mp4']);const graph = graphOf(args);// The untrimmed input still gets normalized + PTS-rebased, but no `trim`.- expect(graph).toContain('[0:v]scale=512:288:force_original_aspect_ratio=decrease,pad=512:288:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=24,setpts=PTS-STARTPTS[v0]');- expect(graph).toContain('trim=start_frame=9,setpts=PTS-STARTPTS[v1]');+ expect(graph).toContain('[0:v]setpts=PTS-STARTPTS,scale=512:288:force_original_aspect_ratio=decrease,pad=512:288:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=24[v0]');+ // `trim` leads, so `start_frame` indexes the SOURCE frames the caller+ // measured — not whatever `fps=` would have resampled them into.+ expect(graph).toContain('[1:v]trim=start_frame=9,setpts=PTS-STARTPTS,scale=');expect(graph).toContain('[v0][v1]concat=n=2:v=1:a=0[outv]');expect(args.slice(-2)).toEqual(['-y', '/v/out.mp4']);});diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex e83df0fff1..1d2f2bf05c 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -1865,12 +1865,16 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFrameslet contextPrefix = 0;if (i > 0) {contextPrefix = contextPrefixFrames({ totalFrames: frames, extendLatents: chunkExtendLatents });- if (contextPrefix > 0) {- chunkTrims.set(chunkId, { startFrame: contextPrefix, frames: frames - contextPrefix });- } else {+ if (contextPrefix <= 0) {console.log(`⚠️ Chunk ${i + 1}/${totalChunks} context prefix unmeasurable (frames=${frames ?? 'unknown'}), leaving it untrimmed`);}}+ // Record the measurement even when there's nothing to cut (chunk 0, or+ // an unmeasurable prefix). An extend render's file is `source ++ // extension`, so a chunk's own history `numFrames` — the count it was+ // REQUESTED at — understates what it contributes to the timeline, and+ // that's the only other number the stitch could fall back on.+ if (frames != null) chunkTrims.set(chunkId, { startFrame: contextPrefix, frames: frames - contextPrefix });if (i < totalChunks - 1) {// Cut the next hop's conditioning window off this chunk's tail. Both@@ -2129,9 +2133,13 @@ export async function stitchVideos(videoIds, opts = {}) {// encode; pre-trimming each chunk file instead would add one full encode// per chunk and re-grade the trimmed chunks relative to their siblings.//- // `frames` feeds the stitched entry's `numFrames`, because a history- // entry's own `numFrames` is the count the clip was RENDERED at — a render- // parameter Remix reuses, not a measurement of what it contributes here.+ // Both numbers are MEASUREMENTS of the file, which is why they have to+ // come from the caller: a history entry's own `numFrames` is the count the+ // clip was RENDERED at — a render parameter Remix reuses — and an extend+ // render's output is `source + extension`, so its file is materially+ // longer than that. `startFrame: 0` is therefore meaningful on its own:+ // "no cut, but here is the real length." Only a non-zero offset routes the+ // concat through the filter graph.trims = null,} = opts;if (!Array.isArray(videoIds) || videoIds.length < 2) {@@ -2155,14 +2163,18 @@ export async function stitchVideos(videoIds, opts = {}) {if (!existsSync(p)) throw new ServerError(`Missing: ${basename(p)}`, { status: 404, code: 'NOT_FOUND' });}- // Leading-frame cut per input, in `videos` order. A zero/absent offset means- // the input joins whole; any non-zero offset routes the whole concat through- // the filter graph, since only that path can express a cut.+ // Measured cut + contribution per input, in `videos` order. A zero offset+ // means the input joins whole (the entry is then purely a length+ // measurement); any non-zero offset routes the whole concat through the+ // filter graph, since only that path can express a cut.const trimPlan = videos.map((v) => {- const startFrame = Math.max(0, Math.floor(Number(trims?.get?.(v.id)?.startFrame) || 0));- if (startFrame <= 0) return null;- const frames = Number(trims.get(v.id).frames);- return { startFrame, frames: Number.isFinite(frames) && frames >= 0 ? frames : null };+ const entry = trims?.get?.(v.id);+ if (!entry) return null;+ const frames = Number(entry.frames);+ return {+ startFrame: Math.max(0, Math.floor(Number(entry.startFrame) || 0)),+ frames: Number.isFinite(frames) && frames >= 0 ? frames : null,+ };});const listFile = join(tmpdir(), `concat-${id}.txt`);@@ -2181,15 +2193,22 @@ export async function stitchVideos(videoIds, opts = {}) {const outFilename = `${filenamePrefix}-${id}.mp4`;const outPath = join(PATHS.videos, outFilename);- const runFfmpeg = (args) => new Promise((resolve, reject) => {- const proc = spawn(ffmpeg, args, { env: safeChildProcessEnv(), stdio: 'ignore' });- proc.on('close', (code) => code === 0 ? resolve() : reject(new ServerError('Stitch failed', { status: 500, code: 'FFMPEG_FAILED' })));+ // `captureStderr` is for the run whose failure is SURVIVABLE — the fallback+ // below turns it into a log line, and "Stitch failed" alone can't tell a+ // filter-graph parse error from a full disk.+ const runFfmpeg = (args, { captureStderr = false } = {}) => new Promise((resolve, reject) => {+ const proc = spawn(ffmpeg, args, { env: safeChildProcessEnv(), stdio: captureStderr ? ['ignore', 'ignore', 'pipe'] : 'ignore' });+ let tail = '';+ proc.stderr?.on('data', (d) => { tail = `${tail}${d}`.slice(-400); });+ proc.on('close', (code) => code === 0+ ? resolve()+ : reject(new ServerError(`Stitch failed${tail ? `: ${tail.trim().split('\n').pop()}` : ''}`, { status: 500, code: 'FFMPEG_FAILED' })));proc.on('error', (err) => reject(new ServerError(`ffmpeg failed to spawn: ${err.message}`, { status: 500, code: 'FFMPEG_FAILED' })));});- // Tracks whether the trims actually made it into the output, so `numFrames`+ // 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(Boolean);+ let trimsApplied = trimPlan.some((t) => t?.startFrame > 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 {@@ -2208,7 +2227,7 @@ export async function stitchVideos(videoIds, opts = {}) {withAudio: (await Promise.all(videoPaths.map((p) => hasAudioStream(p)))).every(Boolean),});const failure = args- ? await runFfmpeg(args).then(() => null, (err) => err)+ ? await runFfmpeg(args, { captureStderr: true }).then(() => null, (err) => err): new Error('could not build the concat filter graph');if (failure) {// Degrade rather than throw away a whole chained render: the untrimmed@@ -2238,9 +2257,17 @@ export async function stitchVideos(videoIds, opts = {}) {seed: videos[0].seed ?? 0,width: videos[0].width,height: videos[0].height,- numFrames: videos.reduce((sum, v, i) => sum + (- (trimsApplied ? trimPlan[i]?.frames : null) ?? v.numFrames ?? 0- ), 0),+ // What each input actually contributes. A measured plan wins over the+ // entry's own `numFrames` either way — but when the cuts didn't make it+ // into the output, the input contributes its WHOLE measured length+ // (`startFrame + frames`), not the trimmed length we asked for.+ numFrames: videos.reduce((sum, v, i) => {+ const plan = trimPlan[i];+ const measured = plan?.frames == null+ ? null+ : (trimsApplied ? plan.frames : plan.startFrame + plan.frames);+ return sum + (measured ?? 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 5a013bf01c..0a45aa229b 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -299,21 +299,26 @@ async function runChainAndCaptureArgs(chainParams, totalChunks) {// ─── tests ───────────────────────────────────────────────────────────────────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 has none)- // the 22-frame conditioning window starts at 25 − 22 = 3- // The chunk files are never rewritten, so that index is measured against the- // full render on every hop: index 3 of a windowed chunk is frame 2 of its own- // new footage, i.e. the same frames the old pre-trim path cut at index 2 of a- // shortened file. What the floor at `contextPrefix` guarantees is that the- // window can never reach back into the echo the stitch is about to drop.+ // numFrames=25 → extendLatentFrames(25) = 3 latents = 24 new pixel frames.+ //+ // The probe is mocked to the lengths a real chain produces, NOT to the+ // rendered numFrames: chunk 0 is a plain 25-frame text render, but a windowed+ // hop returns `context + extension`, so its FILE is 49 frames — 24 new ones+ // behind a 25-frame echo of the window it was conditioned on. That gap is the+ // whole reason the stitch can't fall back on a chunk's own history+ // `numFrames`, and mocking both at 25 would hide it.const CHUNK_FRAMES = 25;+ const HOP_FILE_FRAMES = 49;const EXPECTED_EXTEND_LATENTS = 3;- const EXPECTED_PREFIX_START = 1;- const WINDOW_START = 3;- // 25 + (25−1) + (25−1) once the echoes come out of the timeline.+ // 49 − 24 new frames = a 25-frame echo to drop.+ const EXPECTED_PREFIX_START = 25;+ // The 22-frame window off chunk 0 (25 − 22) and off a hop (49 − 22).+ const WINDOW_START_FIRST = 3;+ const WINDOW_START_HOP = 27;+ // 25 + (49−25) + (49−25) once the echoes come out of the timeline…const STITCHED_FRAMES_3_CHUNKS = 73;+ // …versus the 123 frames actually on the timeline if the cuts don't land.+ const UNTRIMMED_FRAMES_3_CHUNKS = 123;const flagValue = (args, flag) => (Array.isArray(args) && args.includes(flag)? args[args.indexOf(flag) + 1] : null);@@ -324,7 +329,7 @@ describe('generateChainedVideo — continuation strategy (context window vs last* 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) {+ async function runChain(chainParams, totalChunks, probeFrames = null) {const { spawnDetached } = await import('../../lib/detachedSpawn.js');const { trimVideoFromFrame, probeFrameCount } = await import('../../lib/ffmpeg.js');const { spawn } = await import('child_process');@@ -334,6 +339,15 @@ describe('generateChainedVideo — continuation strategy (context window vs lastvi.mocked(probeFrameCount).mockClear();vi.mocked(spawn).mockClear();vi.mocked(atomicWrite).mockClear();+ // Chunk 0 is a plain render; every hop after it comes back as+ // `context + extension`. The orchestrator probes each chunk exactly once,+ // in order, so the call index is the chunk index. `probeFrames` overrides+ // the sequence for chains whose chunk 0 isn't a plain render either.+ let probeCall = 0;+ vi.mocked(probeFrameCount).mockImplementation(async () => {+ const i = probeCall++;+ return probeFrames ? probeFrames[Math.min(i, probeFrames.length - 1)] : (i === 0 ? CHUNK_FRAMES : HOP_FILE_FRAMES);+ });// extractLastFrame and stitchVideos both look their inputs up in history;// feed the chunk ids back as they start so the chain can advance. The@@ -449,12 +463,16 @@ describe('generateChainedVideo — continuation strategy (context window vs last// Each hop's conditioning window is still cut from the tail into tmpdir.const windowStart = (i) => trims.find(([from, to]) => from === chunkPath(i) && to === join(tmpdir(), `chaincontext-${innerJobIds[i]}.mp4`))?.[2]?.startFrame;- expect(windowStart(0)).toBe(WINDOW_START);- expect(windowStart(1)).toBe(WINDOW_START);+ expect(windowStart(0)).toBe(WINDOW_START_FIRST);+ expect(windowStart(1)).toBe(WINDOW_START_HOP);});- it('encodes the timeline exactly once for an N-chunk chain', async () => {- // The whole point: (N−1) chunk encodes + 1 timeline encode collapses to 1.+ it('runs no whole-chunk encode pass — the timeline encode is the only one', async () => {+ // The whole point: (N−1) whole-chunk encodes + 1 timeline encode collapses+ // to just the timeline encode. (The per-hop conditioning-window cut is+ // still an encode, but of ~22 frames, and it goes through the mocked+ // trimVideoFromFrame rather than spawn — the sibling test above is what+ // pins that it never touches a chunk file.)const { spawns, concat } = await runChain({}, 3);const encodes = spawns.filter(([, args]) => Array.isArray(args) && args.includes('libx264'));expect(encodes).toHaveLength(1);@@ -494,9 +512,11 @@ describe('generateChainedVideo — continuation strategy (context window vs last// …and the salvage run, which is the plain demuxer stream copy.const copy = concats.find((args) => args.includes('-f') && args.includes('copy'));expect(copy).toBeTruthy();- // The echoes are still in the output, so the record must say so rather- // than reporting the trimmed length we asked for and never got.- expect(stitched?.numFrames).toBe(CHUNK_FRAMES * 3);+ // The echoes are still in the output, so the record must say so — and+ // "so" is the chunks' MEASURED lengths (25 + 49 + 49), not the numFrames+ // they were rendered at, which understates an extend render's file by+ // the whole context window.+ expect(stitched?.numFrames).toBe(UNTRIMMED_FRAMES_3_CHUNKS);} finally {vi.mocked(spawn).mockImplementation(() => makeProc());}@@ -526,6 +546,21 @@ describe('generateChainedVideo — continuation strategy (context window vs lastexpect(cut[2]).toMatchObject({ startFrame: CHUNK_FRAMES - 8 });});+ it('measures the untrimmed first chunk too, instead of trusting the count it was rendered at', async () => {+ // In an extend chain chunk 0's output is `user clip + extension`, so its+ // file is far longer than the numFrames its history entry records — and+ // nothing trims it, so no cut forces a measurement. It still has to be+ // measured, or the stitched entry's duration is short by the whole source+ // clip and a Remix off it re-renders at the wrong length.+ const FIRST_FILE_FRAMES = 60;+ const { stitched } = await runChain({+ mode: 'extend',+ extendFromVideoPath: join(MOCK_PATHS.videos, 'original-video.mp4'),+ }, 2, [FIRST_FILE_FRAMES, HOP_FILE_FRAMES]);+ // 60 whole + (49 − 25) after the hop's echo comes out.+ expect(stitched?.numFrames).toBe(FIRST_FILE_FRAMES + (HOP_FILE_FRAMES - EXPECTED_PREFIX_START));+ });+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