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.

test(agent-tools): make the unit tests pass on Windows and run them in Windows CI (#9146)

James Dam12d4f0fdd541
diff --git a/.github/workflows/jan-linter-and-test.yml b/.github/workflows/jan-linter-and-test.yml
index 5a06231c7..b632c3727 100644
--- a/.github/workflows/jan-linter-and-test.yml
+++ b/.github/workflows/jan-linter-and-test.yml
@@ -261,6 +261,14 @@ jobs:
sudo apt update
sudo apt install -y libglib2.0-dev libatk1.0-dev libpango1.0-dev libgtk-3-dev libsoup-3.0-dev libwebkit2gtk-4.1-dev librsvg2-dev libfuse2 webkit2gtk-driver
+ # The agent-tools unit tests run the shell tool inside its Linux sandbox,
+ # bubblewrap, which needs unprivileged user namespaces; Ubuntu 24.04's
+ # AppArmor default refuses those.
+ - name: Install the shell sandbox
+ run: |
+ sudo apt install -y bubblewrap
+ sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
+
- name: 'Cleanup cache'
continue-on-error: true
run: |
diff --git a/Makefile b/Makefile
index 2d5eb28bf..d7d32a983 100644
--- a/Makefile
+++ b/Makefile
@@ -154,7 +154,9 @@ test-rust: stub-resources
cargo test --locked --manifest-path src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml
cargo test --locked --manifest-path src-tauri/utils/Cargo.toml
# No --locked: this crate gitignores its Cargo.lock, as rust-check.yml assumes.
- cargo test --manifest-path src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml --no-default-features --test sandbox_spawn
+ # The unit tests that run the shell for real are ignored on Windows, where
+ # sandbox_spawn covers them (it needs its own main to host the helper re-exec).
+ cargo test --manifest-path src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml --no-default-features --lib --test sandbox_spawn
# protocol/schema.json is committed, and core::cli::protocol_schema fails when it
# no longer matches the types that define the channel. This is the fix for that
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 7098cc049..c92398cb9 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
@@ -1424,6 +1424,10 @@ mod tests {
/// the OS can confine it and is refused when it cannot. Asserting both arms
/// keeps the fallback honest on hosts (and CI images) with no backend.
#[tokio::test]
+ #[cfg_attr(
+ windows,
+ ignore = "re-execs the test binary as the AppContainer helper; covered by tests/sandbox_spawn.rs"
+ )]
async fn bash_runs_only_when_the_sandbox_can_enforce() {
let data = unique_data_folder();
let df = data.to_string_lossy().to_string();
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 0faf3111f..3dc916f15 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
@@ -2402,6 +2402,8 @@ mod tests {
async fn write_reports_resolved_path_when_it_escapes_the_project() {
let root = unique_root();
let outside = root.parent().unwrap().join("jan_escape_probe.txt");
+ // A probe left by an aborted run would turn this into a "No change" write.
+ let _ = std::fs::remove_file(&outside);
let out = execute_builtin(
lookup("write").unwrap(),
&json!({"path": "../jan_escape_probe.txt", "content": "x"}),
@@ -2409,11 +2411,24 @@ mod tests {
)
.await;
assert!(outside.exists(), "precondition: the write escapes the root");
+ assert!(!out.contains(".."), "must not echo the raw path: {out}");
+ // Compare the named path by what it resolves to, not by spelling: on
+ // Windows the message uses `/` separators, and the temp dir may be
+ // spelled with an 8.3 short name on one side and not the other.
+ let shown = out
+ .strip_prefix("Created ")
+ .and_then(|rest| rest.rsplit_once(" ("))
+ .map(|(path, _)| path)
+ .unwrap_or_else(|| panic!("unexpected message shape: {out}"));
assert!(
- out.contains(outside.to_str().unwrap()),
+ Path::new(shown).is_absolute(),
+ "an escape is named by its absolute path, got: {out}"
+ );
+ assert_eq!(
+ std::fs::canonicalize(shown).ok(),
+ std::fs::canonicalize(&outside).ok(),
"must name the real destination, got: {out}"
);
- assert!(!out.contains(".."), "must not echo the raw path: {out}");
let _ = std::fs::remove_file(&outside);
let _ = std::fs::remove_dir_all(&root);
}
@@ -3171,6 +3186,10 @@ mod tests {
/// output lands there when the command finishes, so the agent reads that file
/// to collect the result instead of a second tool call.
#[tokio::test]
+ #[cfg_attr(
+ windows,
+ ignore = "re-execs the test binary as the AppContainer helper; covered by tests/sandbox_spawn.rs"
+ )]
async fn backgrounded_output_lands_in_the_reported_file() {
let root = unique_root();
let started = execute_builtin(
@@ -3226,6 +3245,10 @@ mod tests {
}
#[tokio::test]
+ #[cfg_attr(
+ windows,
+ ignore = "re-execs the test binary as the AppContainer helper; covered by tests/sandbox_spawn.rs"
+ )]
async fn bash_nonzero_exit_is_not_error() {
let root = unique_root();
let out = execute_builtin(
@@ -3241,6 +3264,10 @@ mod tests {
}
#[tokio::test]
+ #[cfg_attr(
+ windows,
+ ignore = "re-execs the test binary as the AppContainer helper; covered by tests/sandbox_spawn.rs"
+ )]
async fn bash_success_emits_exit_0_marker() {
let root = unique_root();
let out = execute_builtin(
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 d3284393f..c1de5dc66 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
@@ -1085,11 +1085,13 @@ mod shell_kind_tests {
// Relative paths resolve in the working directory it was started in.
let (code, stdout, _) = run("(Convert-Path .).TrimEnd('/', '\\')").await;
assert_eq!(code, Some(0));
+ // Compared resolved: PowerShell reports the physical path, so on macOS
+ // the `/var` temp dir comes back as `/private/var`.
let tmp = std::env::temp_dir();
assert_eq!(
- stdout,
- tmp.to_string_lossy().trim_end_matches(['/', '\\']),
- "starts in the working directory"
+ std::fs::canonicalize(&stdout).ok(),
+ std::fs::canonicalize(&tmp).ok(),
+ "starts in the working directory: {stdout}"
);
}
}
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 2a25f9fdc..dd9f98557 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
@@ -593,11 +593,16 @@ mod tests {
file.to_string_lossy()
);
}
- // Outside the scratch the path is untouched either way.
+ // 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),
- other.to_string_lossy()
+ if cfg!(windows) {
+ r"\elsewhere\out.txt"
+ } else {
+ "/elsewhere/out.txt"
+ }
);
}
@@ -666,7 +671,10 @@ mod tests {
}
/// `/tmpx` and `/tmp-archive` are not descendants of `/tmp` and must not be
- /// silently redirected into the scratch.
+ /// 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()));
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/tests/sandbox_spawn.rs b/src-tauri/plugins/tauri-plugin-agent-tools/tests/sandbox_spawn.rs
index 24c1fa4a1..a012c8d20 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/tests/sandbox_spawn.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/tests/sandbox_spawn.rs
@@ -9,11 +9,15 @@
//! `harness = false` because the backend re-execs the running binary as its
//! helper: under libtest that re-exec would run the test suite again instead of
//! the spawn, so `main` hands control to the helper before anything else.
+//! For the same reason, the lib's unit tests that run the `shell` tool for real
+//! are ignored on Windows, and their assertions live in `shell_tool` instead.
fn main() {
tauri_plugin_agent_tools::run_sandbox_helper_if_requested();
#[cfg(windows)]
windows::run();
+ #[cfg(windows)]
+ shell_tool::run();
#[cfg(not(windows))]
eprintln!("sandbox_spawn: AppContainer only, nothing to run on this platform");
}
@@ -147,3 +151,95 @@ mod windows {
(out.status.code(), text)
}
}
+
+/// The `shell` tool end to end on Windows: the gate, the sandbox wrap, the spawn
+/// and the result formatting. Mirrors the lib unit tests that are ignored on
+/// Windows because they would re-exec libtest as the helper.
+#[cfg(windows)]
+mod shell_tool {
+ use serde_json::json;
+ use std::path::{Path, PathBuf};
+ use tauri_plugin_agent_tools::tools::{handlers, jail, lookup, ToolContext};
+
+ pub fn run() {
+ let base = std::env::temp_dir().join(format!("jan_shell_tool_{}", std::process::id()));
+ let ws = base.join("ws");
+ std::fs::create_dir_all(&ws).expect("create workspace");
+ // A store under the test's own dir, so nothing lands in the real Jan home.
+ let store = tauri_plugin_agent_tools::workspace::project_store_in(&base.join("home"), &ws);
+ let rt = tokio::runtime::Runtime::new().expect("runtime");
+ let shell = |command: &str, extra: serde_json::Value| {
+ let mut args = json!({ "command": command });
+ if let (Some(args), Some(extra)) = (args.as_object_mut(), extra.as_object()) {
+ args.extend(extra.clone());
+ }
+ let ctx = ToolContext::new(&ws, &store, &[]);
+ rt.block_on(handlers::execute_builtin(
+ lookup("shell").unwrap(),
+ &args,
+ &ctx,
+ ))
+ .0
+ };
+
+ // commands::tests::bash_runs_only_when_the_sandbox_can_enforce
+ let out = shell("echo hi", json!({}));
+ if jail::backend().enforces() {
+ assert!(
+ !out.starts_with("ERROR"),
+ "sandboxed shell should run: {out}"
+ );
+ assert!(out.contains("hi"), "got: {out}");
+ } else {
+ assert!(
+ out.contains("no OS sandbox"),
+ "the model must be told why: {out}"
+ );
+ }
+
+ // handlers::tests::bash_success_emits_exit_0_marker
+ let out = shell("echo done", json!({}));
+ assert!(!out.starts_with("ERROR"), "unexpected: {out}");
+ assert!(
+ out.contains("done") && out.contains("[exit 0]"),
+ "unexpected: {out}"
+ );
+
+ // handlers::tests::bash_nonzero_exit_is_not_error
+ let out = shell("echo hi; exit 3", json!({}));
+ assert!(!out.starts_with("ERROR"), "unexpected: {out}");
+ assert!(
+ out.contains("hi") && out.contains("[exit 3]"),
+ "unexpected: {out}"
+ );
+
+ // handlers::tests::backgrounded_output_lands_in_the_reported_file
+ let started = shell("sleep 0.2; echo done", json!({ "timeout": 0 }));
+ let path = started
+ .split("written to ")
+ .nth(1)
+ .and_then(|rest| rest.split(" once it finishes").next())
+ .map(str::trim)
+ .map(PathBuf::from)
+ .unwrap_or_else(|| panic!("notice names the output file: {started}"));
+ let body = wait_for(&path).expect("output file must appear after the command finishes");
+ assert!(body.contains("done"), "unexpected: {body}");
+ assert!(body.contains("[exit 0]"), "carries the exit marker: {body}");
+ let _ = std::fs::remove_file(&path);
+
+ eprintln!("sandbox_spawn: shell tool ok");
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ /// The backgrounded output file appears only once the command has finished
+ /// (atomic rename), so its existence is the completion signal.
+ fn wait_for(path: &Path) -> Option<String> {
+ for _ in 0..100 {
+ if path.exists() {
+ return std::fs::read_to_string(path).ok();
+ }
+ std::thread::sleep(std::time::Duration::from_millis(100));
+ }
+ None
+ }
+}