connection.rs

  1use crate::AcpThread;
  2use agent_client_protocol::{self as acp};
  3use anyhow::Result;
  4use collections::IndexMap;
  5use gpui::{Entity, SharedString, Task};
  6use language_model::LanguageModelProviderId;
  7use project::Project;
  8use serde::{Deserialize, Serialize};
  9use std::{any::Any, error::Error, fmt, path::Path, rc::Rc, sync::Arc};
 10use ui::{App, IconName};
 11use uuid::Uuid;
 12
 13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
 14pub struct UserMessageId(Arc<str>);
 15
 16impl UserMessageId {
 17    pub fn new() -> Self {
 18        Self(Uuid::new_v4().to_string().into())
 19    }
 20}
 21
 22pub trait AgentConnection {
 23    fn new_thread(
 24        self: Rc<Self>,
 25        project: Entity<Project>,
 26        cwd: &Path,
 27        cx: &mut App,
 28    ) -> Task<Result<Entity<AcpThread>>>;
 29
 30    fn auth_methods(&self) -> &[acp::AuthMethod];
 31
 32    fn authenticate(&self, method: acp::AuthMethodId, cx: &mut App) -> Task<Result<()>>;
 33
 34    fn prompt(
 35        &self,
 36        user_message_id: Option<UserMessageId>,
 37        params: acp::PromptRequest,
 38        cx: &mut App,
 39    ) -> Task<Result<acp::PromptResponse>>;
 40
 41    fn resume(
 42        &self,
 43        _session_id: &acp::SessionId,
 44        _cx: &App,
 45    ) -> Option<Rc<dyn AgentSessionResume>> {
 46        None
 47    }
 48
 49    fn cancel(&self, session_id: &acp::SessionId, cx: &mut App);
 50
 51    fn truncate(
 52        &self,
 53        _session_id: &acp::SessionId,
 54        _cx: &App,
 55    ) -> Option<Rc<dyn AgentSessionTruncate>> {
 56        None
 57    }
 58
 59    fn set_title(
 60        &self,
 61        _session_id: &acp::SessionId,
 62        _cx: &App,
 63    ) -> Option<Rc<dyn AgentSessionSetTitle>> {
 64        None
 65    }
 66
 67    /// Returns this agent as an [Rc<dyn ModelSelector>] if the model selection capability is supported.
 68    ///
 69    /// If the agent does not support model selection, returns [None].
 70    /// This allows sharing the selector in UI components.
 71    fn model_selector(&self) -> Option<Rc<dyn AgentModelSelector>> {
 72        None
 73    }
 74
 75    fn telemetry(&self) -> Option<Rc<dyn AgentTelemetry>> {
 76        None
 77    }
 78    fn into_any(self: Rc<Self>) -> Rc<dyn Any>;
 79}
 80
 81impl dyn AgentConnection {
 82    pub fn downcast<T: 'static + AgentConnection + Sized>(self: Rc<Self>) -> Option<Rc<T>> {
 83        self.into_any().downcast().ok()
 84    }
 85}
 86
 87pub trait AgentSessionTruncate {
 88    fn run(&self, message_id: UserMessageId, cx: &mut App) -> Task<Result<()>>;
 89}
 90
 91pub trait AgentSessionResume {
 92    fn run(&self, cx: &mut App) -> Task<Result<acp::PromptResponse>>;
 93}
 94
 95pub trait AgentSessionSetTitle {
 96    fn run(&self, title: SharedString, cx: &mut App) -> Task<Result<()>>;
 97}
 98
 99pub trait AgentTelemetry {
100    /// The name of the agent used for telemetry.
101    fn agent_name(&self) -> String;
102
103    /// A representation of the current thread state that can be serialized for
104    /// storage with telemetry events.
105    fn thread_data(
106        &self,
107        session_id: &acp::SessionId,
108        cx: &mut App,
109    ) -> Task<Result<serde_json::Value>>;
110}
111
112#[derive(Debug)]
113pub struct AuthRequired {
114    pub description: Option<String>,
115    pub provider_id: Option<LanguageModelProviderId>,
116}
117
118impl AuthRequired {
119    pub fn new() -> Self {
120        Self {
121            description: None,
122            provider_id: None,
123        }
124    }
125
126    pub fn with_description(mut self, description: String) -> Self {
127        self.description = Some(description);
128        self
129    }
130
131    pub fn with_language_model_provider(mut self, provider_id: LanguageModelProviderId) -> Self {
132        self.provider_id = Some(provider_id);
133        self
134    }
135}
136
137impl Error for AuthRequired {}
138impl fmt::Display for AuthRequired {
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        write!(f, "Authentication required")
141    }
142}
143
144/// Trait for agents that support listing, selecting, and querying language models.
145///
146/// This is an optional capability; agents indicate support via [AgentConnection::model_selector].
147pub trait AgentModelSelector: 'static {
148    /// Lists all available language models for this agent.
149    ///
150    /// # Parameters
151    /// - `cx`: The GPUI app context for async operations and global access.
152    ///
153    /// # Returns
154    /// A task resolving to the list of models or an error (e.g., if no models are configured).
155    fn list_models(&self, cx: &mut App) -> Task<Result<AgentModelList>>;
156
157    /// Selects a model for a specific session (thread).
158    ///
159    /// This sets the default model for future interactions in the session.
160    /// If the session doesn't exist or the model is invalid, it returns an error.
161    ///
162    /// # Parameters
163    /// - `session_id`: The ID of the session (thread) to apply the model to.
164    /// - `model`: The model to select (should be one from [list_models]).
165    /// - `cx`: The GPUI app context.
166    ///
167    /// # Returns
168    /// A task resolving to `Ok(())` on success or an error.
169    fn select_model(
170        &self,
171        session_id: acp::SessionId,
172        model_id: AgentModelId,
173        cx: &mut App,
174    ) -> Task<Result<()>>;
175
176    /// Retrieves the currently selected model for a specific session (thread).
177    ///
178    /// # Parameters
179    /// - `session_id`: The ID of the session (thread) to query.
180    /// - `cx`: The GPUI app context.
181    ///
182    /// # Returns
183    /// A task resolving to the selected model (always set) or an error (e.g., session not found).
184    fn selected_model(
185        &self,
186        session_id: &acp::SessionId,
187        cx: &mut App,
188    ) -> Task<Result<AgentModelInfo>>;
189
190    /// Whenever the model list is updated the receiver will be notified.
191    fn watch(&self, cx: &mut App) -> watch::Receiver<()>;
192}
193
194#[derive(Debug, Clone, PartialEq, Eq, Hash)]
195pub struct AgentModelId(pub SharedString);
196
197impl std::ops::Deref for AgentModelId {
198    type Target = SharedString;
199
200    fn deref(&self) -> &Self::Target {
201        &self.0
202    }
203}
204
205impl fmt::Display for AgentModelId {
206    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207        self.0.fmt(f)
208    }
209}
210
211#[derive(Debug, Clone, PartialEq, Eq)]
212pub struct AgentModelInfo {
213    pub id: AgentModelId,
214    pub name: SharedString,
215    pub icon: Option<IconName>,
216}
217
218#[derive(Debug, Clone, PartialEq, Eq, Hash)]
219pub struct AgentModelGroupName(pub SharedString);
220
221#[derive(Debug, Clone)]
222pub enum AgentModelList {
223    Flat(Vec<AgentModelInfo>),
224    Grouped(IndexMap<AgentModelGroupName, Vec<AgentModelInfo>>),
225}
226
227impl AgentModelList {
228    pub fn is_empty(&self) -> bool {
229        match self {
230            AgentModelList::Flat(models) => models.is_empty(),
231            AgentModelList::Grouped(groups) => groups.is_empty(),
232        }
233    }
234
235    pub fn len(&self) -> usize {
236        match self {
237            AgentModelList::Flat(models) => models.len(),
238            AgentModelList::Grouped(groups) => groups.values().len(),
239        }
240    }
241}
242
243#[cfg(feature = "test-support")]
244mod test_support {
245    use std::sync::Arc;
246
247    use action_log::ActionLog;
248    use collections::HashMap;
249    use futures::{channel::oneshot, future::try_join_all};
250    use gpui::{AppContext as _, WeakEntity};
251    use parking_lot::Mutex;
252
253    use super::*;
254
255    #[derive(Clone, Default)]
256    pub struct StubAgentConnection {
257        sessions: Arc<Mutex<HashMap<acp::SessionId, Session>>>,
258        permission_requests: HashMap<acp::ToolCallId, Vec<acp::PermissionOption>>,
259        next_prompt_updates: Arc<Mutex<Vec<acp::SessionUpdate>>>,
260    }
261
262    struct Session {
263        thread: WeakEntity<AcpThread>,
264        response_tx: Option<oneshot::Sender<acp::StopReason>>,
265    }
266
267    impl StubAgentConnection {
268        pub fn new() -> Self {
269            Self {
270                next_prompt_updates: Default::default(),
271                permission_requests: HashMap::default(),
272                sessions: Arc::default(),
273            }
274        }
275
276        pub fn set_next_prompt_updates(&self, updates: Vec<acp::SessionUpdate>) {
277            *self.next_prompt_updates.lock() = updates;
278        }
279
280        pub fn with_permission_requests(
281            mut self,
282            permission_requests: HashMap<acp::ToolCallId, Vec<acp::PermissionOption>>,
283        ) -> Self {
284            self.permission_requests = permission_requests;
285            self
286        }
287
288        pub fn send_update(
289            &self,
290            session_id: acp::SessionId,
291            update: acp::SessionUpdate,
292            cx: &mut App,
293        ) {
294            assert!(
295                self.next_prompt_updates.lock().is_empty(),
296                "Use either send_update or set_next_prompt_updates"
297            );
298
299            self.sessions
300                .lock()
301                .get(&session_id)
302                .unwrap()
303                .thread
304                .update(cx, |thread, cx| {
305                    thread.handle_session_update(update, cx).unwrap();
306                })
307                .unwrap();
308        }
309
310        pub fn end_turn(&self, session_id: acp::SessionId, stop_reason: acp::StopReason) {
311            self.sessions
312                .lock()
313                .get_mut(&session_id)
314                .unwrap()
315                .response_tx
316                .take()
317                .expect("No pending turn")
318                .send(stop_reason)
319                .unwrap();
320        }
321    }
322
323    impl AgentConnection for StubAgentConnection {
324        fn auth_methods(&self) -> &[acp::AuthMethod] {
325            &[]
326        }
327
328        fn new_thread(
329            self: Rc<Self>,
330            project: Entity<Project>,
331            _cwd: &Path,
332            cx: &mut gpui::App,
333        ) -> Task<gpui::Result<Entity<AcpThread>>> {
334            let session_id = acp::SessionId(self.sessions.lock().len().to_string().into());
335            let action_log = cx.new(|_| ActionLog::new(project.clone()));
336            let thread = cx.new(|cx| {
337                AcpThread::new(
338                    "Test",
339                    self.clone(),
340                    project,
341                    action_log,
342                    session_id.clone(),
343                    watch::Receiver::constant(acp::PromptCapabilities {
344                        image: true,
345                        audio: true,
346                        embedded_context: true,
347                    }),
348                    cx,
349                )
350            });
351            self.sessions.lock().insert(
352                session_id,
353                Session {
354                    thread: thread.downgrade(),
355                    response_tx: None,
356                },
357            );
358            Task::ready(Ok(thread))
359        }
360
361        fn authenticate(
362            &self,
363            _method_id: acp::AuthMethodId,
364            _cx: &mut App,
365        ) -> Task<gpui::Result<()>> {
366            unimplemented!()
367        }
368
369        fn prompt(
370            &self,
371            _id: Option<UserMessageId>,
372            params: acp::PromptRequest,
373            cx: &mut App,
374        ) -> Task<gpui::Result<acp::PromptResponse>> {
375            let mut sessions = self.sessions.lock();
376            let Session {
377                thread,
378                response_tx,
379            } = sessions.get_mut(&params.session_id).unwrap();
380            let mut tasks = vec![];
381            if self.next_prompt_updates.lock().is_empty() {
382                let (tx, rx) = oneshot::channel();
383                response_tx.replace(tx);
384                cx.spawn(async move |_| {
385                    let stop_reason = rx.await?;
386                    Ok(acp::PromptResponse { stop_reason })
387                })
388            } else {
389                for update in self.next_prompt_updates.lock().drain(..) {
390                    let thread = thread.clone();
391                    let update = update.clone();
392                    let permission_request = if let acp::SessionUpdate::ToolCall(tool_call) =
393                        &update
394                        && let Some(options) = self.permission_requests.get(&tool_call.id)
395                    {
396                        Some((tool_call.clone(), options.clone()))
397                    } else {
398                        None
399                    };
400                    let task = cx.spawn(async move |cx| {
401                        if let Some((tool_call, options)) = permission_request {
402                            thread
403                                .update(cx, |thread, cx| {
404                                    thread.request_tool_call_authorization(
405                                        tool_call.clone().into(),
406                                        options.clone(),
407                                        cx,
408                                    )
409                                })??
410                                .await;
411                        }
412                        thread.update(cx, |thread, cx| {
413                            thread.handle_session_update(update.clone(), cx).unwrap();
414                        })?;
415                        anyhow::Ok(())
416                    });
417                    tasks.push(task);
418                }
419
420                cx.spawn(async move |_| {
421                    try_join_all(tasks).await?;
422                    Ok(acp::PromptResponse {
423                        stop_reason: acp::StopReason::EndTurn,
424                    })
425                })
426            }
427        }
428
429        fn cancel(&self, session_id: &acp::SessionId, _cx: &mut App) {
430            if let Some(end_turn_tx) = self
431                .sessions
432                .lock()
433                .get_mut(session_id)
434                .unwrap()
435                .response_tx
436                .take()
437            {
438                end_turn_tx.send(acp::StopReason::Cancelled).unwrap();
439            }
440        }
441
442        fn truncate(
443            &self,
444            _session_id: &agent_client_protocol::SessionId,
445            _cx: &App,
446        ) -> Option<Rc<dyn AgentSessionTruncate>> {
447            Some(Rc::new(StubAgentSessionEditor))
448        }
449
450        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
451            self
452        }
453    }
454
455    struct StubAgentSessionEditor;
456
457    impl AgentSessionTruncate for StubAgentSessionEditor {
458        fn run(&self, _: UserMessageId, _: &mut App) -> Task<Result<()>> {
459            Task::ready(Ok(()))
460        }
461    }
462}
463
464#[cfg(feature = "test-support")]
465pub use test_support::*;