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(shutdown): end only our own MLX sidecar, never from a test
purple64c39d8df713
diff --git a/src-tauri/src/commands/mlx.rs b/src-tauri/src/commands/mlx.rsindex efbb88e2..08494804 100644--- a/src-tauri/src/commands/mlx.rs+++ b/src-tauri/src/commands/mlx.rs@@ -591,7 +591,7 @@ fn bring_engine_up_to_date(slot: &crate::install_state::InstallSlot) -> Result<(// The sweep exists on the Mac alone (see its gate in `process_util`), and// so does the sidecar it ends. Without this gate Windows did not compile.#[cfg(target_os = "macos")]- crate::process_util::kill_listeners_on_port(MLX_PORT);+ sweep_orphaned_sidecar();slot.log("image engine updated");Ok(())}@@ -2692,6 +2692,38 @@ pub(crate) fn stop_sidecar() {sidecar().stop();}+/// End the image sidecar of THIS app that no handle reaches any more: one an+/// earlier run of this app left behind after ending hard, or one this process+/// started and lost the handle of. Returns the pids it stopped.+///+/// Ours means: the argv names this app's own `server.py` (the identity's data+/// folder, so a test build or a second identity never matches) AND the parent+/// is this process or launchd (an orphan). A sidecar whose parent is another+/// live LU belongs to that LU and is left alone, and so is anything else on+/// the port. In a test build it does nothing at all: `Drop for AppState` runs+/// this, and a test must never end a process it did not start (N2, 13.11.).+#[cfg(target_os = "macos")]+pub(crate) fn sweep_orphaned_sidecar() -> Vec<u32> {+ if cfg!(test) {+ return Vec::new();+ }+ sweep_sidecar_at(MLX_PORT, &mlx_root().join("server.py"))+}++#[cfg(target_os = "macos")]+fn sweep_sidecar_at(port: u16, server_py: &std::path::Path) -> Vec<u32> {+ let own = std::process::id();+ crate::process_util::kill_own_listeners_on_port(port, |l| is_our_sidecar(l, server_py, own))+}++/// Pure: is this listener a sidecar of ours? See `sweep_orphaned_sidecar`.+#[cfg(any(target_os = "macos", test))]+pub(crate) fn is_our_sidecar(listener: &crate::process_util::PortListener, server_py: &std::path::Path, own_pid: u32) -> bool {+ let runs_our_server = listener.cmd.iter().any(|arg| std::path::Path::new(arg) == server_py);+ let parent_is_us_or_gone = matches!(listener.parent, Some(p) if p == own_pid || p == 1);+ runs_our_server && parent_is_us_or_gone+}+/// Whether an image is being made right now, by either engine. The music/// lane asks this before it loads its model into the same memory.pub(crate) fn image_engine_busy() -> bool {@@ -3018,7 +3050,7 @@ pub fn mlx_start(_state: &AppState, _args: &Value) -> CmdResult {// called from `src/api/mlx-image.ts`). It frees the resident model and// leaves the sidecar up, which is the point of a sidecar — `mlx_status`// returns `modelLoaded`/`idleSeconds` so the UI can offer exactly that.-// * Ending the PROCESS is the quit-time `kill_listeners_on_port(MLX_PORT)`+// * Ending the PROCESS is the quit-time `sweep_orphaned_sidecar()`// in `state.rs::shutdown`. Same call, one line, on the path that actually// runs.//@@ -4432,4 +4464,108 @@ mod tests {assert!(REQUIREMENTS_TXT.contains("torch"));assert!(SERVER_PY.contains("FastAPI"));}++ // ── N3 (3.1.0): the quit sweep ends only our own sidecar ──────────────++ fn listener(pid: u32, parent: Option<u32>, cmd: &[&str]) -> crate::process_util::PortListener {+ crate::process_util::PortListener { pid, parent, cmd: cmd.iter().map(|s| s.to_string()).collect() }+ }++ #[test]+ fn only_our_server_py_under_us_or_orphaned_counts_as_ours() {+ let server = std::path::Path::new("/Users/x/Library/Application Support/lu-labs/mlx/server.py");+ let ours = ["/Users/x/Library/Application Support/lu-labs/mlx/venv/bin/python", "/Users/x/Library/Application Support/lu-labs/mlx/server.py"];+ assert!(is_our_sidecar(&listener(10, Some(500), &ours), server, 500), "started by this process");+ assert!(is_our_sidecar(&listener(10, Some(1), &ours), server, 500), "orphaned by an earlier run");+ // The sidecar of a second, still running LU of the same identity.+ assert!(!is_our_sidecar(&listener(10, Some(777), &ours), server, 500));+ // A test build or another identity: another data folder.+ let other = ["python", "/Users/x/Library/Application Support/lu-labs-n2/mlx/server.py"];+ assert!(!is_our_sidecar(&listener(10, Some(1), &other), server, 500));+ // Anything else on the port, and a process the table no longer knows.+ assert!(!is_our_sidecar(&listener(10, Some(500), &["nc", "-l", "47712"]), server, 500));+ assert!(!is_our_sidecar(&listener(10, None, &[]), server, 500));+ }++ #[test]+ fn a_test_build_never_sweeps_the_port() {+ // Drop for AppState runs the quit path in every test that builds one.+ // A real LU on this Mac keeps its sidecar on MLX_PORT through all of them.+ #[cfg(target_os = "macos")]+ assert!(sweep_orphaned_sidecar().is_empty());+ drop(crate::state::AppState::new());+ }++ /// A real listener: python3 running `script` that binds `port`.+ #[cfg(target_os = "macos")]+ fn python_listener(script: &std::path::Path, port: u16, via_shell: bool) -> Option<std::process::Child> {+ let python = ["/usr/bin/python3", "/opt/homebrew/bin/python3"].into_iter().find(|p| std::path::Path::new(p).exists())?;+ std::fs::write(+ script,+ "import socket,sys,time\ns=socket.socket()\ns.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)\ns.bind(('127.0.0.1',int(sys.argv[1])))\ns.listen(64)\ntime.sleep(60)\n",+ )+ .ok()?;+ let mut cmd = if via_shell {+ // A parent of its own between us and the listener: the second-LU case.+ let mut c = std::process::Command::new("/bin/sh");+ c.args(["-c", &format!("'{python}' -I '{}' {port} & wait", script.display())]);+ c+ } else {+ let mut c = std::process::Command::new(python);+ c.args(["-I", &script.display().to_string(), &port.to_string()]);+ c+ };+ let child = cmd.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).spawn().ok()?;+ for _ in 0..100 {+ if listening(port) {+ return Some(child);+ }+ std::thread::sleep(std::time::Duration::from_millis(50));+ }+ None+ }++ #[cfg(target_os = "macos")]+ fn free_port() -> u16 {+ std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()+ }++ #[cfg(target_os = "macos")]+ fn listening(port: u16) -> bool {+ !crate::process_util::listeners_on_port(port).is_empty()+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn a_foreign_listener_survives_the_sweep_and_our_own_sidecar_does_not() {+ let dir = tempfile::tempdir().unwrap();+ let ours = dir.path().join("server.py");++ // A stranger on the port (another program, another LU's own script).+ let port = free_port();+ let Some(mut foreign) = python_listener(&dir.path().join("foreign.py"), port, false) else {+ eprintln!("no python3 on this Mac, skipped");+ return;+ };+ assert!(sweep_sidecar_at(port, &ours).is_empty(), "a foreign listener was swept");+ assert!(listening(port), "the foreign listener died");+ let _ = foreign.kill();+ let _ = foreign.wait();++ // Our server.py, but under a parent that is not us: a second LU.+ let port = free_port();+ let mut second = python_listener(&ours, port, true).expect("listener under a shell");+ assert!(sweep_sidecar_at(port, &ours).is_empty(), "another LU's sidecar was swept");+ assert!(listening(port));+ crate::process_util::kill_pid_tree(second.id());+ let _ = second.wait();++ // Our server.py, started by this process: that one goes.+ let port = free_port();+ let mut own = python_listener(&ours, port, false).expect("own listener");+ let stopped = sweep_sidecar_at(port, &ours);+ assert_eq!(stopped, vec![own.id()]);+ let _ = own.wait();+ assert!(!listening(port), "our own sidecar is still listening");+ }}diff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rsindex 0b7021ea..641cafdc 100644--- a/src-tauri/src/commands/process.rs+++ b/src-tauri/src/commands/process.rs@@ -1533,6 +1533,12 @@ fn kill_port_owner(port: u16) {}}+/// Pure: may the CORS fix end the listener on the ComfyUI port? Only when the+/// port answers as ComfyUI, and never from a test build.+fn comfy_port_may_be_freed(answers_as_comfyui: bool, test_build: bool) -> bool {+ answers_as_comfyui && !test_build+}+/// One-click fix for the ComfyUI 0.19+ cross-origin block banner (#75/#82/// follow-up, 2026-07-17): stop the user-managed ComfyUI on the/// configured port and relaunch it under LU's management — LU-started@@ -1591,7 +1597,12 @@ fn fix_comfyui_cors_blocking(state: &AppState) -> Result<serde_json::Value, Stri*proc = None;}}- kill_port_owner(port);+ // Only a ComfyUI. The button exists for the ComfyUI behind the CORS+ // banner; whatever else listens on the port (another app, a second LU's+ // ComfyUI that stopped answering) is not this click's to end (N3, 3.1.0).+ if comfy_port_may_be_freed(is_comfyui_running_on_port(port), cfg!(test)) {+ kill_port_owner(port);+ }// Wait for the port to actually free up — start_comfyui short-circuits// with "already_running" while the old process is still winding down.@@ -6249,4 +6260,12 @@ mod boot_start_gpu_tests {assert!(call < spawn, "{name} applies the card after the spawn");}}++ #[test]+ fn the_cors_fix_ends_only_a_comfyui_and_never_from_a_test() {+ use super::comfy_port_may_be_freed;+ assert!(comfy_port_may_be_freed(true, false), "the ComfyUI behind the banner");+ assert!(!comfy_port_may_be_freed(false, false), "a stranger on the port");+ assert!(!comfy_port_may_be_freed(true, true), "a test build ends nothing");+ }}diff --git a/src-tauri/src/process_util.rs b/src-tauri/src/process_util.rsindex 7cc9c521..7db8fb09 100644--- a/src-tauri/src/process_util.rs+++ b/src-tauri/src/process_util.rs@@ -803,52 +803,65 @@ pub fn kill_pid_tree(pid: u32) {}}-/// Best-effort stop of whatever process is LISTENING on a local TCP port.-/// Used by the "Stop" buttons for port-bound backends the bridge didn't spawn-/// itself (so there's no `Child` handle to kill) — the MLX sidecar and the-/// Ollama server. Only the listener is targeted (`-sTCP:LISTEN`), so the-/// bridge's own client connections to that port aren't hit.-// Gated like its only caller (state.rs, app quit): on Windows and Linux the-// function had no caller and a unix-only body, and `-D warnings` on the-// Windows CI row rejected it as dead. The gate says where it is alive.+/// One process LISTENING on a local TCP port, as far as the process table+/// knows it: its parent and its argv.+#[cfg(any(target_os = "macos", test))]+#[derive(Debug, Clone, PartialEq)]+pub struct PortListener {+ pub pid: u32,+ pub parent: Option<u32>,+ pub cmd: Vec<String>,+}++/// Every process listening on `port` (`lsof -sTCP:LISTEN`, so the bridge's+/// own client connections to that port are not among them).#[cfg(target_os = "macos")]-pub fn kill_listeners_on_port(port: u16) {- #[cfg(unix)]- {- if let Ok(out) = Command::new("lsof")- .args(["-ti", &format!("tcp:{port}"), "-sTCP:LISTEN"])- .stderr(Stdio::null())- .output()- {- for pid in String::from_utf8_lossy(&out.stdout)- .split_whitespace()- .filter_map(|s| s.parse::<i32>().ok())- {- unsafe {- libc::kill(pid, libc::SIGTERM);- }+pub fn listeners_on_port(port: u16) -> Vec<PortListener> {+ let Ok(out) = foreign_system_command("lsof")+ .args(["-nP", "-ti", &format!("tcp:{port}"), "-sTCP:LISTEN"])+ .stderr(Stdio::null())+ .output()+ else {+ return Vec::new();+ };+ let table = process_table_with_cmdlines();+ String::from_utf8_lossy(&out.stdout)+ .split_whitespace()+ .filter_map(|s| s.parse::<u32>().ok())+ .map(|pid| {+ let process = table.process(sysinfo::Pid::from_u32(pid));+ PortListener {+ pid,+ parent: process.and_then(|p| p.parent()).map(|p| p.as_u32()),+ cmd: process.map(cmdline_of).unwrap_or_default(),}+ })+ .collect()+}++/// Stop the listeners on `port` that `owned` says are ours, and only those.+/// Returns the pids that were asked to stop.+///+/// Until 3.1.0 this was `kill_listeners_on_port`: SIGTERM to whatever listened+/// on the port, no questions asked (N2's finding, 13.11.2026). Its caller is+/// the quit path, and the quit path also runs in `Drop for AppState`, so every+/// `cargo test` that built and dropped an `AppState` ended the MLX sidecar of+/// the real LU running on the same Mac. A second LU, or a test build with its+/// own identity, lost its sidecar the same way when the other one quit. The+/// caller now names what it owns; a stranger on the port is left alone.+#[cfg(target_os = "macos")]+pub fn kill_own_listeners_on_port(port: u16, owned: impl Fn(&PortListener) -> bool) -> Vec<u32> {+ let mut stopped = Vec::new();+ for listener in listeners_on_port(port) {+ if listener.pid == std::process::id() || !owned(&listener) {+ continue;}- }- #[cfg(windows)]- {- if let Ok(out) = Command::new("cmd")- .args(["/C", &format!("netstat -ano -p tcp | findstr LISTENING | findstr :{port}")])- .stdout(Stdio::piped())- .stderr(Stdio::null())- .output()- {- for line in String::from_utf8_lossy(&out.stdout).lines() {- if let Some(pid) = line.split_whitespace().last() {- let _ = Command::new("taskkill")- .args(["/F", "/PID", pid])- .stdout(Stdio::null())- .stderr(Stdio::null())- .status();- }- }+ unsafe {+ libc::kill(listener.pid as i32, libc::SIGTERM);}+ stopped.push(listener.pid);}+ stopped}#[cfg(unix)]@@ -1380,13 +1393,14 @@ mod command_new_coverage_guard {}}-/// Windows-Gegenprobe, 09.10.2026: `kill_listeners_on_port` exists on the Mac+/// Windows-Gegenprobe, 09.10.2026: the MLX port sweep (since 3.1.0+/// `commands::mlx::sweep_orphaned_sidecar`) exists on the Mac/// alone, and a call without the same gate compiles on the Mac and nowhere/// else. `mlx.rs` had one, and the branch did not build on Windows. Nothing/// on a Mac says so, so this reads the sources on every platform.#[cfg(test)]mod mac_only_port_sweep_guard {- const CALL: &str = "kill_listeners_on_port(";+ const CALL: &str = "sweep_orphaned_sidecar(";const GATE: &str = "#[cfg(target_os = \"macos\")]";/// The lines that call the sweep without the gate on one of the three@@ -1435,10 +1449,10 @@ mod mac_only_port_sweep_guard {#[test]fn the_guard_sees_a_call_without_the_gate() {- let gated = "fn a() {\n #[cfg(target_os = \"macos\")]\n crate::process_util::kill_listeners_on_port(1);\n}\n";- let block = "fn a() {\n #[cfg(target_os = \"macos\")]\n {\n kill_listeners_on_port(1);\n }\n}\n";- let bare = "fn a() {\n stop();\n crate::process_util::kill_listeners_on_port(1);\n}\n";- let comment = "// kill_listeners_on_port(1) was here\n";+ let gated = "fn a() {\n #[cfg(target_os = \"macos\")]\n crate::commands::mlx::sweep_orphaned_sidecar();\n}\n";+ let block = "fn a() {\n #[cfg(target_os = \"macos\")]\n {\n sweep_orphaned_sidecar();\n }\n}\n";+ let bare = "fn a() {\n stop();\n crate::commands::mlx::sweep_orphaned_sidecar();\n}\n";+ let comment = "// sweep_orphaned_sidecar() was here\n";assert!(ungated_calls(gated).is_empty());assert!(ungated_calls(block).is_empty());assert!(ungated_calls(comment).is_empty());diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rsindex 44279efb..0b0e89d9 100644--- a/src-tauri/src/state.rs+++ b/src-tauri/src/state.rs@@ -754,10 +754,15 @@ impl AppState {crate::commands::music::stop();// And a character training, the same way.crate::commands::mlx::train::stop();+ // Only a sidecar of THIS app (its server.py, started by this process+ // or orphaned by an earlier run of it), and never from a test: this+ // path also runs in `Drop for AppState`, and `cargo test` ended the+ // real LU's sidecar through it (N2, 13.11.2026).#[cfg(target_os = "macos")]{- crate::process_util::kill_listeners_on_port(crate::commands::mlx::MLX_PORT);- println!("[MLX] image sidecar stopped (explicit shutdown)");+ if !crate::commands::mlx::sweep_orphaned_sidecar().is_empty() {+ println!("[MLX] image sidecar stopped (explicit shutdown)");+ }}// MLX installs: pip and the hub downloads. Each one registers the