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