Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(agent-runtime): cancel pending tools safely
vastsa9538222594b6
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex 4f86af66b..edc345eb3 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -14,7 +14,7 @@ use std::io::{self, BufRead, BufReader as StdBufReader, Read, Write};use std::path::{Path, PathBuf};use std::sync::Arc;use std::thread;-use std::time::Duration;+use std::time::{Duration, Instant};use anyhow::{anyhow, Result};use serde::{Deserialize, Serialize};@@ -1532,7 +1532,7 @@ impl crate::plugins::InstallObserver for RpcInstallObserver {}}-async fn wait_for_bash_cancellation(+async fn wait_for_tool_cancellation(receiver: &mut Option<tokio::sync::watch::Receiver<bool>>,) -> bool {let Some(receiver) = receiver.as_mut() else {@@ -1551,7 +1551,7 @@ async fn wait_for_bash_cancellation(}}-fn bash_cancellation_requested(receiver: &Option<tokio::sync::watch::Receiver<bool>>) -> bool {+fn tool_cancellation_requested(receiver: &Option<tokio::sync::watch::Receiver<bool>>) -> bool {receiver.as_ref().is_some_and(|receiver| *receiver.borrow())}@@ -1560,11 +1560,29 @@ async fn clear_bash_cancellation(state: &Arc<Mutex<AppState>>, p: &ToolsExecutePst.clear_bash_cancellation(&p.session_id, &p.tool_call_id);}+async fn clear_tool_cancellation(state: &Arc<Mutex<AppState>>, p: &ToolsExecuteParams) {+ let mut st = state.lock().await;+ st.clear_tool_cancellation(&p.session_id, &p.tool_call_id, &p.tool_name);+}+async fn cancel_pending_permission(state: &Arc<Mutex<AppState>>, p: &ToolsExecuteParams) -> bool {let mut st = state.lock().await;st.cancel_pending_permission(&p.session_id, &p.tool_call_id)}+fn tool_aborted_result(p: &ToolsExecuteParams, started: Instant) -> tools::ToolsExecuteResult {+ tools::ToolsExecuteResult {+ tool_call_id: p.tool_call_id.clone(),+ ok: false,+ is_error: Some(true),+ content: json!({ "error": "tool aborted", "code": "TOOL_ABORTED" }),+ duration_ms: started.elapsed().as_millis() as u64,+ denied: None,+ error_code: Some("TOOL_ABORTED".into()),+ command_shell_id: p.expected_command_shell_id.clone(),+ }+}+/// Dispatch a `plugin_*` tool to the desktop runner (Electron main), which/// executes the plugin JS and answers via `plugins.resolveExecution`.async fn execute_plugin_tool(@@ -3940,31 +3958,40 @@ async fn handle_request(};// Register before permission evaluation so tools.abort can cancel- // an approval wait as well as an already-spawned process.- let cancellation_receiver = if remote_workspace.is_some()- || (matches!(p.tool_name.as_str(), "Bash" | "GenerateImages")- // A background Bash task is detached from the turn: it- // never joins the per-tool-call cancellation registry, so- // tools.abort / agent.abort cannot kill it.- && !p.run_in_background)+ // an approval wait even when the tool does not own a process.+ // Bash and image generation retain their existing process registry;+ // all other calls use a typed registry to avoid cross-tool ID reuse.+ let cancellation_receiver = if matches!(p.tool_name.as_str(), "Bash" | "GenerateImages"){+ // Background Bash tasks are detached from the turn and must+ // outlive a later Stop request.+ if remote_workspace.is_none() && p.tool_name == "Bash" && p.run_in_background {+ None+ } else {+ let mut st = state.lock().await;+ match st.register_bash_cancellation(&p.session_id, &p.tool_call_id) {+ Ok(receiver) => Some(receiver),+ Err(error_code) => {+ let result = shell_failure_result(+ &p,+ &error_code,+ "another Bash call is already active for this tool call ID",+ command_shell_id.clone(),+ call_started,+ );+ return serde_json::to_value(result)+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"));+ }+ }+ }+ } else {let mut st = state.lock().await;- match st.register_bash_cancellation(&p.session_id, &p.tool_call_id) {+ match st.register_tool_cancellation(&p.session_id, &p.tool_call_id, &p.tool_name) {Ok(receiver) => Some(receiver),Err(error_code) => {- let result = shell_failure_result(- &p,- &error_code,- "another Bash call is already active for this tool call ID",- command_shell_id.clone(),- call_started,- );- return serde_json::to_value(result)- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"));+ return Err(rpc_err(1008, "tool already executing", &error_code));}}- } else {- None};let outcome: Result<Value, JsonRpcError> = async {@@ -4133,7 +4160,7 @@ async fn handle_request(let prompted = request_opt.is_some();let mut permission_cancellation = cancellation_receiver.clone();- let mut cancelled = bash_cancellation_requested(&permission_cancellation);+ let mut cancelled = tool_cancellation_requested(&permission_cancellation);if cancelled {let _ = cancel_pending_permission(&state, &p).await;}@@ -4164,7 +4191,7 @@ async fn handle_request(let final_decision = if cancelled {PermissionDecision::Deny} else if let Some(d) = auto_decision {- cancelled = bash_cancellation_requested(&permission_cancellation);+ cancelled = tool_cancellation_requested(&permission_cancellation);if cancelled {let _ = cancel_pending_permission(&state, &p).await;PermissionDecision::Deny@@ -4177,7 +4204,7 @@ async fn handle_request(Ok(d) => d,_ => PermissionDecision::Deny,},- _ = wait_for_bash_cancellation(&mut permission_cancellation) => {+ _ = wait_for_tool_cancellation(&mut permission_cancellation) => {let _ = cancel_pending_permission(&state, &p).await;cancelled = true;PermissionDecision::Deny@@ -4186,7 +4213,7 @@ async fn handle_request(} else {PermissionDecision::Deny};- cancelled = cancelled || bash_cancellation_requested(&permission_cancellation);+ cancelled = cancelled || tool_cancellation_requested(&permission_cancellation);if cancelled {let _ = cancel_pending_permission(&state, &p).await;}@@ -4276,12 +4303,21 @@ async fn handle_request();(st.tool_budget.clone(), own)};- let admitted = if own_worktree {- tool_budget- .acquire_in_own_worktree(&p.session_id, &p.tool_name)- .await- } else {- tool_budget.acquire(&p.session_id, &p.tool_name).await+ let mut admission_cancellation = cancellation_receiver.clone();+ let admitted = tokio::select! {+ result = async {+ if own_worktree {+ tool_budget+ .acquire_in_own_worktree(&p.session_id, &p.tool_name)+ .await+ } else {+ tool_budget.acquire(&p.session_id, &p.tool_name).await+ }+ } => result,+ _ = wait_for_tool_cancellation(&mut admission_cancellation) => {+ return serde_json::to_value(tool_aborted_result(&p, call_started))+ .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"));+ }};let _tool_permit = match admitted {Ok(permit) => permit,@@ -4350,6 +4386,13 @@ async fn handle_request(None})};+ if tool_cancellation_requested(&cancellation_receiver) {+ if let Some(pending) = pending_review {+ review::discard_change(pending);+ }+ return serde_json::to_value(tool_aborted_result(&p, call_started))+ .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"));+ }let mut bash_options = None;if p.tool_name == "Bash" && remote_workspace.is_none() {let (shell_id, cancellation) = {@@ -4436,7 +4479,7 @@ async fn handle_request().await} else {- tools::execute_tool_with_path_access(+ let execute = tools::execute_tool_with_path_access(ws_path.as_deref(),scratch_path.as_deref(),&p.tool_name,@@ -4447,8 +4490,18 @@ async fn handle_request(allow_external_paths: external_path_permission,hashline: Some(hashline_ctx),},- )- .await+ );+ if matches!(p.tool_name.as_str(), "Read" | "Glob" | "Grep") {+ let mut read_cancellation = cancellation_receiver.clone();+ tokio::select! {+ result = execute => result,+ _ = wait_for_tool_cancellation(&mut read_cancellation) => {+ tool_aborted_result(&p, call_started)+ }+ }+ } else {+ execute.await+ }};result.tool_call_id = p.tool_call_id.clone();@@ -4551,6 +4604,7 @@ async fn handle_request(}.await;clear_bash_cancellation(&state, &p).await;+ clear_tool_cancellation(&state, &p).await;outcome}@@ -4563,9 +4617,21 @@ async fn handle_request(.get("toolCallId").and_then(|value| value.as_str()).ok_or_else(|| rpc_err(1002, "toolCallId required", "INVALID_PARAMS"))?;+ let tool_name = params.get("toolName").and_then(Value::as_str);let mut st = state.lock().await;let permission_found = st.cancel_pending_permission(session_id, tool_call_id);- let (process_found, queued) = st.abort_or_queue_bash(session_id, tool_call_id);+ let (cancellation_found, queued) = match tool_name {+ Some("Bash" | "GenerateImages") => st.abort_or_queue_bash(session_id, tool_call_id),+ Some(name) => st.abort_or_queue_tool(session_id, tool_call_id, name),+ None => {+ let active_tool = st.abort_active_tool(session_id, tool_call_id);+ if active_tool {+ (true, false)+ } else {+ st.abort_or_queue_bash(session_id, tool_call_id)+ }+ }+ };let remote = match sessions::session_summary(&st.db, session_id).map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?{@@ -4579,7 +4645,7 @@ async fn handle_request(json!({ "sessionId": session_id, "toolCallId": tool_call_id }),);}- let found = process_found || permission_found;+ let found = cancellation_found || permission_found;Ok(json!({"ok": true,"found": found,@@ -7178,6 +7244,25 @@ mod tests {panic!("Bash cancellation was not registered");}+ async fn wait_for_tool_registration(+ state: &Arc<Mutex<AppState>>,+ session_id: &str,+ tool_call_id: &str,+ tool_name: &str,+ ) {+ for _ in 0..500 {+ if state.lock().await.active_tool_cancellations.contains_key(&(+ session_id.to_string(),+ tool_call_id.to_string(),+ tool_name.to_string(),+ )) {+ return;+ }+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;+ }+ panic!("{tool_name} cancellation was not registered");+ }+async fn assert_bash_registry_empty(state: &Arc<Mutex<AppState>>) {assert!(state.lock().await.active_bash_cancellations.is_empty());}@@ -8560,6 +8645,105 @@ mod tests {assert_bash_registry_empty(&state).await;}+ #[tokio::test]+ async fn tools_abort_cancels_a_pending_write_approval_before_it_can_mutate_files() {+ let data_dir = tempfile::tempdir().unwrap();+ let project = data_dir.path().join("project");+ fs::create_dir_all(&project).unwrap();+ let destination = project.join("must-not-exist.txt");+ let destination_for_tool = destination.to_string_lossy().into_owned();+ let mut app_state = AppState::open(data_dir.path()).unwrap();+ app_state.handshook = true;+ let session = sessions::create_session(+ &app_state.db,+ Some("Abort pending Write".into()),+ Some("agent".into()),+ None,+ None,+ Some(project.to_string_lossy().into_owned()),+ )+ .unwrap();+ sessions::configure_session_with_thinking(+ &app_state.db,+ &session.id,+ "agent",+ None,+ None,+ None,+ Some("ask"),+ )+ .unwrap();+ let state = Arc::new(Mutex::new(app_state));+ let (tx, mut rx) = mpsc::unbounded_channel();+ let pending_state = state.clone();+ let pending_session_id = session.id.clone();+ let pending = tokio::spawn(async move {+ handle_request(+ pending_state,+ "tools.execute",+ json!({+ "sessionId": pending_session_id,+ "toolCallId": "write-stop-pending-approval",+ "toolName": "Write",+ "args": {+ "path": destination_for_tool,+ "content": "must not be written"+ },+ "mode": "agent"+ }),+ tx,+ )+ .await+ });+ wait_for_tool_registration(&state, &session.id, "write-stop-pending-approval", "Write")+ .await;+ let permission: Value = serde_json::from_str(+ &tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())+ .await+ .unwrap()+ .unwrap(),+ )+ .unwrap();+ assert_eq!(permission["method"], "permissions.request");++ let aborted = handle_request(+ state.clone(),+ "tools.abort",+ json!({+ "sessionId": session.id,+ "toolCallId": "write-stop-pending-approval",+ "toolName": "Write"+ }),+ mpsc::unbounded_channel().0,+ )+ .await+ .unwrap();+ assert_eq!(aborted["found"], true);+ let result = tokio::time::timeout(std::time::Duration::from_secs(2), pending)+ .await+ .unwrap()+ .unwrap()+ .unwrap();+ assert_eq!(result["errorCode"], "TOOL_ABORTED");+ assert!(!destination.exists());+ assert_bash_registry_empty(&state).await;+ assert!(state.lock().await.active_tool_cancellations.is_empty());+ assert!(state.lock().await.pending_tool_aborts.is_empty());++ let late_resolution = handle_request(+ state,+ "permissions.resolve",+ json!({+ "requestId": permission["params"]["requestId"],+ "decision": "allow-once"+ }),+ mpsc::unbounded_channel().0,+ )+ .await+ .unwrap_err();+ assert_eq!(late_resolution.data.unwrap()["errorCode"], "NOT_FOUND");+ }+#[tokio::test]async fn tools_abort_during_permission_removes_the_pending_request() {let Some(shell_id) = available_test_shell_id() else {diff --git a/crates/host-core/src/rpc/remote_tools.rs b/crates/host-core/src/rpc/remote_tools.rsindex 19f461eed..b9314bfcb 100644--- a/crates/host-core/src/rpc/remote_tools.rs+++ b/crates/host-core/src/rpc/remote_tools.rs@@ -122,7 +122,7 @@ pub(super) async fn execute_remote_tool(started,);}- if bash_cancellation_requested(&cancellation) {+ if tool_cancellation_requested(&cancellation) {return failure(p, "TOOL_ABORTED", "tool aborted", started);}let request_id = uuid::Uuid::new_v4().to_string();@@ -149,7 +149,7 @@ pub(super) async fn execute_remote_tool(outcome = tokio::time::timeout(Duration::from_millis(timeout_ms.saturating_add(15_000)), receiver) => match outcome {Ok(Ok(value)) => Ok(value), _ => Err("TOOL_TIMEOUT"),},- _ = wait_for_bash_cancellation(&mut cancellation) => Err("TOOL_ABORTED"),+ _ = wait_for_tool_cancellation(&mut cancellation) => Err("TOOL_ABORTED"),};state.lock().await.remote_execs.remove(&request_id);match outcome {@@ -322,7 +322,7 @@ pub(super) async fn handle(.map_err(|code| rpc_err(1008, "tool already executing", &code))?;(Some(cancellation), st.hashline.clone(), shell)};- if bash_cancellation_requested(&cancellation) {+ if tool_cancellation_requested(&cancellation) {state.lock().await@@ -356,7 +356,7 @@ pub(super) async fn handle(};let mut result = tokio::select! {result = tools::execute_tool_with_path_access(Some(&root),None,&p.tool_name,&p.args,options) => result,- _ = wait_for_bash_cancellation(&mut cancellation) => failure(&p,"TOOL_ABORTED","tool aborted",started),+ _ = wait_for_tool_cancellation(&mut cancellation) => failure(&p,"TOOL_ABORTED","tool aborted",started),};result.tool_call_id = p.tool_call_id.clone();statediff --git a/crates/host-core/src/rpc/remote_tools_tests.rs b/crates/host-core/src/rpc/remote_tools_tests.rsindex 6cde9950c..6af8d2b48 100644--- a/crates/host-core/src/rpc/remote_tools_tests.rs+++ b/crates/host-core/src/rpc/remote_tools_tests.rs@@ -197,11 +197,13 @@ async fn denied_remote_write_and_cancelled_read_never_run_locally() {handle_request(state.clone(),"tools.abort",- json!({"sessionId":id,"toolCallId":"read-b"}),+ json!({"sessionId":id,"toolCallId":"read-b","toolName":"Read"}),tx.clone(),).await.unwrap();+ let abort_notification: Value = serde_json::from_str(&rx.recv().await.unwrap()).unwrap();+ assert_eq!(abort_notification["method"], "tools.remoteAbort");assert_eq!(read.await.unwrap().unwrap()["errorCode"], "TOOL_ABORTED");assert!(state.lock().await.remote_execs.is_empty());}diff --git a/crates/host-core/src/state.rs b/crates/host-core/src/state.rsindex 56d473491..fe166c336 100644--- a/crates/host-core/src/state.rs+++ b/crates/host-core/src/state.rs@@ -19,6 +19,8 @@ pub const PROTOCOL_VERSION: u32 = 11;pub const HOST_VERSION: &str = env!("CARGO_PKG_VERSION");const BASH_ABORT_TOMBSTONE_TTL: Duration = Duration::from_secs(60);const MAX_BASH_ABORT_TOMBSTONES: usize = 1024;+const TOOL_ABORT_TOMBSTONE_TTL: Duration = Duration::from_secs(60);+const MAX_TOOL_ABORT_TOMBSTONES: usize = 1024;const PLUGIN_IMPORT_RATE_WINDOW: Duration = Duration::from_secs(60);const PLUGIN_IMPORT_RATE_LIMIT: usize = 10;const PLUGIN_BATCH_IMPORT_RATE_LIMIT: usize = 5;@@ -66,6 +68,11 @@ pub struct AppState {/// (session_id, tool_call_id) -> cancellation signal for an active Bash/// process. The signal is removed by the execution owner in all outcomes.pub active_bash_cancellations: HashMap<(String, String), tokio::sync::watch::Sender<bool>>,+ /// (session_id, tool_call_id, tool_name) -> cancellation signal for+ /// in-flight non-process tools, including permission waits and remote+ /// workspace calls.+ pub(crate) active_tool_cancellations:+ HashMap<(String, String, String), tokio::sync::watch::Sender<bool>>,/// request_id -> (session_id, tool_call_id) for permission requests that/// are currently awaited by an RPC task. PermissionManager intentionally/// keeps its pending map private, so AppState tracks the ownership needed@@ -75,6 +82,10 @@ pub struct AppState {/// separate tasks. A short-lived tombstone makes the later request start/// already cancelled instead of executing after Stop was acknowledged.pending_bash_aborts: HashMap<(String, String), Instant>,+ /// Typed aborts that race ahead of a non-process tools.execute request.+ /// Including the tool name prevents an old abort from cancelling a later+ /// tool call that happens to reuse the same id for another tool.+ pub(crate) pending_tool_aborts: HashMap<(String, String, String), Instant>,/// Session-scoped Read/Edit snapshot store (ADR 0087). Interior mutex so/// tool execution does not hold the AppState lock.pub hashline: crate::tools::HashlineStore,@@ -153,8 +164,10 @@ impl AppState {plugin_delete_rates: HashMap::new(),tool_budget: ToolBudget::new(),active_bash_cancellations: HashMap::new(),+ active_tool_cancellations: HashMap::new(),pending_permissions: HashMap::new(),pending_bash_aborts: HashMap::new(),+ pending_tool_aborts: HashMap::new(),hashline: crate::tools::HashlineStore::new(),})}@@ -295,12 +308,105 @@ impl AppState {self.pending_bash_aborts.remove(&key);}+ fn prune_tool_abort_tombstones(&mut self) {+ self.pending_tool_aborts+ .retain(|_, requested_at| requested_at.elapsed() < TOOL_ABORT_TOMBSTONE_TTL);+ while self.pending_tool_aborts.len() > MAX_TOOL_ABORT_TOMBSTONES {+ let Some(oldest) = self+ .pending_tool_aborts+ .iter()+ .min_by_key(|(_, requested_at)| **requested_at)+ .map(|(key, _)| key.clone())+ else {+ break;+ };+ self.pending_tool_aborts.remove(&oldest);+ }+ }++ pub fn register_tool_cancellation(+ &mut self,+ session_id: &str,+ tool_call_id: &str,+ tool_name: &str,+ ) -> Result<tokio::sync::watch::Receiver<bool>, String> {+ if self.shutting_down {+ return Err("HOST_SHUTTING_DOWN".into());+ }+ self.prune_tool_abort_tombstones();+ let key = (+ session_id.to_string(),+ tool_call_id.to_string(),+ tool_name.to_string(),+ );+ if self.active_tool_cancellations.contains_key(&key) {+ return Err("TOOL_BUSY".into());+ }+ let initially_aborted = self.pending_tool_aborts.remove(&key).is_some();+ let (sender, receiver) = tokio::sync::watch::channel(initially_aborted);+ self.active_tool_cancellations.insert(key, sender);+ Ok(receiver)+ }++ pub fn abort_or_queue_tool(+ &mut self,+ session_id: &str,+ tool_call_id: &str,+ tool_name: &str,+ ) -> (bool, bool) {+ self.prune_tool_abort_tombstones();+ let key = (+ session_id.to_string(),+ tool_call_id.to_string(),+ tool_name.to_string(),+ );+ let active = self+ .active_tool_cancellations+ .get(&key)+ .is_some_and(|sender| sender.send(true).is_ok());+ if active {+ (true, false)+ } else {+ self.pending_tool_aborts.insert(key, Instant::now());+ (false, true)+ }+ }++ pub fn abort_active_tool(&mut self, session_id: &str, tool_call_id: &str) -> bool {+ self.active_tool_cancellations+ .iter()+ .find(|((active_session, active_call, _), _)| {+ active_session == session_id && active_call == tool_call_id+ })+ .is_some_and(|(_, sender)| sender.send(true).is_ok())+ }++ pub fn clear_tool_cancellation(+ &mut self,+ session_id: &str,+ tool_call_id: &str,+ tool_name: &str,+ ) {+ let key = (+ session_id.to_string(),+ tool_call_id.to_string(),+ tool_name.to_string(),+ );+ self.active_tool_cancellations.remove(&key);+ self.pending_tool_aborts.remove(&key);+ }+pub fn shutdown(&mut self) {self.shutting_down = true;for sender in self.active_bash_cancellations.values() {let _ = sender.send(true);}self.active_bash_cancellations.clear();+ for sender in self.active_tool_cancellations.values() {+ let _ = sender.send(true);+ }+ self.active_tool_cancellations.clear();+ self.pending_tool_aborts.clear();// Chat-started background tasks follow the application: signal every// running supervisor so its process tree is terminated and reaped.crate::background_tasks::stop_all_running_sync(&self.background_tasks);@@ -344,18 +450,24 @@ mod tests {let mut cancellation = state.register_bash_cancellation("session-1", "tool-call-2").unwrap();+ let mut tool_cancellation = state+ .register_tool_cancellation("session-1", "tool-call-4", "Write")+ .unwrap();state.shutdown();assert!(state.pending_permissions.is_empty());assert!(state.active_bash_cancellations.is_empty());assert!(state.pending_bash_aborts.is_empty());+ assert!(state.active_tool_cancellations.is_empty());+ assert!(state.pending_tool_aborts.is_empty());assert!(state.shutting_down);assert!(matches!(state.register_bash_cancellation("session-1", "tool-call-3"),Err(error) if error == "HOST_SHUTTING_DOWN"));assert!(*cancellation.borrow_and_update());+ assert!(*tool_cancellation.borrow_and_update());assert_eq!(state.permissions.resolve(&request.request_id,@@ -365,6 +477,28 @@ mod tests {);}+ #[test]+ fn tool_abort_tombstones_are_scoped_to_the_tool_name() {+ let data_dir = tempfile::tempdir().unwrap();+ let mut state = AppState::open(data_dir.path()).unwrap();+ let mut write = state+ .register_tool_cancellation("session-1", "same-id", "Write")+ .unwrap();++ assert_eq!(+ state.abort_or_queue_tool("session-1", "same-id", "Edit"),+ (false, true)+ );+ assert!(!*write.borrow_and_update());+ state.clear_tool_cancellation("session-1", "same-id", "Write");++ let edit = state+ .register_tool_cancellation("session-1", "same-id", "Edit")+ .unwrap();+ assert!(*edit.borrow());+ assert!(state.pending_tool_aborts.is_empty());+ }+#[test]fn plugin_session_rate_limits_are_per_plugin_and_per_operation() {let data_dir = tempfile::tempdir().unwrap();diff --git a/docs/adr/tool-abort-abandons-host-call.md b/docs/adr/tool-abort-abandons-host-call.mdindex c2c8e5ca7..b31d0c090 100644--- a/docs/adr/tool-abort-abandons-host-call.md+++ b/docs/adr/tool-abort-abandons-host-call.md@@ -1,7 +1,7 @@-# ADR: A user stop ends the turn even when the running tool cannot be cancelled+# ADR: A user stop preserves tool side-effect boundaries- Status: Accepted for implementation-- Date: 2026-10-20+- Date: 2026-10-20 (amended 2026-10-23)- Issues: #1767- Amends: spec 03-runtime/03-tools-and-permissions.md §3@@ -16,29 +16,40 @@ single long call held the turn, and the session, hostage: one report measured a`Grep` that ran 21m39s after the user clicked Stop six times, with the abortapplying in the same millisecond the tool finally returned.+The fix must avoid telling the user that a turn stopped while a pending+permission can still be approved or a mutating extension call is still running.Three facts constrain the fix:-1. `tools.abort` only cancels what host-core can cancel: it clears a pending- approval and kills a `Bash` / `GenerateImages` process. Every other tool runs- to completion inside the Rust host whatever the runtime sends.-2. A `tools.abort` for a tool call id that has no active cancellation registers- a 60s tombstone in `pending_bash_aborts`, which a later `Bash` reusing that- id would inherit as an immediate kill.+1. Host cancellation can close a pending permission and remote calls. Bash and+ image generation also have process cancellation. Local file writes and+ desktop-dispatched MCP/plugin calls cannot be safely abandoned after their+ operation has started.+2. Bash process aborts retain their short-lived early-arrival tombstones. Other+ tool aborts use a separate registry keyed by session, call id, and tool name,+ so a delayed abort cannot affect a different tool that reuses the call id.3. `TOOL_ABORTED` already means "the tool was cancelled by a user stop or a turnabort before it finished" (spec 03-runtime/08-error-codes.md), so the runtimemay report that outcome without host cooperation.## Decision-The abort listener now applies to every tool. For `Bash` and `GenerateImages` it-keeps sending `tools.abort` and waits a bounded grace window (10s) for the host-to return the output it collected before the kill. For every other tool it stops-waiting the moment the signal fires, without sending `tools.abort`, and the call-rejects with `TOOL_ABORTED`.+The runtime sends typed `tools.abort` requests for in-flight tools. Host-core+registers cancellation before permission evaluation, so stopping a pending+approval or queued tool prevents it from starting. Local `Read`, `Glob`, and+`Grep` calls may end the runtime's wait immediately because they are read-only;+the host also observes cancellation and discards their result. The blocking+filesystem worker may continue until it returns, but it cannot mutate files.-In both cases the wait is a `Promise.race` against the execute call. Losing the-race abandons the wait, not the host call: the orphaned `tools.execute` settles-on its own, its result is discarded, and the runtime never surfaces it.+For `Bash` and `GenerateImages`, the runtime waits a bounded 10s grace window+for the host to return output collected before process termination. For+mutating, MCP, and plugin calls, the runtime waits for the host result after+requesting cancellation. A pending permission is cancelled; an operation that+already started is not reported as stopped until its result arrives.++Read-only and process-backed tools race their execution against cancellation.+For a read-only local filesystem call, the Rust blocking worker may outlive the+RPC, but its result is discarded. Mutating and desktop-dispatched tools are not+locally abandoned while active.The runtime also drives the tools from `abort()` itself, not only from thesignal each tool was handed. `abort()` walks the in-flight tool calls and runs@@ -52,29 +63,20 @@ alive minutes later.## Consequences-- Stop always ends the turn, so a stuck tool can no longer block new turns,- compaction, or session switching.-- A stop releases every in-flight tool, including one whose own abort signal- never fired, so the stop RPC always returns and the renderer always leaves- "processing".-- A non-cancellable tool keeps consuming host resources until it finishes. That- is honest residual work, not a stuck UI, and it is why the durable fix stays- with host-core: teach `tools.execute` an abort token so `Grep` and friends can- actually be cancelled.-- Abandoning a call means the runtime can no longer observe its result. A retry- must carry a fresh tool call id: reusing the abandoned id would race a second- execution against the first and, for `Bash`, could pick up a cancellation- tombstone meant for the abandoned call. This is also why non-cancellable tools- do not send `tools.abort` — the RPC cannot help them, and the tombstone it- leaves behind can only hurt.+- A long-running read-only tool no longer holds the turn open after Stop, while+ pending permission prompts and admission waits are cancelled at the host.+- Local filesystem workers and already-started extension operations may still+ consume resources until they return. Mutating and extension results remain+ observable before the runtime reports the turn settled.+- A new turn uses distinct tool call ids. Typed abort records also prevent an+ early abort for one tool name from being inherited by another tool.- Progress output for an abandoned call stops at the moment of the stop.## Alternatives-- **Send `tools.abort` for every tool.** Cancels pending approvals for- non-cancellable tools, but leaves a 60s tombstone per aborted call that a- later `Bash` could inherit. Rejected as a side effect with no benefit for the- in-flight call.+- **Locally abandon every tool.** Could report a stopped turn while a pending+ `Write` approval is later accepted or an already-started plugin/MCP action+ continues. Rejected because it hides side effects.- **Only arm a grace timer on abort (no race for cancellable tools).** Simpler,but leaves every non-cancellable tool waiting the full window and still keepsthe turn blocked for that window.diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.mdindex 5aac0a098..5cc4eddff 100644--- a/docs/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/spec/03-runtime/03-tools-and-permissions.md@@ -118,17 +118,19 @@ result. Options may be plain strings or `{ label, description? }` objects; theselected label remains the answer value. Stopping the turn resolves outstandingquestions as skipped.-A stop ends the turn even when the running tool cannot be cancelled (ADR-tool-abort-abandons-host-call). `Bash` and `GenerateImages` are cancelled through-`tools.abort`, and the runtime waits a bounded 10s grace window for the host to-return the output it collected before the kill. Every other tool has no-host-side cancellation: the runtime stops waiting the moment the signal fires,-returns `TOOL_ABORTED`, and leaves the host call to settle on its own with its-result discarded. Abandoned calls keep consuming host resources until they-finish, and a retry must carry a fresh tool call id. The stop releases the-in-flight tools directly as well, so it still ends the turn when a tool's own-abort signal never fires; the stop RPC must return even in that case, because-the renderer waits for it before it leaves the running state.+A stop sends a typed `tools.abort` request for each in-flight call (ADR+tool-abort-abandons-host-call). Host-core registers cancellation before+permission evaluation, so a pending approval or queued admission is cancelled+instead of starting after Stop. `Bash` and `GenerateImages` use the existing+process cancellation path; the runtime waits up to 10s for the host to return+output collected before termination. Local `Read`, `Glob`, and `Grep` calls may+end the runtime's wait immediately and return `TOOL_ABORTED`; their results are+discarded. A blocking filesystem worker may continue until it returns, but+these tools do not mutate the workspace. For a mutating, MCP, or plugin call+that has already started, the runtime waits for the host result before it+settles the turn, so Stop cannot hide a write or extension action that is still+running. Typed cancellation records include the tool name and cannot be+inherited by a different tool that reuses the call id.`JevClassify` is an external provider operation rather than a workspaceexecution tool. It validates its structured request, observes cancellation,diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.mdindex e03cfbd78..dcc37ad96 100644--- a/docs/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md@@ -664,6 +664,12 @@ Additive `worktree.*` methods; no protocol version bump. Failures use code- `tools.abort`- `tools.output` notifications for ordered `stdout`/`stderr` chunks+`tools.abort` accepts `sessionId`, `toolCallId`, and the optional `toolName`.+Current runtimes include the name so Host cancellation is scoped to the exact+tool while permission and admission are pending. Older callers may omit it;+that form retains the legacy Bash cancellation behavior and can still stop an+active typed cancellation by session and call id.+### Background tasks- `backgroundTasks.list`- `backgroundTasks.output`diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex f4962985c..d172a3d81 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -1931,26 +1931,36 @@ identify the platform validation still needed.regression in `renderer-stream-safety.test.mjs`, and math delimiter renderingin `latex-math.test.mjs`; full UI observation remains Draft)-#### E2E-010: Abort generation+#### E2E-010: Stop turns and in-flight tools safely- **Preconditions**: A session can produce both a deliberately delayed first- token and a streaming response.+ token and a streaming response. A deterministic Host fixture can hold a+ read-only `Grep` call and expose a pending `Write` approval.- **Steps**: 1) Send ordinary text and click Stop immediately, including whilethe prompt is still being admitted. 2) Confirm the user row is undone andthe text returns to the composer after that first Stop. 3) Send again, waitfor partial output, then stop during the stream. 4) Immediately send a new- prompt after Stop returns, without waiting for an idle delay. 5) Observe the- transcript and composer.+ prompt after Stop returns, without waiting for an idle delay. 5) Start a+ read-only Grep that does not return, press Stop, then start another prompt.+ 6) Start a Write that is waiting for permission, press Stop, then try to+ approve the stale request. 7) Observe the transcript, composer, and workspace.- **Expected**: The first Stop is honored even if prompt admission is still inprogress; the unanswered send is undone and its draft restored. Thestreaming send stops with its partial response preserved and no draft- restoration or duplicate user turn. Stop returns after the active runtime- operation has settled, and the follow-up starts without `AGENT_BUSY`. The- session remains usable.-- **Specs linked**: `03-runtime/02-agent-runtime.md`+ restoration or duplicate user turn. The read-only tool returns+ `TOOL_ABORTED`, its late result is discarded, and the follow-up starts+ without `AGENT_BUSY`. Stopping the pending Write cancels its permission;+ approving the stale request fails and creates no file. A mutating operation+ that already started is not reported stopped before its Host result arrives.+- **Specs linked**: `03-runtime/02-agent-runtime.md`,+ `03-runtime/03-tools-and-permissions.md`, `03-runtime/06-host-rpc-protocol.md`,+ ADR `tool-abort-abandons-host-call`- **Acceptance**: C (abort)- **Milestone**: M2-- **Status**: Draft+- **Status**: Runtime and Host cancellation contracts automated by+ `packages/agent-runtime/src/runtime.test.ts` and the pending-Write regression+ in `crates/host-core/src/rpc/mod.rs`; rendered Electron interaction remains+ a manual validation run.#### E2E-171: Streaming reply survives quit, crash, and stopdiff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 3263f4445..cdc4c7cb0 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -1749,6 +1749,7 @@ describe("DesktopAgentRuntime configuration matching", () => {expect(host.call).toHaveBeenCalledWith("tools.abort", {sessionId: "session-1",toolCallId: "bash-progress",+ toolName: "Bash",});expect(listeners.size).toBe(0);finishExecution({@@ -1850,9 +1851,8 @@ describe("DesktopAgentRuntime configuration matching", () => {await runtime.dispose();});- // #1767: host-core only cancels Bash and GenerateImages, so a stop used to- // leave the turn waiting for every other tool to return on its own.- it("ends the turn when a stop lands while a tool host-core cannot cancel runs", async () => {+ // #1767: a blocking read-only host call must not keep the user turn open.+ it("ends the turn when a stop lands while a read-only core tool is still running", async () => {let finishExecution!: (value: { ok: boolean; content: unknown }) => void;const execution = new Promise<{ ok: boolean; content: unknown }>((resolve) => {finishExecution = resolve;@@ -1861,12 +1861,14 @@ describe("DesktopAgentRuntime configuration matching", () => {call: vi.fn((method: string) =>method === "tools.execute"? execution- : Promise.resolve({ ok: true, content: "done" }),+ : method === "tools.abort"+ ? Promise.resolve({ ok: true, found: true })+ : Promise.resolve({ ok: true, content: "done" }),),onNotification: vi.fn(() => () => undefined),};const runtime = createRuntime({ host });- const grep = (runtime as any).toolCatalog.get("Grep");+ const grep = runtimeTool(runtime, "Grep");const controller = new AbortController();const pending = grep.execute("grep-stop", { query: "needle" }, controller.signal);await new Promise<void>((resolve) => setImmediate(resolve));@@ -1875,9 +1877,11 @@ describe("DesktopAgentRuntime configuration matching", () => {// The Grep is still running in host-core; only this turn stops waiting.await expect(pending).rejects.toMatchObject({ errorCode: "TOOL_ABORTED" });- expect(- host.call.mock.calls.filter((call: unknown[]) => call[0] === "tools.abort"),- ).toHaveLength(0);+ expect(host.call).toHaveBeenCalledWith("tools.abort", {+ sessionId: "session-1",+ toolCallId: "grep-stop",+ toolName: "Grep",+ });// The orphaned call settling later must not resurface as an unhandled// rejection or a second tool result.finishExecution({ ok: true, content: "late result" });@@ -1896,7 +1900,7 @@ describe("DesktopAgentRuntime configuration matching", () => {onNotification: vi.fn(() => () => undefined),};const runtime = createRuntime({ host });- const bash = (runtime as any).toolCatalog.get("Bash");+ const bash = runtimeTool(runtime, "Bash");const controller = new AbortController();const pending = bash.execute("bash-hung",@@ -1914,6 +1918,7 @@ describe("DesktopAgentRuntime configuration matching", () => {expect(host.call).toHaveBeenCalledWith("tools.abort", {sessionId: "session-1",toolCallId: "bash-hung",+ toolName: "Bash",});await runtime.dispose();@@ -1932,7 +1937,7 @@ describe("DesktopAgentRuntime configuration matching", () => {onNotification: vi.fn(() => () => undefined),};const runtime = createRuntime({ host });- const grep = (runtime as any).toolCatalog.get("Grep");+ const grep = runtimeTool(runtime, "Grep");// A signal that never fires stands in for the field case: the stop reached// the runtime but not the tool, so the executor kept awaiting a host call// that would not return and the abort RPC never came back.@@ -1946,6 +1951,53 @@ describe("DesktopAgentRuntime configuration matching", () => {expect(silent.signal.aborted).toBe(false);await runtime.dispose();});++ it("waits for an in-flight Write result after requesting host cancellation", async () => {+ let finishExecution!: (value: { ok: boolean; content: unknown }) => void;+ const execution = new Promise<{ ok: boolean; content: unknown }>((resolve) => {+ finishExecution = resolve;+ });+ let beginExecution!: () => void;+ const executionStarted = new Promise<void>((resolve) => {+ beginExecution = resolve;+ });+ const host = {+ call: vi.fn((method: string) =>+ method === "tools.execute"+ ? (beginExecution(), execution)+ : method === "project.instructions.resolve"+ ? Promise.resolve(undefined)+ : Promise.resolve({ ok: true, found: true }),+ ),+ onNotification: vi.fn(() => () => undefined),+ };+ const runtime = createRuntime({ host });+ const write = runtimeTool(runtime, "Write");+ const controller = new AbortController();+ let settled = false;+ const pending = write+ .execute("write-stop", { path: "file.txt", content: "value" }, controller.signal)+ .then(+ () => { settled = true; },+ () => { settled = true; },+ );+ await executionStarted;++ controller.abort();+ await new Promise<void>((resolve) => setImmediate(resolve));++ expect(host.call).toHaveBeenCalledWith("tools.abort", {+ sessionId: "session-1",+ toolCallId: "write-stop",+ toolName: "Write",+ });+ expect(settled).toBe(false);++ finishExecution({ ok: true, content: { path: "file.txt" } });+ await pending;+ expect(settled).toBe(true);+ await runtime.dispose();+ });});describe("DesktopAgentRuntime live activity", () => {diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex dfbfc365b..f1d920cc8 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -1264,6 +1264,7 @@ const TOOL_PARAM_ALIASES: Record<string, Record<string, string>> = {Grep: { query: "pattern" },};const TOOL_OUTPUT_UPDATE_THROTTLE_MS = 100;+const READ_ONLY_CORE_TOOLS = new Set(["Read", "Glob", "Grep"]);/*** How long a stop request waits for a tool that host-core can actually* interrupt (`Bash`, `GenerateImages`) to hand back the output it collected@@ -3489,14 +3490,12 @@ Do not invent objections or turn speculative risks into blockers. Stop when thescheduleProgress();}): undefined;- // #1767: host-core only honours `tools.abort` for `Bash` and- // `GenerateImages` — it kills the process and answers the in-flight- // execute with `TOOL_ABORTED`. Every other tool keeps running to- // completion whatever the runtime sends, so awaiting it blocked the- // turn long after the user pressed Stop. Those tools therefore abandon- // the wait locally the instant the signal fires; the orphaned host call- // settles on its own and its result is discarded.- const hostAbortsTool = isBash || toolName === "GenerateImages";+ // Read-only core tools may be abandoned locally if host-core is still+ // waiting on a blocking read/search. Mutating, MCP, and plugin calls+ // must settle before the turn is reported stopped. Bash and image+ // generation retain their host process-abort path and grace window.+ const hostAbortsProcess = isBash || toolName === "GenerateImages";+ const canAbandonWait = READ_ONLY_CORE_TOOLS.has(toolName);const abortedMarker = Symbol("tool-aborted");let resolveAborted: (marker: typeof abortedMarker) => void = () => undefined;const aborted = new Promise<typeof abortedMarker>((resolve) => {@@ -3507,31 +3506,31 @@ Do not invent objections or turn speculative risks into blockers. Stop when theconst abort = () => {if (abortRequested || settled) return;abortRequested = true;- if (hostAbortsTool) {- abortPromise = this.host- .call("tools.abort", {- sessionId: this.sessionId,- toolCallId,- })- .then(- () => undefined,- (error) => {- abortError = error;- },- );- }+ abortPromise = this.host+ .call("tools.abort", {+ sessionId: this.sessionId,+ toolCallId,+ toolName,+ })+ .then(+ () => undefined,+ (error) => {+ abortError = error;+ },+ );// Release progress/output resources before arming the grace window:// cleanup is idempotent and must not race the timer it would clear.cleanup(true);- if (hostAbortsTool) {+ if (hostAbortsProcess) {// Bounded window for the partial output the host collected before// the kill; past it the turn ends regardless.abortGraceTimer = setTimeout(() => resolveAborted(abortedMarker),TOOL_ABORT_GRACE_MS,);- } else {- // Nothing host-side can interrupt this tool, so stop waiting now.+ } else if (canAbandonWait) {+ // These tools are read-only, so returning before their host-side+ // work drains cannot leave a write or external action behind.resolveAborted(abortedMarker);}};@@ -3620,9 +3619,10 @@ Do not invent objections or turn speculative risks into blockers. Stop when the? { delegationId: this.delegateWorktrees.get(toolCallId) }: {}),});- // #1767: stop has to end the turn even when the tool never yields.- // Losing the race does not cancel the host call — it only stops this- // turn from waiting on it.+ // #1767: read-only host work must not keep the user-facing turn open+ // indefinitely. Other tool classes deliberately wait for the Host+ // result so a write or extension action cannot outlive a reported+ // stop.const raced = await Promise.race([execution, aborted]);if (raced === abortedMarker) {stopped = true;