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
feat: add selectable text encoders for the LTX-2.5 runtime (#4320)
[._.]/ Adam Eivy863bbc4795b7
diff --git a/.changelog/next/added-issue-4320.md b/.changelog/next/added-issue-4320.mdnew file mode 100644index 0000000000..8d4830806c--- /dev/null+++ b/.changelog/next/added-issue-4320.md@@ -0,0 +1 @@+- Video Gen: LTX-2.5 renders can now swap the prompt conditioner through a shim directory, the same affordance MiniMax H3 has — the two uncensored Gemma 4 substitutes ship gated until an A/B render confirms they stay coherent (#4320)diff --git a/docs/features/video-text-encoders.md b/docs/features/video-text-encoders.mdindex 4cef4dcc3a..d709ba5388 100644--- a/docs/features/video-text-encoders.md+++ b/docs/features/video-text-encoders.md@@ -1,9 +1,12 @@# Swappable video text encoders-Video Gen lets a MiniMax H3 render choose which **prompt conditioner** (text-encoder) reads the prompt. The picker sits under the Model field and defaults to-the conditioner that ships with the model, so nothing changes unless you pick-something else.+Video Gen lets a render choose which **prompt conditioner** (text encoder) reads+the prompt. The picker sits under the Model field and defaults to the conditioner+that ships with the model, so nothing changes unless you pick something else.++Two runtimes have a conditioner table: **MiniMax H3** (the substitutes below) and+**LTX-2.5**, whose mechanism ships but whose substitutes are still gated — see+[LTX-2.5](#ltx-25) at the end. Every other runtime has no picker at all.## Why H3's conditioner is swappable at all@@ -182,10 +185,81 @@ resident so you can switch back instantly. Resident memory during a render isunchanged (the same 50 layers + vision tower are loaded either way); only diskgrows.+## LTX-2.5++LTX-2.5 conditions through a Gemma 4 12B tower packed **inside** the model under+`text_encoder/`. The pinned fork's `PromptEncoder._text_encoder_source()` prefers+that directory unconditionally whenever its `config.json` reports+`model_type: "gemma4"` and ignores `gemma_model_id` entirely — which is why+`--gemma`, the flag the LTX-2.3 runtime uses, cannot substitute anything here.+A 2.5 substitution overrides that **resolution** instead.++**The shim.** `build_ltx25_encoder_shim()` in `scripts/generate_ltx2.py` builds+`~/.portos/ltx25-encoder-shims/<id>/` from scratch each render: every pinned file+of the substitute linked in by basename (the shards, their+`model.safetensors.index.json`, the tokenizer and generation configs), plus a+generated `config.json`. Nothing comes from the model pack — unlike the H3 shim,+which must keep upstream's config, tokenizer and processor, a Gemma 4 tower is+self-describing and the pack contributes only its connector, loaded separately.++`config.json` is generated rather than linked because two things have to change:+`vision_config` / `audio_config` are dropped (so what remains is the+`model_type` + `text_config` + `quantization` triple the fork's own+`convert_ltx25_to_mlx.py --step text-encoder` emits), and the registry entry's+`configOverrides` are merged over the rest. That field exists for exactly one+correction — a *unified* Gemma 4 checkpoint publishes+`model_type: "gemma4_unified"`, which `Gemma4LanguageModel.load()` hard-rejects,+and it is the only thing such a checkpoint gets wrong, since mlx-lm's+`gemma4.Model.sanitize()` already discards the `vision_tower.*` / `audio_tower.*`+/ `multi_modal_projector.*` towers at load. The `quantization` block is never+overridden: per-layer group-size overrides are part of how the weights were+packed, and a mismatch dequantizes to noise.++**The override.** `install_ltx25_encoder_override()` patches+`PromptEncoder._text_encoder_source` on the **class**, once, before any pipeline+is constructed — so no render mode can build a pipeline that skips it, including+one added later. The wrapper delegates to the original to obtain the encoder+class, then swaps only the path, which means nothing imports+`Gemma4LanguageModel` from a path the pinned fork could move; a model dir that+does *not* resolve to it (an LTX-2.3 pack reached through this flag) fails loudly+rather than conditioning on the wrong architecture. The pinned fork source is+never edited.++### The candidate has to be Gemma 4 12B at the LTX-2.5 geometry++48 layers, `hidden_size` 3840, `vocab_size` 262144, `head_dim` 256,+`attention_k_eq_v: true` — `Gemma4LanguageModel` hard-validates `model_type`, the+layer count and the hidden size on load, and the pack's connector was trained+against a 49-hidden-state stack of that width. Those are stock+`google/gemma-4-12B-it` dimensions, which is what makes an off-the-shelf+abliterated Gemma 4 12B a plausible drop-in. A different Gemma generation is not:+Gemma 3's tokenizer, vocabulary and layer count have no mapping onto the module+tree mlx-lm's `gemma4` builds.++### Status: substitutes gated pending a coherence check++Two substitutes are declared in the registry (`ltx25-abliterated-4bit`,+`ltx25-heretic-8bit`) and both carry `verified: false`, which keeps them out of+the picker **and** out of the download lane — an unverified id is rejected by+route validation and its weights cannot be pulled. The LTX-2.5 picker therefore+hides itself today, exactly as it does for a runtime with no substitutes at all.++What is unsettled is empirical, not structural: Lightricks'+`gemma4-12b-with-proj-ltx-2.5` tower may be LTX-fine-tuned rather than stock+`google/gemma-4-12B-it`, in which case a stock-derived abliterated tower would+feed the pack's connector out-of-distribution features and render incoherently.+To settle it, flip an entry to `verified: true` locally, download it from Media+Models, then render the same prompt/seed/steps/resolution against the stock+conditioner and against the substitute — once on a benign prompt (does it stay+structurally coherent?) and once on a prompt the stock conditioner waters down+(does it read differently?). Ship the flag flip only for a substitute that passes+both, and record a failure in the module docblock rather than deleting the entry.+## Related- `server/lib/videoTextEncoders.js` — the registry, and the one place a new entry goes-- `scripts/generate_minimax_h3.py` — the shim builder and key remap+- `scripts/generate_minimax_h3.py` — the H3 shim builder and key remap+- `scripts/generate_ltx2.py` — the LTX-2.5 shim builder and resolution override- `server/services/videoGen/local.js` — cache resolution and argv- `client/src/components/videoGen/TextEncoderPicker.jsx` — the control- `client/src/hooks/useModelDownloadStatus.js` — `startWhenIdle`, the select-starts-the-pull mechanism (generic: any gated-weight picker can adopt it)diff --git a/scripts/generate_ltx2.py b/scripts/generate_ltx2.pyindex 3a13f9509d..847d341fd0 100644--- a/scripts/generate_ltx2.py+++ b/scripts/generate_ltx2.py@@ -60,6 +60,8 @@ import importlibimport inspectimport jsonimport os+import re+import shutilimport sysfrom pathlib import Pathfrom typing import NoReturn@@ -369,6 +371,16 @@ def parse_args() -> argparse.Namespace:p.add_argument("--gemma", default=None,help="Shared Gemma repo for LTX-2.3. Omit on LTX-2.5 packs that ""ship Gemma 4 under text_encoder/.")+ p.add_argument("--text-encoder-id",+ help="id of the substituted LTX-2.5 prompt conditioner (shim directory name)")+ p.add_argument("--text-encoder-file", action="append", default=[],+ help="an already-cached file of the substitute — shards, the shard index and the "+ "tokenizer/generation configs (repeatable; the whole pinned set)")+ p.add_argument("--text-encoder-shim-root",+ help="directory the composed conditioner root is built under")+ p.add_argument("--text-encoder-config-json", default=None,+ help="JSON object merged over the substitute's own config.json in the shim "+ "(e.g. {\"model_type\": \"gemma4\"} for a unified checkpoint)")p.add_argument("--height", type=int, default=480)p.add_argument("--width", type=int, default=704)p.add_argument("--num-frames", type=int, default=97)@@ -460,6 +472,136 @@ def parse_args() -> argparse.Namespace:return p.parse_args()+def parse_text_encoder_config_overrides(raw: str | None) -> dict:+ """Parse `--text-encoder-config-json` into the dict merged over the shim config."""+ if not raw:+ return {}+ try:+ parsed = json.loads(raw)+ except json.JSONDecodeError as exc:+ raise SystemExit(f"--text-encoder-config-json must be valid JSON: {exc}") from exc+ if not isinstance(parsed, dict):+ raise SystemExit(+ f"--text-encoder-config-json must be a JSON object; got {type(parsed).__name__}."+ )+ return parsed+++def validate_text_encoder_args(args: argparse.Namespace) -> None:+ """Reject a partial substitution set before any weights load.++ All-or-nothing, mirroring generate_minimax_h3.py: without the id there is+ nowhere to build the shim, and without the shim root there is nowhere to put+ it. Accepting a partial set would silently fall back to the conditioner+ packed in the model and hand the user a render they'd have no way to tell+ apart from a substituted one.+ """+ encoder_flags = (args.text_encoder_id, args.text_encoder_file, args.text_encoder_shim_root)+ if any(encoder_flags) and not all(encoder_flags):+ raise SystemExit(+ "--text-encoder-id, --text-encoder-file and --text-encoder-shim-root must be given together."+ )+ if args.text_encoder_id and not re.fullmatch(r"[A-Za-z0-9._-]+", args.text_encoder_id):+ raise SystemExit(f"--text-encoder-id must be a bare directory-safe name; got {args.text_encoder_id!r}.")+ if not args.text_encoder_file and args.text_encoder_config_json:+ raise SystemExit("--text-encoder-config-json needs --text-encoder-file.")+ # A substitution and the 2.3 shared encoder are mutually exclusive: --gemma+ # is only read when the pack ships no local gemma4 tower, which is exactly+ # the case where the override below has nothing to replace.+ if args.text_encoder_file and args.gemma:+ raise SystemExit("--text-encoder-file substitutes an LTX-2.5 pack's own conditioner; --gemma cannot apply.")+ parse_text_encoder_config_overrides(args.text_encoder_config_json)+++def build_ltx25_encoder_shim(+ shim_root: Path,+ encoder_id: str,+ encoder_files: list[Path],+ config_overrides: dict,+) -> Path:+ """Compose a standalone Gemma 4 checkpoint directory from the substitute.++ Unlike the MiniMax H3 shim next door — which links an upstream checkpoint+ root through and swaps only `text_encoder/` — everything here comes from the+ substitute: mlx-lm loads a Gemma 4 tower from one self-describing directory,+ and the LTX-2.5 pack contributes only its connector, which is loaded+ separately and never sees this path.++ Every pinned file is linked in under its own basename: the shards, the+ `model.safetensors.index.json` that names them, and the tokenizer /+ generation configs. Only `config.json` is generated, because two things must+ change before `Gemma4LanguageModel.load()` will accept it — `model_type`+ (a unified checkpoint publishes `gemma4_unified`, which that loader+ hard-rejects) and the `vision_config` / `audio_config` blocks, dropped so+ what remains matches what the fork's own converter emits. The substitute's+ `quantization` block is copied verbatim: its per-layer group-size overrides+ are part of how the weights were packed, and a mismatch dequantizes to noise.++ Rebuilt from scratch on every render — the links are free, and a stale shim+ pointing at a blob the user has since re-downloaded would otherwise load+ silently-wrong weights.+ """+ for encoder_file in encoder_files:+ if not encoder_file.is_file():+ raise RuntimeError(f"Substituted text encoder is missing: {encoder_file}")+ names = [f.name for f in encoder_files]+ if len(set(names)) != len(names):+ raise RuntimeError(f"Substituted text encoder has duplicate file names: {sorted(names)}")+ source_config = next((f for f in encoder_files if f.name == "config.json"), None)+ if source_config is None:+ raise RuntimeError("Substituted text encoder must pin its own config.json.")++ root = shim_root / encoder_id+ shutil.rmtree(root, ignore_errors=True)+ root.mkdir(parents=True, exist_ok=True)++ for encoder_file in encoder_files:+ # config.json is generated below, not linked: linking it through would+ # hand the loader the very `model_type` the override exists to correct.+ if encoder_file.name != "config.json":+ (root / encoder_file.name).symlink_to(encoder_file)++ config = json.loads(source_config.read_text(encoding="utf-8"))+ config.pop("vision_config", None)+ config.pop("audio_config", None)+ config.update(config_overrides)+ (root / "config.json").write_text(json.dumps(config, indent=2), encoding="utf-8")++ return root+++def install_ltx25_encoder_override(shim_dir: Path) -> None:+ """Point the pack's conditioner resolution at the shim, for every pipeline.++ ``PromptEncoder._text_encoder_source`` prefers a local ``text_encoder/``+ reporting ``model_type: "gemma4"`` unconditionally and ignores+ ``gemma_model_id``, so a substitution has to override that method rather than+ pass an argument. Patched on the CLASS — not on a constructed pipeline — so+ it cannot be skipped by a mode that builds its pipeline differently, or by a+ mode added later. This is the same shape as+ ``generate_minimax_h3.install_key_prefix_map``.++ The wrapped original still resolves the encoder CLASS, so nothing here has to+ import ``Gemma4LanguageModel`` from a path the pinned fork could move — and a+ pack that does NOT resolve to it (an LTX-2.3 model dir reached through this+ flag) fails loudly instead of conditioning on the wrong architecture.+ """+ from ltx_pipelines_mlx.utils.blocks import PromptEncoder++ original = PromptEncoder._text_encoder_source++ def _text_encoder_source(self):+ _, encoder_class = original(self)+ if encoder_class.__name__ != "Gemma4LanguageModel":+ raise RuntimeError(+ "A substituted text encoder needs an LTX-2.5 pack whose own conditioner is gemma4; "+ f"this model dir resolves to {encoder_class.__name__}."+ )+ return str(shim_dir), encoder_class++ PromptEncoder._text_encoder_source = _text_encoder_source++def _apply_user_loras(pipe, specs: list[tuple[str, float]]) -> None:"""Set the pipeline's _pending_loras hook so user-LoRA deltas fuse into thetransformer at load time.@@ -1031,10 +1173,25 @@ def maybe_strip_audio(output_path: str) -> None:def main() -> NoReturn:args = parse_args()+ validate_text_encoder_args(args)# One-line runtime fingerprint at startup — captured by PortOS onto the# render record so garbled output can be tied to a specific ltx/mlx stack.emit_runtime_fingerprint("ltx2", ["ltx_pipelines_mlx", "ltx_core_mlx", "mlx", "mlx_metal"])Path(args.output).parent.mkdir(parents=True, exist_ok=True)+ # Substituted LTX-2.5 prompt conditioner (#4320). Installed BEFORE any+ # runner builds its pipeline, so every mode picks it up from the class.+ if args.text_encoder_file:+ # Bare phase marker plus a separate STATUS line: the SSE parser reads+ # field 2 of a STAGE frame as `step`/`heartbeat`, so the encoder id+ # cannot ride along in the marker itself.+ print("STAGE:swap-text-encoder", file=sys.stderr, flush=True)+ emit_status(f"Conditioning with the {args.text_encoder_id} text encoder")+ install_ltx25_encoder_override(build_ltx25_encoder_shim(+ Path(args.text_encoder_shim_root),+ args.text_encoder_id,+ [Path(f) for f in args.text_encoder_file],+ parse_text_encoder_config_overrides(args.text_encoder_config_json),+ ))# Parse user LoRAs once up-front (strict validation surfaces bad input# before any model load). Each run_* sets pipe._pending_loras from this.args.user_lora_specs = parse_user_loras(args.user_loras)diff --git a/scripts/generate_ltx2.test.js b/scripts/generate_ltx2.test.jsnew file mode 100644index 0000000000..802e455c88--- /dev/null+++ b/scripts/generate_ltx2.test.js@@ -0,0 +1,325 @@+import { execFileSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { describe, expect, it } from 'vitest';+import { resolveTestPython } from '../server/lib/testHelper.js';++const script = join(dirname(fileURLToPath(import.meta.url)), 'generate_ltx2.py');++// Probe for an interpreter that actually RUNS rather than assuming a name — on+// Windows a bare `python` can be a Store alias STUB that exists and exits+// non-zero. Null when there is genuinely none, so the suite skips rather than+// failing. Every helper exercised here is import-free by design (stdlib only),+// so no mlx/ltx wheel is needed.+const pyBin = resolveTestPython();+const runPython = (source) => execFileSync(pyBin, ['-c', source, script], { encoding: 'utf8' });++const importRunner = [+ 'import importlib.util, sys',+ 'from pathlib import Path',+ 'script = Path(sys.argv[1])',+ 'spec = importlib.util.spec_from_file_location("generate_ltx2", script)',+ 'runner = importlib.util.module_from_spec(spec)',+ 'spec.loader.exec_module(runner)',+].join('\n');++// validate_text_encoder_args reads the namespace argparse produces, so every+// field it touches has to be present — a hand-built literal per test drifts the+// moment a flag is added (and fails as an AttributeError rather than an+// assertion). One builder carries the parser's own defaults; each test overrides+// only what it exercises.+const VALIDATE_ARGS_DEFAULTS = {+ gemma: null,+ text_encoder_id: null,+ text_encoder_file: [],+ text_encoder_shim_root: null,+ text_encoder_config_json: null,+};+const argsExpr = (overrides = {}) => {+ const fields = Object.entries({ ...VALIDATE_ARGS_DEFAULTS, ...overrides })+ .map(([key, value]) => `${key}=${value === null ? 'None' : JSON.stringify(value)}`);+ return `args = SimpleNamespace(${fields.join(', ')})`;+};++describe.skipIf(!pyBin)('generate_ltx2.py', () => {+ // A partial flag set would silently fall back to the conditioner packed in the+ // 2.5 model and hand back a render the user has no way to tell apart from the+ // one they asked for, so the boundary rejects it instead of choosing for them.+ it.each([+ [{ text_encoder_id: 'ltx25-heretic-8bit' }, /must be given together/i],+ [{ text_encoder_file: ['/tmp/config.json'] }, /must be given together/i],+ [+ { text_encoder_id: 'ltx25-heretic-8bit', text_encoder_file: ['/tmp/config.json'] },+ /must be given together/i,+ ],+ // A traversal-shaped id would put the shim tree outside the root PortOS+ // chose — and `rmtree` it from there on the next render.+ [+ {+ text_encoder_id: '../escape',+ text_encoder_file: ['/tmp/config.json'],+ text_encoder_shim_root: '/tmp/shims',+ },+ /bare directory-safe name/i,+ ],+ // A config rewrite with nothing to rewrite: accepting it would imply the+ // stock conditioner's config gets patched, which the shim never touches.+ [{ text_encoder_config_json: '{"model_type": "gemma4"}' }, /needs --text-encoder-file/i],+ // --gemma is only read when the pack ships no local gemma4 tower, which is+ // exactly the case where the override has nothing to replace.+ [+ {+ gemma: 'mlx-community/gemma-3-12b-it-4bit',+ text_encoder_id: 'ltx25-heretic-8bit',+ text_encoder_file: ['/tmp/config.json'],+ text_encoder_shim_root: '/tmp/shims',+ },+ /--gemma cannot apply/i,+ ],+ [+ {+ text_encoder_id: 'ltx25-heretic-8bit',+ text_encoder_file: ['/tmp/config.json'],+ text_encoder_shim_root: '/tmp/shims',+ text_encoder_config_json: 'not json',+ },+ /must be valid JSON/i,+ ],+ // A bare array/string would silently contribute no keys to the merge.+ [+ {+ text_encoder_id: 'ltx25-heretic-8bit',+ text_encoder_file: ['/tmp/config.json'],+ text_encoder_shim_root: '/tmp/shims',+ text_encoder_config_json: '["model_type"]',+ },+ /must be a JSON object/i,+ ],+ ])('rejects an incoherent text-encoder argument set (%j)', (overrides, pattern) => {+ const output = runPython(`${importRunner}\n${[+ 'from types import SimpleNamespace',+ argsExpr(overrides),+ 'try:',+ ' runner.validate_text_encoder_args(args)',+ 'except SystemExit as exc:',+ ' print(str(exc))',+ 'else:',+ ' raise SystemExit("incoherent text-encoder args were accepted")',+ ].join('\n')}`);+ expect(output).toMatch(pattern);+ });++ it.each([+ ['a complete set', {+ text_encoder_id: 'ltx25-heretic-8bit',+ text_encoder_file: ['/tmp/config.json', '/tmp/model-00001-of-00003.safetensors'],+ text_encoder_shim_root: '/tmp/shims',+ text_encoder_config_json: '{"model_type": "gemma4"}',+ }],+ // The stock choice: no flags at all, and --gemma still allowed because that+ // is the untouched LTX-2.3 path through the same runner.+ ['no flags at all', {}],+ ['the 2.3 shared encoder alone', { gemma: 'mlx-community/gemma-3-12b-it-4bit' }],+ ])('accepts %s', (_label, overrides) => {+ const output = runPython(`${importRunner}\n${[+ 'from types import SimpleNamespace',+ argsExpr(overrides),+ 'runner.validate_text_encoder_args(args)',+ 'print("ok")',+ ].join('\n')}`);+ expect(output.trim()).toBe('ok');+ });++ // The shim is a STANDALONE Gemma 4 checkpoint dir — unlike the H3 sibling it+ // links nothing through from the model pack, because mlx-lm loads a Gemma 4+ // tower from one self-describing directory.+ it('links every pinned file and generates config.json from the substitute', () => {+ const output = runPython(`${importRunner}\n${[+ 'import json, tempfile',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' root = Path(temp)',+ ' src = root / "src"',+ ' src.mkdir()',+ ' (src / "config.json").write_text(json.dumps({',+ ' "model_type": "gemma4_unified",',+ ' "text_config": {"num_hidden_layers": 48, "hidden_size": 3840},',+ ' "quantization": {"group_size": 32, "bits": 8},',+ ' "vision_config": {"drop": True},',+ ' "audio_config": {"drop": True},',+ ' }))',+ ' for name in ("model-00001-of-00002.safetensors", "model-00002-of-00002.safetensors",',+ ' "model.safetensors.index.json", "tokenizer.json", "tokenizer_config.json"):',+ ' (src / name).write_text(name)',+ ' files = sorted(src.iterdir())',+ ' shim = runner.build_ltx25_encoder_shim(',+ ' root / "shims", "ltx25-heretic-8bit", files, {"model_type": "gemma4"})',+ ' print(json.dumps({',+ ' "name": shim.name,',+ ' "linked": sorted(p.name for p in shim.iterdir()),',+ ' "config": json.loads((shim / "config.json").read_text()),',+ ' "config_is_link": (shim / "config.json").is_symlink(),',+ ' "shard_resolves": (shim / "tokenizer.json").read_text(),',+ ' }))',+ ].join('\n')}`);+ const result = JSON.parse(output);+ expect(result.name).toBe('ltx25-heretic-8bit');+ // Every pinned file is present, config.json among them — but generated.+ expect(result.linked).toEqual([+ 'config.json',+ 'model-00001-of-00002.safetensors',+ 'model-00002-of-00002.safetensors',+ 'model.safetensors.index.json',+ 'tokenizer.json',+ 'tokenizer_config.json',+ ]);+ expect(result.config_is_link).toBe(false);+ expect(result.shard_resolves).toBe('tokenizer.json');+ // The one label Gemma4LanguageModel.load() hard-rejects, corrected…+ expect(result.config.model_type).toBe('gemma4');+ // …the towers mlx-lm's sanitizer discards anyway, dropped so what remains+ // matches what the fork's own converter emits…+ expect(result.config.vision_config).toBeUndefined();+ expect(result.config.audio_config).toBeUndefined();+ // …and the packing metadata copied verbatim: a group-size mismatch+ // dequantizes to noise.+ expect(result.config.quantization).toEqual({ group_size: 32, bits: 8 });+ expect(result.config.text_config).toEqual({ num_hidden_layers: 48, hidden_size: 3840 });+ });++ // A text-only export already reports `gemma4`, so it declares no overrides —+ // the shim still regenerates config.json (to drop the towers), it just changes+ // no label.+ it('generates config.json unchanged when there are no overrides', () => {+ const output = runPython(`${importRunner}\n${[+ 'import json, tempfile',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' root = Path(temp)',+ ' src = root / "src"',+ ' src.mkdir()',+ ' (src / "config.json").write_text(json.dumps({"model_type": "gemma4", "text_config": {"a": 1}}))',+ ' (src / "model.safetensors").write_text("w")',+ ' shim = runner.build_ltx25_encoder_shim(root / "shims", "ltx25-abliterated-4bit",',+ ' sorted(src.iterdir()), {})',+ ' print(json.dumps(json.loads((shim / "config.json").read_text())))',+ ].join('\n')}`);+ expect(JSON.parse(output)).toEqual({ model_type: 'gemma4', text_config: { a: 1 } });+ });++ // Rebuilt from scratch every render: a stale shim pointing at a blob the user+ // has since re-downloaded would otherwise load silently-wrong weights.+ it('replaces a stale shim rather than merging into it', () => {+ const output = runPython(`${importRunner}\n${[+ 'import json, tempfile',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' root = Path(temp)',+ ' src = root / "src"',+ ' src.mkdir()',+ ' (src / "config.json").write_text(json.dumps({"model_type": "gemma4"}))',+ ' (src / "model.safetensors").write_text("fresh")',+ ' stale = root / "shims" / "ltx25-abliterated-4bit"',+ ' stale.mkdir(parents=True)',+ ' (stale / "model-00009-of-00009.safetensors").write_text("stale")',+ ' shim = runner.build_ltx25_encoder_shim(root / "shims", "ltx25-abliterated-4bit",',+ ' sorted(src.iterdir()), {})',+ ' print(json.dumps(sorted(p.name for p in shim.iterdir())))',+ ].join('\n')}`);+ expect(JSON.parse(output)).toEqual(['config.json', 'model.safetensors']);+ });++ it.each([+ [+ 'a file that is not on disk',+ [' files = [src / "config.json", root / "absent.safetensors"]'],+ /Substituted text encoder is missing/,+ ],+ // Every file is linked by basename, so two same-named files from different+ // subdirectories would collide on one symlink name.+ [+ 'two files with the same basename',+ [+ ' (src / "nested").mkdir()',+ ' (src / "nested" / "config.json").write_text("{}")',+ ' files = [src / "config.json", src / "nested" / "config.json"]',+ ],+ /duplicate file names/,+ ],+ // The generated config.json is derived from the substitute's own, so an+ // entry that never pinned it has nothing to derive from.+ [+ 'a file set with no config.json',+ [' files = [src / "model.safetensors"]'],+ /must pin its own config\.json/,+ ],+ ])('refuses to build a shim from %s', (_label, setup, pattern) => {+ const output = runPython(`${importRunner}\n${[+ 'import json, tempfile',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' root = Path(temp)',+ ' src = root / "src"',+ ' src.mkdir()',+ ' (src / "config.json").write_text(json.dumps({"model_type": "gemma4"}))',+ ' (src / "model.safetensors").write_text("w")',+ ...setup,+ ' try:',+ ' runner.build_ltx25_encoder_shim(root / "shims", "e", files, {})',+ ' except RuntimeError as exc:',+ ' print(str(exc))',+ ' else:',+ ' raise SystemExit("an unbuildable shim was accepted")',+ ].join('\n')}`);+ expect(output).toMatch(pattern);+ });++ // Patched on the CLASS, not on a constructed pipeline, so no mode — present or+ // added later — can build a pipeline that skips the substitution.+ const stubPromptEncoder = (encoderClassName) => [+ 'import sys, types',+ 'pkg = types.ModuleType("ltx_pipelines_mlx")',+ 'utils = types.ModuleType("ltx_pipelines_mlx.utils")',+ 'blocks = types.ModuleType("ltx_pipelines_mlx.utils.blocks")',+ `class ${encoderClassName}: pass`,+ 'class PromptEncoder:',+ ' def _text_encoder_source(self):',+ ` return "/packed/text_encoder", ${encoderClassName}`,+ 'blocks.PromptEncoder = PromptEncoder',+ 'sys.modules["ltx_pipelines_mlx"] = pkg',+ 'sys.modules["ltx_pipelines_mlx.utils"] = utils',+ 'sys.modules["ltx_pipelines_mlx.utils.blocks"] = blocks',+ ];++ it('redirects the packed conditioner resolution at the shim for every instance', () => {+ const output = runPython(`${importRunner}\n${[+ ...stubPromptEncoder('Gemma4LanguageModel'),+ 'runner.install_ltx25_encoder_override(Path("/shims/ltx25-heretic-8bit"))',+ // A pipeline constructed AFTER the patch and one whose class was captured+ // before it both resolve to the shim — that is the point of patching the+ // class rather than an instance.+ 'path, cls = PromptEncoder()._text_encoder_source()',+ 'print(path)',+ // The encoder CLASS still comes from the pinned fork's own resolution, so+ // nothing here imports it from a path the fork could move.+ 'print(cls.__name__)',+ ].join('\n')}`);+ expect(output.trim().split('\n')).toEqual([+ join('/shims', 'ltx25-heretic-8bit'),+ 'Gemma4LanguageModel',+ ]);+ });++ // Reaching this flag on an LTX-2.3 model dir would condition on a Gemma 3+ // tower loaded from a Gemma 4 shim — fail loudly instead.+ it('refuses to substitute into a pack whose own conditioner is not gemma4', () => {+ const output = runPython(`${importRunner}\n${[+ ...stubPromptEncoder('GemmaLanguageModel'),+ 'runner.install_ltx25_encoder_override(Path("/shims/e"))',+ 'try:',+ ' PromptEncoder()._text_encoder_source()',+ 'except RuntimeError as exc:',+ ' print(str(exc))',+ 'else:',+ ' raise SystemExit("a non-gemma4 pack was substituted into")',+ ].join('\n')}`);+ expect(output).toMatch(/needs an LTX-2\.5 pack whose own conditioner is gemma4/);+ expect(output).toMatch(/GemmaLanguageModel/);+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 4cc384858a..11b7e092ed 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -116,10 +116,10 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `mediaModelBuckets.js` | Names and resolves the video registry's two model buckets (#4142). The split is by RUNTIME FAMILY — `mlx` (Apple MLX runtimes) vs `cuda` (plain torch+CUDA, which runs on Windows *and* Linux) — not by operating system, which is why `activeVideoBucket()` keys on `process.platform === 'darwin'` instead of on "is this Windows". `readVideoBucket` / `readVideoDefault` / `matchesVideoBucket` resolve the canonical key first and fall back to the pre-#4142 `macos` / `windows` / `defaultMacos` / `defaultWindows` spellings, so any registry written by an older install still loads untouched; `canonicalizeVideoBuckets` performs the one-time rename (migration 270 and the load-time twin in `mediaModels.js`). Kept separate from `mediaModels.js` so `scripts/migrations/` can share the alias resolution without importing the registry loader, which seeds `data/` as a side effect. || `mediaModels.js` | Single source of truth for image/video model metadata. Entry fields are documented in the module docblock — note `repoFiles[]`, which narrows a model's own repo to an explicit file list for an aggregate repo that holds far more than the runner loads (MiniMax H3 CUDA). || `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. |+| `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. `APACHE_2` / `GEMMA_TERMS` are the shared license descriptors `videoTextEncoders.js` reuses, so a license-text correction reaches both tables from one edit. || `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` / `minimax_h3_cuda` text+image+fflf off one shared array — 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`). |-| `videoTextEncoders.js` | Swappable prompt conditioners for local video runtimes. MiniMax H3 reads the *unnormalized* hidden state after Qwen3-VL language layer 49 (layers 50-63, the final norm and `lm_head` are never evaluated), so any checkpoint carrying the same embedding + layers 0-49 + vision tower is a drop-in conditioner — swapping it changes how the model reads a prompt without touching the diffusion weights. `TEXT_ENCODERS_BY_RUNTIME` declares the shipped options per runtime (pinned repo/revision plus an explicit `files` LIST — one repackaged safetensors, or just the shards of an upstream checkpoint that carry parameters the loader actually builds; in code rather than the media-models registry so a stale `data/media-models.json` can't name a file the runner can't map); `videoTextEncoderOptions(model)` returns the TRUE list stock-first (it deliberately does NOT collapse a one-entry runtime to `[]` — that is a presentation rule, and folding it in here would change what the server believes a model supports and empty the "offers …" list in the error; `TextEncoderPicker` owns the hide-when-there-is-no-real-choice check), `isStockTextEncoder(id)` makes absence and the `stock` sentinel the same request, `resolveVideoTextEncoder(model, id)` returns `null` for the stock choice or throws `VIDEO_TEXT_ENCODER_UNSUPPORTED` (with the non-throwing `supportsVideoTextEncoder` + `videoTextEncoderUnsupportedError` split out so the request path can reject before staging uploads), and `downloadableVideoTextEncoders()` (deduped by id — the table is keyed by RUNTIME, so one conditioner can be offered by two) / `downloadableVideoTextEncoder(id)` feed the `/api/video-gen/text-encoders/:id/(download\|repair)` lane. Two loader-mechanics fields exist because a ComfyUI-packaged conditioner is namespaced differently from the HF checkpoint the MLX port matches: `keyPrefixMap` (`model.` → `model.language_model.`, `visual.` → `model.visual.`) is applied to every checkpoint key by `scripts/generate_minimax_h3.py` BEFORE the pinned loader sees it — no fork of the pinned runtime — and `finalNormKey` names where the runner synthesizes a ones-filled `norm.weight` for a checkpoint published without one (correct upstream, since H3 reads the state *before* the norm, but the pinned loader refuses to load with any parameter missing). Both are absent for an UPSTREAM Qwen3-VL-32B checkpoint, which already uses the loader namespace and ships its own norm. A candidate must BE Qwen3-VL-32B (the shim reuses upstream's config/tokenizer/processor) — a different Qwen generation is not a substitute however close its conditioning width looks; see docs/features/video-text-encoders.md. `publicTextEncoderOption(entry)` is the client projection and deliberately drops both, so the UI can't reimplement the remap. |+| `videoTextEncoders.js` | Swappable prompt conditioners for local video runtimes. MiniMax H3 reads the *unnormalized* hidden state after Qwen3-VL language layer 49 (layers 50-63, the final norm and `lm_head` are never evaluated), so any checkpoint carrying the same embedding + layers 0-49 + vision tower is a drop-in conditioner — swapping it changes how the model reads a prompt without touching the diffusion weights. `TEXT_ENCODERS_BY_RUNTIME` declares the shipped options per runtime (pinned repo/revision plus an explicit `files` LIST — one repackaged safetensors, or just the shards of an upstream checkpoint that carry parameters the loader actually builds; in code rather than the media-models registry so a stale `data/media-models.json` can't name a file the runner can't map); `videoTextEncoderOptions(model)` returns the TRUE list stock-first (it deliberately does NOT collapse a one-entry runtime to `[]` — that is a presentation rule, and folding it in here would change what the server believes a model supports and empty the "offers …" list in the error; `TextEncoderPicker` owns the hide-when-there-is-no-real-choice check), `isStockTextEncoder(id)` makes absence and the `stock` sentinel the same request, `resolveVideoTextEncoder(model, id)` returns `null` for the stock choice or throws `VIDEO_TEXT_ENCODER_UNSUPPORTED` (with the non-throwing `supportsVideoTextEncoder` + `videoTextEncoderUnsupportedError` split out so the request path can reject before staging uploads), and `downloadableVideoTextEncoders()` (deduped by id — the table is keyed by RUNTIME, so one conditioner can be offered by two) / `downloadableVideoTextEncoder(id)` feed the `/api/video-gen/text-encoders/:id/(download\|repair)` lane. Two loader-mechanics fields exist because a ComfyUI-packaged conditioner is namespaced differently from the HF checkpoint the MLX port matches: `keyPrefixMap` (`model.` → `model.language_model.`, `visual.` → `model.visual.`) is applied to every checkpoint key by `scripts/generate_minimax_h3.py` BEFORE the pinned loader sees it — no fork of the pinned runtime — and `finalNormKey` names where the runner synthesizes a ones-filled `norm.weight` for a checkpoint published without one (correct upstream, since H3 reads the state *before* the norm, but the pinned loader refuses to load with any parameter missing). Both are absent for an UPSTREAM Qwen3-VL-32B checkpoint, which already uses the loader namespace and ships its own norm. A candidate must BE Qwen3-VL-32B (the shim reuses upstream's config/tokenizer/processor) — a different Qwen generation is not a substitute however close its conditioning width looks; see docs/features/video-text-encoders.md. `publicTextEncoderOption(entry)` is the client projection and deliberately drops both, so the UI can't reimplement the remap. The `ltx25` table (#4320) uses a third mechanic, `configOverrides`, because an LTX-2.5 pack's OWN Gemma 4 tower wins over `--gemma` inside the pinned fork: the substitution is a standalone shim directory whose generated `config.json` is the substitute's own with these keys merged over it (only ever the `model_type` label a unified checkpoint gets wrong — never `text_config`/`quantization`), and a candidate must BE Gemma 4 12B at 48 layers / hidden 3840 / vocab 262144 / `k_eq_v`. `verified` gates a substitute out of BOTH lanes (picker AND download) until it has been A/B-rendered against its runtime's stock conditioner — required on every non-built-in entry and fail-closed on absence, so a new entry is unreachable until someone states a verdict; both ltx25 substitutes are `verified: false` today. `declaredVideoTextEncoders()` is the UNFILTERED table for shape/invariant checks only — never the render or download path. || `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, model-flag scan helpers incl. `stripBrokenModelFlags`, `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`) plus reasoning-effort helpers for the claude/codex/agy CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `hasEffortFlag`, and `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`) plus codex startup-arg helpers (`CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal). || `providerVendors.js` | `PROVIDER_VENDORS` — one row per coding-agent CLI/TUI vendor (claude/codex/antigravity/opencode/grok/kimi/cursor, plus a deliberately-incomplete legacy `gemini-cli` row), consumed by every dispatch site that used to hand-roll its own vendor if-chain across ~8 branches in 5 files (#3618): `applyCommandDefaults`/`prepareCliPrompt` (re-exported from `tuiHandshake.js`/`cliProviderArgs.js`), `buildVendorCliArgs`/`buildVendorSpawnConfig` (consumed by `cliProviderArgs.js#buildCliArgs` / `agentCliSpawning.js#buildCliSpawnConfig`), `inferTuiCommand` (re-exported from `tuiHandshake.js`), and `injectTuiModelAndEffort` — the shared antigravity-validates-the-pair-vs-everyone-else `--model`/`--effort` injection used by both `tuiHandshake.js#buildTuiInvocation` and `agentTuiSpawning.js#buildTuiSpawnConfig`, replacing a second copy of that split that had already drifted once before this file existed. Doesn't rewrite any vendor's argv-building logic — that stays in `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`/`codex.js`. Dependency-light on purpose, mirroring those files. || `modelPricing.js` | Per-model API billing rates for the /devtools/usage cost estimates — `resolveModelRates(providerId, model)` (exact → family regex → provider default → blended fallback, with a `matched` tier; also derives `cacheReadPer1M`/`cacheWritePer1M` from the input rate via per-family multipliers), `isFreeProvider` (ollama/lmstudio/`ollamaBacked`/localhost = free), `estimateCostUsd(tokensIn, tokensOut, rates, cache?)` — `tokensIn` is UNCACHED input; cache tiers are priced separately via the optional 4th arg — and `PRICING_AS_OF`. Informational only (PortOS runs on subscriptions); still excludes batch/long-context tiers. |diff --git a/server/lib/videoDisclosure.js b/server/lib/videoDisclosure.jsindex 4f9d0d2303..25bc4255f0 100644--- a/server/lib/videoDisclosure.js+++ b/server/lib/videoDisclosure.js@@ -36,6 +36,11 @@ export const VIDEO_DISCLOSURE_REVIEWED_AT = '2026-08-09';// the same `disclosure` shape — a license-text correction here has to reach// both tables, which a second inline literal would prevent.export const APACHE_2 = { name: 'Apache-2.0', url: 'https://www.apache.org/licenses/LICENSE-2.0' };+// Every Gemma derivative stays under Google's Gemma Terms of Use, which travel+// with the weights — a repacker's card that declares Apache-2.0 is relicensing+// something it cannot, so the ltx25 conditioners in lib/videoTextEncoders.js+// disclose THIS rather than whatever their card happens to say.+export const GEMMA_TERMS = { name: 'Gemma Terms of Use', url: 'https://ai.google.dev/gemma/terms' };const TENCENT_HUNYUAN_WEIGHTS = {name: 'Tencent Hunyuan Community License',url: 'https://huggingface.co/tencent/HunyuanVideo/blob/main/LICENSE',diff --git a/server/lib/videoTextEncoders.js b/server/lib/videoTextEncoders.jsindex 4db2c8e37e..8f963cb54a 100644--- a/server/lib/videoTextEncoders.js+++ b/server/lib/videoTextEncoders.js@@ -45,10 +45,70 @@* however similar its conditioning width looks: Qwen3.5's linear-attention* layers, 248320-token vocabulary and separate tokenizer have no mapping onto* the module tree this loader builds, and no key remap can create one.+ *+ * ---------------------------------------------------------------------------+ * LTX-2.5 (#4320)+ *+ * The 2.5 packs condition through a Gemma 4 12B tower that ships INSIDE the+ * pack under `text_encoder/`, and the pinned fork's+ * `PromptEncoder._text_encoder_source` prefers that local directory+ * UNCONDITIONALLY whenever its `config.json` reports `model_type: "gemma4"` —+ * `gemma_model_id` (the `--gemma` flag the 2.3 runtime uses) is ignored. So a+ * 2.5 substitution overrides that RESOLUTION rather than passing a repo id,+ * which is why `ltx2` and `ltx25` share a runner but not a mechanism.+ *+ * The substitution is again a shim directory, but of a different shape than+ * H3's: the runner links the substitute's shards, its+ * `model.safetensors.index.json` and its tokenizer/generation configs into one+ * flat directory and writes `config.json` itself, then points the pinned+ * loader at that directory. Nothing comes from the pack, because unlike H3+ * (where the vision geometry and processor must stay upstream's) a Gemma 4+ * tower is self-describing.+ *+ * `configOverrides` is the one field this runtime adds: the shim's generated+ * `config.json` is the SUBSTITUTE's own config with these keys merged over it+ * (`vision_config` / `audio_config` are dropped either way, so what remains is+ * the `model_type` + `text_config` + `quantization` triple the fork's+ * `convert_ltx25_to_mlx.py --step text-encoder` emits). It exists because a+ * *unified* Gemma 4 checkpoint publishes `model_type: "gemma4_unified"`, which+ * `Gemma4LanguageModel.load()` hard-rejects — and that one string is the only+ * thing it gets wrong, since mlx-lm's `gemma4.Model.sanitize()` already+ * discards the `vision_tower.*` / `audio_tower.*` / `multi_modal_projector.*`+ * towers at load. Omit the field entirely for a text-only checkpoint that+ * already reports `gemma4`; the `quantization` block is NEVER overridden,+ * because per-layer group-size overrides are part of how the weights were+ * packed and a mismatched group size dequantizes to noise.+ *+ * COMPATIBILITY RULE for a new ltx25 entry: the checkpoint must be Gemma 4 12B+ * at the LTX-2.5 tower's exact geometry — 48 layers, hidden 3840, vocab 262144,+ * head_dim 256, `attention_k_eq_v: true` — because `Gemma4LanguageModel`+ * hard-validates `model_type`, the layer count and the hidden size on load, and+ * the pack's connector was trained against a 49-hidden-state stack of that+ * width. A different Gemma generation is not a substitute: Gemma 3's tokenizer,+ * vocabulary and layer count have no mapping onto the module tree mlx-lm's+ * `gemma4` builds.+ *+ * `verified` — PENDING COHERENCE CHECK. Both ltx25 substitutes below are+ * declared `verified: false` and are therefore hidden from `videoTextEncoderOptions`+ * and from the download lane (see `isOfferedTextEncoder`), so neither can be+ * selected in the picker or accepted by route validation. They stay in code+ * because the mechanism, the pins and the sizes are all settled; what is NOT+ * settled is whether Lightricks' `gemma4-12b-with-proj-ltx-2.5` tower is stock+ * `google/gemma-4-12B-it` or an LTX fine-tune. If it is a fine-tune, a+ * stock-derived abliterated tower feeds the pack's connector out-of-distribution+ * features and renders incoherently — which static analysis cannot settle.+ *+ * To settle it: flip an entry to `verified: true` locally, download it from+ * Media Models, then render the same prompt/seed/steps/resolution against the+ * stock conditioner and against the substitute — once on a benign prompt (does+ * it stay structurally coherent?) and once on a prompt the stock conditioner+ * waters down (does it actually read differently?). Ship the flag flip only for+ * a substitute that passes both; record a failure here rather than deleting the+ * entry, so the next person does not re-derive it.*/import { ServerError } from './errorHandler.js';-import { APACHE_2 } from './videoDisclosure.js';+import { APACHE_2, GEMMA_TERMS } from './videoDisclosure.js';// Every runtime's built-in conditioner option. Selected by default and always// present, so the picker never renders a single-option select and a render that@@ -62,6 +122,13 @@ const STOCK_MINIMAX_H3 = Object.freeze({builtIn: true,});+const STOCK_LTX25 = Object.freeze({+ id: STOCK_TEXT_ENCODER_ID,+ label: 'Stock — LTX-2.5 Gemma 4 12B',+ description: 'The Gemma 4 conditioner packed inside the LTX-2.5 model. Already downloaded with the model.',+ builtIn: true,+});+// Substitutable conditioners, keyed by the runtime whose loader can consume// them. A runtime absent from this table has no picker at all.const TEXT_ENCODERS_BY_RUNTIME = Object.freeze({@@ -73,6 +140,8 @@ const TEXT_ENCODERS_BY_RUNTIME = Object.freeze({description:'Abliterated Qwen3-VL-32B conditioner (Heretic v1.2.0, attention-targeted) repackaged for H3. '+ 'Reads prompts the stock conditioner refuses or waters down; the diffusion weights are unchanged.',+ // A/B-rendered against the stock conditioner at fixed seed in #4081.+ verified: true,repo: 'ethanfel/Qwen3-VL-32B-Ultra-Heretic-H3-ComfyUI-INT8-ConvRot',revision: 'e8967f6a39ea5b4939a1aff81be3e8706490c0e8',files: Object.freeze(['qwen3vl_32b_h3_ultra_uncensored_heretic_bf16.safetensors']),@@ -107,6 +176,7 @@ const TEXT_ENCODERS_BY_RUNTIME = Object.freeze({description:'Qwen3-VL-32B-Instruct abliterated by huihui-ai — a different refusal-removal method than the '+ 'Heretic substitute, so it reads prompts differently again. Upstream checkpoint, not a repack.',+ verified: true,repo: 'huihui-ai/Huihui-Qwen3-VL-32B-Instruct-abliterated',revision: '5e88d9b37e5dca1e95d434f5c4ddfa9b51b1591c',// The upstream shard layout, minus the two shards that hold ONLY language@@ -142,8 +212,101 @@ const TEXT_ENCODERS_BY_RUNTIME = Object.freeze({}),}),]),+ // LTX-2.5 (#4320). Unlike H3's, an ltx25 shim takes EVERYTHING from the+ // substitute — a Gemma 4 tower is self-describing — so `files` pins the+ // tokenizer, the shard index and the generation config alongside the shards+ // themselves. All of them are inputs to the shim the runner builds, and+ // `sizeBytes` is their exact published total.+ //+ // Both substitutes are `verified: false` pending the coherence check+ // described in the docblock: they are declared here but hidden from the+ // picker and from the download lane until an A/B render settles whether the+ // pack's connector accepts a stock-derived Gemma 4 tower.+ ltx25: Object.freeze([+ STOCK_LTX25,+ Object.freeze({+ id: 'ltx25-abliterated-4bit',+ label: 'Abliterated uncensored — Gemma 4 12B 4-bit',+ description:+ 'Abliterated Gemma 4 12B conditioner, text tower only, MLX 4-bit. Reads prompts the stock '+ + 'conditioner refuses or waters down; the diffusion weights are unchanged.',+ verified: false,+ repo: 'divinetribe/gemma-4-12B-it-abliterated-4bit-mlx-text',+ revision: '3f123973331780c8702344dad62445ab09436ef3',+ // Already the exact shape convert_ltx25_to_mlx.py emits — its config.json+ // reports `model_type: "gemma4"` — so no `configOverrides`. Every shard is+ // pinned: this is a text-only export with no tower the loader skips, so+ // there is no shard to leave out the way the huihui H3 entry does.+ files: Object.freeze([+ 'config.json',+ 'generation_config.json',+ 'chat_template.jinja',+ 'model-00001-of-00003.safetensors',+ 'model-00002-of-00003.safetensors',+ 'model-00003-of-00003.safetensors',+ 'model.safetensors.index.json',+ 'tokenizer.json',+ 'tokenizer_config.json',+ ]),+ sizeBytes: 10978240781,+ disclosure: Object.freeze({+ modelCardUrl: 'https://huggingface.co/divinetribe/gemma-4-12B-it-abliterated-4bit-mlx-text',+ weightsLicense: GEMMA_TERMS,+ reviewedAt: '2026-08-15',+ }),+ }),+ Object.freeze({+ id: 'ltx25-heretic-8bit',+ label: 'Heretic uncensored — Gemma 4 12B 8-bit',+ description:+ 'Gemma 4 12B abliterated with the Heretic method — the same family as the H3 Ultra-Heretic '+ + 'conditioner, at 8-bit. A unified checkpoint, so its extra towers are dropped at load.',+ verified: false,+ repo: 'culturerevolt/gemma-4-12b-heretic-abliterated-8bit-mlx',+ revision: '86c60c34eb11613fbaae0353e2bfac83a32ce8a3',+ // Published as `gemma4_unified`, which Gemma4LanguageModel.load()+ // hard-rejects. That one string is the ONLY thing it gets wrong: mlx-lm's+ // gemma4 sanitizer already discards the vision/audio towers, so the shim+ // rewrites the type and keeps the substitute's own `quantization` block+ // (group 32 with per-layer 64 overrides on the MLP projections) verbatim.+ configOverrides: Object.freeze({ model_type: 'gemma4' }),+ // All three shards, none skippable: shard 3 interleaves 233 language keys+ // with 17 audio/vision keys, so dropping it to save the towers would take+ // the tail of the language stack with it.+ files: Object.freeze([+ 'config.json',+ 'generation_config.json',+ 'chat_template.jinja',+ 'model-00001-of-00003.safetensors',+ 'model-00002-of-00003.safetensors',+ 'model-00003-of-00003.safetensors',+ 'model.safetensors.index.json',+ 'tokenizer.json',+ 'tokenizer_config.json',+ ]),+ sizeBytes: 12964622094,+ disclosure: Object.freeze({+ modelCardUrl: 'https://huggingface.co/culturerevolt/gemma-4-12b-heretic-abliterated-8bit-mlx',+ weightsLicense: GEMMA_TERMS,+ reviewedAt: '2026-08-15',+ }),+ }),+ ]),});+/**+ * `true` when an entry may be offered to a render at all.+ *+ * A substitute is only shippable once it has been A/B-rendered against the+ * runtime's stock conditioner (see the `verified` note in the docblock), and+ * "not yet checked" must not collapse into "fine" — so the flag is REQUIRED on+ * every non-built-in entry and absence fails closed. Applied to both lanes:+ * an unverified entry is neither offered to the picker (so route validation+ * rejects its id) nor listed as a download target (so its tens of GB can't be+ * pulled for something no render can select).+ */+const isOfferedTextEncoder = (entry) => !!entry.builtIn || entry.verified === true;+/*** Every conditioner option a model can render with, stock first — `[]` for a* runtime this build has no conditioner table for.@@ -154,7 +317,11 @@ const TEXT_ENCODERS_BY_RUNTIME = Object.freeze({* below) for a reason that is only about how a `<select>` looks. The picker* owns the hide-when-there-is-no-real-choice check.*/-export const videoTextEncoderOptions = (model) => TEXT_ENCODERS_BY_RUNTIME[model?.runtime] || [];+export const videoTextEncoderOptions = (model) =>+ (TEXT_ENCODERS_BY_RUNTIME[model?.runtime] || []).filter(isOfferedTextEncoder);++/** Every runtime this build declares conditioners for — what parity/shape tests enumerate. */+export const videoTextEncoderRuntimes = () => Object.keys(TEXT_ENCODERS_BY_RUNTIME);/** Resolve one option by id, or `null` when the model can't render with it. */export const videoTextEncoderOption = (model, id) =>@@ -211,10 +378,23 @@ export const resolveVideoTextEncoder = (model, id) => {// would mean two download targets and two status rows for one file.export const downloadableVideoTextEncoders = () => [...new Map(Object.values(TEXT_ENCODERS_BY_RUNTIME).flat()- .filter((entry) => !entry.builtIn)+ .filter((entry) => !entry.builtIn && isOfferedTextEncoder(entry)).map((entry) => [entry.id, entry]),).values()];+/**+ * Every substitute this build DECLARES, verified or not — the unfiltered table,+ * flattened.+ *+ * Exists so the shape invariants (pinned 40-hex revision, safe repo-relative+ * file list, exact `sizeBytes`, model card) are enforced on an entry the moment+ * it is written down, rather than only once someone flips `verified`. The render+ * and download paths must NOT use this: they go through `videoTextEncoderOptions`+ * / `downloadableVideoTextEncoders`, which apply the gate.+ */+export const declaredVideoTextEncoders = () => Object.values(TEXT_ENCODERS_BY_RUNTIME)+ .flat().filter((entry) => !entry.builtIn);+/** Resolve a downloadable conditioner by id for the download/repair routes. */export const downloadableVideoTextEncoder = (id) =>downloadableVideoTextEncoders().find((entry) => entry.id === id) || null;@@ -223,11 +403,13 @@ export const downloadableVideoTextEncoder = (id) =>* The client-facing projection of an option — exactly what the picker renders,* nothing more.*- * Deliberately drops `keyPrefixMap` / `finalNormKey` (loader mechanics that- * would only invite a client-side reimplementation of the remap), `revision`,- * and `files`: the client never addresses the weight by path — it passes the- * option's `id` and the server resolves the rest. `repo` stays because the- * download badge names it in its tooltip.+ * An allowlist, not a blocklist, so a new loader-mechanics field is invisible to+ * the client by default. It deliberately drops `keyPrefixMap` / `finalNormKey` /+ * `configOverrides` (mechanics that would only invite a client-side+ * reimplementation), `verified` (an entry that isn't offered never reaches the+ * client at all), `revision`, and `files`: the client never addresses the weight+ * by path — it passes the option's `id` and the server resolves the rest. `repo`+ * stays because the download badge names it in its tooltip.*/export const publicTextEncoderOption = (entry) => ({id: entry.id,diff --git a/server/lib/videoTextEncoders.parity.test.js b/server/lib/videoTextEncoders.parity.test.jsindex b8c0b42ec6..0c695a201c 100644--- a/server/lib/videoTextEncoders.parity.test.js+++ b/server/lib/videoTextEncoders.parity.test.js@@ -19,7 +19,9 @@*/import { describe, it, expect } from 'vitest';-import { STOCK_TEXT_ENCODER_ID, isStockTextEncoder, videoTextEncoderOptions } from './videoTextEncoders.js';+import {+ STOCK_TEXT_ENCODER_ID, isStockTextEncoder, videoTextEncoderOptions, videoTextEncoderRuntimes,+} from './videoTextEncoders.js';import {STOCK_TEXT_ENCODER_ID as CLIENT_STOCK_TEXT_ENCODER_ID,normalizeTextEncoderForModel,@@ -34,25 +36,35 @@ describe('video text-encoder client/server parity', () => {// The client emits this value in three places (initial state, the// model-change reset, the record restore). Every one of them must land on// something the server reads as "no override".- it('produces a sentinel the server accepts as no-override', () => {+ // Asserted per RUNTIME rather than for the one the table happened to hold+ // when this was written: every runtime's built-in entry has to normalize to+ // the same sentinel, or adding a table key silently breaks that runtime's+ // model-change reset while the H3 path keeps passing.+ it.each(videoTextEncoderRuntimes())('produces a sentinel the server accepts as no-override (%s)', (runtime) => {expect(isStockTextEncoder(CLIENT_STOCK_TEXT_ENCODER_ID)).toBe(true);expect(isStockTextEncoder(textEncoderIdFromRecord(undefined))).toBe(true);expect(isStockTextEncoder(textEncoderIdFromRecord(''))).toBe(true);- expect(isStockTextEncoder(normalizeTextEncoderForModel('gone', { runtime: 'minimax_h3' }))).toBe(true);+ expect(isStockTextEncoder(normalizeTextEncoderForModel('gone', { runtime }))).toBe(true);});// The server ships the true option list (including a lone built-in entry), so// the client's normalizer has to agree that a stock-only model offers no- // substitute to select.- it('agrees that the built-in option is the stock sentinel', () => {- const options = videoTextEncoderOptions({ runtime: 'minimax_h3' });+ // substitute to select. A runtime whose substitutes are all still gated+ // (ltx25, #4320) is exactly that case, and must normalize the same way.+ it.each(videoTextEncoderRuntimes())('agrees that the built-in option is the stock sentinel (%s)', (runtime) => {+ const options = videoTextEncoderOptions({ runtime });const builtIn = options.filter((option) => option.builtIn);expect(builtIn).toHaveLength(1);expect(builtIn[0].id).toBe(CLIENT_STOCK_TEXT_ENCODER_ID);- // A substitute the model really offers survives normalization unchanged.+ const model = { runtime, textEncoderOptions: options };+ // A substitute the model really offers survives normalization unchanged;+ // with none offered, the built-in is all there is to land on.const substitute = options.find((option) => !option.builtIn);- const model = { runtime: 'minimax_h3', textEncoderOptions: options };- expect(normalizeTextEncoderForModel(substitute.id, model)).toBe(substitute.id);+ if (substitute) {+ expect(normalizeTextEncoderForModel(substitute.id, model)).toBe(substitute.id);+ } else {+ expect(isStockTextEncoder(normalizeTextEncoderForModel(CLIENT_STOCK_TEXT_ENCODER_ID, model))).toBe(true);+ }});});diff --git a/server/lib/videoTextEncoders.test.js b/server/lib/videoTextEncoders.test.jsindex 4791b5374e..e695086d20 100644--- a/server/lib/videoTextEncoders.test.js+++ b/server/lib/videoTextEncoders.test.js@@ -9,11 +9,14 @@ import {downloadableVideoTextEncoders,downloadableVideoTextEncoder,publicTextEncoderOption,+ videoTextEncoderRuntimes,+ declaredVideoTextEncoders,} from './videoTextEncoders.js';import { isSafeHfRepoRelativePath } from './hfCache.js';const H3 = { id: 'minimax_h3_8bit', runtime: 'minimax_h3' };const LTX = { id: 'ltx2_unified', runtime: 'ltx2' };+const LTX25 = { id: 'ltx25_mlx_q8', runtime: 'ltx25' };describe('videoTextEncoders', () => {// An empty list is the signal the client uses to hide the picker entirely, so@@ -33,6 +36,29 @@ describe('videoTextEncoders', () => {expect(options.slice(1).every((option) => !option.builtIn)).toBe(true);});+ // The client selects options[0] by default, so a runtime whose list did not+ // lead with its built-in entry would silently start every render on a+ // substitute. Asserted across EVERY runtime rather than the one the tests+ // above happen to name, so a second table key can't ship mis-ordered.+ it('leads every runtime with exactly one built-in option', () => {+ const runtimes = videoTextEncoderRuntimes();+ expect(runtimes).toContain('minimax_h3');+ expect(runtimes).toContain('ltx25');+ for (const runtime of runtimes) {+ const options = videoTextEncoderOptions({ runtime });+ expect(options[0]).toMatchObject({ id: STOCK_TEXT_ENCODER_ID, builtIn: true });+ expect(options.filter((option) => option.builtIn)).toHaveLength(1);+ }+ });++ // Each runtime's built-in entry names ITS conditioner — the picker's default+ // row would otherwise tell an LTX-2.5 user their prompt runs through H3's+ // Qwen tower.+ it('describes each runtime built-in as its own packed conditioner', () => {+ expect(videoTextEncoderOption(H3, STOCK_TEXT_ENCODER_ID).label).toMatch(/Qwen3-VL/);+ expect(videoTextEncoderOption(LTX25, STOCK_TEXT_ENCODER_ID).label).toMatch(/Gemma 4/);+ });+// Absence and the stock sentinel have to mean the same thing everywhere: the// route drops the sentinel from persisted params, so a resumed render sends// absence where the original sent 'stock'.@@ -81,6 +107,99 @@ describe('videoTextEncoders', () => {expect(finalNormKey.startsWith('model.language_model.')).toBe(false);});+ // The ltx25 substitutes are declared but not yet coherence-checked against+ // the pack's connector (#4320 step 6), so they must be unreachable: not in+ // the picker, not accepted by route validation, and not downloadable — an+ // 11-13 GB pull for something no render can select is pure waste.+ describe('unverified substitutes', () => {+ const UNVERIFIED = ['ltx25-abliterated-4bit', 'ltx25-heretic-8bit'];++ it('offers ltx25 only its built-in conditioner', () => {+ expect(videoTextEncoderOptions(LTX25).map((option) => option.id)).toEqual([STOCK_TEXT_ENCODER_ID]);+ });++ it.each(UNVERIFIED)('refuses to resolve or download %s', (id) => {+ expect(supportsVideoTextEncoder(LTX25, id)).toBe(false);+ expect(() => resolveVideoTextEncoder(LTX25, id)).toThrow(/has no text encoder/);+ expect(downloadableVideoTextEncoder(id)).toBeNull();+ expect(downloadableVideoTextEncoders().map((entry) => entry.id)).not.toContain(id);+ });++ // "Not yet checked" must not collapse into "fine": the flag is required on+ // every substitute and only an explicit `true` opens the gate, so a new+ // entry is invisible until someone states a verdict rather than shipping by+ // omission.+ it('requires every declared substitute to state a verdict', () => {+ const declared = declaredVideoTextEncoders();+ expect(declared.length).toBeGreaterThan(downloadableVideoTextEncoders().length);+ for (const entry of declared) expect(typeof entry.verified).toBe('boolean');+ // Everything the two lanes DO expose said `true` — nothing rode in on an+ // absent or falsy flag.+ const offered = videoTextEncoderRuntimes()+ .flatMap((runtime) => videoTextEncoderOptions({ runtime }))+ .filter((option) => !option.builtIn)+ .concat(downloadableVideoTextEncoders());+ for (const entry of offered) expect(entry.verified).toBe(true);+ });++ // An unverified entry gets no shape checking from the download-lane loop+ // below (it isn't in that lane yet), so the pins are enforced here — a+ // floating revision or an unsafe path must fail when it is WRITTEN, not+ // months later when someone flips the flag.+ it('pins every declared substitute whether or not it is offered yet', () => {+ for (const entry of declaredVideoTextEncoders()) {+ expect(entry.repo).toBeTruthy();+ expect(entry.revision).toMatch(/^[0-9a-f]{40}$/);+ expect(entry.files.every(isSafeHfRepoRelativePath)).toBe(true);+ expect(new Set(entry.files.map((name) => name.split('/').pop())).size)+ .toBe(entry.files.length);+ expect(entry.sizeBytes).toBeGreaterThan(0);+ expect(entry.disclosure?.modelCardUrl).toMatch(/^https:\/\/huggingface\.co\//);+ }+ });++ // The shim reads the substitute's OWN config.json to generate the one it+ // writes, so an entry that never pinned it would fail in the runner with a+ // missing-file error minutes after the download completed.+ it('pins the config.json every ltx25 shim is generated from', () => {+ const ltx25 = declaredVideoTextEncoders().filter((entry) => entry.id.startsWith('ltx25-'));+ expect(ltx25.length).toBeGreaterThan(0);+ for (const entry of ltx25) {+ expect(entry.files).toContain('config.json');+ expect(entry.files).toContain('model.safetensors.index.json');+ expect(entry.files).toContain('tokenizer.json');+ }+ });++ // `configOverrides` corrects the ONE thing a unified checkpoint gets wrong.+ // Overriding `text_config` or `quantization` would change how the weights+ // are interpreted rather than how they are labelled — group-size drift+ // dequantizes to noise — so the field must stay a label fix.+ it('limits configOverrides to the model_type label', () => {+ for (const entry of declaredVideoTextEncoders()) {+ if (!entry.configOverrides) continue;+ expect(Object.keys(entry.configOverrides)).toEqual(['model_type']);+ expect(entry.configOverrides.model_type).toBe('gemma4');+ }+ // The text-only export already reports gemma4, so it declares none.+ expect(declaredVideoTextEncoders()+ .find((entry) => entry.id === 'ltx25-abliterated-4bit').configOverrides).toBeUndefined();+ expect(declaredVideoTextEncoders()+ .find((entry) => entry.id === 'ltx25-heretic-8bit').configOverrides)+ .toEqual({ model_type: 'gemma4' });+ });+ });++ // The picker offers a substitute only where its runtime's loader can consume+ // it — an id is never global, so H3's conditioners must stay off ltx25 and+ // vice versa even once both are verified.+ it('keeps a runtime\'s substitutes off the other runtimes', () => {+ expect(supportsVideoTextEncoder(LTX25, 'heretic-bf16')).toBe(false);+ expect(() => resolveVideoTextEncoder(LTX25, 'heretic-bf16'))+ .toThrow(/has no text encoder "heretic-bf16"/);+ expect(supportsVideoTextEncoder(H3, 'ltx25-abliterated-4bit')).toBe(false);+ });+it('rejects an id the model cannot load', () => {expect(supportsVideoTextEncoder(H3, 'nope')).toBe(false);expect(() => resolveVideoTextEncoder(H3, 'nope')).toThrow(/has no text encoder "nope"/);@@ -109,7 +228,10 @@ describe('videoTextEncoders', () => {// quantizations, generation tails or never-built layers the loader can't// use — tens of GB of waste per entry.expect(entry.files.length).toBeGreaterThan(0);- expect(entry.files.every((name) => name.endsWith('.safetensors'))).toBe(true);+ // Weights are the point; the companion files an ltx25 shim also pins+ // (shard index, tokenizer, generation config) are not weights, so the+ // shape rule is "carries weights", not "is nothing but weights".+ expect(entry.files.some((name) => name.endsWith('.safetensors'))).toBe(true);expect(new Set(entry.files).size).toBe(entry.files.length);// Through the same predicate the download target validates with, so the// registry can't declare a path the route would then reject at runtime.diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex 148de4845a..ef4fdaa2ad 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -52,6 +52,7 @@ import {} from '../../lib/icLoraWeights.js';import {LTX2_HELPER_SCRIPT,+ LTX25_ENCODER_SHIM_DIR,WAN22_VENV_PYTHON,WAN22_HELPER_SCRIPT,MINIMAX_H3_VENV_PYTHON,@@ -422,7 +423,35 @@ export const icLoraArgs = ({ mode, width, height, icReferencePaths, icLoraWeightreturn args;};-const buildLtx2Args = ({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, disableAudio, outputPath, textEncoderRepo, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {+/**+ * Shim flags for a substituted LTX-2.5 prompt conditioner (#4320), or `[]` for+ * the stock choice — so an unswapped render's argv is byte-identical to what it+ * was before the feature existed.+ *+ * A 2.5 pack's own Gemma 4 tower wins unconditionally inside the pinned fork+ * (`PromptEncoder._text_encoder_source` ignores `gemma_model_id` whenever the+ * pack ships a local `text_encoder/` reporting `model_type: "gemma4"`), so the+ * substitution is a shim directory the runner builds and then points that+ * resolution at — NOT a repo id on `--gemma`, which is why this shares no flag+ * with the ltx2 path. `textEncoder.paths` were already resolved against the HF+ * cache by generateVideo; the helper runs offline and never downloads.+ *+ * `--text-encoder-config-json` is emitted only when the entry declares+ * `configOverrides`, mirroring how the H3 builder omits its key-remap flags for+ * a checkpoint that needs none.+ */+export const ltx25TextEncoderArgs = (textEncoder) => {+ if (!textEncoder) return [];+ const args = ['--text-encoder-id', textEncoder.id];+ for (const path of textEncoder.paths) args.push('--text-encoder-file', path);+ args.push('--text-encoder-shim-root', LTX25_ENCODER_SHIM_DIR);+ if (Object.keys(textEncoder.configOverrides || {}).length > 0) {+ args.push('--text-encoder-config-json', JSON.stringify(textEncoder.configOverrides));+ }+ return args;+};++const buildLtx2Args = ({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, disableAudio, outputPath, textEncoderRepo, textEncoder, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {assertByovRuntimeInstalled(model.runtime);// Map PortOS UI modes to the helper's subcommand. Native extend on ltx2// routes to ExtendPipeline.extend_from_video — conditions on the entire@@ -536,6 +565,9 @@ const buildLtx2Args = ({ model, ltxModelPath, prompt, negativePrompt, width, hei// Gemma 3 encoder would either fail load or silently condition on the wrong// model. The 2.3 runtime still needs the explicit shared encoder.if (model.runtime === 'ltx2') args.push('--gemma', textEncoderRepo);+ // The 2.5 substitution, which overrides the pack's OWN conditioner rather+ // than naming a repo — the two runtimes share this builder but not a flag.+ if (model.runtime === 'ltx25') args.push(...ltx25TextEncoderArgs(textEncoder));// User LoRAs — fused into the transformer via the pipeline's _pending_loras// hook. Emitted as a JSON list of { path, strength }; generate_ltx2.py sets// pipe._pending_loras before generation so the deltas fuse at load time@@ -854,7 +886,7 @@ const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeight// runtime. Existing notapalindrome models default to runtime: 'mlx_video'// (or undefined in legacy registries — see backfillRuntime in mediaModels.js).if (isLtx2FamilyRuntime(model.runtime)) {- return buildLtx2Args({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, disableAudio, outputPath, textEncoderRepo, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 });+ return buildLtx2Args({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, disableAudio, outputPath, textEncoderRepo, textEncoder, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 });}// IC-LoRA remix modes are an LTX-2 primitive (ICLoraPipeline) — no other// runtime has an equivalent. The route guards this too, but a non-route@@ -1125,11 +1157,15 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m{ status: 400, code: 'VIDEO_TEXT_ENCODER_NOT_CACHED' },);}+ // Runtime-agnostic: each runner's arg builder reads only the loader+ // mechanics its own helper understands (H3 the key remap and final norm,+ // ltx25 the config overrides), so one resolution serves both.resolvedTextEncoder = {id: textEncoderOption.id,paths: encoderPaths,keyPrefixMap: textEncoderOption.keyPrefixMap,finalNormKey: textEncoderOption.finalNormKey,+ configOverrides: textEncoderOption.configOverrides,};}diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex 5a633f93be..cbf85bdbd0 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -1076,6 +1076,80 @@ describe('generateVideo — LTX-2.5 sibling runtime spawn', () => {expect(calls.some(([bin]) => isLtx25Python(bin))).toBe(false);});+ // Substituted prompt conditioner on 2.5 (#4320). The shim flags and the 2.3+ // `--gemma` flag are different mechanisms sharing one builder, so each+ // runtime must emit exactly its own — and neither when nothing was picked.+ it.each([+ ['ltx25_mlx_q8', isLtx25Python],+ ['ltx2_unified', isLtx2Python],+ ])('adds no text-encoder shim argv to an unswapped %s render', async (modelId, isPython) => {+ const calls = await renderLtxFamily(`${modelId}-no-shim`, modelId);+ const [, args] = calls.find(([bin, a]) => isPython(bin) && Array.isArray(a) && a.includes('--mode'));+ expect(args.filter((arg) => String(arg).startsWith('--text-encoder'))).toEqual([]);+ });++ // Every ltx25 substitute is still gated behind the coherence check, so the+ // route/service path must reject its id rather than half-wire a render.+ it.each(['ltx25-abliterated-4bit', 'ltx25-heretic-8bit'])('rejects the unverified %s', async (textEncoderId) => {+ await expect(generateVideo({+ jobId: `ltx25-unverified-${textEncoderId}`,+ pythonPath: '/usr/bin/python3',+ modelId: 'ltx25_mlx_q8',+ prompt: 'a quiet street at dusk',+ width: 512, height: 512, numFrames: 25, fps: 24,+ textEncoderId,+ })).rejects.toMatchObject({ status: 400, code: 'VIDEO_TEXT_ENCODER_UNSUPPORTED' });+ });++ // The flags a resolved substitute produces, exercised directly: the registry+ // entries that would drive them end-to-end are gated until the A/B render in+ // #4320 lands, and this is the contract that has to survive that flag flip.+ describe('ltx25TextEncoderArgs', () => {+ let ltx25TextEncoderArgs;+ beforeEach(async () => {+ ({ ltx25TextEncoderArgs } = await import('./local.js'));+ });++ it('emits nothing for the stock choice', () => {+ expect(ltx25TextEncoderArgs(null)).toEqual([]);+ });++ it('emits one --text-encoder-file per pinned file plus a shim root outside the checkout', () => {+ const args = ltx25TextEncoderArgs({+ id: 'ltx25-abliterated-4bit',+ paths: ['/mock/hf/snap/config.json', '/mock/hf/snap/model-00001-of-00003.safetensors'],+ });+ expect(args[args.indexOf('--text-encoder-id') + 1]).toBe('ltx25-abliterated-4bit');+ expect(args.flatMap((arg, i) => (arg === '--text-encoder-file' ? [args[i + 1]] : [])))+ .toEqual(['/mock/hf/snap/config.json', '/mock/hf/snap/model-00001-of-00003.safetensors']);+ const shimRoot = args[args.indexOf('--text-encoder-shim-root') + 1];+ expect(shimRoot).toContain(join('.portos', 'ltx25-encoder-shims'));+ expect(shimRoot).not.toContain(join('.portos', 'ltx-2.5-mlx'));+ // No overrides declared — the config rewrite flag stays off, the same way+ // the H3 builder omits its key-remap flags for a checkpoint needing none.+ expect(args).not.toContain('--text-encoder-config-json');+ // Never the 2.3 mechanism: a 2.5 pack's own tower wins over --gemma.+ expect(args).not.toContain('--gemma');+ });++ it('forwards configOverrides as one JSON payload', () => {+ const args = ltx25TextEncoderArgs({+ id: 'ltx25-heretic-8bit',+ paths: ['/mock/hf/snap/config.json'],+ configOverrides: { model_type: 'gemma4' },+ });+ expect(JSON.parse(args[args.indexOf('--text-encoder-config-json') + 1]))+ .toEqual({ model_type: 'gemma4' });+ });++ // An empty object is not an override — emitting `{}` would make the runner+ // rewrite a config for no reason and hide a registry typo behind a no-op.+ it('omits the config flag for an empty override map', () => {+ expect(ltx25TextEncoderArgs({ id: 'x', paths: ['/p'], configOverrides: {} }))+ .not.toContain('--text-encoder-config-json');+ });+ });+it('rejects a missing pinned 2.5 snapshot before spawn', async () => {const { spawnDetached } = await import('../../lib/detachedSpawn.js');vi.mocked(spawnDetached).mockClear();diff --git a/server/services/videoGen/runtimes.js b/server/services/videoGen/runtimes.jsindex cc7d9c808e..2de975324b 100644--- a/server/services/videoGen/runtimes.js+++ b/server/services/videoGen/runtimes.js@@ -32,6 +32,14 @@ export const LTX2_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'generate_ltx2.py'export const LTX25_VENV_PYTHON = join(homedir(), '.portos', 'ltx-2.5-mlx', '.venv', 'bin', 'python3');export const LTX25_REPO_DIR = join(homedir(), '.portos', 'ltx-2.5-mlx');export const LTX25_EXPECTED_REVISION = '57952288076766abe27dda3a774b2c24f7346977';+// Shim roots for a substituted prompt conditioner (lib/videoTextEncoders.js).+// Unlike the H3 sibling below — which composes a whole checkpoint root and+// replaces only `text_encoder/` — an ltx25 shim is a standalone Gemma 4+// checkpoint directory the runner points the pack's PromptEncoder at, so+// nothing here links back into the model snapshot. Deliberately OUTSIDE+// LTX25_REPO_DIR for the same reason: anything written inside the checkout+// would read as untracked in that pin verification.+export const LTX25_ENCODER_SHIM_DIR = join(homedir(), '.portos', 'ltx25-encoder-shims');// Wan 2.2 MLX runtime — pinned MLX-Gen checkout provisioned on demand.export const WAN22_VENV_PYTHON = join(homedir(), '.portos', 'mlx-gen', '.venv', 'bin', 'python3');