Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(agent): harden the sandbox with a session-scoped /tmp scratch (#8674)
Akarshan Biswas7a3af799f2f3
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rsindex 3bf03ee1a..2fdb06334 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs@@ -280,6 +280,7 @@ pub async fn execute_tool(// would be refused if the thread's first tool call arrived before any UI// surface had ensured it.let root = workspace::ensure_thread_workspace(Path::new(&data_folder), &thread_id).await?;+ let scratch = workspace::ensure_scratch_dir(&thread_id).await?;let store = resolve_store(&data_folder, project.as_deref());let tool = lookup(&name).ok_or_else(|| AgentToolsError::from(format!("unknown built-in tool '{name}'")))?;@@ -288,6 +289,7 @@ pub async fn execute_tool(tool,&args,&root,+ Some(&scratch),&ToolPermissions::default(),&SessionGrants::default(),) {@@ -340,7 +342,8 @@ pub async fn execute_tool(let ctx = ToolContext::new(&root, &store, &enabled).with_network(allow_network.unwrap_or(false)).with_confined_writes(true)- .with_mask_root(Path::new(&data_folder));+ .with_mask_root(Path::new(&data_folder))+ .with_scratch_root(&scratch);let (content, diff) = handlers::execute_builtin_with_diff(tool, &args, &ctx).await;let is_error =content.starts_with("ERROR") || (name == "bash" && handlers::bash_result_failed(&content));@@ -488,14 +491,17 @@ mod tests {let _ = std::fs::remove_dir_all(&data);}- /// A write that escapes the sandbox (absolute or `..`) must be refused on the- /// desktop surface, just like an escaping read -- it could reach host files.+ /// A write that escapes the sandbox (absolute or `..`) must be refused on+ /// the desktop surface, just like an escaping read -- it could reach host+ /// files. The session scratch is the exception: it is the agent's own area,+ /// spelled `/tmp/...` where it is bound over the sandbox's `/tmp` and by its+ /// real path where nothing is mounted there.#[tokio::test]async fn escaping_writes_are_refused() {let data = unique_data_folder();let df = data.to_string_lossy().to_string();- for path in ["../escape.txt", "/tmp/jan_cmd_escape.txt"] {+ for path in ["../escape.txt", "/etc/hosts", "/home/akarshan/.bashrc"] {let err = execute_tool(df.clone(),T1.into(),@@ -514,6 +520,37 @@ mod tests {);}+ // A scratch write is not a host escape and succeeds, under whichever+ // spelling reaches the scratch on this platform. The scratch outlives the+ // test process, so the name is per-run: a leftover file would answer+ // "No change" instead of "Created".+ let scratch = crate::workspace::ensure_scratch_dir(T1).await.unwrap();+ let name = format!("jan_cmd_scratch_{}.txt", std::process::id());+ let (requested, expected) = if cfg!(target_os = "linux") {+ let p = format!("/tmp/{name}");+ (p.clone(), p)+ } else {+ let p = scratch.join(&name).to_string_lossy().into_owned();+ (p.clone(), p)+ };+ let res = execute_tool(+ df.clone(),+ T1.into(),+ None,+ "write".into(),+ json!({"path": requested, "content": "x"}),+ None,+ None,+ )+ .await+ .expect("a scratch write is the session scratch and must succeed");+ assert!(+ res.content.starts_with(&format!("Created {expected}")),+ "got: {}",+ res.content+ );+ let _ = std::fs::remove_file(scratch.join(&name));+// An in-sandbox write still succeeds, so we didn't over-tighten.let res = execute_tool(df.clone(),@@ -657,29 +694,61 @@ mod tests {}/// Thread isolation: each conversation gets its own sandbox, and neither a- /// relative nor an absolute path reaches the other's scratch files.+ /// relative climb-out nor a sibling-thread absolute path reaches the other's+ /// scratch files. `/tmp` is the agent's own (per-thread) scratch, so a read+ /// of `/tmp` from a different thread resolves to that thread's empty scratch.#[tokio::test]async fn one_thread_cannot_read_another_threads_files() {let data = unique_data_folder();let df = data.to_string_lossy().to_string();- let one = PathBuf::from(thread_workspace_path(df.clone(), T1.into()).await.unwrap());- thread_workspace_path(df.clone(), T2.into()).await.unwrap();+ // Thread ids unique to this test rather than the ids shared across the+ // module: a scratch is keyed on the session id alone and lives in the+ // host temp dir, so it is global state even though each test gets its+ // own data folder, and any test deleting that thread's workspace also+ // removes its scratch (see `remove_thread_workspace`).+ let (t1, t2) = ("isolation-thread-one", "isolation-thread-two");+ let one = PathBuf::from(thread_workspace_path(df.clone(), t1.into()).await.unwrap());+ thread_workspace_path(df.clone(), t2.into()).await.unwrap();std::fs::write(one.join("secret.txt"), b"classified").unwrap();- for path in [- json!({"path": "../thread-one/secret.txt"}),- json!({"path": one.join("secret.txt").to_string_lossy()}),- ] {- let err = execute_tool(df.clone(), T2.into(), None, "read".into(), path, None, None)- .await- .expect_err("cross-thread read must be refused");- assert!(- err.message.contains("needs user approval"),- "unexpected: {}",- err.message- );- }+ // A relative climb-out reaches the sibling thread's workspace and is an+ // escape, so it must prompt (and is refused on this surface).+ let err = execute_tool(+ df.clone(),+ t2.into(),+ None,+ "read".into(),+ json!({"path": "../isolation-thread-one/secret.txt"}),+ None,+ None,+ )+ .await+ .expect_err("a relative climb-out to a sibling thread must be refused");+ assert!(+ err.message.contains("needs user approval"),+ "unexpected: {}",+ err.message+ );++ // `/tmp` is the per-thread scratch: t1's scratch (written by its shell)+ // is not visible to t2, whose own scratch is empty.+ let one_scratch = crate::workspace::ensure_scratch_dir(t1).await.unwrap();+ std::fs::write(one_scratch.join("secret.txt"), b"classified").unwrap();+ let out = execute_tool(+ df.clone(),+ t2.into(),+ None,+ "read".into(),+ json!({"path": "/tmp/secret.txt"}),+ None,+ None,+ )+ .await+ .unwrap();+ assert!(out.is_error, "t2 sees an empty scratch, got: {}", out.content);let _ = std::fs::remove_dir_all(&data);+ let _ = crate::workspace::remove_scratch_dir(t1).await;+ let _ = crate::workspace::remove_scratch_dir(t2).await;}/// Memory is permanent: wiping a thread's sandbox leaves it untouched, and a@@ -733,20 +802,24 @@ mod tests {.unwrap();thread_workspace_path(df.clone(), T1.into()).await.unwrap();- let store = resolve_store(&df, None);- for path in [+ // A relative climb out of the thread sandbox toward the store is an+ // escape and must be refused.+ let err = execute_tool(+ df.clone(),+ T1.into(),+ None,+ "read".into(),json!({"path": "../../memory/prefs.md"}),- json!({"path": workspace::store_dir(&store, "memory").join("prefs.md").to_string_lossy()}),- ] {- let err = execute_tool(df.clone(), T1.into(), None, "read".into(), path, None, None)- .await- .expect_err("memory must be unreachable from the sandbox");- assert!(- err.message.contains("needs user approval"),- "unexpected: {}",- err.message- );- }+ None,+ None,+ )+ .await+ .expect_err("memory must be unreachable from the sandbox");+ assert!(+ err.message.contains("needs user approval"),+ "unexpected: {}",+ err.message+ );let _ = std::fs::remove_dir_all(&data);}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/appcontainer.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/appcontainer.rsindex 451628a50..e82dc2b8a 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/appcontainer.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/appcontainer.rs@@ -72,9 +72,13 @@ pub fn moniker(workspace: &Path) -> String {/// argv for the helper re-exec. Shaped like the other backends -- fixed/// arguments, then the shell, with the command string appended by the caller ---/// so the spawn path does not change per platform.+/// so the spawn path does not change per platform. The scratch travels with the+/// workspace because both need an ACE, and only the helper holds the container+/// SID to grant one with; an absent scratch is the empty string, since a+/// positional slot cannot simply be omitted.pub fn helper_args(workspace: &Path,+ scratch: Option<&Path>,allow_network: bool,program: &Path,args: &[String],@@ -83,6 +87,9 @@ pub fn helper_args(SANDBOX_EXEC_FLAG.to_string(),if allow_network { NET_ON } else { NET_OFF }.to_string(),workspace.to_string_lossy().to_string(),+ scratch+ .map(|s| s.to_string_lossy().to_string())+ .unwrap_or_default(),"--".to_string(),program.to_string_lossy().to_string(),];@@ -141,6 +148,7 @@ fn command_line(program: &Path, args: &[String]) -> String {#[cfg_attr(not(windows), allow(dead_code))]struct Request {workspace: PathBuf,+ scratch: Option<PathBuf>,allow_network: bool,program: PathBuf,args: Vec<String>,@@ -160,12 +168,17 @@ fn parse_request<I: IntoIterator<Item = String>>(argv: I) -> Option<Request> {_ => return None,};let workspace = PathBuf::from(it.next()?);+ let scratch = match it.next()? {+ s if s.is_empty() => None,+ s => Some(PathBuf::from(s)),+ };if it.next()? != "--" {return None;}let program = PathBuf::from(it.next()?);Some(Request {workspace,+ scratch,allow_network,program,args: it.collect(),@@ -334,8 +347,9 @@ mod win {/// Grant the container full access to `path` and everything created under it./// This is the entire write policy: without an ACE naming the container, a- /// lowbox token can open nothing it was not given.- fn grant_workspace(path: &Path, sid: PSID) -> Result<(), String> {+ /// lowbox token can open nothing it was not given. Called for the workspace+ /// and, when there is one, the session scratch.+ fn grant_path(path: &Path, sid: PSID) -> Result<(), String> {let mut object = wide(path.as_os_str());let mut existing: *mut ACL = std::ptr::null_mut();let mut descriptor: PSECURITY_DESCRIPTOR = std::ptr::null_mut();@@ -492,9 +506,19 @@ mod win {req.workspace.display()));}+ if let Some(scratch) = &req.scratch {+ if !scratch.is_dir() {+ return Err(format!("scratch does not exist: {}", scratch.display()));+ }+ }reap_children_with_this_process();let sid = ensure_profile(&moniker(&req.workspace))?;- grant_workspace(&req.workspace, sid.0)?;+ grant_path(&req.workspace, sid.0)?;+ // The scratch is the shell's `TEMP`/`TMP`, so without this every+ // temp-file write in the container is denied.+ if let Some(scratch) = &req.scratch {+ grant_path(scratch, sid.0)?;+ }let mut capability_sid = Vec::new();let mut capabilities = Vec::new();@@ -651,7 +675,13 @@ mod tests {#[test]fn helper_args_end_with_the_shell_so_the_command_appends_last() {- let args = helper_args(&ws(), false, Path::new("bash.exe"), &["-c".to_string()]);+ let args = helper_args(+ &ws(),+ None,+ false,+ Path::new("bash.exe"),+ &["-c".to_string()],+ );let sep = args.iter().position(|a| a == "--").expect("separator");assert_eq!(&args[sep + 1..],@@ -662,10 +692,10 @@ mod tests {#[test]fn helper_args_carry_the_network_decision() {- let denied = helper_args(&ws(), false, Path::new("bash.exe"), &[]);+ let denied = helper_args(&ws(), None, false, Path::new("bash.exe"), &[]);assert!(denied.contains(&NET_OFF.to_string()));assert!(!denied.contains(&NET_ON.to_string()));- let allowed = helper_args(&ws(), true, Path::new("bash.exe"), &[]);+ let allowed = helper_args(&ws(), None, true, Path::new("bash.exe"), &[]);assert!(allowed.contains(&NET_ON.to_string()));}@@ -673,17 +703,32 @@ mod tests {fn the_helper_round_trips_its_own_argv() {let args = helper_args(&ws(),+ Some(Path::new(r"C:\Temp\jan-agent-s1")),true,Path::new(r"C:\Program Files\Git\bin\bash.exe"),&["-c".to_string(), "echo hi".to_string()],);let req = parse_request(args).expect("parsed");assert_eq!(req.workspace, ws());+ assert_eq!(+ req.scratch.as_deref(),+ Some(Path::new(r"C:\Temp\jan-agent-s1"))+ );assert!(req.allow_network);assert_eq!(req.program, Path::new(r"C:\Program Files\Git\bin\bash.exe"));assert_eq!(req.args, vec!["-c".to_string(), "echo hi".to_string()]);}+ /// The scratch has to reach the helper, because the ACE that makes it+ /// writable can only be granted on the far side of the re-exec.+ #[test]+ fn the_helper_round_trips_an_absent_scratch() {+ let args = helper_args(&ws(), None, false, Path::new("bash.exe"), &[]);+ let req = parse_request(args).expect("parsed");+ assert_eq!(req.workspace, ws());+ assert_eq!(req.scratch, None);+ }+#[test]fn a_normal_launch_is_not_mistaken_for_the_helper() {assert!(parse_request(Vec::<String>::new()).is_none());diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rsindex 9d0d33d58..243f5a8ba 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs@@ -4,9 +4,7 @@ use serde::{Deserialize, Serialize};use crate::permissions::ToolPermissions;use crate::tools::cmdscan::{normalize, scan_command, CommandScan};-use crate::tools::sandbox::{- command_touches_hidden_jan_path, escapes_project, is_hidden_jan_path,-};+use crate::tools::sandbox::{command_touches_hidden_jan_path, escapes_project, is_hidden_jan_path};use crate::tools::{BuiltinTool, Capability};#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]@@ -135,6 +133,7 @@ pub fn resolve_decision(tool: &BuiltinTool,args: &serde_json::Value,project_root: &Path,+ scratch: Option<&Path>,perms: &ToolPermissions,grants: &SessionGrants,) -> Decision {@@ -172,7 +171,7 @@ pub fn resolve_decision(let escapes = tool.path_args.iter().any(|key| {args.get(key).and_then(|v| v.as_str())- .map(|p| escapes_project(project_root, p).unwrap_or(true))+ .map(|p| escapes_project(project_root, scratch, p).unwrap_or(true)).unwrap_or(false)});if !escapes || grants.covers(PromptKind::ReadEscape) {@@ -194,7 +193,7 @@ pub fn resolve_decision(let escapes = tool.path_args.iter().any(|key| {args.get(key).and_then(|v| v.as_str())- .map(|p| escapes_project(project_root, p).unwrap_or(true))+ .map(|p| escapes_project(project_root, scratch, p).unwrap_or(true)).unwrap_or(false)});if escapes {@@ -264,6 +263,7 @@ mod tests {lookup("read").unwrap(),&json!({"path": "inner.txt"}),&root,+ None,&perms,&grants,);@@ -280,6 +280,7 @@ mod tests {lookup("read").unwrap(),&json!({"path": "../x"}),&root,+ None,&perms,&grants,);@@ -297,6 +298,7 @@ mod tests {lookup(tool).unwrap(),&json!({}),&root,+ None,&perms,&grants,);@@ -315,6 +317,7 @@ mod tests {lookup("web_search").unwrap(),&json!({}),&root,+ None,&perms,&grants,);@@ -339,6 +342,7 @@ mod tests {lookup(tool).unwrap(),&json!({ "path": ".jan/agent/agent.toml" }),&root,+ None,&perms,&grants,);@@ -353,6 +357,7 @@ mod tests {lookup("bash").unwrap(),&json!({"command": "cat .jan/agent/agent.toml"}),&root,+ None,&perms,&grants,);@@ -363,6 +368,7 @@ mod tests {lookup("read").unwrap(),&json!({"path": "JAN.md"}),&root,+ None,&perms,&grants,);@@ -379,6 +385,7 @@ mod tests {lookup("write").unwrap(),&json!({"path": "out.txt"}),&root,+ None,&perms,&grants,);@@ -395,6 +402,7 @@ mod tests {lookup("bash").unwrap(),&json!({"command": "ls"}),&root,+ None,&perms,&grants,);@@ -411,6 +419,7 @@ mod tests {lookup("bash").unwrap(),&json!({"job_id": "bash-0"}),&root,+ None,&perms,&grants,);@@ -439,6 +448,7 @@ mod tests {lookup("bash").unwrap(),&json!({"command": "git push"}),&root,+ None,&perms,&grants,);@@ -449,6 +459,7 @@ mod tests {lookup("bash").unwrap(),&json!({"command": "rm -rf /"}),&root,+ None,&perms,&grants,);@@ -473,6 +484,7 @@ mod tests {lookup("bash").unwrap(),&json!({ "command": cmd }),&root,+ None,&perms,&grants,);@@ -493,6 +505,7 @@ mod tests {lookup("bash").unwrap(),&json!({ "command": cmd }),&root,+ None,&perms,&grants,);@@ -513,6 +526,7 @@ mod tests {lookup("bash").unwrap(),&json!({"command": "sudo systemctl restart nginx"}),&root,+ None,&perms,&grants,);@@ -523,6 +537,7 @@ mod tests {lookup("bash").unwrap(),&json!({"command": "sudo rm -rf /"}),&root,+ None,&perms,&grants,);@@ -548,6 +563,7 @@ mod tests {lookup(tool).unwrap(),&json!({ "path": path }),&root,+ None,&perms,&grants,);@@ -571,6 +587,7 @@ mod tests {lookup(name).unwrap(),&json!({"name": "x", "content": "y"}),&root,+ None,&perms,&grants,);@@ -582,6 +599,7 @@ mod tests {lookup("memory_write").unwrap(),&json!({"name": "x", "content": "y"}),&root,+ None,&denied,&grants,);@@ -598,6 +616,7 @@ mod tests {lookup("write").unwrap(),&json!({"path": "out.txt"}),&root,+ None,&perms,&grants,);@@ -614,6 +633,7 @@ mod tests {lookup("write").unwrap(),&json!({"path": "out.txt"}),&root,+ None,&perms,&grants,);@@ -631,6 +651,7 @@ mod tests {lookup("write").unwrap(),&json!({"path": "out.txt"}),&root,+ None,&perms,&grants,);@@ -648,6 +669,7 @@ mod tests {lookup("read").unwrap(),&json!({"path": "../x"}),&root,+ None,&perms,&grants,);@@ -664,6 +686,7 @@ mod tests {lookup("write").unwrap(),&json!({"path": "sub/new.txt"}),&root,+ None,&perms,&grants,);@@ -682,6 +705,7 @@ mod tests {lookup("write").unwrap(),&json!({"path": path}),&root,+ None,&perms,&grants,);@@ -700,6 +724,7 @@ mod tests {lookup("write").unwrap(),&json!({"path": "../x"}),&root,+ None,&perms,&grants,);@@ -716,6 +741,7 @@ mod tests {lookup("read").unwrap(),&json!({"path": "../x"}),&root,+ None,&perms,&grants,);diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rsindex 8d4866eb9..ad7af1b72 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs@@ -15,7 +15,10 @@ use crate::memory;use crate::skills;use crate::tools::jail;use crate::tools::proc;-use crate::tools::sandbox::{escapes_project, is_hidden_jan_path};+use crate::tools::sandbox::{+ escapes_project, in_scratch, is_hidden_jan_path, lexical_normalize, resolve_path,+ scratch_display_path,+};use crate::tools::{BuiltinTool, ToolContext};const MAX_BYTES: usize = 64 * 1024;@@ -47,14 +50,6 @@ fn bash_jobs() -> &'static Mutex<HashMap<String, oneshot::Receiver<String>>> {JOBS.get_or_init(|| Mutex::new(HashMap::new()))}-fn resolve(project_root: &Path, raw: &str) -> PathBuf {- if Path::new(raw).is_absolute() {- PathBuf::from(raw)- } else {- project_root.join(raw)- }-}-fn arg_str<'a>(args: &'a serde_json::Value, key: &str) -> Option<&'a str> {args.get(key).and_then(|v| v.as_str())}@@ -74,31 +69,15 @@ fn rel_to(base: &Path, path: &Path) -> String {.replace('\\', "/")}-/// Resolve `.`/`..` without touching the filesystem, so a path is comparable to-/// the project root even when the target does not exist yet. Purely lexical:-/// `canonicalize` would also follow symlinks and fail on missing files.-fn lexical_normalize(path: &Path) -> PathBuf {- use std::path::Component;- let mut out = PathBuf::new();- for c in path.components() {- match c {- Component::CurDir => {}- Component::ParentDir => {- out.pop();- }- other => out.push(other.as_os_str()),- }- }- out-}-/// How a mutated path is named back to the model: relative inside the project,/// absolute once it escapes. Normalizes first, since `root/../x` strips to a-/// misleading `../x` against an un-normalized root.-fn display_path(root: &Path, target: &Path) -> String {- let target = lexical_normalize(target);- let root = lexical_normalize(root);- rel_to(&root, &target)+/// misleading `../x` against an un-normalized root. A target inside the session+/// scratch is named by whichever spelling the shell can also use there.+fn display_path(root: &Path, scratch: Option<&Path>, target: &Path) -> String {+ if in_scratch(scratch, target) {+ return scratch_display_path(scratch, target);+ }+ rel_to(&lexical_normalize(root), &lexical_normalize(target))}/// Truncate `s` to the smaller of `max_lines` or `max_bytes`, appending@@ -148,14 +127,15 @@ pub async fn execute_builtin(ctx: &ToolContext<'_>,) -> String {let project_root = ctx.project_root;+ let scratch = ctx.scratch_root;match tool.name {- "read" => read(args, project_root).await,- "ls" => ls(args, project_root).await,- "write" => write(args, project_root, ctx.confine_writes).await,- "edit" => edit(args, project_root, ctx.confine_writes).await,+ "read" => read(args, project_root, scratch).await,+ "ls" => ls(args, project_root, scratch).await,+ "write" => write(args, project_root, scratch, ctx.confine_writes).await,+ "edit" => edit(args, project_root, scratch, ctx.confine_writes).await,"bash" => bash(args, ctx).await,- "find" => find(args, project_root).await,- "grep" => grep(args, project_root).await,+ "find" => find(args, project_root, scratch).await,+ "grep" => grep(args, project_root, scratch).await,// Memory and skills live in the store root, not the sandbox: they must// outlive the conversation the filesystem tools are scoped to."memory_list" => memory_list(ctx.store_root).await,@@ -185,6 +165,7 @@ pub async fn preview_diff(ctx: &ToolContext<'_>,) -> Option<String> {let project_root = ctx.project_root;+ let scratch = ctx.scratch_root;match tool.name {"edit" => {let edits = args.get("edits").and_then(|v| v.as_array())?;@@ -192,7 +173,7 @@ pub async fn preview_diff(return None;}let prior = match arg_str(args, "path") {- Some(p) => tokio::fs::read_to_string(resolve(project_root, p))+ Some(p) => tokio::fs::read_to_string(resolve_path(project_root, scratch, p)).await.unwrap_or_default(),None => String::new(),@@ -202,7 +183,7 @@ pub async fn preview_diff(}"write" => {let prior = match arg_str(args, "path") {- Some(p) => tokio::fs::read_to_string(resolve(project_root, p))+ Some(p) => tokio::fs::read_to_string(resolve_path(project_root, scratch, p)).await.ok(),None => None,@@ -466,13 +447,13 @@ async fn memory_write(args: &serde_json::Value, store: &Path) -> String {}}-async fn read(args: &serde_json::Value, root: &Path) -> String {+async fn read(args: &serde_json::Value, root: &Path, scratch: Option<&Path>) -> String {let Some(path) = arg_str(args, "path") else {return "ERROR: missing required argument 'path'".to_string();};let offset = arg_u64(args, "offset").map(|v| v as usize);let limit = arg_u64(args, "limit").map(|v| v as usize);- let target = resolve(root, path);+ let target = resolve_path(root, scratch, path);let bytes = match tokio::fs::read(&target).await {Ok(b) => b,@@ -510,12 +491,12 @@ async fn read(args: &serde_json::Value, root: &Path) -> String {)}-async fn ls(args: &serde_json::Value, root: &Path) -> String {+async fn ls(args: &serde_json::Value, root: &Path, scratch: Option<&Path>) -> String {let path = arg_str(args, "path").unwrap_or(".");let limit = arg_u64(args, "limit").map(|v| v as usize).unwrap_or(LS_DEFAULT_LIMIT);- let mut entries = match tokio::fs::read_dir(resolve(root, path)).await {+ let mut entries = match tokio::fs::read_dir(resolve_path(root, scratch, path)).await {Ok(rd) => rd,Err(e) => return format!("ERROR: {e}"),};@@ -548,7 +529,7 @@ async fn ls(args: &serde_json::Value, root: &Path) -> String {cap_output(&joined, usize::MAX, MAX_BYTES, "\n[truncated: 64KB limit]")}-async fn write(args: &serde_json::Value, root: &Path, confine: bool) -> String {+async fn write(args: &serde_json::Value, root: &Path, scratch: Option<&Path>, confine: bool) -> String {let Some(path) = arg_str(args, "path") else {return "ERROR: missing required argument 'path'".to_string();};@@ -558,13 +539,13 @@ async fn write(args: &serde_json::Value, root: &Path, confine: bool) -> String {// Defense in depth: when the caller confines writes, re-canonicalize on the// canonical root (not the raw argument) so `..` and absolute paths are// caught even if the gate's decision was made against a stale view.- if confine && escapes_project(root, path).unwrap_or(true) {+ let target = resolve_path(root, scratch, path);+ if confine && escapes_project(root, scratch, path).unwrap_or(true) {return format!("ERROR: refused to write outside the agent workspace: {path}");}- let target = resolve(root, path);// Report the resolved location, not the raw argument: an absolute or `../`// path lands outside the project and the model must see where it went.- let shown = display_path(root, &target);+ let shown = display_path(root, scratch, &target);if let Some(parent) = target.parent() {if let Err(e) = tokio::fs::create_dir_all(parent).await {return format!("ERROR: {shown}: {e}");@@ -586,7 +567,7 @@ async fn write(args: &serde_json::Value, root: &Path, confine: bool) -> String {}}-async fn edit(args: &serde_json::Value, root: &Path, confine: bool) -> String {+async fn edit(args: &serde_json::Value, root: &Path, scratch: Option<&Path>, confine: bool) -> String {let Some(path) = arg_str(args, "path") else {return "ERROR: missing required argument 'path'".to_string();};@@ -596,11 +577,11 @@ async fn edit(args: &serde_json::Value, root: &Path, confine: bool) -> String {if edits.is_empty() {return "ERROR: edits must contain at least one replacement".to_string();}- if confine && escapes_project(root, path).unwrap_or(true) {+ let target = resolve_path(root, scratch, path);+ if confine && escapes_project(root, scratch, path).unwrap_or(true) {return format!("ERROR: refused to edit outside the agent workspace: {path}");}- let target = resolve(root, path);- let shown = display_path(root, &target);+ let shown = display_path(root, scratch, &target);let mut content = match tokio::fs::read_to_string(&target).await {Ok(c) => c,Err(e) => return format!("ERROR: {shown}: {e}"),@@ -658,13 +639,17 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {if let Some(mask) = ctx.mask_root {policy = policy.with_mask_root(mask);}+ if let Some(scratch) = ctx.scratch_root {+ policy = policy.with_scratch_root(scratch);+ }let Some(shell) = jail::wrap(proc::shell(), &policy) else {return "ERROR: bash is unavailable because no OS sandbox could be established on this \system. Use the read/ls/find/grep tools instead.".to_string();};- let child = match proc::spawn(&shell, command, root).await {+ let sandbox_tmp = jail::scratch_env_path(jail::backend(), &policy);+ let child = match proc::spawn(&shell, command, root, sandbox_tmp.as_deref()).await {Ok(c) => c,Err(e) => return format!("ERROR: failed to run command: {e}"),};@@ -676,8 +661,9 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {// The child's pid stays registered until the task ends so a shutdown can// reap its whole process tree if it is still running.let (tx, mut rx) = oneshot::channel();+ let spill_scratch = ctx.scratch_root.map(Path::to_path_buf);tokio::spawn(async move {- let mut out = collect_and_format(child).await;+ let mut out = collect_and_format(child, spill_scratch).await;// Appended inside the task so a backgrounded job carries the hint too.// `Permission denied` on its own tells the model nothing about *why*;// without this it retries the same command until it gives up.@@ -722,11 +708,11 @@ async fn await_bash_job(job_id: &str) -> String {/// combined chronologically and spilled to a temp file once it outgrows the/// in-memory window, so the full text stays readable even though only a bounded/// tail is kept in RAM.-async fn collect_and_format(mut child: tokio::process::Child) -> String {+async fn collect_and_format(mut child: tokio::process::Child, scratch: Option<PathBuf>) -> String {use tokio::io::AsyncReadExt;let mut stdout = child.stdout.take();let mut stderr = child.stderr.take();- let mut cap = BashCapture::new();+ let mut cap = BashCapture::new(scratch);let mut bo = vec![0u8; 8192];let mut be = vec![0u8; 8192];let mut out_open = stdout.is_some();@@ -759,16 +745,18 @@ struct BashCapture {total_newlines: usize,spill: Option<std::io::BufWriter<std::fs::File>>,spill_path: Option<PathBuf>,+ scratch: Option<PathBuf>,}impl BashCapture {- fn new() -> Self {+ fn new(scratch: Option<PathBuf>) -> Self {BashCapture {tail: std::collections::VecDeque::new(),total_bytes: 0,total_newlines: 0,spill: None,spill_path: None,+ scratch,}}@@ -779,7 +767,7 @@ impl BashCapture {// yet), so dumping it captures the full prefix before we start// dropping from the front.if self.spill.is_none() && self.tail.len() + chunk.len() > BASH_MAX_BYTES {- let path = new_temp_path();+ let path = new_temp_path(self.scratch.as_deref());if let Ok(file) = std::fs::File::create(&path) {let mut w = std::io::BufWriter::new(file);let (a, b) = self.tail.as_slices();@@ -835,9 +823,10 @@ impl BashCapture {}let path = match self.spill_path.take() {- Some(p) => Some(p.to_string_lossy().into_owned()),- None => write_temp_output(&collapsed),- };+ Some(p) => Some(p),+ None => write_temp_output(&collapsed, self.scratch.as_deref()),+ }+ .map(|p| crate::tools::sandbox::scratch_display_path(self.scratch.as_deref(), &p));match path {Some(p) => format!("{body}\n[output truncated at {} of {} bytes; full output written \@@ -924,38 +913,43 @@ fn tail_cap(s: &str, max_lines: usize, max_bytes: usize) -> String {out}-/// Directory holding bash-output spill files. Purged once on first use so-/// files retained by a previous (possibly crashed) run don't accumulate.-fn spill_dir() -> &'static Path {- static DIR: OnceLock<PathBuf> = OnceLock::new();- DIR.get_or_init(|| {- let dir = std::env::temp_dir().join("jan-bash");- let _ = std::fs::remove_dir_all(&dir);- let _ = std::fs::create_dir_all(&dir);- dir- })- .as_path()+/// Directory holding bash-output spill files: inside the session scratch when+/// there is one, so the file the truncation note points at is reachable by the+/// same `/tmp/jan-bash/...` name from both the filesystem tools and the shell,+/// and is reclaimed when the session's scratch is removed.+///+/// Deliberately not swept on first use: the files are removed individually by+/// [`BashCapture::finish`] and its `Drop`, and the host fallback is a shared+/// path, so a global purge there would delete a concurrent instance's live+/// spill files rather than only stale ones.+fn spill_dir(scratch: Option<&Path>) -> PathBuf {+ let base = scratch+ .map(Path::to_path_buf)+ .unwrap_or_else(std::env::temp_dir);+ let dir = base.join("jan-bash");+ let _ = std::fs::create_dir_all(&dir);+ dir}-fn new_temp_path() -> PathBuf {+fn new_temp_path(scratch: Option<&Path>) -> PathBuf {let n = TEMP_COUNTER.fetch_add(1, Ordering::SeqCst);- spill_dir().join(format!("jan-bash-{}-{}.txt", std::process::id(), n))+ spill_dir(scratch).join(format!("jan-bash-{}-{}.txt", std::process::id(), n))}/// Write `content` to a uniquely named temp file, returning its path on success.-fn write_temp_output(content: &str) -> Option<String> {- let path = new_temp_path();+fn write_temp_output(content: &str, scratch: Option<&Path>) -> Option<PathBuf> {+ let path = new_temp_path(scratch);std::fs::write(&path, content).ok()?;- Some(path.to_string_lossy().into_owned())+ Some(path)}-async fn find(args: &serde_json::Value, root: &Path) -> String {+async fn find(args: &serde_json::Value, root: &Path, scratch: Option<&Path>) -> String {let pattern = arg_str(args, "pattern").map(String::from);let path = arg_str(args, "path").unwrap_or(".").to_string();let limit = arg_u64(args, "limit").map(|v| v as usize).unwrap_or(FIND_DEFAULT_LIMIT);- let base = resolve(root, &path);+ let base = resolve_path(root, scratch, &path);let root_owned = root.to_path_buf();let Some(pattern) = pattern else {@@ -1002,7 +996,7 @@ async fn find(args: &serde_json::Value, root: &Path) -> String {res.unwrap_or_else(|e| format!("ERROR: {e}"))}-async fn grep(args: &serde_json::Value, root: &Path) -> String {+async fn grep(args: &serde_json::Value, root: &Path, scratch: Option<&Path>) -> String {let pattern = arg_str(args, "pattern").map(String::from);let path = arg_str(args, "path").unwrap_or(".").to_string();let glob_filter = arg_str(args, "glob").map(String::from);@@ -1012,7 +1006,7 @@ async fn grep(args: &serde_json::Value, root: &Path) -> String {let limit = arg_u64(args, "limit").map(|v| v as usize).unwrap_or(GREP_DEFAULT_LIMIT);- let base = resolve(root, &path);+ let base = resolve_path(root, scratch, &path);let root_owned = root.to_path_buf();let Some(pattern) = pattern else {@@ -1669,6 +1663,191 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// `find` from a legitimate `/tmp` base must not walk *out* through a+ /// symlinked directory inside the scratch. Pins `WalkBuilder`'s+ /// no-follow default, which is what the containment check cannot cover:+ /// the base path here is honest, only the recursion would escape.+ #[tokio::test]+ #[cfg(target_os = "linux")]+ async fn find_does_not_recurse_out_of_the_scratch_via_a_symlink() {+ let root = unique_root();+ let scratch = unique_root();+ let outside = unique_root();+ std::fs::write(outside.join("secret.txt"), b"classified").unwrap();+ std::os::unix::fs::symlink(&outside, scratch.join("esc")).unwrap();+ let store = crate::workspace::project_store(&root);+ let ctx = ToolContext::new(&root, &store, &[]).with_scratch_root(&scratch);+ let out = super::execute_builtin(+ lookup("find").unwrap(),+ &json!({"pattern": "*.txt", "path": "/tmp"}),+ &ctx,+ )+ .await;+ assert!(+ !out.contains("secret.txt"),+ "walked out of the scratch through a symlink: {out}"+ );+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ let _ = std::fs::remove_dir_all(&outside);+ }++ /// The write escape the scratch clamp is there to stop, spelled with a+ /// symlink instead of `..`: a confined `write` through `/tmp/esc` must be+ /// refused and must leave nothing behind outside the scratch.+ #[tokio::test]+ #[cfg(target_os = "linux")]+ async fn confined_write_refuses_a_tmp_symlink_escape() {+ let root = unique_root();+ let scratch = unique_root();+ let outside = unique_root();+ std::os::unix::fs::symlink(&outside, scratch.join("esc")).unwrap();+ let store = crate::workspace::project_store(&root);+ let ctx = ToolContext::new(&root, &store, &[])+ .with_scratch_root(&scratch)+ .with_confined_writes(true);+ let out = super::execute_builtin(+ lookup("write").unwrap(),+ &json!({"path": "/tmp/esc/pwned.txt", "content": "x"}),+ &ctx,+ )+ .await;+ assert!(out.starts_with("ERROR"), "must be refused, got: {out}");+ assert!(+ !outside.join("pwned.txt").exists(),+ "wrote outside the scratch via a symlink"+ );+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ let _ = std::fs::remove_dir_all(&outside);+ }++ /// A `write` to `/tmp/x` lands in the session scratch, and a `read` of the+ /// same path sees it: every fs tool shares the one `/tmp` the shell sees.+ #[tokio::test]+ async fn write_then_read_via_tmp_persists_in_scratch() {+ let root = unique_root();+ let scratch = unique_root();+ let store = crate::workspace::project_store(&root);+ let ctx = ToolContext::new(&root, &store, &[]).with_scratch_root(&scratch);+ let out = super::execute_builtin(+ lookup("write").unwrap(),+ &json!({"path": "/tmp/scratch.txt", "content": "persist"}),+ &ctx,+ )+ .await;+ assert!(out.starts_with("Created /tmp/scratch.txt"), "got: {out}");+ assert!(scratch.join("scratch.txt").exists(), "wrote into scratch");++ let out = super::execute_builtin(+ lookup("read").unwrap(),+ &json!({"path": "/tmp/scratch.txt"}),+ &ctx,+ )+ .await;+ assert_eq!(out, "persist");++ // No stray file on the real host /tmp.+ assert!(!Path::new("/tmp/scratch.txt").exists());+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }++ /// The bare `/tmp` dir resolves to the scratch root; files written there by+ /// the shell (or a sibling tool) are listable through the file tools.+ #[test]+ fn resolve_path_maps_tmp_into_scratch() {+ let root = unique_root();+ let scratch = unique_root();+ assert_eq!(+ crate::tools::sandbox::resolve_path(&root, Some(&scratch), "/tmp/a/b.txt"),+ scratch.join("a/b.txt")+ );+ assert_eq!(+ crate::tools::sandbox::resolve_path(&root, Some(&scratch), "/tmp"),+ scratch+ );+ // Without a scratch, /tmp stays the host path (i.e. never the project).+ assert_eq!(+ crate::tools::sandbox::resolve_path(&root, None, "/tmp/a.txt"),+ Path::new("/tmp/a.txt")+ );+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }++ /// A `..` climb inside `/tmp` must NOT escape the session scratch: an+ /// absolute path maps into the scratch, and a `..` is clamped back to the+ /// scratch root (chroot semantics, matching the `/tmp` bind mount), so it+ /// can never reach the host temp.+ #[test]+ fn tmp_path_cannot_climb_out_with_dotdot() {+ let root = unique_root();+ let scratch = unique_root();+ // `/tmp/../evil.txt` clamps inside the scratch, never the host parent.+ let out = crate::tools::sandbox::resolve_path(&root, Some(&scratch), "/tmp/../evil.txt");+ assert!(+ out.starts_with(&scratch),+ "must stay inside the scratch, got: {out:?}"+ );+ assert_eq!(out, scratch.join("evil.txt"));+ // Even a deeper climb stays clamped at the scratch root.+ let deep =+ crate::tools::sandbox::resolve_path(&root, Some(&scratch), "/tmp/../../deep.txt");+ assert_eq!(deep, scratch.join("deep.txt"));+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }++ /// The gate treats a scratch-backed `/tmp` write as inside, not an escape.+ #[test]+ fn gate_allows_tmp_write_when_scratch_is_set() {+ let root = unique_root();+ let scratch = unique_root();+ let d = crate::tools::gate::resolve_decision(+ lookup("write").unwrap(),+ &json!({"path": "/tmp/x.txt", "content": "y"}),+ &root,+ Some(&scratch),+ &crate::permissions::ToolPermissions::default(),+ &crate::tools::gate::SessionGrants::default(),+ );+ assert_eq!(+ d,+ crate::tools::gate::Decision::Prompt(crate::tools::gate::PromptKind::Write),+ "in-scratch write is an in-project write, not an escape"+ );+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }++ /// The counterpart: the same write spelled through a symlink out of the+ /// scratch is an escape, so it takes the escape prompt (refused outright on+ /// the desktop) rather than the ordinary in-project one.+ #[test]+ #[cfg(target_os = "linux")]+ fn gate_treats_a_tmp_symlink_escape_as_an_escape() {+ let root = unique_root();+ let scratch = unique_root();+ let outside = unique_root();+ std::os::unix::fs::symlink(&outside, scratch.join("esc")).unwrap();+ let d = crate::tools::gate::resolve_decision(+ lookup("write").unwrap(),+ &json!({"path": "/tmp/esc/x.txt", "content": "y"}),+ &root,+ Some(&scratch),+ &crate::permissions::ToolPermissions::default(),+ &crate::tools::gate::SessionGrants::default(),+ );+ assert_eq!(+ d,+ crate::tools::gate::Decision::Prompt(crate::tools::gate::PromptKind::WriteEscape)+ );+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ let _ = std::fs::remove_dir_all(&outside);+ }+#[tokio::test]async fn edit_error_yields_no_diff() {let root = unique_root();@@ -2052,6 +2231,47 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// The same overflow with a session scratch set: the spill must land in the+ /// scratch and be advertised by the one name that works from both the fs+ /// tools and the shell, so the `read` the note asks for actually finds it.+ /// The no-scratch case above cannot catch this -- there `/tmp` is not remapped.+ #[tokio::test]+ async fn bash_spill_is_readable_when_a_scratch_is_set() {+ let root = unique_root();+ let scratch = unique_root();+ let store = crate::workspace::project_store(&root);+ let ctx = ToolContext::new(&root, &store, &[]).with_scratch_root(&scratch);+ let out = super::execute_builtin(+ lookup("bash").unwrap(),+ &json!({"command": "for i in $(seq 1 16000); do printf '%064d\\n' \"$i\"; done"}),+ &ctx,+ )+ .await;+ let path = out+ .rsplit("full output written to ")+ .next()+ .and_then(|s| s.split(". Use the read tool").next())+ .unwrap_or("");+ if cfg!(target_os = "linux") {+ assert!(+ path.starts_with("/tmp/"),+ "must be advertised as the /tmp name the shell also sees: {out}"+ );+ }+ let full = super::execute_builtin(+ lookup("read").unwrap(),+ &json!({"path": path, "offset": 15999, "limit": 1}),+ &ctx,+ )+ .await;+ assert!(+ full.contains("015999") || full.contains("016000"),+ "spill at {path} must be readable back: {full}"+ );+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }+#[tokio::test]async fn bash_line_overflow_keeps_the_tail_not_the_head() {let root = unique_root();diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rsindex 0a0272efe..b5f590381 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs@@ -87,6 +87,14 @@ pub struct Policy {/// desktop keeps the full isolation so `settings.json` and provider keys/// stay out of the shell's reach.pub home_readonly: bool,+ /// A session-scoped host directory the shell may write to for the whole run,+ /// instead of a scratch that vanishes between commands. How it is exposed is+ /// per backend: bubblewrap binds it over `/tmp`, replacing the volatile+ /// overlay that would otherwise discard scratch files with each command;+ /// Seatbelt grants it by `SCRATCH` parameter; AppContainer grants it an ACE.+ /// The directory must already exist before the sandbox is built (the+ /// backends reference it, they do not create it).+ pub scratch_root: Option<PathBuf>,}impl Policy {@@ -97,6 +105,7 @@ impl Policy {allow_network,hide_root: None,home_readonly: false,+ scratch_root: None,}}@@ -126,6 +135,15 @@ impl Policy {self.home_readonly = home_readonly;self}++ /// Expose `scratch_root` to the shell so scratch files persist across `bash`+ /// calls in a session instead of being discarded with each private tmpfs.+ /// See [`Policy::scratch_root`]. The directory must already exist (the+ /// caller creates and owns its lifecycle).+ pub fn with_scratch_root(mut self, scratch_root: &Path) -> Self {+ self.scratch_root = Some(scratch_root.to_path_buf());+ self+ }}/// The user's home directory, or `None` when it is unset or degenerate. A `/`@@ -185,6 +203,21 @@ fn detect() -> Backend {}}+/// Where the session scratch is reachable from *inside* the sandbox, which is+/// what the shell's `TMPDIR`/`TMP`/`TEMP` must name. Bubblewrap binds the+/// scratch over `/tmp`, so the host path does not exist in that namespace;+/// Seatbelt and AppContainer mount nothing, so the real path is the only one+/// that resolves -- and it is the same name the filesystem tools use there, so+/// a file written by `bash` can be read back by `read`. `None` when the caller+/// set no scratch: the shell then keeps the host's own temp dir.+pub fn scratch_env_path(backend: Backend, policy: &Policy) -> Option<PathBuf> {+ let scratch = policy.scratch_root.as_ref()?;+ Some(match backend {+ Backend::Bubblewrap => PathBuf::from("/tmp"),+ _ => scratch.clone(),+ })+}+/// Wrap `cfg` so the shell it describes runs confined. The returned config keeps/// the same shape -- program, fixed args, command appended last -- so the spawn/// path is unchanged. Returns `None` when no backend can enforce the policy, in@@ -210,6 +243,7 @@ pub fn wrap(cfg: &ShellConfig, policy: &Policy) -> Option<ShellConfig> {program: std::env::current_exe().ok()?,args: appcontainer::helper_args(&policy.workspace,+ policy.scratch_root.as_deref(),policy.allow_network,&cfg.program,&cfg.args,@@ -293,8 +327,16 @@ pub fn bwrap_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {// rather than the host's, and so an unshared pid namespace has a valid /proc.push(&mut args, &["--proc", "/proc"]);push(&mut args, &["--dev", "/dev"]);- // Private temp: writable, discarded with the sandbox, invisible to the host.- push(&mut args, &["--tmpfs", "/tmp"]);+ // `/tmp`: by default a private tmpfs, writable and discarded with the+ // sandbox. When a session-scoped scratch root is set, bind it over `/tmp`+ // instead (the tmpfs would shadow it), so scratch files persist across+ // `bash` calls for the whole run.+ if let Some(scratch) = &policy.scratch_root {+ let scratch = scratch.to_string_lossy();+ push(&mut args, &["--bind", &scratch, "/tmp"]);+ } else {+ push(&mut args, &["--tmpfs", "/tmp"]);+ }// An empty tmpfs over $HOME hides user files without needing a deny rule.// The workspace is re-bound on top, so it survives while its siblings (the@@ -405,6 +447,17 @@ pub fn seatbelt_policy(policy: &Policy) -> String {(allow file-write* (subpath (param \"TMPDIR\")))\n\(allow file-write* (subpath \"/private/tmp\"))\n",);+ // The session scratch by name, rather than trusting it to sit under TMPDIR:+ // a relocated scratch must stay usable, and it is read back after the home+ // denial above, which would otherwise cover a scratch inside $HOME. Emitted+ // only with the matching `-DSCRATCH`, since sandbox-exec refuses a profile+ // that references a parameter no argument supplies.+ if policy.scratch_root.is_some() {+ p.push_str(+ "(allow file-read* (subpath (param \"SCRATCH\")))\n\+ (allow file-write* (subpath (param \"SCRATCH\")))\n",+ );+ }// Last, so it wins over the workspace allow above: the agent's own state// directory is neither readable nor writable, however the command spells it.if policy.hide_root.is_some() {@@ -450,6 +503,9 @@ pub fn seatbelt_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {"-DTMPDIR={}",std::env::temp_dir().to_string_lossy()));+ if let Some(scratch) = &policy.scratch_root {+ args.push(format!("-DSCRATCH={}", scratch.to_string_lossy()));+ }if let Some(home) = home_dir() {args.push(format!("-DHOME_ROOT={}", home.to_string_lossy()));}@@ -502,8 +558,14 @@ pub fn denial_hint(policy: &Policy) -> String {} else {" and files under your home directory are not readable"};+ // Naming only the workspace would send the model away from the scratch,+ // which is writable too and is where temporary work belongs.+ let scratch = match scratch_env_path(backend(), policy) {+ Some(path) => format!(" and the scratch dir ({})", path.display()),+ None => String::new(),+ };format!(- "\n[sandbox: writes are limited to the workspace ({}){home}.{net}]",+ "\n[sandbox: writes are limited to the workspace ({}){scratch}{home}.{net}]",policy.workspace.display())}@@ -628,6 +690,23 @@ mod tests {assert!(text.contains("--tmpfs /tmp"));}+ #[test]+ fn bwrap_binds_scratch_over_tmp_instead_of_a_tmpfs() {+ let scratch = Path::new("/data/agent-workspace/threads/t1/agent-scratch");+ let scratch_bind = format!("--bind {} /tmp", scratch.to_string_lossy());++ // Default: a throwaway tmpfs per command, no scratch bind.+ let default = joined(&bwrap_args(&policy(), &cfg()));+ assert!(default.contains("--tmpfs /tmp"), "{default}");+ assert!(!default.contains(&scratch_bind), "{default}");++ // With a scratch root, /tmp is a real bind so files written there by one+ // bash call survive into the next.+ let bound = joined(&bwrap_args(&policy().with_scratch_root(scratch), &cfg()));+ assert!(!bound.contains("--tmpfs /tmp"), "{bound}");+ assert!(bound.contains(&scratch_bind), "{bound}");+ }+#[test]fn bwrap_ends_with_the_shell_so_the_command_appends_last() {let args = bwrap_args(&policy(), &cfg());@@ -679,6 +758,56 @@ mod tests {assert!(!p.contains("(allow file-write*)"));}+ /// The scratch is granted by name rather than relying on it happening to sit+ /// under the host temp dir, so a relocated scratch stays writable.+ #[test]+ fn seatbelt_grants_the_scratch_as_its_own_parameter() {+ let scratch = Path::new("/var/scratch/jan-agent-s1");+ let p = seatbelt_policy(&policy().with_scratch_root(scratch));+ assert!(p.contains("(allow file-write* (subpath (param \"SCRATCH\")))"));+ let args = seatbelt_args(&policy().with_scratch_root(scratch), &cfg());+ assert!(args+ .iter()+ .any(|a| a == "-DSCRATCH=/var/scratch/jan-agent-s1"));+ assert!(+ !args[1].contains("/var/scratch"),+ "path must not be inlined"+ );+ }++ /// `sandbox-exec` fails to launch when the profile references a `param` no+ /// `-D` supplies, so the rule and the parameter must appear together.+ #[test]+ fn seatbelt_omits_the_scratch_rule_when_there_is_no_scratch() {+ let p = seatbelt_policy(&policy());+ assert!(!p.contains("SCRATCH"));+ let args = seatbelt_args(&policy(), &cfg());+ assert!(!args.iter().any(|a| a.starts_with("-DSCRATCH=")));+ }++ /// What `TMPDIR` must say inside the sandbox: bubblewrap binds the scratch+ /// over `/tmp`, so the host path is meaningless there; the other backends+ /// have no mount, so the real path is the only one that resolves.+ #[test]+ fn scratch_env_path_follows_what_the_backend_actually_mounts() {+ let scratch = Path::new("/var/scratch/jan-agent-s1");+ let with = policy().with_scratch_root(scratch);+ assert_eq!(+ scratch_env_path(Backend::Bubblewrap, &with).as_deref(),+ Some(Path::new("/tmp"))+ );+ for backend in [Backend::Seatbelt, Backend::AppContainer] {+ assert_eq!(+ scratch_env_path(backend, &with).as_deref(),+ Some(scratch),+ "{backend:?} has no mount, so the real path is the scratch"+ );+ }+ // No scratch, nothing to point at: the shell keeps the default temp dir.+ assert_eq!(scratch_env_path(Backend::Bubblewrap, &policy()), None);+ assert_eq!(scratch_env_path(Backend::Seatbelt, &policy()), None);+ }+#[test]fn seatbelt_denies_network_unless_allowed() {assert!(seatbelt_policy(&policy()).contains("(deny network*)"));@@ -726,6 +855,22 @@ mod tests {assert!(hint.contains("/data/agent-workspace/threads/t1"));assert!(hint.contains("Network access is disabled."));assert!(!denial_hint(&Policy::new(Path::new("/w"), true)).contains("Network access"));+ // With no scratch there is nothing to point the model at.+ assert!(!hint.contains("scratch"));+ }++ /// A denied write must not send the model away from the one other place it+ /// is allowed to write, named as the sandbox exposes it.+ #[test]+ fn denial_hint_names_the_scratch_when_there_is_one() {+ let scratch = Path::new("/var/scratch/jan-agent-s1");+ let hint = denial_hint(&policy().with_scratch_root(scratch));+ let expected = scratch_env_path(backend(), &policy().with_scratch_root(scratch))+ .expect("a scratch was set");+ assert!(+ hint.contains(&format!("scratch dir ({})", expected.display())),+ "got: {hint}"+ );}#[test]@@ -783,7 +928,9 @@ mod enforcement_tests {/// Run `command` under `policy`, spawning in `ws`.async fn run_policy(policy: Policy, ws: &Path, command: &str) -> (bool, String) {let wrapped = wrap(super::super::proc::shell(), &policy).expect("backend");- let child = super::super::proc::spawn(&wrapped, command, ws)+ // Mirrors the bash handler: the temp env follows what the backend mounts.+ let tmp = scratch_env_path(backend(), &policy);+ let child = super::super::proc::spawn(&wrapped, command, ws, tmp.as_deref()).await.expect("spawn");let pid = child.id();@@ -841,6 +988,28 @@ mod enforcement_tests {let _ = std::fs::remove_dir_all(&ws);}+ #[tokio::test]+ async fn scratch_persists_across_bash_calls_when_bound_over_tmp() {+ require_backend!();+ let ws = workspace();+ let scratch = ws.join("agent-scratch");+ std::fs::create_dir_all(&scratch).unwrap();+ let policy = Policy::new(&ws, false).with_scratch_root(&scratch);++ // Write into /tmp in the first call, then read it back in a second,+ // separate sandboxed process. This is exactly the pattern the fix+ // exists for: a scratch pad that outlives a single bash invocation.+ let (ok, out) = run_policy(policy.clone(), &ws, "echo persistent > /tmp/scratch.txt").await;+ assert!(ok, "scratch write must succeed: {out}");+ let (ok, out) = run_policy(policy, &ws, "cat /tmp/scratch.txt").await;+ let _ = std::fs::remove_dir_all(&ws);+ assert!(ok, "scratch read must succeed: {out}");+ assert!(+ out.contains("persistent"),+ "scratch must survive a second bash call: {out}"+ );+ }+#[tokio::test]async fn writes_outside_the_workspace_never_reach_the_host() {require_backend!();diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rsindex af7bf56b5..cd6bde773 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs@@ -54,6 +54,13 @@ pub struct ToolContext<'a> {/// Expose `$HOME` to the sandboxed shell read-only (the CLI) instead of/// hiding it (the desktop). Passed through to the `bash` sandbox policy.pub home_readonly: bool,+ /// A session-scoped host directory the shell and the filesystem tools share+ /// for temporary work, so scratch files persist across `bash` calls in the+ /// run. See [`Policy::scratch_root`] for how each backend exposes it, and+ /// [`crate::workspace::scratch_dir`] for where it lives. `None` keeps the+ /// default throwaway per-command tmpfs. Cleaned up with the session (run end+ /// on the CLI, thread teardown on the desktop).+ pub scratch_root: Option<&'a Path>,}impl<'a> ToolContext<'a> {@@ -66,6 +73,7 @@ impl<'a> ToolContext<'a> {confine_writes: false,mask_root: None,home_readonly: false,+ scratch_root: None,}}@@ -89,6 +97,13 @@ impl<'a> ToolContext<'a> {self.home_readonly = home_readonly;self}++ /// Bind `scratch_root` over the sandbox's `/tmp` so scratch files survive+ /// across `bash` calls. See [`Self::scratch_root`].+ pub fn with_scratch_root(mut self, scratch_root: &'a Path) -> Self {+ self.scratch_root = Some(scratch_root);+ self+ }}#[derive(Debug, Clone, Copy, PartialEq, Eq)]diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rsindex a61133337..b6d401709 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs@@ -128,6 +128,11 @@ fn which(name: &str) -> Option<PathBuf> {/// seatbelt, and the Windows AppContainer helper) funnel through.const SANDBOX_ENV_ALLOW: &[&str] = &["PATH", "HOME", "USERPROFILE", "TMPDIR", "TMP", "TEMP", "LANG", "TERM"];+/// Every spelling of "where temporary files go": POSIX tools read `TMPDIR`,+/// Windows ones `TEMP`/`TMP`, and a mixed toolchain (git-bash, MSYS) reads both.+/// All are pointed at the scratch together so no tool falls back to the host.+const TEMP_ENV_KEYS: &[&str] = &["TMPDIR", "TMP", "TEMP"];+/// Bound the resource exhaustion a sandboxed command could otherwise trigger on/// the host. `bwrap` 0.6.1 (and older) has no `--rlimit`, so instead we clamp the/// child's soft limits here, before exec, from the one choke point every backend@@ -164,7 +169,12 @@ fn confine_limits(cmd: &mut Command) {}}-pub async fn spawn(cfg: &ShellConfig, command: &str, cwd: &Path) -> std::io::Result<Child> {+pub async fn spawn(+ cfg: &ShellConfig,+ command: &str,+ cwd: &Path,+ scratch: Option<&Path>,+) -> std::io::Result<Child> {let mut cmd = Command::new(&cfg.program);cmd.args(&cfg.args);if !cfg.via_stdin {@@ -179,6 +189,17 @@ pub async fn spawn(cfg: &ShellConfig, command: &str, cwd: &Path) -> std::io::Rescmd.env(key, val);}}+ // Point the shell's temp env at the session scratch, overriding the host+ // values the allowlist just copied in. Without this a command that writes+ // through `mktemp`/`$TMPDIR` lands in the host temp dir -- unreachable to+ // the filesystem tools, and on the backends that confine by path, not+ // writable at all. `scratch` is what the sandbox exposes, which is not+ // always the host path (see `jail::scratch_env_path`).+ if let Some(scratch) = scratch {+ for key in TEMP_ENV_KEYS {+ cmd.env(key, scratch);+ }+ }cmd.current_dir(cwd).stdout(Stdio::piped()).stderr(Stdio::piped())@@ -286,18 +307,58 @@ mod tests {#[tokio::test]async fn runs_a_command_and_captures_stdout() {- let child = spawn(shell(), "echo hello", &tmp()).await.unwrap();+ let child = spawn(shell(), "echo hello", &tmp(), None).await.unwrap();let pid = child.id().unwrap();let out = child.wait_with_output().await.unwrap();unregister(pid);assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "hello");}+ /// `mktemp`, `pytest`, `cargo` and friends write to `$TMPDIR`, so the scratch+ /// is only useful if it is what the shell's temp env names. All three+ /// spellings are set: POSIX tools read `TMPDIR`, Windows ones `TEMP`/`TMP`.+ #[tokio::test]+ async fn temp_env_points_at_the_scratch_when_one_is_given() {+ let scratch = tmp().join("jan_proc_scratch_env");+ std::fs::create_dir_all(&scratch).unwrap();+ let child = spawn(+ shell(),+ "echo \"$TMPDIR $TMP $TEMP\"",+ &tmp(),+ Some(&scratch),+ )+ .await+ .unwrap();+ let pid = child.id().unwrap();+ let out = child.wait_with_output().await.unwrap();+ unregister(pid);+ let s = scratch.to_string_lossy();+ assert_eq!(+ String::from_utf8_lossy(&out.stdout).trim(),+ format!("{s} {s} {s}")+ );+ let _ = std::fs::remove_dir_all(&scratch);+ }++ /// With no scratch the shell keeps whatever the host allowlist passed+ /// through, rather than being handed an empty temp dir.+ #[tokio::test]+ async fn temp_env_is_left_alone_without_a_scratch() {+ let child = spawn(shell(), "echo ${TMPDIR:-unset}", &tmp(), None)+ .await+ .unwrap();+ let pid = child.id().unwrap();+ let out = child.wait_with_output().await.unwrap();+ unregister(pid);+ let expected = std::env::var("TMPDIR").unwrap_or_else(|_| "unset".to_string());+ assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), expected);+ }+#[tokio::test]async fn kill_tree_reaps_backgrounded_grandchild() {// The shell backgrounds a long sleeper, prints its pid, then waits on// it. Killing the group must take down that grandchild too.- let mut child = spawn(shell(), "sleep 300 & echo $! ; wait", &tmp())+ let mut child = spawn(shell(), "sleep 300 & echo $! ; wait", &tmp(), None).await.unwrap();let leader = child.id().unwrap();@@ -342,14 +403,14 @@ mod tests {async fn confine_limits_caps_the_child_process_count() {// The rlimit mounting must actually reach the spawned child: with NPROC// clamped we still run up to the cap, but a fork-bomb past it fails.- let child = spawn(shell(), "exit 0", &tmp()).await.unwrap();+ let child = spawn(shell(), "exit 0", &tmp(), None).await.unwrap();let pid = child.id().unwrap();child.wait_with_output().await.unwrap();unregister(pid);// Spawn a shell that reports its own soft NOFILE limit; confine_limits// sets it to 1024, which should be visible inside the sandbox.- let child = spawn(shell(), "ulimit -n", &tmp()).await.unwrap();+ let child = spawn(shell(), "ulimit -n", &tmp(), None).await.unwrap();let pid = child.id().unwrap();let out = child.wait_with_output().await.unwrap();unregister(pid);diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rsindex a94013e85..06332d867 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs@@ -1,11 +1,33 @@use std::path::{Path, PathBuf};-/// True iff `raw` resolves to a path outside `project_root`.-/// Relative paths are resolved against `project_root`. Canonicalizes (resolving-/// `..` and symlinks) so string tricks and symlink escapes are caught. For a-/// not-yet-existing leaf (new-file writes), the deepest existing ancestor is-/// canonicalized and the remaining tail re-joined.-pub fn escapes_project(project_root: &Path, raw: &str) -> Result<bool, String> {+/// True iff `raw` resolves to a path outside `project_root` and outside the+/// session scratch. Relative paths are resolved against `project_root`.+/// Canonicalizes (resolving `..` and symlinks) so string tricks and symlink+/// escapes are caught. For a not-yet-existing leaf (new-file writes), the+/// deepest existing ancestor is canonicalized and the remaining tail re-joined.+pub fn escapes_project(+ project_root: &Path,+ scratch: Option<&Path>,+ raw: &str,+) -> Result<bool, String> {+ // Absolute `/tmp` paths map into the session scratch (see [`resolve_path`]),+ // which is the agent's own area -- but only once the mapped path is checked+ // against it. Clamping `..` happens lexically, so a symlink planted in the+ // scratch (the shell can make one: `/tmp` is the scratch bind) would+ // otherwise resolve straight back out to the host. Canonicalize what the+ // clamp produced and require it to still be inside.+ if cfg!(target_os = "linux") {+ if let Some(scratch) = scratch {+ if tmp_relative(raw).is_some() {+ let scratch_root = scratch+ .canonicalize()+ .map_err(|e| format!("scratch root {:?}: {e}", scratch))?;+ let resolved =+ canonicalize_lenient(&resolve_path(project_root, Some(scratch), raw))?;+ return Ok(!resolved.starts_with(&scratch_root));+ }+ }+ }let root = project_root.canonicalize().map_err(|e| format!("project root {:?}: {e}", project_root))?;@@ -15,7 +37,133 @@ pub fn escapes_project(project_root: &Path, raw: &str) -> Result<bool, String> {root.join(raw)};let resolved = canonicalize_lenient(&abs)?;- Ok(!resolved.starts_with(&root))+ if resolved.starts_with(&root) {+ return Ok(false);+ }+ // The scratch is the agent's own per-session area and is writable under+ // every backend, so a path landing in it is not a host escape even though it+ // sits outside the project. On Linux it is normally reached through the+ // `/tmp` branch above; macOS and Windows have no bind mount, so the shell+ // and the filesystem tools both address it by this real path. A scratch that+ // cannot be canonicalized grants nothing: the path stays an escape.+ if let Some(scratch) = scratch {+ if let Ok(scratch) = scratch.canonicalize() {+ return Ok(!resolved.starts_with(&scratch));+ }+ }+ Ok(true)+}++/// Resolve a tool-supplied path to its on-disk location, forwarding an absolute+/// `/tmp/...` path into the session scratch when one is set (and only on Linux,+/// where the bash sandbox binds the scratch over `/tmp`). This keeps every+/// filesystem tool reading and writing the same `/tmp` the shell sees. With no+/// scratch, `/tmp` stays a plain host path.+///+/// The scratch is treated like a chroot: no `..` component may climb above the+/// scratch root, matching how the sandbox's `/tmp` mount behaves (it is a mount+/// point, so `..` above it stays inside `/tmp`).+pub fn resolve_path(project_root: &Path, scratch: Option<&Path>, raw: &str) -> PathBuf {+ if cfg!(target_os = "linux") {+ if let Some(rel) = tmp_relative(raw) {+ if let Some(scratch) = scratch {+ return clamp_scratch(scratch, &rel);+ }+ }+ }+ if Path::new(raw).is_absolute() {+ PathBuf::from(raw)+ } else {+ project_root.join(raw)+ }+}++/// The spelling to hand a tool-facing path back to the model: the inverse of+/// [`resolve_path`]. On Linux a file inside the scratch is named `/tmp/...`, the+/// one name that works from both the filesystem tools (which remap it back) and+/// `bash` (where the scratch is mounted at `/tmp`); its host path would resolve+/// for the former and not exist for the latter. Where nothing is mounted over+/// `/tmp` (macOS, Windows) both surfaces use the real path, so that is the name.+/// Anything outside the scratch is shown as-is.+pub fn scratch_display_path(scratch: Option<&Path>, path: &Path) -> String {+ let target = lexical_normalize(path);+ if cfg!(target_os = "linux") {+ if let Some(rel) = scratch_tail(scratch, &target) {+ let rel = rel.to_string_lossy().replace('\\', "/");+ return if rel.is_empty() {+ "/tmp".to_string()+ } else {+ format!("/tmp/{rel}")+ };+ }+ }+ target.to_string_lossy().into_owned()+}++/// True iff `path` lexically sits inside the session scratch. Lexical on+/// purpose: it names a path the tools are about to create as well as one that+/// already exists.+pub fn in_scratch(scratch: Option<&Path>, path: &Path) -> bool {+ scratch_tail(scratch, &lexical_normalize(path)).is_some()+}++/// The scratch-relative tail of an already-normalized `path`, or `None` when it+/// is not in the scratch. `Some("")` for the scratch root itself.+fn scratch_tail(scratch: Option<&Path>, path: &Path) -> Option<PathBuf> {+ let scratch = lexical_normalize(scratch?);+ path.strip_prefix(&scratch).ok().map(Path::to_path_buf)+}++/// Resolve `.`/`..` without touching the filesystem, so a path is comparable to+/// the project root even when the target does not exist yet. Purely lexical:+/// `canonicalize` would also follow symlinks and fail on missing files.+pub fn lexical_normalize(path: &Path) -> PathBuf {+ use std::path::Component;+ let mut out = PathBuf::new();+ for c in path.components() {+ match c {+ Component::CurDir => {}+ Component::ParentDir => {+ out.pop();+ }+ other => out.push(other.as_os_str()),+ }+ }+ out+}++/// Join `rel` under `scratch`, clamping `..` so it can never climb above the+/// scratch root (chroot semantics). A leading `..` or `/tmp/..` therefore falls+/// back to the scratch root rather than escaping to the host temp.+fn clamp_scratch(scratch: &Path, rel: &str) -> PathBuf {+ let mut out = scratch.to_path_buf();+ for c in Path::new(rel).components() {+ match c {+ std::path::Component::ParentDir => {+ // Clamp: never pop past the scratch root.+ if out != scratch {+ out.pop();+ }+ }+ std::path::Component::CurDir => {}+ other => out.push(other.as_os_str()),+ }+ }+ out+}++/// The `/tmp`-relative tail of an absolute `/tmp/...` path; `Some("")` for the+/// bare `/tmp` dir itself; `None` when `raw` is not such a path.+fn tmp_relative(raw: &str) -> Option<String> {+ let path = Path::new(raw);+ if !path.is_absolute() {+ return None;+ }+ let rest = raw.strip_prefix("/tmp")?;+ if rest.is_empty() {+ return Some(String::new());+ }+ Some(rest.strip_prefix('/').unwrap_or(rest).to_string())}/// The agent's own state directory inside a project. Hidden wholesale rather@@ -111,11 +259,24 @@ mod tests {dir}+ /// A test dir that is *not* under the host temp dir, so a Linux run does not+ /// silently route through the `/tmp` bind branch. Lives under the crate's+ /// `target/`, which is already build output.+ fn unique_root_outside_tmp() -> PathBuf {+ let n = COUNTER.fetch_add(1, Ordering::SeqCst);+ let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .join("target")+ .join("sandbox-tests")+ .join(format!("{}_{}", std::process::id(), n));+ std::fs::create_dir_all(&dir).expect("create test scratch");+ dir+ }+#[test]fn in_project_file_does_not_escape() {let root = unique_root();std::fs::write(root.join("inner.txt"), b"x").unwrap();- assert_eq!(escapes_project(&root, "inner.txt"), Ok(false));+ assert_eq!(escapes_project(&root, None, "inner.txt"), Ok(false));let _ = std::fs::remove_dir_all(&root);}@@ -124,14 +285,14 @@ mod tests {let root = unique_root();std::fs::create_dir_all(root.join("sub")).unwrap();std::fs::write(root.join("sub/inner.txt"), b"x").unwrap();- assert_eq!(escapes_project(&root, "sub/inner.txt"), Ok(false));+ assert_eq!(escapes_project(&root, None, "sub/inner.txt"), Ok(false));let _ = std::fs::remove_dir_all(&root);}#[test]fn dotdot_escapes() {let root = unique_root();- assert_eq!(escapes_project(&root, "../outside.txt"), Ok(true));+ assert_eq!(escapes_project(&root, None, "../outside.txt"), Ok(true));let _ = std::fs::remove_dir_all(&root);}@@ -139,7 +300,7 @@ mod tests {fn absolute_outside_escapes() {let root = unique_root();let outside = std::env::temp_dir().join("definitely_outside_the_root.txt");- assert_eq!(escapes_project(&root, outside.to_str().unwrap()), Ok(true));+ assert_eq!(escapes_project(&root, None, outside.to_str().unwrap()), Ok(true));let _ = std::fs::remove_dir_all(&root);}@@ -148,7 +309,7 @@ mod tests {let root = unique_root();std::fs::write(root.join("inner.txt"), b"x").unwrap();let inside = root.join("inner.txt");- assert_eq!(escapes_project(&root, inside.to_str().unwrap()), Ok(false));+ assert_eq!(escapes_project(&root, None, inside.to_str().unwrap()), Ok(false));let _ = std::fs::remove_dir_all(&root);}@@ -156,7 +317,7 @@ mod tests {fn new_file_in_project_dir_does_not_escape() {let root = unique_root();std::fs::create_dir_all(root.join("sub")).unwrap();- assert_eq!(escapes_project(&root, "sub/newfile.txt"), Ok(false));+ assert_eq!(escapes_project(&root, None, "sub/newfile.txt"), Ok(false));let _ = std::fs::remove_dir_all(&root);}@@ -218,6 +379,116 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// A symlink planted in the scratch (the shell can create one: `/tmp` is+ /// the scratch bind) must not turn `/tmp/...` into a way out. Clamping `..`+ /// is not enough -- the link is a single component that resolves elsewhere.+ #[test]+ #[cfg(target_os = "linux")]+ fn tmp_symlink_cannot_escape_the_scratch() {+ let root = unique_root();+ let scratch = unique_root();+ let outside = unique_root();+ std::os::unix::fs::symlink(&outside, scratch.join("esc")).unwrap();+ assert_eq!(+ escapes_project(&root, Some(&scratch), "/tmp/esc/pwned.txt"),+ Ok(true),+ "a symlink out of the scratch is an escape"+ );+ // A genuine scratch path is still not an escape.+ assert_eq!(+ escapes_project(&root, Some(&scratch), "/tmp/ok.txt"),+ Ok(false)+ );+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ let _ = std::fs::remove_dir_all(&outside);+ }++ /// A scratch reached by its real path (no `/tmp` bind in front of it) is the+ /// agent's own area on every platform, so it must not read as an escape.+ /// The scratch here sits outside the host temp dir on purpose: on Linux a+ /// `/tmp`-prefixed path would be answered by the bind branch above instead,+ /// leaving the cross-platform branch untested on the one OS we can run.+ #[test]+ fn real_scratch_path_is_not_an_escape() {+ let root = unique_root();+ let scratch = unique_root_outside_tmp();+ let inside = scratch.join("notes.txt");+ assert_eq!(+ escapes_project(&root, Some(&scratch), inside.to_str().unwrap()),+ Ok(false),+ "a write into the session scratch is not a host escape"+ );+ assert_eq!(+ escapes_project(&root, Some(&scratch), scratch.to_str().unwrap()),+ Ok(false),+ "the scratch root itself is addressable"+ );+ // The allowance is the scratch, not its parent.+ let sibling = scratch.parent().unwrap().join("not_the_scratch.txt");+ assert_eq!(+ escapes_project(&root, Some(&scratch), sibling.to_str().unwrap()),+ Ok(true)+ );+ // And nothing changes for a caller with no scratch at all.+ assert_eq!(+ escapes_project(&root, None, inside.to_str().unwrap()),+ Ok(true)+ );+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ }++ /// The real-path branch resolves symlinks for the same reason the `/tmp`+ /// branch does: the shell can plant one inside the scratch.+ #[cfg(unix)]+ #[test]+ fn real_scratch_path_symlink_cannot_escape() {+ let root = unique_root();+ let scratch = unique_root_outside_tmp();+ let outside = unique_root();+ std::os::unix::fs::symlink(&outside, scratch.join("esc")).unwrap();+ let via_link = scratch.join("esc").join("pwned.txt");+ assert_eq!(+ escapes_project(&root, Some(&scratch), via_link.to_str().unwrap()),+ Ok(true),+ "a symlink out of the scratch is an escape"+ );+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&scratch);+ let _ = std::fs::remove_dir_all(&outside);+ }++ /// The name handed back to the model: the `/tmp` alias only where something+ /// is actually mounted there, the real path everywhere else.+ #[test]+ fn scratch_is_displayed_under_the_name_the_shell_can_use() {+ let scratch = PathBuf::from(if cfg!(windows) {+ r"C:\Temp\jan-agent-s1"+ } else {+ "/var/scratch/jan-agent-s1"+ });+ let file = scratch.join("out.txt");+ assert!(in_scratch(Some(&scratch), &file));+ assert!(!in_scratch(Some(&scratch), Path::new("/elsewhere/out.txt")));+ assert!(!in_scratch(None, &file));+ if cfg!(target_os = "linux") {+ assert_eq!(scratch_display_path(Some(&scratch), &file), "/tmp/out.txt");+ assert_eq!(scratch_display_path(Some(&scratch), &scratch), "/tmp");+ } else {+ assert_eq!(+ scratch_display_path(Some(&scratch), &file),+ file.to_string_lossy()+ );+ }+ // Outside the scratch the path is untouched either way.+ let other = PathBuf::from("/elsewhere/out.txt");+ assert_eq!(+ scratch_display_path(Some(&scratch), &other),+ other.to_string_lossy()+ );+ }+#[cfg(unix)]#[test]fn symlink_escape_is_caught() {@@ -226,7 +497,7 @@ mod tests {std::fs::write(outside.join("secret.txt"), b"x").unwrap();let link = root.join("link");std::os::unix::fs::symlink(&outside, &link).unwrap();- assert_eq!(escapes_project(&root, "link/secret.txt"), Ok(true));+ assert_eq!(escapes_project(&root, None, "link/secret.txt"), Ok(true));let _ = std::fs::remove_dir_all(&root);let _ = std::fs::remove_dir_all(&outside);}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rsindex 5aa8c8505..0d1dc4a0a 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs@@ -61,6 +61,43 @@ pub fn thread_workspace(jan_data_folder: &Path, thread_id: &str) -> Result<PathBOk(threads_dir(jan_data_folder).join(thread_segment(thread_id)?))}+/// The session-scoped scratch directory: a subdirectory of the host temp dir+/// (e.g. `/tmp/jan-agent-<session>` on Linux), where `bash` scratch files+/// persist across calls for one session and the filesystem tools may write.+///+/// Every backend exposes it, but not the same way. Bubblewrap binds it over the+/// sandbox's `/tmp` -- only this session subdir, not the whole host `/tmp`, so+/// the shell sees its own scratch and none of the machine's other temp files --+/// and the tools remap `/tmp/...` back onto it. Seatbelt and AppContainer have+/// no mount, so it is reached by this real path and made writable by a policy+/// rule and an ACE respectively. Either way `TMPDIR`/`TMP`/`TEMP` point at it+/// (see `tools::jail::scratch_env_path`) and it is cleaned up with the session.+pub fn scratch_dir(session: &str) -> PathBuf {+ std::env::temp_dir().join(format!("jan-agent-{session}"))+}++/// Create the session-scoped scratch directory (idempotent) and return it.+/// Must exist before the Linux sandbox binds it over `/tmp`. The caller owns+/// its teardown: thread deletion on the desktop, run end on the CLI, and+/// session end in the TUI.+pub async fn ensure_scratch_dir(session: &str) -> Result<PathBuf, String> {+ let dir = scratch_dir(session);+ tokio::fs::create_dir_all(&dir)+ .await+ .map_err(|e| format!("ERROR: {e}"))?;+ Ok(dir)+}++/// Delete a session's scratch directory. Idempotent: a missing scratch is Ok.+pub async fn remove_scratch_dir(session: &str) -> Result<(), String> {+ let dir = scratch_dir(session);+ match tokio::fs::remove_dir_all(&dir).await {+ Ok(()) => Ok(()),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(e) => Err(format!("ERROR: {e}")),+ }+}+/// Create the permanent store and its `memory/`/`skills/` subdirectories,/// returning the store root. Idempotent.pub async fn ensure_permanent_store(jan_data_folder: &Path) -> Result<PathBuf, String> {@@ -97,10 +134,13 @@ pub async fn remove_thread_workspace(let dir = thread_workspace(jan_data_folder, thread_id)?;crate::tools::appcontainer::release(&dir);match tokio::fs::remove_dir_all(&dir).await {- Ok(()) => Ok(()),- Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),- Err(e) => Err(format!("ERROR: {e}")),+ Ok(()) => {}+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}+ Err(e) => return Err(format!("ERROR: {e}")),}+ // Wipe the session-scoped host-temp scratch keyed to the same thread id.+ let _ = remove_scratch_dir(thread_id).await;+ Ok(())}/// Delete every thread sandbox whose id is not in `keep`, returning how many@@ -135,6 +175,8 @@ pub async fn sweep_thread_workspaces(crate::tools::appcontainer::release(&entry.path());if tokio::fs::remove_dir_all(entry.path()).await.is_ok() {removed += 1;+ // Wipe the session-scoped host-temp scratch keyed to this thread.+ let _ = remove_scratch_dir(&name).await;}}Ok(removed)@@ -221,6 +263,23 @@ mod tests {assert!(!store_dir(&permanent_store(data), "memory").starts_with(&thread));}+ #[tokio::test]+ async fn scratch_dir_lifecycle_is_session_keyed_and_removable() {+ let session = "t1";+ let scratch = scratch_dir(session);+ assert!(!scratch.exists());++ let created = ensure_scratch_dir(session).await.unwrap();+ assert_eq!(created, scratch);+ assert!(scratch.is_dir());++ std::fs::write(scratch.join("f"), b"x").unwrap();+ remove_scratch_dir(session).await.unwrap();+ assert!(!scratch.exists());+ // Idempotent.+ remove_scratch_dir(session).await.unwrap();+ }+#[test]fn thread_segment_rejects_traversal_and_separators() {for bad in [diff --git a/src-tauri/src/core/agent/commands.rs b/src-tauri/src/core/agent/commands.rsindex c025b7ce2..3e6206a92 100644--- a/src-tauri/src/core/agent/commands.rs+++ b/src-tauri/src/core/agent/commands.rs@@ -74,6 +74,7 @@ fn build_orchestration_args<R: Runtime>(max_parallel_subagents: crate::core::agent::subagent::DEFAULT_MAX_PARALLEL_SUBAGENTS,auto_approve: false,run_mode: crate::core::agent::plan::RunMode::Normal,+ session_id: None,}}diff --git a/src-tauri/src/core/agent/context.rs b/src-tauri/src/core/agent/context.rsindex 5085e7f20..eb3f5ca90 100644--- a/src-tauri/src/core/agent/context.rs+++ b/src-tauri/src/core/agent/context.rs@@ -168,17 +168,18 @@ work: the moment you finish a task call `todo` with `done` for it (or `drop` ifit), before moving on to the next one. Do not leave finished work sitting as pending, and do not \batch the close-out to the end of the turn.";+fn display_path(path: &Path) -> String {+ path.to_string_lossy().replace('\\', "/")+}+/// Build a compact runtime environment block injected into the system prompt at/// session start so the agent is grounded from turn one. Mirrors the/// `<workstation>` / cwd / date context blocks that harnesses like this one/// already inject. Fields: working directory, OS/platform/arch, date, shell, and/// git state (branch name when the project is inside a git repo). Kept short —/// a few lines, not a wall of text.-fn runtime_environment_block(project_root: &Path) -> String {- let cwd = std::env::current_dir()- .ok()- .map(|p| p.to_string_lossy().into_owned())- .unwrap_or_else(|| "unknown".to_string());+fn runtime_environment_block(project_root: &Path, scratch: Option<&Path>) -> String {+ let cwd = display_path(project_root);let os = format!("{} {}",@@ -199,13 +200,26 @@ fn runtime_environment_block(project_root: &Path) -> String {None => "Git: not a git repository (or no commits yet)".to_string(),};+ // Where to do temporary work. Named by the one spelling that resolves from+ // both `bash` and the filesystem tools on this platform: `/tmp` where the+ // sandbox binds the scratch over it, the real path where nothing is mounted+ // there. Same directory either way, and the shell's `TMPDIR`/`TMP`/`TEMP`+ // point at it too.+ let scratch_line = match scratch {+ Some(scratch) => format!(+ "\nScratch: `{}` is a writable scratch space for temporary work; it persists for this session.",+ tauri_plugin_agent_tools::tools::sandbox::scratch_display_path(Some(scratch), scratch)+ ),+ None => String::new(),+ };+format!("# Runtime Environment\n\n\Work directory: `{cwd}`\n\OS: `{os}`\n\Date: `{date}`\n\Shell: `{shell}`\n\-{git_line}"+{git_line}{scratch_line}")}@@ -239,6 +253,7 @@ pub(crate) fn load_memory_catalog(project_root: &Path) -> Option<String> {pub(crate) fn build_system_prompt(base: Option<&str>,project_root: &Path,+ scratch: Option<&Path>,subagents_enabled: bool,) -> Option<String> {let mut blocks: Vec<String> = Vec::new();@@ -251,7 +266,7 @@ pub(crate) fn build_system_prompt("# Working Directory\n\nCurrent project directory: `{}`\n\nAll relative paths in tool calls resolve against this directory unless stated otherwise.",project_root.display()));- blocks.push(runtime_environment_block(project_root));+ blocks.push(runtime_environment_block(project_root, scratch));if subagents_enabled {blocks.push(SUBAGENT_GUIDE.to_string());}@@ -368,7 +383,7 @@ mod tests {fn build_system_prompt_orders_base_guide_then_skills() {let root = scratch_project("merge");write_skill(&root, "s.md", "Do the thing.");- let out = build_system_prompt(Some("You are Jan."), &root, false).expect("prompt");+ let out = build_system_prompt(Some("You are Jan."), &root, None, false).expect("prompt");assert!(out.starts_with("You are Jan."));assert!(out.contains("Do the thing."));// Guide sits between the base prompt and the project skills.@@ -381,7 +396,7 @@ mod tests {#[test]fn build_system_prompt_advertises_native_web_tools() {let root = scratch_project("web");- let out = build_system_prompt(None, &root, false).expect("prompt");+ let out = build_system_prompt(None, &root, None, false).expect("prompt");assert!(out.contains("# Web Access"));assert!(out.contains("web_search"));assert!(out.contains("web_fetch"));@@ -399,13 +414,13 @@ mod tests {fn build_system_prompt_always_includes_guide() {let root = scratch_project("guide");// No base and no project skills: the built-in guide is still injected.- let out = build_system_prompt(None, &root, false).expect("guide always present");+ let out = build_system_prompt(None, &root, None, false).expect("guide always present");assert!(out.contains("Skills and Project Memory"));assert!(out.contains("skill_write"));assert!(out.contains("memory_write"));// Base is preserved and precedes the guide.- let with_base = build_system_prompt(Some("base"), &root, false).expect("prompt");+ let with_base = build_system_prompt(Some("base"), &root, None, false).expect("prompt");assert!(with_base.starts_with("base"));assert!(with_base.contains("Skills and Project Memory"));let _ = std::fs::remove_dir_all(&root);@@ -414,7 +429,7 @@ mod tests {#[test]fn default_identity_and_guidelines_present_without_base() {let root = scratch_project("identity");- let out = build_system_prompt(None, &root, false).expect("prompt");+ let out = build_system_prompt(None, &root, None, false).expect("prompt");assert!(out.starts_with("You're currently running on Jan agent harness"));assert!(out.contains("# Guidelines"));assert!(out.contains("Be concise"));@@ -442,7 +457,7 @@ mod tests {// Nearest (nested) file wins by appearing last.assert!(block.find("ROOT_RULES").unwrap() < block.find("NESTED_RULES").unwrap());- let prompt = build_system_prompt(None, &nested, false).expect("prompt");+ let prompt = build_system_prompt(None, &nested, None, false).expect("prompt");// Context files precede the skills catalog position and follow the guide.assert!(prompt.contains("NESTED_RULES"));let _ = std::fs::remove_dir_all(&root);@@ -459,9 +474,9 @@ mod tests {#[test]fn build_system_prompt_advertises_subagents_only_when_enabled() {let root = scratch_project("subagents");- let without = build_system_prompt(None, &root, false).expect("prompt");+ let without = build_system_prompt(None, &root, None, false).expect("prompt");assert!(!without.contains("dispatch_subagent"));- let with = build_system_prompt(None, &root, true).expect("prompt");+ let with = build_system_prompt(None, &root, None, true).expect("prompt");assert!(with.contains("dispatch_subagent"));let _ = std::fs::remove_dir_all(&root);}@@ -472,7 +487,7 @@ mod tests {fn runtime_environment_block_is_compact() {let root = scratch_project("env");std::fs::create_dir_all(&root).unwrap();- let block = runtime_environment_block(&root);+ let block = runtime_environment_block(&root, None);// Must be a handful of lines, not a wall of text.let lines: Vec<_> = block.lines().filter(|l| !l.is_empty()).collect();assert!(lines.len() <= 15, "env block is too large: {} lines", lines.len());@@ -493,7 +508,7 @@ mod tests {fn runtime_environment_block_injected_into_system_prompt() {let root = scratch_project("inject");std::fs::create_dir_all(&root).unwrap();- let out = build_system_prompt(None, &root, false).expect("prompt");+ let out = build_system_prompt(None, &root, None, false).expect("prompt");assert!(out.contains("# Runtime Environment"));assert!(out.contains("Work directory:"));// The block sits right after the Working Directory section.@@ -507,7 +522,7 @@ mod tests {fn runtime_environment_block_answers_os_date_cwd() {let root = scratch_project("answer");std::fs::create_dir_all(&root).unwrap();- let block = runtime_environment_block(&root);+ let block = runtime_environment_block(&root, None);// The date field must be a real-looking ISO date.assert!(block.contains("Date: `20"), "date should be a 20xx year");// The OS field must identify the host platform.@@ -516,4 +531,75 @@ mod tests {assert!(!block.contains("Work directory: ``"));let _ = std::fs::remove_dir_all(&root);}++ /// The scratch must be advertised under the name that resolves from both+ /// `bash` and the filesystem tools: `/tmp` where the sandbox binds it there,+ /// the real path where nothing is mounted over `/tmp`. Naming the host path+ /// on Linux (or `/tmp` anywhere else) would send the model to a directory+ /// one of the two surfaces cannot reach.+ #[test]+ fn runtime_environment_block_advertises_the_scratch_the_tools_share() {+ let root = scratch_project("scratch");+ std::fs::create_dir_all(&root).unwrap();+ let scratch = root.join("agent-scratch");+ let block = runtime_environment_block(&root, Some(&scratch));+ let expected = if cfg!(target_os = "linux") {+ "/tmp".to_string()+ } else {+ scratch.to_string_lossy().into_owned()+ };+ assert!(+ block.contains(&format!("Scratch: `{expected}`")),+ "want {expected}: {block}"+ );+ assert!(block.contains("persists for this session"), "{block}");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A run with no scratch (the server proxy path) must not promise one.+ #[test]+ fn runtime_environment_block_omits_the_scratch_when_there_is_none() {+ let root = scratch_project("noscratch");+ std::fs::create_dir_all(&root).unwrap();+ let block = runtime_environment_block(&root, None);+ assert!(!block.contains("Scratch:"), "{block}");+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn work_directory_is_the_project_root_not_the_process_cwd() {+ let root = scratch_project("cwd_is_root");+ std::fs::create_dir_all(&root).unwrap();+ let process_cwd = std::env::current_dir().expect("cwd");+ assert_ne!(+ root, process_cwd,+ "the test is meaningless unless the two differ"+ );++ let block = runtime_environment_block(&root, None);+ let expected = root.to_string_lossy().replace('\\', "/");+ assert!(+ block.contains(&format!("Work directory: `{expected}`")),+ "block should report the project root, got: {block}"+ );+ let cwd_shown = process_cwd.to_string_lossy().replace('\\', "/");+ assert!(+ !block.contains(&format!("Work directory: `{cwd_shown}`")),+ "block must not report the process cwd"+ );+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn work_directory_is_written_with_forward_slashes() {+ let root = scratch_project("cwd_slashes");+ std::fs::create_dir_all(&root).unwrap();+ let block = runtime_environment_block(&root, None);+ let line = block+ .lines()+ .find(|l| l.starts_with("Work directory:"))+ .expect("work directory line");+ assert!(!line.contains('\\'), "path should be slash-normalised: {line}");+ let _ = std::fs::remove_dir_all(&root);+ }}diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex f435118d5..db538b0ae 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -92,6 +92,12 @@ pub(crate) struct OrchestrationArgs {/// nor executable: the dispatcher hard-denies them with `plan_mode_read_only`,/// stronger than auto-approval's prompt suppression (it cannot override this).pub run_mode: crate::core::agent::plan::RunMode,+ /// Stable identity for this run's session, used to key the persistent+ /// `bash` `/tmp` scratch directory (`<temp>/jan-agent-<session_id>`) and+ /// wiped at the session boundary specific to each surface. `None` on+ /// code paths with no session (server proxy runs) keeps the default+ /// throwaway per-command tmpfs.+ pub session_id: Option<String>,}#[async_trait]@@ -207,6 +213,10 @@ struct CompositeToolInvoker {/// Whether the sandboxed shell may read `$HOME`. Resolved once per run/// from `[tools].allow_home_read`, falling back to `true` on the CLI.allow_home_read: bool,+ /// Session-scoped scratch directory the shell and the filesystem tools share+ /// (see `workspace::scratch_dir`), so `bash` scratch files persist across+ /// calls for the whole run. Created at run start and wiped at run end.+ scratch_root: std::path::PathBuf,permissions: tauri_plugin_agent_tools::permissions::ToolPermissions,events: mpsc::UnboundedSender<StreamEvent>,permission_requests: PermissionRegistry,@@ -285,6 +295,7 @@ impl CompositeToolInvoker {).with_network(self.allow_network).with_home_readonly(self.allow_home_read)+ .with_scratch_root(&self.scratch_root)}/// Prompt the user to approve an MCP tool call, mirroring the built-in gate.@@ -727,6 +738,7 @@ impl ToolInvoker for CompositeToolInvoker {tool,&args,&self.project_root,+ Some(self.scratch_root.as_path()),&self.permissions,&snapshot,);@@ -749,10 +761,12 @@ impl ToolInvoker for CompositeToolInvoker {let enabled = self.enabled_skills.clone();let allow_network = self.allow_network;let allow_home_read = self.allow_home_read;+ let scratch = self.scratch_root.clone();read_futures.push(async move {let ctx = ToolContext::new(&root, &store, &enabled).with_network(allow_network)- .with_home_readonly(allow_home_read);+ .with_home_readonly(allow_home_read)+ .with_scratch_root(&scratch);let (text, diff) = execute_builtin_with_diff(tool, &args, &ctx).await;ToolOutcome {id,@@ -898,6 +912,7 @@ pub(crate) async fn run_server_side_openai_orchestration(max_parallel_subagents: crate::core::agent::subagent::DEFAULT_MAX_PARALLEL_SUBAGENTS,auto_approve: false,run_mode: crate::core::agent::plan::RunMode::Normal,+ session_id: None,};let body = match json_body.get("max_turns") {Some(_) => std::borrow::Cow::Borrowed(json_body),@@ -1004,17 +1019,39 @@ fn build_run_system_prompt(assistant_instructions: Option<&str>,override_prompt: Option<&str>,project_root: Option<&std::path::Path>,+ session_id: Option<&str>,subagents_enabled: bool,) -> Option<String> {let base = override_prompt.or(assistant_instructions);match project_root {Some(root) => {- crate::core::agent::context::build_system_prompt(base, root, subagents_enabled)+ let scratch = scratch_root_for(session_id, root);+ crate::core::agent::context::build_system_prompt(+ base,+ root,+ Some(&scratch),+ subagents_enabled,+ )}None => base.map(str::to_string),}}+/// Where this run's scratch lives. Session-keyed so it persists across turns in+/// the interactive TUI (and across calls in a one-shot run), then is wiped at the+/// session boundary; a run with no session (the server proxy) gets a per-project+/// directory instead. Pure path math -- [`ensure_scratch_dir`] is what creates+/// it -- so the system prompt can name the scratch before the tools are built.+fn scratch_root_for(+ session_id: Option<&str>,+ project_root: &std::path::Path,+) -> std::path::PathBuf {+ match session_id {+ Some(session) => tauri_plugin_agent_tools::workspace::scratch_dir(session),+ None => project_root.join("agent-scratch"),+ }+}+/// Which todo addendum this turn needs, if any: the init guidance on a `/goal`/// turn with no plan staged, otherwise the upkeep guidance whenever a list/// already exists. `None` when there is nothing to say (no list, and not a@@ -1077,6 +1114,7 @@ async fn orchestrate_inner(max_parallel_subagents,auto_approve,run_mode,+ session_id,} = args;// Per-turn override: the TUI toggles plan mode live via the request body@@ -1119,6 +1157,7 @@ async fn orchestrate_inner(assistant_instructions.as_deref(),system_prompt_override.as_deref(),project_root.as_deref(),+ session_id.as_deref(),*subagents_enabled,);// Child (subagent) runs are excluded via `system_prompt_override`, the@@ -1331,12 +1370,22 @@ async fn orchestrate_inner(bg: bg.clone(),});let settings = resolve_run_settings(root);+ // The same path `build_run_system_prompt` advertised (both go through+ // `scratch_root_for`), created here before the first tool call reaches+ // for it. Created for a session-less run too: the policy binds this path+ // either way, and bubblewrap refuses to bind a directory that is not+ // there -- which would take `bash` down with it.+ let scratch_root = scratch_root_for(session_id.as_deref(), root);+ tokio::fs::create_dir_all(&scratch_root)+ .await+ .map_err(|e| format!("ERROR: {e}"))?;let tools = CompositeToolInvoker {mcp: mcp_tools,store_root: tauri_plugin_agent_tools::workspace::project_store(root),enabled_skills: settings.enabled_skills,allow_network: settings.allow_network,allow_home_read: settings.allow_home_read,+ scratch_root: scratch_root.clone(),project_root: root.clone(),permissions: permissions.clone(),events: events.clone(),@@ -1982,6 +2031,27 @@ mod tests {);}+ /// The prompt names the scratch and the tools bind it, so both must derive+ /// it the same way or the model is told about a directory nothing set up.+ #[test]+ fn scratch_root_is_session_keyed_and_falls_back_to_the_project() {+ let root = unique_project_root();+ assert_eq!(+ scratch_root_for(Some("sess-1"), &root),+ tauri_plugin_agent_tools::workspace::scratch_dir("sess-1")+ );+ assert_eq!(+ scratch_root_for(None, &root),+ root.join("agent-scratch"),+ "a session-less run still needs a scratch to bind"+ );+ // Two sessions never share one scratch.+ assert_ne!(+ scratch_root_for(Some("sess-1"), &root),+ scratch_root_for(Some("sess-2"), &root)+ );+ }+#[test]fn subagent_prompt_reuses_main_prompt_builder() {let root = unique_project_root();@@ -1989,6 +2059,7 @@ mod tests {Some("main assistant"),Some("You are a robotics researcher."),Some(&root),+ Some("test-session"),false,).expect("prompt");@@ -2789,6 +2860,7 @@ mod tests {enabled_skills: Vec::new(),allow_network: DEFAULT_ALLOW_NETWORK,allow_home_read: DEFAULT_ALLOW_HOME_READ,+ scratch_root: tauri_plugin_agent_tools::workspace::scratch_dir("test-session"),project_root: root,// Read-only default => write PROMPTS.permissions: ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]),diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rsindex c458b41a5..437ea4fa9 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -1512,6 +1512,7 @@ mod tests {max_parallel_subagents: 1,auto_approve: false,run_mode: crate::core::agent::plan::RunMode::Normal,+ session_id: None,}}diff --git a/src-tauri/src/core/cli/journal.rs b/src-tauri/src/core/cli/journal.rsindex 8e5931621..1d397a566 100644--- a/src-tauri/src/core/cli/journal.rs+++ b/src-tauri/src/core/cli/journal.rs@@ -200,19 +200,14 @@ mod tests {]}- fn tmp_dir() -> PathBuf {- let dir = std::env::temp_dir().join(format!(- "jan_journal_{}_{}",- std::process::id(),- uuid::Uuid::new_v4()- ));- std::fs::create_dir_all(&dir).unwrap();- dir+ fn tmp_dir() -> tempfile::TempDir {+ tempfile::tempdir().unwrap()}#[test]fn round_trips_every_entry_kind() {- let path = tmp_dir().join(JOURNAL_FILE);+ let dir = tmp_dir();+ let path = dir.path().join(JOURNAL_FILE);let entries = sample();write_journal(&path, &entries).unwrap();assert_eq!(read_journal(&path), entries);@@ -220,7 +215,8 @@ mod tests {#[test]fn rewrite_replaces_a_truncated_log() {- let path = tmp_dir().join(JOURNAL_FILE);+ let dir = tmp_dir();+ let path = dir.path().join(JOURNAL_FILE);write_journal(&path, &sample()).unwrap();let kept = sample()[..2].to_vec();write_journal(&path, &kept).unwrap();@@ -233,7 +229,8 @@ mod tests {#[test]fn read_skips_unparsable_lines() {- let path = tmp_dir().join(JOURNAL_FILE);+ let dir = tmp_dir();+ let path = dir.path().join(JOURNAL_FILE);let good = serde_json::to_string(&user("hi")).unwrap();std::fs::write(&path,@@ -245,7 +242,7 @@ mod tests {#[test]fn read_of_a_missing_journal_is_empty() {- assert!(read_journal(&tmp_dir().join(JOURNAL_FILE)).is_empty());+ assert!(read_journal(&tmp_dir().path().join(JOURNAL_FILE)).is_empty());}#[test]@@ -266,7 +263,8 @@ mod tests {#[test]fn writer_lands_dumps_in_order() {- let path = tmp_dir().join(JOURNAL_FILE);+ let dir = tmp_dir();+ let path = dir.path().join(JOURNAL_FILE);let mut writer = Writer::new();writer.dump(path.clone(), sample());let last = sample()[..1].to_vec();@@ -277,9 +275,10 @@ mod tests {#[test]fn journal_sits_in_the_thread_dir() {- let base = tmp_dir();+ let dir = tmp_dir();+ let base = dir.path();assert_eq!(- journal_path(&base, "t1"),+ journal_path(base, "t1"),base.join("threads").join("t1").join(JOURNAL_FILE));}diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 7b156e8c1..06f704eff 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -458,6 +458,7 @@ use crate::core::agent::r#loop::{run_orchestration_streamed, OrchestrationArgs, PermissionRegistry,};use tauri_plugin_agent_tools::tools::gate::PermissionDecision;+use tauri_plugin_agent_tools::workspace;use crate::core::cli::providers::{load_provider_configs, ProviderOverrides};use crate::core::cli::run_report::{OutputFormat, RunReport};use crate::core::mcp::models::McpSettings;@@ -661,6 +662,11 @@ fn build_cli_orchestration_args(} else {crate::core::agent::plan::RunMode::Normal},+ // Key the persistent bash `/tmp` scratch to this session. Generated per+ // run/session: a one-shot CLI wipes it after its single run; the TUI+ // reuses `args` across turns and wipes it when the interactive session+ // ends.+ session_id: Some(uuid::Uuid::new_v4().to_string()),}}@@ -1084,6 +1090,11 @@ async fn run_agent_loop(final_text.as_deref(),));}+ // The one-shot CLI runs exactly one turn, so its session ends here: wipe+ // the persistent bash `/tmp` scratch this run used.+ if let Some(session) = args.session_id.as_deref() {+ let _ = workspace::remove_scratch_dir(session).await;+ }result.map(|_| ())}diff --git a/src-tauri/src/core/cli/path_refs.rs b/src-tauri/src/core/cli/path_refs.rsindex b2bd6fb36..33e262c34 100644--- a/src-tauri/src/core/cli/path_refs.rs+++ b/src-tauri/src/core/cli/path_refs.rs@@ -358,11 +358,11 @@ mod tests {#[test]fn test_resolve_references_inject() {- let dir = std::env::temp_dir().join("path_ref_test_inject");- let _ = std::fs::create_dir_all(&dir);- std::fs::write(dir.join("hello.txt"), b"hello world").unwrap();+ let dir = tempfile::tempdir().unwrap();+ let root = dir.path();+ std::fs::write(root.join("hello.txt"), b"hello world").unwrap();- let (clean, block) = resolve_references("read @hello.txt", &dir);+ let (clean, block) = resolve_references("read @hello.txt", root);assert_eq!(clean, "read");assert!(block.contains("hello world"));assert!(block.contains("hello.txt"));@@ -370,8 +370,8 @@ mod tests {#[test]fn test_resolve_references_no_refs() {- let dir = std::env::temp_dir().join("path_ref_test_none");- let (clean, block) = resolve_references("plain text", &dir);+ let dir = tempfile::tempdir().unwrap();+ let (clean, block) = resolve_references("plain text", dir.path());assert_eq!(clean, "plain text");assert!(block.is_empty());}@@ -385,8 +385,8 @@ mod tests {let text = "please use bash to ssh [email protected]";assert!(parse_references(text).is_empty());- let dir = std::env::temp_dir().join("path_ref_test_ssh");- let (clean, block) = resolve_references(text, &dir);+ let dir = tempfile::tempdir().unwrap();+ let (clean, block) = resolve_references(text, dir.path());assert_eq!(clean, text);assert!(block.is_empty());}@@ -413,10 +413,10 @@ mod tests {let refs = parse_references("use @README.md to check the build steps");assert_eq!(refs, vec!["README.md"]);- let dir = std::env::temp_dir().join("path_ref_test_rest");- let _ = std::fs::create_dir_all(&dir);- std::fs::write(dir.join("README.md"), b"build steps here").unwrap();- let (clean, block) = resolve_references("use @README.md to check the build steps", &dir);+ let dir = tempfile::tempdir().unwrap();+ let root = dir.path();+ std::fs::write(root.join("README.md"), b"build steps here").unwrap();+ let (clean, block) = resolve_references("use @README.md to check the build steps", root);assert_eq!(clean, "use to check the build steps");assert!(block.contains("build steps here"));}diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 87c73eb20..1eef73e98 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -46,6 +46,7 @@ use crate::core::agent::events::{describe_tool_call, StreamEvent, Usage};use crate::core::agent::git;use crate::core::agent::r#loop::{run_orchestration_streamed, OrchestrationArgs, PermissionRegistry};use tauri_plugin_agent_tools::tools::gate::PermissionDecision;+use tauri_plugin_agent_tools::workspace;/// Mouse tracking, hand-rolled instead of crossterm's `EnableMouseCapture`,/// which also turns on any-motion reporting (1003) -- a stream of events for@@ -447,14 +448,20 @@ impl ToolGroup {}}- /// Live label for an open group: a lone call names itself (so a running- /// command reads as the command), several fall back to the counted- /// breakdown, where no single call describes the group.+ /// Live label for an open group: the tool still in flight, so a running+ /// batch reads as that tool rather than a counted breakdown like "Running+ /// 2 commands, 5 searches" (which would wrongly imply all of them are+ /// executing at once). The past-tense summary only appears once the group+ /// resolves. Results can land out of dispatch order, so the in-flight call+ /// is the latest one still awaiting its result.fn activity(&self) -> String {- match self.calls.as_slice() {- [only] => only.activity.clone(),- _ => group_activity(&self.nouns),- }+ self.calls+ .iter()+ .rev()+ .find(|c| c.content.is_none())+ .or_else(|| self.calls.last())+ .map(|c| c.activity.clone())+ .unwrap_or_default()}/// The group's row: present-tense `▸` only while it is open with a call in@@ -4073,13 +4080,6 @@ fn group_summary(nouns: &[(&str, bool)]) -> String {group_clauses(nouns, "Read", "ran")}-/// Present-tense counterpart to `group_summary` for the live, in-progress group-/// row, e.g. "Reading 3 files, 1 directory; running 2 commands". Keeps the row-/// honest about the mix of calls instead of showing the latest call + a count.-fn group_activity(nouns: &[(&str, bool)]) -> String {- group_clauses(nouns, "Reading", "running")-}-/// Live row for the still-open tool group: a braille throbber in place of the/// static `▸` tag, plus elapsed time, so the user can see it's actively/// working and how long it's taken. Rebuilt fresh every draw (not stored in@@ -4509,6 +4509,7 @@ pub async fn run(args.ask_requests = Some(ask_requests.clone());let todo_registry = crate::core::agent::todo::new_registry();args.todo_registry = Some(todo_registry.clone());+ let session_scratch = args.session_id.clone();let args = Arc::new(args);// Deserializing syntect's syntax/theme dumps takes tens of milliseconds.@@ -4622,6 +4623,11 @@ pub async fn run(if app.update_installing {eprintln!("the update was still installing when jan exited; run `jan update` to finish it");}+ // The interactive session is over: wipe the persistent bash `/tmp` scratch+ // that its turns shared.+ if let Some(session) = session_scratch.as_deref() {+ let _ = workspace::remove_scratch_dir(session).await;+ }res}@@ -9268,7 +9274,7 @@ mod tests {use super::{age_closed_todos, apply_resume, assistant_is_awaiting_user_answer, brand, build_user_message,clipboard_path,- diff_lines, Row, group_activity, group_detail_lines, group_summary, handle_ask_key,+ diff_lines, Row, group_detail_lines, group_summary, handle_ask_key,handle_ask_mouse, handle_key, handle_mouse, image_mime, input_content_lines,route_paste_event,compact_tokens, finish_compaction, finish_login, finish_update_install,@@ -9335,28 +9341,48 @@ mod tests {);}- fn test_app() -> App {+ /// Wraps an `App` bound to a temp dir that is removed when the wrapper is+ /// dropped, so tests that persist threads or journals never leak under+ /// `/tmp` and never dirty the working tree.+ struct TestApp {+ app: App,+ _dir: tempfile::TempDir,+ }++ impl std::ops::Deref for TestApp {+ type Target = App;++ fn deref(&self) -> &App {+ &self.app+ }+ }++ impl std::ops::DerefMut for TestApp {+ fn deref_mut(&mut self) -> &mut App {+ &mut self.app+ }+ }++ fn test_app() -> TestApp {// Persist into a unique temp dir so tests that save threads never- // dirty the working tree (src-tauri/threads/).- let agent_dir = std::env::temp_dir().join(format!(- "jan_tui_{}_{}",- std::process::id(),- uuid::Uuid::new_v4()- ));+ // dirty the working tree (src-tauri/threads/) and the dir is removed on+ // drop.+ let dir = tempfile::tempdir().unwrap();let limits = SessionLimits {context_window: 128_000,reserve_tokens: 16_384,max_tokens: None,max_session_tokens: 128_000,};- App::new(+ let app = App::new("m".into(),limits,false,- agent_dir,+ dir.path().to_path_buf(),std::path::PathBuf::from("/tmp/repo"),None,- )+ );+ TestApp { app, _dir: dir }}/// Draw `app` into an off-screen terminal and return its rows as strings.@@ -10413,22 +10439,6 @@ mod tests {);}- #[test]- fn group_activity_is_present_tense_running_breakdown() {- assert_eq!(- group_activity(&[("file", true), ("file", true), ("command", false)]),- "Reading 2 files; running 1 command"- );- assert_eq!(- group_activity(&[("search", false), ("search", false)]),- "Running 2 searches"- );- assert_eq!(- group_activity(&[("file", true), ("directory", true)]),- "Reading 1 file, 1 directory"- );- }-#[test]fn tool_activity_is_concise_present_tense() {assert_eq!(@@ -12819,10 +12829,11 @@ mod tests {assert!(!text.contains("running 1 command"), "{text}");}- /// Two or more calls in flight go back to the counted breakdown: no single- /// command describes the group.+ /// Two or more calls in flight still name the tool actively running (the+ /// latest outstanding one), not a counted breakdown -- a summary like+ /// "Running 2 commands" would wrongly imply both are executing at once.#[test]- fn running_multi_call_row_falls_back_to_breakdown() {+ fn running_multi_call_row_names_the_in_flight_tool() {let mut app = test_app();for (id, cmd) in [("c1", "cargo test"), ("c2", "cargo clippy")] {app.apply(StreamEvent::ToolCall {@@ -12833,7 +12844,8 @@ mod tests {}let group = app.tool_group.as_ref().expect("group open");let text = line_text(&running_group_row(group, 0, 200));- assert!(text.contains("Running 2 commands"), "{text}");+ assert!(text.contains("Executing: cargo clippy"), "{text}");+ assert!(!text.contains("Running 2 commands"), "{text}");}#[test]@@ -14913,7 +14925,7 @@ mod tests {let mut restored = test_app();restore_goal(&mut restored, Some(&meta));- let g = restored.goal.expect("goal restored");+ let g = restored.goal.clone().expect("goal restored");assert_eq!(g.condition, "tests pass");assert_eq!(g.turns, 2);assert_eq!(g.last_reason, "one failing");@@ -16035,7 +16047,7 @@ mod tests {)}- fn app_with_history(n: usize) -> App {+ fn app_with_history(n: usize) -> TestApp {let mut app = test_app();for i in 0..n {app.history.push(serde_json::json!({