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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(mlx): end a sidecar image when it stops moving, not after 900 s (C71)
purpled0f9b53ba422
diff --git a/src-tauri/resources/mlx/server.py b/src-tauri/resources/mlx/server.pyindex f1dad8d7..33fd5846 100644--- a/src-tauri/resources/mlx/server.py+++ b/src-tauri/resources/mlx/server.py@@ -79,6 +79,34 @@ def _stop_if_cancelled(pipe, step, timestep, callback_kwargs):return callback_kwargs+# How far the image is (C71). The app used to give a whole request 900 s,+# model load included, and Chroma1-HD at 40 steps and 1024 on an M1 Max needs+# longer than that: the render was cut off and reported as "mlx unreachable".+# The app now asks here and ends a run only when nothing has moved for its+# limit. `changed` is when the phase or the step last moved.+_progress_lock = threading.Lock()+_progress = {"phase": "idle", "step": 0, "steps": 0, "step_hook": False, "changed": time.monotonic()}+++def _note_progress(phase=None, step=None, steps=None, step_hook=None):+ with _progress_lock:+ if phase is not None:+ _progress["phase"] = phase+ if step is not None:+ _progress["step"] = step+ if steps is not None:+ _progress["steps"] = steps+ if step_hook is not None:+ _progress["step_hook"] = step_hook+ _progress["changed"] = time.monotonic()+++def _on_step_end(pipe, step, timestep, callback_kwargs):+ # `step` counts from 0 and the call comes at the end of that step.+ _note_progress(step=step + 1)+ return _stop_if_cancelled(pipe, step, timestep, callback_kwargs)++def _takes_step_callback(pipe) -> bool:"""Whether this pipeline calls back after a step. One that does not runsto its end, and the app drops what it returns."""@@ -198,6 +226,17 @@ def health():}[email protected]("/progress")+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)+ snap["quiet_seconds"] = round(time.monotonic() - snap.pop("changed"), 1)+ return snap++@app.post("/unload")def unload():"""Free the resident model now, keeping the server up. Idempotent — the@@ -228,6 +267,7 @@ def generate(req: GenerateRequest):global _activewith _active_lock:_active += 1+ _note_progress(phase="waiting", step=0, steps=req.steps, step_hook=False)try:return _generate(req)finally:@@ -235,6 +275,7 @@ def generate(req: GenerateRequest):_active -= 1if _active == 0:_cancel.clear()+ _note_progress(phase="idle", step=0, steps=0, step_hook=False)def _generate(req: GenerateRequest):@@ -245,6 +286,7 @@ def _generate(req: GenerateRequest):# Cancelled while it waited for the image before it.if _cancel.is_set():raise _cancelled_answer()+ _note_progress(phase="loading")try:pipe = _ensure_pipe(req.model_repo,@@ -275,8 +317,10 @@ def _generate(req: GenerateRequest):}if req.negative_prompt:gen_kwargs["negative_prompt"] = req.negative_prompt- if _takes_step_callback(pipe):- gen_kwargs["callback_on_step_end"] = _stop_if_cancelled+ hook = _takes_step_callback(pipe)+ if hook:+ gen_kwargs["callback_on_step_end"] = _on_step_end+ _note_progress(phase="steps", step=0, steps=req.steps, step_hook=hook)# Cancelled while the model loaded: no step is run for it.if _cancel.is_set():@@ -292,6 +336,7 @@ def _generate(req: GenerateRequest):# unloaded mid-run and the countdown starts from completion._last_activity = time.monotonic()+ _note_progress(phase="saving")img = result.images[0]buf = io.BytesIO()img.save(buf, format="PNG")diff --git a/src-tauri/resources/mlx/tests/test_cancel.py b/src-tauri/resources/mlx/tests/test_cancel.pyindex ea229a8c..05d8f657 100644--- a/src-tauri/resources/mlx/tests/test_cancel.py+++ b/src-tauri/resources/mlx/tests/test_cancel.py@@ -200,3 +200,46 @@ class CancelTest(unittest.TestCase):if __name__ == "__main__":unittest.main()+++class ProgressTest(unittest.TestCase):+ """C71: the app ends a run when nothing moves, so the sidecar says how far it is."""++ def setUp(self):+ self.server = _load_server()++ def test_idle_before_and_after_an_image(self):+ server = self.server+ self.assertEqual(server.progress()["phase"], "idle")+ server._ensure_pipe = lambda *args, **kwargs: Pipe()+ server.generate(server.GenerateRequest(prompt="a cat", steps=3))+ snap = server.progress()+ self.assertEqual((snap["phase"], snap["step"], snap["steps"]), ("idle", 0, 0))++ def test_each_step_is_counted_while_the_image_runs(self):+ server = self.server+ seen = []++ def look(step):+ seen.append(server.progress())++ loads = []++ def load(*args, **kwargs):+ loads.append(server.progress()["phase"])+ return Pipe(on_step=look)++ server._ensure_pipe = load+ server.generate(server.GenerateRequest(prompt="a cat", steps=4))+ self.assertEqual(loads, ["loading"])+ # on_step runs before the callback of its step: step n sees n done.+ self.assertEqual([s["step"] for s in seen], [0, 1, 2, 3])+ self.assertTrue(all(s["phase"] == "steps" and s["steps"] == 4 and s["step_hook"] for s in seen))+ self.assertTrue(all(s["quiet_seconds"] >= 0 for s in seen))++ 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.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.rsindex efbb88e2..726b8017 100644--- a/src-tauri/src/commands/mlx.rs+++ b/src-tauri/src/commands/mlx.rs@@ -2277,6 +2277,10 @@ struct GenerateArgs {/// strength, in the order they were picked. See `mlx_loras`.#[serde(default)]loras: Vec<LoraArg>,+ /// How long an image of the sidecar may go without any progress before+ /// it is ended, in seconds (Settings, Image timeout). Absent: 20 minutes.+ #[serde(default)]+ stall_timeout_secs: Option<u64>,}#[derive(serde::Deserialize)]@@ -2350,6 +2354,108 @@ fn cancel_sidecar_images(run: Option<&str>) -> bool {/// not show it: it has let go of the run already.const IMAGE_CANCELLED: &str = "The image was cancelled.";+// ── How long an image of the sidecar may take (C71) ──────────────────+//+// The request used to carry one fixed limit of 900 s, the model load+// included. Chroma1-HD at 40 steps and 1024 with real CFG takes longer than+// that on an M1 Max, and the cut-off request came back as "mlx unreachable".+// The sidecar now says how far it is (`GET /progress`), and a run is ended+// only when nothing has moved for the limit set in Settings (Image timeout,+// the same setting ComfyUI renders use). A model that loads gets at least+// the old 15 minutes for that alone, whatever the setting.++/// The limit when the request names none: Settings' default Image timeout.+const SIDECAR_STALL_DEFAULT: std::time::Duration = std::time::Duration::from_secs(20 * 60);+/// What a model load always gets, as much as the whole request had before.+const SIDECAR_LOAD_FLOOR: std::time::Duration = std::time::Duration::from_secs(15 * 60);+/// The range Settings allows: 1 to 480 minutes.+const SIDECAR_STALL_MIN_SECS: u64 = 60;+const SIDECAR_STALL_MAX_SECS: u64 = 480 * 60;+/// How often the watch asks the sidecar.+const SIDECAR_WATCH_EVERY: std::time::Duration = std::time::Duration::from_secs(5);++/// The limit a request asks for, held to the range Settings allows.+fn sidecar_stall_limit(asked: Option<u64>) -> std::time::Duration {+ asked.map_or(SIDECAR_STALL_DEFAULT, |s| {+ std::time::Duration::from_secs(s.clamp(SIDECAR_STALL_MIN_SECS, SIDECAR_STALL_MAX_SECS))+ })+}++/// What the sidecar says about the image under way (`GET /progress`).+#[derive(Debug, Clone, PartialEq, serde::Deserialize)]+struct SidecarProgress {+ phase: String,+ #[serde(default)]+ step: u32,+ #[serde(default)]+ steps: u32,+ #[serde(default)]+ step_hook: bool,+ #[serde(default)]+ quiet_seconds: f64,+}++/// Ask the sidecar how far its image is. `None`: no answer, or a sidecar+/// from before 3.1.0 that has no `/progress`.+fn sidecar_progress() -> Option<SidecarProgress> {+ parse_sidecar_progress(&sidecar_ask(MLX_PORT, "GET", "/progress")?)+}++fn parse_sidecar_progress(answer: &str) -> Option<SidecarProgress> {+ let (head, body) = answer.split_once("\r\n\r\n")?;+ if head.lines().next()?.split_whitespace().nth(1)? != "200" {+ return None;+ }+ serde_json::from_str(body).ok()+}++/// "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 {+ let m = s / 60;+ format!("{m} {}", if m == 1 { "minute" } else { "minutes" })+ } else {+ format!("{s} seconds")+ }+}++/// Whether the image of the sidecar has gone quiet for longer than it may,+/// and the sentence that says so. `elapsed` is the time since the request+/// went out, used only when the sidecar does not say how far it is.+fn sidecar_stall_verdict(+ model: &str,+ progress: Option<&SidecarProgress>,+ elapsed: std::time::Duration,+ limit: std::time::Duration,+) -> Option<String> {+ let load_limit = limit.max(SIDECAR_LOAD_FLOOR);+ const WAY_OUT: &str = "Raise Image timeout in Settings, or try fewer steps or a smaller size.";+ let Some(p) = progress else {+ // Nothing to go by: the whole request gets what a load gets.+ return (elapsed >= load_limit).then(|| {+ format!("{model} timed out after {} without saying how far it was. {WAY_OUT}", human_span(load_limit))+ });+ };+ let quiet = std::time::Duration::from_secs_f64(p.quiet_seconds.max(0.0));+ match p.phase.as_str() {+ "waiting" | "loading" if quiet >= load_limit => Some(format!(+ "{model} timed out while loading: nothing moved for {}. {WAY_OUT}",+ human_span(load_limit)+ )),+ "steps" if quiet >= limit && p.step_hook && p.steps > 0 => Some(format!(+ "{model} timed out at step {} of {}: no new step for {}. {WAY_OUT}",+ p.step,+ p.steps,+ human_span(limit)+ )),+ "steps" | "saving" if quiet >= limit => {+ Some(format!("{model} timed out: no progress for {}. {WAY_OUT}", human_span(limit)))+ }+ _ => None,+ }+}+/// A request to the sidecar that must not wait: Cancel is one click and the/// answer is nothing the caller needs. `None`: nobody answered in time.fn sidecar_ask(port: u16, method: &str, path: &str) -> Option<String> {@@ -2527,9 +2633,10 @@ pub async fn mlx_generate(_state: &AppState, args: &Value) -> CmdResult {name_installed_snapshot(entry);let at_image = SidecarImage::begin(req.run.clone());let client = reqwest::Client::builder()- // Big pipelines (Z-Image, Qwen-Image) take minutes to page in from- // disk on first use — the old 120 s timeout aborted mid-load.- .timeout(std::time::Duration::from_secs(900))+ // No limit on the whole request: a big pipeline (Chroma1-HD, Qwen-Image)+ // takes minutes to page in and many more to run. The watch below ends+ // a run that stops moving (C71).+ .connect_timeout(std::time::Duration::from_secs(10)).build().map_err(|e| crate::commands::internal(e.to_string()))?;@@ -2550,16 +2657,37 @@ pub async fn mlx_generate(_state: &AppState, args: &Value) -> CmdResult {// going to the hub. That is what makes an offline render possible."local_files_only": image_model_is_installed(entry),});- let res = client- .post(format!("http://127.0.0.1:{MLX_PORT}/generate"))- .json(&body)- .send()- .await- .map_err(|e| {- crate::commands::internal(- sidecar_failure().unwrap_or_else(|| format!("mlx unreachable: {}", os_error::english(&e))),- )- })?;+ let limit = sidecar_stall_limit(req.stall_timeout_secs);+ let started = std::time::Instant::now();+ let model = entry.name;+ let watch = async move {+ loop {+ tokio::time::sleep(SIDECAR_WATCH_EVERY).await;+ let progress = tokio::task::spawn_blocking(sidecar_progress).await.ok().flatten();+ if let Some(why) = sidecar_stall_verdict(model, progress.as_ref(), started.elapsed(), limit) {+ break why;+ }+ }+ };+ let sent = client.post(format!("http://127.0.0.1:{MLX_PORT}/generate")).json(&body).send();+ let res = tokio::select! {+ res = sent => res.map_err(|e| {+ crate::commands::internal(sidecar_failure().unwrap_or_else(|| {+ if e.is_timeout() {+ format!("{model} timed out: {}", os_error::english(&e))+ } else {+ format!("mlx unreachable: {}", os_error::english(&e))+ }+ }))+ })?,+ why = watch => {+ // The request is let go here; the sidecar stops at the end of the+ // step it is in and frees its lock for the next image.+ let _ = tokio::task::spawn_blocking(|| sidecar_ask(MLX_PORT, "POST", "/cancel")).await;+ tracing::warn!(target: "mlx", "{why}");+ return Err(crate::commands::internal(why));+ }+ };if !res.status().is_success() {// The sidecar ended the image between two steps because it was asked to.if at_image.cancelled() {@@ -2720,9 +2848,20 @@ pub(crate) fn real_run_install_mflux_engine(state: &AppState) -> bool {}/// How far the image is that the second engine is making: `running`, `step`-/// and `steps`. The sidecar reports no steps, and with it `running` is false.+/// and `steps`. An image of the sidecar reports its steps where its pipeline+/// counts them (`GET /progress`); one that does not leaves `running` false.pub fn mlx_generate_progress(_state: &AppState, _args: &Value) -> CmdResult {- Ok(mflux::progress())+ let engine = mflux::progress();+ if engine.get("running").and_then(Value::as_bool) == Some(true) || !sidecar_at_an_image() {+ return Ok(engine);+ }+ // An image of the sidecar: its steps, where its pipeline counts them (C71).+ Ok(match sidecar_progress() {+ Some(p) if p.phase == "steps" && p.step_hook && p.steps > 0 => {+ json!({ "running": true, "step": p.step, "steps": p.steps })+ }+ _ => engine,+ })}/// Cancel in Create: end the image that is being made. `run` is the name@@ -3395,6 +3534,76 @@ mod tests {assert!(hands_over < counted && counted < request);}+ /// C71: Chroma1-HD at 40 steps ran past a fixed 900 s and came back as+ /// "mlx unreachable". A run is ended only when nothing moves.+ #[test]+ fn a_sidecar_image_is_ended_when_it_stops_moving_not_after_a_fixed_time() {+ use std::time::Duration;+ let p = |phase: &str, step: u32, quiet: f64| SidecarProgress {+ phase: phase.into(),+ step,+ steps: 40,+ step_hook: true,+ quiet_seconds: quiet,+ };+ let limit = sidecar_stall_limit(None);+ assert_eq!(limit, Duration::from_secs(1200), "Settings' default of 20 minutes");+ // Two hours in, a step every 3 minutes: it runs on.+ let long = Duration::from_secs(7200);+ assert_eq!(sidecar_stall_verdict("Chroma1-HD", Some(&p("steps", 30, 180.0)), long, limit), None);+ // A load of 14 minutes is a load, even under a limit of 1 minute.+ let short = sidecar_stall_limit(Some(60));+ assert_eq!(sidecar_stall_verdict("Chroma1-HD", Some(&p("loading", 0, 840.0)), long, short), None);+ let stuck = sidecar_stall_verdict("Chroma1-HD", Some(&p("loading", 0, 900.0)), long, short).expect("a load that never ends");+ assert!(stuck.starts_with("Chroma1-HD timed out while loading: nothing moved for 15 minutes."), "{stuck}");+ // A step that never ends says where it stopped, as a timeout.+ let why = sidecar_stall_verdict("Chroma1-HD", Some(&p("steps", 12, 1200.0)), long, limit).expect("stalled");+ assert_eq!(+ why,+ "Chroma1-HD timed out at step 12 of 40: no new step for 20 minutes. Raise Image timeout in Settings, or try fewer steps or a smaller size."+ );+ assert!(!why.contains("unreachable"), "Create retries an unreachable sidecar and would wait the whole limit again");+ // A pipeline that counts no steps: quiet time is all there is.+ let blind = SidecarProgress { step_hook: false, ..p("steps", 0, 1300.0) };+ assert!(sidecar_stall_verdict("SD Turbo", Some(&blind), long, limit).unwrap().starts_with("SD Turbo timed out: no progress for 20 minutes."));+ // A sidecar that does not say how far it is gets what a load gets, in all.+ assert_eq!(sidecar_stall_verdict("X", None, Duration::from_secs(1199), limit), None);+ assert!(sidecar_stall_verdict("X", None, Duration::from_secs(1200), limit).is_some());+ // Idle: the request has not arrived yet or the image is through.+ assert_eq!(sidecar_stall_verdict("X", Some(&p("idle", 0, 99_999.0)), long, limit), None);+ }++ #[test]+ fn the_stall_limit_stays_in_the_range_settings_allows() {+ use std::time::Duration;+ assert_eq!(sidecar_stall_limit(Some(0)), Duration::from_secs(60));+ assert_eq!(sidecar_stall_limit(Some(45 * 60)), Duration::from_secs(45 * 60));+ assert_eq!(sidecar_stall_limit(Some(u64::MAX)), Duration::from_secs(480 * 60));+ assert_eq!(human_span(Duration::from_secs(60)), "1 minute");+ assert_eq!(human_span(Duration::from_secs(90)), "90 seconds");+ }++ #[test]+ fn the_progress_answer_of_the_sidecar_is_read() {+ let ok = "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\n\r\n{\"phase\":\"steps\",\"step\":3,\"steps\":40,\"step_hook\":true,\"quiet_seconds\":1.5}";+ let p = parse_sidecar_progress(ok).expect("read");+ assert_eq!((p.phase.as_str(), p.step, p.steps, p.step_hook), ("steps", 3, 40, true));+ // A sidecar from before 3.1.0 has no such route.+ assert_eq!(parse_sidecar_progress("HTTP/1.1 404 Not Found\r\n\r\n{\"detail\":\"Not Found\"}"), None);+ assert_eq!(parse_sidecar_progress("garbage"), None);+ }++ /// The watch replaces the fixed limit on the whole request.+ #[test]+ fn the_sidecar_request_has_no_fixed_limit_and_is_watched() {+ let src = production_source();+ let generate = &src[src.find("pub async fn mlx_generate(").unwrap()..];+ let generate = &generate[..generate.find("\npub(crate) fn images_root()").unwrap()];+ assert!(!generate.contains(".timeout("), "a fixed limit on the whole request is back");+ assert!(generate.contains("sidecar_stall_verdict("));+ assert!(generate.contains("tokio::select!"));+ }+/// The tests that put an image into the sidecar's list take turns.fn sidecar_images_in_tests() -> std::sync::MutexGuard<'static, ()> {static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(());@@ -3467,7 +3676,9 @@ mod tests {assert!(cancel.contains("sidecar_ask(MLX_PORT, \"POST\", \"/cancel\")"));// The sidecar has the endpoint and looks at the mark after each step.assert!(SERVER_PY.contains("@app.post(\"/cancel\")"));- assert!(SERVER_PY.contains("gen_kwargs[\"callback_on_step_end\"] = _stop_if_cancelled"));+ assert!(SERVER_PY.contains("gen_kwargs[\"callback_on_step_end\"] = _on_step_end"));+ assert!(SERVER_PY.contains("return _stop_if_cancelled(pipe, step, timestep, callback_kwargs)"));+ assert!(SERVER_PY.contains("@app.get(\"/progress\")"));let generate = &src[src.find("pub async fn mlx_generate(").unwrap()..];let generate = &generate[..generate.find("\npub(crate) fn images_root()").unwrap()];assert!(generate.contains("keep_sidecar_image(at_image.cancelled(), payload, entry.guidance, &images_root())"));diff --git a/src/api/__tests__/mlx-sidecar-stall-limit-c71.test.ts b/src/api/__tests__/mlx-sidecar-stall-limit-c71.test.tsnew file mode 100644index 00000000..90c4cfc9--- /dev/null+++ b/src/api/__tests__/mlx-sidecar-stall-limit-c71.test.ts@@ -0,0 +1,44 @@+/**+ * C71: an image of the Mac's sidecar is ended only when it stops moving for+ * the Image timeout in Settings. The request carries that limit to Rust.+ *+ * Run: npx vitest run src/api/__tests__/mlx-sidecar-stall-limit-c71.test.ts+ */+import { beforeEach, describe, expect, it, vi } from 'vitest'++const sent = vi.hoisted(() => [] as Array<{ cmd: string; args: Record<string, unknown> }>)+vi.mock('../mlx-invoke', () => ({+ invokeMedia: vi.fn(async (cmd: string, args: Record<string, unknown>) => {+ sent.push({ cmd, args })+ if (cmd === 'mlx_status') return { installed: true, running: true }+ if (cmd === 'mlx_image_models') return [{ id: 'chroma1-hd', family: 'diffusers', sizeGB: 27.5 }]+ if (cmd === 'mlx_generate_progress') return { running: false, step: 0, steps: 0 }+ return { image_base64: 'AA==', width: 1024, height: 1024 }+ }),+}))++import { generateMlxImageDataUrl, mlxGenerate } from '../mlx-image'+import { useSettingsStore } from '../../stores/settingsStore'++const generateCall = () => sent.find((c) => c.cmd === 'mlx_generate')!++beforeEach(() => { sent.length = 0 })++describe('the stall limit of a Mac image', () => {+ it('a sidecar run carries the Image timeout from Settings, in seconds', async () => {+ useSettingsStore.setState((s) => ({ settings: { ...s.settings, imageGenTimeoutMinutes: 45 } }))+ await generateMlxImageDataUrl({ prompt: 'a fox', model: 'chroma1-hd' })+ expect(generateCall().args.stall_timeout_secs).toBe(45 * 60)+ })++ it('20 minutes when the setting is not a number', async () => {+ useSettingsStore.setState((s) => ({ settings: { ...s.settings, imageGenTimeoutMinutes: undefined as unknown as number } }))+ await generateMlxImageDataUrl({ prompt: 'a fox', model: 'chroma1-hd' })+ expect(generateCall().args.stall_timeout_secs).toBe(20 * 60)+ })++ it('a bare call without the field sends none', async () => {+ await mlxGenerate({ prompt: 'a fox' })+ expect(generateCall().args).not.toHaveProperty('stall_timeout_secs')+ })+})diff --git a/src/api/mlx-image.ts b/src/api/mlx-image.tsindex 37571bdf..f7e5ebc8 100644--- a/src/api/mlx-image.ts+++ b/src/api/mlx-image.ts@@ -14,6 +14,8 @@ import { invokeMedia } from './mlx-invoke'import { siGbToBytes } from '../lib/formatters'import type { ClassifiedModel } from './comfyui'import { MFLUX_FAMILY, imageModelBringsItsEngine, isMlxEnhancer } from '../lib/image-engines'+import { renderStallLimitMs } from '../lib/tool-timeout'+import { useSettingsStore } from '../stores/settingsStore'export interface MlxStatus {/** The engine can run: venv, the record of a finished pip run and the@@ -113,6 +115,9 @@ export interface MlxGenerateArgs {/** The LoRA stack: files of the Mac's LoRA folder (api/mlx-loras) by name,* in the order they were picked. Reaches the second engine alone. */loras?: { name: string; strength: number }[]+ /** C71: how long an image of the sidecar may go without any progress, in+ * seconds. `generateMlxImageDataUrl` sends Settings' Image timeout. */+ stallTimeoutSecs?: number}export interface MlxGenerateResult {@@ -156,13 +161,14 @@ export async function mlxGenerate(args: MlxGenerateArgs): Promise<MlxGenerateResif (args.strength != null && args.strength < 1) body.strength = args.strengthif (args.run) body.run = args.runif (args.loras?.length) body.loras = args.loras.map((l) => ({ name: l.name, strength: l.strength }))+ if (args.stallTimeoutSecs != null) body.stall_timeout_secs = args.stallTimeoutSecs// A single long-blocking request (model load + diffusion) — in-process// invoke has no per-call timeout to pass (unlike the old HTTP bridgeCmd).return invokeMedia<MlxGenerateResult>('mlx_generate', body)}-/** How far the image is that the second engine is making. `running` is false- * for an image in the sidecar, which reports no steps. */+/** How far the image is that the second engine or the sidecar is making.+ * `running` is false for a sidecar pipeline that counts no steps. */export async function mlxGenerateProgress(): Promise<{ running: boolean; step: number; steps: number }> {return invokeMedia('mlx_generate_progress')}@@ -418,7 +424,10 @@ export async function generateMlxImageDataUrl(// The sidecar makes images from text at the catalogue's guidance. An edit// never reaches it: Rust refuses one, and it is not sent a field it drops.// It has no place for a LoRA either, and Create offers it no stack.- const plain = { ...args, guidance: undefined, resolution: undefined, mask: undefined, strength: undefined, loras: undefined, run }+ // C71: Rust ends it only when it stops moving for this long, the same Image+ // timeout ComfyUI renders go by (Settings).+ const stallTimeoutSecs = Math.round(renderStallLimitMs('image', useSettingsStore.getState().settings) / 1000)+ const plain = { ...args, guidance: undefined, resolution: undefined, mask: undefined, strength: undefined, loras: undefined, run, stallTimeoutSecs }if (status.broken) {throw new Error('The image engine is incomplete. Set it up again in the Model Manager.')}diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsxindex 01a6be23..6e0deddf 100644--- a/src/components/settings/SettingsPage.tsx+++ b/src/components/settings/SettingsPage.tsx@@ -2212,12 +2212,15 @@ export function SettingsPage() {</Section>)}- {/* ComfyUI-only knobs, cloud renders use server-side limits, and the- Mac's MLX pipeline has its own fixed timeout, so hide there too. */}- {settings.appMode !== 'cloud' && !isMlxImageHost() && (+ {/* Cloud renders use server-side limits. On a Mac the image limit is+ also the one the MLX image engine goes by (C71); video there has+ its own, so its row stays ComfyUI-only. */}+ {settings.appMode !== 'cloud' && (<Section title="Image / Video Generation Timeouts"><div className="text-[0.6rem] text-gray-500 dark:text-gray-500 leading-relaxed pb-1.5">- Minutes a ComfyUI generation may go without any progress before LU stops it. Raise these if you run on iGPU or CPU only, because a single step of a 1024px image on integrated graphics can take many minutes.+ {isMlxImageHost()+ ? 'Minutes an image may go without any progress before LU stops it. Loading a model always gets at least 15 minutes. Raise this for large models with many steps, where a single step can take minutes.'+ : 'Minutes a ComfyUI generation may go without any progress before LU stops it. Raise these if you run on iGPU or CPU only, because a single step of a 1024px image on integrated graphics can take many minutes.'}</div><div className="flex items-center justify-between"><span className="text-[0.7rem] text-gray-700 dark:text-gray-400">Image timeout (min)</span>@@ -2232,19 +2235,21 @@ export function SettingsPage() {className="w-20 px-1.5 py-0.5 rounded bg-transparent border border-white/8 text-[0.65rem] text-right text-gray-300 font-mono focus:outline-none focus:border-white/20"/></div>- <div className="flex items-center justify-between">- <span className="text-[0.7rem] text-gray-700 dark:text-gray-400">Video timeout (min)</span>- <input- aria-label="Video timeout (min)"- type="number"- value={settings.videoGenTimeoutMinutes ?? 60}- onChange={(e) => updateSettings({ videoGenTimeoutMinutes: Math.min(480, Math.max(1, parseInt(e.target.value) || 60)) })}- min={1}- max={480}- placeholder="60"- className="w-20 px-1.5 py-0.5 rounded bg-transparent border border-white/8 text-[0.65rem] text-right text-gray-300 font-mono focus:outline-none focus:border-white/20"- />- </div>+ {!isMlxImageHost() && (+ <div className="flex items-center justify-between">+ <span className="text-[0.7rem] text-gray-700 dark:text-gray-400">Video timeout (min)</span>+ <input+ aria-label="Video timeout (min)"+ type="number"+ value={settings.videoGenTimeoutMinutes ?? 60}+ onChange={(e) => updateSettings({ videoGenTimeoutMinutes: Math.min(480, Math.max(1, parseInt(e.target.value) || 60)) })}+ min={1}+ max={480}+ placeholder="60"+ className="w-20 px-1.5 py-0.5 rounded bg-transparent border border-white/8 text-[0.65rem] text-right text-gray-300 font-mono focus:outline-none focus:border-white/20"+ />+ </div>+ )}</Section>)}diff --git a/src/lib/__tests__/der-mac-reicht-den-lora-stapel-durch.test.ts b/src/lib/__tests__/der-mac-reicht-den-lora-stapel-durch.test.tsindex 1f2f92f5..beda4e42 100644--- a/src/lib/__tests__/der-mac-reicht-den-lora-stapel-durch.test.ts+++ b/src/lib/__tests__/der-mac-reicht-den-lora-stapel-durch.test.ts@@ -131,7 +131,7 @@ describe('a run hands the stack to the second engine', () => {it('COUNTER-CHECK: a model of the sidecar is never sent one', async () => {await generateMlxImageDataUrl({ prompt: 'x', model: 'sd-turbo', steps: 4, seed: 1, loras: STACK })- expect(sent()).toEqual({ prompt: 'x', model: 'sd-turbo', steps: 4, seed: 1, run: expect.any(String) })+ expect(sent()).toEqual({ prompt: 'x', model: 'sd-turbo', steps: 4, seed: 1, run: expect.any(String), stall_timeout_secs: expect.any(Number) })})})