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
add in-app BYOV runtime installer + rewrite hunyuan runner to honor UI controls
[._.]/ Adam Eivybb074f3fb97c
diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsxindex 3aed687142..4fdec04d44 100644--- a/client/src/components/settings/ImageGenTab.jsx+++ b/client/src/components/settings/ImageGenTab.jsx@@ -156,9 +156,9 @@ export function ImageGenTab() {const cxParallel = clampParallel(cx.parallelLimit, bounds);// Per-mode cleaner reads via the shared helper (mirrored from// server/lib/imageClean.js).- const codexClean = resolveCleanersFromConfig(cx);- const localClean = resolveCleanersFromConfig(ig.local);- const externalClean = resolveCleanersFromConfig(ig.external);+ const codexClean = resolveCleanersFromConfig(cx, IMAGE_GEN_MODE.CODEX);+ const localClean = resolveCleanersFromConfig(ig.local, IMAGE_GEN_MODE.LOCAL);+ const externalClean = resolveCleanersFromConfig(ig.external, IMAGE_GEN_MODE.EXTERNAL);const c2 = { codex: codexClean.cleanC2PA, local: localClean.cleanC2PA, external: externalClean.cleanC2PA };const dn = { codex: codexClean.denoise, local: localClean.denoise, external: externalClean.denoise };setMode(m);diff --git a/client/src/components/videoGen/RuntimeInstallModal.jsx b/client/src/components/videoGen/RuntimeInstallModal.jsxnew file mode 100644index 0000000000..027194d7a8--- /dev/null+++ b/client/src/components/videoGen/RuntimeInstallModal.jsx@@ -0,0 +1,234 @@+/**+ * BYOV video runtime installer modal. Streams progress from+ * GET /api/video-gen/setup/runtime-install?runtime=<id> (SSE) and shows the+ * raw bash output line-by-line so the user sees git-clone / uv venv / pip+ * progress as the script runs.+ *+ * Unlike Flux2InstallModal there's no animated stage pipeline — the underlying+ * scripts/setup-image-video.sh emits free-form log lines, not structured+ * stage events. Stage detection would require parsing bash echos, which+ * would rot every time the script's wording changes.+ *+ * Closing the modal mid-install (X button or Cancel) terminates the+ * EventSource, which the server interprets as a SIGTERM to the bash child.+ */++import { useEffect, useRef, useState } from 'react';+import { CheckCircle2, Loader2, AlertCircle, Download, X } from 'lucide-react';+import { safeParseJSON } from '../../lib/genUtils';+import Modal from '../ui/Modal';++const MAX_LOG_LINES = 1000;++export default function RuntimeInstallModal({ open, runtime, label, onClose, onComplete }) {+ const [logs, setLogs] = useState([]);+ const [streamStarted, setStreamStarted] = useState(false);+ const [done, setDone] = useState(false);+ const [error, setError] = useState(null);+ const [confirmingCancel, setConfirmingCancel] = useState(false);+ const logsEndRef = useRef(null);+ const esRef = useRef(null);+ // Stash onComplete in a ref so the EventSource effect doesn't tear down+ // mid-install on every parent re-render with a fresh inline arrow.+ const onCompleteRef = useRef(onComplete);+ useEffect(() => { onCompleteRef.current = onComplete; }, [onComplete]);++ // Pip and git can each emit hundreds of lines/sec. Per-line setState would+ // re-render the entire log list on every line — buffer into a ref and+ // flush on a short debounce so the React tree settles at ~10 Hz instead.+ const pendingRef = useRef([]);+ const flushTimerRef = useRef(null);+ const flush = () => {+ flushTimerRef.current = null;+ if (pendingRef.current.length === 0) return;+ const incoming = pendingRef.current;+ pendingRef.current = [];+ setLogs((prev) => {+ const combined = prev.length + incoming.length > MAX_LOG_LINES+ ? [...prev, ...incoming].slice(-MAX_LOG_LINES)+ : [...prev, ...incoming];+ return combined;+ });+ };+ const appendLog = (entry) => {+ pendingRef.current.push(entry);+ if (flushTimerRef.current == null) {+ flushTimerRef.current = setTimeout(flush, 100);+ }+ };++ useEffect(() => {+ if (!open || !runtime) {+ setLogs([]);+ setStreamStarted(false);+ setDone(false);+ setError(null);+ setConfirmingCancel(false);+ pendingRef.current = [];+ if (flushTimerRef.current != null) { clearTimeout(flushTimerRef.current); flushTimerRef.current = null; }+ if (esRef.current) { esRef.current.close(); esRef.current = null; }+ return;+ }++ setStreamStarted(true);+ const es = new EventSource(`/api/video-gen/setup/runtime-install?runtime=${encodeURIComponent(runtime)}`);+ esRef.current = es;++ es.onmessage = (ev) => {+ const msg = safeParseJSON(ev.data);+ if (!msg) return;+ if (msg.type === 'log') {+ appendLog({ kind: 'log', text: msg.message });+ } else if (msg.type === 'complete') {+ setDone(true);+ appendLog({ kind: 'success', text: msg.message });+ flush();+ es.close();+ esRef.current = null;+ onCompleteRef.current?.();+ } else if (msg.type === 'error') {+ setError(msg.message);+ appendLog({ kind: 'error', text: msg.message });+ flush();+ es.close();+ esRef.current = null;+ }+ };++ es.onerror = () => {+ setError((prev) => prev ?? (done ? null : 'Connection to installer lost. Restart PortOS or try again.'));+ es.close();+ esRef.current = null;+ };++ return () => {+ if (flushTimerRef.current != null) { clearTimeout(flushTimerRef.current); flushTimerRef.current = null; }+ if (esRef.current) { esRef.current.close(); esRef.current = null; }+ };+ // onComplete intentionally excluded — it lives in onCompleteRef.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open, runtime]);++ useEffect(() => {+ if (logsEndRef.current) {+ logsEndRef.current.scrollIntoView({ behavior: 'auto', block: 'end' });+ }+ }, [logs.length]);++ // True from the moment the EventSource opens — closing the modal between+ // the open and the first log line must still confirm before killing the+ // server-side bash child. Previously gated on `logs.length > 0`, which let+ // a quick X-click silently drop a just-started install.+ const installRunning = streamStarted && !done && !error;++ const performClose = () => {+ if (esRef.current) { esRef.current.close(); esRef.current = null; }+ onClose();+ };++ const handleClose = () => {+ if (installRunning) { setConfirmingCancel(true); return; }+ performClose();+ };++ return (+ <Modal+ open={open}+ onClose={handleClose}+ size="lg"+ align="top"+ zIndexClassName="z-[9999]"+ closeOnEsc={false}+ backdropClassName="bg-black/70 backdrop-blur-sm"+ ariaLabelledBy="runtime-install-title"+ panelClassName="bg-port-card rounded-xl border border-port-border shadow-2xl overflow-hidden flex flex-col max-h-[80vh]"+ >+ <div className="flex items-center justify-between px-5 py-4 border-b border-port-border">+ <div className="flex items-center gap-2.5">+ {done ? <CheckCircle2 size={18} className="text-port-success" />+ : error ? <AlertCircle size={18} className="text-port-error" />+ : <Download size={18} className="text-port-accent" />}+ <h2 id="runtime-install-title" className="text-sm font-semibold text-white">+ Installing {label || runtime}+ </h2>+ </div>+ <button+ onClick={handleClose}+ className="text-gray-400 hover:text-white p-1"+ aria-label="Close installer"+ >+ <X size={18} />+ </button>+ </div>++ <div className="flex-1 overflow-auto bg-port-bg px-4 py-3 font-mono text-[11px] leading-relaxed">+ {logs.length === 0 ? (+ <div className="text-gray-500 italic flex items-center gap-2">+ <Loader2 size={12} className="animate-spin" />+ Connecting to installer…+ </div>+ ) : (+ logs.map((entry, i) => (+ <div+ key={i}+ className={+ entry.kind === 'success' ? 'text-port-success font-semibold'+ : entry.kind === 'error' ? 'text-port-error'+ : 'text-gray-400'+ }+ >+ {entry.text}+ </div>+ ))+ )}+ <div ref={logsEndRef} />+ </div>++ <div className="px-5 py-3 border-t border-port-border flex items-center justify-between gap-3">+ {confirmingCancel ? (+ <>+ <span className="text-xs text-port-warning">+ Cancel the install? In-progress downloads will stop.+ </span>+ <div className="flex gap-2">+ <button+ onClick={() => setConfirmingCancel(false)}+ className="px-3 py-1.5 rounded-lg text-xs font-medium bg-port-border text-gray-300 hover:bg-port-border/70"+ >+ Keep installing+ </button>+ <button+ onClick={performClose}+ className="px-3 py-1.5 rounded-lg text-xs font-medium bg-port-error text-white hover:bg-port-error/80"+ >+ Yes, cancel+ </button>+ </div>+ </>+ ) : (+ <>+ <span className="text-xs text-gray-400">+ {done+ ? `✅ ${label || runtime} is ready. You can close this window.`+ : error+ ? '⚠️ Installer hit an error — see logs above.'+ : 'Cloning repo and installing python packages (large download on first run)…'}+ </span>+ <button+ onClick={handleClose}+ className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${+ done+ ? 'bg-port-success text-white hover:bg-port-success/80'+ : error+ ? 'bg-port-border text-white hover:bg-port-border/70'+ : 'bg-port-border text-gray-300 hover:bg-port-border/70'+ }`}+ >+ {done ? 'Done' : error ? 'Close' : 'Cancel'}+ </button>+ </>+ )}+ </div>+ </Modal>+ );+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex a0a705483f..3e1f5dae5c 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -32,7 +32,7 @@ grep -i "what you want to do" client/src/lib/README.md| `universeStylePreset.js` | Build the client-side style preset that `composeStyledPrompt` layers on top. || `bibleLimits.js` | Mirror of `server/lib/storyBible.js` `BIBLE_LIMITS`. || `editorialRoadmap.js` | `projectAnalyzedPoints` (aggregate roadmap → analyzed chart points with arc-position `frac`) + `dominant` (most-frequent string). Shared by EditorialRoadmapPanel and the Reader Map page. |-| `imageCleaners.js` | Mirror of `resolveCleanersFromConfig` from `server/lib/imageClean.js`. Reads `{cleanC2PA, denoise}` off a per-mode settings record; `cleanC2PA` defaults on, `denoise` defaults off (legacy `autoClean: true` no longer silently enables denoise). |+| `imageCleaners.js` | Mirror of `resolveCleanersFromConfig` from `server/lib/imageClean.js`. Reads `{cleanC2PA, denoise}` off a per-mode settings record. `cleanC2PA` defaults are mode-aware (on for `codex` + `external` — the backends that emit C2PA chunks today — off otherwise, as an allow-list rather than a deny-list); `denoise` defaults off everywhere (lossy, opt-in only). || `runnerFamilies.js` | Mirror of `server/lib/runners.js`. || `issueLength.js` | Mirror of `server/lib/issueLength.js`. |diff --git a/client/src/lib/imageCleaners.js b/client/src/lib/imageCleaners.jsindex 6115bd6df8..3f05e5db61 100644--- a/client/src/lib/imageCleaners.js+++ b/client/src/lib/imageCleaners.js@@ -2,13 +2,15 @@// The server is authoritative — keep the two copies in sync. Used by the// Settings ImageGenTab and the per-render ImageGen page so both surfaces// agree on how the saved per-mode settings map into the two-flag world.-// Legacy `autoClean: true` no longer carries into denoise — upgrading users-// who never explicitly chose denoise get it off (it's lossy and blurs text).+// Defaults are mode-aware: cleanC2PA defaults on only for backends that+// actually emit C2PA chunks today — codex + external. Allow-list rather+// than deny-list so a future 4th backend defaults off until confirmed.-export function resolveCleanersFromConfig(modeCfg) {+export function resolveCleanersFromConfig(modeCfg, mode) {const cfg = modeCfg || {};+ const cleanC2PADefault = mode === 'codex' || mode === 'external';return {- cleanC2PA: typeof cfg.cleanC2PA === 'boolean' ? cfg.cleanC2PA : true,+ cleanC2PA: typeof cfg.cleanC2PA === 'boolean' ? cfg.cleanC2PA : cleanC2PADefault,denoise: typeof cfg.denoise === 'boolean' ? cfg.denoise : false,};}diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex 500a7549d9..4431e5ae4a 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -29,6 +29,7 @@ import { useSearchParams, useNavigate, Link } from 'react-router-dom';import Drawer from '../components/Drawer';import { ImageGenTab } from '../components/settings/ImageGenTab';import LocalSetupPanel from '../components/settings/LocalSetupPanel';+import RuntimeInstallModal from '../components/videoGen/RuntimeInstallModal';import MediaCard from '../components/media/MediaCard';import MediaPreview from '../components/media/MediaPreview';import StylePresetPicker from '../components/media/StylePresetPicker';@@ -472,6 +473,29 @@ export default function VideoGen() {const currentModel = models.find((m) => m.id === modelId);+ // Probe the per-runtime status BEFORE the user hits Generate — without+ // this they'd see the buildArgs-time "venv not found" 500 with no good way+ // to recover. The set of "BYOV" runtimes comes from /status server-side so+ // it can't drift from the server's BYOV_RUNTIME_INFO map.+ const [byovStatus, setByovStatus] = useState(null);+ const [installModalOpen, setInstallModalOpen] = useState(false);+ const byovRuntime = currentModel?.runtime;+ const needsByovProbe = byovRuntime && (status?.byovRuntimes || []).includes(byovRuntime);+ const refreshByovStatus = useCallback((signal) => {+ if (!needsByovProbe) { setByovStatus(null); return Promise.resolve(); }+ return fetch(`/api/video-gen/setup/runtime-status?runtime=${encodeURIComponent(byovRuntime)}`, { signal })+ .then((r) => r.ok ? r.json() : null)+ .then((s) => { if (s) setByovStatus(s); })+ .catch(() => {});+ }, [byovRuntime, needsByovProbe]);+ useEffect(() => {+ if (!needsByovProbe) { setByovStatus(null); return; }+ const controller = new AbortController();+ refreshByovStatus(controller.signal);+ return () => controller.abort();+ }, [needsByovProbe, refreshByovStatus]);+ const byovRuntimeMissing = !!byovStatus && byovStatus.installed === false;+// Inline cache-status badge for the picked video model + the active text// encoder (a separate ~7-25 GB HF pull). Drives the "Available" / "Download"// affordance under the Model select, so users learn about the multi-GB@@ -774,7 +798,7 @@ export default function VideoGen() {// Without these guards the user could press Enter in the prompt// textarea and fire a request the disabled button would otherwise// have prevented.- if (!prompt.trim() || generating || (status && status.connected === false) || extendModeBlocked || a2vModeBlocked) return;+ if (!prompt.trim() || generating || (status && status.connected === false) || extendModeBlocked || a2vModeBlocked || byovRuntimeMissing) return;await runGeneration(buildGeneratePayload()).catch(() => {});};@@ -1055,6 +1079,23 @@ export default function VideoGen() {<form onSubmit={handleGenerate} className="grid grid-cols-1 lg:grid-cols-[3fr_2fr] gap-4"><div className="bg-port-card border border-port-border rounded-xl p-4 space-y-3">+ {byovRuntimeMissing && (+ <div className="rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-3 text-xs text-port-warning flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">+ <div>+ <strong className="font-semibold">{byovStatus.label}</strong> isn't installed yet.+ PortOS can fetch and install it from {byovStatus.repoUrl?.replace('https://', '')} (~5-15 min, multi-GB on first run).+ </div>+ <button+ type="button"+ onClick={() => setInstallModalOpen(true)}+ disabled={generating}+ className="self-start sm:self-auto whitespace-nowrap inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-accent text-white text-xs font-medium hover:bg-port-accent/80 disabled:opacity-50"+ >+ <Sparkles size={14} />+ Install {byovStatus.label}+ </button>+ </div>+ )}<StylePresetPickervalue={stylePreset?.id || ''}onChange={setStylePreset}@@ -1415,10 +1456,11 @@ export default function VideoGen() {) : (<buttontype="submit"- disabled={!prompt.trim() || notConnected || extendModeBlocked || a2vModeBlocked}+ disabled={!prompt.trim() || notConnected || extendModeBlocked || a2vModeBlocked || byovRuntimeMissing}className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg min-h-[40px]"title={- extendModeBlocked ? 'Pick a prior render and wait for the last frame to extract before generating'+ byovRuntimeMissing ? `${byovStatus?.label || byovRuntime} runtime is not installed — use the install banner above`+ : extendModeBlocked ? 'Pick a prior render and wait for the last frame to extract before generating': a2vModeBlocked ? (currentModel?.runtime !== 'ltx2'? 'a2v mode requires an ltx2-runtime model — pick one from the Model dropdown': 'Pick an audio file before generating')@@ -1592,6 +1634,14 @@ export default function VideoGen() {<Drawer open={settingsOpen} onClose={closeSettings} title="Media Generation Settings"><ImageGenTab /></Drawer>++ <RuntimeInstallModal+ open={installModalOpen}+ runtime={byovRuntime}+ label={byovStatus?.label}+ onClose={() => setInstallModalOpen(false)}+ onComplete={() => refreshByovStatus()}+ /></div>);}diff --git a/scripts/generate_hunyuan.py b/scripts/generate_hunyuan.pyindex d8ba0f3796..0e6eaa8fb5 100644--- a/scripts/generate_hunyuan.py+++ b/scripts/generate_hunyuan.py@@ -2,98 +2,361 @@"""PortOS HunyuanVideo MLX helper.-Subprocesses upstream gaurav-nelson/HunyuanVideo_MLX inference entry point-from the cloned repo at --repo-dir. Same subprocess-not-import strategy as-generate_wan22.py — upstream isn't a pip package.+Calls hyvideo.inference.HunyuanVideoSampler from the cloned upstream repo+directly — we no longer subprocess into upstream's sample_video_mps.py+because that wrapper hardcodes infer_steps=40, guidance_scale=7.0, and forces+fp32, which silently overrides whatever the user picked in the PortOS UI.+Owning the predict() kwargs here gives the UI actual control.Spawned by server/services/videoGen/local.js when model.runtime === 'hunyuan'.-EXPERIMENTAL: upstream HunyuanVideo_MLX is community-maintained and its CLI-hasn't been pinned across releases. ~60 GB resident at bf16 → impractical-without first evicting Ollama / Whisper / Kokoro (see the Memory Management-panel under Settings → Local LLMs). If a future upstream commit reshapes-sample_video.py args, set `broken: true` on `hunyuan_video` in-data/media-models.json and grep here to update the translation.+The cloned repo at --repo-dir provides the `hyvideo` package; the model weights+come from a huggingface_hub snapshot of the user-supplied --model-repo+(typically `tencent/HunyuanVideo`)."""import argparse+import gcimport os-import subprocess+import shutilimport sys+import unittest.mockfrom pathlib import Path+sys.path.insert(0, str(Path(__file__).resolve().parent))+from _runner_common import heartbeat, install_hf_error_handler # noqa: E402+def parse_args() -> argparse.Namespace:p = argparse.ArgumentParser(description="PortOS HunyuanVideo MLX helper")p.add_argument("--repo-dir", required=True, help="Cloned HunyuanVideo_MLX repo root")- p.add_argument("--model-repo", required=True, help="HF repo of HunyuanVideo weights (tencent/HunyuanVideo)")+ p.add_argument("--model-repo", required=True, help="HF repo of HunyuanVideo weights (e.g. tencent/HunyuanVideo)")p.add_argument("--prompt", required=True)+ p.add_argument("--negative-prompt", default="")p.add_argument("--width", type=int, required=True)p.add_argument("--height", type=int, required=True)p.add_argument("--num-frames", type=int, default=129)p.add_argument("--steps", type=int, default=30)- p.add_argument("--guidance", type=float, default=6.0)+ p.add_argument("--guidance", type=float, default=6.0, help="embedded_guidance_scale for the cfg-distilled model")p.add_argument("--seed", type=int, default=42)+ p.add_argument("--precision", default="fp32", choices=["fp16", "bf16", "fp32"],+ help="dtype for DiT + VAE + text encoder. fp32 matches upstream's "+ "sample_video_mps.py — fp16/bf16 trip an MPS matmul assertion "+ "(`Destination NDArray and Accumulator NDArray cannot have "+ "different datatype`) at the first text-encoder forward pass.")p.add_argument("--output", required=True)return p.parse_args()+def install_tqdm_step_emitter(stage: str) -> None:+ """Monkey-patch tqdm so each `.update()` also prints a STAGE: line that+ local.js's handleLine() parses into an SSE progress event.++ HunyuanVideo's diffusion loop drives a tqdm progress bar via+ `pipeline.progress_bar(total=num_inference_steps)`. Out of the box,+ tqdm against a pipe (no TTY) emits very sparse output — and even those+ writes are buffered enough that the UI sees nothing for the entire+ ~30-90 min run. We patch the base class so every step also pushes+ `STAGE:inference:step:<cur>:<total>:diffusion step N/M` to stderr;+ PYTHONUNBUFFERED=1 (set on the spawn env) guarantees it flushes.++ `tqdm.tqdm` and `tqdm.auto.tqdm` are separate references — diffusers'+ `progress_bar` uses `tqdm.auto`, but other libs reach for `tqdm.tqdm`+ directly. Patch both for safety.+ """+ import tqdm+ import tqdm.auto+ orig_cls = tqdm.tqdm++ class StageEmittingTqdm(orig_cls):+ def update(self, n=1):+ ret = super().update(n)+ try:+ cur = int(self.n)+ total = int(self.total) if self.total else 0+ except Exception:+ return ret+ print(+ f"STAGE:{stage}:step:{cur}:{total}:diffusion step {cur}/{total}",+ file=sys.stderr,+ flush=True,+ )+ return ret++ tqdm.tqdm = StageEmittingTqdm+ tqdm.auto.tqdm = StageEmittingTqdm+++def ensure_transformers_compat_shims():+ """Make hyvideo's transformers-4.x assumptions still work on transformers 5.x.+ Idempotent.++ hyvideo was written when `CLIPTextModel` exposed its inner stack through a+ `.text_model` attribute. transformers ≥5 flattened that. The mismatch+ trips `hyvideo/text_encoder/__init__.py:34`:+ `text_encoder.final_layer_norm = text_encoder.text_model.final_layer_norm`+ Adding a self-reference makes that reassignment a no-op (the right-hand+ side already exists at the top level in 5.x).++ Companion bandaid: stage_hunyuan_model_base() walks both+ `model.model.language_model` and `model.language_model` for the same+ transformers-5.x flattening on the Llava side.+ """+ import transformers+ if not hasattr(transformers.CLIPTextModel, "text_model"):+ transformers.CLIPTextModel.text_model = property(lambda self: self)+++# Repos Hunyuan needs alongside the main tencent/HunyuanVideo snapshot.+# tencent/HunyuanVideo ships only the DiT + VAE; the two text encoders+# (Llama-3 backbone from Llava, plus CLIP) live in separate public repos+# and have to be staged into the MODEL_BASE tree at the paths hyvideo's+# constants.py expects (<base>/text_encoder, <base>/text_encoder_2).+LLAVA_REPO = "xtuner/llava-llama-3-8b-v1_1-transformers"+CLIP_REPO = "openai/clip-vit-large-patch14"+# CLIP files used by hyvideo's text encoder loader — explicit allowlist+# keeps the snapshot tight (CLIP ships training artifacts we don't need).+CLIP_FILES = (+ "config.json",+ "model.safetensors",+ "preprocessor_config.json",+ "tokenizer.json",+ "tokenizer_config.json",+ "vocab.json",+ "merges.txt",+ "special_tokens_map.json",+)+++def stage_hunyuan_model_base(repo_dir, snapshot_dir):+ """Build a writable MODEL_BASE tree with everything hyvideo needs.++ Layout under `<repo_dir>/portos-models/`:+ - hunyuan-video-t2v-720p/ — symlink to <snapshot>/hunyuan-video-t2v-720p+ (gives the DiT + VAE without duplicating GB)+ - text_encoder/ — Llama backbone extracted from Llava-Llama-3+ - text_encoder_2/ — CLIP ViT-L/14++ Idempotent: skips downloads + preprocessing when the destination already+ looks populated. First-run extra cost is ~17 GB of downloads + a CPU+ preprocess pass that takes a couple of minutes.+ """+ base = Path(repo_dir) / "portos-models"+ base.mkdir(parents=True, exist_ok=True)++ src_main = Path(snapshot_dir) / "hunyuan-video-t2v-720p"+ dst_main = base / "hunyuan-video-t2v-720p"+ # Path.exists() follows symlinks, so a dangling link (snapshot pruned+ # from HF cache between runs) would return False AND then symlink_to+ # would raise FileExistsError because the link itself is present. Use+ # is_symlink to detect that case and recreate. lexists doesn't help+ # because we'd still need to unlink before symlink_to.+ if dst_main.is_symlink() and not dst_main.exists():+ dst_main.unlink()+ if not dst_main.exists():+ dst_main.symlink_to(src_main, target_is_directory=True)++ from huggingface_hub import snapshot_download as _snap++ te2 = base / "text_encoder_2"+ if not (te2 / "config.json").is_file():+ print(f"STAGE:download-clip:{CLIP_REPO}", file=sys.stderr, flush=True)+ with heartbeat("download-clip"):+ _snap(CLIP_REPO, local_dir=str(te2), allow_patterns=list(CLIP_FILES))++ te = base / "text_encoder"+ if not (te / "config.json").is_file():+ # Llava ships ~16 GB of weights; we only need the language_model+ # half (the Llama backbone) plus the tokenizer. Download into a+ # scratch dir, run upstream's split, then delete the raw download.+ scratch = base / "_llava_raw"+ print(f"STAGE:download-llava:{LLAVA_REPO}", file=sys.stderr, flush=True)+ with heartbeat("download-llava"):+ _snap(LLAVA_REPO, local_dir=str(scratch))++ print("STAGE:preprocess-text-encoder", file=sys.stderr, flush=True)+ # transformers + torch are heavy imports — defer until we know we+ # need them (subsequent renders skip this whole branch).+ from transformers import AutoProcessor, LlavaForConditionalGeneration+ import torch+ with heartbeat("preprocess-llava"):+ processor = AutoProcessor.from_pretrained(str(scratch))+ # fp16 halves the peak RAM during preprocessing (Llava is ~16 GB+ # at fp32, ~8 GB at fp16). hyvideo loads text_encoder at fp16+ # downstream anyway, so we save nothing by extracting at fp32.+ model = LlavaForConditionalGeneration.from_pretrained(+ str(scratch),+ torch_dtype=torch.float16,+ low_cpu_mem_usage=True,+ device_map=None,+ )+ # transformers ≥5 wraps the Llama backbone in an outer LlavaModel+ # (model.model.language_model); 4.x had it flat (model.language_model).+ # Walk one level deep first, fall back to flat, raise on neither.+ language_model = getattr(getattr(model, "model", model), "language_model", None)+ if language_model is None:+ raise AttributeError(+ f"Could not locate Llava's language_model on {type(model).__name__}; "+ "transformers structure changed again."+ )+ # Atomic write via `.partial` rename — a crash mid save_pretrained+ # would otherwise leave a half-written text_encoder/ that the+ # config.json idempotency check above would treat as complete.+ staging = te.with_name(te.name + ".partial")+ shutil.rmtree(staging, ignore_errors=True)+ staging.mkdir(parents=True)+ language_model.save_pretrained(str(staging), safe_serialization=True)+ processor.tokenizer.save_pretrained(str(staging))+ del model, processor, language_model+ gc.collect()+ os.replace(staging, te)++ def _warn_on_rmtree_error(func, path, exc_info):+ print(f"⚠️ hunyuan: failed to clean scratch {path}: {exc_info[1]}", file=sys.stderr)+ shutil.rmtree(scratch, onerror=_warn_on_rmtree_error)++ return base+++@install_hf_error_handlerdef main() -> int:- args = parse_args()+ cli = parse_args()- repo_dir = Path(args.repo_dir).expanduser().resolve()+ repo_dir = Path(cli.repo_dir).expanduser().resolve()if not repo_dir.is_dir():print(f"❌ HunyuanVideo MLX repo not found at {repo_dir}", file=sys.stderr)return 64- # Upstream's entry point is sample_video.py (mirrors the original tencent- # script name). Fall back to generate.py if upstream restructures.- sample_py = repo_dir / "sample_video.py"- if not sample_py.exists():- sample_py = repo_dir / "generate.py"- if not sample_py.exists():- print(f"❌ no sample_video.py or generate.py under {repo_dir} — upstream layout changed?", file=sys.stderr)++ # hyvideo isn't pip-installed — it's a package directory inside the repo.+ # Prepend the repo so `import hyvideo.*` resolves without a chdir.+ sys.path.insert(0, str(repo_dir))++ # MPS probe BEFORE the multi-GB snapshot — no point pulling 30 GB if the+ # render can't run. torch import is ~5s, snapshot is gigabytes.+ import torch+ if not torch.backends.mps.is_available():+ print("❌ MPS not available — HunyuanVideo MLX requires Apple Silicon", file=sys.stderr)return 64- print(f"STAGE:download-weights:{args.model_repo}", file=sys.stderr, flush=True)+ print(f"STAGE:download-weights:{cli.model_repo}", file=sys.stderr, flush=True)try:from huggingface_hub import snapshot_downloadexcept Exception as err:print(f"❌ huggingface_hub import failed: {err}", file=sys.stderr)return 64- ckpt_dir = snapshot_download(args.model_repo)+ # snapshot_download can stall for minutes on a single multi-GB shard;+ # heartbeat keeps the PortOS idle watchdog from killing us mid-pull.+ with heartbeat("download-weights"):+ ckpt_dir = snapshot_download(cli.model_repo)print(f"🔧 hunyuan: weights ← {ckpt_dir}", file=sys.stderr)- upstream_args = [- sys.executable,- str(sample_py),- "--model-base", ckpt_dir,- "--video-size", str(args.height), str(args.width),- "--video-length", str(args.num_frames),- "--infer-steps", str(args.steps),- "--guidance-scale", str(args.guidance),- "--prompt", args.prompt,- "--seed", str(args.seed),- "--save-path", args.output,- ]-- print(f"STAGE:inference", file=sys.stderr, flush=True)- print(f"🎬 hunyuan generate {args.width}x{args.height} frames={args.num_frames} steps={args.steps}", file=sys.stderr)-- proc = subprocess.run(- upstream_args,- cwd=str(repo_dir),- env={**os.environ, "PYTHONUNBUFFERED": "1"},+ # tencent/HunyuanVideo ships only the DiT + VAE — the text encoders are+ # separate public repos that have to be staged into a MODEL_BASE tree+ # at the paths hyvideo.constants expects. First run downloads ~17 GB+ # extra; subsequent renders are no-op.+ model_base = stage_hunyuan_model_base(repo_dir, ckpt_dir)+ print(f"🔧 hunyuan: model base ← {model_base}", file=sys.stderr)++ # hyvideo.constants reads MODEL_BASE at import time to build VAE_PATH and+ # TEXT_ENCODER_PATH. Set before importing hyvideo or the lookup hits the+ # default "./ckpts" (relative to cwd) and fails to find the encoders.+ os.environ["MODEL_BASE"] = str(model_base)++ print("STAGE:load-pipeline", file=sys.stderr, flush=True)+ # Install BEFORE importing hyvideo / diffusers — they capture references+ # to `tqdm.tqdm` at import time, so a later patch won't reach the bar+ # that pipeline_hunyuan_video.py actually uses for the diffusion loop.+ install_tqdm_step_emitter("inference")+ ensure_transformers_compat_shims()+ from hyvideo.config import parse_args as hv_parse_args+ from hyvideo.inference import HunyuanVideoSampler+ from hyvideo.utils.file_utils import save_videos_grid++ # Borrow hyvideo's full argparse namespace so every model default+ # (latent_channels, vae='884-16c-hy', flow_shift, etc.) is populated.+ # mock.patch.object scopes the sys.argv swap to the parse_args call so a+ # signal handler firing mid-block can't see our placeholder argv.+ with unittest.mock.patch.object(sys, "argv", ["generate_hunyuan"]):+ hv = hv_parse_args()++ # Override only the fields the UI controls. precision is forced equal+ # across DiT / VAE / text encoder — three precision knobs on a video gen+ # form would be excessive, and they typically need to match for MPS.+ hv.model_base = str(model_base)+ hv.dit_weight = str(model_base / "hunyuan-video-t2v-720p" / "transformers" / "mp_rank_00_model_states.pt")+ hv.video_size = [int(cli.height), int(cli.width)]+ hv.video_length = int(cli.num_frames)+ hv.infer_steps = int(cli.steps)+ hv.embedded_cfg_scale = float(cli.guidance)+ hv.seed = int(cli.seed)+ hv.prompt = cli.prompt+ hv.neg_prompt = cli.negative_prompt or None+ hv.precision = cli.precision+ hv.vae_precision = cli.precision+ hv.text_encoder_precision = cli.precision+ # hyvideo carries a separate precision knob for the second text encoder+ # (CLIP-L). Without this, CLIP-L silently loads at its default (fp16) even+ # when we ask for fp32 everywhere else — and on MPS that single mismatched+ # dtype is enough to trip the matmul accumulator assertion at the first+ # text-encoder forward pass.+ hv.text_encoder_precision_2 = cli.precision+ # Autocast on MPS produces NaNs for some Hunyuan layers; the upstream+ # wrapper disabled it too. Keep off until tested.+ hv.disable_autocast = True++ # Fail-fast: from_pretrained spends ~1-3 min loading other shards before+ # discovering the DiT file is missing. Check up front for a clear error.+ if not Path(hv.dit_weight).is_file():+ print(f"❌ expected DiT weights missing: {hv.dit_weight}", file=sys.stderr)+ return 64++ device = torch.device("mps")+ print(+ f"🎬 hunyuan generate {cli.width}x{cli.height} frames={cli.num_frames} "+ f"steps={cli.steps} guidance={cli.guidance} precision={cli.precision}",+ file=sys.stderr,)- if proc.returncode != 0:- print(f"❌ hunyuan upstream exited {proc.returncode}", file=sys.stderr)- return proc.returncode+ print("STAGE:from-pretrained", file=sys.stderr, flush=True)+ # from_pretrained loads ~30 GB into MPS on a cold run — silent for+ # minutes (mmap + weight assignment, no tqdm). Same idle-watchdog+ # concern as the snapshot pull.+ with heartbeat("from-pretrained"):+ sampler = HunyuanVideoSampler.from_pretrained(model_base, args=hv, device=device)++ print("STAGE:inference", file=sys.stderr, flush=True)+ outputs = sampler.predict(+ prompt=hv.prompt,+ height=hv.video_size[0],+ width=hv.video_size[1],+ video_length=hv.video_length,+ seed=hv.seed,+ negative_prompt=hv.neg_prompt,+ infer_steps=hv.infer_steps,+ # cfg_scale stays at the hyvideo default (1.0) — the cfg-distilled+ # variant uses embedded_guidance_scale as the real CFG knob.+ guidance_scale=hv.cfg_scale,+ embedded_guidance_scale=hv.embedded_cfg_scale,+ flow_shift=hv.flow_shift,+ batch_size=hv.batch_size,+ num_videos_per_prompt=hv.num_videos,+ )++ samples = outputs.get("samples") or []+ if len(samples) == 0:+ print("❌ hunyuan predict() returned no samples", file=sys.stderr)+ return 1++ Path(cli.output).parent.mkdir(parents=True, exist_ok=True)+ # samples[0] is (C, T, H, W) — save_videos_grid wants (B, C, T, H, W),+ # so unsqueeze the batch dim before writing.+ save_videos_grid(samples[0].unsqueeze(0), cli.output, fps=24)- if not Path(args.output).exists():- print(f"❌ hunyuan finished but {args.output} missing", file=sys.stderr)+ if not Path(cli.output).exists():+ print(f"❌ hunyuan finished but {cli.output} missing", file=sys.stderr)return 1- print(f"✅ hunyuan saved {args.output}", file=sys.stderr)+ print(f"✅ hunyuan saved {cli.output}", file=sys.stderr)return 0diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.shindex 095e4ffdf8..6126c355d0 100755--- a/scripts/setup-image-video.sh+++ b/scripts/setup-image-video.sh@@ -31,28 +31,47 @@ mkdir -p "${PORTOS_DATA}/loras"mkdir -p "${PORTOS_DATA}/videos"mkdir -p "${PORTOS_DATA}/video-thumbnails"-INSTALL_VIDEO="${INSTALL_VIDEO:-$(is_macos && echo 1 || echo 0)}"+# When the user only wants a specific BYOV runtime (set via INSTALL_LTX2 /+# INSTALL_WAN22 / INSTALL_HUNYUAN — typically from the in-app installer),+# skip the mflux + legacy mlx_video preamble. Those bring-your-own-venv+# runtimes are self-contained and don't depend on mflux; running the+# preamble unprompted hits PEP 668 ("externally-managed-environment") on+# Homebrew Python and aborts the whole script before the requested runtime+# install ever starts. A bare `bash setup-image-video.sh` still installs+# mflux as before.+ANY_BYOV="${INSTALL_LTX2:-0}${INSTALL_WAN22:-0}${INSTALL_HUNYUAN:-0}"+if [[ "$ANY_BYOV" == "000" ]]; then+ DEFAULT_INSTALL_MFLUX=1+ DEFAULT_INSTALL_VIDEO=$(is_macos && echo 1 || echo 0)+else+ DEFAULT_INSTALL_MFLUX=0+ DEFAULT_INSTALL_VIDEO=0+fi+INSTALL_MFLUX="${INSTALL_MFLUX:-$DEFAULT_INSTALL_MFLUX}"+INSTALL_VIDEO="${INSTALL_VIDEO:-$DEFAULT_INSTALL_VIDEO}"-# Install via pip --user so we don't pollute the system or require a venv.-# mflux comes with the mflux-generate CLI which the local image backend-# spawns directly. transformers<5 is required for MLX compatibility.-#-# `--force-reinstall --no-deps` on mflux only — earlier setup runs could-# leave the user-site copy at the right version number but with stale file-# layout (we hit this in 0.12.1, where `mflux/models/flux/cli/` was missing-# from a partial reinstall, breaking the entry-point shim). Forcing the-# reinstall flushes the file tree without re-resolving torch/mlx and friends.-echo "📦 Installing image generation packages (mflux + deps)..."-"$PYTHON_BIN" -m pip install --upgrade --user --force-reinstall --no-deps mflux-# mflux above is installed with --no-deps to flush its file tree without-# re-resolving torch/mlx — but that means we must explicitly install mflux's-# own runtime deps here (notably `mlx` on macOS, which it imports at startup).-# Without this, INSTALL_VIDEO=0 leaves mflux unable to import.-MFLUX_DEPS=("transformers<5" safetensors huggingface_hub numpy opencv-python tqdm)-if is_macos; then- MFLUX_DEPS+=(mlx)+if [[ "$INSTALL_MFLUX" == "1" ]]; then+ # Install via pip --user so we don't pollute the system or require a venv.+ # mflux comes with the mflux-generate CLI which the local image backend+ # spawns directly. transformers<5 is required for MLX compatibility.+ #+ # `--force-reinstall --no-deps` on mflux only — earlier setup runs could+ # leave the user-site copy at the right version number but with stale file+ # layout (we hit this in 0.12.1, where `mflux/models/flux/cli/` was missing+ # from a partial reinstall, breaking the entry-point shim). Forcing the+ # reinstall flushes the file tree without re-resolving torch/mlx and friends.+ echo "📦 Installing image generation packages (mflux + deps)..."+ "$PYTHON_BIN" -m pip install --upgrade --user --force-reinstall --no-deps mflux+ # mflux above is installed with --no-deps to flush its file tree without+ # re-resolving torch/mlx — but that means we must explicitly install mflux's+ # own runtime deps here (notably `mlx` on macOS, which it imports at startup).+ # Without this, INSTALL_VIDEO=0 leaves mflux unable to import.+ MFLUX_DEPS=("transformers<5" safetensors huggingface_hub numpy opencv-python tqdm)+ if is_macos; then+ MFLUX_DEPS+=(mlx)+ fi+ "$PYTHON_BIN" -m pip install --upgrade --user "${MFLUX_DEPS[@]}"fi-"$PYTHON_BIN" -m pip install --upgrade --user "${MFLUX_DEPS[@]}"if [[ "$INSTALL_VIDEO" == "1" ]]; thenif is_macos; then@@ -230,9 +249,17 @@ if [[ "$INSTALL_HUNYUAN" == "1" ]]; thenecho "📦 Creating HunyuanVideo_MLX venv with Python 3.11..."(cd "${HUNYUAN_DIR}" && uv venv --python 3.11)fi- if [[ -f "${HUNYUAN_DIR}/requirements.txt" ]]; then- echo "📦 Installing HunyuanVideo_MLX requirements..."- (cd "${HUNYUAN_DIR}" && uv pip install -r requirements.txt)+ # Upstream gaurav-nelson ships requirements as `requirements_mps.txt` (the+ # MPS-specific variant — there's no plain `requirements.txt`). Prefer the+ # MPS one when present, then plain `requirements.txt`, then fall back to+ # `uv sync` for repos that use pyproject + lockfile instead.+ HUNYUAN_REQS=""+ for cand in requirements_mps.txt requirements.txt; do+ if [[ -f "${HUNYUAN_DIR}/${cand}" ]]; then HUNYUAN_REQS="$cand"; break; fi+ done+ if [[ -n "$HUNYUAN_REQS" ]]; then+ echo "📦 Installing HunyuanVideo_MLX requirements from ${HUNYUAN_REQS}..."+ (cd "${HUNYUAN_DIR}" && uv pip install -r "$HUNYUAN_REQS")elseecho "📦 Syncing HunyuanVideo_MLX packages..."(cd "${HUNYUAN_DIR}" && uv sync)diff --git a/server/lib/imageClean.js b/server/lib/imageClean.jsindex 9e6bd2a406..9cdae3962c 100644--- a/server/lib/imageClean.js+++ b/server/lib/imageClean.js@@ -23,19 +23,21 @@ import { tryReadFile, safeJSONParse, atomicWrite } from './fileUtils.js';* "what did the user save" rule that resolver + Settings UI + ImageGen* page + test mocks all need to agree on).*- * Defaults: `cleanC2PA` defaults to true (safe, lossless); `denoise` defaults- * to false (lossy, blurs text — must be explicitly opted into). Legacy- * pre-split installs carrying `autoClean: true` keep `cleanC2PA` on (which- * defaults on anyway) but do NOT silently inherit denoise — upgrading users- * who never explicitly chose denoise get it off.+ * Defaults are mode-aware: `cleanC2PA` defaults on only for backends that+ * actually emit C2PA chunks today — `codex` (gpt-image-2) and `external`+ * (A1111 / Forge proxies that may re-encode through ComfyUI's C2PA stamp+ * node). Allow-list rather than deny-list: a future 4th backend defaults+ * off until someone confirms it emits caBX. `denoise` defaults to false+ * everywhere (lossy, blurs text — must be explicitly opted into).** Mirrored verbatim in `client/src/lib/imageCleaners.js` — keep the two* copies in sync; the client tree can't import from server/lib.*/-export function resolveCleanersFromConfig(modeCfg) {+export function resolveCleanersFromConfig(modeCfg, mode) {const cfg = modeCfg || {};+ const cleanC2PADefault = mode === 'codex' || mode === 'external';return {- cleanC2PA: typeof cfg.cleanC2PA === 'boolean' ? cfg.cleanC2PA : true,+ cleanC2PA: typeof cfg.cleanC2PA === 'boolean' ? cfg.cleanC2PA : cleanC2PADefault,denoise: typeof cfg.denoise === 'boolean' ? cfg.denoise : false,};}diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 4da73d631c..d7c08cd9b2 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -11,6 +11,7 @@ import { existsSync } from 'fs';import { copyFile, unlink } from 'fs/promises';import { randomUUID } from 'crypto';import { join, extname } from 'path';+import { spawn } from 'child_process';import { z } from 'zod';import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';import { uploadFields } from '../lib/multipart.js';@@ -22,6 +23,10 @@ import {listVideoModels,defaultVideoModelId,BYOV_VIDEO_RUNTIMES,+ BYOV_RUNTIME_INFO,+ isByovRuntimeInstalled,+ isByovRuntimeReady,+ invalidateByovReadyCache,loadHistory,deleteHistoryItem,setHistoryItemHidden,@@ -159,6 +164,133 @@ router.get('/status', asyncHandler(async (_req, res) => {missingPackages: missing,models: listVideoModels(),defaultModel: defaultVideoModelId(),+ // Authoritative list of bring-your-own-venv runtimes — lets the client+ // gate the install-banner probe without hardcoding the same Set.+ byovRuntimes: Object.keys(BYOV_RUNTIME_INFO),+ });+}));++// `installed` here means "fully ready to render" — both the venv binary+// exists AND its python packages are importable. The sync existsSync gate+// alone is too permissive: a partial install (clone done, `uv pip install`+// aborted) leaves a venv directory present but no torch, which would+// hide the banner and make every render fail with a deep ImportError.+router.get('/setup/runtime-status', asyncHandler(async (req, res) => {+ const runtime = String(req.query?.runtime || '');+ const info = BYOV_RUNTIME_INFO[runtime];+ if (!info) {+ return failValidation(res, `Unknown runtime: ${runtime}. Expected one of: ${Object.keys(BYOV_RUNTIME_INFO).join(', ')}`);+ }+ const binaryPresent = isByovRuntimeInstalled(info.id);+ const packagesReady = binaryPresent ? await isByovRuntimeReady(info.id) : false;+ res.json({+ runtime: info.id,+ label: info.label,+ installed: binaryPresent && packagesReady,+ binaryPresent,+ packagesReady,+ venvPath: info.venvPython,+ repoDir: info.repoDir,+ repoUrl: info.repoUrl,+ installEnvVar: info.installEnvVar,+ });+}));++// In-flight singleton per runtime. A rapid double-click of the install+// button would otherwise race two `bash setup-image-video.sh` processes+// against the same target dir, both trying to git-clone or pip-install at+// once. Existing existsSync gate doesn't help — the install hasn't created+// the venv yet on the second click.+const runtimeInstallInFlight = new Map();++// Shells out to scripts/setup-image-video.sh with the runtime's INSTALL_X+// env pre-set, so the in-app installer and the README's terminal recipe+// invoke the exact same install path — no parallel Node-side implementation+// per runtime to keep in sync.+router.get('/setup/runtime-install', asyncHandler(async (req, res) => {+ const runtime = String(req.query?.runtime || '');+ const info = BYOV_RUNTIME_INFO[runtime];+ res.writeHead(200, {+ 'Content-Type': 'text/event-stream',+ 'Cache-Control': 'no-cache',+ Connection: 'keep-alive',+ });+ const send = (event) => {+ if (!res.writableEnded) res.write(`data: ${JSON.stringify(event)}\n\n`);+ };+ const safeEnd = () => { if (!res.writableEnded) res.end(); };++ if (!info) {+ send({ type: 'error', message: `Unknown runtime: ${runtime}` });+ return safeEnd();+ }+ // Skip ONLY when both the binary AND the import probe pass. A venv with a+ // python binary but no torch is the partial-install case the user is+ // explicitly re-triggering us to fix — short-circuiting would strand them.+ if (isByovRuntimeInstalled(info.id) && await isByovRuntimeReady(info.id)) {+ send({ type: 'log', message: `${info.label} already installed at ${info.venvPython}` });+ send({ type: 'complete', message: 'Already installed — nothing to do.' });+ return safeEnd();+ }+ if (runtimeInstallInFlight.has(info.id)) {+ send({ type: 'error', message: `Another ${info.label} install is already running. Wait for it to finish or restart PortOS.` });+ return safeEnd();+ }+ // The install may add/remove packages; drop any cached "ready" so the+ // post-install /runtime-status response reflects the new state instead of+ // a stale "true" from before a deliberate cleanup.+ invalidateByovReadyCache(info.id);++ const scriptPath = join(PATHS.root, 'scripts', 'setup-image-video.sh');+ if (!existsSync(scriptPath)) {+ send({ type: 'error', message: `Installer script not found at ${scriptPath}` });+ return safeEnd();+ }++ send({ type: 'log', message: `▸ Starting ${info.label} install via ${info.installEnvVar}=1 bash scripts/setup-image-video.sh` });+ const child = spawn('bash', [scriptPath], {+ env: { ...process.env, [info.installEnvVar]: '1' },+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ runtimeInstallInFlight.set(info.id, child);++ const onChunk = (chunk) => {+ for (const line of chunk.toString().split(/[\r\n]+/)) {+ const t = line.trimEnd();+ if (t) send({ type: 'log', message: t });+ }+ };+ child.stdout.on('data', onChunk);+ child.stderr.on('data', onChunk);+ child.on('error', (err) => {+ runtimeInstallInFlight.delete(info.id);+ send({ type: 'error', message: `Installer failed to spawn: ${err.message}` });+ safeEnd();+ });+ child.on('close', async (code) => {+ runtimeInstallInFlight.delete(info.id);+ // Re-probe rather than trusting exit code alone — partial installs+ // (network drop mid-clone, missing requirements file, ctrl-c via+ // SIGTERM) can exit 0 but leave the venv unable to import its core+ // packages. Probe both the binary AND the import surface so the+ // success message can't lie. The banner gate uses the same probe.+ const binaryPresent = isByovRuntimeInstalled(info.id);+ const packagesReady = binaryPresent && await isByovRuntimeReady(info.id);+ if (code === 0 && binaryPresent && packagesReady) {+ send({ type: 'complete', message: `${info.label} ready: ${info.venvPython}` });+ } else if (code === 0 && !binaryPresent) {+ send({ type: 'error', message: `Installer exited 0 but ${info.venvPython} is still missing. Re-run from a terminal to see what happened.` });+ } else if (code === 0) {+ send({ type: 'error', message: `Installer exited 0 but the venv can't import its core packages. Check the log above for pip errors; re-run from a terminal if needed.` });+ } else {+ send({ type: 'error', message: `Installer exited with code ${code}.` });+ }+ safeEnd();+ });++ req.on('close', () => {+ if (!child.killed) child.kill('SIGTERM');+ safeEnd();});}));diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex aa58cc6726..bbc01db895 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -34,6 +34,17 @@ vi.mock('../services/videoGen/local.js', () => ({// "accepts BYOV-runtime when pythonPath missing" case passes and the// negative case (legacy mlx_video model) still 400s.BYOV_VIDEO_RUNTIMES: new Set(['ltx2', 'wan22', 'hunyuan']),+ // The route's /status response now surfaces the BYOV runtime list so the+ // client can drop its hardcoded copy. Mirror the real shape — only the+ // `id` and a couple of UI-display fields are read by /status.+ BYOV_RUNTIME_INFO: {+ ltx2: { id: 'ltx2', label: 'LTX-2 MLX', venvPython: '/tmp/ltx2.py', installEnvVar: 'INSTALL_LTX2', repoUrl: 'x', repoDir: '/tmp' },+ wan22: { id: 'wan22', label: 'Wan 2.2 MLX', venvPython: '/tmp/wan22.py', installEnvVar: 'INSTALL_WAN22', repoUrl: 'x', repoDir: '/tmp' },+ hunyuan: { id: 'hunyuan', label: 'HunyuanVideo MLX', venvPython: '/tmp/hunyuan.py', installEnvVar: 'INSTALL_HUNYUAN', repoUrl: 'x', repoDir: '/tmp' },+ },+ isByovRuntimeInstalled: vi.fn(() => false),+ isByovRuntimeReady: vi.fn(async () => false),+ invalidateByovReadyCache: vi.fn(),}));// Render submissions go through the mediaJobQueue. Mock its surface so thediff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.jsindex 242da9012b..5fbd491909 100644--- a/server/services/imageGen/index.js+++ b/server/services/imageGen/index.js@@ -39,7 +39,7 @@ const codexCfg = (s) => cfg(s).codex || {};// `/generate` and `generateImage()` (safety net for direct callers like// `generateAvatar`).export function resolveImageCleaners(body, settings, mode) {- const saved = resolveCleanersFromConfig(cfg(settings)[mode]);+ const saved = resolveCleanersFromConfig(cfg(settings)[mode], mode);return {cleanC2PA: typeof body?.cleanC2PA === 'boolean' ? body.cleanC2PA : saved.cleanC2PA,denoise: typeof body?.denoise === 'boolean' ? body.denoise : saved.denoise,diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex 802b4bdb89..f66c918d9d 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -392,8 +392,11 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m// Sort by mtime, not filename. mflux names files like `step_1.png` …// `step_20.png` (no zero-padding), so alphabetical sort puts `step_2`// *after* `step_19` and we'd render an early-step latent (mostly noise)- // instead of the latest.- const names = (await readdir(stepwiseDir)).filter((f) => f.endsWith('.png'));+ // instead of the latest. Also drop mflux's `seed_*_composite.png` —+ // it writes that grid right after every step, so its mtime always wins+ // the "latest" race and the user would see a growing thumbnail strip+ // instead of the live diffusion frame.+ const names = (await readdir(stepwiseDir)).filter((f) => f.endsWith('.png') && !f.includes('composite'));const stats = await Promise.all(names.map(async (n) => {const s = await stat(join(stepwiseDir, n)).catch(() => null);return s ? { n, mtimeMs: s.mtimeMs } : null;diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex 8985469285..8d609d4cab 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -57,13 +57,101 @@ const IS_WIN = process.platform === 'win32';// Cached as a plain object at boot for O(1) lookup by id, matching the prior shape.export const VIDEO_MODELS = Object.fromEntries(getVideoModels().map((m) => [m.id, m]));-// "Bring-your-own-venv" video runtimes — runtimes that resolve their own-// Python interpreter inside buildArgs (LTX2_VENV_PYTHON / WAN22_VENV_PYTHON-// / HUNYUAN_VENV_PYTHON), so the legacy mlx_video `settings.imageGen.local.-// pythonPath` is irrelevant. Used by BOTH services/videoGen/local.js and-// routes/videoGen.js to decide when to enforce the pythonPath gate — keep-// the two in sync via this single export.-export const BYOV_VIDEO_RUNTIMES = Object.freeze(new Set(['ltx2', 'wan22', 'hunyuan']));+// Per-runtime metadata for "bring-your-own-venv" video runtimes — those that+// resolve their own Python interpreter inside buildArgs (so the legacy+// mlx_video `settings.imageGen.local.pythonPath` is irrelevant). Single+// source of truth: the BYOV_VIDEO_RUNTIMES Set + the /setup/runtime-* routes+// + the client install banner all derive from this map's keys.+//+// `importProbe` is a tiny Python expression run by isByovRuntimeReady() to+// confirm the venv's *packages* are actually installed (not just the venv+// binary). A partial install (e.g. setup script aborted after `uv venv`+// before `uv pip install`) leaves the binary present but no torch — without+// this probe the UI would hide the install banner and renders would fail+// with a deep ImportError inside the runner script.+export const BYOV_RUNTIME_INFO = Object.freeze({+ hunyuan: {+ id: 'hunyuan',+ label: 'HunyuanVideo MLX',+ venvPython: HUNYUAN_VENV_PYTHON,+ repoDir: HUNYUAN_REPO_DIR,+ installEnvVar: 'INSTALL_HUNYUAN',+ repoUrl: 'https://github.com/gaurav-nelson/HunyuanVideo_MLX',+ importProbe: 'import torch, huggingface_hub, transformers',+ },+ wan22: {+ id: 'wan22',+ label: 'Wan 2.2 MLX',+ venvPython: WAN22_VENV_PYTHON,+ repoDir: WAN22_REPO_DIR,+ installEnvVar: 'INSTALL_WAN22',+ repoUrl: 'https://github.com/osama-ata/Wan2.2-mlx',+ importProbe: 'import torch, transformers, huggingface_hub',+ },+ ltx2: {+ id: 'ltx2',+ label: 'LTX-2 MLX',+ venvPython: LTX2_VENV_PYTHON,+ repoDir: join(homedir(), '.portos', 'ltx-2-mlx'),+ installEnvVar: 'INSTALL_LTX2',+ repoUrl: 'https://github.com/dgrauet/ltx-2-mlx',+ // Matches the post-install check setup-image-video.sh runs after+ // `uv sync` (`import ltx_pipelines_mlx` is the canonical health signal+ // for this venv).+ importProbe: 'import ltx_pipelines_mlx',+ },+});++export const BYOV_VIDEO_RUNTIMES = Object.freeze(new Set(Object.keys(BYOV_RUNTIME_INFO)));++export function isByovRuntimeInstalled(runtimeId) {+ const info = BYOV_RUNTIME_INFO[runtimeId];+ if (!info) return false;+ return existsSync(info.venvPython);+}++// Cache the import-probe result per runtime for the life of the server+// process (or until invalidateByovReadyCache is called). The probe itself+// spawns python + imports torch — measured ~500ms-2s warm, ~5s cold — so+// repeating it on every status request is too slow. Positive results are+// stable (you don't accidentally uninstall packages); negative results we+// re-probe each request so a finished install reflects immediately. The+// install-completion path in routes/videoGen.js explicitly invalidates+// the entry for the runtime it just installed.+const readyCache = new Map();+export function invalidateByovReadyCache(runtimeId) {+ if (runtimeId) readyCache.delete(runtimeId); else readyCache.clear();+}+export async function isByovRuntimeReady(runtimeId) {+ const info = BYOV_RUNTIME_INFO[runtimeId];+ if (!info) return false;+ if (!existsSync(info.venvPython)) return false;+ if (readyCache.get(runtimeId) === true) return true;+ const probeOk = await new Promise((resolve) => {+ const child = spawn(info.venvPython, ['-c', info.importProbe], {+ stdio: ['ignore', 'ignore', 'ignore'],+ });+ const timer = setTimeout(() => { if (!child.killed) child.kill('SIGKILL'); resolve(false); }, 30000);+ child.on('close', (code) => { clearTimeout(timer); resolve(code === 0); });+ child.on('error', () => { clearTimeout(timer); resolve(false); });+ });+ if (probeOk) readyCache.set(runtimeId, true);+ return probeOk;+}++// Throws the same shape the per-runtime buildArgs used to throw inline — a+// 500 with a stable runtime-specific code the route layer and tests already+// match against. The error codes are LTX2_VENV_MISSING / WAN22_VENV_MISSING+// / HUNYUAN_VENV_MISSING; keep `runtimeId.toUpperCase()` to preserve them.+export function assertByovRuntimeInstalled(runtimeId) {+ const info = BYOV_RUNTIME_INFO[runtimeId];+ if (!info) return;+ if (existsSync(info.venvPython)) return;+ throw new ServerError(+ `${info.label} venv not found at ${info.venvPython}. Run \`${info.installEnvVar}=1 bash scripts/setup-image-video.sh\` to install.`,+ { status: 500, code: `${runtimeId.toUpperCase()}_VENV_MISSING` },+ );+}export const listVideoModels = () => getVideoModels();@@ -113,12 +201,7 @@ export const saveHistory = (h) => atomicWrite(HISTORY_FILE, h);// resolves) but the script file lives in the PortOS repo so updates ship// with PortOS releases instead of the user's HF cache.const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo }) => {- if (!existsSync(LTX2_VENV_PYTHON)) {- throw new ServerError(- `ltx-2-mlx venv not found at ${LTX2_VENV_PYTHON}. Run \`INSTALL_LTX2=1 bash scripts/setup-image-video.sh\` to install.`,- { status: 500, code: 'LTX2_VENV_MISSING' },- );- }+ assertByovRuntimeInstalled('ltx2');// Map PortOS UI modes to the helper's subcommand. Native extend on ltx2// routes to ExtendPipeline.extend_from_video — conditions on the entire// source video's latent (motion + visual content) rather than just the@@ -273,12 +356,7 @@ const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames// upstream's --task / --size / --ckpt_dir form so PortOS releases don't// fight upstream CLI changes.const buildWan22Args = ({ model, prompt, width, height, numFrames, steps, guidance, seed, sourceImagePath, mode, outputPath }) => {- if (!existsSync(WAN22_VENV_PYTHON)) {- throw new ServerError(- `wan2.2-mlx venv not found at ${WAN22_VENV_PYTHON}. Run \`INSTALL_WAN22=1 bash scripts/setup-image-video.sh\` to install.`,- { status: 500, code: 'WAN22_VENV_MISSING' },- );- }+ assertByovRuntimeInstalled('wan22');const args = [WAN22_HELPER_SCRIPT,'--repo-dir', WAN22_REPO_DIR,@@ -305,12 +383,24 @@ const buildWan22Args = ({ model, prompt, width, height, numFrames, steps, guidanreturn { bin: WAN22_VENV_PYTHON, args };};-// Build args for the HunyuanVideo MLX helper. Mirror of the Wan 2.2 path.-const buildHunyuanArgs = ({ model, prompt, width, height, numFrames, steps, guidance, seed, outputPath }) => {- if (!existsSync(HUNYUAN_VENV_PYTHON)) {+// Allowed precision tokens for runners that expose dtype as a CLI flag. The+// Python side already gates argparse with `choices=`, but a bogus value in+// data/media-models.json would otherwise reach the helper and surface as a+// less-friendly "invalid choice" inside a Python traceback — failing here+// gives a stable PortOS error code the route + client error path knows.+const VIDEO_PRECISIONS = Object.freeze(['fp16', 'bf16', 'fp32']);++// Build args for the HunyuanVideo MLX helper. Calls hyvideo.inference+// directly (see scripts/generate_hunyuan.py) so the steps / guidance /+// precision flags actually take effect — upstream's sample_video_mps.py+// silently hardcoded them.+const buildHunyuanArgs = ({ model, prompt, negativePrompt, width, height, numFrames, steps, guidance, seed, outputPath }) => {+ assertByovRuntimeInstalled('hunyuan');+ const precision = model.precision || 'fp16';+ if (!VIDEO_PRECISIONS.includes(precision)) {throw new ServerError(- `hunyuan-video-mlx venv not found at ${HUNYUAN_VENV_PYTHON}. Run \`INSTALL_HUNYUAN=1 bash scripts/setup-image-video.sh\` to install.`,- { status: 500, code: 'HUNYUAN_VENV_MISSING' },+ `Invalid precision "${precision}" on model "${model.id}" — expected one of ${VIDEO_PRECISIONS.join(', ')}`,+ { status: 500, code: 'VIDEO_MODEL_MISCONFIGURED' },);}const args = [@@ -324,8 +414,10 @@ const buildHunyuanArgs = ({ model, prompt, width, height, numFrames, steps, guid'--steps', String(steps),'--guidance', String(guidance ?? 6.0),'--seed', String(seed),+ '--precision', precision,'--output', outputPath,];+ if (negativePrompt) args.push('--negative-prompt', negativePrompt);return { bin: HUNYUAN_VENV_PYTHON, args };};@@ -340,7 +432,7 @@ const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width,return buildWan22Args({ model, prompt, width, height, numFrames, steps, guidance, seed, sourceImagePath, mode, outputPath });}if (model.runtime === 'hunyuan') {- return buildHunyuanArgs({ model, prompt, width, height, numFrames, steps, guidance, seed, outputPath });+ return buildHunyuanArgs({ model, prompt, negativePrompt, width, height, numFrames, steps, guidance, seed, outputPath });}if (Array.isArray(keyframes) && keyframes.length >= 2) {throw new ServerError(@@ -608,16 +700,22 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// a gated repo, but the merge is harmless when no token is configured.const childEnv = { ...process.env, ...(await hfTokenEnv()) };delete childEnv.PYTHONPATH;+ // Force unbuffered Python I/O so tqdm + loguru + our own STAGE: prints flush+ // immediately. Without this, child stdio is line-buffered against a pipe and+ // long inference loops emit nothing to handleLine() for minutes — the UI+ // looks dead even when the model is making progress.+ childEnv.PYTHONUNBUFFERED = '1';const proc = spawn(bin, args, { env: childEnv, stdio: ['ignore', 'pipe', 'pipe'] });activeProcess = proc;// Hold a sleep-prevention lock for the lifetime of the python child, so a- // 90s+ render doesn't get aborted by display/system sleep on a laptop. -w- // makes caffeinate self-exit when our pid does, so no manual cleanup is- // needed and a server crash mid-render still releases the assertion.- // macOS-only — `caffeinate` is a darwin binary; gating on `!IS_WIN` would- // also fire on Linux and emit a pointless ENOENT every render.+ // 90s+ render doesn't get aborted by sleep on a laptop. `-s` blocks system+ // sleep (lid-close / low-power), `-i` blocks idle sleep, `-d` blocks display+ // sleep — together they survive everything short of the user forcing sleep+ // from the Apple menu. `-w` makes caffeinate self-exit when our pid does, so+ // no manual cleanup is needed and a server crash mid-render still releases+ // the assertion. macOS-only — `caffeinate` is a darwin binary.if (process.platform === 'darwin' && proc.pid) {- spawn('caffeinate', ['-i', '-w', String(proc.pid)], { stdio: 'ignore', detached: false }).on('error', () => {});+ spawn('caffeinate', ['-dis', '-w', String(proc.pid)], { stdio: 'ignore', detached: false }).on('error', () => {});}// Without an 'error' handler, a missing/non-executable pythonPath would// crash the server with an unhandled error event.