Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(agent): one real sandbox scratch path, and per-project package caches in the OS cache dir (#9606)

Akarshan Biswasde0657f4839a
diff --git a/docs/src/pages/docs/agent/permissions.mdx b/docs/src/pages/docs/agent/permissions.mdx
index 3c2a46c78..0d447c5a5 100644
--- a/docs/src/pages/docs/agent/permissions.mdx
+++ b/docs/src/pages/docs/agent/permissions.mdx
@@ -108,6 +108,21 @@ directory, and reaches the network only if allowed. Reads are looser: the CLI ke
so `git` and `ssh` credential helpers work (`[tools].allow_home_read`, set it to `false` to close
that), while the desktop masks it entirely.
+The scratch directory is per session, in your OS cache dir: `<cache>/jan/<project>/scratch/<session>`
+(`<cache>` is `~/.cache` on Linux, `~/Library/Caches` on macOS, `%LOCALAPPDATA%` on Windows; desktop
+chats use `<cache>/jan/chat`). The shell, the file tools and an approved escalated command all see it
+at that same path. It is removed when the session ends; one a crash left behind is removed at a later
+start once it has gone a week without a turn and no running Jan session holds it.
+
+Confined commands in a project also get a package cache, `<cache>/jan/<project>/pkg`, shared by that
+project's sessions and never by another project. `CARGO_HOME`, `npm_config_cache`, `YARN_CACHE_FOLDER`,
+`PIP_CACHE_DIR`, `UV_CACHE_DIR`, `GOCACHE`/`GOMODCACHE`/`GOPATH`, `GRADLE_USER_HOME` and the other
+package-manager caches point inside it, so builds can download dependencies without touching your own
+`~/.cargo`, `~/.npm` and so on. Your `~/.cargo/config.toml` is available read-only there;
+`credentials.toml` and `~/.cargo/bin` are not copied in. Unconfined and escalated commands keep your
+normal environment (an escalated command of a read-only subagent still runs confined, with the
+package cache). Jan does not clean this folder; delete it to reclaim the space.
+
While the sandbox is on, Jan's own home, `~/.jan`, is hidden from every tool and from the shell,
even when you run `jan` from your home directory. It holds `config.toml` (provider keys and hooks)
and each project's `agent.toml`, memory and threads, so no approval can open it: file tools refuse
diff --git a/e2e/isolation.ts b/e2e/isolation.ts
index e8a52b765..b40d3b6e1 100644
--- a/e2e/isolation.ts
+++ b/e2e/isolation.ts
@@ -22,14 +22,17 @@ import { join } from 'node:path'
* inherited, a run DELETES the developer's real ~/.config/Jan/settings.json.
* Confirmed against a decoy: the file did not survive one run.
*
- * The scratch directory is pinned on every platform, not just Linux.
- * `std::env::temp_dir()` reads TMPDIR on Unix and TMP/TEMP on Windows, and
- * tauri-plugin-agent-tools puts agent scratch at `temp_dir()/jan-agent-<session>`
- * -- then sweep_stale_scratch_dirs() (workspace.rs) DELETES every `jan-agent-*`
- * older than 24h it finds there. The current smoke suite never reaches that
- * sweep (it is gated on an existing thread, and a fresh profile has none), so
- * this is pre-emptive rather than a live bug. It stops being pre-emptive the
- * moment a spec creates a thread.
+ * The temp directory is pinned on every platform, not just Linux.
+ * `std::env::temp_dir()` reads TMPDIR on Unix and TMP/TEMP on Windows. Agent
+ * scratch now lives under the OS cache dir (`<cache>/jan/<project>/scratch/`,
+ * which XDG_CACHE_HOME and the Windows profile redirect below move too), but
+ * sweep_stale_scratch_dirs() (workspace.rs) still DELETES the legacy
+ * `jan-agent-*` and `jan-trash-*` entries older than 7 days it finds in
+ * `temp_dir()`, and with no cache dir at all the cache root itself falls back
+ * to `temp_dir()/jan-<uid>`. The current smoke suite never reaches that sweep
+ * (it is gated on an existing thread, and a fresh profile has none), so this
+ * is pre-emptive rather than a live bug. It stops being pre-emptive the moment
+ * a spec creates a thread.
*
* On Windows the lever is `JAN_DATA_ROOT`, which is Jan's own rather than
* something `dirs` provides: `dirs` asks the known-folder API for
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 38cf77bcf..b16e2790a 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -7972,6 +7972,7 @@ dependencies = [
"base64 0.22.1",
"block2",
"cairo-rs",
+ "dirs 6.0.0",
"fs4",
"gio",
"glib 0.18.5",
diff --git a/src-tauri/jan-cli/Cargo.lock b/src-tauri/jan-cli/Cargo.lock
index 23a8f4f8d..e5d9e8f18 100644
--- a/src-tauri/jan-cli/Cargo.lock
+++ b/src-tauri/jan-cli/Cargo.lock
@@ -5361,6 +5361,7 @@ name = "tauri-plugin-agent-tools"
version = "0.8.3"
dependencies = [
"base64 0.22.1",
+ "dirs",
"fs4",
"glob",
"ignore",
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml
index 515bbf56b..f1031884b 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml
@@ -45,6 +45,9 @@ tauri = [
[dependencies]
base64 = "0.22"
+# The OS cache dir (XDG / ~/Library/Caches / %LOCALAPPDATA%) the session
+# scratch lives under; same version the app crate already resolves.
+dirs = "6.0.0"
# Advisory file locks (flock / LockFileEx) that serialize memory store changes
# across processes: the desktop app and the jan CLI share one store.
fs4 = "1"
@@ -74,7 +77,7 @@ tauri-plugin-websearch = { path = "../tauri-plugin-websearch", default-features
tauri-plugin = { version = "2.3.1", features = ["build"], optional = true }
[target.'cfg(unix)'.dependencies]
-nix = { version = "=0.30.1", features = ["signal", "process", "fs"] }
+nix = { version = "=0.30.1", features = ["signal", "process", "fs", "user"] }
# Webview `screenshot` backend (see `webview_shot.rs`). All optional and enabled
# by the `tauri` feature, so the headless CLI never pulls a GUI stack in.
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
index 03fbb3977..a9a1e0665 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
@@ -147,18 +147,19 @@ pub async fn thread_workspace_delete(
/// were removed. Called once at startup: sandboxes are ephemeral, but a crash or
/// a thread deleted while the app was closed would otherwise leave one behind.
///
-/// Abandoned host-temp scratch directories are collected in the same pass. They
-/// need their own sweep because they are keyed to ids the caller holds (a run,
-/// a thread, a CLI session), so unlike a thread sandbox there is no `keep` list
-/// to compare against -- see [`workspace::sweep_stale_scratch_dirs`]. Their
-/// count is not added to the return value, which names thread sandboxes.
+/// Abandoned scratch directories in the cache are collected in the same pass,
+/// with `keep` as the live set so no surviving thread's scratch goes. The
+/// sweep covers every project's folder, so a CLI session's scratch is only
+/// ever collected once it is a week stale -- see
+/// [`workspace::sweep_stale_scratch_dirs`]. Their count is not added to the
+/// return value, which names thread sandboxes.
#[tauri::command]
pub async fn thread_workspace_sweep(
data_folder: String,
keep: Vec<String>,
) -> Result<usize, AgentToolsError> {
let data_folder = workspace::host_data_folder(&data_folder);
- workspace::sweep_stale_scratch_dirs().await;
+ workspace::sweep_stale_scratch_dirs(&keep).await;
workspace::sweep_thread_workspaces(Path::new(&data_folder), &keep)
.await
.map_err(Into::into)
@@ -447,7 +448,7 @@ pub async fn subagent_result_reserve(
.unwrap_or_default()
.to_string_lossy()
.into_owned(),
- path: crate::tools::sandbox::scratch_display_path(Some(&scratch), &p),
+ path: p.to_string_lossy().into_owned(),
})
})
.await
@@ -502,7 +503,7 @@ pub async fn blackboard_write(
AgentToolsError::from("could not claim a blackboard file".to_string())
})?;
if crate::tools::spill::fill_subagent_result(&path, &content) {
- Ok(crate::tools::sandbox::scratch_display_path(Some(&scratch), &path))
+ Ok(path.to_string_lossy().into_owned())
} else {
Err(AgentToolsError::from(
"could not write the blackboard file".to_string(),
@@ -616,6 +617,8 @@ pub async fn start_monitor(
let ctx = monitor::MonitorCtx {
project_root: root,
scratch_root: Some(scratch),
+ // Desktop chat and Cowork have no filesystem project to key one on.
+ pkg_cache: None,
mask_root: Some(PathBuf::from(&data_folder)),
hidden_root: workspace::hidden_root(true),
read_roots,
@@ -1192,9 +1195,9 @@ mod tests {
std::env::temp_dir().join(format!("jan_cmd_test_{}_{}", std::process::id(), n))
}
- /// A folder that is *not* under the host temp dir. On Linux an absolute
- /// `/tmp/...` path is remapped into the session scratch, which would route
- /// an attached-folder test through the wrong branch entirely.
+ /// A folder that is *not* under the host temp dir, where these tests'
+ /// data folders (and so their thread sandboxes) and scratch live, so an
+ /// attached folder is never mistaken for either.
fn repo_outside_tmp(tag: &str) -> PathBuf {
let n = COUNTER.fetch_add(1, Ordering::SeqCst);
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
@@ -1388,8 +1391,7 @@ mod tests {
/// 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.
+ /// reached by its real path on every platform.
#[tokio::test]
async fn escaping_writes_are_refused() {
let data = unique_data_folder();
@@ -1418,21 +1420,16 @@ 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".
+ // A scratch write is not a host escape and succeeds, at the scratch's
+ // real path. 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(T_SCRATCH)
.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 requested = scratch.join(&name).to_string_lossy().into_owned();
+ let expected = requested.clone();
let res = execute_tool(
df.clone(),
T_SCRATCH.into(),
@@ -1704,15 +1701,12 @@ mod tests {
err.message
);
- // The tool-visible scratch path follows the shell: `/tmp` on Linux,
- // the real per-thread directory on macOS and Windows.
+ // Each thread's scratch is its own directory: t2 naming the file at
+ // its own scratch finds nothing of t1's.
let one_scratch = crate::workspace::ensure_scratch_dir(t1).await.unwrap();
std::fs::write(one_scratch.join("secret.txt"), b"classified").unwrap();
let two_scratch = crate::workspace::ensure_scratch_dir(t2).await.unwrap();
- let requested = crate::tools::sandbox::scratch_display_path(
- Some(&two_scratch),
- &two_scratch.join("secret.txt"),
- );
+ let requested = two_scratch.join("secret.txt").to_string_lossy().into_owned();
let out = execute_tool(
df.clone(),
t2.into(),
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.rs
index 536f5a324..72b807490 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
@@ -73,13 +73,14 @@ 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. 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.
+/// so the spawn path does not change per platform. The scratch and the package
+/// cache travel with the workspace because all need an ACE, and only the helper
+/// holds the container SID to grant one with; an absent one is the empty
+/// string, since a positional slot cannot simply be omitted.
pub fn helper_args(
workspace: &Path,
scratch: Option<&Path>,
+ pkg: Option<&Path>,
allow_network: bool,
program: &Path,
args: &[String],
@@ -91,6 +92,8 @@ pub fn helper_args(
scratch
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_default(),
+ pkg.map(|p| p.to_string_lossy().to_string())
+ .unwrap_or_default(),
"--".to_string(),
program.to_string_lossy().to_string(),
];
@@ -157,6 +160,7 @@ fn command_line(program: &Path, args: &[String]) -> String {
struct Request {
workspace: PathBuf,
scratch: Option<PathBuf>,
+ pkg: Option<PathBuf>,
allow_network: bool,
program: PathBuf,
args: Vec<String>,
@@ -176,10 +180,12 @@ 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)),
+ let mut optional_dir = || match it.next()? {
+ s if s.is_empty() => Some(None),
+ s => Some(Some(PathBuf::from(s))),
};
+ let scratch = optional_dir()?;
+ let pkg = optional_dir()?;
if it.next()? != "--" {
return None;
}
@@ -187,6 +193,7 @@ fn parse_request<I: IntoIterator<Item = String>>(argv: I) -> Option<Request> {
Some(Request {
workspace,
scratch,
+ pkg,
allow_network,
program,
args: it.collect(),
@@ -621,9 +628,9 @@ mod win {
req.workspace.display()
));
}
- if let Some(scratch) = &req.scratch {
- if !scratch.is_dir() {
- return Err(format!("scratch does not exist: {}", scratch.display()));
+ for dir in req.scratch.iter().chain(&req.pkg) {
+ if !dir.is_dir() {
+ return Err(format!("directory does not exist: {}", dir.display()));
}
}
reap_children_with_this_process();
@@ -634,6 +641,13 @@ mod win {
if let Some(scratch) = &req.scratch {
grant_path(scratch, sid.0)?;
}
+ // The package cache is where `CARGO_HOME`, npm and the rest write. The
+ // cargo config copy inside it is only marked read-only: no deny ACE is
+ // used (see the module doc), so the container could clear the mark.
+ // See `workspace::write_read_only` for why that is accepted.
+ if let Some(pkg) = &req.pkg {
+ grant_path(pkg, sid.0)?;
+ }
let mut capability_sid = Vec::new();
let mut capabilities = Vec::new();
@@ -801,6 +815,7 @@ mod tests {
let args = helper_args(
&ws(),
None,
+ None,
false,
Path::new("bash.exe"),
&["-c".to_string()],
@@ -815,10 +830,10 @@ mod tests {
#[test]
fn helper_args_carry_the_network_decision() {
- let denied = helper_args(&ws(), None, false, Path::new("bash.exe"), &[]);
+ let denied = helper_args(&ws(), None, 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(), None, true, Path::new("bash.exe"), &[]);
+ let allowed = helper_args(&ws(), None, None, true, Path::new("bash.exe"), &[]);
assert!(allowed.contains(&NET_ON.to_string()));
}
@@ -827,6 +842,7 @@ mod tests {
let args = helper_args(
&ws(),
Some(Path::new(r"C:\Temp\jan-agent-s1")),
+ Some(Path::new(r"C:\Cache\jan\p\pkg")),
true,
Path::new(r"C:\Program Files\Git\bin\bash.exe"),
&["-c".to_string(), "echo hi".to_string()],
@@ -837,6 +853,7 @@ mod tests {
req.scratch.as_deref(),
Some(Path::new(r"C:\Temp\jan-agent-s1"))
);
+ assert_eq!(req.pkg.as_deref(), Some(Path::new(r"C:\Cache\jan\p\pkg")));
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()]);
@@ -846,10 +863,11 @@ mod tests {
/// 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 args = helper_args(&ws(), None, None, false, Path::new("bash.exe"), &[]);
let req = parse_request(args).expect("parsed");
assert_eq!(req.workspace, ws());
assert_eq!(req.scratch, None);
+ assert_eq!(req.pkg, None);
}
#[test]
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.rs
index 5ba941a5c..255885cbf 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
@@ -150,7 +150,7 @@ pub enum Decision {
pub struct GateContext<'a> {
/// The project root: paths inside it are the agent's own workspace.
pub project_root: &'a Path,
- /// The session scratch, bound over `/tmp` in the sandbox where it is mounted.
+ /// The session scratch, writable at its real path on every backend.
pub scratch: Option<&'a Path>,
/// Folders the user attached read-only: reads may reach them, writes may not.
pub read_roots: &'a [PathBuf],
@@ -196,16 +196,16 @@ pub fn resolve_decision(
&& !requests_escalation(tool, args);
let carved = |p: &str| match tool.capability {
Capability::Read => {
- in_attached_root(ctx.project_root, ctx.scratch, ctx.read_roots, p)
+ in_attached_root(ctx.project_root, ctx.read_roots, p)
}
Capability::Exec if shell_reads_only => {
- in_attached_root(ctx.project_root, ctx.scratch, ctx.read_roots, p)
- && !in_attached_root(ctx.project_root, ctx.scratch, ctx.write_roots, p)
+ in_attached_root(ctx.project_root, ctx.read_roots, p)
+ && !in_attached_root(ctx.project_root, ctx.write_roots, p)
}
_ => false,
};
let hidden_hit = |p: &str| {
- in_hidden_root(ctx.project_root, ctx.scratch, hidden, p) && !carved(p)
+ in_hidden_root(ctx.project_root, hidden, p) && !carved(p)
};
let hits_path = tool.path_args.iter().any(|key| {
args.get(key)
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.rs
index a1235ec86..c2a36caa5 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
@@ -16,7 +16,7 @@ use crate::tools::proc;
use crate::tools::nofollow;
use crate::tools::sandbox::{
escapes_write_roots, hidden_under, in_read_only_root, in_scratch, landing, lexical_normalize,
- refuse_windows_name, resolve_path, scratch_display_path, symlink_escapes_any_root, Landing,
+ refuse_windows_name, resolve_path, symlink_escapes_any_root, Landing,
};
use crate::screenshot_pages::PageScope;
use crate::tools::{BuiltinTool, ImageContentPart, ScreenshotBackend, ToolContext};
@@ -73,10 +73,10 @@ fn rel_to(base: &Path, path: &Path) -> String {
/// 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. A target inside the session
-/// scratch is named by whichever spelling the shell can also use there.
+/// scratch is named by its full real path, which the shell can use too.
fn display_path(root: &Path, scratch: Option<&Path>, target: &Path) -> String {
if in_scratch(scratch, target) {
- return scratch_display_path(scratch, target);
+ return lexical_normalize(target).to_string_lossy().into_owned();
}
rel_to(&lexical_normalize(root), &lexical_normalize(target))
}
@@ -282,7 +282,6 @@ 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())?;
@@ -290,7 +289,7 @@ pub async fn preview_diff(
return None;
}
let prior = match arg_str(args, "path") {
- Some(p) => tokio::fs::read_to_string(resolve_path(project_root, scratch, p))
+ Some(p) => tokio::fs::read_to_string(resolve_path(project_root, p))
.await
.unwrap_or_default(),
None => String::new(),
@@ -300,7 +299,7 @@ pub async fn preview_diff(
}
"write" => {
let prior = match arg_str(args, "path") {
- Some(p) => tokio::fs::read_to_string(resolve_path(project_root, scratch, p))
+ Some(p) => tokio::fs::read_to_string(resolve_path(project_root, p))
.await
.ok(),
None => None,
@@ -682,7 +681,7 @@ async fn read(
};
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_path(root, scratch, path);
+ let target = resolve_path(root, path);
// Fail closed: a component swapped to a symlink after the gate validated
// the path must not redirect the open out of the workspace.
if symlink_escapes_any_root(root, scratch, read_roots, &target) {
@@ -804,7 +803,7 @@ async fn ls(
let limit = arg_u64(args, "limit")
.map(|v| v as usize)
.unwrap_or(LS_DEFAULT_LIMIT);
- let target = resolve_path(root, scratch, path);
+ let target = resolve_path(root, path);
// Names are content too: a symlinked directory would list a host directory.
if symlink_escapes_any_root(root, scratch, read_roots, &target) {
return format!("ERROR: refused to list through a symlink out of the workspace: {path}");
@@ -863,7 +862,7 @@ async fn write(
// canonical root (not the raw argument) so `..` and absolute paths are
// caught even if the gate's decision was made against a stale view.
// `write_roots` widen the confinement exactly as they widened the gate.
- let target = resolve_path(root, scratch, path);
+ let target = resolve_path(root, path);
if confine && escapes_write_roots(root, scratch, write_roots, path).unwrap_or(true) {
return format!("ERROR: refused to write outside the agent workspace: {path}");
}
@@ -995,7 +994,7 @@ async fn edit(
if let Some((name, why)) = refuse_windows_name(path) {
return format!("ERROR: refused to edit '{name}' in {path}: the name {why}");
}
- let target = resolve_path(root, scratch, path);
+ let target = resolve_path(root, path);
if confine && escapes_write_roots(root, scratch, write_roots, path).unwrap_or(true) {
return format!("ERROR: refused to edit outside the agent workspace: {path}");
}
@@ -1037,22 +1036,23 @@ async fn edit(
/// The refusal a `write`/`edit` gets for a path in a read-only root. Refused
/// here rather than left to the prompt, which auto-approval would answer.
-/// Names the scratch only where there is one, by the spelling the tools use.
+/// Names the scratch only where there is one.
fn read_only_refusal(args: &serde_json::Value, scratch: Option<&Path>) -> String {
let path = arg_str(args, "path").unwrap_or_default();
let head = format!("ERROR: {path} is in a read-only checkout; this run cannot change it.");
match scratch {
Some(s) => format!(
"{head} Write temporary files under {} instead.",
- scratch_display_path(Some(s), s)
+ s.display()
),
None => head,
}
}
/// The shell a confined command launches with: the (possibly jail-wrapped)
-/// shell config, the path the sandbox exposes as its temp dir, and the policy
-/// itself (which `denial_hint` reads even when the shell runs unconfined).
+/// shell config, the env that names the scratch and package cache at their
+/// real paths (`None` unconfined), and the policy itself (which `denial_hint`
+/// reads even when the shell runs unconfined).
///
/// With the sandbox off the shell is spawned bare, the way the user's own
/// terminal would run it: no wrapper, no policy mounts, the real `$HOME` and
@@ -1063,7 +1063,7 @@ fn read_only_refusal(args: &serde_json::Value, scratch: Option<&Path>) -> String
/// call would.
pub(crate) fn confined_shell(
ctx: &ToolContext<'_>,
-) -> Result<(proc::ShellConfig, Option<PathBuf>, jail::Policy), String> {
+) -> Result<(proc::ShellConfig, Option<proc::SandboxEnv>, jail::Policy), String> {
let root = ctx.project_root;
let mut policy =
jail::Policy::new(root, ctx.allow_network).with_home_readonly(ctx.home_readonly);
@@ -1076,6 +1076,9 @@ pub(crate) fn confined_shell(
if let Some(scratch) = ctx.scratch_root {
policy = policy.with_scratch_root(scratch);
}
+ if let Some(pkg) = ctx.pkg_cache {
+ policy = policy.with_pkg_cache(pkg);
+ }
if !ctx.read_roots.is_empty() {
policy = policy.with_read_roots(ctx.read_roots.to_vec());
}
@@ -1085,7 +1088,7 @@ pub(crate) fn confined_shell(
policy = policy.with_workspace_readonly(ctx.workspace_readonly);
// A read-only root is only read-only inside the sandbox, so it is never
// run without one, whatever the surface chose.
- let confined = ctx.sandbox || ctx.workspace_readonly;
+ let confined = ctx.shell_confined();
let shell = if confined {
// No confinement available means no shell: running unsandboxed would give
// the command the whole machine, which is never what the caller asked for.
@@ -1100,12 +1103,16 @@ pub(crate) fn confined_shell(
} else {
proc::shell().clone()
};
- let sandbox_tmp = if confined {
- jail::scratch_env_path(jail::backend(), &policy)
- } else {
- None
- };
- Ok((shell, sandbox_tmp, policy))
+ // Every backend exposes the scratch and the package cache at their real
+ // paths, so those are what the shell's env names. Unconfined, there is no
+ // sandbox env at all: the host's own values stand.
+ let sandbox_env = confined.then(|| {
+ proc::SandboxEnv::new(
+ policy.scratch_root.as_deref(),
+ policy.pkg_cache.as_ref().map(|p| p.root.as_path()),
+ )
+ });
+ Ok((shell, sandbox_env, policy))
}
async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
@@ -1123,7 +1130,7 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
);
}
- let (shell, sandbox_tmp, policy) = match confined_shell(ctx) {
+ let (shell, sandbox_env, policy) = match confined_shell(ctx) {
Ok(v) => v,
Err(e) => return e,
};
@@ -1131,7 +1138,7 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
&shell,
command,
root,
- sandbox_tmp.as_deref(),
+ sandbox_env.as_ref(),
ctx.shell_env(),
ctx.thread_id,
)
@@ -1160,7 +1167,7 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
let sink = ctx.on_output.clone();
// A read-only root is confined even in an unsandboxed session, so its
// denials get the note too.
- let sandboxed = ctx.sandbox || ctx.workspace_readonly;
+ let sandboxed = ctx.shell_confined();
let escalation = ctx.escalation;
// Fed from the first byte, so a command the user opens in `/shells` after it
// backgrounded still shows what it printed before the timeout.
@@ -1207,9 +1214,7 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
let command_owned = command.to_string();
let id = next_background_id();
let temp = new_temp_path(ctx.scratch_root);
- let display = temp
- .as_ref()
- .map(|p| crate::tools::sandbox::scratch_display_path(ctx.scratch_root, p));
+ let display = temp.as_ref().map(|p| p.to_string_lossy().into_owned());
// Raised before this call returns, so the caller is already owed a
// result by the time the turn that made the call can end.
if let Some(sink) = &done_sink {
@@ -1492,7 +1497,7 @@ impl BashCapture {
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));
+ .map(|p| p.to_string_lossy().into_owned());
match path {
Some(p) => body.push_str(&format!(
"[output truncated at {shown} of {} bytes; full output written \
@@ -1675,7 +1680,7 @@ fn tail_cap(s: &str, max_lines: usize, max_bytes: usize) -> String {
/// 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,
+/// same real path from both the filesystem tools and the shell,
/// and is reclaimed when the session's scratch is removed.
///
/// The directory is validated as a real, non-symlink directory before use: the
@@ -1977,7 +1982,7 @@ async fn screenshot(
};
let width = arg_u64(args, "width").unwrap_or(1280).clamp(320, 4096);
let height = arg_u64(args, "height").unwrap_or(960).clamp(240, 4096);
- let target = resolve_path(root, scratch, path);
+ let target = resolve_path(root, path);
// A page the user approved outside the trusted roots gets no neighbours:
// its directory was never part of what they approved.
let scope = match landing(root, scratch, read_roots, &target) {
@@ -2023,7 +2028,7 @@ async fn find(
let limit = arg_u64(args, "limit")
.map(|v| v as usize)
.unwrap_or(FIND_DEFAULT_LIMIT);
- let base = resolve_path(root, scratch, &path);
+ let base = resolve_path(root, &path);
if symlink_escapes_any_root(root, scratch, read_roots, &base) {
return format!("ERROR: refused to search through a symlink out of the workspace: {path}");
}
@@ -2097,7 +2102,7 @@ async fn grep(
let limit = arg_u64(args, "limit")
.map(|v| v as usize)
.unwrap_or(GREP_DEFAULT_LIMIT);
- let base = resolve_path(root, scratch, &path);
+ let base = resolve_path(root, &path);
if symlink_escapes_any_root(root, scratch, read_roots, &base) {
return format!("ERROR: refused to search through a symlink out of the workspace: {path}");
}
@@ -2608,7 +2613,7 @@ mod tests {
assert!(out.starts_with("ERROR") && out.contains("read-only"), "{tool}: {out}");
// The host checkout path is not the model's business.
assert!(!out.contains(&*root.to_string_lossy()), "{tool}: {out}");
- let shown = crate::tools::sandbox::scratch_display_path(Some(&scratch), &scratch);
+ let shown = scratch.display();
assert!(out.ends_with(&format!("Write temporary files under {shown} instead.")), "{out}");
}
// No scratch, no pointer at one.
@@ -2625,12 +2630,8 @@ mod tests {
let (read, _) =
super::execute_builtin(lookup("read").unwrap(), &json!({"path": "a.txt"}), &ctx).await;
assert_eq!(read, "one");
- // `/tmp/...` names the scratch on Linux; elsewhere its real path does.
- let in_scratch = if cfg!(target_os = "linux") {
- "/tmp/note.txt".to_string()
- } else {
- scratch.join("note.txt").to_string_lossy().into_owned()
- };
+ // The scratch is named by its real path on every platform.
+ let in_scratch = scratch.join("note.txt").to_string_lossy().into_owned();
let (out, _) = super::execute_builtin(
lookup("write").unwrap(),
&json!({"path": in_scratch, "content": "ok"}),
@@ -3334,8 +3335,8 @@ 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
+ /// `find` from the scratch as its base must not walk *out* through a
+ /// symlinked directory inside it. 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]
@@ -3350,7 +3351,7 @@ mod tests {
let ctx = ToolContext::new(&root, &store, &[]).with_scratch_root(&scratch);
let out = super::execute_builtin(
lookup("find").unwrap(),
- &json!({"pattern": "*.txt", "path": "/tmp"}),
+ &json!({"pattern": "*.txt", "path": scratch.to_string_lossy()}),
&ctx,
)
.await
@@ -3500,12 +3501,11 @@ mod tests {
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.
+ /// A confined `write` through a symlink the shell planted in the scratch
+ /// 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() {
+ #[cfg(unix)]
+ async fn confined_write_refuses_a_scratch_symlink_escape() {
let root = unique_root();
let scratch = unique_root();
let outside = unique_root();
@@ -3516,7 +3516,7 @@ mod tests {
.with_confined_writes(true);
let out = super::execute_builtin(
lookup("write").unwrap(),
- &json!({"path": "/tmp/esc/pwned.txt", "content": "x"}),
+ &json!({"path": scratch.join("esc/pwned.txt").to_string_lossy(), "content": "x"}),
&ctx,
)
.await
@@ -3590,112 +3590,99 @@ mod tests {
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.
+ /// A `write` into the scratch by its real path lands there, a `read` of the
+ /// same path sees it, and the result names that same path.
#[tokio::test]
- #[cfg(target_os = "linux")]
- async fn write_then_read_via_tmp_persists_in_scratch() {
+ async fn write_then_read_in_the_scratch_uses_its_real_path() {
let root = unique_root();
let scratch = unique_root();
+ let file = scratch.join("scratch.txt");
+ let shown = file.to_string_lossy().into_owned();
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"}),
+ &json!({"path": shown, "content": "persist"}),
&ctx,
)
.await
.0;
- assert!(out.starts_with("Created /tmp/scratch.txt"), "got: {out}");
- assert!(scratch.join("scratch.txt").exists(), "wrote into scratch");
+ assert!(out.starts_with(&format!("Created {shown}")), "got: {out}");
+ assert!(file.exists(), "wrote into scratch");
- let out = super::execute_builtin(
- lookup("read").unwrap(),
- &json!({"path": "/tmp/scratch.txt"}),
- &ctx,
- )
- .await
- .0;
+ let out =
+ super::execute_builtin(lookup("read").unwrap(), &json!({"path": shown}), &ctx).await.0;
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]
- #[cfg(target_os = "linux")]
- 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]
+ /// The point of the real path: a file sandboxed `bash` writes through
+ /// `$TMPDIR` is at that same absolute path on the host, so the filesystem
+ /// tools (and an escalated, unconfined command) find it by the name the
+ /// shell printed. Linux, where the scratch used to be mounted over `/tmp`.
+ #[tokio::test]
#[cfg(target_os = "linux")]
- fn tmp_path_cannot_climb_out_with_dotdot() {
+ async fn a_file_bash_writes_to_the_scratch_is_at_the_same_path_on_the_host() {
+ if !crate::tools::jail::backend().enforces() {
+ eprintln!("skipping: no sandbox backend on this host");
+ return;
+ }
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 store = crate::workspace::project_store(&root);
+ let ctx = ToolContext::new(&root, &store, &[]).with_scratch_root(&scratch);
+ let (out, _) = super::execute_builtin(
+ lookup("shell").unwrap(),
+ &json!({"command": "echo made-inside > \"$TMPDIR/out.txt\" && echo \"$TMPDIR/out.txt\""}),
+ &ctx,
+ )
+ .await;
+ let named = scratch.join("out.txt");
+ assert!(out.contains(&*named.to_string_lossy()), "TMPDIR is the real path: {out}");
+ let (read, _) = super::execute_builtin(
+ lookup("read").unwrap(),
+ &json!({"path": named.to_string_lossy()}),
+ &ctx,
+ )
+ .await;
+ assert_eq!(read.trim(), "made-inside");
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.
+ /// The gate treats a write into the scratch, by its real path, as an
+ /// in-project write rather than an escape, and the host `/tmp` as an
+ /// escape now that nothing maps it into the scratch.
#[test]
- #[cfg(target_os = "linux")]
- fn gate_allows_tmp_write_when_scratch_is_set() {
+ #[cfg(unix)]
+ fn gate_allows_a_scratch_write_and_treats_tmp_as_an_escape() {
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"}),
- &crate::tools::gate::GateContext {
- project_root: &root,
- scratch: Some(&scratch),
- read_roots: &[],
- write_roots: &[],
- hidden_root: None,
- },
- &crate::permissions::ToolPermissions::default(),
- &crate::tools::gate::SessionGrants::default(),
- );
+ let gate = |path: String| {
+ crate::tools::gate::resolve_decision(
+ lookup("write").unwrap(),
+ &json!({"path": path, "content": "y"}),
+ &crate::tools::gate::GateContext {
+ project_root: &root,
+ scratch: Some(&scratch),
+ read_roots: &[],
+ write_roots: &[],
+ hidden_root: None,
+ },
+ &crate::permissions::ToolPermissions::default(),
+ &crate::tools::gate::SessionGrants::default(),
+ )
+ };
assert_eq!(
- d,
+ gate(scratch.join("x.txt").to_string_lossy().into_owned()),
crate::tools::gate::Decision::Prompt(crate::tools::gate::PromptKind::Write),
"in-scratch write is an in-project write, not an escape"
);
+ assert_eq!(
+ gate(format!("/tmp/jan-not-the-scratch-{}.txt", std::process::id())),
+ crate::tools::gate::Decision::Prompt(crate::tools::gate::PromptKind::WriteEscape)
+ );
let _ = std::fs::remove_dir_all(&root);
let _ = std::fs::remove_dir_all(&scratch);
}
@@ -3704,15 +3691,15 @@ mod tests {
/// 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() {
+ #[cfg(unix)]
+ fn gate_treats_a_scratch_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"}),
+ &json!({"path": scratch.join("esc/x.txt").to_string_lossy(), "content": "y"}),
&crate::tools::gate::GateContext {
project_root: &root,
scratch: Some(&scratch),
@@ -4478,9 +4465,8 @@ mod tests {
}
/// 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.
+ /// scratch and be advertised by its real path, which works from both the
+ /// fs tools and the shell, so the `read` the note asks for finds it.
// POSIX command text: Windows runs PowerShell.
#[cfg(unix)]
#[tokio::test]
@@ -4501,12 +4487,10 @@ mod tests {
.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}"
- );
- }
+ assert!(
+ Path::new(path).starts_with(&scratch),
+ "must be advertised by its real path in the scratch: {out}"
+ );
let full = super::execute_builtin(
lookup("read").unwrap(),
&json!({"path": path, "offset": 15999, "limit": 1}),
@@ -4550,8 +4534,8 @@ mod tests {
}
/// Dropping the sandbox drops the scratch with it, in either builder order.
- /// A scratch that outlived the sandbox would leave the fs tools rewriting
- /// `/tmp/...` into a directory the unconfined shell never looks at.
+ /// Unconfined, the shell writes wherever the user can with the host's
+ /// own `TMPDIR`, so a scratch would only widen what the fs tools reach.
#[test]
fn unsandboxed_context_has_no_scratch() {
let root = unique_root();
@@ -4574,10 +4558,52 @@ mod tests {
.scratch_root,
Some(scratch.as_path())
);
+ // The package cache goes with it, in either order: an escalated
+ // command (the sandbox cleared for one call) keeps the host's caches.
+ let pkg = crate::workspace::PkgCache { root: scratch.join("pkg"), cargo_config: None };
+ assert!(ToolContext::new(&root, &store, &[])
+ .with_pkg_cache(Some(&pkg))
+ .with_sandbox(false)
+ .pkg_cache
+ .is_none());
+ assert!(ToolContext::new(&root, &store, &[])
+ .with_sandbox(false)
+ .with_pkg_cache(Some(&pkg))
+ .pkg_cache
+ .is_none());
let _ = std::fs::remove_dir_all(&root);
let _ = std::fs::remove_dir_all(&scratch);
}
+ /// A read-only root runs its shell confined even with the sandbox off (a
+ /// reader under the CLI default), so it keeps the package cache: its
+ /// `$HOME` is read-only in there and the host caches are unwritable.
+ /// Clearing the sandbox for one call does not unconfine it either, so it
+ /// keeps the cache then too; only clearing both drops it.
+ #[test]
+ fn a_read_only_root_keeps_its_pkg_cache_with_the_sandbox_off() {
+ let root = unique_root();
+ let store = crate::workspace::project_store(&root);
+ let pkg = crate::workspace::PkgCache { root: root.join("pkg"), cargo_config: None };
+ let reader = || {
+ ToolContext::new(&root, &store, &[])
+ .with_sandbox(false)
+ .with_workspace_readonly(true)
+ .with_pkg_cache(Some(&pkg))
+ };
+ assert_eq!(reader().pkg_cache, Some(&pkg));
+ assert_eq!(reader().with_sandbox(false).pkg_cache, Some(&pkg));
+ assert!(reader().with_workspace_readonly(false).pkg_cache.is_none());
+ // And the shell it builds names the cache.
+ let (_, env, _) = match confined_shell(&reader()) {
+ Ok(v) => v,
+ Err(_) => return, // no backend here: no shell at all
+ };
+ let env = env.expect("a read-only root is always confined");
+ assert!(env.vars().iter().any(|(k, v)| *k == "CARGO_HOME" && v.starts_with(&pkg.root)));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
// POSIX command text: Windows runs PowerShell.
#[cfg(unix)]
#[tokio::test]
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/hooks.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/hooks.rs
index 256d45523..c33c888fd 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/hooks.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/hooks.rs
@@ -497,7 +497,7 @@ pub async fn run_hooks(
/// Run one hook command to completion. `Err` carries the one-line detail a
/// [`HookNotice`] reports; it never propagates as a run failure.
async fn run_one(hook: &Hook, body: &str, ctx: &ToolContext<'_>) -> Result<HookResponse, String> {
- let (shell, sandbox_tmp, _policy) = crate::tools::handlers::confined_shell(ctx)
+ let (shell, sandbox_env, _policy) = crate::tools::handlers::confined_shell(ctx)
.map_err(|e| format!("could not start: {}", e.trim_start_matches("ERROR: ")))?;
// A hook child is short-lived and belongs to the run rather than to a
// cancellable tool call, so it registers in the process-wide bucket the
@@ -506,7 +506,7 @@ async fn run_one(hook: &Hook, body: &str, ctx: &ToolContext<'_>) -> Result<HookR
&shell,
&hook.command,
ctx.project_root,
- sandbox_tmp.as_deref(),
+ sandbox_env.as_ref(),
ctx.shell_env(),
None,
Some(body),
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.rs
index 2784b76fd..5a67d9d72 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
@@ -28,6 +28,8 @@
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
+use crate::workspace::{CargoConfig, PkgCache};
+
use super::appcontainer;
use super::proc::ShellConfig;
@@ -80,13 +82,17 @@ pub struct Policy {
/// 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).
+ /// instead of a scratch that vanishes between commands. Every backend makes
+ /// it writable at its own real path, so the shell, the filesystem tools and
+ /// an escalated (unconfined) command all name it the same way: bubblewrap
+ /// binds it onto itself, 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>,
+ /// The project's package cache, writable at its real path like the
+ /// scratch, with the user's cargo config inside it read-only. See
+ /// [`crate::workspace::prepare_pkg_cache`]; it must already exist.
+ pub pkg_cache: Option<PkgCache>,
/// Folders the user attached read-only. Bound after the `$HOME`/data-folder
/// masks (so a project under either survives) and before the workspace bind
/// (so one can never shadow the only writable path).
@@ -113,6 +119,7 @@ impl Policy {
allow_network,
home_readonly: false,
scratch_root: None,
+ pkg_cache: None,
read_roots: Vec::new(),
write_roots: Vec::new(),
hide_root: None,
@@ -120,6 +127,55 @@ impl Policy {
}
}
+ /// Expose the project's package cache. See [`Policy::pkg_cache`].
+ pub fn with_pkg_cache(mut self, pkg: &PkgCache) -> Self {
+ self.pkg_cache = Some(pkg.clone());
+ self
+ }
+
+ /// The folders writable at their own path besides the workspace and the
+ /// attached roots: the scratch and the package cache.
+ fn own_path_dirs(&self) -> impl Iterator<Item = &Path> {
+ self.scratch_root
+ .as_deref()
+ .into_iter()
+ .chain(self.pkg_cache.as_ref().map(|p| p.root.as_path()))
+ }
+
+ /// The Jan cache root (`<cache>/jan`) holding every project's package
+ /// cache and scratch, hidden whenever this run has a folder in it (a
+ /// package cache, or a scratch under the real cache root): with `$HOME`
+ /// readable (the CLI), with an attached root containing `~/.cache` (the
+ /// desktop), or with `XDG_CACHE_HOME` outside `$HOME`, other sessions'
+ /// scratch and caches would otherwise be readable, and a tampered tarball
+ /// could be read across projects. This run's own scratch and cache are
+ /// exposed again on top of it. A workspace or attached root containing the
+ /// cache root (running in `$HOME`) would show it again, so there it is
+ /// masked a second time after those binds ([`Self::cache_under_a_bind`]).
+ fn cache_mask(&self) -> Option<PathBuf> {
+ if let Some(pkg) = &self.pkg_cache {
+ return pkg.root.parent()?.parent().map(Path::to_path_buf);
+ }
+ // Only the real cache root: a scratch elsewhere (a test's temp dir)
+ // has no ancestor that is safe to mask.
+ let root = crate::workspace::jan_cache_root();
+ self.scratch_root
+ .as_deref()
+ .is_some_and(|scratch| scratch.starts_with(&root) && scratch != root)
+ .then_some(root)
+ }
+
+ /// [`Self::cache_mask`] when a bind contains it and it must be masked
+ /// again after that bind.
+ fn cache_under_a_bind(&self) -> Option<PathBuf> {
+ self.cache_mask().filter(|cache| self.hide_under_a_bind(cache))
+ }
+
+ /// The user's cargo config, when the package cache offers one.
+ fn cargo_config(&self) -> Option<&CargoConfig> {
+ self.pkg_cache.as_ref()?.cargo_config.as_ref()
+ }
+
/// Keep the workspace readable but not writable. AppContainer grants its
/// workspace by a write ACE and has no read-only form, so [`wrap`] refuses
/// such a policy there: no shell rather than a writable one.
@@ -244,21 +300,6 @@ 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
@@ -286,6 +327,7 @@ pub fn wrap(cfg: &ShellConfig, policy: &Policy) -> Option<ShellConfig> {
args: appcontainer::helper_args(
&policy.workspace,
policy.scratch_root.as_deref(),
+ policy.pkg_cache.as_ref().map(|p| p.root.as_path()),
policy.allow_network,
&cfg.program,
&cfg.args,
@@ -474,16 +516,10 @@ 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"]);
- // `/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"]);
- }
+ // `/tmp`: always a private tmpfs, writable and discarded with the sandbox,
+ // so the shell never sees the machine's other temp files. Persistent work
+ // goes in the scratch, bound at its real path below.
+ 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
@@ -519,6 +555,11 @@ pub fn bwrap_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {
if let Some(hide) = &policy.hide_root {
push(&mut args, &["--tmpfs", &hide.to_string_lossy()]);
}
+ // Other projects' caches, masked with the rest; this run's own are bound
+ // back below.
+ if let Some(cache) = policy.cache_mask() {
+ push(&mut args, &["--tmpfs", &cache.to_string_lossy()]);
+ }
// Between the masks above and the workspace below, and that position is the
// enforcement: after the `$HOME`/data-folder tmpfs so a project living under
@@ -542,9 +583,54 @@ pub fn bwrap_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {
let root = root.to_string_lossy();
push(&mut args, &["--bind", &root, &root]);
}
-
+ // The scratch at its real path, so the name the shell uses also exists
+ // outside the sandbox. After the `$HOME`/data-folder/Jan-home tmpfs
+ // masks, because it lives under the OS cache dir (`~/.cache` sits under
+ // `$HOME`) and a later mask would hide it again; after a `/tmp` tmpfs too,
+ // for the temp-dir fallback. Before the workspace bind, like the roots.
+ // The package cache goes the same way, for the same reasons.
+ for dir in policy.own_path_dirs() {
+ let dir = dir.to_string_lossy();
+ push(&mut args, &["--bind", &dir, &dir]);
+ }
let bind = if policy.workspace_readonly { "--ro-bind" } else { "--bind" };
push(&mut args, &[bind, &ws, &ws]);
+ // A workspace containing the Jan cache root (running in `$HOME`) has just
+ // shown every project's cache again: mask it once more, then bind this
+ // run's own folders back, which also restores their write access under a
+ // read-only workspace.
+ if let Some(cache) = policy.cache_under_a_bind() {
+ push(&mut args, &["--tmpfs", &cache.to_string_lossy()]);
+ for dir in policy.own_path_dirs() {
+ let dir = dir.to_string_lossy();
+ push(&mut args, &["--bind", &dir, &dir]);
+ }
+ } else if policy.workspace_readonly {
+ // A read-only workspace that contains the scratch or the package
+ // cache (a reader working in `$HOME`) would otherwise make them
+ // read-only too.
+ for dir in policy.own_path_dirs().filter(|d| d.starts_with(&policy.workspace)) {
+ let dir = dir.to_string_lossy();
+ push(&mut args, &["--bind", &dir, &dir]);
+ }
+ }
+ // The user's cargo config, read-only, after every rw bind (the package
+ // cache, a workspace that contains it) so none can shadow it: mounted
+ // rather than trusted to the copy's mode, which the file's owner could
+ // change. Over both names cargo reads, since it prefers the legacy
+ // `config` when both exist, so neither can be written or planted. Cargo's
+ // folder is bound onto itself first: a mount point cannot be renamed
+ // (EBUSY), so the shell cannot move it aside and make a fresh one with a
+ // config of its own. `pkg` itself already is a mount point.
+ if let Some(config) = policy.cargo_config() {
+ if let Some(cargo) = config.copy.parent() {
+ let cargo = cargo.to_string_lossy();
+ push(&mut args, &["--bind", &cargo, &cargo]);
+ }
+ let host = config.host.to_string_lossy();
+ push(&mut args, &["--ro-bind", &host, &config.copy.to_string_lossy()]);
+ push(&mut args, &["--ro-bind", &host, &config.legacy().to_string_lossy()]);
+ }
// And again after, when a bind contains it (running in `$HOME`): the
// workspace bind would otherwise shadow the mask above and re-expose it.
if let Some(hide) = policy.hide_root.as_deref().filter(|h| policy.hide_under_a_bind(h)) {
@@ -601,6 +687,18 @@ fn real_form(path: &Path) -> Option<PathBuf> {
/// refuses a profile referencing a parameter no argument supplies.
struct SeatbeltPaths {
scratch_real: Option<PathBuf>,
+ pkg_real: Option<PathBuf>,
+ /// What stays unwritable in cargo's folder: the config copy, the legacy
+ /// `config` name and the folder's own path (so it cannot be renamed away
+ /// and recreated), each in every form it has.
+ cargo_config: Vec<PathBuf>,
+ /// The Jan cache root ([`Policy::cache_mask`]), in every form it has.
+ cache_mask: Vec<PathBuf>,
+ /// The folders between the cache root and this run's own scratch and
+ /// package cache, the root included, in every form. The root's read deny
+ /// covers their metadata too, so `mkdir -p` or `realpath` into the run's
+ /// own folders would fail; stat alone is given back, never a listing.
+ cache_ancestors: Vec<PathBuf>,
/// The read-only checkout and read roots, each in every form it has.
deny_write: Vec<PathBuf>,
}
@@ -620,8 +718,52 @@ impl SeatbeltPaths {
}
}
}
+ let forms = |path: &Path| -> Vec<PathBuf> {
+ std::iter::once(path.to_path_buf()).chain(real_form(path)).collect()
+ };
+ // The legacy name usually does not exist, so its resolved form comes
+ // from its folder's.
+ let child_forms = |path: &Path| -> Vec<PathBuf> {
+ let real = path
+ .parent()
+ .and_then(real_form)
+ .zip(path.file_name())
+ .map(|(dir, name)| dir.join(name));
+ std::iter::once(path.to_path_buf()).chain(real).collect()
+ };
+ let cargo_config = policy
+ .cargo_config()
+ .map(|c| {
+ let mut all = child_forms(&c.copy);
+ all.extend(child_forms(&c.legacy()));
+ all.extend(c.copy.parent().map(forms).unwrap_or_default());
+ all.dedup();
+ all
+ })
+ .unwrap_or_default();
+ let cache_mask = policy.cache_mask().map(|c| forms(&c)).unwrap_or_default();
+ let mut cache_ancestors: Vec<PathBuf> = Vec::new();
+ for dir in policy.own_path_dirs() {
+ for form in forms(dir) {
+ let Some(root) = cache_mask.iter().find(|root| form.starts_with(root)) else {
+ continue;
+ };
+ for ancestor in form.ancestors().skip(1) {
+ if !ancestor.starts_with(root) {
+ break;
+ }
+ if !cache_ancestors.iter().any(|a| a == ancestor) {
+ cache_ancestors.push(ancestor.to_path_buf());
+ }
+ }
+ }
+ }
Self {
scratch_real: policy.scratch_root.as_deref().and_then(real_form),
+ pkg_real: policy.pkg_cache.as_ref().and_then(|p| real_form(&p.root)),
+ cargo_config,
+ cache_mask,
+ cache_ancestors,
deny_write,
}
}
@@ -668,6 +810,13 @@ fn seatbelt_profile(policy: &Policy, paths: &SeatbeltPaths) -> String {
if policy.mask_root.is_some() {
p.push_str("(deny file-read* (subpath (param \"MASK_ROOT\")))\n");
}
+ // Other projects' caches, even with `$HOME` readable; this run's scratch
+ // and package cache are allowed back below.
+ for i in 0..paths.cache_mask.len() {
+ p.push_str(&format!(
+ "(deny file-read* (subpath (param \"CACHE_MASK_{i}\")))\n"
+ ));
+ }
// Later rules win. Denied here, before the allows below, when the
// workspace lives under the Jan home (a worktree) so it is read back; when
// the home lies inside an allowed root instead, the deny goes last.
@@ -700,23 +849,7 @@ fn seatbelt_profile(policy: &Policy, paths: &SeatbeltPaths) -> String {
if !policy.workspace_readonly {
p.push_str("(allow file-write* (subpath (param \"WORKSPACE\")))\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",
- );
- }
- if paths.scratch_real.is_some() {
- p.push_str(
- "(allow file-read* (subpath (param \"SCRATCH_REAL\")))\n\
- (allow file-write* (subpath (param \"SCRATCH_REAL\")))\n",
- );
- }
+ push_own_dirs(&mut p, policy, paths);
// After the HOME/MASK denials, so an attached folder inside either is read
// back: in Seatbelt the later rule wins. Read only — no matching
// `file-write*`, so `(deny default)` keeps the folder unwritable. Emitted
@@ -735,6 +868,18 @@ fn seatbelt_profile(policy: &Policy, paths: &SeatbeltPaths) -> String {
(allow file-write* (subpath (param \"WRITE_ROOT_{i}\")))\n"
));
}
+ // A workspace or attached root containing the Jan cache root (running in
+ // `$HOME`) has just allowed every project's cache again: deny it once
+ // more, then allow this run's own folders back, as bubblewrap does.
+ if policy.cache_under_a_bind().is_some() {
+ for i in 0..paths.cache_mask.len() {
+ p.push_str(&format!(
+ "(deny file-read* (subpath (param \"CACHE_MASK_{i}\")))\n\
+ (deny file-write* (subpath (param \"CACHE_MASK_{i}\")))\n"
+ ));
+ }
+ push_own_dirs(&mut p, policy, paths);
+ }
if hide_last {
p.push_str(HIDE_RULES);
}
@@ -756,6 +901,57 @@ fn seatbelt_profile(policy: &Policy, paths: &SeatbeltPaths) -> String {
p
}
+/// Allow the scratch and the package cache, then deny writes to cargo's
+/// config inside the latter (the later rule wins).
+fn push_own_dirs(p: &mut String, policy: &Policy, paths: &SeatbeltPaths) {
+ for i in 0..paths.cache_ancestors.len() {
+ p.push_str(&format!(
+ "(allow file-read-metadata (literal (param \"CACHE_ANCESTOR_{i}\")))\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",
+ );
+ }
+ if paths.scratch_real.is_some() {
+ p.push_str(
+ "(allow file-read* (subpath (param \"SCRATCH_REAL\")))\n\
+ (allow file-write* (subpath (param \"SCRATCH_REAL\")))\n",
+ );
+ }
+ // The package cache, granted the same way and for the same reasons.
+ if policy.pkg_cache.is_some() {
+ p.push_str(
+ "(allow file-read* (subpath (param \"PKG\")))\n\
+ (allow file-write* (subpath (param \"PKG\")))\n",
+ );
+ }
+ if paths.pkg_real.is_some() {
+ p.push_str(
+ "(allow file-read* (subpath (param \"PKG_REAL\")))\n\
+ (allow file-write* (subpath (param \"PKG_REAL\")))\n",
+ );
+ }
+ // The user's cargo config copy stays read-only inside the writable cache:
+ // it can name programs cargo runs. After the cache allow, since the later
+ // rule wins. `literal`, so the legacy `config` name cannot be created
+ // either, and cargo's folder itself cannot be renamed or removed (which
+ // would let the shell make a fresh one with a config of its own); what
+ // it holds below stays writable.
+ for i in 0..paths.cargo_config.len() {
+ p.push_str(&format!(
+ "(deny file-write* (literal (param \"CARGO_CONFIG_{i}\")))\n"
+ ));
+ }
+}
+
/// Build `sandbox-exec`'s argv. Paths travel as `-D` parameters rather than being
/// interpolated into the profile so a path containing profile syntax cannot
/// rewrite the policy.
@@ -787,6 +983,21 @@ pub fn seatbelt_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {
if let Some(real) = &paths.scratch_real {
args.push(format!("-DSCRATCH_REAL={}", real.to_string_lossy()));
}
+ if let Some(pkg) = &policy.pkg_cache {
+ args.push(format!("-DPKG={}", pkg.root.to_string_lossy()));
+ }
+ if let Some(real) = &paths.pkg_real {
+ args.push(format!("-DPKG_REAL={}", real.to_string_lossy()));
+ }
+ for (i, path) in paths.cargo_config.iter().enumerate() {
+ args.push(format!("-DCARGO_CONFIG_{i}={}", path.to_string_lossy()));
+ }
+ for (i, path) in paths.cache_mask.iter().enumerate() {
+ args.push(format!("-DCACHE_MASK_{i}={}", path.to_string_lossy()));
+ }
+ for (i, path) in paths.cache_ancestors.iter().enumerate() {
+ args.push(format!("-DCACHE_ANCESTOR_{i}={}", path.to_string_lossy()));
+ }
if let Some(home) = home_dir() {
args.push(format!("-DHOME_ROOT={}", home.to_string_lossy()));
}
@@ -841,7 +1052,7 @@ pub fn denial_hint(policy: &Policy) -> String {
};
// 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) {
+ let scratch = match &policy.scratch_root {
Some(path) => format!(" and the scratch dir ({})", path.display()),
None => String::new(),
};
@@ -1254,7 +1465,7 @@ mod tests {
}
/// A read-only subagent's checkout is bound read-only, `.git` included
- /// (it is inside the bind), while the scratch stays the writable `/tmp`.
+ /// (it is inside the bind), while the scratch stays writable.
#[test]
fn bwrap_binds_a_read_only_workspace_read_only() {
let ws = "/data/agent-workspace/threads/t1";
@@ -1468,21 +1679,303 @@ mod tests {
assert!(text.contains("--tmpfs /tmp"));
}
+ /// The scratch is bound at its own real path, never over `/tmp`, which
+ /// stays a private tmpfs either way: the name the shell uses must exist
+ /// outside the sandbox too.
#[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());
+ fn bwrap_binds_the_scratch_at_its_real_path_and_keeps_tmp_private() {
+ let scratch = "/home/u/.cache/jan/chat/scratch/t1";
+ let scratch_bind = format!("--bind {scratch} {scratch}");
- // 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}");
+ let bound = joined(&bwrap_args(&policy().with_scratch_root(Path::new(scratch)), &cfg()));
+ assert!(bound.contains("--tmpfs /tmp"), "{bound}");
assert!(bound.contains(&scratch_bind), "{bound}");
+ assert!(!bound.contains(&format!("--bind {scratch} /tmp")), "{bound}");
+ }
+
+ /// The scratch lives under `~/.cache`, so its bind must come after every
+ /// tmpfs mask that could cover it (`$HOME`, the data folder, the Jan
+ /// home) and before the workspace bind; the Jan home re-mask after the
+ /// workspace still comes last.
+ #[test]
+ fn bwrap_binds_the_scratch_after_the_masks_and_before_the_workspace() {
+ let Some(home) = home_dir() else {
+ return;
+ };
+ let scratch = home.join(".cache/jan/p-1/scratch/s1");
+ let hide = home.join(".jan");
+ let p = Policy::new(&home, false)
+ .with_mask_root(Path::new("/data"))
+ .with_hide_root(&hide)
+ .with_scratch_root(&scratch);
+ let args = bwrap_args(&p, &cfg());
+ let text = joined(&args);
+ let s = scratch.to_string_lossy();
+ let h = home.to_string_lossy();
+ let at = text.find(&format!("--bind {s} {s}")).expect(&text);
+ assert!(text.find(&format!("--tmpfs {h} ")).expect(&text) < at, "{text}");
+ assert!(text.find("--tmpfs /data").expect(&text) < at, "{text}");
+ let hide_at = text.find(&format!("--tmpfs {}", hide.to_string_lossy())).expect(&text);
+ assert!(hide_at < at, "{text}");
+ let ws_at = text.find(&format!("--bind {h} {h}")).expect(&text);
+ assert!(at < ws_at, "{text}");
+ assert!(text.rfind(&format!("--tmpfs {}", hide.to_string_lossy())).unwrap() > ws_at);
+ }
+
+ /// A read-only workspace that contains the scratch (a reader working in
+ /// `$HOME`) must not take the scratch's write access with it.
+ #[test]
+ fn bwrap_rebinds_a_scratch_inside_a_read_only_workspace() {
+ let p = Policy::new(Path::new("/home/u"), false)
+ .with_workspace_readonly(true)
+ .with_scratch_root(Path::new("/home/u/.cache/jan/p/scratch/s1"));
+ let text = joined(&bwrap_args(&p, &cfg()));
+ let ws = text.find("--ro-bind /home/u /home/u").expect(&text);
+ let rebind = text
+ .rfind("--bind /home/u/.cache/jan/p/scratch/s1 /home/u/.cache/jan/p/scratch/s1")
+ .expect(&text);
+ assert!(ws < rebind, "{text}");
+ }
+
+ fn pkg_cache(root: &str, config: bool) -> PkgCache {
+ PkgCache {
+ root: PathBuf::from(root),
+ cargo_config: config.then(|| CargoConfig {
+ host: PathBuf::from("/home/u/.cargo/config.toml"),
+ copy: Path::new(root).join("cargo/config.toml"),
+ }),
+ }
+ }
+
+ /// The package cache is bound writable at its real path in the scratch's
+ /// position (after the masks, before the workspace), and the user's cargo
+ /// config read-only over its copy after every rw bind, so none shadows it.
+ // Unix fixture paths: `Path::join` would add `\\` on Windows, which has
+ // neither backend.
+ #[cfg(unix)]
+ #[test]
+ fn bwrap_binds_the_pkg_cache_and_the_cargo_config_read_only() {
+ let pkg = "/home/u/.cache/jan/p-1/pkg";
+ let p = Policy::new(Path::new("/home/u/proj"), true)
+ .with_pkg_cache(&pkg_cache(pkg, true));
+ let text = joined(&bwrap_args(&p, &cfg()));
+ let bind = text.find(&format!("--bind {pkg} {pkg}")).expect(&text);
+ let mask = text.find("--tmpfs /home/u/.cache/jan ").expect(&text);
+ assert!(mask < bind, "other projects' caches are masked first: {text}");
+ let ws = text.find("--bind /home/u/proj /home/u/proj").expect(&text);
+ assert!(bind < ws, "{text}");
+ let ro = text
+ .find(&format!("--ro-bind /home/u/.cargo/config.toml {pkg}/cargo/config.toml"))
+ .expect(&text);
+ assert!(ro > ws, "{text}");
+
+ // No config on the host: no bind (bubblewrap would fail on a missing
+ // source), and no package cache at all without one in the policy.
+ let bare = joined(&bwrap_args(
+ &Policy::new(Path::new("/w"), true).with_pkg_cache(&pkg_cache(pkg, false)),
+ &cfg(),
+ ));
+ assert!(bare.contains(&format!("--bind {pkg} {pkg}")), "{bare}");
+ assert!(!bare.contains("config.toml"), "{bare}");
+ assert!(!joined(&bwrap_args(&policy(), &cfg())).contains("pkg"));
+ }
+
+ /// With no package cache (desktop chat, the MCP server), a scratch under
+ /// the Jan cache root still masks the root: an attached folder holding
+ /// `~/.cache`, or an `XDG_CACHE_HOME` outside `$HOME`, would otherwise
+ /// show every other session's scratch. A scratch elsewhere masks nothing.
+ #[test]
+ fn bwrap_masks_the_cache_root_for_a_scratch_without_a_pkg_cache() {
+ let root = crate::workspace::jan_cache_root();
+ let root_s = root.to_string_lossy().to_string();
+ let scratch = root.join("chat/scratch/t1");
+ let scratch_s = scratch.to_string_lossy().to_string();
+ let p = Policy::new(Path::new("/w"), false)
+ .with_read_roots(vec![root.parent().unwrap().to_path_buf()])
+ .with_scratch_root(&scratch);
+ let text = joined(&bwrap_args(&p, &cfg()));
+ let mask = text.find(&format!("--tmpfs {root_s} ")).expect(&text);
+ let bind = text.rfind(&format!("--bind {scratch_s} {scratch_s}")).expect(&text);
+ assert!(mask < bind, "the run's own scratch is bound back: {text}");
+ assert_eq!(text.matches(&format!("--tmpfs {root_s} ")).count(), 2, "{text}");
+
+ let elsewhere = Policy::new(Path::new("/w"), false)
+ .with_scratch_root(Path::new("/var/tmp/s1"));
+ assert!(!joined(&bwrap_args(&elsewhere, &cfg())).contains(&root_s));
+ }
+
+ /// A read-only workspace containing the package cache rebinds it, and the
+ /// cargo config still lands read-only after that rebind.
+ // Unix fixture paths: `Path::join` would add `\\` on Windows, which has
+ // neither backend.
+ #[cfg(unix)]
+ #[test]
+ fn bwrap_rebinds_a_pkg_cache_inside_a_read_only_workspace() {
+ let pkg = "/home/u/.cache/jan/p/pkg";
+ let p = Policy::new(Path::new("/home/u"), false)
+ .with_workspace_readonly(true)
+ .with_pkg_cache(&pkg_cache(pkg, true));
+ let text = joined(&bwrap_args(&p, &cfg()));
+ let ws = text.find("--ro-bind /home/u /home/u").expect(&text);
+ let rebind = text.rfind(&format!("--bind {pkg} {pkg}")).expect(&text);
+ let ro = text.rfind(&format!("{pkg}/cargo/config.toml")).expect(&text);
+ assert!(ws < rebind && rebind < ro, "{text}");
+ }
+
+ /// Cargo's own folder is a mount point (so it cannot be renamed away and
+ /// recreated), and both names cargo reads its config from are the host
+ /// file, read-only: neither can be written or planted. One inode under
+ /// both names, so cargo (1.79+) sees one file and does not warn.
+ // Unix fixture paths: `Path::join` would add `\\` on Windows, which has
+ // neither backend.
+ #[cfg(unix)]
+ #[test]
+ fn bwrap_pins_cargos_folder_and_both_config_names() {
+ let pkg = "/home/u/.cache/jan/p-1/pkg";
+ let cargo = format!("{pkg}/cargo");
+ let p = Policy::new(Path::new("/home/u/proj"), true).with_pkg_cache(&pkg_cache(pkg, true));
+ let text = joined(&bwrap_args(&p, &cfg()));
+ let ws = text.find("--bind /home/u/proj /home/u/proj").expect(&text);
+ let pin = text.find(&format!("--bind {cargo} {cargo} ")).expect(&text);
+ assert!(ws < pin, "{text}");
+ for name in ["config.toml", "config"] {
+ let ro = text
+ .find(&format!("--ro-bind /home/u/.cargo/config.toml {cargo}/{name} "))
+ .unwrap_or_else(|| panic!("{name} not read-only: {text}"));
+ assert!(pin < ro, "{text}");
+ }
+ }
+
+ /// A workspace containing the Jan cache root (running in `$HOME`) would
+ /// show every project's cache again, so the cache root is masked again
+ /// after the workspace bind and this run's scratch and package cache are
+ /// bound back on top, with cargo's config pinned after that.
+ // Unix fixture paths: `Path::join` would add `\\` on Windows, which has
+ // neither backend.
+ #[cfg(unix)]
+ #[test]
+ fn bwrap_masks_the_cache_root_again_inside_the_workspace() {
+ let pkg = "/home/u/.cache/jan/p-1/pkg";
+ let scratch = "/home/u/.cache/jan/p-1/scratch/s1";
+ let p = Policy::new(Path::new("/home/u"), true)
+ .with_scratch_root(Path::new(scratch))
+ .with_pkg_cache(&pkg_cache(pkg, true));
+ let text = joined(&bwrap_args(&p, &cfg()));
+ let ws = text.find("--bind /home/u /home/u").expect(&text);
+ let remask = text.rfind("--tmpfs /home/u/.cache/jan ").expect(&text);
+ assert!(ws < remask, "{text}");
+ for dir in [pkg, scratch] {
+ let rebind = text.rfind(&format!("--bind {dir} {dir} ")).expect(&text);
+ assert!(remask < rebind, "{dir}: {text}");
+ }
+ let config = text.rfind(&format!("{pkg}/cargo/config.toml")).expect(&text);
+ assert!(remask < config, "{text}");
+
+ // A workspace beside the cache root needs no second mask.
+ let apart = joined(&bwrap_args(
+ &Policy::new(Path::new("/home/u/proj"), true).with_pkg_cache(&pkg_cache(pkg, true)),
+ &cfg(),
+ ));
+ assert_eq!(apart.matches("--tmpfs /home/u/.cache/jan ").count(), 1, "{apart}");
+ }
+
+ /// Seatbelt's equivalent: with the cache root inside the workspace, it is
+ /// denied again (reads and writes) after the workspace allows, and this
+ /// run's own folders are allowed back after that.
+ #[test]
+ fn seatbelt_denies_the_cache_root_again_inside_the_workspace() {
+ let pkg = "/Users/u/Library/Caches/jan/p-1/pkg";
+ let p = Policy::new(Path::new("/Users/u"), true)
+ .with_scratch_root(Path::new("/Users/u/Library/Caches/jan/p-1/scratch/s1"))
+ .with_pkg_cache(&pkg_cache(pkg, true));
+ let profile = seatbelt_policy(&p);
+ let ws = profile
+ .find("(allow file-write* (subpath (param \"WORKSPACE\")))")
+ .expect(&profile);
+ let deny = profile
+ .rfind("(deny file-write* (subpath (param \"CACHE_MASK_0\")))")
+ .expect(&profile);
+ assert!(ws < deny, "{profile}");
+ let read = profile
+ .rfind("(deny file-read* (subpath (param \"CACHE_MASK_0\")))")
+ .expect(&profile);
+ assert!(ws < read, "{profile}");
+ for allow in [
+ "(allow file-write* (subpath (param \"PKG\")))",
+ "(allow file-write* (subpath (param \"SCRATCH\")))",
+ ] {
+ assert!(deny < profile.rfind(allow).expect(&profile), "{allow}: {profile}");
+ }
+ let cargo = profile
+ .rfind("(deny file-write* (literal (param \"CARGO_CONFIG_0\")))")
+ .expect(&profile);
+ assert!(profile.rfind("(param \"PKG\")").unwrap() < cargo, "{profile}");
+
+ let apart = seatbelt_policy(&policy().with_pkg_cache(&pkg_cache(pkg, true)));
+ assert!(!apart.contains("(deny file-write* (subpath (param \"CACHE_MASK_0\")))"), "{apart}");
+ }
+
+ /// The cache root's read deny would also refuse a `stat` of the folders
+ /// above the run's own package cache and scratch, which breaks `mkdir -p`
+ /// and `realpath` into them: their metadata alone is allowed back, after
+ /// the deny, by literal path (no listing of other projects' folders).
+ #[test]
+ fn seatbelt_lets_the_shell_stat_the_folders_above_its_own() {
+ let pkg = "/Users/u/Library/Caches/jan/p-1/pkg";
+ let p = policy()
+ .with_scratch_root(Path::new("/Users/u/Library/Caches/jan/p-1/scratch/s1"))
+ .with_pkg_cache(&pkg_cache(pkg, true));
+ let args = seatbelt_args(&p, &cfg());
+ let want = [
+ "/Users/u/Library/Caches/jan/p-1/scratch",
+ "/Users/u/Library/Caches/jan/p-1",
+ "/Users/u/Library/Caches/jan",
+ ];
+ let ancestors: Vec<&str> = args
+ .iter()
+ .filter_map(|a| a.strip_prefix("-DCACHE_ANCESTOR_"))
+ .map(|a| a.split_once('=').unwrap().1)
+ .collect();
+ assert_eq!(ancestors, want, "{args:?}");
+ let profile = &args[1];
+ let deny = profile.find("(deny file-read* (subpath (param \"CACHE_MASK_0\")))").unwrap();
+ for i in 0..want.len() {
+ let allow = format!("(allow file-read-metadata (literal (param \"CACHE_ANCESTOR_{i}\")))");
+ assert!(deny < profile.find(&allow).expect(profile), "{profile}");
+ }
+ }
+
+ /// Seatbelt grants the package cache by parameter and denies writes to
+ /// the cargo config copy after that grant; every parameter has its `-D`.
+ // Unix fixture paths: `Path::join` would add `\\` on Windows, which has
+ // neither backend.
+ #[cfg(unix)]
+ #[test]
+ fn seatbelt_grants_the_pkg_cache_and_denies_the_cargo_config() {
+ let pkg = "/Users/u/Library/Caches/jan/p-1/pkg";
+ let p = policy().with_pkg_cache(&pkg_cache(pkg, true));
+ let profile = seatbelt_policy(&p);
+ let allow = profile
+ .find("(allow file-write* (subpath (param \"PKG\")))")
+ .expect(&profile);
+ let deny = profile
+ .find("(deny file-write* (literal (param \"CARGO_CONFIG_0\")))")
+ .expect(&profile);
+ assert!(allow < deny, "{profile}");
+ let args = seatbelt_args(&p, &cfg());
+ assert!(args.iter().any(|a| *a == format!("-DPKG={pkg}")), "{args:?}");
+ assert!(
+ args.iter().any(|a| *a == format!("-DCARGO_CONFIG_0={pkg}/cargo/config.toml")),
+ "{args:?}"
+ );
+ assert!(!args[1].contains(pkg), "path must not be inlined");
+
+ let none = seatbelt_policy(&policy());
+ assert!(!none.contains("PKG") && !none.contains("CARGO_CONFIG"), "{none}");
}
#[test]
@@ -1614,7 +2107,8 @@ mod tests {
}
/// bubblewrap layers in order, so a read-only checkout under `/tmp` is
- /// bound read-only after the scratch takes `/tmp`, never shadowed by it.
+ /// bound read-only after the `/tmp` tmpfs and the scratch, never shadowed
+ /// by either.
#[test]
fn bwrap_binds_a_read_only_checkout_under_tmp_after_the_scratch() {
let ws = "/tmp/checkout";
@@ -1623,9 +2117,11 @@ mod tests {
.with_scratch_root(Path::new("/tmp/scratch-s1"))
.with_read_roots(vec![PathBuf::from("/tmp/worktrees")]);
let text = joined(&bwrap_args(&ro, &cfg()));
- let scratch = text.find("--bind /tmp/scratch-s1 /tmp").expect(&text);
- assert!(scratch < text.find(&format!("--ro-bind {ws} {ws}")).expect(&text), "{text}");
- assert!(scratch < text.find("--ro-bind /tmp/worktrees /tmp/worktrees").unwrap());
+ let tmp = text.find("--tmpfs /tmp").expect(&text);
+ let scratch = text.find("--bind /tmp/scratch-s1 /tmp/scratch-s1").expect(&text);
+ let checkout = text.find(&format!("--ro-bind {ws} {ws}")).expect(&text);
+ assert!(tmp < scratch && scratch < checkout, "{text}");
+ assert!(tmp < text.find("--ro-bind /tmp/worktrees /tmp/worktrees").unwrap());
assert!(!text.contains(&format!("--bind {ws} ")), "{text}");
}
@@ -1704,29 +2200,6 @@ mod tests {
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*)"));
@@ -1779,17 +2252,16 @@ mod tests {
}
/// 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.
+ /// is allowed to write, by its real path (the same on every backend).
#[test]
fn denial_hint_names_the_scratch_when_there_is_one() {
- let scratch = Path::new("/var/scratch/jan-agent-s1");
+ let scratch = Path::new("/home/u/.cache/jan/chat/scratch/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())),
+ hint.contains(&format!("scratch dir ({})", scratch.display())),
"got: {hint}"
);
+ assert!(!denial_hint(&policy()).contains("scratch dir"));
}
#[test]
@@ -1847,13 +2319,17 @@ 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");
- // Mirrors the bash handler: the temp env follows what the backend mounts.
- let tmp = scratch_env_path(backend(), &policy);
+ // Mirrors the bash handler: the env names the scratch and the package
+ // cache at their real paths.
+ let env = super::super::proc::SandboxEnv::new(
+ policy.scratch_root.as_deref(),
+ policy.pkg_cache.as_ref().map(|p| p.root.as_path()),
+ );
let child = super::super::proc::spawn(
&wrapped,
command,
ws,
- tmp.as_deref(),
+ Some(&env),
super::super::proc::ShellEnv::default(),
None,
)
@@ -1915,20 +2391,22 @@ mod enforcement_tests {
}
#[tokio::test]
- async fn scratch_persists_across_bash_calls_when_bound_over_tmp() {
+ async fn scratch_persists_across_bash_calls_at_its_real_path() {
require_backend!();
let ws = workspace();
- let scratch = ws.join("agent-scratch");
- std::fs::create_dir_all(&scratch).unwrap();
+ let scratch = workspace();
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;
+ // Write through `$TMPDIR` in the first call, then read it back in a
+ // second, separate sandboxed process: a scratch pad that outlives a
+ // single bash invocation.
+ let (ok, out) = run_policy(policy.clone(), &ws, "echo persistent > \"$TMPDIR/scratch.txt\"").await;
assert!(ok, "scratch write must succeed: {out}");
- let (ok, out) = run_policy(policy, &ws, "cat /tmp/scratch.txt").await;
+ let (ok, out) = run_policy(policy, &ws, "cat \"$TMPDIR/scratch.txt\"").await;
+ let on_host = std::fs::read_to_string(scratch.join("scratch.txt")).unwrap_or_default();
let _ = std::fs::remove_dir_all(&ws);
+ let _ = std::fs::remove_dir_all(&scratch);
+ assert_eq!(on_host.trim(), "persistent", "the file is at the same path on the host");
assert!(ok, "scratch read must succeed: {out}");
assert!(
out.contains("persistent"),
@@ -2065,6 +2543,125 @@ mod enforcement_tests {
assert!(!ok, "the write into the home must fail: {out}");
}
+ /// A folder for a fake Jan cache root outside `/tmp`, which every backend
+ /// hides or replaces on its own: a cache root there would be unreachable
+ /// whether or not the cache mask exists, and prove nothing about it. Under
+ /// the crate's `target/`, which `$HOME` read-only exposes like the real
+ /// `~/.cache`. `None` when that is under the temp dir too.
+ fn cache_base_outside_tmp() -> Option<PathBuf> {
+ let n = N.fetch_add(1, Ordering::SeqCst);
+ let dir = Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("target")
+ .join(format!("jan_jail_cache_{}_{}", std::process::id(), n));
+ if dir.starts_with(temp_dir()) || dir.starts_with("/tmp") {
+ return None;
+ }
+ std::fs::create_dir_all(&dir).ok()?;
+ Some(dir)
+ }
+
+ /// End to end on the real backend: the shell writes its package cache at
+ /// the real path, cannot change the user's cargo config there, and sees
+ /// no credentials; another project's cache is out of reach even with
+ /// `$HOME` readable (the CLI), which only the cache mask provides.
+ #[tokio::test]
+ async fn the_pkg_cache_is_writable_but_its_cargo_config_is_not() {
+ require_backend!();
+ let Some(base) = cache_base_outside_tmp() else {
+ eprintln!("skipping: no cache root outside the temp dir");
+ return;
+ };
+ let ws = workspace();
+ let host = base.join("host-cargo");
+ std::fs::create_dir_all(&host).unwrap();
+ std::fs::write(host.join("config.toml"), "# user config\n").unwrap();
+ std::fs::write(host.join("credentials.toml"), "token = \"SECRET\"\n").unwrap();
+ let mine = crate::workspace::prepare_pkg_cache_in(&base.join("jan/mine"), Some(&host))
+ .await
+ .unwrap();
+ let theirs = crate::workspace::prepare_pkg_cache_in(&base.join("jan/theirs"), None)
+ .await
+ .unwrap();
+ std::fs::write(theirs.root.join("other.txt"), "OTHER_PROJECT").unwrap();
+ let other = theirs.root.join("other.txt");
+ // Control: with `$HOME` readable and no package cache in force (so no
+ // mask), the other project's file is readable. Without this the
+ // denial below could come from anything but the mask.
+ let unmasked = Policy::new(&ws, false).with_home_readonly(true);
+ let (_, out) = run_policy(unmasked, &ws, &format!("cat {}", other.to_string_lossy())).await;
+ assert!(out.contains("OTHER_PROJECT"), "control: the cache root must be readable: {out}");
+ let policy = Policy::new(&ws, false).with_home_readonly(true).with_pkg_cache(&mine);
+
+ let (ok, out) = run_policy(
+ policy.clone(),
+ &ws,
+ "mkdir -p \"$CARGO_HOME/registry\" && echo cached > \"$CARGO_HOME/registry/x\" \
+ && mkdir -p \"$npm_config_cache\" && echo npm > \"$npm_config_cache/y\" && cat \"$CARGO_HOME/config.toml\"",
+ )
+ .await;
+ assert!(ok, "package cache writes must succeed: {out}");
+ assert!(out.contains("# user config"), "config must be readable: {out}");
+ let cached = mine.root.join("cargo/registry/x");
+ assert_eq!(std::fs::read_to_string(&cached).unwrap_or_default().trim(), "cached");
+
+ let (_, out) = run_policy(
+ policy.clone(),
+ &ws,
+ "echo '[build]' >> \"$CARGO_HOME/config.toml\"; chmod u+w \"$CARGO_HOME/config.toml\"; \
+ echo '[build]' >> \"$CARGO_HOME/config.toml\"; ls -A \"$CARGO_HOME\"",
+ )
+ .await;
+ let host_config = std::fs::read_to_string(host.join("config.toml")).unwrap();
+ let copy = std::fs::read_to_string(mine.root.join("cargo/config.toml")).unwrap();
+ assert_eq!(host_config, "# user config\n", "{out}");
+ if backend() == Backend::Bubblewrap {
+ assert_eq!(copy, "# user config\n", "the config must stay read-only: {out}");
+ }
+ assert!(!out.contains("credentials"), "no credentials in CARGO_HOME: {out}");
+
+ // Neither the legacy name nor a fresh cargo folder can carry a config
+ // of the shell's own.
+ let (_, out) = run_policy(
+ policy.clone(),
+ &ws,
+ "echo '[build]' > \"$CARGO_HOME/config\"; mv \"$CARGO_HOME\" \"$CARGO_HOME.moved\"; \
+ mkdir -p \"$CARGO_HOME\" && echo '[build]' > \"$CARGO_HOME/config.toml\"; \
+ cat \"$CARGO_HOME/config\" \"$CARGO_HOME/config.toml\"",
+ )
+ .await;
+ if backend() == Backend::Bubblewrap {
+ assert!(!out.contains("[build]"), "cargo read a planted config: {out}");
+ assert!(!mine.root.join("cargo.moved").exists(), "{out}");
+ let legacy = std::fs::read_to_string(mine.root.join("cargo/config")).unwrap_or_default();
+ assert!(legacy.is_empty(), "{legacy}: {out}");
+ }
+
+ let (ok, out) = run_policy(policy, &ws, &format!("cat {}", other.to_string_lossy())).await;
+ assert!(!ok && !out.contains("OTHER_PROJECT"), "another project's cache: {out}");
+
+ // A user with no cargo config gets an empty one, which lives under
+ // the masked cache root and must still mount (bubblewrap reads bind
+ // sources from the host's view).
+ let bare = Policy::new(&ws, false).with_home_readonly(true).with_pkg_cache(&theirs);
+ let (ok, out) = run_policy(bare, &ws, "cat \"$CARGO_HOME/config.toml\" && echo READ").await;
+ assert!(ok && out.contains("READ"), "empty config: {out}");
+
+ // A workspace holding the cache root (running in `$HOME`) still hides
+ // the other project's cache, and this run's own stays writable.
+ let around = Policy::new(&base, false).with_home_readonly(true).with_pkg_cache(&mine);
+ let (_, out) = run_policy(
+ around,
+ &base,
+ &format!("cat {}; echo mine > \"$CARGO_HOME/registry/z\"", other.to_string_lossy()),
+ )
+ .await;
+ let wrote = mine.root.join("cargo/registry/z").is_file();
+ let _ = std::fs::remove_dir_all(&ws);
+ let _ = std::fs::remove_dir_all(&base);
+ assert!(!out.contains("OTHER_PROJECT"), "workspace around the cache root: {out}");
+ assert!(wrote, "this run's cache must stay writable: {out}");
+ }
+
#[tokio::test]
async fn the_network_is_unreachable_by_default() {
require_backend!();
@@ -2092,7 +2689,7 @@ mod enforcement_tests {
assert!(!ok, "{out}");
let (ok, out) = run_policy(policy.clone(), &ws, "touch .git/index.lock").await;
assert!(!ok, "{out}");
- let (ok, out) = run_policy(policy, &ws, "cat kept.txt && echo s > /tmp/s.txt").await;
+ let (ok, out) = run_policy(policy, &ws, "cat kept.txt && echo s > \"$TMPDIR/s.txt\"").await;
let kept = std::fs::read_to_string(ws.join("kept.txt")).unwrap();
let scratched = scratch.join("s.txt").exists();
let _ = std::fs::remove_dir_all(&ws);
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.rs
index 919d4b003..c9a322bd0 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
@@ -129,10 +129,16 @@ pub struct ToolContext<'a> {
/// 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
+ /// [`crate::workspace::scratch_dir_in`] 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>,
+ /// The project's package cache, which the confined shell's package
+ /// managers write to (see [`crate::tools::proc::PKG_CACHE_ENV`]). Only on a
+ /// confined run (sandboxed, or a read-only root) with a filesystem project;
+ /// `None` keeps the host's caches (unconfined) or none at all (desktop
+ /// chat, which has no network).
+ pub pkg_cache: Option<&'a crate::workspace::PkgCache>,
/// Whether `bash` runs under OS confinement. On by default, and the desktop
/// keeps it that way: there, `bash` is either sandboxed or withheld.
///
@@ -249,6 +255,7 @@ impl std::fmt::Debug for ToolContext<'_> {
.field("hidden_root", &self.hidden_root)
.field("home_readonly", &self.home_readonly)
.field("scratch_root", &self.scratch_root)
+ .field("pkg_cache", &self.pkg_cache)
.field("sandbox", &self.sandbox)
.field("escalation", &self.escalation)
.field("on_output", &self.on_output.is_some())
@@ -408,6 +415,7 @@ impl<'a> ToolContext<'a> {
hidden_root: None,
home_readonly: false,
scratch_root: None,
+ pkg_cache: None,
sandbox: true,
escalation: false,
on_output: None,
@@ -429,11 +437,22 @@ impl<'a> ToolContext<'a> {
}
/// Make `project_root` read-only. See [`Self::workspace_readonly`].
+ /// Lifting it from an unsandboxed context drops the package cache, as
+ /// [`Self::with_sandbox`] does: the shell is no longer confined.
pub fn with_workspace_readonly(mut self, readonly: bool) -> Self {
self.workspace_readonly = readonly;
+ if !self.shell_confined() {
+ self.pkg_cache = None;
+ }
self
}
+ /// Whether `bash` runs confined: sandboxed, or in a read-only root, which
+ /// is never run without a sandbox whatever the surface chose.
+ pub fn shell_confined(&self) -> bool {
+ self.sandbox || self.workspace_readonly
+ }
+
/// Route the web tools to the host's chosen backend. See
/// [`Self::web_search`].
pub fn with_web_search(
@@ -615,8 +634,8 @@ impl<'a> ToolContext<'a> {
self
}
- /// Bind `scratch_root` over the sandbox's `/tmp` so scratch files survive
- /// across `bash` calls. See [`Self::scratch_root`].
+ /// Make `scratch_root` writable to the sandboxed shell at its real path so
+ /// scratch files survive across `bash` calls. See [`Self::scratch_root`].
/// Ignored when the sandbox is off, so the two builders commute (see
/// [`Self::with_sandbox`] for why an unconfined run has no scratch).
pub fn with_scratch_root(mut self, scratch_root: &'a Path) -> Self {
@@ -626,6 +645,19 @@ impl<'a> ToolContext<'a> {
self
}
+ /// Point the confined shell's package managers at `pkg`. See
+ /// [`Self::pkg_cache`]. Ignored when the shell runs unconfined. Unlike the
+ /// scratch it follows confinement rather than the sandbox setting: a
+ /// read-only root is confined with the sandbox off, and its read-only
+ /// `$HOME` leaves the host caches unwritable, so it needs one. Call after
+ /// [`Self::with_sandbox`] and [`Self::with_workspace_readonly`].
+ pub fn with_pkg_cache(mut self, pkg: Option<&'a crate::workspace::PkgCache>) -> Self {
+ if self.shell_confined() {
+ self.pkg_cache = pkg;
+ }
+ self
+ }
+
/// Mention escalation in sandbox denials. See [`Self::escalation`].
pub fn with_escalation(mut self, escalation: bool) -> Self {
self.escalation = escalation;
@@ -634,16 +666,23 @@ impl<'a> ToolContext<'a> {
/// Run `bash` under OS confinement (the default). See [`Self::sandbox`].
///
- /// Turning it off also drops the scratch: the scratch only makes sense as
- /// the thing bound over the sandbox's `/tmp`. Unconfined, the shell sees the
- /// real `/tmp`, and leaving the scratch set would have the filesystem tools
- /// still rewriting `/tmp/...` into a directory the shell never looks at --
- /// two tools disagreeing about what one path means.
+ /// Turning it off also drops the scratch: it is the sandbox's sanctioned
+ /// writable area, and unconfined the shell already writes wherever the
+ /// user can, with the host's own `TMPDIR`. Keeping it would only grant the
+ /// filesystem tools a directory outside the project for no reason.
+ ///
+ /// The package cache goes too unless the root is read-only: that shell
+ /// stays confined (see [`Self::shell_confined`]), which is also why an
+ /// escalated command there keeps it, while an escalated command anywhere
+ /// else runs with the host's own caches.
pub fn with_sandbox(mut self, sandbox: bool) -> Self {
self.sandbox = sandbox;
if !sandbox {
self.scratch_root = None;
}
+ if !self.shell_confined() {
+ self.pkg_cache = None;
+ }
self
}
}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs
index 93fb01f16..04dd1dfed 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs
@@ -58,6 +58,7 @@ pub struct MonitorSpec {
pub struct MonitorCtx {
pub project_root: PathBuf,
pub scratch_root: Option<PathBuf>,
+ pub pkg_cache: Option<crate::workspace::PkgCache>,
pub mask_root: Option<PathBuf>,
pub hidden_root: Option<PathBuf>,
pub read_roots: Vec<PathBuf>,
@@ -73,6 +74,7 @@ impl MonitorCtx {
Self {
project_root: ctx.project_root.to_path_buf(),
scratch_root: ctx.scratch_root.map(Path::to_path_buf),
+ pkg_cache: ctx.pkg_cache.cloned(),
mask_root: ctx.mask_root.map(Path::to_path_buf),
hidden_root: ctx.hidden_root.map(Path::to_path_buf),
read_roots: ctx.read_roots.to_vec(),
@@ -102,7 +104,7 @@ impl MonitorCtx {
if let Some(scratch) = &self.scratch_root {
ctx = ctx.with_scratch_root(scratch);
}
- ctx
+ ctx.with_pkg_cache(self.pkg_cache.as_ref())
}
}
@@ -503,14 +505,14 @@ fn match_update(monitor_id: &str, name: &str, content: &str) -> MonitorUpdate {
/// "not yet" and are retried on the next poll.
async fn eval_script(ctx: &MonitorCtx, script: &str) -> Option<String> {
let tool_ctx = ctx.as_tool_context();
- let (shell, sandbox_tmp, _policy) = crate::tools::handlers::confined_shell(&tool_ctx).ok()?;
+ let (shell, sandbox_env, _policy) = crate::tools::handlers::confined_shell(&tool_ctx).ok()?;
// A poll child is short-lived and re-spawned each interval; it is not tied
// to a session's Stop, so it registers in the process-wide bucket.
let mut child = crate::tools::proc::spawn(
&shell,
script,
&ctx.project_root,
- sandbox_tmp.as_deref(),
+ sandbox_env.as_ref(),
tool_ctx.shell_env(),
None,
)
@@ -612,6 +614,7 @@ mod tests {
MonitorCtx {
project_root: root.to_path_buf(),
scratch_root: None,
+ pkg_cache: None,
mask_root: None,
hidden_root: None,
read_roots: Vec::new(),
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/plugin_tools.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/plugin_tools.rs
index 4a9867c07..f80742ca1 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/plugin_tools.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/plugin_tools.rs
@@ -198,7 +198,7 @@ fn is_safe_name(name: &str) -> bool {
/// is always text the model can read, never a transport failure.
pub async fn execute(tool: &PluginTool, args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
let body = serde_json::to_string(args).unwrap_or_else(|_| "{}".to_string());
- let (shell, sandbox_tmp, _policy) = match crate::tools::handlers::confined_shell(ctx) {
+ let (shell, sandbox_env, _policy) = match crate::tools::handlers::confined_shell(ctx) {
Ok(parts) => parts,
Err(e) => return e,
};
@@ -206,7 +206,7 @@ pub async fn execute(tool: &PluginTool, args: &serde_json::Value, ctx: &ToolCont
&shell,
&tool.command,
ctx.project_root,
- sandbox_tmp.as_deref(),
+ sandbox_env.as_ref(),
ctx.shell_env(),
ctx.thread_id,
Some(&body),
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.rs
index 182ab8829..195cb994e 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
@@ -36,6 +36,9 @@ pub fn set_plugin_env(root: &Path, vars: BTreeMap<String, String>) {
pub fn is_reserved_env_key(key: &str) -> bool {
SANDBOX_ENV_ALLOW.contains(&key)
|| TEMP_ENV_KEYS.contains(&key)
+ // Case-blind: npm reads `NPM_CONFIG_CACHE` as readily as the lowercase
+ // spelling, and Windows env names have no case at all.
+ || PKG_CACHE_ENV.iter().any(|(name, _)| name.eq_ignore_ascii_case(key))
|| key.starts_with("LD_")
|| key.starts_with("DYLD_")
|| key.starts_with("SUDO_")
@@ -407,6 +410,75 @@ const SANDBOX_ENV_ALLOW: &[&str] = &[
/// All are pointed at the scratch together so no tool falls back to the host.
const TEMP_ENV_KEYS: &[&str] = &["TMPDIR", "TMP", "TEMP"];
+/// Where package managers keep their caches and homes in a sandboxed command:
+/// each name, and the folder under the project's package cache
+/// (`<cache>/jan/<slug>/pkg`, see [`crate::workspace::pkg_dir_in`]) it points
+/// at. Their defaults (`~/.cargo`, `~/.npm`, `~/.cache/...`, `~/go`,
+/// `~/.gradle`) sit in a `$HOME` the sandbox masks or makes read-only, so
+/// without these an ordinary build fails and the model escalates for it.
+/// Unconfined commands keep the host's own values: the user's real caches are
+/// never written from a sandbox, so a tampered download cannot reach a later
+/// unsandboxed build, and one project's cache never feeds another's.
+///
+/// pnpm: `PNPM_HOME` moves its store on every version (`$PNPM_HOME/store`);
+/// v11+ reads only `pnpm_config_*`, which also names the store and cache
+/// explicitly. `npm_config_store_dir` is left out: npm warns about it on every
+/// run as an unknown key.
+pub const PKG_CACHE_ENV: &[(&str, &str)] = &[
+ // XDG-aware tools (pip, uv, pnpm's cache, and many more) on Linux, where it
+ // is the standard. macOS and Windows tools do not read it.
+ #[cfg(target_os = "linux")]
+ ("XDG_CACHE_HOME", "xdg-cache"),
+ ("npm_config_cache", "npm"),
+ ("YARN_CACHE_FOLDER", "yarn-cache"),
+ ("YARN_GLOBAL_FOLDER", "yarn-global"),
+ ("COREPACK_HOME", "corepack"),
+ ("PNPM_HOME", "pnpm-home"),
+ ("pnpm_config_store_dir", "pnpm-store"),
+ ("pnpm_config_cache_dir", "pnpm-cache"),
+ ("PIP_CACHE_DIR", "pip"),
+ ("UV_CACHE_DIR", "uv"),
+ ("GOCACHE", "go-build"),
+ ("GOMODCACHE", "go-mod"),
+ ("GOPATH", "go-path"),
+ ("GRADLE_USER_HOME", "gradle"),
+ ("CCACHE_DIR", "ccache"),
+ ("SCCACHE_DIR", "sccache"),
+ ("DENO_DIR", "deno"),
+ ("BUN_INSTALL_CACHE_DIR", "bun-cache"),
+ // The whole `CARGO_HOME`, not just `registry/` and `git/`: cargo keeps its
+ // lock files at its top. See `workspace::prepare_pkg_cache` for what it
+ // holds of the user's own.
+ ("CARGO_HOME", crate::workspace::PKG_CARGO_HOME),
+];
+
+/// The env a confined command gets over the allowlist, naming folders its
+/// sandbox makes writable: the temp keys at the session scratch and
+/// [`PKG_CACHE_ENV`] under the project's package cache. Built only by the
+/// caller that also built the sandbox (`handlers::confined_shell`), so an
+/// unconfined spawn, which has none, keeps the host's values for all of them.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct SandboxEnv {
+ vars: Vec<(&'static str, PathBuf)>,
+}
+
+impl SandboxEnv {
+ pub fn new(scratch: Option<&Path>, pkg: Option<&Path>) -> Self {
+ let mut vars = Vec::new();
+ if let Some(scratch) = scratch {
+ vars.extend(TEMP_ENV_KEYS.iter().map(|key| (*key, scratch.to_path_buf())));
+ }
+ if let Some(pkg) = pkg {
+ vars.extend(PKG_CACHE_ENV.iter().map(|(key, dir)| (*key, pkg.join(dir))));
+ }
+ Self { vars }
+ }
+
+ pub fn vars(&self) -> &[(&'static str, PathBuf)] {
+ &self.vars
+ }
+}
+
/// Soft limits the sandboxed child runs under, each capped by the host's hard
/// limit. `NOFILE` and `FSIZE` are deliberately generous: toolchains (linkers,
/// node, cargo) routinely want tens of thousands of descriptors, and a debug
@@ -562,11 +634,11 @@ pub async fn spawn(
cfg: &ShellConfig,
command: &str,
cwd: &Path,
- scratch: Option<&Path>,
+ sandbox: Option<&SandboxEnv>,
env: ShellEnv<'_>,
thread: Option<&str>,
) -> std::io::Result<Child> {
- spawn_with_stdin(cfg, command, cwd, scratch, env, thread, None).await
+ spawn_with_stdin(cfg, command, cwd, sandbox, env, thread, None).await
}
/// `path` without the `\\?\` verbatim prefix `canonicalize` adds on Windows:
@@ -622,7 +694,7 @@ pub async fn spawn_with_stdin(
cfg: &ShellConfig,
command: &str,
cwd: &Path,
- scratch: Option<&Path>,
+ sandbox: Option<&SandboxEnv>,
env: ShellEnv<'_>,
thread: Option<&str>,
stdin_payload: Option<&str>,
@@ -658,15 +730,32 @@ pub async fn spawn_with_stdin(
cmd.envs(vars);
}
}
- // 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);
+ // Point the shell's temp env at the session scratch and its package caches
+ // at the project's, overriding the host values copied in above. Without
+ // this a command that writes through `mktemp`/`$TMPDIR` or downloads a
+ // dependency targets the host's dirs -- unreachable to the filesystem
+ // tools, and on the backends that confine by path, not writable at all.
+ // Every backend exposes both at their real paths, so those are the values.
+ if let Some(sandbox) = sandbox {
+ // A case variant copied in above (`NPM_CONFIG_CACHE` from the host,
+ // `Tmpdir` from `env_set`) would sit beside the exact name set here,
+ // and tools that read either spelling (npm) would get two answers.
+ // Only on Unix: Windows env names have no case, so the set below
+ // already replaces any spelling.
+ #[cfg(unix)]
+ {
+ let names: Vec<std::ffi::OsString> =
+ cmd.as_std().get_envs().map(|(name, _)| name.to_owned()).collect();
+ for name in names {
+ let Some(text) = name.to_str() else { continue };
+ let variant = |(key, _): &(&str, PathBuf)| key.eq_ignore_ascii_case(text) && *key != text;
+ if sandbox.vars().iter().any(variant) {
+ cmd.env_remove(&name);
+ }
+ }
+ }
+ for (key, dir) in sandbox.vars() {
+ cmd.env(key, dir);
}
}
cmd.current_dir(without_verbatim_prefix(cwd))
@@ -1024,6 +1113,85 @@ mod env_allowlist_tests {
);
}
}
+
+ /// Every package-manager name the issue lists is set, each to its own
+ /// folder inside the package cache, so no two tools share one and none
+ /// lands outside what the sandbox makes writable.
+ #[test]
+ fn every_pkg_cache_name_is_set_under_the_package_cache() {
+ let pkg = Path::new("/c/jan/p-1/pkg");
+ let env = SandboxEnv::new(None, Some(pkg));
+ let mut expected = vec![
+ "npm_config_cache", "YARN_CACHE_FOLDER", "YARN_GLOBAL_FOLDER", "COREPACK_HOME",
+ "PNPM_HOME", "pnpm_config_store_dir", "pnpm_config_cache_dir", "PIP_CACHE_DIR",
+ "UV_CACHE_DIR", "GOCACHE", "GOMODCACHE", "GOPATH", "GRADLE_USER_HOME",
+ "CCACHE_DIR", "SCCACHE_DIR", "DENO_DIR", "BUN_INSTALL_CACHE_DIR", "CARGO_HOME",
+ ];
+ if cfg!(target_os = "linux") {
+ expected.push("XDG_CACHE_HOME");
+ }
+ let names: Vec<&str> = env.vars().iter().map(|(k, _)| *k).collect();
+ for name in &expected {
+ assert!(names.contains(name), "{name} missing from {names:?}");
+ assert!(is_reserved_env_key(name), "{name} must be reserved");
+ }
+ assert_eq!(names.len(), expected.len(), "{names:?}");
+ let mut dirs: Vec<&PathBuf> = env.vars().iter().map(|(_, v)| v).collect();
+ for dir in &dirs {
+ assert_eq!(dir.parent(), Some(pkg), "{dir:?} is not directly under pkg/");
+ }
+ dirs.sort();
+ dirs.dedup();
+ assert_eq!(dirs.len(), expected.len(), "two tools share a folder");
+ let cargo = env.vars().iter().find(|(k, _)| *k == "CARGO_HOME").unwrap();
+ assert_eq!(cargo.1, pkg.join("cargo"));
+ }
+
+ /// A plugin must not redirect a sandboxed cache, in either spelling npm
+ /// accepts.
+ #[test]
+ fn pkg_cache_names_are_reserved_in_any_case() {
+ assert!(is_reserved_env_key("NPM_CONFIG_CACHE"));
+ assert!(is_reserved_env_key("cargo_home"));
+ assert!(!is_reserved_env_key("CARGO_TARGET_DIR"));
+ }
+
+ /// A host `NPM_CONFIG_CACHE` copied in by passthrough (or set) must not
+ /// sit beside the sandbox's `npm_config_cache`: npm reads both spellings,
+ /// so the shell would get two answers to one key. Any case variant of a
+ /// name the sandbox env sets is dropped; unconfined, it is kept.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn a_case_variant_of_a_sandbox_env_name_is_dropped() {
+ let pkg = std::env::temp_dir().join(format!("jan_proc_case_{}", std::process::id()));
+ let set = vec![
+ ("NPM_CONFIG_CACHE".to_string(), "/host/npm".to_string()),
+ ("Tmpdir".to_string(), "/host/tmp".to_string()),
+ ("KEEP_ME".to_string(), "yes".to_string()),
+ ];
+ let env = ShellEnv { passthrough: &[], set: &set };
+ let run = |sandbox: Option<SandboxEnv>| async move {
+ let child = spawn(shell(), "env", Path::new("/"), sandbox.as_ref(), env, None)
+ .await
+ .unwrap();
+ let out = child.wait_with_output().await.unwrap();
+ String::from_utf8_lossy(&out.stdout).into_owned()
+ };
+ let out = run(Some(SandboxEnv::new(Some(&pkg), Some(&pkg)))).await;
+ assert!(!out.contains("/host/"), "{out}");
+ assert!(out.contains("npm_config_cache=") && out.contains("KEEP_ME=yes"), "{out}");
+ let bare = run(None).await;
+ assert!(bare.contains("NPM_CONFIG_CACHE=/host/npm"), "{bare}");
+ }
+
+ /// No scratch and no package cache: nothing is overridden.
+ #[test]
+ fn an_empty_sandbox_env_sets_nothing() {
+ assert!(SandboxEnv::new(None, None).vars().is_empty());
+ let temp = SandboxEnv::new(Some(Path::new("/s")), None);
+ let names: Vec<&str> = temp.vars().iter().map(|(k, _)| *k).collect();
+ assert_eq!(names, TEMP_ENV_KEYS);
+ }
}
#[cfg(test)]
@@ -1280,7 +1448,7 @@ mod tests {
shell(),
"echo \"$TMPDIR $TMP $TEMP\"",
&tmp(),
- Some(&scratch),
+ Some(&SandboxEnv::new(Some(&scratch), None)),
ShellEnv::default(),
None,
)
@@ -1297,6 +1465,30 @@ mod tests {
let _ = std::fs::remove_dir_all(&scratch);
}
+ /// A spawn with a package cache names it; one without (unconfined, or an
+ /// escalated command) passes none of the redirect names through, so the
+ /// host's own caches and `CARGO_HOME` stand.
+ #[tokio::test]
+ async fn pkg_cache_env_is_set_only_for_a_sandbox_env() {
+ let probe = "echo \"${CARGO_HOME-unset} ${npm_config_cache-unset}\"";
+ let pkg = tmp().join("jan_proc_pkg_env");
+ let run = |env: Option<SandboxEnv>| async move {
+ let child = spawn(shell(), probe, &tmp(), env.as_ref(), ShellEnv::default(), None)
+ .await
+ .unwrap();
+ let pid = child.id().unwrap();
+ let out = child.wait_with_output().await.unwrap();
+ unregister(None, pid);
+ String::from_utf8_lossy(&out.stdout).trim().to_string()
+ };
+ let p = pkg.to_string_lossy();
+ assert_eq!(
+ run(Some(SandboxEnv::new(None, Some(&pkg)))).await,
+ format!("{p}/cargo {p}/npm")
+ );
+ assert_eq!(run(None).await, "unset unset");
+ }
+
/// With no scratch the shell keeps whatever the host allowlist passed
/// through, rather than being handed an empty temp dir.
#[tokio::test]
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.rs
index 4e4c10304..3be1b3c03 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
@@ -10,24 +10,6 @@ pub fn escapes_project(
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))?;
@@ -41,11 +23,11 @@ pub fn escapes_project(
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.
+ // every backend at this same real path, so a path landing in it is not a
+ // host escape even though it sits outside the project. Canonicalized, so
+ // a symlink the shell planted in the scratch cannot lead back out. 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));
@@ -131,23 +113,11 @@ pub fn escapes_write_roots(
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);
- }
- }
- }
+/// Resolve a tool-supplied path to its on-disk location: absolute paths as
+/// given, relative ones against the project. The scratch needs no mapping: the
+/// sandbox exposes it at its real path, so the shell and the tools already
+/// agree on its name.
+pub fn resolve_path(project_root: &Path, raw: &str) -> PathBuf {
if Path::new(raw).is_absolute() {
PathBuf::from(raw)
} else {
@@ -207,40 +177,11 @@ pub fn refuse_windows_name(raw: &str) -> Option<(String, &'static str)> {
})
}
-/// 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)
+ scratch.is_some_and(|s| lexical_normalize(path).starts_with(lexical_normalize(s)))
}
/// Resolve `.`/`..` without touching the filesystem, so a path is comparable to
@@ -261,46 +202,11 @@ pub fn lexical_normalize(path: &Path) -> PathBuf {
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;
- }
- // Match only the exact `/tmp` dir or a genuine `/tmp/...` descendant: a
- // raw string prefix would treat `/tmpx` and `/tmp-archive` as inside /tmp.
- if raw == "/tmp" {
- return Some(String::new());
- }
- Some(raw.strip_prefix("/tmp/")?.to_string())
-}
-
/// True iff a write to `raw` would land in a read-only `project_root`: inside
/// it and not in the session scratch (which a read-only subagent still writes
/// to). Fails closed: a path that cannot be resolved counts as inside.
pub fn in_read_only_root(project_root: &Path, scratch: Option<&Path>, raw: &str) -> bool {
- let target = resolve_path(project_root, scratch, raw);
+ let target = resolve_path(project_root, raw);
let Ok(resolved) = canonicalize_lenient(&target) else {
return true;
};
@@ -322,11 +228,11 @@ pub fn in_read_only_root(project_root: &Path, scratch: Option<&Path>, raw: &str)
/// One exception: a project that itself lives under `hidden` (a Jan worktree in
/// `~/.jan/worktrees/`) is the agent's working tree, so paths inside it stay
/// reachable. The home itself as the project grants nothing.
-pub fn in_hidden_root(project_root: &Path, scratch: Option<&Path>, hidden: &Path, raw: &str) -> bool {
+pub fn in_hidden_root(project_root: &Path, hidden: &Path, raw: &str) -> bool {
let Ok(hidden) = canonicalize_lenient(hidden) else {
return false;
};
- let Ok(resolved) = canonicalize_lenient(&resolve_path(project_root, scratch, raw)) else {
+ let Ok(resolved) = canonicalize_lenient(&resolve_path(project_root, raw)) else {
return false;
};
if !resolved.starts_with(&hidden) {
@@ -357,16 +263,11 @@ pub fn hidden_tokens(hidden: &Path, command: &str) -> Vec<String> {
/// True iff `raw` resolves inside one of `roots` (canonicalized attached
/// folders). Relative paths belong to the project, never to a root.
-pub fn in_attached_root(
- project_root: &Path,
- scratch: Option<&Path>,
- roots: &[PathBuf],
- raw: &str,
-) -> bool {
+pub fn in_attached_root(project_root: &Path, roots: &[PathBuf], raw: &str) -> bool {
if roots.is_empty() || !Path::new(raw).is_absolute() {
return false;
}
- let Ok(resolved) = canonicalize_lenient(&resolve_path(project_root, scratch, raw)) else {
+ let Ok(resolved) = canonicalize_lenient(&resolve_path(project_root, raw)) else {
return false;
};
roots
@@ -609,9 +510,9 @@ 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.
+ /// A test dir that is *not* under the host temp dir, as the real scratch
+ /// (in the OS cache dir) is not, so a `/tmp` path can be told apart from
+ /// it. 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"))
@@ -677,36 +578,27 @@ 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.
+ /// Nothing is mounted over `/tmp` any more, so a `/tmp/...` path is a
+ /// plain host path: outside the project and the scratch it is an escape,
+ /// and it resolves to itself rather than into the scratch.
#[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.
+ fn tmp_is_a_plain_host_path_even_with_a_scratch() {
+ let root = unique_root_outside_tmp();
+ let scratch = unique_root_outside_tmp();
assert_eq!(
escapes_project(&root, Some(&scratch), "/tmp/ok.txt"),
- Ok(false)
+ Ok(true),
+ "the host /tmp is not the scratch"
);
+ assert_eq!(resolve_path(&root, "/tmp/a.txt"), Path::new("/tmp/a.txt"));
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.
+ /// The scratch, reached by its real path, is the agent's own area on
+ /// every platform, so it must not read as an escape. The scratch sits
+ /// outside the host temp dir, as the real one (in the OS cache dir) does.
#[test]
fn real_scratch_path_is_not_an_escape() {
let root = unique_root();
@@ -737,8 +629,8 @@ mod tests {
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.
+ /// The scratch check resolves symlinks: the shell can plant one inside
+ /// the scratch, and a link is a single component that resolves elsewhere.
#[cfg(unix)]
#[test]
fn real_scratch_path_symlink_cannot_escape() {
@@ -757,39 +649,21 @@ mod tests {
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.
+ /// `in_scratch` is lexical and component-wise: a sibling that merely
+ /// shares the scratch's name as a prefix is not inside it.
#[test]
- fn scratch_is_displayed_under_the_name_the_shell_can_use() {
+ fn in_scratch_is_component_wise() {
let scratch = PathBuf::from(if cfg!(windows) {
- r"C:\Temp\jan-agent-s1"
+ r"C:\cache\jan\chat\scratch\s1"
} else {
- "/var/scratch/jan-agent-s1"
+ "/cache/jan/chat/scratch/s1"
});
let file = scratch.join("out.txt");
assert!(in_scratch(Some(&scratch), &file));
+ assert!(in_scratch(Some(&scratch), &scratch));
+ assert!(!in_scratch(Some(&scratch), &scratch.with_file_name("s10").join("x")));
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 only lexically normalized, which on
- // Windows also spells it with the native separator.
- let other = PathBuf::from("/elsewhere/out.txt");
- assert_eq!(
- scratch_display_path(Some(&scratch), &other),
- if cfg!(windows) {
- r"\elsewhere\out.txt"
- } else {
- "/elsewhere/out.txt"
- }
- );
}
#[cfg(unix)]
@@ -909,19 +783,6 @@ mod tests {
let _ = std::fs::remove_dir_all(&scratch);
}
- /// `/tmpx` and `/tmp-archive` are not descendants of `/tmp` and must not be
- /// silently redirected into the scratch. Unix only: the remap exists only
- /// where a sandbox mounts the scratch over `/tmp`, and on Windows `/tmp` is
- /// not an absolute path at all.
- #[cfg(unix)]
- #[test]
- fn tmp_lookalikes_are_not_remapped() {
- assert_eq!(tmp_relative("/tmp"), Some(String::new()));
- assert_eq!(tmp_relative("/tmp/"), Some(String::new()));
- assert_eq!(tmp_relative("/tmp/a.txt"), Some("a.txt".to_string()));
- assert_eq!(tmp_relative("/tmpx"), None);
- assert_eq!(tmp_relative("/tmp-archive/a.txt"), None);
- }
// ---- read-only attached roots -------------------------------------------
#[test]
@@ -1043,15 +904,15 @@ mod tests {
let jan = home.join(".jan");
std::fs::create_dir_all(jan.join("projects/p-1/memory")).unwrap();
std::fs::write(jan.join("config.toml"), b"k").unwrap();
- assert!(in_hidden_root(&home, None, &jan, ".jan/config.toml"));
- assert!(in_hidden_root(&home, None, &jan, "./.jan/../.jan/config.toml"));
- assert!(in_hidden_root(&home, None, &jan, jan.join("config.toml").to_str().unwrap()));
- assert!(in_hidden_root(&home, None, &jan, ".jan"));
- assert!(in_hidden_root(&home, None, &jan, ".jan/projects/p-1/agent.toml"));
+ assert!(in_hidden_root(&home, &jan, ".jan/config.toml"));
+ assert!(in_hidden_root(&home, &jan, "./.jan/../.jan/config.toml"));
+ assert!(in_hidden_root(&home, &jan, jan.join("config.toml").to_str().unwrap()));
+ assert!(in_hidden_root(&home, &jan, ".jan"));
+ assert!(in_hidden_root(&home, &jan, ".jan/projects/p-1/agent.toml"));
// Not yet existing files are hidden too, so a write cannot create one.
- assert!(in_hidden_root(&home, None, &jan, ".jan/hooks.toml"));
- assert!(!in_hidden_root(&home, None, &jan, "JAN.md"));
- assert!(!in_hidden_root(&home, None, &jan, ".janitor"));
+ assert!(in_hidden_root(&home, &jan, ".jan/hooks.toml"));
+ assert!(!in_hidden_root(&home, &jan, "JAN.md"));
+ assert!(!in_hidden_root(&home, &jan, ".janitor"));
let _ = std::fs::remove_dir_all(&home);
}
@@ -1064,22 +925,17 @@ mod tests {
let wt = jan.join("worktrees/repo-1/feature");
std::fs::create_dir_all(&wt).unwrap();
std::fs::write(jan.join("config.toml"), b"k").unwrap();
- assert!(!in_hidden_root(&wt, None, &jan, "src/main.rs"));
- assert!(!in_hidden_root(&wt, None, &jan, wt.to_str().unwrap()));
- assert!(in_hidden_root(&wt, None, &jan, "../../../config.toml"));
- assert!(in_hidden_root(&wt, None, &jan, jan.join("config.toml").to_str().unwrap()));
+ assert!(!in_hidden_root(&wt, &jan, "src/main.rs"));
+ assert!(!in_hidden_root(&wt, &jan, wt.to_str().unwrap()));
+ assert!(in_hidden_root(&wt, &jan, "../../../config.toml"));
+ assert!(in_hidden_root(&wt, &jan, jan.join("config.toml").to_str().unwrap()));
let _ = std::fs::remove_dir_all(&home);
}
- fn command_touches_hidden_root(
- project: &Path,
- scratch: Option<&Path>,
- hidden: &Path,
- cmd: &str,
- ) -> bool {
+ fn command_touches_hidden_root(project: &Path, hidden: &Path, cmd: &str) -> bool {
hidden_tokens(hidden, cmd)
.iter()
- .any(|t| in_hidden_root(project, scratch, hidden, t))
+ .any(|t| in_hidden_root(project, hidden, t))
}
#[test]
@@ -1097,12 +953,12 @@ mod tests {
"cat ../.jan/config.toml",
"F=~/.jan/config.toml",
] {
- assert!(command_touches_hidden_root(&project, None, &jan, cmd), "{cmd}");
+ assert!(command_touches_hidden_root(&project, &jan, cmd), "{cmd}");
}
let abs = format!("cat '{}'", jan.join("config.toml").display());
- assert!(command_touches_hidden_root(&project, None, &jan, &abs));
- assert!(!command_touches_hidden_root(&project, None, &jan, "cat ~/.bashrc"));
- assert!(!command_touches_hidden_root(&project, None, &jan, "ls -la src"));
+ assert!(command_touches_hidden_root(&project, &jan, &abs));
+ assert!(!command_touches_hidden_root(&project, &jan, "cat ~/.bashrc"));
+ assert!(!command_touches_hidden_root(&project, &jan, "ls -la src"));
let _ = std::fs::remove_dir_all(&home);
}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs
index 016116dfe..2d85e3671 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs
@@ -234,6 +234,94 @@ pub fn project_meta(store: &Path) -> Option<String> {
value.get("path")?.as_str().map(str::to_string)
}
+/// The folder under the Jan cache root for sessions with no filesystem
+/// project: desktop chat threads and Cowork sessions.
+const CHAT_CACHE: &str = "chat";
+
+/// `<project cache>/scratch`, the parent of every session scratch.
+const SCRATCH: &str = "scratch";
+
+/// The Jan cache root, `<OS cache dir>/jan` (`$XDG_CACHE_HOME` or `~/.cache`
+/// on Linux, `~/Library/Caches` on macOS, `%LOCALAPPDATA%` on Windows).
+///
+/// Not the system temp dir: a scratch there is invisible at its own path to
+/// anything outside a sandbox that mounts it elsewhere, and per-project
+/// siblings here keep one project's files out of another's. With no cache dir
+/// at all it falls back to the temp dir so the scratch still works (see
+/// [`temp_cache_root_in`]).
+///
+/// Test builds of this crate resolve a per-process temp directory instead, so
+/// no test writes into the developer's real cache.
+pub fn jan_cache_root() -> PathBuf {
+ #[cfg(test)]
+ {
+ std::env::temp_dir().join(format!("jan-test-cache-{}", std::process::id()))
+ }
+ #[cfg(not(test))]
+ {
+ match dirs::cache_dir() {
+ Some(cache) => cache.join("jan"),
+ None => temp_cache_root_in(&std::env::temp_dir()),
+ }
+ }
+}
+
+/// The cache root under the temp dir `temp`, for a machine with no OS cache
+/// dir (no `HOME`). A shared `/tmp` is writable by every local user, so a
+/// fixed `jan` there could have been made by another user, who would then
+/// see every slug and could swap folders under it. Named per user instead
+/// (`jan-<uid>`), and a name already taken by anything but a directory this
+/// user owns is passed over for the next one. A name planted between this
+/// check and its creation is caught there: [`ensure_scratch_dir_path`]
+/// refuses a directory this user does not own, the root and every other
+/// folder it creates on the way included. Windows keeps a plain `jan`:
+/// its temp dir is already per user.
+pub fn temp_cache_root_in(temp: &Path) -> PathBuf {
+ #[cfg(unix)]
+ {
+ let base = format!("jan-{}", nix::unistd::getuid());
+ let names = std::iter::once(base.clone()).chain((1..16).map(|n| format!("{base}-{n}")));
+ let mut last = temp.join(&base);
+ for name in names {
+ last = temp.join(name);
+ match std::fs::symlink_metadata(&last) {
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return last,
+ Ok(meta) if meta.is_dir() && owned_by_me(&meta) => return last,
+ _ => {}
+ }
+ }
+ // Every candidate taken: the last one, which the ownership check at
+ // creation refuses, so the scratch fails closed.
+ last
+ }
+ #[cfg(not(unix))]
+ {
+ temp.join("jan")
+ }
+}
+
+/// Whether `meta` (from `symlink_metadata`) belongs to this process's user.
+#[cfg(unix)]
+fn owned_by_me(meta: &std::fs::Metadata) -> bool {
+ use std::os::unix::fs::MetadataExt;
+ meta.uid() == nix::unistd::getuid().as_raw()
+}
+
+/// A project's folder under `cache_root`: `<cache_root>/<slug>`, with the
+/// same slug as its store (`~/.jan/projects/<slug>`), so the two always name
+/// one project the same way. `<cache_root>/chat` with no project.
+pub fn project_cache_dir_in(cache_root: &Path, project_root: Option<&Path>) -> PathBuf {
+ match project_root {
+ Some(root) => cache_root.join(path_slug(&project_key(root))),
+ None => cache_root.join(CHAT_CACHE),
+ }
+}
+
+/// [`project_cache_dir_in`] under the real [`jan_cache_root`].
+pub fn project_cache_dir(project_root: Option<&Path>) -> PathBuf {
+ project_cache_dir_in(&jan_cache_root(), project_root)
+}
+
/// Where a project kept its store before the move: `<project_root>/.jan/agent`.
pub fn legacy_project_store(project_root: &Path) -> PathBuf {
project_root.join(LEGACY_DIR).join("agent")
@@ -491,38 +579,48 @@ pub fn validate_write_root(
Ok(())
}
-/// 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.
+/// The session-scoped scratch directory: `<project cache>/scratch/<session>`,
+/// where `<project cache>` is [`project_cache_dir_in`] (`<cache>/jan/<slug>`,
+/// or `<cache>/jan/chat` for a desktop thread). `bash` scratch files persist
+/// there across calls for one session and the filesystem tools may write it.
///
-/// 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.
+/// Every backend exposes it at this same real path (bubblewrap binds it onto
+/// itself, Seatbelt grants it by rule, AppContainer by ACE), and
+/// `TMPDIR`/`TMP`/`TEMP` name it too. One spelling works inside the sandbox,
+/// in the filesystem tools and in an escalated command that runs unconfined;
+/// a scratch mounted somewhere else inside the sandbox would not exist at that
+/// name outside it.
///
/// Pure path arithmetic: `session` is not checked here. Anything that reaches
-/// the filesystem with an id from outside goes through [`ensure_scratch_dir`] or
-/// [`remove_scratch_dir`] / [`trash_scratch_dir`], which accept only a valid
+/// the filesystem with an id from outside goes through [`ensure_scratch_dir`],
+/// [`remove_scratch_dir`] or [`trash_scratch_dir`], which accept only a valid
/// [`thread_segment`].
-pub fn scratch_dir(session: &str) -> PathBuf {
- std::env::temp_dir().join(format!("jan-agent-{session}"))
+pub fn scratch_dir_in(project_cache: &Path, session: &str) -> PathBuf {
+ project_cache.join(SCRATCH).join(session)
}
-/// [`scratch_dir`] for an id that must first pass [`thread_segment`], so a
-/// separator or `..` in it can never move the scratch out of `jan-agent-*`.
-fn checked_scratch_dir(session: &str) -> Result<PathBuf, String> {
- Ok(scratch_dir(&thread_segment(session)?))
+/// [`scratch_dir_in`] for an id that must first pass [`thread_segment`], so a
+/// separator or a parent-dir component in it can never move the scratch out
+/// of `scratch/`.
+fn checked_scratch_dir(project_cache: &Path, session: &str) -> Result<PathBuf, String> {
+ Ok(scratch_dir_in(project_cache, &thread_segment(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> {
- ensure_scratch_dir_path(&checked_scratch_dir(session)?).await
+/// A desktop thread's scratch, `<cache>/jan/chat/scratch/<thread>`, checked.
+fn thread_scratch_dir(thread_id: &str) -> Result<PathBuf, String> {
+ checked_scratch_dir(&project_cache_dir(None), thread_id)
+}
+
+/// Create a desktop thread's scratch (idempotent) and return it.
+///
+/// Always under `<cache>/jan/chat`: a desktop thread has no filesystem
+/// project (desktop projects are UI folders), and every command that reaches
+/// a thread's scratch (subagent results, the blackboard, monitors, tool
+/// calls, thread delete) knows only the thread id, so this is the one place
+/// they all agree on. Must exist before a sandbox binds it. Thread deletion
+/// owns its teardown.
+pub async fn ensure_scratch_dir(thread_id: &str) -> Result<PathBuf, String> {
+ ensure_scratch_dir_path(&thread_scratch_dir(thread_id)?).await
}
/// Create a scratch directory at an explicit path, hardening it against a
@@ -530,13 +628,21 @@ pub async fn ensure_scratch_dir(session: &str) -> Result<PathBuf, String> {
/// attacker-selected directory as its sanctioned scratch. Refuses (fail
/// closed) when the target already exists as a symlink or is not a real
/// directory, and applies restrictive 0700 permissions on Unix so no other
-/// local user can read the session's scratch files. `create_dir` (not
-/// `create_dir_all`) is used so the final component is created directly and a
-/// parent symlink cannot redirect it.
+/// local user can read the session's scratch files. Missing parents are
+/// created one at a time, owner-only too: the cache root may be the temp-dir
+/// fallback, where a world-readable `jan/` would list every project's slug.
+/// The final component is made with a plain create (never "all") and
+/// re-checked, so a parent symlink cannot redirect it unnoticed. On Unix it
+/// must also belong to this user: one another user made (a shared temp dir)
+/// is theirs to read and swap, whatever its mode.
pub async fn ensure_scratch_dir_path(dir: &Path) -> Result<PathBuf, String> {
+ #[cfg(unix)]
+ let mine = owned_by_me;
+ #[cfg(not(unix))]
+ let mine = |_: &std::fs::Metadata| true;
match tokio::fs::symlink_metadata(dir).await {
Ok(meta) => {
- if !meta.file_type().is_symlink() && meta.is_dir() {
+ if !meta.file_type().is_symlink() && meta.is_dir() && mine(&meta) {
// Already a real directory; keep it.
} else {
return Err(format!(
@@ -547,14 +653,11 @@ pub async fn ensure_scratch_dir_path(dir: &Path) -> Result<PathBuf, String> {
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
if let Some(parent) = dir.parent() {
- tokio::fs::create_dir_all(parent)
- .await
- .map_err(|e| format!("ERROR: {e}"))?;
+ create_private_dirs(parent).await?;
}
- // `create_dir` (not `create_dir_all`) so the final component is made
- // directly and a parent symlink cannot redirect it. A concurrent
- // creator is fine: re-verify the existing node is a real directory.
- if let Err(e) = tokio::fs::create_dir(dir).await {
+ // A concurrent creator is fine: re-verify the existing node is a
+ // real directory.
+ if let Err(e) = private_dir_builder().create(dir).await {
if e.kind() != std::io::ErrorKind::AlreadyExists {
return Err(format!("ERROR: {e}"));
}
@@ -562,7 +665,7 @@ pub async fn ensure_scratch_dir_path(dir: &Path) -> Result<PathBuf, String> {
// Re-verify after creation: a concurrent swap could have replaced
// the freshly made directory with a symlink.
match tokio::fs::symlink_metadata(dir).await {
- Ok(meta) if !meta.file_type().is_symlink() && meta.is_dir() => {}
+ Ok(meta) if !meta.file_type().is_symlink() && meta.is_dir() && mine(&meta) => {}
_ => {
return Err(format!(
"ERROR: scratch path {:?} is not a real directory",
@@ -581,76 +684,562 @@ pub async fn ensure_scratch_dir_path(dir: &Path) -> Result<PathBuf, String> {
Ok(dir.to_path_buf())
}
-/// How long a scratch directory may sit untouched before the startup sweep
-/// treats it as abandoned. Age-based rather than "remove every scratch at
-/// startup" so a second Jan instance cannot wipe the first one's live scratch.
-const SCRATCH_STALE_AFTER: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);
+/// Prefix of a scratch's lease file, `scratch/.lease-<session>`, beside the
+/// scratch rather than in it: the sandbox can write the scratch but not its
+/// parent, so a command cannot remove or lock its own lease. The leading dot
+/// keeps it from ever reading as a session id.
+const SCRATCH_LEASE_PREFIX: &str = ".lease-";
+
+/// A run's hold on its scratch, which the startup sweep of every Jan process
+/// respects: dropping it releases the lock.
+#[derive(Debug)]
+pub struct ScratchClaim {
+ _lease: Option<std::fs::File>,
+}
-/// Delete abandoned scratch directories in the host temp dir, returning how many
-/// were removed.
+/// The lease file for the scratch at `dir`.
+fn lease_path(dir: &Path) -> Option<PathBuf> {
+ let name = dir.file_name()?.to_str()?;
+ Some(dir.with_file_name(format!("{SCRATCH_LEASE_PREFIX}{name}")))
+}
+
+/// Open (creating it owner-only) the lease file at `path`, never through a
+/// symlink planted there.
+fn open_lease(path: &Path) -> Option<std::fs::File> {
+ if std::fs::symlink_metadata(path).is_ok_and(|m| !m.is_file()) {
+ return None;
+ }
+ let mut open = std::fs::OpenOptions::new();
+ open.read(true).write(true).create(true).truncate(false);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ open.mode(0o600).custom_flags(nix::fcntl::OFlag::O_NOFOLLOW.bits());
+ }
+ open.open(path).ok()
+}
+
+/// Create the scratch at `dir` ([`ensure_scratch_dir_path`]) and claim it for
+/// a run, so no Jan process's startup sweep deletes it while the run is live.
+///
+/// The keep list a sweep is given names only its own process's sessions, and
+/// a scratch's own mtime does not change when files are written in its
+/// subfolders, so another CLI/TUI session working for a week would otherwise
+/// look abandoned. Two signals, because each covers what the other cannot:
+/// - a shared advisory lock on the scratch's lease file (flock/LockFileEx via
+/// `fs4`, already used for the memory store), held until the claim drops;
+/// the OS releases it when the process dies, so a crashed session leaves
+/// nothing that looks live. Shared, so a run's subagents can hold it too.
+/// - the scratch's mtime, set to now, so an interactive session idle between
+/// turns (no claim held) still reads as recently used for a week.
+///
+/// The lock is taken before the scratch is made or touched, and the sweep
+/// re-reads the mtime after taking it exclusively, so a sweep can never
+/// delete a scratch claimed while it was deciding. Both are best effort: a
+/// filesystem without locks or times still gets its scratch.
+pub async fn claim_scratch_dir(dir: &Path) -> Result<ScratchClaim, String> {
+ if let Some(parent) = dir.parent() {
+ create_private_dirs(parent).await?;
+ }
+ // Blocking: waits out a sweep deleting a stale scratch of the same name.
+ let lease = match lease_path(dir) {
+ Some(path) => tokio::task::spawn_blocking(move || lock_lease_shared(&path))
+ .await
+ .ok()
+ .flatten(),
+ None => None,
+ };
+ ensure_scratch_dir_path(dir).await?;
+ touch_dir(dir);
+ Ok(ScratchClaim { _lease: lease })
+}
+
+/// The lease at `path`, share-locked. A sweep unlinks a lease once it has
+/// deleted the scratch, so a claim that waited behind it may hold a lock on a
+/// file no longer there; it then retries on the one at the path now.
+fn lock_lease_shared(path: &Path) -> Option<std::fs::File> {
+ for _ in 0..3 {
+ let file = open_lease(path)?;
+ fs4::FileExt::lock_shared(&file).ok()?;
+ if std::fs::symlink_metadata(path).is_ok() {
+ return Some(file);
+ }
+ }
+ None
+}
+
+/// The lease at `path`, exclusively locked without waiting, for a sweep about
+/// to delete its scratch. `Err` while a live run holds it; `Ok(None)` when it
+/// cannot be locked at all (no file, a filesystem without locks), which
+/// leaves the mtime as the only signal, as before leases existed.
+fn try_lock_lease(path: &Path) -> Result<Option<std::fs::File>, ()> {
+ if std::fs::symlink_metadata(path).is_err() {
+ return Ok(None);
+ }
+ let Some(file) = open_lease(path) else {
+ return Ok(None);
+ };
+ match fs4::FileExt::try_lock(&file) {
+ Ok(()) => Ok(Some(file)),
+ Err(fs4::TryLockError::WouldBlock) => Err(()),
+ Err(fs4::TryLockError::Error(_)) => Ok(None),
+ }
+}
+
+/// Set `dir`'s mtime to now, ignoring failure (see [`claim_scratch_dir`]).
+fn touch_dir(dir: &Path) {
+ let mut open = std::fs::OpenOptions::new();
+ open.read(true);
+ // Windows opens a directory only with backup semantics
+ // (FILE_FLAG_BACKUP_SEMANTICS), and setting its times needs write access.
+ #[cfg(windows)]
+ {
+ use std::os::windows::fs::OpenOptionsExt;
+ open.write(true).custom_flags(0x0200_0000);
+ }
+ if let Ok(file) = open.open(dir) {
+ let _ = file.set_modified(std::time::SystemTime::now());
+ }
+}
+
+/// A builder for directories only their owner may enter (Unix; elsewhere the
+/// profile directory's inherited ACL already is).
+#[cfg(unix)]
+fn private_dir_builder() -> tokio::fs::DirBuilder {
+ let mut builder = tokio::fs::DirBuilder::new();
+ builder.mode(0o700);
+ builder
+}
+
+#[cfg(not(unix))]
+fn private_dir_builder() -> tokio::fs::DirBuilder {
+ tokio::fs::DirBuilder::new()
+}
+
+/// Create `dir` and any missing ancestors owner-only, leaving ancestors that
+/// already exist (`~/.cache` itself) exactly as they are.
+async fn create_private_dirs(dir: &Path) -> Result<(), String> {
+ #[cfg(unix)]
+ let trusted = |_: &Path, meta: &std::fs::Metadata| {
+ use std::os::unix::fs::MetadataExt;
+ owned_by_me(meta) || meta.uid() == 0
+ };
+ #[cfg(not(unix))]
+ let trusted = |_: &Path, _: &std::fs::Metadata| true;
+ #[cfg(unix)]
+ let mine = |_: &Path, meta: &std::fs::Metadata| owned_by_me(meta);
+ #[cfg(not(unix))]
+ let mine = |_: &Path, _: &std::fs::Metadata| true;
+ create_private_dirs_owned(dir, trusted, mine).await
+}
+
+/// [`create_private_dirs`] with its ownership tests. In a shared temp dir
+/// another user can plant `/tmp/jan-<uid>` (before the walk, or between it
+/// and the create) and would then own, and could swap, everything under it.
+/// So the nearest ancestor that already exists must belong to a `trusted`
+/// owner (this user, or root for `/tmp` and `/home` themselves), and each
+/// ancestor this call had to create must be a real directory that is `mine`,
+/// including one that turned out to exist already.
+async fn create_private_dirs_owned(
+ dir: &Path,
+ trusted: impl Fn(&Path, &std::fs::Metadata) -> bool,
+ mine: impl Fn(&Path, &std::fs::Metadata) -> bool,
+) -> Result<(), String> {
+ let mut missing = Vec::new();
+ for ancestor in dir.ancestors() {
+ match tokio::fs::symlink_metadata(ancestor).await {
+ Ok(meta) if trusted(ancestor, &meta) => break,
+ Ok(_) => {
+ return Err(format!(
+ "ERROR: scratch path {:?} belongs to another user",
+ ancestor
+ ))
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => missing.push(ancestor),
+ Err(e) => return Err(format!("ERROR: {e}")),
+ }
+ }
+ for ancestor in missing.into_iter().rev() {
+ if let Err(e) = private_dir_builder().create(ancestor).await {
+ if e.kind() != std::io::ErrorKind::AlreadyExists {
+ return Err(format!("ERROR: {e}"));
+ }
+ }
+ match tokio::fs::symlink_metadata(ancestor).await {
+ Ok(meta) if !meta.file_type().is_symlink() && meta.is_dir() && mine(ancestor, &meta) => {}
+ _ => {
+ return Err(format!(
+ "ERROR: scratch path {:?} is not a real directory",
+ ancestor
+ ))
+ }
+ }
+ }
+ Ok(())
+}
+
+/// `<project cache>/pkg`, the project's package cache.
+const PKG: &str = "pkg";
+
+/// `CARGO_HOME` inside the package cache.
+pub const PKG_CARGO_HOME: &str = "cargo";
+
+/// A project's package cache, `<cache>/jan/<slug>/pkg`. Only for a project:
+/// desktop chat has no network to fill one.
+pub fn pkg_dir_in(project_cache: &Path) -> PathBuf {
+ project_cache.join(PKG)
+}
+
+/// A prepared package cache: the folder a sandboxed command may write and
+/// whose subfolders its package-manager env names (`proc::PKG_CACHE_ENV`),
+/// plus the cargo config offered in it. `cargo_config` is `None` only for a
+/// hand-built cache (tests); [`prepare_pkg_cache_in`] always offers one.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct PkgCache {
+ pub root: PathBuf,
+ pub cargo_config: Option<CargoConfig>,
+}
+
+/// The cargo config offered read-only at `<CARGO_HOME>/config.toml`: the
+/// user's, or an empty one when they have none, so the name is always taken
+/// by a read-only file rather than left free for a sandbox to plant.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct CargoConfig {
+ /// The source: `config.toml`, or legacy `config`, in the host's
+ /// `CARGO_HOME`, or an empty file in the project's cache folder (outside
+ /// the package cache, so no sandbox can write it). Bubblewrap binds it
+ /// read-only over [`Self::copy`] and over [`Self::legacy`].
+ pub host: PathBuf,
+ /// `<pkg>/cargo/config.toml`. A read-only copy made at session start,
+ /// which is what Seatbelt and AppContainer expose (they cannot mount), and
+ /// bubblewrap's mount point.
+ pub copy: PathBuf,
+}
+
+impl CargoConfig {
+ /// `<pkg>/cargo/config`, the legacy name cargo prefers over
+ /// `config.toml` when both exist, so it must not be writable either.
+ pub fn legacy(&self) -> PathBuf {
+ self.copy.with_file_name("config")
+ }
+}
+
+/// The empty stand-in config's name in the project's cache folder.
+const EMPTY_CARGO_CONFIG: &str = "cargo-config-empty.toml";
+
+/// The host's cargo config: `config.toml` (or the legacy `config`) in
+/// `cargo_home`, the host's `CARGO_HOME` or `~/.cargo`.
+fn host_cargo_config(cargo_home: &Path) -> Option<PathBuf> {
+ ["config.toml", "config"]
+ .iter()
+ .map(|name| cargo_home.join(name))
+ .find(|path| path.is_file())
+}
+
+/// The host's `CARGO_HOME`, honoring an explicit one. `None` without a home.
+fn host_cargo_home() -> Option<PathBuf> {
+ match std::env::var_os("CARGO_HOME").filter(|v| !v.is_empty()) {
+ Some(dir) => Some(PathBuf::from(dir)),
+ None => user_home().map(|home| home.join(".cargo")),
+ }
+}
+
+/// [`prepare_pkg_cache_in`] with the host's own cargo home.
+pub async fn prepare_pkg_cache(project_cache: &Path) -> Result<PkgCache, String> {
+ prepare_pkg_cache_in(project_cache, host_cargo_home().as_deref()).await
+}
+
+/// Create a project's package cache owner-only and symlink-hardened (as
+/// [`ensure_scratch_dir_path`] does a scratch), and refresh its cargo config.
+///
+/// The sandbox's `CARGO_HOME` is `<pkg>/cargo`, never the user's: a sandbox
+/// that could write `~/.cargo/registry/src` could tamper with sources a later
+/// unsandboxed build compiles. So nothing else of the host's comes in: not
+/// `credentials.toml` (a sandboxed command must not publish with the user's
+/// token) and not `bin/` (installed tools stay on the host `PATH`). The user's
+/// config does (mirrors, registries, `net.offline`), read-only, because cargo
+/// config can name programs to run (`build.rustc-wrapper`,
+/// `target.<triple>.runner`). It is copied afresh every session so host edits
+/// apply; with no host config an empty one takes its place, so a copy left by
+/// an earlier session (or written by its sandbox) never outlives the user's.
+/// Toolchains are untouched: rustup keeps them in `RUSTUP_HOME`.
+pub async fn prepare_pkg_cache_in(
+ project_cache: &Path,
+ host_cargo_home: Option<&Path>,
+) -> Result<PkgCache, String> {
+ let root = ensure_scratch_dir_path(&pkg_dir_in(project_cache)).await?;
+ let cargo = ensure_scratch_dir_path(&root.join(PKG_CARGO_HOME)).await?;
+ let copy = cargo.join("config.toml");
+ let refresh_error = |path: &Path, e: std::io::Error| {
+ format!("ERROR: cannot refresh {}: {e}", path.display())
+ };
+ // Cargo reads the legacy name too, so one a sandbox planted would apply.
+ // An empty one is what bubblewrap leaves as the mount point it binds the
+ // config over; it is kept, since deleting a file another live sandbox
+ // has mounted over detaches that mount (Linux 3.18+) and would free the
+ // name inside it. Empty, it holds nothing a planter could want.
+ let legacy = cargo.join("config");
+ let empty_file = |m: &std::fs::Metadata| m.is_file() && m.len() == 0;
+ if !tokio::fs::symlink_metadata(&legacy).await.is_ok_and(|m| empty_file(&m)) {
+ remove_read_only_file(&legacy).await.map_err(|e| refresh_error(&legacy, e))?;
+ }
+ let host = match host_cargo_home.and_then(host_cargo_config) {
+ Some(host) => host,
+ None => {
+ let empty = project_cache.join(EMPTY_CARGO_CONFIG);
+ write_read_only(&[], &empty).await.map_err(|e| refresh_error(&empty, e))?;
+ empty
+ }
+ };
+ let bytes = tokio::fs::read(&host).await.map_err(|e| refresh_error(&host, e))?;
+ write_read_only(&bytes, &copy).await.map_err(|e| refresh_error(&copy, e))?;
+ Ok(PkgCache { root, cargo_config: Some(CargoConfig { host, copy }) })
+}
+
+/// Remove `path` if it is there, whatever it is: the copy is read-only, and a
+/// sandbox may have left a directory or symlink in its place. A read-only file
+/// goes too: on Unix only the folder's mode matters, and std deletes one on
+/// Windows since Rust 1.86.
+async fn remove_read_only_file(path: &Path) -> std::io::Result<()> {
+ match tokio::fs::symlink_metadata(path).await {
+ Ok(meta) if meta.is_dir() => tokio::fs::remove_dir_all(path).await,
+ Ok(_) => tokio::fs::remove_file(path).await,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(e) => Err(e),
+ }
+}
+
+/// Write `bytes` to a new read-only file at `path`. The folder is writable by
+/// every sandboxed command of the project, so the name may hold a symlink
+/// planted after it was cleared: created exclusively and never through a
+/// symlink, the open fails instead of truncating whatever file the link
+/// names, and the mode is set through the handle, not the name.
+fn create_read_only_new(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
+ use std::io::Write;
+ let mut open = std::fs::OpenOptions::new();
+ open.write(true).create_new(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ open.mode(0o600).custom_flags(nix::fcntl::OFlag::O_NOFOLLOW.bits());
+ }
+ let mut file = open.open(path)?;
+ file.write_all(bytes)?;
+ let mut perms = file.metadata()?.permissions();
+ perms.set_readonly(true);
+ file.set_permissions(perms)
+}
+
+/// Write `bytes` to `dst` and mark it read-only. Through a fresh file and a
+/// rename, so a concurrent session never reads a half-written config, and so
+/// a symlink planted at `dst` is replaced rather than followed. Skipped when
+/// `dst` already is a read-only regular file holding exactly `bytes` (every
+/// session but the first after an edit): replacing a file a live sibling
+/// sandbox has mounted over detaches that mount inside it (Linux 3.18+).
+/// That still happens when the host config changes mid-session; the sibling
+/// then sees the new, read-only-moded copy until its next session.
+///
+/// The read-only mark is the whole protection on AppContainer, which grants
+/// by ACE and has no deny: the container holds full access on the package
+/// cache, so it could clear the mark or replace the file. Accepted: the copy
+/// configures only sandboxed cargo and is rewritten every session. Seatbelt
+/// also denies writes to it by rule, and bubblewrap mounts the host file over
+/// it read-only.
+async fn write_read_only(bytes: &[u8], dst: &Path) -> std::io::Result<()> {
+ if let Ok(meta) = tokio::fs::symlink_metadata(dst).await {
+ if meta.is_file()
+ && meta.permissions().readonly()
+ && tokio::fs::read(dst).await.is_ok_and(|have| have == bytes)
+ {
+ return Ok(());
+ }
+ }
+ // Unique per call: a parent run and its subagents share a process and may
+ // prepare the same project's cache at once.
+ static COPIES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
+ let n = COPIES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ let tmp = dst.with_extension(format!("tmp-{}-{n}", std::process::id()));
+ remove_read_only_file(&tmp).await?;
+ let (path, owned) = (tmp.clone(), bytes.to_vec());
+ tokio::task::spawn_blocking(move || create_read_only_new(&path, &owned))
+ .await
+ .map_err(std::io::Error::other)??;
+ // Replaced in one step where the OS allows it, so a sibling session's
+ // bubblewrap never finds its mount point missing. Windows refuses to
+ // rename over a read-only file; there the old copy goes first.
+ if tokio::fs::rename(&tmp, dst).await.is_err() {
+ remove_read_only_file(dst).await?;
+ tokio::fs::rename(&tmp, dst).await?;
+ }
+ Ok(())
+}
+
+/// How long a scratch directory may sit untouched, with no live session
+/// claiming it, before the startup sweep treats it as abandoned. A week
+/// rather than a day: the live check is only as good as the caller's `keep`
+/// list, and another Jan instance's live session is never in it.
+const SCRATCH_STALE_AFTER: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 60 * 60);
+
+/// Delete abandoned scratch directories, returning how many were removed.
///
-/// Every scratch has an owner that removes it (run end, thread deletion, session
-/// end), but a kill -9 or a power loss leaves one behind with nobody left to
-/// claim it: the id it is keyed to lives in the caller's state, not on disk, so
-/// no `keep` list can be reconstructed the way [`sweep_thread_workspaces`] does
-/// it. Age is the only signal available, so anything untouched for
-/// [`SCRATCH_STALE_AFTER`] is collected. Called once at startup. A scratch
-/// already moved into trash by [`trash_scratch_dir`] goes once it is
-/// [`TRASH_KEPT_FOR`] old.
+/// Every scratch has an owner that removes it (run end, thread deletion,
+/// session end), but a kill -9 or a power loss leaves one behind with nobody
+/// left to claim it, and unlike a temp dir the OS cache dir is never cleaned
+/// for us. Scans every `<cache>/jan/*/scratch/`: an entry goes when its id is
+/// not in `keep` (the caller's live sessions: the desktop's surviving thread
+/// ids, a CLI run's own session) and it was last modified
+/// [`SCRATCH_STALE_AFTER`] ago. Trash goes once it is [`TRASH_KEPT_FOR`] old.
///
+/// Also collects the `jan-agent-*` scratches and `jan-trash-*` trash older
+/// versions left in the system temp dir: nothing else would ever remove them
+/// from a temp dir the OS does not clean (Windows, a persistent `/tmp`).
/// Failures are silent per entry: another user's `jan-agent-*` in a shared
/// `/tmp` is not ours to delete and simply fails the unlink.
-pub async fn sweep_stale_scratch_dirs() -> usize {
- sweep_scratch_older_than(&std::env::temp_dir(), SCRATCH_STALE_AFTER).await
+pub async fn sweep_stale_scratch_dirs(keep: &[String]) -> usize {
+ sweep_stale_scratch_dirs_in(&jan_cache_root(), keep).await
}
-/// Sweep an explicit directory so tests never collect another session's scratch.
-async fn sweep_scratch_older_than(root: &Path, max_age: std::time::Duration) -> usize {
- let Ok(mut entries) = tokio::fs::read_dir(root).await else {
+/// [`sweep_stale_scratch_dirs`] under an explicit Jan cache root, for callers
+/// that resolve the root themselves (the app substitutes a temp root in its
+/// tests).
+pub async fn sweep_stale_scratch_dirs_in(cache_root: &Path, keep: &[String]) -> usize {
+ sweep_scratch_in(cache_root, keep, SCRATCH_STALE_AFTER).await
+ + sweep_legacy_scratch_in(&std::env::temp_dir(), SCRATCH_STALE_AFTER).await
+}
+
+/// [`sweep_stale_scratch_dirs`] over an explicit cache root, so tests never
+/// collect another session's scratch.
+async fn sweep_scratch_in(cache_root: &Path, keep: &[String], max_age: std::time::Duration) -> usize {
+ let keep: std::collections::HashSet<&str> = keep.iter().map(String::as_str).collect();
+ let Ok(mut projects) = tokio::fs::read_dir(cache_root).await else {
return 0;
};
let mut removed = 0;
- while let Ok(Some(entry)) = entries.next_entry().await {
- let name = entry.file_name();
- let Some(name) = name.to_str() else { continue };
- let trash = name.starts_with(SCRATCH_TRASH_PREFIX);
- if !name.starts_with("jan-agent-") && !trash {
- continue;
+ while let Ok(Some(project)) = projects.next_entry().await {
+ // `symlink_metadata` throughout: a symlink planted where a folder is
+ // expected must not lead the sweep into deleting what it points at.
+ let scratch = project.path().join(SCRATCH);
+ match tokio::fs::symlink_metadata(&scratch).await {
+ Ok(meta) if meta.is_dir() && !meta.file_type().is_symlink() => {}
+ _ => continue,
}
- // `symlink_metadata`: a symlink named like a scratch is not one, and
- // following it would delete whatever it points at.
- let Ok(meta) = tokio::fs::symlink_metadata(entry.path()).await else {
+ let Ok(mut entries) = tokio::fs::read_dir(&scratch).await else {
continue;
};
- if trash && meta.file_type().is_symlink() {
- let _ = tokio::fs::remove_file(entry.path()).await;
- continue;
+ while let Ok(Some(entry)) = entries.next_entry().await {
+ let name = entry.file_name();
+ let Some(name) = name.to_str() else { continue };
+ if let Some(session) = name.strip_prefix(SCRATCH_LEASE_PREFIX) {
+ remove_orphan_lease(&entry.path(), &scratch.join(session));
+ continue;
+ }
+ let trash = name.starts_with(SCRATCH_TRASH_PREFIX);
+ // Only names this module makes: anything else was not made here.
+ if !trash && (keep.contains(name) || thread_segment(name).is_err()) {
+ continue;
+ }
+ if trash {
+ if remove_if_stale(&entry.path(), name, true, max_age).await {
+ removed += 1;
+ }
+ continue;
+ }
+ // Held exclusively across the age check and the delete, so a run
+ // claiming this scratch meanwhile waits rather than losing it.
+ let Some(lease) = lease_path(&entry.path()) else { continue };
+ let Ok(lock) = try_lock_lease(&lease) else {
+ continue; // a live run, in some Jan process, holds it
+ };
+ if remove_if_stale(&entry.path(), name, false, max_age).await {
+ removed += 1;
+ if lock.is_some() {
+ let _ = std::fs::remove_file(&lease);
+ }
+ }
+ }
+ }
+ removed
+}
+
+/// Remove the lease at `lease` once its scratch is gone (trashed at session
+/// end, or deleted by hand) and no run holds it.
+fn remove_orphan_lease(lease: &Path, scratch: &Path) {
+ if std::fs::symlink_metadata(scratch).is_ok() {
+ return;
+ }
+ match std::fs::symlink_metadata(lease) {
+ // Not something `open_lease` would make: unlink it, never follow it.
+ Ok(meta) if !meta.is_file() => {
+ if meta.file_type().is_symlink() {
+ let _ = std::fs::remove_file(lease);
+ }
+ }
+ Ok(_) => {
+ if let Ok(Some(_lock)) = try_lock_lease(lease) {
+ let _ = std::fs::remove_file(lease);
+ }
}
- if meta.file_type().is_symlink() || !meta.is_dir() {
+ Err(_) => {}
+ }
+}
+
+/// The legacy layout: `jan-agent-<session>` and `jan-trash-*` directly in the
+/// system temp dir. Age is the only signal there, as it always was.
+async fn sweep_legacy_scratch_in(root: &Path, max_age: std::time::Duration) -> usize {
+ let Ok(mut entries) = tokio::fs::read_dir(root).await else {
+ return 0;
+ };
+ let mut removed = 0;
+ while let Ok(Some(entry)) = entries.next_entry().await {
+ let name = entry.file_name();
+ let Some(name) = name.to_str() else { continue };
+ let trash = name.starts_with(LEGACY_TRASH_PREFIX);
+ if !name.starts_with(LEGACY_SCRATCH_PREFIX) && !trash {
continue;
}
- // A trashed scratch is never in use (the rename that made it is
- // atomic), but it holds the session's subagent results, kept a while
- // in case the user wants one back.
- let stale = if trash {
- trash_expired(name, &meta)
- } else {
- meta.modified()
- .ok()
- .and_then(|m| m.elapsed().ok())
- .is_some_and(|age| age >= max_age)
- };
- if stale && tokio::fs::remove_dir_all(entry.path()).await.is_ok() {
+ if remove_if_stale(&entry.path(), name, trash, max_age).await {
removed += 1;
}
}
removed
}
-/// Prefix of a scratch moved aside for deletion. Deliberately not `jan-agent-`:
-/// a session id is any `thread_segment`, so `jan-agent-trash-*` could be a live
-/// scratch that the any-age trash sweep would wipe.
-const SCRATCH_TRASH_PREFIX: &str = "jan-trash-";
+/// Delete the scratch or trash entry at `path` when it is stale, returning
+/// whether it went. A symlink named like trash is unlinked (never followed);
+/// one named like a scratch is not ours and is left alone.
+async fn remove_if_stale(path: &Path, name: &str, trash: bool, max_age: std::time::Duration) -> bool {
+ let Ok(meta) = tokio::fs::symlink_metadata(path).await else {
+ return false;
+ };
+ if trash && meta.file_type().is_symlink() {
+ let _ = tokio::fs::remove_file(path).await;
+ return false;
+ }
+ if meta.file_type().is_symlink() || !meta.is_dir() {
+ return false;
+ }
+ // A trashed scratch is never in use (the rename that made it is atomic),
+ // but it holds the session's subagent results, kept a while in case the
+ // user wants one back.
+ let stale = if trash {
+ trash_expired(name, &meta)
+ } else {
+ meta.modified()
+ .ok()
+ .and_then(|m| m.elapsed().ok())
+ .is_some_and(|age| age >= max_age)
+ };
+ stale && tokio::fs::remove_dir_all(path).await.is_ok()
+}
+
+/// Prefix of a scratch moved aside for deletion, next to the live ones in
+/// `scratch/`. It starts with a dot, which [`thread_segment`] never accepts,
+/// so no session id can ever be mistaken for trash and swept at any age.
+const SCRATCH_TRASH_PREFIX: &str = ".trash-";
+
+/// What older versions named a scratch and its trash in the system temp dir.
+const LEGACY_SCRATCH_PREFIX: &str = "jan-agent-";
+const LEGACY_TRASH_PREFIX: &str = "jan-trash-";
/// How long Jan's trash (a removed scratch, a subagent worktree that read as
/// empty) is kept before a startup sweep deletes it: long enough for a user
@@ -684,11 +1273,11 @@ pub fn trash_expired(name: &str, meta: &std::fs::Metadata) -> bool {
.is_some_and(|age| age >= TRASH_KEPT_FOR)
}
-/// Delete a session's scratch directory now. Idempotent: a missing scratch is
+/// Delete a desktop thread's scratch now. Idempotent: a missing scratch is
/// Ok. For an explicit delete (a thread or session the user removed): its
/// results and caches must not outlive it in the trash.
-pub async fn remove_scratch_dir(session: &str) -> Result<(), String> {
- let dir = checked_scratch_dir(session)?;
+pub async fn remove_scratch_dir(thread_id: &str) -> Result<(), String> {
+ let dir = thread_scratch_dir(thread_id)?;
match tokio::fs::remove_dir_all(&dir).await {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
@@ -696,22 +1285,26 @@ pub async fn remove_scratch_dir(session: &str) -> Result<(), String> {
}
}
-/// Move a finished session's scratch into trash, for the exit path only.
-/// Idempotent: a missing scratch is Ok.
+/// Move a finished CLI/TUI session's scratch, under the project cache folder
+/// `project_cache` ([`project_cache_dir_in`]), into trash. For the exit path
+/// only. Idempotent: a missing scratch is Ok.
///
/// Read-only subagents keep package caches there, so deleting it can walk
/// tens of thousands of files while the user waits to exit. A rename is
/// instant, and a startup sweep empties the trash once it is old.
-pub async fn trash_scratch_dir(session: &str) -> Result<(), String> {
- let dir = checked_scratch_dir(session)?;
- trash_dir_in(&std::env::temp_dir(), &dir, session).await
+pub async fn trash_scratch_dir_in(project_cache: &Path, session: &str) -> Result<(), String> {
+ trash_dir(&checked_scratch_dir(project_cache, session)?, session).await
}
-/// Move `dir` into `root` under a trash name made from `stem`, deleting it in
-/// place when the rename fails (another volume, a handle still open on
-/// Windows). A missing `dir` is Ok.
-async fn trash_dir_in(root: &Path, dir: &Path, stem: &str) -> Result<(), String> {
- let trash = root.join(trash_name(&format!(
+/// Move `dir` into trash beside it, in its own `scratch/` folder: the same
+/// filesystem, so the rename is atomic and instant, and the folder the sweep
+/// already scans. Deleted in place when the rename fails (a handle still open
+/// on Windows). A missing `dir` is Ok.
+async fn trash_dir(dir: &Path, stem: &str) -> Result<(), String> {
+ let Some(parent) = dir.parent() else {
+ return Err(format!("ERROR: scratch path {dir:?} has no parent"));
+ };
+ let trash = parent.join(trash_name(&format!(
"{SCRATCH_TRASH_PREFIX}{stem}-{}",
std::process::id()
)));
@@ -787,7 +1380,7 @@ async fn remove_workspace_at(dir: PathBuf, id: &str) -> Result<(), String> {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(format!("ERROR: {e}")),
}
- // Wipe the host-temp scratch keyed to the same id.
+ // Wipe the cache scratch keyed to the same id.
let _ = remove_scratch_dir(id).await;
Ok(())
}
@@ -847,7 +1440,7 @@ async fn sweep_workspaces_in(dir: PathBuf, keep: &[String]) -> Result<usize, Str
crate::tools::appcontainer::release(&entry.path());
if tokio::fs::remove_dir_all(entry.path()).await.is_ok() {
removed += 1;
- // Wipe the host-temp scratch keyed to this id.
+ // Wipe the cache scratch keyed to this id.
let _ = remove_scratch_dir(&name).await;
}
}
@@ -1033,90 +1626,293 @@ mod tests {
assert!(!store_dir(&permanent_store(data), "memory").starts_with(&thread));
}
+ /// The cache layout: one folder per project under the Jan cache root,
+ /// named with the very slug the project's store uses, so `~/.jan/projects/<slug>`
+ /// and `<cache>/jan/<slug>` always name one project the same way.
+ #[test]
+ fn a_project_cache_uses_the_store_slug() {
+ let home = Path::new("/home/u/.jan");
+ let cache = Path::new("/home/u/.cache/jan");
+ let project = unique_data_folder();
+ std::fs::create_dir_all(&project).unwrap();
+ let dir = project_cache_dir_in(cache, Some(&project));
+ let store = project_store_in(home, &project);
+ assert_eq!(dir.parent(), Some(cache));
+ assert_eq!(dir.file_name(), store.file_name());
+ assert_eq!(
+ scratch_dir_in(&dir, "s1"),
+ cache.join(store.file_name().unwrap()).join("scratch/s1")
+ );
+ let _ = std::fs::remove_dir_all(&project);
+ }
+
+ /// A linked worktree of a project shares its cache folder, as it shares
+ /// its store.
+ #[test]
+ fn a_linked_worktree_shares_its_main_checkouts_cache() {
+ let base = unique_data_folder();
+ let main = base.join("main");
+ std::fs::create_dir_all(main.join(".git/worktrees/w1")).unwrap();
+ let wt = base.join("wt");
+ std::fs::create_dir_all(&wt).unwrap();
+ let gitdir = main.canonicalize().unwrap().join(".git/worktrees/w1");
+ std::fs::write(wt.join(".git"), format!("gitdir: {}\n", gitdir.display())).unwrap();
+ let cache = Path::new("/c/jan");
+ assert_eq!(
+ project_cache_dir_in(cache, Some(&wt)),
+ project_cache_dir_in(cache, Some(&main))
+ );
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ /// No filesystem project (a desktop thread): the fixed `chat` sibling.
+ #[test]
+ fn a_session_with_no_project_uses_the_chat_folder() {
+ let cache = Path::new("/c/jan");
+ assert_eq!(project_cache_dir_in(cache, None), Path::new("/c/jan/chat"));
+ assert_eq!(
+ scratch_dir_in(&project_cache_dir_in(cache, None), "t1"),
+ Path::new("/c/jan/chat/scratch/t1")
+ );
+ // The real helpers agree with the explicit-root ones.
+ assert_eq!(project_cache_dir(None), jan_cache_root().join("chat"));
+ assert_eq!(
+ thread_scratch_dir("t1").unwrap(),
+ jan_cache_root().join("chat/scratch/t1")
+ );
+ }
+
+ /// A desktop thread's scratch is created, keyed by its id under `chat/`,
+ /// and removed with it.
#[tokio::test]
async fn scratch_dir_lifecycle_is_session_keyed_and_removable() {
- let session = "t1";
- let scratch = scratch_dir(session);
+ let session = format!("t1-{}", std::process::id());
+ let scratch = thread_scratch_dir(&session).unwrap();
assert!(!scratch.exists());
- let created = ensure_scratch_dir(session).await.unwrap();
+ let created = ensure_scratch_dir(&session).await.unwrap();
assert_eq!(created, scratch);
assert!(scratch.is_dir());
+ assert!(scratch.starts_with(jan_cache_root().join("chat").join("scratch")));
std::fs::write(scratch.join("f"), b"x").unwrap();
- remove_scratch_dir(session).await.unwrap();
+ remove_scratch_dir(&session).await.unwrap();
assert!(!scratch.exists());
// Idempotent.
- remove_scratch_dir(session).await.unwrap();
+ remove_scratch_dir(&session).await.unwrap();
}
- /// A scratch whose owner died (kill -9, power loss) has nobody left to
- /// remove it and no `keep` list to rebuild, so the startup sweep collects it
- /// by age. Nothing else in the temp dir is touched, and a fresh scratch
- /// survives the real 24h threshold.
+ /// Backdate `path`'s mtime by `age`, so the real 7-day threshold can be
+ /// exercised without waiting a week.
+ fn age_by(path: &Path, age: std::time::Duration) {
+ let when = std::time::SystemTime::now() - age;
+ let mut open = std::fs::OpenOptions::new();
+ open.read(true);
+ // Windows opens a directory only with backup semantics, and setting
+ // its times needs write access.
+ #[cfg(windows)]
+ {
+ use std::os::windows::fs::OpenOptionsExt;
+ open.write(true).custom_flags(0x0200_0000);
+ }
+ open.open(path).unwrap().set_modified(when).unwrap();
+ }
+
+ const EIGHT_DAYS: std::time::Duration = std::time::Duration::from_secs(8 * 24 * 60 * 60);
+
+ /// A scratch whose owner died (kill -9, power loss) is collected at the
+ /// next start once it is a week old and no live session claims it, in
+ /// every project's folder. A live one (in `keep`) and a fresh one stay,
+ /// whatever their age; anything not named like a scratch is left alone.
#[tokio::test]
- async fn stale_scratch_dirs_are_swept_and_fresh_ones_are_not() {
- let root = tmp_root("scratch_sweep");
- let orphan = root.join("jan-agent-orphan");
- ensure_scratch_dir_path(&orphan).await.unwrap();
- std::fs::write(orphan.join("spill.txt"), b"leaked").unwrap();
- let bystander = root.join("not-a-scratch");
+ async fn the_startup_sweep_removes_only_stale_scratch_no_session_claims() {
+ let cache = tmp_root("scratch_sweep");
+ let a = project_cache_dir_in(&cache, None);
+ let b = cache.join("proj-1234abcd");
+ let crashed = scratch_dir_in(&a, "crashed");
+ let live = scratch_dir_in(&a, "live");
+ let fresh = scratch_dir_in(&b, "fresh");
+ let other_crashed = scratch_dir_in(&b, "gone");
+ for dir in [&crashed, &live, &fresh, &other_crashed] {
+ ensure_scratch_dir_path(dir).await.unwrap();
+ std::fs::write(dir.join("spill.txt"), b"x").unwrap();
+ }
+ let bystander = a.join("scratch").join("not.a.scratch");
std::fs::create_dir_all(&bystander).unwrap();
+ for dir in [&crashed, &live, &other_crashed, &bystander] {
+ age_by(dir, EIGHT_DAYS);
+ }
- assert_eq!(
- sweep_scratch_older_than(&root, SCRATCH_STALE_AFTER).await,
- 0,
- "a fresh scratch is live"
- );
- assert!(orphan.is_dir());
+ let keep = vec!["live".to_string()];
+ assert_eq!(sweep_scratch_in(&cache, &keep, SCRATCH_STALE_AFTER).await, 2);
+ assert!(!crashed.exists() && !other_crashed.exists(), "stale scratch goes");
+ assert!(live.join("spill.txt").is_file(), "a live session's scratch stays");
+ assert!(fresh.join("spill.txt").is_file(), "a fresh scratch stays");
+ assert!(bystander.is_dir(), "swept a directory that is not a scratch");
+ let _ = std::fs::remove_dir_all(&cache);
+ }
- assert_eq!(
- sweep_scratch_older_than(&root, std::time::Duration::ZERO).await,
- 1
- );
- assert!(!orphan.exists(), "an abandoned scratch must be collected");
- assert!(
- bystander.is_dir(),
- "swept a directory that is not a scratch"
- );
+ /// With no OS cache dir the cache root falls back to the shared temp dir,
+ /// so it is named per user, and a name already taken by something that is
+ /// not this user's own directory (planted by another local user, or a
+ /// symlink) is passed over rather than trusted.
+ #[cfg(unix)]
+ #[test]
+ fn the_temp_fallback_is_per_user_and_skips_what_is_not_ours() {
+ let temp = tmp_root("temp_fallback");
+ std::fs::create_dir_all(&temp).unwrap();
+ let uid = nix::unistd::getuid();
+ let first = temp_cache_root_in(&temp);
+ assert_eq!(first, temp.join(format!("jan-{uid}")));
+ // Ours already: reused.
+ std::fs::create_dir(&first).unwrap();
+ assert_eq!(temp_cache_root_in(&temp), first);
+ // Not a directory of ours: skipped.
+ std::fs::remove_dir(&first).unwrap();
+ std::os::unix::fs::symlink(&temp, &first).unwrap();
+ let next = temp_cache_root_in(&temp);
+ assert_ne!(next, first);
+ assert!(next.file_name().unwrap().to_string_lossy().starts_with(&format!("jan-{uid}-")));
+ let _ = std::fs::remove_dir_all(&temp);
+ }
+
+ /// Another live session's scratch (another CLI/TUI process, so not in this
+ /// one's `keep`) survives the sweep while its run holds a claim, however
+ /// old its mtime; once released it goes, lease file and all.
+ #[tokio::test]
+ async fn a_claimed_scratch_survives_the_sweep() {
+ let cache = tmp_root("scratch_sweep_claim");
+ let scratch = scratch_dir_in(&project_cache_dir_in(&cache, None), "other-live");
+ ensure_scratch_dir_path(&scratch).await.unwrap();
+ let claim = claim_scratch_dir(&scratch).await.unwrap();
+ // A run that has gone on for over a week, writing only in subfolders.
+ age_by(&scratch, EIGHT_DAYS);
+ assert_eq!(sweep_scratch_in(&cache, &[], SCRATCH_STALE_AFTER).await, 0);
+ assert!(scratch.is_dir(), "a claimed scratch must survive");
+ drop(claim);
+ assert_eq!(sweep_scratch_in(&cache, &[], SCRATCH_STALE_AFTER).await, 1);
+ assert!(!scratch.exists());
+ let leftovers: Vec<_> = std::fs::read_dir(scratch.parent().unwrap())
+ .unwrap()
+ .flatten()
+ .map(|e| e.file_name())
+ .collect();
+ assert!(leftovers.is_empty(), "the lease goes with its scratch: {leftovers:?}");
+ let _ = std::fs::remove_dir_all(&cache);
+ }
+
+ /// Claiming a scratch at the start of each turn marks it fresh, so an
+ /// interactive session idle between turns is not swept for a week after
+ /// its last one; a lease left by a scratch that is gone is collected.
+ #[tokio::test]
+ async fn claiming_a_scratch_marks_it_fresh() {
+ let cache = tmp_root("scratch_sweep_touch");
+ let project = project_cache_dir_in(&cache, None);
+ let scratch = scratch_dir_in(&project, "idle");
+ ensure_scratch_dir_path(&scratch).await.unwrap();
+ age_by(&scratch, EIGHT_DAYS);
+ drop(claim_scratch_dir(&scratch).await.unwrap());
+ assert_eq!(sweep_scratch_in(&cache, &[], SCRATCH_STALE_AFTER).await, 0);
+ assert!(scratch.is_dir(), "a scratch claimed just now is fresh");
+
+ let gone = scratch_dir_in(&project, "gone");
+ ensure_scratch_dir_path(&gone).await.unwrap();
+ drop(claim_scratch_dir(&gone).await.unwrap());
+ std::fs::remove_dir_all(&gone).unwrap();
+ sweep_scratch_in(&cache, &[], SCRATCH_STALE_AFTER).await;
+ let names: Vec<String> = std::fs::read_dir(project.join(SCRATCH))
+ .unwrap()
+ .flatten()
+ .map(|e| e.file_name().to_string_lossy().into_owned())
+ .collect();
+ assert!(names.iter().all(|n| !n.contains("gone")), "{names:?}");
+ let _ = std::fs::remove_dir_all(&cache);
+ }
+ /// The sweep must not follow a symlink planted where a project's
+ /// `scratch/` folder or a scratch would be.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn the_startup_sweep_never_follows_a_symlink() {
+ let cache = tmp_root("scratch_sweep_link");
+ let victim = tmp_root("scratch_sweep_victim");
+ std::fs::create_dir_all(victim.join("old")).unwrap();
+ age_by(&victim.join("old"), EIGHT_DAYS);
+ std::fs::create_dir_all(cache.join("p-1")).unwrap();
+ std::os::unix::fs::symlink(&victim, cache.join("p-1").join("scratch")).unwrap();
+ let scratch = cache.join("p-2").join("scratch");
+ std::fs::create_dir_all(&scratch).unwrap();
+ std::os::unix::fs::symlink(victim.join("old"), scratch.join("linked")).unwrap();
+ assert_eq!(sweep_scratch_in(&cache, &[], std::time::Duration::ZERO).await, 0);
+ assert!(victim.join("old").is_dir());
+ let _ = std::fs::remove_dir_all(&cache);
+ let _ = std::fs::remove_dir_all(&victim);
+ }
+
+ /// Older versions kept the scratch in the system temp dir; those are still
+ /// collected by age so an upgrade does not leak them.
+ #[tokio::test]
+ async fn legacy_temp_scratch_is_still_swept() {
+ let root = tmp_root("legacy_sweep");
+ let orphan = root.join("jan-agent-orphan");
+ let recent = root.join("jan-agent-recent");
+ for dir in [&orphan, &recent] {
+ ensure_scratch_dir_path(dir).await.unwrap();
+ }
+ age_by(&orphan, EIGHT_DAYS);
+ let old_trash = root.join("jan-trash-old-1-1000000000000000000");
+ std::fs::create_dir_all(&old_trash).unwrap();
+ let bystander = root.join("not-a-scratch");
+ std::fs::create_dir_all(&bystander).unwrap();
+ age_by(&bystander, EIGHT_DAYS);
+ assert_eq!(sweep_legacy_scratch_in(&root, SCRATCH_STALE_AFTER).await, 2);
+ assert!(!orphan.exists() && !old_trash.exists());
+ assert!(recent.is_dir() && bystander.is_dir());
let _ = std::fs::remove_dir_all(&root);
}
/// Exit must not wait for a scratch full of package caches to be deleted:
- /// it is moved aside, whole, next to where it was.
+ /// it is moved aside, whole, beside where it was (same `scratch/` folder,
+ /// so the same filesystem).
#[tokio::test]
- async fn removing_a_scratch_moves_it_to_trash_in_the_temp_dir() {
- let root = tmp_root("scratch_trash");
- let scratch = root.join("jan-agent-s1");
+ async fn trashing_a_scratch_moves_it_beside_itself() {
+ let cache = tmp_root("scratch_trash");
+ let scratch = scratch_dir_in(&cache.join("p-1"), "s1");
ensure_scratch_dir_path(&scratch).await.unwrap();
std::fs::write(scratch.join("cache.bin"), b"x").unwrap();
- trash_dir_in(&root, &scratch, "s1").await.unwrap();
+ trash_dir(&scratch, "s1").await.unwrap();
assert!(!scratch.exists());
- let trashed: Vec<PathBuf> = std::fs::read_dir(&root)
+ let trashed: Vec<PathBuf> = std::fs::read_dir(scratch.parent().unwrap())
.unwrap()
.map(|e| e.unwrap().path())
.collect();
assert_eq!(trashed.len(), 1, "{trashed:?}");
let name = trashed[0].file_name().unwrap().to_string_lossy().into_owned();
assert!(name.starts_with(SCRATCH_TRASH_PREFIX), "{name}");
+ assert!(thread_segment(&name).is_err(), "trash can never pass for a session id");
assert!(trashed[0].join("cache.bin").is_file());
// Idempotent: a scratch already gone is Ok.
- trash_dir_in(&root, &scratch, "s1").await.unwrap();
- let _ = std::fs::remove_dir_all(&root);
+ trash_dir(&scratch, "s1").await.unwrap();
+ let _ = std::fs::remove_dir_all(&cache);
}
- /// A rename can fail (another volume, a handle still open on Windows);
- /// the scratch is then deleted in place, as before.
+ /// The real exit path: a CLI session's scratch under its project's folder
+ /// goes to trash there.
#[tokio::test]
- async fn a_scratch_that_cannot_be_renamed_is_deleted() {
- let root = tmp_root("scratch_norename");
- let scratch = root.join("jan-agent-s2");
- ensure_scratch_dir_path(&scratch).await.unwrap();
- std::fs::write(scratch.join("f"), b"x").unwrap();
- trash_dir_in(&root.join("missing"), &scratch, "s2").await.unwrap();
+ async fn a_cli_session_scratch_is_trashed_in_its_project_folder() {
+ let project = unique_data_folder();
+ std::fs::create_dir_all(&project).unwrap();
+ let session = format!("cli-exit-{}", std::process::id());
+ let cache = project_cache_dir(Some(&project));
+ let scratch = ensure_scratch_dir_path(&scratch_dir_in(&cache, &session))
+ .await
+ .unwrap();
+ trash_scratch_dir_in(&cache, &session).await.unwrap();
assert!(!scratch.exists());
- let _ = std::fs::remove_dir_all(&root);
+ let parent = scratch.parent().unwrap();
+ assert_eq!(std::fs::read_dir(parent).unwrap().count(), 1);
+ let _ = std::fs::remove_dir_all(&cache);
+ let _ = std::fs::remove_dir_all(&project);
}
/// A trashed scratch is kept a week (it holds the session's subagent
@@ -1125,33 +1921,39 @@ mod tests {
/// following it.
#[tokio::test]
async fn trash_is_kept_a_week_then_emptied_by_the_startup_sweep() {
- let root = tmp_root("scratch_trash_sweep");
- let live = root.join("jan-agent-live");
+ let cache = tmp_root("scratch_trash_sweep");
+ let project = cache.join("p-1");
+ let live = scratch_dir_in(&project, "live");
ensure_scratch_dir_path(&live).await.unwrap();
- let ended = root.join("jan-agent-ended");
+ let ended = scratch_dir_in(&project, "ended");
ensure_scratch_dir_path(&ended).await.unwrap();
- trash_dir_in(&root, &ended, "ended").await.unwrap();
- let trash = root.join("jan-trash-old-1-1000000000000000000");
+ trash_dir(&ended, "ended").await.unwrap();
+ let root = project.join("scratch");
+ let trash = root.join(format!("{SCRATCH_TRASH_PREFIX}old-1-1000000000000000000"));
std::fs::create_dir_all(trash.join("deep")).unwrap();
std::fs::write(trash.join("deep/f"), b"x").unwrap();
- let bystander = root.join("not-a-scratch");
+ let bystander = cache.join("not-a-scratch");
std::fs::create_dir_all(&bystander).unwrap();
std::fs::write(bystander.join("keep"), b"x").unwrap();
+ let link = root.join(format!("{SCRATCH_TRASH_PREFIX}link"));
#[cfg(unix)]
- std::os::unix::fs::symlink(&bystander, root.join("jan-trash-link")).unwrap();
+ std::os::unix::fs::symlink(&bystander, &link).unwrap();
- assert_eq!(sweep_scratch_older_than(&root, SCRATCH_STALE_AFTER).await, 1);
+ assert_eq!(sweep_scratch_in(&cache, &[], SCRATCH_STALE_AFTER).await, 1);
assert!(!trash.exists(), "week-old trash goes");
let fresh = std::fs::read_dir(&root)
.unwrap()
- .filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().starts_with("jan-trash-ended-"))
+ .filter(|e| {
+ let name = e.as_ref().unwrap().file_name();
+ name.to_string_lossy().starts_with(&format!("{SCRATCH_TRASH_PREFIX}ended-"))
+ })
.count();
assert_eq!(fresh, 1, "fresh trash is kept");
assert!(live.is_dir(), "a fresh scratch is live");
assert!(bystander.join("keep").is_file(), "nothing outside trash is touched");
#[cfg(unix)]
- assert!(std::fs::symlink_metadata(root.join("jan-trash-link")).is_err());
- let _ = std::fs::remove_dir_all(&root);
+ assert!(std::fs::symlink_metadata(&link).is_err());
+ let _ = std::fs::remove_dir_all(&cache);
}
/// A session scratch as subagents leave it: session files under
@@ -1173,7 +1975,7 @@ mod tests {
let session = format!("sub-exit-{}", std::process::id());
let scratch = ensure_scratch_dir(&session).await.unwrap();
let files = seed_subagent_files(&scratch);
- trash_scratch_dir(&session).await.unwrap();
+ trash_scratch_dir_in(&project_cache_dir(None), &session).await.unwrap();
assert!(files.iter().all(|f| !f.exists()) && !scratch.exists());
}
@@ -1202,7 +2004,7 @@ mod tests {
std::fs::write(scratch.join("f"), b"x").unwrap();
remove_thread_workspace(&data, &thread).await.unwrap();
let trashed = format!("{SCRATCH_TRASH_PREFIX}{thread}-");
- let left: Vec<_> = std::fs::read_dir(std::env::temp_dir())
+ let left: Vec<_> = std::fs::read_dir(scratch.parent().unwrap())
.unwrap()
.filter_map(Result::ok)
.filter(|e| e.file_name().to_string_lossy().starts_with(&trashed))
@@ -1212,26 +2014,24 @@ mod tests {
}
/// Crash: a scratch nobody removed is collected by the stale sweep with its
- /// subagent files, and a live one keeps them.
+ /// subagent files, and a fresh one keeps them.
#[tokio::test]
async fn subagent_files_in_an_abandoned_scratch_are_swept() {
- let root = tmp_root("subagent_sweep");
- let orphan = root.join("jan-agent-crashed");
+ let cache = tmp_root("subagent_sweep");
+ let orphan = scratch_dir_in(&cache.join("chat"), "crashed");
ensure_scratch_dir_path(&orphan).await.unwrap();
let files = seed_subagent_files(&orphan);
- assert_eq!(sweep_scratch_older_than(&root, SCRATCH_STALE_AFTER).await, 0);
- assert!(files.iter().all(|f| f.exists()), "a live scratch keeps its files");
- assert_eq!(
- sweep_scratch_older_than(&root, std::time::Duration::ZERO).await,
- 1
- );
+ assert_eq!(sweep_scratch_in(&cache, &[], SCRATCH_STALE_AFTER).await, 0);
+ assert!(files.iter().all(|f| f.exists()), "a fresh scratch keeps its files");
+ age_by(&orphan, EIGHT_DAYS);
+ assert_eq!(sweep_scratch_in(&cache, &[], SCRATCH_STALE_AFTER).await, 1);
assert!(files.iter().all(|f| !f.exists()) && !orphan.exists());
- let _ = std::fs::remove_dir_all(&root);
+ let _ = std::fs::remove_dir_all(&cache);
}
/// The scratch root must never be a pre-planted symlink to another
- /// directory: the sandbox binds it as `/tmp`, so trusting a redirect would
- /// sanction an attacker-selected directory as the session's scratch.
+ /// directory: the sandbox binds it writable at its own path, so trusting a
+ /// redirect would sanction an attacker-selected directory as the scratch.
#[cfg(unix)]
#[tokio::test]
async fn scratch_root_refuses_a_pre_planted_symlink() {
@@ -1244,19 +2044,181 @@ mod tests {
let _ = std::fs::remove_dir_all(&outside);
}
- /// A freshly created scratch root is a real, restrictive directory.
+ /// A freshly created scratch root is a real, restrictive directory, and
+ /// the parents Jan had to create for it (`jan/<slug>/scratch`) are
+ /// owner-only too; a parent that already existed keeps its mode.
#[cfg(unix)]
#[tokio::test]
async fn scratch_root_creation_is_a_real_private_dir() {
use std::os::unix::fs::PermissionsExt;
- let dir = unique_data_folder();
+ let base = unique_data_folder();
+ std::fs::create_dir_all(&base).unwrap();
+ std::fs::set_permissions(&base, std::fs::Permissions::from_mode(0o755)).unwrap();
+ let dir = scratch_dir_in(&base.join("jan").join("p-1"), "s1");
let r = ensure_scratch_dir_path(&dir).await;
assert_eq!(r.unwrap(), dir);
let meta = std::fs::symlink_metadata(&dir).unwrap();
assert!(!meta.file_type().is_symlink());
assert!(meta.is_dir());
- assert_eq!(meta.permissions().mode() & 0o777, 0o700);
- let _ = std::fs::remove_dir_all(&dir);
+ let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
+ for created in [dir.as_path(), dir.parent().unwrap(), &base.join("jan/p-1"), &base.join("jan")] {
+ assert_eq!(mode(created), 0o700, "{created:?}");
+ }
+ assert_eq!(mode(&base), 0o755, "an existing parent is left alone");
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ /// A folder on the way to the scratch that is not this user's is refused,
+ /// even when it is one Jan meant to create: a `/tmp/jan-<uid>` another
+ /// user planted just before the create reads as "already exists", and
+ /// adopting it would let them swap everything under it. Another user's
+ /// node cannot be made without root, so `mine` stands in for ownership.
+ #[tokio::test]
+ async fn a_created_parent_that_is_not_mine_is_refused() {
+ let base = unique_data_folder();
+ std::fs::create_dir_all(&base).unwrap();
+ let root = base.join("jan-1000");
+ let parent = root.join("p-1").join("scratch");
+
+ let yes = |_: &Path, _: &std::fs::Metadata| true;
+ let not_root = |p: &Path, _: &std::fs::Metadata| p != root;
+
+ // Planted between the walk and the create: refused once created.
+ let r = create_private_dirs_owned(&parent, yes, not_root).await;
+ assert!(r.is_err(), "another user's root was adopted");
+ assert!(!root.join("p-1").exists(), "nothing created under a refused root");
+
+ // Planted before the walk: the existing root is refused as found.
+ let r = create_private_dirs_owned(&parent, not_root, yes).await;
+ assert!(r.is_err(), "an existing root of another user's was adopted");
+ assert!(!root.join("p-1").exists(), "nothing created under a refused root");
+
+ // Mine, the same tree is accepted, the root now existing included.
+ let r = create_private_dirs_owned(&parent, yes, yes).await;
+ assert!(r.is_ok(), "{r:?}");
+ assert!(parent.is_dir());
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ /// A symlink planted at the temp copy's name is refused, never followed:
+ /// the file it names keeps its contents and stays writable.
+ #[cfg(unix)]
+ #[test]
+ fn the_read_only_copy_never_writes_through_a_planted_symlink() {
+ let base = unique_data_folder();
+ std::fs::create_dir_all(&base).unwrap();
+ let victim = base.join("victim");
+ std::fs::write(&victim, "mine").unwrap();
+ let planted = base.join("config.tmp-1-0");
+ std::os::unix::fs::symlink(&victim, &planted).unwrap();
+ assert!(create_read_only_new(&planted, b"[net]").is_err());
+ assert_eq!(std::fs::read_to_string(&victim).unwrap(), "mine");
+ assert!(!std::fs::metadata(&victim).unwrap().permissions().readonly());
+
+ let fresh = base.join("config.tmp-1-1");
+ create_read_only_new(&fresh, b"[net]").unwrap();
+ assert_eq!(std::fs::read(&fresh).unwrap(), b"[net]");
+ assert!(std::fs::metadata(&fresh).unwrap().permissions().readonly());
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ /// The package cache is `<project cache>/pkg`, private, with a cargo home
+ /// that holds a read-only copy of the user's config and nothing else of
+ /// theirs: no credentials, no installed binaries.
+ #[tokio::test]
+ async fn pkg_cache_holds_only_a_read_only_cargo_config() {
+ let base = unique_data_folder();
+ let host = base.join("host-cargo");
+ std::fs::create_dir_all(host.join("bin")).unwrap();
+ std::fs::write(host.join("config.toml"), "[net]\noffline = true\n").unwrap();
+ std::fs::write(host.join("credentials.toml"), "token = \"secret\"\n").unwrap();
+ std::fs::write(host.join("bin/tool"), "").unwrap();
+ let project = base.join("cache/jan/p-1");
+
+ let pkg = prepare_pkg_cache_in(&project, Some(&host)).await.unwrap();
+ assert_eq!(pkg.root, project.join("pkg"));
+ let cargo = pkg.root.join("cargo");
+ let config = pkg.cargo_config.clone().expect("config offered");
+ assert_eq!(config.host, host.join("config.toml"));
+ assert_eq!(config.copy, cargo.join("config.toml"));
+ assert_eq!(std::fs::read_to_string(&config.copy).unwrap(), "[net]\noffline = true\n");
+ assert!(std::fs::metadata(&config.copy).unwrap().permissions().readonly());
+ let names: Vec<_> = std::fs::read_dir(&cargo)
+ .unwrap()
+ .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
+ .collect();
+ assert_eq!(names, vec!["config.toml".to_string()], "{names:?}");
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ for dir in [&pkg.root, &cargo] {
+ let mode = std::fs::metadata(dir).unwrap().permissions().mode() & 0o777;
+ assert_eq!(mode, 0o700, "{dir:?}");
+ }
+ }
+
+ // Re-copied each session, so a host edit applies; a host with no config
+ // gets an empty one (so the sandbox finds both names read-only rather
+ // than free to plant), outside the package cache, where no sandbox
+ // can write it; and a planted legacy `config` is cleared.
+ std::fs::write(host.join("config.toml"), "[net]\noffline = false\n").unwrap();
+ let again = prepare_pkg_cache_in(&project, Some(&host)).await.unwrap();
+ let copy = again.cargo_config.unwrap().copy;
+ assert_eq!(std::fs::read_to_string(&copy).unwrap(), "[net]\noffline = false\n");
+ std::fs::write(cargo.join("config"), "planted").unwrap();
+ std::fs::remove_file(host.join("config.toml")).unwrap();
+ for host_home in [Some(host.as_path()), None] {
+ let none = prepare_pkg_cache_in(&project, host_home).await.unwrap();
+ let empty = none.cargo_config.expect("an empty config stands in");
+ assert!(!empty.host.starts_with(&none.root), "{:?}", empty.host);
+ assert!(empty.host.starts_with(&project), "{:?}", empty.host);
+ assert_eq!(std::fs::read(&empty.host).unwrap(), b"");
+ assert_eq!(std::fs::read(&copy).unwrap(), b"");
+ assert!(!cargo.join("config").exists());
+ }
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ /// A host with only the legacy `config` name still gets it offered, under
+ /// the name cargo prefers.
+ #[tokio::test]
+ async fn pkg_cache_offers_a_legacy_cargo_config() {
+ let base = unique_data_folder();
+ let host = base.join("host-cargo");
+ std::fs::create_dir_all(&host).unwrap();
+ std::fs::write(host.join("config"), "legacy").unwrap();
+ let pkg = prepare_pkg_cache_in(&base.join("p"), Some(&host)).await.unwrap();
+ let config = pkg.cargo_config.unwrap();
+ assert_eq!(config.host, host.join("config"));
+ assert_eq!(config.copy.file_name().unwrap(), "config.toml");
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ /// Two projects never share a package cache.
+ #[test]
+ fn projects_get_distinct_pkg_dirs() {
+ let cache = Path::new("/c/jan");
+ let a = unique_data_folder();
+ let b = unique_data_folder();
+ let pa = pkg_dir_in(&project_cache_dir_in(cache, Some(&a)));
+ let pb = pkg_dir_in(&project_cache_dir_in(cache, Some(&b)));
+ assert_ne!(pa, pb);
+ assert!(pa.starts_with(cache) && pa.ends_with("pkg"));
+ }
+
+ /// A symlink planted where the package cache goes is refused, as for the
+ /// scratch: the sandbox must never bind an attacker-chosen folder.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn pkg_cache_refuses_a_pre_planted_symlink() {
+ let base = unique_data_folder();
+ let outside = unique_data_folder();
+ std::fs::create_dir_all(&base).unwrap();
+ std::fs::create_dir_all(&outside).unwrap();
+ std::os::unix::fs::symlink(&outside, base.join("pkg")).unwrap();
+ assert!(prepare_pkg_cache_in(&base, None).await.is_err());
+ let _ = std::fs::remove_dir_all(&base);
+ let _ = std::fs::remove_dir_all(&outside);
}
#[test]
@@ -1300,7 +2262,7 @@ mod tests {
for bad in ["../x", "..", "a/b", "a\\b", "", "nul"] {
assert!(ensure_scratch_dir(bad).await.is_err(), "{bad:?}");
assert!(remove_scratch_dir(bad).await.is_err(), "{bad:?}");
- assert!(trash_scratch_dir(bad).await.is_err(), "{bad:?}");
+ assert!(trash_scratch_dir_in(Path::new("/c"), bad).await.is_err(), "{bad:?}");
}
}
diff --git a/src-tauri/src/core/agent/child_workspace.rs b/src-tauri/src/core/agent/child_workspace.rs
index 4b1c90526..265a1b119 100644
--- a/src-tauri/src/core/agent/child_workspace.rs
+++ b/src-tauri/src/core/agent/child_workspace.rs
@@ -23,7 +23,7 @@
//! checkout at that ref (fetched from `origin` when it is not local).
//!
//! Checkouts live under `~/.jan/worktrees/<project-slug>/`, never under `/tmp`
-//! (the sandbox binds the session scratch over `/tmp`). The ledger here
+//! (the sandbox gives the shell a private, throwaway `/tmp`). The ledger here
//! remembers every child's workspace for the session, so a later dispatch can
//! name it, and at the session's end removes the checkouts that hold nothing:
//! no commit past their base and no uncommitted change, `ref` ones included
@@ -282,26 +282,17 @@ pub(crate) fn project_worktrees_dir(root: &Path) -> Option<PathBuf> {
const CARGO_TARGET: &str = "cargo-target";
/// The scope a child in `ws` runs under: the shared build directory for any
-/// child outside the plain writable checkout, and package caches in the
-/// session scratch for a reader. A writer is granted nothing of the user's
-/// `.git`: its commits go to its own, inside its workspace. `scratch` is the
-/// session scratch, when the session has one.
-pub(crate) fn scope_for(
- ws: &ChildWorkspace,
- parent_root: &Path,
- scratch: Option<&Path>,
-) -> ChildScope {
+/// child outside the plain writable checkout. A writer is granted nothing of
+/// the user's `.git`: its commits go to its own, inside its workspace.
+/// Package caches need nothing here: a sandboxed child, reader or not, gets
+/// the project's package cache like any run (its checkout keys to the same
+/// project), which is how a reader that cannot write its checkout still
+/// installs.
+pub(crate) fn scope_for(ws: &ChildWorkspace, parent_root: &Path) -> ChildScope {
let mut scope = ChildScope {
read_only: ws.read_only,
..ChildScope::default()
};
- if let Some(scratch) = scratch.filter(|_| ws.read_only) {
- let shown = tauri_plugin_agent_tools::tools::sandbox::scratch_display_path(
- Some(scratch),
- scratch,
- );
- scope.env_set.extend(reader_env(&shown));
- }
if ws.worktree.is_some() || ws.read_only {
if let Some(target) = project_worktrees_dir(parent_root).map(|d| d.join(CARGO_TARGET)) {
if std::fs::create_dir_all(&target).is_ok() {
@@ -331,12 +322,12 @@ pub(crate) struct Placement {
/// Resolve the [`Placement`] of a child in `ws`: its checkout's branch and the
/// scope its tools enforce. Runs git, so the dispatch calls it on
/// the blocking pool and [`apply`], on the async child task, runs none.
-pub(crate) fn place(ws: &ChildWorkspace, parent_root: &Path, scratch: Option<&Path>) -> Placement {
+pub(crate) fn place(ws: &ChildWorkspace, parent_root: &Path) -> Placement {
Placement {
session_start: ws.worktree.as_ref().map(|wt| {
crate::core::agent::context::SessionStart::with_branch(worktree_branch(wt))
}),
- scope: scope_for(ws, parent_root, scratch),
+ scope: scope_for(ws, parent_root),
}
}
@@ -355,17 +346,6 @@ pub(crate) fn apply(
args.child_scope = Some(placement.scope);
}
-/// Package-manager caches a read-only child keeps in its scratch, since it
-/// cannot write them into the project. `scratch_shell` is the scratch as the
-/// shell names it.
-fn reader_env(scratch_shell: &str) -> Vec<(String, String)> {
- let scratch = scratch_shell.trim_end_matches('/');
- vec![
- ("YARN_CACHE_FOLDER".to_string(), format!("{scratch}/yarn-cache")),
- ("COREPACK_HOME".to_string(), format!("{scratch}/corepack")),
- ]
-}
-
/// The directory the parent's sandboxed tools may read its children's
/// worktrees through, created so the sandbox has something to bind. `None`
/// outside the CLI build or when there is no Jan home.
@@ -1245,9 +1225,10 @@ pub(crate) fn sweep_orphans(root: &Path) -> Settled {
}
/// What a session start sweeps, without holding the start up: the stale and
-/// trashed session scratches, `root`'s project's worktree trash, and the
-/// worktrees crashed sessions left there. `report` gets each notice and says
-/// whether it was taken (a run that already ended cannot show it).
+/// trashed session scratches (every project's, a week stale, never `session`'s
+/// own), `root`'s project's worktree trash, and the worktrees crashed sessions
+/// left there. `report` gets each notice and says whether it was taken (a run
+/// that already ended cannot show it).
///
/// A plain thread, not the runtime's: dropping a tokio runtime (which `main`
/// returning does) waits for its blocking tasks, so a sweep there would hold
@@ -1257,11 +1238,16 @@ pub(crate) fn sweep_orphans(root: &Path) -> Settled {
#[cfg(feature = "cli")]
pub(crate) fn spawn_startup_sweep(
root: PathBuf,
+ session: Option<String>,
mut report: impl FnMut(String) -> bool + Send + 'static,
) {
std::thread::spawn(move || {
if let Ok(rt) = tokio::runtime::Builder::new_current_thread().enable_all().build() {
- rt.block_on(tauri_plugin_agent_tools::workspace::sweep_stale_scratch_dirs());
+ let keep: Vec<String> = session.into_iter().collect();
+ rt.block_on(tauri_plugin_agent_tools::workspace::sweep_stale_scratch_dirs_in(
+ &crate::core::agent::project::jan_cache_root(),
+ &keep,
+ ));
}
empty_trash(&root);
sweep_and_report(&root, &mut report);
@@ -1395,7 +1381,7 @@ mod tests {
let (ws, lease) = ledger.assign(&root, "explore", false, None).unwrap();
assert!(lease.is_none());
assert!(!ws.read_only, "{ws:?}");
- assert_eq!(scope_for(&ws, &root, Some(&root)), ChildScope::default());
+ assert_eq!(scope_for(&ws, &root), ChildScope::default());
let _ = std::fs::remove_dir_all(&root);
}
@@ -1896,7 +1882,7 @@ mod git_tests {
let wt = ws.worktree.clone().unwrap();
let mut args = crate::core::agent::subagent::tests::max_par_args(&root);
args.session_start = Some(crate::core::agent::context::SessionStart::capture(Some(&root)));
- apply(&mut args, &ws, place(&ws, &root, None));
+ apply(&mut args, &ws, place(&ws, &root));
assert_eq!(args.project_root.as_deref(), Some(wt.path.as_path()));
let start = args.session_start.as_ref().unwrap().block();
assert!(start.contains(&wt.branch), "{start}");
@@ -1919,7 +1905,7 @@ mod git_tests {
let (reader, _) = ledger.assign(&root, "explore", false, None).unwrap();
let mut args = crate::core::agent::subagent::tests::max_par_args(&root);
let parent_start = args.session_start.clone();
- apply(&mut args, &reader, place(&reader, &root, None));
+ apply(&mut args, &reader, place(&reader, &root));
assert_eq!(args.project_root.as_deref(), Some(root.as_path()));
assert_eq!(args.session_start, parent_start, "a reader keeps the parent's start");
assert!(args.child_scope.as_ref().unwrap().read_only);
@@ -1992,7 +1978,7 @@ mod git_tests {
let wt = ws.worktree.clone().expect("a writer gets a worktree");
assert!(!wt.path.to_string_lossy().starts_with(r"\\?\"), "{wt:?}");
assert!(wt.path.join(".git").is_dir(), "{wt:?}");
- let scope = scope_for(&ws, &verbatim, None);
+ let scope = scope_for(&ws, &verbatim);
assert!(scope.read_roots.contains(&root.join(".git/objects")), "{scope:?}");
let _ = ledger.finish_session();
let _ = std::fs::remove_dir_all(&root);
@@ -2003,7 +1989,7 @@ mod git_tests {
let Some(root) = repo("scope") else { return };
let ledger = Arc::new(Ledger::default());
let (w, _lease) = ledger.assign(&root, "general", true, None).unwrap();
- let scope = scope_for(&w, &root, None);
+ let scope = scope_for(&w, &root);
assert!(!scope.read_only);
// Its commits go to the repository it is, inside its workspace: none
// of the user's `.git` is writable, only its objects readable.
@@ -2013,14 +1999,12 @@ mod git_tests {
assert!(scope.env_set.iter().any(|(k, v)| k == "CARGO_TARGET_DIR" && Path::new(v) == target));
let (r, _) = ledger.assign(&root, "explore", false, None).unwrap();
- let scratch = std::env::temp_dir().join(format!("jan_child_scratch_{}", std::process::id()));
- let scope = scope_for(&r, &root, Some(&scratch));
+ let scope = scope_for(&r, &root);
assert!(scope.read_only);
assert_eq!(scope.write_roots, vec![target], "a reader never gets the git dir");
assert!(scope.read_roots.is_empty(), "{scope:?}");
- let yarn = scope.env_set.iter().find(|(k, _)| k == "YARN_CACHE_FOLDER");
- assert!(yarn.is_some_and(|(_, v)| v.ends_with("/yarn-cache")), "{scope:?}");
- assert!(scope.env_set.iter().any(|(k, _)| k == "COREPACK_HOME"), "{scope:?}");
+ // Package caches come from the run's own package cache, not the scope.
+ assert!(!scope.env_set.iter().any(|(k, _)| k == "YARN_CACHE_FOLDER"), "{scope:?}");
let _ = ledger.finish_session();
let _ = std::fs::remove_dir_all(&root);
}
@@ -2044,7 +2028,7 @@ mod git_tests {
eprintln!("skipping: no sandbox backend on this host");
return None;
}
- let scope = scope_for(ws, parent_root, None);
+ let scope = scope_for(ws, parent_root);
let reads: Vec<PathBuf> = scope
.write_roots
.iter()
@@ -2677,7 +2661,7 @@ mod git_tests {
return;
}
let rt = tokio::runtime::Runtime::new().unwrap();
- rt.block_on(async { spawn_startup_sweep(root.clone(), |_| true) });
+ rt.block_on(async { spawn_startup_sweep(root.clone(), None, |_| true) });
// Long enough for the sweep to be blocked in that status.
std::thread::sleep(Duration::from_millis(500));
let started = Instant::now();
diff --git a/src-tauri/src/core/agent/context.rs b/src-tauri/src/core/agent/context.rs
index 778d308b3..e11189afd 100644
--- a/src-tauri/src/core/agent/context.rs
+++ b/src-tauri/src/core/agent/context.rs
@@ -339,15 +339,14 @@ fn runtime_environment_block(project_root: &Path, scratch: Option<&Path>) -> Str
.map(|note| format!("\n{note}"))
.unwrap_or_default();
- // 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.
+ // Where to do temporary work, by its real path: every sandbox backend
+ // exposes it there, so the same name works from `bash`, the filesystem
+ // tools and an escalated command, and the shell's `TMPDIR`/`TMP`/`TEMP`
+ // name 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)
+ display_path(scratch)
),
None => String::new(),
};
@@ -1491,22 +1490,17 @@ mod tests {
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.
+ /// The scratch is advertised by its real path on every platform: the one
+ /// name that resolves from `bash`, the filesystem tools and an escalated
+ /// command alike. `/tmp` would name the host's temp dir to the latter.
#[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()
- };
+ let expected = display_path(&scratch);
+ assert!(!block.contains("Scratch: `/tmp`"), "{block}");
assert!(
block.contains(&format!("Scratch: `{expected}`")),
"want {expected}: {block}"
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 9850402bc..f491fd4b8 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -148,7 +148,7 @@ pub(crate) struct OrchestrationArgs {
/// 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
+ /// `bash` scratch directory (`<cache>/jan/<project slug>/scratch/<session_id>`),
/// 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.
@@ -812,9 +812,13 @@ struct CompositeToolInvoker {
/// with it, so the two cannot disagree.
hidden_root: Option<std::path::PathBuf>,
/// Session-scoped scratch directory the shell and the filesystem tools share
- /// (see `workspace::scratch_dir`), so `bash` scratch files persist across
+ /// (see [`scratch_root_for`]), 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,
+ /// The project's package cache, for a sandboxed run (see
+ /// [`crate::core::agent::project::prepare_pkg_cache`]); `None` unconfined,
+ /// where the shell keeps the host's own caches.
+ pkg_cache: Option<tauri_plugin_agent_tools::workspace::PkgCache>,
/// Host env-var names/globs the shell may inherit beyond the base allowlist,
/// and explicit key=value overrides. Resolved once per run by merging
/// `~/.jan/config.toml` with the project's `[tools]` section.
@@ -1337,6 +1341,7 @@ impl CompositeToolInvoker {
.with_escalation(self.escalation.offered())
.with_hidden_root(self.hidden_root.as_deref())
.with_scratch_root(&self.scratch_root)
+ .with_pkg_cache(self.pkg_cache.as_ref())
.with_env_passthrough(&self.env_passthrough)
.with_env_set(&self.env_set)
.with_web_search(self.web_search.as_ref())
@@ -2869,6 +2874,7 @@ impl ToolInvoker for CompositeToolInvoker {
let sandbox = self.sandbox;
let hidden = self.hidden_root.clone();
let scratch = self.scratch_root.clone();
+ let pkg_cache = self.pkg_cache.clone();
let web_search = self.web_search.clone();
let read_roots = self.workspace.read_roots.clone();
// Hooks come along: a read is still a tool call, and a
@@ -2895,6 +2901,7 @@ impl ToolInvoker for CompositeToolInvoker {
.with_sandbox(sandbox)
.with_hidden_root(hidden.as_deref())
.with_scratch_root(&scratch)
+ .with_pkg_cache(pkg_cache.as_ref())
.with_read_roots(&read_roots)
.with_web_search(web_search.as_ref())
.with_hooks(&hooks, planning, Some(hook_sink));
@@ -3535,9 +3542,9 @@ fn build_run_system_prompt(
let base = override_prompt.or(assistant_instructions);
match project_root {
Some(root) => {
- // No sandbox, no scratch: unconfined, the shell already has the
- // real `/tmp`, and advertising a scratch nothing binds would send
- // the model to a directory only the filesystem tools can see.
+ // No sandbox, no scratch: unconfined, the shell already writes
+ // wherever the user can with the host's own temp dir, and nothing
+ // would create or clean up a scratch the prompt advertised.
let scratch = sandbox.then(|| scratch_root_for(session_id, root));
// A subagent (the run with an override prompt) has no memory, so
// its prompt carries no memory index or memory instructions.
@@ -3669,29 +3676,65 @@ pub(crate) async fn context_advertised_tools(
tools
}
-/// 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. Pure path math -- [`ensure_scratch_dir`] is what creates it
-/// -- so the system prompt can name the scratch before the tools are built.
+/// Where this run's scratch lives: `<cache>/jan/<project slug>/scratch/<session>`
+/// (see [`crate::core::agent::project::scratch_dir`]). 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. Pure path math --
+/// [`ensure_scratch_dir_path`] is what creates it -- so the system prompt can
+/// name the scratch before the tools are built.
///
-/// A session-less run gets a throwaway in the host temp dir, never a directory
+/// A session-less run gets a throwaway beside the sessions', never a directory
/// inside the project: a project-level scratch is shared by every session
/// working that checkout, accumulates spill files with no owner to remove them,
/// and fails outright on a read-only checkout. Nothing wipes a throwaway at run
/// end (there is no session boundary to hang it on), so it is left to the
/// startup sweep -- which is why it must live where that sweep looks.
+///
+/// [`ensure_scratch_dir_path`]: tauri_plugin_agent_tools::workspace::ensure_scratch_dir_path
fn scratch_root_for(
session_id: Option<&str>,
- _project_root: &std::path::Path,
+ project_root: &std::path::Path,
) -> std::path::PathBuf {
static ANONYMOUS_RUN: AtomicUsize = AtomicUsize::new(0);
- match session_id {
- Some(session) => tauri_plugin_agent_tools::workspace::scratch_dir(session),
- None => tauri_plugin_agent_tools::workspace::scratch_dir(&format!(
+ let session = match session_id {
+ Some(session) => session.to_string(),
+ None => format!(
"anon-{}-{}",
std::process::id(),
ANONYMOUS_RUN.fetch_add(1, Ordering::Relaxed)
- )),
+ ),
+ };
+ crate::core::agent::project::scratch_dir(project_root, &session)
+}
+
+/// The run's package cache: prepared whenever its shell runs confined --
+/// sandboxed, or a read-only child, which is confined even with the sandbox
+/// off and whose read-only `$HOME` leaves the host caches unwritable. `None`
+/// unconfined, where the shell keeps the host's own caches and nothing would
+/// bind one.
+///
+/// A sandboxed run whose cache cannot be prepared (an unreadable
+/// `~/.cargo/config.toml`, a cache folder another user owns) runs without one,
+/// with a warning: the cache only spares downloads, and the run's scratch still
+/// masks the Jan cache root, so losing it must not cost the user the run. A
+/// read-only child with the sandbox off has no scratch, and the package cache
+/// is the only thing masking that root from its readable `$HOME`, so there the
+/// error stands rather than exposing every project's scratch.
+async fn pkg_cache_for(
+ sandbox: bool,
+ workspace_readonly: bool,
+ project_root: &std::path::Path,
+) -> Result<Option<tauri_plugin_agent_tools::workspace::PkgCache>, String> {
+ if !(sandbox || workspace_readonly) {
+ return Ok(None);
+ }
+ match crate::core::agent::project::prepare_pkg_cache(project_root).await {
+ Ok(pkg) => Ok(Some(pkg)),
+ Err(e) if sandbox => {
+ log::warn!("agent: running without a package cache: {e}");
+ Ok(None)
+ }
+ Err(e) => Err(e),
}
}
@@ -4246,10 +4289,22 @@ async fn orchestrate_inner(
// directory as its sanctioned scratch. Skipped entirely when the shell
// is unconfined: nothing binds it, so creating it would only leave an
// empty directory behind.
+ //
+ // Claimed for as long as this turn runs, and freshened each turn, so
+ // another Jan process's startup sweep (whose keep list cannot name
+ // this session) leaves it alone; see `claim_scratch_dir`.
let scratch_root = scratch_root_for(session_id.as_deref(), root);
- if settings.sandbox {
- tauri_plugin_agent_tools::workspace::ensure_scratch_dir_path(&scratch_root).await?;
- }
+ let _scratch_claim = if settings.sandbox {
+ Some(tauri_plugin_agent_tools::workspace::claim_scratch_dir(&scratch_root).await?)
+ } else {
+ None
+ };
+ let pkg_cache = pkg_cache_for(
+ settings.sandbox,
+ child_scope.as_ref().is_some_and(|scope| scope.read_only),
+ root,
+ )
+ .await?;
let (store_root, memory_home, cross_project) =
crate::core::agent::project::memory_roots(root);
let tool_notices = settings.tool_notices;
@@ -4265,6 +4320,7 @@ async fn orchestrate_inner(
escalation: settings.escalation,
hidden_root: crate::core::agent::project::hidden_root(settings.sandbox),
scratch_root: scratch_root.clone(),
+ pkg_cache,
env_passthrough: settings.env_passthrough,
// A child's workspace adds its build and cache dirs on top.
env_set: merge_env_set(
@@ -6647,21 +6703,21 @@ mod tests {
#[test]
fn scratch_root_is_session_keyed_and_never_lands_in_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")
- );
+ // Under the project's own cache folder, whose slug is its store's.
+ let store = tauri_plugin_agent_tools::workspace::project_store_in(std::path::Path::new("/h"), &root);
+ let cache = crate::core::agent::project::jan_cache_root().join(store.file_name().unwrap());
+ assert_eq!(scratch_root_for(Some("sess-1"), &root), cache.join("scratch/sess-1"));
// Two sessions never share one scratch.
assert_ne!(
scratch_root_for(Some("sess-1"), &root),
scratch_root_for(Some("sess-2"), &root)
);
- // A session-less run still needs a scratch to bind, but it belongs in
- // the host temp dir: a directory inside the project would be shared by
- // every session on that checkout and never collected.
+ // A session-less run still needs a scratch to bind, but it belongs
+ // where the startup sweep looks: a directory inside the project would
+ // be shared by every session on that checkout and never collected.
let anon = scratch_root_for(None, &root);
assert!(!anon.starts_with(&root), "scratch leaked into the project");
- assert!(anon.starts_with(std::env::temp_dir()));
+ assert!(anon.starts_with(cache.join("scratch")), "{anon:?}");
assert_ne!(
anon,
scratch_root_for(None, &root),
@@ -6669,6 +6725,43 @@ mod tests {
);
}
+ /// A confined run gets its project's package cache under the project's
+ /// cache folder, beside the scratch; an unconfined one gets none, and
+ /// creates nothing. A read-only child is confined with the sandbox off
+ /// (the CLI default), so it gets one too.
+ #[tokio::test]
+ async fn pkg_cache_is_prepared_only_for_a_confined_run() {
+ let root = unique_project_root();
+ let cache = crate::core::agent::project::project_cache_dir(&root);
+ assert_eq!(pkg_cache_for(false, false, &root).await.unwrap(), None);
+ assert!(!cache.join("pkg").exists());
+ let reader = pkg_cache_for(false, true, &root).await.unwrap().expect("read-only");
+ assert_eq!(reader.root, cache.join("pkg"));
+ let pkg = pkg_cache_for(true, false, &root).await.unwrap().expect("sandboxed");
+ assert_eq!(pkg.root, cache.join("pkg"));
+ assert!(pkg.root.join("cargo").is_dir());
+ assert_ne!(
+ pkg.root,
+ pkg_cache_for(true, false, &unique_project_root()).await.unwrap().unwrap().root,
+ "two projects never share a package cache"
+ );
+ }
+
+ /// A sandboxed run whose cache cannot be prepared runs without one; a
+ /// read-only child with the sandbox off, which only the package cache
+ /// masks the Jan cache root for, still refuses. Here the package folder's
+ /// name is taken by a file.
+ #[tokio::test]
+ async fn an_unpreparable_pkg_cache_leaves_the_run_without_one() {
+ let root = unique_project_root();
+ let cache = crate::core::agent::project::project_cache_dir(&root);
+ std::fs::create_dir_all(&cache).unwrap();
+ std::fs::write(cache.join("pkg"), "not a folder").unwrap();
+ assert_eq!(pkg_cache_for(true, false, &root).await, Ok(None));
+ assert_eq!(pkg_cache_for(true, true, &root).await, Ok(None));
+ assert!(pkg_cache_for(false, true, &root).await.is_err());
+ }
+
#[test]
fn subagent_prompt_reuses_main_prompt_builder() {
let root = unique_project_root();
@@ -10093,7 +10186,8 @@ 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"),
+ scratch_root: std::env::temp_dir().join("jan-loop-test-scratch"),
+ pkg_cache: None,
env_passthrough: Vec::new(),
env_set: Vec::new(),
web_search: None,
@@ -11468,9 +11562,10 @@ mod tests {
assert_eq!(run_session_start(None, None), SessionStart::capture(None));
}
- /// An unconfined run has no scratch, so the prompt must not name one: the
- /// shell sees the real `/tmp` and would never find the directory the
- /// scratch line points at.
+ /// An unconfined run has no scratch, so the prompt must not name one:
+ /// nothing would create or clean up the directory the line points at. A
+ /// confined run names the real path, the same one an escalated command
+ /// would find.
#[test]
fn unsandboxed_prompt_does_not_advertise_a_scratch() {
let root = unique_project_root();
@@ -11488,6 +11583,15 @@ mod tests {
.expect("project prompt")
.as_prompt();
assert!(confined.contains("Scratch:"), "{confined}");
+ let scratch = scratch_root_for(Some("s1"), &root);
+ assert!(
+ // The prompt names paths with forward slashes on every OS.
+ confined.contains(&format!(
+ "Scratch: `{}`",
+ scratch.to_string_lossy().replace('\\', "/")
+ )),
+ "{confined}"
+ );
let bare = build_run_system_prompt(
None,
Some("do things"),
diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rs
index 1139dff49..e42e6ad55 100644
--- a/src-tauri/src/core/agent/project.rs
+++ b/src-tauri/src/core/agent/project.rs
@@ -442,6 +442,42 @@ pub(crate) fn jan_home() -> Option<PathBuf> {
}
}
+/// The Jan cache root (`<OS cache dir>/jan`), where session scratch lives.
+/// Tests resolve a per-process temp directory instead, so no test writes into
+/// the developer's real cache.
+pub(crate) fn jan_cache_root() -> PathBuf {
+ #[cfg(test)]
+ {
+ std::env::temp_dir().join(format!("jan-app-test-cache-{}", std::process::id()))
+ }
+ #[cfg(not(test))]
+ {
+ tauri_plugin_agent_tools::workspace::jan_cache_root()
+ }
+}
+
+/// `project_root`'s folder under the Jan cache root, `<cache>/jan/<slug>`,
+/// with the same slug as its store under `~/.jan/projects/`.
+pub(crate) fn project_cache_dir(project_root: &Path) -> PathBuf {
+ tauri_plugin_agent_tools::workspace::project_cache_dir_in(&jan_cache_root(), Some(project_root))
+}
+
+/// A CLI/TUI session's scratch: `<cache>/jan/<slug>/scratch/<session>`. The
+/// one place the app derives it, so the prompt, the tools, the subagent
+/// replay and the exit trash all name the same directory.
+pub(crate) fn scratch_dir(project_root: &Path, session: &str) -> PathBuf {
+ tauri_plugin_agent_tools::workspace::scratch_dir_in(&project_cache_dir(project_root), session)
+}
+
+/// Prepare `project_root`'s package cache, `<cache>/jan/<slug>/pkg`, for a
+/// sandboxed run: shared by the project's sessions (subagent worktrees map to
+/// the same slug), never by another project's.
+pub(crate) async fn prepare_pkg_cache(
+ project_root: &Path,
+) -> Result<tauri_plugin_agent_tools::workspace::PkgCache, String> {
+ tauri_plugin_agent_tools::workspace::prepare_pkg_cache(&project_cache_dir(project_root)).await
+}
+
/// The Jan home the general tools and the sandboxed shell may not reach while
/// `sandbox` is on (see `workspace::hidden_root`). Resolved through [`jan_home`]
/// so tests hide their temp home, not the developer's.
diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rs
index 971931a4d..b51da330a 100644
--- a/src-tauri/src/core/agent/subagent.rs
+++ b/src-tauri/src/core/agent/subagent.rs
@@ -10,7 +10,6 @@ use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use tauri_plugin_agent_tools::permissions::ToolPermissions;
-use tauri_plugin_agent_tools::tools::sandbox::scratch_display_path;
use tauri_plugin_agent_tools::tools::spill::{
compose_subagent_result, fill_subagent_result, reserve_blackboard_result,
SUBAGENT_INLINE_MAX_BYTES,
@@ -2553,10 +2552,6 @@ async fn assign_dispatch(
// a ref possibly a network fetch, and placing the child reads its branch,
// which would otherwise stall every other task on this runtime worker
// until git returns.
- let scratch = parent_args
- .session_id
- .as_deref()
- .map(tauri_plugin_agent_tools::workspace::scratch_dir);
let (workspace, placement, lease) = {
let scope = scope.clone();
let root = project_root.clone();
@@ -2577,7 +2572,7 @@ async fn assign_dispatch(
return Err(SubagentError::Cancelled);
}
let placement =
- crate::core::agent::child_workspace::place(&ws, &root, scratch.as_deref());
+ crate::core::agent::child_workspace::place(&ws, &root);
Ok((ws, placement, lease))
})
.await
@@ -2627,7 +2622,7 @@ fn start_dispatch(
let run_id = next_subagent_run_id(&name);
let (tx, rx) = tokio::sync::oneshot::channel();
let result_file = scratch.and_then(|s| {
- reserve_blackboard_result(s, &name).map(|path| (scratch_display_path(Some(s), &path), path))
+ reserve_blackboard_result(s, &name).map(|path| (path.to_string_lossy().into_owned(), path))
});
let display_path = result_file.as_ref().map(|(display, _)| display.clone());
@@ -2697,12 +2692,11 @@ fn start_dispatch(
tauri_plugin_agent_tools::tools::spill::SUBAGENT_DIR,
)
});
- // The session file the blackboard entry links to, in the model's spelling.
+ // The session file the blackboard entry links to, by its real path.
let session_display = transcript_dir.as_ref().map(|dir| {
- scratch_display_path(
- scratch,
- &crate::core::agent::subagent_session::session_file(dir, &name),
- )
+ crate::core::agent::subagent_session::session_file(dir, &name)
+ .to_string_lossy()
+ .into_owned()
});
let slot = ChildSlot::new();
let slot_task = slot.clone();
@@ -2902,6 +2896,8 @@ pub(crate) async fn spawn_memory_tidy(
..parent.clone()
};
let args = memory_tidy_args(parent_args, budget);
+ // No scratch: its answer comes back through `await_subagent`, not the
+ // blackboard.
let prepared = assign_dispatch(scope, &args, resolved, req, parent).await?;
start_dispatch(scope, &args, prepared, events, None, false)
}
@@ -3143,7 +3139,7 @@ pub(crate) async fn spawn_dispatch_plan(
let phase_count = plan.phases.len();
let total_subagents = plan.phases.iter().map(|p| p.subagents.len()).sum();
let names = plan.names.clone();
- let blackboard_dir = scratch.map(|s| scratch_display_path(Some(s), &blackboard_dir_path(s)));
+ let blackboard_dir = scratch.map(|s| blackboard_dir_path(s).to_string_lossy().into_owned());
let multi = phase_count > 1;
if multi {
@@ -3328,7 +3324,7 @@ async fn run_phase_plan(
// Only read when there is a scratch, which `inputs` being non-empty implies.
let dir = scratch
.as_deref()
- .map(|s| scratch_display_path(Some(s), &blackboard_dir_path(s)))
+ .map(|s| blackboard_dir_path(s).to_string_lossy().into_owned())
.unwrap_or_default();
let mut ids = Vec::with_capacity(phase.subagents.len());
let mut names = Vec::with_capacity(phase.subagents.len());
@@ -5586,10 +5582,9 @@ pub(crate) mod tests {
let entry = tauri_plugin_agent_tools::tools::spill::read_blackboard_result(&scratch, "reviewer")
.expect("blackboard entry");
- let session = scratch_display_path(
- Some(&scratch),
- &crate::core::agent::subagent_session::session_path(&scratch, "reviewer"),
- );
+ let session = crate::core::agent::subagent_session::session_path(&scratch, "reviewer")
+ .to_string_lossy()
+ .into_owned();
assert!(entry.starts_with("ERROR: "), "the result leads: {entry}");
assert!(entry.ends_with(&session_link(&session)), "{entry}");
let _ = std::fs::remove_dir_all(&root);
diff --git a/src-tauri/src/core/agent/subagent_session.rs b/src-tauri/src/core/agent/subagent_session.rs
index ef18bbd7b..eda67d44c 100644
--- a/src-tauri/src/core/agent/subagent_session.rs
+++ b/src-tauri/src/core/agent/subagent_session.rs
@@ -509,10 +509,10 @@ mod tests {
#[test]
fn a_subagent_session_lives_under_the_scratch_subagents_dir() {
- let scratch = Path::new("/tmp/jan-agent-s");
+ let scratch = Path::new("/c/jan/p-1/scratch/s");
assert_eq!(
session_path(scratch, "explore-2"),
- Path::new("/tmp/jan-agent-s/subagents/explore-2-session.jsonl")
+ Path::new("/c/jan/p-1/scratch/s/subagents/explore-2-session.jsonl")
);
}
@@ -550,12 +550,20 @@ mod tests {
assert_eq!(loaded.record, session_log::SessionRecord::default());
}
- /// The session file is in the scratch, so ending the session deletes it.
+ /// The session file is in the scratch, so ending the session takes it
+ /// away with the scratch (the CLI/TUI exit path: into trash).
#[tokio::test]
async fn a_subagent_session_file_is_deleted_with_the_session_scratch() {
- use tauri_plugin_agent_tools::workspace::{ensure_scratch_dir, remove_scratch_dir};
+ use tauri_plugin_agent_tools::workspace::{ensure_scratch_dir_path, trash_scratch_dir_in};
+ let project = tmp();
let session = format!("subagent-session-exit-{}", std::process::id());
- let scratch = ensure_scratch_dir(&session).await.unwrap();
+ let cache = crate::core::agent::project::project_cache_dir(project.path());
+ let scratch = ensure_scratch_dir_path(&crate::core::agent::project::scratch_dir(
+ project.path(),
+ &session,
+ ))
+ .await
+ .unwrap();
let dir = tauri_plugin_agent_tools::tools::spill::validated_subdir(
&scratch,
tauri_plugin_agent_tools::tools::spill::SUBAGENT_DIR,
@@ -567,8 +575,9 @@ mod tests {
load(&scratch, "w").unwrap().record.meta.unwrap().status,
RunStatus::Finished
);
- remove_scratch_dir(&session).await.unwrap();
+ trash_scratch_dir_in(&cache, &session).await.unwrap();
assert!(!path.exists());
assert!(!session_log::lock_path(&path).exists());
+ let _ = std::fs::remove_dir_all(&cache);
}
}
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 3ffed8418..f44e31c52 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -1572,7 +1572,7 @@ fn build_cli_orchestration_args(
} else {
crate::core::agent::plan::RunMode::Normal
},
- // Key the persistent bash `/tmp` scratch to this session. Generated per
+ // Key the persistent bash 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.
@@ -2565,12 +2565,16 @@ async fn run_agent_loop(
// start to report.
if let Some(root) = args.project_root.clone() {
let sweep_tx = tx.downgrade();
- crate::core::agent::child_workspace::spawn_startup_sweep(root, move |text| {
- sweep_tx
- .upgrade()
- .is_some_and(|tx| tx.send(StreamEvent::Notice { text }).is_ok())
- && format.shows_notices()
- });
+ crate::core::agent::child_workspace::spawn_startup_sweep(
+ root,
+ args.session_id.clone(),
+ move |text| {
+ sweep_tx
+ .upgrade()
+ .is_some_and(|tx| tx.send(StreamEvent::Notice { text }).is_ok())
+ && format.shows_notices()
+ },
+ );
}
let reader = input.as_ref().map(|input| {
spawn_input_reader(
@@ -2714,9 +2718,10 @@ async fn run_agent_loop(
);
}
// 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::trash_scratch_dir(session).await;
+ // the persistent bash scratch this run used, in its project's cache folder.
+ if let (Some(session), Some(root)) = (args.session_id.as_deref(), args.project_root.as_deref()) {
+ let cache = crate::core::agent::project::project_cache_dir(root);
+ let _ = workspace::trash_scratch_dir_in(&cache, session).await;
}
if aborted {
return Ok(());
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 2800bf5fe..24738bfa9 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -13937,7 +13937,10 @@ pub async fn run(
args.max_parallel_subagents,
));
args.subagent_bg = Some(subagent_set.clone());
- let session_scratch = args.session_id.clone();
+ // The project cache folder the run keys its scratch under, with the id.
+ let session_scratch = args.session_id.clone().zip(
+ args.project_root.as_deref().map(crate::core::agent::project::project_cache_dir),
+ );
let args = Arc::new(args);
// Resolve the colour theme before anything highlights: `warm` below caches
@@ -14032,6 +14035,7 @@ pub async fn run(
if let Some(reports) = app.cleanup_reports.as_ref().map(mpsc::UnboundedSender::downgrade) {
crate::core::agent::child_workspace::spawn_startup_sweep(
app.project_root.clone(),
+ args.session_id.clone(),
move |kept| reports.upgrade().is_some_and(|reports| reports.send(kept).is_ok()),
);
}
@@ -14157,15 +14161,15 @@ pub async fn run(
// holds its worktree, which would otherwise outlive the process even
// when empty.
app.subagent_set.abort_all();
- // Then the persistent bash `/tmp` scratch its turns shared and its
+ // Then the persistent bash scratch its turns shared and its
// subagents' worktrees that hold nothing go, together (both are renames
// into trash); the rest are named on the real terminal, since they are
// what is left to merge. The worktrees on the blocking pool, as every
// worktree sweep is: it runs git per worktree.
let workspaces = app.subagent_set.workspaces.clone();
let scratch = async {
- if let Some(session) = session_scratch.as_deref() {
- let _ = workspace::trash_scratch_dir(session).await;
+ if let Some((session, cache)) = &session_scratch {
+ let _ = workspace::trash_scratch_dir_in(cache, session).await;
}
};
let ((), kept) = tokio::join!(
@@ -21707,7 +21711,9 @@ fn agent_picker_items(
/// unreadable file, or a file another run of the same name left behind keeps
/// the rows as they are.
fn replay_finished_agent(app: &mut App, run_id: &str) {
- let Some(session) = app.args.as_ref().and_then(|a| a.session_id.clone()) else {
+ let Some(scratch) = app.args.as_ref().and_then(|a| {
+ Some(crate::core::agent::project::scratch_dir(a.project_root.as_deref()?, a.session_id.as_deref()?))
+ }) else {
return;
};
let Some(block) = app
@@ -21718,7 +21724,6 @@ fn replay_finished_agent(app: &mut App, run_id: &str) {
else {
return;
};
- let scratch = tauri_plugin_agent_tools::workspace::scratch_dir(&session);
match crate::core::agent::subagent_session::load(&scratch, &block.panel.name) {
Ok(loaded) if loaded.record.meta.as_ref().is_some_and(|m| m.run_id == run_id) => {
block.panel.replay_record(&loaded.record);
@@ -40866,7 +40871,8 @@ fn a() {}
name: "alpha".into(),
error: None,
});
- let scratch = tauri_plugin_agent_tools::workspace::scratch_dir(&session);
+ let root = app.args.as_ref().and_then(|a| a.project_root.clone()).expect("a project");
+ let scratch = crate::core::agent::project::scratch_dir(&root, &session);
std::fs::create_dir_all(scratch.join("subagents")).unwrap();
let dir = tauri_plugin_agent_tools::tools::spill::validated_subdir(
&scratch,
@@ -49045,6 +49051,7 @@ fn a() {}
tauri_plugin_agent_tools::tools::monitor::MonitorCtx {
project_root: root.to_path_buf(),
scratch_root: None,
+ pkg_cache: None,
mask_root: None,
hidden_root: None,
read_roots: Vec::new(),
diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.ts
index 115cc8681..a23cae27b 100644
--- a/web-app/src/lib/agentTools.ts
+++ b/web-app/src/lib/agentTools.ts
@@ -413,9 +413,8 @@ export async function cancelAgentThreadBash(sessionId: string): Promise<void> {
}
}
-/** A file claimed for a subagent's answer: the name to fill it by, and the
- * model-visible path (`/tmp/subagents/<id>.md`, where the scratch is mounted
- * over `/tmp`) the parent agent can `read`. */
+/** A file claimed for a subagent's answer: the name to fill it by, and its
+ * real path in the session scratch, which the parent agent can `read`. */
export type SubagentResultFile = { file: string; path: string }
/**
@@ -453,17 +452,6 @@ export async function fillSubagentResult(
}
}
-/**
- * The model-visible blackboard directory on Linux only, where the session
- * scratch is bound over `/tmp` (see `scratch_display_path`, whose `/tmp`
- * mapping is gated on `target_os = "linux"`), so a finished child's answer is
- * read from `/tmp/blackboard/<name>.md`. On macOS/Windows the scratch is a real
- * host path, so callers must not advertise this constant there. Reported up
- * front by the plan summary; each child's completion notice always carries the
- * exact path `writeBlackboard` returns.
- */
-export const BLACKBOARD_DIR_DISPLAY = '/tmp/blackboard'
-
/**
* Write a finished subagent's answer to `blackboard/<name>.md` in the session
* scratch -- the name-keyed coordination file a phased dispatch's next phase
diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsx
index 29915458a..b471c0601 100644
--- a/web-app/src/routes/cowork.tsx
+++ b/web-app/src/routes/cowork.tsx
@@ -107,12 +107,10 @@ import {
getSandboxStatus,
sandboxEnforces,
writeBlackboard,
- BLACKBOARD_DIR_DISPLAY,
importAttachment,
cancelAgentThreadBash,
activeAgentMonitorIds,
} from '@/lib/agentTools'
-import { isPlatformTauri } from '@/lib/platform'
import { monitorLaneFor, type MonitorLane } from '@/lib/coworkMonitor'
import { CoworkParkedNotice } from '@/containers/CoworkParkedNotice'
import type { MonitorView } from '@/types/coworkSession'
@@ -829,16 +827,11 @@ function CoworkPage() {
}
const model = transport.model
- // `BLACKBOARD_DIR_DISPLAY` (/tmp/blackboard) is only where the
- // scratch surfaces on Linux, where the sandbox binds it over
- // /tmp (`scratch_display_path`). On macOS/Windows the scratch
- // is a real host path we don't know up front, so advertise no
- // dir there and let each completion notice carry the exact
- // path `writeBlackboard` returns.
- const blackboardDir =
- isPlatformTauri() && environment.os === 'linux'
- ? BLACKBOARD_DIR_DISPLAY
- : null
+ // The scratch is a real host path (in the OS cache dir) on
+ // every platform, which this side does not know up front, so
+ // no dir is advertised: each completion notice carries the
+ // exact path `writeBlackboard` returns.
+ const blackboardDir = null
// The plan hold keeps the run alive across the whole plan,
// including the gap between one phase finishing and the next