Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(host-core): add a session visualization root
zszz363f1cf855a4c
diff --git a/crates/host-core/src/main.rs b/crates/host-core/src/main.rsindex 3b5036678..cca6c6826 100644--- a/crates/host-core/src/main.rs+++ b/crates/host-core/src/main.rs@@ -34,6 +34,7 @@ mod transcripts;mod turn_queue;mod user_skills;mod user_subagents;+mod visualizations;mod workspace;use std::sync::Arc;@@ -96,6 +97,9 @@ async fn main() -> anyhow::Result<()> {if let Ok(list) = sessions::list_sessions(&st.db) {let live: std::collections::HashSet<String> = list.into_iter().map(|s| s.id).collect();scratch::sweep(&data_dir, &live);+ // Visualization dirs are swept for orphans only, never by age+ // (D671): live transcripts still reference their cards.+ visualizations::sweep(&data_dir, &live);review::sweep(&data_dir, &live);}}diff --git a/crates/host-core/src/review.rs b/crates/host-core/src/review.rsindex 0885a9af2..7004b2c9e 100644--- a/crates/host-core/src/review.rs+++ b/crates/host-core/src/review.rs@@ -14,7 +14,7 @@ use std::io::Read;use std::path::{Path, PathBuf};use uuid::Uuid;-use crate::workspace::{self, ToolRoot};+use crate::workspace::{self, ContainedRoots, ToolRoot};const REVIEW_DIR: &str = "review-changes";const MAX_SNAPSHOT_BYTES: u64 = 16 * 1024 * 1024;@@ -217,7 +217,7 @@ pub fn prepare_change(session_id: &str,message_id: &str,workspace_root: Option<&Path>,- scratch_root: Option<&Path>,+ roots: &ContainedRoots,tool_name: &str,args: &Value,) -> Result<Option<PendingChange>> {@@ -230,7 +230,7 @@ pub fn prepare_change(let Some(input) = args.get("path").and_then(Value::as_str) else {return Ok(None);};- let Ok((resolved, root_kind)) = workspace::resolve_tool_path(root, scratch_root, input) else {+ let Ok((resolved, root_kind)) = workspace::resolve_tool_path(root, roots, input) else {return Ok(None);};if root_kind != ToolRoot::Workspace {@@ -614,7 +614,7 @@ mod tests {session,message,Some(workspace_root),- None,+ &ContainedRoots::new(),"Edit",&json!({ "path": path }),)diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex edc345eb3..e61b4a4fa 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -9,6 +9,8 @@ mod worktree_rpc;#[cfg(test)]mod plugin_reviews_rpc_tests;+#[cfg(test)]+mod visualization_tests;use std::io::{self, BufRead, BufReader as StdBufReader, Read, Write};use std::path::{Path, PathBuf};@@ -38,7 +40,8 @@ use crate::state::{AppState, HOST_VERSION, PROTOCOL_VERSION};use crate::tools::{self, ToolsExecuteParams};use crate::transcripts::{self, CompactionRecord};use crate::turn_queue;-use crate::workspace;+use crate::visualizations;+use crate::workspace::{self, ContainedRoots, ToolRoot};#[derive(Debug, Deserialize)]struct JsonRpcRequest {@@ -782,6 +785,7 @@ fn permission_parent_param(params: &Value) -> Result<Option<String>, JsonRpcErro/// exactly the same side data as deleting one session.fn drop_session_side_data(st: &AppState, id: &str) {scratch::remove_session_dir(&st.data_dir, id);+ visualizations::remove_session_dir(&st.data_dir, id);review::remove_session(&st.data_dir, id);st.hashline.drop_session(id);}@@ -1403,11 +1407,11 @@ fn resolve_tool_workspace_for_call(/// Read/search tools are low risk inside their normal roots, but an explicit/// path outside both roots is a separate capability. The check is deliberately/// based on the same resolver used for execution so `..` and symlink escapes-/// cannot avoid the permission card. Scratch paths are recognized lexically-/// before the lazy scratch directory exists.+/// cannot avoid the permission card. Contained roots (scratch, visualization)+/// are recognized lexically before their lazy directories exist.fn requires_external_path_permission(workspace_path: Option<&str>,- scratch_path: Option<&Path>,+ roots: &ContainedRoots,tool_name: &str,args: &Value,) -> bool {@@ -1417,18 +1421,63 @@ fn requires_external_path_permission(let Some(path) = args.get("path").and_then(Value::as_str) else {return false;};- if scratch_path.is_some_and(|root| workspace::lexically_inside(root, path)) {+ if roots.lexical_root(path).is_some() {return false;}let Some(workspace_path) = workspace_path else {return false;};matches!(- workspace::resolve_tool_path(Path::new(workspace_path), scratch_path, path),+ workspace::resolve_tool_path(Path::new(workspace_path), roots, path),Err(error) if error == "PATH_OUTSIDE_WORKSPACE")}+/// Contained roots of a local session: scratch (D114) then visualization+/// (D671). Remote-workspace sessions get no visualization root.+fn local_contained_roots(data_dir: &Path, session_id: &str, remote: bool) -> ContainedRoots {+ let visualization = if remote {+ None+ } else {+ visualizations::session_dir(data_dir, session_id)+ };+ ContainedRoots::scratch_only(scratch::session_dir(data_dir, session_id).as_deref())+ .with(ToolRoot::Visualization, visualization)+}++/// Whether a Write/Edit lexically targets one of the session's contained roots+/// and may skip the permission prompt. Never for remote workspaces or contract+/// modes (their hard deny is not bypassed).+fn contained_write_auto_allowed(+ remote: bool,+ durable_mode: &str,+ roots: &ContainedRoots,+ tool_name: &str,+ args: &Value,+) -> bool {+ !remote+ && !sessions::is_contract_mode(durable_mode)+ && matches!(tool_name, "Write" | "Edit")+ && args+ .get("path")+ .and_then(Value::as_str)+ .is_some_and(|path| roots.lexical_root(path).is_some())+ && edit_move_stays_contained(roots, args)+}++/// An Edit can carry `MV <dest>`; the prompt may be skipped only when that+/// destination is inside a contained root too. Unparseable ops never reach+/// the filesystem, so they do not need a prompt.+fn edit_move_stays_contained(roots: &ContainedRoots, args: &Value) -> bool {+ let Some(ops) = args.get("ops").and_then(Value::as_str) else {+ return true;+ };+ let Ok(parsed) = crate::tools::hashline::parse_ops(ops) else {+ return true;+ };+ crate::tools::hashline::mv_dest(&parsed).is_none_or(|dest| roots.lexical_root(dest).is_some())+}+/// Plans are owned by the session's persisted project. Unlike the legacy/// tool compatibility resolver, a plan submission never inherits the mutable/// global workspace or accepts a session-less request.@@ -4056,6 +4105,11 @@ async fn handle_request(None => resolve_tool_workspace_for_call(&st, &p.session_id, &p.args)?,};let scratch = scratch::session_dir(&st.data_dir, &p.session_id);+ let contained_roots = local_contained_roots(+ &st.data_dir,+ &p.session_id,+ remote_workspace.is_some(),+ );let external_path_permission = if remote_workspace.is_some() {remote_tools::requires_external_permission(ws.as_deref(),@@ -4065,7 +4119,7 @@ async fn handle_request(} else {requires_external_path_permission(ws.as_deref(),- scratch.as_deref(),+ &contained_roots,&p.tool_name,&p.args,)@@ -4084,25 +4138,22 @@ async fn handle_request(plan_safe_actions: p.plan_safe_actions.as_deref(),},);- // Write/Edit targeting the session scratch dir never touch- // the user's project — skip the prompt (D114). The lexical- // pre-check only decides prompting; execution still goes- // through the symlink-aware resolver, so it cannot be used- // to escape containment. A contract mode's hard deny is- // never bypassed.- if remote_workspace.is_none()- && !sessions::is_contract_mode(&durable_mode)- && auto.is_none()- && matches!(p.tool_name.as_str(), "Write" | "Edit")+ // Write/Edit targeting the session scratch dir (D114) or+ // visualization dir (D671) never touch the user's project —+ // skip the prompt. The lexical pre-check only decides+ // prompting; execution still goes through the symlink-aware+ // resolver, so it cannot be used to escape containment. A+ // contract mode's hard deny is never bypassed.+ if auto.is_none()+ && contained_write_auto_allowed(+ remote_workspace.is_some(),+ &durable_mode,+ &contained_roots,+ &p.tool_name,+ &p.args,+ ){- if let (Some(scratch_dir), Some(path)) = (- scratch.as_deref(),- p.args.get("path").and_then(|v| v.as_str()),- ) {- if workspace::lexically_inside(scratch_dir, path) {- auto = Some(PermissionDecision::AllowOnce);- }- }+ auto = Some(PermissionDecision::AllowOnce);}if let Some(decision) = auto {(@@ -4364,6 +4415,12 @@ async fn handle_request(session_id: p.session_id.as_str(),store: &hashline_store,};+ // Remote-workspace sessions get no visualization root (D671).+ let visualization_path = if remote_workspace.is_some() {+ None+ } else {+ visualizations::session_dir(&data_dir, &p.session_id)+ };let pending_review = if remote_workspace.is_some() {None} else {@@ -4372,7 +4429,7 @@ async fn handle_request(&p.session_id,&p.tool_call_id,ws_path.as_deref(),- scratch_path.as_deref(),+ &local_contained_roots(&data_dir, &p.session_id, false),&p.tool_name,&p.args,)@@ -4489,6 +4546,7 @@ async fn handle_request(bash_options,allow_external_paths: external_path_permission,hashline: Some(hashline_ctx),+ visualization_root: visualization_path.as_deref(),},);if matches!(p.tool_name.as_str(), "Read" | "Glob" | "Grep") {@@ -4702,7 +4760,6 @@ async fn handle_request(.unwrap_or_else(|| "ask".into());let args = params.get("args").cloned().unwrap_or_else(|| json!({}));let workspace_path = resolve_tool_workspace_for_call(&st, session_id, &args)?;- let scratch_path = scratch::session_dir(&st.data_dir, session_id);let external_path_permission =if remote_tools::session_remote_workspace(&st, session_id)?.is_some() {remote_tools::requires_external_permission(@@ -4713,7 +4770,7 @@ async fn handle_request(} else {requires_external_path_permission(workspace_path.as_deref(),- scratch_path.as_deref(),+ &local_contained_roots(&st.data_dir, session_id, false),tool_name,&args,)@@ -7481,6 +7538,7 @@ mod tests {bash_options: None,allow_external_paths: false,hashline: None,+ visualization_root: None,},).await;@@ -7501,6 +7559,7 @@ mod tests {bash_options: None,allow_external_paths: false,hashline: None,+ visualization_root: None,},).await;diff --git a/crates/host-core/src/rpc/remote_tools.rs b/crates/host-core/src/rpc/remote_tools.rsindex b9314bfcb..98cf10d74 100644--- a/crates/host-core/src/rpc/remote_tools.rs+++ b/crates/host-core/src/rpc/remote_tools.rs@@ -353,6 +353,7 @@ pub(super) async fn handle(session_id: &p.session_id,store: &hashline,}),+ visualization_root: None,};let mut result = tokio::select! {result = tools::execute_tool_with_path_access(Some(&root),None,&p.tool_name,&p.args,options) => result,diff --git a/crates/host-core/src/rpc/visualization_tests.rs b/crates/host-core/src/rpc/visualization_tests.rsnew file mode 100644index 000000000..ba1adcdb0--- /dev/null+++ b/crates/host-core/src/rpc/visualization_tests.rs@@ -0,0 +1,293 @@+//! Session visualization root (D671): containment, `.html`-only writes,+//! prompting, review exclusion, and lifecycle.++use super::*;+use std::fs;++fn options(visualization_root: Option<&Path>) -> tools::ToolExecutionOptions<'_> {+ tools::ToolExecutionOptions {+ timeout_ms: None,+ bash_options: None,+ allow_external_paths: false,+ hashline: None,+ visualization_root,+ }+}++struct Fixture {+ _data: tempfile::TempDir,+ data_dir: PathBuf,+ workspace: PathBuf,+ scratch: PathBuf,+ visualization: PathBuf,+}++fn fixture() -> Fixture {+ let data = tempfile::tempdir().unwrap();+ // Canonical paths keep the symlink-aware resolver's comparisons simple on+ // macOS, where the temp dir lives behind /var -> /private/var.+ let data_dir = fs::canonicalize(data.path()).unwrap();+ let workspace = data_dir.join("project");+ fs::create_dir_all(&workspace).unwrap();+ let scratch = scratch::session_dir(&data_dir, "s1").unwrap();+ let visualization = visualizations::session_dir(&data_dir, "s1").unwrap();+ Fixture {+ _data: data,+ data_dir,+ workspace,+ scratch,+ visualization,+ }+}++async fn run(f: &Fixture, tool: &str, args: Value) -> tools::ToolsExecuteResult {+ tools::execute_tool_with_path_access(+ Some(&f.workspace),+ Some(&f.scratch),+ tool,+ &args,+ options(Some(&f.visualization)),+ )+ .await+}++#[tokio::test]+async fn writes_and_reads_html_fragments_in_the_visualization_root() {+ let f = fixture();+ let card = f.visualization.join("chart.html");+ let written = run(+ &f,+ "Write",+ json!({ "path": card.to_string_lossy(), "content": "<p>hi</p>" }),+ )+ .await;+ assert!(written.ok, "{:?}", written.content);+ assert_eq!(written.content["root"], "visualization");+ assert_eq!(fs::read_to_string(&card).unwrap(), "<p>hi</p>");++ let read = run(&f, "Read", json!({ "path": card.to_string_lossy() })).await;+ assert!(read.ok, "{:?}", read.content);+ assert_eq!(read.content["root"], "visualization");+}++#[tokio::test]+async fn rejects_non_html_writes_in_the_visualization_root() {+ let f = fixture();+ let script = f.visualization.join("evil.js");+ let written = run(+ &f,+ "Write",+ json!({ "path": script.to_string_lossy(), "content": "x" }),+ )+ .await;+ assert!(!written.ok);+ assert_eq!(+ written.error_code.as_deref(),+ Some("VISUALIZATION_HTML_ONLY")+ );+ assert!(!script.exists());++ // Nested paths are unreachable by the card URL, so they are refused too.+ let nested = f.visualization.join("sub").join("chart.html");+ let nested_write = run(+ &f,+ "Write",+ json!({ "path": nested.to_string_lossy(), "content": "<p>x</p>" }),+ )+ .await;+ assert_eq!(+ nested_write.error_code.as_deref(),+ Some("VISUALIZATION_HTML_ONLY")+ );+ assert!(!nested.exists());++ // Scratch keeps accepting any extension.+ let note = f.scratch.join("notes.txt");+ let scratch_write = run(+ &f,+ "Write",+ json!({ "path": note.to_string_lossy(), "content": "x" }),+ )+ .await;+ assert!(scratch_write.ok, "{:?}", scratch_write.content);+ assert_eq!(scratch_write.content["root"], "scratch");+}++#[tokio::test]+async fn rejects_dotdot_and_symlink_escapes_from_the_visualization_root() {+ let f = fixture();+ let escape = format!("{}/../../outside.html", f.visualization.to_string_lossy());+ let dotdot = run(&f, "Write", json!({ "path": escape, "content": "x" })).await;+ assert!(!dotdot.ok);+ assert!(!f.data_dir.join("outside.html").exists());++ #[cfg(unix)]+ {+ let outside = f.data_dir.join("elsewhere");+ fs::create_dir_all(&outside).unwrap();+ fs::create_dir_all(&f.visualization).unwrap();+ std::os::unix::fs::symlink(&outside, f.visualization.join("link")).unwrap();+ let through_link = f.visualization.join("link").join("x.html");+ let linked = run(+ &f,+ "Write",+ json!({ "path": through_link.to_string_lossy(), "content": "x" }),+ )+ .await;+ assert!(!linked.ok);+ assert!(!outside.join("x.html").exists());+ }+}++#[test]+fn visualization_writes_skip_prompts_except_remote_and_contract_modes() {+ let f = fixture();+ let roots = local_contained_roots(&f.data_dir, "s1", false);+ let args = json!({ "path": f.visualization.join("a.html").to_string_lossy() });+ assert!(contained_write_auto_allowed(+ false, "agent", &roots, "Write", &args+ ));+ assert!(contained_write_auto_allowed(+ false, "agent", &roots, "Edit", &args+ ));+ assert!(!contained_write_auto_allowed(+ false, "plan", &roots, "Write", &args+ ));+ assert!(!contained_write_auto_allowed(+ false, "goal", &roots, "Write", &args+ ));+ assert!(!contained_write_auto_allowed(+ true, "agent", &roots, "Write", &args+ ));+ assert!(!contained_write_auto_allowed(+ false, "agent", &roots, "Bash", &args+ ));+ let workspace_args = json!({ "path": "notes.txt" });+ assert!(!contained_write_auto_allowed(+ false,+ "agent",+ &roots,+ "Write",+ &workspace_args+ ));+}++#[test]+fn remote_sessions_get_no_visualization_root() {+ let f = fixture();+ let remote = local_contained_roots(&f.data_dir, "s1", true);+ let path = f.visualization.join("a.html");+ assert!(remote.lexical_root(&path.to_string_lossy()).is_none());+ let local = local_contained_roots(&f.data_dir, "s1", false);+ assert_eq!(+ local+ .lexical_root(&path.to_string_lossy())+ .map(|root| root.kind),+ Some(ToolRoot::Visualization)+ );+}++#[test]+fn visualization_paths_do_not_require_external_path_permission() {+ let f = fixture();+ let roots = local_contained_roots(&f.data_dir, "s1", false);+ let workspace = f.workspace.to_string_lossy().to_string();+ let inside = json!({ "path": f.visualization.join("a.html").to_string_lossy() });+ assert!(!requires_external_path_permission(+ Some(&workspace),+ &roots,+ "Read",+ &inside+ ));+ assert!(!requires_external_path_permission(+ Some(&workspace),+ &roots,+ "Write",+ &inside+ ));+ let other_session = visualizations::session_dir(&f.data_dir, "s2").unwrap();+ let foreign = json!({ "path": other_session.join("a.html").to_string_lossy() });+ assert!(requires_external_path_permission(+ Some(&workspace),+ &roots,+ "Write",+ &foreign+ ));+}++#[test]+fn visualization_writes_are_not_review_snapshotted() {+ let f = fixture();+ let roots = local_contained_roots(&f.data_dir, "s1", false);+ let pending = review::prepare_change(+ &f.data_dir,+ "s1",+ "call-1",+ Some(&f.workspace),+ &roots,+ "Write",+ &json!({ "path": f.visualization.join("a.html").to_string_lossy() }),+ )+ .unwrap();+ assert!(pending.is_none());+}++#[test]+fn deleting_session_side_data_removes_its_visualizations() {+ let data = tempfile::tempdir().unwrap();+ let state = AppState::open(data.path()).unwrap();+ let dir = visualizations::session_dir(&state.data_dir, "gone").unwrap();+ fs::create_dir_all(&dir).unwrap();+ fs::write(dir.join("a.html"), "<p></p>").unwrap();+ let kept = visualizations::session_dir(&state.data_dir, "kept").unwrap();+ fs::create_dir_all(&kept).unwrap();+ drop_session_side_data(&state, "gone");+ assert!(!dir.exists());+ assert!(kept.exists());+}++#[test]+fn moving_a_fragment_out_of_contained_roots_needs_a_prompt() {+ let f = fixture();+ let roots = local_contained_roots(&f.data_dir, "s1", false);+ let path = f.visualization.join("a.html");+ let ops_for = |dest: &str| format!("[{}#AAAA]\nMV {dest}\n", path.display());+ let to_workspace = json!({ "path": path.to_string_lossy(), "ops": ops_for("src/main.rs") });+ assert!(!contained_write_auto_allowed(+ false,+ "agent",+ &roots,+ "Edit",+ &to_workspace+ ));+ let inside = f.visualization.join("b.html");+ let within = json!({+ "path": path.to_string_lossy(),+ "ops": ops_for(&inside.to_string_lossy()),+ });+ assert!(contained_write_auto_allowed(+ false, "agent", &roots, "Edit", &within+ ));+}++#[tokio::test]+async fn visualization_rules_apply_when_the_workspace_contains_the_data_dir() {+ let f = fixture();+ let roots = local_contained_roots(&f.data_dir, "s1", false);+ let nested = f.visualization.join("nested").join("x.html");+ let resolved = workspace::resolve_tool_path(&f.data_dir, &roots, &nested.to_string_lossy());+ assert!(+ resolved.is_err() || resolved.as_ref().unwrap().1 == ToolRoot::Visualization,+ "visualization paths must not resolve as workspace: {resolved:?}"+ );+ let result = tools::execute_tool_with_path_access(+ Some(&f.data_dir),+ Some(&f.scratch),+ "Write",+ &json!({ "path": f.visualization.join("notes.txt").to_string_lossy(), "content": "x" }),+ options(Some(&f.visualization)),+ )+ .await;+ assert!(!result.ok, "non-html write must be rejected: {result:?}");+ assert!(!f.visualization.join("notes.txt").exists());+}diff --git a/crates/host-core/src/rpc/worktree_rpc/tests.rs b/crates/host-core/src/rpc/worktree_rpc/tests.rsindex ef7c349bb..7a5c30a15 100644--- a/crates/host-core/src/rpc/worktree_rpc/tests.rs+++ b/crates/host-core/src/rpc/worktree_rpc/tests.rs@@ -34,6 +34,7 @@ fn tool_options(bash_options: bash,allow_external_paths: false,hashline: None,+ visualization_root: None,}}@@ -112,7 +113,7 @@ async fn isolated_session_user_path_from_create_to_delete() {// external-path permission; isolation does not weaken containment.assert!(requires_external_path_permission(Some(&root.to_string_lossy()),- None,+ &crate::workspace::ContainedRoots::new(),"Write",&json!({ "path": project.join("f.txt").to_string_lossy() }),));diff --git a/crates/host-core/src/session_worktrees/lifecycle.rs b/crates/host-core/src/session_worktrees/lifecycle.rsindex 7f28157ab..2103a9188 100644--- a/crates/host-core/src/session_worktrees/lifecycle.rs+++ b/crates/host-core/src/session_worktrees/lifecycle.rs@@ -442,6 +442,7 @@ pub(super) async fn run_setup(}),allow_external_paths: false,hashline: None,+ visualization_root: None,},).await;diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rsindex fd7a3650d..4e3f7fb75 100644--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@ -1780,6 +1780,13 @@ pub fn fork_session_through(&mut records,&mut compactions,)?;+ let visualization_files = fork_files::preserve_visualizations(+ db.data_dir(),+ source_id,+ &id,+ &mut records,+ &mut compactions,+ )?;let texts = records.iter().map(record_index_text).collect::<Vec<_>>();let now = now_ms();let created_at = ms_to_ts(now);@@ -1824,6 +1831,7 @@ pub fn fork_session_through(return Err(error);}files.commit();+ visualization_files.commit();let summary = SessionSummary {id,@@ -6312,6 +6320,44 @@ mod tests {assert_eq!(std::fs::read_to_string(file).unwrap(), "keep source");}+ #[test]+ fn fork_copies_referenced_visualizations_so_cards_survive_source_deletion() {+ let db = test_db();+ let source = create_session(&db, Some("Charts".into()), None, None, None, None).unwrap();+ let dir = crate::visualizations::session_dir(db.data_dir(), &source.id).unwrap();+ std::fs::create_dir_all(&dir).unwrap();+ let chart = dir.join("chart.html");+ std::fs::write(&chart, "<p>chart</p>").unwrap();+ std::fs::write(dir.join("unused.html"), "<p>unused</p>").unwrap();+ let text = format!("::visualize{{\"path\":\"{}\"}}", chart.display());+ append_message(+ &db,+ &source.id,+ &user_msg("viz-1", &text, "2025-05-01T00:00:00Z"),+ None,+ )+ .unwrap();+ let ForkSessionResult::Created(child) =+ fork_session_through(&db, &source.id, None, None).unwrap()+ else {+ panic!("expected child")+ };+ let child_dir =+ crate::visualizations::session_dir(db.data_dir(), &child.summary.id).unwrap();+ let child_chart = child_dir.join("chart.html");+ assert_eq!(+ child.messages[0].content,+ format!("::visualize{{\"path\":\"{}\"}}", child_chart.display())+ );+ assert!(!child_dir.join("unused.html").exists());+ delete_session(&db, &source.id).unwrap();+ crate::visualizations::remove_session_dir(db.data_dir(), &source.id);+ assert_eq!(+ std::fs::read_to_string(&child_chart).unwrap(),+ "<p>chart</p>"+ );+ }+#[test]fn fork_preserves_referenced_pasted_files_independently() {let db = test_db();diff --git a/crates/host-core/src/sessions/fork_files.rs b/crates/host-core/src/sessions/fork_files.rsindex 8b9f8d29a..0177e5d05 100644--- a/crates/host-core/src/sessions/fork_files.rs+++ b/crates/host-core/src/sessions/fork_files.rs@@ -6,8 +6,8 @@ use std::path::{Path, PathBuf};use anyhow::{anyhow, Context, Result};use serde_json::Value;-use crate::scratch;use crate::transcripts::{CompactionRecord, MessageRecord};+use crate::{scratch, visualizations};/// Roll back copied inputs if transcript/index publication fails.pub(super) struct ForkFiles {@@ -170,33 +170,97 @@ pub(super) fn preserve(if !entry.file_type()?.is_file() {return Err(anyhow!("referenced fork input is not a regular file"));}- let mut options = OpenOptions::new();- options.read(true);- #[cfg(unix)]- {- use std::os::unix::fs::OpenOptionsExt;- options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);+ fs::create_dir_all(guard.destination.join("pasted"))?;+ copy_regular_file(&path, &target)?;+ }+ Ok(guard)+}++/// Copy one regular file without following a symlink at the source and+/// without overwriting anything at the target.+fn copy_regular_file(path: &Path, target: &Path) -> Result<()> {+ let mut options = OpenOptions::new();+ options.read(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);+ }+ #[cfg(windows)]+ {+ use std::os::windows::fs::OpenOptionsExt;+ options.custom_flags(windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT);+ }+ let mut input = options.open(path).context("open fork input")?;+ let metadata = input.metadata()?;+ if !metadata.is_file() || metadata.file_type().is_symlink() {+ return Err(anyhow!("referenced fork input is not a regular file"));+ }+ let mut output = OpenOptions::new()+ .write(true)+ .create_new(true)+ .open(target)+ .context("create fork input copy")?;+ std::io::copy(&mut input, &mut output).context("copy fork input")?;+ output.sync_all()?;+ Ok(())+}++/// Give a fork its own copies of the visualization fragments its transcript+/// references (D671), so deleting the source session cannot break the+/// child's cards. Unreferenced fragments stay behind.+pub(super) fn preserve_visualizations(+ data_dir: &Path,+ source_id: &str,+ child_id: &str,+ records: &mut [MessageRecord],+ compactions: &mut [CompactionRecord],+) -> Result<ForkFiles> {+ let source = visualizations::session_dir(data_dir, source_id)+ .ok_or_else(|| anyhow!("invalid source session id"))?;+ let destination = visualizations::session_dir(data_dir, child_id)+ .ok_or_else(|| anyhow!("invalid child session id"))?;+ if destination.try_exists()? {+ return Err(anyhow!("fork visualization directory already exists"));+ }+ let guard = ForkFiles {+ destination,+ committed: false,+ };+ // Visualizations are disposable like scratch: a missing directory does+ // not prevent branching, and a symlinked one is never followed.+ for directory in [visualizations::base_dir(data_dir), source.clone()] {+ match fs::symlink_metadata(&directory) {+ Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => {}+ Ok(_) => return Ok(guard),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(guard),+ Err(error) => return Err(error.into()),}+ }+ for entry in fs::read_dir(&source)? {+ let entry = entry?;+ let path = entry.path();+ if !entry.file_type()?.is_file() || !visualizations::is_fragment_path(&path) {+ continue;+ }+ let target = guard.destination.join(entry.file_name());+ let source_path = path.to_string_lossy();+ let target_path = target.to_string_lossy();+ let referenced = rewrite(records, compactions, &source_path, &target_path);+ // Renderer path references may use forward slashes on Windows.#[cfg(windows)]- {- use std::os::windows::fs::OpenOptionsExt;- options.custom_flags(- windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT,+ let referenced = referenced+ | rewrite(+ records,+ compactions,+ &source_path.replace('\\', "/"),+ &target_path.replace('\\', "/"),);+ if !referenced {+ continue;}- let mut input = options.open(&path).context("open fork input")?;- let metadata = input.metadata()?;- if !metadata.is_file() || metadata.file_type().is_symlink() {- return Err(anyhow!("referenced fork input is not a regular file"));- }- fs::create_dir_all(guard.destination.join("pasted"))?;- let mut output = OpenOptions::new()- .write(true)- .create_new(true)- .open(&target)- .context("create fork input copy")?;- std::io::copy(&mut input, &mut output).context("copy fork input")?;- output.sync_all()?;+ fs::create_dir_all(&guard.destination)?;+ copy_regular_file(&path, &target)?;}Ok(guard)}diff --git a/crates/host-core/src/tools/hashline/mod.rs b/crates/host-core/src/tools/hashline/mod.rsindex 3fecc82f2..12295e59a 100644--- a/crates/host-core/src/tools/hashline/mod.rs+++ b/crates/host-core/src/tools/hashline/mod.rs@@ -10,7 +10,7 @@ mod tag;pub use apply::{apply_edit, canonical_key, encode_success, record_post_write, ToolError};#[allow(unused_imports)]-pub use parse::mv_dest;+pub use parse::{mv_dest, parse_ops};pub use store::HashlineStore;pub use tag::{looks_binary_bytes, normalize_file, section_header, split_lines, strip_write_markup,diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rsindex f01a6381d..6d3f1b88d 100644--- a/crates/host-core/src/tools/mod.rs+++ b/crates/host-core/src/tools/mod.rs@@ -19,7 +19,9 @@ use tokio::io::{AsyncRead, AsyncReadExt};use tokio::process::{ChildStderr, ChildStdin, ChildStdout, Command};use tokio::sync::{mpsc, watch};-use crate::workspace::{resolve_tool_path_with_external, simple_canonicalize, ToolRoot};+use crate::workspace::{+ resolve_tool_path_with_external, simple_canonicalize, ContainedRoots, ToolRoot,+};mod grep_rg;pub mod hashline;@@ -862,6 +864,9 @@ pub struct ToolExecutionOptions<'a> {pub bash_options: Option<BashExecutionOptions>,pub allow_external_paths: bool,pub hashline: Option<HashlineContext<'a>>,+ /// Session visualization directory: a contained root for Read and for+ /// `.html`-only Write/Edit (D671). `None` for remote sessions (contract modes still deny writes).+ pub visualization_root: Option<&'a Path>,}pub fn validate_timeout_ms(timeout_ms: Option<u64>) -> Result<(), (String, String)> {@@ -1110,6 +1115,7 @@ pub async fn execute_tool_with_options(bash_options,allow_external_paths: false,hashline: None,+ visualization_root: None,},).await@@ -1119,14 +1125,13 @@ pub async fn execute_tool_with_options(/// traversal, read, or rg child wait cannot occupy an async worker (#1071).async fn run_file_tool(workspace: Option<&Path>,- scratch: Option<&Path>,+ roots: ContainedRoots,tool_name: &str,args: &Value,allow_external_paths: bool,hashline: Option<&HashlineContext<'_>>,) -> Result<Value, hashline::ToolError> {let workspace = workspace.map(Path::to_path_buf);- let scratch = scratch.map(Path::to_path_buf);let tool_name = tool_name.to_string();let args = args.clone();let hashline = hashline.map(|ctx| (ctx.session_id.to_string(), ctx.store.clone()));@@ -1141,19 +1146,18 @@ async fn run_file_tool(session_id: id,store,});- let (workspace, scratch, hashline) =- (workspace.as_deref(), scratch.as_deref(), hashline.as_ref());+ let (workspace, roots, hashline) = (workspace.as_deref(), &roots, hashline.as_ref());let args = &args;match tool_name.as_str() {- "Read" => tool_read(workspace, scratch, args, allow_external_paths, hashline)+ "Read" => tool_read(workspace, roots, args, allow_external_paths, hashline).map_err(Into::into),- "Glob" => tool_glob(workspace, scratch, args, allow_external_paths).map_err(Into::into),- "Grep" => tool_grep(workspace, scratch, args, allow_external_paths, hashline)+ "Glob" => tool_glob(workspace, roots, args, allow_external_paths).map_err(Into::into),+ "Grep" => tool_grep(workspace, roots, args, allow_external_paths, hashline).map_err(Into::into),- "Write" => tool_write(workspace, scratch, args, allow_external_paths, hashline)+ "Write" => tool_write(workspace, roots, args, allow_external_paths, hashline).map_err(Into::into),// "Edit": the caller routes only these five file tools here.- _ => tool_edit(workspace, scratch, args, allow_external_paths, hashline),+ _ => tool_edit(workspace, roots, args, allow_external_paths, hashline),}}).await@@ -1174,6 +1178,7 @@ pub async fn execute_tool_with_path_access(bash_options,allow_external_paths,hashline,+ visualization_root,} = options;let started = Instant::now();let timeout_ms = effective_timeout_ms(tool_name, requested_timeout_ms);@@ -1192,6 +1197,19 @@ pub async fn execute_tool_with_path_access(let _ = std::fs::create_dir_all(dir);}}+ // The visualization dir is created only when a Write/Edit actually+ // targets it, so ordinary sessions never get an empty directory (D671).+ if matches!(tool_name, "Write" | "Edit") {+ if let (Some(dir), Some(path)) =+ (visualization_root, args.get("path").and_then(Value::as_str))+ {+ if crate::workspace::lexically_inside(dir, path) {+ if let Err(error) = std::fs::create_dir_all(dir) {+ tracing::warn!(%error, "failed to create visualization directory");+ }+ }+ }+ }let result: Result<Value, hashline::ToolError> = match tool_name {// Authorize the desktop-owned image request through the normal host gate.// Only the trusted desktop runner performs the external call.@@ -1199,7 +1217,10 @@ pub async fn execute_tool_with_path_access("Read" | "Glob" | "Grep" | "Write" | "Edit" => {run_file_tool(workspace,- scratch,+ ContainedRoots::scratch_only(scratch).with(+ ToolRoot::Visualization,+ visualization_root.map(Path::to_path_buf),+ ),tool_name,args,allow_external_paths,@@ -1301,14 +1322,44 @@ fn require_workspace(workspace: Option<&Path>) -> Result<&Path, (String, String)fn display_tool_path(root_kind: ToolRoot, workspace_root: &Path, resolved: &Path) -> String {match root_kind {ToolRoot::Workspace => relative_display(workspace_root, resolved),- ToolRoot::Scratch | ToolRoot::External => resolved.to_string_lossy().to_string(),+ ToolRoot::Scratch | ToolRoot::Visualization | ToolRoot::External => {+ resolved.to_string_lossy().to_string()+ }}}+/// The visualization root holds only HTML fragments served to sandboxed+/// cards (D671): Write/Edit there must target an `.html` file.+fn ensure_visualization_fragment(+ roots: &ContainedRoots,+ root_kind: ToolRoot,+ resolved: &Path,+) -> Result<(), (String, String)> {+ if root_kind != ToolRoot::Visualization {+ return Ok(());+ }+ // The renderer can only address `<root>/<file>.html`, so nested paths and+ // other extensions would produce files no card can ever show.+ let direct_child = roots+ .iter()+ .find(|root| root.kind == ToolRoot::Visualization)+ .and_then(|root| std::fs::canonicalize(&root.path).ok())+ .is_some_and(|root| resolved.parent() == Some(root.as_path()));+ if !direct_child || !crate::visualizations::is_fragment_path(resolved) {+ return Err((+ "VISUALIZATION_HTML_ONLY".into(),+ "Only .html fragments directly inside the visualization directory can be written there"+ .into(),+ ));+ }+ Ok(())+}+fn root_label(root_kind: ToolRoot) -> &'static str {match root_kind {ToolRoot::Workspace => "workspace",ToolRoot::Scratch => "scratch",+ ToolRoot::Visualization => "visualization",ToolRoot::External => "external",}}@@ -1396,7 +1447,7 @@ fn read_image_block(fn tool_read(workspace: Option<&Path>,- scratch: Option<&Path>,+ roots: &ContainedRoots,args: &Value,allow_external_paths: bool,hashline: Option<&HashlineContext<'_>>,@@ -1407,7 +1458,7 @@ fn tool_read(.and_then(|v| v.as_str()).ok_or_else(|| ("INVALID_ARGUMENT".into(), "path required".into()))?;let (resolved, root_kind) =- resolve_tool_path_with_external(root, scratch, path, allow_external_paths)+ resolve_tool_path_with_external(root, roots, path, allow_external_paths).map_err(|e| (e.clone(), e))?;if ignore_rules::is_sensitive_path(&resolved) {return Err(ignore_rules::denied_error(path));@@ -1542,7 +1593,7 @@ fn tool_read(fn tool_write(workspace: Option<&Path>,- scratch: Option<&Path>,+ roots: &ContainedRoots,args: &Value,allow_external_paths: bool,hashline: Option<&HashlineContext<'_>>,@@ -1558,11 +1609,12 @@ fn tool_write(.ok_or_else(|| ("INVALID_ARGUMENT".into(), "content required".into()))?;let content = hashline::strip_write_markup(content);let (resolved, root_kind) =- resolve_tool_path_with_external(root, scratch, path, allow_external_paths)+ resolve_tool_path_with_external(root, roots, path, allow_external_paths).map_err(|e| (e.clone(), e))?;if ignore_rules::is_sensitive_path(&resolved) {return Err(ignore_rules::denied_error(path));}+ ensure_visualization_fragment(roots, root_kind, &resolved)?;if let Some(parent) = resolved.parent() {std::fs::create_dir_all(parent).map_err(|e| ("TOOL_FAILED".into(), format!("mkdir failed: {e}")))?;@@ -1636,7 +1688,7 @@ fn legacy_replace_ops(text: &str, start: usize, old: &str, new: &str) -> Option<fn tool_edit(workspace: Option<&Path>,- scratch: Option<&Path>,+ roots: &ContainedRoots,args: &Value,allow_external_paths: bool,hashline: Option<&HashlineContext<'_>>,@@ -1647,12 +1699,14 @@ fn tool_edit(.and_then(|v| v.as_str()).ok_or_else(|| hashline::ToolError::new("INVALID_ARGUMENT", "path required"))?;let (resolved, root_kind) =- resolve_tool_path_with_external(root, scratch, path, allow_external_paths)+ resolve_tool_path_with_external(root, roots, path, allow_external_paths).map_err(|e| hashline::ToolError::new(e.clone(), e))?;if ignore_rules::is_sensitive_path(&resolved) {let (code, message) = ignore_rules::denied_error(path);return Err(hashline::ToolError::new(code, message));}+ ensure_visualization_fragment(roots, root_kind, &resolved)+ .map_err(|(code, message)| hashline::ToolError::new(code, message))?;let live = std::fs::read(&resolved).map_err(|e| {if e.kind() == std::io::ErrorKind::NotFound {hashline::ToolError::new("FILE_NOT_FOUND", format!("File not found: {path}"))@@ -1740,12 +1794,14 @@ fn tool_edit(let bytes = hashline::encode_success(&file);if let Some(dest) = &success.moved_to {let (dest_resolved, dest_root) =- resolve_tool_path_with_external(root, scratch, dest, allow_external_paths)+ resolve_tool_path_with_external(root, roots, dest, allow_external_paths).map_err(|e| hashline::ToolError::new(e.clone(), e))?;if ignore_rules::is_sensitive_path(&dest_resolved) {let (code, message) = ignore_rules::denied_error(dest);return Err(hashline::ToolError::new(code, message));}+ ensure_visualization_fragment(roots, dest_root, &dest_resolved)+ .map_err(|(code, message)| hashline::ToolError::new(code, message))?;// Both paths have passed the same canonical, permission-aware resolver.// Writing then unlinking an alias of the source would delete the file.if dest_resolved == resolved {@@ -1835,7 +1891,7 @@ enum SearchPathKind {fn search_root(root: &Path,- scratch: Option<&Path>,+ roots: &ContainedRoots,args: &Value,allow_external_paths: bool,expected: SearchPathKind,@@ -1848,7 +1904,7 @@ fn search_root({Some(path) => {let (resolved, kind) =- resolve_tool_path_with_external(root, scratch, path, allow_external_paths)+ resolve_tool_path_with_external(root, roots, path, allow_external_paths).map_err(|e| (e.clone(), e))?;let accepted = resolved.is_dir()|| matches!(expected, SearchPathKind::FileOrDirectory) && resolved.is_file();@@ -1931,7 +1987,7 @@ fn candidate_files(fn tool_glob(workspace: Option<&Path>,- scratch: Option<&Path>,+ roots: &ContainedRoots,args: &Value,allow_external_paths: bool,) -> Result<Value, (String, String)> {@@ -1943,7 +1999,7 @@ fn tool_glob(let set = build_glob_set(pattern)?;let (search_dir, root_kind, scoped) = search_root(root,- scratch,+ roots,args,allow_external_paths,SearchPathKind::DirectoryOnly,@@ -1998,7 +2054,7 @@ fn tool_glob(fn tool_grep(workspace: Option<&Path>,- scratch: Option<&Path>,+ roots: &ContainedRoots,args: &Value,allow_external_paths: bool,hashline: Option<&HashlineContext<'_>>,@@ -2018,7 +2074,7 @@ fn tool_grep(.map_err(|e| ("INVALID_ARGUMENT".into(), e.to_string()))?;let (search_dir, root_kind, scoped) = search_root(root,- scratch,+ roots,args,allow_external_paths,SearchPathKind::FileOrDirectory,@@ -2080,7 +2136,7 @@ fn tool_grep(}) {return Ok(mint_grep_tags(root,- scratch,+ roots,allow_external_paths,mode,value,@@ -2160,7 +2216,7 @@ fn tool_grep(Ok(mint_grep_tags(root,- scratch,+ roots,allow_external_paths,mode,grep_output(@@ -2223,7 +2279,7 @@ pub(super) fn grep_output(fn mint_grep_tags(root: &Path,- scratch: Option<&Path>,+ roots: &ContainedRoots,allow_external_paths: bool,mode: &str,out: Value,@@ -2271,7 +2327,7 @@ fn mint_grep_tags(let mut tags = serde_json::Map::new();for (display, lines) in per_file {let Ok((resolved, _)) =- resolve_tool_path_with_external(root, scratch, &display, allow_external_paths)+ resolve_tool_path_with_external(root, roots, &display, allow_external_paths)else {continue;};@@ -3963,6 +4019,7 @@ mod tests {bash_options: None,allow_external_paths: true,hashline: None,+ visualization_root: None,},).await;@@ -4122,6 +4179,7 @@ mod tests {bash_options: None,allow_external_paths: true,hashline: None,+ visualization_root: None,},).await;@@ -4145,6 +4203,7 @@ mod tests {bash_options: None,allow_external_paths: true,hashline: None,+ visualization_root: None,},).await;@@ -4168,6 +4227,7 @@ mod tests {bash_options: None,allow_external_paths: true,hashline: None,+ visualization_root: None,},).await;@@ -4195,6 +4255,7 @@ mod tests {bash_options: None,allow_external_paths: true,hashline: None,+ visualization_root: None,},).await;@@ -4222,6 +4283,7 @@ mod tests {bash_options: None,allow_external_paths: true,hashline: None,+ visualization_root: None,},).await;@@ -4243,6 +4305,7 @@ mod tests {bash_options: None,allow_external_paths: true,hashline: None,+ visualization_root: None,},).await;diff --git a/crates/host-core/src/visualizations.rs b/crates/host-core/src/visualizations.rsnew file mode 100644index 000000000..ae7d2fb81--- /dev/null+++ b/crates/host-core/src/visualizations.rs@@ -0,0 +1,153 @@+//! Per-session visualization directories (D671).+//!+//! Inline GenUI cards are HTML fragments the agent writes under+//! `<data_dir>/visualizations/<session_id>/`; the desktop serves them through+//! the sandboxed `pi-genui:` protocol. Unlike scratch, these files are part of+//! the transcript: they are never removed by age, only together with their+//! session (or by the startup sweep once the session no longer exists).+//! Created lazily on the first Write/Edit that targets the directory.++use std::collections::HashSet;+use std::path::{Path, PathBuf};++/// Session ids come from our own DB (UUIDs), but stay defensive: an id that+/// could traverse out of the base directory gets no directory at all.+fn safe_session_id(session_id: &str) -> bool {+ !session_id.is_empty()+ && session_id+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')+}++pub fn base_dir(data_dir: &Path) -> PathBuf {+ data_dir.join("visualizations")+}++/// Absolute visualization directory for a session, or None for unsafe ids.+pub fn session_dir(data_dir: &Path, session_id: &str) -> Option<PathBuf> {+ if !safe_session_id(session_id) {+ return None;+ }+ Some(base_dir(data_dir).join(session_id))+}++/// True when `path` names an `.html` file (lowercase `.html` only).+pub fn is_fragment_path(path: &Path) -> bool {+ // Mirrors `isGenUiFileName` in packages/shared/src/gen-ui.ts.+ let Some(name) = path.file_name().and_then(|name| name.to_str()) else {+ return false;+ };+ let Some(stem) = name.strip_suffix(".html") else {+ return false;+ };+ let mut chars = stem.chars();+ stem.len() <= 128+ && !name.contains("..")+ && chars.next().is_some_and(|c| c.is_ascii_alphanumeric())+ && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))+}++/// Remove a session's visualization directory (idempotent, best-effort).+pub fn remove_session_dir(data_dir: &Path, session_id: &str) {+ if let Some(dir) = session_dir(data_dir, session_id) {+ if dir.exists() {+ if let Err(error) = std::fs::remove_dir_all(&dir) {+ tracing::warn!(path = %dir.display(), %error, "visualization cleanup failed");+ }+ }+ }+}++/// Startup sweep: drop directories whose session no longer exists. Live+/// sessions keep their cards regardless of age — the transcript still+/// references them.+pub fn sweep(data_dir: &Path, live_session_ids: &HashSet<String>) {+ let base = base_dir(data_dir);+ let Ok(entries) = std::fs::read_dir(&base) else {+ return;+ };+ for entry in entries.flatten() {+ let path = entry.path();+ // Do not follow symlinks out of the base directory.+ let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);+ if !is_dir {+ continue;+ }+ let name = entry.file_name().to_string_lossy().to_string();+ if live_session_ids.contains(&name) {+ continue;+ }+ if let Err(error) = std::fs::remove_dir_all(&path) {+ tracing::warn!(path = %path.display(), %error, "visualization sweep failed");+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::time::{Duration, SystemTime};+ use tempfile::tempdir;++ #[test]+ fn rejects_unsafe_session_ids() {+ let dir = tempdir().unwrap();+ assert!(session_dir(dir.path(), "../evil").is_none());+ assert!(session_dir(dir.path(), "a/b").is_none());+ assert!(session_dir(dir.path(), "").is_none());+ assert_eq!(+ session_dir(dir.path(), "0b0e9a52-1_ok").unwrap(),+ dir.path().join("visualizations").join("0b0e9a52-1_ok")+ );+ }++ #[test]+ fn fragment_paths_require_html_extension() {+ assert!(is_fragment_path(Path::new("/x/chart.html")));+ assert!(!is_fragment_path(Path::new("/x/Chart.HTML")));+ assert!(!is_fragment_path(Path::new("/x/.hidden.html")));+ assert!(!is_fragment_path(Path::new("/x/a..b.html")));+ assert!(is_fragment_path(Path::new("/x/chart-v2_final.html")));+ assert!(!is_fragment_path(Path::new("/x/chart.htm")));+ assert!(!is_fragment_path(Path::new("/x/chart.js")));+ assert!(!is_fragment_path(Path::new("/x/html")));+ }++ #[test]+ fn remove_is_idempotent() {+ let dir = tempdir().unwrap();+ let s = session_dir(dir.path(), "s1").unwrap();+ std::fs::create_dir_all(&s).unwrap();+ std::fs::write(s.join("a.html"), "<p>x</p>").unwrap();+ remove_session_dir(dir.path(), "s1");+ assert!(!s.exists());+ remove_session_dir(dir.path(), "s1");+ }++ #[test]+ fn sweep_removes_orphans_and_keeps_live_regardless_of_age() {+ let dir = tempdir().unwrap();+ let live = session_dir(dir.path(), "live").unwrap();+ let orphan = session_dir(dir.path(), "orphan").unwrap();+ std::fs::create_dir_all(&live).unwrap();+ std::fs::create_dir_all(&orphan).unwrap();+ let card = live.join("old.html");+ std::fs::write(&card, "<p>old</p>").unwrap();+ let ancient = SystemTime::now() - Duration::from_secs(365 * 24 * 60 * 60);+ std::fs::File::options()+ .write(true)+ .open(&card)+ .unwrap()+ .set_modified(ancient)+ .unwrap();+ std::fs::File::open(&live)+ .unwrap()+ .set_modified(ancient)+ .ok();+ let mut ids = HashSet::new();+ ids.insert("live".to_string());+ sweep(dir.path(), &ids);+ assert!(card.exists());+ assert!(!orphan.exists());+ }+}diff --git a/crates/host-core/src/workspace.rs b/crates/host-core/src/workspace.rsindex 25930325e..02720b8ad 100644--- a/crates/host-core/src/workspace.rs+++ b/crates/host-core/src/workspace.rs@@ -94,9 +94,58 @@ impl WorkspaceState {pub enum ToolRoot {Workspace,Scratch,+ /// Per-session GenUI fragment directory (D671).+ Visualization,External,}+/// A host-owned directory a session may address by absolute path in addition+/// to its workspace. Every contained root gets the same lexical + symlink+/// containment defense as the workspace.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ContainedRoot {+ pub path: PathBuf,+ pub kind: ToolRoot,+}++/// Ordered list of contained roots tried after the workspace. The first root+/// that contains a path wins.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct ContainedRoots {+ roots: Vec<ContainedRoot>,+}++impl ContainedRoots {+ pub fn new() -> Self {+ Self::default()+ }++ /// Roots holding only the session scratch directory (D114), if any.+ pub fn scratch_only(scratch: Option<&Path>) -> Self {+ Self::new().with(ToolRoot::Scratch, scratch.map(Path::to_path_buf))+ }++ /// Append a root; `None` leaves the list unchanged.+ pub fn with(mut self, kind: ToolRoot, path: Option<PathBuf>) -> Self {+ if let Some(path) = path {+ self.roots.push(ContainedRoot { path, kind });+ }+ self+ }++ pub fn iter(&self) -> impl Iterator<Item = &ContainedRoot> {+ self.roots.iter()+ }++ /// The first root that lexically contains `input` (absolute paths only).+ /// Decides prompting only; execution runs the symlink-aware resolver.+ pub fn lexical_root(&self, input: &str) -> Option<&ContainedRoot> {+ self.roots+ .iter()+ .find(|root| lexically_inside(&root.path, input))+ }+}+/// Lexically resolve `.` / `..` components without touching the filesystem./// `..` at the filesystem root clamps (stays at root); the caller's/// starts_with check then rejects anything that climbed out of the workspace.@@ -243,50 +292,61 @@ pub fn resolve_external_path(workspace_root: &Path, input: &str) -> Result<PathB}/// Resolve a tool path against the workspace root, falling back to the-/// session scratch root (D114). Relative paths always resolve against the-/// workspace; the scratch directory is addressed by absolute path only (the-/// model learns it from the system prompt / `PI_SCRATCH_DIR`). Both roots get-/// the same lexical + symlink containment defense.+/// session's contained roots in order (scratch per D114, visualizations).+/// Relative paths always resolve against the workspace; contained roots are+/// addressed by absolute path only (the model learns them from the system+/// prompt). Every root gets the same lexical + symlink containment defense.pub fn resolve_tool_path(workspace_root: &Path,- scratch_root: Option<&Path>,+ roots: &ContainedRoots,input: &str,) -> Result<(PathBuf, ToolRoot), String> {+ // A contained root is more specific than the workspace: when a workspace+ // happens to contain the data directory (for example `$HOME`), a path+ // spelled inside a contained root must still resolve against that root so+ // its own containment and write rules apply.+ if let Some(root) = roots.lexical_root(input) {+ return resolve_in_contained_root(root, input)+ .map(|path| (path, root.kind))+ .ok_or_else(|| "PATH_OUTSIDE_WORKSPACE".to_string());+ }let workspace_err = match resolve_in_workspace(workspace_root, input) {Ok(path) => return Ok((path, ToolRoot::Workspace)),Err(e) => e,};if Path::new(input).is_absolute() {- if let Some(scratch) = scratch_root {- if let Ok(path) = resolve_in_workspace(scratch, input) {- return Ok((path, ToolRoot::Scratch));- }- // The model addresses scratch with the exact spelling we- // advertised, which may differ from the canonical one (macOS- // /var vs /private/var, /tmp vs /private/tmp). Rewrite a literal- // scratch-root prefix to a relative path and resolve that — the- // full containment defense still runs.- let candidate = normalize_lexical(Path::new(input));- if let Ok(rel) = candidate.strip_prefix(normalize_lexical(scratch)) {- if let Ok(path) = resolve_in_workspace(scratch, &rel.to_string_lossy()) {- return Ok((path, ToolRoot::Scratch));- }+ for root in roots.iter() {+ if let Some(path) = resolve_in_contained_root(root, input) {+ return Ok((path, root.kind));}}}Err(workspace_err)}+fn resolve_in_contained_root(root: &ContainedRoot, input: &str) -> Option<PathBuf> {+ if let Ok(path) = resolve_in_workspace(&root.path, input) {+ return Some(path);+ }+ // The model addresses a root with the exact spelling we advertised, which+ // may differ from the canonical one (macOS /var vs /private/var, /tmp vs+ // /private/tmp). Rewrite a literal root prefix to a relative path and+ // resolve that — the full containment defense still runs.+ let candidate = normalize_lexical(Path::new(input));+ let rel = candidate.strip_prefix(normalize_lexical(&root.path)).ok()?;+ resolve_in_workspace(&root.path, &rel.to_string_lossy()).ok()+}+/// Resolve a tool path after the host has granted explicit outside-workspace-/// access for this call. Contained workspace and scratch paths keep their+/// access for this call. Workspace and contained-root paths keep their/// normal roots; only an otherwise rejected path becomes `External`.pub fn resolve_tool_path_with_external(workspace_root: &Path,- scratch_root: Option<&Path>,+ roots: &ContainedRoots,input: &str,allow_external: bool,) -> Result<(PathBuf, ToolRoot), String> {- match resolve_tool_path(workspace_root, scratch_root, input) {+ match resolve_tool_path(workspace_root, roots, input) {Ok(result) => Ok(result),Err(error) if allow_external && error == "PATH_OUTSIDE_WORKSPACE" => Ok((resolve_external_path(workspace_root, input)?,@@ -314,6 +374,10 @@ mod tests {use std::fs;use tempfile::tempdir;+ fn scratch_roots(scratch: &Path) -> ContainedRoots {+ ContainedRoots::scratch_only(Some(scratch))+ }+#[test]fn blocks_escape() {let dir = tempdir().unwrap();@@ -419,7 +483,8 @@ mod tests {fn tool_path_relative_resolves_to_workspace() {let ws = tempdir().unwrap();let scratch = tempdir().unwrap();- let (p, root) = resolve_tool_path(ws.path(), Some(scratch.path()), "notes.txt").unwrap();+ let (p, root) =+ resolve_tool_path(ws.path(), &scratch_roots(scratch.path()), "notes.txt").unwrap();assert_eq!(root, ToolRoot::Workspace);assert!(p.starts_with(simple_canonicalize(ws.path()).unwrap()));}@@ -429,8 +494,12 @@ mod tests {let ws = tempdir().unwrap();let scratch = tempdir().unwrap();let input = scratch.path().join("tmp.json");- let (p, root) =- resolve_tool_path(ws.path(), Some(scratch.path()), input.to_str().unwrap()).unwrap();+ let (p, root) = resolve_tool_path(+ ws.path(),+ &scratch_roots(scratch.path()),+ input.to_str().unwrap(),+ )+ .unwrap();assert_eq!(root, ToolRoot::Scratch);assert!(p.starts_with(simple_canonicalize(scratch.path()).unwrap()));}@@ -440,8 +509,12 @@ mod tests {let ws = tempdir().unwrap();let scratch = tempdir().unwrap();let input = scratch.path().join("a/../../evil.txt");- let err = resolve_tool_path(ws.path(), Some(scratch.path()), input.to_str().unwrap())- .unwrap_err();+ let err = resolve_tool_path(+ ws.path(),+ &scratch_roots(scratch.path()),+ input.to_str().unwrap(),+ )+ .unwrap_err();assert_eq!(err, "PATH_OUTSIDE_WORKSPACE");}@@ -453,8 +526,12 @@ mod tests {let outside = tempdir().unwrap();std::os::unix::fs::symlink(outside.path(), scratch.path().join("link")).unwrap();let input = scratch.path().join("link/new.txt");- let err = resolve_tool_path(ws.path(), Some(scratch.path()), input.to_str().unwrap())- .unwrap_err();+ let err = resolve_tool_path(+ ws.path(),+ &scratch_roots(scratch.path()),+ input.to_str().unwrap(),+ )+ .unwrap_err();assert_eq!(err, "PATH_OUTSIDE_WORKSPACE");}@@ -462,7 +539,8 @@ mod tests {fn tool_path_absolute_outside_both_roots_blocked() {let ws = tempdir().unwrap();let scratch = tempdir().unwrap();- let err = resolve_tool_path(ws.path(), Some(scratch.path()), "/etc/hosts").unwrap_err();+ let err =+ resolve_tool_path(ws.path(), &scratch_roots(scratch.path()), "/etc/hosts").unwrap_err();assert_eq!(err, "PATH_OUTSIDE_WORKSPACE");}@@ -473,9 +551,13 @@ mod tests {let input = outside.path().join("outside.txt");fs::write(&input, "outside").unwrap();- let (resolved, root) =- resolve_tool_path_with_external(ws.path(), None, input.to_str().unwrap(), true)- .unwrap();+ let (resolved, root) = resolve_tool_path_with_external(+ ws.path(),+ &ContainedRoots::new(),+ input.to_str().unwrap(),+ true,+ )+ .unwrap();assert_eq!(root, ToolRoot::External);assert_eq!(resolved, simple_canonicalize(&input).unwrap());}@@ -490,10 +572,11 @@ mod tests {let input = "../outside.txt";assert_eq!(- resolve_tool_path(&ws, None, input).unwrap_err(),+ resolve_tool_path(&ws, &ContainedRoots::new(), input).unwrap_err(),"PATH_OUTSIDE_WORKSPACE");- let (resolved, root) = resolve_tool_path_with_external(&ws, None, input, true).unwrap();+ let (resolved, root) =+ resolve_tool_path_with_external(&ws, &ContainedRoots::new(), input, true).unwrap();assert_eq!(root, ToolRoot::External);assert_eq!(resolved, simple_canonicalize(&outside).unwrap());}