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
fix([issue-740]): gate two-stage T2V experiment Node-side so the knob actually fires
Adam Eivy663a1d9af056
diff --git a/scripts/generate_ltx2.py b/scripts/generate_ltx2.pyindex 19fd8316de..0ee15d1f0b 100644--- a/scripts/generate_ltx2.py+++ b/scripts/generate_ltx2.py@@ -70,11 +70,6 @@ def emit_download(msg: str) -> None:print(f"DOWNLOAD:{msg}", file=sys.stderr, flush=True)-def env_truthy(name: str) -> bool:- """True when env var `name` is set to a recognized truthy value (1/true/yes/on)."""- return os.environ.get(name, "").strip().lower() in {"1", "true", "yes", "on"}--_EXTEND_TC_CONFIG: dict | None = None_A2V_TC_CONFIG: dict | None = None_EXTEND_TC_PATCH_OK = False@@ -279,22 +274,8 @@ def configure_image_strength(image_strength: float | None) -> None:emit_status(f"Using image strength {image_strength:g}")-def run_two_stage(- args: argparse.Namespace,- image: str | None = None,- *,- stage1_steps: int | None = None,- stage2_steps: int | None = None,- cfg_scale: float | None = None,- status: str = "Generating with CFG…",-) -> str:- """T2V/I2V path via the dgrauet two-stage pipeline.-- The keyword overrides let the env-gated T2V perf experiment- (PORTOS_T2V_TWO_STAGE) drive a fast half-res config with no CFG;- callers that omit them keep the original CFG-path defaults- (30 stage-1 steps, args.stage2_steps, cfg_scale 3.0).- """+def run_two_stage(args: argparse.Namespace, image: str | None = None) -> str:+ """T2V/I2V path that honors CFG via the dgrauet two-stage pipeline."""from ltx_pipelines_mlx import TwoStagePipelineemit_status(f"Loading two-stage pipeline ({args.model})…")emit_stage(1, 0, 1, "Loading model")@@ -307,7 +288,7 @@ def run_two_stage()bind_output_fps(pipe, args.fps)emit_stage(1, 1, 1, "Loaded")- emit_status(status)+ emit_status("Generating with CFG…")return pipe.generate_and_save(prompt=args.prompt,output_path=args.output,@@ -316,30 +297,15 @@ def run_two_stage(width=args.width,num_frames=args.num_frames,seed=args.seed,- stage1_steps=stage1_steps if stage1_steps is not None- else (args.steps if args.steps is not None else 30),- stage2_steps=stage2_steps if stage2_steps is not None else args.stage2_steps,- cfg_scale=cfg_scale if cfg_scale is not None- else (args.cfg_scale if args.cfg_scale is not None else 3.0),+ stage1_steps=args.steps if args.steps is not None else 30,+ stage2_steps=args.stage2_steps,+ cfg_scale=args.cfg_scale if args.cfg_scale is not None else 3.0,)def run_text(args: argparse.Namespace) -> str:if args.cfg_scale is not None:return run_two_stage(args)- # Env-gated perf experiment: route the default no-CFG T2V Standard path- # through the two-stage pipeline (half-res stage 1 + latent upsample +- # short stage-2 refine) for a predicted ~30-35% wall-time reduction.- # Default off — set PORTOS_T2V_TWO_STAGE=1 to A/B it; explicit --steps /- # --stage2-steps still win over the fast 8/3 defaults.- if env_truthy("PORTOS_T2V_TWO_STAGE"):- return run_two_stage(- args,- stage1_steps=args.steps if args.steps is not None else 8,- stage2_steps=args.stage2_steps if args.stage2_steps is not None else 3,- cfg_scale=1.0,- status="Generating T2V (two-stage)…",- )from ltx_pipelines_mlx import TextToVideoPipelineemit_status(f"Loading T2V pipeline ({args.model})…")emit_stage(1, 0, 1, "Loading model")diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex 8613f03f5d..a5c8087029 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -254,11 +254,52 @@ export const computeFflfSafeFrames = (width, height, numFrames, budget = resolvereturn safeLatent * 8 + 1;};+// Env-gated LTX-2 T2V "two-stage" perf experiment (PORTOS_T2V_TWO_STAGE).+//+// Phosphene found that routing a plain T2V Standard render through the+// two-stage pipeline at a fast half-res config (8 stage-1 + 3 stage-2 steps,+// cfg 1.0) cuts ~30-35% of wall time. This DECISION has to live on the Node+// side, not in generate_ltx2.py: buildLtx2Args always emits `--cfg-scale`+// from model.guidance, so the Python helper can't tell a defaulted guidance+// from one the user set on purpose. Here we still know.+//+// Returns the override `{ guidance, steps, stage2Steps }` only when ALL hold:+// the runtime is ltx2, it's a no-conditioning text render, the user left+// guidance AND steps at their defaults (so we only ever hijack the "Standard"+// render, never a customized one), and the env knob is truthy. Otherwise null+// (no change → existing behavior). Pure + exported so it's unit-tested+// directly, mirroring the FFLF pixel-budget helpers above.+export const resolveT2vTwoStageOverride = ({+ runtime, mode, guidanceScale, steps,+ sourceImagePath, uploadedTempPath, uploadedTempPaths,+ keyframes, extendFromVideoPath, audioFilePath,+ env = process.env,+}) => {+ const enabled = ['1', 'true', 'yes', 'on']+ .includes(String(env.PORTOS_T2V_TWO_STAGE ?? '').trim().toLowerCase());+ if (!enabled || runtime !== 'ltx2') return null;+ // Only the default text mode — anything explicitly fflf/a2v/extend/image+ // is conditioned and out of scope for the T2V Standard experiment.+ if (mode != null && mode !== 'text') return null;+ // Customized renders opt out — the experiment is the Standard render only.+ const userSetGuidance = guidanceScale != null && guidanceScale !== '';+ const userSetSteps = !!steps;+ if (userSetGuidance || userSetSteps) return null;+ // Any conditioning input makes this not a plain T2V (matches the helperMode+ // 'text' inference in buildLtx2Args).+ const hasConditioning = !!sourceImagePath || !!uploadedTempPath+ || (Array.isArray(uploadedTempPaths) && uploadedTempPaths.length > 0)+ || (Array.isArray(keyframes) && keyframes.length > 0)+ || !!extendFromVideoPath || !!audioFilePath;+ if (hasConditioning) return null;+ return { guidance: 1.0, steps: 8, stage2Steps: 3 };+};+// 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// with PortOS releases instead of the user's HF cache.-const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo }) => {+const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo }) => {assertByovRuntimeInstalled('ltx2');// Map PortOS UI modes to the helper's subcommand. Native extend on ltx2// routes to ExtendPipeline.extend_from_video — conditions on the entire@@ -366,6 +407,9 @@ const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames'--steps', String(steps),'--cfg-scale', String(guidance),];+ // Two-stage T2V experiment passes an explicit stage-2 step count; omitted+ // otherwise so the pipeline keeps its own default.+ if (stage2Steps != null) args.push('--stage2-steps', String(stage2Steps));if (negativePrompt) args.push('--negative-prompt', negativePrompt);if (imageStrength != null) args.push('--image-strength', String(imageStrength));if (disableAudio) args.push('--no-audio');@@ -474,12 +518,12 @@ const buildHunyuanArgs = ({ model, prompt, negativePrompt, width, height, numFrareturn { bin: HUNYUAN_VENV_PYTHON, args };};-const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, textEncoderRepo, outputPath }) => {+const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, textEncoderRepo, outputPath }) => {// Route to the dgrauet/ltx-2-mlx helper when the model declares the new// runtime. Existing notapalindrome models default to runtime: 'mlx_video'// (or undefined in legacy registries — see backfillRuntime in mediaModels.js).if (model.runtime === 'ltx2') {- return buildLtx2Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo });+ return buildLtx2Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo });}if (model.runtime === 'wan22') {return buildWan22Args({ model, prompt, width, height, numFrames, steps, guidance, seed, sourceImagePath, mode, outputPath });@@ -593,8 +637,23 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', mconst w = Math.floor(Number(width) / 64) * 64;const h = Math.floor(Number(height) / 64) * 64;const actualSeed = seed != null && seed !== '' ? Number(seed) : Math.floor(Math.random() * 2147483647);- const actualSteps = steps ? Number(steps) : model.steps;- const actualGuidance = guidanceScale != null && guidanceScale !== '' ? Number(guidanceScale) : model.guidance;+ let actualSteps = steps ? Number(steps) : model.steps;+ let actualGuidance = guidanceScale != null && guidanceScale !== '' ? Number(guidanceScale) : model.guidance;+ // Opt-in T2V Standard two-stage perf experiment — overrides steps/guidance+ // (and adds an explicit stage-2 step count) only for a plain default text+ // render when PORTOS_T2V_TWO_STAGE is on. No-op otherwise.+ let actualStage2Steps = null;+ const t2vTwoStage = resolveT2vTwoStageOverride({+ runtime: model.runtime, mode, guidanceScale, steps,+ sourceImagePath, uploadedTempPath, uploadedTempPaths,+ keyframes, extendFromVideoPath, audioFilePath,+ });+ if (t2vTwoStage) {+ actualGuidance = t2vTwoStage.guidance;+ actualSteps = t2vTwoStage.steps;+ actualStage2Steps = t2vTwoStage.stage2Steps;+ console.log(`🎬 PORTOS_T2V_TWO_STAGE on — T2V Standard via fast two-stage (${actualSteps}/${actualStage2Steps} steps, cfg ${actualGuidance}) [${jobId.slice(0, 8)}]`);+ }// Caller may pass null/'' to use mlx_video's default (1.0 = preserve source).const actualImageStrength = imageStrength != null && imageStrength !== '' ? Number(imageStrength) : null;const actualTextEncoderRepo = getTextEncoderRepo();@@ -724,7 +783,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// logic of the spawn-error handler so failure modes converge.let bin, args;try {- ({ bin, args } = buildArgs({ pythonPath, modelId, model, prompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, keyframes: resolvedKeyframes, extendFromVideoPath, audioFilePath, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, outputPath }));+ ({ bin, args } = buildArgs({ pythonPath, modelId, model, prompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, stage2Steps: actualStage2Steps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, keyframes: resolvedKeyframes, extendFromVideoPath, audioFilePath, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, outputPath }));} catch (err) {job.status = 'error';const reason = err.message || 'Failed to build video gen args';diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex f8bdf2980c..b8444c3551 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -458,6 +458,66 @@ describe('FFLF/ltx2 pixel-budget helpers', () => {});});+describe('resolveT2vTwoStageOverride — PORTOS_T2V_TWO_STAGE gate', () => {+ let resolveT2vTwoStageOverride;+ const ON = { PORTOS_T2V_TWO_STAGE: '1' };+ const FAST = { guidance: 1.0, steps: 8, stage2Steps: 3 };+ // A plain default T2V Standard render: ltx2, no mode, no conditioning, no+ // explicit guidance/steps.+ const plainT2V = { runtime: 'ltx2', mode: null, guidanceScale: null, steps: undefined };++ beforeEach(async () => {+ ({ resolveT2vTwoStageOverride } = await import('./local.js'));+ });++ it('returns the fast two-stage override for a plain T2V Standard render when the knob is on', () => {+ expect(resolveT2vTwoStageOverride({ ...plainT2V, env: ON })).toEqual(FAST);+ expect(resolveT2vTwoStageOverride({ ...plainT2V, mode: 'text', env: ON })).toEqual(FAST);+ });++ it('returns null when the knob is off / unset / non-truthy', () => {+ expect(resolveT2vTwoStageOverride({ ...plainT2V, env: {} })).toBeNull();+ expect(resolveT2vTwoStageOverride({ ...plainT2V, env: { PORTOS_T2V_TWO_STAGE: '0' } })).toBeNull();+ expect(resolveT2vTwoStageOverride({ ...plainT2V, env: { PORTOS_T2V_TWO_STAGE: 'false' } })).toBeNull();+ });++ it('accepts common truthy spellings (1/true/yes/on, case/space-insensitive)', () => {+ for (const v of ['1', 'true', 'TRUE', 'yes', 'on', ' On ']) {+ expect(resolveT2vTwoStageOverride({ ...plainT2V, env: { PORTOS_T2V_TWO_STAGE: v } })).toEqual(FAST);+ }+ });++ it('returns null for non-ltx2 runtimes even with the knob on', () => {+ expect(resolveT2vTwoStageOverride({ ...plainT2V, runtime: 'mlx_video', env: ON })).toBeNull();+ expect(resolveT2vTwoStageOverride({ ...plainT2V, runtime: 'wan22', env: ON })).toBeNull();+ });++ it('only applies to the default text mode, not conditioned modes', () => {+ for (const mode of ['image', 'fflf', 'a2v', 'extend']) {+ expect(resolveT2vTwoStageOverride({ ...plainT2V, mode, env: ON })).toBeNull();+ }+ });++ it('opts out when the user explicitly set guidance or steps (Standard only)', () => {+ expect(resolveT2vTwoStageOverride({ ...plainT2V, guidanceScale: 3.5, env: ON })).toBeNull();+ expect(resolveT2vTwoStageOverride({ ...plainT2V, guidanceScale: '7', env: ON })).toBeNull();+ expect(resolveT2vTwoStageOverride({ ...plainT2V, steps: 30, env: ON })).toBeNull();+ // Empty-string guidance is "not set" → still eligible.+ expect(resolveT2vTwoStageOverride({ ...plainT2V, guidanceScale: '', env: ON })).toEqual(FAST);+ });++ it('opts out when any conditioning input is present (not a plain T2V)', () => {+ expect(resolveT2vTwoStageOverride({ ...plainT2V, sourceImagePath: '/tmp/a.png', env: ON })).toBeNull();+ expect(resolveT2vTwoStageOverride({ ...plainT2V, uploadedTempPath: '/tmp/up.png', env: ON })).toBeNull();+ expect(resolveT2vTwoStageOverride({ ...plainT2V, uploadedTempPaths: ['/tmp/up.png'], env: ON })).toBeNull();+ expect(resolveT2vTwoStageOverride({ ...plainT2V, keyframes: [{ path: '/a', index: 0 }, { path: '/b', index: 8 }], env: ON })).toBeNull();+ expect(resolveT2vTwoStageOverride({ ...plainT2V, extendFromVideoPath: '/tmp/v.mp4', env: ON })).toBeNull();+ expect(resolveT2vTwoStageOverride({ ...plainT2V, audioFilePath: '/tmp/a.wav', env: ON })).toBeNull();+ // Empty arrays are not conditioning → still eligible.+ expect(resolveT2vTwoStageOverride({ ...plainT2V, uploadedTempPaths: [], keyframes: null, env: ON })).toEqual(FAST);+ });+});+describe('generateVideo — panel-side completion watchdog', () => {// Build a fake child that does NOT auto-exit, exposing handles to its stdout// 'data' listener and 'close' handler so the test can drive completion