Skip to content

armgit / jan

Public Imported from GitHub
0

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

feat(cowork): mount the attached shared folder writable

Akarshan Biswas4d4fd983475c
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.ts
index fa77b7aa6..94d8cf93a 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
@@ -307,9 +307,11 @@ export async function sandboxStatus(): Promise<SandboxStatus> {
* `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.
+ * `readOnlyProject` attaches a folder the tools may read. 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. By default it is never
+ * written; `projectWritable` opts the same folder into writes and edits in
+ * place (Cowork's shared-folder mode).
*/
export async function executeTool(
dataFolder: string,
@@ -320,6 +322,7 @@ export async function executeTool(
enabledSkills?: string[],
allowNetwork?: boolean,
readOnlyProject?: string,
+ projectWritable?: boolean,
scope?: WorkspaceScope,
callId?: string
): Promise<ToolResult> {
@@ -332,6 +335,7 @@ export async function executeTool(
enabledSkills,
allowNetwork,
readOnlyProject,
+ projectWritable,
scope,
callId,
})
@@ -355,6 +359,7 @@ export async function executeToolStreaming(
enabledSkills?: string[]
allowNetwork?: boolean
readOnlyProject?: string
+ projectWritable?: boolean
scope?: WorkspaceScope
callId?: string
}
@@ -369,6 +374,7 @@ export async function executeToolStreaming(
enabledSkills: options?.enabledSkills,
allowNetwork: options?.allowNetwork,
readOnlyProject: options?.readOnlyProject,
+ projectWritable: options?.projectWritable,
scope: options?.scope,
callId: options?.callId,
})
@@ -390,6 +396,7 @@ export async function startMonitor(
options?: {
allowNetwork?: boolean
readOnlyProject?: string
+ projectWritable?: boolean
scope?: WorkspaceScope
}
): Promise<string> {
@@ -402,6 +409,7 @@ export async function startMonitor(
onUpdate: channel,
allowNetwork: options?.allowNetwork,
readOnlyProject: options?.readOnlyProject,
+ projectWritable: options?.projectWritable,
scope: options?.scope,
})
}
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.json
index 21cbfd664..9b55f74ce 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
@@ -294,6 +294,18 @@
"PermissionKind": {
"type": "string",
"oneOf": [
+ {
+ "description": "Enables the attachment_import command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-attachment-import",
+ "markdownDescription": "Enables the attachment_import command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the attachment_import command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-attachment-import",
+ "markdownDescription": "Denies the attachment_import command without any pre-configured scope."
+ },
{
"description": "Enables the execute_tool command without any pre-configured scope.",
"type": "string",
@@ -390,6 +402,30 @@
"const": "deny-memory-write",
"markdownDescription": "Denies the memory_write command without any pre-configured scope."
},
+ {
+ "description": "Enables the preview_register_root command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-preview-register-root",
+ "markdownDescription": "Enables the preview_register_root command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the preview_register_root command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-preview-register-root",
+ "markdownDescription": "Denies the preview_register_root command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the preview_unregister_root command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-preview-unregister-root",
+ "markdownDescription": "Enables the preview_unregister_root command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the preview_unregister_root command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-preview-unregister-root",
+ "markdownDescription": "Denies the preview_unregister_root command without any pre-configured scope."
+ },
{
"description": "Enables the sandbox_status command without any pre-configured scope.",
"type": "string",
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
index ce6059228..23010ed06 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
@@ -462,6 +462,7 @@ pub async fn start_monitor(
args: serde_json::Value,
allow_network: Option<bool>,
read_only_project: Option<String>,
+ project_writable: Option<bool>,
scope: Option<WorkspaceScope>,
on_update: tauri::ipc::Channel<crate::tools::monitor::MonitorUpdate>,
) -> Result<String, AgentToolsError> {
@@ -486,11 +487,17 @@ pub async fn start_monitor(
)?],
None => Vec::new(),
};
+ let write_roots = if project_writable.unwrap_or(false) {
+ read_roots.clone()
+ } else {
+ Vec::new()
+ };
let ctx = monitor::MonitorCtx {
project_root: root,
scratch_root: Some(scratch),
mask_root: Some(PathBuf::from(&data_folder)),
read_roots,
+ write_roots,
allow_network: allow_network.unwrap_or(false),
home_readonly: false,
sandbox: true,
@@ -578,6 +585,7 @@ pub async fn execute_tool(
enabled_skills: Option<Vec<String>>,
allow_network: Option<bool>,
read_only_project: Option<String>,
+ project_writable: Option<bool>,
scope: Option<WorkspaceScope>,
call_id: Option<String>,
) -> Result<ToolResult, AgentToolsError> {
@@ -590,6 +598,7 @@ pub async fn execute_tool(
enabled_skills,
allow_network,
read_only_project,
+ project_writable,
scope,
call_id,
None,
@@ -613,6 +622,7 @@ pub async fn execute_tool_streaming(
enabled_skills: Option<Vec<String>>,
allow_network: Option<bool>,
read_only_project: Option<String>,
+ project_writable: Option<bool>,
scope: Option<WorkspaceScope>,
call_id: Option<String>,
on_output: tauri::ipc::Channel<ToolOutputChunk>,
@@ -627,6 +637,7 @@ pub async fn execute_tool_streaming(
enabled_skills,
allow_network,
read_only_project,
+ project_writable,
scope,
call_id,
Some(sink),
@@ -644,6 +655,7 @@ async fn execute_tool_inner(
enabled_skills: Option<Vec<String>>,
allow_network: Option<bool>,
read_only_project: Option<String>,
+ project_writable: Option<bool>,
scope: Option<WorkspaceScope>,
call_id: Option<String>,
sink: Option<crate::tools::OutputSink>,
@@ -668,6 +680,13 @@ async fn execute_tool_inner(
)?],
None => Vec::new(),
};
+ // Writable attach: the same validated roots, so the two lists cannot name
+ // different places. Read containment still comes from `read_roots`.
+ let write_roots: Vec<PathBuf> = if project_writable.unwrap_or(false) {
+ read_roots.clone()
+ } else {
+ Vec::new()
+ };
let tool = lookup(&name)
.ok_or_else(|| AgentToolsError::from(format!("unknown built-in tool '{name}'")))?;
@@ -678,6 +697,7 @@ async fn execute_tool_inner(
project_root: &root,
scratch: Some(&scratch),
read_roots: &read_roots,
+ write_roots: &write_roots,
hide_jan: true,
},
&ToolPermissions::default(),
@@ -708,6 +728,12 @@ async fn execute_tool_inner(
// refusing here while `bash` may already write the same files would be a
// control a sibling tool bypasses.
//
+ // With `project_writable` the attached folder is in range too. That is
+ // the surface's own opt-in (Cowork's shared folder): the user attached
+ // the folder to be worked on, its UI shows every change as a diff, and
+ // `bash` under the jail can already write there -- so a prompt here
+ // would again be a control a sibling tool bypasses.
+ //
// A write that *escapes* the sandbox (absolute or `..`) is different:
// it can reach host files (rc files, ssh keys, LaunchAgents, the store)
// that the ephemeral-root reasoning does not cover. It is gated as
@@ -718,12 +744,19 @@ async fn execute_tool_inner(
// model retries the same write until the step budget runs out.
Decision::Prompt(PromptKind::WriteEscape) => {
return Err(match read_roots.first() {
- Some(attached) => format!(
+ // With a writable attach the gate only lands here for a path
+ // outside both roots, so the read-only advice would be wrong.
+ Some(attached) if write_roots.is_empty() => 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()
),
+ Some(attached) => format!(
+ "tool '{name}' cannot write outside the agent workspace or the attached \
+ folder {}.",
+ attached.display()
+ ),
None => format!(
"tool '{name}' tried to write outside the agent workspace and was refused"
),
@@ -744,7 +777,8 @@ async fn execute_tool_inner(
.with_confined_writes(true)
.with_mask_root(Path::new(&data_folder))
.with_scratch_root(&scratch)
- .with_read_roots(&read_roots);
+ .with_read_roots(&read_roots)
+ .with_write_roots(&write_roots);
if let Some(id) = call_id.as_deref() {
ctx = ctx.with_call_id(id);
}
@@ -845,6 +879,7 @@ mod tests {
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 T_ATTACH_WRITABLE: &str = "thread-attach-writable";
const T2: &str = "thread-two";
#[test]
@@ -897,6 +932,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.expect("a write inside the sandbox is allowed");
@@ -930,6 +966,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -965,6 +1002,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.expect_err("an escaping read must be refused");
@@ -998,6 +1036,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.expect_err("an escaping write must be refused");
@@ -1034,6 +1073,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.expect("a scratch write is the session scratch and must succeed");
@@ -1056,6 +1096,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.expect("an in-workspace write must succeed");
@@ -1093,6 +1134,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await;
@@ -1135,6 +1177,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -1167,6 +1210,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -1193,6 +1237,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -1230,6 +1275,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.expect_err("a relative climb-out to a sibling thread must be refused");
@@ -1259,6 +1305,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -1290,6 +1337,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -1311,6 +1359,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -1342,6 +1391,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.expect_err("memory must be unreachable from the sandbox");
@@ -1397,6 +1447,7 @@ mod tests {
None,
None,
None,
+ None,
None
)
.await
@@ -1424,6 +1475,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.expect_err("agent config must be hard-denied");
@@ -1450,6 +1502,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.expect_err("unknown tool");
@@ -1531,6 +1584,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -1549,6 +1603,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -1578,6 +1633,7 @@ mod tests {
attached.clone(),
None,
None,
+ None,
)
.await
.unwrap();
@@ -1595,6 +1651,7 @@ mod tests {
attached,
None,
None,
+ None,
)
.await;
let err = write.expect_err("a write into the attached folder must be refused");
@@ -1609,6 +1666,86 @@ mod tests {
let _ = std::fs::remove_dir_all(&repo);
}
+ /// The Cowork opt-in: with `project_writable` the same attached folder
+ /// takes writes and edits in place, and only paths outside both roots stay
+ /// refused.
+ #[tokio::test]
+ async fn a_writable_attachment_takes_writes_in_place() {
+ let data = unique_data_folder();
+ let df = data.to_string_lossy().to_string();
+ let repo = repo_outside_tmp("rw_writable");
+ std::fs::write(repo.join("main.rs"), b"fn main() {}").unwrap();
+ let attached = Some(repo.to_string_lossy().to_string());
+
+ let write = execute_tool(
+ df.clone(),
+ T_ATTACH_WRITABLE.into(),
+ None,
+ "write".into(),
+ json!({"path": repo.join("notes.md").to_string_lossy(), "content": "hi"}),
+ None,
+ None,
+ attached.clone(),
+ Some(true),
+ None,
+ None,
+ )
+ .await
+ .expect("a write into a writable attachment is allowed");
+ assert!(!write.is_error, "{}", write.content);
+ assert_eq!(
+ std::fs::read_to_string(repo.join("notes.md")).ok(),
+ Some("hi".to_string())
+ );
+
+ let edit = execute_tool(
+ df.clone(),
+ T_ATTACH_WRITABLE.into(),
+ None,
+ "edit".into(),
+ json!({
+ "path": repo.join("main.rs").to_string_lossy(),
+ "edits": [{"old_string": "fn main() {}", "new_string": "fn main() { run() }"}]
+ }),
+ None,
+ None,
+ attached.clone(),
+ Some(true),
+ None,
+ None,
+ )
+ .await
+ .expect("an edit inside a writable attachment is allowed");
+ assert!(!edit.is_error, "{}", edit.content);
+
+ // Outside both roots is still refused, and the message no longer gives
+ // the read-only copy-it advice that would now be wrong.
+ let outside = repo_outside_tmp("rw_writable_outside");
+ let err = execute_tool(
+ df.clone(),
+ T_ATTACH_WRITABLE.into(),
+ None,
+ "write".into(),
+ json!({"path": outside.join("evil.txt").to_string_lossy(), "content": "x"}),
+ None,
+ None,
+ attached,
+ Some(true),
+ None,
+ None,
+ )
+ .await
+ .expect_err("a write outside both roots is refused");
+ let msg = format!("{err:?}");
+ assert!(msg.contains("or the attached"), "{msg}");
+ assert!(!msg.contains("read-only"), "{msg}");
+ assert!(!outside.join("evil.txt").exists());
+
+ let _ = std::fs::remove_dir_all(&data);
+ let _ = std::fs::remove_dir_all(&repo);
+ let _ = std::fs::remove_dir_all(&outside);
+ }
+
/// Without an attached folder nothing outside the sandbox is readable, so
/// the mount is genuinely opt-in.
#[tokio::test]
@@ -1629,6 +1766,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await;
assert!(out.is_err() || out.unwrap().is_error);
@@ -1660,6 +1798,7 @@ mod tests {
Some(inside.to_string_lossy().to_string()),
None,
None,
+ None,
)
.await;
let err = out.expect_err("a root inside the workspace must be refused");
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs
index 701079ce8..70c686d9c 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
@@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};
use crate::permissions::ToolPermissions;
use crate::tools::cmdscan::{normalize, scan_command, CommandScan};
use crate::tools::sandbox::{
- command_touches_hidden_jan_path, escapes_project, escapes_read_roots, is_hidden_jan_path,
+ command_touches_hidden_jan_path, escapes_read_roots, escapes_write_roots, is_hidden_jan_path,
};
use crate::tools::{BuiltinTool, Capability};
@@ -133,6 +133,9 @@ pub struct GateContext<'a> {
pub scratch: Option<&'a Path>,
/// Folders the user attached read-only: reads may reach them, writes may not.
pub read_roots: &'a [PathBuf],
+ /// The subset of `read_roots` the caller marked writable: writes inside one
+ /// are ordinary in-project writes rather than escapes.
+ pub write_roots: &'a [PathBuf],
/// Hide the agent's own `.jan` state (skills/memory/config) from general tools.
pub hide_jan: bool,
}
@@ -186,9 +189,9 @@ 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.
+ // Read roots widen only this branch; the Write branch below widens
+ // only by `write_roots`, so an attached folder is writable exactly
+ // when the caller marked it so.
let escapes = tool.path_args.iter().any(|key| {
args.get(key)
.and_then(|v| v.as_str())
@@ -213,11 +216,17 @@ pub fn resolve_decision(
// escapes the project -- absolute or `..` -- can reach host files no
// sandbox confines, so mirror the Read branch and gate it separately. It
// is refused outright on the desktop, where no prompt round-trip exists.
+ // `write_roots` (an attached folder the caller marked writable) widen
+ // this branch exactly the way read roots widen the Read branch; a
+ // caller that passes none keeps the unchanged `escapes_project`.
Capability::Write => {
let escapes = tool.path_args.iter().any(|key| {
args.get(key)
.and_then(|v| v.as_str())
- .map(|p| escapes_project(ctx.project_root, ctx.scratch, p).unwrap_or(true))
+ .map(|p| {
+ escapes_write_roots(ctx.project_root, ctx.scratch, ctx.write_roots, p)
+ .unwrap_or(true)
+ })
.unwrap_or(false)
});
if escapes {
@@ -296,6 +305,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -317,6 +327,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -339,6 +350,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -362,6 +374,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -391,6 +404,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -410,6 +424,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -425,6 +440,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -452,6 +468,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: false,
},
&perms,
@@ -471,6 +488,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: false,
},
&perms,
@@ -492,6 +510,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -513,6 +532,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -535,6 +555,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -557,6 +578,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -590,6 +612,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -605,6 +628,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -634,6 +658,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -663,6 +688,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -688,6 +714,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -703,6 +730,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -733,6 +761,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -761,6 +790,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -778,6 +808,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&denied,
@@ -799,6 +830,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -820,6 +852,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -842,6 +875,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -864,6 +898,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -885,6 +920,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -908,6 +944,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -931,6 +968,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -952,6 +990,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -979,6 +1018,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &roots,
+ write_roots: &[],
hide_jan: true,
},
&perms,
@@ -993,6 +1033,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &roots,
+ write_roots: &[],
hide_jan: true,
},
&ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]),
@@ -1004,6 +1045,53 @@ mod tests {
let _ = std::fs::remove_dir_all(&repo);
}
+ /// The Cowork opt-in at the gate layer: an attached root also passed as a
+ /// write root takes the ordinary in-project Write prompt, not WriteEscape,
+ /// while a path outside both roots keeps the escape classification.
+ #[test]
+ fn a_write_root_downgrades_the_escape_to_an_ordinary_write() {
+ let root = unique_root();
+ let repo = unique_root();
+ let elsewhere = unique_root();
+ let roots = vec![repo.clone()];
+ let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]);
+ let grants = SessionGrants::default();
+
+ let inside = resolve_decision(
+ lookup("write").unwrap(),
+ &json!({"path": repo.join("new.txt").to_string_lossy(), "content": "y"}),
+ &GateContext {
+ project_root: &root,
+ scratch: None,
+ read_roots: &roots,
+ write_roots: &roots,
+ hide_jan: true,
+ },
+ &perms,
+ &grants,
+ );
+ assert_eq!(inside, Decision::Prompt(PromptKind::Write));
+
+ let outside = resolve_decision(
+ lookup("write").unwrap(),
+ &json!({"path": elsewhere.join("x.txt").to_string_lossy(), "content": "y"}),
+ &GateContext {
+ project_root: &root,
+ scratch: None,
+ read_roots: &roots,
+ write_roots: &roots,
+ hide_jan: true,
+ },
+ &perms,
+ &grants,
+ );
+ assert_eq!(outside, Decision::Prompt(PromptKind::WriteEscape));
+
+ for d in [&root, &repo, &elsewhere] {
+ let _ = std::fs::remove_dir_all(d);
+ }
+ }
+
#[test]
fn an_escaping_read_still_prompts_when_no_root_covers_it() {
let root = unique_root();
@@ -1017,6 +1105,7 @@ mod tests {
project_root: &root,
scratch: None,
read_roots: &roots,
+ write_roots: &[],
hide_jan: true,
},
&ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]),
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
index 8c37d6205..5b532bba1 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
@@ -16,8 +16,8 @@ use crate::skills;
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_any_root, symlink_escapes_root,
+ escapes_write_roots, in_scratch, is_hidden_jan_path, lexical_normalize, resolve_path,
+ scratch_display_path, symlink_escapes_any_root,
};
use crate::tools::{BuiltinTool, ImageContentPart, ToolContext};
@@ -165,8 +165,26 @@ async fn execute_text(
// 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,
+ "write" => {
+ write(
+ args,
+ project_root,
+ scratch,
+ ctx.confine_writes,
+ ctx.write_roots,
+ )
+ .await
+ }
+ "edit" => {
+ edit(
+ args,
+ project_root,
+ scratch,
+ ctx.confine_writes,
+ ctx.write_roots,
+ )
+ .await
+ }
"bash" => bash(args, ctx).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,
@@ -632,6 +650,7 @@ async fn write(
root: &Path,
scratch: Option<&Path>,
confine: bool,
+ write_roots: &[PathBuf],
) -> String {
let Some(path) = arg_str(args, "path") else {
return "ERROR: missing required argument 'path'".to_string();
@@ -642,8 +661,9 @@ async fn write(
// Defense in depth: when the caller confines writes, re-canonicalize on the
// canonical root (not the raw argument) so `..` and absolute paths are
// caught even if the gate's decision was made against a stale view.
+ // `write_roots` widen the confinement exactly as they widened the gate.
let target = resolve_path(root, scratch, path);
- if confine && escapes_project(root, scratch, path).unwrap_or(true) {
+ if confine && escapes_write_roots(root, scratch, write_roots, path).unwrap_or(true) {
return format!("ERROR: refused to write outside the agent workspace: {path}");
}
// Report the resolved location, not the raw argument: an absolute or `../`
@@ -653,7 +673,7 @@ async fn write(
// concurrent sandboxed process can swap a path component between the gate
// decision and this call, and creating the parents first would already have
// made directories through the swapped link. Fail closed.
- if symlink_escapes_root(root, scratch, &target) {
+ if symlink_escapes_any_root(root, scratch, write_roots, &target) {
return format!("ERROR: refused to write through a symlink out of the workspace: {path}");
}
if let Some(parent) = target.parent() {
@@ -682,6 +702,7 @@ async fn edit(
root: &Path,
scratch: Option<&Path>,
confine: bool,
+ write_roots: &[PathBuf],
) -> String {
let Some(path) = arg_str(args, "path") else {
return "ERROR: missing required argument 'path'".to_string();
@@ -693,13 +714,13 @@ async fn edit(
return "ERROR: edits must contain at least one replacement".to_string();
}
let target = resolve_path(root, scratch, path);
- if confine && escapes_project(root, scratch, path).unwrap_or(true) {
+ if confine && escapes_write_roots(root, scratch, write_roots, path).unwrap_or(true) {
return format!("ERROR: refused to edit outside the agent workspace: {path}");
}
let shown = display_path(root, scratch, &target);
// Re-validate before the final read+write pair so a swapped symlink cannot
// redirect either the read or the later write.
- if symlink_escapes_root(root, scratch, &target) {
+ if symlink_escapes_any_root(root, scratch, write_roots, &target) {
return format!("ERROR: refused to edit through a symlink out of the workspace: {path}");
}
let mut content = match tokio::fs::read_to_string(&target).await {
@@ -766,6 +787,9 @@ pub(crate) fn confined_shell(
if !ctx.read_roots.is_empty() {
policy = policy.with_read_roots(ctx.read_roots.to_vec());
}
+ if !ctx.write_roots.is_empty() {
+ policy = policy.with_write_roots(ctx.write_roots.to_vec());
+ }
let shell = if ctx.sandbox {
// No confinement available means no shell: running unsandboxed would give
// the command the whole machine, which is never what the caller asked for.
@@ -2557,6 +2581,7 @@ mod tests {
project_root: &root,
scratch: Some(&scratch),
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&crate::permissions::ToolPermissions::default(),
@@ -2588,6 +2613,7 @@ mod tests {
project_root: &root,
scratch: Some(&scratch),
read_roots: &[],
+ write_roots: &[],
hide_jan: true,
},
&crate::permissions::ToolPermissions::default(),
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs
index 7d82827f8..2ee6f1def 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
@@ -99,6 +99,10 @@ pub struct Policy {
/// 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>,
+ /// The subset of attached folders the surface marked writable. Bound (or
+ /// allowed) read-write in the same position as `read_roots`; an entry
+ /// present in both lists is bound once, writable.
+ pub write_roots: Vec<PathBuf>,
}
impl Policy {
@@ -111,6 +115,7 @@ impl Policy {
home_readonly: false,
scratch_root: None,
read_roots: Vec::new(),
+ write_roots: Vec::new(),
}
}
@@ -121,6 +126,12 @@ impl Policy {
self
}
+ /// Mark attached roots writable. See [`Policy::write_roots`].
+ pub fn with_write_roots(mut self, write_roots: Vec<PathBuf>) -> Self {
+ self.write_roots = write_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
@@ -396,9 +407,21 @@ pub fn bwrap_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {
// 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 {
+ // A root the surface also marked writable is bound once, below, rw: a
+ // later rw bind would shadow this one anyway, so skipping is the same
+ // mount table with one entry instead of two.
+ if policy.write_roots.contains(root) {
+ continue;
+ }
let root = root.to_string_lossy();
push(&mut args, &["--ro-bind", &root, &root]);
}
+ // Same position and the same reasoning as the read roots; `--bind` is the
+ // whole difference, which is what makes the attached folder writable.
+ for root in &policy.write_roots {
+ let root = root.to_string_lossy();
+ push(&mut args, &["--bind", &root, &root]);
+ }
push(&mut args, &["--bind", &ws, &ws]);
// After the workspace bind, so it is not shadowed by it: an empty tmpfs where
@@ -507,6 +530,14 @@ pub fn seatbelt_policy(policy: &Policy) -> String {
"(allow file-read* (subpath (param \"READ_ROOT_{i}\")))\n"
));
}
+ // Writable attached roots: read *and* write allowed, same position so the
+ // HOME/MASK denials above are overridden for them too.
+ for i in 0..policy.write_roots.len() {
+ p.push_str(&format!(
+ "(allow file-read* (subpath (param \"WRITE_ROOT_{i}\")))\n\
+ (allow file-write* (subpath (param \"WRITE_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() {
@@ -548,6 +579,9 @@ pub fn seatbelt_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {
for (i, root) in policy.read_roots.iter().enumerate() {
args.push(format!("-DREAD_ROOT_{i}={}", root.to_string_lossy()));
}
+ for (i, root) in policy.write_roots.iter().enumerate() {
+ args.push(format!("-DWRITE_ROOT_{i}={}", root.to_string_lossy()));
+ }
if let Some(hide) = &policy.hide_root {
args.push(format!("-DHIDE_ROOT={}", hide.to_string_lossy()));
}
@@ -624,19 +658,37 @@ pub fn denial_hint(policy: &Policy) -> String {
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 \
+ " The attached folder is reachable 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
+ let list = |roots: &[PathBuf]| {
+ roots
.iter()
.map(|r| r.display().to_string())
.collect::<Vec<_>>()
.join(", ")
- )
+ };
+ let readonly: Vec<PathBuf> = policy
+ .read_roots
+ .iter()
+ .filter(|r| !policy.write_roots.contains(r))
+ .cloned()
+ .collect();
+ let mut s = String::new();
+ if !policy.write_roots.is_empty() {
+ s.push_str(&format!(
+ " The attached folder ({}) is readable and writable.",
+ list(&policy.write_roots)
+ ));
+ }
+ if !readonly.is_empty() {
+ s.push_str(&format!(
+ " The attached folder ({}) is readable but not writable.",
+ list(&readonly)
+ ));
+ }
+ s
};
format!(
"\n[sandbox: writes are limited to the workspace ({}){scratch}{home}.{net}{attached}]",
@@ -771,6 +823,55 @@ mod tests {
assert!(!joined(&bwrap_args(&policy(), &cfg())).contains(repo));
}
+ /// The writable-attach opt-in: the root is bound rw, exactly once, in the
+ /// read-root position (after the home mask, before the workspace bind).
+ #[test]
+ fn bwrap_binds_a_write_root_rw_and_never_twice() {
+ 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)])
+ .with_write_roots(vec![PathBuf::from(repo)]),
+ &cfg(),
+ ));
+ assert!(text.contains(&format!("--bind {repo} {repo}")), "{text}");
+ assert!(
+ !text.contains(&format!("--ro-bind {repo} {repo}")),
+ "one entry in the mount table, writable: {text}"
+ );
+ let home = home_dir().expect("a home dir");
+ let home_tmpfs = text
+ .find(&format!("--tmpfs {}", home.to_string_lossy()))
+ .expect("home tmpfs");
+ let rw = text
+ .find(&format!("--bind {repo} {repo}"))
+ .expect("write root bind");
+ let ws_bind = text.find(&format!("--bind {ws} {ws}")).expect("ws bind");
+ assert!(home_tmpfs < rw && rw < ws_bind, "{text}");
+ }
+
+ #[test]
+ fn seatbelt_allows_a_write_root_to_write() {
+ let repo = "/Users/u/repo";
+ let p = seatbelt_policy(
+ &policy()
+ .with_read_roots(vec![PathBuf::from(repo)])
+ .with_write_roots(vec![PathBuf::from(repo)]),
+ );
+ assert!(
+ p.contains("(allow file-write* (subpath (param \"WRITE_ROOT_0\")))"),
+ "{p}"
+ );
+ let args = seatbelt_args(
+ &policy()
+ .with_read_roots(vec![PathBuf::from(repo)])
+ .with_write_roots(vec![PathBuf::from(repo)]),
+ &cfg(),
+ );
+ assert!(args.iter().any(|a| a == &format!("-DWRITE_ROOT_0={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]
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
index ecee1569f..d10cc9dcc 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
@@ -106,6 +106,12 @@ pub struct ToolContext<'a> {
/// attach time; re-canonicalizing per call would be both slower and a
/// check/use race of its own.
pub read_roots: &'a [PathBuf],
+ /// The subset of attached folders the caller marked writable: `write`/`edit`
+ /// and the sandboxed shell treat them like the workspace. Every entry must
+ /// also be in `read_roots` (a folder the agent can change but not read back
+ /// is useless), and the default is empty -- attaching stays read-only unless
+ /// a surface opts in.
+ pub write_roots: &'a [PathBuf],
/// Correlation id echoed on every streamed output chunk.
///
/// Needed because `bash` with `timeout: 0` backgrounds and keeps streaming
@@ -132,6 +138,7 @@ impl std::fmt::Debug for ToolContext<'_> {
.field("sandbox", &self.sandbox)
.field("on_output", &self.on_output.is_some())
.field("read_roots", &self.read_roots)
+ .field("write_roots", &self.write_roots)
.field("call_id", &self.call_id)
.finish()
}
@@ -155,6 +162,7 @@ impl<'a> ToolContext<'a> {
sandbox: true,
on_output: None,
read_roots: &[],
+ write_roots: &[],
call_id: None,
}
}
@@ -166,6 +174,13 @@ impl<'a> ToolContext<'a> {
self
}
+ /// Mark attached folders writable. See [`Self::write_roots`]; callers pass
+ /// the same canonical paths they put in `read_roots`.
+ pub fn with_write_roots(mut self, write_roots: &'a [PathBuf]) -> Self {
+ self.write_roots = write_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);
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs
index b0784ed53..22dda2ef7 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs
@@ -65,6 +65,7 @@ pub struct MonitorCtx {
pub scratch_root: Option<PathBuf>,
pub mask_root: Option<PathBuf>,
pub read_roots: Vec<PathBuf>,
+ pub write_roots: Vec<PathBuf>,
pub allow_network: bool,
pub home_readonly: bool,
pub sandbox: bool,
@@ -77,6 +78,7 @@ impl MonitorCtx {
scratch_root: ctx.scratch_root.map(Path::to_path_buf),
mask_root: ctx.mask_root.map(Path::to_path_buf),
read_roots: ctx.read_roots.to_vec(),
+ write_roots: ctx.write_roots.to_vec(),
allow_network: ctx.allow_network,
home_readonly: ctx.home_readonly,
sandbox: ctx.sandbox,
@@ -91,7 +93,8 @@ impl MonitorCtx {
.with_network(self.allow_network)
.with_home_readonly(self.home_readonly)
.with_sandbox(self.sandbox)
- .with_read_roots(&self.read_roots);
+ .with_read_roots(&self.read_roots)
+ .with_write_roots(&self.write_roots);
if let Some(mask) = &self.mask_root {
ctx = ctx.with_mask_root(mask);
}
@@ -258,9 +261,7 @@ impl MonitorSet {
let waiter = self.wake.notified();
tokio::pin!(waiter);
waiter.as_mut().enable();
- if !self.notices.lock().unwrap().is_empty()
- || self.active.load(Ordering::SeqCst) == 0
- {
+ if !self.notices.lock().unwrap().is_empty() || self.active.load(Ordering::SeqCst) == 0 {
return;
}
waiter.await;
@@ -287,8 +288,7 @@ impl MonitorSet {
));
}
let scratch = ctx.scratch_root.as_deref();
- match sandbox::escapes_read_roots(&ctx.project_root, scratch, &ctx.read_roots, &spec.file)
- {
+ match sandbox::escapes_read_roots(&ctx.project_root, scratch, &ctx.read_roots, &spec.file) {
Ok(false) => {}
Ok(true) => {
return Err(format!(
@@ -517,16 +517,11 @@ fn match_update(
/// which read as "not matched yet" and are retried on the next change.
async fn eval_condition(ctx: &MonitorCtx, script: &str) -> Option<String> {
let tool_ctx = ctx.as_tool_context();
- let (shell, sandbox_tmp, _policy) =
- crate::tools::handlers::confined_shell(&tool_ctx).ok()?;
- let mut child = crate::tools::proc::spawn(
- &shell,
- script,
- &ctx.project_root,
- sandbox_tmp.as_deref(),
- )
- .await
- .ok()?;
+ let (shell, sandbox_tmp, _policy) = crate::tools::handlers::confined_shell(&tool_ctx).ok()?;
+ let mut child =
+ crate::tools::proc::spawn(&shell, script, &ctx.project_root, sandbox_tmp.as_deref())
+ .await
+ .ok()?;
let pid = child.id();
let result = tokio::time::timeout(EVAL_TIMEOUT, async {
let stdout = child.stdout.take();
@@ -635,6 +630,7 @@ mod tests {
scratch_root: None,
mask_root: None,
read_roots: Vec::new(),
+ write_roots: Vec::new(),
allow_network: false,
home_readonly: false,
// Bare shell: these tests exercise the monitor loop, not the jail.
@@ -697,7 +693,10 @@ mod tests {
);
let mut low = base.clone();
low["timeout"] = serde_json::json!(1);
- assert_eq!(parse_start_args(&low).unwrap().timeout_secs, MIN_TIMEOUT_SECS);
+ assert_eq!(
+ parse_start_args(&low).unwrap().timeout_secs,
+ MIN_TIMEOUT_SECS
+ );
let mut high = base;
high["timeout"] = serde_json::json!(1_000_000);
assert_eq!(
@@ -753,7 +752,11 @@ mod tests {
assert!(first.text.contains("'one'"), "{}", first.text);
assert!(!first.done);
assert!(set.has_pending_work(), "condition 'two' is still owed");
- assert!(set.list().contains("met: one; unmet: two"), "{}", set.list());
+ assert!(
+ set.list().contains("met: one; unmet: two"),
+ "{}",
+ set.list()
+ );
let mut content = std::fs::read_to_string(&log).unwrap();
content.push_str("phase two done\n");
@@ -805,10 +808,7 @@ mod tests {
let dir = unique_root();
let set = Arc::new(MonitorSet::new());
let err = set
- .start(
- spec("/etc/passwd", &[("x", "true")], 30),
- ctx_for(&dir),
- )
+ .start(spec("/etc/passwd", &[("x", "true")], 30), ctx_for(&dir))
.unwrap_err();
assert!(err.contains("outside the project"), "{err}");
assert!(!set.has_pending_work());
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs
index 836c79939..f345902d0 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
@@ -94,6 +94,43 @@ pub fn escapes_read_roots(
Ok(true)
}
+/// True iff `raw` escapes every root a *write* may legitimately reach: the
+/// project, the scratch, or any attached root the caller marked writable.
+///
+/// The mirror image of [`escapes_read_roots`], layered on [`escapes_project`]
+/// for the same reason: a writable root can only ever widen what writes reach,
+/// and a caller that passes none keeps today's exact check. A root that cannot
+/// be canonicalized grants nothing.
+pub fn escapes_write_roots(
+ project_root: &Path,
+ scratch: Option<&Path>,
+ write_roots: &[PathBuf],
+ raw: &str,
+) -> Result<bool, String> {
+ if !escapes_project(project_root, scratch, raw)? {
+ return Ok(false);
+ }
+ if write_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
+ // -- the same rule reads follow, so one path means one place to both.
+ project_root.join(raw)
+ };
+ let resolved = canonicalize_lenient(&abs)?;
+ for root in write_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
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 5da2689bd..67521c726 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -1171,8 +1171,9 @@ impl ToolInvoker for CompositeToolInvoker {
project_root: &self.project_root,
scratch: Some(self.scratch_root.as_path()),
// The CLI works *in* the project, so it has no separate
- // read-only root to attach.
+ // read-only or writable root to attach.
read_roots: &[],
+ write_roots: &[],
hide_jan: self.sandbox,
},
&self.permissions,
@@ -4173,7 +4174,9 @@ mod tests {
let requests = model.requests.lock().unwrap();
let sent = requests[1]["messages"].as_array().unwrap();
let last = sent.last().unwrap();
- assert!(crate::core::agent::reminder::is_reminder_only(&last["content"]));
+ assert!(crate::core::agent::reminder::is_reminder_only(
+ &last["content"]
+ ));
assert!(last["content"].as_str().unwrap().contains("BUILD OK"));
let mut saw_notice = false;
@@ -5980,7 +5983,11 @@ mod tests {
}
assert_eq!(notices.len(), 1, "one match, one ping");
assert!(
- notices[0].headline.as_deref().unwrap_or("").contains("'ready' matched"),
+ notices[0]
+ .headline
+ .as_deref()
+ .unwrap_or("")
+ .contains("'ready' matched"),
"{:?}",
notices[0].headline
);
diff --git a/web-app/src/containers/CoworkWorkspacePill.tsx b/web-app/src/containers/CoworkWorkspacePill.tsx
index ef7d088b7..d2e897a4b 100644
--- a/web-app/src/containers/CoworkWorkspacePill.tsx
+++ b/web-app/src/containers/CoworkWorkspacePill.tsx
@@ -1,4 +1,4 @@
-import { Folder, FolderPlus, GitBranch, Lock } from 'lucide-react'
+import { Folder, FolderPlus, GitBranch, PencilLine } from 'lucide-react'
import { Button } from '@/components/ui/button'
import {
Popover,
@@ -20,12 +20,12 @@ type Props = {
}
/**
- * Attach, inspect and detach the read-only project folder.
+ * Attach, inspect and detach the shared project folder.
*
- * The sandbox it writes into is deliberately unnamed: it is an implementation
- * detail the user never picks or opens, and surfacing it invited the reading
- * that the folder and the sandbox are two halves of one choice. What has to
- * stay visible is the read-only contract on the folder.
+ * The sandbox is deliberately unnamed: it is an implementation detail the user
+ * never picks or opens, and surfacing it invited the reading that the folder
+ * and the sandbox are two halves of one choice. What has to stay visible is the
+ * access contract on the folder — the agent reads AND edits it in place.
*
* The trigger is icon-only until a folder is attached, matching the composer
* row's other controls: with nothing attached there is no name to print, and a
@@ -60,7 +60,7 @@ export function CoworkWorkspacePill({
<span className="max-w-[120px] truncate text-foreground">
{folderName}
</span>
- <Lock className="size-3 shrink-0 text-muted-foreground/70" />
+ <PencilLine className="size-3 shrink-0 text-muted-foreground/70" />
</>
) : (
<FolderPlus className="size-[18px] shrink-0" />
@@ -78,8 +78,8 @@ export function CoworkWorkspacePill({
<Folder size={14} className="shrink-0 text-muted-foreground" />
<span className="truncate text-sm font-medium">{folderName}</span>
<span className="ml-auto inline-flex shrink-0 items-center gap-1 rounded-full bg-muted px-1.5 py-0.5 text-xs font-mono text-muted-foreground">
- <Lock size={10} />
- {t('common:workspace.readOnly')}
+ <PencilLine size={10} />
+ {t('common:workspace.writable')}
</span>
</div>
<p
diff --git a/web-app/src/containers/__tests__/CoworkWorkspacePill.test.tsx b/web-app/src/containers/__tests__/CoworkWorkspacePill.test.tsx
index 85c84b127..9459cbba5 100644
--- a/web-app/src/containers/__tests__/CoworkWorkspacePill.test.tsx
+++ b/web-app/src/containers/__tests__/CoworkWorkspacePill.test.tsx
@@ -37,10 +37,11 @@ describe('CoworkWorkspacePill', () => {
).toBeGreaterThan(0)
})
- // The honesty requirement: whenever a folder is attached, the popover must
- // name the direction and mark the folder read-only. A regression here would
- // have the UI implying the agent edits the user's project.
- it('names the read direction and marks the folder read-only', async () => {
+ // The honesty requirement, inverted from the read-only days: the folder is
+ // mounted writable now, so the popover must say the agent edits it in place.
+ // A regression here would have the UI promising an untouched project while
+ // the agent changes real files.
+ it('names the folder and marks it read & write', async () => {
render(
<CoworkWorkspacePill
folder="/home/u/Projects/jan-app"
@@ -53,8 +54,9 @@ describe('CoworkWorkspacePill', () => {
expect(screen.getByText('common:workspace.readsFrom')).toBeInTheDocument()
expect(
- screen.getAllByText('common:workspace.readOnly').length
+ screen.getAllByText('common:workspace.writable').length
).toBeGreaterThan(0)
+ expect(screen.queryByText('common:workspace.readOnly')).toBeNull()
expect(screen.getByText('dev')).toBeInTheDocument()
expect(screen.getByText('common:workspace.footnote')).toBeInTheDocument()
})
diff --git a/web-app/src/lib/__tests__/agentTools.test.ts b/web-app/src/lib/__tests__/agentTools.test.ts
index 7b998934b..515a73017 100644
--- a/web-app/src/lib/__tests__/agentTools.test.ts
+++ b/web-app/src/lib/__tests__/agentTools.test.ts
@@ -154,6 +154,7 @@ describe('agentTools', () => {
undefined,
false,
undefined,
+ false,
'thread'
)
})
@@ -179,6 +180,7 @@ describe('agentTools', () => {
undefined,
true,
undefined,
+ false,
'thread'
)
})
@@ -212,6 +214,7 @@ describe('agentTools', () => {
undefined,
false,
undefined,
+ false,
'thread'
)
})
@@ -235,6 +238,7 @@ describe('agentTools', () => {
undefined,
false,
'/home/u/repo',
+ false,
'thread'
)
})
@@ -291,6 +295,7 @@ describe('agentTools', () => {
undefined,
false,
undefined,
+ false,
'thread'
)
})
diff --git a/web-app/src/lib/__tests__/coworkDispatch.test.ts b/web-app/src/lib/__tests__/coworkDispatch.test.ts
index b94a117c2..c76797f38 100644
--- a/web-app/src/lib/__tests__/coworkDispatch.test.ts
+++ b/web-app/src/lib/__tests__/coworkDispatch.test.ts
@@ -52,6 +52,7 @@ describe('dispatchCoworkTool', () => {
's1',
null,
'session',
+ true,
true
)
})
@@ -66,6 +67,7 @@ describe('dispatchCoworkTool', () => {
's1',
null,
'session',
+ true,
true
)
coworkConfig.networkEnabled = false
@@ -77,7 +79,8 @@ describe('dispatchCoworkTool', () => {
's1',
null,
'session',
- false
+ false,
+ true
)
} finally {
coworkConfig.networkEnabled = true
@@ -116,6 +119,7 @@ describe('dispatchCoworkTool', () => {
's1',
'/repo',
'session',
+ true,
true
)
})
diff --git a/web-app/src/lib/__tests__/coworkPrompt.test.ts b/web-app/src/lib/__tests__/coworkPrompt.test.ts
index 269cf3870..5cee9ffa6 100644
--- a/web-app/src/lib/__tests__/coworkPrompt.test.ts
+++ b/web-app/src/lib/__tests__/coworkPrompt.test.ts
@@ -23,14 +23,17 @@ describe('buildCoworkSystemPrompt', () => {
expect(p).toContain('No project folder is attached')
})
- // Without this the model retries the same refused write until the step
- // budget runs out — the single most expensive thing it can get wrong here.
- it('spells out that an attached folder is read-only and how to work around it', () => {
+ // The shared folder is writable on this surface. The prompt has to say so —
+ // a model that assumes read-only copies files into the sandbox and hands the
+ // user stale duplicates — and to say it is real user data, since the
+ // sandbox's anything-goes norms no longer apply.
+ it('spells out that an attached folder is writable, in place, and real data', () => {
const p = buildCoworkSystemPrompt(opts({ readOnlyFolder: '/home/u/repo' }))
expect(p).toContain('/home/u/repo')
- expect(p).toContain('READ-ONLY')
- expect(p).toMatch(/copy it into your workspace/i)
- expect(p).toMatch(/Do not\s+retry a refused write/i)
+ expect(p).toMatch(/writable/i)
+ expect(p).toMatch(/IN PLACE/)
+ expect(p).toMatch(/real user\s+data/i)
+ expect(p).not.toContain('READ-ONLY')
})
it('explains a missing shell rather than staying silent about it', () => {
@@ -142,7 +145,8 @@ describe('buildSubagentSystemPrompt', () => {
// for the CLI (cwd is the project) but leaves a desktop child unable to
// guess its sandbox path.
expect(out).toContain('/ws/s1')
- expect(out).toContain('READ-ONLY')
+ expect(out).toContain('/home/me/repo')
+ expect(out).toMatch(/writable/i)
})
it('states the three things a child cannot do', () => {
diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.ts
index f8bc9f9a5..bc6990256 100644
--- a/web-app/src/lib/agentTools.ts
+++ b/web-app/src/lib/agentTools.ts
@@ -253,7 +253,10 @@ export async function executeAgentTool(
*/
scope: WorkspaceScope = 'thread',
/** Opens the sandboxed shell's network namespace. Closed by default. */
- allowNetwork = false
+ allowNetwork = false,
+ /** Opt the attached folder into writes and edits in place (Cowork's shared
+ * folder). Off by default, so chat's attachment stays read-only. */
+ projectWritable = false
): Promise<AgentToolResult> {
try {
const dataFolder = await getServiceHub().app().getJanDataFolder()
@@ -271,6 +274,7 @@ export async function executeAgentTool(
undefined,
allowNetwork,
readOnlyProject ?? undefined,
+ projectWritable,
scope
)
if (result.isError) return { error: result.content }
@@ -296,7 +300,8 @@ export async function startAgentMonitor(
args: unknown,
onUpdate: (update: MonitorUpdate) => void,
readOnlyProject?: string | null,
- allowNetwork = false
+ allowNetwork = false,
+ projectWritable = false
): Promise<{ output: string; isError?: boolean }> {
try {
const dataFolder = await getServiceHub().app().getJanDataFolder()
@@ -306,6 +311,7 @@ export async function startAgentMonitor(
const output = await startMonitor(dataFolder, sessionId, input, onUpdate, {
allowNetwork,
readOnlyProject: readOnlyProject ?? undefined,
+ projectWritable,
scope: 'session',
})
return { output }
diff --git a/web-app/src/lib/coworkDispatch.ts b/web-app/src/lib/coworkDispatch.ts
index 949e230eb..0db501082 100644
--- a/web-app/src/lib/coworkDispatch.ts
+++ b/web-app/src/lib/coworkDispatch.ts
@@ -75,7 +75,9 @@ async function runMonitorOp(
input,
(update) => monitors.update(update),
ctx.readOnlyFolder,
- useCoworkConfig.getState().networkEnabled
+ useCoworkConfig.getState().networkEnabled,
+ // Cowork mounts the attached folder writable (shared-folder mode).
+ true
)
if (!started.isError) monitors.started(started.output)
return { output: started.output, isError: started.isError }
@@ -142,13 +144,16 @@ export async function dispatchCoworkTool(
// because no chat thread claims it. The network flag follows Cowork's own
// setting (on by default), read per call so a toggle in Settings applies to
// the next command; chat's shell stays network-closed regardless.
+ // The attached folder is writable on this surface: Cowork's shared folder
+ // takes writes and edits in place, unlike chat's read-only attachment.
const result = await executeAgentTool(
toolName,
call.input,
ctx.sessionId,
ctx.readOnlyFolder,
'session',
- useCoworkConfig.getState().networkEnabled
+ useCoworkConfig.getState().networkEnabled,
+ true
)
if (result.error) return { output: result.error, isError: true }
return {
diff --git a/web-app/src/lib/coworkPrompt.ts b/web-app/src/lib/coworkPrompt.ts
index b9888bb75..bce571d8d 100644
--- a/web-app/src/lib/coworkPrompt.ts
+++ b/web-app/src/lib/coworkPrompt.ts
@@ -2,9 +2,9 @@
* System prompt for a Cowork run.
*
* The workspace block is the load-bearing part. The agent writes into a sandbox
- * and may only *read* an attached project folder, which is an arrangement no
- * model assumes — left unsaid, it retries the same denied write until the step
- * budget runs out.
+ * and, when a project folder is attached, works on it in place (the shared
+ * folder is mounted writable on this surface) — an arrangement no model
+ * assumes, so it is spelled out along with where scratch work belongs.
*/
const IDENTITY =
@@ -56,7 +56,8 @@ export type CoworkEnvironment = {
export type CoworkPromptOptions = {
/** The sandbox directory: the only writable location. */
workspacePath: string | null
- /** An attached project folder, readable but never writable. */
+ /** An attached project folder. Despite the historical name (it is the
+ * plugin's validated read root), Cowork mounts it writable. */
readOnlyFolder: string | null
planMode: boolean
/** False when no OS sandbox enforces, in which case `bash` is not offered. */
@@ -130,11 +131,12 @@ function workspaceBlock(opts: CoworkPromptOptions): string {
if (opts.readOnlyFolder) {
lines.push(
'',
- `The user attached a project folder: \`${opts.readOnlyFolder}\`.`,
- 'It is mounted READ-ONLY. You can read, search and list inside it, but every',
- 'write, edit or shell command targeting it will be refused. To work on one of',
- 'its files, copy it into your workspace first and edit the copy there. Do not',
- 'retry a refused write against the original path.'
+ `The user attached a shared project folder: \`${opts.readOnlyFolder}\`.`,
+ 'It is writable: read, search, and edit its files IN PLACE with targeted',
+ 'edits, and put files that belong to the project directly inside it. Use',
+ 'your workspace for scratch work and intermediate files. This is real user',
+ 'data with no undo, so re-read a file before editing it and keep changes',
+ 'minimal.'
)
} else {
lines.push('', 'No project folder is attached, so there is nothing outside the workspace to read.')
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index d4119a9a5..1ea179b4d 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -658,23 +658,23 @@
"artifactsSearch": "Search artifacts",
"artifactsShowMore": "Show {{count}} more",
"workspace": {
- "readsFrom": "Reads from",
- "readOnly": "read-only",
- "footnote": "The agent only reads this folder. Nothing inside it is ever modified.",
- "footnoteEmpty": "Attach a folder to let the agent read your project. It still won't change anything in it.",
+ "readsFrom": "Works in",
+ "writable": "read & write",
+ "footnote": "The agent reads and edits this folder directly. Review what changed in the diff panel.",
+ "footnoteEmpty": "Attach a folder to let the agent work on your project. It can read and edit files inside it.",
"attach": "Attach a folder",
"change": "Change folder",
"detach": "Detach folder",
"open": "Open",
"reveal": "Reveal",
"missing": "This folder isn't there anymore. Attach a different one.",
- "a11yWithFolder": "Project folder {{folder}}, attached read-only. Change or detach it.",
+ "a11yWithFolder": "Project folder {{folder}}, attached with read and write access. Change or detach it.",
"a11yNoFolder": "No project folder attached. Attach one."
},
"coworkEmpty": {
"title": "What are we working on?",
"subtitleSandbox": "Give Jan a task. It reads and writes files, runs commands, and works through the steps on its own.",
- "subtitleFolder": "Give Jan a task. It reads {{folder}} without changing anything in it, and works on its own from there.",
+ "subtitleFolder": "Give Jan a task. It works directly in {{folder}}, reading and editing files on its own.",
"try": "Try",
"sandbox": {
"first": "Write a Python script that renames files by the date they were taken",