connection.rs

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