Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

acp: Add experimental elicitation UI support (#58927)

Ben Brandtfa66442a0110
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index e85a0bd48fb..87c9dd1c42c 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -387,10 +387,366 @@ pub enum AgentThreadEntry {
UserMessage(UserMessage),
AssistantMessage(AssistantMessage),
ToolCall(ToolCall),
+ Elicitation(ElicitationEntryId),
CompletedPlan(Vec<PlanEntry>),
ContextCompaction(ContextCompaction),
}
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct ElicitationEntryId(pub Arc<str>);
+
+#[derive(Debug)]
+pub struct Elicitation {
+ pub id: ElicitationEntryId,
+ pub request: acp::CreateElicitationRequest,
+ pub status: ElicitationStatus,
+}
+
+#[derive(Debug)]
+pub enum ElicitationStatus {
+ Pending {
+ respond_tx: oneshot::Sender<acp::CreateElicitationResponse>,
+ },
+ Accepted,
+ Declined,
+ Canceled,
+ Completed,
+}
+
+#[derive(Clone, Debug)]
+pub enum ElicitationStoreEvent {
+ ElicitationRequested(ElicitationEntryId),
+ ElicitationResponded(ElicitationEntryId),
+ ElicitationUpdated(ElicitationEntryId),
+}
+
+#[derive(Default)]
+pub struct ElicitationStore {
+ elicitations: Vec<Elicitation>,
+}
+
+impl EventEmitter<ElicitationStoreEvent> for ElicitationStore {}
+
+impl ElicitationStore {
+ pub fn elicitations(&self) -> &[Elicitation] {
+ &self.elicitations
+ }
+
+ fn validate_request(
+ request: &acp::CreateElicitationRequest,
+ cx: &App,
+ ) -> Result<(), acp::Error> {
+ if !cx.has_flag::<AcpBetaFeatureFlag>() {
+ return Err(
+ acp::Error::invalid_params().data("elicitation support requires the ACP beta flag")
+ );
+ }
+
+ if let acp::ElicitationMode::Url(mode) = &request.mode {
+ url::Url::parse(&mode.url)
+ .map_err(|_| acp::Error::invalid_params().data("invalid elicitation URL"))?;
+ }
+
+ Ok(())
+ }
+
+ fn insert_pending_elicitation(
+ &mut self,
+ request: acp::CreateElicitationRequest,
+ ) -> (
+ ElicitationEntryId,
+ oneshot::Receiver<acp::CreateElicitationResponse>,
+ ) {
+ let (respond_tx, response_rx) = oneshot::channel();
+ let id = ElicitationEntryId(Uuid::new_v4().to_string().into());
+ self.elicitations.push(Elicitation {
+ id: id.clone(),
+ request,
+ status: ElicitationStatus::Pending { respond_tx },
+ });
+ (id, response_rx)
+ }
+
+ fn response_task<T>(
+ id: ElicitationEntryId,
+ response_rx: oneshot::Receiver<acp::CreateElicitationResponse>,
+ cx: &mut Context<T>,
+ emit_responded: impl FnOnce(&mut T, &mut Context<T>, ElicitationEntryId) + 'static,
+ ) -> Task<acp::CreateElicitationResponse>
+ where
+ T: 'static,
+ {
+ cx.spawn(async move |this, cx| {
+ let response = response_rx.await.unwrap_or_else(|oneshot::Canceled| {
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Cancel)
+ });
+ this.update(cx, |this, cx| emit_responded(this, cx, id))
+ .ok();
+ response
+ })
+ }
+
+ fn respond_to_elicitation_entry(
+ elicitation: &mut Elicitation,
+ response: acp::CreateElicitationResponse,
+ ) -> bool {
+ if !matches!(elicitation.status, ElicitationStatus::Pending { .. }) {
+ return false;
+ }
+ let ElicitationStatus::Pending { respond_tx } = mem::replace(
+ &mut elicitation.status,
+ elicitation_status_for_response(&response),
+ ) else {
+ return false;
+ };
+ respond_tx.send(response).ok();
+ true
+ }
+
+ fn complete_url_elicitation_entry(elicitation: &mut Elicitation) -> bool {
+ let previous_status = mem::replace(&mut elicitation.status, ElicitationStatus::Completed);
+ match previous_status {
+ ElicitationStatus::Pending { respond_tx } => {
+ respond_tx
+ .send(acp::CreateElicitationResponse::new(
+ acp::ElicitationAction::Accept(acp::ElicitationAcceptAction::new()),
+ ))
+ .ok();
+ true
+ }
+ ElicitationStatus::Accepted => true,
+ ElicitationStatus::Completed => false,
+ previous_status @ (ElicitationStatus::Declined | ElicitationStatus::Canceled) => {
+ elicitation.status = previous_status;
+ false
+ }
+ }
+ }
+
+ fn cancel_elicitation_entry(
+ elicitation: &mut Elicitation,
+ cancel_accepted_url_elicitations: bool,
+ ) -> bool {
+ match mem::replace(&mut elicitation.status, ElicitationStatus::Canceled) {
+ ElicitationStatus::Pending { respond_tx } => {
+ respond_tx
+ .send(acp::CreateElicitationResponse::new(
+ acp::ElicitationAction::Cancel,
+ ))
+ .ok();
+ true
+ }
+ ElicitationStatus::Accepted
+ if cancel_accepted_url_elicitations
+ && matches!(&elicitation.request.mode, acp::ElicitationMode::Url(_)) =>
+ {
+ true
+ }
+ previous_status => {
+ elicitation.status = previous_status;
+ false
+ }
+ }
+ }
+
+ fn respond_to_elicitation_by_id(
+ &mut self,
+ id: &ElicitationEntryId,
+ response: acp::CreateElicitationResponse,
+ ) -> bool {
+ let Some((_, elicitation)) = self.elicitation_mut(id) else {
+ return false;
+ };
+ Self::respond_to_elicitation_entry(elicitation, response)
+ }
+
+ fn complete_url_elicitation_by_id(&mut self, id: &ElicitationEntryId) -> bool {
+ let Some((_, elicitation)) = self.elicitation_mut(id) else {
+ return false;
+ };
+ Self::complete_url_elicitation_entry(elicitation)
+ }
+
+ fn cancel_elicitation_by_id(
+ &mut self,
+ id: &ElicitationEntryId,
+ cancel_accepted_url_elicitations: bool,
+ ) -> bool {
+ let Some((_, elicitation)) = self.elicitation_mut(id) else {
+ return false;
+ };
+ Self::cancel_elicitation_entry(elicitation, cancel_accepted_url_elicitations)
+ }
+
+ pub fn request_elicitation(
+ &mut self,
+ request: acp::CreateElicitationRequest,
+ cx: &mut Context<Self>,
+ ) -> Result<Task<acp::CreateElicitationResponse>, acp::Error> {
+ self.request_elicitation_with_id(request, cx)
+ .map(|(_, task)| task)
+ }
+
+ pub fn request_elicitation_with_id(
+ &mut self,
+ request: acp::CreateElicitationRequest,
+ cx: &mut Context<Self>,
+ ) -> Result<(ElicitationEntryId, Task<acp::CreateElicitationResponse>), acp::Error> {
+ Self::validate_request(&request, cx)?;
+ let (id, response_rx) = self.insert_pending_elicitation(request);
+ cx.emit(ElicitationStoreEvent::ElicitationRequested(id.clone()));
+ cx.notify();
+
+ let task = Self::response_task(id.clone(), response_rx, cx, |_store, cx, id| {
+ cx.emit(ElicitationStoreEvent::ElicitationResponded(id));
+ cx.notify();
+ });
+
+ Ok((id, task))
+ }
+
+ pub fn respond_to_elicitation(
+ &mut self,
+ id: &ElicitationEntryId,
+ response: acp::CreateElicitationResponse,
+ cx: &mut Context<Self>,
+ ) {
+ if !self.respond_to_elicitation_by_id(id, response) {
+ return;
+ }
+
+ cx.emit(ElicitationStoreEvent::ElicitationUpdated(id.clone()));
+ cx.notify();
+ }
+
+ pub fn complete_url_elicitation(
+ &mut self,
+ elicitation_id: &acp::ElicitationId,
+ cx: &mut Context<Self>,
+ ) {
+ let Some(entry_id) = self.entry_id_for_url_elicitation(elicitation_id) else {
+ return;
+ };
+ if !self.complete_url_elicitation_by_id(&entry_id) {
+ return;
+ }
+
+ cx.emit(ElicitationStoreEvent::ElicitationUpdated(entry_id));
+ cx.notify();
+ }
+
+ pub fn cancel_elicitation(&mut self, id: &ElicitationEntryId, cx: &mut Context<Self>) {
+ if !self.cancel_elicitation_by_id(id, true) {
+ return;
+ }
+
+ cx.emit(ElicitationStoreEvent::ElicitationUpdated(id.clone()));
+ cx.notify();
+ }
+
+ pub fn cancel_all(&mut self, cx: &mut Context<Self>) {
+ let canceled_ids = self.cancel_pending(|_| true);
+ for id in canceled_ids {
+ cx.emit(ElicitationStoreEvent::ElicitationUpdated(id));
+ }
+ cx.notify();
+ }
+
+ pub fn clear(&mut self, cx: &mut Context<Self>) {
+ let canceled_ids = self.cancel_pending(|_| true);
+ self.elicitations.clear();
+ for id in canceled_ids {
+ cx.emit(ElicitationStoreEvent::ElicitationUpdated(id));
+ }
+ cx.notify();
+ }
+
+ pub fn clear_resolved(&mut self, cx: &mut Context<Self>) -> Vec<ElicitationEntryId> {
+ let mut cleared_ids = Vec::new();
+ self.elicitations.retain(|elicitation| {
+ let keep = matches!(
+ (&elicitation.status, &elicitation.request.mode),
+ (ElicitationStatus::Pending { .. }, _)
+ | (ElicitationStatus::Accepted, acp::ElicitationMode::Url(_))
+ );
+ if !keep {
+ cleared_ids.push(elicitation.id.clone());
+ }
+ keep
+ });
+
+ if !cleared_ids.is_empty() {
+ for id in &cleared_ids {
+ cx.emit(ElicitationStoreEvent::ElicitationUpdated(id.clone()));
+ }
+ cx.notify();
+ }
+
+ cleared_ids
+ }
+
+ pub fn cancel_request(&mut self, request_id: &acp::RequestId, cx: &mut Context<Self>) {
+ let canceled_ids = self.cancel_pending(|elicitation| {
+ matches!(
+ elicitation.request.scope(),
+ acp::ElicitationScope::Request(scope) if &scope.request_id == request_id
+ )
+ });
+ for id in canceled_ids {
+ cx.emit(ElicitationStoreEvent::ElicitationUpdated(id));
+ }
+ cx.notify();
+ }
+
+ pub fn elicitation(&self, id: &ElicitationEntryId) -> Option<(usize, &Elicitation)> {
+ self.elicitations
+ .iter()
+ .enumerate()
+ .rev()
+ .find_map(|(index, elicitation)| {
+ (&elicitation.id == id).then_some((index, elicitation))
+ })
+ }
+
+ fn entry_id_for_url_elicitation(
+ &self,
+ elicitation_id: &acp::ElicitationId,
+ ) -> Option<ElicitationEntryId> {
+ self.elicitations.iter().rev().find_map(|elicitation| {
+ if let acp::ElicitationMode::Url(mode) = &elicitation.request.mode
+ && &mode.elicitation_id == elicitation_id
+ {
+ Some(elicitation.id.clone())
+ } else {
+ None
+ }
+ })
+ }
+
+ fn elicitation_mut(&mut self, id: &ElicitationEntryId) -> Option<(usize, &mut Elicitation)> {
+ self.elicitations
+ .iter_mut()
+ .enumerate()
+ .rev()
+ .find_map(|(index, elicitation)| {
+ (&elicitation.id == id).then_some((index, elicitation))
+ })
+ }
+
+ fn cancel_pending(
+ &mut self,
+ mut should_cancel: impl FnMut(&Elicitation) -> bool,
+ ) -> Vec<ElicitationEntryId> {
+ let mut canceled_ids = Vec::new();
+ for elicitation in &mut self.elicitations {
+ if should_cancel(elicitation) && Self::cancel_elicitation_entry(elicitation, true) {
+ canceled_ids.push(elicitation.id.clone());
+ }
+ }
+ canceled_ids
+ }
+}
+
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContextCompactionId(pub Arc<str>);
@@ -432,6 +788,7 @@ impl AgentThreadEntry {
Self::UserMessage(message) => message.indented,
Self::AssistantMessage(message) => message.indented,
Self::ToolCall(_) => false,
+ Self::Elicitation(_) => false,
Self::CompletedPlan(_) => false,
Self::ContextCompaction(_) => false,
}
@@ -442,6 +799,7 @@ impl AgentThreadEntry {
Self::UserMessage(message) => message.to_markdown(cx),
Self::AssistantMessage(message) => message.to_markdown(cx),
Self::ToolCall(tool_call) => tool_call.to_markdown(cx),
+ Self::Elicitation(_) => "## Input Requested\n\n".to_string(),
Self::CompletedPlan(entries) => {
let mut md = String::from("## Plan\n\n");
for entry in entries {
@@ -971,6 +1329,15 @@ impl Display for ToolCallStatus {
}
}
+fn elicitation_status_for_response(response: &acp::CreateElicitationResponse) -> ElicitationStatus {
+ match &response.action {
+ acp::ElicitationAction::Accept(_) => ElicitationStatus::Accepted,
+ acp::ElicitationAction::Decline => ElicitationStatus::Declined,
+ acp::ElicitationAction::Cancel => ElicitationStatus::Canceled,
+ _ => ElicitationStatus::Canceled,
+ }
+}
+
#[derive(Debug, PartialEq, Clone)]
pub enum ContentBlock {
Empty,
@@ -1721,6 +2088,7 @@ pub struct AcpThread {
title: Option<SharedString>,
provisional_title: Option<SharedString>,
entries: Vec<AgentThreadEntry>,
+ elicitations: ElicitationStore,
plan: Plan,
project: Entity<Project>,
action_log: Entity<ActionLog>,
@@ -1789,6 +2157,8 @@ pub enum AcpThreadEvent {
EntriesRemoved(Range<usize>),
ToolAuthorizationRequested(acp::ToolCallId),
ToolAuthorizationReceived(acp::ToolCallId),
+ ElicitationRequested(ElicitationEntryId),
+ ElicitationResponded(ElicitationEntryId),
Retry(RetryStatus),
SubagentSpawned(acp::SessionId),
Stopped(acp::StopReason),
@@ -1932,6 +2302,7 @@ impl AcpThread {
update_last_checkpoint_if_changed_task: None,
shared_buffers: Default::default(),
entries: Default::default(),
+ elicitations: ElicitationStore::default(),
plan: Default::default(),
title,
provisional_title: None,
@@ -2084,7 +2455,17 @@ impl AcpThread {
status: ToolCallStatus::WaitingForConfirmation { .. },
..
}) => return true,
+ AgentThreadEntry::Elicitation(elicitation_id)
+ if self.elicitations.elicitation(elicitation_id).is_some_and(
+ |(_, elicitation)| {
+ matches!(elicitation.status, ElicitationStatus::Pending { .. })
+ },
+ ) =>
+ {
+ return true;
+ }
AgentThreadEntry::ToolCall(_)
+ | AgentThreadEntry::Elicitation(_)
| AgentThreadEntry::AssistantMessage(_)
| AgentThreadEntry::CompletedPlan(_)
| AgentThreadEntry::ContextCompaction(_) => {}
@@ -2114,6 +2495,7 @@ impl AcpThread {
return true;
}
AgentThreadEntry::ToolCall(_)
+ | AgentThreadEntry::Elicitation(_)
| AgentThreadEntry::AssistantMessage(_)
| AgentThreadEntry::CompletedPlan(_)
| AgentThreadEntry::ContextCompaction(_) => {}
@@ -2134,6 +2516,7 @@ impl AcpThread {
return true;
}
AgentThreadEntry::ToolCall(_)
+ | AgentThreadEntry::Elicitation(_)
| AgentThreadEntry::AssistantMessage(_)
| AgentThreadEntry::CompletedPlan(_)
| AgentThreadEntry::ContextCompaction(_) => {}
@@ -2149,7 +2532,8 @@ impl AcpThread {
AgentThreadEntry::UserMessage(..) => return false,
AgentThreadEntry::AssistantMessage(..)
| AgentThreadEntry::CompletedPlan(..)
- | AgentThreadEntry::ContextCompaction(_) => continue,
+ | AgentThreadEntry::ContextCompaction(_)
+ | AgentThreadEntry::Elicitation(_) => continue,
AgentThreadEntry::ToolCall(..) => return true,
}
}
@@ -3089,6 +3473,99 @@ impl AcpThread {
cx.emit(AcpThreadEvent::EntryUpdated(ix));
}
+ pub fn request_elicitation(
+ &mut self,
+ request: acp::CreateElicitationRequest,
+ cx: &mut Context<Self>,
+ ) -> Result<Task<acp::CreateElicitationResponse>, acp::Error> {
+ self.request_elicitation_with_id(request, cx)
+ .map(|(_, task)| task)
+ }
+
+ pub fn request_elicitation_with_id(
+ &mut self,
+ request: acp::CreateElicitationRequest,
+ cx: &mut Context<Self>,
+ ) -> Result<(ElicitationEntryId, Task<acp::CreateElicitationResponse>), acp::Error> {
+ ElicitationStore::validate_request(&request, cx)?;
+
+ let (id, response_rx) = self.elicitations.insert_pending_elicitation(request);
+ self.push_entry(AgentThreadEntry::Elicitation(id.clone()), cx);
+ cx.emit(AcpThreadEvent::ElicitationRequested(id.clone()));
+
+ let task =
+ ElicitationStore::response_task(id.clone(), response_rx, cx, |_thread, cx, id| {
+ cx.emit(AcpThreadEvent::ElicitationResponded(id))
+ });
+
+ Ok((id, task))
+ }
+
+ pub fn respond_to_elicitation(
+ &mut self,
+ id: &ElicitationEntryId,
+ response: acp::CreateElicitationResponse,
+ cx: &mut Context<Self>,
+ ) {
+ let Some(ix) = self.elicitation_entry_ix(id) else {
+ return;
+ };
+ if !self.elicitations.respond_to_elicitation_by_id(id, response) {
+ return;
+ }
+
+ cx.emit(AcpThreadEvent::EntryUpdated(ix));
+ }
+
+ pub fn complete_url_elicitation(
+ &mut self,
+ elicitation_id: &acp::ElicitationId,
+ cx: &mut Context<Self>,
+ ) {
+ let Some(entry_id) = self
+ .elicitations
+ .entry_id_for_url_elicitation(elicitation_id)
+ else {
+ return;
+ };
+ let Some(ix) = self.elicitation_entry_ix(&entry_id) else {
+ return;
+ };
+ if !self.elicitations.complete_url_elicitation_by_id(&entry_id) {
+ return;
+ }
+
+ cx.emit(AcpThreadEvent::EntryUpdated(ix));
+ }
+
+ pub fn cancel_elicitation(&mut self, id: &ElicitationEntryId, cx: &mut Context<Self>) {
+ let Some(ix) = self.elicitation_entry_ix(id) else {
+ return;
+ };
+ if !self.elicitations.cancel_elicitation_by_id(id, true) {
+ return;
+ }
+
+ cx.emit(AcpThreadEvent::EntryUpdated(ix));
+ }
+
+ fn elicitation_entry_ix(&self, id: &ElicitationEntryId) -> Option<usize> {
+ self.entries
+ .iter()
+ .enumerate()
+ .rev()
+ .find_map(|(index, entry)| {
+ matches!(entry, AgentThreadEntry::Elicitation(elicitation_id) if elicitation_id == id)
+ .then_some(index)
+ })
+ }
+
+ pub fn elicitation(&self, id: &ElicitationEntryId) -> Option<(usize, &Elicitation)> {
+ let index = self.elicitation_entry_ix(id)?;
+ let (_, elicitation) = self.elicitations.elicitation(id)?;
+ Some((index, elicitation))
+ }
+
pub fn plan(&self) -> &Plan {
&self.plan
}
@@ -3333,14 +3810,14 @@ impl AcpThread {
log::error!("Max tokens reached. Usage: {:?}", this.token_usage);
}
if is_same_turn {
- this.mark_pending_entries_as_canceled(cx);
+ this.cancel_pending_turn_entries(cx);
}
return Err(anyhow!(MaxOutputTokensError));
}
let canceled = matches!(r.stop_reason, acp::StopReason::Cancelled);
if canceled && is_same_turn {
- this.mark_pending_entries_as_canceled(cx);
+ this.cancel_pending_turn_entries(cx);
}
if !canceled {
@@ -3404,7 +3881,7 @@ impl AcpThread {
}
Self::flush_streaming_text(&mut this.streaming_text_buffer, cx);
if is_same_turn {
- this.mark_pending_entries_as_canceled(cx);
+ this.cancel_pending_turn_entries(cx);
}
this.had_error = true;
cx.emit(AcpThreadEvent::Error);
@@ -3418,19 +3895,25 @@ impl AcpThread {
}
pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {
+ Self::flush_streaming_text(&mut self.streaming_text_buffer, cx);
+ self.cancel_outstanding_elicitations(cx);
+
let Some(turn) = self.running_turn.take() else {
return Task::ready(());
};
- self.connection.cancel(&self.session_id, cx);
-
- Self::flush_streaming_text(&mut self.streaming_text_buffer, cx);
self.mark_pending_entries_as_canceled(cx);
+ self.connection.cancel(&self.session_id, cx);
cx.emit(AcpThreadEvent::StatusChanged);
// Wait for the send task to complete
cx.background_spawn(turn.send_task)
}
+ fn cancel_pending_turn_entries(&mut self, cx: &mut Context<Self>) {
+ self.mark_pending_entries_as_canceled(cx);
+ self.cancel_outstanding_elicitations(cx);
+ }
+
fn mark_pending_entries_as_canceled(&mut self, cx: &mut Context<Self>) {
for (ix, entry) in self.entries.iter_mut().enumerate() {
match entry {
@@ -3457,6 +3940,20 @@ impl AcpThread {
}
}
+ fn cancel_outstanding_elicitations(&mut self, cx: &mut Context<Self>) {
+ for ix in 0..self.entries.len() {
+ let Some(AgentThreadEntry::Elicitation(elicitation_id)) = self.entries.get(ix) else {
+ continue;
+ };
+ if self
+ .elicitations
+ .cancel_elicitation_by_id(elicitation_id, true)
+ {
+ cx.emit(AcpThreadEvent::EntryUpdated(ix));
+ }
+ }
+ }
+
/// Restores the git working tree to the state at the given checkpoint (if one exists)
pub fn restore_checkpoint(
&mut self,
@@ -4051,7 +4548,19 @@ impl AcpThread {
}
pub fn to_markdown(&self, cx: &App) -> String {
- self.entries.iter().map(|e| e.to_markdown(cx)).collect()
+ self.entries
+ .iter()
+ .map(|entry| match entry {
+ AgentThreadEntry::Elicitation(elicitation_id) => self
+ .elicitations
+ .elicitation(elicitation_id)
+ .map(|(_, elicitation)| {
+ format!("## Input Requested\n\n{}\n\n", elicitation.request.message)
+ })
+ .unwrap_or_else(|| entry.to_markdown(cx)),
+ _ => entry.to_markdown(cx),
+ })
+ .collect()
}
pub fn emit_load_error(&mut self, error: LoadError, cx: &mut Context<Self>) {
@@ -4225,8 +4734,10 @@ fn markdown_for_raw_output(
mod tests {
use super::*;
use anyhow::anyhow;
+ use feature_flags::FeatureFlag as _;
use futures::stream::StreamExt as _;
use futures::{channel::mpsc, future::LocalBoxFuture, select};
+ use gpui::UpdateGlobal as _;
use gpui::{App, AsyncApp, TestAppContext, WeakEntity};
use indoc::indoc;
use project::{AgentId, FakeFs, Fs};
@@ -4284,11 +4795,31 @@ mod tests {
fn init_test(cx: &mut TestAppContext) {
env_logger::try_init().ok();
cx.update(|cx| {
- let settings_store = SettingsStore::test(cx);
+ let mut settings_store = SettingsStore::test(cx);
+ settings_store.register_setting::<feature_flags::FeatureFlagsSettings>();
cx.set_global(settings_store);
});
}
+ fn enable_acp_beta(cx: &mut TestAppContext) {
+ cx.update(|cx| {
+ cx.update_flags(false, vec![AcpBetaFeatureFlag::NAME.to_string()]);
+ });
+ }
+
+ fn set_acp_beta_override(value: &str, cx: &mut TestAppContext) {
+ cx.update(|cx| {
+ SettingsStore::update_global(cx, |store, cx| {
+ store.update_user_settings(cx, |content| {
+ content
+ .feature_flags
+ .get_or_insert_default()
+ .insert(AcpBetaFeatureFlag::NAME.to_string(), value.to_string());
+ });
+ });
+ });
+ }
+
#[test]
fn text_resource_markdown_uses_mime_type_for_code_blocks() {
let shell = acp::TextResourceContents::new("echo 'hello from exec test'", "tool://preview")
@@ -6769,6 +7300,1216 @@ mod tests {
});
}
+ async fn new_test_thread(cx: &mut TestAppContext) -> Entity<AcpThread> {
+ let fs = FakeFs::new(cx.executor());
+ let project = Project::test(fs, [], cx).await;
+ let connection = Rc::new(FakeAgentConnection::new());
+ cx.update(|cx| {
+ connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
+ })
+ .await
+ .unwrap()
+ }
+
+ fn only_thread_elicitation(thread: &AcpThread) -> (ElicitationEntryId, &Elicitation) {
+ let [entry] = thread.entries() else {
+ panic!("expected one elicitation entry, got {:?}", thread.entries());
+ };
+ let AgentThreadEntry::Elicitation(id) = entry else {
+ panic!("expected one elicitation entry, got {:?}", thread.entries());
+ };
+ let Some((_, elicitation)) = thread.elicitation(id) else {
+ panic!("missing elicitation entry");
+ };
+ (id.clone(), elicitation)
+ }
+
+ fn latest_thread_elicitation(thread: &AcpThread) -> (ElicitationEntryId, &Elicitation) {
+ let Some(AgentThreadEntry::Elicitation(id)) = thread.entries().last() else {
+ panic!("expected latest entry to be an elicitation");
+ };
+ let Some((_, elicitation)) = thread.elicitation(id) else {
+ panic!("missing elicitation entry");
+ };
+ (id.clone(), elicitation)
+ }
+
+ #[gpui::test]
+ async fn test_elicitation_requires_acp_beta_flag(cx: &mut TestAppContext) {
+ init_test(cx);
+ cx.update(|cx| {
+ cx.update_flags(false, vec![]);
+ });
+ set_acp_beta_override("off", cx);
+ let thread = new_test_thread(cx).await;
+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+
+ let result = thread.update(cx, |thread, cx| {
+ thread.request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationSessionScope::new(session_id),
+ acp::ElicitationSchema::new().string("name", true),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ });
+
+ assert!(result.is_err());
+ thread.read_with(cx, |thread, _| assert!(thread.entries().is_empty()));
+ }
+
+ #[gpui::test]
+ async fn test_form_elicitation_accepts_response(cx: &mut TestAppContext) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let thread = new_test_thread(cx).await;
+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+ let tool_call_id = acp::ToolCallId::new("tool-1");
+
+ let response_task = thread.update(cx, |thread, cx| {
+ thread
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationSessionScope::new(session_id.clone())
+ .tool_call_id(tool_call_id.clone()),
+ acp::ElicitationSchema::new().string("name", true),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+
+ let elicitation_id = thread.read_with(cx, |thread, _| {
+ let (elicitation_id, elicitation) = only_thread_elicitation(thread);
+ let acp::ElicitationScope::Session(scope) = elicitation.request.scope() else {
+ panic!("expected session-scoped elicitation");
+ };
+ assert_eq!(scope.tool_call_id.as_ref(), Some(&tool_call_id));
+ elicitation_id
+ });
+
+ let expected_content = std::collections::BTreeMap::from([(
+ "name".to_string(),
+ acp::ElicitationContentValue::from("Ada"),
+ )]);
+ thread.update(cx, |thread, cx| {
+ thread.respond_to_elicitation(
+ &elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new().content(expected_content.clone()),
+ )),
+ cx,
+ );
+ });
+
+ let response = response_task.await;
+ assert_eq!(
+ response.action,
+ acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new().content(expected_content)
+ )
+ );
+ thread.read_with(cx, |thread, _| {
+ let Some((_, elicitation)) = thread.elicitation(&elicitation_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Accepted));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_url_elicitation_can_be_completed(cx: &mut TestAppContext) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let thread = new_test_thread(cx).await;
+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+ let url_elicitation_id = acp::ElicitationId::new("url-1");
+
+ let response_task = thread.update(cx, |thread, cx| {
+ thread
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationUrlMode::new(
+ acp::ElicitationSessionScope::new(session_id),
+ url_elicitation_id.clone(),
+ "https://example.com/complete",
+ ),
+ "Complete this in the browser",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+
+ let entry_id = thread.read_with(cx, |thread, _| {
+ let (entry_id, _) = only_thread_elicitation(thread);
+ entry_id
+ });
+
+ thread.update(cx, |thread, cx| {
+ thread.complete_url_elicitation(&url_elicitation_id, cx);
+ });
+ assert!(matches!(
+ response_task.await.action,
+ acp::ElicitationAction::Accept(_)
+ ));
+ thread.update(cx, |thread, cx| {
+ thread.respond_to_elicitation(
+ &entry_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ cx,
+ );
+ });
+ thread.read_with(cx, |thread, _| {
+ let Some((_, elicitation)) = thread.elicitation(&entry_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Completed));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_idle_cancel_cancels_accepted_url_elicitation(cx: &mut TestAppContext) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let thread = new_test_thread(cx).await;
+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+ let url_elicitation_id = acp::ElicitationId::new("url-1");
+
+ let response_task = thread.update(cx, |thread, cx| {
+ thread
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationUrlMode::new(
+ acp::ElicitationSessionScope::new(session_id),
+ url_elicitation_id.clone(),
+ "https://example.com/complete",
+ ),
+ "Complete this in the browser",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+
+ let entry_id = thread.read_with(cx, |thread, _| {
+ let (entry_id, _) = only_thread_elicitation(thread);
+ entry_id
+ });
+
+ thread.update(cx, |thread, cx| {
+ thread.respond_to_elicitation(
+ &entry_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new(),
+ )),
+ cx,
+ );
+ });
+ assert!(matches!(
+ response_task.await.action,
+ acp::ElicitationAction::Accept(_)
+ ));
+
+ thread.update(cx, |thread, cx| {
+ thread.cancel(cx).detach();
+ });
+ thread.read_with(cx, |thread, _| {
+ let Some((_, elicitation)) = thread.elicitation(&entry_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Canceled));
+ });
+
+ thread.update(cx, |thread, cx| {
+ thread.complete_url_elicitation(&url_elicitation_id, cx);
+ });
+ thread.read_with(cx, |thread, _| {
+ let Some((_, elicitation)) = thread.elicitation(&entry_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Canceled));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_cancel_accepted_url_elicitation_marks_canceled(cx: &mut TestAppContext) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let thread = new_test_thread(cx).await;
+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+ let url_elicitation_id = acp::ElicitationId::new("url-1");
+
+ let response_task = thread.update(cx, |thread, cx| {
+ thread
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationUrlMode::new(
+ acp::ElicitationSessionScope::new(session_id),
+ url_elicitation_id.clone(),
+ "https://example.com/complete",
+ ),
+ "Complete this in the browser",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+
+ let entry_id = thread.read_with(cx, |thread, _| {
+ let (entry_id, _) = only_thread_elicitation(thread);
+ entry_id
+ });
+
+ thread.update(cx, |thread, cx| {
+ thread.respond_to_elicitation(
+ &entry_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new(),
+ )),
+ cx,
+ );
+ });
+ assert!(matches!(
+ response_task.await.action,
+ acp::ElicitationAction::Accept(_)
+ ));
+ thread.read_with(cx, |thread, _| {
+ let Some((_, elicitation)) = thread.elicitation(&entry_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Accepted));
+ });
+
+ thread.update(cx, |thread, cx| {
+ thread.cancel(cx).detach();
+ });
+ thread.read_with(cx, |thread, _| {
+ let Some((_, elicitation)) = thread.elicitation(&entry_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Canceled));
+ });
+
+ thread.update(cx, |thread, cx| {
+ thread.complete_url_elicitation(&url_elicitation_id, cx);
+ });
+ thread.read_with(cx, |thread, _| {
+ let Some((_, elicitation)) = thread.elicitation(&entry_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Canceled));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_turn_cancel_cancels_accepted_url_elicitation_from_previous_turn(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let fs = FakeFs::new(cx.executor());
+ let project = Project::test(fs, [], cx).await;
+ let prompt_count = Rc::new(RefCell::new(0usize));
+ let connection = Rc::new(FakeAgentConnection::new().on_user_message({
+ let prompt_count = prompt_count.clone();
+ move |_request, _thread, _cx| {
+ let stop_reason = {
+ let mut prompt_count = prompt_count.borrow_mut();
+ let stop_reason = if *prompt_count == 0 {
+ acp::StopReason::EndTurn
+ } else {
+ acp::StopReason::Cancelled
+ };
+ *prompt_count += 1;
+ stop_reason
+ };
+
+ async move { Ok(acp::PromptResponse::new(stop_reason)) }.boxed_local()
+ }
+ }));
+ let thread = cx
+ .update(|cx| {
+ connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
+ })
+ .await
+ .expect("new session should succeed");
+
+ let response = thread
+ .update(cx, |thread, cx| thread.send(vec!["first turn".into()], cx))
+ .await
+ .expect("first turn should succeed")
+ .expect("first turn should return a response");
+ assert_eq!(response.stop_reason, acp::StopReason::EndTurn);
+
+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+ let url_elicitation_id = acp::ElicitationId::new("url-1");
+ let response_task = thread.update(cx, |thread, cx| {
+ thread
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationUrlMode::new(
+ acp::ElicitationSessionScope::new(session_id),
+ url_elicitation_id.clone(),
+ "https://example.com/complete",
+ ),
+ "Complete this in the browser",
+ ),
+ cx,
+ )
+ .expect("url elicitation should be accepted")
+ });
+
+ let entry_id = thread.read_with(cx, |thread, _| {
+ let (entry_id, _) = latest_thread_elicitation(thread);
+ entry_id
+ });
+
+ thread.update(cx, |thread, cx| {
+ thread.respond_to_elicitation(
+ &entry_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new(),
+ )),
+ cx,
+ );
+ });
+ assert!(matches!(
+ response_task.await.action,
+ acp::ElicitationAction::Accept(_)
+ ));
+
+ let response = thread
+ .update(cx, |thread, cx| thread.send(vec!["second turn".into()], cx))
+ .await
+ .expect("second turn should succeed")
+ .expect("second turn should return a response");
+ assert_eq!(response.stop_reason, acp::StopReason::Cancelled);
+ thread.read_with(cx, |thread, _| {
+ let Some((_, elicitation)) = thread.elicitation(&entry_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Canceled));
+ });
+
+ thread.update(cx, |thread, cx| {
+ thread.complete_url_elicitation(&url_elicitation_id, cx);
+ });
+ thread.read_with(cx, |thread, _| {
+ let Some((_, elicitation)) = thread.elicitation(&entry_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Canceled));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_request_scoped_elicitation_store_accepts_response(cx: &mut TestAppContext) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let store = cx.update(|cx| cx.new(|_| ElicitationStore::default()));
+
+ let response_task = store.update(cx, |store, cx| {
+ store
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
+ acp::ElicitationSchema::new().string("name", true),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+
+ let elicitation_id = store.read_with(cx, |store, _| {
+ let [elicitation] = store.elicitations() else {
+ panic!(
+ "expected one elicitation entry, got {:?}",
+ store.elicitations()
+ );
+ };
+ let acp::ElicitationScope::Request(scope) = elicitation.request.scope() else {
+ panic!("expected request-scoped elicitation");
+ };
+ assert_eq!(scope.request_id, acp::RequestId::Number(1));
+ elicitation.id.clone()
+ });
+
+ store.update(cx, |store, cx| {
+ store.respond_to_elicitation(
+ &elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ cx,
+ );
+ });
+
+ assert_eq!(response_task.await.action, acp::ElicitationAction::Decline);
+ store.read_with(cx, |store, _| {
+ let Some((_, elicitation)) = store.elicitation(&elicitation_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Declined));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_request_elicitation_store_ignores_duplicate_response(cx: &mut TestAppContext) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let store = cx.update(|cx| cx.new(|_| ElicitationStore::default()));
+
+ let response_task = store.update(cx, |store, cx| {
+ store
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
+ acp::ElicitationSchema::new().string("name", true),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+
+ let elicitation_id = store.read_with(cx, |store, _| {
+ let [elicitation] = store.elicitations() else {
+ panic!(
+ "expected one elicitation entry, got {:?}",
+ store.elicitations()
+ );
+ };
+ elicitation.id.clone()
+ });
+
+ store.update(cx, |store, cx| {
+ store.respond_to_elicitation(
+ &elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ cx,
+ );
+ store.respond_to_elicitation(
+ &elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new(),
+ )),
+ cx,
+ );
+ });
+
+ assert_eq!(response_task.await.action, acp::ElicitationAction::Decline);
+ store.read_with(cx, |store, _| {
+ let Some((_, elicitation)) = store.elicitation(&elicitation_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Declined));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_cancel_session_elicitation_by_id_resolves_cancel(cx: &mut TestAppContext) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let thread = new_test_thread(cx).await;
+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+
+ let (elicitation_id, response_task) = thread.update(cx, |thread, cx| {
+ thread
+ .request_elicitation_with_id(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationSessionScope::new(session_id),
+ acp::ElicitationSchema::new().string("name", true),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+
+ thread.update(cx, |thread, cx| {
+ thread.cancel_elicitation(&elicitation_id, cx);
+ });
+
+ assert_eq!(response_task.await.action, acp::ElicitationAction::Cancel);
+ thread.read_with(cx, |thread, _| {
+ let Some((_, elicitation)) = thread.elicitation(&elicitation_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Canceled));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_cancel_pending_session_elicitation_resolves_cancel(cx: &mut TestAppContext) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let thread = new_test_thread(cx).await;
+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+
+ let response_task = thread.update(cx, |thread, cx| {
+ thread
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationSessionScope::new(session_id),
+ acp::ElicitationSchema::new().string("name", true),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+
+ let elicitation_id = thread.read_with(cx, |thread, _| {
+ let (elicitation_id, _) = only_thread_elicitation(thread);
+ elicitation_id
+ });
+
+ thread.update(cx, |thread, cx| {
+ thread.cancel(cx).detach();
+ });
+
+ assert_eq!(response_task.await.action, acp::ElicitationAction::Cancel);
+ thread.read_with(cx, |thread, _| {
+ let Some((_, elicitation)) = thread.elicitation(&elicitation_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Canceled));
+ });
+ }
+
+ fn request_test_session_elicitation(
+ thread: WeakEntity<AcpThread>,
+ session_id: acp::SessionId,
+ cx: &mut AsyncApp,
+ ) -> Result<Task<acp::CreateElicitationResponse>> {
+ thread.update(cx, |thread, cx| {
+ thread
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationSessionScope::new(session_id),
+ acp::ElicitationSchema::new().string("name", true),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ .map_err(|error| anyhow!(error))
+ })?
+ }
+
+ #[gpui::test]
+ async fn test_prompt_error_cancels_pending_session_elicitation(cx: &mut TestAppContext) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let fs = FakeFs::new(cx.executor());
+ let project = Project::test(fs, [], cx).await;
+ let elicitation_action = Rc::new(RefCell::new(None));
+ let connection = Rc::new(FakeAgentConnection::new().on_user_message({
+ let elicitation_action = elicitation_action.clone();
+ move |request, thread, mut cx| {
+ let elicitation_action = elicitation_action.clone();
+ async move {
+ let response_task =
+ request_test_session_elicitation(thread, request.session_id, &mut cx)?;
+ cx.spawn(async move |_cx| {
+ let response = response_task.await;
+ *elicitation_action.borrow_mut() = Some(response.action);
+ })
+ .detach();
+
+ Err(anyhow!("prompt failed"))
+ }
+ .boxed_local()
+ }
+ }));
+ let thread = cx
+ .update(|cx| {
+ connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
+ })
+ .await
+ .expect("new session should succeed");
+
+ let result = thread
+ .update(cx, |thread, cx| thread.send(vec!["hello".into()], cx))
+ .await;
+
+ assert!(result.is_err());
+ cx.run_until_parked();
+ assert_eq!(
+ *elicitation_action.borrow(),
+ Some(acp::ElicitationAction::Cancel)
+ );
+ thread.read_with(cx, |thread, _| {
+ let Some(elicitation) = thread.entries().iter().find_map(|entry| match entry {
+ AgentThreadEntry::Elicitation(id) => {
+ thread.elicitation(id).map(|(_, elicitation)| elicitation)
+ }
+ _ => None,
+ }) else {
+ panic!("expected an elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Canceled));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_max_tokens_cancels_pending_session_elicitation(cx: &mut TestAppContext) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let fs = FakeFs::new(cx.executor());
+ let project = Project::test(fs, [], cx).await;
+ let elicitation_action = Rc::new(RefCell::new(None));
+ let connection = Rc::new(FakeAgentConnection::new().on_user_message({
+ let elicitation_action = elicitation_action.clone();
+ move |request, thread, mut cx| {
+ let elicitation_action = elicitation_action.clone();
+ async move {
+ let response_task =
+ request_test_session_elicitation(thread, request.session_id, &mut cx)?;
+ cx.spawn(async move |_cx| {
+ let response = response_task.await;
+ *elicitation_action.borrow_mut() = Some(response.action);
+ })
+ .detach();
+
+ Ok(acp::PromptResponse::new(acp::StopReason::MaxTokens))
+ }
+ .boxed_local()
+ }
+ }));
+ let thread = cx
+ .update(|cx| {
+ connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)
+ })
+ .await
+ .expect("new session should succeed");
+
+ let result = thread
+ .update(cx, |thread, cx| thread.send(vec!["hello".into()], cx))
+ .await;
+
+ assert!(result.is_err());
+ cx.run_until_parked();
+ assert_eq!(
+ *elicitation_action.borrow(),
+ Some(acp::ElicitationAction::Cancel)
+ );
+ thread.read_with(cx, |thread, _| {
+ let Some(elicitation) = thread.entries().iter().find_map(|entry| match entry {
+ AgentThreadEntry::Elicitation(id) => {
+ thread.elicitation(id).map(|(_, elicitation)| elicitation)
+ }
+ _ => None,
+ }) else {
+ panic!("expected an elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Canceled));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_cancel_request_scoped_elicitation_resolves_cancel(cx: &mut TestAppContext) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let store = cx.update(|cx| cx.new(|_| ElicitationStore::default()));
+
+ let (elicitation_id, response_task) = store.update(cx, |store, cx| {
+ store
+ .request_elicitation_with_id(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
+ acp::ElicitationSchema::new().string("name", true),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+
+ store.update(cx, |store, cx| {
+ store.cancel_elicitation(&elicitation_id, cx);
+ });
+
+ assert_eq!(response_task.await.action, acp::ElicitationAction::Cancel);
+ store.read_with(cx, |store, _| {
+ let Some((_, elicitation)) = store.elicitation(&elicitation_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Canceled));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_request_elicitation_store_cancel_all_resolves_cancel(cx: &mut TestAppContext) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let store = cx.update(|cx| cx.new(|_| ElicitationStore::default()));
+
+ let response_task = store.update(cx, |store, cx| {
+ store
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
+ acp::ElicitationSchema::new().string("name", true),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+
+ store.update(cx, |store, cx| {
+ store.cancel_all(cx);
+ });
+
+ assert_eq!(response_task.await.action, acp::ElicitationAction::Cancel);
+ }
+
+ #[gpui::test]
+ async fn test_request_elicitation_store_clear_removes_answered_and_cancels_pending(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let store = cx.update(|cx| cx.new(|_| ElicitationStore::default()));
+
+ let first_response_task = store.update(cx, |store, cx| {
+ store
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
+ acp::ElicitationSchema::new().string("name", true),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+ let second_response_task = store.update(cx, |store, cx| {
+ store
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationRequestScope::new(acp::RequestId::Number(2)),
+ acp::ElicitationSchema::new().string("account", true),
+ ),
+ "Provide an account",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+
+ let first_elicitation_id = store.read_with(cx, |store, _| {
+ let [first, _second] = store.elicitations() else {
+ panic!("expected two elicitations, got {:?}", store.elicitations());
+ };
+ first.id.clone()
+ });
+
+ store.update(cx, |store, cx| {
+ store.respond_to_elicitation(
+ &first_elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ cx,
+ );
+ store.clear(cx);
+ });
+
+ assert_eq!(
+ first_response_task.await.action,
+ acp::ElicitationAction::Decline
+ );
+ assert_eq!(
+ second_response_task.await.action,
+ acp::ElicitationAction::Cancel
+ );
+ store.read_with(cx, |store, _| assert!(store.elicitations().is_empty()));
+ }
+
+ #[gpui::test]
+ async fn test_request_elicitation_store_clear_resolved_preserves_outstanding(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let store = cx.update(|cx| cx.new(|_| ElicitationStore::default()));
+ let url_elicitation_id = acp::ElicitationId::new("url-1");
+
+ let accepted_response_task = store.update(cx, |store, cx| {
+ store
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
+ acp::ElicitationSchema::new().string("name", true),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+ let pending_response_task = store.update(cx, |store, cx| {
+ store
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationRequestScope::new(acp::RequestId::Number(2)),
+ acp::ElicitationSchema::new().string("account", true),
+ ),
+ "Provide an account",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+ let accepted_url_response_task = store.update(cx, |store, cx| {
+ store
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationUrlMode::new(
+ acp::ElicitationRequestScope::new(acp::RequestId::Number(3)),
+ url_elicitation_id,
+ "https://example.com/complete",
+ ),
+ "Complete this in the browser",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+
+ let (accepted_id, pending_id, accepted_url_id) = store.read_with(cx, |store, _| {
+ let [accepted, pending, accepted_url] = store.elicitations() else {
+ panic!(
+ "expected three request-scoped elicitations, got {:?}",
+ store.elicitations()
+ );
+ };
+ (
+ accepted.id.clone(),
+ pending.id.clone(),
+ accepted_url.id.clone(),
+ )
+ });
+
+ store.update(cx, |store, cx| {
+ store.respond_to_elicitation(
+ &accepted_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new(),
+ )),
+ cx,
+ );
+ store.respond_to_elicitation(
+ &accepted_url_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new(),
+ )),
+ cx,
+ );
+ });
+ assert!(matches!(
+ accepted_response_task.await.action,
+ acp::ElicitationAction::Accept(_)
+ ));
+ assert!(matches!(
+ accepted_url_response_task.await.action,
+ acp::ElicitationAction::Accept(_)
+ ));
+
+ let cleared_ids = store.update(cx, |store, cx| store.clear_resolved(cx));
+ assert_eq!(cleared_ids, vec![accepted_id]);
+ store.read_with(cx, |store, _| {
+ let [pending, accepted_url] = store.elicitations() else {
+ panic!(
+ "expected pending and accepted url elicitations, got {:?}",
+ store.elicitations()
+ );
+ };
+ assert_eq!(pending.id, pending_id);
+ assert!(matches!(pending.status, ElicitationStatus::Pending { .. }));
+ assert_eq!(accepted_url.id, accepted_url_id);
+ assert!(matches!(accepted_url.status, ElicitationStatus::Accepted));
+ });
+
+ store.update(cx, |store, cx| store.clear(cx));
+ assert_eq!(
+ pending_response_task.await.action,
+ acp::ElicitationAction::Cancel
+ );
+ }
+
+ #[gpui::test]
+ async fn test_request_url_elicitation_store_can_be_completed(cx: &mut TestAppContext) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let store = cx.update(|cx| cx.new(|_| ElicitationStore::default()));
+ let url_elicitation_id = acp::ElicitationId::new("url-1");
+
+ let response_task = store.update(cx, |store, cx| {
+ store
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationUrlMode::new(
+ acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
+ url_elicitation_id.clone(),
+ "https://example.com/complete",
+ ),
+ "Complete this in the browser",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+
+ let entry_id = store.read_with(cx, |store, _| {
+ let [elicitation] = store.elicitations() else {
+ panic!(
+ "expected one request-scoped elicitation, got {:?}",
+ store.elicitations()
+ );
+ };
+ elicitation.id.clone()
+ });
+
+ store.update(cx, |store, cx| {
+ store.complete_url_elicitation(&url_elicitation_id, cx);
+ });
+
+ assert!(matches!(
+ response_task.await.action,
+ acp::ElicitationAction::Accept(_)
+ ));
+ store.update(cx, |store, cx| {
+ store.respond_to_elicitation(
+ &entry_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ cx,
+ );
+ });
+ store.read_with(cx, |store, _| {
+ let Some((_, elicitation)) = store.elicitation(&entry_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Completed));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_request_url_elicitation_store_cancel_all_cancels_accepted_url(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let store = cx.update(|cx| cx.new(|_| ElicitationStore::default()));
+ let url_elicitation_id = acp::ElicitationId::new("url-1");
+
+ let response_task = store.update(cx, |store, cx| {
+ store
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationUrlMode::new(
+ acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
+ url_elicitation_id.clone(),
+ "https://example.com/complete",
+ ),
+ "Complete this in the browser",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+
+ let entry_id = store.read_with(cx, |store, _| {
+ let [elicitation] = store.elicitations() else {
+ panic!(
+ "expected one elicitation entry, got {:?}",
+ store.elicitations()
+ );
+ };
+ elicitation.id.clone()
+ });
+
+ store.update(cx, |store, cx| {
+ store.respond_to_elicitation(
+ &entry_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new(),
+ )),
+ cx,
+ );
+ });
+ assert!(matches!(
+ response_task.await.action,
+ acp::ElicitationAction::Accept(_)
+ ));
+ store.update(cx, |store, cx| {
+ store.cancel_all(cx);
+ });
+ store.read_with(cx, |store, _| {
+ let Some((_, elicitation)) = store.elicitation(&entry_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Canceled));
+ });
+
+ store.update(cx, |store, cx| {
+ store.complete_url_elicitation(&url_elicitation_id, cx);
+ });
+ store.read_with(cx, |store, _| {
+ let Some((_, elicitation)) = store.elicitation(&entry_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Canceled));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_cancel_pending_elicitations_preserves_responded_statuses(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let thread = new_test_thread(cx).await;
+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+
+ let response_task = thread.update(cx, |thread, cx| {
+ thread
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationSessionScope::new(session_id),
+ acp::ElicitationSchema::new().string("name", true),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+
+ let elicitation_id = thread.read_with(cx, |thread, _| {
+ let (elicitation_id, _) = only_thread_elicitation(thread);
+ elicitation_id
+ });
+
+ thread.update(cx, |thread, cx| {
+ thread.respond_to_elicitation(
+ &elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ cx,
+ );
+ thread.cancel(cx).detach();
+ });
+
+ assert_eq!(response_task.await.action, acp::ElicitationAction::Decline);
+ thread.read_with(cx, |thread, _| {
+ let Some((_, elicitation)) = thread.elicitation(&elicitation_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Declined));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_session_elicitation_ignores_duplicate_response(cx: &mut TestAppContext) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let thread = new_test_thread(cx).await;
+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+
+ let response_task = thread.update(cx, |thread, cx| {
+ thread
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationSessionScope::new(session_id),
+ acp::ElicitationSchema::new().string("name", true),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+
+ let elicitation_id = thread.read_with(cx, |thread, _| {
+ let (elicitation_id, _) = only_thread_elicitation(thread);
+ elicitation_id
+ });
+
+ thread.update(cx, |thread, cx| {
+ thread.respond_to_elicitation(
+ &elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ cx,
+ );
+ thread.respond_to_elicitation(
+ &elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new(),
+ )),
+ cx,
+ );
+ });
+
+ assert_eq!(response_task.await.action, acp::ElicitationAction::Decline);
+ thread.read_with(cx, |thread, _| {
+ let Some((_, elicitation)) = thread.elicitation(&elicitation_id) else {
+ panic!("missing elicitation entry");
+ };
+ assert!(matches!(elicitation.status, ElicitationStatus::Declined));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_url_elicitation_rejects_invalid_url(cx: &mut TestAppContext) {
+ init_test(cx);
+ enable_acp_beta(cx);
+ let thread = new_test_thread(cx).await;
+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+
+ let result = thread.update(cx, |thread, cx| {
+ thread.request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationUrlMode::new(
+ acp::ElicitationSessionScope::new(session_id),
+ "url-1",
+ "not a url",
+ ),
+ "Complete this in the browser",
+ ),
+ cx,
+ )
+ });
+
+ assert!(result.is_err());
+ thread.read_with(cx, |thread, _| assert!(thread.entries().is_empty()));
+ }
+
async fn run_until_first_tool_call(
thread: &Entity<AcpThread>,
cx: &mut TestAppContext,
diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rs
index 71c46d3e622..eaf51978b5d 100644
--- a/crates/acp_thread/src/connection.rs
+++ b/crates/acp_thread/src/connection.rs
@@ -1,4 +1,4 @@
-use crate::AcpThread;
+use crate::{AcpThread, ElicitationStore};
use agent_client_protocol::schema::v1 as acp;
use anyhow::Result;
use chrono::{DateTime, Utc};
@@ -201,6 +201,13 @@ pub trait AgentConnection {
fn cancel(&self, session_id: &acp::SessionId, cx: &mut App);
+ /// Request-scoped elicitations are connection-level because they can arrive before a session
+ /// thread exists. Session-scoped elicitations stay in the thread timeline, but use
+ /// `ElicitationStore` for shared processing.
+ fn request_elicitations(&self) -> Option<Entity<ElicitationStore>> {
+ None
+ }
+
fn truncate(
&self,
_session_id: &acp::SessionId,
diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs
index 708d1c71687..9acc88da755 100644
--- a/crates/agent_servers/src/acp.rs
+++ b/crates/agent_servers/src/acp.rs
@@ -1,6 +1,6 @@
use acp_thread::{
AgentConnection, AgentSessionInfo, AgentSessionList, AgentSessionListRequest,
- AgentSessionListResponse,
+ AgentSessionListResponse, ElicitationStore,
};
use action_log::ActionLog;
use agent_client_protocol::schema::{
@@ -269,6 +269,7 @@ impl<T> FlattenAcpResult<T> for Result<Result<T, acp::Error>, anyhow::Error> {
struct ClientContext {
sessions: Rc<RefCell<HashMap<acp::SessionId, AcpSession>>>,
session_list: Rc<RefCell<Option<Rc<AcpSessionList>>>>,
+ request_elicitations: Entity<ElicitationStore>,
}
fn dispatch_queue_closed_error() -> acp::Error {
@@ -394,6 +395,7 @@ pub struct AcpConnection {
auth_methods: Vec<acp::AuthMethod>,
agent_server_store: WeakEntity<AgentServerStore>,
agent_capabilities: acp::AgentCapabilities,
+ request_elicitations: Entity<ElicitationStore>,
defaults: AcpConnectionDefaults,
child: Option<Child>,
session_list: Option<Rc<AcpSessionList>>,
@@ -726,11 +728,19 @@ fn connect_client_future(
on_request!(handle_wait_for_terminal_exit),
agent_client_protocol::on_receive_request!(),
)
+ .on_receive_request(
+ on_request!(handle_create_elicitation),
+ agent_client_protocol::on_receive_request!(),
+ )
// --- Notification handlers (agent→client) ---
.on_receive_notification(
on_notification!(handle_session_notification),
agent_client_protocol::on_receive_notification!(),
)
+ .on_receive_notification(
+ on_notification!(handle_complete_elicitation),
+ agent_client_protocol::on_receive_notification!(),
+ )
.connect_with(
transport,
move |connection: ConnectionTo<Agent>| async move {
@@ -745,7 +755,7 @@ fn connect_client_future(
fn client_capabilities_for_agent(
agent_id: &AgentId,
- supports_boolean_config_options: bool,
+ supports_beta_features: bool,
) -> acp::ClientCapabilities {
let mut meta = acp::Meta::from_iter([
("terminal_output".into(), true.into()),
@@ -764,13 +774,19 @@ fn client_capabilities_for_agent(
.auth(acp::AuthCapabilities::new().terminal(true))
.meta(meta);
- if supports_boolean_config_options {
- capabilities = capabilities.session(
- acp::ClientSessionCapabilities::new().config_options(
- acp::SessionConfigOptionsCapabilities::new()
- .boolean(acp::BooleanConfigOptionCapabilities::new()),
- ),
- );
+ if supports_beta_features {
+ capabilities = capabilities
+ .elicitation(
+ acp::ElicitationCapabilities::new()
+ .form(acp::ElicitationFormCapabilities::new())
+ .url(acp::ElicitationUrlCapabilities::new()),
+ )
+ .session(
+ acp::ClientSessionCapabilities::new().config_options(
+ acp::SessionConfigOptionsCapabilities::new()
+ .boolean(acp::BooleanConfigOptionCapabilities::new()),
+ ),
+ );
}
capabilities
@@ -861,6 +877,7 @@ impl AcpConnection {
let client_session_list: Rc<RefCell<Option<Rc<AcpSessionList>>>> =
Rc::new(RefCell::new(None));
+ let request_elicitations = cx.new(|_| ElicitationStore::default());
// Set up the foreground dispatch channel for bridging Send handler
// closures to the !Send foreground thread.
@@ -950,6 +967,7 @@ impl AcpConnection {
let dispatch_context = ClientContext {
sessions: sessions.clone(),
session_list: client_session_list.clone(),
+ request_elicitations: request_elicitations.clone(),
};
let dispatch_task = cx.spawn({
let mut dispatch_rx = dispatch_rx;
@@ -1075,6 +1093,7 @@ impl AcpConnection {
sessions,
pending_sessions: Rc::new(RefCell::new(HashMap::default())),
agent_capabilities: response.agent_capabilities,
+ request_elicitations,
defaults,
session_list,
debug_log,
@@ -1096,6 +1115,7 @@ impl AcpConnection {
connection: ConnectionTo<Agent>,
sessions: Rc<RefCell<HashMap<acp::SessionId, AcpSession>>>,
agent_capabilities: acp::AgentCapabilities,
+ request_elicitations: Entity<ElicitationStore>,
agent_server_store: WeakEntity<AgentServerStore>,
io_task: Task<()>,
dispatch_task: Task<()>,
@@ -1115,6 +1135,7 @@ impl AcpConnection {
auth_methods: vec![],
agent_server_store,
agent_capabilities,
+ request_elicitations,
defaults,
child: None,
session_list: None,
@@ -1993,6 +2014,10 @@ impl AgentConnection for AcpConnection {
self.connection.send_notification(params).log_err();
}
+ fn request_elicitations(&self) -> Option<Entity<ElicitationStore>> {
+ Some(self.request_elicitations.clone())
+ }
+
fn session_modes(
&self,
session_id: &acp::SessionId,
@@ -2073,6 +2098,10 @@ pub mod test_support {
load_session_count: Arc<AtomicUsize>,
close_session_count: Arc<AtomicUsize>,
fail_next_prompt: Arc<AtomicBool>,
+ auth_elicitation_request: Arc<Mutex<Option<acp::CreateElicitationRequest>>>,
+ auth_elicitation_response:
+ Arc<Mutex<Option<async_channel::Sender<acp::CreateElicitationResponse>>>>,
+ auth_elicitation_completion: Arc<Mutex<Option<acp::CompleteElicitationNotification>>>,
exit_status_sender:
Arc<std::sync::Mutex<Option<async_channel::Sender<std::process::ExitStatus>>>>,
}
@@ -2105,6 +2134,23 @@ pub mod test_support {
pub fn fail_next_prompt(&self) {
self.fail_next_prompt.store(true, Ordering::SeqCst);
}
+
+ pub fn request_elicitation_during_auth(
+ &self,
+ request: acp::CreateElicitationRequest,
+ ) -> async_channel::Receiver<acp::CreateElicitationResponse> {
+ let (response_tx, response_rx) = async_channel::bounded(1);
+ *self
+ .auth_elicitation_request
+ .lock()
+ .expect("auth elicitation request lock should not be poisoned") = Some(request);
+ *self
+ .auth_elicitation_response
+ .lock()
+ .expect("auth elicitation response lock should not be poisoned") =
+ Some(response_tx);
+ response_rx
+ }
}
impl crate::AgentServer for FakeAcpAgentServer {
@@ -2125,6 +2171,9 @@ pub mod test_support {
let load_session_count = self.load_session_count.clone();
let close_session_count = self.close_session_count.clone();
let fail_next_prompt = self.fail_next_prompt.clone();
+ let auth_elicitation_request = self.auth_elicitation_request.clone();
+ let auth_elicitation_response = self.auth_elicitation_response.clone();
+ let auth_elicitation_completion = self.auth_elicitation_completion.clone();
let exit_status_sender = self.exit_status_sender.clone();
cx.spawn(async move |cx| {
let harness = build_fake_acp_connection(
@@ -2132,6 +2181,9 @@ pub mod test_support {
load_session_count,
close_session_count,
fail_next_prompt,
+ auth_elicitation_request,
+ auth_elicitation_response,
+ auth_elicitation_completion,
cx,
)
.await?;
@@ -2303,6 +2355,10 @@ pub mod test_support {
self.inner.cancel(session_id, cx)
}
+ fn request_elicitations(&self) -> Option<Entity<ElicitationStore>> {
+ self.inner.request_elicitations()
+ }
+
fn truncate(
&self,
session_id: &acp::SessionId,
@@ -2353,6 +2409,11 @@ pub mod test_support {
load_session_count: Arc<AtomicUsize>,
close_session_count: Arc<AtomicUsize>,
fail_next_prompt: Arc<AtomicBool>,
+ auth_elicitation_request: Arc<Mutex<Option<acp::CreateElicitationRequest>>>,
+ auth_elicitation_response: Arc<
+ Mutex<Option<async_channel::Sender<acp::CreateElicitationResponse>>>,
+ >,
+ auth_elicitation_completion: Arc<Mutex<Option<acp::CompleteElicitationNotification>>>,
cx: &mut AsyncApp,
) -> Result<FakeAcpConnectionHarness> {
let (client_transport, agent_transport) = agent_client_protocol::Channel::duplex();
@@ -2382,8 +2443,41 @@ pub mod test_support {
agent_client_protocol::on_receive_request!(),
)
.on_receive_request(
- async move |_req: acp::AuthenticateRequest, responder, _cx| {
- responder.respond(Default::default())
+ {
+ let auth_elicitation_request = auth_elicitation_request.clone();
+ let auth_elicitation_response = auth_elicitation_response.clone();
+ let auth_elicitation_completion = auth_elicitation_completion.clone();
+ async move |_req: acp::AuthenticateRequest, responder, cx| {
+ let request = auth_elicitation_request
+ .lock()
+ .expect("auth elicitation request lock should not be poisoned")
+ .take();
+ let response_tx = auth_elicitation_response
+ .lock()
+ .expect("auth elicitation response lock should not be poisoned")
+ .take();
+ let completion = auth_elicitation_completion
+ .lock()
+ .expect("auth elicitation completion lock should not be poisoned")
+ .take();
+
+ if let Some(request) = request {
+ cx.send_request(request)
+ .on_receiving_result(async move |result| {
+ if let (Ok(response), Some(response_tx)) = (result, response_tx)
+ {
+ response_tx.send(response).await.ok();
+ }
+ responder.respond(Default::default())
+ })?;
+ if let Some(completion) = completion {
+ cx.send_notification(completion)?;
+ }
+ Ok(())
+ } else {
+ responder.respond(Default::default())
+ }
+ }
},
agent_client_protocol::on_receive_request!(),
)
@@ -2471,9 +2565,11 @@ pub mod test_support {
let agent_capabilities = response.agent_capabilities;
+ let request_elicitations = cx.new(|_| ElicitationStore::default());
let dispatch_context = ClientContext {
sessions: sessions.clone(),
session_list: client_session_list.clone(),
+ request_elicitations: request_elicitations.clone(),
};
let dispatch_task = cx.spawn({
let mut dispatch_rx = dispatch_rx;
@@ -2492,6 +2588,7 @@ pub mod test_support {
client_conn,
sessions,
agent_capabilities,
+ request_elicitations,
agent_server_store,
client_io_task,
dispatch_task,
@@ -2527,11 +2624,77 @@ pub mod test_support {
Arc::new(AtomicUsize::new(0)),
Arc::new(AtomicUsize::new(0)),
Arc::new(AtomicBool::new(false)),
+ Arc::new(Mutex::new(None)),
+ Arc::new(Mutex::new(None)),
+ Arc::new(Mutex::new(None)),
&mut cx.to_async(),
)
.await
.expect("failed to initialize ACP connection")
}
+
+ #[cfg(test)]
+ pub async fn connect_fake_acp_connection_with_auth_elicitation(
+ project: Entity<Project>,
+ request: acp::CreateElicitationRequest,
+ cx: &mut gpui::TestAppContext,
+ ) -> (
+ FakeAcpConnectionHarness,
+ async_channel::Receiver<acp::CreateElicitationResponse>,
+ ) {
+ cx.update(|cx| {
+ let store = settings::SettingsStore::test(cx);
+ cx.set_global(store);
+ });
+
+ let (response_tx, response_rx) = async_channel::bounded(1);
+ let harness = build_fake_acp_connection(
+ project,
+ Arc::new(AtomicUsize::new(0)),
+ Arc::new(AtomicUsize::new(0)),
+ Arc::new(AtomicBool::new(false)),
+ Arc::new(Mutex::new(Some(request))),
+ Arc::new(Mutex::new(Some(response_tx))),
+ Arc::new(Mutex::new(None)),
+ &mut cx.to_async(),
+ )
+ .await
+ .expect("failed to initialize ACP connection");
+
+ (harness, response_rx)
+ }
+
+ #[cfg(test)]
+ pub async fn connect_fake_acp_connection_with_auth_elicitation_completion(
+ project: Entity<Project>,
+ request: acp::CreateElicitationRequest,
+ completion: acp::CompleteElicitationNotification,
+ cx: &mut gpui::TestAppContext,
+ ) -> (
+ FakeAcpConnectionHarness,
+ async_channel::Receiver<acp::CreateElicitationResponse>,
+ ) {
+ cx.update(|cx| {
+ let store = settings::SettingsStore::test(cx);
+ cx.set_global(store);
+ });
+
+ let (response_tx, response_rx) = async_channel::bounded(1);
+ let harness = build_fake_acp_connection(
+ project,
+ Arc::new(AtomicUsize::new(0)),
+ Arc::new(AtomicUsize::new(0)),
+ Arc::new(AtomicBool::new(false)),
+ Arc::new(Mutex::new(Some(request))),
+ Arc::new(Mutex::new(Some(response_tx))),
+ Arc::new(Mutex::new(Some(completion))),
+ &mut cx.to_async(),
+ )
+ .await
+ .expect("failed to initialize ACP connection");
+
+ (harness, response_rx)
+ }
}
#[cfg(test)]
@@ -2540,8 +2703,322 @@ mod tests {
use super::*;
use feature_flags::FeatureFlag as _;
+ use gpui::UpdateGlobal as _;
use settings::Settings as _;
+ fn init_feature_flags_test(cx: &mut gpui::TestAppContext) {
+ cx.update(|cx| {
+ let mut settings_store = SettingsStore::test(cx);
+ settings_store.register_setting::<feature_flags::FeatureFlagsSettings>();
+ cx.set_global(settings_store);
+ cx.update_flags(false, vec![]);
+ });
+ }
+
+ fn set_acp_beta_override(value: &str, cx: &mut gpui::TestAppContext) {
+ cx.update(|cx| {
+ SettingsStore::update_global(cx, |store, cx| {
+ store.update_user_settings(cx, |content| {
+ content
+ .feature_flags
+ .get_or_insert_default()
+ .insert(AcpBetaFeatureFlag::NAME.to_string(), value.to_string());
+ });
+ });
+ });
+ }
+
+ #[gpui::test]
+ async fn client_capabilities_omit_elicitation_without_acp_beta(cx: &mut gpui::TestAppContext) {
+ init_feature_flags_test(cx);
+ set_acp_beta_override("off", cx);
+
+ let capabilities = cx.update(|cx| {
+ client_capabilities_for_agent(
+ &AgentId::new("codex-acp"),
+ cx.has_flag::<AcpBetaFeatureFlag>(),
+ )
+ });
+
+ assert!(capabilities.elicitation.is_none());
+ }
+
+ #[gpui::test]
+ async fn client_capabilities_include_elicitation_with_acp_beta(cx: &mut gpui::TestAppContext) {
+ init_feature_flags_test(cx);
+ cx.update(|cx| {
+ cx.update_flags(false, vec![AcpBetaFeatureFlag::NAME.to_string()]);
+ });
+
+ let capabilities = cx.update(|cx| {
+ client_capabilities_for_agent(
+ &AgentId::new("codex-acp"),
+ cx.has_flag::<AcpBetaFeatureFlag>(),
+ )
+ });
+ let elicitation = capabilities
+ .elicitation
+ .expect("elicitation should be advertised when acp-beta is enabled");
+
+ assert!(elicitation.form.is_some());
+ assert!(elicitation.url.is_some());
+ }
+
+ #[gpui::test]
+ async fn request_scoped_elicitation_during_auth_uses_connection_store(
+ cx: &mut gpui::TestAppContext,
+ ) {
+ init_feature_flags_test(cx);
+ cx.update(|cx| {
+ cx.update_flags(false, vec![AcpBetaFeatureFlag::NAME.to_string()]);
+ });
+
+ let fs = fs::FakeFs::new(cx.executor());
+ fs.insert_tree("/", serde_json::json!({ "a": {} })).await;
+ let project = project::Project::test(fs, [std::path::Path::new("/a")], cx).await;
+
+ let request_id = acp::RequestId::Number(1);
+ let (harness, response_rx) =
+ test_support::connect_fake_acp_connection_with_auth_elicitation(
+ project,
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationRequestScope::new(request_id.clone()),
+ acp::ElicitationSchema::new().string("name", true),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ .await;
+ let connection = harness.connection.clone();
+ let auth_task =
+ cx.update(|cx| connection.authenticate(acp::AuthMethodId::new("login"), cx));
+ cx.run_until_parked();
+
+ let store = connection
+ .request_elicitations()
+ .expect("ACP connections expose request-scoped elicitations");
+ let elicitation_id = store.read_with(cx, |store, _| {
+ let [elicitation] = store.elicitations() else {
+ panic!(
+ "expected one request-scoped elicitation, got {:?}",
+ store.elicitations()
+ );
+ };
+ let acp::ElicitationScope::Request(scope) = elicitation.request.scope() else {
+ panic!("expected request-scoped elicitation");
+ };
+ assert_eq!(scope.request_id, request_id);
+ elicitation.id.clone()
+ });
+ assert!(
+ connection.sessions.borrow().is_empty(),
+ "auth-time request-scoped elicitations must not require a session"
+ );
+
+ let expected_content = std::collections::BTreeMap::from([(
+ "name".to_string(),
+ acp::ElicitationContentValue::from("Ada"),
+ )]);
+ store.update(cx, |store, cx| {
+ store.respond_to_elicitation(
+ &elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new().content(expected_content.clone()),
+ )),
+ cx,
+ );
+ });
+
+ let response = response_rx
+ .recv()
+ .await
+ .expect("fake auth flow should receive elicitation response");
+ assert_eq!(
+ response.action,
+ acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new().content(expected_content)
+ )
+ );
+ auth_task.await.expect("auth should complete");
+ }
+
+ #[gpui::test]
+ async fn request_scoped_url_elicitation_completion_after_create_is_observed(
+ cx: &mut gpui::TestAppContext,
+ ) {
+ init_feature_flags_test(cx);
+ cx.update(|cx| {
+ cx.update_flags(false, vec![AcpBetaFeatureFlag::NAME.to_string()]);
+ });
+
+ let fs = fs::FakeFs::new(cx.executor());
+ fs.insert_tree("/", serde_json::json!({ "a": {} })).await;
+ let project = project::Project::test(fs, [std::path::Path::new("/a")], cx).await;
+
+ let request_id = acp::RequestId::Number(1);
+ let url_elicitation_id = acp::ElicitationId::new("auth-url");
+ let (harness, response_rx) =
+ test_support::connect_fake_acp_connection_with_auth_elicitation_completion(
+ project,
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationUrlMode::new(
+ acp::ElicitationRequestScope::new(request_id.clone()),
+ url_elicitation_id.clone(),
+ "https://auth.example.com/device",
+ ),
+ "Authorize Zed in your browser",
+ ),
+ acp::CompleteElicitationNotification::new(url_elicitation_id),
+ cx,
+ )
+ .await;
+ let connection = harness.connection.clone();
+ let auth_task =
+ cx.update(|cx| connection.authenticate(acp::AuthMethodId::new("login"), cx));
+ cx.run_until_parked();
+
+ let response = response_rx
+ .recv()
+ .await
+ .expect("fake auth flow should receive elicitation response");
+ assert_eq!(
+ response.action,
+ acp::ElicitationAction::Accept(acp::ElicitationAcceptAction::new())
+ );
+
+ let store = connection
+ .request_elicitations()
+ .expect("ACP connections expose request-scoped elicitations");
+ store.read_with(cx, |store, _| {
+ let [elicitation] = store.elicitations() else {
+ panic!(
+ "expected one request-scoped elicitation, got {:?}",
+ store.elicitations()
+ );
+ };
+ let acp::ElicitationScope::Request(scope) = elicitation.request.scope() else {
+ panic!("expected request-scoped elicitation");
+ };
+ assert_eq!(scope.request_id, request_id);
+ assert!(matches!(
+ elicitation.status,
+ acp_thread::ElicitationStatus::Completed
+ ));
+ });
+
+ auth_task.await.expect("auth should complete");
+ }
+
+ #[gpui::test]
+ async fn request_scoped_elicitation_ignores_open_sessions(cx: &mut gpui::TestAppContext) {
+ init_feature_flags_test(cx);
+ cx.update(|cx| {
+ cx.update_flags(false, vec![AcpBetaFeatureFlag::NAME.to_string()]);
+ });
+
+ let fs = fs::FakeFs::new(cx.executor());
+ fs.insert_tree("/", serde_json::json!({ "a": {} })).await;
+ let project = project::Project::test(fs, [std::path::Path::new("/a")], cx).await;
+
+ let request_id = acp::RequestId::Number(1);
+ let (harness, response_rx) =
+ test_support::connect_fake_acp_connection_with_auth_elicitation(
+ project.clone(),
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationRequestScope::new(request_id.clone()),
+ acp::ElicitationSchema::new().string("name", true),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ .await;
+ let connection = harness.connection.clone();
+ let work_dirs = util::path_list::PathList::new(&[std::path::Path::new("/a")]);
+
+ let first_thread = cx
+ .update(|cx| {
+ connection.clone().load_session(
+ acp::SessionId::new("session-1"),
+ project.clone(),
+ work_dirs.clone(),
+ None,
+ cx,
+ )
+ })
+ .await
+ .expect("first load_session should succeed");
+ let second_thread = cx
+ .update(|cx| {
+ connection.clone().load_session(
+ acp::SessionId::new("session-2"),
+ project,
+ work_dirs,
+ None,
+ cx,
+ )
+ })
+ .await
+ .expect("second load_session should succeed");
+ cx.run_until_parked();
+ assert_eq!(
+ connection.sessions.borrow().len(),
+ 2,
+ "test setup should have multiple open sessions"
+ );
+
+ let auth_task =
+ cx.update(|cx| connection.authenticate(acp::AuthMethodId::new("login"), cx));
+ cx.run_until_parked();
+
+ let store = connection
+ .request_elicitations()
+ .expect("ACP connections expose request-scoped elicitations");
+ let elicitation_id = store.read_with(cx, |store, _| {
+ let [elicitation] = store.elicitations() else {
+ panic!(
+ "expected one request-scoped elicitation, got {:?}",
+ store.elicitations()
+ );
+ };
+ let acp::ElicitationScope::Request(scope) = elicitation.request.scope() else {
+ panic!("expected request-scoped elicitation");
+ };
+ assert_eq!(scope.request_id, request_id);
+ elicitation.id.clone()
+ });
+
+ for thread in [first_thread, second_thread] {
+ thread.read_with(cx, |thread, _| {
+ assert!(
+ thread.entries().iter().all(|entry| !matches!(
+ entry,
+ acp_thread::AgentThreadEntry::Elicitation(_)
+ )),
+ "request-scoped elicitation should not be inserted into a session thread"
+ );
+ });
+ }
+
+ store.update(cx, |store, cx| {
+ store.respond_to_elicitation(
+ &elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ cx,
+ );
+ });
+
+ let response = response_rx
+ .recv()
+ .await
+ .expect("fake auth flow should receive elicitation response");
+ assert_eq!(response.action, acp::ElicitationAction::Decline);
+ auth_task.await.expect("auth should complete");
+ }
+
#[test]
fn cursor_client_capabilities_include_parameterized_model_picker_meta() {
let capabilities = client_capabilities_for_agent(&AgentId::new(CURSOR_ID), false);
@@ -3243,10 +3720,12 @@ mod tests {
let sessions = Rc::new(RefCell::new(HashMap::default()));
let connection = cx.update(|cx| {
+ let request_elicitations = cx.new(|_| ElicitationStore::default());
AcpConnection::new_for_test(
client_conn,
sessions,
acp::AgentCapabilities::default(),
+ request_elicitations,
WeakEntity::new_invalid(),
client_io_task,
Task::ready(()),
@@ -3519,9 +3998,11 @@ mod tests {
let agent_capabilities = response.agent_capabilities;
+ let request_elicitations = cx.new(|_| ElicitationStore::default());
let dispatch_context = ClientContext {
sessions: sessions.clone(),
session_list: client_session_list.clone(),
+ request_elicitations: request_elicitations.clone(),
};
// `TestAppContext::spawn` hands out an `AsyncApp` by value, whereas the
// production path uses `Context::spawn` which hands out `&mut AsyncApp`.
@@ -3545,6 +4026,7 @@ mod tests {
client_conn,
sessions,
agent_capabilities,
+ request_elicitations,
agent_server_store,
client_io_task,
dispatch_task,
@@ -3709,6 +4191,7 @@ mod tests {
acp_thread::AgentThreadEntry::UserMessage(_) => "user",
acp_thread::AgentThreadEntry::AssistantMessage(_) => "assistant",
acp_thread::AgentThreadEntry::ToolCall(_) => "tool_call",
+ acp_thread::AgentThreadEntry::Elicitation(_) => "elicitation",
acp_thread::AgentThreadEntry::CompletedPlan(_) => "plan",
acp_thread::AgentThreadEntry::ContextCompaction(_) => "compaction",
})
@@ -4164,6 +4647,135 @@ fn handle_request_permission(
.detach();
}
+fn handle_create_elicitation(
+ args: acp::CreateElicitationRequest,
+ responder: Responder<acp::CreateElicitationResponse>,
+ cx: &mut AsyncApp,
+ ctx: &ClientContext,
+) {
+ if !cx.update(|cx| cx.has_flag::<AcpBetaFeatureFlag>()) {
+ return respond_err(
+ responder,
+ acp::Error::invalid_params().data("elicitation support requires the ACP beta flag"),
+ );
+ }
+
+ match args.scope() {
+ acp::ElicitationScope::Session(scope) => {
+ let thread = match session_thread(ctx, &scope.session_id) {
+ Ok(t) => t,
+ Err(e) => return respond_err(responder, e),
+ };
+
+ let (elicitation_id, task) = match thread
+ .update(cx, |thread, cx| {
+ thread.request_elicitation_with_id(args, cx)
+ })
+ .flatten_acp()
+ {
+ Ok(task) => task,
+ Err(e) => return respond_err(responder, e),
+ };
+
+ let cancellation = responder.cancellation();
+ cx.spawn(async move |cx| {
+ let result: Result<_, acp::Error> = cancellation
+ .run_until_cancelled(async { Ok(task.await) })
+ .await;
+
+ match result {
+ Ok(response) => {
+ responder.respond(response).log_err();
+ }
+ Err(e) => {
+ if e.code == ErrorCode::RequestCancelled {
+ thread
+ .update(cx, |thread, cx| {
+ thread.cancel_elicitation(&elicitation_id, cx)
+ })
+ .log_err();
+ }
+ respond_err(responder, e);
+ }
+ }
+ })
+ .detach();
+ }
+ acp::ElicitationScope::Request(_) => {
+ let store = ctx.request_elicitations.clone();
+ let (elicitation_id, task) =
+ match store.update(cx, |store, cx| store.request_elicitation_with_id(args, cx)) {
+ Ok(task) => task,
+ Err(e) => return respond_err(responder, e),
+ };
+ let store = store.downgrade();
+
+ let cancellation = responder.cancellation();
+ cx.spawn(async move |cx| {
+ let result: Result<_, acp::Error> = cancellation
+ .run_until_cancelled(async { Ok(task.await) })
+ .await;
+
+ match result {
+ Ok(response) => {
+ responder.respond(response).log_err();
+ }
+ Err(e) => {
+ if e.code == ErrorCode::RequestCancelled {
+ store
+ .update(cx, |store, cx| {
+ store.cancel_elicitation(&elicitation_id, cx)
+ })
+ .log_err();
+ }
+ respond_err(responder, e);
+ }
+ }
+ })
+ .detach();
+ }
+ _ => {
+ respond_err(
+ responder,
+ acp::Error::invalid_params().data("unknown elicitation scope"),
+ );
+ }
+ }
+}
+
+fn handle_complete_elicitation(
+ args: acp::CompleteElicitationNotification,
+ cx: &mut AsyncApp,
+ ctx: &ClientContext,
+) {
+ if !cx.update(|cx| cx.has_flag::<AcpBetaFeatureFlag>()) {
+ return;
+ }
+
+ let threads = ctx
+ .sessions
+ .borrow()
+ .values()
+ .map(|session| session.thread.clone())
+ .collect::<Vec<_>>();
+ let request_elicitations = ctx.request_elicitations.clone();
+ let elicitation_id = args.elicitation_id;
+
+ cx.spawn(async move |cx| {
+ for thread in threads {
+ thread
+ .update(cx, |thread, cx| {
+ thread.complete_url_elicitation(&elicitation_id, cx);
+ })
+ .ok();
+ }
+ request_elicitations.update(cx, |store, cx| {
+ store.complete_url_elicitation(&elicitation_id, cx);
+ });
+ })
+ .detach();
+}
+
fn handle_write_text_file(
args: acp::WriteTextFileRequest,
responder: Responder<acp::WriteTextFileResponse>,
diff --git a/crates/agent_ui/src/agent_diff.rs b/crates/agent_ui/src/agent_diff.rs
index 8a329bdc7c8..ba731ec3b9e 100644
--- a/crates/agent_ui/src/agent_diff.rs
+++ b/crates/agent_ui/src/agent_diff.rs
@@ -1437,6 +1437,8 @@ impl AgentDiff {
| AcpThreadEvent::EntriesRemoved(_)
| AcpThreadEvent::ToolAuthorizationRequested(_)
| AcpThreadEvent::ToolAuthorizationReceived(_)
+ | AcpThreadEvent::ElicitationRequested(_)
+ | AcpThreadEvent::ElicitationResponded(_)
| AcpThreadEvent::PromptCapabilitiesUpdated
| AcpThreadEvent::AvailableCommandsUpdated(_)
| AcpThreadEvent::Retry(_)
diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs
index 5267e7adfa6..350d9c2f912 100644
--- a/crates/agent_ui/src/conversation_view.rs
+++ b/crates/agent_ui/src/conversation_view.rs
@@ -1,8 +1,9 @@
use acp_thread::{
AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk,
- AuthRequired, ClientUserMessageId, LoadError, MaxOutputTokensError, MentionUri,
- PermissionOptionChoice, PermissionOptions, PermissionPattern, RetryStatus,
- SelectedPermissionOutcome, ThreadStatus, ToolCall, ToolCallContent, ToolCallStatus,
+ AuthRequired, ClientUserMessageId, ElicitationEntryId, ElicitationStatus, ElicitationStore,
+ LoadError, MaxOutputTokensError, MentionUri, PermissionOptionChoice, PermissionOptions,
+ PermissionPattern, RetryStatus, SelectedPermissionOutcome, ThreadStatus, ToolCall,
+ ToolCallContent, ToolCallStatus,
};
use acp_thread::{AgentConnection, Plan};
use action_log::{ActionLog, ActionLogTelemetry, DiffStats};
@@ -22,6 +23,7 @@ use editor::scroll::Autoscroll;
use editor::{
Editor, EditorEvent, EditorMode, MultiBuffer, PathKey, SelectionEffects, SizingBehavior,
};
+use feature_flags::{AcpBetaFeatureFlag, FeatureFlagAppExt as _};
use file_icons::FileIcons;
use fs::Fs;
use futures::FutureExt as _;
@@ -40,6 +42,9 @@ use markdown::{
use parking_lot::{Mutex, RwLock};
use project::{AgentId, AgentServerStore, Project, ProjectEntryId, ProjectPath};
+use crate::conversation_view::elicitation::{
+ ElicitationCard, ElicitationCardHandlers, ElicitationFormState, should_render_elicitation,
+};
use crate::message_editor::SessionCapabilities;
use crate::{AgentThreadSource, DEFAULT_THREAD_TITLE, resolve_agent_image};
use lru::LruCache;
@@ -103,6 +108,7 @@ const TOKEN_THRESHOLD: u64 = 250;
pub(crate) const DRAFT_PROMPT_PERSIST_DEBOUNCE: Duration = Duration::from_millis(250);
+pub(crate) mod elicitation;
mod message_queue;
mod thread_search_bar;
mod thread_view;
@@ -261,6 +267,7 @@ impl ProfileProvider for Entity<agent::Thread> {
pub(crate) struct Conversation {
threads: HashMap<acp::SessionId, Entity<AcpThread>>,
permission_requests: IndexMap<acp::SessionId, Vec<acp::ToolCallId>>,
+ elicitation_requests: IndexMap<acp::SessionId, Vec<ElicitationEntryId>>,
subscriptions: Vec<Subscription>,
updated_at: Option<Instant>,
}
@@ -270,7 +277,7 @@ impl Conversation {
let session_id = thread.read(cx).session_id().clone();
let subscription = cx.subscribe(&thread, {
let session_id = session_id.clone();
- move |this, _thread, event, _cx| {
+ move |this, _thread, event, cx| {
this.updated_at = Some(Instant::now());
match event {
AcpThreadEvent::ToolAuthorizationRequested(id) => {
@@ -287,6 +294,23 @@ impl Conversation {
}
}
}
+ AcpThreadEvent::ElicitationRequested(id)
+ if cx.has_flag::<AcpBetaFeatureFlag>() =>
+ {
+ this.elicitation_requests
+ .entry(session_id.clone())
+ .or_default()
+ .push(id.clone());
+ }
+ AcpThreadEvent::ElicitationRequested(_) => {}
+ AcpThreadEvent::ElicitationResponded(id) => {
+ if let Some(elicitations) = this.elicitation_requests.get_mut(&session_id) {
+ elicitations.retain(|elicitation_id| elicitation_id != id);
+ if elicitations.is_empty() {
+ this.elicitation_requests.shift_remove(&session_id);
+ }
+ }
+ }
AcpThreadEvent::NewEntry
| AcpThreadEvent::StatusChanged
| AcpThreadEvent::TitleUpdated
@@ -391,6 +415,24 @@ impl Conversation {
.unwrap_or(0)
}
+ pub fn respond_to_elicitation(
+ &mut self,
+ session_id: acp::SessionId,
+ elicitation_id: ElicitationEntryId,
+ response: acp::CreateElicitationResponse,
+ cx: &mut Context<Self>,
+ ) -> Option<()> {
+ if !cx.has_flag::<AcpBetaFeatureFlag>() {
+ return None;
+ }
+
+ let thread = self.threads.get(&session_id)?.clone();
+ thread.update(cx, |thread, cx| {
+ thread.respond_to_elicitation(&elicitation_id, response, cx);
+ });
+ Some(())
+ }
+
pub fn authorize_pending_tool_call(
&mut self,
session_id: &acp::SessionId,
@@ -526,6 +568,8 @@ fn affects_thread_metadata(event: &AcpThreadEvent) -> bool {
| AcpThreadEvent::TitleUpdated
| AcpThreadEvent::ToolAuthorizationRequested(_)
| AcpThreadEvent::ToolAuthorizationReceived(_)
+ | AcpThreadEvent::ElicitationRequested(_)
+ | AcpThreadEvent::ElicitationResponded(_)
| AcpThreadEvent::Stopped(_)
| AcpThreadEvent::Error
| AcpThreadEvent::LoadError(_)
@@ -575,6 +619,7 @@ pub struct ConversationView {
/// Cache + worktree snapshot for resolving paths in markdown code spans.
/// Shared with the child [`ThreadView`] when one is constructed.
pub(crate) code_span_resolver: AgentCodeSpanResolver,
+ request_elicitation_form_states: HashMap<ElicitationEntryId, ElicitationFormState>,
_subscriptions: Vec<Subscription>,
}
@@ -686,8 +731,14 @@ impl ConversationView {
}
enum ServerState {
- Loading { _loading: Entity<LoadingView> },
- LoadError { error: LoadError },
+ Loading {
+ _loading: Entity<LoadingView>,
+ connection: Option<Rc<dyn AgentConnection>>,
+ _request_elicitation_subscription: Option<Subscription>,
+ },
+ LoadError {
+ error: LoadError,
+ },
Connected(ConnectedServerState),
}
@@ -700,6 +751,7 @@ pub struct ConnectedServerState {
connection: Rc<dyn AgentConnection>,
conversation: Entity<Conversation>,
_connection_entry_subscription: Subscription,
+ _request_elicitation_subscription: Option<Subscription>,
}
enum AuthState {
@@ -800,6 +852,7 @@ impl ConversationView {
}));
cx.on_release(|this, cx| {
+ this.request_elicitation_form_states.clear();
if let Some(connected) = this.as_connected() {
connected.close_all_sessions(cx).detach();
}
@@ -845,16 +898,29 @@ impl ConversationView {
last_theme_id: Some(cx.theme().id.clone()),
draft_prompt_persist_task: None,
code_span_resolver,
+ request_elicitation_form_states: HashMap::default(),
_subscriptions: subscriptions,
focus_handle: cx.focus_handle(),
}
}
fn set_server_state(&mut self, state: ServerState, cx: &mut Context<Self>) {
+ let previous_request_elicitation_connection = self.request_elicitation_connection();
+ let next_request_elicitation_connection =
+ Self::request_elicitation_connection_for_state(&state);
+
if let Some(connected) = self.as_connected() {
connected.close_all_sessions(cx).detach();
}
+ if let Some(connection) = previous_request_elicitation_connection
+ && !next_request_elicitation_connection
+ .as_ref()
+ .is_some_and(|next_connection| Rc::ptr_eq(&connection, next_connection))
+ {
+ self.request_elicitation_form_states.clear();
+ }
+
self.server_state = state;
cx.emit(StateChange);
cx.emit(AcpServerViewEvent::ActiveThreadChanged);
@@ -864,6 +930,53 @@ impl ConversationView {
cx.notify();
}
+ fn request_elicitation_subscription(
+ connection: &Rc<dyn AgentConnection>,
+ cx: &mut Context<Self>,
+ ) -> Option<Subscription> {
+ let store = connection.request_elicitations()?;
+ Some(cx.observe(&store, |this, _store, cx| {
+ if let Some(active_thread) = this.active_thread().cloned() {
+ active_thread.update(cx, |_thread, cx| cx.notify());
+ }
+ cx.notify();
+ }))
+ }
+
+ fn request_elicitation_connection(&self) -> Option<Rc<dyn AgentConnection>> {
+ Self::request_elicitation_connection_for_state(&self.server_state)
+ }
+
+ fn active_thread_renders_request_elicitations(&self) -> bool {
+ match &self.server_state {
+ ServerState::Connected(connected) => {
+ connected.auth_state.is_ok() && connected.active_view().is_some()
+ }
+ _ => false,
+ }
+ }
+
+ fn request_elicitation_connection_for_state(
+ state: &ServerState,
+ ) -> Option<Rc<dyn AgentConnection>> {
+ match state {
+ ServerState::Loading {
+ connection: Some(connection),
+ ..
+ } => Some(connection.clone()),
+ ServerState::Connected(connected) => Some(connected.connection.clone()),
+ ServerState::Loading {
+ connection: None, ..
+ }
+ | ServerState::LoadError { .. } => None,
+ }
+ }
+
+ fn request_elicitation_store(&self) -> Option<Entity<ElicitationStore>> {
+ self.request_elicitation_connection()?
+ .request_elicitations()
+ }
+
fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let (resume_session_id, work_dirs, title) = self
.root_thread_view()
@@ -889,6 +1002,7 @@ impl ConversationView {
(session_id, work_dirs, title)
});
+ self.clear_resolved_request_elicitations(cx);
self.loading_status = None;
let state = Self::initial_state(
@@ -978,6 +1092,22 @@ impl ConversationView {
}
};
+ this.update_in(cx, |this, _window, cx| {
+ let request_elicitation_subscription =
+ Self::request_elicitation_subscription(&connection, cx);
+ if let ServerState::Loading {
+ connection: loading_connection,
+ _request_elicitation_subscription,
+ ..
+ } = &mut this.server_state
+ {
+ *loading_connection = Some(connection.clone());
+ *_request_elicitation_subscription = request_elicitation_subscription;
+ cx.notify();
+ }
+ })
+ .log_err();
+
telemetry::event!(
"Agent Thread Started",
agent = connection.telemetry_id(),
@@ -1050,6 +1180,7 @@ impl ConversationView {
this.update_in(cx, |this, window, cx| {
match result {
Ok(thread) => {
+ this.clear_resolved_request_elicitations_for_connection(&connection, cx);
let root_session_id = thread.read(cx).session_id().clone();
let conversation = cx.new(|cx| {
@@ -1076,6 +1207,8 @@ impl ConversationView {
}
this.root_session_id = Some(root_session_id.clone());
+ let request_elicitation_subscription =
+ Self::request_elicitation_subscription(&connection, cx);
this.set_server_state(
ServerState::Connected(ConnectedServerState {
connection,
@@ -1084,6 +1217,7 @@ impl ConversationView {
threads: HashMap::from_iter([(root_session_id, current)]),
conversation,
_connection_entry_subscription: connection_entry_subscription,
+ _request_elicitation_subscription: request_elicitation_subscription,
}),
cx,
);
@@ -1106,6 +1240,8 @@ impl ConversationView {
ServerState::Loading {
_loading: loading_view,
+ connection: None,
+ _request_elicitation_subscription: None,
}
}
@@ -1376,6 +1512,8 @@ impl ConversationView {
this.focus_handle.focus(window, cx)
}
} else {
+ let request_elicitation_subscription =
+ Self::request_elicitation_subscription(&connection, cx);
this.set_server_state(
ServerState::Connected(ConnectedServerState {
auth_state,
@@ -1384,6 +1522,7 @@ impl ConversationView {
connection,
conversation: cx.new(|_cx| Conversation::default()),
_connection_entry_subscription: Subscription::new(|| {}),
+ _request_elicitation_subscription: request_elicitation_subscription,
}),
cx,
);
@@ -1521,6 +1660,7 @@ impl ConversationView {
);
});
active.update(cx, |active, cx| {
+ active.sync_elicitation_state_for_entry(index, window, cx);
active.sync_editor_mode_for_empty_state(cx);
active.sync_generating_indicator(cx);
});
@@ -1535,6 +1675,7 @@ impl ConversationView {
});
list_state.remeasure_items(*index..*index + 1);
active.update(cx, |active, cx| {
+ active.sync_elicitation_state_for_entry(*index, window, cx);
active.auto_expand_streaming_thought(cx);
active.sync_generating_indicator(cx);
});
@@ -1558,6 +1699,11 @@ impl ConversationView {
self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
}
AcpThreadEvent::ToolAuthorizationReceived(_) => {}
+ AcpThreadEvent::ElicitationRequested(_) if cx.has_flag::<AcpBetaFeatureFlag>() => {
+ self.notify_with_sound("Waiting for input", IconName::Info, window, cx);
+ }
+ AcpThreadEvent::ElicitationRequested(_) => {}
+ AcpThreadEvent::ElicitationResponded(_) => {}
AcpThreadEvent::Retry(retry) => {
if let Some(active) = self.thread_view(&session_id) {
active.update(cx, |active, _cx| {
@@ -1868,6 +2014,7 @@ impl ConversationView {
this.update_in(cx, |this, window, cx| {
if let Err(err) = result {
+ this.cancel_request_elicitations(cx);
if let Some(ConnectedServerState {
auth_state:
AuthState::Unauthenticated {
@@ -1918,6 +2065,7 @@ impl ConversationView {
this.update_in(cx, |this, window, cx| {
if let Err(err) = result {
+ this.cancel_request_elicitations(cx);
if let Some(ConnectedServerState {
auth_state:
AuthState::Unauthenticated {
@@ -2256,6 +2404,311 @@ impl ConversationView {
.into_any_element()
}
+ fn sync_request_elicitation_states(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if !cx.has_flag::<AcpBetaFeatureFlag>() {
+ self.request_elicitation_form_states.clear();
+ return;
+ }
+
+ let Some(store) = self.request_elicitation_store() else {
+ self.request_elicitation_form_states.clear();
+ return;
+ };
+
+ let elicitations = store
+ .read(cx)
+ .elicitations()
+ .iter()
+ .map(|elicitation| {
+ let is_pending = matches!(elicitation.status, ElicitationStatus::Pending { .. });
+ let schema = match &elicitation.request.mode {
+ acp::ElicitationMode::Form(mode) => Some(mode.requested_schema.clone()),
+ _ => None,
+ };
+ (elicitation.id.clone(), is_pending, schema)
+ })
+ .collect::<Vec<_>>();
+
+ let known_ids = elicitations
+ .iter()
+ .map(|(id, _, _)| id.clone())
+ .collect::<HashSet<_>>();
+ self.request_elicitation_form_states
+ .retain(|id, _| known_ids.contains(id));
+
+ for (id, is_pending, schema) in elicitations {
+ if is_pending
+ && let Some(schema) = schema
+ && !self.request_elicitation_form_states.contains_key(&id)
+ {
+ self.request_elicitation_form_states
+ .insert(id, ElicitationFormState::new(&schema, window, cx));
+ } else if !is_pending {
+ self.request_elicitation_form_states.remove(&id);
+ }
+ }
+ }
+
+ fn render_request_elicitations(
+ &self,
+ connection: &Rc<dyn AgentConnection>,
+ view: WeakEntity<Self>,
+ cx: &App,
+ ) -> Vec<AnyElement> {
+ if !cx.has_flag::<AcpBetaFeatureFlag>() {
+ return Vec::new();
+ }
+
+ let Some(store) = connection.request_elicitations() else {
+ return Vec::new();
+ };
+
+ let handlers = Self::request_elicitation_card_handlers(view);
+
+ store
+ .read(cx)
+ .elicitations()
+ .iter()
+ .enumerate()
+ .filter(|(_, elicitation)| should_render_elicitation(elicitation))
+ .map(|(ix, elicitation)| {
+ ElicitationCard::new(
+ ix,
+ elicitation,
+ self.request_elicitation_form_states.get(&elicitation.id),
+ handlers.clone(),
+ )
+ .render(cx)
+ .into_any_element()
+ })
+ .collect()
+ }
+
+ fn request_elicitation_card_handlers(view: WeakEntity<Self>) -> ElicitationCardHandlers {
+ ElicitationCardHandlers::new(
+ {
+ let view = view.clone();
+ move |elicitation_id, window, cx| {
+ view.update(cx, |this, cx| {
+ this.submit_request_elicitation(elicitation_id, window, cx);
+ })
+ .log_err();
+ }
+ },
+ {
+ let view = view.clone();
+ move |elicitation_id, window, cx| {
+ view.update(cx, |this, cx| {
+ this.decline_request_elicitation(elicitation_id, window, cx);
+ })
+ .log_err();
+ }
+ },
+ {
+ let view = view.clone();
+ move |elicitation_id, window, cx| {
+ view.update(cx, |this, cx| {
+ this.cancel_request_elicitation(elicitation_id, window, cx);
+ })
+ .log_err();
+ }
+ },
+ {
+ let view = view.clone();
+ move |elicitation_id, url, window, cx| {
+ cx.open_url(&url);
+ view.update(cx, |this, cx| {
+ this.submit_request_elicitation(elicitation_id, window, cx);
+ })
+ .log_err();
+ }
+ },
+ {
+ let view = view.clone();
+ move |elicitation_id, field_name, value, cx| {
+ view.update(cx, |this, cx| {
+ this.update_request_elicitation_form_state(
+ &elicitation_id,
+ |form| form.set_boolean(&field_name, value),
+ cx,
+ );
+ })
+ .log_err();
+ }
+ },
+ {
+ let view = view.clone();
+ move |elicitation_id, field_name, value, cx| {
+ view.update(cx, |this, cx| {
+ this.update_request_elicitation_form_state(
+ &elicitation_id,
+ |form| form.set_single_select(&field_name, value),
+ cx,
+ );
+ })
+ .log_err();
+ }
+ },
+ move |elicitation_id, field_name, value, selected, cx| {
+ view.update(cx, |this, cx| {
+ this.update_request_elicitation_form_state(
+ &elicitation_id,
+ |form| form.set_multi_select(&field_name, value, selected),
+ cx,
+ );
+ })
+ .log_err();
+ },
+ )
+ }
+
+ fn update_request_elicitation_form_state(
+ &mut self,
+ elicitation_id: &ElicitationEntryId,
+ update: impl FnOnce(&mut ElicitationFormState),
+ cx: &mut Context<Self>,
+ ) {
+ if let Some(form) = self.request_elicitation_form_states.get_mut(elicitation_id) {
+ update(form);
+ self.notify_request_elicitation_renderers(cx);
+ }
+ }
+
+ fn notify_request_elicitation_renderers(&self, cx: &mut Context<Self>) {
+ if let Some(active_thread) = self.active_thread().cloned() {
+ active_thread.update(cx, |_thread, cx| cx.notify());
+ }
+ cx.notify();
+ }
+
+ fn submit_request_elicitation(
+ &mut self,
+ elicitation_id: ElicitationEntryId,
+ _window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if !cx.has_flag::<AcpBetaFeatureFlag>() {
+ return;
+ }
+
+ let Some(store) = self.request_elicitation_store() else {
+ return;
+ };
+
+ let mode = store
+ .read(cx)
+ .elicitation(&elicitation_id)
+ .map(|(_, elicitation)| elicitation.request.mode.clone());
+ let Some(mode) = mode else {
+ return;
+ };
+
+ let response = match mode {
+ acp::ElicitationMode::Form(mode) => {
+ let Some(state) = self.request_elicitation_form_states.get(&elicitation_id) else {
+ return;
+ };
+ match state.collect(&mode.requested_schema, cx) {
+ Ok(content) => {
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new().content(content),
+ ))
+ }
+ Err(errors) => {
+ self.update_request_elicitation_form_state(
+ &elicitation_id,
+ |state| state.set_errors(errors),
+ cx,
+ );
+ return;
+ }
+ }
+ }
+ acp::ElicitationMode::Url(_) => acp::CreateElicitationResponse::new(
+ acp::ElicitationAction::Accept(acp::ElicitationAcceptAction::new()),
+ ),
+ _ => return,
+ };
+
+ self.respond_to_request_elicitation(elicitation_id, response, cx);
+ }
+
+ fn decline_request_elicitation(
+ &mut self,
+ elicitation_id: ElicitationEntryId,
+ _window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if !cx.has_flag::<AcpBetaFeatureFlag>() {
+ return;
+ }
+
+ self.respond_to_request_elicitation(
+ elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ cx,
+ );
+ }
+
+ fn cancel_request_elicitation(
+ &mut self,
+ elicitation_id: ElicitationEntryId,
+ _window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if !cx.has_flag::<AcpBetaFeatureFlag>() {
+ return;
+ }
+
+ self.respond_to_request_elicitation(
+ elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Cancel),
+ cx,
+ );
+ }
+
+ fn respond_to_request_elicitation(
+ &mut self,
+ elicitation_id: ElicitationEntryId,
+ response: acp::CreateElicitationResponse,
+ cx: &mut Context<Self>,
+ ) {
+ self.request_elicitation_form_states.remove(&elicitation_id);
+ if let Some(store) = self.request_elicitation_store() {
+ store.update(cx, |store, cx| {
+ store.respond_to_elicitation(&elicitation_id, response, cx);
+ });
+ }
+ cx.notify();
+ }
+
+ fn cancel_request_elicitations(&mut self, cx: &mut App) {
+ self.request_elicitation_form_states.clear();
+ if let Some(store) = self.request_elicitation_store() {
+ store.update(cx, |store, cx| store.clear(cx));
+ }
+ }
+
+ fn clear_resolved_request_elicitations(&mut self, cx: &mut App) {
+ if let Some(connection) = self.request_elicitation_connection() {
+ self.clear_resolved_request_elicitations_for_connection(&connection, cx);
+ }
+ }
+
+ fn clear_resolved_request_elicitations_for_connection(
+ &mut self,
+ connection: &Rc<dyn AgentConnection>,
+ cx: &mut App,
+ ) {
+ let Some(store) = connection.request_elicitations() else {
+ return;
+ };
+ let cleared_ids = store.update(cx, |store, cx| store.clear_resolved(cx));
+ for id in cleared_ids {
+ self.request_elicitation_form_states.remove(&id);
+ }
+ }
+
fn emit_load_error_telemetry(&self, error: &LoadError) {
let error_kind = match error {
LoadError::Unsupported { .. } => "unsupported",
@@ -2793,6 +3246,7 @@ impl ConversationView {
pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let agent_id = self.agent.agent_id();
+ self.cancel_request_elicitations(cx);
if let Some(active) = self.root_thread_view() {
active.update(cx, |active, cx| active.clear_thread_error(cx));
}
@@ -2829,24 +3283,27 @@ impl ConversationView {
if let Some(active) = this.root_thread_view() {
active.update(cx, |active, cx| active.handle_thread_error(err, cx));
}
- } else if let Some(connected) = this.as_connected_mut() {
- connected.auth_state = AuthState::Unauthenticated {
- description: None,
- configuration_view: None,
- pending_auth_method: None,
- _subscription: None,
- };
- cx.emit(StateChange);
- if let Some(view) = connected.active_view()
- && view
- .read(cx)
- .message_editor
- .focus_handle(cx)
- .is_focused(window)
- {
- this.focus_handle.focus(window, cx)
+ } else {
+ this.cancel_request_elicitations(cx);
+ if let Some(connected) = this.as_connected_mut() {
+ connected.auth_state = AuthState::Unauthenticated {
+ description: None,
+ configuration_view: None,
+ pending_auth_method: None,
+ _subscription: None,
+ };
+ cx.emit(StateChange);
+ if let Some(view) = connected.active_view()
+ && view
+ .read(cx)
+ .message_editor
+ .focus_handle(cx)
+ .is_focused(window)
+ {
+ this.focus_handle.focus(window, cx)
+ }
+ cx.notify();
}
- cx.notify();
}
drop(this.auth_task.take());
})
@@ -2936,71 +3393,85 @@ impl ConversationView {
impl Render for ConversationView {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
- v_flex()
- .track_focus(&self.focus_handle)
- .size_full()
- .bg(cx.theme().colors().panel_background)
- .child(match &self.server_state {
- ServerState::Loading { .. } => {
- let label_text = self
- .loading_status
- .clone()
- .unwrap_or_else(|| "Loading…".into());
- v_flex()
- .flex_1()
- .size_full()
- .items_center()
- .justify_center()
- .child(
- Label::new(label_text).color(Color::Muted).with_animation(
- "loading-agent-label",
- Animation::new(Duration::from_secs(2))
- .repeat()
- .with_easing(pulsating_between(0.3, 0.7)),
- |label, delta| label.alpha(delta),
- ),
- )
- .into_any()
- }
- ServerState::LoadError { error: e, .. } => v_flex()
+ self.sync_request_elicitation_states(window, cx);
+ let request_elicitation_connection = self.request_elicitation_connection();
+ let active_thread_renders_request_elicitations =
+ self.active_thread_renders_request_elicitations();
+ let content = match &self.server_state {
+ ServerState::Loading { .. } => {
+ let label_text = self
+ .loading_status
+ .clone()
+ .unwrap_or_else(|| "Loading…".into());
+ v_flex()
.flex_1()
.size_full()
.items_center()
- .justify_end()
- .child(self.render_load_error(e, window, cx))
- .into_any(),
- ServerState::Connected(ConnectedServerState {
+ .justify_center()
+ .child(
+ Label::new(label_text).color(Color::Muted).with_animation(
+ "loading-agent-label",
+ Animation::new(Duration::from_secs(2))
+ .repeat()
+ .with_easing(pulsating_between(0.3, 0.7)),
+ |label, delta| label.alpha(delta),
+ ),
+ )
+ .into_any()
+ }
+ ServerState::LoadError { error: e, .. } => v_flex()
+ .flex_1()
+ .size_full()
+ .items_center()
+ .justify_end()
+ .child(self.render_load_error(e, window, cx))
+ .into_any(),
+ ServerState::Connected(ConnectedServerState {
+ connection,
+ auth_state:
+ AuthState::Unauthenticated {
+ description,
+ configuration_view,
+ pending_auth_method,
+ _subscription,
+ },
+ ..
+ }) => v_flex()
+ .flex_1()
+ .size_full()
+ .justify_end()
+ .child(self.render_auth_required_state(
connection,
- auth_state:
- AuthState::Unauthenticated {
- description,
- configuration_view,
- pending_auth_method,
- _subscription,
- },
- ..
- }) => v_flex()
- .flex_1()
- .size_full()
- .justify_end()
- .child(self.render_auth_required_state(
- connection,
- description.as_ref(),
- configuration_view.as_ref(),
- pending_auth_method.as_ref(),
- window,
- cx,
- ))
- .into_any_element(),
- ServerState::Connected(connected) => {
- if let Some(view) = connected.active_view() {
- view.clone().into_any_element()
- } else {
- debug_panic!("This state should never be reached");
- div().into_any_element()
- }
+ description.as_ref(),
+ configuration_view.as_ref(),
+ pending_auth_method.as_ref(),
+ window,
+ cx,
+ ))
+ .into_any_element(),
+ ServerState::Connected(connected) => {
+ if let Some(view) = connected.active_view() {
+ view.clone().into_any_element()
+ } else {
+ debug_panic!("This state should never be reached");
+ div().into_any_element()
}
- })
+ }
+ };
+
+ v_flex()
+ .track_focus(&self.focus_handle)
+ .size_full()
+ .bg(cx.theme().colors().panel_background)
+ .child(v_flex().flex_1().min_h_0().child(content))
+ .when(!active_thread_renders_request_elicitations, |this| {
+ this.children(request_elicitation_connection.as_ref().map_or_else(
+ Vec::new,
+ |connection| {
+ self.render_request_elicitations(connection, cx.entity().downgrade(), cx)
+ },
+ ))
+ })
}
}
@@ -3227,7 +3698,7 @@ pub(crate) mod tests {
use agent_servers::FakeAcpAgentServer;
use editor::MultiBufferOffset;
use editor::actions::Paste;
- use feature_flags::FeatureFlagAppExt as _;
+ use feature_flags::{FeatureFlag as _, FeatureFlagAppExt as _};
use fs::FakeFs;
use gpui::{ClipboardItem, EventEmitter, TestAppContext, VisualTestContext, point, size};
use parking_lot::Mutex;
@@ -3273,6 +3744,192 @@ pub(crate) mod tests {
assert!(!weak_view.is_upgradable());
}
+ #[gpui::test]
+ async fn test_drop_preserves_shared_pending_request_elicitations(cx: &mut TestAppContext) {
+ init_test(cx);
+ cx.update(|cx| {
+ cx.update_flags(true, vec![AcpBetaFeatureFlag::NAME.to_string()]);
+ });
+
+ let response = Arc::new(Mutex::new(None));
+ let server = ReleaseRequestElicitationServer {
+ response: response.clone(),
+ };
+ let (conversation_view, cx) = setup_conversation_view(server, cx).await;
+ let _connection = conversation_view
+ .read_with(cx, |view, _cx| view.request_elicitation_connection())
+ .expect("conversation should have an active connection");
+ let store = _connection
+ .request_elicitations()
+ .expect("connection should expose request elicitations");
+ store.read_with(cx, |store, _cx| {
+ assert_eq!(
+ store.elicitations().len(),
+ 1,
+ "test should start with one pending request elicitation"
+ );
+ });
+
+ assert_eq!(*response.lock(), None);
+ let weak_view = conversation_view.downgrade();
+ drop(conversation_view);
+ cx.update(|_, _| {});
+ cx.run_until_parked();
+
+ assert!(!weak_view.is_upgradable());
+ store.read_with(cx, |store, _cx| {
+ assert_eq!(
+ store.elicitations().len(),
+ 1,
+ "view release should not clear connection-wide request elicitations"
+ );
+ });
+ assert_eq!(*response.lock(), None);
+
+ store.update(cx, |store, cx| store.clear(cx));
+ cx.run_until_parked();
+ assert!(matches!(
+ response.lock().as_ref(),
+ Some(acp::ElicitationAction::Cancel)
+ ));
+ }
+
+ #[gpui::test]
+ async fn test_state_transition_preserves_shared_pending_request_elicitations(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ cx.update(|cx| {
+ cx.update_flags(true, vec![AcpBetaFeatureFlag::NAME.to_string()]);
+ });
+
+ let response = Arc::new(Mutex::new(None));
+ let server = ReleaseRequestElicitationServer {
+ response: response.clone(),
+ };
+ let (conversation_view, cx) = setup_conversation_view(server, cx).await;
+ let connection = conversation_view
+ .read_with(cx, |view, _cx| view.request_elicitation_connection())
+ .expect("conversation should have an active connection");
+ let store = connection
+ .request_elicitations()
+ .expect("connection should expose request elicitations");
+ store.read_with(cx, |store, _cx| {
+ assert_eq!(
+ store.elicitations().len(),
+ 1,
+ "test should start with one pending request elicitation"
+ );
+ });
+
+ conversation_view.update(cx, |view, cx| {
+ view.set_server_state(
+ ServerState::LoadError {
+ error: LoadError::Other("load failed".into()),
+ },
+ cx,
+ );
+ });
+ cx.run_until_parked();
+
+ store.read_with(cx, |store, _cx| {
+ assert_eq!(
+ store.elicitations().len(),
+ 1,
+ "leaving a connection should not clear connection-wide request elicitations"
+ );
+ });
+ assert_eq!(*response.lock(), None);
+
+ store.update(cx, |store, cx| store.clear(cx));
+ cx.run_until_parked();
+ assert!(matches!(
+ response.lock().as_ref(),
+ Some(acp::ElicitationAction::Cancel)
+ ));
+ }
+
+ #[gpui::test]
+ async fn test_successful_session_creation_clears_resolved_request_elicitations(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ cx.update(|cx| {
+ cx.update_flags(true, vec![AcpBetaFeatureFlag::NAME.to_string()]);
+ });
+
+ let store = cx.update(|cx| cx.new(|_| ElicitationStore::default()));
+ let response = Arc::new(Mutex::new(None));
+ let server = SessionCreationRequestElicitationServer {
+ store: store.clone(),
+ response: response.clone(),
+ };
+ let (conversation_view, cx) = setup_conversation_view(server, cx).await;
+ let first_request_id = acp::RequestId::Number(1);
+ let second_request_id = acp::RequestId::Number(2);
+ let first_elicitation_id = store.read_with(cx, |store, _cx| {
+ assert_eq!(
+ store.elicitations().len(),
+ 2,
+ "session creation should be waiting on one prompt with another prompt still pending"
+ );
+ store
+ .elicitations()
+ .iter()
+ .find_map(|elicitation| {
+ let acp::ElicitationScope::Request(scope) = elicitation.request.scope() else {
+ return None;
+ };
+ (&scope.request_id == &first_request_id).then(|| elicitation.id.clone())
+ })
+ .expect("first request-scoped elicitation should exist")
+ });
+
+ store.update(cx, |store, cx| {
+ store.respond_to_elicitation(
+ &first_elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new(),
+ )),
+ cx,
+ );
+ });
+ cx.run_until_parked();
+
+ assert!(matches!(
+ response.lock().as_ref(),
+ Some(acp::ElicitationAction::Accept(_))
+ ));
+ conversation_view.read_with(cx, |view, _cx| {
+ let connected = view
+ .as_connected()
+ .expect("session creation should complete successfully");
+ assert!(
+ connected.active_id.is_some(),
+ "successful session creation should install an active thread"
+ );
+ });
+ store.read_with(cx, |store, _cx| {
+ let [remaining] = store.elicitations() else {
+ panic!(
+ "expected only the pending request elicitation to remain, got {:?}",
+ store.elicitations()
+ );
+ };
+ let acp::ElicitationScope::Request(scope) = remaining.request.scope() else {
+ panic!("expected request-scoped elicitation");
+ };
+ assert_eq!(scope.request_id, second_request_id);
+ assert!(matches!(
+ remaining.status,
+ ElicitationStatus::Pending { .. }
+ ));
+ });
+
+ store.update(cx, |store, cx| store.clear(cx));
+ cx.run_until_parked();
+ }
+
#[gpui::test]
async fn test_external_source_prompt_requires_manual_send(cx: &mut TestAppContext) {
init_test(cx);
@@ -3656,6 +4313,31 @@ pub(crate) mod tests {
);
}
+ #[gpui::test]
+ async fn test_thread_view_seeds_existing_elicitation_form_state(cx: &mut TestAppContext) {
+ init_test(cx);
+ cx.update(|cx| {
+ cx.update_flags(true, vec![AcpBetaFeatureFlag::NAME.to_string()]);
+ });
+
+ let connection = PreloadedElicitationConnection::default();
+ let elicitation_id = connection.elicitation_id.clone();
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::new(connection), cx).await;
+
+ let elicitation_id = elicitation_id
+ .lock()
+ .clone()
+ .expect("connection should preload an elicitation");
+ let active_thread = active_thread(&conversation_view, cx);
+ active_thread.read_with(cx, |thread, _cx| {
+ assert!(
+ thread.has_elicitation_form_state(&elicitation_id),
+ "pending form elicitations that predate ThreadView construction should be usable"
+ );
+ });
+ }
+
#[gpui::test]
async fn test_resume_without_history_adds_notice(cx: &mut TestAppContext) {
init_test(cx);
@@ -4120,6 +4802,10 @@ pub(crate) mod tests {
connected.active_id.is_none(),
"There should be no active thread since no session was created"
);
+ assert!(
+ !view.active_thread_renders_request_elicitations(),
+ "request elicitations should render outside ThreadView when no thread exists"
+ );
assert!(
connected.threads.is_empty(),
"There should be no threads since no session was created"
@@ -4159,6 +4845,10 @@ pub(crate) mod tests {
connected.active_id.is_some(),
"There should be an active thread after successful auth"
);
+ assert!(
+ view.active_thread_renders_request_elicitations(),
+ "request elicitations should render inside ThreadView while authenticated"
+ );
assert_eq!(
connected.threads.len(),
1,
@@ -4189,6 +4879,14 @@ pub(crate) mod tests {
!view.supports_logout(),
"Logout should be hidden after logout"
);
+ assert!(
+ view.active_thread().is_some(),
+ "The existing thread should still exist after logout"
+ );
+ assert!(
+ !view.active_thread_renders_request_elicitations(),
+ "Unauthenticated auth UI should render request elicitations outside ThreadView"
+ );
});
}
@@ -5225,6 +5923,330 @@ pub(crate) mod tests {
})
}
+ #[derive(Clone, Default)]
+ struct PreloadedElicitationConnection {
+ elicitation_id: Arc<Mutex<Option<ElicitationEntryId>>>,
+ }
+
+ impl AgentConnection for PreloadedElicitationConnection {
+ fn agent_id(&self) -> AgentId {
+ AgentId::new("preloaded-elicitation")
+ }
+
+ fn telemetry_id(&self) -> SharedString {
+ "preloaded-elicitation".into()
+ }
+
+ fn new_session(
+ self: Rc<Self>,
+ project: Entity<Project>,
+ _work_dirs: PathList,
+ cx: &mut App,
+ ) -> Task<gpui::Result<Entity<AcpThread>>> {
+ let session_id = acp::SessionId::new("new-session");
+ let thread = build_test_thread(
+ self.clone(),
+ project,
+ "PreloadedElicitationConnection",
+ session_id.clone(),
+ cx,
+ );
+ thread.update(cx, |thread, cx| {
+ thread
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationSessionScope::new(session_id),
+ acp::ElicitationSchema::new().string("name", true),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ .expect("preloaded elicitation should be accepted")
+ .detach();
+ });
+ let elicitation_id = thread.read_with(cx, |thread, _cx| {
+ thread.entries().iter().find_map(|entry| {
+ if let AgentThreadEntry::Elicitation(elicitation_id) = entry {
+ Some(elicitation_id.clone())
+ } else {
+ None
+ }
+ })
+ });
+ *self.elicitation_id.lock() = elicitation_id;
+ Task::ready(Ok(thread))
+ }
+
+ fn auth_methods(&self) -> &[acp::AuthMethod] {
+ &[]
+ }
+
+ fn authenticate(
+ &self,
+ _method_id: acp::AuthMethodId,
+ _cx: &mut App,
+ ) -> Task<gpui::Result<()>> {
+ Task::ready(Ok(()))
+ }
+
+ fn prompt(
+ &self,
+ _params: acp::PromptRequest,
+ _cx: &mut App,
+ ) -> Task<gpui::Result<acp::PromptResponse>> {
+ Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ }
+
+ fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
+
+ fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
+ self
+ }
+ }
+
+ struct SessionCreationRequestElicitationServer {
+ store: Entity<ElicitationStore>,
+ response: Arc<Mutex<Option<acp::ElicitationAction>>>,
+ }
+
+ impl AgentServer for SessionCreationRequestElicitationServer {
+ fn logo(&self) -> ui::IconName {
+ ui::IconName::ZedAgent
+ }
+
+ fn agent_id(&self) -> AgentId {
+ "SessionCreationRequestElicitation".into()
+ }
+
+ fn connect(
+ &self,
+ _delegate: AgentServerDelegate,
+ _project: Entity<Project>,
+ _cx: &mut App,
+ ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
+ let connection = SessionCreationRequestElicitationConnection {
+ store: self.store.clone(),
+ response: self.response.clone(),
+ };
+ Task::ready(Ok(Rc::new(connection)))
+ }
+
+ fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
+ self
+ }
+ }
+
+ struct SessionCreationRequestElicitationConnection {
+ store: Entity<ElicitationStore>,
+ response: Arc<Mutex<Option<acp::ElicitationAction>>>,
+ }
+
+ impl AgentConnection for SessionCreationRequestElicitationConnection {
+ fn agent_id(&self) -> AgentId {
+ AgentId::new("session-creation-request-elicitation")
+ }
+
+ fn telemetry_id(&self) -> SharedString {
+ "session-creation-request-elicitation".into()
+ }
+
+ fn new_session(
+ self: Rc<Self>,
+ project: Entity<Project>,
+ _work_dirs: PathList,
+ cx: &mut App,
+ ) -> Task<gpui::Result<Entity<AcpThread>>> {
+ let thread = build_test_thread(
+ self.clone(),
+ project,
+ "SessionCreationRequestElicitationConnection",
+ acp::SessionId::new("session-creation-request-elicitation-session"),
+ cx,
+ );
+ let first_response_task = self.store.update(cx, |store, cx| {
+ store
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
+ acp::ElicitationSchema::new().string("name", true),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ .expect("first request-scoped elicitation should be accepted")
+ });
+ self.store
+ .update(cx, |store, cx| {
+ store
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationRequestScope::new(acp::RequestId::Number(2)),
+ acp::ElicitationSchema::new().string("account", true),
+ ),
+ "Provide an account",
+ ),
+ cx,
+ )
+ .expect("second request-scoped elicitation should be accepted")
+ })
+ .detach();
+
+ let response = self.response.clone();
+ cx.spawn(async move |_cx| {
+ let elicitation_response = first_response_task.await;
+ *response.lock() = Some(elicitation_response.action);
+ Ok(thread)
+ })
+ }
+
+ fn request_elicitations(&self) -> Option<Entity<ElicitationStore>> {
+ Some(self.store.clone())
+ }
+
+ fn auth_methods(&self) -> &[acp::AuthMethod] {
+ &[]
+ }
+
+ fn authenticate(
+ &self,
+ _method_id: acp::AuthMethodId,
+ _cx: &mut App,
+ ) -> Task<gpui::Result<()>> {
+ Task::ready(Ok(()))
+ }
+
+ fn prompt(
+ &self,
+ _params: acp::PromptRequest,
+ _cx: &mut App,
+ ) -> Task<gpui::Result<acp::PromptResponse>> {
+ Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ }
+
+ fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
+
+ fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
+ self
+ }
+ }
+
+ struct ReleaseRequestElicitationServer {
+ response: Arc<Mutex<Option<acp::ElicitationAction>>>,
+ }
+
+ impl AgentServer for ReleaseRequestElicitationServer {
+ fn logo(&self) -> ui::IconName {
+ ui::IconName::ZedAgent
+ }
+
+ fn agent_id(&self) -> AgentId {
+ "ReleaseRequestElicitation".into()
+ }
+
+ fn connect(
+ &self,
+ _delegate: AgentServerDelegate,
+ _project: Entity<Project>,
+ cx: &mut App,
+ ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
+ let connection = ReleaseRequestElicitationConnection {
+ store: cx.new(|_| ElicitationStore::default()),
+ response: self.response.clone(),
+ };
+ Task::ready(Ok(Rc::new(connection)))
+ }
+
+ fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
+ self
+ }
+ }
+
+ struct ReleaseRequestElicitationConnection {
+ store: Entity<ElicitationStore>,
+ response: Arc<Mutex<Option<acp::ElicitationAction>>>,
+ }
+
+ impl AgentConnection for ReleaseRequestElicitationConnection {
+ fn agent_id(&self) -> AgentId {
+ AgentId::new("release-request-elicitation")
+ }
+
+ fn telemetry_id(&self) -> SharedString {
+ "release-request-elicitation".into()
+ }
+
+ fn new_session(
+ self: Rc<Self>,
+ project: Entity<Project>,
+ _work_dirs: PathList,
+ cx: &mut App,
+ ) -> Task<gpui::Result<Entity<AcpThread>>> {
+ let thread = build_test_thread(
+ self.clone(),
+ project,
+ "ReleaseRequestElicitationConnection",
+ acp::SessionId::new("release-request-elicitation-session"),
+ cx,
+ );
+ let response_task = self.store.update(cx, |store, cx| {
+ store
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
+ acp::ElicitationSchema::new().string("name", true),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ .expect("request-scoped elicitation should be accepted")
+ });
+ let response = self.response.clone();
+ cx.spawn(async move |_cx| {
+ let elicitation_response = response_task.await;
+ *response.lock() = Some(elicitation_response.action);
+ })
+ .detach();
+ Task::ready(Ok(thread))
+ }
+
+ fn request_elicitations(&self) -> Option<Entity<ElicitationStore>> {
+ Some(self.store.clone())
+ }
+
+ fn auth_methods(&self) -> &[acp::AuthMethod] {
+ &[]
+ }
+
+ fn authenticate(
+ &self,
+ _method_id: acp::AuthMethodId,
+ _cx: &mut App,
+ ) -> Task<gpui::Result<()>> {
+ Task::ready(Ok(()))
+ }
+
+ fn prompt(
+ &self,
+ _params: acp::PromptRequest,
+ _cx: &mut App,
+ ) -> Task<gpui::Result<acp::PromptResponse>> {
+ Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ }
+
+ fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
+
+ fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
+ self
+ }
+ }
+
#[derive(Clone)]
struct ResumeOnlyAgentConnection;
diff --git a/crates/agent_ui/src/conversation_view/elicitation.rs b/crates/agent_ui/src/conversation_view/elicitation.rs
new file mode 100644
index 00000000000..ae3f3a81b85
--- /dev/null
+++ b/crates/agent_ui/src/conversation_view/elicitation.rs
@@ -0,0 +1,1642 @@
+use acp_thread::{Elicitation, ElicitationEntryId, ElicitationStatus};
+use agent_client_protocol::schema::v1 as acp;
+use collections::{HashMap, HashSet};
+use component::{Component, ComponentScope, example_group_with_title, single_example};
+use editor::Editor;
+use futures::channel::oneshot;
+use gpui::{AnyElement, App, Div, Empty, Entity, Hsla, SharedString, Window, div};
+use std::collections::BTreeMap;
+use std::rc::Rc;
+use ui::{
+ Button, Checkbox, Color, Icon, IconName, IconSize, Indicator, Label, LabelSize, ToggleState,
+ prelude::*,
+};
+
+#[derive(Clone)]
+struct ElicitationOption {
+ value: String,
+ label: SharedString,
+}
+
+enum ElicitationFieldState {
+ Text(Entity<Editor>),
+ Boolean(bool),
+ SingleSelect { value: Option<String> },
+ MultiSelect(HashSet<String>),
+}
+
+pub(crate) struct ElicitationFormState {
+ fields: HashMap<String, ElicitationFieldState>,
+ field_errors: HashMap<String, SharedString>,
+}
+
+impl ElicitationFormState {
+ pub(crate) fn new(schema: &acp::ElicitationSchema, window: &mut Window, cx: &mut App) -> Self {
+ let required = schema.required.as_deref().unwrap_or_default();
+ let mut fields = HashMap::default();
+
+ for (name, property) in &schema.properties {
+ let is_required = required.iter().any(|required| required == name);
+ let field = match property {
+ acp::ElicitationPropertySchema::String(schema) => {
+ let options = single_select_options(schema);
+ if options.is_empty() {
+ let editor = cx.new(|cx| {
+ let mut editor = Editor::single_line(window, cx);
+ if let Some(default) = &schema.default {
+ editor.set_text(default.clone(), window, cx);
+ }
+ editor
+ });
+ ElicitationFieldState::Text(editor)
+ } else {
+ let value = single_select_default_value(schema, &options).or_else(|| {
+ is_required
+ .then(|| options.first().map(|option| option.value.clone()))
+ .flatten()
+ });
+ ElicitationFieldState::SingleSelect { value }
+ }
+ }
+ acp::ElicitationPropertySchema::Number(schema) => {
+ let editor = cx.new(|cx| {
+ let mut editor = Editor::single_line(window, cx);
+ if let Some(default) = schema.default {
+ editor.set_text(default.to_string(), window, cx);
+ }
+ editor
+ });
+ ElicitationFieldState::Text(editor)
+ }
+ acp::ElicitationPropertySchema::Integer(schema) => {
+ let editor = cx.new(|cx| {
+ let mut editor = Editor::single_line(window, cx);
+ if let Some(default) = schema.default {
+ editor.set_text(default.to_string(), window, cx);
+ }
+ editor
+ });
+ ElicitationFieldState::Text(editor)
+ }
+ acp::ElicitationPropertySchema::Boolean(schema) => {
+ ElicitationFieldState::Boolean(schema.default.unwrap_or(false))
+ }
+ acp::ElicitationPropertySchema::Array(schema) => {
+ ElicitationFieldState::MultiSelect(
+ schema
+ .default
+ .clone()
+ .unwrap_or_default()
+ .into_iter()
+ .collect(),
+ )
+ }
+ _ => continue,
+ };
+ fields.insert(name.clone(), field);
+ }
+
+ Self {
+ fields,
+ field_errors: HashMap::default(),
+ }
+ }
+
+ pub(crate) fn collect(
+ &self,
+ schema: &acp::ElicitationSchema,
+ cx: &App,
+ ) -> Result<BTreeMap<String, acp::ElicitationContentValue>, HashMap<String, SharedString>> {
+ let required = schema.required.as_deref().unwrap_or_default();
+ let mut content = BTreeMap::new();
+ let mut errors = HashMap::default();
+
+ for (name, property) in &schema.properties {
+ let is_required = required.iter().any(|required| required == name);
+ let Some(field) = self.fields.get(name) else {
+ continue;
+ };
+
+ let field_content = match (property, field) {
+ (
+ acp::ElicitationPropertySchema::String(schema),
+ ElicitationFieldState::Text(editor),
+ ) => {
+ let value = editor.read(cx).text(cx).to_string();
+ if value.is_empty() {
+ if is_required {
+ Err(format!("{} is required", property_title(name, property)).into())
+ } else {
+ Ok(None)
+ }
+ } else {
+ validate_string_value(property_title(name, property), schema, &value)
+ .map(|()| Some(value.into()))
+ }
+ }
+ (
+ acp::ElicitationPropertySchema::String(schema),
+ ElicitationFieldState::SingleSelect { value },
+ ) => {
+ if let Some(value) = value {
+ validate_single_select_value(property_title(name, property), schema, value)
+ .and_then(|()| {
+ validate_string_value(property_title(name, property), schema, value)
+ })
+ .map(|()| Some(value.clone().into()))
+ } else if is_required {
+ Err(format!("{} is required", property_title(name, property)).into())
+ } else {
+ Ok(None)
+ }
+ }
+ (
+ acp::ElicitationPropertySchema::Number(schema),
+ ElicitationFieldState::Text(editor),
+ ) => {
+ let value = editor.read(cx).text(cx).trim().to_string();
+ if value.is_empty() {
+ if is_required {
+ Err(format!("{} is required", property_title(name, property)).into())
+ } else {
+ Ok(None)
+ }
+ } else {
+ validate_number_value(property_title(name, property), schema, &value)
+ .map(|parsed| Some(parsed.into()))
+ }
+ }
+ (
+ acp::ElicitationPropertySchema::Integer(schema),
+ ElicitationFieldState::Text(editor),
+ ) => {
+ let value = editor.read(cx).text(cx).trim().to_string();
+ if value.is_empty() {
+ if is_required {
+ Err(format!("{} is required", property_title(name, property)).into())
+ } else {
+ Ok(None)
+ }
+ } else {
+ validate_integer_value(property_title(name, property), schema, &value)
+ .map(|parsed| Some(parsed.into()))
+ }
+ }
+ (
+ acp::ElicitationPropertySchema::Boolean(schema),
+ ElicitationFieldState::Boolean(value),
+ ) => {
+ if is_required || *value || schema.default.is_some() {
+ Ok(Some((*value).into()))
+ } else {
+ Ok(None)
+ }
+ }
+ (
+ acp::ElicitationPropertySchema::Array(schema),
+ ElicitationFieldState::MultiSelect(selected),
+ ) => {
+ let mut values = multi_select_options(schema)
+ .into_iter()
+ .filter_map(|option| {
+ selected.contains(&option.value).then_some(option.value)
+ })
+ .collect::<Vec<_>>();
+ values.sort();
+ if values.is_empty() && !is_required {
+ Ok(None)
+ } else if schema
+ .min_items
+ .is_some_and(|min_items| values.len() < min_items as usize)
+ {
+ Err(
+ format!("{} needs more selections", property_title(name, property))
+ .into(),
+ )
+ } else if schema
+ .max_items
+ .is_some_and(|max_items| values.len() > max_items as usize)
+ {
+ Err(
+ format!("{} has too many selections", property_title(name, property))
+ .into(),
+ )
+ } else {
+ Ok(Some(values.into()))
+ }
+ }
+ _ => Ok(None),
+ };
+
+ match field_content {
+ Ok(Some(value)) => {
+ content.insert(name.clone(), value);
+ }
+ Ok(None) => {}
+ Err(error) => {
+ errors.insert(name.clone(), error);
+ }
+ }
+ }
+
+ if errors.is_empty() {
+ Ok(content)
+ } else {
+ Err(errors)
+ }
+ }
+
+ pub(crate) fn set_errors(&mut self, errors: HashMap<String, SharedString>) {
+ self.field_errors = errors;
+ }
+
+ pub(crate) fn set_field_error(
+ &mut self,
+ field_name: impl Into<String>,
+ error: impl Into<SharedString>,
+ ) {
+ self.field_errors.insert(field_name.into(), error.into());
+ }
+
+ pub(crate) fn set_boolean(&mut self, field_name: &str, value: bool) {
+ if let Some(ElicitationFieldState::Boolean(field)) = self.fields.get_mut(field_name) {
+ *field = value;
+ self.field_errors.remove(field_name);
+ }
+ }
+
+ pub(crate) fn set_single_select(&mut self, field_name: &str, value: String) {
+ if let Some(ElicitationFieldState::SingleSelect { value: selected }) =
+ self.fields.get_mut(field_name)
+ {
+ *selected = Some(value);
+ self.field_errors.remove(field_name);
+ }
+ }
+
+ pub(crate) fn set_multi_select(&mut self, field_name: &str, value: String, selected: bool) {
+ if let Some(ElicitationFieldState::MultiSelect(values)) = self.fields.get_mut(field_name) {
+ if selected {
+ values.insert(value);
+ } else {
+ values.remove(&value);
+ }
+ self.field_errors.remove(field_name);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use gpui::TestAppContext;
+
+ #[test]
+ fn string_validation_rejects_email_format_mismatch() {
+ let schema = acp::StringPropertySchema::email();
+
+ validate_string_value("Email".into(), &schema, "[email protected]")
+ .expect("valid email should be accepted");
+ assert_eq!(
+ validate_string_value("Email".into(), &schema, "not-an-email")
+ .expect_err("invalid email should be rejected")
+ .to_string(),
+ "Email must be an email address"
+ );
+ }
+
+ #[test]
+ fn string_validation_rejects_pattern_mismatch() {
+ let schema = acp::StringPropertySchema::new().pattern("^prod-[0-9]+$");
+
+ validate_string_value("Environment".into(), &schema, "prod-42")
+ .expect("matching pattern should be accepted");
+ assert_eq!(
+ validate_string_value("Environment".into(), &schema, "dev-42")
+ .expect_err("pattern mismatch should be rejected")
+ .to_string(),
+ "Environment does not match the requested pattern"
+ );
+ }
+
+ #[test]
+ fn number_validation_rejects_non_finite_values() {
+ let schema = acp::NumberPropertySchema::new();
+
+ assert_eq!(
+ validate_number_value("Amount".into(), &schema, "42.5")
+ .expect("finite number should be accepted"),
+ 42.5
+ );
+
+ for value in ["NaN", "inf", "-inf", "1e309"] {
+ assert_eq!(
+ validate_number_value("Amount".into(), &schema, value)
+ .expect_err("non-finite number should be rejected")
+ .to_string(),
+ "Amount must be a finite number"
+ );
+ }
+ }
+
+ #[test]
+ fn should_render_pending_and_accepted_url_elicitations() {
+ let pending = Elicitation {
+ id: ElicitationEntryId("pending".into()),
+ request: acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ preview_request_scope(0),
+ acp::ElicitationSchema::new(),
+ ),
+ "Review this request.",
+ ),
+ status: pending_status(),
+ };
+ assert!(should_render_elicitation(&pending));
+
+ let accepted_url = Elicitation {
+ id: ElicitationEntryId("accepted-url".into()),
+ request: acp::CreateElicitationRequest::new(
+ acp::ElicitationUrlMode::new(
+ preview_request_scope(1),
+ acp::ElicitationId::new("accepted-url"),
+ "https://auth.example.com/device",
+ ),
+ "Authorize Zed in your browser.",
+ ),
+ status: ElicitationStatus::Accepted,
+ };
+ assert!(should_render_elicitation(&accepted_url));
+
+ let accepted_form = Elicitation {
+ id: ElicitationEntryId("accepted-form".into()),
+ request: acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ preview_request_scope(2),
+ acp::ElicitationSchema::new(),
+ ),
+ "Review this request.",
+ ),
+ status: ElicitationStatus::Accepted,
+ };
+ assert!(!should_render_elicitation(&accepted_form));
+ }
+
+ #[test]
+ fn display_url_segments_never_elide_url_characters() {
+ let url = format!(
+ "https://auth.example.com/oauth/authorize?state={}",
+ "a".repeat(MAX_URL_DISPLAY_SEGMENT_CHARS * 2)
+ );
+
+ let display_url_segments = display_url_segments(&url)
+ .into_iter()
+ .map(|segment| segment.to_string())
+ .collect::<Vec<_>>();
+ assert!(display_url_segments.len() > 1);
+ assert!(
+ !display_url_segments
+ .iter()
+ .any(|segment| segment.contains('…'))
+ );
+ assert!(
+ display_url_segments
+ .iter()
+ .all(|segment| segment.chars().count() <= MAX_URL_DISPLAY_SEGMENT_CHARS)
+ );
+ assert_eq!(display_url_segments.concat(), url);
+ }
+
+ #[test]
+ fn display_url_segments_use_larger_url_boundaries() {
+ let url = "https://auth.example.com/oauth/authorize?client_id=zed-desktop&scope=repository";
+
+ let display_url_segments = display_url_segments(url)
+ .into_iter()
+ .map(|segment| segment.to_string())
+ .collect::<Vec<_>>();
+ assert_eq!(display_url_segments.concat(), url);
+ assert_eq!(display_url_segments[0], "https://auth.example.com/");
+ assert!(
+ display_url_segments
+ .iter()
+ .any(|segment| segment.ends_with('?'))
+ );
+ assert!(
+ display_url_segments
+ .iter()
+ .any(|segment| segment.ends_with('&'))
+ );
+ }
+
+ #[gpui::test]
+ fn form_state_preserves_string_whitespace(cx: &mut TestAppContext) {
+ crate::conversation_view::tests::init_test(cx);
+
+ cx.add_window(|window, cx| {
+ let schema = acp::ElicitationSchema::new().property(
+ "token",
+ acp::StringPropertySchema::new()
+ .title("Token")
+ .default_value(" secret "),
+ true,
+ );
+ let form_state = ElicitationFormState::new(&schema, window, cx);
+ let content = form_state
+ .collect(&schema, cx)
+ .expect("string with whitespace should be submitted");
+
+ assert_eq!(
+ content.get("token"),
+ Some(&acp::ElicitationContentValue::String(
+ " secret ".to_string()
+ ))
+ );
+
+ Editor::single_line(window, cx)
+ });
+ }
+
+ #[gpui::test]
+ fn form_state_discards_invalid_optional_single_select_default(cx: &mut TestAppContext) {
+ crate::conversation_view::tests::init_test(cx);
+
+ cx.add_window(|window, cx| {
+ let schema = acp::ElicitationSchema::new().property(
+ "environment",
+ acp::StringPropertySchema::new()
+ .title("Environment")
+ .enum_values(vec!["production".to_string(), "staging".to_string()])
+ .default_value("development"),
+ false,
+ );
+ let form_state = ElicitationFormState::new(&schema, window, cx);
+ let content = form_state
+ .collect(&schema, cx)
+ .expect("invalid optional default should be ignored");
+
+ assert_eq!(content.get("environment"), None);
+
+ Editor::single_line(window, cx)
+ });
+ }
+
+ #[gpui::test]
+ fn form_state_replaces_invalid_required_single_select_default(cx: &mut TestAppContext) {
+ crate::conversation_view::tests::init_test(cx);
+
+ cx.add_window(|window, cx| {
+ let schema = acp::ElicitationSchema::new().property(
+ "environment",
+ acp::StringPropertySchema::new()
+ .title("Environment")
+ .enum_values(vec!["production".to_string(), "staging".to_string()])
+ .default_value("development"),
+ true,
+ );
+ let form_state = ElicitationFormState::new(&schema, window, cx);
+ let content = form_state
+ .collect(&schema, cx)
+ .expect("required select should use the first valid choice");
+
+ assert_eq!(
+ content.get("environment"),
+ Some(&acp::ElicitationContentValue::String(
+ "production".to_string()
+ ))
+ );
+
+ Editor::single_line(window, cx)
+ });
+ }
+
+ #[gpui::test]
+ fn form_state_rejects_invalid_single_select_value(cx: &mut TestAppContext) {
+ crate::conversation_view::tests::init_test(cx);
+
+ cx.add_window(|window, cx| {
+ let schema = acp::ElicitationSchema::new().property(
+ "environment",
+ acp::StringPropertySchema::new()
+ .title("Environment")
+ .enum_values(vec!["production".to_string(), "staging".to_string()]),
+ false,
+ );
+ let mut form_state = ElicitationFormState::new(&schema, window, cx);
+ form_state.set_single_select("environment", "development".to_string());
+
+ let errors = form_state
+ .collect(&schema, cx)
+ .expect_err("invalid selected value should be rejected");
+ assert_eq!(
+ errors
+ .get("environment")
+ .expect("environment should have an error")
+ .to_string(),
+ "Environment must be one of the provided options"
+ );
+
+ Editor::single_line(window, cx)
+ });
+ }
+
+ #[gpui::test]
+ fn form_state_reports_all_validation_errors(cx: &mut TestAppContext) {
+ crate::conversation_view::tests::init_test(cx);
+
+ cx.add_window(|window, cx| {
+ let schema = acp::ElicitationSchema::new()
+ .string("account", true)
+ .property(
+ "age",
+ acp::IntegerPropertySchema::new().title("Age").minimum(18),
+ true,
+ )
+ .property(
+ "environment",
+ acp::StringPropertySchema::new()
+ .title("Environment")
+ .enum_values(vec!["production".to_string(), "staging".to_string()]),
+ false,
+ );
+ let mut form_state = ElicitationFormState::new(&schema, window, cx);
+ if let Some(ElicitationFieldState::Text(editor)) = form_state.fields.get("age") {
+ editor.update(cx, |editor, cx| editor.set_text("abc", window, cx));
+ }
+ form_state.set_single_select("environment", "development".to_string());
+
+ let errors = form_state
+ .collect(&schema, cx)
+ .expect_err("all invalid fields should be reported");
+ assert_eq!(
+ errors
+ .get("account")
+ .expect("account should have an error")
+ .to_string(),
+ "account is required"
+ );
+ assert_eq!(
+ errors
+ .get("age")
+ .expect("age should have an error")
+ .to_string(),
+ "Age must be an integer"
+ );
+ assert_eq!(
+ errors
+ .get("environment")
+ .expect("environment should have an error")
+ .to_string(),
+ "Environment must be one of the provided options"
+ );
+
+ Editor::single_line(window, cx)
+ });
+ }
+}
+
+#[derive(RegisterComponent)]
+pub struct ElicitationCardPreview;
+
+impl Component for ElicitationCardPreview {
+ fn scope() -> ComponentScope {
+ ComponentScope::Agent
+ }
+
+ fn description() -> &'static str {
+ "ACP elicitation request cards as rendered in the agent panel."
+ }
+
+ fn preview(window: &mut Window, cx: &mut App) -> AnyElement {
+ v_flex()
+ .gap_6()
+ .children([
+ example_group_with_title(
+ "Form Requests",
+ vec![
+ single_example(
+ "Pending Form",
+ render_form_preview(0, pending_status(), &[], window, cx),
+ )
+ .width(px(640.)),
+ single_example(
+ "Validation Errors",
+ render_form_preview(
+ 1,
+ pending_status(),
+ &[
+ ("account_name", "Account name is required"),
+ ("environment", "Choose an environment"),
+ ("scopes", "Choose at least one access scope"),
+ ],
+ window,
+ cx,
+ ),
+ )
+ .width(px(640.)),
+ ],
+ )
+ .vertical()
+ .into_any_element(),
+ example_group_with_title(
+ "URL Requests",
+ vec![
+ single_example(
+ "URL Consent",
+ render_url_preview(3, pending_status(), window, cx),
+ )
+ .width(px(640.)),
+ ],
+ )
+ .vertical()
+ .into_any_element(),
+ example_group_with_title(
+ "Terminal States",
+ vec![
+ single_example(
+ "Declined",
+ render_form_preview(6, ElicitationStatus::Declined, &[], window, cx),
+ )
+ .width(px(640.)),
+ single_example(
+ "Canceled",
+ render_form_preview(7, ElicitationStatus::Canceled, &[], window, cx),
+ )
+ .width(px(640.)),
+ ],
+ )
+ .vertical()
+ .into_any_element(),
+ ])
+ .into_any_element()
+ }
+}
+
+fn render_form_preview(
+ entry_ix: usize,
+ status: ElicitationStatus,
+ field_errors: &[(&'static str, &'static str)],
+ window: &mut Window,
+ cx: &mut App,
+) -> AnyElement {
+ let request = acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(preview_request_scope(entry_ix), preview_form_schema()),
+ "Choose how Zed should connect to this account.",
+ );
+ let mut form_state = matches!(status, ElicitationStatus::Pending { .. }).then(|| {
+ let acp::ElicitationMode::Form(mode) = &request.mode else {
+ unreachable!();
+ };
+ ElicitationFormState::new(&mode.requested_schema, window, cx)
+ });
+ if let Some(form_state) = &mut form_state {
+ for (field_name, error) in field_errors {
+ form_state.set_field_error(*field_name, *error);
+ }
+ }
+
+ render_preview_card(entry_ix, request, status, form_state.as_ref(), cx)
+}
+
+fn preview_url() -> &'static str {
+ "https://auth.example.com/oauth/authorize?client_id=zed-desktop&redirect_uri=zed%3A%2F%2Fagent%2Facp%2Fcallback&scope=profile%20repository%20terminal&state=9b8b0a873a1e4b57b7f9f7b6d2d3d0f4"
+}
+
+fn render_url_preview(
+ entry_ix: usize,
+ status: ElicitationStatus,
+ _window: &mut Window,
+ cx: &mut App,
+) -> AnyElement {
+ let request = acp::CreateElicitationRequest::new(
+ acp::ElicitationUrlMode::new(
+ preview_request_scope(entry_ix),
+ acp::ElicitationId::new(format!("preview-url-{entry_ix}")),
+ preview_url(),
+ ),
+ "Authorize Zed in your browser to finish signing in.",
+ );
+
+ render_preview_card(entry_ix, request, status, None, cx)
+}
+
+fn render_preview_card(
+ entry_ix: usize,
+ request: acp::CreateElicitationRequest,
+ status: ElicitationStatus,
+ form_state: Option<&ElicitationFormState>,
+ cx: &App,
+) -> AnyElement {
+ let elicitation = Elicitation {
+ id: ElicitationEntryId(format!("preview-elicitation-{entry_ix}").into()),
+ request,
+ status,
+ };
+
+ div()
+ .w_full()
+ .max_w(px(640.))
+ .child(
+ ElicitationCard::new(
+ entry_ix,
+ &elicitation,
+ form_state,
+ ElicitationCardHandlers::noop(),
+ )
+ .render(cx),
+ )
+ .into_any_element()
+}
+
+fn pending_status() -> ElicitationStatus {
+ let (respond_tx, _response_rx) = oneshot::channel();
+ ElicitationStatus::Pending { respond_tx }
+}
+
+fn preview_request_scope(index: usize) -> acp::ElicitationRequestScope {
+ acp::ElicitationRequestScope::new(acp::RequestId::Number(index as i64))
+}
+
+fn preview_form_schema() -> acp::ElicitationSchema {
+ acp::ElicitationSchema::new()
+ .property(
+ "account_name",
+ acp::StringPropertySchema::new()
+ .title("Account Name")
+ .description("Used to label this connection in the agent panel.")
+ .default_value("Work"),
+ true,
+ )
+ .property(
+ "environment",
+ acp::StringPropertySchema::new()
+ .title("Environment")
+ .description("Select the environment this credential should target.")
+ .one_of(vec![
+ acp::EnumOption::new("production", "Production"),
+ acp::EnumOption::new("staging", "Staging"),
+ acp::EnumOption::new("development", "Development"),
+ ])
+ .default_value("staging"),
+ true,
+ )
+ .property(
+ "scopes",
+ acp::MultiSelectPropertySchema::titled(vec![
+ acp::EnumOption::new("profile", "Profile"),
+ acp::EnumOption::new("repository", "Repository Access"),
+ acp::EnumOption::new("terminal", "Terminal Commands"),
+ ])
+ .title("Access")
+ .description("Choose what the agent can use for this authorization.")
+ .min_items(1)
+ .default_value(vec!["profile".to_string(), "repository".to_string()]),
+ true,
+ )
+ .property(
+ "remember",
+ acp::BooleanPropertySchema::new()
+ .title("Remember Authorization")
+ .description("Store this authorization for future sessions.")
+ .default_value(true),
+ false,
+ )
+}
+
+fn single_select_options(schema: &acp::StringPropertySchema) -> Vec<ElicitationOption> {
+ if let Some(options) = &schema.one_of {
+ return options
+ .iter()
+ .map(|option| ElicitationOption {
+ value: option.value.clone(),
+ label: SharedString::from(option.title.clone()),
+ })
+ .collect();
+ }
+
+ schema
+ .enum_values
+ .as_deref()
+ .unwrap_or_default()
+ .iter()
+ .map(|value| ElicitationOption {
+ value: value.clone(),
+ label: SharedString::from(value.clone()),
+ })
+ .collect()
+}
+
+fn single_select_default_value(
+ schema: &acp::StringPropertySchema,
+ options: &[ElicitationOption],
+) -> Option<String> {
+ schema
+ .default
+ .as_ref()
+ .filter(|default| {
+ options
+ .iter()
+ .any(|option| option.value.as_str() == default.as_str())
+ })
+ .cloned()
+}
+
+fn multi_select_options(schema: &acp::MultiSelectPropertySchema) -> Vec<ElicitationOption> {
+ match &schema.items {
+ acp::MultiSelectItems::Untitled(items) => items
+ .values
+ .iter()
+ .map(|value| ElicitationOption {
+ value: value.clone(),
+ label: SharedString::from(value.clone()),
+ })
+ .collect(),
+ acp::MultiSelectItems::Titled(items) => items
+ .options
+ .iter()
+ .map(|option| ElicitationOption {
+ value: option.value.clone(),
+ label: SharedString::from(option.title.clone()),
+ })
+ .collect(),
+ _ => Vec::new(),
+ }
+}
+
+fn validate_number_value(
+ title: SharedString,
+ schema: &acp::NumberPropertySchema,
+ value: &str,
+) -> Result<f64, SharedString> {
+ let parsed = value
+ .parse::<f64>()
+ .map_err(|_| SharedString::from(format!("{title} must be a number")))?;
+ if !parsed.is_finite() {
+ return Err(format!("{title} must be a finite number").into());
+ }
+ if let Some(minimum) = schema.minimum
+ && parsed < minimum
+ {
+ return Err(format!("{title} must be at least {minimum}").into());
+ }
+ if let Some(maximum) = schema.maximum
+ && parsed > maximum
+ {
+ return Err(format!("{title} must be at most {maximum}").into());
+ }
+
+ Ok(parsed)
+}
+
+fn validate_integer_value(
+ title: SharedString,
+ schema: &acp::IntegerPropertySchema,
+ value: &str,
+) -> Result<i64, SharedString> {
+ let parsed = value
+ .parse::<i64>()
+ .map_err(|_| SharedString::from(format!("{title} must be an integer")))?;
+ if let Some(minimum) = schema.minimum
+ && parsed < minimum
+ {
+ return Err(format!("{title} must be at least {minimum}").into());
+ }
+ if let Some(maximum) = schema.maximum
+ && parsed > maximum
+ {
+ return Err(format!("{title} must be at most {maximum}").into());
+ }
+
+ Ok(parsed)
+}
+
+fn validate_string_value(
+ title: SharedString,
+ schema: &acp::StringPropertySchema,
+ value: &str,
+) -> Result<(), SharedString> {
+ let length = value.chars().count();
+ if schema
+ .min_length
+ .is_some_and(|min_length| length < min_length as usize)
+ {
+ return Err(format!("{title} is too short").into());
+ }
+ if schema
+ .max_length
+ .is_some_and(|max_length| length > max_length as usize)
+ {
+ return Err(format!("{title} is too long").into());
+ }
+
+ validate_string_pattern_and_format(title, schema, value)
+}
+
+fn validate_single_select_value(
+ title: SharedString,
+ schema: &acp::StringPropertySchema,
+ value: &str,
+) -> Result<(), SharedString> {
+ let options = single_select_options(schema);
+ if options.iter().any(|option| option.value.as_str() == value) {
+ Ok(())
+ } else {
+ Err(format!("{title} must be one of the provided options").into())
+ }
+}
+
+fn validate_string_pattern_and_format(
+ title: SharedString,
+ schema: &acp::StringPropertySchema,
+ value: &str,
+) -> Result<(), SharedString> {
+ if schema.pattern.is_none() && schema.format.and_then(string_format_json_name).is_none() {
+ return Ok(());
+ }
+
+ let mut validation_schema = serde_json::Map::new();
+ validation_schema.insert(
+ "type".to_string(),
+ serde_json::Value::String("string".into()),
+ );
+ if let Some(pattern) = &schema.pattern {
+ validation_schema.insert(
+ "pattern".to_string(),
+ serde_json::Value::String(pattern.clone()),
+ );
+ }
+ if let Some(format) = schema.format.and_then(string_format_json_name) {
+ validation_schema.insert(
+ "format".to_string(),
+ serde_json::Value::String(format.into()),
+ );
+ }
+
+ let validation_schema = serde_json::Value::Object(validation_schema);
+ let validator = jsonschema::options()
+ .should_validate_formats(true)
+ .build(&validation_schema)
+ .map_err(|_| {
+ if schema.pattern.is_some() {
+ format!("{title} has an invalid validation pattern")
+ } else {
+ format!("{title} has an invalid validation format")
+ }
+ })?;
+ if validator.is_valid(&serde_json::Value::String(value.to_string())) {
+ return Ok(());
+ }
+
+ match (
+ schema.pattern.is_some(),
+ schema.format.and_then(string_format_label),
+ ) {
+ (true, Some(_)) => Err(format!("{title} does not match the requested constraints").into()),
+ (true, None) => Err(format!("{title} does not match the requested pattern").into()),
+ (false, Some(format)) => Err(format!("{title} must be {format}").into()),
+ (false, None) => Ok(()),
+ }
+}
+
+fn string_format_json_name(format: acp::StringFormat) -> Option<&'static str> {
+ match format {
+ acp::StringFormat::Email => Some("email"),
+ acp::StringFormat::Uri => Some("uri"),
+ acp::StringFormat::Date => Some("date"),
+ acp::StringFormat::DateTime => Some("date-time"),
+ _ => None,
+ }
+}
+
+fn string_format_label(format: acp::StringFormat) -> Option<&'static str> {
+ match format {
+ acp::StringFormat::Email => Some("an email address"),
+ acp::StringFormat::Uri => Some("a URI"),
+ acp::StringFormat::Date => Some("a date"),
+ acp::StringFormat::DateTime => Some("a date and time"),
+ _ => None,
+ }
+}
+
+fn property_title(name: &str, property: &acp::ElicitationPropertySchema) -> SharedString {
+ let title = match property {
+ acp::ElicitationPropertySchema::String(schema) => schema.title.as_deref(),
+ acp::ElicitationPropertySchema::Number(schema) => schema.title.as_deref(),
+ acp::ElicitationPropertySchema::Integer(schema) => schema.title.as_deref(),
+ acp::ElicitationPropertySchema::Boolean(schema) => schema.title.as_deref(),
+ acp::ElicitationPropertySchema::Array(schema) => schema.title.as_deref(),
+ _ => None,
+ };
+ SharedString::from(title.unwrap_or(name).to_string())
+}
+
+fn property_description(property: &acp::ElicitationPropertySchema) -> Option<SharedString> {
+ match property {
+ acp::ElicitationPropertySchema::String(schema) => schema.description.clone(),
+ acp::ElicitationPropertySchema::Number(schema) => schema.description.clone(),
+ acp::ElicitationPropertySchema::Integer(schema) => schema.description.clone(),
+ acp::ElicitationPropertySchema::Boolean(schema) => schema.description.clone(),
+ acp::ElicitationPropertySchema::Array(schema) => schema.description.clone(),
+ _ => None,
+ }
+ .map(SharedString::from)
+}
+
+type RespondHandler = Rc<dyn Fn(ElicitationEntryId, &mut Window, &mut App)>;
+type OpenUrlHandler = Rc<dyn Fn(ElicitationEntryId, String, &mut Window, &mut App)>;
+type BooleanHandler = Rc<dyn Fn(ElicitationEntryId, String, bool, &mut App)>;
+type SelectHandler = Rc<dyn Fn(ElicitationEntryId, String, String, &mut App)>;
+type MultiSelectHandler = Rc<dyn Fn(ElicitationEntryId, String, String, bool, &mut App)>;
+
+#[derive(Clone)]
+pub(crate) struct ElicitationCardHandlers {
+ on_submit: RespondHandler,
+ on_decline: RespondHandler,
+ on_cancel: RespondHandler,
+ on_open_url: OpenUrlHandler,
+ on_boolean_change: BooleanHandler,
+ on_single_select_change: SelectHandler,
+ on_multi_select_change: MultiSelectHandler,
+}
+
+impl ElicitationCardHandlers {
+ pub(crate) fn new(
+ on_submit: impl Fn(ElicitationEntryId, &mut Window, &mut App) + 'static,
+ on_decline: impl Fn(ElicitationEntryId, &mut Window, &mut App) + 'static,
+ on_cancel: impl Fn(ElicitationEntryId, &mut Window, &mut App) + 'static,
+ on_open_url: impl Fn(ElicitationEntryId, String, &mut Window, &mut App) + 'static,
+ on_boolean_change: impl Fn(ElicitationEntryId, String, bool, &mut App) + 'static,
+ on_single_select_change: impl Fn(ElicitationEntryId, String, String, &mut App) + 'static,
+ on_multi_select_change: impl Fn(ElicitationEntryId, String, String, bool, &mut App) + 'static,
+ ) -> Self {
+ Self {
+ on_submit: Rc::new(on_submit),
+ on_decline: Rc::new(on_decline),
+ on_cancel: Rc::new(on_cancel),
+ on_open_url: Rc::new(on_open_url),
+ on_boolean_change: Rc::new(on_boolean_change),
+ on_single_select_change: Rc::new(on_single_select_change),
+ on_multi_select_change: Rc::new(on_multi_select_change),
+ }
+ }
+
+ pub(crate) fn noop() -> Self {
+ Self::new(
+ |_, _, _| {},
+ |_, _, _| {},
+ |_, _, _| {},
+ |_, _, _, _| {},
+ |_, _, _, _| {},
+ |_, _, _, _| {},
+ |_, _, _, _, _| {},
+ )
+ }
+}
+
+pub(crate) fn should_render_elicitation(elicitation: &Elicitation) -> bool {
+ matches!(
+ (&elicitation.status, &elicitation.request.mode),
+ (ElicitationStatus::Pending { .. }, _)
+ | (ElicitationStatus::Accepted, acp::ElicitationMode::Url(_))
+ )
+}
+
+const MIN_URL_DISPLAY_SEGMENT_CHARS: usize = 16;
+const MAX_URL_DISPLAY_SEGMENT_CHARS: usize = 64;
+
+fn display_url_segments(url: &str) -> Vec<SharedString> {
+ let mut segments = Vec::new();
+ let mut segment = String::new();
+ let mut segment_chars = 0;
+ let mut characters = url.chars().peekable();
+
+ while let Some(character) = characters.next() {
+ segment.push(character);
+ segment_chars += 1;
+
+ let should_split_at_boundary = segment_chars >= MIN_URL_DISPLAY_SEGMENT_CHARS
+ && is_url_display_segment_boundary(character);
+ let should_split_at_length = segment_chars >= MAX_URL_DISPLAY_SEGMENT_CHARS;
+
+ if characters.peek().is_some() && (should_split_at_boundary || should_split_at_length) {
+ segments.push(std::mem::take(&mut segment).into());
+ segment_chars = 0;
+ }
+ }
+
+ if !segment.is_empty() {
+ segments.push(segment.into());
+ }
+
+ segments
+}
+
+fn is_url_display_segment_boundary(character: char) -> bool {
+ matches!(character, '/' | '?' | '&' | '#')
+}
+
+pub(crate) struct ElicitationCard<'a> {
+ entry_ix: usize,
+ elicitation: &'a Elicitation,
+ form_state: Option<&'a ElicitationFormState>,
+ handlers: ElicitationCardHandlers,
+}
+
+impl<'a> ElicitationCard<'a> {
+ pub(crate) fn new(
+ entry_ix: usize,
+ elicitation: &'a Elicitation,
+ form_state: Option<&'a ElicitationFormState>,
+ handlers: ElicitationCardHandlers,
+ ) -> Self {
+ Self {
+ entry_ix,
+ elicitation,
+ form_state,
+ handlers,
+ }
+ }
+
+ pub(crate) fn render(self, cx: &App) -> Div {
+ let border_color = cx.theme().colors().border.opacity(0.8);
+ let header_background = cx
+ .theme()
+ .colors()
+ .element_background
+ .blend(cx.theme().colors().editor_foreground.opacity(0.025));
+ let tool_name_font_size = rems_from_px(13.);
+ let is_pending = matches!(&self.elicitation.status, ElicitationStatus::Pending { .. });
+ let is_accepted_url = matches!(
+ (&self.elicitation.status, &self.elicitation.request.mode),
+ (ElicitationStatus::Accepted, acp::ElicitationMode::Url(_))
+ );
+ let (status_label, status_icon, status_color) = match &self.elicitation.status {
+ ElicitationStatus::Pending { .. } => ("Waiting for input", IconName::Info, Color::Info),
+ ElicitationStatus::Accepted if is_accepted_url => {
+ ("Waiting for completion", IconName::Info, Color::Info)
+ }
+ ElicitationStatus::Accepted => ("Submitted", IconName::Check, Color::Success),
+ ElicitationStatus::Declined => ("Declined", IconName::Close, Color::Muted),
+ ElicitationStatus::Canceled => ("Canceled", IconName::Circle, Color::Muted),
+ ElicitationStatus::Completed => ("Completed", IconName::Check, Color::Success),
+ };
+
+ let body = v_flex()
+ .gap_2()
+ .p_3()
+ .child(Label::new(self.elicitation.request.message.clone()).size(LabelSize::Small));
+ let body = match &self.elicitation.request.mode {
+ acp::ElicitationMode::Form(mode) if is_pending => {
+ body.child(self.render_form(mode, cx))
+ }
+ acp::ElicitationMode::Url(mode) if is_pending || is_accepted_url => {
+ body.child(self.render_url_elicitation(mode))
+ }
+ _ => body,
+ };
+
+ v_flex()
+ .mx_5()
+ .my_1p5()
+ .rounded_md()
+ .border_1()
+ .border_color(border_color)
+ .overflow_hidden()
+ .child(
+ h_flex()
+ .h_8()
+ .p_1()
+ .w_full()
+ .justify_between()
+ .bg(header_background)
+ .child(
+ h_flex()
+ .min_w_0()
+ .gap_1p5()
+ .px_1()
+ .child(
+ Icon::new(status_icon)
+ .size(IconSize::Small)
+ .color(status_color),
+ )
+ .child(
+ Label::new("Input Requested")
+ .size(LabelSize::Custom(tool_name_font_size))
+ .truncate(),
+ ),
+ )
+ .child(
+ Label::new(status_label)
+ .size(LabelSize::Small)
+ .color(Color::Muted),
+ ),
+ )
+ .child(body)
+ .when(is_pending, |this| this.child(self.render_actions(cx)))
+ }
+
+ fn render_form(&self, mode: &acp::ElicitationFormMode, cx: &App) -> AnyElement {
+ let Some(state) = self.form_state else {
+ return Empty.into_any_element();
+ };
+
+ v_flex()
+ .gap_2()
+ .children(mode.requested_schema.properties.iter().filter_map(
+ |(field_name, property)| {
+ let field = state.fields.get(field_name)?;
+ Some(self.render_field(
+ field_name,
+ property,
+ field,
+ state.field_errors.get(field_name),
+ cx,
+ ))
+ },
+ ))
+ .into_any_element()
+ }
+
+ fn render_field(
+ &self,
+ field_name: &str,
+ property: &acp::ElicitationPropertySchema,
+ field: &ElicitationFieldState,
+ error: Option<&SharedString>,
+ cx: &App,
+ ) -> AnyElement {
+ let label = property_title(field_name, property);
+ let description = property_description(property);
+ let border_color = cx.theme().colors().border.opacity(0.8);
+ let field_border_color = if error.is_some() {
+ Color::Error.color(cx)
+ } else {
+ border_color
+ };
+ let editor_background = cx.theme().colors().editor_background;
+ let label_color = if error.is_some() {
+ Color::Error
+ } else {
+ Color::Default
+ };
+
+ if let ElicitationFieldState::Boolean(value) = field {
+ let checkbox_state = if *value {
+ ToggleState::Selected
+ } else {
+ ToggleState::Unselected
+ };
+ let next_value = !*value;
+ let on_boolean_change = self.handlers.on_boolean_change.clone();
+ let elicitation_id = self.elicitation.id.clone();
+ let field_name = field_name.to_string();
+ let row_id = format!("elicitation-bool-row-{}-{field_name}", self.entry_ix);
+ let checkbox_id = format!("elicitation-bool-{}-{field_name}", self.entry_ix);
+
+ return v_flex()
+ .gap_1()
+ .child(
+ h_flex()
+ .id(row_id)
+ .w_full()
+ .items_start()
+ .gap_1()
+ .cursor_pointer()
+ .on_click(move |_, _window, cx| {
+ on_boolean_change(
+ elicitation_id.clone(),
+ field_name.clone(),
+ next_value,
+ cx,
+ );
+ })
+ .child(
+ div()
+ .mt_0p5()
+ .child(Checkbox::new(checkbox_id, checkbox_state)),
+ )
+ .child(
+ v_flex()
+ .gap_0p5()
+ .child(Label::new(label).size(LabelSize::Small).color(label_color))
+ .when_some(description, |this, description| {
+ this.child(
+ Label::new(description)
+ .size(LabelSize::Small)
+ .color(Color::Muted),
+ )
+ }),
+ ),
+ )
+ .when_some(error.cloned(), |this, error| {
+ this.child(Label::new(error).size(LabelSize::Small).color(Color::Error))
+ })
+ .into_any_element();
+ }
+
+ let label = if error.is_some() {
+ Label::new(label).size(LabelSize::Small).color(Color::Error)
+ } else {
+ Label::new(label).size(LabelSize::Small)
+ };
+
+ v_flex()
+ .gap_1()
+ .child(label)
+ .when_some(description, |this, description| {
+ this.child(
+ Label::new(description)
+ .size(LabelSize::Small)
+ .color(Color::Muted),
+ )
+ })
+ .child(match field {
+ ElicitationFieldState::Text(editor) => div()
+ .rounded_sm()
+ .border_1()
+ .border_color(field_border_color)
+ .bg(editor_background)
+ .px_1()
+ .py_0p5()
+ .text_xs()
+ .child(editor.clone().into_any_element())
+ .into_any_element(),
+ ElicitationFieldState::Boolean(_) => Empty.into_any_element(),
+ ElicitationFieldState::SingleSelect { value } => {
+ let options = match property {
+ acp::ElicitationPropertySchema::String(schema) => {
+ single_select_options(schema)
+ }
+ _ => Vec::new(),
+ };
+ self.render_single_select(
+ field_name,
+ value.as_ref(),
+ options,
+ error.is_some(),
+ cx,
+ )
+ }
+ ElicitationFieldState::MultiSelect(selected) => {
+ let options = match property {
+ acp::ElicitationPropertySchema::Array(schema) => {
+ multi_select_options(schema)
+ }
+ _ => Vec::new(),
+ };
+ v_flex()
+ .gap_1()
+ .children(options.into_iter().map(|option| {
+ let is_selected = selected.contains(&option.value);
+ let checkbox_state = if is_selected {
+ ToggleState::Selected
+ } else {
+ ToggleState::Unselected
+ };
+ let row_background = Self::option_row_background(is_selected, cx);
+ let hover_background =
+ Self::option_row_hover_background(is_selected, cx);
+ let on_multi_select_change =
+ self.handlers.on_multi_select_change.clone();
+ let elicitation_id = self.elicitation.id.clone();
+ let field_name = field_name.to_string();
+ let value = option.value.clone();
+ let checkbox_id = format!(
+ "elicitation-multi-{}-{field_name}-{}",
+ self.entry_ix, option.value
+ );
+ h_flex()
+ .id(SharedString::from(format!(
+ "elicitation-multi-option-{}-{field_name}-{}",
+ self.entry_ix, option.value
+ )))
+ .w_full()
+ .min_h(rems_from_px(28.))
+ .items_center()
+ .gap_2()
+ .rounded_sm()
+ .border_1()
+ .border_color(field_border_color.opacity(0.5))
+ .bg(row_background)
+ .px_2()
+ .py_1()
+ .hover(move |this| this.bg(hover_background).cursor_pointer())
+ .on_click(move |_, _window, cx| {
+ on_multi_select_change(
+ elicitation_id.clone(),
+ field_name.clone(),
+ value.clone(),
+ !is_selected,
+ cx,
+ );
+ })
+ .child(Checkbox::new(checkbox_id, checkbox_state))
+ .child(Label::new(option.label).size(LabelSize::Small).truncate())
+ }))
+ .into_any_element()
+ }
+ })
+ .when_some(error.cloned(), |this, error| {
+ this.child(Label::new(error).size(LabelSize::Small).color(Color::Error))
+ })
+ .into_any_element()
+ }
+
+ fn render_single_select(
+ &self,
+ field_name: &str,
+ selected_value: Option<&String>,
+ options: Vec<ElicitationOption>,
+ has_error: bool,
+ cx: &App,
+ ) -> AnyElement {
+ let entry_ix = self.entry_ix;
+ let border_color = if has_error {
+ Color::Error.color(cx)
+ } else {
+ cx.theme().colors().border.opacity(0.8)
+ };
+ let elicitation_id = self.elicitation.id.clone();
+ let field_name = field_name.to_string();
+ let on_single_select_change = self.handlers.on_single_select_change.clone();
+
+ v_flex()
+ .gap_1()
+ .children(options.into_iter().map(move |option| {
+ let option_value = option.value.clone();
+ let option_id =
+ format!("elicitation-select-option-{entry_ix}-{field_name}-{option_value}");
+ let is_selected =
+ selected_value.is_some_and(|selected_value| selected_value == &option.value);
+ let row_background = Self::option_row_background(is_selected, cx);
+ let hover_background = Self::option_row_hover_background(is_selected, cx);
+ let control_background = Self::option_control_background(cx);
+ let elicitation_id = elicitation_id.clone();
+ let field_name = field_name.clone();
+ let on_single_select_change = on_single_select_change.clone();
+
+ h_flex()
+ .id(option_id)
+ .w_full()
+ .min_h(rems_from_px(28.))
+ .items_center()
+ .gap_2()
+ .rounded_sm()
+ .border_1()
+ .border_color(border_color.opacity(0.5))
+ .bg(row_background)
+ .px_2()
+ .py_1()
+ .hover(move |this| this.bg(hover_background).cursor_pointer())
+ .on_click(move |_, _window, cx| {
+ on_single_select_change(
+ elicitation_id.clone(),
+ field_name.clone(),
+ option_value.clone(),
+ cx,
+ );
+ })
+ .child(Self::render_radio_indicator(
+ is_selected,
+ border_color,
+ control_background,
+ ))
+ .child(Label::new(option.label).size(LabelSize::Small).truncate())
+ }))
+ .into_any_element()
+ }
+
+ fn option_row_background(is_selected: bool, cx: &App) -> Hsla {
+ let editor_background = cx.theme().colors().editor_background;
+ if is_selected {
+ editor_background.blend(Color::Accent.color(cx).opacity(0.08))
+ } else {
+ editor_background
+ }
+ }
+
+ fn option_row_hover_background(is_selected: bool, cx: &App) -> Hsla {
+ let editor_background = cx.theme().colors().editor_background;
+ if is_selected {
+ editor_background.blend(Color::Accent.color(cx).opacity(0.1))
+ } else {
+ cx.theme()
+ .colors()
+ .element_background
+ .blend(cx.theme().colors().editor_foreground.opacity(0.025))
+ }
+ }
+
+ fn option_control_background(cx: &App) -> Hsla {
+ cx.theme().colors().editor_background
+ }
+
+ fn render_radio_indicator(is_selected: bool, border_color: Hsla, background: Hsla) -> Div {
+ div()
+ .size_3()
+ .flex()
+ .items_center()
+ .justify_center()
+ .rounded_full()
+ .border_1()
+ .border_color(border_color)
+ .bg(background)
+ .when(is_selected, |this| {
+ this.child(Indicator::dot().color(Color::Accent))
+ })
+ }
+
+ fn render_url_elicitation(&self, mode: &acp::ElicitationUrlMode) -> AnyElement {
+ v_flex()
+ .gap_2()
+ .child(Self::render_url_summary(&mode.url))
+ .into_any_element()
+ }
+
+ fn render_url_summary(url: &str) -> AnyElement {
+ h_flex()
+ .gap_1()
+ .w_full()
+ .min_w_0()
+ .items_start()
+ .child(
+ div().h(rems_from_px(16.)).flex().items_center().child(
+ Icon::new(IconName::Link)
+ .size(IconSize::XSmall)
+ .color(Color::Muted),
+ ),
+ )
+ .child(h_flex().min_w_0().flex_1().flex_wrap().children(
+ display_url_segments(url).into_iter().map(|segment| {
+ Label::new(segment)
+ .size(LabelSize::Small)
+ .color(Color::Muted)
+ }),
+ ))
+ .into_any_element()
+ }
+
+ fn render_actions(&self, cx: &App) -> AnyElement {
+ let open_url = match &self.elicitation.request.mode {
+ acp::ElicitationMode::Url(mode) => Some(mode.url.clone()),
+ _ => None,
+ };
+ let (accept_label, accept_icon, accept_icon_color) = if open_url.is_some() {
+ ("Open", IconName::ArrowUpRight, Color::Muted)
+ } else {
+ ("Submit", IconName::Check, Color::Success)
+ };
+ let border_color = cx.theme().colors().border.opacity(0.8);
+ let on_submit = self.handlers.on_submit.clone();
+ let on_open_url = self.handlers.on_open_url.clone();
+ let on_decline = self.handlers.on_decline.clone();
+ let on_cancel = self.handlers.on_cancel.clone();
+ let submit_id = self.elicitation.id.clone();
+ let decline_id = self.elicitation.id.clone();
+ let cancel_id = self.elicitation.id.clone();
+
+ h_flex()
+ .w_full()
+ .p_1()
+ .gap_1()
+ .justify_end()
+ .border_t_1()
+ .border_color(border_color)
+ .child(
+ Button::new(("elicitation-accept", self.entry_ix), accept_label)
+ .start_icon(
+ Icon::new(accept_icon)
+ .size(IconSize::XSmall)
+ .color(accept_icon_color),
+ )
+ .label_size(LabelSize::Small)
+ .on_click(move |_, window, cx| {
+ if let Some(url) = &open_url {
+ on_open_url(submit_id.clone(), url.clone(), window, cx);
+ } else {
+ on_submit(submit_id.clone(), window, cx);
+ }
+ }),
+ )
+ .child(
+ Button::new(("elicitation-decline", self.entry_ix), "Decline")
+ .start_icon(
+ Icon::new(IconName::Close)
+ .size(IconSize::XSmall)
+ .color(Color::Error),
+ )
+ .label_size(LabelSize::Small)
+ .on_click(move |_, window, cx| {
+ on_decline(decline_id.clone(), window, cx);
+ }),
+ )
+ .child(
+ Button::new(("elicitation-cancel", self.entry_ix), "Cancel")
+ .label_size(LabelSize::Small)
+ .on_click(move |_, window, cx| {
+ on_cancel(cancel_id.clone(), window, cx);
+ }),
+ )
+ .into_any_element()
+ }
+}
diff --git a/crates/agent_ui/src/conversation_view/thread_search_bar.rs b/crates/agent_ui/src/conversation_view/thread_search_bar.rs
index f936edcd35a..643cceda36a 100644
--- a/crates/agent_ui/src/conversation_view/thread_search_bar.rs
+++ b/crates/agent_ui/src/conversation_view/thread_search_bar.rs
@@ -946,6 +946,7 @@ fn collect_markdowns(
out.push(summary.clone());
}
}
+ AgentThreadEntry::Elicitation(_) => {}
AgentThreadEntry::ContextCompaction(_) => {}
}
out
diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs
index 16b6b60875d..8720ff145c0 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -9,8 +9,8 @@ use agent_client_protocol::schema::v1 as acp;
use std::cell::RefCell;
use acp_thread::{
- PlanEntry, SandboxAuthorizationDetails, SandboxFallbackAuthorizationDetails,
- SandboxNotAppliedReason,
+ Elicitation, ElicitationEntryId, ElicitationStatus, PlanEntry, SandboxAuthorizationDetails,
+ SandboxFallbackAuthorizationDetails, SandboxNotAppliedReason,
};
use agent::{
SandboxStatusKey, SandboxStatusRefresh, SkillLoadingIssue, SkillLoadingIssueKind,
@@ -20,6 +20,7 @@ use agent_settings::UserAgentsMd;
use agent_skills::MAX_SKILL_DESCRIPTION_LEN;
use cloud_api_types::{SubmitAgentThreadFeedbackBody, SubmitAgentThreadFeedbackCommentsBody};
use editor::actions::OpenExcerpts;
+use feature_flags::{AcpBetaFeatureFlag, FeatureFlagAppExt as _};
use sandbox::{GitSandboxPolicy, SandboxFsPolicy, SandboxNetPolicy, SandboxPolicy};
use crate::completion_provider::AvailableSkill;
@@ -42,6 +43,9 @@ use ui::{
};
use workspace::{OpenOptions, SERIALIZATION_THROTTLE_TIME};
+use super::elicitation::{
+ ElicitationCard, ElicitationCardHandlers, ElicitationFormState, should_render_elicitation,
+};
use super::*;
const DATA_RETENTION_LEARN_MORE_URL: &str = "https://support.claude.com/en/articles/15425996-data-retention-practices-for-mythos-class-models";
@@ -598,6 +602,7 @@ pub struct ThreadView {
pub new_server_version_available: Option<SharedString>,
pub resumed_without_history: bool,
pub(crate) permission_selections: HashMap<acp::ToolCallId, PermissionSelection>,
+ elicitation_form_states: HashMap<ElicitationEntryId, ElicitationFormState>,
pub _cancel_task: Option<Task<()>>,
_save_task: Option<Task<()>>,
_draft_resolve_task: Option<Task<()>>,
@@ -989,6 +994,7 @@ impl ThreadView {
is_loading_contents: false,
new_server_version_available: None,
permission_selections: HashMap::default(),
+ elicitation_form_states: HashMap::default(),
_cancel_task: None,
_save_task: None,
_draft_resolve_task: None,
@@ -1016,6 +1022,7 @@ impl ThreadView {
this.sync_generating_indicator(cx);
this.sync_editor_mode_for_empty_state(cx);
+ this.sync_existing_elicitation_states(window, cx);
let list_state_for_scroll = this.list_state.clone();
let thread_view = cx.entity().downgrade();
@@ -2480,15 +2487,182 @@ impl ThreadView {
Some(())
}
- fn is_waiting_for_confirmation(entry: &AgentThreadEntry) -> bool {
- if let AgentThreadEntry::ToolCall(tool_call) = entry {
- matches!(
- tool_call.status,
- ToolCallStatus::WaitingForConfirmation { .. }
+ fn is_waiting_for_confirmation(&self, entry: &AgentThreadEntry, cx: &Context<Self>) -> bool {
+ match entry {
+ AgentThreadEntry::ToolCall(tool_call) => {
+ matches!(
+ tool_call.status,
+ ToolCallStatus::WaitingForConfirmation { .. }
+ )
+ }
+ AgentThreadEntry::Elicitation(elicitation_id) => {
+ cx.has_flag::<AcpBetaFeatureFlag>()
+ && self
+ .thread
+ .read(cx)
+ .elicitation(elicitation_id)
+ .is_some_and(|(_, elicitation)| {
+ matches!(elicitation.status, ElicitationStatus::Pending { .. })
+ })
+ }
+ _ => false,
+ }
+ }
+
+ pub fn sync_elicitation_state_for_entry(
+ &mut self,
+ index: usize,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ let elicitation_id = {
+ let thread = self.thread.read(cx);
+ let Some(AgentThreadEntry::Elicitation(elicitation_id)) = thread.entries().get(index)
+ else {
+ return;
+ };
+ elicitation_id.clone()
+ };
+
+ if !cx.has_flag::<AcpBetaFeatureFlag>() {
+ self.elicitation_form_states.remove(&elicitation_id);
+ return;
+ }
+
+ let thread = self.thread.read(cx);
+ let entry = thread.elicitation(&elicitation_id).map(|(_, elicitation)| {
+ (
+ elicitation_id.clone(),
+ matches!(elicitation.status, ElicitationStatus::Pending { .. }),
+ match &elicitation.request.mode {
+ acp::ElicitationMode::Form(mode) => Some(mode.requested_schema.clone()),
+ _ => None,
+ },
)
- } else {
- false
+ });
+
+ let Some((id, is_pending, schema)) = entry else {
+ return;
+ };
+
+ if is_pending
+ && let Some(schema) = schema
+ && !self.elicitation_form_states.contains_key(&id)
+ {
+ self.elicitation_form_states
+ .insert(id, ElicitationFormState::new(&schema, window, cx));
+ } else if !is_pending {
+ self.elicitation_form_states.remove(&id);
+ }
+ }
+
+ fn sync_existing_elicitation_states(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ let entry_count = self.thread.read(cx).entries().len();
+ for index in 0..entry_count {
+ self.sync_elicitation_state_for_entry(index, window, cx);
+ }
+ }
+
+ #[cfg(test)]
+ pub(crate) fn has_elicitation_form_state(&self, id: &ElicitationEntryId) -> bool {
+ self.elicitation_form_states.contains_key(id)
+ }
+
+ fn submit_elicitation(
+ &mut self,
+ elicitation_id: ElicitationEntryId,
+ _window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if !cx.has_flag::<AcpBetaFeatureFlag>() {
+ return;
+ }
+
+ let mode = self
+ .thread
+ .read(cx)
+ .elicitation(&elicitation_id)
+ .map(|(_, elicitation)| elicitation.request.mode.clone());
+
+ let Some(mode) = mode else {
+ return;
+ };
+
+ let response = match mode {
+ acp::ElicitationMode::Form(mode) => {
+ let Some(state) = self.elicitation_form_states.get(&elicitation_id) else {
+ return;
+ };
+ match state.collect(&mode.requested_schema, cx) {
+ Ok(content) => {
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
+ acp::ElicitationAcceptAction::new().content(content),
+ ))
+ }
+ Err(errors) => {
+ if let Some(state) = self.elicitation_form_states.get_mut(&elicitation_id) {
+ state.set_errors(errors);
+ }
+ cx.notify();
+ return;
+ }
+ }
+ }
+ acp::ElicitationMode::Url(_) => acp::CreateElicitationResponse::new(
+ acp::ElicitationAction::Accept(acp::ElicitationAcceptAction::new()),
+ ),
+ _ => return,
+ };
+
+ self.respond_to_elicitation(elicitation_id, response, cx);
+ }
+
+ fn decline_elicitation(
+ &mut self,
+ elicitation_id: ElicitationEntryId,
+ _window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if !cx.has_flag::<AcpBetaFeatureFlag>() {
+ return;
+ }
+
+ self.respond_to_elicitation(
+ elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ cx,
+ );
+ }
+
+ fn cancel_elicitation(
+ &mut self,
+ elicitation_id: ElicitationEntryId,
+ _window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if !cx.has_flag::<AcpBetaFeatureFlag>() {
+ return;
}
+
+ self.respond_to_elicitation(
+ elicitation_id,
+ acp::CreateElicitationResponse::new(acp::ElicitationAction::Cancel),
+ cx,
+ );
+ }
+
+ fn respond_to_elicitation(
+ &mut self,
+ elicitation_id: ElicitationEntryId,
+ response: acp::CreateElicitationResponse,
+ cx: &mut Context<Self>,
+ ) {
+ let session_id = self.session_id.clone();
+ self.elicitation_form_states.remove(&elicitation_id);
+ self.conversation.update(cx, |conversation, cx| {
+ conversation.respond_to_elicitation(session_id, elicitation_id, response, cx);
+ });
+ cx.notify();
}
fn handle_authorize_tool_call(
@@ -5859,7 +6033,7 @@ impl ThreadView {
} else if this.generating_indicator_in_list {
let confirmation = entries
.last()
- .is_some_and(|entry| Self::is_waiting_for_confirmation(entry));
+ .is_some_and(|entry| this.is_waiting_for_confirmation(entry, cx));
let rendered = this.render_generating(confirmation, cx);
centered_container(rendered.into_any_element()).into_any_element()
} else {
@@ -6178,6 +6352,28 @@ impl ThreadView {
tool_call.into_any()
}
}
+ AgentThreadEntry::Elicitation(elicitation_id) => {
+ let thread = self.thread.read(cx);
+ if cx.has_flag::<AcpBetaFeatureFlag>()
+ && let Some((_, elicitation)) = thread.elicitation(elicitation_id)
+ && should_render_elicitation(elicitation)
+ {
+ let elicitation = self.render_elicitation(entry_ix, elicitation, window, cx);
+
+ if let Some(handle) = self
+ .entry_view_state
+ .read(cx)
+ .entry(entry_ix)
+ .and_then(|entry| entry.focus_handle(cx))
+ {
+ elicitation.track_focus(&handle).into_any()
+ } else {
+ elicitation.into_any()
+ }
+ } else {
+ Empty.into_any()
+ }
+ }
AgentThreadEntry::CompletedPlan(entries) => {
self.render_completed_plan(entries, window, cx)
}
@@ -6251,7 +6447,7 @@ impl ThreadView {
primary
};
- let needs_confirmation = Self::is_waiting_for_confirmation(entry);
+ let needs_confirmation = self.is_waiting_for_confirmation(entry, cx);
let comments_editor = self.thread_feedback.comments_editor.clone();
@@ -6295,6 +6491,99 @@ impl ThreadView {
}
}
+ fn render_elicitation(
+ &self,
+ entry_ix: usize,
+ elicitation: &Elicitation,
+ _window: &Window,
+ cx: &Context<Self>,
+ ) -> Div {
+ ElicitationCard::new(
+ entry_ix,
+ elicitation,
+ self.elicitation_form_states.get(&elicitation.id),
+ self.elicitation_card_handlers(cx),
+ )
+ .render(cx)
+ }
+
+ fn elicitation_card_handlers(&self, cx: &Context<Self>) -> ElicitationCardHandlers {
+ let view = cx.entity().downgrade();
+
+ ElicitationCardHandlers::new(
+ {
+ let view = view.clone();
+ move |elicitation_id, window, cx| {
+ view.update(cx, |this, cx| {
+ this.submit_elicitation(elicitation_id, window, cx);
+ })
+ .log_err();
+ }
+ },
+ {
+ let view = view.clone();
+ move |elicitation_id, window, cx| {
+ view.update(cx, |this, cx| {
+ this.decline_elicitation(elicitation_id, window, cx);
+ })
+ .log_err();
+ }
+ },
+ {
+ let view = view.clone();
+ move |elicitation_id, window, cx| {
+ view.update(cx, |this, cx| {
+ this.cancel_elicitation(elicitation_id, window, cx);
+ })
+ .log_err();
+ }
+ },
+ {
+ let view = view.clone();
+ move |elicitation_id, url, window, cx| {
+ cx.open_url(&url);
+ view.update(cx, |this, cx| {
+ this.submit_elicitation(elicitation_id, window, cx);
+ })
+ .log_err();
+ }
+ },
+ {
+ let view = view.clone();
+ move |elicitation_id, field_name, value, cx| {
+ view.update(cx, |this, cx| {
+ if let Some(form) = this.elicitation_form_states.get_mut(&elicitation_id) {
+ form.set_boolean(&field_name, value);
+ cx.notify();
+ }
+ })
+ .log_err();
+ }
+ },
+ {
+ let view = view.clone();
+ move |elicitation_id, field_name, value, cx| {
+ view.update(cx, |this, cx| {
+ if let Some(form) = this.elicitation_form_states.get_mut(&elicitation_id) {
+ form.set_single_select(&field_name, value);
+ cx.notify();
+ }
+ })
+ .log_err();
+ }
+ },
+ move |elicitation_id, field_name, value, selected, cx| {
+ view.update(cx, |this, cx| {
+ if let Some(form) = this.elicitation_form_states.get_mut(&elicitation_id) {
+ form.set_multi_select(&field_name, value, selected);
+ cx.notify();
+ }
+ })
+ .log_err();
+ },
+ )
+ }
+
fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
h_flex()
.key_context("AgentFeedbackMessageEditor")
@@ -6506,6 +6795,19 @@ impl ThreadView {
.into_any_element()
}
+ fn render_request_elicitations(&self, cx: &Context<Self>) -> Vec<AnyElement> {
+ let server_view = self.server_view.clone();
+ let handlers_view = server_view.clone();
+ server_view
+ .read_with(cx, |server_view, cx| {
+ let Some(connection) = server_view.request_elicitation_connection() else {
+ return Vec::new();
+ };
+ server_view.render_request_elicitations(&connection, handlers_view, cx)
+ })
+ .unwrap_or_default()
+ }
+
pub(crate) fn scroll_to_most_recent_user_prompt(&mut self, cx: &mut Context<Self>) {
let entries = self.thread.read(cx).entries();
if entries.is_empty() {
@@ -7241,6 +7543,7 @@ impl ThreadView {
}
}
AgentThreadEntry::ToolCall(_)
+ | AgentThreadEntry::Elicitation(_)
| AgentThreadEntry::AssistantMessage(_)
| AgentThreadEntry::CompletedPlan(_)
| AgentThreadEntry::ContextCompaction(_) => {}
@@ -11642,6 +11945,7 @@ impl Render for ThreadView {
|this, version| this.child(self.render_new_version_callout(&version, cx)),
)
.children(self.render_token_limit_callout(cx))
+ .children(self.render_request_elicitations(cx))
.child(self.render_message_editor(window, cx))
}
}
diff --git a/crates/agent_ui/src/entry_view_state.rs b/crates/agent_ui/src/entry_view_state.rs
index d19a1067bae..e2ad7ca71ec 100644
--- a/crates/agent_ui/src/entry_view_state.rs
+++ b/crates/agent_ui/src/entry_view_state.rs
@@ -377,6 +377,16 @@ impl EntryViewState {
});
}
}
+ AgentThreadEntry::Elicitation(_) => {
+ if !matches!(self.entries.get(index), Some(Entry::Elicitation { .. })) {
+ self.set_entry(
+ index,
+ Entry::Elicitation {
+ focus_handle: cx.focus_handle(),
+ },
+ );
+ }
+ }
AgentThreadEntry::AssistantMessage(message) => {
let entry = if let Some(Entry::AssistantMessage(entry)) =
self.entries.get_mut(index)
@@ -452,6 +462,7 @@ impl EntryViewState {
match entry {
Entry::UserMessage { .. }
| Entry::AssistantMessage { .. }
+ | Entry::Elicitation { .. }
| Entry::CompletedPlan
| Entry::ContextCompaction => {}
Entry::ToolCall(ToolCallEntry { content, .. }) => {
@@ -521,6 +532,7 @@ pub enum Entry {
UserMessage(Entity<MessageEditor>),
AssistantMessage(AssistantMessageEntry),
ToolCall(ToolCallEntry),
+ Elicitation { focus_handle: FocusHandle },
CompletedPlan,
ContextCompaction,
}
@@ -531,6 +543,7 @@ impl Entry {
Self::UserMessage(editor) => Some(editor.read(cx).focus_handle(cx)),
Self::AssistantMessage(message) => Some(message.focus_handle.clone()),
Self::ToolCall(tool_call) => Some(tool_call.focus_handle.clone()),
+ Self::Elicitation { focus_handle } => Some(focus_handle.clone()),
Self::CompletedPlan | Self::ContextCompaction => None,
}
}
@@ -540,6 +553,7 @@ impl Entry {
Self::UserMessage(editor) => Some(editor),
Self::AssistantMessage(_)
| Self::ToolCall(_)
+ | Self::Elicitation { .. }
| Self::CompletedPlan
| Self::ContextCompaction => None,
}
@@ -570,6 +584,7 @@ impl Entry {
Self::AssistantMessage(message) => message.scroll_handle_for_chunk(chunk_ix),
Self::UserMessage(_)
| Self::ToolCall(_)
+ | Self::Elicitation { .. }
| Self::CompletedPlan
| Self::ContextCompaction => None,
}
@@ -588,6 +603,7 @@ impl Entry {
Self::ToolCall(ToolCallEntry { content, .. }) => !content.is_empty(),
Self::UserMessage(_)
| Self::AssistantMessage(_)
+ | Self::Elicitation { .. }
| Self::CompletedPlan
| Self::ContextCompaction => false,
}
@@ -606,6 +622,7 @@ impl Focusable for Entry {
Self::UserMessage(editor) => editor.read(cx).focus_handle(cx),
Self::AssistantMessage(message) => message.focus_handle.clone(),
Self::ToolCall(tool_call) => tool_call.focus_handle.clone(),
+ Self::Elicitation { focus_handle } => focus_handle.clone(),
Self::CompletedPlan | Self::ContextCompaction => cx.focus_handle(),
}
}
@@ -693,11 +710,12 @@ mod tests {
use agent_client_protocol::schema::v1 as acp;
use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
use editor::RowInfo;
+ use feature_flags::{AcpBetaFeatureFlag, FeatureFlag as _, FeatureFlagAppExt as _};
use fs::FakeFs;
use gpui::{AppContext as _, TestAppContext};
use parking_lot::RwLock;
- use crate::entry_view_state::EntryViewState;
+ use crate::entry_view_state::{Entry, EntryViewState};
use crate::message_editor::SessionCapabilities;
use multi_buffer::MultiBufferRow;
use pretty_assertions::assert_matches;
@@ -829,9 +847,90 @@ mod tests {
);
}
+ #[gpui::test]
+ async fn test_hidden_elicitation_preserves_entry_index(cx: &mut TestAppContext) {
+ init_test(cx);
+ cx.update(|cx| {
+ cx.update_flags(false, vec![AcpBetaFeatureFlag::NAME.to_string()]);
+ });
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree("/project", json!({})).await;
+ let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
+
+ let (multi_workspace, cx) =
+ cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
+ let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
+
+ let connection = Rc::new(StubAgentConnection::new());
+ let thread = cx
+ .update(|_, cx| {
+ connection.clone().new_session(
+ project.clone(),
+ PathList::new(&[Path::new(path!("/project"))]),
+ cx,
+ )
+ })
+ .await
+ .unwrap();
+ let session_id = thread.update(cx, |thread, _| thread.session_id().clone());
+
+ let _response_task = thread.update(cx, |thread, cx| {
+ thread
+ .request_elicitation(
+ acp::CreateElicitationRequest::new(
+ acp::ElicitationFormMode::new(
+ acp::ElicitationSessionScope::new(session_id.clone()),
+ acp::ElicitationSchema::new().string("name", true),
+ ),
+ "Provide a name",
+ ),
+ cx,
+ )
+ .unwrap()
+ });
+ cx.update(|_, cx| {
+ connection.send_update(
+ session_id,
+ acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
+ acp::ContentBlock::Text(acp::TextContent::new("hello")),
+ )),
+ cx,
+ );
+ cx.update_flags(false, vec![]);
+ });
+
+ let view_state = cx.new(|_cx| {
+ EntryViewState::new(
+ workspace.downgrade(),
+ project.downgrade(),
+ None,
+ Arc::new(RwLock::new(SessionCapabilities::default())),
+ "Test Agent".into(),
+ )
+ });
+
+ view_state.update_in(cx, |view_state, window, cx| {
+ view_state.sync_entry(0, &thread, window, cx);
+ view_state.sync_entry(1, &thread, window, cx);
+ });
+
+ view_state.read_with(cx, |view_state, _cx| {
+ assert!(matches!(
+ view_state.entry(0),
+ Some(Entry::Elicitation { .. })
+ ));
+ assert!(matches!(
+ view_state.entry(1),
+ Some(Entry::AssistantMessage(_))
+ ));
+ });
+ }
+
fn init_test(cx: &mut TestAppContext) {
cx.update(|cx| {
- let settings_store = SettingsStore::test(cx);
+ let mut settings_store = SettingsStore::test(cx);
+ settings_store.register_setting::<feature_flags::FeatureFlagsSettings>();
cx.set_global(settings_store);
theme_settings::init(theme::LoadThemes::JustBase, cx);
release_channel::init(semver::Version::new(0, 0, 0), cx);