From 68b54296e5fe5aa0095e1ffbc4c9fb8f7dc7e1ba Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 3 Dec 2026 06:04:28 +0100 Subject: [PATCH] fix(automation): bind a window request to the agent folders it was checked against A command with folders of its own now sends each window request as agents.call with those folders; the window runs it only while they are still its agent folders, so a Preferences change while the request is on its way can't let it run (or save) under other folders. Co-Authored-By: Claude Opus 5.5 --- apps/pdfcraft-cli/src/agents.rs | 9 +++++ apps/pdfcraft-cli/src/agents/tests.rs | 5 ++- crates/ui-egui/src/agents.rs | 47 ++++++++++++++++++++++++--- crates/ui-egui/src/app.rs | 2 ++ crates/ui-egui/src/control.rs | 8 +++++ crates/ui-egui/src/lib.rs | 3 ++ crates/ui-egui/tests/it/agents.rs | 23 +++++++++++++ docs/mcp.md | 4 ++- 8 files changed, 95 insertions(+), 6 deletions(-) diff --git a/apps/pdfcraft-cli/src/agents.rs b/apps/pdfcraft-cli/src/agents.rs index 79a73d6f01..da8a44a6da 100644 --- a/apps/pdfcraft-cli/src/agents.rs +++ b/apps/pdfcraft-cli/src/agents.rs @@ -475,6 +475,15 @@ impl Sessions for LiveSessions { let (_, method) = WINDOW_TOOLS.iter().find(|(tool, _)| *tool == name)?; Some(window_request(name, method, args).and_then(|(method, params)| { self.check_window_folders()?; + // With folders of its own, the request carries them: the window runs it only while + // they are still its agent folders. + let (method, params) = if self.has_command_folders() { + let path = |p: &Option| p.as_ref().map(|p| p.to_string_lossy().into_owned()); + let folders = json!({"read": path(&self.command_folders.read), "write": path(&self.command_folders.write)}); + ("agents.call".to_owned(), json!({"method": method, "params": params, "folders": folders})) + } else { + (method, params) + }; match self.live.resolve()? { Route::Window(window) => window_content(window.lock().unwrap_or_else(PoisonError::into_inner).call(&method, params)?), Route::Headless(_) => Err(format!( diff --git a/apps/pdfcraft-cli/src/agents/tests.rs b/apps/pdfcraft-cli/src/agents/tests.rs index 75a1cb0e18..1346ec0e93 100644 --- a/apps/pdfcraft-cli/src/agents/tests.rs +++ b/apps/pdfcraft-cli/src/agents/tests.rs @@ -198,8 +198,11 @@ fn the_commands_own_folders_are_not_filled_in_from_preferences() { // The same folders as the window's: the window enforces them itself. let mut same = sessions_with_roots(&dir, &folder, Some(&folder), Some(&folder)); - tool(&mut same, "ui_state", json!({})).unwrap(); + let reply = tool(&mut same, "ui_state", json!({})).unwrap(); assert_eq!(answered.load(Ordering::SeqCst), 1); + // Bound to the folders checked, which the window compares with its own when it runs it. + assert_eq!((reply["method"].as_str(), reply["params"]["method"].as_str()), (Some("agents.call"), Some("ui.state"))); + assert!(reply["params"]["folders"]["write"].as_str().is_some_and(|f| Path::new(f) == folder), "{reply}"); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/ui-egui/src/agents.rs b/crates/ui-egui/src/agents.rs index 028ba610ee..b1e5f5bfe8 100644 --- a/crates/ui-egui/src/agents.rs +++ b/crates/ui-egui/src/agents.rs @@ -176,14 +176,53 @@ pub(crate) fn sync(app: &mut PdfCraftApp, ctx: &egui::Context) { if !update.changed { return; } + app.agent_folders = None; app.agent_guard = Some(if link.status().port.is_none() { agent_scope::deny_all() } else { // Looked up only when something changed: the default folder is created on the way. let folders = agents.settings.folders_with(agents.default_folder.as_deref()); - (agents.guard_for)(&folders).unwrap_or_else(|e| { - link.note(LinkProblem::App(format!("Agents can't open or save files: {e}"))); - agent_scope::deny_all() - }) + match (agents.guard_for)(&folders) { + Ok(guard) => { + app.agent_folders = Some(folders); + guard + } + Err(e) => { + link.note(LinkProblem::App(format!("Agents can't open or save files: {e}"))); + agent_scope::deny_all() + } + } }); } + +/// `agents.call {method, params, folders: {read, write}}`: runs `method` only while the agent +/// folders the window holds requests to are `folders`. `pdfcraft-cli mcp` started with folders of +/// its own checked that they are the window's; this binds the request to that check, so a change +/// in Preferences while the request is on its way can't let it run under other folders. +pub const BOUND_CALL: &str = "agents.call"; + +/// The method and params of an `agents.call` whose folders still hold; `Err` says why not. +pub(crate) fn bound_request(app: &PdfCraftApp, params: &Value) -> Result<(String, Value), String> { + let method = params.get("method").and_then(Value::as_str).ok_or("agents.call needs a method")?; + if method == BOUND_CALL { + return Err("agents.call can't call itself".into()); + } + let folder = |key: &str| match params.get("folders").and_then(|f| f.get(key)) { + Some(Value::String(path)) => Ok(Some(PathBuf::from(path))), + Some(Value::Null) => Ok(None), + _ => Err(format!("agents.call needs folders.{key}: a path or null")), + }; + let (read, write) = (folder("read")?, folder("write")?); + let same = |a: &Option, b: &Option| match (a, b) { + (Some(a), Some(b)) => std::fs::canonicalize(a).ok().is_some_and(|a| std::fs::canonicalize(b).ok().is_some_and(|b| a == b)), + (None, None) => true, + _ => false, + }; + let held = app.agent_folders.as_ref().is_some_and(|now| same(&read, &now.read) && same(&write, &now.write)); + if !held { + return Err( + "the agent folders in PdfCraft's Preferences › AI Integrations changed; nothing was done: check agent_folders and try again".into() + ); + } + Ok((method.to_owned(), params.get("params").cloned().unwrap_or_else(|| json!({})))) +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 27417fa134..bccb82049d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -496,6 +496,8 @@ impl PdfCraftApp { #[cfg(not(target_arch = "wasm32"))] agents: None, agent_guard: None, + #[cfg(not(target_arch = "wasm32"))] + agent_folders: None, agent_input: None, bookmark_clipboard: None, word_count_options: Default::default(), diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 94376d7f55..2503218d06 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -130,6 +130,14 @@ impl PdfCraftApp { /// The reply to one request: the framework's methods, then the app's. fn answer(&mut self, ctx: &egui::Context, req: &ControlRequest) -> Reply { let (method, params) = (req.method.as_str(), &req.params); + // An agent's request bound to the agent folders it was checked against (`crate::agents`). + #[cfg(not(target_arch = "wasm32"))] + if method == crate::agents::BOUND_CALL { + return match crate::agents::bound_request(self, params) { + Ok((method, params)) => self.answer(ctx, &ControlRequest::new(method, params).0), + Err(e) => Reply::from_result(Err(e)), + }; + } let host = WindowHost::of(ctx); if let Some(queued) = input_method(method, params, &host, ViewportId::ROOT, &|_, _| None) { return match queued { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c1d4af87aa..6251957002 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -716,6 +716,9 @@ pub struct PdfCraftApp { /// The agent folders the agents link's requests run with (`None`: the control channel is the /// launch options' and runs unconfined, as before). agent_guard: Option, + /// The agent folders `agent_guard` holds requests to (`agents.call` checks them). + #[cfg(not(target_arch = "wasm32"))] + agent_folders: Option, /// The agent folders an agent's request leaves in force while the input it queued is handled. agent_input: Option, /// Bookmarks copied or cut in the Bookmarks panel, with their subtrees, ready to paste into diff --git a/crates/ui-egui/tests/it/agents.rs b/crates/ui-egui/tests/it/agents.rs index 1f41f8fd97..5224dcc8cd 100644 --- a/crates/ui-egui/tests/it/agents.rs +++ b/crates/ui-egui/tests/it/agents.rs @@ -142,3 +142,26 @@ fn agent_requests_stay_in_the_agent_folders() { assert!(refused.contains("outside the agent folders"), "{refused}"); let _ = std::fs::remove_dir_all(base); } + +// A request bound to the agent folders it was checked against runs only while they are still the +// window's folders, so a Preferences change while it is on its way can't widen it. +#[test] +fn a_bound_request_runs_only_under_the_folders_it_was_checked_against() { + let base = temp("bound"); + let (dir, folder, other) = (base.join("settings"), base.join("agents"), base.join("other")); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::create_dir_all(&other).unwrap(); + let mut h = window(&dir, &folder, Arc::new(AtomicBool::new(true))); + assert!(frames_until(&mut h, || read_connection(&dir).ok().flatten().is_some())); + let client = connect(&dir); + let bound = |folders: &Path| { + let path = folders.to_string_lossy().into_owned(); + json!({"method": "ui.state", "params": {}, "folders": {"read": path, "write": path}}) + }; + + let state = agent_call(&mut h, &client, "agents.call", bound(&folder)).unwrap(); + assert_eq!(state["agents"]["allowed"], true, "the checked folders hold: it ran"); + let refused = agent_call(&mut h, &client, "agents.call", bound(&other)).unwrap_err(); + assert!(refused.contains("changed"), "{refused}"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/docs/mcp.md b/docs/mcp.md index 6374326ee4..4dbc97ec2f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -166,7 +166,9 @@ writes no client configuration of its own. The switch counts while the suite's ` folders as a pair, as given: a root left out grants none of its access, rather than falling back to Preferences. The window holds every agent request to its own agent folders (a Save writes the document's own path), so with folders of its own that differ from those, the - command's window tools are off and say so; the document tools still work. + command's window tools are off and say so; the document tools still work. With the same + folders, each window request carries them (`agents.call`), and the window runs it only if + they are still its agent folders when it gets there. - While the switch doesn't name PdfCraft, `mcp` works as before: no window, and only the folders the command was given. `--headless` always works that way.