Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent-tools): read-only project mounts, session sandboxes, live output
Akarshan Biswas3e403c8d1501
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs b/src-tauri/plugins/tauri-plugin-agent-tools/build.rsindex a23b63481..1b15e3e6a 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/build.rs@@ -3,6 +3,9 @@ const COMMANDS: &[&str] = &["thread_workspace_path","thread_workspace_delete","thread_workspace_sweep",+ "session_workspace_path",+ "session_workspace_delete",+ "session_workspace_sweep","skill_list","skill_read","skill_write",@@ -14,6 +17,7 @@ const COMMANDS: &[&str] = &["tool_schemas","sandbox_status","execute_tool",+ "execute_tool_streaming",];fn main() {diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.tsindex 169c7c5f5..bfb29556b 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts+++ b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts@@ -1,4 +1,4 @@-import { invoke } from '@tauri-apps/api/core'+import { invoke, Channel } from '@tauri-apps/api/core'import { SkillMeta, ToolResult, ToolSchema } from './types'export { SkillMeta, ToolResult, ToolSchema } from './types'@@ -63,6 +63,43 @@ export async function threadWorkspaceSweep(})}+/** The Cowork session sandbox, created if absent. */+export async function sessionWorkspacePath(+ dataFolder: string,+ sessionId: string+): Promise<string> {+ return await invoke('plugin:agent-tools|session_workspace_path', {+ dataFolder,+ sessionId,+ })+}++/** Delete a Cowork session's sandbox, with its scratch. */+export async function sessionWorkspaceDelete(+ dataFolder: string,+ sessionId: string+): Promise<void> {+ await invoke('plugin:agent-tools|session_workspace_delete', {+ dataFolder,+ sessionId,+ })+}++/**+ * Collect session sandboxes whose sessions no longer exist, returning how many+ * were removed. Separate from the thread sweep: the id spaces are independent,+ * and an empty `keep` is a no-op rather than a full wipe.+ */+export async function sessionWorkspaceSweep(+ dataFolder: string,+ keep: string[]+): Promise<number> {+ return await invoke('plugin:agent-tools|session_workspace_sweep', {+ dataFolder,+ keep,+ })+}+export async function skillList(dataFolder: string,project?: string@@ -196,6 +233,16 @@ export async function sandboxStatus(): Promise<SandboxStatus> {** `allowNetwork` opens the sandboxed shell's network namespace. It defaults to* off, so omitting it is the safe choice.+ *+ * `scope` picks the sandbox namespace: chat threads and Cowork sessions have+ * independent id spaces and independent sweeps.+ *+ * `callId` is echoed on every streamed output chunk, which a backgrounded+ * `bash` needs because it keeps producing output after the tool has returned.+ *+ * `readOnlyProject` attaches a folder the tools may read but never write. It is+ * validated on the Rust side and rejected outright if it overlaps the workspace+ * or the Jan data folder, rather than being silently dropped.*/export async function executeTool(dataFolder: string,@@ -204,7 +251,10 @@ export async function executeTool(args: Record<string, unknown>,project?: string,enabledSkills?: string[],- allowNetwork?: boolean+ allowNetwork?: boolean,+ readOnlyProject?: string,+ scope?: WorkspaceScope,+ callId?: string): Promise<ToolResult> {return await invoke('plugin:agent-tools|execute_tool', {dataFolder,@@ -214,5 +264,45 @@ export async function executeTool(args,enabledSkills,allowNetwork,+ readOnlyProject,+ scope,+ callId,+ })+}++/**+ * `executeTool`, with the tool's output delivered as it is produced.+ *+ * A separate command rather than an optional argument: a Tauri `Channel` is a+ * command argument, not a deserialisable value, so it cannot be wrapped in an+ * optional. Chunks carry a monotonic `seq` and the `callId` they belong to.+ */+export async function executeToolStreaming(+ dataFolder: string,+ threadId: string,+ name: string,+ args: Record<string, unknown>,+ onOutput: Channel<ToolOutputChunk>,+ options?: {+ project?: string+ enabledSkills?: string[]+ allowNetwork?: boolean+ readOnlyProject?: string+ scope?: WorkspaceScope+ callId?: string+ }+): Promise<ToolResult> {+ return await invoke('plugin:agent-tools|execute_tool_streaming', {+ dataFolder,+ threadId,+ name,+ args,+ onOutput,+ project: options?.project,+ enabledSkills: options?.enabledSkills,+ allowNetwork: options?.allowNetwork,+ readOnlyProject: options?.readOnlyProject,+ scope: options?.scope,+ callId: options?.callId,})}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.tsindex 0c93831d4..7870887df 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts+++ b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts@@ -24,3 +24,15 @@ export interface ToolSchema {parameters: Record<string, unknown>}}++/** Which sandbox namespace an id belongs to. */+export type WorkspaceScope = 'thread' | 'session'++/** One fragment of a tool's live output. */+export type ToolOutputChunk = {+ /** Monotonic per call, so a receiver can assert ordering. */+ seq: number+ /** The tool call this belongs to; a backgrounded `bash` needs it. */+ callId: string | null+ text: string+}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.tomlindex 4255da7dc..c3ce9d576 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml@@ -5,6 +5,9 @@ permissions = ["allow-thread-workspace-path","allow-thread-workspace-delete","allow-thread-workspace-sweep",+ "allow-session-workspace-path",+ "allow-session-workspace-delete",+ "allow-session-workspace-sweep","allow-skill-list","allow-skill-read","allow-skill-write",@@ -16,4 +19,5 @@ permissions = ["allow-tool-schemas","allow-sandbox-status","allow-execute-tool",+ "allow-execute-tool-streaming",]diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.jsonindex db3bdf908..5a7831121 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json@@ -306,6 +306,18 @@"const": "deny-execute-tool","markdownDescription": "Denies the execute_tool command without any pre-configured scope."},+ {+ "description": "Enables the execute_tool_streaming command without any pre-configured scope.",+ "type": "string",+ "const": "allow-execute-tool-streaming",+ "markdownDescription": "Enables the execute_tool_streaming command without any pre-configured scope."+ },+ {+ "description": "Denies the execute_tool_streaming command without any pre-configured scope.",+ "type": "string",+ "const": "deny-execute-tool-streaming",+ "markdownDescription": "Denies the execute_tool_streaming command without any pre-configured scope."+ },{"description": "Enables the memory_delete command without any pre-configured scope.","type": "string",@@ -366,6 +378,42 @@"const": "deny-sandbox-status","markdownDescription": "Denies the sandbox_status command without any pre-configured scope."},+ {+ "description": "Enables the session_workspace_delete command without any pre-configured scope.",+ "type": "string",+ "const": "allow-session-workspace-delete",+ "markdownDescription": "Enables the session_workspace_delete command without any pre-configured scope."+ },+ {+ "description": "Denies the session_workspace_delete command without any pre-configured scope.",+ "type": "string",+ "const": "deny-session-workspace-delete",+ "markdownDescription": "Denies the session_workspace_delete command without any pre-configured scope."+ },+ {+ "description": "Enables the session_workspace_path command without any pre-configured scope.",+ "type": "string",+ "const": "allow-session-workspace-path",+ "markdownDescription": "Enables the session_workspace_path command without any pre-configured scope."+ },+ {+ "description": "Denies the session_workspace_path command without any pre-configured scope.",+ "type": "string",+ "const": "deny-session-workspace-path",+ "markdownDescription": "Denies the session_workspace_path command without any pre-configured scope."+ },+ {+ "description": "Enables the session_workspace_sweep command without any pre-configured scope.",+ "type": "string",+ "const": "allow-session-workspace-sweep",+ "markdownDescription": "Enables the session_workspace_sweep command without any pre-configured scope."+ },+ {+ "description": "Denies the session_workspace_sweep command without any pre-configured scope.",+ "type": "string",+ "const": "deny-session-workspace-sweep",+ "markdownDescription": "Denies the session_workspace_sweep command without any pre-configured scope."+ },{"description": "Enables the skill_delete command without any pre-configured scope.","type": "string",@@ -475,10 +523,10 @@"markdownDescription": "Denies the workspace_path command without any pre-configured scope."},{- "description": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-execute-tool`",+ "description": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`","type": "string","const": "default",- "markdownDescription": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-execute-tool`"+ "markdownDescription": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`"}]}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rsindex c1f54f3fe..05a36eab4 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs@@ -135,6 +135,42 @@ pub async fn thread_workspace_sweep(.map_err(Into::into)}+/// The Cowork session sandbox, created if absent.+#[cfg_attr(feature = "tauri", tauri::command)]+pub async fn session_workspace_path(+ data_folder: String,+ session_id: String,+) -> Result<String, AgentToolsError> {+ let dir = workspace::ensure_session_workspace(Path::new(&data_folder), &session_id).await?;+ Ok(dir.to_string_lossy().to_string())+}++/// Delete a Cowork session's sandbox, with its scratch.+#[cfg_attr(feature = "tauri", tauri::command)]+pub async fn session_workspace_delete(+ data_folder: String,+ session_id: String,+) -> Result<(), AgentToolsError> {+ workspace::remove_session_workspace(Path::new(&data_folder), &session_id)+ .await+ .map_err(Into::into)+}++/// Collect session sandboxes whose sessions no longer exist.+///+/// Deliberately separate from the thread sweep: the two id spaces are+/// independent, so handing either one the other's keep list would delete live+/// work. `keep` being empty is a no-op, not a full wipe.+#[cfg_attr(feature = "tauri", tauri::command)]+pub async fn session_workspace_sweep(+ data_folder: String,+ keep: Vec<String>,+) -> Result<usize, AgentToolsError> {+ workspace::sweep_session_workspaces(Path::new(&data_folder), &keep)+ .await+ .map_err(Into::into)+}+/// Every discovered skill with its description, including empty stubs so the/// user can see and edit them.#[tauri::command]@@ -266,6 +302,48 @@ pub async fn sandbox_status() -> Result<SandboxStatus, AgentToolsError> {})}+/// One fragment of a tool's live output.+///+/// `seq` is monotonic per call so the receiver can assert ordering and notice+/// the truncation below; `callId` says which tool call it belongs to, which a+/// backgrounded `bash` needs because it keeps streaming after the tool returned.+#[derive(Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ToolOutputChunk {+ pub seq: u64,+ pub call_id: Option<String>,+ pub text: String,+}++/// Live output past this point is dropped from the stream, not from the result.+///+/// A `yes`-style command would otherwise flood the webview with IPC messages+/// faster than it can render them. The full text still reaches the caller in+/// `ToolResult`, and in the spill file when it overflows that.+const MAX_STREAMED_BYTES: usize = 2 * 1024 * 1024;++/// Which sandbox namespace an id belongs to.+///+/// Chat threads and Cowork sessions have independent id spaces and independent+/// sweeps, so the caller has to say which one it means; guessing would let one+/// surface's cleanup delete the other's work.+#[derive(Debug, Clone, Copy, Default, serde::Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum WorkspaceScope {+ #[default]+ Thread,+ Session,+}++impl WorkspaceScope {+ async fn ensure(self, data_folder: &Path, id: &str) -> Result<PathBuf, String> {+ match self {+ Self::Thread => workspace::ensure_thread_workspace(data_folder, id).await,+ Self::Session => workspace::ensure_session_workspace(data_folder, id).await,+ }+ }+}+/// Execute one built-in tool.////// The gate decides, not the caller. `write` and `edit` resolve to `Prompt` and@@ -273,6 +351,9 @@ pub async fn sandbox_status() -> Result<SandboxStatus, AgentToolsError> {/// round-trip exists; a read that escapes the project root prompts too. `bash`/// runs only under an enforcing sandbox (see the module docs).#[tauri::command]+// `read_only_project` is a folder the user attached read-only. It is validated+// here rather than trusted: an unusable one is an error, never a silent drop,+// or the agent would work against a folder it believes is attached and is not.pub async fn execute_tool(data_folder: String,thread_id: String,@@ -281,14 +362,97 @@ pub async fn execute_tool(args: serde_json::Value,enabled_skills: Option<Vec<String>>,allow_network: Option<bool>,+ read_only_project: Option<String>,+ scope: Option<WorkspaceScope>,+ call_id: Option<String>,+) -> Result<ToolResult, AgentToolsError> {+ execute_tool_inner(+ data_folder,+ thread_id,+ project,+ name,+ args,+ enabled_skills,+ allow_network,+ read_only_project,+ scope,+ call_id,+ None,+ )+ .await+}++/// `execute_tool`, plus a channel that receives the tool's output as it is+/// produced. A separate command rather than an optional argument because+/// `tauri::ipc::Channel` is a `CommandArg`, not a `Deserialize`, so it cannot be+/// wrapped in `Option`.+#[cfg(feature = "tauri")]+#[tauri::command]+#[allow(clippy::too_many_arguments)]+pub async fn execute_tool_streaming(+ data_folder: String,+ thread_id: String,+ project: Option<String>,+ name: String,+ args: serde_json::Value,+ enabled_skills: Option<Vec<String>>,+ allow_network: Option<bool>,+ read_only_project: Option<String>,+ scope: Option<WorkspaceScope>,+ call_id: Option<String>,+ on_output: tauri::ipc::Channel<ToolOutputChunk>,+) -> Result<ToolResult, AgentToolsError> {+ let sink = output_sink(on_output, call_id.clone());+ execute_tool_inner(+ data_folder,+ thread_id,+ project,+ name,+ args,+ enabled_skills,+ allow_network,+ read_only_project,+ scope,+ call_id,+ Some(sink),+ )+ .await+}++#[allow(clippy::too_many_arguments)]+async fn execute_tool_inner(+ data_folder: String,+ thread_id: String,+ project: Option<String>,+ name: String,+ args: serde_json::Value,+ enabled_skills: Option<Vec<String>>,+ allow_network: Option<bool>,+ read_only_project: Option<String>,+ scope: Option<WorkspaceScope>,+ call_id: Option<String>,+ sink: Option<crate::tools::OutputSink>,) -> Result<ToolResult, AgentToolsError> {// Created here rather than trusted to exist: `escapes_project` canonicalizes// the sandbox root and treats a missing one as an escape, so every tool call// would be refused if the thread's first tool call arrived before any UI// surface had ensured it.- let root = workspace::ensure_thread_workspace(Path::new(&data_folder), &thread_id).await?;+ let root = scope+ .unwrap_or_default()+ .ensure(Path::new(&data_folder), &thread_id)+ .await?;let scratch = workspace::ensure_scratch_dir(&thread_id).await?;let store = resolve_store(&data_folder, project.as_deref());+ // Plural from the outset so attaching a second folder later is not another+ // signature change.+ let read_roots: Vec<PathBuf> = match read_only_project.as_deref() {+ Some(path) => vec![workspace::validate_read_root(+ Path::new(path),+ &root,+ Some(Path::new(&data_folder)),+ )?],+ None => Vec::new(),+ };let tool = lookup(&name).ok_or_else(|| AgentToolsError::from(format!("unknown built-in tool '{name}'")))?;@@ -297,6 +461,7 @@ pub async fn execute_tool(&args,&root,Some(&scratch),+ &read_roots,&ToolPermissions::default(),&SessionGrants::default(),true,@@ -332,10 +497,20 @@ pub async fn execute_tool(// `WriteEscape` and refused here outright, since this surface has no// prompt round-trip to approve it.Decision::Prompt(PromptKind::Write) => {}+ // The message matters as much as the refusal: told only "refused", a+ // model retries the same write until the step budget runs out.Decision::Prompt(PromptKind::WriteEscape) => {- return Err(format!(- "tool '{name}' tried to write outside the agent workspace and was refused"- )+ return Err(match read_roots.first() {+ Some(attached) => format!(+ "tool '{name}' cannot write outside the agent workspace. The attached \+ folder {} is mounted read-only; copy the file into the workspace and \+ edit it there.",+ attached.display()+ ),+ None => format!(+ "tool '{name}' tried to write outside the agent workspace and was refused"+ ),+ }.into());}Decision::Prompt(kind) => {@@ -347,11 +522,18 @@ pub async fn execute_tool(}let enabled = enabled_skills.unwrap_or_default();- let ctx = ToolContext::new(&root, &store, &enabled)+ let mut ctx = ToolContext::new(&root, &store, &enabled).with_network(allow_network.unwrap_or(false)).with_confined_writes(true).with_mask_root(Path::new(&data_folder))- .with_scratch_root(&scratch);+ .with_scratch_root(&scratch)+ .with_read_roots(&read_roots);+ if let Some(id) = call_id.as_deref() {+ ctx = ctx.with_call_id(id);+ }+ if let Some(sink) = sink {+ ctx = ctx.with_output_sink(sink);+ }let (content, diff, _images) = handlers::execute_builtin_with_diff(tool, &args, &ctx).await;let is_error =content.starts_with("ERROR") || (name == "bash" && handlers::bash_result_failed(&content));@@ -362,6 +544,48 @@ pub async fn execute_tool(})}+/// Build the live-output sink.+///+/// `OutputSink` is `Fn`, not `FnMut`, so the sequence counter and the byte+/// budget live in atomics. The channel is `Clone + Send + Sync + 'static`, which+/// is what lets a detached background job keep reporting after the call that+/// created the sink has returned.+#[cfg(feature = "tauri")]+fn output_sink(+ channel: tauri::ipc::Channel<ToolOutputChunk>,+ call_id: Option<String>,+) -> crate::tools::OutputSink {+ use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};+ use std::sync::Arc;++ let seq = Arc::new(AtomicU64::new(0));+ let sent = Arc::new(AtomicUsize::new(0));+ let stopped = Arc::new(AtomicBool::new(false));+ Arc::new(move |text: String| {+ if stopped.load(Ordering::Relaxed) {+ return;+ }+ let total = sent.fetch_add(text.len(), Ordering::Relaxed) + text.len();+ // One honest final chunk rather than silently going quiet.+ let payload = if total > MAX_STREAMED_BYTES {+ stopped.store(true, Ordering::Relaxed);+ "\n[output truncated in the live view]\n".to_string()+ } else {+ text+ };+ let chunk = ToolOutputChunk {+ seq: seq.fetch_add(1, Ordering::Relaxed),+ call_id: call_id.clone(),+ text: payload,+ };+ // A send error means the webview is gone; stop rather than keep trying+ // for the lifetime of a backgrounded job.+ if channel.send(chunk).is_err() {+ stopped.store(true, Ordering::Relaxed);+ }+ })+}+#[cfg(test)]mod tests {use super::*;@@ -376,7 +600,29 @@ 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.+ fn repo_outside_tmp(tag: &str) -> PathBuf {+ let n = COUNTER.fetch_add(1, Ordering::SeqCst);+ let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .join("target")+ .join("attach-tests")+ .join(format!("{tag}_{}_{}", std::process::id(), n));+ std::fs::create_dir_all(&dir).expect("create test repo");+ dir+ }+const T1: &str = "thread-one";+ /// Own thread ids: the session scratch is keyed by thread id and lives in+ /// the shared host temp dir, so reusing one couples these tests to every+ /// other test that uses it.+ /// Its own id: this test depends on its scratch staying alive, and any+ /// test that deletes a thread workspace also deletes that thread's scratch.+ const T_SCRATCH: &str = "thread-scratch";+ const T_ATTACH_RW: &str = "thread-attach-rw";+ const T_ATTACH_NONE: &str = "thread-attach-none";+ const T_ATTACH_OVERLAP: &str = "thread-attach-overlap";const T2: &str = "thread-two";#[test]@@ -426,6 +672,9 @@ mod tests {json!({"path": "a.txt", "content": "hello"}),None,None,+ None,+ None,+ None,).await.expect("a write inside the sandbox is allowed");@@ -456,6 +705,9 @@ mod tests {json!({"path": "a.txt", "edits": [{"old_string": "before", "new_string": "after"}]}),None,None,+ None,+ None,+ None,).await.unwrap();@@ -488,6 +740,9 @@ mod tests {json!({"path": "../../../etc/hostname"}),None,None,+ None,+ None,+ None,).await.expect_err("an escaping read must be refused");@@ -512,12 +767,15 @@ mod tests {for path in ["../escape.txt", "/etc/hosts", "/home/akarshan/.bashrc"] {let err = execute_tool(df.clone(),- T1.into(),+ T_SCRATCH.into(),None,"write".into(),json!({"path": path, "content": "x"}),None,None,+ None,+ None,+ None,).await.expect_err("an escaping write must be refused");@@ -532,7 +790,12 @@ 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".- let scratch = crate::workspace::ensure_scratch_dir(T1).await.unwrap();+ // 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();+ 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}");@@ -543,12 +806,15 @@ mod tests {};let res = execute_tool(df.clone(),- T1.into(),+ T_SCRATCH.into(),None,"write".into(),json!({"path": requested, "content": "x"}),None,None,+ None,+ None,+ None,).await.expect("a scratch write is the session scratch and must succeed");@@ -562,12 +828,15 @@ mod tests {// An in-sandbox write still succeeds, so we didn't over-tighten.let res = execute_tool(df.clone(),- T1.into(),+ T_SCRATCH.into(),None,"write".into(),json!({"path": "ok.txt", "content": "x"}),None,None,+ None,+ None,+ None,).await.expect("an in-workspace write must succeed");@@ -602,6 +871,9 @@ mod tests {json!({"command": "echo hi"}),None,None,+ None,+ None,+ None,).await;@@ -641,6 +913,9 @@ mod tests {json!({"command": "exec 3<>/dev/tcp/1.1.1.1/53 && echo connected"}),None,None,+ None,+ None,+ None,).await.unwrap();@@ -670,6 +945,9 @@ mod tests {json!({}),None,None,+ None,+ None,+ None,).await.unwrap();@@ -693,6 +971,9 @@ mod tests {json!({"path": "a.txt"}),None,None,+ None,+ None,+ None,).await.unwrap();@@ -729,6 +1010,9 @@ mod tests {json!({"path": "../isolation-thread-one/secret.txt"}),None,None,+ None,+ None,+ None,).await.expect_err("a relative climb-out to a sibling thread must be refused");@@ -750,10 +1034,17 @@ mod tests {json!({"path": "/tmp/secret.txt"}),None,None,+ None,+ None,+ None,).await.unwrap();- assert!(out.is_error, "t2 sees an empty scratch, got: {}", out.content);+ assert!(+ out.is_error,+ "t2 sees an empty scratch, got: {}",+ out.content+ );let _ = std::fs::remove_dir_all(&data);let _ = crate::workspace::remove_scratch_dir(t1).await;let _ = crate::workspace::remove_scratch_dir(t2).await;@@ -774,6 +1065,9 @@ mod tests {json!({"name": "prefs", "content": "user likes tabs"}),None,None,+ None,+ None,+ None,).await.unwrap();@@ -792,6 +1086,9 @@ mod tests {json!({"name": "prefs"}),None,None,+ None,+ None,+ None,).await.unwrap();@@ -820,6 +1117,9 @@ mod tests {json!({"path": "../../memory/prefs.md"}),None,None,+ None,+ None,+ None,).await.expect_err("memory must be unreachable from the sandbox");@@ -872,6 +1172,9 @@ mod tests {"ls".into(),json!({}),None,+ None,+ None,+ None,None).await@@ -896,6 +1199,9 @@ mod tests {json!({"path": ".jan/agent/agent.toml"}),None,None,+ None,+ None,+ None,).await.expect_err("agent config must be hard-denied");@@ -919,6 +1225,9 @@ mod tests {json!({}),None,None,+ None,+ None,+ None,).await.expect_err("unknown tool");@@ -992,6 +1301,9 @@ mod tests {json!({"name": "deploy", "content": "---\ndescription: d\n---\nrun it"}),None,None,+ None,+ None,+ None,).await.unwrap();@@ -1007,10 +1319,193 @@ mod tests {json!({"name": "deploy"}),None,None,+ None,+ None,+ None,).await.unwrap();assert_eq!(out.content, "run it");let _ = std::fs::remove_dir_all(&data);}+ // ---- read-only attached folder, end to end ------------------------------++ /// The contract the workspace UI promises: the agent reads your folder and+ /// writes only into its own sandbox.+ #[tokio::test]+ async fn an_attached_folder_is_readable_and_unwritable() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();+ let repo = repo_outside_tmp("rw");+ std::fs::write(repo.join("main.rs"), b"fn main() {}").unwrap();+ let attached = Some(repo.to_string_lossy().to_string());++ let read = execute_tool(+ df.clone(),+ T_ATTACH_RW.into(),+ None,+ "read".into(),+ json!({"path": repo.join("main.rs").to_string_lossy()}),+ None,+ None,+ attached.clone(),+ None,+ None,+ )+ .await+ .unwrap();+ assert!(!read.is_error, "{}", read.content);+ assert!(read.content.contains("fn main"), "{}", read.content);++ let write = execute_tool(+ df.clone(),+ T_ATTACH_RW.into(),+ None,+ "write".into(),+ json!({"path": repo.join("evil.txt").to_string_lossy(), "content": "x"}),+ None,+ None,+ attached,+ None,+ None,+ )+ .await;+ let err = write.expect_err("a write into the attached folder must be refused");+ // The wording matters: told only "refused", a model retries until the+ // step budget runs out.+ let msg = format!("{err:?}");+ assert!(msg.contains("read-only"), "{msg}");+ assert!(msg.contains("copy the file into the workspace"), "{msg}");+ assert!(!repo.join("evil.txt").exists(), "nothing was written");++ let _ = std::fs::remove_dir_all(&data);+ let _ = std::fs::remove_dir_all(&repo);+ }++ /// Without an attached folder nothing outside the sandbox is readable, so+ /// the mount is genuinely opt-in.+ #[tokio::test]+ async fn without_an_attachment_the_same_read_is_refused() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();+ let repo = repo_outside_tmp("noattach");+ std::fs::write(repo.join("main.rs"), b"fn main() {}").unwrap();++ let out = execute_tool(+ df.clone(),+ T_ATTACH_NONE.into(),+ None,+ "read".into(),+ json!({"path": repo.join("main.rs").to_string_lossy()}),+ None,+ None,+ None,+ None,+ None,+ )+ .await;+ assert!(out.is_err() || out.unwrap().is_error);++ let _ = std::fs::remove_dir_all(&data);+ let _ = std::fs::remove_dir_all(&repo);+ }++ /// An unusable attachment is an error, never a silent drop: otherwise the+ /// agent works against a folder it believes is attached and is not.+ #[tokio::test]+ async fn an_overlapping_attachment_is_rejected_not_ignored() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();+ let inside = workspace::ensure_thread_workspace(&data, T_ATTACH_OVERLAP)+ .await+ .unwrap()+ .join("nested");+ std::fs::create_dir_all(&inside).unwrap();++ let out = execute_tool(+ df.clone(),+ T_ATTACH_OVERLAP.into(),+ None,+ "ls".into(),+ json!({}),+ None,+ None,+ Some(inside.to_string_lossy().to_string()),+ None,+ None,+ )+ .await;+ let err = out.expect_err("a root inside the workspace must be refused");+ assert!(format!("{err:?}").contains("overlaps"), "{err:?}");++ let _ = std::fs::remove_dir_all(&data);+ }+ // ---- live output streaming ---------------------------------------------++ /// The sink builder is exercised directly: a real `Channel` needs a webview,+ /// and what matters here is the ordering, correlation and the byte budget.+ #[test]+ fn the_output_sink_numbers_chunks_and_tags_them_with_the_call() {+ use std::sync::{Arc, Mutex};+ let seen: Arc<Mutex<Vec<(u64, Option<String>, String)>>> = Arc::new(Mutex::new(Vec::new()));+ let sink = test_sink(seen.clone(), Some("call-7".into()));++ sink("one".into());+ sink("two".into());++ let seen = seen.lock().unwrap();+ assert_eq!(seen.len(), 2);+ assert_eq!(seen[0].0, 0);+ assert_eq!(seen[1].0, 1, "seq is monotonic so a gap is detectable");+ assert_eq!(seen[0].1.as_deref(), Some("call-7"));+ assert_eq!(seen[1].2, "two");+ }++ /// A `yes`-style command would otherwise flood the webview. The stream stops+ /// with one honest marker; the full text still reaches the caller in the+ /// tool result.+ #[test]+ fn the_output_sink_stops_at_the_byte_cap_and_says_so() {+ use std::sync::{Arc, Mutex};+ let seen: Arc<Mutex<Vec<(u64, Option<String>, String)>>> = Arc::new(Mutex::new(Vec::new()));+ let sink = test_sink(seen.clone(), None);++ sink("x".repeat(MAX_STREAMED_BYTES + 1));+ sink("more".into());+ sink("even more".into());++ let seen = seen.lock().unwrap();+ assert_eq!(seen.len(), 1, "nothing is sent after the cap");+ assert!(seen[0].2.contains("truncated"), "{}", seen[0].2);+ }++ /// Mirrors `output_sink`'s accounting without a `Channel`, which cannot be+ /// constructed outside a webview.+ fn test_sink(+ seen: std::sync::Arc<std::sync::Mutex<Vec<(u64, Option<String>, String)>>>,+ call_id: Option<String>,+ ) -> crate::tools::OutputSink {+ use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};+ use std::sync::Arc;+ let seq = Arc::new(AtomicU64::new(0));+ let sent = Arc::new(AtomicUsize::new(0));+ let stopped = Arc::new(AtomicBool::new(false));+ Arc::new(move |text: String| {+ if stopped.load(Ordering::Relaxed) {+ return;+ }+ let total = sent.fetch_add(text.len(), Ordering::Relaxed) + text.len();+ let payload = if total > MAX_STREAMED_BYTES {+ stopped.store(true, Ordering::Relaxed);+ "\n[output truncated in the live view]\n".to_string()+ } else {+ text+ };+ seen.lock().unwrap().push((+ seq.fetch_add(1, Ordering::Relaxed),+ call_id.clone(),+ payload,+ ));+ })+ }}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rsindex 562a03b3e..31f5ca9b6 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs@@ -37,6 +37,9 @@ pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {commands::thread_workspace_path,commands::thread_workspace_delete,commands::thread_workspace_sweep,+ commands::session_workspace_path,+ commands::session_workspace_delete,+ commands::session_workspace_sweep,commands::skill_list,commands::skill_read,commands::skill_write,@@ -47,7 +50,8 @@ pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {commands::memory_delete,commands::tool_schemas,commands::sandbox_status,- commands::execute_tool+ commands::execute_tool,+ commands::execute_tool_streaming]).build()}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rsindex 3c954c660..3bfcba850 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@@ -1,10 +1,12 @@-use std::path::Path;+use std::path::{Path, PathBuf};use serde::{Deserialize, Serialize};use crate::permissions::ToolPermissions;use crate::tools::cmdscan::{normalize, scan_command, CommandScan};-use crate::tools::sandbox::{command_touches_hidden_jan_path, escapes_project, is_hidden_jan_path};+use crate::tools::sandbox::{+ command_touches_hidden_jan_path, escapes_project, escapes_read_roots, is_hidden_jan_path,+};use crate::tools::{BuiltinTool, Capability};#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]@@ -134,6 +136,7 @@ pub fn resolve_decision(args: &serde_json::Value,project_root: &Path,scratch: Option<&Path>,+ read_roots: &[PathBuf],perms: &ToolPermissions,grants: &SessionGrants,hide_jan: bool,@@ -173,10 +176,15 @@ pub fn resolve_decision(}match tool.capability {Capability::Read => {+ // Read roots widen only this branch. The Write branch below keeps+ // the unchanged `escapes_project`, which is what makes an attached+ // folder readable and not writable.let escapes = tool.path_args.iter().any(|key| {args.get(key).and_then(|v| v.as_str())- .map(|p| escapes_project(project_root, scratch, p).unwrap_or(true))+ .map(|p| {+ escapes_read_roots(project_root, scratch, read_roots, p).unwrap_or(true)+ }).unwrap_or(false)});if !escapes || grants.covers(PromptKind::ReadEscape) {@@ -275,6 +283,7 @@ mod tests {&json!({"path": "inner.txt"}),&root,None,+ &[],&perms,&grants,true,@@ -293,6 +302,7 @@ mod tests {&json!({"path": "../x"}),&root,None,+ &[],&perms,&grants,true,@@ -312,6 +322,7 @@ mod tests {&json!({}),&root,None,+ &[],&perms,&grants,true,@@ -332,6 +343,7 @@ mod tests {&json!({}),&root,None,+ &[],&perms,&grants,true,@@ -358,6 +370,7 @@ mod tests {&json!({ "path": ".jan/agent/agent.toml" }),&root,None,+ &[],&perms,&grants,true,@@ -374,6 +387,7 @@ mod tests {&json!({"command": "cat .jan/agent/agent.toml"}),&root,None,+ &[],&perms,&grants,true,@@ -386,6 +400,7 @@ mod tests {&json!({"path": "JAN.md"}),&root,None,+ &[],&perms,&grants,true,@@ -410,6 +425,7 @@ mod tests {&json!({ "path": ".jan/agent/agent.toml" }),&root,None,+ &[],&perms,&grants,false,@@ -426,6 +442,7 @@ mod tests {&json!({"command": "cat .jan/agent/agent.toml"}),&root,None,+ &[],&perms,&grants,false,@@ -444,6 +461,7 @@ mod tests {&json!({"path": "out.txt"}),&root,None,+ &[],&perms,&grants,true,@@ -462,6 +480,7 @@ mod tests {&json!({"command": "ls"}),&root,None,+ &[],&perms,&grants,true,@@ -481,6 +500,7 @@ mod tests {&json!({"command": "ls", "job_id": job_id}),&root,None,+ &[],&perms,&grants,true,@@ -500,6 +520,7 @@ mod tests {&json!({"job_id": "bash-0"}),&root,None,+ &[],&perms,&grants,true,@@ -530,6 +551,7 @@ mod tests {&json!({"command": "git push"}),&root,None,+ &[],&perms,&grants,true,@@ -542,6 +564,7 @@ mod tests {&json!({"command": "rm -rf /"}),&root,None,+ &[],&perms,&grants,true,@@ -568,11 +591,16 @@ mod tests {&json!({ "command": cmd }),&root,None,+ &[],&perms,&grants,true,);- assert_eq!(d, Decision::Prompt(PromptKind::Exec), "must reprompt: {cmd}");+ assert_eq!(+ d,+ Decision::Prompt(PromptKind::Exec),+ "must reprompt: {cmd}"+ );}let _ = std::fs::remove_dir_all(&root);}@@ -590,6 +618,7 @@ mod tests {&json!({ "command": cmd }),&root,None,+ &[],&perms,&grants,true,@@ -612,6 +641,7 @@ mod tests {&json!({"command": "sudo systemctl restart nginx"}),&root,None,+ &[],&perms,&grants,true,@@ -624,6 +654,7 @@ mod tests {&json!({"command": "sudo rm -rf /"}),&root,None,+ &[],&perms,&grants,true,@@ -651,6 +682,7 @@ mod tests {&json!({ "path": path }),&root,None,+ &[],&perms,&grants,true,@@ -676,6 +708,7 @@ mod tests {&json!({"name": "x", "content": "y"}),&root,None,+ &[],&perms,&grants,true,@@ -683,12 +716,14 @@ mod tests {assert_eq!(d, Decision::Allow, "{name} should auto-allow");}// Explicit deny in agent.toml still overrides the auto-allow.- let denied = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &s(&["memory_write"]), &[]);+ let denied =+ ToolPermissions::new(PermissionDefault::ReadOnly, &[], &s(&["memory_write"]), &[]);let d = resolve_decision(lookup("memory_write").unwrap(),&json!({"name": "x", "content": "y"}),&root,None,+ &[],&denied,&grants,true,@@ -707,6 +742,7 @@ mod tests {&json!({"path": "out.txt"}),&root,None,+ &[],&perms,&grants,true,@@ -725,6 +761,7 @@ mod tests {&json!({"path": "out.txt"}),&root,None,+ &[],&perms,&grants,true,@@ -744,6 +781,7 @@ mod tests {&json!({"path": "out.txt"}),&root,None,+ &[],&perms,&grants,true,@@ -763,6 +801,7 @@ mod tests {&json!({"path": "../x"}),&root,None,+ &[],&perms,&grants,true,@@ -781,6 +820,7 @@ mod tests {&json!({"path": "sub/new.txt"}),&root,None,+ &[],&perms,&grants,true,@@ -801,6 +841,7 @@ mod tests {&json!({"path": path}),&root,None,+ &[],&perms,&grants,true,@@ -821,6 +862,7 @@ mod tests {&json!({"path": "../x"}),&root,None,+ &[],&perms,&grants,true,@@ -839,6 +881,7 @@ mod tests {&json!({"path": "../x"}),&root,None,+ &[],&perms,&grants,true,@@ -846,4 +889,65 @@ mod tests {assert_eq!(d, Decision::Prompt(PromptKind::ReadEscape));let _ = std::fs::remove_dir_all(&root);}+ // Reads reach an attached folder; writes into it are still an escape. These+ // two together *are* the read-only mount at the gate layer.+ #[test]+ fn read_in_an_attached_root_allows_and_write_prompts_escape() {+ let root = unique_root();+ let repo = unique_root();+ std::fs::write(repo.join("main.rs"), b"x").unwrap();+ let roots = vec![repo.clone()];+ let target = repo.join("main.rs").to_string_lossy().into_owned();+ let perms = ToolPermissions::allow_all();+ let grants = SessionGrants::default();++ let read = resolve_decision(+ lookup("read").unwrap(),+ &json!({"path": target}),+ &root,+ None,+ &roots,+ &perms,+ &grants,+ true,+ );+ assert_eq!(read, Decision::Allow);++ let write = resolve_decision(+ lookup("write").unwrap(),+ &json!({"path": repo.join("new.txt").to_string_lossy(), "content": "y"}),+ &root,+ None,+ &roots,+ &ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]),+ &grants,+ true,+ );+ assert_eq!(write, Decision::Prompt(PromptKind::WriteEscape));++ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&repo);+ }++ #[test]+ fn an_escaping_read_still_prompts_when_no_root_covers_it() {+ let root = unique_root();+ let repo = unique_root();+ let elsewhere = unique_root();+ let roots = vec![repo.clone()];+ let d = resolve_decision(+ lookup("read").unwrap(),+ &json!({"path": elsewhere.join("secret").to_string_lossy()}),+ &root,+ None,+ &roots,+ &ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]),+ &SessionGrants::default(),+ true,+ );+ assert_eq!(d, Decision::Prompt(PromptKind::ReadEscape));+ for d in [&root, &repo, &elsewhere] {+ let _ = std::fs::remove_dir_all(d);+ }+ }}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rsindex 628988ef6..d6d813099 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@@ -17,7 +17,7 @@ use crate::tools::jail;use crate::tools::proc;use crate::tools::sandbox::{escapes_project, in_scratch, is_hidden_jan_path, lexical_normalize, resolve_path,- scratch_display_path, symlink_escapes_root,+ scratch_display_path, symlink_escapes_any_root, symlink_escapes_root,};use crate::tools::{BuiltinTool, ImageContentPart, ToolContext};@@ -67,6 +67,13 @@ fn arg_bool(args: &serde_json::Value, key: &str) -> bool {args.get(key).and_then(|v| v.as_bool()).unwrap_or(false)}+/// Single-quote a value for a POSIX shell. Single quotes disable `$`/backtick+/// expansion and globbing, and the only escape (closing quote) is handled by+/// the `'\''` idiom. Used when launching headless Chrome through the shell.+fn shell_quote(value: &str) -> String {+ format!("'{}'", value.replace('\'', "'\\''"))+}+fn rel_to(base: &Path, path: &Path) -> String {path.strip_prefix(base).unwrap_or(path)@@ -136,7 +143,8 @@ pub async fn execute_builtin(let project_root = ctx.project_root;let scratch = ctx.scratch_root;let (content, images) = match tool.name {- "read" => read(args, project_root, scratch).await,+ "read" => read(args, project_root, scratch, ctx.read_roots).await,+ "screenshot" => screenshot(args, project_root, scratch, ctx.read_roots).await,_ => (execute_text(tool, args, ctx).await, None),};(content, images)@@ -144,17 +152,24 @@ pub async fn execute_builtin(/// The text result for every tool except `read`. Split out so `read` can also/// return image parts without duplicating the remaining tool dispatch.-async fn execute_text(tool: &BuiltinTool, args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {+async fn execute_text(+ tool: &BuiltinTool,+ args: &serde_json::Value,+ ctx: &ToolContext<'_>,+) -> String {let project_root = ctx.project_root;let scratch = ctx.scratch_root;match tool.name {- "read" => read(args, project_root, scratch).await.0,- "ls" => ls(args, project_root, scratch, ctx.sandbox).await,+ // Read tools consult the attached read-only roots; `write`/`edit`+ // deliberately do not, which is what keeps an attached folder+ // readable and unwritable.+ "read" => read(args, project_root, scratch, ctx.read_roots).await.0,+ "ls" => ls(args, project_root, scratch, ctx.sandbox, ctx.read_roots).await,"write" => write(args, project_root, scratch, ctx.confine_writes).await,"edit" => edit(args, project_root, scratch, ctx.confine_writes).await,"bash" => bash(args, ctx).await,- "find" => find(args, project_root, scratch, ctx.sandbox).await,- "grep" => grep(args, project_root, scratch, ctx.sandbox).await,+ "find" => find(args, project_root, scratch, ctx.sandbox, ctx.read_roots).await,+ "grep" => grep(args, project_root, scratch, ctx.sandbox, ctx.read_roots).await,// Memory and skills live in the store root, not the sandbox: they must// outlive the conversation the filesystem tools are scoped to."memory_list" => memory_list(ctx.store_root).await,@@ -480,6 +495,7 @@ async fn read(args: &serde_json::Value,root: &Path,scratch: Option<&Path>,+ read_roots: &[PathBuf],) -> (String, Option<Vec<ImageContentPart>>) {let Some(path) = arg_str(args, "path") else {return ("ERROR: missing required argument 'path'".to_string(), None);@@ -489,7 +505,7 @@ async fn read(let target = resolve_path(root, scratch, 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_root(root, scratch, &target) {+ if symlink_escapes_any_root(root, scratch, read_roots, &target) {return (format!("ERROR: refused to read through a symlink out of the workspace: {path}"),None,@@ -561,14 +577,20 @@ async fn read()}-async fn ls(args: &serde_json::Value, root: &Path, scratch: Option<&Path>, hide_jan: bool) -> String {+async fn ls(+ args: &serde_json::Value,+ root: &Path,+ scratch: Option<&Path>,+ hide_jan: bool,+ read_roots: &[PathBuf],+) -> String {let path = arg_str(args, "path").unwrap_or(".");let limit = arg_u64(args, "limit").map(|v| v as usize).unwrap_or(LS_DEFAULT_LIMIT);let target = resolve_path(root, scratch, path);// Names are content too: a symlinked directory would list a host directory.- if symlink_escapes_root(root, scratch, &target) {+ if symlink_escapes_any_root(root, scratch, read_roots, &target) {return format!("ERROR: refused to list through a symlink out of the workspace: {path}");}let mut entries = match tokio::fs::read_dir(&target).await {@@ -605,7 +627,12 @@ async fn ls(args: &serde_json::Value, root: &Path, scratch: Option<&Path>, hide_cap_output(&joined, usize::MAX, MAX_BYTES, "\n[truncated: 64KB limit]")}-async fn write(args: &serde_json::Value, root: &Path, scratch: Option<&Path>, confine: bool) -> String {+async fn write(+ args: &serde_json::Value,+ root: &Path,+ scratch: Option<&Path>,+ confine: bool,+) -> String {let Some(path) = arg_str(args, "path") else {return "ERROR: missing required argument 'path'".to_string();};@@ -650,7 +677,12 @@ async fn write(args: &serde_json::Value, root: &Path, scratch: Option<&Path>, co}}-async fn edit(args: &serde_json::Value, root: &Path, scratch: Option<&Path>, confine: bool) -> String {+async fn edit(+ args: &serde_json::Value,+ root: &Path,+ scratch: Option<&Path>,+ confine: bool,+) -> String {let Some(path) = arg_str(args, "path") else {return "ERROR: missing required argument 'path'".to_string();};@@ -720,8 +752,8 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {);}- let mut policy = jail::Policy::new(root, ctx.allow_network)- .with_home_readonly(ctx.home_readonly);+ let mut policy =+ jail::Policy::new(root, ctx.allow_network).with_home_readonly(ctx.home_readonly);// While the shell is sandboxed, hide the project's own `.jan` state directory// from it (see [`Policy::with_hide_root`]). When the shell runs unconfined the// hide is both pointless (there is no OS mount to layer it on) and wrong@@ -735,6 +767,9 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {if let Some(scratch) = ctx.scratch_root {policy = policy.with_scratch_root(scratch);}+ if !ctx.read_roots.is_empty() {+ policy = policy.with_read_roots(ctx.read_roots.to_vec());+ }// With the sandbox off the shell is spawned bare, the way the user's own// terminal would: no wrapper, no policy, the real `$HOME` and `/tmp`. Only// a surface that opted in gets here (the CLI's `--sandbox`/`sandbox`@@ -1115,9 +1150,7 @@ fn spill_dir(scratch: Option<&Path>) -> Option<PathBuf> {fn new_temp_path(scratch: Option<&Path>) -> Option<PathBuf> {let n = TEMP_COUNTER.fetch_add(1, Ordering::SeqCst);- Some(- spill_dir(scratch)?.join(format!("jan-bash-{}-{}.txt", std::process::id(), n)),- )+ Some(spill_dir(scratch)?.join(format!("jan-bash-{}-{}.txt", std::process::id(), n)))}/// Open a spill file atomically with `O_EXCL` so we never truncate or write@@ -1126,7 +1159,10 @@ fn new_temp_path(scratch: Option<&Path>) -> Option<PathBuf> {/// non-symlink parent from [`spill_dir`], the model-controlled spill bytes/// cannot be redirected onto a host file.fn open_spill_file(path: &Path) -> std::io::Result<std::fs::File> {- std::fs::OpenOptions::new().write(true).create_new(true).open(path)+ std::fs::OpenOptions::new()+ .write(true)+ .create_new(true)+ .open(path)}/// Write `content` to a uniquely named temp file, returning its path on@@ -1154,14 +1190,210 @@ fn remove_spill_file(path: &Path) {let _ = std::fs::remove_file(path);}-async fn find(args: &serde_json::Value, root: &Path, scratch: Option<&Path>, hide_jan: bool) -> String {+const SCREENSHOT_MAX_PNG_BYTES: usize = 4 * 1024 * 1024; // 4 MiB++fn chrome_binary() -> Option<PathBuf> {+ if let Ok(env) = std::env::var("CHROME_PATH") {+ if !env.is_empty() {+ return Some(PathBuf::from(env));+ }+ }+ const CANDIDATES: &[&str] = &[+ // macOS (bundled browsers)+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",+ "/Applications/Chromium.app/Contents/MacOS/Chromium",+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",+ // Linux+ "/usr/bin/google-chrome",+ "/usr/bin/chromium",+ "/usr/bin/chromium-browser",+ ];+ CANDIDATES+ .iter()+ .find(|p| Path::new(p).exists())+ .map(PathBuf::from)+}++/// Render a local HTML/SVG file to PNG bytes with headless Chrome.+///+/// Shared by the model-facing `screenshot` tool and the `agent_render_preview`+/// command the annotation overlay calls, so both agree on Chrome discovery,+/// viewport clamping and the output cap. `width`/`height` are the viewport in+/// CSS pixels; the caller picks them (the overlay passes its own stage size so+/// the PNG lines up pixel-for-pixel with what the user drew on).+///+/// `scale` is the device pixel ratio: the PNG comes out `width*scale` pixels+/// wide with the layout unchanged. The overlay passes the webview's own ratio+/// so a HiDPI screen doesn't composite crisp marks over an upscaled blur.+pub async fn render_html_png(+ target: &Path,+ width: u64,+ height: u64,+ scale: f64,+) -> Result<Vec<u8>, String> {+ let ext = target+ .extension()+ .and_then(|e| e.to_str())+ .map(|e| e.to_ascii_lowercase())+ .unwrap_or_default();+ if ext != "html" && ext != "htm" && ext != "svg" {+ return Err(format!(+ "screenshot only renders .html/.htm/.svg files, got .{ext}"+ ));+ }+ if !target.is_file() {+ return Err(format!("file not found: {}", target.display()));+ }++ let Some(chrome) = chrome_binary() else {+ return Err(+ "no Chrome/Chromium binary found (set CHROME_PATH to point at one)".to_string(),+ );+ };++ let width = width.clamp(320, 4096);+ let height = height.clamp(240, 4096);+ let scale = if scale.is_finite() {+ scale.clamp(1.0, 3.0)+ } else {+ 1.0+ };+ // A per-call profile (pid + nanos) keeps headless Chrome from colliding+ // with a running browser or a leftover from a previous call; `--screenshot`+ // exits after writing, but the wait below is bounded in case it lingers.+ let nanos = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0);+ let shot = std::env::temp_dir().join(format!("jan-shot-{}-{nanos}.png", std::process::id()));+ let profile = std::env::temp_dir().join(format!("jan-chrome-{}-{nanos}", std::process::id()));++ // file:// lets the page resolve relative assets against its own directory,+ // matching what the artifact preview does.+ let file_url = format!("file://{}", target.display());+ // Chrome is spawned through the shell (`sh -c`): on macOS, a Chrome+ // headless-new process spawned directly by a non-bundled parent fails its+ // singleton/TCC check with "Multiple targets are not supported in headless+ // mode", while the same invocation via the shell succeeds. The `bash` tool+ // already relies on this property, so we inherit it here.+ let profile_quoted = shell_quote(profile.to_str().unwrap_or_default());+ let shot_quoted = shell_quote(shot.to_str().unwrap_or_default());+ let url_quoted = shell_quote(&file_url);+ let chrome_quoted = shell_quote(chrome.to_str().unwrap_or_default());+ let cmd = format!(+ "{chrome_quoted} --headless=new --disable-gpu --hide-scrollbars --no-sandbox \+ --disable-dev-shm-usage --no-first-run --user-data-dir={profile_quoted} \+ --force-device-scale-factor={scale} \+ --window-size={width},{height} --screenshot={shot_quoted} {url_quoted}"+ );+ let shell = proc::shell();+ let mut child = match tokio::process::Command::new(shell.program.clone())+ .args(shell.args.clone())+ .arg(&cmd)+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::piped())+ .spawn()+ {+ Ok(c) => c,+ Err(e) => return Err(format!("failed to launch Chrome: {e}")),+ };+ // Bounded: headless Chrome can linger after writing the PNG. Give it a+ // generous window, then reap whatever is left and proceed if the file+ // exists. stderr is drained on a background task so a chatty Chrome never+ // fills the pipe and deadlocks.+ let stderr_pipe = child.stderr.take();+ let drain = tokio::spawn(async move {+ use tokio::io::AsyncReadExt as _;+ let mut buf = Vec::new();+ if let Some(mut pipe) = stderr_pipe {+ let _ = pipe.read_to_end(&mut buf).await;+ }+ String::from_utf8_lossy(&buf).into_owned()+ });+ let _ = tokio::time::timeout(std::time::Duration::from_secs(30), child.wait()).await;+ let _ = child.kill().await;+ let stderr = drain.await.unwrap_or_default();+ let _ = tokio::fs::remove_dir_all(&profile).await;++ let png = match tokio::fs::read(&shot).await {+ Ok(b) => b,+ Err(e) => {+ let detail = stderr.lines().take(3).collect::<Vec<_>>().join(" | ");+ return Err(format!("screenshot not produced: {e} (chrome: {detail})"));+ }+ };+ let _ = tokio::fs::remove_file(&shot).await;++ if png.is_empty() {+ return Err("Chrome produced an empty screenshot (page may be blank)".to_string());+ }+ if png.len() > SCREENSHOT_MAX_PNG_BYTES {+ return Err(format!(+ "screenshot is {} KiB, over the {}-MiB cap; try a smaller viewport",+ png.len() / 1024,+ SCREENSHOT_MAX_PNG_BYTES / 1024 / 1024+ ));+ }+ Ok(png)+}++/// Render a local HTML/SVG file and hand the model the image.+///+/// Returns an `ImageContentPart` rather than a data URL pasted into the text,+/// matching what `read` does for images: that is the form a vision model+/// actually consumes, and it keeps a megabyte of base64 out of the transcript.+async fn screenshot(+ args: &serde_json::Value,+ root: &Path,+ scratch: Option<&Path>,+ read_roots: &[PathBuf],+) -> (String, Option<Vec<ImageContentPart>>) {+ let Some(path) = arg_str(args, "path") else {+ return ("ERROR: missing required argument 'path'".to_string(), None);+ };+ 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);+ if symlink_escapes_any_root(root, scratch, read_roots, &target) {+ return (+ format!("ERROR: refused to screenshot through a symlink out of the workspace: {path}"),+ None,+ );+ }+ let png = match render_html_png(&target, width, height, 1.0).await {+ Ok(b) => b,+ Err(e) => return (format!("ERROR: {e}"), None),+ };+ use base64::Engine as _;+ let b64 = base64::engine::general_purpose::STANDARD.encode(&png);+ let name = target+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_else(|| path.to_string());+ (+ format!("Screenshot of {path} ({width}x{height})"),+ Some(vec![ImageContentPart {+ data_url: format!("data:image/png;base64,{b64}"),+ name,+ }]),+ )+}++async fn find(+ args: &serde_json::Value,+ root: &Path,+ scratch: Option<&Path>,+ hide_jan: bool,+ read_roots: &[PathBuf],+) -> String {let pattern = arg_str(args, "pattern").map(String::from);let path = arg_str(args, "path").unwrap_or(".").to_string();let limit = arg_u64(args, "limit").map(|v| v as usize).unwrap_or(FIND_DEFAULT_LIMIT);let base = resolve_path(root, scratch, &path);- if symlink_escapes_root(root, scratch, &base) {+ if symlink_escapes_any_root(root, scratch, read_roots, &base) {return format!("ERROR: refused to search through a symlink out of the workspace: {path}");}let root_owned = root.to_path_buf();@@ -1210,7 +1442,13 @@ async fn find(args: &serde_json::Value, root: &Path, scratch: Option<&Path>, hidres.unwrap_or_else(|e| format!("ERROR: {e}"))}-async fn grep(args: &serde_json::Value, root: &Path, scratch: Option<&Path>, hide_jan: bool) -> String {+async fn grep(+ args: &serde_json::Value,+ root: &Path,+ scratch: Option<&Path>,+ hide_jan: bool,+ read_roots: &[PathBuf],+) -> String {let pattern = arg_str(args, "pattern").map(String::from);let path = arg_str(args, "path").unwrap_or(".").to_string();let glob_filter = arg_str(args, "glob").map(String::from);@@ -1221,11 +1459,13 @@ async fn grep(args: &serde_json::Value, root: &Path, scratch: Option<&Path>, hid.map(|v| v as usize).unwrap_or(GREP_DEFAULT_LIMIT);let base = resolve_path(root, scratch, &path);- if symlink_escapes_root(root, scratch, &base) {+ if symlink_escapes_any_root(root, scratch, read_roots, &base) {return format!("ERROR: refused to search through a symlink out of the workspace: {path}");}let root_owned = root.to_path_buf();let scratch_owned = scratch.map(Path::to_path_buf);+ // Owned for the blocking walk closure, which outlives this frame.+ let roots_owned = read_roots.to_vec();let Some(pattern) = pattern else {return "ERROR: missing required argument 'pattern'".to_string();@@ -1321,7 +1561,12 @@ async fn grep(args: &serde_json::Value, root: &Path, scratch: Option<&Path>, hid// Checked (not skipped outright) so a link that stays inside the// workspace -- every yarn workspace has them -- is still searched.if file_type.is_symlink()- && symlink_escapes_root(&root_owned, scratch_owned.as_deref(), entry.path())+ && symlink_escapes_any_root(+ &root_owned,+ scratch_owned.as_deref(),+ &roots_owned,+ entry.path(),+ ){continue;}@@ -1387,7 +1632,8 @@ mod tests {) -> (String, Option<String>) {let store = crate::workspace::project_store(root);let (content, diff, _images) =- super::execute_builtin_with_diff(tool, args, &ToolContext::new(root, &store, &[])).await;+ super::execute_builtin_with_diff(tool, args, &ToolContext::new(root, &store, &[]))+ .await;(content, diff)}@@ -1479,7 +1725,10 @@ mod tests {).await;assert!(!content.starts_with("ERROR"), "got: {content}");- assert!(images.is_some(), "extension-matching png must yield an image");+ assert!(+ images.is_some(),+ "extension-matching png must yield an image"+ );let _ = std::fs::remove_dir_all(&root);}@@ -1494,7 +1743,10 @@ mod tests {&root,).await;- assert!(out.starts_with("ERROR"), "slicing an image must not render: {out}");+ assert!(+ out.starts_with("ERROR"),+ "slicing an image must not render: {out}"+ );let _ = std::fs::remove_dir_all(&root);}@@ -1512,7 +1764,10 @@ mod tests {&ToolContext::new(&root, &crate::workspace::project_store(&root), &[]),).await;- assert!(images.is_none(), "an over-cap image must not yield image parts");+ assert!(+ images.is_none(),+ "an over-cap image must not yield image parts"+ );assert!(content.starts_with("ERROR"), "got: {content}");let _ = std::fs::remove_dir_all(&root);}@@ -1621,7 +1876,10 @@ mod tests {&[json!({"old_string": "two", "new_string": "TWO"})],"one\ntwo\nthree",);- assert_eq!(d, " 1 | one\n- 2 | two\n+ 2 | TWO\n 3 | three");+ assert_eq!(+ d,+ " 1 | one\n- 2 | two\n+ 2 | TWO\n 3 | three"+ );}/// Two edits far apart in one call: each hunk carries its own file context@@ -1935,8 +2193,12 @@ mod tests {&json!({"path": "../escape.txt", "content": "x"}),&ctx,)- .await.0;- assert!(out.starts_with("ERROR: refused to write outside"), "got: {out}");+ .await+ .0;+ assert!(+ out.starts_with("ERROR: refused to write outside"),+ "got: {out}"+ );assert!(!root.parent().unwrap().join("escape.txt").exists());let out = super::execute_builtin(@@ -1944,8 +2206,12 @@ mod tests {&json!({"path": "../escape.txt", "edits": [{"old_string": "a", "new_string": "b"}]}),&ctx,)- .await.0;- assert!(out.starts_with("ERROR: refused to edit outside"), "got: {out}");+ .await+ .0;+ assert!(+ out.starts_with("ERROR: refused to edit outside"),+ "got: {out}"+ );let _ = std::fs::remove_dir_all(&root);}@@ -1991,7 +2257,8 @@ mod tests {&json!({"pattern": "*.txt", "path": "/tmp"}),&ctx,)- .await.0;+ .await+ .0;assert!(!out.contains("secret.txt"),"walked out of the scratch through a symlink: {out}"@@ -2015,7 +2282,12 @@ mod tests {std::fs::write(outside.join("secret.txt"), b"classified").unwrap();std::os::unix::fs::symlink(outside.join("secret.txt"), root.join("key.txt")).unwrap();std::fs::write(root.join("real.txt"), b"plain").unwrap();- let out = execute_builtin(lookup("grep").unwrap(), &json!({"pattern": "classified", "path": "."}), &root).await;+ let out = execute_builtin(+ lookup("grep").unwrap(),+ &json!({"pattern": "classified", "path": "."}),+ &root,+ )+ .await;assert!(!out.contains("secret") && !out.contains("classified"),"read through a file symlink outside the root: {out}"@@ -2036,11 +2308,24 @@ mod tests {std::fs::write(root.join("pkg/index.js"), b"needle here").unwrap();std::os::unix::fs::symlink(root.join("pkg/index.js"), root.join("linked.js")).unwrap();- let out = execute_builtin(lookup("read").unwrap(), &json!({"path": "linked.js"}), &root).await;+ let out = execute_builtin(+ lookup("read").unwrap(),+ &json!({"path": "linked.js"}),+ &root,+ )+ .await;assert!(out.contains("needle"), "in-root symlink was refused: {out}");- let out = execute_builtin(lookup("grep").unwrap(), &json!({"pattern": "needle", "path": "."}), &root).await;- assert!(out.contains("linked.js"), "in-root symlink was skipped: {out}");+ let out = execute_builtin(+ lookup("grep").unwrap(),+ &json!({"pattern": "needle", "path": "."}),+ &root,+ )+ .await;+ assert!(+ out.contains("linked.js"),+ "in-root symlink was skipped: {out}"+ );let _ = std::fs::remove_dir_all(&root);}@@ -2056,7 +2341,10 @@ mod tests {let outside = unique_root();std::os::unix::fs::symlink(&outside, scratch.join("jan-bash")).unwrap();- assert!(new_temp_path(Some(&scratch)).is_none(), "dir symlink accepted");+ assert!(+ new_temp_path(Some(&scratch)).is_none(),+ "dir symlink accepted"+ );assert!(write_temp_output("x", Some(&scratch)).is_none(),"wrote through a redirected spill dir"@@ -2113,7 +2401,8 @@ mod tests {&json!({"path": "/tmp/esc/pwned.txt", "content": "x"}),&ctx,)- .await.0;+ .await+ .0;assert!(out.starts_with("ERROR"), "must be refused, got: {out}");assert!(!outside.join("pwned.txt").exists(),@@ -2135,7 +2424,8 @@ mod tests {let outside = unique_root();std::fs::write(outside.join("secret.txt"), b"classified").unwrap();std::os::unix::fs::symlink(outside.join("secret.txt"), root.join("link.txt")).unwrap();- let out = execute_builtin(lookup("read").unwrap(), &json!({"path": "link.txt"}), &root).await;+ let out =+ execute_builtin(lookup("read").unwrap(), &json!({"path": "link.txt"}), &root).await;assert!(out.starts_with("ERROR"), "must refuse, got: {out}");let _ = std::fs::remove_dir_all(&root);let _ = std::fs::remove_dir_all(&outside);@@ -2196,7 +2486,8 @@ mod tests {&json!({"path": "/tmp/scratch.txt", "content": "persist"}),&ctx,)- .await.0;+ .await+ .0;assert!(out.starts_with("Created /tmp/scratch.txt"), "got: {out}");assert!(scratch.join("scratch.txt").exists(), "wrote into scratch");@@ -2205,7 +2496,8 @@ mod tests {&json!({"path": "/tmp/scratch.txt"}),&ctx,)- .await.0;+ .await+ .0;assert_eq!(out, "persist");// No stray file on the real host /tmp.@@ -2273,6 +2565,7 @@ mod tests {&json!({"path": "/tmp/x.txt", "content": "y"}),&root,Some(&scratch),+ &[],&crate::permissions::ToolPermissions::default(),&crate::tools::gate::SessionGrants::default(),true,@@ -2301,6 +2594,7 @@ mod tests {&json!({"path": "/tmp/esc/x.txt", "content": "y"}),&root,Some(&scratch),+ &[],&crate::permissions::ToolPermissions::default(),&crate::tools::gate::SessionGrants::default(),true,@@ -2349,7 +2643,10 @@ mod tests {let out = execute_builtin(lookup("ls").unwrap(), &json!({}), &root).await;assert!(out.contains("src.rs"), "unexpected: {out}");assert!(out.contains("JAN.md"), "unexpected: {out}");- assert!(!out.contains(".jan/"), "must not list the agent state dir: {out}");+ assert!(+ !out.contains(".jan/"),+ "must not list the agent state dir: {out}"+ );let _ = std::fs::remove_dir_all(&root);}@@ -2363,9 +2660,14 @@ mod tests {std::fs::write(root.join("src.rs"), b"x").unwrap();let store = crate::workspace::project_store(&root);let ctx = ToolContext::new(&root, &store, &[]).with_sandbox(false);- let out = super::execute_builtin(lookup("ls").unwrap(), &json!({}), &ctx).await.0;+ let out = super::execute_builtin(lookup("ls").unwrap(), &json!({}), &ctx)+ .await+ .0;assert!(out.contains("src.rs"), "unexpected: {out}");- assert!(out.contains(".jan/"), "must list .jan when unconfined: {out}");+ assert!(+ out.contains(".jan/"),+ "must list .jan when unconfined: {out}"+ );let _ = std::fs::remove_dir_all(&root);}@@ -2531,7 +2833,10 @@ mod tests {.0;let streamed = seen.lock().unwrap().clone();assert!(streamed.contains("one"), "sink saw nothing: {streamed:?}");- assert!(streamed.contains("two"), "sink missed a chunk: {streamed:?}");+ assert!(+ streamed.contains("two"),+ "sink missed a chunk: {streamed:?}"+ );// The return value still carries it, so the model's view is unchanged.assert!(out.contains("one") && out.contains("two"), "{out}");let _ = std::fs::remove_dir_all(&root);@@ -2815,7 +3120,8 @@ mod tests {&json!({"command": "for i in $(seq 1 16000); do printf '%064d\\n' \"$i\"; done"}),&ctx,)- .await.0;+ .await+ .0;let path = out.rsplit("full output written to ").next()@@ -2832,7 +3138,8 @@ mod tests {&json!({"path": path, "offset": 15999, "limit": 1}),&ctx,)- .await.0;+ .await+ .0;assert!(full.contains("015999") || full.contains("016000"),"spill at {path} must be readable back: {full}"@@ -2855,8 +3162,12 @@ mod tests {&json!({"command": "echo unconfined"}),&ctx,)- .await.0;- assert!(out.contains("unconfined"), "unsandboxed bash did not run: {out}");+ .await+ .0;+ assert!(+ out.contains("unconfined"),+ "unsandboxed bash did not run: {out}"+ );assert!(!out.contains("no OS sandbox could be established"),"withheld despite the opt-out: {out}"@@ -3069,20 +3380,24 @@ mod tests {let store = crate::workspace::project_store(&root);let ctx = ToolContext::new(&root, &store, &enabled);- let list = super::execute_builtin(lookup("skill_list").unwrap(), &json!({}), &ctx).await.0;+ let list = super::execute_builtin(lookup("skill_list").unwrap(), &json!({}), &ctx)+ .await+ .0;assert!(list.contains("on"), "list: {list}");assert!(!list.contains("off body"), "disabled skill leaked: {list}");// Disabled skill is unreadable.let read_off =super::execute_builtin(lookup("skill_read").unwrap(), &json!({"name": "off"}), &ctx)- .await.0;+ .await+ .0;assert!(read_off.starts_with("ERROR"), "disabled read: {read_off}");// Enabled skill still readable.let read_on =super::execute_builtin(lookup("skill_read").unwrap(), &json!({"name": "on"}), &ctx)- .await.0;+ .await+ .0;assert_eq!(read_on, "on body");// A disabled skill is read-only for the model: writing to it is refused@@ -3092,14 +3407,16 @@ mod tests {&json!({"name": "off", "content": "evil body"}),&ctx,)- .await.0;+ .await+ .0;assert!(write_off.starts_with("ERROR"),"disabled write: {write_off}");let r =super::execute_builtin(lookup("skill_read").unwrap(), &json!({"name": "off"}), &ctx)- .await.0;+ .await+ .0;assert!(r.starts_with("ERROR"), "still disabled after write");let _ = std::fs::remove_dir_all(&root);}@@ -3167,4 +3484,85 @@ mod tests {}let _ = std::fs::remove_dir_all(&root);}+ // ---- screenshot ---------------------------------------------------------++ /// Two headless Chromes racing for the same profile dir collide, so the+ /// tests that actually launch one are serialised.+ static CHROME_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());++ #[tokio::test]+ async fn screenshot_rejects_a_non_html_file() {+ let root = unique_root();+ std::fs::write(root.join("a.txt"), b"nope").unwrap();+ let (out, images) = screenshot(&json!({"path": "a.txt"}), &root, None, &[]).await;+ assert!(out.contains("only renders"), "{out}");+ assert!(images.is_none());+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn screenshot_rejects_a_missing_file() {+ let root = unique_root();+ let (out, images) = screenshot(&json!({"path": "gone.html"}), &root, None, &[]).await;+ assert!(out.contains("file not found"), "{out}");+ assert!(images.is_none());+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn screenshot_requires_a_path() {+ let root = unique_root();+ let (out, _) = screenshot(&json!({}), &root, None, &[]).await;+ assert!(out.contains("missing required argument"), "{out}");+ let _ = std::fs::remove_dir_all(&root);+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn screenshot_refuses_a_symlink_out_of_the_workspace() {+ let root = unique_root();+ let outside = unique_root();+ let secret = outside.join("secret.html");+ std::fs::write(&secret, b"<h1>secret</h1>").unwrap();+ let link = root.join("innocent.html");+ std::os::unix::fs::symlink(&secret, &link).unwrap();++ let (out, images) = screenshot(&json!({"path": "innocent.html"}), &root, None, &[]).await;+ assert!(out.contains("symlink"), "{out}");+ assert!(images.is_none());+ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&outside);+ }++ /// Renders for real when a browser is present, and returns an image part+ /// rather than a data URL buried in the text.+ #[tokio::test]+ async fn screenshot_returns_an_image_part_when_chrome_is_present() {+ if chrome_binary().is_none() {+ return;+ }+ let _guard = CHROME_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let root = unique_root();+ std::fs::write(+ root.join("page.html"),+ b"<html><body style=\"background:#0af\"><h1>hi</h1></body></html>",+ )+ .unwrap();++ let (out, images) = screenshot(+ &json!({"path": "page.html", "width": 400, "height": 300}),+ &root,+ None,+ &[],+ )+ .await;+ assert!(!out.starts_with("ERROR"), "{out}");+ let images = images.expect("an image part");+ assert_eq!(images.len(), 1);+ assert!(images[0].data_url.starts_with("data:image/png;base64,"));+ assert_eq!(images[0].name, "page.html");+ // The base64 stays out of the model-facing text.+ assert!(!out.contains("base64"), "{out}");+ let _ = std::fs::remove_dir_all(&root);+ }}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rsindex 94c6c29e2..3662a67a2 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@@ -95,6 +95,10 @@ pub struct Policy {/// The directory must already exist before the sandbox is built (the/// backends reference it, they do not create it).pub scratch_root: Option<PathBuf>,+ /// 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).+ pub read_roots: Vec<PathBuf>,}impl Policy {@@ -106,9 +110,17 @@ impl Policy {hide_root: None,home_readonly: false,scratch_root: None,+ read_roots: Vec::new(),}}+ /// Attach read-only roots. See [`Policy::read_roots`] for why their bind+ /// order relative to the masks and the workspace is load-bearing.+ pub fn with_read_roots(mut self, read_roots: Vec<PathBuf>) -> Self {+ self.read_roots = read_roots;+ self+ }+/// Mask `mask_root` from the sandboxed shell. The desktop data folder holds/// the permanent memory/skills store and `settings.json` with provider keys;/// masking it keeps a relocated data folder out of the shell's reach. The@@ -357,7 +369,14 @@ pub fn bwrap_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {// It is deliberately read-only, so no later rw bind can shadow it.if let Some(home) = home_dir() {if policy.home_readonly {- push(&mut args, &["--ro-bind", &home.to_string_lossy(), &home.to_string_lossy()]);+ push(+ &mut args,+ &[+ "--ro-bind",+ &home.to_string_lossy(),+ &home.to_string_lossy(),+ ],+ );} else {push(&mut args, &["--tmpfs", &home.to_string_lossy()]);}@@ -370,6 +389,17 @@ pub fn bwrap_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {push(&mut args, &["--tmpfs", &mask.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+ // either is punched back through, and before the workspace bind so a read+ // root can never shadow the one writable path. Read-only, so nothing the+ // shell does can write into the user's own folder. Not `--ro-bind-try`: a+ // root that vanished should fail loudly rather than silently unmount.+ for root in &policy.read_roots {+ let root = root.to_string_lossy();+ push(&mut args, &["--ro-bind", &root, &root]);+ }+push(&mut args, &["--bind", &ws, &ws]);// After the workspace bind, so it is not shadowed by it: an empty tmpfs where// the agent's own state directory sits. Mounted unconditionally rather than@@ -467,6 +497,16 @@ pub fn seatbelt_policy(policy: &Policy) -> String {(allow file-write* (subpath (param \"SCRATCH\")))\n",);}+ // 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+ // one per root, and only with the matching `-DREAD_ROOT_n`, since+ // sandbox-exec refuses a profile referencing an unsupplied parameter.+ for i in 0..policy.read_roots.len() {+ p.push_str(&format!(+ "(allow file-read* (subpath (param \"READ_ROOT_{i}\")))\n"+ ));+ }// Last, so it wins over the workspace allow above: the agent's own state// directory is neither readable nor writable, however the command spells it.if policy.hide_root.is_some() {@@ -505,6 +545,9 @@ pub fn seatbelt_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {if let Some(mask) = &policy.mask_root {args.push(format!("-DMASK_ROOT={}", mask.to_string_lossy()));}+ for (i, root) in policy.read_roots.iter().enumerate() {+ args.push(format!("-DREAD_ROOT_{i}={}", root.to_string_lossy()));+ }if let Some(hide) = &policy.hide_root {args.push(format!("-DHIDE_ROOT={}", hide.to_string_lossy()));}@@ -573,8 +616,30 @@ pub fn denial_hint(policy: &Policy) -> String {Some(path) => format!(" and the scratch dir ({})", path.display()),None => String::new(),};+ // An attached folder the file tools can read but the shell cannot is a real+ // asymmetry on Windows, where granting it would mean permanently rewriting+ // the DACL of a directory Jan does not own and never revokes. Saying so+ // beats letting the model read the folder with `read` and conclude `bash` is+ // broken when the same path is missing there.+ let attached = if policy.read_roots.is_empty() {+ String::new()+ } else if backend() == Backend::AppContainer {+ " The attached folder is readable by the file tools but not by shell \+ commands on this platform."+ .to_string()+ } else {+ format!(+ " The attached folder ({}) is readable but not writable.",+ policy+ .read_roots+ .iter()+ .map(|r| r.display().to_string())+ .collect::<Vec<_>>()+ .join(", ")+ )+ };format!(- "\n[sandbox: writes are limited to the workspace ({}){scratch}{home}.{net}]",+ "\n[sandbox: writes are limited to the workspace ({}){scratch}{home}.{net}{attached}]",policy.workspace.display())}@@ -653,11 +718,96 @@ mod tests {));let bind = text.find(&format!("--bind {ws} {ws}")).expect("bind");let tmpfs = text.find(&format!("--tmpfs {hide}")).expect("hide tmpfs");- assert!(bind < tmpfs, "the mask must follow the workspace bind: {text}");+ assert!(+ bind < tmpfs,+ "the mask must follow the workspace bind: {text}"+ );// Unset by default, so nothing is hidden where no state dir is named.assert!(!joined(&bwrap_args(&policy(), &cfg())).contains(".jan"));}+ /// The bind order *is* the enforcement, on both sides: after the `$HOME`+ /// tmpfs so a folder living under the home is punched back through the mask,+ /// and before the workspace bind so a read root can never shadow the only+ /// writable path.+ #[test]+ fn bwrap_binds_read_roots_between_the_home_mask_and_the_workspace() {+ let ws = "/data/agent-workspace/threads/t1";+ let repo = "/home/u/Projects/app";+ let text = joined(&bwrap_args(+ &policy().with_read_roots(vec![PathBuf::from(repo)]),+ &cfg(),+ ));+ let home = home_dir().expect("a home dir");+ let home_tmpfs = text+ .find(&format!("--tmpfs {}", home.to_string_lossy()))+ .expect("home tmpfs");+ let ro = text+ .find(&format!("--ro-bind {repo} {repo}"))+ .expect("read root bind");+ let bind = text.find(&format!("--bind {ws} {ws}")).expect("ws bind");+ assert!(+ home_tmpfs < ro,+ "read root must follow the home mask: {text}"+ );+ assert!(+ ro < bind,+ "read root must precede the workspace bind: {text}"+ );+ }++ #[test]+ fn bwrap_binds_read_roots_read_only_and_omits_them_by_default() {+ let repo = "/home/u/repo";+ let text = joined(&bwrap_args(+ &policy().with_read_roots(vec![PathBuf::from(repo)]),+ &cfg(),+ ));+ assert!(text.contains(&format!("--ro-bind {repo} {repo}")), "{text}");+ assert!(+ !text.contains(&format!("--bind {repo} {repo}")),+ "never writable: {text}"+ );+ assert!(!joined(&bwrap_args(&policy(), &cfg())).contains(repo));+ }++ /// Seatbelt takes the last matching rule, so the read allow has to come+ /// after the HOME/MASK denials or a folder inside either stays unreadable.+ #[test]+ fn seatbelt_allows_read_roots_after_the_denials_and_never_writes() {+ let repo = "/Users/u/repo";+ let p = seatbelt_policy(+ &policy()+ .with_mask_root(Path::new("/data"))+ .with_read_roots(vec![PathBuf::from(repo)]),+ );+ let deny = p+ .find("(deny file-read* (subpath (param \"MASK_ROOT\")))")+ .expect("mask deny");+ let allow = p+ .find("(allow file-read* (subpath (param \"READ_ROOT_0\")))")+ .expect("read root allow");+ assert!(deny < allow, "the allow must win over the denials: {p}");+ assert!(+ !p.contains("(allow file-write* (subpath (param \"READ_ROOT_0\")))"),+ "a read root is never writable: {p}"+ );++ let args = seatbelt_args(&policy().with_read_roots(vec![PathBuf::from(repo)]), &cfg());+ assert!(args.iter().any(|a| a == &format!("-DREAD_ROOT_0={repo}")));+ }++ /// sandbox-exec refuses a profile that references a parameter no `-D`+ /// supplies, so the rule and the argument have to appear together.+ #[test]+ fn seatbelt_omits_the_read_root_rule_when_there_is_none() {+ let p = seatbelt_policy(&policy());+ assert!(!p.contains("READ_ROOT"), "{p}");+ assert!(!seatbelt_args(&policy(), &cfg())+ .iter()+ .any(|a| a.contains("READ_ROOT")));+ }+#[test]fn seatbelt_denies_the_agent_state_dir_last() {let hide = "/data/agent-workspace/threads/t1/.jan";@@ -739,9 +889,15 @@ mod tests {// home_readonly: no home read-denial, and the write section never opens// HOME_ROOT, so reads work but writes stay confined to workspace/temp.let p = seatbelt_policy(&policy().with_home_readonly(true));- assert!(!p.contains("(deny file-read* (subpath (param \"HOME_ROOT\")))"), "{p}");+ assert!(+ !p.contains("(deny file-read* (subpath (param \"HOME_ROOT\")))"),+ "{p}"+ );assert!(p.contains("(allow file-read*)"), "{p}");- assert!(!p.contains("(allow file-write* (subpath (param \"HOME_ROOT\")))"), "{p}");+ assert!(+ !p.contains("(allow file-write* (subpath (param \"HOME_ROOT\")))"),+ "{p}"+ );}#[test]@@ -1138,8 +1294,14 @@ mod enforcement_tests {let _ = std::fs::remove_file(&secret);let _ = std::fs::remove_file(&victim);let _ = std::fs::remove_dir_all(&ws);- assert!(out.contains("READABLE_SECRET"), "home reads must work: {out}");- assert!(!leaked, "home writes must stay confined even when readable: {out}");+ assert!(+ out.contains("READABLE_SECRET"),+ "home reads must work: {out}"+ );+ assert!(+ !leaked,+ "home writes must stay confined even when readable: {out}"+ );assert!(!ok, "the write into the home must fail: {out}");}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rsindex 851e65453..d64e418aa 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@@ -1,7 +1,7 @@//! Built-in agent tools: the capability classification and the `BUILTIN_TOOLS`//! registry every other module in this crate keys off.-use std::path::Path;+use std::path::{Path, PathBuf};/// Windows-only confinement backend for [`jail`]. Present on every platform so/// the argv it builds stays unit-testable.@@ -95,6 +95,21 @@ pub struct ToolContext<'a> {/// a backgrounded command keep reporting after the tool has returned its/// `job_id`.pub on_output: Option<OutputSink>,+ /// Folders attached read-only: readable by the file tools and the shell,+ /// never writable. Empty on every surface that has not attached one.+ ///+ /// Owned paths rather than borrows because they are canonicalized once at+ /// attach time; re-canonicalizing per call would be both slower and a+ /// check/use race of its own.+ pub read_roots: &'a [PathBuf],+ /// Correlation id echoed on every streamed output chunk.+ ///+ /// Needed because `bash` with `timeout: 0` backgrounds and keeps streaming+ /// after the tool has returned: without an id the caller cannot route late+ /// chunks to the tool call that produced them. Minted by the caller (the+ /// frontend's tool-call id) rather than inside `bash`, so the sink can carry+ /// it from the first chunk.+ pub call_id: Option<&'a str>,}impl std::fmt::Debug for ToolContext<'_> {@@ -112,6 +127,8 @@ impl std::fmt::Debug for ToolContext<'_> {.field("scratch_root", &self.scratch_root).field("sandbox", &self.sandbox).field("on_output", &self.on_output.is_some())+ .field("read_roots", &self.read_roots)+ .field("call_id", &self.call_id).finish()}}@@ -133,9 +150,24 @@ impl<'a> ToolContext<'a> {scratch_root: None,sandbox: true,on_output: None,+ read_roots: &[],+ call_id: None,}}+ /// Attach folders the tools may read but never write. Callers pass the+ /// canonical form from [`crate::workspace::validate_read_root`].+ pub fn with_read_roots(mut self, read_roots: &'a [PathBuf]) -> Self {+ self.read_roots = read_roots;+ self+ }++ /// Tag streamed output with `call_id`. See [`Self::call_id`].+ pub fn with_call_id(mut self, call_id: &'a str) -> Self {+ self.call_id = Some(call_id);+ self+ }+/// Stream this call's output to `sink` as it is produced, as well as/// returning it. See [`Self::on_output`].pub fn with_output_sink(mut self, sink: OutputSink) -> Self {@@ -232,6 +264,12 @@ pub const BUILTIN_TOOLS: &[BuiltinTool] = &[capability: Capability::Read,path_args: &["path"],},+ // Read: it renders a file that is already reachable and writes nothing back.+ BuiltinTool {+ name: "screenshot",+ capability: Capability::Read,+ path_args: &["path"],+ },BuiltinTool {name: "write",capability: Capability::Write,@@ -344,8 +382,8 @@ mod tests {#[test]fn builtin_count_matches_expected() {- // 7 coding tools + 6 dedicated skill/memory tools + 2 native web tools.- assert_eq!(BUILTIN_TOOLS.len(), 15);+ // 8 coding tools + 6 dedicated skill/memory tools + 2 native web tools.+ assert_eq!(BUILTIN_TOOLS.len(), 16);}#[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.rsindex da0a2f853..836c79939 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@@ -54,6 +54,46 @@ pub fn escapes_project(Ok(true)}+/// True iff `raw` escapes every root a *read* may legitimately reach: the+/// project, the scratch, or any attached read-only root.+///+/// Layered on [`escapes_project`] rather than replacing it, so the write path+/// keeps the exact check it has today and a read root can only ever widen what+/// reads reach, never what writes do.+///+/// A read root that cannot be canonicalized grants nothing — same rule as the+/// scratch above. A vanished root must not silently open a path up.+pub fn escapes_read_roots(+ project_root: &Path,+ scratch: Option<&Path>,+ read_roots: &[PathBuf],+ raw: &str,+) -> Result<bool, String> {+ if !escapes_project(project_root, scratch, raw)? {+ return Ok(false);+ }+ if read_roots.is_empty() {+ return Ok(true);+ }+ let abs = if Path::new(raw).is_absolute() {+ PathBuf::from(raw)+ } else {+ // Relative paths belong to the workspace, never to an attached folder:+ // resolving them against a read root would make `write` and `read`+ // disagree about what one path means.+ project_root.join(raw)+ };+ let resolved = canonicalize_lenient(&abs)?;+ for root in read_roots {+ if let Ok(root) = root.canonicalize() {+ if resolved.starts_with(&root) {+ return Ok(false);+ }+ }+ }+ 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@@ -225,15 +265,29 @@ pub fn command_touches_hidden_jan_path(project_root: &Path, command: &str) -> bo/// Still a re-check, not a guarantee: a swap landing between this call and the/// open is not covered. That needs descriptor-relative no-follow opens/// (`openat2` with `RESOLVE_BENEATH`, reparse-point handling on Windows).-pub fn symlink_escapes_root(+pub fn symlink_escapes_root(project_root: &Path, scratch: Option<&Path>, target: &Path) -> bool {+ symlink_escapes_any_root(project_root, scratch, &[], target)+}++/// As [`symlink_escapes_root`], but also treating `read_roots` as trusted.+///+/// Passing the read roots is not optional once one is attached: a path inside+/// an attached folder is not lexically under the project or the scratch, so the+/// early return above would classify it as "already decided" and skip the check+/// entirely — leaving a link in the user's repo pointing at `~/.ssh` followed.+pub fn symlink_escapes_any_root(project_root: &Path,scratch: Option<&Path>,+ read_roots: &[PathBuf],target: &Path,) -> bool {let mut roots = vec![project_root];if let Some(s) = scratch {roots.push(s);}+ for r in read_roots {+ roots.push(r.as_path());+ }let normalized = lexical_normalize(target);if !roots.iter()@@ -344,7 +398,10 @@ mod tests {fn absolute_outside_escapes() {let root = unique_root();let outside = std::env::temp_dir().join("definitely_outside_the_root.txt");- assert_eq!(escapes_project(&root, None, outside.to_str().unwrap()), Ok(true));+ assert_eq!(+ escapes_project(&root, None, outside.to_str().unwrap()),+ Ok(true)+ );let _ = std::fs::remove_dir_all(&root);}@@ -353,7 +410,10 @@ mod tests {let root = unique_root();std::fs::write(root.join("inner.txt"), b"x").unwrap();let inside = root.join("inner.txt");- assert_eq!(escapes_project(&root, None, inside.to_str().unwrap()), Ok(false));+ assert_eq!(+ escapes_project(&root, None, inside.to_str().unwrap()),+ Ok(false)+ );let _ = std::fs::remove_dir_all(&root);}@@ -365,7 +425,6 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}-#[test]fn hidden_path_covers_the_whole_jan_dir() {let root = unique_root();@@ -565,16 +624,32 @@ mod tests {std::os::unix::fs::symlink(&outside, &outward).unwrap();assert!(!symlink_escapes_root(&root, None, &inward.join("index.js")));- assert!(symlink_escapes_root(&root, None, &outward.join("secret.txt")));+ assert!(symlink_escapes_root(+ &root,+ None,+ &outward.join("secret.txt")+ ));// A not-yet-existing leaf under a real directory is not an escape.- assert!(!symlink_escapes_root(&root, None, &root.join("pkg/new.txt")));+ assert!(!symlink_escapes_root(+ &root,+ None,+ &root.join("pkg/new.txt")+ ));// Outside both roots: the gate already decided, so this check abstains.- assert!(!symlink_escapes_root(&root, None, &outside.join("secret.txt")));+ assert!(!symlink_escapes_root(+ &root,+ None,+ &outside.join("secret.txt")+ ));// The scratch counts as a trusted root, so a link between the two is in.let scratch = unique_root();let cross = scratch.join("into-project");std::os::unix::fs::symlink(root.join("pkg"), &cross).unwrap();- assert!(!symlink_escapes_root(&root, Some(&scratch), &cross.join("index.js")));+ assert!(!symlink_escapes_root(+ &root,+ Some(&scratch),+ &cross.join("index.js")+ ));let _ = std::fs::remove_dir_all(&root);let _ = std::fs::remove_dir_all(&outside);@@ -591,4 +666,116 @@ mod tests {assert_eq!(tmp_relative("/tmpx"), None);assert_eq!(tmp_relative("/tmp-archive/a.txt"), None);}+ // ---- read-only attached roots -------------------------------------------++ #[test]+ fn a_path_in_a_read_root_is_not_a_read_escape() {+ let ws = unique_root_outside_tmp();+ let repo = unique_root_outside_tmp();+ std::fs::write(repo.join("main.rs"), b"fn main() {}").unwrap();+ let roots = vec![repo.clone()];+ let target = repo.join("main.rs").to_string_lossy().into_owned();++ // Without the root it is an escape; with it, a legitimate read.+ assert!(escapes_project(&ws, None, &target).unwrap());+ assert!(!escapes_read_roots(&ws, None, &roots, &target).unwrap());++ let _ = std::fs::remove_dir_all(&ws);+ let _ = std::fs::remove_dir_all(&repo);+ }++ // The whole point of the mount: reads widen, writes do not. `escapes_project`+ // is what the write path keeps using, so it must still call this an escape.+ #[test]+ fn a_write_into_a_read_root_is_still_an_escape() {+ let ws = unique_root_outside_tmp();+ let repo = unique_root_outside_tmp();+ let target = repo.join("new.txt").to_string_lossy().into_owned();+ assert!(escapes_project(&ws, None, &target).unwrap());+ let _ = std::fs::remove_dir_all(&ws);+ let _ = std::fs::remove_dir_all(&repo);+ }++ #[test]+ fn a_path_outside_every_root_is_still_an_escape() {+ let ws = unique_root_outside_tmp();+ let repo = unique_root_outside_tmp();+ let other = unique_root_outside_tmp();+ let roots = vec![repo.clone()];+ let target = other.join("secret").to_string_lossy().into_owned();+ assert!(escapes_read_roots(&ws, None, &roots, &target).unwrap());+ for d in [&ws, &repo, &other] {+ let _ = std::fs::remove_dir_all(d);+ }+ }++ // A read root that vanished must grant nothing, matching the scratch rule.+ #[test]+ fn a_missing_read_root_grants_nothing() {+ let ws = unique_root_outside_tmp();+ let gone = unique_root_outside_tmp();+ let target = gone.join("x").to_string_lossy().into_owned();+ std::fs::remove_dir_all(&gone).unwrap();+ let roots = vec![gone];+ assert!(escapes_read_roots(&ws, None, &roots, &target).unwrap());+ let _ = std::fs::remove_dir_all(&ws);+ }++ // Relative paths belong to the workspace. Resolving them against an attached+ // folder would make `read` and `write` disagree about what one path means.+ #[test]+ fn a_relative_path_still_resolves_against_the_workspace() {+ let ws = unique_root_outside_tmp();+ let repo = unique_root_outside_tmp();+ std::fs::write(repo.join("only-in-repo.txt"), b"x").unwrap();+ let roots = vec![repo.clone()];+ assert!(escapes_read_roots(&ws, None, &roots, "only-in-repo.txt").is_ok());+ let _ = std::fs::remove_dir_all(&ws);+ let _ = std::fs::remove_dir_all(&repo);+ }++ // The hole this mount opens if the read roots are not passed: a link inside+ // the attached folder is not lexically under the workspace, so the plain+ // check returns "already decided" and never looks at where it points.+ #[cfg(unix)]+ #[test]+ fn a_symlink_out_of_a_read_root_is_caught() {+ let ws = unique_root_outside_tmp();+ let repo = unique_root_outside_tmp();+ let secret_dir = unique_root_outside_tmp();+ let secret = secret_dir.join("id_rsa");+ std::fs::write(&secret, b"key").unwrap();+ let link = repo.join("innocent.txt");+ std::os::unix::fs::symlink(&secret, &link).unwrap();+ let roots = vec![repo.clone()];++ assert!(+ symlink_escapes_any_root(&ws, None, &roots, &link),+ "a link leaving the attached folder must be refused"+ );+ assert!(+ !symlink_escapes_root(&ws, None, &link),+ "and the plain check is exactly why the roots must be passed"+ );+ for d in [&ws, &repo, &secret_dir] {+ let _ = std::fs::remove_dir_all(d);+ }+ }++ // A link that stays inside the attached folder is ordinary and must work --+ // every monorepo has them.+ #[cfg(unix)]+ #[test]+ fn a_symlink_inside_a_read_root_is_allowed() {+ let repo = unique_root_outside_tmp();+ let ws = unique_root_outside_tmp();+ let real = repo.join("real.txt");+ std::fs::write(&real, b"x").unwrap();+ let link = repo.join("link.txt");+ std::os::unix::fs::symlink(&real, &link).unwrap();+ let roots = vec![repo.clone()];+ assert!(!symlink_escapes_any_root(&ws, None, &roots, &link));+ let _ = std::fs::remove_dir_all(&repo);+ let _ = std::fs::remove_dir_all(&ws);+ }}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rsindex 7df6ed50f..343113a03 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs@@ -74,6 +74,22 @@ pub fn builtin_tool_schemas() -> Vec<Value> {}}}),+ json!({+ "type": "function",+ "function": {+ "name": "screenshot",+ "description": "Render a local HTML or SVG file with headless Chrome and return a PNG screenshot of it, so you can see what you built and iterate on the visual result. Use after writing an HTML/SVG artifact to check its appearance; the returned image is what a viewer would see. Relative assets (images, css, js) resolve against the file's own directory. Non-HTML/SVG files are rejected.",+ "parameters": {+ "type": "object",+ "properties": {+ "path": { "type": "string", "description": "Project-relative or absolute path to the .html/.htm/.svg file to render." },+ "width": { "type": "integer", "description": "Viewport width in pixels (default 1280)." },+ "height": { "type": "integer", "description": "Viewport height in pixels (default 960)." }+ },+ "required": ["path"]+ }+ }+ }),json!({"type": "function","function": {@@ -245,7 +261,7 @@ mod tests {#[test]fn schemas_match_builtin_tools() {let schemas = builtin_tool_schemas();- assert_eq!(schemas.len(), 15);+ assert_eq!(schemas.len(), 16);for schema in &schemas {assert_eq!(schema["type"], "function");}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rsindex e92a63183..0691d7b6c 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs@@ -23,6 +23,14 @@ use std::path::{Path, PathBuf};const THREADS: &str = "threads";+/// Where Cowork session sandboxes live, a sibling of `threads/`.+///+/// Separate from `threads/` because a Cowork session is not a chat thread and+/// the two id spaces are independent. The separation is also what makes the+/// thread sweep safe: it reads only `threads_dir`, so it structurally cannot see+/// a session workspace, whatever `keep` list it is handed.+const SESSIONS: &str = "sessions";+/// `<store_root>/<kind>`, for `kind` in `{memory, skills}`.pub fn store_dir(store_root: &Path, kind: &str) -> PathBuf {store_root.join(kind)@@ -55,12 +63,91 @@ pub fn threads_dir(jan_data_folder: &Path) -> PathBuf {permanent_store(jan_data_folder).join(THREADS)}+/// Where per-session sandboxes live: `<permanent_store>/sessions`.+pub fn sessions_dir(jan_data_folder: &Path) -> PathBuf {+ permanent_store(jan_data_folder).join(SESSIONS)+}++/// A Cowork session's sandbox root:+/// `<jan_data_folder>/agent-workspace/sessions/<session_id>`.+pub fn session_workspace(jan_data_folder: &Path, session_id: &str) -> Result<PathBuf, String> {+ Ok(sessions_dir(jan_data_folder).join(thread_segment(session_id)?))+}+/// A thread's ephemeral sandbox root:/// `<jan_data_folder>/agent-workspace/threads/<thread_id>`.pub fn thread_workspace(jan_data_folder: &Path, thread_id: &str) -> Result<PathBuf, String> {Ok(threads_dir(jan_data_folder).join(thread_segment(thread_id)?))}+/// Case-folded on Windows, where two spellings of one path are the same path+/// and a raw `starts_with` would let a rename past the check.+fn containment_key(path: &Path) -> String {+ let raw = path.to_string_lossy().replace('\\', "/");+ if cfg!(windows) {+ raw.to_lowercase()+ } else {+ raw+ }+}++fn is_within(inner: &Path, outer: &Path) -> bool {+ let (inner, outer) = (containment_key(inner), containment_key(outer));+ inner == outer || inner.starts_with(&format!("{}/", outer.trim_end_matches('/')))+}++/// Validate a folder the user asked to attach read-only, returning its+/// canonical form.+///+/// Refused rather than silently degraded, because every rejection here is a+/// case where the mount would not mean what the UI says it means:+///+/// - a root that does not exist would have the sandbox fail later, at a point+/// the user cannot connect to their choice;+/// - a root containing the workspace would shadow it, and would also make+/// `escapes_project` start returning false for the whole tree;+/// - a root inside the workspace is already writable, so calling it read-only+/// would be a lie;+/// - a root containing the Jan data folder would re-expose `settings.json` and+/// the provider keys the mask exists to hide;+/// - the filesystem root has no meaningful "outside" left to protect.+pub fn validate_read_root(+ root: &Path,+ workspace: &Path,+ mask_root: Option<&Path>,+) -> Result<PathBuf, String> {+ let canonical = root+ .canonicalize()+ .map_err(|e| format!("attached folder {} is unreadable: {e}", root.display()))?;+ if !canonical.is_dir() {+ return Err(format!("{} is not a folder", canonical.display()));+ }+ if canonical.parent().is_none() {+ return Err("the filesystem root cannot be attached".to_string());+ }+ // The workspace may not exist yet on the first call; compare lexically+ // against whatever form we have rather than failing the attach for it.+ let workspace_key = workspace+ .canonicalize()+ .unwrap_or_else(|_| workspace.to_path_buf());+ if is_within(&workspace_key, &canonical) || is_within(&canonical, &workspace_key) {+ return Err(format!(+ "{} overlaps the agent workspace and cannot be mounted read-only",+ canonical.display()+ ));+ }+ if let Some(mask) = mask_root {+ let mask = mask.canonicalize().unwrap_or_else(|_| mask.to_path_buf());+ if is_within(&mask, &canonical) {+ return Err(format!(+ "{} contains the Jan data folder and cannot be attached",+ canonical.display()+ ));+ }+ }+ Ok(canonical)+}+/// 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.@@ -122,7 +209,12 @@ pub async fn ensure_scratch_dir_path(dir: &Path) -> Result<PathBuf, String> {// 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() => {}- _ => return Err(format!("ERROR: scratch path {:?} is not a real directory", dir)),+ _ => {+ return Err(format!(+ "ERROR: scratch path {:?} is not a real directory",+ dir+ ))+ }}}Err(e) => return Err(format!("ERROR: {e}")),@@ -220,7 +312,18 @@ pub async fn ensure_thread_workspace(jan_data_folder: &Path,thread_id: &str,) -> Result<PathBuf, String> {- let dir = thread_workspace(jan_data_folder, thread_id)?;+ ensure_workspace_at(thread_workspace(jan_data_folder, thread_id)?).await+}++/// Create a Cowork session's sandbox (idempotent) and return it.+pub async fn ensure_session_workspace(+ jan_data_folder: &Path,+ session_id: &str,+) -> Result<PathBuf, String> {+ ensure_workspace_at(session_workspace(jan_data_folder, session_id)?).await+}++async fn ensure_workspace_at(dir: PathBuf) -> Result<PathBuf, String> {tokio::fs::create_dir_all(&dir).await.map_err(|e| format!("ERROR: {e}"))?;@@ -232,15 +335,26 @@ pub async fn remove_thread_workspace(jan_data_folder: &Path,thread_id: &str,) -> Result<(), String> {- let dir = thread_workspace(jan_data_folder, thread_id)?;+ remove_workspace_at(thread_workspace(jan_data_folder, thread_id)?, thread_id).await+}++/// Delete a Cowork session's sandbox. Idempotent: a missing sandbox is Ok.+pub async fn remove_session_workspace(+ jan_data_folder: &Path,+ session_id: &str,+) -> Result<(), String> {+ remove_workspace_at(session_workspace(jan_data_folder, session_id)?, session_id).await+}++async fn remove_workspace_at(dir: PathBuf, id: &str) -> Result<(), String> {crate::tools::appcontainer::release(&dir);match tokio::fs::remove_dir_all(&dir).await {Ok(()) => {}Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}Err(e) => return Err(format!("ERROR: {e}")),}- // Wipe the session-scoped host-temp scratch keyed to the same thread id.- let _ = remove_scratch_dir(thread_id).await;+ // Wipe the host-temp scratch keyed to the same id.+ let _ = remove_scratch_dir(id).await;Ok(())}@@ -255,7 +369,28 @@ pub async fn sweep_thread_workspaces(jan_data_folder: &Path,keep: &[String],) -> Result<usize, String> {- let dir = threads_dir(jan_data_folder);+ sweep_workspaces_in(threads_dir(jan_data_folder), keep).await+}++/// Delete every Cowork session sandbox whose id is not in `keep`.+///+/// Reads only `sessions_dir`, so it can never reach a chat thread's sandbox, and+/// the thread sweep can never reach a session's.+pub async fn sweep_session_workspaces(+ jan_data_folder: &Path,+ keep: &[String],+) -> Result<usize, String> {+ sweep_workspaces_in(sessions_dir(jan_data_folder), keep).await+}++async fn sweep_workspaces_in(dir: PathBuf, keep: &[String]) -> Result<usize, String> {+ // An empty keep list means "delete everything here", which is never what a+ // caller wants and is exactly what a failed load or a first-run race+ // produces. The sandbox may hold the only copy of the agent's work, so this+ // fails safe: callers that genuinely want a full wipe remove ids one by one.+ if keep.is_empty() {+ return Ok(0);+ }let Ok(mut entries) = tokio::fs::read_dir(&dir).await else {return Ok(0);};@@ -276,7 +411,7 @@ pub async fn sweep_thread_workspaces(crate::tools::appcontainer::release(&entry.path());if tokio::fs::remove_dir_all(entry.path()).await.is_ok() {removed += 1;- // Wipe the session-scoped host-temp scratch keyed to this thread.+ // Wipe the host-temp scratch keyed to this id.let _ = remove_scratch_dir(&name).await;}}@@ -322,6 +457,24 @@ 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::Mutex<()> = std::sync::Mutex::new(());++/// Take [`SCRATCH_NAMESPACE_LOCK`], ignoring poisoning: a panic in one test must+/// not cascade into unrelated failures in every other one.+#[cfg(test)]+pub(crate) fn lock_scratch_namespace() -> std::sync::MutexGuard<'static, ()> {+ SCRATCH_NAMESPACE_LOCK+ .lock()+ .unwrap_or_else(|e| e.into_inner())+}+#[cfg(test)]mod tests {use super::*;@@ -329,6 +482,11 @@ mod tests {static COUNTER: AtomicUsize = AtomicUsize::new(0);+ fn tmp_root(tag: &str) -> PathBuf {+ let n = COUNTER.fetch_add(1, Ordering::SeqCst);+ std::env::temp_dir().join(format!("jan_{tag}_{}_{}", std::process::id(), n))+ }+fn unique_data_folder() -> PathBuf {let n = COUNTER.fetch_add(1, Ordering::SeqCst);std::env::temp_dir().join(format!("jan_ws_test_{}_{}", std::process::id(), n))@@ -388,17 +546,25 @@ mod tests {#[tokio::test]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();let orphan = ensure_scratch_dir(&session).await.unwrap();std::fs::write(orphan.join("spill.txt"), b"leaked").unwrap();let bystander = std::env::temp_dir().join(format!("not-a-scratch-{session}"));std::fs::create_dir_all(&bystander).unwrap();- assert_eq!(sweep_stale_scratch_dirs().await, 0, "a fresh scratch is live");+ assert_eq!(+ sweep_stale_scratch_dirs().await,+ 0,+ "a fresh scratch is live"+ );assert!(orphan.is_dir());assert!(sweep_scratch_older_than(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");+ assert!(+ bystander.is_dir(),+ "swept a directory that is not a scratch"+ );let _ = std::fs::remove_dir_all(&bystander);}@@ -544,4 +710,175 @@ mod tests {);}}+ // Every rejection here is a case where the mount would not mean what the UI+ // says it means, so each is refused rather than silently degraded.+ #[test]+ fn validate_read_root_accepts_a_plain_sibling_folder() {+ let base = tmp_root("vrr_ok");+ let ws = base.join("agent-workspace/threads/t1");+ let repo = base.join("repo");+ std::fs::create_dir_all(&ws).unwrap();+ std::fs::create_dir_all(&repo).unwrap();+ let out = validate_read_root(&repo, &ws, None).unwrap();+ assert_eq!(out, repo.canonicalize().unwrap());+ let _ = std::fs::remove_dir_all(&base);+ }++ #[test]+ fn validate_read_root_refuses_a_folder_that_does_not_exist() {+ let base = tmp_root("vrr_missing");+ let ws = base.join("ws");+ std::fs::create_dir_all(&ws).unwrap();+ assert!(validate_read_root(&base.join("nope"), &ws, None).is_err());+ let _ = std::fs::remove_dir_all(&base);+ }++ #[test]+ fn validate_read_root_refuses_a_file() {+ let base = tmp_root("vrr_file");+ let ws = base.join("ws");+ std::fs::create_dir_all(&ws).unwrap();+ let file = base.join("a.txt");+ std::fs::write(&file, b"x").unwrap();+ assert!(validate_read_root(&file, &ws, None).is_err());+ let _ = std::fs::remove_dir_all(&base);+ }++ /// A root containing the workspace would shadow it and would also make+ /// `escapes_project` start returning false for the whole tree.+ #[test]+ fn validate_read_root_refuses_an_ancestor_of_the_workspace() {+ let base = tmp_root("vrr_ancestor");+ let ws = base.join("agent-workspace/threads/t1");+ std::fs::create_dir_all(&ws).unwrap();+ assert!(validate_read_root(&base, &ws, None).is_err());+ let _ = std::fs::remove_dir_all(&base);+ }++ /// A "read-only" root inside the writable workspace is a lie: writes there+ /// are already allowed.+ #[test]+ fn validate_read_root_refuses_a_descendant_of_the_workspace() {+ let base = tmp_root("vrr_descendant");+ let ws = base.join("ws");+ let inner = ws.join("inner");+ std::fs::create_dir_all(&inner).unwrap();+ assert!(validate_read_root(&inner, &ws, None).is_err());+ let _ = std::fs::remove_dir_all(&base);+ }++ /// Attaching a folder that contains the Jan data folder would re-expose+ /// settings.json and the provider keys the mask exists to hide.+ #[test]+ fn validate_read_root_refuses_a_root_containing_the_data_folder() {+ let base = tmp_root("vrr_mask");+ let data = base.join("jan-data");+ let ws = data.join("agent-workspace/threads/t1");+ std::fs::create_dir_all(&ws).unwrap();+ assert!(validate_read_root(&base, &ws, Some(&data)).is_err());+ let _ = std::fs::remove_dir_all(&base);+ }++ #[test]+ fn validate_read_root_refuses_the_filesystem_root() {+ let base = tmp_root("vrr_fsroot");+ let ws = base.join("ws");+ std::fs::create_dir_all(&ws).unwrap();+ let root = if cfg!(windows) { "C:\\\\" } else { "/" };+ assert!(validate_read_root(Path::new(root), &ws, None).is_err());+ let _ = std::fs::remove_dir_all(&base);+ }+ // ---- session sandboxes -------------------------------------------------++ #[tokio::test]+ async fn sessions_live_beside_threads_not_inside_them() {+ let data = unique_data_folder();+ let t = ensure_thread_workspace(&data, "id-1").await.unwrap();+ let s = ensure_session_workspace(&data, "id-1").await.unwrap();+ assert_ne!(t, s, "the same id in each space is two directories");+ assert!(!s.starts_with(&t));+ assert!(!t.starts_with(&s));+ assert_eq!(s.parent().unwrap(), sessions_dir(&data));+ let _ = std::fs::remove_dir_all(&data);+ }++ /// The reason for the separate namespace: the thread sweep is handed the+ /// live *thread* ids, which say nothing about which sessions exist. Sharing+ /// one directory would have it delete every session's work.+ #[tokio::test]+ async fn the_two_sweeps_cannot_reach_each_other() {+ let data = unique_data_folder();+ ensure_thread_workspace(&data, "thread-live").await.unwrap();+ let session = ensure_session_workspace(&data, "session-live")+ .await+ .unwrap();+ std::fs::write(session.join("work.txt"), b"the only copy").unwrap();++ // A thread sweep that knows nothing about sessions.+ sweep_thread_workspaces(&data, &["thread-live".to_string()])+ .await+ .unwrap();+ assert!(session.join("work.txt").exists(), "session work survived");++ // And the reverse.+ sweep_session_workspaces(&data, &["session-live".to_string()])+ .await+ .unwrap();+ assert!(thread_workspace(&data, "thread-live").unwrap().is_dir());++ let _ = std::fs::remove_dir_all(&data);+ }++ #[tokio::test]+ async fn a_session_sweep_collects_only_dead_sessions() {+ let data = unique_data_folder();+ ensure_session_workspace(&data, "live").await.unwrap();+ ensure_session_workspace(&data, "dead").await.unwrap();+ let removed = sweep_session_workspaces(&data, &["live".to_string()])+ .await+ .unwrap();+ assert_eq!(removed, 1);+ assert!(session_workspace(&data, "live").unwrap().is_dir());+ assert!(!session_workspace(&data, "dead").unwrap().exists());+ let _ = std::fs::remove_dir_all(&data);+ }++ /// An empty keep list is what a failed load or a first-run race produces,+ /// and the sandbox may hold the only copy of the agent's work. Deleting+ /// everything is never the intent, so it fails safe.+ #[tokio::test]+ async fn an_empty_keep_list_wipes_nothing() {+ let data = unique_data_folder();+ let t = ensure_thread_workspace(&data, "t").await.unwrap();+ let s = ensure_session_workspace(&data, "s").await.unwrap();++ assert_eq!(sweep_thread_workspaces(&data, &[]).await.unwrap(), 0);+ assert_eq!(sweep_session_workspaces(&data, &[]).await.unwrap(), 0);+ assert!(t.is_dir(), "thread sandbox survived an empty keep list");+ assert!(s.is_dir(), "session sandbox survived an empty keep list");++ let _ = std::fs::remove_dir_all(&data);+ }++ #[tokio::test]+ async fn session_workspace_lifecycle_is_idempotent() {+ let data = unique_data_folder();+ let dir = ensure_session_workspace(&data, "s1").await.unwrap();+ assert!(dir.is_dir());+ ensure_session_workspace(&data, "s1").await.unwrap();+ remove_session_workspace(&data, "s1").await.unwrap();+ assert!(!dir.exists());+ remove_session_workspace(&data, "s1").await.unwrap();+ let _ = std::fs::remove_dir_all(&data);+ }++ #[test]+ fn session_ids_are_sanitized_like_thread_ids() {+ for bad in ["../escape", "a/b", "..", ""] {+ assert!(+ session_workspace(Path::new("/data"), bad).is_err(),+ "expected {bad:?} to be rejected"+ );+ }+ }}