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 (codex): clamp FFLF keyframe indices to the resolution pixel budget
[._.]/ Adam Eivy77b4cef8f386
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex c0f912ec07..dde30030f9 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -93,6 +93,25 @@ const videoModelMemoryGb = (model) => {return match ? Number(match[1]) : Number.POSITIVE_INFINITY;};+// Mirror of server computeFflfSafeFrames (server/services/videoGen/local.js):+// the largest numFrames that fits the FFLF/ltx2 stage-2 pixel-frame budget at+// this resolution, rounded down to the LTX 8k+1 latent boundary. The budget+// itself comes from /status (`fflfLtx2PixelBudget`, honors the env override) so+// only this back-solve arithmetic is duplicated — not the constant. Lets the+// multi-keyframe picker reject out-of-budget indices before submit instead of+// letting the worker 400 mid-render. Returns numFrames when it already fits or+// the budget is unknown (fail-open — the server still enforces the real cap).+const computeFflfSafeFrames = (width, height, numFrames, budget) => {+ const wh = Number(width) * Number(height);+ const nf = Number(numFrames);+ const b = Number(budget);+ if (!(wh > 0) || !(nf > 0) || !(b > 0)) return nf;+ if (wh * nf <= b) return nf;+ const safeRaw = Math.floor(b / wh);+ const safeLatent = Math.max(1, Math.floor((safeRaw - 1) / 8));+ return safeLatent * 8 + 1;+};+// Mode-compatibility predicate for the Model dropdown. a2v requires the// ltx2 runtime (dgrauet's pipeline) — the legacy mlx_video pipeline has no// audio-conditioned mode, and Wan/Hunyuan don't either. Server enforces the@@ -643,6 +662,15 @@ export default function VideoGen() {// file, indices strictly ascending and within [0, numFrames-1].const keyframesSupported = currentModel?.runtime === 'ltx2';const keyframesActive = mode === 'fflf' && keyframesMode && keyframesSupported;+ // The worker clamps FFLF/ltx2 numFrames down to fit a pixel-frame budget that+ // depends on resolution, so at default 768×512 the real frame ceiling is far+ // below numFrames. Compute the same cap the server enforces so the picker can+ // gate indices (and the auto-seed) against it. Falls back to numFrames when+ // the budget hasn't loaded yet (server still enforces the real cap).+ const maxSafeFrames = useMemo(+ () => computeFflfSafeFrames(width, height, numFrames, status?.fflfLtx2PixelBudget),+ [width, height, numFrames, status?.fflfLtx2PixelBudget],+ );const keyframesError = useMemo(() => {if (!keyframesActive) return null;if (keyframes.length < 2) return 'Add at least 2 keyframes.';@@ -653,11 +681,17 @@ export default function VideoGen() {if (!kf.file) return `Keyframe ${i + 1} needs a gallery image.`;if (!Number.isInteger(kf.index) || kf.index < 0) return `Keyframe ${i + 1} needs a frame index ≥ 0.`;if (kf.index > numFrames - 1) return `Keyframe ${i + 1} frame ${kf.index} must be below numFrames (${numFrames}).`;+ // Effective cap from the resolution-dependent pixel budget (< numFrames at+ // higher resolutions). Mirrors the worker's clamp so we don't POST a+ // render that 400s with LTX2_FFLF_PIXEL_BUDGET_EXCEEDED.+ if (maxSafeFrames < numFrames && kf.index > maxSafeFrames - 1) {+ return `Keyframe ${i + 1} frame ${kf.index} exceeds the ${width}×${height} pixel budget (max frame ${maxSafeFrames - 1}). Lower the resolution or raise FFLF_LTX2_PIXEL_BUDGET.`;+ }if (kf.index <= prev) return 'Keyframe frame indices must be strictly ascending.';prev = kf.index;}return null;- }, [keyframesActive, keyframes, numFrames]);+ }, [keyframesActive, keyframes, numFrames, maxSafeFrames, width, height]);const keyframesBlocked = keyframesActive && !!keyframesError;// Probe the per-runtime status BEFORE the user hits Generate — without@@ -734,13 +768,19 @@ export default function VideoGen() {setLastImageUpload(null);};+ // The last addressable frame index — the smaller of numFrames and the+ // resolution-dependent pixel-budget cap (maxSafeFrames), minus 1. Seeding new+ // keyframe rows against this keeps the auto-seeded index inside the budget the+ // server enforces, so toggling keyframes on at a high resolution doesn't seed+ // an index that immediately trips keyframesError.+ const lastSeedableIndex = Math.max(0, Math.min(numFrames, maxSafeFrames) - 1);// Multi-keyframe list mutators. A new row defaults its index to the prior// row's index + 1 (clamped to the last addressable frame) so the strictly-// ascending invariant holds out of the box without the user hand-typing it.const addKeyframe = () => setKeyframes((prev) => {if (prev.length >= 8) return prev;const lastIndex = prev.length ? prev[prev.length - 1].index : -1;- const nextIndex = Math.min(lastIndex + 1, Math.max(0, numFrames - 1));+ const nextIndex = Math.min(lastIndex + 1, lastSeedableIndex);return [...prev, { file: '', index: nextIndex }];});const updateKeyframe = (i, patch) => setKeyframes((prev) =>@@ -757,7 +797,7 @@ export default function VideoGen() {clearLastImage();setKeyframes((prev) => (prev.length >= 2 ? prev : [{ file: '', index: 0 },- { file: '', index: Math.max(1, numFrames - 1) },+ { file: '', index: Math.max(1, lastSeedableIndex) },]));} else {setKeyframes([]);diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 00ae895b81..12d3e6ded8 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -36,6 +36,7 @@ import {stitchVideos,upscaleHistoryItem,DEFAULT_NUM_FRAMES,+ resolveFflfLtx2PixelBudget,} from '../services/videoGen/local.js';import { enqueueJob, attachSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';import { repoForModel, getTextEncoderRepo, isHfRepoId } from '../lib/mediaModels.js';@@ -174,6 +175,11 @@ router.get('/status', asyncHandler(async (_req, res) => {// Rounded to nearest GB; sub-GB precision isn't useful for the// model-size comparison and reads more cleanly in the UI.systemMemoryGb: Math.round(os.totalmem() / 1024 ** 3),+ // Effective FFLF/ltx2 stage-2 pixel-frame budget (honors+ // FFLF_LTX2_PIXEL_BUDGET). The multi-keyframe picker mirrors the+ // back-solve so it can reject out-of-budget keyframe indices before+ // submit instead of letting the worker 400 mid-render.+ fflfLtx2PixelBudget: resolveFflfLtx2PixelBudget(),});}));diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex 5ea4e3a14f..ac279b2d32 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -29,6 +29,10 @@ vi.mock('../services/videoGen/local.js', () => ({// Mirrors the real export — keeps the route's keyframe-range check in// sync with whatever the service actually defaults to.DEFAULT_NUM_FRAMES: 121,+ // /status advertises the FFLF pixel-frame budget so the client can mirror+ // the keyframe-index clamp. Mock returns the real default so the status+ // shape test sees a concrete number.+ resolveFflfLtx2PixelBudget: vi.fn(() => 704 * 448 * 25),// The route gates pythonPath enforcement on this allowlist (ltx2/wan22/// hunyuan bring their own venv). Mirror the real export so the// "accepts BYOV-runtime when pythonPath missing" case passes and the@@ -187,6 +191,10 @@ describe('videoGen routes', () => {// presence + type so a future accidental removal is caught here.expect(typeof r.body.systemMemoryGb).toBe('number');expect(r.body.systemMemoryGb).toBeGreaterThan(0);+ // fflfLtx2PixelBudget lets the client mirror the FFLF keyframe-index+ // clamp without hardcoding the constant. Pin presence + type.+ expect(typeof r.body.fflfLtx2PixelBudget).toBe('number');+ expect(r.body.fflfLtx2PixelBudget).toBeGreaterThan(0);});it('reports disconnected with reason + missingPackages when packages fail to import', async () => {diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex cbd534fc97..c3c6fae013 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -205,6 +205,33 @@ export const cancel = () => {export const loadHistory = () => readJSONFile(HISTORY_FILE, []);export const saveHistory = (h) => atomicWrite(HISTORY_FILE, h);+// Effective FFLF/ltx2 stage-2 pixel-frame budget (width × height × numFrames).+// The default fit 48 GB unified RAM in testing; FFLF_LTX2_PIXEL_BUDGET lets+// users with more RAM raise it. This is the SINGLE source of truth for the cap+// — `buildLtx2Args` enforces it server-side AND the /status route advertises it+// so the client can gate keyframe indices before submit (see computeFflfSafeFrames).+export const resolveFflfLtx2PixelBudget = () => {+ const envBudget = Number(process.env.FFLF_LTX2_PIXEL_BUDGET);+ return Number.isFinite(envBudget) && envBudget > 0+ ? envBudget+ : 704 * 448 * 25; // ≈7.9M pixel-frames, confirmed to fit 48 GB unified RAM+};++// Back-solve the largest numFrames that fits `budget` at this resolution,+// rounded DOWN to the LTX 8k+1 latent boundary (so the model doesn't silently+// snap). Returns the input numFrames unchanged when it already fits. Pure and+// shared: the server clamps with it, the client mirrors it to validate keyframe+// indices against the same cap the worker will enforce.+export const computeFflfSafeFrames = (width, height, numFrames, budget = resolveFflfLtx2PixelBudget()) => {+ const wh = Number(width) * Number(height);+ const nf = Number(numFrames);+ if (!(wh > 0) || !(nf > 0) || !(budget > 0)) return nf;+ if (wh * nf <= budget) return nf;+ const safeRaw = Math.floor(budget / wh);+ const safeLatent = Math.max(1, Math.floor((safeRaw - 1) / 8));+ return safeLatent * 8 + 1;+};+// Build the spawn args for dgrauet's ltx-2-mlx runtime via our Python helper.// The helper lives in the ltx-2-mlx venv (so its `import ltx_pipelines_mlx`// resolves) but the script file lives in the PortOS repo so updates ship@@ -266,15 +293,10 @@ const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames// to the LTX 8k+1 latent-boundary so the model doesn't silently snap.// FFLF_LTX2_PIXEL_BUDGET env var lets users with more RAM raise the cap.if (helperMode === 'fflf') {- const envBudget = Number(process.env.FFLF_LTX2_PIXEL_BUDGET);- const pixelBudget = Number.isFinite(envBudget) && envBudget > 0- ? envBudget- : 704 * 448 * 25; // ≈7.9M pixel-frames, confirmed to fit 48 GB unified RAM+ const pixelBudget = resolveFflfLtx2PixelBudget();const requested = Number(width) * Number(height) * Number(numFrames);if (requested > pixelBudget) {- const safeRaw = Math.floor(pixelBudget / (Number(width) * Number(height)));- const safeLatent = Math.max(1, Math.floor((safeRaw - 1) / 8));- const safeFrames = safeLatent * 8 + 1;+ const safeFrames = computeFflfSafeFrames(width, height, numFrames, pixelBudget);// Multi-keyframe renders pin specific pixel-frame indices — clamping// numFrames below `max(keyframe.index)` would either drop a keyframe// or hand the Python helper an out-of-range index that hard-failsdiff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex 47c21676a7..9c08f850d0 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -387,3 +387,73 @@ describe('generateVideo — ltx2 FFLF image resizing', () => {expect(args[args.indexOf('--last-image') + 1]).toBe(join(tmpdir(), `resized-last-${jobId}.png`));});});++describe('FFLF/ltx2 pixel-budget helpers', () => {+ const DEFAULT_BUDGET = 704 * 448 * 25; // ≈7.9M pixel-frames++ let resolveFflfLtx2PixelBudget;+ let computeFflfSafeFrames;++ beforeEach(async () => {+ ({ resolveFflfLtx2PixelBudget, computeFflfSafeFrames } = await import('./local.js'));+ delete process.env.FFLF_LTX2_PIXEL_BUDGET;+ });++ afterEach(() => {+ delete process.env.FFLF_LTX2_PIXEL_BUDGET;+ });++ describe('resolveFflfLtx2PixelBudget', () => {+ it('defaults to the 48 GB-RAM budget when the env var is unset', () => {+ expect(resolveFflfLtx2PixelBudget()).toBe(DEFAULT_BUDGET);+ });++ it('honors a positive numeric FFLF_LTX2_PIXEL_BUDGET override', () => {+ process.env.FFLF_LTX2_PIXEL_BUDGET = '12000000';+ expect(resolveFflfLtx2PixelBudget()).toBe(12_000_000);+ });++ it('ignores a non-positive or non-numeric override and falls back to the default', () => {+ process.env.FFLF_LTX2_PIXEL_BUDGET = '0';+ expect(resolveFflfLtx2PixelBudget()).toBe(DEFAULT_BUDGET);+ process.env.FFLF_LTX2_PIXEL_BUDGET = '-5';+ expect(resolveFflfLtx2PixelBudget()).toBe(DEFAULT_BUDGET);+ process.env.FFLF_LTX2_PIXEL_BUDGET = 'lots';+ expect(resolveFflfLtx2PixelBudget()).toBe(DEFAULT_BUDGET);+ });+ });++ describe('computeFflfSafeFrames', () => {+ it('returns numFrames unchanged when the request already fits the budget', () => {+ expect(computeFflfSafeFrames(704, 448, 25, DEFAULT_BUDGET)).toBe(25);+ expect(computeFflfSafeFrames(704, 448, 10, DEFAULT_BUDGET)).toBe(10);+ });++ it('clamps down to the 8k+1 latent boundary when the request exceeds the budget', () => {+ // 768×512 = 393216 px/frame. budget/wh ≈ 20.05 → safeLatent floor((20-1)/8)=2 → 2*8+1=17.+ const safe = computeFflfSafeFrames(768, 512, 121, DEFAULT_BUDGET);+ expect(safe).toBe(17);+ expect(safe).toBeLessThan(121);+ expect(768 * 512 * safe).toBeLessThanOrEqual(DEFAULT_BUDGET);+ // The clamp lands on the latent boundary (8k+1).+ expect((safe - 1) % 8).toBe(0);+ });++ it('never returns below the minimum single-latent frame count (8*1+1)', () => {+ // A resolution so large that even one latent block barely fits.+ const safe = computeFflfSafeFrames(4000, 4000, 200, DEFAULT_BUDGET);+ expect(safe).toBe(9);+ });++ it('falls open (returns numFrames) when inputs are invalid', () => {+ expect(computeFflfSafeFrames(0, 448, 25, DEFAULT_BUDGET)).toBe(25);+ expect(computeFflfSafeFrames(704, 448, 0, DEFAULT_BUDGET)).toBe(0);+ expect(computeFflfSafeFrames(704, 448, 25, 0)).toBe(25);+ });++ it('defaults the budget arg to the resolved env budget', () => {+ process.env.FFLF_LTX2_PIXEL_BUDGET = String(704 * 448 * 25);+ expect(computeFflfSafeFrames(704, 448, 25)).toBe(25);+ });+ });+});