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(IPC): die Angriffsfläche der WebView schrumpft, der Datei-Jail hält was er verspricht
David3218b16c0892
diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex 0445159f..3cbb4ddf 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -1,7 +1,7 @@{"$schema": "../gen/schemas/desktop-schema.json","identifier": "default",- "description": "Capability for the main window",+ "description": "Main-window capability. shell:allow-spawn is the only permission here that can start a process, and it is scoped to the two package runners external MCP servers are actually launched with (npx, uvx). Every general-purpose interpreter and container runtime was removed: node, deno, bun, python and py all take a one-shot eval flag (node -e, python -c), npm/pnpm/yarn run whatever a package.json in the cwd defines, and docker run -v /:/host hands out the whole disk. With those in the allow-list, any script-execution bug in the WebView (a PDF viewer, a markdown renderer, a dependency) was code execution on the user's machine rather than defacement inside the app.","windows": ["main"],"permissions": ["core:default",@@ -19,26 +19,7 @@"allow": [{ "name": "npx", "cmd": "npx", "args": true },{ "name": "npx.cmd", "cmd": "npx.cmd", "args": true },- { "name": "npm", "cmd": "npm", "args": true },- { "name": "npm.cmd", "cmd": "npm.cmd", "args": true },- { "name": "pnpm", "cmd": "pnpm", "args": true },- { "name": "pnpm.cmd", "cmd": "pnpm.cmd", "args": true },- { "name": "yarn", "cmd": "yarn", "args": true },- { "name": "yarn.cmd", "cmd": "yarn.cmd", "args": true },- { "name": "bun", "cmd": "bun", "args": true },- { "name": "bun.cmd", "cmd": "bun.cmd", "args": true },- { "name": "bunx", "cmd": "bunx", "args": true },- { "name": "bunx.cmd", "cmd": "bunx.cmd", "args": true },- { "name": "node", "cmd": "node", "args": true },- { "name": "node.cmd", "cmd": "node.cmd", "args": true },- { "name": "deno", "cmd": "deno", "args": true },- { "name": "deno.cmd", "cmd": "deno.cmd", "args": true },- { "name": "uv", "cmd": "uv", "args": true },- { "name": "uvx", "cmd": "uvx", "args": true },- { "name": "python", "cmd": "python", "args": true },- { "name": "python3", "cmd": "python3", "args": true },- { "name": "py", "cmd": "py", "args": true },- { "name": "docker", "cmd": "docker", "args": true }+ { "name": "uvx", "cmd": "uvx", "args": true }]},"shell:allow-stdin-write",diff --git a/src-tauri/gen/schemas/capabilities.json b/src-tauri/gen/schemas/capabilities.jsonindex b32bc965..511e60d3 100644--- a/src-tauri/gen/schemas/capabilities.json+++ b/src-tauri/gen/schemas/capabilities.json@@ -1 +1 @@-{"default":{"identifier":"default","description":"Capability for the main window","local":true,"windows":["main"],"permissions":["core:default","core:window:default","core:window:allow-minimize","core:window:allow-maximize","core:window:allow-unmaximize","core:window:allow-close","core:window:allow-is-maximized","core:window:allow-toggle-maximize","core:window:allow-start-dragging","core:webview:default",{"identifier":"shell:allow-spawn","allow":[{"args":true,"cmd":"npx","name":"npx"},{"args":true,"cmd":"npx.cmd","name":"npx.cmd"},{"args":true,"cmd":"npm","name":"npm"},{"args":true,"cmd":"npm.cmd","name":"npm.cmd"},{"args":true,"cmd":"pnpm","name":"pnpm"},{"args":true,"cmd":"pnpm.cmd","name":"pnpm.cmd"},{"args":true,"cmd":"yarn","name":"yarn"},{"args":true,"cmd":"yarn.cmd","name":"yarn.cmd"},{"args":true,"cmd":"bun","name":"bun"},{"args":true,"cmd":"bun.cmd","name":"bun.cmd"},{"args":true,"cmd":"bunx","name":"bunx"},{"args":true,"cmd":"bunx.cmd","name":"bunx.cmd"},{"args":true,"cmd":"node","name":"node"},{"args":true,"cmd":"node.cmd","name":"node.cmd"},{"args":true,"cmd":"deno","name":"deno"},{"args":true,"cmd":"deno.cmd","name":"deno.cmd"},{"args":true,"cmd":"uv","name":"uv"},{"args":true,"cmd":"uvx","name":"uvx"},{"args":true,"cmd":"python","name":"python"},{"args":true,"cmd":"python3","name":"python3"},{"args":true,"cmd":"py","name":"py"},{"args":true,"cmd":"docker","name":"docker"}]},"shell:allow-stdin-write","shell:allow-kill","shell:allow-open","updater:default"]}}\ No newline at end of file+{"default":{"identifier":"default","description":"Main-window capability. shell:allow-spawn is the only permission here that can start a process, and it is scoped to the two package runners external MCP servers are actually launched with (npx, uvx). Every general-purpose interpreter and container runtime was removed: node, deno, bun, python and py all take a one-shot eval flag (node -e, python -c), npm/pnpm/yarn run whatever a package.json in the cwd defines, and docker run -v /:/host hands out the whole disk. With those in the allow-list, any script-execution bug in the WebView (a PDF viewer, a markdown renderer, a dependency) was code execution on the user's machine rather than defacement inside the app.","local":true,"windows":["main"],"permissions":["core:default","core:window:default","core:window:allow-minimize","core:window:allow-maximize","core:window:allow-unmaximize","core:window:allow-close","core:window:allow-is-maximized","core:window:allow-toggle-maximize","core:window:allow-start-dragging","core:webview:default",{"identifier":"shell:allow-spawn","allow":[{"args":true,"cmd":"npx","name":"npx"},{"args":true,"cmd":"npx.cmd","name":"npx.cmd"},{"args":true,"cmd":"uvx","name":"uvx"}]},"shell:allow-stdin-write","shell:allow-kill","shell:allow-open","updater:default"]}}\ No newline at end of filediff --git a/src-tauri/src/commands/agent.rs b/src-tauri/src/commands/agent.rsindex 72a4755d..5e1e2905 100644--- a/src-tauri/src/commands/agent.rs+++ b/src-tauri/src/commands/agent.rs@@ -409,6 +409,50 @@ pub async fn execute_code(.map_err(|e| format!("Code execution task failed to run: {e}"))?}+/// Put the agent's script somewhere only this user can read it, under a name+/// nobody can guess, and hand back the directory that owns its lifetime.+///+/// It used to be `<shared temp>/agent-code-<millis>.py`, executed by that exact+/// path. Both halves are the problem: a millisecond timestamp is guessable by+/// any process on the machine, and the shared temp directory is world-readable+/// — the script (which carries whatever the user or the model put in it, file+/// paths included) was readable by every account on the box, and a racing local+/// process could swap the file between the write and the spawn.+///+/// `TempDir` creates a directory with a random name and removes it with its+/// contents when the returned handle drops — including on every early return of+/// the caller. The 0700 mode is passed to `mkdir` itself rather than chmod'ed+/// afterwards (tempfile defaults to the umask, i.e. 0755), so the directory is+/// never briefly readable. The file is created with `create_new`, so a+/// pre-placed name is an error rather than a target, and 0600.+fn write_private_script(code: &str) -> Result<(tempfile::TempDir, PathBuf), String> {+ use std::io::Write;+ let mut builder = tempfile::Builder::new();+ builder.prefix("lu-agent-code-");+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ builder.permissions(std::fs::Permissions::from_mode(0o700));+ }+ let dir = builder+ .tempdir()+ .map_err(|e| format!("Create temp dir: {}", os_error::english(&e)))?;+ let path = dir.path().join("agent-code.py");+ let mut opts = fs::OpenOptions::new();+ opts.write(true).create_new(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ opts.mode(0o600);+ }+ let mut file = opts+ .open(&path)+ .map_err(|e| format!("Write temp script: {}", os_error::english(&e)))?;+ file.write_all(code.as_bytes())+ .map_err(|e| format!("Write temp script: {}", os_error::english(&e)))?;+ Ok((dir, path))+}+#[allow(non_snake_case)]pub(crate) fn execute_code_blocking(code: String,@@ -419,14 +463,9 @@ pub(crate) fn execute_code_blocking() -> Result<serde_json::Value, String> {let timeout_ms = timeout.unwrap_or(30000);- let tmp_dir = std::env::temp_dir();- let script_path = tmp_dir.join(format!("agent-code-{}.py", std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.as_millis())- .unwrap_or(0)));-- fs::write(&script_path, &code)- .map_err(|e| format!("Write temp script: {}", os_error::english(&e)))?;+ // The handle is never read, only held: dropping it deletes the directory,+ // and it must outlive the interpreter that is running the script in it.+ let (_script_dir, script_path) = write_private_script(&code)?;// cwd: prefer the agent's folder workspace (the repo the user picked,// threaded from chatCtx as workingDirectory) so a script's relative file@@ -472,7 +511,6 @@ pub(crate) fn execute_code_blocking(match child.try_wait() {Ok(Some(status)) => {super::shell::settle(&out_done, &err_done, std::time::Duration::from_millis(500));- let _ = fs::remove_file(&script_path);return Ok(serde_json::json!({"stdout": super::shell::captured_text(&out_buf),"stderr": super::shell::captured_text(&err_buf),@@ -486,7 +524,6 @@ pub(crate) fn execute_code_blocking(let _ = child.kill();let _ = child.wait();super::shell::settle(&out_done, &err_done, std::time::Duration::from_millis(200));- let _ = fs::remove_file(&script_path);let mut stderr_str = super::shell::captured_text(&err_buf);if !stderr_str.is_empty() {stderr_str.push('\n');@@ -502,7 +539,6 @@ pub(crate) fn execute_code_blocking(std::thread::sleep(std::time::Duration::from_millis(50));}Err(e) => {- let _ = fs::remove_file(&script_path);return Err(format!("Wait error: {}", e));}}@@ -584,14 +620,32 @@ pub fn set_chat_workspace_override(path: Option<String>,state: State<'_, AppState>,) -> Result<(), String> {- let id = chatId.trim();+ set_chat_workspace_override_impl(&chatId, path.as_deref(), state.inner())+}++/// The body of the command above, minus the `State` wrapper — the validation+/// it performs is the reason it needs to be reachable from a test.+pub(crate) fn set_chat_workspace_override_impl(+ chat_id: &str,+ path: Option<&str>,+ state: &AppState,+) -> Result<(), String> {+ let id = chat_id.trim();if id.is_empty() {return Err("chatId cannot be empty".into());}let mut map = state.chat_workspace_overrides.lock().map_err(|e| e.to_string())?;- match path.as_ref().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) {+ match path.map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) {Some(p) => {let pb = std::path::PathBuf::from(p);+ // This path becomes a JAIL ROOT for every later file op of this+ // chat, including the ones the remote bridge serves — so it is+ // checked here, once, instead of being trusted on every call. It is+ // then remembered as a user-picked root, which is what lets a+ // folder outside the structural rules (a mount point, a short path)+ // work once the user has actually chosen it in the dialog.+ crate::commands::filesystem::validate_workspace_root(&pb)?;+ crate::commands::filesystem::remember_picked_root(&pb);// Best-effort: create the folder if missing so the first// file_write doesn't fail with "no such directory".let _ = std::fs::create_dir_all(&pb);@@ -712,3 +766,116 @@ mod read_tests {assert_eq!(format_bytes(3 * 1024 * 1024 * 1024), "3.0 GB");}}++/// The agent's script is code, and it used to be written to a world-readable+/// temp path whose name was a millisecond timestamp — guessable, and swappable+/// between the write and the spawn.+#[cfg(test)]+mod script_file_tests {+ use super::*;++ #[test]+ fn the_script_lands_in_a_private_directory_under_an_unguessable_name() {+ let (dir_a, path_a) = write_private_script("print('a')").expect("write");+ let (dir_b, path_b) = write_private_script("print('b')").expect("write");++ assert_eq!(fs::read_to_string(&path_a).unwrap(), "print('a')");+ assert_ne!(dir_a.path(), dir_b.path(), "two runs shared a directory");+ // No timestamp, no pid: nothing a second process can compute.+ let name = dir_a.path().file_name().unwrap().to_string_lossy().to_string();+ let suffix = name.trim_start_matches("lu-agent-code-");+ assert!(suffix.len() >= 6, "name is too short to be unguessable: {name}");+ assert!(+ !suffix.chars().all(|c| c.is_ascii_digit()),+ "the name is a plain number again: {name}",+ );+ drop(dir_b);+ assert!(!path_b.exists(), "the script outlived its handle");+ }++ #[cfg(unix)]+ #[test]+ fn nothing_outside_this_user_can_read_the_script() {+ use std::os::unix::fs::PermissionsExt;+ let (dir, path) = write_private_script("print('secret')").expect("write");++ let dmode = fs::metadata(dir.path()).unwrap().permissions().mode() & 0o777;+ assert_eq!(dmode, 0o700, "temp dir is {dmode:o}, not 0700");+ let fmode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;+ assert_eq!(fmode & 0o077, 0, "script is group/world accessible: {fmode:o}");+ }++ /// The whole directory goes with the handle, so no early return can leave+ /// the script behind.+ #[test]+ fn dropping_the_handle_removes_the_directory() {+ let (dir, path) = write_private_script("print('x')").expect("write");+ let dir_path = dir.path().to_path_buf();+ drop(dir);+ assert!(!path.exists());+ assert!(!dir_path.exists());+ }++ /// A name that already exists is an error, never a target: `create_new`+ /// keeps a pre-placed file (or symlink) from being written through.+ #[test]+ fn an_existing_file_is_not_written_through() {+ let (dir, path) = write_private_script("print('first')").expect("write");+ let mut opts = fs::OpenOptions::new();+ opts.write(true).create_new(true);+ assert!(opts.open(&path).is_err(), "create_new accepted an existing path");+ drop(dir);+ }+}++/// The override path becomes a JAIL ROOT for every later file op of that chat,+/// including the ones the remote HTTP bridge serves — so it is checked when it+/// is set, not trusted on every call.+#[cfg(test)]+mod workspace_override_tests {+ use super::*;++ #[test]+ fn a_system_or_home_root_is_refused() {+ let state = AppState::new();+ let home = dirs::home_dir().unwrap_or_default();+ let home_s = home.to_string_lossy().to_string();+ let ssh = home.join(".ssh").to_string_lossy().to_string();+ let roots: Vec<&str> = if cfg!(windows) {+ vec!["C:/", "C:/Windows", &home_s, &ssh]+ } else {+ vec!["/", "/etc", &home_s, &ssh]+ };+ for root in roots {+ let got = set_chat_workspace_override_impl("__remote__", Some(root), &state);+ assert!(got.is_err(), "{root:?} was accepted as a workspace override");+ }+ assert!(+ state.chat_workspace_overrides.lock().unwrap().is_empty(),+ "a refused root was still stored",+ );+ }++ /// The real flow: the user picks a folder, it is stored, and it is+ /// remembered as picked so the fs tools accept it as a root.+ #[test]+ fn a_picked_project_folder_is_stored_and_trusted_afterwards() {+ let state = AppState::new();+ let dir = std::env::temp_dir().join(format!("lu-ovr-{}", std::process::id()));+ let _ = fs::remove_dir_all(&dir);+ let s = dir.to_string_lossy().to_string();++ set_chat_workspace_override_impl("__remote__", Some(&s), &state).expect("accepted");+ assert_eq!(+ state.chat_workspace_overrides.lock().unwrap().get("__remote__"),+ Some(&dir),+ );+ assert!(dir.is_dir(), "the folder was not created");+ assert!(crate::commands::filesystem::validate_workspace_root(&dir).is_ok());++ // Clearing still works and takes the entry with it.+ set_chat_workspace_override_impl("__remote__", None, &state).expect("cleared");+ assert!(state.chat_workspace_overrides.lock().unwrap().is_empty());+ let _ = fs::remove_dir_all(&dir);+ }+}diff --git a/src-tauri/src/commands/bg_tasks.rs b/src-tauri/src/commands/bg_tasks.rsindex 12166d53..3f846319 100644--- a/src-tauri/src/commands/bg_tasks.rs+++ b/src-tauri/src/commands/bg_tasks.rs@@ -55,6 +55,10 @@ struct BgTaskInner {output_buf: Vec<u8>,/// Send `()` to ask the reader task to terminate the child.cancel_tx: Option<tokio::sync::oneshot::Sender<()>>,+ /// The shell's pid, kept out of the serialized status. The reader task owns+ /// the `Child`, so this is the only handle the shutdown sweep below has on+ /// a task it must kill.+ pid: Option<u32>,}#[derive(Clone)]@@ -232,7 +236,9 @@ pub(crate) async fn shell_task_start_impl(args: &Value) -> CmdResult {},output_buf: Vec::with_capacity(8 * 1024),cancel_tx: Some(cancel_tx),+ pid: child.id(),}));+ arm_exit_sweep();REGISTRY.insert(BgTask {inner: Arc::clone(&inner),@@ -306,6 +312,9 @@ pub(crate) async fn shell_task_start_impl(args: &Value) -> CmdResult {g.status.finished_at = Some(now_secs());g.status.output_tail = render_tail(&g.output_buf);g.cancel_tx = None;+ // Drop the pid with the process: the OS may hand that number to a+ // stranger, and the shutdown sweep would then kill their tree.+ g.pid = None;});Ok(json!({ "id": id }))@@ -344,6 +353,71 @@ pub(crate) async fn shell_task_kill_impl(args: &Value) -> CmdResult {}}+/// Kill every still-running background task, children included.+///+/// These tasks exist for `pnpm install` / `cargo build`, so they are long-lived+/// by design and their trees are deep. Windows ties each one to a kill-on-close+/// Job Object at spawn, so LU dying takes them along; macOS and Linux have no+/// equivalent, and `AppState::shutdown_subprocesses` only knows the pids IT+/// holds — never this process-wide REGISTRY. A background build therefore+/// outlived every quit, forever, still holding its port and CPU.+// On Windows only the tests reach it — the Job Object gets there first.+#[cfg_attr(target_os = "windows", allow(dead_code))]+pub(crate) fn kill_all_background_tasks() {+ let pids: Vec<u32> = {+ // try_lock, not lock: this also runs from the process-exit hook, where+ // a thread that is holding the registry mutex may never be scheduled+ // again. Losing the sweep beats hanging the quit.+ let mut got = None;+ for _ in 0..20 {+ if let Ok(g) = REGISTRY.tasks.try_lock() {+ got = Some(+ g.iter()+ .filter_map(|t| {+ let inner = t.inner.try_lock().ok()?;+ inner.status.running.then_some(inner.pid).flatten()+ })+ .collect::<Vec<u32>>(),+ );+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(10));+ }+ match got {+ Some(p) => p,+ None => return,+ }+ };+ for pid in pids {+ crate::commands::shell::kill_tree(pid);+ }+}++/// Run the sweep when the process exits.+///+/// Every quit path ends in `exit()` — the tray Quit, `exit_app`, the updater,+/// Tauri's own `RunEvent::Exit` — and a C `atexit` handler fires on all of+/// them, including the ones that never construct or drop `AppState`. Windows+/// needs none of this: the Job Object from `shell_task_start_impl` already+/// kills the tree when the app's handle closes.+#[cfg(not(target_os = "windows"))]+fn arm_exit_sweep() {+ use std::sync::Once;+ static ARMED: Once = Once::new();+ extern "C" fn sweep() {+ kill_all_background_tasks();+ }+ extern "C" {+ fn atexit(cb: extern "C" fn()) -> std::os::raw::c_int;+ }+ ARMED.call_once(|| unsafe {+ atexit(sweep);+ });+}++#[cfg(target_os = "windows")]+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.@@ -541,6 +615,91 @@ mod cancel_tests {}}+/// Shutdown sweep (audit: bg tasks were only tied to the app's lifetime on+/// Windows). The atexit registration itself cannot be exercised in-process —+/// the handler runs after the test harness is gone — so the sweep it calls is+/// tested directly, with a real tree.+#[cfg(test)]+mod shutdown_sweep_tests {+ use super::*;++ fn alive(pid: u32) -> bool {+ let out = std::process::Command::new("ps")+ .args(["-o", "state=", "-p", &pid.to_string()])+ .output();+ match out {+ Ok(o) => {+ let st = String::from_utf8_lossy(&o.stdout).trim().to_string();+ !st.is_empty() && !st.starts_with('Z')+ }+ Err(_) => false,+ }+ }++ #[tokio::test]+ #[cfg_attr(target_os = "windows", ignore = "uses sh/ps; Windows has the Job Object")]+ async fn quitting_takes_a_running_task_and_its_children_with_it() {+ let start = shell_task_start_impl(&json!({+ "command": "sleep 30 & echo $! ; wait",+ "shell": "sh",+ }))+ .await+ .expect("start");+ let id = start["id"].as_str().expect("id").to_string();++ let mut grandchild = None;+ for _ in 0..50 {+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ let st = shell_task_status_impl(&json!({ "id": id })).await.expect("status");+ let tail = st["output_tail"].as_str().unwrap_or("");+ if let Some(line) = tail.lines().find(|l| l.trim().parse::<u32>().is_ok()) {+ grandchild = line.trim().parse::<u32>().ok();+ break;+ }+ }+ let grandchild = grandchild.expect("grandchild never reported its pid");+ let shell_pid = REGISTRY+ .get(&id)+ .and_then(|t| t.inner.lock().unwrap().pid)+ .expect("a running task must carry its pid");+ assert!(alive(shell_pid) && alive(grandchild), "test setup is wrong");++ kill_all_background_tasks();++ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);+ while alive(shell_pid) || alive(grandchild) {+ assert!(+ std::time::Instant::now() < deadline,+ "the quit sweep left {shell_pid}/{grandchild} running",+ );+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ }+ }++ /// A finished task's pid may already belong to somebody else — the sweep+ /// must never fire at it. Sweeping an idle registry must also not panic.+ #[tokio::test]+ #[cfg_attr(target_os = "windows", ignore = "uses sh")]+ async fn a_finished_task_is_not_swept() {+ let start = shell_task_start_impl(&json!({ "command": "true", "shell": "sh" }))+ .await+ .expect("start");+ let id = start["id"].as_str().unwrap().to_string();+ for _ in 0..50 {+ let st = shell_task_status_impl(&json!({ "id": id })).await.unwrap();+ if !st["running"].as_bool().unwrap_or(true) {+ break;+ }+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ }+ assert!(+ REGISTRY.get(&id).and_then(|t| t.inner.lock().unwrap().pid).is_none(),+ "a finished task still carries a pid the sweep could kill",+ );+ kill_all_background_tasks();+ }+}+#[cfg(test)]mod cwd_default_tests {use super::*;diff --git a/src-tauri/src/commands/filesystem.rs b/src-tauri/src/commands/filesystem.rsindex 4d88b5c5..e19a9f3c 100644--- a/src-tauri/src/commands/filesystem.rs+++ b/src-tauri/src/commands/filesystem.rs@@ -1,10 +1,12 @@use crate::os_error;use std::fs;use std::path::{Path, PathBuf};+use std::sync::Mutex;use std::time::UNIX_EPOCH;use base64::Engine;use glob::glob as glob_match;+use once_cell::sync::Lazy;use regex::RegexBuilder;use walkdir::WalkDir;@@ -47,32 +49,81 @@ fn lexical_normalize(p: &Path) -> PathBuf {out}+/// Resolve symlinks as far as the path actually exists, then re-attach the+/// rest verbatim.+///+/// Plain `canonicalize` is unusable here because half the paths that reach the+/// jail don't exist yet (`file_write` creating a new file), and plain lexical+/// normalization is unusable as a *boundary* because it believes the path+/// string: a symlink inside the workspace pointing at `~/.ssh` reads as+/// `<root>/link/id_rsa` and sails through containment while the open() behind+/// it lands outside. Canonicalizing the deepest EXISTING ancestor covers both —+/// the link is resolved, the not-yet-created tail is kept.+fn resolve_existing_prefix(p: &Path) -> PathBuf {+ let normalized = lexical_normalize(p);+ let mut tail: Vec<std::ffi::OsString> = Vec::new();+ let mut cur = normalized.clone();+ loop {+ if let Ok(real) = fs::canonicalize(&cur) {+ let mut out = real;+ for seg in tail.iter().rev() {+ out.push(seg);+ }+ return out;+ }+ let name = match cur.file_name() {+ Some(n) => n.to_os_string(),+ None => return normalized, // hit a root / prefix: nothing exists+ };+ let parent = match cur.parent() {+ Some(par) if par != cur && !par.as_os_str().is_empty() => par.to_path_buf(),+ _ => return normalized,+ };+ tail.push(name);+ cur = parent;+ }+}++/// True when `cand` is `root` or lives under it, compared on normalized paths+/// with a component boundary so `…/foo` never matches `…/foobar`.+fn is_within(root: &Path, cand: &Path) -> bool {+ #[cfg(windows)]+ {+ // Windows paths are case-insensitive; compare lowercased. Both sides go+ // through the SAME key builder (which strips any `\\?\` verbatim prefix)+ // so an extended-length root and a plain candidate — or vice versa —+ // still compare equal.+ let r = win_compare_key(root);+ let c = win_compare_key(cand);+ c == r || c.starts_with(&format!("{}/", r))+ }+ #[cfg(not(windows))]+ {+ cand == root || cand.starts_with(root)+ }+}+/// Jail `candidate` to `root`: return the normalized path when it stays inside/// `root`, otherwise an error. This is the single containment boundary for/// every agent/remote file op — it stops a prompt-injected model or a remote/// client from reading `~/.ssh/id_rsa`, writing into `\Startup\`, or `..`-ing/// out of the workspace. Absolute paths are allowed ONLY when they fall within/// `root`, so the desktop coding agent can still use absolute paths inside the-/// user-picked project folder (#62). Symlink-based escape is a residual (it-/// needs a prior local write) and is intentionally out of scope here.+/// user-picked project folder (#62).+///+/// The DECISION is made on symlink-resolved paths, the RETURNED path is the+/// lexical one the caller asked for: canonicalize() hands back `\\?\C:\…` on+/// Windows and `/private/var/…` on macOS, and that string is echoed to the UI+/// and compared in the frontend. Opening the lexical path is equivalent —+/// its link target was just proven to be inside the root.pub(crate) fn contain_within(root: &Path, candidate: &Path) -> Result<PathBuf, String> {let nroot = lexical_normalize(root);let ncand = lexical_normalize(candidate);- let within = {- #[cfg(windows)]- {- // Windows paths are case-insensitive; compare lowercased with a- // component boundary so `…/foo` can't match `…/foobar`. Both sides- // go through the SAME key builder (which strips any `\\?\` verbatim- // prefix) so an extended-length root and a plain candidate — or vice- // versa — still compare equal.- let r = win_compare_key(&nroot);- let c = win_compare_key(&ncand);- c == r || c.starts_with(&format!("{}/", r))- }- #[cfg(not(windows))]- { ncand == nroot || ncand.starts_with(&nroot) }- };+ let within = is_within(&nroot, &ncand)+ && is_within(+ &resolve_existing_prefix(&nroot),+ &resolve_existing_prefix(&ncand),+ );if within {Ok(ncand)} else {@@ -108,29 +159,177 @@ fn win_compare_key(p: &Path) -> String {/// The jail root for a file op: a configured folder workspace `working_dir`/// (the repo the user picked, threaded from the frontend as `workingDirectory`)/// when set; otherwise the per-chat sandbox `~/agent-workspace/<chat_id>/`.-/// `chat_id` is sanitised to `[A-Za-z0-9_\-\.]` (else `_`), capped at 64 chars.+///+/// The `chat_id` slug goes through `agent::sanitize_chat_slug`, which is the+/// ONLY sanitiser in the tree that drops `.`. This function used to keep its+/// own copy that allowed it, so a chat id of `".."` made the root+/// `~/agent-workspace/..` == `$HOME` and every containment check below it+/// passed for the whole home directory (audit IPC-1) — the hole was fixed in+/// agent.rs and left standing in this copy.+///+/// NOTE: this is a path derivation, not a permission check. A caller-supplied+/// `working_dir` is only trustworthy once `check_workspace_root` has passed;+/// `resolve_path` does that, direct callers must decide for themselves.pub(crate) fn workspace_root(chat_id: Option<&str>, working_dir: Option<&str>) -> PathBuf {if let Some(wd) = working_dir.map(str::trim).filter(|w| !w.is_empty()) {return PathBuf::from(wd);}- let id = chat_id.unwrap_or("default");- let safe: String = id- .chars()- .take(64)- .map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' { c } else { '_' })- .collect();- let slug = if safe.is_empty() { "default".to_string() } else { safe };+ let slug = crate::commands::agent::sanitize_chat_slug(chat_id.unwrap_or("default"));dirs::home_dir().unwrap_or_default().join("agent-workspace").join(slug)}+/// Folders the user picked in a native dialog this run. A registered root is+/// trusted verbatim; everything else has to pass `check_workspace_root`.+static PICKED_ROOTS: Lazy<Mutex<Vec<PathBuf>>> = Lazy::new(|| Mutex::new(Vec::new()));++/// Record a folder the USER chose in a native dialog as a legitimate workspace+/// root. Called by `set_chat_workspace_override` (the Remote dispatch picker).+pub(crate) fn remember_picked_root(root: &Path) {+ let norm = lexical_normalize(root);+ if let Ok(mut roots) = PICKED_ROOTS.lock() {+ if !roots.iter().any(|r| r == &norm) {+ roots.push(norm);+ }+ }+}++/// Directories that are never a project workspace, only a target.+fn forbidden_root_prefixes() -> Vec<PathBuf> {+ let home = dirs::home_dir();+ let mut system: Vec<PathBuf> = Vec::new();+ #[cfg(not(windows))]+ for p in [+ "/etc", "/private/etc", "/dev", "/proc", "/sys", "/boot", "/root",+ "/var/root", "/usr", "/bin", "/sbin", "/System", "/Library",+ ] {+ system.push(PathBuf::from(p));+ }+ #[cfg(windows)]+ {+ let drive = std::env::var("SystemDrive").unwrap_or_else(|_| "C:".to_string());+ for rel in ["Windows", "Program Files", "Program Files (x86)", "ProgramData"] {+ system.push(PathBuf::from(format!("{}\\{}", drive, rel)));+ }+ }+ // A "system" directory that CONTAINS the user's home is not a system+ // directory for this user: with HOME=/root (containers, some Linux setups)+ // the agent workspace itself lives under /root.+ let mut out: Vec<PathBuf> = system+ .into_iter()+ .filter(|p| match &home {+ Some(h) => !is_within(&lexical_normalize(p), &lexical_normalize(h)),+ None => true,+ })+ .collect();+ if let Some(home) = home {+ // The credential stores an escaped jail was worth escaping FOR.+ for rel in [+ ".ssh", ".aws", ".gnupg", ".kube", ".docker", ".config", ".lu",+ "Library/Keychains", "AppData",+ ] {+ out.push(home.join(rel));+ }+ }+ out+}++/// Directories that hold OTHER people's homes or every mounted volume. Denied+/// as an exact root only — the folders inside them are ordinary workspaces.+fn forbidden_exact_roots() -> Vec<PathBuf> {+ let mut out: Vec<PathBuf> = ["/Users", "/home", "/Volumes", "/mnt", "/media"]+ .iter()+ .map(PathBuf::from)+ .collect();+ #[cfg(windows)]+ {+ let drive = std::env::var("SystemDrive").unwrap_or_else(|_| "C:".to_string());+ out.push(PathBuf::from(format!("{}\\Users", drive)));+ }+ if let Some(home) = dirs::home_dir() {+ out.push(home);+ }+ out+}++/// Count of NAMED components — `/` and `C:\` are 0, `/etc` is 1.+fn named_depth(p: &Path) -> usize {+ p.components()+ .filter(|c| matches!(c, std::path::Component::Normal(_)))+ .count()+}++/// Is this frontend-supplied path allowed to BE a jail root?+///+/// `contain_within` only ever answered "does the path stay inside the root" —+/// the root itself arrived from the WebView on every call and was taken on+/// faith, so `fs_read("/etc/shadow", null, "/")` passed containment perfectly+/// and read the file. The jail was only ever as narrow as the string the caller+/// chose for it.+///+/// A root is accepted when the user picked it in a native dialog (see+/// `remember_picked_root`), or, failing that, when it is structurally a project+/// folder: deep enough not to be a drive or filesystem root, not a container of+/// other people's homes, and not inside a system or credential directory. The+/// structural fallback exists because `system::pick_folder` — the one dialog+/// every folder choice goes through — does not register its result yet; without+/// it, enforcing the allowlist alone would refuse every workspace the user+/// picked in an earlier session.+fn check_workspace_root(root: &Path) -> Result<(), String> {+ let norm = lexical_normalize(root);+ if let Ok(roots) = PICKED_ROOTS.lock() {+ if roots.iter().any(|r| is_within(r, &norm)) {+ return Ok(());+ }+ }+ let refuse = |why: &str| {+ Err(format!(+ "Not an allowed workspace folder ({}): {}",+ why,+ root.display()+ ))+ };+ // `D:\Projects` is an ordinary Windows layout and only one component deep;+ // on Unix the same depth is `/etc` or `/var`, which is not.+ let min_depth = if cfg!(windows) { 1 } else { 2 };+ if named_depth(&norm) < min_depth {+ return refuse("a drive or filesystem root is not a workspace");+ }+ // Mutual containment == equality, and it stays case-insensitive on Windows+ // the way every other comparison in this file is.+ let same = |a: &Path, b: &Path| is_within(a, b) && is_within(b, a);+ for bad in forbidden_exact_roots() {+ if same(&lexical_normalize(&bad), &norm) {+ return refuse("a home or mount container is not a workspace");+ }+ }+ for bad in forbidden_root_prefixes() {+ if is_within(&lexical_normalize(&bad), &norm) {+ return refuse("system or credential directory");+ }+ }+ Ok(())+}++/// `check_workspace_root` for callers outside this module (the Remote dispatch+/// folder picker validates the folder before storing it as an override).+pub(crate) fn validate_workspace_root(root: &Path) -> Result<(), String> {+ check_workspace_root(root)+}+/// Resolve + CONTAIN a tool-call path. A relative path resolves against the/// workspace root (folder workspace #62, else the per-chat sandbox); an-/// absolute path is accepted only when it falls inside that root. Returns an-/// error on any escape (`..`, an out-of-root absolute path, etc.) — the+/// absolute path is accepted only when it falls inside that root.+///+/// Two checks, and they are not the same one: `check_workspace_root` decides+/// whether the caller-supplied root may be a jail at all, `contain_within`+/// decides whether the path stays inside it. Only both together are the/// security boundary for fs_read/fs_write/fs_list/fs_search/fs_info.fn resolve_path(path: &str, chat_id: Option<&str>, working_dir: Option<&str>) -> Result<PathBuf, String> {let cleaned = normalize_duplicate_drive_prefix(path);let root = workspace_root(chat_id, working_dir);+ if working_dir.map(str::trim).is_some_and(|w| !w.is_empty()) {+ check_workspace_root(&root)?;+ }let p = Path::new(&cleaned);let candidate = if p.is_absolute() { p.to_path_buf() } else { root.join(&cleaned) };contain_within(&root, &candidate)@@ -168,9 +367,25 @@ fn file_meta(path: &Path) -> serde_json::Value {})}+/// Reading a file is unbounded blocking IO — a multi-gigabyte model file on a+/// slow external disk takes as long as it takes. As a plain sync `#[command]`+/// that ran on the Tauri main thread, so the whole window froze for the+/// duration; the work goes to the blocking pool instead (same treatment as+/// `execute_code` and the shell tool).#[tauri::command]#[allow(non_snake_case)]-pub fn fs_read(path: String, chatId: Option<String>, workingDirectory: Option<String>) -> Result<serde_json::Value, String> {+pub async fn fs_read(+ path: String,+ chatId: Option<String>,+ workingDirectory: Option<String>,+) -> Result<serde_json::Value, String> {+ tauri::async_runtime::spawn_blocking(move || fs_read_sync(path, chatId, workingDirectory))+ .await+ .map_err(|e| format!("fs_read task failed to run: {e}"))?+}++#[allow(non_snake_case)]+pub(crate) fn fs_read_sync(path: String, chatId: Option<String>, workingDirectory: Option<String>) -> Result<serde_json::Value, String> {let full = resolve_path(&path, chatId.as_deref(), workingDirectory.as_deref())?;if !full.exists() {return Err(format!("File not found: {}", full.display()));@@ -398,7 +613,15 @@ pub fn fs_list(Ok(serde_json::json!({ "entries": entries, "count": entries.len() }))}-#[tauri::command]+/// Walks up to eight directory levels and reads every file under a megabyte:+/// on a real repo that is seconds of blocking IO, and as a plain sync+/// `#[command]` every one of those seconds was spent on the Tauri main thread+/// with the window frozen.+///+/// `#[command(async)]` — not an `async fn` — because this is also called+/// directly (not awaited) from the Remote bridge; the attribute keeps the+/// signature synchronous while Tauri runs the command off the main thread.+#[tauri::command(async)]#[allow(non_snake_case)]pub fn fs_search(path: String,@@ -863,6 +1086,143 @@ mod jail_adversarial_tests {}}+/// The root itself used to be taken on faith. `contain_within` answered+/// "does this path stay inside the root" perfectly — and the root arrived from+/// the WebView on every single call, so the jail was only ever as narrow as the+/// string the caller picked for it.+#[cfg(test)]+mod workspace_root_guard_tests {+ use super::*;++ #[test]+ fn a_root_that_is_not_a_project_folder_is_refused() {+ let home = dirs::home_dir().unwrap_or_default();+ let sensitive = home.join(".ssh").to_string_lossy().to_string();+ let home_s = home.to_string_lossy().to_string();+ let roots: Vec<&str> = if cfg!(windows) {+ vec!["C:/", "C:/Windows", "C:/Program Files", "C:/Users", &home_s, &sensitive]+ } else {+ vec!["/", "/etc", "/usr", "/Library", "/Users", "/home", &home_s, &sensitive]+ };+ for root in roots {+ let probe = if cfg!(windows) { "Windows/win.ini" } else { "hosts" };+ let got = resolve_path(probe, None, Some(root));+ assert!(got.is_err(), "root {root:?} was accepted as a workspace: {got:?}");+ }+ }++ /// The reported shape, verbatim: a root of `/` turns the containment check+ /// into a formality, because everything is inside `/`.+ #[test]+ #[cfg(not(windows))]+ fn the_filesystem_root_cannot_be_used_to_read_etc_shadow() {+ let err = resolve_path("/etc/shadow", None, Some("/")).expect_err("must refuse");+ assert!(err.contains("Not an allowed workspace folder"), "got: {err}");+ }++ /// The ordinary project folders — the cases that must keep working.+ #[test]+ fn an_ordinary_project_folder_is_still_a_valid_root() {+ let home = dirs::home_dir().unwrap_or_default();+ let under_home = home.join("dev").join("site").to_string_lossy().to_string();+ let mut roots = vec![under_home];+ if cfg!(windows) {+ // A second drive is a normal Windows layout and only ONE component+ // deep — the depth rule must not refuse it.+ roots.push("D:/Projects".to_string());+ roots.push("D:/Projects/site".to_string());+ } else {+ roots.push("/projects/site".to_string());+ roots.push("/Volumes/Work/site".to_string());+ }+ for root in roots {+ assert!(+ resolve_path("src/main.rs", Some("c"), Some(&root)).is_ok(),+ "root {root:?} was refused",+ );+ }+ }++ /// A folder the user picked in the native dialog is trusted verbatim, even+ /// when the structural rules would have refused it.+ #[test]+ fn a_folder_the_user_picked_is_trusted() {+ let odd = std::env::temp_dir().join(format!("lu-picked-{}", std::process::id()));+ let _ = fs::create_dir_all(&odd);+ remember_picked_root(&odd);+ let root = odd.to_string_lossy().to_string();+ assert!(resolve_path("notes.md", None, Some(&root)).is_ok());+ // Registering a root does NOT widen the jail inside it.+ assert!(resolve_path("../elsewhere.md", None, Some(&root)).is_err());+ let _ = fs::remove_dir_all(&odd);+ }++ /// filesystem.rs kept its own copy of the chat-id sanitiser, and that copy+ /// still allowed `.` — so a chat id of ".." made the sandbox root+ /// `~/agent-workspace/..` == `$HOME` (audit IPC-1, fixed in agent.rs only).+ #[test]+ fn a_dotdot_chat_id_cannot_move_the_sandbox_root_to_home() {+ let home = dirs::home_dir().unwrap_or_default();+ assert_eq!(+ workspace_root(Some(".."), None),+ home.join("agent-workspace").join("__"),+ );+ for id in ["..", ".", "../.."] {+ let target = home.join(".ssh").join("id_rsa");+ assert!(+ resolve_path(&target.to_string_lossy(), Some(id), None).is_err(),+ "chat id {id:?} still reaches {target:?}",+ );+ }+ }++ /// A path that does not exist yet must still resolve — file_write creates+ /// files, and the symlink hardening must not break that.+ #[test]+ fn a_file_that_does_not_exist_yet_still_resolves() {+ let ws = std::env::temp_dir().join(format!("lu-newfile-{}", std::process::id()));+ let _ = fs::create_dir_all(&ws);+ let root = ws.to_string_lossy().to_string();+ let got = resolve_path("deep/new/dir/notes.md", None, Some(&root)).expect("new path");+ assert!(got.ends_with("deep/new/dir/notes.md"), "got: {got:?}");+ let _ = fs::remove_dir_all(&ws);+ }++ /// Lexical normalization believes the path string. A symlink inside the+ /// workspace reads as `<root>/link/…` and passed containment, while the+ /// open() behind it landed wherever the link pointed.+ #[test]+ #[cfg(unix)]+ fn a_symlink_pointing_out_of_the_workspace_is_refused() {+ let base = std::env::temp_dir().join(format!("lu-symjail-{}", std::process::id()));+ let _ = fs::remove_dir_all(&base);+ let ws = base.join("workspace");+ let outside = base.join("outside");+ fs::create_dir_all(&ws).unwrap();+ fs::create_dir_all(&outside).unwrap();+ fs::write(outside.join("secret.txt"), b"private").unwrap();+ std::os::unix::fs::symlink(&outside, ws.join("escape")).unwrap();+ let root = ws.to_string_lossy().to_string();++ assert!(+ resolve_path("escape/secret.txt", None, Some(&root)).is_err(),+ "a symlink walked out of the workspace",+ );+ assert!(+ fs_read_sync("escape/secret.txt".into(), None, Some(root.clone())).is_err(),+ "fs_read followed the symlink out",+ );+ // A symlink that stays INSIDE the workspace is still fine.+ let inner = ws.join("real");+ fs::create_dir_all(&inner).unwrap();+ fs::write(inner.join("ok.txt"), b"fine").unwrap();+ std::os::unix::fs::symlink(&inner, ws.join("alias")).unwrap();+ assert!(resolve_path("alias/ok.txt", None, Some(&root)).is_ok());++ let _ = fs::remove_dir_all(&base);+ }+}+#[cfg(test)]mod binary_read_tests {use super::*;@@ -878,8 +1238,8 @@ mod binary_read_tests {/// A binary must come back as a MARKER, not as a payload. Every consumer/// discards the bytes, so encoding them only bought a memory spike/// proportional to the file — the phone relay already refused to do it.- #[test]- fn a_binary_file_reports_its_size_and_no_content() {+ #[tokio::test]+ async fn a_binary_file_reports_its_size_and_no_content() {let dir = ws("bin");// Invalid UTF-8 — what read_to_string rejects.fs::write(dir.join("model.gguf"), [0xff, 0xfe, 0x00, 0x01, 0x80]).unwrap();@@ -889,6 +1249,7 @@ mod binary_read_tests {None,Some(dir.to_string_lossy().to_string()),)+ .await.expect("read");assert_eq!(v["encoding"], "binary");@@ -897,12 +1258,13 @@ mod binary_read_tests {let _ = fs::remove_dir_all(&dir);}- #[test]- fn a_text_file_still_comes_back_verbatim() {+ #[tokio::test]+ async fn a_text_file_still_comes_back_verbatim() {let dir = ws("txt");fs::write(dir.join("a.txt"), "hallo\nwelt\n").unwrap();let v = fs_read("a.txt".into(), None, Some(dir.to_string_lossy().to_string()))+ .await.expect("read");assert_eq!(v["encoding"], "utf8");@@ -911,8 +1273,8 @@ mod binary_read_tests {}/// The whole point: cost must not scale with the file any more.- #[test]- fn a_large_binary_is_cheap_to_read() {+ #[tokio::test]+ async fn a_large_binary_is_cheap_to_read() {let dir = ws("big");let mut big = vec![0x80u8; 8 * 1024 * 1024]; // 8 MiB, invalid UTF-8big[0] = 0xff;@@ -920,6 +1282,7 @@ mod binary_read_tests {let started = std::time::Instant::now();let v = fs_read("big.bin".into(), None, Some(dir.to_string_lossy().to_string()))+ .await.expect("read");let took = started.elapsed();diff --git a/src-tauri/src/commands/shell.rs b/src-tauri/src/commands/shell.rsindex 32724bb7..cfeb77e9 100644--- a/src-tauri/src/commands/shell.rs+++ b/src-tauri/src/commands/shell.rs@@ -17,18 +17,16 @@ use std::path::{Path, PathBuf};/// SAME folder the file tools write to. Used as the fallback cwd when the/// caller doesn't pass one — without it the child process inherits the LU/// app's ambient cwd and dumps build output into ~/Documents (David 2026-06-04).+///+/// The slug comes from `agent::sanitize_chat_slug`, the one copy that drops+/// `.`: this file used to carry its own that kept it, so a chat id of ".."+/// resolved to `~/agent-workspace/..` == `$HOME` and the shell tool ran (and+/// created directories) straight in the user's home (audit IPC-1).fn workspace_cwd(chat_id: Option<&str>) -> PathBuf {- let id = chat_id.unwrap_or("default");- let safe: String = id- .chars()- .take(64)- .map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' { c } else { '_' })- .collect();- let slug = if safe.is_empty() { "default".to_string() } else { safe };dirs::home_dir().unwrap_or_default().join("agent-workspace")- .join(slug)+ .join(crate::commands::agent::sanitize_chat_slug(chat_id.unwrap_or("default")))}/// How much of a command's output travels back to the model. Anything past this@@ -340,6 +338,108 @@ fn shell_execute_sync(}}+/// The IPC surface itself, asserted against the shipped config files.+///+/// `shell:allow-spawn` is the only permission the WebView holds that starts a+/// process, and it used to list ~20 programs with `"args": true` — every+/// interpreter with a one-shot eval flag plus `docker`. Combined with+/// `withGlobalTauri`, that turned any script-execution bug in the WebView into+/// `node -e "…"` with the user's rights. These tests fail the moment either+/// half comes back.+#[cfg(test)]+mod ipc_surface_tests {+ use std::path::PathBuf;++ fn manifest_dir() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ }++ fn read_json(rel: &str) -> serde_json::Value {+ let p = manifest_dir().join(rel);+ let raw = std::fs::read_to_string(&p).unwrap_or_else(|e| panic!("read {p:?}: {e}"));+ serde_json::from_str(&raw).unwrap_or_else(|e| panic!("parse {p:?}: {e}"))+ }++ #[test]+ fn the_spawn_allow_list_carries_no_general_purpose_interpreter() {+ let cap = read_json("capabilities/default.json");+ let mut spawn_entries = Vec::new();+ for perm in cap["permissions"].as_array().expect("permissions") {+ if perm.get("identifier").and_then(|v| v.as_str()) == Some("shell:allow-spawn") {+ for entry in perm["allow"].as_array().expect("allow list") {+ spawn_entries.push(entry.clone());+ }+ }+ }+ assert!(!spawn_entries.is_empty(), "no shell:allow-spawn entry found");++ // Anything that runs code handed to it on the command line, or that+ // runs whatever a package.json / image says.+ const BANNED: [&str; 15] = [+ "node", "node.cmd", "deno", "deno.cmd", "bun", "bun.cmd", "python", "python3",+ "py", "docker", "npm", "npm.cmd", "pnpm", "yarn", "uv",+ ];+ for entry in &spawn_entries {+ let name = entry["name"].as_str().unwrap_or_default().to_lowercase();+ let cmd = entry["cmd"].as_str().unwrap_or_default().to_lowercase();+ for bad in BANNED {+ assert_ne!(cmd, bad, "{bad} is back in the spawn allow-list");+ assert_ne!(name, bad, "{bad} is back in the spawn allow-list");+ }+ }+ }++ /// `withGlobalTauri` publishes the whole JS API on `window.__TAURI__`, i.e.+ /// hands any injected script a ready-made `shell.Command` without it having+ /// to know the internal invoke shape. The app detects its runtime through+ /// `__TAURI_INTERNALS__` (see `isTauri` in src/api/backend.ts), which Tauri+ /// injects regardless, so nothing needs the global.+ #[test]+ fn the_full_js_api_is_not_published_on_the_window_object() {+ let conf = read_json("tauri.conf.json");+ assert_eq!(+ conf["app"]["withGlobalTauri"],+ serde_json::Value::Bool(false),+ "withGlobalTauri is back on",+ );+ }++ /// The reason turning it off is safe — asserted instead of assumed. A+ /// `window.__TAURI__.something` anywhere in the frontend would go undefined+ /// at runtime with no compile-time warning.+ #[test]+ fn no_frontend_code_calls_through_the_global() {+ let src = manifest_dir().join("..").join("src");+ if !src.is_dir() {+ return; // source-less build tree: nothing to check+ }+ let mut offenders: Vec<String> = Vec::new();+ for entry in walkdir::WalkDir::new(&src).into_iter().filter_map(|e| e.ok()) {+ let p = entry.path();+ let is_source = p+ .extension()+ .and_then(|e| e.to_str())+ .map(|e| matches!(e, "ts" | "tsx" | "js" | "jsx" | "html"))+ .unwrap_or(false);+ if !is_source {+ continue;+ }+ if let Ok(text) = std::fs::read_to_string(p) {+ for (i, line) in text.lines().enumerate() {+ // A member access, not the `w.__TAURI__` presence check.+ if line.contains("__TAURI__.") {+ offenders.push(format!("{}:{}", p.display(), i + 1));+ }+ }+ }+ }+ assert!(+ offenders.is_empty(),+ "these still call through window.__TAURI__: {offenders:?}",+ );+ }+}+#[cfg(test)]mod tests {use super::*;@@ -373,6 +473,27 @@ mod tests {assert_eq!(text, "hello\n");}+ /// The shell tool creates its fallback cwd with `create_dir_all`. With the+ /// local sanitiser copy that still allowed `.`, a chat id of ".." resolved+ /// to `~/agent-workspace/..` — the user's HOME — and every relative command+ /// from that chat ran there (audit IPC-1, fixed in agent.rs only).+ #[test]+ fn a_dotted_chat_id_cannot_walk_the_cwd_out_of_the_workspace() {+ let root = dirs::home_dir().unwrap_or_default().join("agent-workspace");+ for id in ["..", ".", "../..", "a.b"] {+ let cwd = workspace_cwd(Some(id));+ assert!(cwd.starts_with(&root), "id {id:?} escaped to {cwd:?}");+ assert_ne!(cwd, root, "id {id:?} landed on the workspace root itself");+ assert!(+ !cwd.to_string_lossy().contains('.'),+ "id {id:?} kept a dot: {cwd:?}",+ );+ }+ // Ordinary ids keep their own folder.+ assert_eq!(workspace_cwd(Some("coding-agent-8b0c71")), root.join("coding-agent-8b0c71"));+ assert_eq!(workspace_cwd(None), root.join("default"));+ }+#[cfg(unix)]#[test]fn a_bounded_probe_returns_output_and_gives_up_on_a_hang() {diff --git a/src-tauri/src/process_util.rs b/src-tauri/src/process_util.rsindex a54b1b7f..334bb310 100644--- a/src-tauri/src/process_util.rs+++ b/src-tauri/src/process_util.rs@@ -3,8 +3,9 @@//!//! On Windows we use Job Objects (KILL_ON_JOB_CLOSE) so any child process tree//! gets cleaned up when the bridge exits, and prefer `taskkill /T /F` for-//! recursive kills. On Unix we use a process-group kill via `kill -- -PGID` so-//! Python subprocess trees don't leak.+//! recursive kills. On Unix `kill_tree` walks the real parent/child links: a+//! process-group kill only reaches children that were put in a group at spawn,+//! which is true for `spawn_piped` but not for every caller.use std::process::{Child, Command, Stdio};@@ -52,8 +53,48 @@ pub fn spawn_piped(mut cmd: Command) -> std::io::Result<Child> {cmd.spawn()}-/// Recursive process-tree kill. On Windows uses `taskkill /T /F /PID`; on-/// Unix sends SIGTERM to the process group then SIGKILL after a grace.+/// Every process in `root`'s tree, root last, paired with its start time.+///+/// The start time is the anti-PID-reuse token for the delayed SIGKILL below:+/// a descendant is reparented to init the moment its parent dies, init reaps+/// it, and the kernel is then free to hand that number to a stranger inside+/// our own grace window. Same pid AND same start time is the same process.+#[cfg(unix)]+fn tree_snapshot(root: u32) -> Vec<(u32, u64)> {+ use sysinfo::{Pid, ProcessesToUpdate, System};+ let mut sys = System::new();+ sys.refresh_processes(ProcessesToUpdate::All, true);+ let mut order = crate::commands::shell::descendants(root, &sys);+ order.reverse(); // leaves first — a live parent can't respawn what we killed+ order.push(root);+ order+ .into_iter()+ .map(|pid| {+ let start = sys+ .process(Pid::from_u32(pid))+ .map(|p| p.start_time())+ .unwrap_or(0);+ (pid, start)+ })+ .collect()+}++/// Recursive process-tree kill: SIGTERM the whole tree now, SIGKILL whatever+/// is left after a grace. Windows delegates the walk to `taskkill /T /F`.+///+/// The Unix branch used to signal the process GROUP (`kill -- -PGID`). Only+/// `spawn_piped` puts a child in its own group, and its one caller here+/// (`video_cancel` → the mlx_video Python job) spawns through a plain+/// `Command::spawn`, so `-PID` addressed a group that never existed: the kill+/// went nowhere and the generation kept running on the GPU. The tree is+/// therefore walked explicitly, and it MUST be walked before the root dies —+/// afterwards its children are reparented to init and the parent links that+/// identify them are gone.+///+/// Nothing here blocks the caller: `video_cancel` holds the `video_process`+/// mutex across this call and the UI polls that same mutex, so the old+/// 800 ms sleep froze the window for the whole grace. The grace, the escalation+/// and the final reap run on a detached thread instead.pub fn kill_tree(child: &mut Child) -> std::io::Result<()> {let pid = child.id();#[cfg(windows)]@@ -63,20 +104,47 @@ pub fn kill_tree(child: &mut Child) -> std::io::Result<()> {.stdout(Stdio::null()).stderr(Stdio::null()).status();+ let _ = child.kill();+ let _ = child.wait();}#[cfg(unix)]{- unsafe {- // Negative PID kills the process group.- libc::kill(-(pid as i32), libc::SIGTERM);- }- std::thread::sleep(std::time::Duration::from_millis(800));- unsafe {- libc::kill(-(pid as i32), libc::SIGKILL);+ let tree = tree_snapshot(pid);+ for (p, _) in &tree {+ unsafe {+ libc::kill(*p as i32, libc::SIGTERM);+ }}+ std::thread::spawn(move || {+ std::thread::sleep(std::time::Duration::from_millis(800));+ let survivors = {+ use sysinfo::{Pid, ProcessesToUpdate, System};+ let mut sys = System::new();+ sys.refresh_processes(ProcessesToUpdate::All, true);+ tree.iter()+ .filter(|(p, start)| {+ sys.process(Pid::from_u32(*p))+ .map(|proc_| *start == 0 || proc_.start_time() == *start)+ .unwrap_or(false)+ })+ .map(|(p, _)| *p)+ .collect::<Vec<u32>>()+ };+ for p in survivors {+ unsafe {+ libc::kill(p as i32, libc::SIGKILL);+ }+ }+ // The caller drops its `Child` without waiting, and a dropped+ // Child is never reaped — the job would sit in the table as a+ // zombie for as long as LU runs. Its pid also cannot be recycled+ // until this call, which is what makes the SIGKILL above safe.+ unsafe {+ let mut status: libc::c_int = 0;+ libc::waitpid(pid as libc::pid_t, &mut status, 0);+ }+ });}- let _ = child.kill();- let _ = child.wait();Ok(())}@@ -144,5 +212,118 @@ mod libc {pub const SIGKILL: c_int = 9;extern "C" {pub fn kill(pid: pid_t, sig: c_int) -> c_int;+ pub fn waitpid(pid: pid_t, status: *mut c_int, options: c_int) -> pid_t;+ }+}++#[cfg(all(test, unix))]+mod kill_tree_tests {+ use super::*;+ use std::time::{Duration, Instant};++ fn alive(pid: u32) -> bool {+ let out = Command::new("ps")+ .args(["-o", "state=", "-p", &pid.to_string()])+ .output();+ match out {+ Ok(o) => {+ let st = String::from_utf8_lossy(&o.stdout).trim().to_string();+ !st.is_empty() && !st.starts_with('Z')+ }+ Err(_) => false,+ }+ }++ fn wait_until_gone(pids: &[u32], max: Duration) {+ let deadline = Instant::now() + max;+ loop {+ let left: Vec<u32> = pids.iter().copied().filter(|p| alive(*p)).collect();+ if left.is_empty() {+ return;+ }+ assert!(Instant::now() < deadline, "still running: {left:?}");+ std::thread::sleep(Duration::from_millis(100));+ }+ }++ /// The only caller (`video_cancel`) spawns with a plain `Command::spawn`,+ /// so the child is NOT a process-group leader — which is exactly why the+ /// old `kill(-pid)` signalled nothing and left the tree running.+ #[test]+ fn a_child_without_a_process_group_still_loses_its_whole_tree() {+ let mut child = Command::new("sh")+ .arg("-c")+ .arg("sleep 40 & sleep 40")+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn sh");+ let pid = child.id();+ std::thread::sleep(Duration::from_millis(400));++ let mut sys = sysinfo::System::new();+ sys.refresh_processes(sysinfo::ProcessesToUpdate::All, true);+ let kids = crate::commands::shell::descendants(pid, &sys);+ assert!(!kids.is_empty(), "sh spawned nothing — test setup is wrong");++ kill_tree(&mut child).expect("kill_tree");++ let mut all = kids.clone();+ all.push(pid);+ wait_until_gone(&all, Duration::from_secs(5));+ }++ /// `video_cancel` holds the `video_process` mutex for the duration of this+ /// call and the progress poll waits on the same mutex, so a blocking grace+ /// froze the window. The kill must be ordered, not awaited.+ #[test]+ fn the_call_does_not_block_for_the_grace_period() {+ let mut child = Command::new("sh")+ .arg("-c")+ .arg("sleep 40")+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn sh");+ let pid = child.id();+ std::thread::sleep(Duration::from_millis(200));++ let started = Instant::now();+ kill_tree(&mut child).expect("kill_tree");+ let took = started.elapsed();++ assert!(took < Duration::from_millis(400), "kill_tree blocked for {took:?}");+ wait_until_gone(&[pid], Duration::from_secs(5));+ }++ /// A killed child that nobody waits on stays in the process table as a+ /// zombie for the app's lifetime — and its pid can never be recycled.+ #[test]+ fn the_direct_child_is_reaped_not_left_as_a_zombie() {+ let mut child = Command::new("sh")+ .arg("-c")+ .arg("sleep 40")+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn sh");+ let pid = child.id();+ std::thread::sleep(Duration::from_millis(200));+ kill_tree(&mut child).expect("kill_tree");+ drop(child); // exactly what video_cancel does with its taken handle++ let deadline = Instant::now() + Duration::from_secs(5);+ loop {+ let out = Command::new("ps")+ .args(["-o", "state=", "-p", &pid.to_string()])+ .output()+ .expect("ps");+ let st = String::from_utf8_lossy(&out.stdout).trim().to_string();+ if st.is_empty() {+ return; // gone from the table entirely == reaped+ }+ assert!(Instant::now() < deadline, "pid {pid} is still listed as {st:?}");+ std::thread::sleep(Duration::from_millis(100));+ }}}diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex 775d6240..bebc3fb1 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -10,7 +10,7 @@"frontendDist": "../dist"},"app": {- "withGlobalTauri": true,+ "withGlobalTauri": false,"windows": [{"title": "LU",diff --git a/src/components/settings/MCPServerSettings.tsx b/src/components/settings/MCPServerSettings.tsxindex 3f9a4d62..dffbc12e 100644--- a/src/components/settings/MCPServerSettings.tsx+++ b/src/components/settings/MCPServerSettings.tsx@@ -40,7 +40,18 @@ export function MCPServerSettings() {setError(null)try {const { MCPExternalClient } = await import('../../api/mcp/external-client')- const client = new MCPExternalClient(server)+ // A server process can die on its own (crash, OOM kill, a bad config it+ // quits on). Before this the panel stayed green and its tools stayed in+ // the registry, so the model kept being offered a terminal that was not+ // there and every call failed with "Not connected" until the app closed.+ const client = new MCPExternalClient(server, {+ onExit: (id) => {+ toolRegistry.unregisterServer(id)+ setConnected(id, false)+ clearServerTools(id)+ clients.delete(id)+ },+ })const tools = await client.connect()clients.set(server.id, client)setConnected(server.id, true)