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-tools): isolate scratch cleanup regression tests

thinhlpgab532f769a38
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 bdc8ad0b7..d93065e59 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
@@ -768,7 +768,6 @@ mod tests {
/// spelled `/tmp/...` where it is bound over the sandbox's `/tmp` and by its
/// real path where nothing is mounted there.
#[tokio::test]
- #[allow(clippy::await_holding_lock)]
async fn escaping_writes_are_refused() {
let data = unique_data_folder();
let df = data.to_string_lossy().to_string();
@@ -799,9 +798,6 @@ mod tests {
// 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".
- // The sweep test collects every scratch in the shared temp dir; without
- // this it can delete ours between the write and the assertion.
- let _guard = crate::workspace::lock_scratch_namespace().await;
let scratch = crate::workspace::ensure_scratch_dir(T_SCRATCH)
.await
.unwrap();
@@ -991,10 +987,8 @@ mod tests {
let _ = std::fs::remove_dir_all(&data);
}
- /// Thread isolation: each conversation gets its own sandbox, and neither a
- /// relative climb-out nor a sibling-thread absolute path reaches the other's
- /// scratch files. `/tmp` is the agent's own (per-thread) scratch, so a read
- /// of `/tmp` from a different thread resolves to that thread's empty scratch.
+ /// Thread isolation: a relative climb-out cannot reach another thread's
+ /// workspace, and each thread sees only its own scratch files.
#[tokio::test]
async fn one_thread_cannot_read_another_threads_files() {
let data = unique_data_folder();
@@ -1031,16 +1025,21 @@ mod tests {
err.message
);
- // `/tmp` is the per-thread scratch: t1's scratch (written by its shell)
- // is not visible to t2, whose own scratch is empty.
+ // The tool-visible scratch path follows the shell: `/tmp` on Linux,
+ // the real per-thread directory on macOS and Windows.
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 out = execute_tool(
df.clone(),
t2.into(),
None,
"read".into(),
- json!({"path": "/tmp/secret.txt"}),
+ json!({"path": requested}),
None,
None,
None,
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs
index de72a2bca..701079ce8 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
@@ -124,17 +124,7 @@ pub enum Decision {
Prompt(PromptKind),
}
-/// Decide how a built-in tool call should be gated, combining the static
-/// agent.toml policy, capability class, sandbox escape, and session grants.
-///
-/// Precedence: deny (agent.toml) > explicit allow/allow_write (agent.toml) >
-/// session grant > capability rules. Reads inside the project are silently
-/// allowed; reads that escape the project, and all writes/exec, prompt (unless
-/// already granted this session or pre-approved in agent.toml).
-///
-/// The sandbox geometry is bundled in [`GateContext`] so callers describe the
-/// filesystem and hiding policy once instead of repeating four trailing args.
-
+/// Filesystem roots and hiding policy used when gating a tool call.
#[derive(Debug, Clone, Copy)]
pub struct GateContext<'a> {
/// The project root: paths inside it are the agent's own workspace.
@@ -147,6 +137,13 @@ pub struct GateContext<'a> {
pub hide_jan: bool,
}
+/// Decide how a built-in tool call should be gated, combining the static
+/// agent.toml policy, capability class, sandbox escape, and session grants.
+///
+/// Precedence: deny (agent.toml) > explicit allow/allow_write (agent.toml) >
+/// session grant > capability rules. Reads inside the project are silently
+/// allowed; reads that escape the project, and all writes/exec, prompt (unless
+/// already granted this session or pre-approved in agent.toml).
pub fn resolve_decision(
tool: &BuiltinTool,
args: &serde_json::Value,
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 0736d2c51..1b2b17769 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs
@@ -245,13 +245,12 @@ const SCRATCH_STALE_AFTER: std::time::Duration = std::time::Duration::from_secs(
/// 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(SCRATCH_STALE_AFTER).await
+ sweep_scratch_older_than(&std::env::temp_dir(), SCRATCH_STALE_AFTER).await
}
-/// [`sweep_stale_scratch_dirs`] with an explicit age, so a test can collect a
-/// scratch it just created instead of waiting a day.
-async fn sweep_scratch_older_than(max_age: std::time::Duration) -> usize {
- let Ok(mut entries) = tokio::fs::read_dir(std::env::temp_dir()).await else {
+/// 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 {
return 0;
};
let mut removed = 0;
@@ -457,25 +456,6 @@ pub fn workspace_filename(name: &str) -> Result<String, String> {
Ok(format!("{stem}.md"))
}
-/// Serialises tests that touch the *global* scratch namespace.
-///
-/// `sweep_scratch_older_than` collects every scratch dir in the shared host temp
-/// dir, so running it beside a test that needs its own scratch alive is a race:
-/// the sweep deletes the directory the other test is mid-way through using. Any
-/// test that either sweeps or depends on a live scratch takes this first.
-#[cfg(test)]
-pub(crate) static SCRATCH_NAMESPACE_LOCK: std::sync::LazyLock<tokio::sync::Mutex<()>> =
- std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));
-
-/// Take [`SCRATCH_NAMESPACE_LOCK`], awaiting the mutex like the tests that use
-/// it. The guard is held across the async body on purpose: these tests serialise
-/// against the sweep that otherwise races them, and [`tokio::sync::Mutex`] drops
-/// the guard if a task is cancelled, so it cannot deadlock.
-#[cfg(test)]
-pub(crate) async fn lock_scratch_namespace() -> tokio::sync::MutexGuard<'static, ()> {
- SCRATCH_NAMESPACE_LOCK.lock().await
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -545,30 +525,32 @@ mod tests {
/// by age. Nothing else in the temp dir is touched, and a fresh scratch
/// survives the real 24h threshold.
#[tokio::test]
- #[allow(clippy::await_holding_lock)]
async fn stale_scratch_dirs_are_swept_and_fresh_ones_are_not() {
- let session = format!("sweep-stale-{}", std::process::id());
- let _guard = lock_scratch_namespace().await;
- let orphan = ensure_scratch_dir(&session).await.unwrap();
+ 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 = std::env::temp_dir().join(format!("not-a-scratch-{session}"));
+ let bystander = root.join("not-a-scratch");
std::fs::create_dir_all(&bystander).unwrap();
assert_eq!(
- sweep_stale_scratch_dirs().await,
+ sweep_scratch_older_than(&root, SCRATCH_STALE_AFTER).await,
0,
"a fresh scratch is live"
);
assert!(orphan.is_dir());
- assert!(sweep_scratch_older_than(std::time::Duration::ZERO).await >= 1);
+ 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"
);
- let _ = std::fs::remove_dir_all(&bystander);
+ let _ = std::fs::remove_dir_all(&root);
}
/// The scratch root must never be a pre-planted symlink to another