Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
acp_thread: Scope permission lifetimes to requests (#65039)
Ben Brandtc5b6d4386e7f
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex 832766aec72..184da930509 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -9,7 +9,7 @@ use action_log::{ActionLog, ActionLogTelemetry};use agent_client_protocol::schema::{MaybeUndefined, v1 as acp_v1, v2 as acp_v2};use agent_settings::AgentSettings;use anyhow::{Context as _, Result, anyhow};-use collections::HashSet;+use collections::{HashSet, IndexMap};pub use connection::*;pub use diff::*;use feature_flags::{AcpBetaFeatureFlag, FeatureFlagAppExt as _};@@ -1030,7 +1030,7 @@ pub struct ToolCall {pub meta: Option<acp_v2::Meta>,structured_content: Vec<ToolCallContent>,local_status: Option<ToolCallStatus>,- authorization: Option<ToolCallAuthorization>,+ authorization: Option<PermissionRequestId>,pub locations: Vec<acp_v1::ToolCallLocation>,pub resolved_locations: Vec<Option<AgentLocation>>,pub raw_input: Option<serde_json::Value>,@@ -1047,8 +1047,14 @@ pub struct ToolCall {pub sandbox_not_applied: Option<SandboxNotAppliedReason>,}+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(transparent)]+pub struct PermissionRequestId(Uuid);+#[derive(Debug)]-pub struct ToolCallAuthorization {+pub struct PermissionRequest {+ pub id: PermissionRequestId,+ pub tool_call_id: acp_v1::ToolCallId,pub options: PermissionOptions,pub kind: AuthorizationKind,respond_tx: oneshot::Sender<RequestPermissionOutcome>,@@ -1262,8 +1268,8 @@ impl ToolCall {}}- pub fn authorization(&self) -> Option<&ToolCallAuthorization> {- self.authorization.as_ref()+ pub fn authorization_id(&self) -> Option<PermissionRequestId> {+ self.authorization}fn underlying_status(&self) -> ToolCallStatus {@@ -3301,6 +3307,7 @@ pub struct AcpThread {notices: Vec<(usize, acp_v1::Notice)>,next_notice_id: usize,elicitations: ElicitationStore,+ permission_requests: IndexMap<PermissionRequestId, PermissionRequest>,plans: HashMap<PlanIdentity, Plan>,visible_plan: Option<PlanIdentity>,project: Entity<Project>,@@ -3440,8 +3447,8 @@ pub enum AcpThreadEvent {TokenUsageUpdated,EntryUpdated(usize),EntriesRemoved(Range<usize>),- ToolAuthorizationRequested(acp_v1::ToolCallId),- ToolAuthorizationReceived(acp_v1::ToolCallId),+ ToolAuthorizationRequested(PermissionRequestId),+ ToolAuthorizationReceived(PermissionRequestId),ElicitationRequested(ElicitationEntryId),/// The request left `Pending`; this does not imply delivery to its response waiter.ElicitationResponded(ElicitationEntryId),@@ -3629,6 +3636,7 @@ impl AcpThread {notices: Vec::new(),next_notice_id: 0,elicitations: ElicitationStore::default(),+ permission_requests: IndexMap::default(),plans: HashMap::default(),visible_plan: None,title,@@ -3828,7 +3836,13 @@ impl AcpThread {for entry in self.entries.iter().rev() {match entry {AgentThreadEntry::UserMessage(_) => return false,- AgentThreadEntry::ToolCall(call) if call.authorization().is_some() => return true,+ AgentThreadEntry::ToolCall(call)+ if call+ .authorization_id()+ .is_some_and(|id| self.permission_request(id).is_some()) =>+ {+ return true;+ }AgentThreadEntry::Elicitation(elicitation_id)if self.elicitations.elicitation(elicitation_id).is_some_and(|(_, elicitation)| {@@ -3873,8 +3887,8 @@ impl AcpThread {self.status() == ThreadStatus::Idle&& !self.has_unsettled_submissions()&& self.recoverable_submissions().next().is_none()+ && self.permission_requests.is_empty()&& !self.entries.iter().any(|entry| match entry {- AgentThreadEntry::ToolCall(call) => call.authorization().is_some(),AgentThreadEntry::Elicitation(id) => {self.elicitations.elicitation(id)@@ -4872,6 +4886,22 @@ impl AcpThread {cx.emit(AcpThreadEvent::NewEntry);}+ fn truncate_entries(&mut self, index: usize, cx: &mut Context<Self>) {+ let removed_requests = self+ .entries+ .iter()+ .skip(index)+ .filter_map(|entry| match entry {+ AgentThreadEntry::ToolCall(call) => call.authorization_id(),+ _ => None,+ })+ .collect::<Vec<_>>();+ self.entries.truncate(index);+ for id in removed_requests {+ self.resolve_permission_request(id, RequestPermissionOutcome::Cancelled, cx);+ }+ }+pub fn push_context_compaction(&mut self,compaction: ContextCompaction,@@ -5068,9 +5098,15 @@ impl AcpThread {match update {ToolCallUpdate::UpdateFields(update) => {let location_updated = update.fields.locations.is_some();- if let Err(error) =- call.update_fields(update.fields, update.meta, languages, &self.terminals, cx)- {+ let authorization_id = call.authorization_id();+ let result =+ call.update_fields(update.fields, update.meta, languages, &self.terminals, cx);+ let detached_id =+ authorization_id.filter(|id| call.authorization_id() != Some(*id));+ if let Some(id) = detached_id {+ self.resolve_permission_request(id, RequestPermissionOutcome::Cancelled, cx);+ }+ if let Err(error) = result {cx.emit(AcpThreadEvent::EntryUpdated(ix));return Err(error);}@@ -5145,19 +5181,27 @@ impl AcpThread {unreachable!()};- if let Err(error) = call.update_fields(+ let authorization_id = call.authorization_id();+ let result = call.update_fields(update.fields,update.meta,language_registry,&self.terminals,cx,- ) {+ );+ let detached_id = authorization_id.filter(|id| call.authorization_id() != Some(*id));+ if result.is_ok()+ && let Some(status) = status+ {+ call.set_legacy_status(status);+ }+ if let Some(id) = detached_id {+ self.resolve_permission_request(id, RequestPermissionOutcome::Cancelled, cx);+ }+ if let Err(error) = result {cx.emit(AcpThreadEvent::EntryUpdated(ix));return Err(acp_v1::Error::from(error));}- if let Some(status) = status {- call.set_legacy_status(status);- }cx.emit(AcpThreadEvent::EntryUpdated(ix));} else {@@ -5201,7 +5245,12 @@ impl AcpThread {let AgentThreadEntry::ToolCall(call) = &mut self.entries[index] else {unreachable!()};+ let authorization_id = call.authorization_id();let result = call.apply_patch(patch, languages, &self.terminals, cx);+ let detached_id = authorization_id.filter(|id| call.authorization_id() != Some(*id));+ if let Some(id) = detached_id {+ self.resolve_permission_request(id, RequestPermissionOutcome::Cancelled, cx);+ }cx.emit(AcpThreadEvent::EntryUpdated(index));result?;} else {@@ -5344,6 +5393,22 @@ impl AcpThread {.detach();}+ pub fn permission_request(&self, id: PermissionRequestId) -> Option<&PermissionRequest> {+ self.permission_requests.get(&id)+ }++ pub fn permission_request_for_tool(+ &self,+ tool_call_id: &acp_v1::ToolCallId,+ ) -> Option<&PermissionRequest> {+ let (_, call) = self.tool_call(tool_call_id)?;+ self.permission_request(call.authorization_id()?)+ }++ pub fn pending_permission_requests(&self) -> impl Iterator<Item = &PermissionRequest> {+ self.permission_requests.values()+ }+pub fn request_tool_call_authorization(&mut self,tool_call: acp_v1::ToolCallUpdate,@@ -5351,6 +5416,17 @@ impl AcpThread {kind: AuthorizationKind,cx: &mut Context<Self>,) -> Result<Task<RequestPermissionOutcome>> {+ self.request_tool_call_authorization_with_id(tool_call, options, kind, cx)+ .map(|(_, task)| task)+ }++ pub fn request_tool_call_authorization_with_id(+ &mut self,+ tool_call: acp_v1::ToolCallUpdate,+ options: PermissionOptions,+ kind: AuthorizationKind,+ cx: &mut Context<Self>,+ ) -> Result<(PermissionRequestId, Task<RequestPermissionOutcome>)> {let (tx, rx) = oneshot::channel();let current_status = self@@ -5363,28 +5439,37 @@ impl AcpThread {let tool_call_id = tool_call.tool_call_id.clone();self.upsert_tool_call_inner(tool_call, Some(current_status), cx)?;+ if let Some(id) = self+ .tool_call(&tool_call_id)+ .and_then(|(_, call)| call.authorization_id())+ {+ self.resolve_permission_request(id, RequestPermissionOutcome::Cancelled, cx);+ }+ let id = PermissionRequestId(Uuid::new_v4());let (_, call) = self.tool_call_mut(&tool_call_id).context("tool call disappeared while requesting authorization")?;// A new explicit request is installed after applying its descriptive// fields, preserving the legacy request's captured continuation status.- call.authorization = Some(ToolCallAuthorization {- options,- respond_tx: tx,- kind,- });- cx.emit(AcpThreadEvent::ToolAuthorizationRequested(- tool_call_id.clone(),- ));+ call.authorization = Some(id);+ self.permission_requests.insert(+ id,+ PermissionRequest {+ id,+ tool_call_id,+ options,+ respond_tx: tx,+ kind,+ },+ );+ cx.emit(AcpThreadEvent::ToolAuthorizationRequested(id));- Ok(cx.spawn(async move |this, cx| {- let outcome = rx.await.unwrap_or(RequestPermissionOutcome::Cancelled);- this.update(cx, |_this, cx| {- cx.emit(AcpThreadEvent::ToolAuthorizationReceived(tool_call_id))- })- .ok();- outcome- }))+ Ok((+ id,+ cx.spawn(async move |_this, _cx| {+ rx.await.unwrap_or(RequestPermissionOutcome::Cancelled)+ }),+ ))}pub fn cancel_tool_call_authorization(@@ -5392,17 +5477,35 @@ impl AcpThread {id: &acp_v1::ToolCallId,cx: &mut Context<Self>,) {- let Some((ix, call)) = self.tool_call_mut(id) else {+ let Some(request_id) = self+ .tool_call(id)+ .and_then(|(_, call)| call.authorization_id())+ else {return;};- if call.authorization.is_none() {+ self.cancel_permission_request(request_id, cx);+ }++ pub fn cancel_permission_request(&mut self, id: PermissionRequestId, cx: &mut Context<Self>) {+ self.cancel_permission_request_with_outcome(id, RequestPermissionOutcome::Cancelled, cx);+ }++ fn cancel_permission_request_with_outcome(+ &mut self,+ id: PermissionRequestId,+ outcome: RequestPermissionOutcome,+ cx: &mut Context<Self>,+ ) {+ let Some(request) = self.permission_requests.get(&id) else {return;+ };+ let tool_call_id = request.tool_call_id.clone();+ if let Some((_, call)) = self.tool_call_mut(&tool_call_id)+ && call.authorization_id() == Some(id)+ {+ call.set_local_status(ToolCallStatus::Canceled);}-- call.authorization = None;- call.set_local_status(ToolCallStatus::Canceled);- cx.emit(AcpThreadEvent::EntryUpdated(ix));- cx.emit(AcpThreadEvent::ToolAuthorizationReceived(id.clone()));+ self.resolve_permission_request(id, outcome, cx);}pub fn authorize_tool_call(@@ -5411,45 +5514,72 @@ impl AcpThread {outcome: SelectedPermissionOutcome,cx: &mut Context<Self>,) {- let Some((ix, call)) = self.tool_call_mut(&id) else {+ let Some(request_id) = self+ .tool_call(&id)+ .and_then(|(_, call)| call.authorization_id())+ else {return;};+ self.authorize_permission_request(request_id, outcome, cx);+ }- let new_status = match call.authorization() {- Some(ToolCallAuthorization {- kind: AuthorizationKind::ActionChoice,- ..- }) => ToolCallStatus::InProgress,- Some(_) => {+ pub fn authorize_permission_request(+ &mut self,+ id: PermissionRequestId,+ mut outcome: SelectedPermissionOutcome,+ cx: &mut Context<Self>,+ ) {+ let Some(request) = self.permission_requests.get(&id) else {+ return;+ };+ let Some(option) = request.options.option_for_id(&outcome.option_id) else {+ log::debug!("Permission choice is not an offered option");+ return;+ };+ outcome.option_kind = option.kind;+ let tool_call_id = request.tool_call_id.clone();+ let kind = request.kind;+ let Some((_, call)) = self.tool_call_mut(&tool_call_id) else {+ return;+ };+ if call.authorization_id() != Some(id) {+ return;+ }++ let new_status = match kind {+ AuthorizationKind::ActionChoice => ToolCallStatus::InProgress,+ AuthorizationKind::PermissionGrant => {let current_status = call.permission_status().unwrap_or_default();match outcome.option_kind {acp_v1::PermissionOptionKind::RejectOnce| acp_v1::PermissionOptionKind::RejectAlways => ToolCallStatus::Rejected,- acp_v1::PermissionOptionKind::AllowOnce- | acp_v1::PermissionOptionKind::AllowAlways => {- ToolCallStatus::status_after_permission_grant(current_status)- }_ => ToolCallStatus::status_after_permission_grant(current_status),}}- _ => match outcome.option_kind {- acp_v1::PermissionOptionKind::RejectOnce- | acp_v1::PermissionOptionKind::RejectAlways => ToolCallStatus::Rejected,- acp_v1::PermissionOptionKind::AllowOnce- | acp_v1::PermissionOptionKind::AllowAlways => ToolCallStatus::InProgress,- _ => ToolCallStatus::InProgress,- },};-call.set_local_status(new_status);- if let Some(authorization) = call.authorization.take() {- authorization- .respond_tx- .send(RequestPermissionOutcome::Selected(outcome))- .ok();- }+ self.resolve_permission_request(id, RequestPermissionOutcome::Selected(outcome), cx);+ }- cx.emit(AcpThreadEvent::EntryUpdated(ix));+ fn resolve_permission_request(+ &mut self,+ id: PermissionRequestId,+ outcome: RequestPermissionOutcome,+ cx: &mut Context<Self>,+ ) {+ let Some(request) = self.permission_requests.shift_remove(&id) else {+ return;+ };+ if let Some((index, call)) = self.tool_call_mut(&request.tool_call_id)+ && call.authorization_id() == Some(id)+ {+ call.authorization = None;+ cx.emit(AcpThreadEvent::EntryUpdated(index));+ }+ if request.respond_tx.send(outcome).is_err() {+ log::debug!("Permission request closed before the outcome was delivered");+ }+ cx.emit(AcpThreadEvent::ToolAuthorizationReceived(id));}pub fn request_elicitation(@@ -5921,7 +6051,7 @@ impl AcpThread {// User prompt was refused - truncate back to before the user messagelet range = user_msg_ix..this.entries.len();if range.start < range.end {- this.entries.truncate(user_msg_ix);+ this.truncate_entries(user_msg_ix, cx);cx.emit(AcpThreadEvent::EntriesRemoved(range));}cx.emit(AcpThreadEvent::Refusal);@@ -6005,6 +6135,10 @@ impl AcpThread {self.cancel_outstanding_elicitations(cx);let Some(turn) = self.running_turn.take() else {+ let request_ids = self.permission_requests.keys().copied().collect::<Vec<_>>();+ for id in request_ids {+ self.cancel_permission_request_with_outcome(id, permission_outcome.clone(), cx);+ }return Task::ready(());};self.shrink_message_source_capacity(turn.first_entry_index);@@ -6061,6 +6195,7 @@ impl AcpThread {permission_outcome: RequestPermissionOutcome,cx: &mut Context<Self>,) {+ let mut canceled_requests = Vec::new();for (ix, entry) in self.entries.iter_mut().enumerate() {match entry {AgentThreadEntry::ToolCall(call) => {@@ -6072,15 +6207,8 @@ impl AcpThread {);if cancel {call.set_local_status(ToolCallStatus::Canceled);- if let Some(authorization) = call.authorization.take()- && authorization- .respond_tx- .send(permission_outcome.clone())- .is_err()- {- log::debug!(- "Permission request closed before cancellation was delivered"- );+ if let Some(id) = call.authorization.take() {+ canceled_requests.push(id);}cx.emit(AcpThreadEvent::EntryUpdated(ix));}@@ -6094,6 +6222,9 @@ impl AcpThread {_ => {}}}+ for id in canceled_requests {+ self.resolve_permission_request(id, permission_outcome.clone(), cx);+ }}fn cancel_outstanding_elicitations(&mut self, cx: &mut Context<Self>) {@@ -6167,7 +6298,7 @@ impl AcpThread {.collect();let range = ix..this.entries.len();- this.entries.truncate(ix);+ this.truncate_entries(ix, cx);cx.emit(AcpThreadEvent::EntriesRemoved(range));// Kill and remove the terminals@@ -10408,7 +10539,7 @@ mod tests {assert!(thread.has_unsettled_submissions());assert!(!thread.is_idle_for_retention());assert!(thread.entries().iter().any(|entry| matches!(entry,- AgentThreadEntry::ToolCall(call) if call.authorization().is_some())));+ AgentThreadEntry::ToolCall(call) if call.authorization_id().is_some())));});pending_sender.send(Ok(acp_v2::PromptResponse::new("pending-id")))@@ -12799,7 +12930,14 @@ mod tests {.expect("nonterminal status");let (_, call) = thread.tool_call(&id).expect("tool");assert_eq!(call.status(), ToolCallStatus::WaitingForConfirmation);- assert!(call.authorization().is_some());+ let request_id = call.authorization_id().expect("pending request link");+ assert_eq!(+ thread+ .permission_request(request_id)+ .expect("pending request")+ .tool_call_id,+ id+ );assert_eq!(serde_json::to_value(&call.reported_status).expect("reported status"),status@@ -12870,7 +13008,8 @@ mod tests {Some(acp_v2::ToolCallStatus::Cancelled));assert_eq!(call.status(), ToolCallStatus::Canceled);- assert!(call.authorization().is_none());+ assert!(call.authorization_id().is_none());+ assert!(thread.permission_request_for_tool(&id).is_none());assert_eq!(call.label, original_label);assert_eq!(call.label.read(cx).source(), "Cancelled command");assert!(call.terminals().next().is_some());@@ -12971,7 +13110,8 @@ mod tests {let (_, call) = thread.tool_call(&id).expect("authorized tool");assert_eq!(call.status(), expected);assert_eq!(call.reported_status.as_ref(), Some(&reported));- assert!(call.authorization().is_none());+ assert!(call.authorization_id().is_none());+ assert!(thread.permission_request_for_tool(&id).is_none());});assert!(matches!(permission.await, RequestPermissionOutcome::Selected(outcome) if outcome.option_id == "selected".into())@@ -13793,9 +13933,9 @@ mod tests {] {let thread = new_test_thread(cx).await;let id = acp_v1::ToolCallId::new("atomic-tool");- let permission = thread+ let (request_id, permission) = thread.update(cx, |thread, cx| {- thread.request_tool_call_authorization(+ thread.request_tool_call_authorization_with_id(acp_v1::ToolCall::new(id.clone(), "Original title").name("original-tool").kind(acp_v1::ToolKind::Read)@@ -13867,6 +14007,8 @@ mod tests {call.status(),ToolCallStatus::WaitingForConfirmation));+ assert_eq!(call.authorization_id(), Some(request_id));+ assert!(thread.permission_request(request_id).is_some());thread.authorize_tool_call(id.clone(),SelectedPermissionOutcome::new(@@ -13877,7 +14019,11 @@ mod tests {);} else {assert!(matches!(call.status(), ToolCallStatus::Completed));+ assert!(call.authorization_id().is_none());}+ assert!(thread.permission_request(request_id).is_none());+ assert!(thread.permission_request_for_tool(&id).is_none());+ assert_eq!(thread.pending_permission_requests().count(), 0);});if status == acp_v1::ToolCallStatus::InProgress {assert!(matches!(@@ -17144,9 +17290,9 @@ mod tests {cx.run_until_parked();assert_eq!(thread.read_with(cx, |t, _| t.turn_id), 1);assert_eq!(cx.active_idle_sleep_preventions(), 1);- let permission_task = thread+ let (permission_id, permission_task) = thread.update(cx, |thread, cx| {- thread.request_tool_call_authorization(+ thread.request_tool_call_authorization_with_id(acp_v1::ToolCall::new("permission", "Needs permission").into(),PermissionOptions::Flat(Vec::new()),AuthorizationKind::PermissionGrant,@@ -17159,6 +17305,20 @@ mod tests {// 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));+ thread.read_with(cx, |thread, _| {+ let tool_id = acp_v1::ToolCallId::new("permission");+ assert!(thread.permission_request(permission_id).is_none());+ assert!(thread.permission_request_for_tool(&tool_id).is_none());+ assert_eq!(thread.pending_permission_requests().count(), 0);+ assert!(+ thread+ .tool_call(&tool_id)+ .expect("interrupted tool")+ .1+ .authorization_id()+ .is_none()+ );+ });assert!(matches!(permission_task.await,RequestPermissionOutcome::InterruptedByFollowUp@@ -18872,12 +19032,26 @@ mod tests {cx.run_until_parked();assert_eq!(cx.active_idle_sleep_preventions(), 1);let tool_call_id = acp_v1::ToolCallId::new("permission");- let permission = request_test_permission(&thread, tool_call_id.clone(), cx);+ let (permission_id, permission) =+ request_test_permission_with_id(&thread, tool_call_id.clone(), cx);let (elicitation_id, elicitation_response) = request_test_form_elicitation(&thread, cx);cx.run_until_parked();assert_eq!(cx.active_idle_sleep_preventions(), 0);let cancel = thread.update(cx, |thread, cx| thread.cancel(cx));+ thread.read_with(cx, |thread, _| {+ assert!(thread.permission_request(permission_id).is_none());+ assert!(thread.permission_request_for_tool(&tool_call_id).is_none());+ assert_eq!(thread.pending_permission_requests().count(), 0);+ assert!(+ thread+ .tool_call(&tool_call_id)+ .expect("cancelled tool")+ .1+ .authorization_id()+ .is_none()+ );+ });assert!(matches!(permission.await,RequestPermissionOutcome::Cancelled@@ -19174,7 +19348,8 @@ mod tests {.expect("unseen terminal references create placeholders");let (_, first) = thread.tool_call(&first_id).expect("updated tool");assert_eq!(first.reported_status.as_ref(), Some(&status));- assert!(first.authorization().is_none());+ assert!(first.authorization_id().is_none());+ assert!(thread.permission_request_for_tool(&first_id).is_none());assert_eq!(first.label, original_label);assert_eq!(first.label.read(cx).source(), "Terminal result");let terminal = first.terminals().next().expect("terminal placeholder");@@ -19185,7 +19360,7 @@ mod tests {.tool_call(&second_id).expect("second tool").1- .authorization()+ .authorization_id().is_some());index@@ -19217,6 +19392,632 @@ mod tests {}}+ #[gpui::test]+ async fn test_failed_permission_replacement_keeps_status_settlement_contract(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ for status in [+ acp_v1::ToolCallStatus::InProgress,+ acp_v1::ToolCallStatus::Completed,+ ] {+ let thread = new_test_thread(cx).await;+ let tool_id = acp_v1::ToolCallId::new("replacement");+ let (events, _subscription) = track_permission_events(&thread, cx);+ let (old_id, old_response) =+ request_test_permission_with_id(&thread, tool_id.clone(), cx);+ let result = thread.update(cx, |thread, cx| {+ thread.request_tool_call_authorization_with_id(+ acp_v1::ToolCallUpdate::new(+ tool_id.clone(),+ acp_v1::ToolCallUpdateFields::new()+ .status(status)+ .title("Must not replace presentation")+ .content(vec![acp_v1::ToolCallContent::Terminal(+ acp_v1::Terminal::new("missing"),+ )]),+ ),+ PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(+ "new-choice",+ "New choice",+ acp_v1::PermissionOptionKind::RejectOnce,+ )]),+ AuthorizationKind::ActionChoice,+ cx,+ )+ });+ assert!(result.is_err());+ thread.read_with(cx, |thread, _| {+ let (_, call) = thread.tool_call(&tool_id).expect("existing tool");+ if status == acp_v1::ToolCallStatus::Completed {+ assert!(thread.permission_request(old_id).is_none());+ assert!(call.authorization_id().is_none());+ assert_eq!(call.status(), ToolCallStatus::Completed);+ assert_eq!(*events.borrow(), [(true, old_id), (false, old_id)]);+ } else {+ let request = thread+ .permission_request(old_id)+ .expect("old request remains");+ assert_eq!(request.kind, AuthorizationKind::PermissionGrant);+ assert!(request.options.option_for_id(&"allow".into()).is_some());+ assert!(+ request+ .options+ .option_for_id(&"new-choice".into())+ .is_none()+ );+ assert_eq!(call.authorization_id(), Some(old_id));+ assert_eq!(call.status(), ToolCallStatus::WaitingForConfirmation);+ assert_eq!(*events.borrow(), [(true, old_id)]);+ }+ });+ thread.update(cx, |thread, cx| {+ thread.cancel_permission_request(old_id, cx)+ });+ assert!(matches!(+ old_response.await,+ RequestPermissionOutcome::Cancelled+ ));+ assert_eq!(*events.borrow(), [(true, old_id), (false, old_id)]);+ }+ }++ #[gpui::test]+ async fn test_permission_response_task_does_not_keep_thread_alive(cx: &mut TestAppContext) {+ init_test(cx);+ let thread = new_test_thread(cx).await;+ let (id, response) = request_test_permission_with_id(&thread, "same-tool".into(), cx);+ let released = thread.downgrade();+ drop(thread);+ cx.run_until_parked();+ assert!(released.upgrade().is_none());+ assert!(matches!(+ response.await,+ RequestPermissionOutcome::Cancelled+ ));++ let replacement = new_test_thread(cx).await;+ let (new_id, new_response) =+ request_test_permission_with_id(&replacement, "same-tool".into(), cx);+ assert_ne!(id, new_id);+ replacement.update(cx, |thread, cx| {+ thread.cancel_permission_request(id, cx);+ assert!(thread.permission_request(new_id).is_some());+ thread.cancel_permission_request(new_id, cx);+ });+ assert!(matches!(+ new_response.await,+ RequestPermissionOutcome::Cancelled+ ));+ }++ #[gpui::test]+ async fn test_idle_cancel_settles_permissions_without_canceling_other_tools(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let thread = new_test_thread(cx).await;+ let tool_id = acp_v1::ToolCallId::new("idle-permission");+ let unrelated_id = acp_v1::ToolCallId::new("unrelated");+ let (events, _subscription) = track_permission_events(&thread, cx);+ thread.update(cx, |thread, cx| {+ assert!(thread.running_turn.is_none());+ thread+ .upsert_tool_call(+ acp_v1::ToolCall::new(unrelated_id.clone(), "Unrelated work")+ .status(acp_v1::ToolCallStatus::InProgress),+ cx,+ )+ .expect("unrelated tool");+ });+ let (id, response) = request_test_permission_with_id(&thread, tool_id.clone(), cx);+ let cancellation = thread.update(cx, |thread, cx| {+ assert!(!thread.is_idle_for_retention());+ let cancellation = thread.cancel(cx);+ assert!(thread.permission_request(id).is_none());+ assert!(thread.permission_request_for_tool(&tool_id).is_none());+ assert_eq!(+ thread.tool_call(&tool_id).expect("tool").1.status(),+ ToolCallStatus::Canceled+ );+ assert_eq!(+ thread+ .tool_call(&unrelated_id)+ .expect("unrelated tool")+ .1+ .status(),+ ToolCallStatus::InProgress+ );+ assert!(thread.is_idle_for_retention());+ cancellation+ });+ cancellation.await;+ assert!(matches!(+ response.await,+ RequestPermissionOutcome::Cancelled+ ));+ thread.update(cx, |thread, cx| thread.cancel(cx)).await;+ assert_eq!(*events.borrow(), [(true, id), (false, id)]);+ }++ #[gpui::test]+ async fn test_permission_settlement_does_not_depend_on_response_waiter(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let thread = new_test_thread(cx).await;+ let (complete, turn) = start_test_turn(&thread, cx);+ cx.run_until_parked();+ assert_eq!(cx.active_idle_sleep_preventions(), 1);+ let (events, _subscription) = track_permission_events(&thread, cx);+ let first_tool = acp_v1::ToolCallId::new("first");+ let second_tool = acp_v1::ToolCallId::new("second");+ let (first_id, first_response) =+ request_test_permission_with_id(&thread, first_tool.clone(), cx);+ let (second_id, second_response) =+ request_test_permission_with_id(&thread, second_tool.clone(), cx);+ drop(first_response);+ drop(second_response);+ cx.run_until_parked();+ assert_eq!(*events.borrow(), [(true, first_id), (true, second_id)]);+ assert_eq!(cx.active_idle_sleep_preventions(), 0);+ thread.read_with(cx, |thread, _| {+ assert_eq!(+ thread.foreground_activity(),+ ForegroundActivity::RequiresAction+ );+ assert_eq!(+ thread+ .pending_permission_requests()+ .map(|request| request.id)+ .collect::<Vec<_>>(),+ [first_id, second_id]+ );+ assert_eq!(+ thread+ .permission_request_for_tool(&first_tool)+ .expect("first request")+ .id,+ first_id+ );+ });++ thread.update(cx, |thread, cx| {+ thread.authorize_permission_request(+ first_id,+ SelectedPermissionOutcome::new(+ "allow".into(),+ acp_v1::PermissionOptionKind::AllowOnce,+ ),+ cx,+ );+ assert!(thread.permission_request(first_id).is_none());+ assert!(thread.permission_request_for_tool(&first_tool).is_none());+ let (_, call) = thread.tool_call(&first_tool).expect("selected tool");+ assert!(call.authorization_id().is_none());+ assert_eq!(call.status(), ToolCallStatus::InProgress);+ assert_eq!(+ thread.foreground_activity(),+ ForegroundActivity::RequiresAction+ );+ assert_eq!(+ thread+ .pending_permission_requests()+ .map(|request| request.id)+ .collect::<Vec<_>>(),+ [second_id]+ );+ });+ assert_eq!(+ *events.borrow(),+ [(true, first_id), (true, second_id), (false, first_id)]+ );+ assert_eq!(cx.active_idle_sleep_preventions(), 0);+ thread.update(cx, |thread, cx| {+ thread.cancel_permission_request(second_id, cx);+ thread.cancel_permission_request(second_id, cx);+ assert!(thread.permission_request(second_id).is_none());+ assert!(thread.permission_request_for_tool(&second_tool).is_none());+ assert_eq!(thread.pending_permission_requests().count(), 0);+ let (_, call) = thread.tool_call(&second_tool).expect("cancelled tool");+ assert!(call.authorization_id().is_none());+ assert_eq!(call.status(), ToolCallStatus::Canceled);+ });+ thread.read_with(cx, |thread, _| {+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Running);+ });+ assert_eq!(+ *events.borrow(),+ [+ (true, first_id),+ (true, second_id),+ (false, first_id),+ (false, second_id)+ ]+ );+ cx.run_until_parked();+ assert_eq!(cx.active_idle_sleep_preventions(), 1);+ complete+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))+ .expect("turn should still be running");+ turn.await.expect("turn should complete");+ assert_eq!(cx.active_idle_sleep_preventions(), 0);+ }++ #[gpui::test]+ async fn test_replaced_permission_request_cannot_settle_its_successor(cx: &mut TestAppContext) {+ init_test(cx);+ let thread = new_test_thread(cx).await;+ let (events, _subscription) = track_permission_events(&thread, cx);+ let tool_id = acp_v1::ToolCallId::new("reused");+ let (old_id, old_response) = request_test_permission_with_id(&thread, tool_id.clone(), cx);+ let (new_id, new_response) = request_test_permission_with_id(&thread, tool_id.clone(), cx);+ assert_ne!(old_id, new_id);+ thread.update(cx, |thread, cx| {+ thread.cancel_permission_request(old_id, cx);+ thread.authorize_permission_request(+ old_id,+ SelectedPermissionOutcome::new(+ "reject".into(),+ acp_v1::PermissionOptionKind::RejectOnce,+ ),+ cx,+ );+ assert!(thread.permission_request(old_id).is_none());+ assert_eq!(+ thread+ .permission_request_for_tool(&tool_id)+ .expect("replacement request")+ .id,+ new_id+ );+ let (_, call) = thread.tool_call(&tool_id).expect("replacement tool");+ assert_eq!(call.authorization_id(), Some(new_id));+ assert_eq!(call.status(), ToolCallStatus::WaitingForConfirmation);+ });+ assert!(matches!(+ old_response.await,+ RequestPermissionOutcome::Cancelled+ ));+ assert_eq!(+ *events.borrow(),+ [(true, old_id), (false, old_id), (true, new_id)]+ );+ thread.read_with(cx, |thread, _| {+ assert_eq!(+ thread+ .pending_permission_requests()+ .map(|request| request.id)+ .collect::<Vec<_>>(),+ [new_id]+ );+ assert_eq!(+ thread+ .tool_call(&tool_id)+ .expect("replacement tool")+ .1+ .authorization_id(),+ Some(new_id)+ );+ });++ let other_thread = new_test_thread(cx).await;+ let (other_id, other_response) =+ request_test_permission_with_id(&other_thread, tool_id.clone(), cx);+ assert_ne!(other_id, old_id);+ assert_ne!(other_id, new_id);+ other_thread.update(cx, |thread, cx| {+ thread.cancel_permission_request(new_id, cx);+ assert_eq!(+ thread+ .tool_call(&tool_id)+ .expect("other thread tool")+ .1+ .authorization_id(),+ Some(other_id)+ );+ thread.cancel_permission_request(other_id, cx);+ });+ assert!(matches!(+ other_response.await,+ RequestPermissionOutcome::Cancelled+ ));+ thread.update(cx, |thread, cx| {+ thread.cancel_permission_request(other_id, cx);+ thread.authorize_permission_request(+ new_id,+ SelectedPermissionOutcome::new(+ "allow".into(),+ acp_v1::PermissionOptionKind::AllowOnce,+ ),+ cx,+ );+ });+ assert!(matches!(+ new_response.await,+ RequestPermissionOutcome::Selected(outcome)+ if outcome.option_id == "allow".into()+ && outcome.option_kind == acp_v1::PermissionOptionKind::AllowOnce+ ));+ thread.read_with(cx, |thread, _| {+ assert!(thread.permission_request(new_id).is_none());+ assert_eq!(thread.pending_permission_requests().count(), 0);+ let (_, call) = thread.tool_call(&tool_id).expect("selected replacement");+ assert!(call.authorization_id().is_none());+ assert_eq!(call.status(), ToolCallStatus::InProgress);+ });+ assert_eq!(+ *events.borrow(),+ [+ (true, old_id),+ (false, old_id),+ (true, new_id),+ (false, new_id)+ ]+ );+ }++ #[gpui::test]+ async fn test_permission_selection_validates_offered_id_and_derives_kind(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ for (kind, option_id, offered_kind, spoofed_kind, expected) in [+ (+ AuthorizationKind::PermissionGrant,+ "allow",+ acp_v1::PermissionOptionKind::AllowOnce,+ acp_v1::PermissionOptionKind::RejectOnce,+ ToolCallStatus::InProgress,+ ),+ (+ AuthorizationKind::PermissionGrant,+ "reject",+ acp_v1::PermissionOptionKind::RejectOnce,+ acp_v1::PermissionOptionKind::AllowOnce,+ ToolCallStatus::Rejected,+ ),+ (+ AuthorizationKind::ActionChoice,+ "reject",+ acp_v1::PermissionOptionKind::RejectOnce,+ acp_v1::PermissionOptionKind::AllowOnce,+ ToolCallStatus::InProgress,+ ),+ ] {+ let allow = acp_v1::PermissionOption::new(+ "allow",+ "Allow",+ acp_v1::PermissionOptionKind::AllowOnce,+ );+ let reject = acp_v1::PermissionOption::new(+ "reject",+ "Reject",+ acp_v1::PermissionOptionKind::RejectOnce,+ );+ let choice = PermissionOptionChoice {+ allow: allow.clone(),+ deny: reject.clone(),+ sub_patterns: vec!["^cargo build$".into()],+ };+ for options in [+ PermissionOptions::Flat(vec![allow, reject]),+ PermissionOptions::Dropdown(vec![choice.clone()]),+ PermissionOptions::DropdownWithPatterns {+ choices: vec![choice],+ patterns: vec![+ PermissionPattern {+ pattern: "^cargo build$".into(),+ display_name: "cargo build".into(),+ },+ PermissionPattern {+ pattern: "^git status$".into(),+ display_name: "git status".into(),+ },+ ],+ tool_name: "test".into(),+ },+ ] {+ let (mut selected_outcome, expected_patterns) = match &options {+ PermissionOptions::Flat(_) => (+ SelectedPermissionOutcome::new(option_id.into(), offered_kind),+ None,+ ),+ PermissionOptions::Dropdown(choices) => (+ choices+ .first()+ .expect("choice")+ .build_outcome(option_id == "allow"),+ Some(vec!["^cargo build$".to_owned()]),+ ),+ PermissionOptions::DropdownWithPatterns { .. } => (+ options+ .build_outcome_for_checked_patterns(&[1], option_id == "allow")+ .expect("checked pattern"),+ Some(vec!["^git status$".to_owned()]),+ ),+ };+ selected_outcome.option_kind = spoofed_kind;+ let thread = new_test_thread(cx).await;+ let (events, _subscription) = track_permission_events(&thread, cx);+ let tool_id = acp_v1::ToolCallId::new("choice");+ let (request_id, response) = thread.update(cx, |thread, cx| {+ thread+ .request_tool_call_authorization_with_id(+ acp_v1::ToolCall::new(tool_id.clone(), "Choose").into(),+ options,+ kind,+ cx,+ )+ .expect("permission request")+ });+ thread.update(cx, |thread, cx| {+ thread.authorize_permission_request(+ request_id,+ SelectedPermissionOutcome::new("not-offered".into(), spoofed_kind),+ cx,+ );+ let request = thread+ .permission_request(request_id)+ .expect("invalid choice stays pending");+ assert_eq!(request.kind, kind);+ assert_eq!(request.tool_call_id, tool_id);+ assert_eq!(thread.pending_permission_requests().count(), 1);+ let (_, call) = thread.tool_call(&tool_id).expect("waiting tool");+ assert_eq!(call.authorization_id(), Some(request_id));+ assert_eq!(call.status(), ToolCallStatus::WaitingForConfirmation);+ });+ assert_eq!(*events.borrow(), [(true, request_id)]);+ thread.update(cx, |thread, cx| {+ thread.authorize_permission_request(request_id, selected_outcome, cx);+ assert!(thread.permission_request(request_id).is_none());+ assert!(thread.permission_request_for_tool(&tool_id).is_none());+ assert_eq!(thread.pending_permission_requests().count(), 0);+ let (_, call) = thread.tool_call(&tool_id).expect("selected tool");+ assert!(call.authorization_id().is_none());+ assert_eq!(call.status(), expected);+ });+ assert_eq!(*events.borrow(), [(true, request_id), (false, request_id)]);+ let RequestPermissionOutcome::Selected(outcome) = response.await else {+ panic!("expected selected permission");+ };+ assert_eq!(outcome.option_id, option_id.into());+ assert_eq!(outcome.option_kind, offered_kind);+ match (outcome.params, expected_patterns) {+ (Some(SelectedPermissionParams::Terminal { patterns }), Some(expected)) => {+ assert_eq!(patterns, expected);+ }+ (None, None) => {}+ _ => panic!("native permission parameters were not preserved"),+ }+ }+ }+ }++ #[gpui::test]+ async fn test_entry_removal_cleans_permission_records_without_reusing_identity(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ for refuse_prompt in [false, true] {+ let thread = new_test_thread(cx).await;+ thread.update(cx, |thread, cx| {+ thread.push_user_content_block(None, "retained".into(), cx);+ });+ let refusal_turn = refuse_prompt.then(|| start_test_turn(&thread, cx));+ let retained_tool = acp_v1::ToolCallId::new("retained");+ let (retained_id, retained_response) =+ request_test_permission_with_id(&thread, retained_tool.clone(), cx);+ let client_id = ClientUserMessageId::new();+ thread.update(cx, |thread, cx| {+ thread.push_user_content_block(Some(client_id.clone()), "remove me".into(), cx);+ });+ let removed_tool = acp_v1::ToolCallId::new("reused");+ let (removed_id, removed_response) =+ request_test_permission_with_id(&thread, removed_tool.clone(), cx);+ if let Some((complete, turn)) = refusal_turn {+ complete+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::Refusal)))+ .expect("turn should still be running");+ turn.await.expect("refusal should complete");+ } else {+ thread+ .update(cx, |thread, cx| thread.rewind(client_id, cx))+ .await+ .expect("rewind should complete");+ }+ assert!(matches!(+ removed_response.await,+ RequestPermissionOutcome::Cancelled+ ));+ thread.read_with(cx, |thread, _| {+ assert!(thread.tool_call(&removed_tool).is_none());+ assert!(thread.permission_request(removed_id).is_none());+ assert!(thread.permission_request_for_tool(&removed_tool).is_none());+ assert_eq!(+ thread+ .pending_permission_requests()+ .map(|request| request.id)+ .collect::<Vec<_>>(),+ [retained_id]+ );+ assert_eq!(+ thread+ .tool_call(&retained_tool)+ .expect("retained tool")+ .1+ .authorization_id(),+ Some(retained_id)+ );+ });+ let (reopened_id, reopened_response) =+ request_test_permission_with_id(&thread, removed_tool.clone(), cx);+ assert_ne!(reopened_id, removed_id);+ assert_ne!(reopened_id, retained_id);+ thread.update(cx, |thread, cx| {+ thread.cancel_permission_request(removed_id, cx);+ thread.authorize_permission_request(+ removed_id,+ SelectedPermissionOutcome::new(+ "reject".into(),+ acp_v1::PermissionOptionKind::RejectOnce,+ ),+ cx,+ );+ let (_, call) = thread.tool_call(&removed_tool).expect("reopened tool");+ assert_eq!(call.authorization_id(), Some(reopened_id));+ assert_eq!(call.status(), ToolCallStatus::WaitingForConfirmation);+ assert_eq!(+ thread+ .pending_permission_requests()+ .map(|request| request.id)+ .collect::<Vec<_>>(),+ [retained_id, reopened_id]+ );+ thread.cancel_permission_request(retained_id, cx);+ thread.cancel_permission_request(reopened_id, cx);+ assert!(thread.permission_request(retained_id).is_none());+ assert!(thread.permission_request(reopened_id).is_none());+ assert_eq!(thread.pending_permission_requests().count(), 0);+ for tool_id in [&retained_tool, &removed_tool] {+ let (_, call) = thread.tool_call(tool_id).expect("cancelled tool");+ assert!(call.authorization_id().is_none());+ assert!(thread.permission_request_for_tool(tool_id).is_none());+ }+ });+ assert!(matches!(+ retained_response.await,+ RequestPermissionOutcome::Cancelled+ ));+ assert!(matches!(+ reopened_response.await,+ RequestPermissionOutcome::Cancelled+ ));+ }+ }++ fn track_permission_events(+ thread: &Entity<AcpThread>,+ cx: &mut TestAppContext,+ ) -> (Rc<RefCell<Vec<(bool, PermissionRequestId)>>>, Subscription) {+ let events = Rc::new(RefCell::new(Vec::new()));+ let subscription = cx.update(|cx| {+ cx.subscribe(thread, {+ let events = events.clone();+ move |_, event, _| match event {+ AcpThreadEvent::ToolAuthorizationRequested(id) => {+ events.borrow_mut().push((true, *id))+ }+ AcpThreadEvent::ToolAuthorizationReceived(id) => {+ events.borrow_mut().push((false, *id))+ }+ _ => {}+ }+ })+ });+ (events, subscription)+ }+fn start_test_turn(thread: &Entity<AcpThread>,cx: &mut TestAppContext,@@ -19249,9 +20050,17 @@ mod tests {tool_call_id: acp_v1::ToolCallId,cx: &mut TestAppContext,) -> Task<RequestPermissionOutcome> {+ request_test_permission_with_id(thread, tool_call_id, cx).1+ }++ fn request_test_permission_with_id(+ thread: &Entity<AcpThread>,+ tool_call_id: acp_v1::ToolCallId,+ cx: &mut TestAppContext,+ ) -> (PermissionRequestId, Task<RequestPermissionOutcome>) {thread.update(cx, |thread, cx| {thread- .request_tool_call_authorization(+ .request_tool_call_authorization_with_id(acp_v1::ToolCall::new(tool_call_id, "Needs permission").into(),PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(@@ -19417,7 +20226,8 @@ mod tests {cx.run_until_parked();assert_eq!(cx.active_idle_sleep_preventions(), 1);let tool_call_id = acp_v1::ToolCallId::new("permission");- let permission = request_test_permission(&thread, tool_call_id.clone(), cx);+ let (permission_id, permission) =+ request_test_permission_with_id(&thread, tool_call_id.clone(), cx);cx.run_until_parked();assert!(thread.read_with(cx, |thread, _| thread.is_waiting_for_confirmation()));assert_eq!(cx.active_idle_sleep_preventions(), 0);@@ -19456,6 +20266,17 @@ mod tests {Some(acp_v1::ToolCallStatus::Completed));assert!(!thread.is_waiting_for_confirmation());+ assert!(thread.permission_request(permission_id).is_none());+ assert!(thread.permission_request_for_tool(&tool_call_id).is_none());+ assert_eq!(thread.pending_permission_requests().count(), 0);+ assert!(+ thread+ .tool_call(&tool_call_id)+ .expect("terminal tool")+ .1+ .authorization_id()+ .is_none()+ );});assert!(matches!(permission.await,diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rsindex 2c1f0ce5c17..21f81b72948 100644--- a/crates/acp_thread/src/connection.rs+++ b/crates/acp_thread/src/connection.rs@@ -624,6 +624,26 @@ impl PermissionOptions {}}+ pub fn option_for_id(+ &self,+ id: &acp_v1::PermissionOptionId,+ ) -> Option<&acp_v1::PermissionOption> {+ match self {+ Self::Flat(options) => options.iter().find(|option| &option.option_id == id),+ Self::Dropdown(choices) | Self::DropdownWithPatterns { choices, .. } => {+ choices.iter().find_map(|choice| {+ if &choice.allow.option_id == id {+ Some(&choice.allow)+ } else if &choice.deny.option_id == id {+ Some(&choice.deny)+ } else {+ None+ }+ })+ }+ }+ }+pub fn first_option_of_kind(&self,kind: acp_v1::PermissionOptionKind,diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rsindex 9968cff0e42..d60713f729d 100644--- a/crates/agent_servers/src/acp.rs+++ b/crates/agent_servers/src/acp.rs@@ -4493,6 +4493,22 @@ exit 7Arc<std::sync::Mutex<Vec<acp::SessionUpdate>>>,Arc<std::sync::Mutex<Option<async_channel::Receiver<()>>>>,Task<anyhow::Result<()>>,+ ) {+ connect_fake_agent_with_handle(close_session_gate, None, cx).await+ }++ async fn connect_fake_agent_with_handle(+ close_session_gate: Option<async_channel::Receiver<()>>,+ agent_sender: Option<futures::channel::oneshot::Sender<ConnectionTo<Client>>>,+ cx: &mut gpui::TestAppContext,+ ) -> (+ Rc<AcpConnection>,+ Entity<project::Project>,+ Arc<AtomicUsize>,+ Arc<AtomicUsize>,+ Arc<std::sync::Mutex<Vec<acp::SessionUpdate>>>,+ Arc<std::sync::Mutex<Option<async_channel::Receiver<()>>>>,+ Task<anyhow::Result<()>>,) {cx.update(|cx| {let store = settings::SettingsStore::test(cx);@@ -4617,7 +4633,12 @@ exit 7async move |_notif: acp::CancelNotification, _cx| Ok(()),agent_client_protocol::on_receive_notification!(),)- .connect_to(agent_transport);+ .connect_with(agent_transport, async move |agent| {+ if let Some(sender) = agent_sender {+ assert!(sender.send(agent).is_ok(), "receive fake agent handle");+ }+ futures::future::pending::<Result<(), agent_client_protocol::Error>>().await+ });let agent_io_task = cx.background_spawn(agent_future);@@ -4706,6 +4727,172 @@ exit 7)}+ #[gpui::test]+ async fn test_permission_rpc_cancellation_does_not_cancel_successor(+ cx: &mut gpui::TestAppContext,+ ) {+ let (agent_sender, agent_receiver) = futures::channel::oneshot::channel();+ let (connection, project, _, _, _, _, _keep_agent_alive) =+ connect_fake_agent_with_handle(None, Some(agent_sender), cx).await;+ let agent = agent_receiver.await.expect("fake agent handle");+ let session_id = acp::SessionId::new("permission-session");+ let thread = cx+ .update(|cx| {+ connection.clone().load_session(+ session_id.clone(),+ project,+ PathList::new(&[std::path::Path::new("/a")]),+ None,+ cx,+ )+ })+ .await+ .expect("load permission session");+ cx.background_executor.allow_parking();++ let timeout = cx+ .background_executor+ .timer(std::time::Duration::from_secs(5));+ let exchange = async {+ let tool_id = acp::ToolCallId::new("reused-tool");+ let permission = |option_id: &str| {+ acp::RequestPermissionRequest::new(+ session_id.clone(),+ acp::ToolCallUpdate::new(+ tool_id.clone(),+ acp::ToolCallUpdateFields::default()+ .title("Run a command")+ .status(acp::ToolCallStatus::Pending),+ ),+ vec![acp::PermissionOption::new(+ option_id.to_owned(),+ "Allow once",+ acp::PermissionOptionKind::AllowOnce,+ )],+ )+ };+ let old = agent.send_request(permission("allow-old"));+ cx.run_until_parked();+ let old_id = thread.read_with(cx, |thread, _| {+ let request = thread+ .permission_request_for_tool(&tool_id)+ .expect("first permission request");+ assert_eq!(request.tool_call_id, tool_id);+ request.id+ });++ let successor = agent.send_request(permission("allow-successor"));+ let executor = cx.executor();+ let dispatcher = executor+ .dispatcher()+ .as_test()+ .expect("deterministic test dispatcher");+ let drain_sdk = || {+ for _ in 0..1000 {+ if !dispatcher.tick(true) {+ return;+ }+ }+ panic!("SDK dispatch did not drain within bounded ticks");+ };+ drain_sdk();+ let (acknowledgment, mut dispatched) = futures::channel::oneshot::channel();+ let barrier: ForegroundWork = Box::new(ForegroundBarrier { acknowledgment });+ assert!(+ connection.dispatch_tx.unbounded_send(barrier).is_ok(),+ "enqueue permission setup barrier"+ );+ let mut setup_queued = false;+ for _ in 0..1000 {+ if dispatched+ .try_recv()+ .expect("live permission setup barrier")+ .is_some()+ {+ setup_queued = true;+ break;+ }+ assert!(executor.tick(), "permission dispatch must make progress");+ }+ assert!(+ setup_queued,+ "permission setup queued within bounded dispatch"+ );+ thread.read_with(cx, |thread, _| {+ assert_eq!(+ thread+ .permission_request_for_tool(&tool_id)+ .expect("old request still active before successor setup")+ .id,+ old_id+ );+ });++ // Foreground FIFO puts successor setup before old cancellation cleanup,+ // and cleanup before the old waiter consumes its superseded outcome.+ old.cancel().expect("send old RPC cancellation");+ drain_sdk();++ let error = old+ .block_task()+ .await+ .expect_err("old RPC must exercise RequestCancelled cleanup");+ assert_eq!(error.code, ErrorCode::RequestCancelled);+ let successor_id = thread.read_with(cx, |thread, _| {+ assert!(thread.permission_request(old_id).is_none());+ let successor_id = thread+ .permission_request_for_tool(&tool_id)+ .expect("successor survives old RPC cancellation")+ .id;+ assert_ne!(successor_id, old_id);+ assert_eq!(thread.pending_permission_requests().count(), 1);+ let (_, call) = thread.tool_call(&tool_id).expect("tool presentation");+ assert_eq!(call.authorization_id(), Some(successor_id));+ assert_eq!(+ call.status(),+ acp_thread::ToolCallStatus::WaitingForConfirmation+ );+ successor_id+ });+ thread.update(cx, |thread, cx| {+ thread.authorize_permission_request(+ successor_id,+ acp_thread::SelectedPermissionOutcome::new(+ acp::PermissionOptionId::new("allow-successor"),+ acp::PermissionOptionKind::AllowOnce,+ ),+ cx,+ );+ });+ let response = successor+ .block_task()+ .await+ .expect("successor RPC receives its exact offered choice");+ assert_eq!(+ response.outcome,+ acp::RequestPermissionOutcome::Selected(acp::SelectedPermissionOutcome::new(+ "allow-successor"+ ))+ );+ thread.read_with(cx, |thread, _| {+ assert!(thread.permission_request(successor_id).is_none());+ assert_eq!(thread.pending_permission_requests().count(), 0);+ let (_, call) = thread.tool_call(&tool_id).expect("tool presentation");+ assert_eq!(call.authorization_id(), None);+ assert_eq!(call.status(), acp_thread::ToolCallStatus::InProgress);+ });+ thread+ .update(cx, |thread, cx| thread.send_raw("channel still usable", cx))+ .await+ .expect("next SDK prompt succeeds after old RPC cancellation");+ };+ futures::pin_mut!(exchange, timeout);+ if let futures::future::Either::Right(_) = futures::future::select(exchange, timeout).await+ {+ panic!("timed out exercising permission RPC supersession and cancellation");+ }+ }+#[gpui::test]async fn test_loaded_sessions_keep_state_until_last_handle_drops(cx: &mut gpui::TestAppContext,@@ -5698,24 +5885,24 @@ fn handle_request_permission(};let cancellation = responder.cancellation();- let tool_call_id = args.tool_call.tool_call_id.clone();cx.spawn(async move |cx| {- let result: Result<_, acp::Error> = async {- let task = thread- .update(cx, |thread, cx| {- thread.request_tool_call_authorization(- args.tool_call,- acp_thread::PermissionOptions::Flat(args.options),- acp_thread::AuthorizationKind::PermissionGrant,- cx,- )- })- .flatten_acp()?;- cancellation- .run_until_cancelled(async { Ok(task.await) })- .await- }- .await;+ let (request_id, task) = match thread+ .update(cx, |thread, cx| {+ thread.request_tool_call_authorization_with_id(+ args.tool_call,+ acp_thread::PermissionOptions::Flat(args.options),+ acp_thread::AuthorizationKind::PermissionGrant,+ cx,+ )+ })+ .flatten_acp()+ {+ Ok(request) => request,+ Err(error) => return respond_err(responder, error),+ };+ let result = cancellation+ .run_until_cancelled(async { Ok(task.await) })+ .await;match result {Ok(outcome) => {@@ -5727,7 +5914,7 @@ fn handle_request_permission(if e.code == ErrorCode::RequestCancelled {thread.update(cx, |thread, cx| {- thread.cancel_tool_call_authorization(&tool_call_id, cx)+ thread.cancel_permission_request(request_id, cx)}).log_err();}diff --git a/crates/agent_ui/src/agent_ui.rs b/crates/agent_ui/src/agent_ui.rsindex 7d28603d468..e40c40ebab2 100644--- a/crates/agent_ui/src/agent_ui.rs+++ b/crates/agent_ui/src/agent_ui.rs@@ -346,6 +346,11 @@ actions!(pub struct AuthorizeToolCall {/// The tool call ID to authorize.pub tool_call_id: String,+ #[serde(default)]+ #[schemars(with = "Option<String>")]+ pub request_id: Option<acp_thread::PermissionRequestId>,+ #[serde(default)]+ pub session_id: Option<String>,/// The permission option ID to use.pub option_id: String,/// The kind of permission option (serialized as string).@@ -360,6 +365,11 @@ pub struct AuthorizeToolCall {pub struct SelectPermissionGranularity {/// The tool call ID for which to select the granularity.pub tool_call_id: String,+ #[serde(default)]+ #[schemars(with = "Option<String>")]+ pub request_id: Option<acp_thread::PermissionRequestId>,+ #[serde(default)]+ pub session_id: Option<String>,/// The index of the selected granularity option.pub index: usize,}@@ -371,6 +381,11 @@ pub struct SelectPermissionGranularity {pub struct ToggleCommandPattern {/// The tool call ID for which to toggle the pattern.pub tool_call_id: String,+ #[serde(default)]+ #[schemars(with = "Option<String>")]+ pub request_id: Option<acp_thread::PermissionRequestId>,+ #[serde(default)]+ pub session_id: Option<String>,/// The index of the command pattern to toggle.pub pattern_index: usize,}diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex ee223fdd877..185586de4ef 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -2,8 +2,8 @@ use acp_thread::{AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk,AuthRequired, ClientUserMessageId, ElicitationEntryId, ElicitationStatus, ElicitationStore,ForegroundActivity, LoadError, MaxOutputTokensError, MentionUri, PermissionOptionChoice,- PermissionOptions, PermissionPattern, RetryStatus, SelectedPermissionOutcome, ThreadStatus,- ToolCall, ToolCallContent, ToolCallStatus,+ PermissionOptions, PermissionPattern, PermissionRequest, PermissionRequestId, RetryStatus,+ SelectedPermissionOutcome, ThreadStatus, ToolCall, ToolCallContent, ToolCallStatus,};use acp_thread::{AgentConnection, Plan};use action_log::{ActionLog, ActionLogTelemetry, DiffStats};@@ -285,7 +285,8 @@ impl ProfileProvider for Entity<agent::Thread> {#[derive(Default)]pub(crate) struct Conversation {threads: HashMap<acp_v1::SessionId, Entity<AcpThread>>,- permission_requests: IndexMap<acp_v1::SessionId, Vec<acp_v1::ToolCallId>>,+ permission_requests: IndexMap<acp_v1::SessionId, Vec<PermissionRequestId>>,+ permission_selections: HashMap<PermissionRequestId, thread_view::PermissionSelection>,elicitation_requests: IndexMap<acp_v1::SessionId, Vec<ElicitationEntryId>>,subscriptions: Vec<Subscription>,updated_at: Option<Instant>,@@ -295,29 +296,27 @@ impl Conversation {pub fn register_thread(&mut self, thread: Entity<AcpThread>, cx: &mut Context<Self>) {let thread_state = thread.read(cx);let session_id = thread_state.session_id().clone();- for entry in thread_state.entries() {- if let AgentThreadEntry::ToolCall(tool_call) = entry- && matches!(tool_call.status(), ToolCallStatus::WaitingForConfirmation)- {- self.add_permission_request(&session_id, &tool_call.id);- }+ for request in thread_state.pending_permission_requests() {+ self.add_permission_request(&session_id, &request.id);}let subscription = cx.subscribe(&thread, {let session_id = session_id.clone();- move |this, _thread, event, _cx| {+ move |this, _thread, event, cx| {match event {AcpThreadEvent::NoticesUpdated => return,AcpThreadEvent::ToolAuthorizationRequested(id) => {this.add_permission_request(&session_id, id);}AcpThreadEvent::ToolAuthorizationReceived(id) => {- if let Some(tool_calls) = this.permission_requests.get_mut(&session_id) {- tool_calls.retain(|tool_call_id| tool_call_id != id);- if tool_calls.is_empty() {+ this.permission_selections.remove(id);+ if let Some(requests) = this.permission_requests.get_mut(&session_id) {+ requests.retain(|request_id| request_id != id);+ if requests.is_empty() {this.permission_requests.shift_remove(&session_id);}}+ cx.notify();}AcpThreadEvent::ElicitationRequested(id) => {this.elicitation_requests@@ -360,32 +359,114 @@ impl Conversation {self.threads.insert(session_id, thread);}+ fn set_permission_choice(+ &mut self,+ session_id: &acp_v1::SessionId,+ request_id: PermissionRequestId,+ index: usize,+ cx: &mut Context<Self>,+ ) {+ if self+ .permission_request(session_id, request_id, cx)+ .is_none()+ {+ return;+ }+ self.permission_selections+ .insert(request_id, thread_view::PermissionSelection::Choice(index));+ cx.notify();+ }++ fn toggle_permission_pattern(+ &mut self,+ session_id: &acp_v1::SessionId,+ request_id: PermissionRequestId,+ pattern_index: usize,+ cx: &mut Context<Self>,+ ) {+ let Some(request) = self.permission_request(session_id, request_id, cx) else {+ return;+ };+ let pattern_count = match &request.options {+ PermissionOptions::DropdownWithPatterns { patterns, .. } => patterns.len(),+ _ => 0,+ };+ match self.permission_selections.get_mut(&request_id) {+ Some(selection @ thread_view::PermissionSelection::SelectedPatterns(_)) => {+ selection.toggle_pattern(pattern_index);+ }+ _ => {+ self.permission_selections.insert(+ request_id,+ thread_view::PermissionSelection::SelectedPatterns(+ (0..pattern_count).collect(),+ ),+ );+ }+ }+ cx.notify();+ }+fn add_permission_request(&mut self,session_id: &acp_v1::SessionId,- tool_call_id: &acp_v1::ToolCallId,+ request_id: &PermissionRequestId,) {let requests = self.permission_requests.entry(session_id.clone()).or_default();- if !requests.contains(tool_call_id) {- requests.push(tool_call_id.clone());+ if !requests.contains(request_id) {+ requests.push(*request_id);}}- pub fn permission_options_for_tool_call<'a>(+ fn permission_request<'a>(&'a self,session_id: &acp_v1::SessionId,- tool_call_id: acp_v1::ToolCallId,+ request_id: PermissionRequestId,cx: &'a App,- ) -> Option<&'a PermissionOptions> {- let thread = self.threads.get(session_id)?;- let (_, tool_call) = thread.read(cx).tool_call(&tool_call_id)?;- if !matches!(tool_call.status(), ToolCallStatus::WaitingForConfirmation) {- return None;+ ) -> Option<&'a PermissionRequest> {+ self.threads+ .get(session_id)?+ .read(cx)+ .permission_request(request_id)+ }++ fn pending_permission_request_for_session<'a>(+ &'a self,+ session_id: &acp_v1::SessionId,+ cx: &'a App,+ ) -> Option<&'a PermissionRequest> {+ self.permission_requests+ .get(session_id)?+ .iter()+ .find_map(|id| self.permission_request(session_id, *id, cx))+ }++ fn pending_permission_request<'a>(+ &'a self,+ session_id: &acp_v1::SessionId,+ cx: &'a App,+ ) -> Option<(acp_v1::SessionId, &'a PermissionRequest)> {+ if self+ .threads+ .get(session_id)?+ .read(cx)+ .parent_session_id()+ .is_some()+ {+ return Some((+ session_id.clone(),+ self.pending_permission_request_for_session(session_id, cx)?,+ ));}- Some(&tool_call.authorization()?.options)+ self.permission_requests.keys().find_map(|session_id| {+ Some((+ session_id.clone(),+ self.pending_permission_request_for_session(session_id, cx)?,+ ))+ })}pub fn pending_tool_call<'a>(@@ -393,36 +474,22 @@ impl Conversation {session_id: &acp_v1::SessionId,cx: &'a App,) -> Option<(acp_v1::SessionId, acp_v1::ToolCallId, &'a PermissionOptions)> {- let thread = self.threads.get(session_id)?;- let is_subagent = thread.read(cx).parent_session_id().is_some();- let (result_session_id, thread, tool_id) = if is_subagent {- let id = self.permission_requests.get(session_id)?.iter().next()?;- (session_id.clone(), thread, id)- } else {- let (id, tool_calls) = self.permission_requests.first()?;- let thread = self.threads.get(id)?;- let tool_id = tool_calls.iter().next()?;- (id.clone(), thread, tool_id)- };- let (_, tool_call) = thread.read(cx).tool_call(tool_id)?;-- if !matches!(tool_call.status(), ToolCallStatus::WaitingForConfirmation) {- return None;- }+ let (result_session_id, request) = self.pending_permission_request(session_id, cx)?;Some((result_session_id,- tool_id.clone(),- &tool_call.authorization()?.options,+ request.tool_call_id.clone(),+ &request.options,))}pub fn subagents_awaiting_permission(&self, cx: &App) -> Vec<(acp_v1::SessionId, usize)> {self.permission_requests.iter()- .filter_map(|(session_id, tool_call_ids)| {+ .filter_map(|(session_id, _)| {let thread = self.threads.get(session_id)?;- if thread.read(cx).parent_session_id().is_some() && !tool_call_ids.is_empty() {- Some((session_id.clone(), tool_call_ids.len()))+ let count = self.pending_tool_call_count_for_session(session_id, cx);+ if thread.read(cx).parent_session_id().is_some() && count > 0 {+ Some((session_id.clone(), count))} else {None}@@ -438,19 +505,25 @@ impl Conversation {session_id: &acp_v1::SessionId,cx: &App,) -> Option<acp_v1::ToolCallId> {- let thread = self.threads.get(session_id)?;- let tool_call_id = self.permission_requests.get(session_id)?.iter().next()?;- let (_, tool_call) = thread.read(cx).tool_call(tool_call_id)?;- if !matches!(tool_call.status(), ToolCallStatus::WaitingForConfirmation) {- return None;- }- Some(tool_call_id.clone())+ Some(+ self.pending_permission_request_for_session(session_id, cx)?+ .tool_call_id+ .clone(),+ )}- pub fn pending_tool_call_count_for_session(&self, session_id: &acp_v1::SessionId) -> usize {+ pub fn pending_tool_call_count_for_session(+ &self,+ session_id: &acp_v1::SessionId,+ cx: &App,+ ) -> usize {self.permission_requests.get(session_id)- .map(|tool_call_ids| tool_call_ids.len())+ .map(|ids| {+ ids.iter()+ .filter(|id| self.permission_request(session_id, **id, cx).is_some())+ .count()+ }).unwrap_or(0)}@@ -474,12 +547,11 @@ impl Conversation {kind: acp_v1::PermissionOptionKind,cx: &mut Context<Self>,) -> Option<()> {- let (authorize_session_id, tool_call_id, options) =- self.pending_tool_call(session_id, cx)?;- let option = permission_option_for_action(options, kind)?;- self.authorize_tool_call(+ let (authorize_session_id, request) = self.pending_permission_request(session_id, cx)?;+ let option = permission_option_for_action(&request.options, kind)?;+ self.authorize_permission_request(authorize_session_id,- tool_call_id,+ request.id,SelectedPermissionOutcome::new(option.option_id.clone(), option.kind),cx,);@@ -489,28 +561,51 @@ impl Conversation {pub fn authorize_with_granularity(&mut self,session_id: acp_v1::SessionId,- tool_call_id: acp_v1::ToolCallId,- selection: Option<&thread_view::PermissionSelection>,+ request_id: PermissionRequestId,is_allow: bool,cx: &mut Context<Self>,) -> Option<()> {- let options =- self.permission_options_for_tool_call(&session_id, tool_call_id.clone(), cx)?;- let outcome = resolve_outcome_from_selection(options, selection, is_allow)?;- self.authorize_tool_call(session_id, tool_call_id, outcome, cx);+ let request = self.permission_request(&session_id, request_id, cx)?;+ let outcome = resolve_outcome_from_selection(+ &request.options,+ self.permission_selections.get(&request_id),+ is_allow,+ )?;+ self.authorize_permission_request(session_id, request_id, outcome, cx);Some(())}- pub fn authorize_tool_call(+ #[cfg(test)]+ fn authorize_tool_call(&mut self,session_id: acp_v1::SessionId,tool_call_id: acp_v1::ToolCallId,outcome: SelectedPermissionOutcome,cx: &mut Context<Self>,+ ) {+ let Some(request) = self+ .threads+ .get(&session_id)+ .and_then(|thread| thread.read(cx).permission_request_for_tool(&tool_call_id))+ else {+ return;+ };+ self.authorize_permission_request(session_id, request.id, outcome, cx);+ }++ pub fn authorize_permission_request(+ &mut self,+ session_id: acp_v1::SessionId,+ request_id: PermissionRequestId,+ outcome: SelectedPermissionOutcome,+ cx: &mut Context<Self>,) {let Some(thread) = self.threads.get(&session_id) else {return;};+ if thread.read(cx).permission_request(request_id).is_none() {+ return;+ }let agent_telemetry_id = thread.read(cx).connection().telemetry_id();let session_id = thread.read(cx).session_id().clone();@@ -522,7 +617,7 @@ impl Conversation {);thread.update(cx, |thread, cx| {- thread.authorize_tool_call(tool_call_id, outcome, cx);+ thread.authorize_permission_request(request_id, outcome, cx);});cx.notify();}@@ -9516,7 +9611,8 @@ pub(crate) mod tests {let (entry_index, hunk_buffer) = thread.read_with(cx, |thread, _| {let (entry_index, call) = thread.tool_call(&tool_call_id).expect("tool exists");- assert!(call.authorization().is_some());+ let request_id = call.authorization_id().expect("authorization exists");+ assert!(thread.permission_request(request_id).is_some());let [acp_thread::ToolCallContent::DiffPatch { render, .. }, ..] = call.content() else {panic!("expected patch content");};@@ -12590,7 +12686,10 @@ pub(crate) mod tests {);// Verify the options count (granularity options only, no separate Deny option)- if let Some(authorization) = tool_call.authorization() {+ if let Some(authorization) = tool_call+ .authorization_id()+ .and_then(|id| thread.permission_request(id))+ {let options = &authorization.options;let PermissionOptions::Dropdown(choices) = options else {panic!("Expected dropdown permission options");@@ -12688,7 +12787,10 @@ pub(crate) mod tests {assert!(tool_call.is_some(), "Expected a tool call entry");let tool_call = tool_call.unwrap();- if let Some(authorization) = tool_call.authorization() {+ if let Some(authorization) = tool_call+ .authorization_id()+ .and_then(|id| thread.permission_request(id))+ {let options = &authorization.options;let PermissionOptions::Dropdown(choices) = options else {panic!("Expected dropdown permission options");@@ -12777,7 +12879,10 @@ pub(crate) mod tests {assert!(tool_call.is_some(), "Expected a tool call entry");let tool_call = tool_call.unwrap();- if let Some(authorization) = tool_call.authorization() {+ if let Some(authorization) = tool_call+ .authorization_id()+ .and_then(|id| thread.permission_request(id))+ {let options = &authorization.options;let PermissionOptions::Dropdown(choices) = options else {panic!("Expected dropdown permission options");@@ -12870,7 +12975,10 @@ pub(crate) mod tests {assert!(tool_call.is_some(), "Expected a tool call entry");let tool_call = tool_call.unwrap();- if let Some(authorization) = tool_call.authorization() {+ if let Some(authorization) = tool_call+ .authorization_id()+ .and_then(|id| thread.permission_request(id))+ {let options = &authorization.options;let PermissionOptions::Dropdown(choices) = options else {panic!("Expected dropdown permission options");@@ -12963,6 +13071,8 @@ pub(crate) mod tests {window.dispatch_action(crate::AuthorizeToolCall {tool_call_id: "action-test-1".to_string(),+ request_id: None,+ session_id: None,option_id: "allow".to_string(),option_kind: "AllowOnce".to_string(),}@@ -13042,6 +13152,8 @@ pub(crate) mod tests {window.dispatch_action(crate::AuthorizeToolCall {tool_call_id: "pattern-action-test-1".to_string(),+ request_id: None,+ session_id: None,option_id: pattern_option.option_id.0.to_string(),option_kind: "AllowAlways".to_string(),}@@ -13107,7 +13219,18 @@ pub(crate) mod tests {// Verify default granularity is the last option (index 2 = "Only this time")thread_view.read_with(cx, |thread_view, cx| {let state = thread_view.active_thread().unwrap();- let selected = state.read(cx).permission_selections.get(&tool_call_id);+ let state = state.read(cx);+ let request_id = state+ .thread+ .read(cx)+ .permission_request_for_tool(&tool_call_id)+ .expect("permission request exists")+ .id;+ let selected = state+ .conversation+ .read(cx)+ .permission_selections+ .get(&request_id);assert!(selected.is_none(),"Should have no selection initially (defaults to last)"@@ -13119,6 +13242,8 @@ pub(crate) mod tests {window.dispatch_action(crate::SelectPermissionGranularity {tool_call_id: "granularity-test-1".to_string(),+ request_id: None,+ session_id: None,index: 0,}.boxed_clone(),@@ -13131,7 +13256,18 @@ pub(crate) mod tests {// Verify the selection was updatedthread_view.read_with(cx, |thread_view, cx| {let state = thread_view.active_thread().unwrap();- let selected = state.read(cx).permission_selections.get(&tool_call_id);+ let state = state.read(cx);+ let request_id = state+ .thread+ .read(cx)+ .permission_request_for_tool(&tool_call_id)+ .expect("permission request exists")+ .id;+ let selected = state+ .conversation+ .read(cx)+ .permission_selections+ .get(&request_id);assert_eq!(selected.and_then(|s| s.choice_index()),Some(0),@@ -13210,6 +13346,8 @@ pub(crate) mod tests {window.dispatch_action(crate::SelectPermissionGranularity {tool_call_id: "allow-granularity-test-1".to_string(),+ request_id: None,+ session_id: None,index: 1,}.boxed_clone(),@@ -13645,29 +13783,556 @@ pub(crate) mod tests {option_id: &str,cx: &mut TestAppContext,) -> Task<acp_thread::RequestPermissionOutcome> {+ request_test_tool_authorization_with_options(+ thread,+ tool_call_id,+ PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(+ acp_v1::PermissionOptionId::new(option_id),+ "Allow",+ acp_v1::PermissionOptionKind::AllowOnce,+ )]),+ cx,+ )+ .1+ }++ fn request_test_tool_authorization_with_options(+ thread: &Entity<AcpThread>,+ tool_call_id: &str,+ options: PermissionOptions,+ cx: &mut TestAppContext,+ ) -> (+ PermissionRequestId,+ Task<acp_thread::RequestPermissionOutcome>,+ ) {let tool_call_id = acp_v1::ToolCallId::new(tool_call_id);let label = format!("Tool {tool_call_id}");- let option_id = acp_v1::PermissionOptionId::new(option_id);cx.update(|cx| {thread.update(cx, |thread, cx| {thread- .request_tool_call_authorization(+ .request_tool_call_authorization_with_id(acp_v1::ToolCall::new(tool_call_id, label).kind(acp_v1::ToolKind::Edit).into(),- PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(- option_id,- "Allow",- acp_v1::PermissionOptionKind::AllowOnce,- )]),+ options,acp_thread::AuthorizationKind::PermissionGrant,cx,)- .unwrap()+ .expect("permission request should succeed")})})}+ fn select_embedded_child_permission(+ child_view: &Entity<ThreadView>,+ with_patterns: bool,+ cx: &mut VisualTestContext,+ ) {+ let handle = child_view.read_with(cx, |view, _| view.permission_dropdown_handle.clone());+ cx.update(|window, cx| handle.show(window, cx));+ cx.run_until_parked();+ assert!(+ handle.is_deployed(),+ "the embedded child's dropdown should open"+ );+ let choice = cx+ .debug_bounds("MENU_ITEM-Always for terminal")+ .expect("the rendered dropdown should offer the terminal-wide choice");+ cx.simulate_click(choice.center(), gpui::Modifiers::default());+ cx.run_until_parked();++ if with_patterns {+ for _ in 0..2 {+ let pattern = cx+ .debug_bounds("MENU_ITEM-Always for `sort` commands")+ .expect("the rendered persistent dropdown should offer the sort pattern");+ cx.simulate_click(pattern.center(), gpui::Modifiers::default());+ cx.run_until_parked();+ }+ cx.update(|_, cx| handle.hide(cx));+ cx.run_until_parked();+ }+ }++ #[gpui::test]+ async fn test_embedded_child_permission_selection_uses_conversation_and_cleans_up(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let (conversation_view, cx) =+ setup_conversation_view(StubAgentServer::default_response(), cx).await;+ add_to_workspace_with_size(conversation_view.clone(), true, cx);+ cx.update(|_, cx| {+ AgentSettings::override_global(+ AgentSettings {+ notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,+ ..AgentSettings::get_global(cx).clone()+ },+ cx,+ );+ });+ let root_view = active_thread(&conversation_view, cx);+ let (root, conversation) = root_view.read_with(cx, |view, _| {+ (view.thread.clone(), view.conversation.clone())+ });+ let root_session_id = root.read_with(cx, |thread, _| thread.session_id().clone());+ let child_session_id = acp_v1::SessionId::new("embedded-permission-child");+ let child_view = conversation_view.update_in(cx, |view, window, cx| {+ let child = create_test_acp_thread(+ Some(root_session_id.clone()),+ child_session_id.0.as_ref(),+ Rc::new(StubAgentConnection::new()),+ view.project.clone(),+ cx,+ );+ conversation.update(cx, |conversation, cx| {+ conversation.register_thread(child.clone(), cx);+ });+ let child_view =+ view.new_thread_view(child, conversation.clone(), false, None, window, cx);+ view.as_connected_mut()+ .expect("conversation should be connected")+ .threads+ .insert(child_session_id.clone(), child_view.clone());+ child_view+ });+ let child = child_view.read_with(cx, |view, _| view.thread.clone());+ let parent_options =+ ToolPermissionContext::new(TerminalTool::NAME, vec!["cargo build".into()])+ .build_permission_options();+ let (parent_id, parent_response) = request_test_tool_authorization_with_options(+ &root,+ "unrelated-parent",+ parent_options,+ cx,+ );+ root.update(cx, |thread, cx| {+ let mut spawn = acp_v1::ToolCall::new("spawn-child", "Running child")+ .name("spawn_agent")+ .kind(acp_v1::ToolKind::Other)+ .status(acp_v1::ToolCallStatus::InProgress);+ spawn.meta = Some(acp_v1::Meta::from_iter([(+ acp_thread::SUBAGENT_SESSION_INFO_META_KEY.into(),+ serde_json::to_value(acp_thread::SubagentSessionInfo {+ session_id: child_session_id.clone(),+ message_start_index: 0,+ message_end_index: None,+ })+ .expect("subagent session info should serialize"),+ )]));+ thread+ .handle_session_update(acp_v1::SessionUpdate::ToolCall(spawn), cx)+ .expect("running subagent tool should be accepted");+ });+ cx.run_until_parked();+ cx.focus(&root_view);+ cx.dispatch_action(crate::SelectPermissionGranularity {+ tool_call_id: "unrelated-parent".into(),+ request_id: Some(parent_id),+ session_id: Some(root_session_id.0.to_string()),+ index: 0,+ });+ cx.run_until_parked();++ let mut child_request_ids = HashSet::default();+ for with_patterns in [false, true] {+ let command = if with_patterns {+ "cargo test | sort"+ } else {+ "cargo build"+ };+ let options = ToolPermissionContext::new(TerminalTool::NAME, vec![command.into()])+ .build_permission_options();+ let expected_outcome = if with_patterns {+ options+ .build_outcome_for_checked_patterns(&[0], true)+ .expect("the cargo pattern should have an outcome")+ } else {+ let PermissionOptions::Dropdown(choices) = &options else {+ panic!("single-command permission should use the simple dropdown");+ };+ choices+ .first()+ .expect("terminal-wide choice")+ .build_outcome(true)+ };+ for resolution in 0..6 {+ let (request_id, response) = request_test_tool_authorization_with_options(+ &child,+ "reused-child-tool",+ options.clone(),+ cx,+ );+ assert!(child_request_ids.insert(request_id));+ cx.run_until_parked();+ assert!(+ cx.debug_bounds("PERMISSION_BUTTONS-embedded-permission-child-Only this time")+ .is_some(),+ "the running child card should display a fresh default selection in the root"+ );+ assert_eq!(+ active_thread(&conversation_view, cx),+ root_view,+ "the child controls must remain embedded, not in a standalone child view"+ );+ select_embedded_child_permission(&child_view, with_patterns, cx);+ conversation.read_with(cx, |conversation, _| {+ let selection = conversation+ .permission_selections+ .get(&request_id)+ .expect("embedded controls must write to the shared owner");+ if with_patterns {+ assert!(+ matches!(selection, thread_view::PermissionSelection::SelectedPatterns(checked) if checked == &[0])+ );+ } else {+ assert_eq!(selection.choice_index(), Some(0));+ }+ assert_eq!(conversation.permission_selections.len(), 2);+ });+ let selected_buttons = cx+ .debug_bounds(if with_patterns {+ "PERMISSION_BUTTONS-embedded-permission-child-Always for selected commands"+ } else {+ "PERMISSION_BUTTONS-embedded-permission-child-Always for terminal"+ })+ .expect("the embedded card must render the shared selection");++ match resolution % 3 {+ 0 => {+ cx.simulate_click(+ point(+ selected_buttons.left() + px(24.0),+ selected_buttons.center().y,+ ),+ gpui::Modifiers::default(),+ );+ cx.run_until_parked();+ let acp_thread::RequestPermissionOutcome::Selected(outcome) =+ response.await+ else {+ panic!("the embedded Allow button should authorize the child request");+ };+ assert_eq!(outcome.option_id, expected_outcome.option_id);+ assert_eq!(outcome.option_kind, expected_outcome.option_kind);+ match (&outcome.params, &expected_outcome.params) {+ (None, None) => {}+ (+ Some(acp_thread::SelectedPermissionParams::Terminal { patterns }),+ Some(acp_thread::SelectedPermissionParams::Terminal {+ patterns: expected,+ }),+ ) => assert_eq!(patterns, expected),+ _ => panic!(+ "the child outcome should contain only the selected patterns"+ ),+ }+ }+ 1 => {+ child.update(cx, |thread, cx| {+ thread.cancel_permission_request(request_id, cx);+ });+ cx.run_until_parked();+ assert!(matches!(+ response.await,+ acp_thread::RequestPermissionOutcome::Cancelled+ ));+ }+ _ => {+ let (successor_id, successor_response) =+ request_test_tool_authorization_with_options(+ &child,+ "reused-child-tool",+ options.clone(),+ cx,+ );+ assert!(child_request_ids.insert(successor_id));+ cx.run_until_parked();+ assert!(matches!(+ response.await,+ acp_thread::RequestPermissionOutcome::Cancelled+ ));+ conversation.read_with(cx, |conversation, cx| {+ assert!(!conversation.permission_selections.contains_key(&request_id));+ assert!(+ !conversation+ .permission_selections+ .contains_key(&successor_id)+ );+ assert!(+ conversation+ .permission_request(&child_session_id, successor_id, cx)+ .is_some()+ );+ assert_eq!(conversation.permission_selections.len(), 1);+ });+ assert!(+ cx.debug_bounds(+ "PERMISSION_BUTTONS-embedded-permission-child-Only this time"+ )+ .is_some(),+ "a superseding request must not inherit the previous UUID's selection"+ );+ select_embedded_child_permission(&child_view, with_patterns, cx);+ child.update(cx, |thread, cx| {+ thread.cancel_permission_request(successor_id, cx);+ });+ cx.run_until_parked();+ assert!(matches!(+ successor_response.await,+ acp_thread::RequestPermissionOutcome::Cancelled+ ));+ }+ }+ cx.run_until_parked();+ conversation.read_with(cx, |conversation, cx| {+ assert_eq!(conversation.permission_selections.len(), 1);+ assert_eq!(+ conversation+ .permission_selections+ .get(&parent_id)+ .and_then(|selection| selection.choice_index()),+ Some(0),+ "child cleanup must leave the unrelated parent's selection intact"+ );+ assert!(+ conversation+ .permission_request(&root_session_id, parent_id, cx)+ .is_some()+ );+ assert!(+ child_request_ids+ .iter()+ .all(|id| !conversation.permission_selections.contains_key(id)),+ "reused child tool IDs must not accumulate selection entries under old UUIDs"+ );+ assert_eq!(+ conversation.pending_tool_call_count_for_session(&child_session_id, cx),+ 0+ );+ });+ }+ }+ root.update(cx, |thread, cx| {+ thread.cancel_permission_request(parent_id, cx);+ });+ cx.run_until_parked();+ assert!(matches!(+ parent_response.await,+ acp_thread::RequestPermissionOutcome::Cancelled+ ));+ conversation.read_with(cx, |conversation, _| {+ assert!(conversation.permission_selections.is_empty());+ });+ }++ #[gpui::test]+ async fn test_dropped_permission_waiter_selection_and_cancel_cleanup(cx: &mut TestAppContext) {+ init_test(cx);+ let (conversation_view, cx) =+ setup_conversation_view(StubAgentServer::default_response(), cx).await;+ add_to_workspace(conversation_view.clone(), cx);+ let thread_view = active_thread(&conversation_view, cx);+ let thread = thread_view.read_with(cx, |view, _| view.thread.clone());+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());+ let options = ToolPermissionContext::new(TerminalTool::NAME, vec!["cargo build".into()])+ .build_permission_options();++ for cancel in [false, true] {+ let (request_id, response) = thread.update(cx, |thread, cx| {+ thread+ .request_tool_call_authorization_with_id(+ acp_v1::ToolCall::new("dropped-waiter", "Run cargo build")+ .kind(acp_v1::ToolKind::Execute)+ .into(),+ options.clone(),+ acp_thread::AuthorizationKind::PermissionGrant,+ cx,+ )+ .expect("permission request should succeed")+ });+ drop(response);+ cx.run_until_parked();+ conversation_view.update_in(cx, |_, window, cx| {+ window.dispatch_action(+ crate::SelectPermissionGranularity {+ tool_call_id: "dropped-waiter".into(),+ request_id: Some(request_id),+ session_id: Some(session_id.0.to_string()),+ index: 0,+ }+ .boxed_clone(),+ cx,+ );+ });+ cx.run_until_parked();+ thread_view.read_with(cx, |view, cx| {+ assert_eq!(+ view.conversation+ .read(cx)+ .permission_selections+ .get(&request_id)+ .and_then(|selection| selection.choice_index()),+ Some(0)+ );+ assert_eq!(+ view.conversation+ .read(cx)+ .pending_tool_call_count_for_session(&session_id, cx),+ 1+ );+ });++ if cancel {+ thread.update(cx, |thread, cx| {+ thread.cancel_permission_request(request_id, cx)+ });+ } else {+ conversation_view.update_in(cx, |_, window, cx| {+ window.dispatch_action(AllowOnce.boxed_clone(), cx);+ });+ }+ cx.run_until_parked();+ thread_view.read_with(cx, |view, cx| {+ assert!(+ !view+ .conversation+ .read(cx)+ .permission_selections+ .contains_key(&request_id)+ );+ assert!(+ view.thread+ .read(cx)+ .permission_request(request_id)+ .is_none()+ );+ assert!(+ view.thread+ .read(cx)+ .tool_call(&"dropped-waiter".into())+ .expect("tool call remains")+ .1+ .authorization_id()+ .is_none()+ );+ assert_eq!(+ view.conversation+ .read(cx)+ .pending_tool_call_count_for_session(&session_id, cx),+ 0+ );+ assert!(+ view.conversation+ .read(cx)+ .pending_tool_call(&session_id, cx)+ .is_none()+ );+ });+ }+ }++ #[gpui::test]+ async fn test_replaced_permission_ignores_captured_actions(cx: &mut TestAppContext) {+ init_test(cx);+ let (conversation_view, cx) =+ setup_conversation_view(StubAgentServer::default_response(), cx).await;+ add_to_workspace(conversation_view.clone(), cx);+ let thread_view = active_thread(&conversation_view, cx);+ let thread = thread_view.read_with(cx, |view, _| view.thread.clone());+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());+ let first_response = request_test_tool_authorization(&thread, "reused-tool", "allow", cx);+ let first_id = thread.read_with(cx, |thread, _| {+ thread+ .permission_request_for_tool(&"reused-tool".into())+ .expect("first request")+ .id+ });+ let captured_action = crate::AuthorizeToolCall {+ tool_call_id: "reused-tool".into(),+ request_id: Some(first_id),+ session_id: Some(session_id.0.to_string()),+ option_id: "allow".into(),+ option_kind: "AllowOnce".into(),+ };+ let captured_selection = crate::SelectPermissionGranularity {+ tool_call_id: "reused-tool".into(),+ request_id: Some(first_id),+ session_id: Some(session_id.0.to_string()),+ index: 0,+ };+ cx.run_until_parked();+ conversation_view.update_in(cx, |_, window, cx| {+ window.dispatch_action(captured_selection.boxed_clone(), cx);+ });+ cx.run_until_parked();+ thread_view.read_with(cx, |view, cx| {+ assert!(+ view.conversation+ .read(cx)+ .permission_selections+ .contains_key(&first_id)+ );+ });++ let second_response = request_test_tool_authorization(&thread, "reused-tool", "allow", cx);+ let second_id = thread.read_with(cx, |thread, _| {+ assert!(thread.permission_request(first_id).is_none());+ thread+ .permission_request_for_tool(&"reused-tool".into())+ .expect("successor request")+ .id+ });+ assert_ne!(first_id, second_id);+ assert!(matches!(+ first_response.await,+ acp_thread::RequestPermissionOutcome::Cancelled+ ));+ cx.run_until_parked();+ conversation_view.update_in(cx, |_, window, cx| {+ window.dispatch_action(captured_selection.boxed_clone(), cx);+ window.dispatch_action(captured_action.boxed_clone(), cx);+ });+ thread.update(cx, |thread, cx| {+ thread.cancel_permission_request(first_id, cx)+ });+ cx.run_until_parked();+ thread_view.read_with(cx, |view, cx| {+ let conversation = view.conversation.read(cx);+ assert!(!conversation.permission_selections.contains_key(&first_id));+ assert!(!conversation.permission_selections.contains_key(&second_id));+ assert!(view.thread.read(cx).permission_request(second_id).is_some());+ assert_eq!(+ view.conversation+ .read(cx)+ .pending_tool_call_count_for_session(&session_id, cx),+ 1+ );+ });++ conversation_view.update_in(cx, |_, window, cx| {+ window.dispatch_action(+ crate::AuthorizeToolCall {+ request_id: Some(second_id),+ ..captured_action.clone()+ }+ .boxed_clone(),+ cx,+ );+ });+ cx.run_until_parked();+ assert!(matches!(second_response.await,+ acp_thread::RequestPermissionOutcome::Selected(outcome) if outcome.option_id == "allow".into()));+ thread_view.read_with(cx, |view, cx| {+ assert!(+ view.conversation+ .read(cx)+ .pending_tool_call(&session_id, cx)+ .is_none()+ );+ });+ }+#[gpui::test]async fn test_conversation_multiple_tool_calls_fifo_ordering(cx: &mut TestAppContext) {init_test(cx);@@ -13750,6 +14415,210 @@ pub(crate) mod tests {});}+ #[gpui::test]+ async fn test_late_permission_registration_uses_owner_order_and_counts(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let fs = FakeFs::new(cx.executor());+ let project = Project::test(fs, [], cx).await;+ let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());+ let root_session_id = acp_v1::SessionId::new("root");+ let child_session_id = acp_v1::SessionId::new("child");+ let (root, child) = cx.update(|cx| {+ let root =+ create_test_acp_thread(None, "root", connection.clone(), project.clone(), cx);+ let child = create_test_acp_thread(+ Some(root_session_id.clone()),+ "child",+ connection,+ project,+ cx,+ );+ child.update(cx, |thread, cx| {+ thread+ .handle_session_update(+ acp_v1::SessionUpdate::ToolCall(acp_v1::ToolCall::new(+ "second",+ "Second tool",+ )),+ cx,+ )+ .expect("tool presentation should be accepted");+ });+ (root, child)+ });+ drop(request_test_tool_authorization(+ &child, "first", "allow", cx,+ ));+ drop(request_test_tool_authorization(+ &child, "second", "allow", cx,+ ));+ let (first_id, second_id) = child.read_with(cx, |thread, _| {+ (+ thread+ .permission_request_for_tool(&"first".into())+ .expect("first request")+ .id,+ thread+ .permission_request_for_tool(&"second".into())+ .expect("second request")+ .id,+ )+ });+ let conversation = cx.update(|cx| {+ cx.new(|cx| {+ let mut conversation = Conversation::default();+ conversation.register_thread(root, cx);+ conversation.register_thread(child.clone(), cx);+ conversation+ })+ });+ cx.run_until_parked();+ conversation.read_with(cx, |conversation, cx| {+ assert_eq!(+ conversation.pending_tool_call_for_session(&child_session_id, cx),+ Some("first".into()),+ "Request order must not come from tool-entry order"+ );+ assert_eq!(+ conversation.pending_tool_call_count_for_session(&child_session_id, cx),+ 2+ );+ assert_eq!(+ conversation.subagents_awaiting_permission(cx),+ vec![(child_session_id.clone(), 2)]+ );+ assert_eq!(+ conversation+ .pending_tool_call(&root_session_id, cx)+ .expect("child is discoverable")+ .0,+ child_session_id+ );+ });+ cx.update(|cx| {+ child.update(cx, |thread, cx| {+ thread.cancel_permission_request(first_id, cx)+ });+ let conversation = conversation.read(cx);+ assert_eq!(+ conversation.pending_tool_call_for_session(&child_session_id, cx),+ Some("second".into())+ );+ assert_eq!(+ conversation.pending_tool_call_count_for_session(&child_session_id, cx),+ 1+ );+ assert_eq!(+ conversation.subagents_awaiting_permission(cx),+ vec![(child_session_id.clone(), 1)]+ );+ });+ cx.update(|cx| {+ child.update(cx, |thread, cx| {+ thread.cancel_permission_request(second_id, cx)+ });+ let conversation = conversation.read(cx);+ assert!(+ conversation+ .pending_tool_call(&root_session_id, cx)+ .is_none()+ );+ assert_eq!(+ conversation.pending_tool_call_count_for_session(&child_session_id, cx),+ 0+ );+ assert!(conversation.subagents_awaiting_permission(cx).is_empty());+ });+ cx.run_until_parked();+ }++ #[gpui::test]+ async fn test_interleaved_permission_requests_preserve_session_buckets(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let fs = FakeFs::new(cx.executor());+ let project = Project::test(fs, [], cx).await;+ let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());+ let root_session_id = acp_v1::SessionId::new("root");+ let child_session_id = acp_v1::SessionId::new("child");+ let (root, child, conversation) = cx.update(|cx| {+ let root =+ create_test_acp_thread(None, "root", connection.clone(), project.clone(), cx);+ let child = create_test_acp_thread(+ Some(root_session_id.clone()),+ "child",+ connection,+ project,+ cx,+ );+ let conversation = cx.new(|cx| {+ let mut conversation = Conversation::default();+ conversation.register_thread(root.clone(), cx);+ conversation.register_thread(child.clone(), cx);+ conversation+ });+ (root, child, conversation)+ });+ drop(request_test_tool_authorization(+ &root, "root-a1", "allow", cx,+ ));+ drop(request_test_tool_authorization(+ &child, "child-b1", "allow", cx,+ ));+ drop(request_test_tool_authorization(+ &root, "root-a2", "allow", cx,+ ));+ cx.run_until_parked();++ for expected_tool in ["root-a1", "root-a2", "child-b1"] {+ let (session_id, request_id) = conversation.read_with(cx, |conversation, cx| {+ let (session_id, request) = conversation+ .pending_permission_request(&root_session_id, cx)+ .expect("next grouped request");+ assert_eq!(request.tool_call_id, expected_tool.into());+ if expected_tool.starts_with("root") {+ assert_eq!(session_id, root_session_id);+ assert_eq!(+ conversation.pending_tool_call_for_session(&child_session_id, cx),+ Some("child-b1".into())+ );+ } else {+ assert_eq!(session_id, child_session_id);+ }+ (session_id, request.id)+ });+ let owner = if session_id == root_session_id {+ &root+ } else {+ &child+ };+ cx.update(|cx| {+ owner.update(cx, |thread, cx| {+ thread.cancel_permission_request(request_id, cx)+ })+ });+ cx.run_until_parked();+ }+ conversation.read_with(cx, |conversation, cx| {+ assert!(+ conversation+ .pending_tool_call(&root_session_id, cx)+ .is_none()+ );+ assert_eq!(+ conversation.pending_tool_call_count_for_session(&root_session_id, cx),+ 0+ );+ assert_eq!(+ conversation.pending_tool_call_count_for_session(&child_session_id, cx),+ 0+ );+ });+ }+#[gpui::test]async fn test_conversation_subagent_scoped_pending_tool_call(cx: &mut TestAppContext) {init_test(cx);@@ -14376,6 +15245,8 @@ pub(crate) mod tests {window.dispatch_action(crate::AuthorizeToolCall {tool_call_id: "perm-allow".to_string(),+ request_id: None,+ session_id: None,option_id: "allow".to_string(),option_kind: "AllowOnce".to_string(),}diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex d5713c947f5..8eee909d5a1 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -514,7 +514,7 @@ mod numbered_code_block_tests {}}-/// Tracks the user's permission dropdown selection state for a specific tool call.+/// Tracks the user's permission dropdown selection state for a specific request.////// Default (no entry in the map) means the last dropdown choice is selected,/// which is typically "Only this time".@@ -553,7 +553,7 @@ impl PermissionSelection {}}- fn toggle_pattern(&mut self, index: usize) {+ pub(super) fn toggle_pattern(&mut self, index: usize) {if let Self::SelectedPatterns(checked) = self {if let Some(pos) = checked.iter().position(|&i| i == index) {checked.swap_remove(pos);@@ -612,7 +612,6 @@ pub struct ThreadView {pub is_loading_contents: bool,pub new_server_version_available: Option<SharedString>,pub resumed_without_history: bool,- pub(crate) permission_selections: HashMap<acp_v1::ToolCallId, PermissionSelection>,elicitation_form_states: HashMap<ElicitationEntryId, ElicitationFormState>,pub _cancel_task: Option<Task<()>>,_save_task: Option<Task<()>>,@@ -805,6 +804,7 @@ impl ThreadView {let parent_session_id = thread.read(cx).parent_session_id().cloned();subscriptions.push(cx.observe(&thread, |_, _, cx| cx.notify()));+ subscriptions.push(cx.observe(&conversation, |_, _, cx| cx.notify()));let has_slash_completions = session_capabilities.read().has_slash_completions();let placeholder = placeholder_text(agent_display_name.as_ref(), has_slash_completions);@@ -1030,7 +1030,6 @@ impl ThreadView {discarded_partial_edits: HashSet::default(),is_loading_contents: false,new_server_version_available: None,- permission_selections: HashMap::default(),elicitation_form_states: HashMap::default(),_cancel_task: None,_save_task: None,@@ -2781,16 +2780,16 @@ impl ThreadView {cx.notify();}- pub fn authorize_tool_call(+ pub fn authorize_permission_request(&mut self,session_id: acp_v1::SessionId,- tool_call_id: acp_v1::ToolCallId,+ request_id: PermissionRequestId,outcome: SelectedPermissionOutcome,window: &mut Window,cx: &mut Context<Self>,) {self.conversation.update(cx, |conversation, cx| {- conversation.authorize_tool_call(session_id, tool_call_id, outcome, cx);+ conversation.authorize_permission_request(session_id, request_id, outcome, cx);});if self.should_be_following {self.workspace@@ -3071,7 +3070,14 @@ impl ThreadView {window: &mut Window,cx: &mut Context<Self>,) {- let tool_call_id = acp_v1::ToolCallId::new(action.tool_call_id.clone());+ let Some((session_id, request_id)) = self.permission_action_target(+ action.session_id.as_deref(),+ action.request_id,+ &action.tool_call_id,+ cx,+ ) else {+ return;+ };let option_id = acp_v1::PermissionOptionId::new(action.option_id.clone());let option_kind = match action.option_kind.as_str() {"AllowOnce" => acp_v1::PermissionOptionKind::AllowOnce,@@ -3081,27 +3087,55 @@ impl ThreadView {_ => acp_v1::PermissionOptionKind::AllowOnce,};- let session_id = self.thread.read(cx).session_id().clone();- self.authorize_tool_call(+ self.authorize_permission_request(session_id,- tool_call_id,+ request_id,SelectedPermissionOutcome::new(option_id, option_kind),window,cx,);}+ fn permission_action_target(+ &self,+ session_id: Option<&str>,+ request_id: Option<PermissionRequestId>,+ tool_call_id: &str,+ cx: &App,+ ) -> Option<(acp_v1::SessionId, PermissionRequestId)> {+ let session_id = session_id+ .map(acp_v1::SessionId::new)+ .unwrap_or_else(|| self.thread.read(cx).session_id().clone());+ let conversation = self.conversation.read(cx);+ let request = if let Some(id) = request_id {+ conversation.permission_request(&session_id, id, cx)?+ } else {+ conversation+ .threads+ .get(&session_id)?+ .read(cx)+ .permission_request_for_tool(&acp_v1::ToolCallId::new(tool_call_id))?+ };+ Some((session_id, request.id))+ }+pub fn handle_select_permission_granularity(&mut self,action: &SelectPermissionGranularity,_window: &mut Window,cx: &mut Context<Self>,) {- let tool_call_id = acp_v1::ToolCallId::new(action.tool_call_id.clone());- self.permission_selections- .insert(tool_call_id, PermissionSelection::Choice(action.index));-- cx.notify();+ let Some((session_id, request_id)) = self.permission_action_target(+ action.session_id.as_deref(),+ action.request_id,+ &action.tool_call_id,+ cx,+ ) else {+ return;+ };+ self.conversation.update(cx, |conversation, cx| {+ conversation.set_permission_choice(&session_id, request_id, action.index, cx);+ });}pub fn handle_toggle_command_pattern(@@ -3110,48 +3144,22 @@ impl ThreadView {_window: &mut Window,cx: &mut Context<Self>,) {- let tool_call_id = acp_v1::ToolCallId::new(action.tool_call_id.clone());-- match self.permission_selections.get_mut(&tool_call_id) {- Some(PermissionSelection::SelectedPatterns(checked)) => {- // Already in pattern mode — toggle the individual pattern.- if let Some(pos) = checked.iter().position(|&i| i == action.pattern_index) {- checked.swap_remove(pos);- } else {- checked.push(action.pattern_index);- }- }- _ => {- // First click: activate "Select options" with all patterns checked.- let thread = self.thread.read(cx);- let pattern_count = thread- .entries()- .iter()- .find_map(|entry| {- if let AgentThreadEntry::ToolCall(call) = entry {- if call.id == tool_call_id {- if let Some(authorization) = call.authorization() {- let options = &authorization.options;- if let PermissionOptions::DropdownWithPatterns {- patterns,- ..- } = options- {- return Some(patterns.len());- }- }- }- }- None- })- .unwrap_or(0);- self.permission_selections.insert(- tool_call_id,- PermissionSelection::SelectedPatterns((0..pattern_count).collect()),- );- }- }- cx.notify();+ let Some((session_id, request_id)) = self.permission_action_target(+ action.session_id.as_deref(),+ action.request_id,+ &action.tool_call_id,+ cx,+ ) else {+ return;+ };+ self.conversation.update(cx, |conversation, cx| {+ conversation.toggle_permission_pattern(+ &session_id,+ request_id,+ action.pattern_index,+ cx,+ );+ });}fn authorize_pending_with_granularity(@@ -3161,30 +3169,23 @@ impl ThreadView {cx: &mut Context<Self>,) -> Option<()> {let session_id = self.thread.read(cx).session_id().clone();- let (returned_session_id, tool_call_id, _) = self+ let (returned_session_id, request) = self.conversation.read(cx)- .pending_tool_call(&session_id, cx)?;- self.authorize_with_granularity(returned_session_id, tool_call_id, is_allow, window, cx)+ .pending_permission_request(&session_id, cx)?;+ self.authorize_with_granularity(returned_session_id, request.id, is_allow, window, cx)}fn authorize_with_granularity(&mut self,session_id: acp_v1::SessionId,- tool_call_id: acp_v1::ToolCallId,+ request_id: PermissionRequestId,is_allow: bool,window: &mut Window,cx: &mut Context<Self>,) -> Option<()> {- let selection = self.permission_selections.get(&tool_call_id).cloned();let result = self.conversation.update(cx, |conversation, cx| {- conversation.authorize_with_granularity(- session_id,- tool_call_id,- selection.as_ref(),- is_allow,- cx,- )+ conversation.authorize_with_granularity(session_id, request_id, is_allow, cx)});if self.should_be_following {self.workspace@@ -3861,7 +3862,8 @@ impl ThreadView {let active_session_id = self.thread.read(cx).session_id().clone();let conversation = self.conversation.read(cx);let tool_call_id = conversation.pending_tool_call_for_session(&active_session_id, cx)?;- let pending_count = conversation.pending_tool_call_count_for_session(&active_session_id);+ let pending_count =+ conversation.pending_tool_call_count_for_session(&active_session_id, cx);let thread = self.thread.read(cx);let (entry_ix, tool_call) = thread.tool_call(&tool_call_id)?;@@ -8126,10 +8128,10 @@ impl ThreadView {ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed);- let confirmation_options = tool_call- .authorization()- .map(|authorization| &authorization.options);- let needs_confirmation = confirmation_options.is_some();+ let permission_request = tool_call+ .authorization_id()+ .and_then(|id| self.thread.read(cx).permission_request(id));+ let needs_confirmation = permission_request.is_some();let output = terminal_data.output();let command_finished = output.is_some()@@ -8292,15 +8294,14 @@ impl ThreadView {})),)})- .when_some(confirmation_options, |this, options| {+ .when_some(permission_request, |this, request| {let is_first = self.is_first_tool_call(active_session_id, &tool_call.id, cx);let allow_disabled = self.sandbox_confusables_block_allow(tool_call, cx);this.child(self.render_permission_buttons(self.thread.read(cx).session_id().clone(),is_first,- options,+ request,entry_ix,- tool_call.id.clone(),focus_handle,allow_disabled,cx,@@ -8724,14 +8725,15 @@ impl ThreadView {None};- let permission_buttons = if let Some(authorization) = tool_call.authorization() {- let options = &authorization.options;+ let permission_buttons = if let Some(request) = tool_call+ .authorization_id()+ .and_then(|id| self.thread.read(cx).permission_request(id))+ {Some(self.render_permission_buttons(self.thread.read(cx).session_id().clone(),self.is_first_tool_call(active_session_id, &tool_call.id, cx),- options,+ request,entry_ix,- tool_call.id.clone(),focus_handle,self.sandbox_confusables_block_allow(tool_call, cx),cx,@@ -9648,22 +9650,21 @@ impl ThreadView {&self,session_id: acp_v1::SessionId,is_first: bool,- options: &PermissionOptions,+ request: &PermissionRequest,entry_ix: usize,- tool_call_id: acp_v1::ToolCallId,focus_handle: &FocusHandle,// When true, the "allow" choices are disabled (e.g. an unacknowledged// surprising-Unicode warning is showing). "Deny"/"Retry" stay enabled.allow_disabled: bool,cx: &Context<Self>,) -> Div {- match options {+ match &request.options {PermissionOptions::Flat(options) => self.render_permission_buttons_flat(session_id,is_first,options,entry_ix,- tool_call_id,+ request.id,focus_handle,allow_disabled,cx,@@ -9674,7 +9675,8 @@ impl ThreadView {None,entry_ix,session_id,- tool_call_id,+ request.id,+ request.tool_call_id.clone(),focus_handle,allow_disabled,cx,@@ -9689,7 +9691,8 @@ impl ThreadView {Some((patterns, tool_name)),entry_ix,session_id,- tool_call_id,+ request.id,+ request.tool_call_id.clone(),focus_handle,allow_disabled,cx,@@ -9704,12 +9707,17 @@ impl ThreadView {patterns: Option<(&[PermissionPattern], &str)>,entry_ix: usize,session_id: acp_v1::SessionId,+ request_id: PermissionRequestId,tool_call_id: acp_v1::ToolCallId,focus_handle: &FocusHandle,allow_disabled: bool,cx: &Context<Self>,) -> Div {- let selection = self.permission_selections.get(&tool_call_id);+ let selection = self+ .conversation+ .read(cx)+ .permission_selections+ .get(&request_id);let selected_index = selection.and_then(|s| s.choice_index())@@ -9725,6 +9733,11 @@ impl ThreadView {.map(|choice| choice.label()).unwrap_or_else(|| "Only this time".into())};+ let permission_buttons_selector = {+ let session_id = session_id.clone();+ let dropdown_label = dropdown_label.clone();+ move || format!("PERMISSION_BUTTONS-{session_id}-{dropdown_label}")+ };let dropdown = if let Some((pattern_list, tool_name)) = patterns {self.render_permission_granularity_dropdown_with_patterns(@@ -9733,7 +9746,8 @@ impl ThreadView {tool_name,dropdown_label,entry_ix,- tool_call_id.clone(),+ session_id.clone(),+ request_id,is_first,cx,)@@ -9742,7 +9756,9 @@ impl ThreadView {choices,dropdown_label,entry_ix,- tool_call_id.clone(),+ session_id.clone(),+ request_id,+ tool_call_id,selected_index,is_first,cx,@@ -9751,6 +9767,7 @@ impl ThreadView {h_flex().w_full()+ .debug_selector(permission_buttons_selector).p_1().gap_2().justify_between()@@ -9780,11 +9797,10 @@ impl ThreadView {}).on_click(cx.listener({let session_id = session_id.clone();- let tool_call_id = tool_call_id.clone();move |this, _, window, cx| {this.authorize_with_granularity(session_id.clone(),- tool_call_id.clone(),+ request_id,true,window,cx,@@ -9814,7 +9830,7 @@ impl ThreadView {move |this, _, window, cx| {this.authorize_with_granularity(session_id.clone(),- tool_call_id.clone(),+ request_id,false,window,cx,@@ -9831,6 +9847,8 @@ impl ThreadView {choices: &[PermissionOptionChoice],current_label: SharedString,entry_ix: usize,+ session_id: acp_v1::SessionId,+ request_id: PermissionRequestId,tool_call_id: acp_v1::ToolCallId,selected_index: usize,is_first: bool,@@ -9867,6 +9885,7 @@ impl ThreadView {).menu(move |window, cx| {let tool_call_id = tool_call_id.clone();+ let session_id = session_id.clone();let options = menu_options.clone();Some(ContextMenu::build(window, cx, move |mut menu, _, _| {@@ -9874,6 +9893,7 @@ impl ThreadView {let display_name = display_name.clone();let index = *index;let tool_call_id_for_entry = tool_call_id.clone();+ let session_id = session_id.clone();let is_selected = index == selected_index;menu = menu.toggleable_entry(display_name,@@ -9884,6 +9904,8 @@ impl ThreadView {window.dispatch_action(SelectPermissionGranularity {tool_call_id: tool_call_id_for_entry.0.to_string(),+ request_id: Some(request_id),+ session_id: Some(session_id.0.to_string()),index,}.boxed_clone(),@@ -9906,7 +9928,8 @@ impl ThreadView {_tool_name: &str,current_label: SharedString,entry_ix: usize,- tool_call_id: acp_v1::ToolCallId,+ session_id: acp_v1::SessionId,+ request_id: PermissionRequestId,is_first: bool,cx: &Context<Self>,) -> AnyElement {@@ -9928,9 +9951,8 @@ impl ThreadView {}).collect();- let pattern_count = patterns.len();let permission_dropdown_handle = self.permission_dropdown_handle.clone();- let view = cx.entity().downgrade();+ let conversation = self.conversation.downgrade();PopoverMenu::new(("permission-granularity", entry_ix)).with_handle(permission_dropdown_handle.clone())@@ -9956,10 +9978,10 @@ impl ThreadView {}),).menu(move |window, cx| {- let tool_call_id = tool_call_id.clone();+ let session_id = session_id.clone();let options = menu_options.clone();let patterns = pattern_options.clone();- let view = view.clone();+ let conversation = conversation.clone();let dropdown_handle = permission_dropdown_handle.clone();Some(ContextMenu::build_persistent(@@ -9968,10 +9990,12 @@ impl ThreadView {move |menu, _window, cx| {let mut menu = menu;- // Read fresh selection state from the view on each rebuild.- let selection: Option<PermissionSelection> = view.upgrade().and_then(|v| {- let view = v.read(cx);- view.permission_selections.get(&tool_call_id).cloned()+ let selection = conversation.upgrade().and_then(|conversation| {+ conversation+ .read(cx)+ .permission_selections+ .get(&request_id)+ .cloned()});let is_pattern_mode =@@ -9981,28 +10005,30 @@ impl ThreadView {for (index, display_name) in options.iter() {let display_name = display_name.clone();let index = *index;- let tool_call_id_for_entry = tool_call_id.clone();+ let session_id = session_id.clone();let is_selected = !is_pattern_mode&& selection.as_ref().and_then(|s| s.choice_index()).map_or(index == default_choice_index, |ci| ci == index);- let view = view.clone();+ let conversation = conversation.clone();menu = menu.toggleable_entry(display_name,is_selected,IconPosition::End,None,move |_window, cx| {- view.update(cx, |this, cx| {- this.permission_selections.insert(- tool_call_id_for_entry.clone(),- PermissionSelection::Choice(index),- );- cx.notify();- })- .log_err();+ conversation+ .update(cx, |conversation, cx| {+ conversation.set_permission_choice(+ &session_id,+ request_id,+ index,+ cx,+ );+ })+ .log_err();},);}@@ -10012,45 +10038,28 @@ impl ThreadView {for (pattern_index, label) in patterns.iter() {let label = label.clone();let pattern_index = *pattern_index;- let tool_call_id_for_pattern = tool_call_id.clone();+ let session_id = session_id.clone();let is_checked = selection.as_ref().is_some_and(|s| s.is_pattern_checked(pattern_index));- let view = view.clone();+ let conversation = conversation.clone();menu = menu.toggleable_entry(label,is_checked,IconPosition::End,None,move |_window, cx| {- view.update(cx, |this, cx| {- let selection = this- .permission_selections- .get_mut(&tool_call_id_for_pattern);-- match selection {- Some(PermissionSelection::SelectedPatterns(_)) => {- // Already in pattern mode — toggle.- this.permission_selections- .get_mut(&tool_call_id_for_pattern)- .expect("just matched above")- .toggle_pattern(pattern_index);- }- _ => {- // First click: activate pattern mode- // with all patterns checked.- this.permission_selections.insert(- tool_call_id_for_pattern.clone(),- PermissionSelection::SelectedPatterns(- (0..pattern_count).collect(),- ),- );- }- }- cx.notify();- })- .log_err();+ conversation+ .update(cx, |conversation, cx| {+ conversation.toggle_permission_pattern(+ &session_id,+ request_id,+ pattern_index,+ cx,+ );+ })+ .log_err();},);}@@ -10092,7 +10101,7 @@ impl ThreadView {is_first: bool,options: &[acp_v1::PermissionOption],entry_ix: usize,- tool_call_id: acp_v1::ToolCallId,+ request_id: PermissionRequestId,focus_handle: &FocusHandle,allow_disabled: bool,cx: &Context<Self>,@@ -10186,14 +10195,13 @@ impl ThreadView {}).label_size(LabelSize::Small).on_click(cx.listener({- let tool_call_id = tool_call_id.clone();let option_id = option.option_id.clone();let option_kind = option.kind;let session_id = session_id.clone();move |this, _, window, cx| {- this.authorize_tool_call(+ this.authorize_permission_request(session_id.clone(),- tool_call_id.clone(),+ request_id,SelectedPermissionOutcome::new(option_id.clone(), option_kind),window,cx,diff --git a/crates/agent_ui/src/entry_view_state.rs b/crates/agent_ui/src/entry_view_state.rsindex df5c8bcfeaf..afdb13d5507 100644--- a/crates/agent_ui/src/entry_view_state.rs+++ b/crates/agent_ui/src/entry_view_state.rs@@ -79,7 +79,7 @@ impl EntryViewState {}pub(crate) fn is_tool_call_content_visible(&self, tool_call: &ToolCall) -> bool {- self.is_tool_call_expanded(&tool_call.id) || tool_call.authorization().is_some()+ self.is_tool_call_expanded(&tool_call.id) || tool_call.authorization_id().is_some()}pub(crate) fn expand_tool_call(&mut self, tool_call_id: acp_v1::ToolCallId) {