Skip to content

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

allow a video text encoder to be pinned as several shards, and add huihui's abliterated Qwen3-VL-32B

[._.]/ Adam Eivy1e0a0837e8ed
diff --git a/scripts/generate_minimax_h3.py b/scripts/generate_minimax_h3.py
index 144943dcc9..f0c3bfafc4 100644
--- a/scripts/generate_minimax_h3.py
+++ b/scripts/generate_minimax_h3.py
@@ -53,8 +53,9 @@ def parse_args() -> argparse.Namespace:
help="strength for each --lora, in the same order")
parser.add_argument("--text-encoder-id",
help="id of the substituted prompt conditioner (shim directory name)")
- parser.add_argument("--text-encoder-file",
- help="already-cached safetensors to condition with instead of the checkpoint's own")
+ parser.add_argument("--text-encoder-file", action="append", default=[],
+ help="already-cached safetensors to condition with instead of the checkpoint's own "
+ "(repeatable — one per shard of a multi-shard conditioner)")
parser.add_argument("--text-encoder-shim-root",
help="directory the composed checkpoint root is built under")
parser.add_argument("--text-encoder-key-prefix", action="append", default=[],
@@ -167,7 +168,7 @@ def build_encoder_shim(
checkpoint_dir: Path,
shim_root: Path,
encoder_id: str,
- encoder_file: Path,
+ encoder_files: list[Path],
final_norm_key: str | None,
) -> Path:
"""Compose a checkpoint root whose `text_encoder/` is the substitute.
@@ -180,12 +181,22 @@ def build_encoder_shim(
is correct because abliteration changes weights, not the vocabulary or the
vision geometry.
+ A substitute may be one repackaged safetensors or several shards of an
+ upstream checkpoint: every file is linked into the same `text_encoder/`,
+ which the loader globs, so a multi-shard conditioner needs no index file.
+ Only the shards carrying parameters the loader actually builds are pulled,
+ so the glob deliberately sees fewer files than the upstream repo publishes.
+
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.
"""
- if not encoder_file.is_file():
- raise RuntimeError(f"Substituted text encoder is missing: {encoder_file}")
+ 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 shard names: {sorted(names)}")
root = shim_root / encoder_id
shutil.rmtree(root, ignore_errors=True)
@@ -203,7 +214,8 @@ def build_encoder_shim(
if not stock_config.is_file():
raise RuntimeError(f"Upstream text-encoder config is missing: {stock_config}")
(root / "text_encoder" / "config.json").symlink_to(stock_config)
- (root / "text_encoder" / encoder_file.name).symlink_to(encoder_file)
+ for encoder_file in encoder_files:
+ (root / "text_encoder" / encoder_file.name).symlink_to(encoder_file)
if final_norm_key:
hidden_size = json.loads(stock_config.read_text(encoding="utf-8"))["text_config"]["hidden_size"]
@@ -363,7 +375,7 @@ def main() -> int:
checkpoint_dir,
Path(args.text_encoder_shim_root),
args.text_encoder_id,
- Path(args.text_encoder_file),
+ [Path(f) for f in args.text_encoder_file],
args.text_encoder_final_norm_key,
)
diff --git a/scripts/generate_minimax_h3.test.js b/scripts/generate_minimax_h3.test.js
index a7e8be3968..c283ebc6fd 100644
--- a/scripts/generate_minimax_h3.test.js
+++ b/scripts/generate_minimax_h3.test.js
@@ -56,7 +56,7 @@ const VALIDATE_ARGS_DEFAULTS = {
lora: [],
lora_scale: [],
text_encoder_id: null,
- text_encoder_file: null,
+ text_encoder_file: [],
text_encoder_shim_root: null,
text_encoder_key_prefix: [],
text_encoder_final_norm_key: null,
@@ -158,14 +158,14 @@ describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {
// for, so the boundary rejects it instead of choosing for them.
it.each([
[{ text_encoder_id: 'heretic-bf16' }, /must be given together/i],
- [{ text_encoder_file: '/tmp/e.safetensors' }, /must be given together/i],
- [{ text_encoder_id: 'heretic-bf16', text_encoder_file: '/tmp/e.safetensors' }, /must be given together/i],
+ [{ text_encoder_file: ['/tmp/e.safetensors'] }, /must be given together/i],
+ [{ text_encoder_id: 'heretic-bf16', text_encoder_file: ['/tmp/e.safetensors'] }, /must be given together/i],
// A traversal-shaped id would put the shim tree outside the root PortOS
// chose (and `rmtree` it from there).
[
{
text_encoder_id: '../escape',
- text_encoder_file: '/tmp/e.safetensors',
+ text_encoder_file: ['/tmp/e.safetensors'],
text_encoder_shim_root: '/tmp/shims',
},
/bare directory-safe name/i,
@@ -193,7 +193,7 @@ describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {
'from types import SimpleNamespace',
argsExpr({
text_encoder_id: 'heretic-bf16',
- text_encoder_file: '/tmp/e.safetensors',
+ text_encoder_file: ['/tmp/e.safetensors'],
text_encoder_shim_root: '/tmp/shims',
text_encoder_key_prefix: ['model.=model.language_model.', 'visual.=model.visual.'],
text_encoder_final_norm_key: 'model.norm.weight',
@@ -306,7 +306,7 @@ describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {
' (checkpoint / "text_encoder" / "model-00001-of-00002.safetensors").write_text("stock")',
' substitute = root / "substitute.safetensors"',
' substitute.write_text("swapped")',
- ' shim = runner.build_encoder_shim(checkpoint, root / "shims", "heretic-bf16", substitute, None)',
+ ' shim = runner.build_encoder_shim(checkpoint, root / "shims", "heretic-bf16", [substitute], None)',
' print(json.dumps({',
' "name": shim.name,',
' "root": sorted(p.name for p in shim.iterdir()),',
@@ -337,7 +337,7 @@ describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {
' (checkpoint / "text_encoder" / "config.json").write_text(json.dumps({"text_config": {"hidden_size": 8}}))',
' substitute = root / "substitute.safetensors"',
' substitute.write_text("swapped")',
- ' shim = runner.build_encoder_shim(checkpoint, root / "shims", "heretic-bf16", substitute, "model.norm.weight")',
+ ' shim = runner.build_encoder_shim(checkpoint, root / "shims", "heretic-bf16", [substitute], "model.norm.weight")',
' import mlx.core as mx',
' loaded = mx.load(str(shim / "text_encoder" / "_portos_final_norm.safetensors"))',
' key = next(iter(loaded))',
@@ -365,7 +365,7 @@ describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {
' (stale / "old.safetensors").write_text("stale")',
' substitute = root / "substitute.safetensors"',
' substitute.write_text("swapped")',
- ' shim = runner.build_encoder_shim(checkpoint, root / "shims", "heretic-bf16", substitute, None)',
+ ' shim = runner.build_encoder_shim(checkpoint, root / "shims", "heretic-bf16", [substitute], None)',
' print(json.dumps(sorted(p.name for p in (shim / "text_encoder").iterdir())))',
].join('\n')}`);
expect(JSON.parse(output)).toEqual(['config.json', 'substitute.safetensors']);
@@ -379,7 +379,7 @@ describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {
' checkpoint = root / "FL2VA"',
' (checkpoint / "text_encoder").mkdir(parents=True)',
' try:',
- ' runner.build_encoder_shim(checkpoint, root / "shims", "heretic-bf16", root / "absent.safetensors", None)',
+ ' runner.build_encoder_shim(checkpoint, root / "shims", "heretic-bf16", [root / "absent.safetensors"], None)',
' except RuntimeError as exc:',
' print(json.dumps({"error": str(exc), "built": (root / "shims").exists()}))',
' else:',
@@ -390,6 +390,67 @@ describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {
expect(result.built).toBe(false);
});
+ // An upstream (rather than repackaged) conditioner arrives as several shards.
+ // The loader globs *.safetensors in the shim, so every shard has to be linked
+ // in — a partial link set loads a module tree with missing parameters.
+ it('links every shard of a multi-shard substitute into one text_encoder', () => {
+ const output = runPython(`${importRunner}\n${[
+ 'import json, tempfile',
+ 'with tempfile.TemporaryDirectory() as temp:',
+ ' root = Path(temp)',
+ ' checkpoint = root / "FL2VA"',
+ ' (checkpoint / "text_encoder").mkdir(parents=True)',
+ ' (checkpoint / "text_encoder" / "config.json").write_text(json.dumps({"text_config": {"hidden_size": 8}}))',
+ ' shards = []',
+ ' for name in ("model-00001-of-00014.safetensors", "model-00002-of-00014.safetensors", "model-00014-of-00014.safetensors"):',
+ ' shard = root / name',
+ ' shard.write_text(name)',
+ ' shards.append(shard)',
+ ' shim = runner.build_encoder_shim(checkpoint, root / "shims", "huihui-abliterated", shards, None)',
+ ' linked = sorted(p.name for p in (shim / "text_encoder").iterdir())',
+ ' print(json.dumps({"linked": linked, "resolves": [(shim / "text_encoder" / s.name).read_text() for s in shards]}))',
+ ].join('\n')}`);
+ const result = JSON.parse(output);
+ expect(result.linked).toEqual([
+ 'config.json',
+ 'model-00001-of-00014.safetensors',
+ 'model-00002-of-00014.safetensors',
+ 'model-00014-of-00014.safetensors',
+ ]);
+ expect(result.resolves).toEqual([
+ 'model-00001-of-00014.safetensors',
+ 'model-00002-of-00014.safetensors',
+ 'model-00014-of-00014.safetensors',
+ ]);
+ });
+
+ // Two shards sharing a basename would collide on the single symlink name, and
+ // whichever lost would be silently absent from the glob.
+ it('refuses a substitute whose shards share a basename', () => {
+ const output = runPython(`${importRunner}\n${[
+ 'import json, tempfile',
+ 'with tempfile.TemporaryDirectory() as temp:',
+ ' root = Path(temp)',
+ ' checkpoint = root / "FL2VA"',
+ ' (checkpoint / "text_encoder").mkdir(parents=True)',
+ ' shards = []',
+ ' for parent in ("a", "b"):',
+ ' (root / parent).mkdir()',
+ ' shard = root / parent / "model-00001-of-00002.safetensors"',
+ ' shard.write_text(parent)',
+ ' shards.append(shard)',
+ ' try:',
+ ' runner.build_encoder_shim(checkpoint, root / "shims", "dupe", shards, None)',
+ ' except RuntimeError as exc:',
+ ' print(json.dumps({"error": str(exc), "built": (root / "shims").exists()}))',
+ ' else:',
+ ' raise SystemExit("colliding shard names were accepted")',
+ ].join('\n')}`);
+ const result = JSON.parse(output);
+ expect(result.error).toMatch(/duplicate shard names/);
+ expect(result.built).toBe(false);
+ });
+
it('loads only the pinned namespace and cannot import a root-level shadow module', () => {
const output = runPython(`${importRunner}\n${[
'import importlib, tempfile',
diff --git a/server/lib/README.md b/server/lib/README.md
index 3da4ecb4c2..0430ea0151 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -117,7 +117,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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. |
| `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/file, 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). `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. |
| `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. |
@@ -141,7 +141,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `ansiStrip.js` | Streaming ANSI / control-byte stripper. |
| `hfToken.js` | HuggingFace token resolution (settings > env > CLI): `getHfToken` / `getHfTokenInfo` / `hfTokenEnv`, plus `hfChildEnv(extra?)` for a complete Malloc-stripped child environment that preserves inherited variables while injecting the resolved token. |
| `hfErrors.js` | Parse huggingface_hub gated-access errors: `isGatedRepoError(text)` classifies a failure as gated (403/restricted), `extractGatedRepo(text)` → `owner/name` (or null) for the UI's license deep-link. Shared by the image runner and MIDI transcription (LoRA trainer keeps its own regex to also match bare 401). Pure. |
-| `hfCache.js` | HuggingFace Hub cache inspection (`inspectModelCache(repoId,{revision?})` → `{cached,sizeBytes,snapshotPath}`, `isModelCached`, `getHfCacheRoot`). Drives the inline "Available / Download" badge on the image + video gen forms. Also `verifyModelCache(repoId,{deep,revision?})` (structural safetensors-header + optional sha256 integrity check) and `repairModelCache(repoId,{deep,revision?})` (delete corrupt weight files so the download path re-fetches them) — power the "Repair model" banner. `findCachedRepoSnapshot(repoId,revision)` resolves an immutable local snapshot; `findCachedRepoFile(repoId,filename,{revision?})` resolves ONE known file without walking it; `isSafeHfRepoRelativePath` rejects traversal/absolute dependency filenames; `verifyCachedRepoFiles` / `repairCachedRepoFiles` apply that revision-aware exact-file contract to pinned adapter pairs; and `repairCachedFile(path,{snapshotPath?})` is the containment-checked matching single-file repair. `verifySafetensorsStructure(path,size)` is the reusable header/size structural check. |
+| `hfCache.js` | HuggingFace Hub cache inspection (`inspectModelCache(repoId,{revision?})` → `{cached,sizeBytes,snapshotPath}`, `isModelCached`, `getHfCacheRoot`). Drives the inline "Available / Download" badge on the image + video gen forms. Also `verifyModelCache(repoId,{deep,revision?})` (structural safetensors-header + optional sha256 integrity check) and `repairModelCache(repoId,{deep,revision?})` (delete corrupt weight files so the download path re-fetches them) — power the "Repair model" banner. `findCachedRepoSnapshot(repoId,revision)` resolves an immutable local snapshot; `findCachedRepoFile(repoId,filename,{revision?})` resolves ONE known file without walking it, and `findCachedRepoFiles(repoId,filenames,{revision?})` is its all-or-nothing plural form (paths in request order, or `null` if ANY is missing — a caller needing several pinned files, e.g. the shards of one checkpoint, can do nothing useful with a partial set); `isSafeHfRepoRelativePath` rejects traversal/absolute dependency filenames; `verifyCachedRepoFiles` / `repairCachedRepoFiles` apply that revision-aware exact-file contract to pinned adapter pairs; and `repairCachedFile(path,{snapshotPath?})` is the containment-checked matching single-file repair. `verifySafetensorsStructure(path,size)` is the reusable header/size structural check. |
| `hfDownload.js` | `downloadHfRepo({repo,revision?,only?,onEvent,pythonPath?})` returning `{promise,kill}` — spawns `scripts/hf_download_repo.py` in a caller-preferred runtime or the shared fallback venvs and emits SSE-friendly stage/progress/complete events. Powers the inline "Download" button next to the model picker. `parseHfDownloadLine(line)` is the wire decoder (`STAGE:download` / `STAGE:bytes` / `STAGE:verify` / `STAGE:complete` / `USER_ERROR`) so a single-file multi-GB pull reports byte progress instead of sitting at 100% for the whole transfer. |
| `icLoraWeights.js` | IC-LoRA weight registry for the local LTX-2 remix modes (`IC_LORA_MODES`, `IC_LORA_MODE_VALUES`, `listIcLoraWeights()`, `isIcLoraMode(mode)`, `icLoraSpecForMode(mode)`, `icLoraRepos()`, `icLoraWeightCandidates(spec)`, `findCachedIcLoraWeight(spec)`, `resolveIcLoraWeight(mode)` → `{path,cached,spec}`). Single source of truth mapping each remix mode (`ic-control`, `ic-colorize`, `ic-ingredients`) → its HF repo/filename, reference-count rule, per-weight `referenceDownscaleFactor` (read from the weight's safetensors metadata, never assumed), and input surface (`referenceKind: 'video' | 'image'`). A `requiresPreDownload` spec (Ingredients) suppresses `resolveIcLoraWeight`'s bare-repo-id fallback — the pipeline would `snapshot_download` it, and its candidates are a gated first-party repo plus a ~708 GB aggregate mirror, so the weight must be pre-fetched single-file instead. Also owns the two rules derived from that data: `assertIcReferenceCount(spec,count,fail)` / `describeIcReferenceRange(spec)` and `icResolutionIssue(spec,w,h)` (the output-resolution divisibility its reference encoder imposes). Mirrored to `client/src/lib/videoGenParams.js`; `icLoraWeights.parity.test.js` diffs the two. |
| `sseHeaders.js` | `SSE_HEADERS` — the canonical SSE response headers (incl. `X-Accel-Buffering:no`) in a dependency-free module so any producer (`sseDownload.js`, `sseUtils.js`) can share them without pulling in a heavier module's transitive imports. |
diff --git a/server/lib/hfCache.js b/server/lib/hfCache.js
index ec496a68d1..6af6b9c2d5 100644
--- a/server/lib/hfCache.js
+++ b/server/lib/hfCache.js
@@ -199,6 +199,27 @@ export async function findCachedRepoFile(repoId, filename, { revision = null } =
return stat && stat.size > 0 ? candidate : null;
}
+/**
+ * All-or-nothing plural form of `findCachedRepoFile`: the resolved paths in the
+ * SAME order as `filenames`, or `null` when any one of them is missing.
+ *
+ * The all-or-nothing verdict is the point. A caller that needs several pinned
+ * files (the shards of one checkpoint, a runtime's required weights) can't do
+ * anything useful with a partial set — resolving them one at a time and
+ * "handling" the misses individually is how a half-downloaded checkpoint reaches
+ * a loader that then fails deep inside a load. Mirrors the plural exact-file
+ * contract `verifyCachedRepoFiles` / `repairCachedRepoFiles` already use, and
+ * resolves the files concurrently.
+ */
+export async function findCachedRepoFiles(repoId, filenames, { revision = null } = {}) {
+ const wanted = Array.isArray(filenames) ? filenames : [];
+ if (wanted.length === 0) return null;
+ const paths = await Promise.all(
+ wanted.map((name) => findCachedRepoFile(repoId, name, { revision })),
+ );
+ return paths.every(Boolean) ? paths : null;
+}
+
// Verify an explicit file subset inside an aggregate HF repo without walking
// unrelated siblings. Lightning repositories commonly contain many adapters;
// a PortOS profile needs only its pinned high/low-noise pair.
diff --git a/server/lib/videoTextEncoders.js b/server/lib/videoTextEncoders.js
index c9d59ab072..4db2c8e37e 100644
--- a/server/lib/videoTextEncoders.js
+++ b/server/lib/videoTextEncoders.js
@@ -28,6 +28,23 @@
* the final norm — correct, since H3 reads the state before it — would trip
* that check, so the runner synthesizes a ones-filled `norm.weight` under this
* key. Absent means "the checkpoint ships its own norm".
+ *
+ * `files` is always a LIST, because a substitute is either one repackaged
+ * safetensors or the subset of an upstream model's shards that actually carries
+ * the 903 parameters the loader builds. The runner symlinks every entry into the
+ * shim's `text_encoder/` and the loader globs `*.safetensors` there, so a
+ * multi-shard checkpoint needs no index file and no loader change — but the list
+ * must stay an explicit pin rather than a repo snapshot, since these repos also
+ * publish quantizations, generation tails and (for a full upstream checkpoint)
+ * the layers past the conditioning depth that H3 never evaluates.
+ *
+ * COMPATIBILITY RULE for a new entry: the checkpoint must be Qwen3-VL-32B —
+ * same `text_config` (hidden 5120, 64 layers, vocab 151936, head_dim 128) and
+ * the same vision geometry, because the shim reuses UPSTREAM's config,
+ * tokenizer and processor. A different Qwen generation is not a substitute
+ * 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.
*/
import { ServerError } from './errorHandler.js';
@@ -58,7 +75,7 @@ const TEXT_ENCODERS_BY_RUNTIME = Object.freeze({
+ 'Reads prompts the stock conditioner refuses or waters down; the diffusion weights are unchanged.',
repo: 'ethanfel/Qwen3-VL-32B-Ultra-Heretic-H3-ComfyUI-INT8-ConvRot',
revision: 'e8967f6a39ea5b4939a1aff81be3e8706490c0e8',
- file: 'qwen3vl_32b_h3_ultra_uncensored_heretic_bf16.safetensors',
+ files: Object.freeze(['qwen3vl_32b_h3_ultra_uncensored_heretic_bf16.safetensors']),
// ComfyUI namespace -> the HF namespace the pinned MLX loader matches.
// Longest-prefix-first is applied at the runner, so these two disjoint
// rules can be declared in any order.
@@ -84,6 +101,46 @@ const TEXT_ENCODERS_BY_RUNTIME = Object.freeze({
reviewedAt: '2026-08-14',
}),
}),
+ Object.freeze({
+ id: 'huihui-abliterated',
+ label: 'Huihui abliterated — Qwen3-VL-32B bf16',
+ 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.',
+ repo: 'huihui-ai/Huihui-Qwen3-VL-32B-Instruct-abliterated',
+ revision: '5e88d9b37e5dca1e95d434f5c4ddfa9b51b1591c',
+ // The upstream shard layout, minus the two shards that hold ONLY language
+ // layers 50-63 — parameters the loader never builds (H3 conditions on the
+ // state after layer 49). Verified against this revision's
+ // model.safetensors.index.json: the 12 shards below carry all 903
+ // parameters the port instantiates, and shards 12 + 13 carry none of them.
+ // Pinned by name rather than snapshotted so a repo re-shard can't silently
+ // change what gets pulled — it fails the cache check instead.
+ files: Object.freeze([
+ 'model-00001-of-00014.safetensors',
+ 'model-00002-of-00014.safetensors',
+ 'model-00003-of-00014.safetensors',
+ 'model-00004-of-00014.safetensors',
+ 'model-00005-of-00014.safetensors',
+ 'model-00006-of-00014.safetensors',
+ 'model-00007-of-00014.safetensors',
+ 'model-00008-of-00014.safetensors',
+ 'model-00009-of-00014.safetensors',
+ 'model-00010-of-00014.safetensors',
+ 'model-00011-of-00014.safetensors',
+ 'model-00014-of-00014.safetensors',
+ ]),
+ // No keyPrefixMap and no finalNormKey: this is the upstream Hugging Face
+ // namespace the pinned loader already matches, and it ships its own
+ // `model.language_model.norm.weight` (in shard 14, which is why that shard
+ // is pulled for one tensor rather than synthesized).
+ sizeBytes: 56962931632,
+ disclosure: Object.freeze({
+ modelCardUrl: 'https://huggingface.co/huihui-ai/Huihui-Qwen3-VL-32B-Instruct-abliterated',
+ weightsLicense: APACHE_2,
+ reviewedAt: '2026-08-15',
+ }),
+ }),
]),
});
@@ -168,7 +225,7 @@ export const downloadableVideoTextEncoder = (id) =>
*
* Deliberately drops `keyPrefixMap` / `finalNormKey` (loader mechanics that
* would only invite a client-side reimplementation of the remap), `revision`,
- * and `file`: the client never addresses the weight by path — it passes the
+ * 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.
*/
diff --git a/server/lib/videoTextEncoders.test.js b/server/lib/videoTextEncoders.test.js
index 5f81546b2e..4791b5374e 100644
--- a/server/lib/videoTextEncoders.test.js
+++ b/server/lib/videoTextEncoders.test.js
@@ -10,6 +10,7 @@ import {
downloadableVideoTextEncoder,
publicTextEncoderOption,
} from './videoTextEncoders.js';
+import { isSafeHfRepoRelativePath } from './hfCache.js';
const H3 = { id: 'minimax_h3_8bit', runtime: 'minimax_h3' };
const LTX = { id: 'ltx2_unified', runtime: 'ltx2' };
@@ -48,10 +49,24 @@ describe('videoTextEncoders', () => {
// A floating revision would let the upstream repo change the weights under
// a pinned PortOS build.
expect(option.revision).toMatch(/^[0-9a-f]{40}$/);
- expect(option.file).toMatch(/\.safetensors$/);
+ expect(option.files).toEqual([expect.stringMatching(/\.safetensors$/)]);
expect(Object.keys(option.keyPrefixMap).length).toBeGreaterThan(0);
});
+ // An upstream checkpoint arrives as several shards; the ones holding only
+ // language layers past the conditioning depth are deliberately not pinned, so
+ // the list is a subset of the repo rather than every shard it publishes.
+ it('resolves a multi-shard substitute with no loader adapters', () => {
+ const option = resolveVideoTextEncoder(H3, 'huihui-abliterated');
+ expect(option.revision).toMatch(/^[0-9a-f]{40}$/);
+ expect(option.files.length).toBeGreaterThan(1);
+ expect(option.files.every((name) => name.endsWith('.safetensors'))).toBe(true);
+ // Upstream Hugging Face namespace, and it ships its own final norm — the
+ // remap and the synthesized norm exist only for a repackaged checkpoint.
+ expect(option.keyPrefixMap).toBeUndefined();
+ expect(option.finalNormKey).toBeUndefined();
+ });
+
// The remap has to land on the namespace the pinned MLX loader matches
// (`model.language_model.` / `model.visual.`), or every tensor is skipped and
// the load fails with "missing N tensors" after reading ~48 GB.
@@ -90,7 +105,18 @@ describe('videoTextEncoders', () => {
expect(downloadableVideoTextEncoder('heretic-bf16')).toBeTruthy();
for (const entry of downloadableVideoTextEncoders()) {
expect(entry.repo).toBeTruthy();
- expect(entry.file).toBeTruthy();
+ // Always an explicit file list. A snapshot of any of these repos pulls
+ // 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);
+ 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.
+ expect(entry.files.every(isSafeHfRepoRelativePath)).toBe(true);
+ // The shim links every shard into one flat directory, so two shards with
+ // the same basename would collide on one symlink name.
+ expect(new Set(entry.files.map((name) => name.split('/').pop())).size).toBe(entry.files.length);
}
});
diff --git a/server/routes/videoGen.integrity.test.js b/server/routes/videoGen.integrity.test.js
index 79e9fb0327..00e66d346e 100644
--- a/server/routes/videoGen.integrity.test.js
+++ b/server/routes/videoGen.integrity.test.js
@@ -215,13 +215,24 @@ describe('Video Gen integrity routes', () => {
// Substitutable prompt conditioners (#4081) — their own lane, keyed by the
// registry id rather than a model id (they aren't listVideoModels() entries).
- // Every operation is scoped to the ONE pinned file: the upstream repo also
- // publishes INT8 ConvRot / NVFP4 quantizations and 50-63 generation tails this
- // MLX loader can't read, so a repo-wide pull would cost ~130 GB for ~48 GB of
- // usable weights — and a repo-wide verify would flag those as corrupt.
+ // Every operation is scoped to the entry's pinned FILE LIST: the upstream
+ // repos also publish INT8 ConvRot / NVFP4 quantizations, 50-63 generation
+ // tails and (for a full checkpoint) the language layers past the conditioning
+ // depth this MLX loader never builds, so a repo-wide pull would cost ~130 GB
+ // for ~48 GB of usable weights — and a repo-wide verify would flag the rest as
+ // corrupt.
describe('substitutable text encoders', () => {
const encoder = () => downloadableVideoTextEncoders()[0];
+ // Every entry gets its own row, not just the first: a substitute missing
+ // from this lane has no Download badge and no repair path in the UI.
+ it('GET /models/status reports every registered substitute', async () => {
+ const res = await request(app).get('/api/video-gen/models/status');
+ expect(res.status).toBe(200);
+ expect(res.body.textEncoderOptions.map((o) => o.id))
+ .toEqual(downloadableVideoTextEncoders().map((e) => e.id));
+ });
+
it('GET /models/status reports each substitute with the badge shape', async () => {
const res = await request(app).get('/api/video-gen/models/status');
expect(res.status).toBe(200);
@@ -238,7 +249,7 @@ describe('Video Gen integrity routes', () => {
// Through the shared target verifier, so the badge is checked exactly the
// way the integrity scan and the repair route check it.
expect(verifyCachedRepoFiles).toHaveBeenCalledWith(
- encoder().repo, [encoder().file], { deep: false, revision: encoder().revision },
+ encoder().repo, encoder().files, { deep: false, revision: encoder().revision },
);
});
@@ -246,7 +257,7 @@ describe('Video Gen integrity routes', () => {
const res = await request(app).get(`/api/video-gen/text-encoders/${encoder().id}/download`);
expect(res.status).toBe(200);
expect(sseDownload.start).toHaveBeenCalledWith(expect.objectContaining({
- repos: [{ repo: encoder().repo, revision: encoder().revision, only: [encoder().file] }],
+ repos: [{ repo: encoder().repo, revision: encoder().revision, only: encoder().files }],
force: false,
}));
});
@@ -261,9 +272,9 @@ describe('Video Gen integrity routes', () => {
const res = await request(app).post(`/api/video-gen/text-encoders/${encoder().id}/repair`).send({ deep: true });
expect(res.status).toBe(200);
expect(res.body.deep).toBe(true);
- expect(res.body.deleted).toEqual([{ repo: encoder().repo, name: encoder().file }]);
+ expect(res.body.deleted).toEqual(encoder().files.map((name) => ({ repo: encoder().repo, name })));
expect(repairCachedRepoFiles).toHaveBeenCalledWith(
- encoder().repo, [encoder().file], { deep: true, revision: encoder().revision },
+ encoder().repo, encoder().files, { deep: true, revision: encoder().revision },
);
});
@@ -286,7 +297,7 @@ describe('Video Gen integrity routes', () => {
it('POST /models/verify covers every substitute in an unscoped scan', async () => {
await request(app).post('/api/video-gen/models/verify').send({});
expect(verifyCachedRepoFiles).toHaveBeenCalledWith(
- encoder().repo, [encoder().file], { deep: false, revision: encoder().revision },
+ encoder().repo, encoder().files, { deep: false, revision: encoder().revision },
);
});
});
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 4a8b52f71d..7274e7d105 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -593,17 +593,23 @@ router.get('/models', (_req, res) => {
// Resolve the repo set an integrity scan should cover. A specific `modelId`
// scopes to that model's repo; no modelId scans every model repo plus the
// shared text encoder.
-const safeOnlyList = (model, files, label) => {
+// One definition of "a valid `only` list" for every download target this file
+// builds — model repos, their required weights, and the substitutable prompt
+// conditioners. `owner` is only used to name the offender in the error, so a
+// conditioner entry can pass its own registry id.
+const safeOnlyList = (owner, files, label) => {
const only = Array.isArray(files) ? files.filter((file) => typeof file === 'string' && file.length > 0) : [];
if (only.some((file) => !isSafeHfRepoRelativePath(file))) {
throw new ServerError(
- `Video model "${model.id}" has an unsafe ${label} path. Use repo-relative POSIX filenames only.`,
+ `${owner} has an unsafe ${label} path. Use repo-relative POSIX filenames only.`,
{ status: 500, code: 'VIDEO_MODEL_MISCONFIGURED' },
);
}
return only;
};
+const videoModelLabel = (model) => `Video model "${model?.id}"`;
+
const modelDownloadTargets = (model) => {
const repo = repoForModel(model);
if (!repo) return [];
@@ -618,24 +624,26 @@ const modelDownloadTargets = (model) => {
const targets = [{
repo,
revision: model?.revision || null,
- only: safeOnlyList(model, model?.repoFiles, 'repo-file'),
+ only: safeOnlyList(videoModelLabel(model), model?.repoFiles, 'repo-file'),
}];
for (const dep of Array.isArray(model?.requiredWeights) ? model.requiredWeights : []) {
if (typeof dep?.repo !== 'string') continue;
- const only = safeOnlyList(model, dep.files, 'required-weight');
+ const only = safeOnlyList(videoModelLabel(model), dep.files, 'required-weight');
if (only.length > 0) targets.push({ repo: dep.repo, revision: dep.revision || null, only });
}
return targets;
};
-// One download target per substitutable prompt conditioner. Each is a single
-// pinned file inside a repo that also publishes quantizations and generation
-// tails PortOS's MLX loader can't read, so these are ALWAYS scoped to `only:
-// [file]` — a repo-wide snapshot would pull ~130 GB of unusable variants.
+// One download target per substitutable prompt conditioner. Each names an
+// explicit file list inside a repo that holds more than the loader can use —
+// quantizations and generation tails in a repack, or the language layers past
+// the conditioning depth in an upstream checkpoint — so these are ALWAYS scoped
+// to `only: entry.files`. A repo-wide snapshot would pull ~130 GB of unusable
+// variants for the repack and ~10 GB of never-built layers for the upstream one.
const textEncoderDownloadTarget = (entry) => ({
repo: entry.repo,
revision: entry.revision || null,
- only: [entry.file],
+ only: safeOnlyList(`Text encoder "${entry.id}"`, entry.files, 'weight-file'),
});
// Paired with its entry so the status lane can project the registry fields
// (label, size) alongside the cache verdict without a second lookup.
@@ -911,10 +919,11 @@ const textEncoderFromParam = (id) => {
return entry;
};
-// Always single-file, never a snapshot: the upstream repo also publishes INT8
-// ConvRot / NVFP4 quantizations and 50-63 generation tails that this MLX loader
-// cannot read, so a repo-wide pull would cost ~130 GB for ~48 GB of usable
-// weights.
+// Always the entry's pinned file list, never a snapshot: these repos publish
+// more than the loader can read — INT8 ConvRot / NVFP4 quantizations and 50-63
+// generation tails in a repack, the language layers past the conditioning depth
+// in an upstream checkpoint — so a repo-wide pull would cost ~130 GB for ~48 GB
+// of usable weights.
router.get('/text-encoders/:id/download', asyncHandler(async (req, res) => {
const entry = textEncoderFromParam(req.params.id);
await startHfDownloadStream({
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 7e321cec12..874a97bb25 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -36,7 +36,7 @@ import {
contextPrefixFrames, tailWindowStartFrame,
} from '../../lib/videoContinuity.js';
import { hfChildEnv } from '../../lib/hfToken.js';
-import { inspectModelCache, findCachedRepoFile } from '../../lib/hfCache.js';
+import { inspectModelCache, findCachedRepoFile, findCachedRepoFiles } from '../../lib/hfCache.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
import { makeVideoGenLineHandler, finalizeGeneratedVideo, isWatchdogSuccess, describeSignalDeath, describeRenderConditioning, RENDER_INPUTS_VERSION } from './generateVideoHelpers.js';
import { assertSafeLoraFilename, getLoraKeyLayout } from '../loras.js';
@@ -724,11 +724,13 @@ const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numF
for (const l of loras ?? []) args.push('--lora', l.path, '--lora-scale', String(l.strength));
// Substituted prompt conditioner (lib/videoTextEncoders.js). Absent for the
// stock choice, so the argv of an unswapped render is byte-identical to what
- // it was before this feature existed. `textEncoder.path` was already resolved
- // against the HF cache by generateVideo — the helper never downloads.
+ // it was before this feature existed. `textEncoder.paths` were already
+ // resolved against the HF cache by generateVideo — the helper never downloads.
+ // One --text-encoder-file per shard; the shim links them all into the same
+ // `text_encoder/`, which the loader globs.
if (textEncoder) {
args.push('--text-encoder-id', textEncoder.id);
- args.push('--text-encoder-file', textEncoder.path);
+ for (const path of textEncoder.paths) args.push('--text-encoder-file', path);
args.push('--text-encoder-shim-root', MINIMAX_H3_ENCODER_SHIM_DIR);
for (const [from, to] of Object.entries(textEncoder.keyPrefixMap || {})) {
args.push('--text-encoder-key-prefix', `${from}=${to}`);
@@ -1109,10 +1111,13 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
const textEncoderOption = resolveVideoTextEncoder(model, textEncoderId);
let resolvedTextEncoder = null;
if (textEncoderOption) {
- const encoderPath = await findCachedRepoFile(
- textEncoderOption.repo, textEncoderOption.file, { revision: textEncoderOption.revision },
+ // All-or-nothing across every pinned shard: a partially-cached multi-shard
+ // conditioner must fail here as a clean 400 rather than loading a module
+ // tree with missing parameters minutes into the render.
+ const encoderPaths = await findCachedRepoFiles(
+ textEncoderOption.repo, textEncoderOption.files, { revision: textEncoderOption.revision },
);
- if (!encoderPath) {
+ if (!encoderPaths) {
throw new ServerError(
`Text encoder "${textEncoderOption.label}" is not downloaded. Download it in Video Gen before rendering.`,
{ status: 400, code: 'VIDEO_TEXT_ENCODER_NOT_CACHED' },
@@ -1120,7 +1125,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
}
resolvedTextEncoder = {
id: textEncoderOption.id,
- path: encoderPath,
+ paths: encoderPaths,
keyPrefixMap: textEncoderOption.keyPrefixMap,
finalNormKey: textEncoderOption.finalNormKey,
};
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index 7b7aa326f3..66b9b22f41 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -210,6 +210,13 @@ const { mockInspectModelCache, mockFindCachedRepoFile } = vi.hoisted(() => ({
vi.mock('../../lib/hfCache.js', () => ({
inspectModelCache: mockInspectModelCache,
findCachedRepoFile: mockFindCachedRepoFile,
+ // Built on the singular mock rather than stubbed independently, mirroring the
+ // real helper — so a test that makes ONE file miss (the partial-download
+ // cases) still drives the plural probe's all-or-nothing verdict.
+ findCachedRepoFiles: async (repo, filenames, opts) => {
+ const paths = await Promise.all(filenames.map((name) => mockFindCachedRepoFile(repo, name, opts)));
+ return paths.every(Boolean) ? paths : null;
+ },
}));
vi.mock('fs', () => ({
@@ -2337,6 +2344,54 @@ describe('generateVideo — MiniMax H3 MLX contract', () => {
expect(args[args.indexOf('--text-encoder-final-norm-key') + 1]).toBe('model.norm.weight');
});
+ // An upstream conditioner arrives as several shards, and the loader globs the
+ // shim directory — so every pinned shard has to reach the helper. Forwarding
+ // just the first would load a module tree with most of its layers missing.
+ it('forwards every shard of a multi-shard text encoder', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const { downloadableVideoTextEncoder } = await import('../../lib/videoTextEncoders.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ spawnMock.mockClear();
+
+ await generateVideo({
+ jobId: 'h3-multishard-encoder',
+ modelId: 'minimax_h3_8bit',
+ prompt: 'a fox watches the rain',
+ mode: 'text',
+ textEncoderId: 'huihui-abliterated',
+ });
+
+ const [, args] = spawnMock.mock.calls.find(([, a]) => (
+ Array.isArray(a) && a.some((arg) => basename(String(arg)) === 'generate_minimax_h3.py')
+ ));
+ const forwarded = args.flatMap((arg, i) => (arg === '--text-encoder-file' ? [args[i + 1]] : []));
+ expect(forwarded).toEqual(
+ downloadableVideoTextEncoder('huihui-abliterated').files.map((name) => join('/mock/hf/snap', name)),
+ );
+ // Upstream namespace, own final norm — neither adapter is emitted.
+ expect(args).not.toContain('--text-encoder-key-prefix');
+ expect(args).not.toContain('--text-encoder-final-norm-key');
+ });
+
+ // A partially-cached multi-shard conditioner (one shard interrupted) must fail
+ // as a clean 400, not load a module tree with missing parameters.
+ it('rejects a multi-shard text encoder missing any one shard', async () => {
+ mockFindCachedRepoFile.mockImplementation(async (_repo, filename) => (
+ filename === 'model-00011-of-00014.safetensors' ? null : join('/mock/hf/snap', filename)
+ ));
+ try {
+ await expect(generateVideo({
+ jobId: 'h3-multishard-partial',
+ modelId: 'minimax_h3_8bit',
+ prompt: 'a fox watches the rain',
+ mode: 'text',
+ textEncoderId: 'huihui-abliterated',
+ })).rejects.toMatchObject({ status: 400, code: 'VIDEO_TEXT_ENCODER_NOT_CACHED' });
+ } finally {
+ mockFindCachedRepoFile.mockImplementation(async (_repo, filename) => join('/mock/hf/snap', filename));
+ }
+ });
+
// A ~48 GB weight that isn't downloaded must fail as a clean 400 on the
// request, not minutes into the render when the helper's cache probe misses.
it('rejects a substituted text encoder that is not downloaded', async () => {