Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
agent: Report follow-up messages as tool permission denials (#61754)
Ben Kunklea1510de54e99
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex d76511bd590..8c711bd916f 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -1222,16 +1222,18 @@ impl From<SelectedPermissionOutcome> for acp::SelectedPermissionOutcome {}}-#[derive(Debug)]+#[derive(Clone, Debug)]pub enum RequestPermissionOutcome {Cancelled,+ InterruptedByFollowUp,Selected(SelectedPermissionOutcome),}impl From<RequestPermissionOutcome> for acp::RequestPermissionOutcome {fn from(value: RequestPermissionOutcome) -> Self {match value {- RequestPermissionOutcome::Cancelled => Self::Cancelled,+ RequestPermissionOutcome::Cancelled+ | RequestPermissionOutcome::InterruptedByFollowUp => Self::Cancelled,RequestPermissionOutcome::Selected(outcome) => Self::Selected(outcome.into()),}}@@ -1262,7 +1264,7 @@ pub enum ToolCallStatus {WaitingForConfirmation {current_status: acp::ToolCallStatus,options: PermissionOptions,- respond_tx: oneshot::Sender<SelectedPermissionOutcome>,+ respond_tx: oneshot::Sender<RequestPermissionOutcome>,kind: AuthorizationKind,},/// The tool call is currently running.@@ -3401,10 +3403,7 @@ impl AcpThread {));Ok(cx.spawn(async move |this, cx| {- let outcome = match rx.await {- Ok(outcome) => RequestPermissionOutcome::Selected(outcome),- Err(oneshot::Canceled) => RequestPermissionOutcome::Cancelled,- };+ let outcome = rx.await.unwrap_or(RequestPermissionOutcome::Cancelled);this.update(cx, |_this, cx| {cx.emit(AcpThreadEvent::ToolAuthorizationReceived(tool_call_id))})@@ -3465,7 +3464,9 @@ impl AcpThread {let curr_status = mem::replace(&mut call.status, new_status);if let ToolCallStatus::WaitingForConfirmation { respond_tx, .. } = curr_status {- respond_tx.send(outcome).ok();+ respond_tx+ .send(RequestPermissionOutcome::Selected(outcome))+ .ok();}cx.emit(AcpThreadEvent::EntryUpdated(ix));@@ -3734,7 +3735,7 @@ impl AcpThread {self.had_error = false;let (tx, rx) = oneshot::channel();- let cancel_task = self.cancel(cx);+ let cancel_task = self.cancel_inner(RequestPermissionOutcome::InterruptedByFollowUp, cx);self.turn_id += 1;let turn_id = self.turn_id;@@ -3893,13 +3894,21 @@ impl AcpThread {}pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {+ self.cancel_inner(RequestPermissionOutcome::Cancelled, cx)+ }++ fn cancel_inner(+ &mut self,+ permission_outcome: RequestPermissionOutcome,+ cx: &mut Context<Self>,+ ) -> Task<()> {Self::flush_streaming_text(&mut self.streaming_text_buffer, cx);self.cancel_outstanding_elicitations(cx);let Some(turn) = self.running_turn.take() else {return Task::ready(());};- self.mark_pending_entries_as_canceled(cx);+ self.mark_pending_entries_as_canceled(permission_outcome, cx);self.connection.cancel(&self.session_id, cx);cx.emit(AcpThreadEvent::StatusChanged);@@ -3908,11 +3917,15 @@ impl AcpThread {}fn cancel_pending_turn_entries(&mut self, cx: &mut Context<Self>) {- self.mark_pending_entries_as_canceled(cx);+ self.mark_pending_entries_as_canceled(RequestPermissionOutcome::Cancelled, cx);self.cancel_outstanding_elicitations(cx);}- fn mark_pending_entries_as_canceled(&mut self, cx: &mut Context<Self>) {+ fn mark_pending_entries_as_canceled(+ &mut self,+ permission_outcome: RequestPermissionOutcome,+ cx: &mut Context<Self>,+ ) {for (ix, entry) in self.entries.iter_mut().enumerate() {match entry {AgentThreadEntry::ToolCall(call) => {@@ -3923,7 +3936,16 @@ impl AcpThread {| ToolCallStatus::InProgress);if cancel {- call.status = ToolCallStatus::Canceled;+ let previous_status =+ mem::replace(&mut call.status, ToolCallStatus::Canceled);+ if let ToolCallStatus::WaitingForConfirmation { respond_tx, .. } =+ previous_status+ && respond_tx.send(permission_outcome.clone()).is_err()+ {+ log::debug!(+ "Permission request closed before cancellation was delivered"+ );+ }cx.emit(AcpThreadEvent::EntryUpdated(ix));}}@@ -6479,7 +6501,8 @@ mod tests {assert_eq!(outcome.option_id, allow_option_id);assert_eq!(outcome.option_kind, acp::PermissionOptionKind::AllowOnce);}- RequestPermissionOutcome::Cancelled => {+ RequestPermissionOutcome::Cancelled+ | RequestPermissionOutcome::InterruptedByFollowUp => {panic!("permission request should remain open after duplicate tool call update")}}@@ -6591,7 +6614,8 @@ mod tests {assert_eq!(outcome.option_id, acp::PermissionOptionId::new("allow"));assert_eq!(outcome.option_kind, acp::PermissionOptionKind::AllowOnce);}- RequestPermissionOutcome::Cancelled => {+ RequestPermissionOutcome::Cancelled+ | RequestPermissionOutcome::InterruptedByFollowUp => {panic!("resolved permission request should select an outcome")}}@@ -6675,7 +6699,8 @@ mod tests {assert_eq!(outcome.option_id, acp::PermissionOptionId::new("allow"));assert_eq!(outcome.option_kind, acp::PermissionOptionKind::AllowOnce);}- RequestPermissionOutcome::Cancelled => {+ RequestPermissionOutcome::Cancelled+ | RequestPermissionOutcome::InterruptedByFollowUp => {panic!("permission request should resolve after authorization")}}@@ -6729,7 +6754,8 @@ mod tests {match permission_task.await {RequestPermissionOutcome::Cancelled => {}- RequestPermissionOutcome::Selected(_) => {+ RequestPermissionOutcome::InterruptedByFollowUp+ | RequestPermissionOutcome::Selected(_) => {panic!("cancelled permission request should not select an outcome")}}@@ -6791,7 +6817,8 @@ mod tests {match permission_task.await {RequestPermissionOutcome::Cancelled => {}- RequestPermissionOutcome::Selected(_) => {+ RequestPermissionOutcome::InterruptedByFollowUp+ | RequestPermissionOutcome::Selected(_) => {panic!("terminal tool call update should close pending permission request")}}@@ -9477,10 +9504,24 @@ mod tests {// Send first message (turn_id=1) - handler will blocklet first_request = thread.update(cx, |thread, cx| thread.send_raw("first", cx));assert_eq!(thread.read_with(cx, |t, _| t.turn_id), 1);+ let permission_task = thread+ .update(cx, |thread, cx| {+ thread.request_tool_call_authorization(+ acp::ToolCall::new("permission", "Needs permission").into(),+ PermissionOptions::Flat(Vec::new()),+ AuthorizationKind::PermissionGrant,+ cx,+ )+ })+ .unwrap();// Send second message (turn_id=2) while first is still blocked// This calls cancel() which takes turn 1's running_turn and sets turn 2'slet second_request = thread.update(cx, |thread, cx| thread.send_raw("second", cx));+ assert!(matches!(+ permission_task.await,+ RequestPermissionOutcome::InterruptedByFollowUp+ ));assert_eq!(thread.read_with(cx, |t, _| t.turn_id), 2);let running_turn_after_second_send =diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rsindex f96174baac1..594032852ea 100644--- a/crates/agent/src/agent.rs+++ b/crates/agent/src/agent.rs@@ -2208,16 +2208,22 @@ impl NativeAgentConnection {)})??;cx.background_spawn(async move {- if let acp_thread::RequestPermissionOutcome::Selected(outcome) =- outcome_task.await- {- response- .send(outcome)- .map_err(|_| {- anyhow!("authorization receiver was dropped")- })- .log_err();- }+ let outcome = match outcome_task.await {+ acp_thread::RequestPermissionOutcome::Selected(outcome) => outcome,+ acp_thread::RequestPermissionOutcome::InterruptedByFollowUp => {+ acp_thread::SelectedPermissionOutcome::new(+ acp::PermissionOptionId::new(+ FOLLOW_UP_PERMISSION_DENIED_OPTION_ID,+ ),+ acp::PermissionOptionKind::RejectOnce,+ )+ }+ acp_thread::RequestPermissionOutcome::Cancelled => return,+ };+ response+ .send(outcome)+ .map_err(|_| anyhow!("authorization receiver was dropped"))+ .log_err();}).detach();}diff --git a/crates/agent/src/tests/mod.rs b/crates/agent/src/tests/mod.rsindex 95cbcd9ca2e..98beabb86a5 100644--- a/crates/agent/src/tests/mod.rs+++ b/crates/agent/src/tests/mod.rs@@ -907,9 +907,20 @@ async fn test_tool_authorization(cx: &mut TestAppContext) {thought_signature: None,},));+ fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(+ LanguageModelToolUse {+ id: "tool_id_interrupted".into(),+ name: ToolRequiringPermission::NAME.into(),+ raw_input: "{}".into(),+ input: language_model::LanguageModelToolUseInput::Json(json!({})),+ is_input_complete: true,+ thought_signature: None,+ },+ ));fake_model.end_last_completion_stream();let tool_call_auth_1 = next_tool_call_authorization(&mut events).await;let tool_call_auth_2 = next_tool_call_authorization(&mut events).await;+ let interrupted_tool_call_auth = next_tool_call_authorization(&mut events).await;// Approve the first - send "allow" option_id (UI transforms "once" to "allow")tool_call_auth_1@@ -929,6 +940,13 @@ async fn test_tool_authorization(cx: &mut TestAppContext) {acp::PermissionOptionKind::RejectOnce,)).unwrap();+ interrupted_tool_call_auth+ .response+ .send(acp_thread::SelectedPermissionOutcome::new(+ acp::PermissionOptionId::new(FOLLOW_UP_PERMISSION_DENIED_OPTION_ID),+ acp::PermissionOptionKind::RejectOnce,+ ))+ .unwrap();cx.run_until_parked();let completion = fake_model.pending_completions().pop().unwrap();@@ -949,6 +967,13 @@ async fn test_tool_authorization(cx: &mut TestAppContext) {is_error: true,content: vec!["Permission to run tool denied by user".into()],output: Some("Permission to run tool denied by user".into())+ }),+ language_model::MessageContent::ToolResult(LanguageModelToolResult {+ tool_use_id: "tool_id_interrupted".into(),+ tool_name: ToolRequiringPermission::NAME.into(),+ is_error: true,+ content: vec!["Permission denied: user sent a follow-up message instead of approving the tool call.".into()],+ output: Some("Permission denied: user sent a follow-up message instead of approving the tool call.".into())})]);diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rsindex 75fb004ed3a..0591576e856 100644--- a/crates/agent/src/thread.rs+++ b/crates/agent/src/thread.rs@@ -70,6 +70,9 @@ use util::{ResultExt, debug_panic, markdown::MarkdownCodeBlock, paths::PathStyleuse uuid::Uuid;const TOOL_CANCELED_MESSAGE: &str = "Tool canceled by user";+const TOOL_CALL_INTERRUPTED_BY_FOLLOW_UP_MESSAGE: &str =+ "Permission denied: user sent a follow-up message instead of approving the tool call.";+pub(crate) const FOLLOW_UP_PERMISSION_DENIED_OPTION_ID: &str = "follow_up_permission_denied";pub const MAX_TOOL_NAME_LENGTH: usize = 64;pub const MAX_SUBAGENT_DEPTH: u8 = 1;@@ -1153,6 +1156,16 @@ pub struct ToolCallAuthorization {pub kind: acp_thread::AuthorizationKind,}+fn ensure_tool_call_authorization_not_interrupted(+ outcome: &acp_thread::SelectedPermissionOutcome,+) -> Result<()> {+ if outcome.option_id.0.as_ref() == FOLLOW_UP_PERMISSION_DENIED_OPTION_ID {+ Err(anyhow!(TOOL_CALL_INTERRUPTED_BY_FOLLOW_UP_MESSAGE))+ } else {+ Ok(())+ }+}+fn auto_resolve_permission_outcome(options: &acp_thread::PermissionOptions,is_allow: bool,@@ -5860,8 +5873,8 @@ impl ToolCallEventStream {};futures::select_biased! {outcome = (&mut response_rx).fuse() => {- let outcome = outcome- .map_err(|_| anyhow!("authorization channel closed"))?;+ let outcome = outcome.map_err(|_| anyhow!("authorization channel closed"))?;+ ensure_tool_call_authorization_not_interrupted(&outcome)?;return Self::handle_sandbox_permission_outcome(&outcome,&request,@@ -6151,6 +6164,7 @@ impl ToolCallEventStream {let outcome = response_rx.await.map_err(|_| anyhow!("authorization channel closed"))?;+ ensure_tool_call_authorization_not_interrupted(&outcome)?;let option_id = outcome.option_id.0.as_ref();if option_id == acp_thread::SANDBOX_FALLBACK_RETRY_OPTION_ID {@@ -6250,6 +6264,7 @@ impl ToolCallEventStream {let outcome = response_rx.await.map_err(|_| anyhow!("authorization channel closed"))?;+ ensure_tool_call_authorization_not_interrupted(&outcome)?;Ok(outcome.option_id)})}@@ -6324,6 +6339,7 @@ impl ToolCallEventStream {let outcome = response_rx.await.map_err(|_| anyhow!("authorization channel closed"))?;+ ensure_tool_call_authorization_not_interrupted(&outcome)?;return Self::persist_permission_outcome(&outcome, fs, cx);};@@ -6351,8 +6367,8 @@ impl ToolCallEventStream {};futures::select_biased! {outcome = (&mut response_rx).fuse() => {- let outcome = outcome- .map_err(|_| anyhow!("authorization channel closed"))?;+ let outcome = outcome.map_err(|_| anyhow!("authorization channel closed"))?;+ ensure_tool_call_authorization_not_interrupted(&outcome)?;return Self::persist_permission_outcome(&outcome, fs.clone(), cx);}_ = settings_changed.fuse() => {