Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Show live previews during local video renders (#4816)

[._.]/ Adam Eivyabd29f2cabe1
diff --git a/scripts/_runner_common.py b/scripts/_runner_common.py
index b2cb32e46a..ac6e402ad4 100644
--- a/scripts/_runner_common.py
+++ b/scripts/_runner_common.py
@@ -505,6 +505,34 @@ def write_sidecar(output: str, payload: dict) -> None:
sidecar.write_text(json.dumps(payload, indent=2))
+def write_stepwise_preview(stepwise_dir: str, frame) -> bool:
+ """Atomically publish one bounded preview frame for the active render.
+
+ The server watches a job-scoped directory and reads ``preview.png``. A
+ fixed filename keeps the directory bounded even when a runner emits a
+ progress callback for every denoise step; replacing it atomically also
+ prevents the watcher from reading a partially-written PNG.
+ """
+ if not stepwise_dir:
+ return False
+ from PIL import Image
+
+ out = Path(stepwise_dir)
+ out.mkdir(parents=True, exist_ok=True)
+ image = frame if isinstance(frame, Image.Image) else Image.fromarray(frame)
+ # Pillow < 9 exposes the resampling constants directly on Image rather
+ # than through Image.Resampling. The runner environments are user-managed,
+ # so keep the bounded preview contract compatible with both shapes.
+ resampling = getattr(Image, "Resampling", Image).LANCZOS
+ image.thumbnail((512, 512), resampling)
+ # Keep the staging file out of directory scans that look for visible PNGs;
+ # the explicit format argument still makes Pillow encode it as PNG.
+ temporary = out / f".preview-{os.getpid()}.tmp"
+ image.save(temporary, "PNG", optimize=False)
+ os.replace(temporary, out / "preview.png")
+ return True
+
+
def make_stepwise_callback(
stepwise_dir: str,
pipe,
@@ -536,7 +564,6 @@ def make_stepwise_callback(
if not stepwise_dir:
return None
import torch
- from PIL import Image
out = Path(stepwise_dir)
out.mkdir(parents=True, exist_ok=True)
vae = pipe.vae
@@ -599,10 +626,8 @@ def make_stepwise_callback(
decoded = vae.decode(scaled, return_dict=False)[0]
decoded = (decoded.clamp(-1, 1) + 1) / 2
arr = (decoded[0].float().cpu().permute(1, 2, 0).numpy() * 255).astype("uint8")
- img = Image.fromarray(arr)
- img.thumbnail((512, 512), Image.LANCZOS)
- img.save(out / f"step_{step_index + 1}.png", "PNG", optimize=False)
- fired["saved"] += 1
+ if write_stepwise_preview(str(out), arr):
+ fired["saved"] += 1
except Exception as err:
print(f"⚠️ stepwise preview failed at step {step_index}: {type(err).__name__}: {err}", file=sys.stderr)
return callback_kwargs
diff --git a/scripts/generate_ltx2.py b/scripts/generate_ltx2.py
index cdb62481f7..00d4afd18d 100644
--- a/scripts/generate_ltx2.py
+++ b/scripts/generate_ltx2.py
@@ -86,7 +86,7 @@ os.environ.setdefault("LTX2_GEMMA_EVAL_EVERY", "1")
# (mirrors generate_hunyuan.py). _runner_common is stdlib-only at import time, so
# this is safe from the ltx-2-mlx venv (no torch pulled in).
sys.path.insert(0, str(Path(__file__).resolve().parent))
-from _runner_common import emit_runtime_fingerprint, parse_user_loras # noqa: E402
+from _runner_common import emit_runtime_fingerprint, parse_user_loras, write_stepwise_preview # noqa: E402
def emit_status(msg: str) -> None:
@@ -437,6 +437,8 @@ def parse_args() -> argparse.Namespace:
p.add_argument("--prompt", required=True)
p.add_argument("--negative-prompt", default="")
p.add_argument("--output", required=True, help="Output .mp4 path")
+ p.add_argument("--preview-dir", default=None,
+ help="Job-scoped directory where the latest decoded denoise frame is published")
p.add_argument("--model", required=True, help="HF repo id or local path (e.g. dgrauet/ltx-2.3-mlx-q4)")
p.add_argument("--gemma", default=None,
help="Shared Gemma repo for LTX-2.3. Omit on LTX-2.5 packs that "
@@ -756,6 +758,153 @@ def bind_output_fps(pipe, fps: float) -> None:
pipe._decode_and_save_video = decode_with_fps
+def _ltx_preview_shapes(args: argparse.Namespace) -> list[tuple[int, int, int]]:
+ """Return the one-stage and two-stage latent shapes this pin may denoise.
+
+ The LTX sampler carries packed video rows rather than a 5-D latent. The
+ pipeline's own shape helper is the compatibility boundary for both the
+ pre-rename and v0.14.x pins, so the preview hook never hardcodes the
+ temporal or spatial compression factors.
+ """
+ try:
+ from ltx_core_mlx.components.patchifiers import compute_video_latent_shape
+ except ImportError:
+ return []
+
+ try:
+ from ltx_core_mlx.components.patchifiers import snap_output_dimensions
+ except ImportError:
+ # Older checked-out pins do not expose the convenience snapper. Their
+ # public latent-shape helper still accepts snapped dimensions, and the
+ # server's video dimensions are already multiples of 64 in practice.
+ snap_output_dimensions = lambda height, width, two_stage: (height, width)
+
+ one_h, one_w = snap_output_dimensions(args.height, args.width, two_stage=False)
+ full_h, full_w = snap_output_dimensions(args.height, args.width, two_stage=True)
+ dimensions = ((one_h, one_w), (full_h // 2, full_w // 2), (full_h, full_w))
+ shapes = []
+ seen = set()
+ for height, width in dimensions:
+ shape = compute_video_latent_shape(args.num_frames, height, width)
+ if shape not in seen:
+ seen.add(shape)
+ shapes.append(shape)
+ return shapes
+
+
+def _install_ltx_stepwise_preview(pipe, args: argparse.Namespace):
+ """Tap the installed LTX sampler after each video denoise step.
+
+ ``ltx-pipelines-mlx`` has no stable public callback on the versions PortOS
+ supports. Its sampler does, however, call the module-local ``euler_step``
+ once for video and once for audio. Wrapping that narrow primitive keeps the
+ bridge source-pinned and lets us project the packed video rows back through
+ the pipeline's own patchifier and decoder. Preview failures are deliberately
+ non-fatal: the final render remains the source of truth.
+ """
+ preview_dir = getattr(args, "preview_dir", None)
+ if not preview_dir:
+ return lambda: None
+ try:
+ import numpy as np
+ import mlx.core as mx
+ from ltx_pipelines_mlx.utils import samplers
+ except ImportError as exc:
+ print(f"⚠️ stepwise LTX preview unavailable: {type(exc).__name__}: {exc}", file=sys.stderr, flush=True)
+ return lambda: None
+
+ shapes = _ltx_preview_shapes(args)
+ if not shapes:
+ return lambda: None
+ original_euler_step = samplers.euler_step
+ state = {"expect_video": True, "saved": 0}
+
+ def shape_for_tokens(token_count: int):
+ exact = [(shape[0] * shape[1] * shape[2], shape) for shape in shapes
+ if shape[0] * shape[1] * shape[2] == token_count]
+ if exact:
+ return exact[0][1]
+ # Keyframe conditioning appends rows to the generated video rows. Pick
+ # the smallest compatible base shape so the appended rows are not
+ # mistaken for a larger two-stage canvas.
+ compatible = [(token_count - base, shape) for base, shape in
+ ((shape[0] * shape[1] * shape[2], shape) for shape in shapes)
+ if token_count > base and token_count - base <= base * 4]
+ return min(compatible, key=lambda item: item[0])[1] if compatible else None
+
+ def publish(result, shape) -> None:
+ stage = "start"
+ try:
+ frames, latent_height, latent_width = shape
+ token_count = frames * latent_height * latent_width
+ stage = "eval-sampler-result"
+ mx.eval(result)
+ tokens = result[:, :token_count, :]
+ stage = "unpatchify"
+ latent = pipe.video_patchifier.unpatchify(tokens, shape)
+ # Decode one temporal latent slice. It is enough to show the
+ # forming composition and avoids decoding the entire clip while
+ # the DiT is still resident for the next step.
+ frame_index = max(0, frames // 2)
+ latent = latent[:, :, frame_index:frame_index + 1, :, :]
+ stage = "load-decoder"
+ decoder_block = getattr(pipe, "video_decoder_block", None)
+ if decoder_block is not None and hasattr(decoder_block, "load"):
+ decoder = decoder_block.load()
+ else:
+ decoder = getattr(pipe, "vae_decoder", decoder_block)
+ if decoder is None:
+ raise RuntimeError("pipeline exposes no video decoder")
+ stage = "decode"
+ decoded = decoder.decode(latent)
+ # Some MLX decoder implementations return bfloat16-backed arrays;
+ # normalize before crossing into NumPy, whose buffer bridge does
+ # not support that dtype consistently on Apple Silicon.
+ decoded = decoded.astype(mx.float32)
+ stage = "eval-decoded"
+ mx.eval(decoded)
+ # MLX exposes a buffer view whose PEP 3118 item size is not
+ # consistent for some decoded uint8 tensors. Force a detached
+ # NumPy copy at this boundary instead of asking numpy.asarray to
+ # consume that view in place.
+ stage = "numpy-copy"
+ array = np.array(decoded)
+ frame = array[0, :, array.shape[2] // 2, :, :].transpose(1, 2, 0)
+ frame = np.clip((frame + 1.0) * 127.5, 0, 255).astype("uint8")
+ stage = "publish-png"
+ if write_stepwise_preview(preview_dir, frame):
+ state["saved"] += 1
+ except Exception as exc: # best-effort instrumentation around a live runner
+ print(f"⚠️ LTX stepwise preview failed at {stage}: {type(exc).__name__}: {exc}", file=sys.stderr, flush=True)
+
+ def euler_step(sample, denoised, sigma, sigma_next):
+ result = original_euler_step(sample, denoised, sigma, sigma_next)
+ is_video_turn = state["expect_video"]
+ state["expect_video"] = not state["expect_video"]
+ if not is_video_turn:
+ return result
+ shape = shape_for_tokens(int(sample.shape[1]))
+ if shape is not None:
+ publish(result, shape)
+ return result
+
+ samplers.euler_step = euler_step
+
+ def restore():
+ if samplers.euler_step is euler_step:
+ samplers.euler_step = original_euler_step
+
+ return restore
+
+
+def _run_with_ltx_stepwise_preview(pipe, args: argparse.Namespace, render):
+ restore = _install_ltx_stepwise_preview(pipe, args)
+ try:
+ return render()
+ finally:
+ restore()
+
+
def _apply_legacy_image_strength(image_strength: float) -> bool:
"""Inject I2V strength on pre-rename pins; return True if the hook applied.
@@ -900,7 +1049,7 @@ def run_two_stage(args: argparse.Namespace, image: str | None = None) -> str:
bind_output_fps(pipe, args.fps)
emit_stage(1, 1, 1, "Loaded")
emit_status("Generating with CFG…")
- return pipe.generate_and_save(
+ return _run_with_ltx_stepwise_preview(pipe, args, lambda: pipe.generate_and_save(
prompt=args.prompt,
output_path=args.output,
height=args.height,
@@ -912,7 +1061,7 @@ def run_two_stage(args: argparse.Namespace, image: str | None = None) -> str:
cfg_scale=args.cfg_scale if args.cfg_scale is not None else 3.0,
**_image_conditioning_kwargs(pipe.generate_and_save, image, args.image_strength),
**_rate_kwargs(pipe.generate_and_save, args.fps),
- )
+ ))
def run_text(args: argparse.Namespace) -> str:
@@ -926,10 +1075,10 @@ def run_text(args: argparse.Namespace) -> str:
bind_output_fps(pipe, args.fps)
emit_stage(1, 1, 1, "Loaded")
emit_status("Generating T2V…")
- return pipe.generate_and_save(
+ return _run_with_ltx_stepwise_preview(pipe, args, lambda: pipe.generate_and_save(
**_one_stage_kwargs(args),
**_rate_kwargs(pipe.generate_and_save, args.fps),
- )
+ ))
def run_image(args: argparse.Namespace) -> str:
@@ -951,10 +1100,10 @@ def run_image(args: argparse.Namespace) -> str:
image_kwargs = _image_conditioning_kwargs(
pipe.generate_and_save, args.image, args.image_strength
)
- return pipe.generate_and_save(
+ return _run_with_ltx_stepwise_preview(pipe, args, lambda: pipe.generate_and_save(
**_one_stage_kwargs(args, **image_kwargs),
**_rate_kwargs(pipe.generate_and_save, args.fps),
- )
+ ))
def _resolve_keyframes(args: argparse.Namespace) -> tuple[list[str], list[int]]:
@@ -1036,7 +1185,7 @@ def run_fflf(args: argparse.Namespace) -> str:
_apply_user_loras(pipe, args.user_lora_specs)
emit_stage(1, 1, 1, "Loaded")
emit_status(f"Interpolating between {len(keyframe_images)} keyframes at indices {keyframe_indices}…")
- return pipe.generate_and_save(
+ return _run_with_ltx_stepwise_preview(pipe, args, lambda: pipe.generate_and_save(
prompt=args.prompt,
output_path=args.output,
keyframe_images=keyframe_images,
@@ -1049,7 +1198,7 @@ def run_fflf(args: argparse.Namespace) -> str:
stage2_steps=args.stage2_steps,
cfg_scale=args.cfg_scale if args.cfg_scale is not None else 3.0,
**_rate_kwargs(pipe.generate_and_save, args.fps),
- )
+ ))
def run_extend(args: argparse.Namespace) -> str:
@@ -1080,7 +1229,7 @@ def run_extend(args: argparse.Namespace) -> str:
if _EXTEND_TC_CONFIG["enable"]:
emit_status(f"TeaCache active on extend (thresh={_teacache_thresh_label(args.teacache_thresh)})")
try:
- video_latent, audio_latent = pipe.extend_from_video(
+ video_latent, audio_latent = _run_with_ltx_stepwise_preview(pipe, args, lambda: pipe.extend_from_video(
prompt=args.prompt,
video_path=args.extend_from_video,
extend_frames=args.extend_frames,
@@ -1088,7 +1237,7 @@ def run_extend(args: argparse.Namespace) -> str:
seed=args.seed,
num_steps=num_steps,
cfg_scale=args.cfg_scale if args.cfg_scale is not None else 3.0,
- )
+ ))
finally:
_EXTEND_TC_CONFIG = None
# Mirror cli._decode_and_save: drop the DiT + text encoder before the VAE
@@ -1136,7 +1285,7 @@ def run_a2v(args: argparse.Namespace) -> str:
emit_status(f"TeaCache active on A2V Stage 1 (thresh={_teacache_thresh_label(args.teacache_thresh)})")
restore_image_rate = _patch_a2v_image_conditioning_rate(args.fps)
try:
- return pipe.generate_and_save(
+ return _run_with_ltx_stepwise_preview(pipe, args, lambda: pipe.generate_and_save(
prompt=args.prompt,
output_path=args.output,
audio_path=args.audio,
@@ -1150,7 +1299,7 @@ def run_a2v(args: argparse.Namespace) -> str:
cfg_scale=args.cfg_scale if args.cfg_scale is not None else 3.0,
audio_start_time=args.audio_start,
**_rate_kwargs(pipe.generate_and_save, args.fps),
- )
+ ))
finally:
restore_image_rate()
_A2V_TC_CONFIG = None
@@ -1251,7 +1400,7 @@ def run_ic_lora(args: argparse.Namespace) -> str:
)
if args.ic_attention_strength is not None:
kwargs["conditioning_attention_strength"] = args.ic_attention_strength
- return pipe.generate_and_save(**kwargs)
+ return _run_with_ltx_stepwise_preview(pipe, args, lambda: pipe.generate_and_save(**kwargs))
def maybe_strip_audio(output_path: str) -> None:
diff --git a/scripts/generate_ltx2.test.js b/scripts/generate_ltx2.test.js
index 715868c34f..e9f926423c 100644
--- a/scripts/generate_ltx2.test.js
+++ b/scripts/generate_ltx2.test.js
@@ -468,4 +468,13 @@ describe.skipIf(!pyBin)('generate_ltx2.py', () => {
].join('\n')}`);
expect(output.trim()).toBe(expected);
});
+
+ it('parses the optional bounded preview directory', () => {
+ const output = runPython(`${importRunner}\n${[
+ 'import sys',
+ 'sys.argv = ["generate_ltx2.py", "--mode", "text", "--prompt", "p", "--output", "/tmp/o.mp4", "--model", "m", "--preview-dir", "/tmp/previews"]',
+ 'print(runner.parse_args().preview_dir)',
+ ].join('\n')}`);
+ expect(output.trim()).toBe('/tmp/previews');
+ });
});
diff --git a/scripts/generate_minimax_h3.py b/scripts/generate_minimax_h3.py
index 1881a4c8f3..36a655532c 100644
--- a/scripts/generate_minimax_h3.py
+++ b/scripts/generate_minimax_h3.py
@@ -27,6 +27,7 @@ from types import SimpleNamespace
sys.path.insert(0, str(Path(__file__).resolve().parent))
from _runner_common import ( # noqa: E402
emit_runtime_fingerprint, establish_process_group, heartbeat, register_source_namespace,
+ write_stepwise_preview,
)
from _minimax_h3_common import ( # noqa: E402
FPS, add_h3_common_args, emit_result, load_keyframes, resolve_cached_snapshot,
@@ -52,6 +53,8 @@ def parse_args() -> argparse.Namespace:
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("--preview-dir", default=None,
+ help="Job-scoped directory where the latest decoded denoise frame is published")
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=[],
@@ -425,11 +428,89 @@ def verify_runtime_checkout(runtime_dir: Path, expected_revision: str) -> None:
raise RuntimeError("MiniMax H3 runtime source differs from the pinned checkout; use Repair in Video Gen.")
+class _H3StepwisePreview:
+ """Decode one selected H3 video frame when ProgressWriter sees a step."""
+
+ def __init__(self, pipe, stepwise_dir: str, num_frames: int, height: int, width: int) -> None:
+ from minimax_h3_mlx.packing import align_num_frames, video_latent_num_frames
+
+ self.pipe = pipe
+ self.stepwise_dir = stepwise_dir
+ self.num_frames = align_num_frames(num_frames)
+ self.num_latent_frames = video_latent_num_frames(self.num_frames)
+ ratio = pipe.video_vae.config.spatial_compression_ratio
+ self.latent_height = height // ratio
+ self.latent_width = width // ratio
+ patch_t, patch_h, patch_w = tuple(pipe.dit.config.patch_size)
+ self.target_rows = (
+ (self.num_latent_frames // patch_t)
+ * (self.latent_height // patch_h)
+ * (self.latent_width // patch_w)
+ )
+ self._latest_rows = None
+ self.saved = 0
+
+ def capture(self, rows) -> None:
+ # The pinned pipeline passes generated video rows as the first DiT
+ # argument. They are the state immediately before the current forward;
+ # ProgressWriter publishes them after that forward's step line, which
+ # keeps the hook independent of private scheduler locals.
+ self._latest_rows = rows[0] if len(rows.shape) == 3 else rows
+
+ def publish(self, step: int, total: int) -> None:
+ if self._latest_rows is None:
+ return
+ try:
+ rows = self._latest_rows[-self.target_rows:]
+ frames = self.pipe._decode_video(
+ rows,
+ self.num_latent_frames,
+ self.latent_height,
+ self.latent_width,
+ )
+ frame = frames[len(frames) // 2]
+ if write_stepwise_preview(self.stepwise_dir, frame):
+ self.saved += 1
+ except Exception as exc: # best-effort instrumentation around a live runner
+ print(
+ f"⚠️ MiniMax H3 stepwise preview failed at {step}/{total}: "
+ f"{type(exc).__name__}: {exc}",
+ file=sys.stderr,
+ flush=True,
+ )
+
+
+class _PreviewingDiT:
+ """Delegate the pinned DiT while exposing its latest video input rows."""
+
+ def __init__(self, inner, preview: _H3StepwisePreview) -> None:
+ self._inner = inner
+ self._preview = preview
+
+ def __getattr__(self, name):
+ return getattr(self._inner, name)
+
+ def __call__(self, *args, **kwargs):
+ rows = args[0] if args else kwargs.get("video_latents")
+ if rows is not None:
+ self._preview.capture(rows)
+ return self._inner(*args, **kwargs)
+
+
+def _install_h3_stepwise_preview(pipe, args: argparse.Namespace):
+ if not args.preview_dir:
+ return None
+ preview = _H3StepwisePreview(pipe, args.preview_dir, args.num_frames, args.height, args.width)
+ pipe.dit = _PreviewingDiT(pipe.dit, preview)
+ return preview
+
+
class ProgressWriter:
"""Translate the port's human step lines into PortOS STAGE progress."""
- def __init__(self) -> None:
+ def __init__(self, preview: _H3StepwisePreview | None = None) -> None:
self._carry = ""
+ self._preview = preview
def write(self, text: str) -> int:
self._carry += text
@@ -443,8 +524,7 @@ class ProgressWriter:
self._emit(self._carry)
self._carry = ""
- @staticmethod
- def _emit(line: str) -> None:
+ def _emit(self, line: str) -> None:
clean = line.strip()
if not clean:
return
@@ -456,6 +536,8 @@ class ProgressWriter:
file=sys.stderr,
flush=True,
)
+ if self._preview is not None:
+ self._preview.publish(int(step), int(total))
return
print(clean, file=sys.stderr, flush=True)
@@ -591,7 +673,8 @@ def main() -> int:
)
print("STAGE:inference", file=sys.stderr, flush=True)
- progress = ProgressWriter()
+ preview = _install_h3_stepwise_preview(pipe, args)
+ progress = ProgressWriter(preview)
with heartbeat("minimax-h3-inference"), redirect_stdout(progress):
result = pipe(
args.prompt,
diff --git a/scripts/generate_minimax_h3.test.js b/scripts/generate_minimax_h3.test.js
index 9cf6f1b654..679706574c 100644
--- a/scripts/generate_minimax_h3.test.js
+++ b/scripts/generate_minimax_h3.test.js
@@ -128,6 +128,66 @@ describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {
expect(output.trim()).toBe('9');
});
+ it('parses the optional bounded preview directory', () => {
+ const output = runPython(`${importRunner}\n${[
+ 'import sys',
+ 'sys.argv = ["generate_minimax_h3.py", "--model-repo", "example/model", "--model-revision", "revision",',
+ ' "--runtime-dir", "/tmp/runtime", "--runtime-revision", "revision",',
+ ' "--checkpoint-repo", "example/checkpoint", "--checkpoint-revision", "revision",',
+ ' "--prompt", "a test prompt", "--width", "1344", "--height", "768", "--num-frames", "124",',
+ ' "--output", "test.mp4", "--preview-dir", "/tmp/previews"]',
+ 'print(runner.parse_args().preview_dir)',
+ ].join('\n')}`);
+ expect(output.trim()).toBe('/tmp/previews');
+ });
+
+ it('projects the DiT batch rows to the generated video rows before decoding', () => {
+ const output = runPython(`${importRunner}\n${[
+ 'import json, sys, types',
+ 'packing = types.ModuleType("minimax_h3_mlx.packing")',
+ 'packing.align_num_frames = lambda value: value',
+ 'packing.video_latent_num_frames = lambda value: 2',
+ 'sys.modules["minimax_h3_mlx"] = types.ModuleType("minimax_h3_mlx")',
+ 'sys.modules["minimax_h3_mlx.packing"] = packing',
+ 'class Config:',
+ ' spatial_compression_ratio = 2',
+ 'class DitConfig:',
+ ' patch_size = (1, 2, 2)',
+ 'class VideoVae:',
+ ' config = Config()',
+ 'class Dit:',
+ ' config = DitConfig()',
+ 'class Rows:',
+ ' def __init__(self, shape): self.shape = shape',
+ ' def __getitem__(self, key):',
+ ' if key == 0: return Rows((10, 4))',
+ ' if isinstance(key, slice): return Rows((8, 4))',
+ ' raise AssertionError(f"unexpected row key: {key!r}")',
+ 'class Frame:',
+ ' shape = (4, 4, 3)',
+ 'class Frames:',
+ ' def __len__(self): return 2',
+ ' def __getitem__(self, key): return Frame()',
+ 'class Pipe:',
+ ' video_vae = VideoVae()',
+ ' dit = Dit()',
+ ' def _decode_video(self, rows, *shape):',
+ ' print(json.dumps({"rows": list(rows.shape), "shape": list(shape)}))',
+ ' return Frames()',
+ 'seen = []',
+ 'runner.write_stepwise_preview = lambda directory, frame: seen.append((directory, list(frame.shape))) or True',
+ 'preview = runner._H3StepwisePreview(Pipe(), "/tmp/previews", 17, 8, 8)',
+ 'rows = Rows((1, 10, 4))',
+ 'proxy = runner._PreviewingDiT(lambda *args: "ok", preview)',
+ 'proxy(rows)',
+ 'preview.publish(1, 2)',
+ 'print(json.dumps({"seen": seen, "saved": preview.saved}))',
+ ].join('\n')}`);
+ const lines = output.trim().split('\n').map((line) => JSON.parse(line));
+ expect(lines[0]).toMatchObject({ rows: [8, 4], shape: [2, 4, 4] });
+ expect(lines[1]).toEqual({ seen: [['/tmp/previews', [4, 4, 3]]], saved: 1 });
+ });
+
// 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
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index a134bd215d..28d2ce05a5 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -11,8 +11,8 @@
*/
import { execFile, spawn } from '../../lib/childProcess.js';
-import { existsSync, statSync } from 'fs';
-import { unlink, writeFile, copyFile, rm } from 'fs/promises';
+import { existsSync, statSync, watch as fsWatch } from 'fs';
+import { unlink, writeFile, copyFile, rm, readFile, mkdtemp } from 'fs/promises';
import { join, basename } from 'path';
import { tmpdir, totalmem } from 'os';
import { randomUUID } from 'crypto';
@@ -492,7 +492,7 @@ export const ltx25TextEncoderArgs = (textEncoder) => {
return args;
};
-const buildLtx2Args = ({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, disableAudio, outputPath, textEncoderRepo, textEncoder, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {
+const buildLtx2Args = ({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, disableAudio, outputPath, previewDir, textEncoderRepo, textEncoder, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {
assertByovRuntimeInstalled(model.runtime);
// Map PortOS UI modes to the helper's subcommand. Native extend on ltx2
// routes to ExtendPipeline.extend_from_video — conditions on the entire
@@ -602,6 +602,7 @@ const buildLtx2Args = ({ model, ltxModelPath, prompt, negativePrompt, width, hei
'--steps', String(steps),
'--cfg-scale', String(guidance),
];
+ if (previewDir) args.push('--preview-dir', previewDir);
// LTX-2.5 packs ship Gemma 4 under text_encoder/. Passing the shared 2.3
// Gemma 3 encoder would either fail load or silently condition on the wrong
// model. The 2.3 runtime still needs the explicit shared encoder.
@@ -754,7 +755,7 @@ const assertMiniMaxH3Preflight = ({
// 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 }) => {
+const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath, previewDir, loras, textEncoder }) => {
assertMiniMaxH3Preflight({
runtimeId: 'minimax_h3',
repoLabel: 'transformer repo or revision',
@@ -787,6 +788,7 @@ const buildMiniMaxH3Args = ({ model, prompt, negativePrompt, width, height, numF
'--seed', String(seed),
'--output', outputPath,
];
+ if (previewDir) args.push('--preview-dir', previewDir);
for (const file of files) args.push('--checkpoint-file', file);
// Anchor order is packed order: the helper stretches the FIRST keyframe onto
// the canvas as the geometry anchor, so a first-frame image must lead.
@@ -922,12 +924,12 @@ const buildHunyuanArgs = ({ model, prompt, negativePrompt, width, height, numFra
return { bin: HUNYUAN_VENV_PYTHON, args };
};
-const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeights, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, textEncoderRepo, textEncoder, outputPath, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {
+const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeights, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, textEncoderRepo, textEncoder, outputPath, previewDir, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 }) => {
// Route to the dgrauet/ltx-2-mlx helper when the model declares the new
// runtime. Existing notapalindrome models default to runtime: 'mlx_video'
// (or undefined in legacy registries — see backfillRuntime in mediaModels.js).
if (isLtx2FamilyRuntime(model.runtime)) {
- return buildLtx2Args({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, disableAudio, outputPath, textEncoderRepo, textEncoder, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 });
+ return buildLtx2Args({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, disableAudio, outputPath, previewDir, textEncoderRepo, textEncoder, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2 });
}
// IC-LoRA remix modes are an LTX-2 primitive (ICLoraPipeline) — no other
// runtime has an equivalent. The route guards this too, but a non-route
@@ -967,7 +969,7 @@ const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeight
return buildWan22Args({ model, wanModelPath, wanRequiredWeights, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, mode, outputPath });
}
if (model.runtime === 'minimax_h3') {
- return buildMiniMaxH3Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath, loras, textEncoder });
+ return buildMiniMaxH3Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath, previewDir, loras, textEncoder });
}
if (model.runtime === 'minimax_h3_cuda') {
return buildMiniMaxH3CudaArgs({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, icReferencePaths, mode, tiling, disableAudio, outputPath });
@@ -1585,6 +1587,10 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
...(addedTriggerWords.length ? { renderPrompt, addedTriggerWords } : {}),
...(hidden ? { hidden: true } : {}),
};
+ // Each render gets one private preview directory. Runners overwrite the
+ // fixed `preview.png` path atomically, so a long render cannot accumulate
+ // one PNG per step and a stale preview can never cross job boundaries.
+ const stepwiseDir = await mkdtemp(join(tmpdir(), 'portos-video-stepwise-'));
const job = { ...meta, clients: [], status: 'running' };
jobs.set(jobId, job);
@@ -1596,7 +1602,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// logic of the spawn-error handler so failure modes converge.
let bin, args;
try {
- ({ bin, args } = buildArgs({ pythonPath, modelId, model: loraCapableModel, wanModelPath, wanRequiredWeights, ltxModelPath, prompt: renderPrompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, stage2Steps: actualStage2Steps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, keyframes: resolvedKeyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, textEncoder: resolvedTextEncoder, outputPath, loras: resolvedLoras, icReferencePaths: resolvedIcReferencePaths, icLoraWeightPath, icStrength: actualIcStrength, icAttentionStrength: actualIcAttentionStrength, icSkipStage2 }));
+ ({ bin, args } = buildArgs({ pythonPath, modelId, model: loraCapableModel, wanModelPath, wanRequiredWeights, ltxModelPath, prompt: renderPrompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, stage2Steps: actualStage2Steps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, keyframes: resolvedKeyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, textEncoder: resolvedTextEncoder, outputPath, previewDir: stepwiseDir, loras: resolvedLoras, icReferencePaths: resolvedIcReferencePaths, icLoraWeightPath, icStrength: actualIcStrength, icAttentionStrength: actualIcAttentionStrength, icSkipStage2 }));
} catch (err) {
job.status = 'error';
const reason = err.message || 'Failed to build video gen args';
@@ -1604,6 +1610,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
broadcastSse(job, { type: 'error', error: reason });
videoGenEvents.emit('failed', { generationId: jobId, error: reason });
void cleanupTempFiles({ includeUploads: true, includeUntrackedAudio: true });
+ void rm(stepwiseDir, { recursive: true, force: true });
closeJobAfterDelay(jobs, jobId);
throw err;
}
@@ -1612,6 +1619,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
if (!heavyClaim.ok) {
jobs.delete(jobId);
await cleanupTempFiles({ includeUploads: true });
+ await rm(stepwiseDir, { recursive: true, force: true });
throw new ServerError(heavyClaim.message, { status: 409, code: 'HEAVY_LOCAL_JOB_BUSY', context: { holder: heavyClaim.holder } });
}
const releaseHeavyClaim = () => heavyClaim.release()
@@ -1630,6 +1638,53 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// plus a lowered Gemma budget, instead of rebuilding it from scratch.
let childEnv;
+ // Runners publish one atomically-replaced `preview.png`. Keep the reader
+ // serialized because fs.watch can report several events for one replacement;
+ // a pending flag collapses those events to the newest available frame.
+ let previewWatcher = null;
+ let previewReading = false;
+ let previewPending = false;
+ let previewClosed = false;
+ const cleanupStepwisePreview = () => {
+ if (previewClosed) return;
+ previewClosed = true;
+ if (previewWatcher) {
+ try { previewWatcher.close(); } catch { /* already closed */ }
+ previewWatcher = null;
+ }
+ void rm(stepwiseDir, { recursive: true, force: true });
+ };
+ const processLatestPreview = async () => {
+ if (previewClosed) return;
+ if (previewReading) {
+ previewPending = true;
+ return;
+ }
+ previewReading = true;
+ try {
+ const framePath = join(stepwiseDir, 'preview.png');
+ const currentImage = (await readFile(framePath)).toString('base64');
+ if (jobs.get(jobId) === job && job.status === 'running') {
+ job.currentImage = currentImage;
+ videoGenEvents.emit('progress', { generationId: jobId, currentImage });
+ }
+ } catch (err) {
+ // A replacement can race a read, and cancel/close removes the directory;
+ // both are ordinary teardown races rather than render failures.
+ if (!previewClosed) console.log(`⚠️ Video preview read skipped [${jobId.slice(0, 8)}]: ${err.message}`);
+ }
+ previewReading = false;
+ if (previewPending) {
+ previewPending = false;
+ void processLatestPreview();
+ }
+ };
+ try {
+ previewWatcher = fsWatch(stepwiseDir, (event) => {
+ if (event === 'rename' || event === 'change') void processLatestPreview();
+ });
+ } catch { /* preview is best-effort; the final video remains authoritative */ }
+
// ── one render child, fully wired ──────────────────────────────────────────
// Everything per-CHILD lives in here — the process handle, both watchdogs, the
// line readers, the close handler — so the same job can be relaunched once
@@ -1768,6 +1823,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// Defensive cleanup includes audio passed directly without the route's
// uploadedTempPaths tracking. Duplicate unlinks remain harmless.
void cleanupTempFiles({ includeUploads: true, includeUntrackedAudio: true });
+ cleanupStepwisePreview();
closeJobAfterDelay(jobs, jobId);
};
@@ -1867,6 +1923,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// before emitting the terminal completion event: an extend chain starts its
// next child from that event and must be able to acquire the machine claim.
await releaseHeavyClaim();
+ cleanupStepwisePreview();
// Wrap the whole teardown so a throw from finalizeGeneratedVideo (history
// save, thumbnail, file move) can't leak as an unhandled rejection — on
// Node ≥15 that kills the process AND strands the media job `running` with
@@ -2115,6 +2172,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
broadcastSse(job, { type: 'error', error: reason });
videoGenEvents.emit('failed', { generationId: jobId, error: reason });
void cleanupTempFiles({ includeUploads: true, includeUntrackedAudio: true });
+ cleanupStepwisePreview();
closeJobAfterDelay(jobs, jobId);
};
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index 633c2d538e..c92360cfbd 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -260,6 +260,7 @@ vi.mock('fs', () => ({
if (i >= 0) { fsState.missOnce.splice(i, 1); return undefined; }
return { size: 1000 };
}),
+ watch: vi.fn(() => ({ close: vi.fn() })),
}));
// Anchor scoring. The scorer itself is unit-tested in lib/frameQuality.test.js;
@@ -309,6 +310,8 @@ vi.mock('fs/promises', () => ({
writeFile: vi.fn(async () => {}),
copyFile: vi.fn(async () => {}),
rm: vi.fn(async () => {}),
+ readFile: vi.fn(async () => Buffer.from('')),
+ mkdtemp: vi.fn(async (prefix) => `${prefix}mock`),
// Unused by the code under test, but lib/ffmpeg.js imports it and the ffmpeg
// mock above pulls the real module in for buildTrimConcatArgs.
rename: vi.fn(async () => {}),
@@ -1412,6 +1415,7 @@ describe('generateVideo — PORTOS_T2V_TWO_STAGE arg threading', () => {
it('threads --stage2-steps 3 + fast steps/cfg when the knob is on', async () => {
process.env.PORTOS_T2V_TWO_STAGE = '1';
const args = await renderArgsFor('t2v-twostage-on');
+ expect(args[args.indexOf('--preview-dir') + 1]).toContain('portos-video-stepwise-');
expect(args[args.indexOf('--stage2-steps') + 1]).toBe('3');
expect(args[args.indexOf('--steps') + 1]).toBe('8');
expect(args[args.indexOf('--cfg-scale') + 1]).toBe('1');
@@ -2890,6 +2894,7 @@ describe('generateVideo — MiniMax H3 MLX contract', () => {
expect(args[args.indexOf('--height') + 1]).toBe('672');
expect(args[args.indexOf('--num-frames') + 1]).toBe('107');
expect(args[args.indexOf('--steps') + 1]).toBe('8');
+ expect(args[args.indexOf('--preview-dir') + 1]).toContain('portos-video-stepwise-');
expect(args.flatMap((arg, i) => arg === '--checkpoint-file' ? [args[i + 1]] : []))
.toEqual(['LICENSE', 'FL2VA/vae/video/config.json']);
expect(options.killProcessGroup).toBe(true);
@@ -2904,6 +2909,61 @@ describe('generateVideo — MiniMax H3 MLX contract', () => {
expect(hfChildEnv).not.toHaveBeenCalled();
});
+ it('forwards the newest preview as currentImage and ignores events after teardown', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const { watch } = await import('fs');
+ const { readFile } = await import('fs/promises');
+ const listeners = {};
+ const proc = {
+ pid: 6789,
+ exitCode: null,
+ signalCode: null,
+ killed: false,
+ stdout: { on: vi.fn() },
+ stderr: { on: vi.fn() },
+ on(event, fn) { listeners[event] = fn; return proc; },
+ off(event, fn) { if (listeners[event] === fn) delete listeners[event]; return proc; },
+ kill: vi.fn(),
+ };
+ vi.mocked(spawnDetached).mockImplementationOnce(async () => proc);
+ const progress = [];
+ const onProgress = (event) => {
+ if (event.generationId === 'preview-current-image') progress.push(event);
+ };
+ videoGenEvents.on('progress', onProgress);
+
+ try {
+ await generateVideo({
+ jobId: 'preview-current-image',
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'a quiet street at dusk',
+ width: 512,
+ height: 512,
+ numFrames: 25,
+ fps: 24,
+ });
+ const watchCall = vi.mocked(watch).mock.calls.at(-1);
+ expect(watchCall[0]).toContain('portos-video-stepwise-');
+ vi.mocked(readFile).mockResolvedValueOnce(Buffer.from('frame-one'));
+ watchCall[1]('rename', 'preview.png');
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(progress).toContainEqual({
+ generationId: 'preview-current-image',
+ currentImage: Buffer.from('frame-one').toString('base64'),
+ });
+
+ listeners.close?.(1, null);
+ await new Promise((resolve) => setImmediate(resolve));
+ vi.mocked(readFile).mockResolvedValueOnce(Buffer.from('stale-frame'));
+ watchCall[1]('rename', 'preview.png');
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(progress).toHaveLength(1);
+ } finally {
+ videoGenEvents.off('progress', onProgress);
+ }
+ });
+
// Substituted prompt conditioner (#4081). The whole override path has to stay
// dormant unless it was asked for — an unswapped render's argv must be
// byte-identical to what it was before the feature existed.