Skip to content

Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.

fix(agent,panel): six code-review findings (P1+P2+P3)

mrbizarro9b005b629181
diff --git a/agent/image_engine.py b/agent/image_engine.py
index 447e721..81505c1 100644
--- a/agent/image_engine.py
+++ b/agent/image_engine.py
@@ -609,9 +609,18 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
# stdout and stderr to one stream so the line ordering matches what
# mflux actually printed; tail of the stream is kept for inclusion
# in any error message.
+ #
+ # Use select() with a poll interval so the deadline check fires even
+ # when the child goes silent (e.g. model-load hang, Metal driver
+ # deadlock, stuck weight download). Previous design used blocking
+ # `for raw in iter(readline, "")` which could block forever if mflux
+ # stopped flushing — the deadline check after each line never tripped
+ # and the queue worker hung indefinitely.
import collections
+ import select
last_lines: collections.deque[str] = collections.deque(maxlen=64)
stderr_tail = ""
+ timed_out = False
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
@@ -619,30 +628,79 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
env=env,
text=True,
bufsize=1,
+ # Own process group so the Popen.terminate/kill below escalates
+ # to the entire mflux+MLX subtree (mflux can spawn helper procs
+ # for download / Metal init that survive a parent kill).
+ start_new_session=True,
)
try:
deadline = time.time() + timeout_s
+ poll_interval = 0.5
if proc.stdout is not None:
- for raw in iter(proc.stdout.readline, ""):
- line = raw.rstrip("\n")
- if not line:
- if proc.poll() is not None:
- break
- continue
- last_lines.append(line)
- if on_log is not None:
+ while True:
+ # Wait up to poll_interval for a readable line; fall
+ # through to the deadline + exit-status check otherwise.
+ ready, _, _ = select.select(
+ [proc.stdout], [], [], poll_interval,
+ )
+ if ready:
try:
- on_log(line)
- except Exception: # noqa: BLE001
- # A buggy logger callback must not break the gen.
- pass
+ raw = proc.stdout.readline()
+ except (OSError, ValueError):
+ # Pipe closed — child likely exited; let the
+ # poll() / wait() branch below handle it.
+ raw = ""
+ if raw == "":
+ # EOF — readline returns "" only at end-of-stream
+ # for text-mode pipes. Drop into the post-loop
+ # cleanup (waits for rc).
+ break
+ line = raw.rstrip("\n")
+ if line:
+ last_lines.append(line)
+ if on_log is not None:
+ try:
+ on_log(line)
+ except Exception: # noqa: BLE001
+ # A buggy logger callback must not break the gen.
+ pass
+ # Deadline check — runs every iteration whether or not
+ # the child wrote a line, so a silent stall still trips.
if time.time() > deadline:
- proc.kill()
- raise RuntimeError(
- f"{bin_name} timed out after {timeout_s}s on a batch of "
- f"{n} seeds. First run downloads weights — qwen_edit Q8 "
- f"weights are ~34 GB; give it longer or pre-pull."
- )
+ timed_out = True
+ break
+ # Child exited but we haven't seen EOF yet — flush any
+ # remaining buffered output on the next select cycle.
+ # Don't break here: select+readline above will drain
+ # the pipe to "" and end the loop cleanly.
+ if proc.poll() is not None and not ready:
+ # No data in this slice + child gone → drain done.
+ break
+ if timed_out:
+ # SIGTERM the whole process group, give it 2s to clean up,
+ # then SIGKILL if still alive. The except subprocess.TimeoutExpired
+ # branch below would also fire but only after proc.wait() blocks
+ # for the remaining timeout window — we skip that by killing now.
+ try:
+ os.killpg(os.getpgid(proc.pid), 15) # SIGTERM
+ except (OSError, ProcessLookupError):
+ pass
+ try:
+ proc.wait(timeout=2)
+ except subprocess.TimeoutExpired:
+ try:
+ os.killpg(os.getpgid(proc.pid), 9) # SIGKILL
+ except (OSError, ProcessLookupError):
+ pass
+ try:
+ proc.wait(timeout=2)
+ except subprocess.TimeoutExpired:
+ pass
+ raise RuntimeError(
+ f"{bin_name} timed out after {timeout_s}s on a batch of "
+ f"{n} seeds. First run downloads weights — qwen_edit Q8 "
+ f"weights are ~34 GB; give it longer or pre-pull."
+ )
rc = proc.wait(timeout=max(1, deadline - time.time()))
except subprocess.TimeoutExpired as e:
try:
@@ -737,16 +795,20 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
# Try the templated path first (old mflux behavior + the n=1 case).
path = Path(output_template.format(seed=seed))
if not path.is_file():
- # Fall back to scanning the output dir for any file whose name
- # contains the seed and ends in .png. mflux's
- # auto-_seed_<seed> suffix lands here. Take the most recent
- # match in case the dir has stale files.
- seed_str = str(seed)
+ # Fall back to scanning the output dir for the EXACT filename
+ # mflux >=0.18 writes (template + auto-`_seed_<seed>` suffix).
+ # Substring matching by `seed_str in p.name` was wrong: seed
+ # 123 would also match `cand_9123_mflux.png` from a previous
+ # run in the same agent shot folder, returning the wrong PNG.
+ # Pin to the two known templates and mtime-sort defensively
+ # in case both happen to coexist. (Code-review P2-2.)
+ exact_patterns = (
+ f"cand_{seed}_mflux.png", # old mflux
+ f"cand_{seed}_mflux_seed_{seed}.png", # mflux >=0.18
+ )
candidates = sorted(
(p for p in output_dir.iterdir()
- if p.is_file()
- and p.suffix.lower() == ".png"
- and seed_str in p.name),
+ if p.is_file() and p.name in exact_patterns),
key=lambda p: p.stat().st_mtime,
reverse=True,
)
@@ -763,7 +825,13 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
"model": config.mflux_model,
"width": width, "height": height,
"refs": refs_used,
- "refs_ignored": (bool(refs) and fam not in ("qwen_edit", "flux2_edit")),
+ # refs_ignored derives from refs_used so kontext (which DOES
+ # consume refs[0]) no longer reports refs_ignored=True. Was
+ # checking `fam not in ("qwen_edit", "flux2_edit")`, which
+ # excluded kontext incorrectly — the panel's "this engine
+ # ignored your refs" warning lit up on every kontext sidecar.
+ # (Code-review P3, 2026-05-09.)
+ "refs_ignored": (bool(refs) and not refs_used),
"lora_paths": list(config.mflux_lora_paths or []),
})
diff --git a/agent/runtime.py b/agent/runtime.py
index 4390233..9b85a44 100644
--- a/agent/runtime.py
+++ b/agent/runtime.py
@@ -357,9 +357,11 @@ def run_turn(session: Session, user_message: str | None,
# Clear finished flag — a new user message resets the loop.
session.finished = False
- # Per-turn submit budget — see MAX_SUBMITS_PER_TURN. Local to this
- # run_turn() call: a fresh user message always gets a fresh budget.
- submits_used = 0
+ # Per-turn submit budget — see MAX_SUBMITS_PER_TURN. Cap enforcement
+ # itself lives in tools.dispatch() so both runtimes inherit it; we
+ # only need to clear the counter at the start of every run_turn()
+ # call so a fresh user message always gets a fresh budget.
+ tools.reset_submit_budget(session.tool_state)
# 2. Drive the loop.
for step_i in range(max_steps):
@@ -403,32 +405,11 @@ def run_turn(session: Session, user_message: str | None,
"tool": tool_name, "args": tool_args, "step": step_i,
}))
- # Enforce the per-turn submit budget BEFORE dispatch. We refuse the
- # call (and synthesize an error result for the agent) the moment
- # this call would push the running total past the cap. Partial
- # batches are not allowed: a submit_shots(shots=[a,b,c,d]) when 6
- # have already been queued is rejected wholesale rather than
- # silently truncated, since truncation would surprise the agent.
- submit_count = 0
- if tool_name == "submit_shot":
- submit_count = 1
- elif tool_name == "submit_shots":
- shots = tool_args.get("shots") if isinstance(tool_args, dict) else None
- submit_count = len(shots) if isinstance(shots, list) else 1
-
- if submit_count and submits_used + submit_count > MAX_SUBMITS_PER_TURN:
- result_obj = {
- "ok": False,
- "error": (
- f"submit cap reached: agent already queued "
- f"{submits_used} shots this turn (limit "
- f"{MAX_SUBMITS_PER_TURN}). Use multiple turns to "
- f"queue more, or call finish."
- ),
- }
- else:
- submits_used += submit_count
- result_obj = tools.dispatch(tool_name, tool_args, panel_ops, session.tool_state)
+ # Submit-budget enforcement now lives in tools.dispatch (so both
+ # runtimes inherit it). Just call dispatch — it returns the
+ # same {"ok": false, "error": "submit cap reached..."} shape the
+ # legacy code used to synthesize inline.
+ result_obj = tools.dispatch(tool_name, tool_args, panel_ops, session.tool_state)
yield emit(TurnEvent("tool_result", {
"tool": tool_name, "result": result_obj, "step": step_i,
}))
diff --git a/agent/runtime_smol.py b/agent/runtime_smol.py
index 30aa989..f4d20f2 100644
--- a/agent/runtime_smol.py
+++ b/agent/runtime_smol.py
@@ -443,6 +443,14 @@ def run_turn(session: Session, user_message: str | None,
session.messages.append({"role": "user", "content": user_message})
session.finished = False
+ # Reset the per-turn submit budget so the cap restarts fresh on every
+ # user message. Enforcement itself lives in `tools.dispatch` — this
+ # call just zeroes the counter the centralized check reads. Without
+ # this, a smol CodeAgent could call `submit_shots` past the 8-shot
+ # cap (security review H4 — was previously enforced only inside
+ # legacy runtime's loop, leaving _LegacyToolWrapper.forward exposed).
+ tools.reset_submit_budget(session.tool_state)
+
# 3. Build instructions = system prompt + condensed prior conversation.
# smolagents merges this into its own ReAct system prompt template;
# the agent sees both our LTX guidance AND smolagents' code-block
diff --git a/agent/tools.py b/agent/tools.py
index f444e71..4fd8e62 100644
--- a/agent/tools.py
+++ b/agent/tools.py
@@ -97,6 +97,16 @@ def dispatch(tool_name: str, args: dict, ops: PanelOps,
Result shape: `{"ok": bool, "result": Any, "error": str|None}`.
The caller wraps this in a <tool_result> message back to the model.
+
+ Per-turn submit budget enforcement lives HERE (not in either runtime)
+ so both the legacy ReAct loop AND the smolagents CodeAgent runtime
+ inherit the cap automatically. The counter is stored in
+ `session_state["_submits_used"]`; both runtimes call
+ `reset_submit_budget(session_state)` at the top of each `run_turn`
+ to start a fresh budget. (Security review H4 — was previously
+ enforced only in agent/runtime.py:run_turn, which left
+ runtime_smol.py exposed to the same DoS vector since its
+ `_LegacyToolWrapper.forward()` calls dispatch() directly.)
"""
handler = TOOL_HANDLERS.get(tool_name)
if handler is None:
@@ -108,8 +118,36 @@ def dispatch(tool_name: str, args: dict, ops: PanelOps,
f"Available: {sorted(TOOL_HANDLERS.keys())}"
),
}
+ # Pre-dispatch submit-budget check. We refuse the call wholesale (no
+ # partial truncation of submit_shots batches) the moment it would
+ # push the running total past MAX_SUBMITS_PER_TURN. Imported lazily
+ # to avoid an agent.tools ↔ agent.runtime import cycle.
+ submit_count = 0
+ if tool_name == "submit_shot":
+ submit_count = 1
+ elif tool_name == "submit_shots":
+ shots = args.get("shots") if isinstance(args, dict) else None
+ submit_count = len(shots) if isinstance(shots, list) else 1
+ if submit_count:
+ from agent.runtime import MAX_SUBMITS_PER_TURN
+ used = int(session_state.get("_submits_used") or 0)
+ if used + submit_count > MAX_SUBMITS_PER_TURN:
+ return {
+ "ok": False,
+ "result": None,
+ "error": (
+ f"submit cap reached: agent already queued "
+ f"{used} shots this turn (limit "
+ f"{MAX_SUBMITS_PER_TURN}). Use multiple turns to "
+ f"queue more, or call finish."
+ ),
+ }
try:
result = handler(args, ops, session_state)
+ if submit_count:
+ session_state["_submits_used"] = (
+ int(session_state.get("_submits_used") or 0) + submit_count
+ )
return {"ok": True, "result": result, "error": None}
except _ToolValidationError as e:
return {"ok": False, "result": None, "error": f"validation: {e}"}
@@ -117,6 +155,15 @@ def dispatch(tool_name: str, args: dict, ops: PanelOps,
return {"ok": False, "result": None, "error": f"{type(e).__name__}: {e}"}
+def reset_submit_budget(session_state: dict) -> None:
+ """Clear the per-turn submit counter at the top of a run_turn() call.
+
+ Both `agent.runtime.run_turn` and `agent.runtime_smol.run_turn` call
+ this once before driving the model loop so the cap restarts fresh.
+ """
+ session_state["_submits_used"] = 0
+
+
class _ToolValidationError(Exception):
pass
@@ -1507,11 +1554,22 @@ def _upload_image(args: dict, ops: PanelOps, session: dict) -> dict:
"""
p = _required(args, "attachment_id")
p = _resolve_path(p, ops.uploads_dir)
- pp = Path(p)
+ # Containment check — without this, a prompt-injected agent could
+ # probe arbitrary local paths (`/etc/passwd`, ~/.ssh/*, etc.) and
+ # exfil existence + size + filename via the tool result. Resolve
+ # first so symlink / `..` traversal that lands BACK inside
+ # uploads_dir is still accepted, then verify the resolved path
+ # lives under uploads_dir. (Code-review P2-1, 2026-05-09.)
+ try:
+ pp = _ensure_under(Path(p), [ops.uploads_dir])
+ except _ToolValidationError as e:
+ raise _ToolValidationError(
+ f"attachment_id must live under uploads_dir, got {p!r} ({e})"
+ ) from e
if not pp.is_file():
raise _ToolValidationError(f"attachment not found: {p}")
return {
- "absolute_path": p,
+ "absolute_path": str(pp),
"size_bytes": pp.stat().st_size,
"name": pp.name,
}
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index 69cfe51..57594b6 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -4286,8 +4286,14 @@ def _auto_promote_image_engine_kind(
Returns a new config copy with kind/family/model set to match the
chosen family, or None if no family is installed (caller keeps mock).
"""
+ # Auto-promote uses the same Qwen-Edit version the inline presets do
+ # (qwen_edit_inline + qwen_edit_lightning_inline + qwen_edit_high_inline
+ # all point at 2511 since commit f68bfb0). Pinning at 2509 here meant a
+ # fresh install or "Reset settings" wrote a config that pulled the
+ # OLDER 54 GB model with weaker character consistency. (Code-review
+ # P2-3, 2026-05-09.)
candidates = [
- ("qwen_edit", "Qwen/Qwen-Image-Edit-2509"),
+ ("qwen_edit", "Qwen/Qwen-Image-Edit-2511"),
("flux2", "Runpod/FLUX.2-klein-4B-mflux-4bit"),
("z_image_turbo", "filipstrand/Z-Image-Turbo-mflux-4bit"),
("flux1", "krea-dev"),
@@ -14700,8 +14706,10 @@ HTML = r"""<!doctype html>
<div class="field" id="agentMfluxModelField" style="display:none">
<label>mflux model</label>
<select id="agentMfluxModel" onchange="agentMfluxModelChanged()">
- <optgroup label="Qwen-Image-Edit-2509 (Apache 2.0 · multi-reference) — character + place composition">
- <option value="Qwen/Qwen-Image-Edit-2509">Qwen-Image-Edit-2509 — 1-3 ref images + prompt → composed still · ~22-34 GB lazy download (Q4 / Q8 picked via the quant slider below)</option>
+ <optgroup label="Qwen-Image-Edit-2511 (Apache 2.0 · multi-reference) — character + place composition">
+ <!-- 2511 supersedes 2509: stronger character consistency, mitigated multi-ref drift, built-in popular LoRAs. Same ~54 GB on disk; matches the inline presets used by Image Studio's engine dropdown. (Code-review P2-3.) -->
+ <option value="Qwen/Qwen-Image-Edit-2511">Qwen-Image-Edit-2511 — 1-3 ref images + prompt → composed still · ~22-34 GB lazy download (Q4 / Q8 picked via the quant slider below)</option>
+ <option value="Qwen/Qwen-Image-Edit-2509">Qwen-Image-Edit-2509 (legacy — prefer 2511)</option>
</optgroup>
<optgroup label="FLUX.2 (Apache 2.0 · 4-step) — fast text-to-image default">
<option value="Runpod/FLUX.2-klein-4B-mflux-4bit" selected>FLUX.2 [klein] 4B — 4-bit, 4 steps · ~4.3 GB · recommended for plain T2I anchors</option>
@@ -14743,7 +14751,12 @@ HTML = r"""<!doctype html>
<div class="field">
<label>Quantize (bits)</label>
<select id="agentMfluxQuantize">
- <option value="4">4-bit (~6 GB, recommended)</option>
+ <!-- Q6 is the Apple-Silicon community sweet spot (~4-6% quality
+ loss vs full precision; Q4 is 8-12%). Matches
+ ImageEngineConfig.mflux_quantize default + every inline
+ preset. (Code-review P2-3.) -->
+ <option value="4">4-bit (~6 GB, smallest)</option>
+ <option value="6" selected>6-bit (~9 GB, recommended)</option>
<option value="8">8-bit (~12 GB, sharper)</option>
</select>
</div>
@@ -21070,7 +21083,7 @@ function openAgentSettings() {
else stepsForDisplay = 25; // flux1-dev/krea, z-image base
}
document.getElementById('agentMfluxSteps').value = stepsForDisplay;
- document.getElementById('agentMfluxQuantize').value = String(imgCfg.mflux_quantize || 4);
+ document.getElementById('agentMfluxQuantize').value = String(imgCfg.mflux_quantize || 6);
// BFL
document.getElementById('agentBflModel').value = imgCfg.bfl_model || 'flux-dev';
document.getElementById('agentBflKey').value = '';
@@ -21395,9 +21408,14 @@ function agentMfluxModelChanged() {
const stepsInput = document.getElementById('agentMfluxSteps');
if (stepsInput && !stepsInput.dataset.userTouched) {
// Family-aware step picks (must stay in sync with image_engine.py
- // MFLUX_FAMILY_DEFAULTS — flagged at the source).
+ // MFLUX_FAMILY_DEFAULTS — flagged at the source). Qwen-Edit default
+ // is 8 (matches MFLUX_FAMILY_DEFAULTS["qwen_edit"]["steps"] and the
+ // `qwen_edit_inline` preset's standard tier — was 30, which is the
+ // final-quality count and slowed every fresh user's first run by
+ // ~4x). Bump to 30/40 manually when committing a final render.
+ // (Code-review P2-3.)
let steps = null;
- if (/qwen-image-edit|qwen_image_edit|qwen-edit/i.test(v)) steps = 30;
+ if (/qwen-image-edit|qwen_image_edit|qwen-edit/i.test(v)) steps = 8;
else if (/flux\.?2.*klein/i.test(v) || /flux2-klein/i.test(v)) steps = 4;
else if (/z-image-turbo|z_image_turbo/i.test(v)) steps = 9;
else if (/^schnell$/i.test(v)) steps = 4;
@@ -21520,7 +21538,7 @@ async function agentSaveSettings() {
imgPayload.mflux_base_model = '';
}
imgPayload.mflux_steps = parseInt(document.getElementById('agentMfluxSteps').value || '25', 10);
- imgPayload.mflux_quantize = parseInt(document.getElementById('agentMfluxQuantize').value || '4', 10);
+ imgPayload.mflux_quantize = parseInt(document.getElementById('agentMfluxQuantize').value || '6', 10);
try {
const ir = await fetch('/agent/image/config', {
method: 'POST',