connection.rs

  1use crate::AcpThread;
  2use agent_client_protocol::{self as acp};
  3use anyhow::Result;
  4use chrono::{DateTime, Utc};
  5use collections::IndexMap;
  6use gpui::{Entity, SharedString, Task};
  7use language_model::LanguageModelProviderId;
  8use project::Project;
  9use serde::{Deserialize, Serialize};
 10use std::{
 11    any::Any,
 12    error::Error,
 13    fmt,
 14    path::{Path, PathBuf},
 15    rc::Rc,
 16    sync::Arc,
 17};
 18use ui::{App, IconName};
 19use uuid::Uuid;
 20
 21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
 22pub struct UserMessageId(Arc<str>);
 23
 24impl UserMessageId {
 25    pub fn new() -> Self {
 26        Self(Uuid::new_v4().to_string().into())
 27    }
 28}
 29
 30pub trait AgentConnection {
 31    fn telemetry_id(&self) -> SharedString;
 32
 33    fn new_thread(
 34        self: Rc<Self>,
 35        project: Entity<Project>,
 36        cwd: &Path,
 37        cx: &mut App,
 38    ) -> Task<Result<Entity<AcpThread>>>;
 39
 40    fn auth_methods(&self) -> &[acp::AuthMethod];
 41
 42    fn authenticate(&self, method: acp::AuthMethodId, cx: &mut App) -> Task<Result<()>>;
 43
 44    fn prompt(
 45        &self,
 46        user_message_id: Option<UserMessageId>,
 47        params: acp::PromptRequest,
 48        cx: &mut App,
 49    ) -> Task<Result<acp::PromptResponse>>;
 50
 51    fn resume(
 52        &self,
 53        _session_id: &acp::SessionId,
 54        _cx: &App,
 55    ) -> Option<Rc<dyn AgentSessionResume>> {
 56        None
 57    }
 58
 59    fn cancel(&self, session_id: &acp::SessionId, cx: &mut App);
 60
 61    fn truncate(
 62        &self,
 63        _session_id: &acp::SessionId,
 64        _cx: &App,
 65    ) -> Option<Rc<dyn AgentSessionTruncate>> {
 66        None
 67    }
 68
 69    fn set_title(
 70        &self,
 71        _session_id: &acp::SessionId,
 72        _cx: &App,
 73    ) -> Option<Rc<dyn AgentSessionSetTitle>> {
 74        None
 75    }
 76
 77    /// Returns this agent as an [Rc<dyn ModelSelector>] if the model selection capability is supported.
 78    ///
 79    /// If the agent does not support model selection, returns [None].
 80    /// This allows sharing the selector in UI components.
 81    fn model_selector(&self, _session_id: &acp::SessionId) -> Option<Rc<dyn AgentModelSelector>> {
 82        None
 83    }
 84
 85    fn telemetry(&self) -> Option<Rc<dyn AgentTelemetry>> {
 86        None
 87    }
 88
 89    fn session_modes(
 90        &self,
 91        _session_id: &acp::SessionId,
 92        _cx: &App,
 93    ) -> Option<Rc<dyn AgentSessionModes>> {
 94        None
 95    }
 96
 97    fn session_config_options(
 98        &self,
 99        _session_id: &acp::SessionId,
100        _cx: &App,
101    ) -> Option<Rc<dyn AgentSessionConfigOptions>> {
102        None
103    }
104
105    fn session_list(&self, _cx: &mut App) -> Option<Rc<dyn AgentSessionList>> {
106        None
107    }
108
109    fn into_any(self: Rc<Self>) -> Rc<dyn Any>;
110}
111
112impl dyn AgentConnection {
113    pub fn downcast<T: 'static + AgentConnection + Sized>(self: Rc<Self>) -> Option<Rc<T>> {
114        self.into_any().downcast().ok()
115    }
116}
117
118pub trait AgentSessionTruncate {
119    fn run(&self, message_id: UserMessageId, cx: &mut App) -> Task<Result<()>>;
120}
121
122pub trait AgentSessionResume {
123    fn run(&self, cx: &mut App) -> Task<Result<acp::PromptResponse>>;
124}
125
126pub trait AgentSessionSetTitle {
127    fn run(&self, title: SharedString, cx: &mut App) -> Task<Result<()>>;
128}
129
130pub trait AgentTelemetry {
131    /// A representation of the current thread state that can be serialized for
132    /// storage with telemetry events.
133    fn thread_data(
134        &self,
135        session_id: &acp::SessionId,
136        cx: &mut App,
137    ) -> Task<Result<serde_json::Value>>;
138}
139
140pub trait AgentSessionModes {
141    fn current_mode(&self) -> acp::SessionModeId;
142
143    fn all_modes(&self) -> Vec<acp::SessionMode>;
144
145    fn set_mode(&self, mode: acp::SessionModeId, cx: &mut App) -> Task<Result<()>>;
146}
147
148pub trait AgentSessionConfigOptions {
149    /// Get all current config options with their state
150    fn config_options(&self) -> Vec<acp::SessionConfigOption>;
151
152    /// Set a config option value
153    /// Returns the full updated list of config options
154    fn set_config_option(
155        &self,
156        config_id: acp::SessionConfigId,
157        value: acp::SessionConfigValueId,
158        cx: &mut App,
159    ) -> Task<Result<Vec<acp::SessionConfigOption>>>;
160
161    /// Whenever the config options are updated the receiver will be notified.
162    /// Optional for agents that don't update their config options dynamically.
163    fn watch(&self, _cx: &mut App) -> Option<watch::Receiver<()>> {
164        None
165    }
166}
167
168#[derive(Debug, Clone, Default)]
169pub struct AgentSessionListRequest {
170    pub cwd: Option<PathBuf>,
171    pub cursor: Option<String>,
172    pub meta: Option<acp::Meta>,
173}
174
175#[derive(Debug, Clone)]
176pub struct AgentSessionListResponse {
177    pub sessions: Vec<AgentSessionInfo>,
178    pub next_cursor: Option<String>,
179    pub meta: Option<acp::Meta>,
180}
181
182impl AgentSessionListResponse {
183    pub fn new(sessions: Vec<AgentSessionInfo>) -> Self {
184        Self {
185            sessions,
186            next_cursor: None,
187            meta: None,
188        }
189    }
190}
191
192#[derive(Debug, Clone, PartialEq)]
193pub struct AgentSessionInfo {
194    pub session_id: acp::SessionId,
195    pub cwd: Option<PathBuf>,
196    pub title: Option<SharedString>,
197    pub updated_at: Option<DateTime<Utc>>,
198    pub meta: Option<acp::Meta>,
199}
200
201impl AgentSessionInfo {
202    pub fn new(session_id: impl Into<acp::SessionId>) -> Self {
203        Self {
204            session_id: session_id.into(),
205            cwd: None,
206            title: None,
207            updated_at: None,
208            meta: None,
209        }
210    }
211}
212
213pub trait AgentSessionList {
214    fn list_sessions(
215        &self,
216        request: AgentSessionListRequest,
217        cx: &mut App,
218    ) -> Task<Result<AgentSessionListResponse>>;
219
220    fn delete_session(&self, _session_id: &acp::SessionId, _cx: &mut App) -> Task<Result<()>> {
221        Task::ready(Ok(()))
222    }
223
224    fn delete_sessions(&self, _cx: &mut App) -> Task<Result<()>> {
225        Task::ready(Ok(()))
226    }
227
228    fn watch(&self, _cx: &mut App) -> Option<watch::Receiver<()>> {
229        None
230    }
231
232    fn into_any(self: Rc<Self>) -> Rc<dyn Any>;
233}
234
235impl dyn AgentSessionList {
236    pub fn downcast<T: 'static + AgentSessionList + Sized>(self: Rc<Self>) -> Option<Rc<T>> {
237        self.into_any().downcast().ok()
238    }
239}
240
241#[derive(Debug)]
242pub struct AuthRequired {
243    pub description: Option<String>,
244    pub provider_id: Option<LanguageModelProviderId>,
245}
246
247impl AuthRequired {
248    pub fn new() -> Self {
249        Self {
250            description: None,
251            provider_id: None,
252        }
253    }
254
255    pub fn with_description(mut self, description: String) -> Self {
256        self.description = Some(description);
257        self
258    }
259
260    pub fn with_language_model_provider(mut self, provider_id: LanguageModelProviderId) -> Self {
261        self.provider_id = Some(provider_id);
262        self
263    }
264}
265
266impl Error for AuthRequired {}
267impl fmt::Display for AuthRequired {
268    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269        write!(f, "Authentication required")
270    }
271}
272
273/// Trait for agents that support listing, selecting, and querying language models.
274///
275/// This is an optional capability; agents indicate support via [AgentConnection::model_selector].
276pub trait AgentModelSelector: 'static {
277    /// Lists all available language models for this agent.
278    ///
279    /// # Parameters
280    /// - `cx`: The GPUI app context for async operations and global access.
281    ///
282    /// # Returns
283    /// A task resolving to the list of models or an error (e.g., if no models are configured).
284    fn list_models(&self, cx: &mut App) -> Task<Result<AgentModelList>>;
285
286    /// Selects a model for a specific session (thread).
287    ///
288    /// This sets the default model for future interactions in the session.
289    /// If the session doesn't exist or the model is invalid, it returns an error.
290    ///
291    /// # Parameters
292    /// - `model`: The model to select (should be one from [list_models]).
293    /// - `cx`: The GPUI app context.
294    ///
295    /// # Returns
296    /// A task resolving to `Ok(())` on success or an error.
297    fn select_model(&self, model_id: acp::ModelId, cx: &mut App) -> Task<Result<()>>;
298
299    /// Retrieves the currently selected model for a specific session (thread).
300    ///
301    /// # Parameters
302    /// - `cx`: The GPUI app context.
303    ///
304    /// # Returns
305    /// A task resolving to the selected model (always set) or an error (e.g., session not found).
306    fn selected_model(&self, cx: &mut App) -> Task<Result<AgentModelInfo>>;
307
308    /// Whenever the model list is updated the receiver will be notified.
309    /// Optional for agents that don't update their model list.
310    fn watch(&self, _cx: &mut App) -> Option<watch::Receiver<()>> {
311        None
312    }
313
314    /// Returns whether the model picker should render a footer.
315    fn should_render_footer(&self) -> bool {
316        false
317    }
318}
319
320/// Icon for a model in the model selector.
321#[derive(Debug, Clone, PartialEq, Eq)]
322pub enum AgentModelIcon {
323    /// A built-in icon from Zed's icon set.
324    Named(IconName),
325    /// Path to a custom SVG icon file.
326    Path(SharedString),
327}
328
329#[derive(Debug, Clone, PartialEq, Eq)]
330pub struct AgentModelInfo {
331    pub id: acp::ModelId,
332    pub name: SharedString,
333    pub description: Option<SharedString>,
334    pub icon: Option<AgentModelIcon>,
335}
336
337impl From<acp::ModelInfo> for AgentModelInfo {
338    fn from(info: acp::ModelInfo) -> Self {
339        Self {
340            id: info.model_id,
341            name: info.name.into(),
342            description: info.description.map(|desc| desc.into()),
343            icon: None,
344        }
345    }
346}
347
348#[derive(Debug, Clone, PartialEq, Eq, Hash)]
349pub struct AgentModelGroupName(pub SharedString);
350
351#[derive(Debug, Clone)]
352pub enum AgentModelList {
353    Flat(Vec<AgentModelInfo>),
354    Grouped(IndexMap<AgentModelGroupName, Vec<AgentModelInfo>>),
355}
356
357impl AgentModelList {
358    pub fn is_empty(&self) -> bool {
359        match self {
360            AgentModelList::Flat(models) => models.is_empty(),
361            AgentModelList::Grouped(groups) => groups.is_empty(),
362        }
363    }
364
365    pub fn is_flat(&self) -> bool {
366        matches!(self, AgentModelList::Flat(_))
367    }
368}
369
370#[cfg(feature = "test-support")]
371mod test_support {
372    //! Test-only stubs and helpers for acp_thread.
373    //!
374    //! This module is gated by the `test-support` feature and is not included
375    //! in production builds. It provides:
376    //! - `StubAgentConnection` for mocking agent connections in tests
377    //! - `create_test_png_base64` for generating test images
378
379    use std::sync::Arc;
380
381    use action_log::ActionLog;
382    use collections::HashMap;
383    use futures::{channel::oneshot, future::try_join_all};
384    use gpui::{AppContext as _, WeakEntity};
385    use parking_lot::Mutex;
386
387    use super::*;
388
389    /// Creates a PNG image encoded as base64 for testing.
390    ///
391    /// Generates a solid-color PNG of the specified dimensions and returns
392    /// it as a base64-encoded string suitable for use in `ImageContent`.
393    pub fn create_test_png_base64(width: u32, height: u32, color: [u8; 4]) -> String {
394        use image::ImageEncoder as _;
395
396        let mut png_data = Vec::new();
397        {
398            let encoder = image::codecs::png::PngEncoder::new(&mut png_data);
399            let mut pixels = Vec::with_capacity((width * height * 4) as usize);
400            for _ in 0..(width * height) {
401                pixels.extend_from_slice(&color);
402            }
403            encoder
404                .write_image(&pixels, width, height, image::ExtendedColorType::Rgba8)
405                .expect("Failed to encode PNG");
406        }
407
408        use image::EncodableLayout as _;
409        base64::Engine::encode(
410            &base64::engine::general_purpose::STANDARD,
411            png_data.as_bytes(),
412        )
413    }
414
415    #[derive(Clone, Default)]
416    pub struct StubAgentConnection {
417        sessions: Arc<Mutex<HashMap<acp::SessionId, Session>>>,
418        permission_requests: HashMap<acp::ToolCallId, Vec<acp::PermissionOption>>,
419        next_prompt_updates: Arc<Mutex<Vec<acp::SessionUpdate>>>,
420    }
421
422    struct Session {
423        thread: WeakEntity<AcpThread>,
424        response_tx: Option<oneshot::Sender<acp::StopReason>>,
425    }
426
427    impl StubAgentConnection {
428        pub fn new() -> Self {
429            Self {
430                next_prompt_updates: Default::default(),
431                permission_requests: HashMap::default(),
432                sessions: Arc::default(),
433            }
434        }
435
436        pub fn set_next_prompt_updates(&self, updates: Vec<acp::SessionUpdate>) {
437            *self.next_prompt_updates.lock() = updates;
438        }
439
440        pub fn with_permission_requests(
441            mut self,
442            permission_requests: HashMap<acp::ToolCallId, Vec<acp::PermissionOption>>,
443        ) -> Self {
444            self.permission_requests = permission_requests;
445            self
446        }
447
448        pub fn send_update(
449            &self,
450            session_id: acp::SessionId,
451            update: acp::SessionUpdate,
452            cx: &mut App,
453        ) {
454            assert!(
455                self.next_prompt_updates.lock().is_empty(),
456                "Use either send_update or set_next_prompt_updates"
457            );
458
459            self.sessions
460                .lock()
461                .get(&session_id)
462                .unwrap()
463                .thread
464                .update(cx, |thread, cx| {
465                    thread.handle_session_update(update, cx).unwrap();
466                })
467                .unwrap();
468        }
469
470        pub fn end_turn(&self, session_id: acp::SessionId, stop_reason: acp::StopReason) {
471            self.sessions
472                .lock()
473                .get_mut(&session_id)
474                .unwrap()
475                .response_tx
476                .take()
477                .expect("No pending turn")
478                .send(stop_reason)
479                .unwrap();
480        }
481    }
482
483    impl AgentConnection for StubAgentConnection {
484        fn telemetry_id(&self) -> SharedString {
485            "stub".into()
486        }
487
488        fn auth_methods(&self) -> &[acp::AuthMethod] {
489            &[]
490        }
491
492        fn model_selector(
493            &self,
494            _session_id: &acp::SessionId,
495        ) -> Option<Rc<dyn AgentModelSelector>> {
496            Some(self.model_selector_impl())
497        }
498
499        fn new_thread(
500            self: Rc<Self>,
501            project: Entity<Project>,
502            _cwd: &Path,
503            cx: &mut gpui::App,
504        ) -> Task<gpui::Result<Entity<AcpThread>>> {
505            let session_id = acp::SessionId::new(self.sessions.lock().len().to_string());
506            let action_log = cx.new(|_| ActionLog::new(project.clone()));
507            let thread = cx.new(|cx| {
508                AcpThread::new(
509                    "Test",
510                    self.clone(),
511                    project,
512                    action_log,
513                    session_id.clone(),
514                    watch::Receiver::constant(
515                        acp::PromptCapabilities::new()
516                            .image(true)
517                            .audio(true)
518                            .embedded_context(true),
519                    ),
520                    cx,
521                )
522            });
523            self.sessions.lock().insert(
524                session_id,
525                Session {
526                    thread: thread.downgrade(),
527                    response_tx: None,
528                },
529            );
530            Task::ready(Ok(thread))
531        }
532
533        fn authenticate(
534            &self,
535            _method_id: acp::AuthMethodId,
536            _cx: &mut App,
537        ) -> Task<gpui::Result<()>> {
538            unimplemented!()
539        }
540
541        fn prompt(
542            &self,
543            _id: Option<UserMessageId>,
544            params: acp::PromptRequest,
545            cx: &mut App,
546        ) -> Task<gpui::Result<acp::PromptResponse>> {
547            let mut sessions = self.sessions.lock();
548            let Session {
549                thread,
550                response_tx,
551            } = sessions.get_mut(&params.session_id).unwrap();
552            let mut tasks = vec![];
553            if self.next_prompt_updates.lock().is_empty() {
554                let (tx, rx) = oneshot::channel();
555                response_tx.replace(tx);
556                cx.spawn(async move |_| {
557                    let stop_reason = rx.await?;
558                    Ok(acp::PromptResponse::new(stop_reason))
559                })
560            } else {
561                for update in self.next_prompt_updates.lock().drain(..) {
562                    let thread = thread.clone();
563                    let update = update.clone();
564                    let permission_request = if let acp::SessionUpdate::ToolCall(tool_call) =
565                        &update
566                        && let Some(options) = self.permission_requests.get(&tool_call.tool_call_id)
567                    {
568                        Some((tool_call.clone(), options.clone()))
569                    } else {
570                        None
571                    };
572                    let task = cx.spawn(async move |cx| {
573                        if let Some((tool_call, options)) = permission_request {
574                            thread
575                                .update(cx, |thread, cx| {
576                                    thread.request_tool_call_authorization(
577                                        tool_call.clone().into(),
578                                        options.clone(),
579                                        false,
580                                        cx,
581                                    )
582                                })??
583                                .await;
584                        }
585                        thread.update(cx, |thread, cx| {
586                            thread.handle_session_update(update.clone(), cx).unwrap();
587                        })?;
588                        anyhow::Ok(())
589                    });
590                    tasks.push(task);
591                }
592
593                cx.spawn(async move |_| {
594                    try_join_all(tasks).await?;
595                    Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
596                })
597            }
598        }
599
600        fn cancel(&self, session_id: &acp::SessionId, _cx: &mut App) {
601            if let Some(end_turn_tx) = self
602                .sessions
603                .lock()
604                .get_mut(session_id)
605                .unwrap()
606                .response_tx
607                .take()
608            {
609                end_turn_tx.send(acp::StopReason::Cancelled).unwrap();
610            }
611        }
612
613        fn truncate(
614            &self,
615            _session_id: &agent_client_protocol::SessionId,
616            _cx: &App,
617        ) -> Option<Rc<dyn AgentSessionTruncate>> {
618            Some(Rc::new(StubAgentSessionEditor))
619        }
620
621        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
622            self
623        }
624    }
625
626    struct StubAgentSessionEditor;
627
628    impl AgentSessionTruncate for StubAgentSessionEditor {
629        fn run(&self, _: UserMessageId, _: &mut App) -> Task<Result<()>> {
630            Task::ready(Ok(()))
631        }
632    }
633
634    #[derive(Clone)]
635    struct StubModelSelector {
636        selected_model: Arc<Mutex<AgentModelInfo>>,
637    }
638
639    impl StubModelSelector {
640        fn new() -> Self {
641            Self {
642                selected_model: Arc::new(Mutex::new(AgentModelInfo {
643                    id: acp::ModelId::new("visual-test-model"),
644                    name: "Visual Test Model".into(),
645                    description: Some("A stub model for visual testing".into()),
646                    icon: Some(AgentModelIcon::Named(ui::IconName::ZedAssistant)),
647                })),
648            }
649        }
650    }
651
652    impl AgentModelSelector for StubModelSelector {
653        fn list_models(&self, _cx: &mut App) -> Task<Result<AgentModelList>> {
654            let model = self.selected_model.lock().clone();
655            Task::ready(Ok(AgentModelList::Flat(vec![model])))
656        }
657
658        fn select_model(&self, model_id: acp::ModelId, _cx: &mut App) -> Task<Result<()>> {
659            self.selected_model.lock().id = model_id;
660            Task::ready(Ok(()))
661        }
662
663        fn selected_model(&self, _cx: &mut App) -> Task<Result<AgentModelInfo>> {
664            Task::ready(Ok(self.selected_model.lock().clone()))
665        }
666    }
667
668    impl StubAgentConnection {
669        /// Returns a model selector for this stub connection.
670        pub fn model_selector_impl(&self) -> Rc<dyn AgentModelSelector> {
671            Rc::new(StubModelSelector::new())
672        }
673    }
674}
675
676#[cfg(feature = "test-support")]
677pub use test_support::*;