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): browser-driven UX audit — orphan engines, status lies, layout bugs

mrbizarro351f60625be5
diff --git a/agent/image_engine.py b/agent/image_engine.py
index f37dadc..e6699ec 100644
--- a/agent/image_engine.py
+++ b/agent/image_engine.py
@@ -487,9 +487,10 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
# for a confusing argparse failure.
if fam == "qwen_edit" and not refs:
raise ValueError(
- "qwen_edit requires at least 1 reference image. Either "
- "switch the engine to 'qwen' (text-to-image, same model "
- "family) or pass refs=[<path>] to compose against."
+ "Qwen-Image-Edit-2509 needs at least 1 reference image — drop "
+ "a photo into one of the 3 reference slots above, or switch "
+ "the Engine dropdown to FLUX.2 [klein] / Z-Image-Turbo for "
+ "text-only generation."
)
# Effective steps + guidance: prefer user-set values if non-zero,
diff --git a/agent/local_server.py b/agent/local_server.py
index 0376c04..d00d873 100644
--- a/agent/local_server.py
+++ b/agent/local_server.py
@@ -34,13 +34,59 @@ _MODEL_PATH: str = ""
_LAST_ERROR: str = ""
+_LAST_REACHABLE_AT: float = 0.0
+
+
+def _port_reachable(port: int, timeout: float = 0.25) -> bool:
+ """Cheap TCP-connect probe to see if the engine is actually serving.
+
+ `_PROC.poll() is None` returns True for a few hundred ms after a
+ failed bind (the process is alive long enough for the bind error
+ to crash it). Without this probe the panel would tell the user the
+ engine is "live" while requests time out. Cached for 750 ms so the
+ polling status endpoint stays cheap.
+ """
+ import socket
+ try:
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.settimeout(timeout)
+ try:
+ sock.connect(("127.0.0.1", port))
+ finally:
+ sock.close()
+ return True
+ except OSError:
+ return False
+
+
def status() -> dict:
- """Snapshot for the UI: is the local engine running, and on what?"""
- global _PROC
+ """Snapshot for the UI: is the local engine running, and on what?
+
+ Two booleans because they can disagree:
+ - `running` — `_PROC` is alive (process-level, cheap)
+ - `reachable` — port is bound and accepts TCP connect
+ During the bind-collision window after panel restart, the new
+ engine is `running=True` but `reachable=False` for the second or
+ two until it crashes; the UI should treat the engine as healthy
+ only when BOTH are true.
+ """
+ global _PROC, _LAST_REACHABLE_AT
with _LOCK:
running = _PROC is not None and _PROC.poll() is None
+ reachable = False
+ if running:
+ now = time.time()
+ # Cache the probe for 750 ms so status() polls cheaply.
+ if now - _LAST_REACHABLE_AT > 0.75:
+ reachable = _port_reachable(_PORT)
+ if reachable:
+ _LAST_REACHABLE_AT = now
+ else:
+ # Recent successful probe — assume still good.
+ reachable = True
return {
"running": running,
+ "reachable": reachable,
"port": _PORT,
"model_path": _MODEL_PATH,
"pid": _PROC.pid if running else None,
@@ -74,6 +120,21 @@ def start(model_path: str, *, venv_python: str, log_sink=None) -> dict:
return _status_locked()
_stop_locked(reason="model change")
+ # Reap orphaned `mlx_lm.server` processes left behind by prior
+ # panel sessions. mlx_lm.server is spawned with `start_new_session=True`
+ # so when the panel exits without a clean shutdown, the engine
+ # survives — and on next panel boot it still holds port 8200.
+ # The new spawn would then fail with `[Errno 48] Address already
+ # in use` and exit immediately, but `_PROC.poll()` returned None
+ # for a few hundred ms before it died, so the panel's status pill
+ # showed "live" while the engine was actually broken.
+ # Symptom Salo hit: "live" pill + "Local unreachable" banner side
+ # by side; agent submits return "engine error: Remote end closed
+ # connection without response". Fix: scan for any python running
+ # `mlx_lm.server` against our port BEFORE we try to spawn, and
+ # SIGTERM them (escalating to SIGKILL on holdouts).
+ _reap_orphan_servers(port=_PORT, log_sink=log_sink)
+
if not Path(venv_python).exists():
_LAST_ERROR = f"venv python not found: {venv_python}"
return _status_locked()
@@ -149,6 +210,72 @@ def start(model_path: str, *, venv_python: str, log_sink=None) -> dict:
return status()
+def _reap_orphan_servers(*, port: int, log_sink=None) -> None:
+ """SIGTERM any `mlx_lm.server` python processes pointing at our port.
+
+ Survives panel restarts because mlx_lm.server is spawned with
+ `start_new_session=True` (so the engine doesn't die when the panel
+ process tree dies). Without this reap, a fresh panel boot collides
+ with the surviving engine from the previous session. Best-effort
+ only — failures are logged but don't abort the start path.
+ """
+ import shutil
+
+ if not shutil.which("ps"):
+ return # macOS edge case; ps should always be there
+ try:
+ out = subprocess.run(
+ ["ps", "-ax", "-o", "pid=,command="],
+ capture_output=True, text=True, timeout=5,
+ )
+ except (subprocess.SubprocessError, OSError):
+ return
+ if out.returncode != 0:
+ return
+
+ port_marker = f"--port {port}"
+ needle = "mlx_lm.server"
+ self_pid = os.getpid()
+ targets: list[int] = []
+ for raw in out.stdout.splitlines():
+ if needle not in raw or port_marker not in raw:
+ continue
+ # Lines look like "12345 /path/to/python -m mlx_lm.server --port 8200 ..."
+ try:
+ pid_str = raw.strip().split(None, 1)[0]
+ pid = int(pid_str)
+ except (ValueError, IndexError):
+ continue
+ if pid == self_pid:
+ continue
+ targets.append(pid)
+
+ if not targets:
+ return
+
+ msg = f"local_server: reaping {len(targets)} orphan engine(s) on port {port}: {targets}"
+ if log_sink is not None:
+ try: log_sink(msg)
+ except Exception: pass # noqa: BLE001
+ # First SIGTERM all of them, give the kernel a beat to release the
+ # port, then SIGKILL anything that didn't exit. Without the wait,
+ # the next bind would still race with port shutdown.
+ for pid in targets:
+ try:
+ os.kill(pid, signal.SIGTERM)
+ except OSError:
+ pass
+ time.sleep(1.5)
+ for pid in targets:
+ try:
+ os.kill(pid, 0) # probe — raises if already dead
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+ # Final settle so the kernel surrenders the port before our spawn.
+ time.sleep(0.5)
+
+
def stop(reason: str = "manual stop") -> dict:
with _LOCK:
_stop_locked(reason)
@@ -178,9 +305,14 @@ def _stop_locked(reason: str) -> None:
def _status_locked() -> dict:
+ # Note: this internal helper deliberately does NOT call _port_reachable —
+ # callers from inside _LOCK don't need the probe (they're either
+ # mid-spawn or mid-stop, neither of which has a stable port state).
+ # The public status() is the only path that pays the probe cost.
running = _PROC is not None and _PROC.poll() is None
return {
"running": running,
+ "reachable": False, # internal helper — caller is mid-flux
"port": _PORT,
"model_path": _MODEL_PATH,
"pid": _PROC.pid if running else None,
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index 6b2ab90..30c499b 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -12661,7 +12661,7 @@ HTML = r"""<!doctype html>
<div style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px">
<div class="field">
<label>Engine</label>
- <select id="imgStudioEngine">
+ <select id="imgStudioEngine" onchange="imgStudioUpdateValidity()">
<option value="auto" selected>Auto (use Settings)</option>
<option value="qwen_edit_inline">Qwen-Image-Edit-2509 (multi-ref · 8-step Q4, ~1 min/image)</option>
<option value="qwen_edit_lightning_inline">Qwen-Image-Edit-2509 + Lightning (multi-ref · 4-step Q4, ~10-15 s/image)</option>
@@ -13492,6 +13492,39 @@ const IMG_STUDIO = {
busy: false,
};
+// Engine families that REQUIRE at least one reference image (mflux's
+// qwen-edit CLI marks --image-paths as required; calling it without
+// refs returns an argparse error after model load). The Studio engine
+// override values map 1:1 to these check predicates. Used by
+// imgStudioUpdateValidity() to gate the Generate button.
+function imgStudioRequiresRefs(engineOverride) {
+ return engineOverride === 'qwen_edit_inline'
+ || engineOverride === 'qwen_edit_lightning_inline'
+ || engineOverride === 'qwen_edit_high_inline';
+}
+
+function imgStudioUpdateValidity() {
+ const btn = document.getElementById('imgStudioGenBtn');
+ const eng = document.getElementById('imgStudioEngine');
+ const status = document.getElementById('imgStudioStatus');
+ if (!btn || !eng) return;
+ const refsCount = IMG_STUDIO.refs.filter(r => r && r.path).length;
+ const needsRefs = imgStudioRequiresRefs(eng.value);
+ let invalidReason = '';
+ if (needsRefs && refsCount === 0) {
+ invalidReason = 'Pick at least 1 reference image (drop a file into one of the 3 slots above) — Qwen-Image-Edit composes against an image, it cannot run text-only. Use the Lightning preset only after picking a ref.';
+ }
+ // Don't override the busy state — imgStudioGenerate manages disabled
+ // during in-flight gens.
+ if (!IMG_STUDIO.busy) {
+ btn.disabled = !!invalidReason;
+ btn.title = invalidReason || 'Generate (Cmd/Ctrl+Enter)';
+ if (status && !status.textContent.startsWith('Generating')) {
+ status.textContent = invalidReason ? '⚠ ' + invalidReason : '';
+ }
+ }
+}
+
// Reveal the mock-engine option only when the URL has ?debug=1.
// Mock paints flat colored rectangles — useful for testing the UX
// without spending GPU time, but a casual user picks it and gets
@@ -13513,6 +13546,10 @@ const IMG_STUDIO = {
// mode hides it. The pill row drives both flows.
function openImageStudio() {
setMode('image');
+ // Re-evaluate Generate button state (engine + ref count) every time the
+ // user enters Studio so they don't see a stale "ready" button when the
+ // engine selection makes refs mandatory.
+ imgStudioUpdateValidity();
setTimeout(() => {
const t = document.getElementById('imgStudioPrompt');
if (t) {
@@ -13572,6 +13609,7 @@ function imgStudioRenderSlot(idx) {
slot.classList.remove('has-image');
slot.innerHTML = `<div class="placeholder">Drop or click<br>ref ${idx + 1}</div>`;
}
+ imgStudioUpdateValidity();
}
function imgStudioClearRef(idx) {
@@ -16739,9 +16777,17 @@ function workflowSwitch(name) {
.forEach(b => b.classList.toggle('active', b.dataset.workflow === name));
const manual = document.getElementById('genForm');
const agent = document.getElementById('agentPane');
+ const studio = document.getElementById('studioSection');
// Set body data attribute so CSS can switch the layout (wider form-pane,
// show agent-stage-pane on the right).
document.body.setAttribute('data-workflow', name);
+ // Studio is an inline pane inside form-pane — when leaving Manual it
+ // must hide too, otherwise the user lands on Agentic Flows with the
+ // Studio form overlapping the chat. Also reset currentMode to t2v so
+ // a future Manual click returns to a sane default. Bug fix from the
+ // browser-driven audit: switching tabs while Studio was active left
+ // the chat inaccessible.
+ if (studio) studio.classList.remove('show');
if (name === 'agent') {
if (manual) manual.style.display = 'none';
if (agent) agent.hidden = false;
@@ -16876,16 +16922,64 @@ function agentEngineBannerShow(j, opts) {
detail = j.message || 'Will auto-start on first message.';
actionLabel = 'Start engine';
actionEl && (actionEl.onclick = function() {
- // Reuse the existing one-click engine-start path.
- fetch('/agent/local/start', {method: 'POST'})
- .then(() => agentRefreshConfig())
- .then(() => setTimeout(() => agentCheckEngine({forceShow: true}), 1500));
+ // Reuse the existing one-click engine-start path. After the
+ // POST returns we poll agentRefreshConfig + agentCheckEngine
+ // every 2 s for up to 45 s — Gemma 12B 4-bit binds the port
+ // ~10-15 s after spawn, longer if weights need to come off
+ // disk. Without the poll, the pill stays "starting…" forever
+ // because nothing triggers a refresh once port is bound.
+ fetch('/agent/local/start', {method: 'POST'}).then(() => {
+ let tries = 0;
+ const maxTries = 22; // ~45 s budget
+ const tick = () => {
+ agentRefreshConfig().then(() => {
+ const local = (window.AGENT.config || {}).local_server || {};
+ const reachable = (typeof local.reachable === 'boolean')
+ ? local.reachable : !!local.running;
+ if (reachable || tries >= maxTries) {
+ agentCheckEngine({forceShow: true});
+ return;
+ }
+ tries += 1;
+ setTimeout(tick, 2000);
+ }).catch(() => {
+ tries += 1;
+ if (tries < maxTries) setTimeout(tick, 2000);
+ });
+ };
+ // First tick immediately so the pill flips out of "click to start"
+ // the moment the spawn reports running=true.
+ setTimeout(tick, 500);
+ });
});
} else {
title = `${kindLabel} unreachable`;
detail = j.message || 'Probe failed.';
- actionLabel = 'Open Settings';
- actionEl && (actionEl.onclick = function() { openAgentSettings(); });
+ actionLabel = 'Restart engine';
+ actionEl && (actionEl.onclick = function() {
+ // Restart-engine action — for the most common cause of unreachable
+ // (orphaned process holding the port). The local_server.start path
+ // now reaps orphans before spawning, so this is a clean recovery.
+ fetch('/agent/local/stop', {method: 'POST'}).then(() =>
+ fetch('/agent/local/start', {method: 'POST'})
+ ).then(() => {
+ let tries = 0;
+ const tick = () => {
+ agentRefreshConfig().then(() => {
+ const local = (window.AGENT.config || {}).local_server || {};
+ const reachable = (typeof local.reachable === 'boolean')
+ ? local.reachable : !!local.running;
+ if (reachable || tries >= 22) {
+ agentCheckEngine({forceShow: true});
+ return;
+ }
+ tries += 1;
+ setTimeout(tick, 2000);
+ });
+ };
+ setTimeout(tick, 500);
+ });
+ });
}
if (titleEl) titleEl.textContent = title;
@@ -16939,7 +17033,17 @@ async function agentRefreshConfig() {
let live = false;
let summary = '';
if (eng.kind === 'phosphene_local') {
- live = !!local.running;
+ // The pill is green only when BOTH process is alive AND port
+ // accepts connections. Without the reachable check, a freshly
+ // crashed engine (bind error after orphan collision) still
+ // shows green for ~1 s and the user submits a chat that 500s
+ // with "Remote end closed connection without response".
+ // `local.reachable` is `true | false`; older panels that don't
+ // expose it default to !!local.running for backward compat.
+ const reachableOk = (typeof local.reachable === 'boolean')
+ ? local.reachable
+ : !!local.running;
+ live = !!local.running && reachableOk;
const modelName = formatModelName(eng.model || '');
// Look up the resident size from the discovered models so the user
// sees "22 GB" inline next to the name — no surprise loads.
@@ -16950,9 +17054,17 @@ async function agentRefreshConfig() {
const hit = list.find(m => m.path === path);
if (hit && hit.size_gb) sizeBit = ` · ${hit.size_gb.toFixed(1)} GB`;
} catch (e) {}
- summary = live
- ? `${modelName || 'Local'}${sizeBit} · live`
- : `${modelName || 'Local'}${sizeBit} · click to start`;
+ // Three-state summary: live / starting / click-to-start. The
+ // "starting" state appears the moment a spawn begins until the
+ // port is bound (typically 5-15 s for Gemma 12B, longer on first
+ // run if weights need to come off disk).
+ if (local.running && !reachableOk) {
+ summary = `${modelName || 'Local'}${sizeBit} · starting…`;
+ } else if (live) {
+ summary = `${modelName || 'Local'}${sizeBit} · live`;
+ } else {
+ summary = `${modelName || 'Local'}${sizeBit} · click to start`;
+ }
} else {
const u = (eng.base_url || '').replace(/^https?:\/\//, '').replace(/\/v1$/, '');
summary = `${eng.model || 'remote'} · ${u}`;