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(video-gen): let the server own FastH3's two derived-artifact roots
[._.]/ Adam Eivyb77af0e1c398
diff --git a/scripts/generate_fastvideo.py b/scripts/generate_fastvideo.pyindex eb12b37d63..4dc7dba3af 100755--- a/scripts/generate_fastvideo.py+++ b/scripts/generate_fastvideo.py@@ -139,8 +139,10 @@ def parse_args() -> argparse.Namespace:p.add_argument("--mlx-checkpoint", default=None, help="MLX checkpoint path (defaults to model-root)")p.add_argument("--mlx-format", choices=MLX_DIT_FORMATS, default=None,help="convert this snapshot's transformer/ to an MLX DiT of this format on first use")+ p.add_argument("--mlx-checkpoint-cache-dir", default=None,+ help="root for converted MLX DiTs (default: a shared dir under ~/.portos/fastvideo)")p.add_argument("--prompt-cache-dir", default=None,- help="reusable FastH3 prompt-embedding cache (default: a shared dir under the repo)")+ help="reusable FastH3 prompt-embedding cache (default: a shared dir under ~/.portos/fastvideo)")p.add_argument("--prompt", required=True)p.add_argument("--negative-prompt", default="")p.add_argument("--width", type=int, required=True)@@ -198,11 +200,16 @@ def find_entry_script(repo_dir: Path, family: str = "fastmetal") -> Path:# running FastVideo's own converter once, so a row can point at the upstream# checkpoint instead of depending on a third party having published a repack.MLX_DIT_FORMATS = ("int8", "int6", "int4")+# PortOS declares both of these roots in server/services/videoGen/runtimes.js and+# passes them as flags. These defaults exist only so the script runs standalone,+# the same role --repo-dir's fallback plays.+MLX_CHECKPOINT_CACHE = Path.home() / ".portos" / "fastvideo" / "mlx-checkpoints"+PROMPT_CACHE = Path.home() / ".portos" / "fastvideo" / "prompt-cache"_CONVERTER_SCRIPT = ("scripts", "checkpoint_conversion", "convert_minimax_h3_mlx.py")_MLX_CHECKPOINT_FILES = ("mlx_h3_dit.safetensors", "mlx_h3_dit.json")-def mlx_checkpoint_root(model_root: Path) -> Path:+def mlx_checkpoint_root(model_root: Path, base: Path | None = None) -> Path:"""Where DiTs converted from `model_root` are cached.Keyed by the SNAPSHOT, not by the repo id -- an HF cache path ends in the@@ -218,16 +225,17 @@ def mlx_checkpoint_root(model_root: Path) -> Path:# snapshots resolving to ONE converted DiT would render the wrong weights# without any error to notice.digest = hashlib.sha256(str(model_root).encode("utf-8")).hexdigest()[:12]- return Path.home() / ".portos" / "fastvideo" / "mlx-checkpoints" / f"{label}-{digest}"+ return (base or MLX_CHECKPOINT_CACHE) / f"{label}-{digest}"def is_converted(checkpoint_dir: Path) -> bool:return all((checkpoint_dir / name).is_file() for name in _MLX_CHECKPOINT_FILES)-def ensure_mlx_checkpoint(repo_dir: Path, model_root: Path, fmt: str, env: dict) -> Path:+def ensure_mlx_checkpoint(repo_dir: Path, model_root: Path, fmt: str, env: dict,+ base: Path | None = None) -> Path:"""Return the converted MLX DiT for `fmt`, converting it if it is missing."""- out_base = mlx_checkpoint_root(model_root)+ out_base = mlx_checkpoint_root(model_root, base)out_dir = out_base / fmtif is_converted(out_dir):return out_dir@@ -242,20 +250,13 @@ def ensure_mlx_checkpoint(repo_dir: Path, model_root: Path, fmt: str, env: dict)print(f"STATUS:converting the FastH3 DiT to MLX {fmt} — one time, into {out_dir}",file=sys.stderr, flush=True)out_base.mkdir(parents=True, exist_ok=True)- proc = subprocess.Popen(+ code = run_child([sys.executable, str(converter),"--model-root", str(transformer),"--out", str(out_base),"--formats", fmt],- stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,- env=env, cwd=str(repo_dir),+ env, repo_dir, lambda line: f"STATUS:{line}",)- assert proc.stdout is not None- for raw in proc.stdout:- line = raw.rstrip()- if line:- print(f"STATUS:{line}", file=sys.stderr, flush=True)- code = proc.wait()if code != 0:raise RuntimeError(f"FastH3 MLX conversion exited with code {code}")if not is_converted(out_dir):@@ -276,9 +277,26 @@ def resolve_prompt_cache_dir(args) -> Path:version, the model root AND the prompt, so one shared directory cannot servea stale entry across models or across a conditioner change."""- if args.prompt_cache_dir:- return Path(args.prompt_cache_dir)- return Path.home() / ".portos" / "fastvideo" / "prompt-cache"+ return Path(args.prompt_cache_dir) if args.prompt_cache_dir else PROMPT_CACHE+++def run_child(cmd: list, env: dict, cwd: Path, transform) -> int:+ """Spawn a child, stream its merged output through `transform`, return its code.++ Shared by the conversion child and the inference child so their stream+ handling cannot drift: both fold stderr into stdout and re-emit line by+ line on THIS process's stderr, which is the channel PortOS parses.+ """+ proc = subprocess.Popen(+ cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,+ env=env, cwd=str(cwd),+ )+ assert proc.stdout is not None+ for raw in proc.stdout:+ line = raw.rstrip()+ if line:+ print(transform(line), file=sys.stderr, flush=True)+ return proc.wait()def build_child_env(repo_dir: Path) -> dict:@@ -387,7 +405,9 @@ def main() -> int:mlx_checkpoint = Path(args.mlx_checkpoint).resolve()elif args.mlx_format:try:- mlx_checkpoint = ensure_mlx_checkpoint(repo_dir, model_root, args.mlx_format, env)+ mlx_checkpoint = ensure_mlx_checkpoint(+ repo_dir, model_root, args.mlx_format, env,+ Path(args.mlx_checkpoint_cache_dir) if args.mlx_checkpoint_cache_dir else None)except (FileNotFoundError, RuntimeError) as err:print(f"❌ {err}", file=sys.stderr)return 1@@ -395,8 +415,11 @@ def main() -> int:mlx_checkpoint = model_rootcmd = build_command(args, entry_script, model_root, mlx_checkpoint)- if args.family == "fasth3":- resolve_prompt_cache_dir(args).mkdir(parents=True, exist_ok=True)+ # The child writes into this directory but will not create it. Keyed off the+ # argv rather than a second family test, so it cannot disagree with the one+ # branch in build_command that decides the flag is passed at all.+ if "--prompt-cache-dir" in cmd:+ Path(cmd[cmd.index("--prompt-cache-dir") + 1]).mkdir(parents=True, exist_ok=True)print(f"🎬 fastvideo {args.family} generate {args.width}x{args.height} frames={args.num_frames} steps={args.steps} seed={args.seed}", file=sys.stderr, flush=True)diff --git a/scripts/generate_fastvideo_test.py b/scripts/generate_fastvideo_test.pyindex b3e09bcbdf..4a0fb8d566 100644--- a/scripts/generate_fastvideo_test.py+++ b/scripts/generate_fastvideo_test.py@@ -10,7 +10,6 @@ from __future__ import annotationsimport importlib.utilimport io-import shutilimport sysimport tempfileimport unittest@@ -50,6 +49,7 @@ def make_args(**overrides):enhance_prompt=False,refine=False,prompt_cache_dir="/fixture/prompt-cache",+ mlx_checkpoint_cache_dir=None,)for key, value in overrides.items():setattr(args, key, value)@@ -227,24 +227,22 @@ class MlxCheckpointTest(unittest.TestCase):# The steady state after the user deletes the 66 GB bf16 transformer:# rendering must keep working off the converted DiT alone.with tempfile.TemporaryDirectory() as tmp:+ base = Path(tmp) / "mlx-checkpoints"model_root = Path(tmp) / "models--Org--Repo" / "snapshots" / "abc123"model_root.mkdir(parents=True)- out = self.helper.mlx_checkpoint_root(model_root) / "int6"+ out = self.helper.mlx_checkpoint_root(model_root, base) / "int6"out.mkdir(parents=True)for name in ("mlx_h3_dit.safetensors", "mlx_h3_dit.json"):(out / name).write_text("")- try:- resolved = self.helper.ensure_mlx_checkpoint(Path(tmp), model_root, "int6", {})- self.assertEqual(resolved, out)- finally:- shutil.rmtree(self.helper.mlx_checkpoint_root(model_root), ignore_errors=True)+ resolved = self.helper.ensure_mlx_checkpoint(Path(tmp), model_root, "int6", {}, base)+ self.assertEqual(resolved, out)def test_a_snapshot_without_a_transformer_fails_loudly(self):with tempfile.TemporaryDirectory() as tmp:model_root = Path(tmp) / "models--Org--Repo" / "snapshots" / "def456"model_root.mkdir(parents=True)with self.assertRaises(FileNotFoundError) as ctx:- self.helper.ensure_mlx_checkpoint(Path(tmp), model_root, "int4", {})+ self.helper.ensure_mlx_checkpoint(Path(tmp), model_root, "int4", {}, Path(tmp) / "cache")self.assertIn("transformer", str(ctx.exception))diff --git a/server/services/videoGen/renderArgs.js b/server/services/videoGen/renderArgs.jsindex fef5217aae..afca704569 100644--- a/server/services/videoGen/renderArgs.js+++ b/server/services/videoGen/renderArgs.js@@ -50,6 +50,8 @@ import {FASTVIDEO_VENV_PYTHON,FASTVIDEO_HELPER_SCRIPT,FASTVIDEO_REPO_DIR,+ FASTVIDEO_MLX_CHECKPOINT_DIR,+ FASTVIDEO_PROMPT_CACHE_DIR,LTX25_CUDA_VENV_PYTHON,LTX25_CUDA_HELPER_SCRIPT,WAN22_CUDA_VENV_PYTHON,@@ -574,6 +576,10 @@ export const fastvideoFamily = (model) =>// directory instead. A row that names one of these formats is pointing at that// upstream snapshot and wants the helper to run FastVideo's own converter once;// a row that omits it already ships the quantized DiT beside its model root.+// Mirrors MLX_DIT_FORMATS in scripts/generate_fastvideo.py, itself the+// converter's own format list. Kept in sync by hand — the helper's argparse+// `choices=` is the enforcement; this list is what lets the server reject a+// bad value before queueing a render.export const FASTVIDEO_MLX_FORMATS = Object.freeze(['int8', 'int6', 'int4']);export const fastvideoMlxFormat = (model) =>(FASTVIDEO_MLX_FORMATS.includes(model?.fastvideoMlxFormat) ? model.fastvideoMlxFormat : null);@@ -610,8 +616,11 @@ export const buildFastVideoArgs = ({// vae/audio_vae/text_encoder/tokenizer IS its own checkpoint, and says so// explicitly rather than leaning on the helper's default-to-model-root.if (family === 'fasth3') {+ // Conditioning is half the wall clock of a render and recomputes identical+ // embeddings every time, so every FastH3 row reuses one cache.+ args.push('--prompt-cache-dir', FASTVIDEO_PROMPT_CACHE_DIR);const mlxFormat = fastvideoMlxFormat(model);- if (mlxFormat) args.push('--mlx-format', mlxFormat);+ if (mlxFormat) args.push('--mlx-format', mlxFormat, '--mlx-checkpoint-cache-dir', FASTVIDEO_MLX_CHECKPOINT_DIR);else args.push('--mlx-checkpoint', modelRoot);}if (negativePrompt) args.push('--negative-prompt', negativePrompt);diff --git a/server/services/videoGen/renderArgsFastVideo.test.js b/server/services/videoGen/renderArgsFastVideo.test.jsindex 03afa2a2f0..860b520c21 100644--- a/server/services/videoGen/renderArgsFastVideo.test.js+++ b/server/services/videoGen/renderArgsFastVideo.test.js@@ -9,6 +9,8 @@ vi.mock('./runtimes.js', async (importOriginal) => ({FASTVIDEO_VENV_PYTHON: '/fixture/fastvideo/.venv/bin/python3',FASTVIDEO_HELPER_SCRIPT: '/fixture/scripts/generate_fastvideo.py',FASTVIDEO_REPO_DIR: '/fixture/fastvideo',+ FASTVIDEO_MLX_CHECKPOINT_DIR: '/fixture/fastvideo/mlx-checkpoints',+ FASTVIDEO_PROMPT_CACHE_DIR: '/fixture/fastvideo/prompt-cache',}));const { buildFastVideoArgs, fastvideoFamily, fastvideoMlxFormat } = await import('./renderArgs.js');@@ -98,6 +100,9 @@ describe('buildFastVideoArgs', () => {expect(flagValue(args, '--family')).toBe('fasth3');expect(flagValue(args, '--model-root')).toBe('/fixture/cache/fasth3');expect(flagValue(args, '--mlx-checkpoint')).toBe('/fixture/cache/fasth3');+ // It already holds a quantized DiT, so it must never trigger a conversion.+ expect(args).not.toContain('--mlx-format');+ expect(args).not.toContain('--mlx-checkpoint-cache-dir');});it('passes the pinned render controls through for FastH3', () => {@@ -151,19 +156,24 @@ describe('buildFastVideoArgs — upstream FastH3 snapshot', () => {...base, model: fasth3Source, fastvideoModelPath: '/fixture/models/fasth3-source',});expect(flagValue(args, '--mlx-format')).toBe('int6');- // The converted DiT lands in a helper-owned cache, NOT beside the snapshot,- // so pinning --mlx-checkpoint here would point the pipeline at the bf16- // diffusers layout it cannot load.+ // The converted DiT lands under a SERVER-declared cache root, not beside the+ // snapshot, so pinning --mlx-checkpoint here would point the pipeline at the+ // bf16 diffusers layout it cannot load.expect(args).not.toContain('--mlx-checkpoint');+ expect(flagValue(args, '--mlx-checkpoint-cache-dir')).toBe('/fixture/fastvideo/mlx-checkpoints');expect(flagValue(args, '--model-root')).toBe('/fixture/models/fasth3-source');});- it('still pins the checkpoint for a pre-converted row, and never asks to convert', () => {- const { args } = buildFastVideoArgs({- ...base, model: fasth3, fastvideoModelPath: '/fixture/models/fasth3-packed',- });- expect(flagValue(args, '--mlx-checkpoint')).toBe('/fixture/models/fasth3-packed');- expect(args).not.toContain('--mlx-format');+ it('reuses one server-declared prompt cache for every FastH3 row', () => {+ // Conditioning is half a render's wall clock and recomputes identical+ // embeddings, so both layouts must get the flag — and FastMetal must not,+ // since mlx_wan_prompt_to_video.py would reject it.+ for (const model of [fasth3, fasth3Source]) {+ const { args } = buildFastVideoArgs({ ...base, model, fastvideoModelPath: '/fixture/cache/fasth3' });+ expect(flagValue(args, '--prompt-cache-dir')).toBe('/fixture/fastvideo/prompt-cache');+ }+ const { args } = buildFastVideoArgs({ ...base, model: fastmetal, fastvideoModelPath: '/fixture/cache/fastmetal' });+ expect(args).not.toContain('--prompt-cache-dir');});it('never asks FastMetal to convert, even if a row mislabels a format', () => {diff --git a/server/services/videoGen/runtimes.js b/server/services/videoGen/runtimes.jsindex 824f933bc6..5b3fa556bc 100644--- a/server/services/videoGen/runtimes.js+++ b/server/services/videoGen/runtimes.js@@ -112,6 +112,14 @@ export const MINIMAX_H3_CUDA_OFFLOAD_PROFILES = Object.freeze([export const FASTVIDEO_VENV_PYTHON = join(homedir(), '.portos', 'fastvideo', '.venv', 'bin', 'python3');export const FASTVIDEO_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'generate_fastvideo.py');export const FASTVIDEO_REPO_DIR = join(homedir(), '.portos', 'fastvideo');+// FastH3's two derived-artifact roots, declared here for the same reason the+// H3 shim and prompt-embedding roots above are: the server owns WHERE they+// live so it can name, report and reclaim them, and the helper owns only the+// layout underneath. Both are plain caches the user can delete at any time —+// but the converted DiT is multi-GB per (snapshot, format), so leaving PortOS+// with no name for it is what makes it unreclaimable.+export const FASTVIDEO_MLX_CHECKPOINT_DIR = join(homedir(), '.portos', 'fastvideo', 'mlx-checkpoints');+export const FASTVIDEO_PROMPT_CACHE_DIR = join(homedir(), '.portos', 'fastvideo', 'prompt-cache');// LTX-2.5 on CUDA — the official Lightricks ltx-core / ltx-pipelines runtime.export const LTX25_CUDA_REPO_DIR = join(homedir(), '.portos', 'ltx-2.5-cuda');