Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(mlx): a silent sidecar is not a stalled one; real Mac run harness for the sidecar (C71)

purplef41d8edebd4e
diff --git a/src-tauri/resources/mlx/server.py b/src-tauri/resources/mlx/server.py
index 33fd5846..bf947b15 100644
--- a/src-tauri/resources/mlx/server.py
+++ b/src-tauri/resources/mlx/server.py
@@ -227,12 +227,15 @@ def health():
@app.get("/progress")
-def progress():
+async def progress():
"""Where the image under way is: `phase` is idle, waiting, loading, steps
or saving; `step` of `steps` once the steps run (only a pipeline with the
- step hook counts them, `step_hook`); `quiet_seconds` since anything moved."""
- with _progress_lock:
- snap = dict(_progress)
+ step hook counts them, `step_hook`); `quiet_seconds` since anything moved.
+
+ `async` on purpose: it is answered on the event loop itself and never
+ waits for a worker thread next to the image. Copying the dict needs no
+ lock: the writers replace whole values."""
+ snap = dict(_progress)
snap["quiet_seconds"] = round(time.monotonic() - snap.pop("changed"), 1)
return snap
diff --git a/src-tauri/resources/mlx/tests/test_cancel.py b/src-tauri/resources/mlx/tests/test_cancel.py
index 05d8f657..1b64d390 100644
--- a/src-tauri/resources/mlx/tests/test_cancel.py
+++ b/src-tauri/resources/mlx/tests/test_cancel.py
@@ -5,6 +5,7 @@ fastapi, pydantic, uvicorn and torch are replaced by stand-ins, and the
pipeline is a loop that calls back after each step the way diffusers does.
"""
+import asyncio
import importlib.util
import sys
import threading
@@ -210,10 +211,10 @@ class ProgressTest(unittest.TestCase):
def test_idle_before_and_after_an_image(self):
server = self.server
- self.assertEqual(server.progress()["phase"], "idle")
+ self.assertEqual(asyncio.run(server.progress())["phase"], "idle")
server._ensure_pipe = lambda *args, **kwargs: Pipe()
server.generate(server.GenerateRequest(prompt="a cat", steps=3))
- snap = server.progress()
+ snap = asyncio.run(server.progress())
self.assertEqual((snap["phase"], snap["step"], snap["steps"]), ("idle", 0, 0))
def test_each_step_is_counted_while_the_image_runs(self):
@@ -221,12 +222,12 @@ class ProgressTest(unittest.TestCase):
seen = []
def look(step):
- seen.append(server.progress())
+ seen.append(asyncio.run(server.progress()))
loads = []
def load(*args, **kwargs):
- loads.append(server.progress()["phase"])
+ loads.append(asyncio.run(server.progress())["phase"])
return Pipe(on_step=look)
server._ensure_pipe = load
@@ -240,6 +241,6 @@ class ProgressTest(unittest.TestCase):
def test_a_pipeline_without_the_hook_says_it_counts_no_steps(self):
server = self.server
seen = []
- server._ensure_pipe = lambda *args, **kwargs: OldPipe(on_step=lambda step: seen.append(server.progress()))
+ server._ensure_pipe = lambda *args, **kwargs: OldPipe(on_step=lambda step: seen.append(asyncio.run(server.progress())))
server.generate(server.GenerateRequest(prompt="a cat", steps=2))
self.assertEqual([(s["phase"], s["step"], s["step_hook"]) for s in seen], [("steps", 0, False)] * 2)
diff --git a/src-tauri/src/commands/mlx.rs b/src-tauri/src/commands/mlx.rs
index 187b56da..03d77270 100644
--- a/src-tauri/src/commands/mlx.rs
+++ b/src-tauri/src/commands/mlx.rs
@@ -2409,16 +2409,22 @@ fn parse_sidecar_progress(answer: &str) -> Option<SidecarProgress> {
serde_json::from_str(body).ok()
}
-/// The last answer of the sidecar, `since` later with no new one: nothing
-/// has moved in between.
-fn still_quiet(p: &SidecarProgress, since: std::time::Duration) -> SidecarProgress {
- SidecarProgress { quiet_seconds: p.quiet_seconds + since.as_secs_f64(), ..p.clone() }
+/// A sidecar that answered before and has not answered for `silent`: ended
+/// once that is as long as a model load may take, never sooner.
+fn sidecar_silence_verdict(model: &str, silent: std::time::Duration, limit: std::time::Duration) -> Option<String> {
+ let load_limit = limit.max(SIDECAR_LOAD_FLOOR);
+ (silent >= load_limit).then(|| {
+ format!(
+ "{model} timed out: the image engine has not answered for {}. Raise Image timeout in Settings, or try fewer steps or a smaller size.",
+ human_span(load_limit)
+ )
+ })
}
/// "1 minute", "20 minutes", "90 seconds".
fn human_span(d: std::time::Duration) -> String {
let s = d.as_secs();
- if s >= 60 && s % 60 == 0 {
+ if s >= 60 && s.is_multiple_of(60) {
let m = s / 60;
format!("{m} {}", if m == 1 { "minute" } else { "minutes" })
} else {
@@ -2667,20 +2673,24 @@ pub async fn mlx_generate(_state: &AppState, args: &Value) -> CmdResult {
let started = std::time::Instant::now();
let model = entry.name;
let watch = async move {
- // The last answer and when it came: a sidecar that stops answering
- // (frozen, swapping) is as quiet as one that answers "no new step".
- let mut last: Option<(SidecarProgress, std::time::Instant)> = None;
+ // When the sidecar last answered. An ask that goes unanswered is not
+ // taken for a stall: a busy sidecar can be slow to answer and still
+ // be making steps. Only a long silence ends the run (see
+ // `sidecar_silence_verdict`).
+ let mut answered: Option<std::time::Instant> = None;
loop {
tokio::time::sleep(SIDECAR_WATCH_EVERY).await;
- let answer = tokio::task::spawn_blocking(sidecar_progress).await.ok().flatten();
- let progress = match answer {
+ let why = match tokio::task::spawn_blocking(sidecar_progress).await.ok().flatten() {
Some(p) => {
- last = Some((p.clone(), std::time::Instant::now()));
- Some(p)
+ answered = Some(std::time::Instant::now());
+ sidecar_stall_verdict(model, Some(&p), started.elapsed(), limit)
}
- None => last.as_ref().map(|(p, at)| still_quiet(p, at.elapsed())),
+ None => match answered {
+ Some(at) => sidecar_silence_verdict(model, at.elapsed(), limit),
+ None => sidecar_stall_verdict(model, None, started.elapsed(), limit),
+ },
};
- if let Some(why) = sidecar_stall_verdict(model, progress.as_ref(), started.elapsed(), limit) {
+ if let Some(why) = why {
break why;
}
}
@@ -2857,6 +2867,18 @@ pub(crate) fn reap_orphaned_mflux() {
}
}
+/// For `commands::real_run_mac`: whether the sidecar's port answers.
+#[cfg(all(test, target_os = "macos"))]
+pub(crate) fn real_run_sidecar_up() -> bool {
+ sidecar_running()
+}
+
+/// For `commands::real_run_mac`: end the sidecar the run started.
+#[cfg(all(test, target_os = "macos"))]
+pub(crate) fn real_run_stop_sidecar() {
+ stop_sidecar();
+}
+
/// For `commands::real_run_mac`: see `mflux::install_engine_alone`.
#[cfg(all(test, target_os = "macos"))]
pub(crate) fn real_run_install_mflux_engine(state: &AppState) -> bool {
@@ -3589,14 +3611,22 @@ mod tests {
assert_eq!(sidecar_stall_verdict("X", Some(&p("idle", 0, 99_999.0)), long, limit), None);
}
+ /// Real run, 12.11.2026: SD Turbo at 300 steps went on stepping while its
+ /// progress asks went unanswered from step 67 (its listener had been
+ /// ended by a SIGTERM on the port; uvicorn then finishes the request it
+ /// has), and the run was ended as stalled after a minute. Silence is not
+ /// a stall: only as long as a load may take.
#[test]
- fn a_sidecar_that_stops_answering_is_quiet_from_its_last_answer() {
+ fn a_sidecar_that_does_not_answer_is_ended_only_after_the_load_limit() {
use std::time::Duration;
- let at_step = SidecarProgress { phase: "steps".into(), step: 7, steps: 40, step_hook: true, quiet_seconds: 3.0 };
- let later = still_quiet(&at_step, Duration::from_secs(60));
- assert_eq!((later.step, later.quiet_seconds), (7, 63.0));
- let why = sidecar_stall_verdict("SD Turbo", Some(&later), Duration::from_secs(90), sidecar_stall_limit(Some(60))).expect("a minute of silence");
- assert!(why.starts_with("SD Turbo timed out at step 7 of 40: no new step for 1 minute."), "{why}");
+ let minute = sidecar_stall_limit(Some(60));
+ assert_eq!(sidecar_silence_verdict("SD Turbo", Duration::from_secs(120), minute), None);
+ assert_eq!(sidecar_silence_verdict("SD Turbo", Duration::from_secs(899), minute), None);
+ let why = sidecar_silence_verdict("SD Turbo", Duration::from_secs(900), minute).expect("15 minutes without an answer");
+ assert!(why.starts_with("SD Turbo timed out: the image engine has not answered for 15 minutes."), "{why}");
+ // A longer Image timeout is longer here too.
+ assert_eq!(sidecar_silence_verdict("X", Duration::from_secs(1700), sidecar_stall_limit(Some(30 * 60))), None);
+ assert!(!why.contains("unreachable"));
}
#[test]
diff --git a/src-tauri/src/commands/real_run_mac.rs b/src-tauri/src/commands/real_run_mac.rs
index ac43f88a..f43327ca 100644
--- a/src-tauri/src/commands/real_run_mac.rs
+++ b/src-tauri/src/commands/real_run_mac.rs
@@ -703,6 +703,10 @@ fn image() {
if user_sampling {
args["steps"] = json!(steps);
args["guidance"] = json!(guidance);
+ } else if model["family"] == "diffusers" {
+ // A model of the sidecar takes Create's steps and no guidance
+ // (`generateMlxImageDataUrl`, the `plain` request).
+ args["steps"] = json!(steps);
}
if let Some(negative) = var("LU_REAL_NEGATIVE") {
args["negative_prompt"] = json!(negative);
@@ -738,6 +742,18 @@ fn image() {
args["images"] = json!(staged);
}
println!("mlx_generate {args}");
+ // A model of the sidecar: start it and wait for its port, as Create does
+ // (`mlxStart`, `waitForMlxRunning`). It is ended again below.
+ let sidecar = model["family"] == "diffusers";
+ if sidecar {
+ mlx::mlx_start(state, &none).expect("mlx_start");
+ let up = Instant::now();
+ while !mlx::real_run_sidecar_up() {
+ assert!(up.elapsed() < Duration::from_secs(120), "the sidecar did not come up");
+ std::thread::sleep(Duration::from_millis(250));
+ }
+ println!("sidecar up after {:.1}s", seconds(up));
+ }
let images_before = std::fs::read_dir(mlx::images_root()).map(|d| d.count()).unwrap_or(0);
let available_before = available_memory_gb();
@@ -796,6 +812,9 @@ fn image() {
}
let answer = rt.block_on(job).expect("the generate task");
let took = seconds(started);
+ if sidecar {
+ mlx::real_run_stop_sidecar();
+ }
let memory = sampler.finish();
let stepping: Vec<f64> = steps_seen.windows(2).filter(|w| w[1].1 == w[0].1 + 1).map(|w| w[1].0 - w[0].0).collect();