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
tech(AS-10b/KF-7): das zweite stumme Gate bekommt Zaehne
Davidbda6cb90a948
diff --git a/src-tauri/src/commands/agent.rs b/src-tauri/src/commands/agent.rsindex ba66bf84..82563140 100644--- a/src-tauri/src/commands/agent.rs+++ b/src-tauri/src/commands/agent.rs@@ -447,7 +447,7 @@ pub(crate) fn execute_code_blocking(// resolution order as the file_* tools and shell_execute.let workspace = match workingDirectory.as_deref().map(str::trim).filter(|s| !s.is_empty()) {Some(wd) => PathBuf::from(wd),- None => agent_workspace(chatId.as_deref(), Some(&*state)),+ None => agent_workspace(chatId.as_deref(), Some(state)),};let _ = fs::create_dir_all(&workspace);diff --git a/src-tauri/src/commands/bg_tasks.rs b/src-tauri/src/commands/bg_tasks.rsindex fec51958..601438e0 100644--- a/src-tauri/src/commands/bg_tasks.rs+++ b/src-tauri/src/commands/bg_tasks.rs@@ -121,14 +121,32 @@ static REGISTRY: Lazy<BgRegistry> = Lazy::new(BgRegistry::default);/// the registry is one static shared by every test in this binary — so a test/// that sweeps and a test that is standing up a live task must not overlap, or/// the second one loses its child to the first one's quit. Both kinds hold this-/// lock. (Poisoning is ignored on purpose: a panicking test has already failed,-/// and turning that into a cascade of poisoned-lock failures hides which one.)+/// lock.+///+/// It is an ASYNC mutex, and that is not cosmetic. Every holder is a+/// `#[tokio::test]` that awaits while holding it — spawning a task, waiting for+/// its children, sleeping through a grace period — so a `std::sync::Mutex`+/// guard would live across those awaits. `clippy::await_holding_lock` flagged+/// exactly that at four of the six call sites (a fifth carried a hand-written+/// `#[allow]`), and the lint is right about the fact even though the deadlock+/// it warns about could not fire here: a `#[tokio::test]` is a current-thread+/// runtime whose only task is the test body, and nothing but these tests ever+/// takes this lock. What the std guard really cost was a parked OS thread per+/// waiting test and a rule that only held as long as nobody spawned a second+/// task. `tokio::sync::Mutex` removes both — waiters yield instead of blocking+/// their runtime — and it removes the lint honestly rather than silencing it.+///+/// Poisoning disappears with it, which is the behaviour that was wanted anyway:+/// the std version deliberately called `into_inner()` on a poisoned lock,+/// because a panicking test has already failed and turning that into a cascade+/// of poisoned-lock failures hides which one. A tokio mutex simply hands the+/// next waiter the lock.#[cfg(test)]-static SWEEP_ISOLATION: Mutex<()> = Mutex::new(());+static SWEEP_ISOLATION: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());#[cfg(test)]-fn sweep_isolation() -> std::sync::MutexGuard<'static, ()> {- SWEEP_ISOLATION.lock().unwrap_or_else(|e| e.into_inner())+async fn sweep_isolation() -> tokio::sync::MutexGuard<'static, ()> {+ SWEEP_ISOLATION.lock().await}/// Start arguments for a task that keeps a CHILD process of its own alive —@@ -584,7 +602,7 @@ fn arm_exit_sweep() {}pub(crate) async fn shell_task_list_impl(_args: &Value) -> CmdResult {let mut tasks = REGISTRY.list();// Reverse-chronological — newest first reads better in the UI.- tasks.sort_by(|a, b| b.started_at.cmp(&a.started_at));+ tasks.sort_by_key(|t| std::cmp::Reverse(t.started_at));Ok(json!({ "tasks": tasks }))}@@ -737,7 +755,7 @@ mod cancel_tests {/// mechanism in disguise.#[tokio::test]async fn cancelling_takes_the_grandchild_with_it() {- let _isolation = super::sweep_isolation();+ let _isolation = super::sweep_isolation().await;let start = shell_task_start_impl(&super::a_task_that_starts_a_child()).await.expect("start");@@ -777,7 +795,7 @@ mod shutdown_sweep_tests {#[tokio::test]#[cfg(unix)]async fn quitting_takes_a_running_task_and_its_children_with_it() {- let _isolation = super::sweep_isolation();+ let _isolation = super::sweep_isolation().await;let start = shell_task_start_impl(&super::a_task_that_starts_a_child()).await.expect("start");@@ -856,7 +874,7 @@ mod shutdown_sweep_tests {}}- let _isolation = super::sweep_isolation();+ let _isolation = super::sweep_isolation().await;let start = shell_task_start_impl(&super::a_task_that_starts_a_child()).await.expect("start");@@ -929,7 +947,7 @@ mod shutdown_sweep_tests {#[tokio::test]#[cfg(unix)]async fn a_reaped_pid_is_gone_from_the_registry_the_instant_it_is_freed() {- let _isolation = super::sweep_isolation();+ let _isolation = super::sweep_isolation().await;let start = shell_task_start_impl(&json!({// The shell exits at once; the grandchild inherits stdout and keeps// the reader task running long after the shell has been reaped.@@ -980,7 +998,7 @@ mod shutdown_sweep_tests {/// must never fire at it. Sweeping an idle registry must also not panic.#[tokio::test]async fn a_finished_task_is_not_swept() {- let _isolation = super::sweep_isolation();+ let _isolation = super::sweep_isolation().await;let start = shell_task_start_impl(&super::a_task_that_finishes_at_once()).await.expect("start");@@ -1187,15 +1205,14 @@ mod foreground_parity_tests {/// contract on both paths, which is the property that has to keep holding/// for the Windows one to stay true.///- /// The isolation guard is a plain `Mutex` held across the awaits below, on- /// purpose and like every other test here that stands up a live task: it is- /// what keeps the shutdown-sweep tests from killing this task's child- /// mid-run. There is nothing to deadlock against — the lock is only ever- /// taken by tests, never by the code under test.- #[allow(clippy::await_holding_lock)]+ /// The isolation guard is held across the awaits below, on purpose and like+ /// every other test here that stands up a live task: it is what keeps the+ /// shutdown-sweep tests from killing this task's child mid-run. It used to+ /// carry an `#[allow(clippy::await_holding_lock)]` for that; the lock is an+ /// async mutex now, so there is nothing left to allow.#[tokio::test]async fn a_named_shell_behaves_the_same_in_the_background_as_in_the_foreground() {- let _isolation = super::sweep_isolation();+ let _isolation = super::sweep_isolation().await;let dir = a_directory();let (foreground, fg_code) = what_the_foreground_printed(&dir).await;diff --git a/src-tauri/src/commands/download.rs b/src-tauri/src/commands/download.rsindex 548c2cbd..155a75a2 100644--- a/src-tauri/src/commands/download.rs+++ b/src-tauri/src/commands/download.rs@@ -17,7 +17,7 @@ use crate::state::{AppState, DownloadProgress};/// Menu\\Programs\\Startup\\x.bat") can't escape the target directory and drop/// an autostart payload. Falls back to "download" if nothing usable remains.fn sanitize_filename(name: &str) -> String {- let base = name.rsplit(|c| c == '/' || c == '\\').next().unwrap_or("");+ let base = name.rsplit(['/', '\\']).next().unwrap_or("");let cleaned: String = base.chars().filter(|c| !matches!(c, '/' | '\\' | ':' | '\0')).collect();let cleaned = cleaned.trim();if cleaned.is_empty() || cleaned == "." || cleaned == ".." {@@ -300,7 +300,8 @@ pub async fn download_model(let filename_clone = filename.clone();tokio::spawn(async move {- match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset, expected_bytes, expected_sha256).await {+ match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset,+ CatalogClaims { expected_bytes, expected_sha256 }).await {Ok(_) => {if let Ok(mut dl) = downloads_arc.lock() {if let Some(p) = dl.get_mut(&id_clone) {@@ -646,6 +647,20 @@ async fn digest_of_prefix(path: &Path, len: u64) -> Result<Sha256, String> {Ok(hasher)}+/// What the catalog entry claims about the file, as opposed to what the server+/// says on the wire. The two travel together everywhere and are the only+/// arguments `do_download` takes that are not about the transfer itself, so+/// they ride as one — which also puts the argument count back under+/// `clippy::too_many_arguments`'s threshold without an `allow`.+struct CatalogClaims {+ /// Catalog estimate. Plans the space guard when the server states no length;+ /// never decides that a transfer is finished.+ expected_bytes: Option<u64>,+ /// Digest from the catalog entry, already normalised. `None` means the+ /// content of this file cannot be verified at all.+ expected_sha256: Option<String>,+}+async fn do_download(url: &str,dest: &PathBuf,@@ -653,13 +668,9 @@ async fn do_download(id: &str,token: CancellationToken,resume_offset: u64,- // Catalog estimate. Plans the space guard when the server states no length;- // never decides that a transfer is finished.- expected_bytes: Option<u64>,- // Digest from the catalog entry, already normalised. `None` means the- // content of this file cannot be verified at all.- expected_sha256: Option<String>,+ claims: CatalogClaims,) -> Result<(), String> {+ let CatalogClaims { expected_bytes, expected_sha256 } = claims;// SSRF guard: model downloads come from public catalogs (HuggingFace,// civitai, ollama). Block private/loopback/metadata hosts and re-validate// every redirect hop so a crafted catalog/model URL can't pull from an@@ -1234,7 +1245,7 @@ fn scan_for_partials(roots: Vec<PathBuf>, live: Vec<String>) -> Vec<OrphanDownlo}}// Biggest first: that is the one whose loss would hurt most.- out.sort_by(|a, b| b.bytes.cmp(&a.bytes));+ out.sort_by_key(|o| std::cmp::Reverse(o.bytes));out}@@ -1324,7 +1335,8 @@ pub async fn resume_download(let id_clone = id.clone();tokio::spawn(async move {- match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset, expected_bytes, expected_sha256).await {+ match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset,+ CatalogClaims { expected_bytes, expected_sha256 }).await {Ok(_) => {if let Ok(mut dl) = downloads_arc.lock() {if let Some(p) = dl.get_mut(&id_clone) {@@ -1563,7 +1575,8 @@ pub async fn download_model_to_path(let filename_clone = filename.clone();tokio::spawn(async move {- match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset, expected_bytes, expected_sha256).await {+ match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset,+ CatalogClaims { expected_bytes, expected_sha256 }).await {Ok(_) => {if let Ok(mut dl) = downloads_arc.lock() {if let Some(p) = dl.get_mut(&id_clone) {diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rsindex 0db95afa..621c3165 100644--- a/src-tauri/src/commands/engine.rs+++ b/src-tauri/src/commands/engine.rs@@ -321,13 +321,19 @@ pub(crate) fn split_shard_stem(stem: &str) -> Option<(&str, u32, u32)> {/// "models" that can never load. A set with missing parts is not listed at/// all, so a paused or aborted multi-part download never impersonates an/// installed model (same rule a9ea114 established for MLX downloads).+/// Accumulator for multi-part GGUF sets: `(dir, base, total)` →+/// `(part numbers seen, path of part 1, byte sum)`.+///+/// The directory is part of the key: two unrelated split sets that share a base+/// name in different subfolders must never merge into one entry. Named because+/// the bare type is what `clippy::type_complexity` fires on, and a name says+/// what the tuples mean better than the tuples do.+type GgufSplitSets =+ std::collections::HashMap<(PathBuf, String, u32), (Vec<u32>, Option<String>, u64)>;+pub(crate) fn scan_gguf_models(dir: &Path) -> Vec<BundledModel> {let mut out = Vec::new();- // (dir, base, total) → (part-numbers seen, path of part 1, byte sum).- // The directory is part of the key: two unrelated split sets that share a- // base name in different subfolders must never merge into one entry.- let mut sets: std::collections::HashMap<(PathBuf, String, u32), (Vec<u32>, Option<String>, u64)> =- std::collections::HashMap::new();+ let mut sets: GgufSplitSets = GgufSplitSets::new();scan_gguf_dir(dir, 0, &mut out, &mut sets);for ((_dir, base, total), (mut parts, first_path, size)) in sets {parts.sort_unstable();@@ -370,7 +376,7 @@ fn scan_gguf_dir(dir: &Path,depth: usize,out: &mut Vec<BundledModel>,- sets: &mut std::collections::HashMap<(PathBuf, String, u32), (Vec<u32>, Option<String>, u64)>,+ sets: &mut GgufSplitSets,) {let entries = match std::fs::read_dir(dir) {Ok(e) => e,@@ -988,7 +994,7 @@ fn spawn_engine_attempt(args: args.to_vec(),});- let outcome = wait_for_health_or_exit(&**state, port, health_timeout_for(model_path));+ let outcome = wait_for_health_or_exit(state, port, health_timeout_for(model_path));if matches!(outcome, HealthWait::Ready) {// Health said OK, but was it OUR child that answered? A spawn that// loses the port to an orphaned llama-server (left behind by a crasheddiff --git a/src-tauri/src/commands/gguf.rs b/src-tauri/src/commands/gguf.rsindex ca082d4e..a41876aa 100644--- a/src-tauri/src/commands/gguf.rs+++ b/src-tauri/src/commands/gguf.rs@@ -66,8 +66,8 @@ fn fixed_size(ty: u32) -> Option<u64> {match ty {0 | 1 | 7 => Some(1), // u8 / i8 / bool2 | 3 => Some(2), // u16 / i16- 4 | 5 | 6 => Some(4), // u32 / i32 / f32- 10 | 11 | 12 => Some(8), // u64 / i64 / f64+ 4..=6 => Some(4), // u32 / i32 / f32+ 10..=12 => Some(8), // u64 / i64 / f64_ => None, // 8 = string, 9 = array, unknown}}diff --git a/src-tauri/src/commands/gpu.rs b/src-tauri/src/commands/gpu.rsindex 37e41570..65f84233 100644--- a/src-tauri/src/commands/gpu.rs+++ b/src-tauri/src/commands/gpu.rs@@ -149,8 +149,17 @@ fn note_for(vendor: &str) -> Option<String> {}}-#[cfg(target_os = "linux")]+/// `if cfg!` and not `#[cfg]`, for the same reason the parser below gives for+/// itself: with a `#[cfg(target_os = "linux")]` here plus a stub for everyone+/// else, `detect_other_via_lspci_from` and `lspci_device_name` have no caller+/// at all in a macOS or Windows build — so they compile, they are tested, and+/// rustc still reports them as dead code. Gating at run time on a constant+/// keeps the chain intact everywhere (the early return folds away) and lets+/// `-D warnings` stay on without an `allow` per parser.fn detect_other_via_lspci(have_rocm: bool) -> Vec<DetectedGpu> {+ if !cfg!(target_os = "linux") {+ return vec![];+ }// Best-effort fallback for Intel iGPUs / Intel Arc / Apple-Silicon-in-VM// when neither nvidia-smi nor rocm-smi cover them. `lspci -nn | grep VGA`// gives "00:02.0 VGA compatible controller [0300]: Intel Corporation@@ -238,9 +247,6 @@ fn lspci_device_name(line: &str) -> String {if out.is_empty() { "GPU".to_string() } else { out }}-#[cfg(not(target_os = "linux"))]-fn detect_other_via_lspci(_have_rocm: bool) -> Vec<DetectedGpu> { vec![] }-#[cfg(target_os = "macos")]fn detect_macos() -> Vec<DetectedGpu> {// macOS uses Metal/MPS via the unified GPU. We surface a single entry so@@ -374,8 +380,16 @@ fn windows_fallback_from(}}-#[cfg(target_os = "windows")]+/// `if cfg!` and not `#[cfg]`, same reason as `detect_other_via_lspci`: this is+/// the only caller of `parse_reg_query`, `parse_reg_hex`, `adapter_subkey`,+/// `windows_fallback_from`, `detect_other_via_registry_from` and+/// `detect_other_via_wmic_from`, all of which are deliberately compiled and+/// tested on every platform. Gating the caller with `#[cfg]` orphaned the lot+/// of them in a macOS build.fn detect_other_on_windows(have_rocm: bool) -> Vec<DetectedGpu> {+ if !cfg!(target_os = "windows") {+ return vec![];+ }// Microsoft disabled wmic.exe by default in Windows 11 23H2 and 24H2 and// removed it outright in the August 2026 servicing update, where it is no// longer even a Feature on Demand. It used to be this module's only way to@@ -469,9 +483,6 @@ fn detect_other_via_wmic_from(gpus}-#[cfg(not(target_os = "windows"))]-fn detect_other_on_windows(_have_rocm: bool) -> Vec<DetectedGpu> { vec![] }-/// Class GUID of the display-adapter registry branch, lowercase, as/// `adapter_subkey` matches it. Microsoft lists it as the "Display Adapters"/// setup class, and the software key of every display adapter is created under@@ -896,7 +907,7 @@ End of search: 3 match(es) found.use super::lspci_device_name;// NEGATIVE CONTROL: the old expression, which was fine while only// Intel reached this branch and is nonsense for anything else.- let old_rule = LSPCI_AMD.split(':').last().unwrap();+ let old_rule = LSPCI_AMD.split(':').next_back().unwrap();assert_eq!(old_rule.trim(), "7550] (rev c0)");assert_eq!(diff --git a/src-tauri/src/commands/install.rs b/src-tauri/src/commands/install.rsindex 1899b8b9..201f6c76 100644--- a/src-tauri/src/commands/install.rs+++ b/src-tauri/src/commands/install.rs@@ -545,7 +545,7 @@ pub fn pip_install_streaming_with_retry_cancellable(Ok(Some(s)) => break s,Ok(None) => {tick += 1;- if tick % 5 == 0 {+ if tick.is_multiple_of(5) {let total = announced_total.load(Ordering::Relaxed);if total > 0 {if let Some(read) = process_read_bytes(pid) {@@ -2079,6 +2079,11 @@ pub fn linux_python_install_hint(os_release: &str) -> String {/// Missing → "install Git for Windows", NonNative → "WSL/non-native git on/// PATH may break Windows-path clones", Native → proceed.#[derive(Debug, Clone, PartialEq, Eq)]+/// Dead on every non-Windows target and deliberately so: the only production+/// caller is `windows_git_probe`, which needs `CommandExt::creation_flags` and+/// therefore cannot be compiled off Windows. Keeping THIS half uncfg'd is what+/// lets the unit tests below prove the Windows classification on a macOS run.+#[cfg_attr(not(target_os = "windows"), allow(dead_code))]pub enum WindowsGitState {/// `git --version` failed to run (not installed or not on PATH).Missing,@@ -2092,6 +2097,11 @@ pub enum WindowsGitState {/// Pure helper for testability. Classifies a `git --version` invocation/// from its stdout (trimmed) plus the spawn/exit status.+/// Dead on every non-Windows target and deliberately so: the only production+/// caller is `windows_git_probe`, which needs `CommandExt::creation_flags` and+/// therefore cannot be compiled off Windows. Keeping THIS half uncfg'd is what+/// lets the unit tests below prove the Windows classification on a macOS run.+#[cfg_attr(not(target_os = "windows"), allow(dead_code))]pub fn windows_git_probe_from_output(stdout: &str, exited_successfully: bool) -> WindowsGitState {if !exited_successfully {return WindowsGitState::Missing;@@ -2125,6 +2135,11 @@ pub fn windows_git_probe() -> WindowsGitState {/// User-facing hint for the probed state. Returns `None` for Native (no hint/// needed). For Missing the hint is fatal; for NonNative it's a soft warning.+/// Dead on every non-Windows target and deliberately so: the only production+/// caller is `windows_git_probe`, which needs `CommandExt::creation_flags` and+/// therefore cannot be compiled off Windows. Keeping THIS half uncfg'd is what+/// lets the unit tests below prove the Windows classification on a macOS run.+#[cfg_attr(not(target_os = "windows"), allow(dead_code))]pub fn windows_git_install_hint(state: &WindowsGitState) -> Option<String> {match state {WindowsGitState::Native => None,@@ -2689,6 +2704,10 @@ fn install_ollama_linux_impl<F: Fn(&str, &str)>(/// Bug G revisit — distro-specific install command for `ollama`. Same parsing/// shape as `linux_python_install_hint` (ID + ID_LIKE tokens, quoted values/// handled). Falls back to ollama.com/install.sh for unknown distros.+/// Dead off Linux: the only production caller is `install_ollama_linux_impl`,+/// which is `#[cfg(target_os = "linux")]` as a whole. The function itself is+/// left compiled everywhere so its distro table stays unit-tested here.+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]pub fn linux_ollama_install_hint(os_release: &str) -> String {let mut families: Vec<String> = Vec::new();for line in os_release.lines() {@@ -2970,11 +2989,6 @@ fn lmstudio_path_from_registry() -> Option<PathBuf> {None}-#[cfg(not(target_os = "windows"))]-fn lmstudio_path_from_registry() -> Option<PathBuf> {- None-}-/// Path to the LM Studio GUI executable on Windows. We only need to launch/// this in the rare case where `lms bootstrap` from the pre-bootstrap binary/// reports success but `~/.lmstudio/` is still missing — some installs@@ -3063,8 +3077,7 @@ pub fn install_lmstudio(state: State<'_, AppState>) -> Result<serde_json::Value,// AppImage whose URL rotates with every release, so we can't// mirror it from a stable in-binary string — surface a clear// download pointer instead of pretending to auto-install.- #[cfg(target_os = "linux")]- {+ if cfg!(target_os = "linux") {update("error","LM Studio's Linux distribution is an AppImage with a URL that \@@ -3074,216 +3087,233 @@ pub fn install_lmstudio(state: State<'_, AppState>) -> Result<serde_json::Value,Tip: if you prefer the CLI-only path, the `lms` CLI ships with \the AppImage and lands at ~/.lmstudio/bin/lms after first run.",);- return;}- #[cfg(target_os = "macos")]- {+ if cfg!(target_os = "macos") {update("error","On macOS, download LM Studio.app from https://lmstudio.ai/download, \drag it to /Applications, launch it once to finish setup, then \come back to LU and click Re-detect.",);- return;}- // Pre-check: if LM Studio is already installed (an `lms.exe` is- // findable in any of the locations `lmstudio_lms_path()` knows about)- // we skip the ~570 MB download entirely. Re-installing on a box where- // it's already there was the previous behaviour and made the- // "LM Studio detected but server offline" Plug-and-Play scenario- // turn into a 5-minute no-op download. The bootstrap + server-start- // steps below are idempotent, so the same code path now serves both- // first-install and offline-reactivation users.- let already_installed = lmstudio_lms_path().is_some();- if already_installed && lmstudio_server_running() {- update(- "complete",- "LM Studio is already installed and the server is up on localhost:1234.",- );- return;- }+ // ── The Windows path ────────────────────────────────────────────────+ //+ // Everything below is the winget install. It used to sit behind the two+ // `return`s above, which made rustc call it an `unreachable statement`+ // on macOS and Linux — correct about the control flow, and saying+ // nothing about the code: this is not dead code, it is the OTHER+ // platform's implementation.+ //+ // `if cfg!` and not `#[cfg]`, for the reason `test_support.rs` states at+ // its top: a `#[cfg]` would delete this whole branch from a macOS build,+ // and with it the type-checking of ~150 lines of Windows installer plus+ // the dozen helpers it is the only caller of (`sha256_file`,+ // `installer_size_verdict`, `windows_git_probe_from_output` …), which+ // would then read as dead code here. Compiled-and-never-taken keeps the+ // Windows half honest on the machine this is developed on.+ //+ // The condition is `not(linux or macos)` rather than `windows` so the+ // set of targets that run it is exactly the set that ran it before.+ if !cfg!(any(target_os = "linux", target_os = "macos")) {+ // Pre-check: if LM Studio is already installed (an `lms.exe` is+ // findable in any of the locations `lmstudio_lms_path()` knows about)+ // we skip the ~570 MB download entirely. Re-installing on a box where+ // it's already there was the previous behaviour and made the+ // "LM Studio detected but server offline" Plug-and-Play scenario+ // turn into a 5-minute no-op download. The bootstrap + server-start+ // steps below are idempotent, so the same code path now serves both+ // first-install and offline-reactivation users.+ let already_installed = lmstudio_lms_path().is_some();+ if already_installed && lmstudio_server_running() {+ update(+ "complete",+ "LM Studio is already installed and the server is up on localhost:1234.",+ );+ return;+ }- if already_installed {- update(- "starting",- "LM Studio is already installed — skipping download. Bootstrapping CLI and starting server…",- );- } else {- let temp_dir = std::env::temp_dir();- let installer_path = temp_dir.join("LMStudioSetup.exe");-- println!("[LMStudio] Downloading {}", LMSTUDIO_INSTALLER_URL);- if let Err(e) =- download_file_blocking(LMSTUDIO_INSTALLER_URL, &installer_path, &lms_state)- {- let err = format!(- "Download failed: {}. If the network is fine, the installer URL may have rotated — fall back to https://lmstudio.ai/download in your browser.",- e- );- println!("[LMStudio] {}", err);- update("error", &err);- return;- }+ if already_installed {+ update(+ "starting",+ "LM Studio is already installed — skipping download. Bootstrapping CLI and starting server…",+ );+ } else {+ let temp_dir = std::env::temp_dir();+ let installer_path = temp_dir.join("LMStudioSetup.exe");++ println!("[LMStudio] Downloading {}", LMSTUDIO_INSTALLER_URL);+ if let Err(e) =+ download_file_blocking(LMSTUDIO_INSTALLER_URL, &installer_path, &lms_state)+ {+ let err = format!(+ "Download failed: {}. If the network is fine, the installer URL may have rotated — fall back to https://lmstudio.ai/download in your browser.",+ e+ );+ println!("[LMStudio] {}", err);+ update("error", &err);+ return;+ }- // OI-8: verified before it is executed. See- // LMSTUDIO_INSTALLER_SHA256 for why the digest pin is not filled- // in yet and what filling it in takes.- if let Err(e) = verify_downloaded_installer(- &installer_path,- LMSTUDIO_INSTALLER_SHA256,- LMSTUDIO_INSTALLER_BYTES,- "LM Studio",- ) {- let _ = fs::remove_file(&installer_path);- println!("[LMStudio] {}", e);- update("error", &e);- return;- }+ // OI-8: verified before it is executed. See+ // LMSTUDIO_INSTALLER_SHA256 for why the digest pin is not filled+ // in yet and what filling it in takes.+ if let Err(e) = verify_downloaded_installer(+ &installer_path,+ LMSTUDIO_INSTALLER_SHA256,+ LMSTUDIO_INSTALLER_BYTES,+ "LM Studio",+ ) {+ let _ = fs::remove_file(&installer_path);+ println!("[LMStudio] {}", e);+ update("error", &e);+ return;+ }- update(- "installing",- "Download complete. Running silent installer (this can take a minute)...",- );+ update(+ "installing",+ "Download complete. Running silent installer (this can take a minute)...",+ );- // electron-builder NSIS supports /S for silent install. Ignore exit- // code: real failures surface via the absence of lms.exe afterwards.- let mut cmd = Command::new(&installer_path);- cmd.arg("/S");- #[cfg(target_os = "windows")]- cmd.creation_flags(CREATE_NO_WINDOW);- match cmd.output() {- Ok(_) => println!("[LMStudio] Installer finished"),- Err(e) => {- let err = format!("Could not run installer: {}", e);- println!("[LMStudio] {}", err);- update("error", &err);- return;+ // electron-builder NSIS supports /S for silent install. Ignore exit+ // code: real failures surface via the absence of lms.exe afterwards.+ let mut cmd = Command::new(&installer_path);+ cmd.arg("/S");+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);+ match cmd.output() {+ Ok(_) => println!("[LMStudio] Installer finished"),+ Err(e) => {+ let err = format!("Could not run installer: {}", e);+ println!("[LMStudio] {}", err);+ update("error", &err);+ return;+ }+ }++ let _ = fs::remove_file(&installer_path);}- }- let _ = fs::remove_file(&installer_path);- }+ // Bootstrap the lms CLI. We do this in two passes:+ // (1) Run `lms bootstrap` from whatever path `lmstudio_lms_path()`+ // resolves — on a fresh install that's the pre-bootstrap binary+ // inside `resources/app/.webpack/lms.exe`. This alone is enough+ // on most boxes.+ // (2) Verify that ~/.lmstudio/bin/lms.exe now exists. If not, some+ // LM Studio builds require the GUI to run once to populate+ // ~/.lmstudio/ before the bootstrap registers a launcher there.+ // In that case we briefly launch the GUI, wait for ~/.lmstudio/+ // to appear, retry bootstrap, then move on. The user sees the+ // GUI flash up — not ideal, but strictly better than the old+ // "Open LM Studio once from the Start menu" error dialog and a+ // failed install.+ update("starting", "Bootstrapping `lms` CLI...");+ let initial_lms = lmstudio_lms_path();+ match &initial_lms {+ Some(p) => {+ let mut bs = Command::new(p);+ bs.arg("bootstrap");+ #[cfg(target_os = "windows")]+ bs.creation_flags(CREATE_NO_WINDOW);+ let _ = bs.output();+ }+ None => {+ update(+ "error",+ "LM Studio installed but `lms.exe` not found in any expected location. \+ The installer may have failed silently. Try installing LM Studio manually \+ from https://lmstudio.ai/download and then click Re-Scan.",+ );+ return;+ }+ }- // Bootstrap the lms CLI. We do this in two passes:- // (1) Run `lms bootstrap` from whatever path `lmstudio_lms_path()`- // resolves — on a fresh install that's the pre-bootstrap binary- // inside `resources/app/.webpack/lms.exe`. This alone is enough- // on most boxes.- // (2) Verify that ~/.lmstudio/bin/lms.exe now exists. If not, some- // LM Studio builds require the GUI to run once to populate- // ~/.lmstudio/ before the bootstrap registers a launcher there.- // In that case we briefly launch the GUI, wait for ~/.lmstudio/- // to appear, retry bootstrap, then move on. The user sees the- // GUI flash up — not ideal, but strictly better than the old- // "Open LM Studio once from the Start menu" error dialog and a- // failed install.- update("starting", "Bootstrapping `lms` CLI...");- let initial_lms = lmstudio_lms_path();- match &initial_lms {- Some(p) => {- let mut bs = Command::new(p);- bs.arg("bootstrap");- #[cfg(target_os = "windows")]- bs.creation_flags(CREATE_NO_WINDOW);- let _ = bs.output();- }- None => {- update(- "error",- "LM Studio installed but `lms.exe` not found in any expected location. \- The installer may have failed silently. Try installing LM Studio manually \- from https://lmstudio.ai/download and then click Re-Scan.",- );- return;- }- }+ // Did pass 1 produce ~/.lmstudio/bin/lms.exe? If yes, skip the GUI+ // dance entirely. If no, fall back to launching the GUI so it seeds+ // its user-data dir, then retry bootstrap.+ let post_bootstrap_path = dirs::home_dir()+ .map(|h| h.join(".lmstudio").join("bin").join("lms.exe"));+ let needs_gui_seed = post_bootstrap_path+ .as_ref()+ .map(|p| !p.exists())+ .unwrap_or(true);++ if needs_gui_seed {+ update(+ "starting",+ "Launching LM Studio briefly to finalise CLI setup (you may see the window flash)...",+ );+ if let Some(gui) = lmstudio_gui_exe() {+ let mut g = Command::new(&gui);+ #[cfg(target_os = "windows")]+ g.creation_flags(CREATE_NO_WINDOW);+ let _ = g.spawn();+ }- // Did pass 1 produce ~/.lmstudio/bin/lms.exe? If yes, skip the GUI- // dance entirely. If no, fall back to launching the GUI so it seeds- // its user-data dir, then retry bootstrap.- let post_bootstrap_path = dirs::home_dir()- .map(|h| h.join(".lmstudio").join("bin").join("lms.exe"));- let needs_gui_seed = post_bootstrap_path- .as_ref()- .map(|p| !p.exists())- .unwrap_or(true);-- if needs_gui_seed {- update(- "starting",- "Launching LM Studio briefly to finalise CLI setup (you may see the window flash)...",- );- if let Some(gui) = lmstudio_gui_exe() {- let mut g = Command::new(&gui);- #[cfg(target_os = "windows")]- g.creation_flags(CREATE_NO_WINDOW);- let _ = g.spawn();- }+ // Wait up to 30 s for ~/.lmstudio/ to appear. The first GUI launch+ // typically writes this within 3–8 s, but on a slow VM 30 s is a+ // safer ceiling than failing the install.+ let lmstudio_dir = dirs::home_dir().map(|h| h.join(".lmstudio"));+ for _ in 0..30 {+ std::thread::sleep(std::time::Duration::from_secs(1));+ if let Some(d) = &lmstudio_dir {+ if d.exists() {+ break;+ }+ }+ }- // Wait up to 30 s for ~/.lmstudio/ to appear. The first GUI launch- // typically writes this within 3–8 s, but on a slow VM 30 s is a- // safer ceiling than failing the install.- let lmstudio_dir = dirs::home_dir().map(|h| h.join(".lmstudio"));- for _ in 0..30 {- std::thread::sleep(std::time::Duration::from_secs(1));- if let Some(d) = &lmstudio_dir {- if d.exists() {- break;+ // Retry bootstrap from the (now possibly different) lms.exe.+ // After GUI launch the .lmstudio dir might already contain a+ // launcher; if not, the pre-bootstrap path is still valid.+ if let Some(p) = lmstudio_lms_path() {+ let mut bs = Command::new(&p);+ bs.arg("bootstrap");+ #[cfg(target_os = "windows")]+ bs.creation_flags(CREATE_NO_WINDOW);+ let _ = bs.output();}}- }- // Retry bootstrap from the (now possibly different) lms.exe.- // After GUI launch the .lmstudio dir might already contain a- // launcher; if not, the pre-bootstrap path is still valid.- if let Some(p) = lmstudio_lms_path() {- let mut bs = Command::new(&p);- bs.arg("bootstrap");- #[cfg(target_os = "windows")]- bs.creation_flags(CREATE_NO_WINDOW);- let _ = bs.output();- }- }-- // Start the embedded server. `lms server start` is non-blocking — it- // detaches a background httpd. --cors so LU's web view (which is on a- // tauri:// origin) isn't blocked by the SOP. Port matches the- // provider-store default of 1234 so user config Just Works.- // Re-resolve the path because the bootstrap dance above may have- // promoted us from the pre-bootstrap path to ~/.lmstudio/bin/lms.exe.- update("starting", "Starting LM Studio server on port 1234...");- if let Some(p) = lmstudio_lms_path() {- let mut srv = Command::new(&p);- srv.args(["server", "start", "--cors", "--port"])- .arg(LMSTUDIO_DEFAULT_PORT.to_string())- .stdout(Stdio::null())- .stderr(Stdio::null());- #[cfg(target_os = "windows")]- srv.creation_flags(CREATE_NO_WINDOW);- let _ = srv.spawn();- }+ // Start the embedded server. `lms server start` is non-blocking — it+ // detaches a background httpd. --cors so LU's web view (which is on a+ // tauri:// origin) isn't blocked by the SOP. Port matches the+ // provider-store default of 1234 so user config Just Works.+ // Re-resolve the path because the bootstrap dance above may have+ // promoted us from the pre-bootstrap path to ~/.lmstudio/bin/lms.exe.+ update("starting", "Starting LM Studio server on port 1234...");+ if let Some(p) = lmstudio_lms_path() {+ let mut srv = Command::new(&p);+ srv.args(["server", "start", "--cors", "--port"])+ .arg(LMSTUDIO_DEFAULT_PORT.to_string())+ .stdout(Stdio::null())+ .stderr(Stdio::null());+ #[cfg(target_os = "windows")]+ srv.creation_flags(CREATE_NO_WINDOW);+ let _ = srv.spawn();+ }- // Wait for the server to respond. LM Studio's server typically takes- // ~3-5 s to bind in a fresh install (it loads its model index first).- update("starting", "Waiting for LM Studio server...");- let mut ready = false;- for i in 0..15 {- std::thread::sleep(std::time::Duration::from_secs(2));- if lmstudio_server_running() {- ready = true;- break;- }- println!("[LMStudio] Server not ready, attempt {}/15", i + 1);- }+ // Wait for the server to respond. LM Studio's server typically takes+ // ~3-5 s to bind in a fresh install (it loads its model index first).+ update("starting", "Waiting for LM Studio server...");+ let mut ready = false;+ for i in 0..15 {+ std::thread::sleep(std::time::Duration::from_secs(2));+ if lmstudio_server_running() {+ ready = true;+ break;+ }+ println!("[LMStudio] Server not ready, attempt {}/15", i + 1);+ }- if ready {- update("complete", "LM Studio server is up on localhost:1234.");- } else {- update(- "error",- "LM Studio installed but the server didn't come up. Open LM Studio from the Start menu and toggle the Server tab on, then click Re-Scan.",- );+ if ready {+ update("complete", "LM Studio server is up on localhost:1234.");+ } else {+ update(+ "error",+ "LM Studio installed but the server didn't come up. Open LM Studio from the Start menu and toggle the Server tab on, then click Re-Scan.",+ );+ }}});@@ -3647,8 +3677,7 @@ pub fn install_python(state: State<'_, AppState>) -> Result<serde_json::Value, S// button rarely needs to fire — but when it does, surfacing the// right distro-specific install command beats a cryptic spawn// error.- #[cfg(target_os = "linux")]- {+ if cfg!(target_os = "linux") {let os_release = std::fs::read_to_string("/etc/os-release").unwrap_or_default();let suggestion = linux_python_install_hint(&os_release);update(@@ -3660,161 +3689,178 @@ pub fn install_python(state: State<'_, AppState>) -> Result<serde_json::Value, Ssuggestion),);- return;}- #[cfg(target_os = "macos")]- {+ if cfg!(target_os = "macos") {update("error","Python isn't installed system-wide. On macOS, install it via \`brew install python` (Homebrew) or download Python 3.12+ from \https://www.python.org/downloads/macos/ then click Re-detect.",);- return;}- // Stream-friendly winget invocation. `--silent --accept-*-agreements`- // drops the EULA prompts; without them winget will sit and wait for- // user input forever inside our background thread. Python.Python.3.12- // is the canonical winget id for the python.org installer (matches- // `winget search python` top result).- update("installing", "Running: winget install Python.Python.3.12 --silent --accept-package-agreements --accept-source-agreements");-- let mut cmd = Command::new("winget");- cmd.args([- "install",- "Python.Python.3.12",- "--silent",- "--accept-package-agreements",- "--accept-source-agreements",- "--scope",- "user",- ])- .stdout(Stdio::piped())- .stderr(Stdio::piped());- #[cfg(target_os = "windows")]- cmd.creation_flags(CREATE_NO_WINDOW);-- let child = match cmd.spawn() {- Ok(c) => c,- Err(e) => {- update(- "error",- &format!(- "Could not run winget: {}. winget ships with Windows 10/11 — \- if it's missing, run 'Get App Installer' from the Microsoft \- Store (free) and retry.",- e- ),- );- return;- }- };+ // ── The Windows path ────────────────────────────────────────────────+ //+ // Everything below is the winget install. It used to sit behind the two+ // `return`s above, which made rustc call it an `unreachable statement`+ // on macOS and Linux — correct about the control flow, and saying+ // nothing about the code: this is not dead code, it is the OTHER+ // platform's implementation.+ //+ // `if cfg!` and not `#[cfg]`, for the reason `test_support.rs` states at+ // its top: a `#[cfg]` would delete this whole branch from a macOS build,+ // and with it the type-checking of ~150 lines of Windows installer plus+ // the dozen helpers it is the only caller of (`sha256_file`,+ // `installer_size_verdict`, `windows_git_probe_from_output` …), which+ // would then read as dead code here. Compiled-and-never-taken keeps the+ // Windows half honest on the machine this is developed on.+ //+ // The condition is `not(linux or macos)` rather than `windows` so the+ // set of targets that run it is exactly the set that ran it before.+ if !cfg!(any(target_os = "linux", target_os = "macos")) {+ // Stream-friendly winget invocation. `--silent --accept-*-agreements`+ // drops the EULA prompts; without them winget will sit and wait for+ // user input forever inside our background thread. Python.Python.3.12+ // is the canonical winget id for the python.org installer (matches+ // `winget search python` top result).+ update("installing", "Running: winget install Python.Python.3.12 --silent --accept-package-agreements --accept-source-agreements");++ let mut cmd = Command::new("winget");+ cmd.args([+ "install",+ "Python.Python.3.12",+ "--silent",+ "--accept-package-agreements",+ "--accept-source-agreements",+ "--scope",+ "user",+ ])+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);- // Stream stdout + stderr line-by-line so the UI's log card animates- // as winget extracts and installs (otherwise it freezes for 1–2 min).- let mut child = child;- let stdout = child.stdout.take();- let stderr = child.stderr.take();- let stdout_state = py_state.clone();- let stdout_handle = std::thread::spawn(move || {- if let Some(out) = stdout {- let reader = BufReader::new(out);- for line in reader.lines().map_while(Result::ok) {- let trimmed = line.trim();- if !trimmed.is_empty() {- if let Ok(mut s) = stdout_state.lock() {- s.logs.push(trimmed.to_string());+ let child = match cmd.spawn() {+ Ok(c) => c,+ Err(e) => {+ update(+ "error",+ &format!(+ "Could not run winget: {}. winget ships with Windows 10/11 — \+ if it's missing, run 'Get App Installer' from the Microsoft \+ Store (free) and retry.",+ e+ ),+ );+ return;+ }+ };++ // Stream stdout + stderr line-by-line so the UI's log card animates+ // as winget extracts and installs (otherwise it freezes for 1–2 min).+ let mut child = child;+ let stdout = child.stdout.take();+ let stderr = child.stderr.take();+ let stdout_state = py_state.clone();+ let stdout_handle = std::thread::spawn(move || {+ if let Some(out) = stdout {+ let reader = BufReader::new(out);+ for line in reader.lines().map_while(Result::ok) {+ let trimmed = line.trim();+ if !trimmed.is_empty() {+ if let Ok(mut s) = stdout_state.lock() {+ s.logs.push(trimmed.to_string());+ }+ }}}- }- }- });- let stderr_state = py_state.clone();- let stderr_handle = std::thread::spawn(move || {- if let Some(err) = stderr {- let reader = BufReader::new(err);- for line in reader.lines().map_while(Result::ok) {- let trimmed = line.trim();- if !trimmed.is_empty() {- if let Ok(mut s) = stderr_state.lock() {- s.logs.push(trimmed.to_string());+ });+ let stderr_state = py_state.clone();+ let stderr_handle = std::thread::spawn(move || {+ if let Some(err) = stderr {+ let reader = BufReader::new(err);+ for line in reader.lines().map_while(Result::ok) {+ let trimmed = line.trim();+ if !trimmed.is_empty() {+ if let Ok(mut s) = stderr_state.lock() {+ s.logs.push(trimmed.to_string());+ }+ }}}- }- }- });+ });- let exit_status = match child.wait() {- Ok(s) => s,- Err(e) => {- update("error", &format!("winget wait failed: {}", e));- return;- }- };- let _ = stdout_handle.join();- let _ = stderr_handle.join();+ let exit_status = match child.wait() {+ Ok(s) => s,+ Err(e) => {+ update("error", &format!("winget wait failed: {}", e));+ return;+ }+ };+ let _ = stdout_handle.join();+ let _ = stderr_handle.join();- if !exit_status.success() {- // winget exit codes are HRESULT-shaped; -1978335189 (0x8A150011)- // means "no upgrade applicable" which is fine if Python is- // already present. Anything else is a real failure.- let code = exit_status.code().unwrap_or(-1);- // Re-resolve regardless: Python may already be on the box from- // a previous install attempt that the original where-scan- // missed (e.g. Add-to-PATH was unchecked).- let resolved = crate::python::get_python_bin();- if crate::python::is_real_python(&resolved) {- if let Ok(mut slot) = py_bin_slot.lock() {- *slot = resolved.clone();+ if !exit_status.success() {+ // winget exit codes are HRESULT-shaped; -1978335189 (0x8A150011)+ // means "no upgrade applicable" which is fine if Python is+ // already present. Anything else is a real failure.+ let code = exit_status.code().unwrap_or(-1);+ // Re-resolve regardless: Python may already be on the box from+ // a previous install attempt that the original where-scan+ // missed (e.g. Add-to-PATH was unchecked).+ let resolved = crate::python::get_python_bin();+ if crate::python::is_real_python(&resolved) {+ if let Ok(mut slot) = py_bin_slot.lock() {+ *slot = resolved.clone();+ }+ update(+ "complete",+ &format!("Python ready (winget exit {} ignored, Python detected at {})", code, resolved),+ );+ return;+ }+ update(+ "error",+ &format!(+ "winget exited with code {}. Python was not detected after \+ install. Try installing manually from python.org with the \+ 'Add Python to PATH' checkbox on, then return here and \+ click Re-Scan.",+ code+ ),+ );+ return;}- update(- "complete",- &format!("Python ready (winget exit {} ignored, Python detected at {})", code, resolved),- );- return;- }- update(- "error",- &format!(- "winget exited with code {}. Python was not detected after \- install. Try installing manually from python.org with the \- 'Add Python to PATH' checkbox on, then return here and \- click Re-Scan.",- code- ),- );- return;- }- update("starting", "winget finished. Re-resolving Python…");-- // Give the freshly installed Python a moment to settle (winget can- // signal completion before the file is fully linked into PATH on- // some boxes), then re-resolve and persist.- for attempt in 0..15 {- std::thread::sleep(std::time::Duration::from_secs(1));- let resolved = crate::python::get_python_bin();- if crate::python::is_real_python(&resolved) {- if let Ok(mut slot) = py_bin_slot.lock() {- *slot = resolved.clone();+ update("starting", "winget finished. Re-resolving Python…");++ // Give the freshly installed Python a moment to settle (winget can+ // signal completion before the file is fully linked into PATH on+ // some boxes), then re-resolve and persist.+ for attempt in 0..15 {+ std::thread::sleep(std::time::Duration::from_secs(1));+ let resolved = crate::python::get_python_bin();+ if crate::python::is_real_python(&resolved) {+ if let Ok(mut slot) = py_bin_slot.lock() {+ *slot = resolved.clone();+ }+ update(+ "complete",+ &format!("Python ready at {}", resolved),+ );+ return;+ }+ println!("[Python] post-install resolve attempt {}/15 — not yet on PATH", attempt + 1);}+update(- "complete",- &format!("Python ready at {}", resolved),+ "error",+ "winget reported success but Python is still not on PATH. \+ Restart Locally Uncensored — sometimes Windows needs the new PATH \+ to take effect. If it still doesn't show up, install manually \+ from python.org with 'Add Python to PATH' on.",);- return;- }- println!("[Python] post-install resolve attempt {}/15 — not yet on PATH", attempt + 1);}-- update(- "error",- "winget reported success but Python is still not on PATH. \- Restart Locally Uncensored — sometimes Windows needs the new PATH \- to take effect. If it still doesn't show up, install manually \- from python.org with 'Add Python to PATH' on.",- );});Ok(serde_json::json!({"status": "installing"}))diff --git a/src-tauri/src/commands/logging.rs b/src-tauri/src/commands/logging.rsindex 5cc42dc9..58ebcf14 100644--- a/src-tauri/src/commands/logging.rs+++ b/src-tauri/src/commands/logging.rs@@ -9,18 +9,16 @@//! main.rs now owns the Rust half (a rolling file writer next to the crash//! log). This module is the part the WebView can reach://!-//! * `log_write` — the frontend mirrors its own warn/error lines into the-//! same file, so a support log holds BOTH halves of the app-//! in one chronological stream. Without it the file would-//! describe the backend of a bug whose visible half happened-//! in React.+//! * `log_write` — the frontend mirrors its own warn/error lines into the+//! same file, so a support log holds BOTH halves of the app in one+//! chronological stream. Without it the file would describe the backend of a+//! bug whose visible half happened in React.//! * `log_file_path` — Settings → Troubleshoot shows the user where the file-//! is, which is the whole point of writing one.-//! * `log_reveal` — opens that folder in the file manager. `plugin:shell|open`-//! cannot do this: with no `plugins.shell.open` entry in-//! tauri.conf.json the plugin falls back to its built-in-//! validator, which only accepts `https?:` / `mailto:` /-//! `tel:` URLs and rejects a filesystem path.+//! is, which is the whole point of writing one.+//! * `log_reveal` — opens that folder in the file manager. `plugin:shell|open`+//! cannot do this: with no `plugins.shell.open` entry in tauri.conf.json the+//! plugin falls back to its built-in validator, which only accepts+//! `https?:` / `mailto:` / `tel:` URLs and rejects a filesystem path.use serde::Serialize;diff --git a/src-tauri/src/commands/mlx.rs b/src-tauri/src/commands/mlx.rsindex 7eb579c8..ec409b9c 100644--- a/src-tauri/src/commands/mlx.rs+++ b/src-tauri/src/commands/mlx.rs@@ -866,6 +866,14 @@ pub fn mlx_start(_state: &AppState, _args: &Value) -> CmdResult {/// Stop the MLX sidecar (the long-lived image/video server on MLX_PORT). We/// didn't keep a Child handle, so stop it by its listening port — the "Stop"/// button counterpart to `mlx_start`.+/// FINDING (clippy paydown, 01.09.2026): this has no caller and no bridge.+/// `media_cmds.rs` wraps `mlx_status`, `mlx_start`, `mlx_unload`, `mlx_generate`+/// and the rest as `#[tauri::command]`s — but not this one, so the frontend+/// cannot reach it and the "Stop" button it describes cannot exist. The only+/// production path that actually stops the sidecar is the quit-time+/// `kill_listeners_on_port(MLX_PORT)` in `state.rs`. Either add the wrapper or+/// delete this; the `allow` only keeps `-D warnings` usable meanwhile.+#[allow(dead_code)]pub fn mlx_stop(_state: &AppState, _args: &Value) -> CmdResult {crate::process_util::kill_listeners_on_port(MLX_PORT);Ok(json!({ "ok": true, "port": MLX_PORT }))diff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rsindex a15fdb91..037a695f 100644--- a/src-tauri/src/commands/process.rs+++ b/src-tauri/src/commands/process.rs@@ -1469,7 +1469,7 @@ fn start_comfyui_blocking(state: &AppState) -> Result<serde_json::Value, String>};let comfy_path = comfy_path- .or_else(|| find_comfyui_path())+ .or_else(find_comfyui_path).ok_or_else(|| "ComfyUI not found".to_string())?;// Store the path for future use@@ -1578,7 +1578,7 @@ fn start_comfyui_blocking(state: &AppState) -> Result<serde_json::Value, String>// guarantees we never pass the flag on a broken install (ComfyUI would// error at startup); probe result is cached per python path. CPU mode// skips it — flash-attn is CUDA-only.- if !needs_cpu_fallback && flash_attention_cached(&state, &python) {+ if !needs_cpu_fallback && flash_attention_cached(state, &python) {comfy_args.push("--use-flash-attention");println!("[ComfyUI] flash-attn detected in {} — enabling Flash Attention", python);}@@ -1801,7 +1801,17 @@ pub(crate) fn find_orphaned_comfyui(port: u16) -> Option<u32> {// The table MUST come from this helper: a bare `refresh_processes` does not// fetch command lines, and every match here would silently be against "".// See the note above `process_table_with_cmdlines`.- let sys = crate::process_util::process_table_with_cmdlines();+ find_orphaned_comfyui_in(&crate::process_util::process_table_with_cmdlines(), port)+}++/// The same scan, against a table the caller already holds.+///+/// Split out for the test that proves the scan is wired to real data. Taking the+/// snapshot as an argument is what lets that test assert on a table+/// `test_support::checked_table` has already vouched for, with no clock and no+/// second enumeration between the check and the assertion. `remote.rs` split+/// `find_stale_tunnels` the same way and for the same reason.+pub(crate) fn find_orphaned_comfyui_in(sys: &sysinfo::System, port: u16) -> Option<u32> {let own = std::process::id();for (pid, process) in sys.processes() {let pid = pid.as_u32();@@ -1986,8 +1996,7 @@ pub async fn comfyui_status(state: State<'_, AppState>) -> Result<serde_json::Valet running = reqwest::Client::builder().timeout(std::time::Duration::from_secs(3)).build()- .ok()- .and_then(|c| Some(c.get(format!("http://{}:{}/system_stats", host, port))))+ .ok().map(|c| c.get(format!("http://{}:{}/system_stats", host, port))).map(|req| async move { req.send().await.map(|r| r.status().is_success()).unwrap_or(false) });let running = match running {@@ -2309,7 +2318,7 @@ fn normalize_ollama_base(input: &str) -> Result<String, String> {};// Sanity-check with a URL parse so "http://" alone or "http://:1234" can't pass.match url::Url::parse(&with_scheme) {- Ok(u) if u.host_str().map_or(false, |h| !h.is_empty()) => Ok(with_scheme),+ Ok(u) if u.host_str().is_some_and(|h| !h.is_empty()) => Ok(with_scheme),_ => Err(format!("Not a valid URL: {}", input)),}}@@ -2536,10 +2545,8 @@ pub fn auto_start_comfyui(state: &AppState) {std::thread::spawn(move || {use std::io::{BufRead, BufReader};let reader = BufReader::new(stdout);- for line in reader.lines() {- if let Ok(line) = line {- println!("[ComfyUI] {}", line);- }+ for line in reader.lines().map_while(Result::ok) {+ println!("[ComfyUI] {}", line);}});}@@ -2547,10 +2554,8 @@ pub fn auto_start_comfyui(state: &AppState) {std::thread::spawn(move || {use std::io::{BufRead, BufReader};let reader = BufReader::new(stderr);- for line in reader.lines() {- if let Ok(line) = line {- println!("[ComfyUI] {}", line);- }+ for line in reader.lines().map_while(Result::ok) {+ println!("[ComfyUI] {}", line);}});}@@ -3041,10 +3046,10 @@ pub(crate) fn offload_local_models_blocking(state: &AppState, include_comfyui: O// Both are graceful no-ops when not running, and lazy-start on next use.// Call the lifecycle helpers directly — the #[command] wrappers are async// now (they moved off the Tauri main thread) and this caller is sync.- if crate::commands::engine::stop_engine_locked(&state) {+ if crate::commands::engine::stop_engine_locked(state) {freed.push("bundled-engine");}- if crate::commands::engine::stop_embed_locked(&state) {+ if crate::commands::engine::stop_embed_locked(state) {freed.push("bundled-embed");}@@ -3792,25 +3797,25 @@ mod comfy_adoption_tests {));}- /// The scan runs against the real process table. A process whose argv- /// matches must be found by pid; the same process on another port must- /// not.+ /// A live process carrying exactly the argv `start_comfyui_blocking` spawns.+ ///+ /// `examples/park`, run directly. It ignores its arguments and blocks on+ /// stdin, so it carries the argv this test chose, lives exactly as long as+ /// the test holds the pipe, and forks nothing that could be orphaned.///- /// Unix only: the stand-in needs a program that keeps LU's argv shape- /// while doing nothing, and `sh -c` is the portable way to get one. The- /// finding itself is a Linux/macOS one — Windows children join the- /// kill-on-close job object and do not orphan in the first place.+ /// What it replaced was `/bin/sh -c "sleep 30; :" main.py …`, and both+ /// halves of that were a liability:+ ///+ /// * `sleep 30` is a wall-clock budget on a test, and it forks a+ /// grandchild that `child.kill()` does not reach.+ /// * `sh` is a SIP platform binary. This one was invoked rather than+ /// copied, so it escaped the SIGKILL that `examples/park.rs` documents —+ /// but the next person to reach for "make a copy and rename it" would+ /// not, and the stand-in that does not have the problem is right here.#[cfg(unix)]- #[test]- fn the_scan_finds_a_real_process_by_the_argv_lu_would_have_used() {- // The trailing `; :` matters: a single simple command makes sh exec- // it and hand over its argv, which would erase the very thing being- // matched.- let port: u16 = 61888;- let mut child = Command::new("/bin/sh")+ fn live_comfy_stand_in(port: u16) -> std::process::Child {+ Command::new(crate::test_support::park_binary()).args([- "-c",- "sleep 30; :","main.py","--listen","127.0.0.1",@@ -3819,22 +3824,94 @@ mod comfy_adoption_tests {"--enable-cors-header","*",])- .stdin(Stdio::null())+ // Piped, not null: closing this pipe is how the stand-in is ended.+ .stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null()).spawn()- .expect("spawn the stand-in");+ .expect("spawn the stand-in")+ }++ /// The scan runs against the real process table. A process whose argv+ /// matches must be found by pid; the same process on another port must+ /// not.+ ///+ /// Unix only: the finding is a Linux/macOS one — Windows children join the+ /// kill-on-close job object and do not orphan in the first place. (The old+ /// reason, "`sh -c` is the portable way to get a stand-in", is gone with the+ /// stand-in; what keeps the gate is that `park_binary()` would need the+ /// `.exe` suffix there and no Windows machine was available to check it.)+ ///+ /// ── Why this test looked like it worked and did not ──+ ///+ /// It used to sleep a fixed 300 ms, take exactly one snapshot, and assert on+ /// it, with a hard-coded port 61888. Measured on 01.09.2026 over a delay+ /// series under three concurrent copies of the whole suite — the shape the+ /// flake was reported in — it failed 0/25 at 0 ms, 1/25 at 300 ms, 2/25 at+ /// 600 ms and 6/25 at 1000 ms, and every single one of those nine failures+ /// was the same thing: `find_orphaned_comfyui` returned a pid HIGHER than+ /// this test's own child. A stranger's. A second suite running this very+ /// test had its own stand-in on 61888, and the scan returned whichever of+ /// the two the table iteration reached first.+ ///+ /// That the failure rate RISES with the sleep is the proof of which+ /// mechanism it was: a longer sleep is a longer window in which a concurrent+ /// copy's stand-in is alive at the same time as this one's. A settle-time+ /// problem would have behaved the other way round.+ ///+ /// So the port is no longer written down. It is leased from the kernel, and+ /// the lease is held for the whole test, which is what makes it impossible+ /// for a concurrent copy to draw the same number.+ ///+ /// Turned up to the maximum — 30 copies of this one test started at the same+ /// instant, three rounds — the old body failed 87 of 90 and this one 0 of 90+ /// (0 of 150 at 50 copies). And with everything else here left alone and+ /// only `reserved_port()` swapped back for the constant 61888, this body+ /// fails 79 of 90 again. The lease is the fix; the stand-in and the checked+ /// snapshot are what stop the OTHER two ways it could rot.+ #[cfg(unix)]+ #[test]+ fn the_scan_finds_a_real_process_by_the_argv_lu_would_have_used() {+ use crate::test_support::{checked_table, reserved_port};- // sysinfo needs the process to be in the table.- std::thread::sleep(std::time::Duration::from_millis(300));- let found = find_orphaned_comfyui(port);- let other = find_orphaned_comfyui(port + 1);+ // Held to the end of the test: while these sockets are bound, no other+ // process on this machine is handed either number.+ let (ours, _ours_lease) = reserved_port();+ let (stranger, _stranger_lease) = reserved_port();+ let mut child = live_comfy_stand_in(ours);+ let pid = child.id();++ // One snapshot that has shown it contains this process AND the stand-in.+ // Everything asserted below is a pure function of it — no clock, no+ // second enumeration, nothing that can change under the assertions.+ let table = checked_table(pid);let _ = child.kill();let _ = child.wait();- assert_eq!(found, Some(child.id()), "the scan did not find the stand-in");- assert_eq!(other, None, "the scan matched a process on another port");+ let sys = table.unwrap_or_else(|why| panic!("{why}"));+ let entry = sys+ .process(sysinfo::Pid::from_u32(pid))+ .expect("checked_table only returns a table containing this pid");++ // If this fails the rest means nothing: the stand-in would not be+ // carrying the argv the scan matches on.+ let argv = crate::process_util::cmdline_of(entry);+ assert!(+ argv.iter().any(|a| a == "main.py"),+ "the stand-in is not carrying LU's argv at all: {argv:?}",+ );++ assert_eq!(+ find_orphaned_comfyui_in(&sys, ours),+ Some(pid),+ "the scan did not find the stand-in. argv={argv:?}",+ );+ assert_ne!(+ find_orphaned_comfyui_in(&sys, stranger),+ Some(pid),+ "the scan matched this process while looking for another port ({stranger})",+ );}/// Stop must not still be the no-op the finding describes.diff --git a/src-tauri/src/commands/proxy.rs b/src-tauri/src/commands/proxy.rsindex 56daa961..731f8dee 100644--- a/src-tauri/src/commands/proxy.rs+++ b/src-tauri/src/commands/proxy.rs@@ -1665,7 +1665,7 @@ mod tests {.await;let client = proxy_client(Duration::from_secs(10), ProxyAllowList::default()).unwrap();let out = client.get(format!("http://127.0.0.1:{}/start", port)).send().await;- let err = out.err().expect("the metadata redirect must not be followed");+ let err = out.expect_err("the metadata redirect must not be followed");assert!(err.is_redirect(), "refused for the wrong reason: {err}");});}diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rsindex 19f07f63..853e79a0 100644--- a/src-tauri/src/commands/remote.rs+++ b/src-tauri/src/commands/remote.rs@@ -313,23 +313,15 @@ async fn auth_middleware(.unwrap_or("");let cookie_token = cookie_header.split(';')- .find_map(|c| {- let c = c.trim();- if c.starts_with("lu-remote-token=") {- Some(&c[16..])- } else {- None- }- })+ .find_map(|c| c.trim().strip_prefix("lu-remote-token=")).unwrap_or("");let query_token = req.uri().query().unwrap_or("").split('&')- .find(|p| p.starts_with("token="))- .map(|p| &p[6..])+ .find_map(|p| p.strip_prefix("token=")).unwrap_or("");- let token = if auth_header.starts_with("Bearer ") {- &auth_header[7..]+ let token = if let Some(bearer) = auth_header.strip_prefix("Bearer ") {+ bearer} else if !cookie_token.is_empty() {cookie_token} else if !query_token.is_empty() {@@ -3090,7 +3082,7 @@ pub async fn start_tunnel(std::thread::spawn(move || {use std::io::BufRead;let reader = std::io::BufReader::new(stderr);- for line in reader.lines().flatten() {+ for line in reader.lines().map_while(Result::ok) {println!("[Tunnel] {}", line);// cloudflared prints: "... https://xxx.trycloudflare.com ..."if let Some(start) = line.find("https://") {@@ -4121,52 +4113,11 @@ mod remote_hardening_tests {/// A process table that has PROVEN itself, or the reason it could not.///- /// The check is an invariant that cannot be false when the enumeration- /// worked: this very process is running, so a table without it was not read- /// at all. That is not a theoretical concern — sysinfo-0.33.1's macOS- /// `refresh_processes_specifics` takes its pids from `get_proc_list()`, and- /// when that returns `None` (its second `proc_listallpids` filling the- /// buffer the first one sized) the function returns 0 and leaves the list- /// untouched, so a fresh `System` comes back EMPTY with no error anywhere.- ///- /// Retrying is therefore not hope: every retry is gated on a check, and the- /// caller only ever asserts on a snapshot that passed. Between the check- /// and the assertion there is no clock, no syscall and no other thread —- /// the assertions are a pure function of data already in hand.+ /// Moved to `test_support::checked_table` when `commands/process.rs` needed+ /// the same guarantee for the ComfyUI adoption scan — the argument for it is+ /// written out there, in one copy.#[cfg(unix)]- fn checked_table(pid: u32) -> Result<sysinfo::System, String> {- use std::time::{Duration, Instant};- let me = sysinfo::Pid::from_u32(std::process::id());- let deadline = Instant::now() + Duration::from_secs(10);- let mut attempts = 0usize;- let mut blind = 0usize;- loop {- if Instant::now() >= deadline {- return Err(format!(- "no usable process table in 10s ({attempts} attempts, {blind} of them \- without this test's own process in them). That is the TEST ENVIRONMENT, \- not the sweep."- ));- }- if attempts > 0 {- // Paces retries so a pathological environment does not spin a- // core. It is not what makes the result correct — the checks- // below are.- std::thread::sleep(Duration::from_millis(20));- }- attempts += 1;- let sys = crate::process_util::process_table_with_cmdlines();- if sys.process(me).is_none() {- blind += 1;- continue;- }- if sys.process(sysinfo::Pid::from_u32(pid)).is_none() {- blind += 1;- continue;- }- return Ok(sys);- }- }+ use crate::test_support::checked_table;/// A live process that really is NAMED `cloudflared`, publishing `port`.///@@ -4179,19 +4130,7 @@ mod remote_hardening_tests {fn live_cloudflared(port: u16) -> (tempfile::TempDir, std::process::Child) {use std::process::{Command, Stdio};- // target/<profile>/deps/<test binary> -> target/<profile>/examples/park- let exe = std::env::current_exe().expect("current_exe");- let park = exe- .parent()- .and_then(|deps| deps.parent())- .map(|profile| profile.join("examples").join("park"))- .expect("no target/<profile>/ above the test binary");- assert!(- park.is_file(),- "{} is missing. It is `src-tauri/examples/park.rs`, which `cargo test` builds \- alongside the tests; if it is gone, this test is not measuring the sweep.",- park.display(),- );+ let park = crate::test_support::park_binary();let dir = tempfile::tempdir().expect("tempdir");let bin = dir.path().join("cloudflared");diff --git a/src-tauri/src/commands/repo_map.rs b/src-tauri/src/commands/repo_map.rsindex c3c5a9f1..95fb79c2 100644--- a/src-tauri/src/commands/repo_map.rs+++ b/src-tauri/src/commands/repo_map.rs@@ -251,12 +251,9 @@ fn resolve_rust_use(prefix: &str, path: &str, from: &str, files: &HashSet<String} else {format!("{}/{}", base, path_segs.join("/"))};- for cand in [format!("{}.rs", joined), format!("{}/mod.rs", joined)] {- if files.contains(&cand) {- return Some(cand);- }- }- None+ [format!("{}.rs", joined), format!("{}/mod.rs", joined)]+ .into_iter()+ .find(|cand| files.contains(cand))}/// Heuristic: the crate root for a Rust file is the closest ancestor that@@ -297,16 +294,13 @@ fn resolve_python_import(} else {format!("{}/{}", base, module_path)};- for cand in [+ [format!("{}.py", joined),format!("{}/__init__.py", joined),format!("src/{}.py", module_path),- ] {- if files.contains(&cand) {- return Some(cand);- }- }- None+ ]+ .into_iter()+ .find(|cand| files.contains(cand))}/// Extracts all repo-internal imports a file declares. Pure on top ofdiff --git a/src-tauri/src/commands/search.rs b/src-tauri/src/commands/search.rsindex 4d5c700e..1c19dfda 100644--- a/src-tauri/src/commands/search.rs+++ b/src-tauri/src/commands/search.rs@@ -90,12 +90,12 @@ async fn try_ddg(query: &str, count: usize) -> Result<Vec<SearchResult>, String>.collect();let mut results = Vec::new();- for i in 0..titles.len().min(count) {+ for (i, title) in titles.iter().take(count).enumerate() {let url = urls.get(i).cloned().unwrap_or_default();let snippet = snippets.get(i).cloned().unwrap_or_default();if !url.is_empty() {results.push(SearchResult {- title: titles[i].clone(),+ title: title.clone(),url,snippet,});diff --git a/src-tauri/src/commands/secret.rs b/src-tauri/src/commands/secret.rsindex 41f2775c..49446a40 100644--- a/src-tauri/src/commands/secret.rs+++ b/src-tauri/src/commands/secret.rs@@ -96,10 +96,23 @@ fn check_account(account: &str) -> Result<(), String> {mod chunked {use super::SERVICE;- /// Per-entry budget in UTF-16 units. keyring's windows-native backend- /// rejects blobs over 2560 bytes (1280 units) — stay comfortably under.- /// macOS has no limit, so it never chunks and writes stay single-entry.- const MAX_UNITS: usize = if cfg!(target_os = "windows") { 1000 } else { usize::MAX };+ /// Per-entry budget in UTF-16 units, or `None` where the platform's store+ /// has no per-entry limit at all. keyring's windows-native backend rejects+ /// blobs over 2560 bytes (1280 units) — stay comfortably under. macOS has+ /// no limit, so it never chunks and writes stay single-entry.+ ///+ /// "No limit" is `None` and not `usize::MAX` on purpose. With the sentinel,+ /// the `count() <= MAX_UNITS` in `set` was a comparison against the maximum+ /// of the type on every non-Windows target, i.e. always true —+ /// `clippy::absurd_extreme_comparisons`, which is deny-by-default, so this+ /// one line made `cargo clippy` exit non-zero for the whole crate even+ /// without `-D warnings`. `Option` states the same fact without a value+ /// that only pretends to be a bound.+ const MAX_UNITS: Option<usize> = if cfg!(target_os = "windows") {+ Some(1000)+ } else {+ None+ };/// Head marker for a chunked value. No provider key or session JSON ever/// starts with this, so plain pre-existing entries read back unchanged.@@ -170,15 +183,16 @@ mod chunked {}pub fn set(account: &str, value: &str) -> Result<(), String> {- if value.encode_utf16().count() <= MAX_UNITS {+ // No budget (macOS) means it always fits; with a budget, measure.+ let Some(max_units) = MAX_UNITS.filter(|max| value.encode_utf16().count() > *max) else {entry(account)?.set_password(value).map_err(|e| e.to_string())?;// Drop every chunk: this value lives in the head alone now.let _ = sweep_chunks_from(account, 0);return Ok(());- }+ };// Chunks first, marker last — a torn write keeps the old head (and// thus the old value) readable.- let parts = split_units(value, MAX_UNITS);+ let parts = split_units(value, max_units);for (i, part) in parts.iter().enumerate() {entry(&chunk_account(account, i))?.set_password(part)diff --git a/src-tauri/src/commands/shell.rs b/src-tauri/src/commands/shell.rsindex a9489e36..62bc0d35 100644--- a/src-tauri/src/commands/shell.rs+++ b/src-tauri/src/commands/shell.rs@@ -236,8 +236,12 @@ pub(crate) fn default_shell(windows: bool) -> &'static str {}}+/// The eight arguments are the IPC contract: `#[tauri::command]` derives the+/// invoke payload from this signature, so folding them into a struct would+/// change the JSON the frontend sends. `clippy::too_many_arguments` is allowed+/// here for that reason and not as a matter of taste.#[tauri::command]-#[allow(non_snake_case)]+#[allow(non_snake_case, clippy::too_many_arguments)]pub async fn shell_execute(command: String,args: Option<Vec<String>>,@@ -255,6 +259,10 @@ pub async fn shell_execute(.map_err(|e| format!("Task join error: {}", e))?}+/// Mirrors `shell_execute`'s parameter list one-to-one on purpose — it is the+/// blocking half of the same command, and a different shape here would be a+/// second place to keep in step with the frontend contract.+#[allow(clippy::too_many_arguments)]fn shell_execute_sync(command: String,args: Option<Vec<String>>,@@ -285,7 +293,7 @@ fn shell_execute_sync(// back to the per-chat agent workspace (created if missing) so a relative// command never runs in the app's ambient cwd and scatters files into// ~/Documents (David 2026-06-04). Mirrors the file tools' path resolution.- let workdir: PathBuf = match cwd.as_ref().map(|d| Path::new(d)) {+ let workdir: PathBuf = match cwd.as_ref().map(Path::new) {Some(p) if p.is_dir() => p.to_path_buf(),_ => match working_directory.as_deref().map(str::trim).filter(|s| !s.is_empty()) {// Folder workspace (the user's repo, from chatCtx.workingDirectory)diff --git a/src-tauri/src/commands/trainer.rs b/src-tauri/src/commands/trainer.rsindex aeff246b..58086993 100644--- a/src-tauri/src/commands/trainer.rs+++ b/src-tauri/src/commands/trainer.rs@@ -582,9 +582,7 @@ fn preflight_verdict(exit_ok: bool, stdout: &str, stderr: &str, gpu: Option<&strif !exit_ok || !stdout.contains("TORCH_OK") {let tail = stderr.lines()- .map(str::trim)- .filter(|l| !l.is_empty())- .next_back()+ .map(str::trim).rfind(|l| !l.is_empty()).unwrap_or("no detail from python").to_string();return Preflight::TorchBroken(tail);diff --git a/src-tauri/src/commands/whisper.rs b/src-tauri/src/commands/whisper.rsindex 87fe4454..e37afe29 100644--- a/src-tauri/src/commands/whisper.rs+++ b/src-tauri/src/commands/whisper.rs@@ -116,15 +116,13 @@ impl WhisperServer {let tx_clone = tx.clone();std::thread::spawn(move || {let reader = BufReader::new(stdout);- for line in reader.lines() {- if let Ok(line) = line {- let trimmed = line.trim();- if trimmed.is_empty() {- continue;- }- if let Ok(json) = serde_json::from_str::<serde_json::Value>(trimmed) {- let _ = tx_clone.send(json);- }+ for line in reader.lines().map_while(Result::ok) {+ let trimmed = line.trim();+ if trimmed.is_empty() {+ continue;+ }+ if let Ok(json) = serde_json::from_str::<serde_json::Value>(trimmed) {+ let _ = tx_clone.send(json);}}});@@ -132,11 +130,9 @@ impl WhisperServer {// Stderr reader thread — log Python outputstd::thread::spawn(move || {let reader = BufReader::new(stderr);- for line in reader.lines() {- if let Ok(line) = line {- if !line.trim().is_empty() {- println!("[Whisper] {}", line.trim());- }+ for line in reader.lines().map_while(Result::ok) {+ if !line.trim().is_empty() {+ println!("[Whisper] {}", line.trim());}}});diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 92a73b82..ff08aa81 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -224,8 +224,14 @@ fn main() {// Windows investigation had to untangle by hand.crash_report::install_panic_hook();- #[cfg(target_os = "linux")]- apply_linux_webkit_workarounds();+ // `if cfg!` and not `#[cfg]`: the function is module-level on purpose so the+ // no-overwrite logic is unit-testable off Linux (see the note on it), and a+ // `#[cfg]` here left it without a single caller in a macOS build — dead code+ // by rustc's reckoning, for a function whose whole point is being reachable+ // from the tests.+ if cfg!(target_os = "linux") {+ apply_linux_webkit_workarounds();+ }// Before anything can spawn a child: an AppImage exports PYTHONHOME and// PYTHONPATH into its own mount, and every python3 we start inherits them// and dies on "No module named 'encodings'".diff --git a/src-tauri/src/os_error.rs b/src-tauri/src/os_error.rsindex fa356e85..ccd1a070 100644--- a/src-tauri/src/os_error.rs+++ b/src-tauri/src/os_error.rs@@ -258,13 +258,16 @@ mod tests {#[test]fn the_red_hint_over_the_microphone_is_english() {let e = Error::from_raw_os_error(232);- // What the three call sites used to write: the error's own Display,- // which on a German Windows is "Die Pipe wird gerade geschlossen.".- let before = format!("stdin flush: {}", e);+ // What the three call sites used to write was `format!("stdin flush: {e}")`+ // — the error's own Display, which on a German Windows is "Die Pipe wird+ // gerade geschlossen.". That used to be bound to a `before` variable and+ // then never read; `e.to_string()` in the last assertion is the same+ // string, so the binding is gone rather than renamed to `_before`.+ //// What they write now.let after = format!("stdin flush: {}", io_english(&e));assert_eq!(after, "stdin flush: the pipe is closing (os error 232)");- // On a German box `before` is German; here it is only "Unknown error",+ // On a German box the old wording is German; here it is only "Unknown error",// so the assertion that says something on every platform is that the// new wording no longer depends on what the system happens to say.assert!(!after.contains(&e.to_string()) || e.to_string() == io_english(&e));diff --git a/src-tauri/src/os_paths.rs b/src-tauri/src/os_paths.rsindex fbd83bfa..c17d6d20 100644--- a/src-tauri/src/os_paths.rs+++ b/src-tauri/src/os_paths.rs@@ -378,6 +378,13 @@ pub fn find_lmstudio_app() -> Option<PathBuf> {}/// Is LM Studio installed anywhere — the `lms` CLI or the app bundle?+/// FINDING (clippy paydown, 01.09.2026): nothing in this repository calls this —+/// not the Rust side, not a `#[tauri::command]` wrapper, not the frontend. It is+/// kept rather than deleted because deleting a detection helper is a product+/// decision, not a lint decision; the `allow` is here so the rest of the crate+/// can run under `-D warnings` while that decision is pending. Wire it or drop+/// it, but do not leave it in this state indefinitely.+#[allow(dead_code)]pub fn lmstudio_installed() -> bool {find_lms_cli().is_some() || find_lmstudio_app().is_some()}@@ -427,11 +434,25 @@ pub fn find_ollama_bin() -> Option<PathBuf> {}/// Is Ollama installed anywhere — CLI binary or app bundle?+/// FINDING (clippy paydown, 01.09.2026): nothing in this repository calls this —+/// not the Rust side, not a `#[tauri::command]` wrapper, not the frontend. It is+/// kept rather than deleted because deleting a detection helper is a product+/// decision, not a lint decision; the `allow` is here so the rest of the crate+/// can run under `-D warnings` while that decision is pending. Wire it or drop+/// it, but do not leave it in this state indefinitely.+#[allow(dead_code)]pub fn ollama_installed() -> bool {find_ollama_bin().is_some() || find_ollama_app().is_some()}/// Reasonable places to look for an existing ComfyUI install.+/// FINDING (clippy paydown, 01.09.2026): nothing in this repository calls this —+/// not the Rust side, not a `#[tauri::command]` wrapper, not the frontend. It is+/// kept rather than deleted because deleting a detection helper is a product+/// decision, not a lint decision; the `allow` is here so the rest of the crate+/// can run under `-D warnings` while that decision is pending. Wire it or drop+/// it, but do not leave it in this state indefinitely.+#[allow(dead_code)]pub fn comfyui_search_roots() -> Vec<PathBuf> {let mut out = Vec::new();let h = home();@@ -450,6 +471,10 @@ pub fn comfyui_search_roots() -> Vec<PathBuf> {/// Default ComfyUI install target — where install_comfyui will drop the/// portable bundle on Windows / clone the repo on macOS+Linux.+/// Only the path-inventory test in `app_identity.rs` calls this today — no+/// production caller is left, so it is dead in the `bin` target and alive in the+/// `test` one. Same standing decision as the helpers above.+#[allow(dead_code)]pub fn default_comfyui_dir() -> PathBuf {data_dir().join("ComfyUI")}diff --git a/src-tauri/src/test_support.rs b/src-tauri/src/test_support.rsindex 122755a6..a6449ab5 100644--- a/src-tauri/src/test_support.rs+++ b/src-tauri/src/test_support.rs@@ -304,6 +304,118 @@ pub(crate) fn worker_descendants_of(root: u32) -> Vec<u32> {// ── Tests for the helpers themselves ──────────────────────────────────────+// ── Ports, stand-ins and the process table ────────────────────────────────+//+// Three things every test that scans the REAL process table needs, in one+// place instead of once per module. `commands/remote.rs` grew them first, for+// the cloudflared sweep; `commands/process.rs` needed the same three for the+// ComfyUI adoption scan and copying them would have meant two versions of an+// argument that took a day to get right.++/// A port number the kernel will not hand to anybody else for as long as the+/// returned listener is alive.+///+/// Tests that need a port NUMBER rather than a socket — because the thing under+/// test matches on a command line, not on a connection — used to write a+/// constant. A constant is shared by every concurrent copy of the same test+/// binary, and that is not hypothetical: with a hard-coded 61888, a second+/// suite running the ComfyUI adoption test at the same moment put a second+/// stand-in with the identical argv into the table, and the scan returned+/// whichever the iteration reached first. Measured over a 0/300/600/1000 ms+/// delay series under three concurrent suites, every one of the nine failures+/// was that: a found pid HIGHER than the test's own, i.e. a stranger's.+///+/// Binding `:0` and holding the socket removes the collision at the source: the+/// kernel does not assign a bound port to a second `bind(0)`, so two concurrent+/// copies of a test cannot draw the same number. Keep the listener in scope for+/// as long as the number has to stay yours.+pub(crate) fn reserved_port() -> (u16, std::net::TcpListener) {+ let listener = std::net::TcpListener::bind("127.0.0.1:0")+ .expect("the loopback interface refused an ephemeral port");+ let port = listener+ .local_addr()+ .expect("a bound listener has a local address")+ .port();+ (port, listener)+}++/// Path to `examples/park`, the compiled do-nothing stand-in.+///+/// Why a compiled binary and not a copy of `/bin/sh`: the full argument is in+/// the header of `src-tauri/examples/park.rs`. The short version is that macOS+/// SIGKILLs a copy of a SIP platform binary within a few hundred milliseconds,+/// so a test built on one is racing the kernel; a binary this toolchain+/// produced is ad-hoc signed and is left alone.+///+/// `cargo test` builds examples, so it is there whenever the tests are, and it+/// lives next to the test binary: `target/<profile>/deps/<test binary>` →+/// `target/<profile>/examples/park`.+#[cfg(unix)]+pub(crate) fn park_binary() -> PathBuf {+ let exe = std::env::current_exe().expect("current_exe");+ let park = exe+ .parent()+ .and_then(|deps| deps.parent())+ .map(|profile| profile.join("examples").join("park"))+ .expect("no target/<profile>/ above the test binary");+ assert!(+ park.is_file(),+ "{} is missing. It is `src-tauri/examples/park.rs`, which `cargo test` builds \+ alongside the tests; if it is gone, the tests that spawn it are not measuring \+ anything.",+ park.display(),+ );+ park+}++/// A process table that has PROVEN itself, or the reason it could not.+///+/// The check is an invariant that cannot be false when the enumeration worked:+/// this very process is running, so a table without it was not read at all.+/// That is not a theoretical concern — sysinfo-0.33.1's macOS+/// `refresh_processes_specifics` takes its pids from `get_proc_list()`, and when+/// that returns `None` (its second `proc_listallpids` filling the buffer the+/// first one sized) the function returns 0 and leaves the list untouched, so a+/// fresh `System` comes back EMPTY with no error anywhere.+///+/// Retrying is therefore not hope: every retry is gated on a check, and the+/// caller only ever asserts on a snapshot that passed. Between the check and the+/// assertion there is no clock, no syscall and no other thread — the assertions+/// are a pure function of data already in hand.+#[cfg(unix)]+pub(crate) fn checked_table(pid: u32) -> Result<sysinfo::System, String> {+ use std::time::{Duration, Instant};+ let me = sysinfo::Pid::from_u32(std::process::id());+ let deadline = Instant::now() + Duration::from_secs(10);+ let mut attempts = 0usize;+ let mut blind = 0usize;+ loop {+ if Instant::now() >= deadline {+ return Err(format!(+ "no usable process table in 10s ({attempts} attempts, {blind} of them \+ without this test's own process in them). That is the TEST ENVIRONMENT, \+ not the code under test."+ ));+ }+ if attempts > 0 {+ // Paces retries so a pathological environment does not spin a core.+ // It is not what makes the result correct — the checks below are.+ std::thread::sleep(Duration::from_millis(20));+ }+ attempts += 1;+ let sys = crate::process_util::process_table_with_cmdlines();+ if sys.process(me).is_none() {+ blind += 1;+ continue;+ }+ if sys.process(sysinfo::Pid::from_u32(pid)).is_none() {+ blind += 1;+ continue;+ }+ return Ok(sys);+ }+}+#[cfg(test)]mod tests {use super::*;