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
refactor: collapse the duplication the second H3 runtime introduced
[._.]/ Adam Eivy244c4b7b9dd0
diff --git a/scripts/_minimax_h3_common.py b/scripts/_minimax_h3_common.pyindex b228ecdf42..b04adf05dd 100644--- a/scripts/_minimax_h3_common.py+++ b/scripts/_minimax_h3_common.py@@ -15,8 +15,10 @@ dependency it didn't already pin.What must NOT move here: anything true of only one runner. The MLX port's`resolve_transformer_snapshot` (its quantized DiT ships a separate-`quant_config.json`), its LoRA argument pairing, and the CUDA path's-`--repo-file` requirement and offload profiles all stay in their own runner.+`quant_config.json`), its LoRA argument pairing, its `require_ffmpeg` preflight+(it shells out to the binary to mux, where the CUDA runner muxes in-process via+PyAV), and the CUDA path's `--repo-file` requirement and offload profiles all+stay in their own runner.The frame WINDOW is the subtle one — it differs between the two (diffusersrequires the snapped duration in 5-15s where the MLX port accepts 4-15s), so`validate_h3_output_args` takes it as a parameter rather than asserting one.@@ -24,8 +26,8 @@ requires the snapped duration in 5-15s where the MLX port accepts 4-15s), sofrom __future__ import annotations+import argparseimport json-import shutilimport sysfrom pathlib import Path@@ -36,6 +38,33 @@ FRAME_MODULUS = 17FRAME_REMAINDER = 5+def add_h3_common_args(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:+ """Declare the CLI surface both runners present to PortOS.++ `validate_h3_output_args` below reads exactly these fields off the parsed+ Namespace, so the schema and its validator have to agree — declaring them+ apart is how one runner's `--steps` default drifts from the other's with+ nothing failing until a render. Each runner adds its own flags on top+ (`--checkpoint-*` and the LoRA / text-encoder pairs for MLX, `--repo-file`+ and `--offload-profile` for CUDA).+ """+ parser.add_argument("--model-repo", required=True)+ parser.add_argument("--model-revision", required=True)+ parser.add_argument("--prompt", required=True)+ parser.add_argument("--width", type=int, required=True)+ parser.add_argument("--height", type=int, required=True)+ parser.add_argument("--num-frames", type=int, required=True)+ parser.add_argument("--fps", type=int, default=FPS)+ parser.add_argument("--steps", type=int, default=8)+ parser.add_argument("--seed", type=int, default=0)+ parser.add_argument("--image", action="append", default=[],+ help="keyframe conditioning image (repeatable, max 2)")+ parser.add_argument("--anchor", action="append", default=[], choices=["first", "last"],+ help="latent anchor for each --image, in the same order")+ parser.add_argument("--output", required=True)+ return parser++def snapshot_root(resolved_file: str | Path, repo_filename: str) -> Path:"""Return the HF snapshot directory containing one resolved repo file."""levels = len(Path(repo_filename).parts)@@ -75,14 +104,6 @@ def resolve_cached_snapshot(repo: str, revision: str, required_files: list[str])return roots.pop()-def require_ffmpeg() -> str:- """Fail before loading tens of GB of weights when muxing cannot succeed."""- path = shutil.which("ffmpeg")- if path is None:- raise RuntimeError("ffmpeg is required to mux MiniMax H3 video and audio; install it before generating.")- return path--def emit_result(output: Path) -> None:"""Emit the completion contract that arms PortOS's teardown watchdog."""print(json.dumps({"video_path": str(output)}), flush=True)@@ -152,12 +173,9 @@ def load_keyframes(paths: list[str]) -> list:__all__ = ["FPS",- "FRAME_MODULUS",- "FRAME_REMAINDER",+ "add_h3_common_args","emit_result","load_keyframes",- "require_ffmpeg","resolve_cached_snapshot",- "snapshot_root","validate_h3_output_args",]diff --git a/scripts/_minimax_h3_common.test.js b/scripts/_minimax_h3_common.test.jsindex 119db8e649..b345164a8b 100644--- a/scripts/_minimax_h3_common.test.js+++ b/scripts/_minimax_h3_common.test.js@@ -60,6 +60,36 @@ const validate = (overrides = {}, window = {}) => {};describe.skipIf(!pyBin)('_minimax_h3_common.py — checkpoint facts shared by both H3 runners', () => {+ // The shared validator reads these exact fields off the parsed Namespace, so+ // the two runners have to present the same surface or one of them can hand it+ // an attribute that doesn't exist. Declaring the flags once is what makes that+ // true; this pins the set so a runner can't quietly drop one back into its own+ // parser with a different type or default.+ it('declares the CLI surface both runners share', () => {+ const output = lines(runPython(`${importShared}\n${[+ 'import argparse',+ 'parser = shared.add_h3_common_args(argparse.ArgumentParser())',+ 'for action in parser._actions:',+ ' if action.dest == "help":',+ ' continue',+ ' print(f"{action.dest}:{action.required}:{action.default}")',+ ].join('\n')}`));+ expect(output).toEqual([+ 'model_repo:True:None',+ 'model_revision:True:None',+ 'prompt:True:None',+ 'width:True:None',+ 'height:True:None',+ 'num_frames:True:None',+ 'fps:False:24',+ 'steps:False:8',+ 'seed:False:0',+ 'image:False:[]',+ 'anchor:False:[]',+ 'output:True:None',+ ]);+ });+it('states the fixed fps and frame grid once', () => {const output = lines(runPython(`${importShared}\n${['print(f"{shared.FPS},{shared.FRAME_MODULUS},{shared.FRAME_REMAINDER}")',@@ -185,19 +215,6 @@ describe.skipIf(!pyBin)('_minimax_h3_common.py — checkpoint facts shared by bo});});- it('fails the ffmpeg preflight before any model load can begin', () => {- // Tens of GB of weights load before the mux; discovering a missing ffmpeg- // after that wastes the whole render.- const output = runPython(`${importShared}\n${[- 'shared.shutil.which = lambda name: None',- 'try:',- ' shared.require_ffmpeg()',- 'except RuntimeError as exc:',- ' print(exc)',- ].join('\n')}`);- expect(output).toContain('ffmpeg is required');- });-it('emits the video_path JSON completion contract on stdout', () => {// PortOS arms its teardown watchdog on this line, so it must be the only// thing on stdout and must parse.diff --git a/scripts/_runner_common.py b/scripts/_runner_common.pyindex 55f558ac10..746495194a 100644--- a/scripts/_runner_common.py+++ b/scripts/_runner_common.py@@ -233,6 +233,27 @@ def suppress_cosmetic_clip_truncation() -> None:handler.addFilter(f)+def establish_process_group() -> None:+ """Make this helper the leader of its own process group, where supported.++ PortOS cancels a render by signalling the whole group, so any child the+ runner spawns (an ffmpeg mux, a git pin probe) is torn down with it rather+ than surviving to finish work the user just cancelled. Call it before the+ first child is spawned.++ A no-op on Windows, which has no POSIX process groups — the Node side kills+ by PID there. `setpgid` can also fail with EPERM when the process is already+ a group leader, which is harmless and equally not worth failing a render+ over, so both cases fall through quietly.+ """+ if not hasattr(os, "setpgid"):+ return+ try:+ os.setpgid(0, 0)+ except OSError:+ pass++def pick_device(requested: str) -> str:"""Resolve `auto`/`mps`/`cuda`/`cpu` against what torch actually has.Falls back to CPU with a warning when the requested accelerator isn'tdiff --git a/scripts/generate_minimax_h3.py b/scripts/generate_minimax_h3.pyindex 9ce2966400..7d778d8632 100644--- a/scripts/generate_minimax_h3.py+++ b/scripts/generate_minimax_h3.py@@ -24,9 +24,11 @@ from contextlib import redirect_stdoutfrom pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parent))-from _runner_common import emit_runtime_fingerprint, heartbeat, register_source_namespace # noqa: E402+from _runner_common import ( # noqa: E402+ emit_runtime_fingerprint, establish_process_group, heartbeat, register_source_namespace,+)from _minimax_h3_common import ( # noqa: E402- FPS, emit_result, load_keyframes, require_ffmpeg, resolve_cached_snapshot,+ FPS, add_h3_common_args, emit_result, load_keyframes, resolve_cached_snapshot,validate_h3_output_args,)@@ -40,25 +42,12 @@ STEP_RE = re.compile(r"\bstep\s+(\d+)/(\d+)\b", re.IGNORECASE)def parse_args() -> argparse.Namespace:- parser = argparse.ArgumentParser(description=__doc__)+ parser = add_h3_common_args(argparse.ArgumentParser(description=__doc__))parser.add_argument("--runtime-dir", required=True)parser.add_argument("--runtime-revision", required=True)- parser.add_argument("--model-repo", required=True)- parser.add_argument("--model-revision", required=True)parser.add_argument("--checkpoint-repo", required=True)parser.add_argument("--checkpoint-revision", required=True)parser.add_argument("--checkpoint-file", action="append", default=[])- parser.add_argument("--prompt", required=True)- parser.add_argument("--width", type=int, required=True)- parser.add_argument("--height", type=int, required=True)- parser.add_argument("--num-frames", type=int, required=True)- parser.add_argument("--fps", type=int, default=FPS)- parser.add_argument("--steps", type=int, default=8)- parser.add_argument("--seed", type=int, default=0)- parser.add_argument("--image", action="append", default=[],- help="keyframe conditioning image (repeatable, max 2)")- parser.add_argument("--anchor", action="append", default=[], choices=["first", "last"],- help="latent anchor for each --image, in the same order")parser.add_argument("--lora", action="append", default=[],help="user LoRA safetensors applied at runtime (repeatable)")parser.add_argument("--lora-scale", action="append", type=float, default=[],@@ -74,10 +63,22 @@ def parse_args() -> argparse.Namespace:help="rewrite this checkpoint-key prefix before the loader matches it (repeatable)")parser.add_argument("--text-encoder-final-norm-key",help="synthesize a ones-filled final norm under this key (for a conditioner published without one)")- parser.add_argument("--output", required=True)return parser.parse_args()+def require_ffmpeg() -> str:+ """Fail before loading tens of GB of weights when muxing cannot succeed.++ Only this runner needs it: it shells out to the ffmpeg binary to mux the+ joint video+audio output, where the CUDA sibling muxes in-process through+ diffusers' PyAV-backed encode_video().+ """+ path = shutil.which("ffmpeg")+ if path is None:+ raise RuntimeError("ffmpeg is required to mux MiniMax H3 video and audio; install it before generating.")+ return path++def resolve_transformer_snapshot(repo: str, revision: str) -> Path:"""Resolve the quantized transformer and every shard named by its index."""root = resolve_cached_snapshot(@@ -315,14 +316,9 @@ def main() -> int:# image should not cost seconds before it reports.images = load_keyframes(args.image)- # PortOS cancels this helper by process group; ffmpeg inherits the group and- # cannot remain behind muxing after the user presses Cancel. Establish the- # group before the git pin probe, which is the first child process.- if hasattr(os, "setpgid"):- try:- os.setpgid(0, 0)- except OSError:- pass+ # Before the git pin probe, which is the first child process — and before+ # the ffmpeg this runner shells out to mux with.+ establish_process_group()require_ffmpeg()diff --git a/scripts/generate_minimax_h3.test.js b/scripts/generate_minimax_h3.test.jsindex 69008aaf9b..a7e8be3968 100644--- a/scripts/generate_minimax_h3.test.js+++ b/scripts/generate_minimax_h3.test.js@@ -68,6 +68,21 @@ const argsExpr = (overrides = {}) => {};describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {+ // Only this runner shells out to ffmpeg (the CUDA sibling muxes in-process+ // via PyAV), so the preflight lives here rather than in the shared module.+ // Tens of GB of weights load before the mux; discovering a missing ffmpeg+ // after that wastes the whole render.+ it('fails the ffmpeg preflight before any model load can begin', () => {+ const output = runPython(`${importRunner}\n${[+ 'runner.shutil.which = lambda name: None',+ 'try:',+ ' runner.require_ffmpeg()',+ 'except RuntimeError as exc:',+ ' print(exc)',+ ].join('\n')}`);+ expect(output).toContain('ffmpeg is required');+ });+it('preflights transformer config, quant config, index, and every indexed shard', () => {const output = runPython(`${importRunner}\n${['import json, tempfile',diff --git a/scripts/generate_minimax_h3_cuda.py b/scripts/generate_minimax_h3_cuda.pyindex 94b780933e..6925deb252 100644--- a/scripts/generate_minimax_h3_cuda.py+++ b/scripts/generate_minimax_h3_cuda.py@@ -31,9 +31,9 @@ import sysfrom pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parent))-from _runner_common import emit_runtime_fingerprint, heartbeat # noqa: E402+from _runner_common import emit_runtime_fingerprint, establish_process_group, heartbeat # noqa: E402from _minimax_h3_common import ( # noqa: E402- FPS, emit_result, load_keyframes, resolve_cached_snapshot,+ FPS, add_h3_common_args, emit_result, load_keyframes, resolve_cached_snapshot,validate_h3_output_args,)@@ -68,25 +68,11 @@ def log(message: str) -> None:def parse_args() -> argparse.Namespace:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--model-repo", required=True)- parser.add_argument("--model-revision", required=True)+ parser = add_h3_common_args(argparse.ArgumentParser(description=__doc__))parser.add_argument("--repo-file", action="append", default=[],help="repo-relative diffusers component file that must already be cached (repeatable)")- parser.add_argument("--prompt", required=True)- parser.add_argument("--width", type=int, required=True)- parser.add_argument("--height", type=int, required=True)- parser.add_argument("--num-frames", type=int, required=True)- parser.add_argument("--fps", type=int, default=FPS)- parser.add_argument("--steps", type=int, default=8)- parser.add_argument("--seed", type=int, default=0)- parser.add_argument("--image", action="append", default=[],- help="keyframe conditioning image (repeatable, max 2)")- parser.add_argument("--anchor", action="append", default=[], choices=["first", "last"],- help="latent anchor for each --image, in the same order")parser.add_argument("--offload-profile", choices=OFFLOAD_PROFILES, default="auto",help="weight-placement recipe; 'auto' sizes one from the visible CUDA device")- parser.add_argument("--output", required=True)return parser.parse_args()@@ -219,15 +205,7 @@ def main() -> int:# cost seconds before it reports.images = load_keyframes(args.image)- # PortOS cancels this helper by process group; ffmpeg inherits the group and- # cannot remain behind muxing after the user presses Cancel. No-op on- # Windows, which has no process groups in this sense — the Node side kills- # by PID there.- if hasattr(os, "setpgid"):- try:- os.setpgid(0, 0)- except OSError:- pass+ establish_process_group()# No ffmpeg preflight here, unlike the MLX runner: that one shells out to the# binary to mux, while this one muxes in-process through diffusers'diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.jsindex 98e074369a..cc0c4b9c97 100644--- a/server/lib/mediaModels.js+++ b/server/lib/mediaModels.js@@ -90,6 +90,18 @@ export const MINIMAX_H3_CANVAS = Object.freeze({]),});+// H3's video VAE decodes only frame counts on the 17n+5 grid, so every frame+// list PortOS ships is an arithmetic sequence stepping by 17 — the runners+// enforce the same modulus. Generated rather than typed out for the reason+// `shardFiles` below is: a single wrong digit among the ~45 literals these three+// lists would otherwise need is invisible in review and surfaces only as a+// rejected render, and the three lists could silently disagree about the grid.+const h3FrameGrid = (min, max) => {+ const out = [];+ for (let frames = min; frames <= max; frames += 17) out.push(frames);+ return Object.freeze(out);+};+// The MLX entry's output profile: the shared canvas above PLUS the upgrade// machinery migration 267 and `upgradeMiniMaxH3OutputControls` key off (the id,// the repo it was checked against, and the frame list it supersedes). That@@ -98,8 +110,8 @@ export const MINIMAX_H3_CANVAS = Object.freeze({export const MINIMAX_H3_OUTPUT_PROFILE = Object.freeze({id: 'minimax_h3_8bit',shippedRepo: 'pipenetwork/MiniMax-H3-MLX-8bit',- oldFrameOptions: Object.freeze([124, 141, 158, 175, 192, 209, 226, 243, 260, 277, 294, 311, 328, 345, 362]),- frameOptions: Object.freeze([107, 124, 141, 158, 175, 192, 209, 226, 243, 260, 277, 294, 311, 328, 345, 362]),+ oldFrameOptions: h3FrameGrid(124, 362),+ frameOptions: h3FrameGrid(107, 362),...MINIMAX_H3_CANVAS,});@@ -167,9 +179,7 @@ const MINIMAX_H3_CUDA_REPO_FILES = Object.freeze([// duration must land in 5-15 s, so 107 (4.46 s) is under the floor and 362// (15.08 s) is over the ceiling. Mirrored by MIN_FRAMES / MAX_FRAMES in// scripts/generate_minimax_h3_cuda.py, which rejects the same values.-const MINIMAX_H3_CUDA_FRAME_OPTIONS = Object.freeze([- 124, 141, 158, 175, 192, 209, 226, 243, 260, 277, 294, 311, 328, 345,-]);+const MINIMAX_H3_CUDA_FRAME_OPTIONS = h3FrameGrid(124, 345);const sameValues = (left, right) => (Array.isArray(left)diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex f1ee22b96e..ad2f204a21 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -65,6 +65,8 @@ import {MINIMAX_H3_CUDA_VENV_PYTHON,MINIMAX_H3_CUDA_HELPER_SCRIPT,MINIMAX_H3_CUDA_OFFLOAD_PROFILES,+ runtimeIsCacheOnly,+ runtimeNeedsProcessGroupKill,HUNYUAN_VENV_PYTHON,HUNYUAN_HELPER_SCRIPT,HUNYUAN_REPO_DIR,@@ -644,8 +646,20 @@ const buildWan22Args = ({ model, wanModelPath, wanRequiredWeights, prompt, negat// Build args for PipeNetwork's pinned MiniMax H3 MLX port. The helper resolves// only exact, already-cached HF revisions; every network download remains an// explicit Video Gen UI action guarded by the model's terms acknowledgement.-const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath, loras, textEncoder }) => {- assertByovRuntimeInstalled('minimax_h3');+// Everything both H3 builders must clear before they start assembling argv:+// the venv is installed, the mode/source combination is legal, H3's fixed+// controls were not overridden, and the entry carries its pin. The two lanes+// had carried byte-identical copies of all four — the same shape that put the+// control checks in `minimaxH3Controls.js` in the first place — so a field+// added to `assertRenderModeContract` can no longer be threaded into one H3+// runner and forgotten in the other. `repoLabel` is the only real difference:+// the MLX entry pins a *transformer* repo, the CUDA entry the model repo.+const assertMiniMaxH3Preflight = ({+ runtimeId, repoLabel, model, mode, sourceImagePath, lastImagePath, keyframes,+ extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths,+ negativePrompt, disableAudio, tiling, numFrames, fps,+}) => {+ assertByovRuntimeInstalled(runtimeId);assertRenderModeContract({model,mode,@@ -661,10 +675,20 @@ const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numFif (controlError) throw controlError;if (typeof model.repo !== 'string' || typeof model.revision !== 'string') {throw new ServerError(- `MiniMax H3 model "${model.id}" is missing its pinned transformer repo or revision.`,+ `MiniMax H3 model "${model.id}" is missing its pinned ${repoLabel}.`,{ status: 500, code: 'VIDEO_MODEL_MISCONFIGURED' },);}+};++const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath, loras, textEncoder }) => {+ assertMiniMaxH3Preflight({+ runtimeId: 'minimax_h3',+ repoLabel: 'transformer repo or revision',+ model, mode, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath,+ audioFilePath, audioStartSec, icReferencePaths,+ negativePrompt, disableAudio, tiling, numFrames, fps,+ });const checkpoint = Array.isArray(model.requiredWeights) ? model.requiredWeights[0] : null;const files = Array.isArray(checkpoint?.files) ? checkpoint.files : [];if (!checkpoint?.repo || !checkpoint?.revision || files.length === 0) {@@ -730,26 +754,13 @@ const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numF// `repo`, so the file list rides on `repoFiles` and there is no separate// upstream-checkpoint dependency to resolve.const buildMiniMaxH3CudaArgs = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath }) => {- assertByovRuntimeInstalled('minimax_h3_cuda');- assertRenderModeContract({- model,- mode,- sourceImagePath,- lastImagePath,- keyframes,- extendFromVideoPath,- audioFilePath,- audioStartSec,- icReferencePaths,+ assertMiniMaxH3Preflight({+ runtimeId: 'minimax_h3_cuda',+ repoLabel: 'repo or revision',+ model, mode, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath,+ audioFilePath, audioStartSec, icReferencePaths,+ negativePrompt, disableAudio, tiling, numFrames, fps,});- const controlError = minimaxH3ControlError({ model, negativePrompt, disableAudio, tiling, numFrames, fps });- if (controlError) throw controlError;- if (typeof model.repo !== 'string' || typeof model.revision !== 'string') {- throw new ServerError(- `MiniMax H3 model "${model.id}" is missing its pinned repo or revision.`,- { status: 500, code: 'VIDEO_MODEL_MISCONFIGURED' },- );- }const files = Array.isArray(model.repoFiles) ? model.repoFiles.filter((file) => typeof file === 'string' && file) : [];if (files.length === 0) {// Fail here rather than let the helper fall back to a repo-wide resolve:@@ -868,8 +879,9 @@ const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeight// Windows BYOV runtime now gets the same runner-based reason the enqueue gate// gives it, instead of a blanket "can't fuse LoRAs on Windows" that would// contradict it.- if (hasLoras && (!videoLoraFamily(model) || routesToWindowsHelper(model))) {- throw routesToWindowsHelper(model)+ const usesWindowsHelper = routesToWindowsHelper(model);+ if (hasLoras && (!videoLoraFamily(model) || usesWindowsHelper)) {+ throw usesWindowsHelper? new ServerError(`LoRA fusion runs through the macOS-only mlx_video path; model "${modelId}" can't fuse LoRAs on the Windows LTX-Video helper.`,{ status: 400, code: 'LORAS_REQUIRE_LTX2' },@@ -1519,7 +1531,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// python helpers can authenticate snapshot_download() against gated repos// (mirrors the imageGen child-spawn pattern). LTX-2 doesn't currently use// a gated repo, but the merge is harmless when no token is configured.- const childEnv = isMiniMaxH3Runtime(model.runtime)+ const childEnv = runtimeIsCacheOnly(model.runtime)? safeChildProcessEnv(): await hfChildEnv();delete childEnv.PYTHONPATH;@@ -1528,9 +1540,9 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// long inference loops emit nothing to handleLine() for minutes — the UI// looks dead even when the model is making progress.childEnv.PYTHONUNBUFFERED = '1';- if (isMiniMaxH3Runtime(model.runtime)) {- // The H3 repositories are public and the runner is cache-only. Do not hand- // it an ambient saved HF credential it neither needs nor may transmit.+ if (runtimeIsCacheOnly(model.runtime)) {+ // A cache-only runner never reaches the network. Do not hand it an ambient+ // saved HF credential it neither needs nor may transmit.delete childEnv.HF_TOKEN;delete childEnv.HUGGING_FACE_HUB_TOKEN;childEnv.HF_HUB_DISABLE_IMPLICIT_TOKEN = '1';@@ -1550,7 +1562,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', menv: childEnv,controlDir: join(PATHS.videos, '.detached', jobId),cleanup: true,- killProcessGroup: model.runtime === 'wan22' || isMiniMaxH3Runtime(model.runtime),+ killProcessGroup: runtimeNeedsProcessGroupKill(model.runtime),});activeProcess = proc;diff --git a/server/services/videoGen/runtimes.js b/server/services/videoGen/runtimes.jsindex b2d5294a35..2082c455ca 100644--- a/server/services/videoGen/runtimes.js+++ b/server/services/videoGen/runtimes.js@@ -107,6 +107,13 @@ export const BYOV_RUNTIME_INFO = Object.freeze({venvPython: MINIMAX_H3_VENV_PYTHON,repoDir: MINIMAX_H3_REPO_DIR,installEnvVar: 'INSTALL_MINIMAX_H3',+ // Cache-only: the runner never reaches the network, so the spawn site hands+ // it a bare env and strips any ambient HF credential rather than passing one+ // it neither needs nor may transmit. Absent means "the runner may fetch".+ cacheOnly: true,+ // The runner spawns children of its own (an ffmpeg mux, a git pin probe), so+ // cancelling has to signal the whole group or they outlive the render.+ killProcessGroup: true,repoUrl: 'https://github.com/PipeNetwork/minimax-h3-mlx',expectedRevision: MINIMAX_H3_EXPECTED_REVISION,// Source-only runtime: both status and the render helper verify this@@ -136,6 +143,9 @@ export const BYOV_RUNTIME_INFO = Object.freeze({venvPython: MINIMAX_H3_CUDA_VENV_PYTHON,repoDir: MINIMAX_H3_CUDA_REPO_DIR,installEnvVar: 'INSTALL_MINIMAX_H3_CUDA',+ // Cache-only: see minimax_h3 above. The Video Gen UI owns every download.+ cacheOnly: true,+ killProcessGroup: true,// Everything this runtime executes is an installed distribution, so there// is no `expectedRevision` / `sourcePath` clean-checkout probe to run: the// `==` set in scripts/requirements-minimax-h3-cuda.txt is the pin. `repoUrl`@@ -180,6 +190,7 @@ export const BYOV_RUNTIME_INFO = Object.freeze({venvPython: WAN22_VENV_PYTHON,repoDir: WAN22_REPO_DIR,installEnvVar: 'INSTALL_WAN22',+ killProcessGroup: true,repoUrl: 'https://github.com/lpalbou/mlx-gen',expectedRevision: WAN22_EXPECTED_REVISION,pinEnvVar: 'WAN22_PIN',@@ -205,6 +216,14 @@ export const BYOV_RUNTIME_INFO = Object.freeze({export const BYOV_VIDEO_RUNTIMES = Object.freeze(new Set(Object.keys(BYOV_RUNTIME_INFO)));+// Per-runtime EXECUTION facts, read off the registry rather than re-derived from+// a runtime id at the spawn site. Both are "key absent means off", the same+// convention `loraProbeArgs` / `expectedRevision` already use here — so the next+// cache-only or group-killed runtime is a line in the table above rather than an+// edit to the child-spawn path in local.js.+export const runtimeIsCacheOnly = (runtime) => BYOV_RUNTIME_INFO[runtime]?.cacheOnly === true;+export const runtimeNeedsProcessGroupKill = (runtime) => BYOV_RUNTIME_INFO[runtime]?.killProcessGroup === true;+// Does this model render through the legacy Windows helper, `generate_win.py`?// That script is the fallback `buildArgs` reaches only after every BYOV runtime// has declined, so the answer is "on win32, and not a BYOV runtime" — NOT thediff --git a/server/services/videoGen/runtimes.test.js b/server/services/videoGen/runtimes.test.jsindex 0b6978e100..82073a397e 100644--- a/server/services/videoGen/runtimes.test.js+++ b/server/services/videoGen/runtimes.test.js@@ -1,4 +1,7 @@import { EventEmitter } from 'node:events';+import { readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';import { beforeEach, describe, expect, it, vi } from 'vitest';const runtimeMocks = vi.hoisted(() => ({@@ -16,10 +19,10 @@ vi.mock('child_process', async (importOriginal) => ({}));import {- BYOV_RUNTIME_INFO, BYOV_VIDEO_RUNTIMES,+ BYOV_RUNTIME_INFO, BYOV_VIDEO_RUNTIMES, MINIMAX_H3_CUDA_OFFLOAD_PROFILES,byovRuntimeLoraCapable, invalidateByovLoraCapabilityCache, invalidateByovReadyCache,isByovRuntimeReady, isPinnedSourceStatusClean, modelAnchorsLastFrame,- resolveByovRuntimeLoraCapable,+ resolveByovRuntimeLoraCapable, runtimeIsCacheOnly, runtimeNeedsProcessGroupKill,} from './runtimes.js';const REVISION = 'fcd9e9b79a1d6018d91ac477c0968de1fa067e49';@@ -214,3 +217,42 @@ describe('minimax_h3_cuda runtime registration', () => {expect(runtimeMocks.spawn).not.toHaveBeenCalled();});});++// The JS list exists so the server can reject a bad registry `offloadProfile`+// with a stable code instead of an opaque non-zero child exit — which only+// works while it agrees with the argparse `choices=` that actually enforces it.+// Hand-synced across a language boundary is the established shape here (see+// VIDEO_PRECISIONS), so pin it rather than leave the two free to drift.+describe('MiniMax H3 CUDA offload profiles', () => {+ it('matches OFFLOAD_PROFILES in the Python runner', () => {+ const runner = readFileSync(+ join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', 'scripts', 'generate_minimax_h3_cuda.py'),+ 'utf8',+ );+ const declared = runner.match(/^OFFLOAD_PROFILES = \(([^)]*)\)/m);+ expect(declared).not.toBeNull();+ const fromPython = [...declared[1].matchAll(/"([^"]+)"/g)].map(([, value]) => value);+ expect(fromPython).toEqual([...MINIMAX_H3_CUDA_OFFLOAD_PROFILES]);+ });+});++// Execution facts read off the registry rather than re-derived from a runtime id+// at the spawn site, so a new cache-only runtime is a table line, not an edit to+// the child-spawn path. Absent means off, as with every other optional key here.+describe('runtime execution flags', () => {+ it('reports cache-only for exactly the runners that never touch the network', () => {+ expect(runtimeIsCacheOnly('minimax_h3')).toBe(true);+ expect(runtimeIsCacheOnly('minimax_h3_cuda')).toBe(true);+ expect(runtimeIsCacheOnly('ltx2')).toBe(false);+ expect(runtimeIsCacheOnly('wan22')).toBe(false);+ expect(runtimeIsCacheOnly(undefined)).toBe(false);+ });++ it('reports group-kill for the runners that spawn children of their own', () => {+ expect(runtimeNeedsProcessGroupKill('wan22')).toBe(true);+ expect(runtimeNeedsProcessGroupKill('minimax_h3')).toBe(true);+ expect(runtimeNeedsProcessGroupKill('minimax_h3_cuda')).toBe(true);+ expect(runtimeNeedsProcessGroupKill('ltx2')).toBe(false);+ expect(runtimeNeedsProcessGroupKill('nope')).toBe(false);+ });+});