1use acp_thread::{
2 AcpThread, AcpThreadEvent, AgentSessionInfo, AgentThreadEntry, AssistantMessage,
3 AssistantMessageChunk, AuthRequired, LoadError, MentionUri, PermissionOptionChoice,
4 PermissionOptions, RetryStatus, ThreadStatus, ToolCall, ToolCallContent, ToolCallStatus,
5 UserMessageId,
6};
7use acp_thread::{AgentConnection, Plan};
8use action_log::{ActionLog, ActionLogTelemetry};
9use agent::{NativeAgentServer, NativeAgentSessionList, SharedThread, ThreadStore};
10use agent_client_protocol::{self as acp, PromptCapabilities};
11use agent_servers::{AgentServer, AgentServerDelegate};
12use agent_settings::{AgentProfileId, AgentSettings};
13use anyhow::{Result, anyhow};
14use arrayvec::ArrayVec;
15use audio::{Audio, Sound};
16use buffer_diff::BufferDiff;
17use client::zed_urls;
18use collections::{HashMap, HashSet};
19use editor::scroll::Autoscroll;
20use editor::{
21 Editor, EditorEvent, EditorMode, MultiBuffer, PathKey, SelectionEffects, SizingBehavior,
22};
23use feature_flags::{AgentSharingFeatureFlag, AgentV2FeatureFlag, FeatureFlagAppExt as _};
24use file_icons::FileIcons;
25use fs::Fs;
26use futures::FutureExt as _;
27use gpui::{
28 Action, Animation, AnimationExt, AnyView, App, ClickEvent, ClipboardItem, CursorStyle,
29 ElementId, Empty, Entity, FocusHandle, Focusable, Hsla, ListOffset, ListState, ObjectFit,
30 PlatformDisplay, ScrollHandle, SharedString, Subscription, Task, TextStyle, WeakEntity, Window,
31 WindowHandle, div, ease_in_out, img, linear_color_stop, linear_gradient, list, point,
32 pulsating_between,
33};
34use language::Buffer;
35use language_model::LanguageModelRegistry;
36use markdown::{Markdown, MarkdownElement, MarkdownFont, MarkdownStyle};
37use project::{AgentServerStore, ExternalAgentServerName, Project, ProjectEntryId};
38use prompt_store::{PromptId, PromptStore};
39use rope::Point;
40use settings::{NotifyWhenAgentWaiting, Settings as _, SettingsStore};
41use std::cell::RefCell;
42use std::path::Path;
43use std::sync::Arc;
44use std::time::Instant;
45use std::{collections::BTreeMap, rc::Rc, time::Duration};
46use terminal_view::terminal_panel::TerminalPanel;
47use text::{Anchor, ToPoint as _};
48use theme::AgentFontSize;
49use ui::{
50 Callout, CircularProgress, CommonAnimationExt, ContextMenu, ContextMenuEntry, CopyButton,
51 DecoratedIcon, DiffStat, Disclosure, Divider, DividerColor, IconDecoration, IconDecorationKind,
52 KeyBinding, PopoverMenu, PopoverMenuHandle, SpinnerLabel, TintColor, Tooltip, WithScrollbar,
53 prelude::*, right_click_menu,
54};
55use util::{ResultExt, size::format_file_size, time::duration_alt_display};
56use util::{debug_panic, defer};
57use workspace::{
58 CollaboratorId, MultiWorkspace, NewTerminal, Toast, Workspace, notifications::NotificationId,
59};
60use zed_actions::agent::{Chat, ToggleModelSelector};
61use zed_actions::assistant::OpenRulesLibrary;
62
63use super::config_options::ConfigOptionsView;
64use super::entry_view_state::EntryViewState;
65use super::thread_history::AcpThreadHistory;
66use crate::acp::AcpModelSelectorPopover;
67use crate::acp::ModeSelector;
68use crate::acp::entry_view_state::{EntryViewEvent, ViewEvent};
69use crate::acp::message_editor::{MessageEditor, MessageEditorEvent};
70use crate::agent_diff::AgentDiff;
71use crate::profile_selector::{ProfileProvider, ProfileSelector};
72use crate::ui::{AgentNotification, AgentNotificationEvent};
73use crate::{
74 AgentDiffPane, AgentPanel, AllowAlways, AllowOnce, AuthorizeToolCall, ClearMessageQueue,
75 CycleFavoriteModels, CycleModeSelector, CycleThinkingEffort, EditFirstQueuedMessage,
76 ExpandMessageEditor, ExternalAgentInitialContent, Follow, KeepAll, NewThread,
77 OpenAddContextMenu, OpenAgentDiff, OpenHistory, RejectAll, RejectOnce,
78 RemoveFirstQueuedMessage, SelectPermissionGranularity, SendImmediately, SendNextQueuedMessage,
79 ToggleProfileSelector, ToggleThinkingEffortMenu, ToggleThinkingMode,
80};
81
82const STOPWATCH_THRESHOLD: Duration = Duration::from_secs(30);
83const TOKEN_THRESHOLD: u64 = 250;
84
85mod active_thread;
86pub use active_thread::*;
87
88pub struct QueuedMessage {
89 pub content: Vec<acp::ContentBlock>,
90 pub tracked_buffers: Vec<Entity<Buffer>>,
91}
92
93#[derive(Copy, Clone, Debug, PartialEq, Eq)]
94enum ThreadFeedback {
95 Positive,
96 Negative,
97}
98
99#[derive(Debug)]
100pub(crate) enum ThreadError {
101 PaymentRequired,
102 Refusal,
103 AuthenticationRequired(SharedString),
104 Other {
105 message: SharedString,
106 acp_error_code: Option<SharedString>,
107 },
108}
109
110impl ThreadError {
111 fn from_err(error: anyhow::Error, agent_name: &str) -> Self {
112 if error.is::<language_model::PaymentRequiredError>() {
113 Self::PaymentRequired
114 } else if let Some(acp_error) = error.downcast_ref::<acp::Error>()
115 && acp_error.code == acp::ErrorCode::AuthRequired
116 {
117 Self::AuthenticationRequired(acp_error.message.clone().into())
118 } else {
119 let message: SharedString = format!("{:#}", error).into();
120
121 // Extract ACP error code if available
122 let acp_error_code = error
123 .downcast_ref::<acp::Error>()
124 .map(|acp_error| SharedString::from(acp_error.code.to_string()));
125
126 // TODO: we should have Gemini return better errors here.
127 if agent_name == "Gemini CLI"
128 && message.contains("Could not load the default credentials")
129 || message.contains("API key not valid")
130 || message.contains("Request had invalid authentication credentials")
131 {
132 Self::AuthenticationRequired(message)
133 } else {
134 Self::Other {
135 message,
136 acp_error_code,
137 }
138 }
139 }
140 }
141}
142
143impl ProfileProvider for Entity<agent::Thread> {
144 fn profile_id(&self, cx: &App) -> AgentProfileId {
145 self.read(cx).profile().clone()
146 }
147
148 fn set_profile(&self, profile_id: AgentProfileId, cx: &mut App) {
149 self.update(cx, |thread, cx| {
150 // Apply the profile and let the thread swap to its default model.
151 thread.set_profile(profile_id, cx);
152 });
153 }
154
155 fn profiles_supported(&self, cx: &App) -> bool {
156 self.read(cx)
157 .model()
158 .is_some_and(|model| model.supports_tools())
159 }
160}
161
162pub struct AcpServerView {
163 agent: Rc<dyn AgentServer>,
164 agent_server_store: Entity<AgentServerStore>,
165 workspace: WeakEntity<Workspace>,
166 project: Entity<Project>,
167 thread_store: Option<Entity<ThreadStore>>,
168 prompt_store: Option<Entity<PromptStore>>,
169 server_state: ServerState,
170 login: Option<task::SpawnInTerminal>, // is some <=> Active | Unauthenticated
171 history: Entity<AcpThreadHistory>,
172 focus_handle: FocusHandle,
173 notifications: Vec<WindowHandle<AgentNotification>>,
174 notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
175 auth_task: Option<Task<()>>,
176 _subscriptions: Vec<Subscription>,
177}
178
179impl AcpServerView {
180 pub fn active_thread(&self) -> Option<&Entity<AcpThreadView>> {
181 match &self.server_state {
182 ServerState::Connected(connected) => connected.active_view(),
183 _ => None,
184 }
185 }
186
187 pub fn parent_thread(&self, cx: &App) -> Option<Entity<AcpThreadView>> {
188 match &self.server_state {
189 ServerState::Connected(connected) => {
190 let mut current = connected.active_view()?;
191 while let Some(parent_id) = current.read(cx).parent_id.clone() {
192 if let Some(parent) = connected.threads.get(&parent_id) {
193 current = parent;
194 } else {
195 break;
196 }
197 }
198 Some(current.clone())
199 }
200 _ => None,
201 }
202 }
203
204 pub fn thread_view(&self, session_id: &acp::SessionId) -> Option<Entity<AcpThreadView>> {
205 let connected = self.as_connected()?;
206 connected.threads.get(session_id).cloned()
207 }
208
209 pub fn as_connected(&self) -> Option<&ConnectedServerState> {
210 match &self.server_state {
211 ServerState::Connected(connected) => Some(connected),
212 _ => None,
213 }
214 }
215
216 pub fn as_connected_mut(&mut self) -> Option<&mut ConnectedServerState> {
217 match &mut self.server_state {
218 ServerState::Connected(connected) => Some(connected),
219 _ => None,
220 }
221 }
222
223 pub fn navigate_to_session(
224 &mut self,
225 session_id: acp::SessionId,
226 window: &mut Window,
227 cx: &mut Context<Self>,
228 ) {
229 let Some(connected) = self.as_connected_mut() else {
230 return;
231 };
232
233 connected.navigate_to_session(session_id);
234 if let Some(view) = self.active_thread() {
235 view.focus_handle(cx).focus(window, cx);
236 }
237 cx.notify();
238 }
239}
240
241enum ServerState {
242 Loading(Entity<LoadingView>),
243 LoadError(LoadError),
244 Connected(ConnectedServerState),
245}
246
247// current -> Entity
248// hashmap of threads, current becomes session_id
249pub struct ConnectedServerState {
250 auth_state: AuthState,
251 active_id: Option<acp::SessionId>,
252 threads: HashMap<acp::SessionId, Entity<AcpThreadView>>,
253 connection: Rc<dyn AgentConnection>,
254}
255
256enum AuthState {
257 Ok,
258 Unauthenticated {
259 description: Option<Entity<Markdown>>,
260 configuration_view: Option<AnyView>,
261 pending_auth_method: Option<acp::AuthMethodId>,
262 _subscription: Option<Subscription>,
263 },
264}
265
266impl AuthState {
267 pub fn is_ok(&self) -> bool {
268 matches!(self, Self::Ok)
269 }
270}
271
272struct LoadingView {
273 title: SharedString,
274 _load_task: Task<()>,
275 _update_title_task: Task<anyhow::Result<()>>,
276}
277
278impl ConnectedServerState {
279 pub fn active_view(&self) -> Option<&Entity<AcpThreadView>> {
280 self.active_id.as_ref().and_then(|id| self.threads.get(id))
281 }
282
283 pub fn has_thread_error(&self, cx: &App) -> bool {
284 self.active_view()
285 .map_or(false, |view| view.read(cx).thread_error.is_some())
286 }
287
288 pub fn navigate_to_session(&mut self, session_id: acp::SessionId) {
289 if self.threads.contains_key(&session_id) {
290 self.active_id = Some(session_id);
291 }
292 }
293
294 pub fn close_all_sessions(&self, cx: &mut App) -> Task<()> {
295 let tasks = self
296 .threads
297 .keys()
298 .map(|id| self.connection.close_session(id, cx));
299 let task = futures::future::join_all(tasks);
300 cx.background_spawn(async move {
301 task.await;
302 })
303 }
304}
305
306impl AcpServerView {
307 pub fn new(
308 agent: Rc<dyn AgentServer>,
309 resume_thread: Option<AgentSessionInfo>,
310 initial_content: Option<ExternalAgentInitialContent>,
311 workspace: WeakEntity<Workspace>,
312 project: Entity<Project>,
313 thread_store: Option<Entity<ThreadStore>>,
314 prompt_store: Option<Entity<PromptStore>>,
315 history: Entity<AcpThreadHistory>,
316 window: &mut Window,
317 cx: &mut Context<Self>,
318 ) -> Self {
319 let agent_server_store = project.read(cx).agent_server_store().clone();
320 let subscriptions = vec![
321 cx.observe_global_in::<SettingsStore>(window, Self::agent_ui_font_size_changed),
322 cx.observe_global_in::<AgentFontSize>(window, Self::agent_ui_font_size_changed),
323 cx.subscribe_in(
324 &agent_server_store,
325 window,
326 Self::handle_agent_servers_updated,
327 ),
328 ];
329
330 cx.on_release(|this, cx| {
331 if let Some(connected) = this.as_connected() {
332 connected.close_all_sessions(cx).detach();
333 }
334 for window in this.notifications.drain(..) {
335 window
336 .update(cx, |_, window, _| {
337 window.remove_window();
338 })
339 .ok();
340 }
341 })
342 .detach();
343
344 Self {
345 agent: agent.clone(),
346 agent_server_store,
347 workspace,
348 project: project.clone(),
349 thread_store,
350 prompt_store,
351 server_state: Self::initial_state(
352 agent.clone(),
353 resume_thread,
354 project,
355 initial_content,
356 window,
357 cx,
358 ),
359 login: None,
360 notifications: Vec::new(),
361 notification_subscriptions: HashMap::default(),
362 auth_task: None,
363 history,
364 _subscriptions: subscriptions,
365 focus_handle: cx.focus_handle(),
366 }
367 }
368
369 fn set_server_state(&mut self, state: ServerState, cx: &mut Context<Self>) {
370 if let Some(connected) = self.as_connected() {
371 connected.close_all_sessions(cx).detach();
372 }
373
374 self.server_state = state;
375 cx.notify();
376 }
377
378 fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
379 let resume_thread_metadata = self
380 .active_thread()
381 .and_then(|thread| thread.read(cx).resume_thread_metadata.clone());
382
383 let state = Self::initial_state(
384 self.agent.clone(),
385 resume_thread_metadata,
386 self.project.clone(),
387 None,
388 window,
389 cx,
390 );
391 self.set_server_state(state, cx);
392
393 if let Some(view) = self.active_thread() {
394 view.update(cx, |this, cx| {
395 this.message_editor.update(cx, |editor, cx| {
396 editor.set_command_state(
397 this.prompt_capabilities.clone(),
398 this.available_commands.clone(),
399 cx,
400 );
401 });
402 });
403 }
404 cx.notify();
405 }
406
407 fn initial_state(
408 agent: Rc<dyn AgentServer>,
409 resume_thread: Option<AgentSessionInfo>,
410 project: Entity<Project>,
411 initial_content: Option<ExternalAgentInitialContent>,
412 window: &mut Window,
413 cx: &mut Context<Self>,
414 ) -> ServerState {
415 if project.read(cx).is_via_collab()
416 && agent.clone().downcast::<NativeAgentServer>().is_none()
417 {
418 return ServerState::LoadError(LoadError::Other(
419 "External agents are not yet supported in shared projects.".into(),
420 ));
421 }
422 let mut worktrees = project.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
423 // Pick the first non-single-file worktree for the root directory if there are any,
424 // and otherwise the parent of a single-file worktree, falling back to $HOME if there are no visible worktrees.
425 worktrees.sort_by(|l, r| {
426 l.read(cx)
427 .is_single_file()
428 .cmp(&r.read(cx).is_single_file())
429 });
430 let worktree_roots: Vec<Arc<Path>> = worktrees
431 .iter()
432 .filter_map(|worktree| {
433 let worktree = worktree.read(cx);
434 if worktree.is_single_file() {
435 Some(worktree.abs_path().parent()?.into())
436 } else {
437 Some(worktree.abs_path())
438 }
439 })
440 .collect();
441 let root_dir = worktree_roots.first().cloned();
442 let session_cwd = resume_thread
443 .as_ref()
444 .and_then(|resume| {
445 resume
446 .cwd
447 .as_ref()
448 .and_then(|cwd| util::paths::normalize_lexically(cwd).ok())
449 .filter(|cwd| {
450 worktree_roots
451 .iter()
452 .any(|root| cwd.starts_with(root.as_ref()))
453 })
454 .map(|path| path.into())
455 })
456 .or_else(|| root_dir.clone())
457 .unwrap_or_else(|| paths::home_dir().as_path().into());
458
459 let (status_tx, mut status_rx) = watch::channel("Loading…".into());
460 let (new_version_available_tx, mut new_version_available_rx) = watch::channel(None);
461 let delegate = AgentServerDelegate::new(
462 project.read(cx).agent_server_store().clone(),
463 project.clone(),
464 Some(status_tx),
465 Some(new_version_available_tx),
466 );
467
468 let connect_task = agent.connect(root_dir.as_deref(), delegate, cx);
469 let load_task = cx.spawn_in(window, async move |this, cx| {
470 let connection = match connect_task.await {
471 Ok((connection, login)) => {
472 this.update(cx, |this, _| this.login = login).ok();
473 connection
474 }
475 Err(err) => {
476 this.update_in(cx, |this, window, cx| {
477 if err.downcast_ref::<LoadError>().is_some() {
478 this.handle_load_error(err, window, cx);
479 } else if let Some(active) = this.active_thread() {
480 active.update(cx, |active, cx| active.handle_any_thread_error(err, cx));
481 }
482 cx.notify();
483 })
484 .log_err();
485 return;
486 }
487 };
488
489 telemetry::event!("Agent Thread Started", agent = connection.telemetry_id());
490
491 let mut resumed_without_history = false;
492 let result = if let Some(resume) = resume_thread.clone() {
493 cx.update(|_, cx| {
494 if connection.supports_load_session() {
495 connection
496 .clone()
497 .load_session(resume, project.clone(), &session_cwd, cx)
498 } else if connection.supports_resume_session() {
499 resumed_without_history = true;
500 connection
501 .clone()
502 .resume_session(resume, project.clone(), &session_cwd, cx)
503 } else {
504 Task::ready(Err(anyhow!(LoadError::Other(
505 "Loading or resuming sessions is not supported by this agent.".into()
506 ))))
507 }
508 })
509 .log_err()
510 } else {
511 cx.update(|_, cx| {
512 connection
513 .clone()
514 .new_session(project.clone(), session_cwd.as_ref(), cx)
515 })
516 .log_err()
517 };
518
519 let Some(result) = result else {
520 return;
521 };
522
523 let result = match result.await {
524 Err(e) => match e.downcast::<acp_thread::AuthRequired>() {
525 Ok(err) => {
526 cx.update(|window, cx| {
527 Self::handle_auth_required(
528 this,
529 err,
530 agent.name(),
531 connection,
532 window,
533 cx,
534 )
535 })
536 .log_err();
537 return;
538 }
539 Err(err) => Err(err),
540 },
541 Ok(thread) => Ok(thread),
542 };
543
544 this.update_in(cx, |this, window, cx| {
545 match result {
546 Ok(thread) => {
547 let current = this.new_thread_view(
548 None,
549 thread,
550 resumed_without_history,
551 resume_thread,
552 initial_content,
553 window,
554 cx,
555 );
556
557 if this.focus_handle.contains_focused(window, cx) {
558 current
559 .read(cx)
560 .message_editor
561 .focus_handle(cx)
562 .focus(window, cx);
563 }
564
565 let id = current.read(cx).thread.read(cx).session_id().clone();
566 this.set_server_state(
567 ServerState::Connected(ConnectedServerState {
568 connection,
569 auth_state: AuthState::Ok,
570 active_id: Some(id.clone()),
571 threads: HashMap::from_iter([(id, current)]),
572 }),
573 cx,
574 );
575 }
576 Err(err) => {
577 this.handle_load_error(err, window, cx);
578 }
579 };
580 })
581 .log_err();
582 });
583
584 cx.spawn(async move |this, cx| {
585 while let Ok(new_version) = new_version_available_rx.recv().await {
586 if let Some(new_version) = new_version {
587 this.update(cx, |this, cx| {
588 if let Some(thread) = this.active_thread() {
589 thread.update(cx, |thread, _cx| {
590 thread.new_server_version_available = Some(new_version.into());
591 });
592 }
593 cx.notify();
594 })
595 .ok();
596 }
597 }
598 })
599 .detach();
600
601 let loading_view = cx.new(|cx| {
602 let update_title_task = cx.spawn(async move |this, cx| {
603 loop {
604 let status = status_rx.recv().await?;
605 this.update(cx, |this: &mut LoadingView, cx| {
606 this.title = status;
607 cx.notify();
608 })?;
609 }
610 });
611
612 LoadingView {
613 title: "Loading…".into(),
614 _load_task: load_task,
615 _update_title_task: update_title_task,
616 }
617 });
618
619 ServerState::Loading(loading_view)
620 }
621
622 fn new_thread_view(
623 &self,
624 parent_id: Option<acp::SessionId>,
625 thread: Entity<AcpThread>,
626 resumed_without_history: bool,
627 resume_thread: Option<AgentSessionInfo>,
628 initial_content: Option<ExternalAgentInitialContent>,
629 window: &mut Window,
630 cx: &mut Context<Self>,
631 ) -> Entity<AcpThreadView> {
632 let agent_name = self.agent.name();
633 let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
634 let available_commands = Rc::new(RefCell::new(vec![]));
635
636 let action_log = thread.read(cx).action_log().clone();
637
638 prompt_capabilities.replace(thread.read(cx).prompt_capabilities());
639
640 let entry_view_state = cx.new(|_| {
641 EntryViewState::new(
642 self.workspace.clone(),
643 self.project.downgrade(),
644 self.thread_store.clone(),
645 self.history.downgrade(),
646 self.prompt_store.clone(),
647 prompt_capabilities.clone(),
648 available_commands.clone(),
649 self.agent.name(),
650 )
651 });
652
653 let count = thread.read(cx).entries().len();
654 let list_state = ListState::new(0, gpui::ListAlignment::Bottom, px(2048.0));
655 entry_view_state.update(cx, |view_state, cx| {
656 for ix in 0..count {
657 view_state.sync_entry(ix, &thread, window, cx);
658 }
659 list_state.splice_focusable(
660 0..0,
661 (0..count).map(|ix| view_state.entry(ix)?.focus_handle(cx)),
662 );
663 });
664
665 AgentDiff::set_active_thread(&self.workspace, thread.clone(), window, cx);
666
667 let connection = thread.read(cx).connection().clone();
668 let session_id = thread.read(cx).session_id().clone();
669 let session_list = if connection.supports_session_history() {
670 connection.session_list(cx)
671 } else {
672 None
673 };
674 self.history.update(cx, |history, cx| {
675 history.set_session_list(session_list, cx);
676 });
677
678 // Check for config options first
679 // Config options take precedence over legacy mode/model selectors
680 // (feature flag gating happens at the data layer)
681 let config_options_provider = connection.session_config_options(&session_id, cx);
682
683 let config_options_view;
684 let mode_selector;
685 let model_selector;
686 if let Some(config_options) = config_options_provider {
687 // Use config options - don't create mode_selector or model_selector
688 let agent_server = self.agent.clone();
689 let fs = self.project.read(cx).fs().clone();
690 config_options_view =
691 Some(cx.new(|cx| {
692 ConfigOptionsView::new(config_options, agent_server, fs, window, cx)
693 }));
694 model_selector = None;
695 mode_selector = None;
696 } else {
697 // Fall back to legacy mode/model selectors
698 config_options_view = None;
699 model_selector = connection.model_selector(&session_id).map(|selector| {
700 let agent_server = self.agent.clone();
701 let fs = self.project.read(cx).fs().clone();
702 cx.new(|cx| {
703 AcpModelSelectorPopover::new(
704 selector,
705 agent_server,
706 fs,
707 PopoverMenuHandle::default(),
708 self.focus_handle(cx),
709 window,
710 cx,
711 )
712 })
713 });
714
715 mode_selector = connection
716 .session_modes(&session_id, cx)
717 .map(|session_modes| {
718 let fs = self.project.read(cx).fs().clone();
719 cx.new(|_cx| ModeSelector::new(session_modes, self.agent.clone(), fs))
720 });
721 }
722
723 let subscriptions = vec![
724 cx.subscribe_in(&thread, window, Self::handle_thread_event),
725 cx.observe(&action_log, |_, _, cx| cx.notify()),
726 ];
727
728 let parent_session_id = thread.read(cx).session_id().clone();
729 let subagent_sessions = thread
730 .read(cx)
731 .entries()
732 .iter()
733 .filter_map(|entry| match entry {
734 AgentThreadEntry::ToolCall(call) => call.subagent_session_id.clone(),
735 _ => None,
736 })
737 .collect::<Vec<_>>();
738
739 if !subagent_sessions.is_empty() {
740 cx.spawn_in(window, async move |this, cx| {
741 this.update_in(cx, |this, window, cx| {
742 for subagent_id in subagent_sessions {
743 this.load_subagent_session(
744 subagent_id,
745 parent_session_id.clone(),
746 window,
747 cx,
748 );
749 }
750 })
751 })
752 .detach();
753 }
754
755 let profile_selector: Option<Rc<agent::NativeAgentConnection>> =
756 connection.clone().downcast();
757 let profile_selector = profile_selector
758 .and_then(|native_connection| native_connection.thread(&session_id, cx))
759 .map(|native_thread| {
760 cx.new(|cx| {
761 ProfileSelector::new(
762 <dyn Fs>::global(cx),
763 Arc::new(native_thread),
764 self.focus_handle(cx),
765 cx,
766 )
767 })
768 });
769
770 let agent_display_name = self
771 .agent_server_store
772 .read(cx)
773 .agent_display_name(&ExternalAgentServerName(agent_name.clone()))
774 .unwrap_or_else(|| agent_name.clone());
775
776 let agent_icon = self.agent.logo();
777
778 let weak = cx.weak_entity();
779 cx.new(|cx| {
780 AcpThreadView::new(
781 parent_id,
782 thread,
783 self.login.clone(),
784 weak,
785 agent_icon,
786 agent_name,
787 agent_display_name,
788 self.workspace.clone(),
789 entry_view_state,
790 config_options_view,
791 mode_selector,
792 model_selector,
793 profile_selector,
794 list_state,
795 prompt_capabilities,
796 available_commands,
797 resumed_without_history,
798 resume_thread,
799 self.project.downgrade(),
800 self.thread_store.clone(),
801 self.history.clone(),
802 self.prompt_store.clone(),
803 initial_content,
804 subscriptions,
805 window,
806 cx,
807 )
808 })
809 }
810
811 fn handle_auth_required(
812 this: WeakEntity<Self>,
813 err: AuthRequired,
814 agent_name: SharedString,
815 connection: Rc<dyn AgentConnection>,
816 window: &mut Window,
817 cx: &mut App,
818 ) {
819 let (configuration_view, subscription) = if let Some(provider_id) = &err.provider_id {
820 let registry = LanguageModelRegistry::global(cx);
821
822 let sub = window.subscribe(®istry, cx, {
823 let provider_id = provider_id.clone();
824 let this = this.clone();
825 move |_, ev, window, cx| {
826 if let language_model::Event::ProviderStateChanged(updated_provider_id) = &ev
827 && &provider_id == updated_provider_id
828 && LanguageModelRegistry::global(cx)
829 .read(cx)
830 .provider(&provider_id)
831 .map_or(false, |provider| provider.is_authenticated(cx))
832 {
833 this.update(cx, |this, cx| {
834 this.reset(window, cx);
835 })
836 .ok();
837 }
838 }
839 });
840
841 let view = registry.read(cx).provider(&provider_id).map(|provider| {
842 provider.configuration_view(
843 language_model::ConfigurationViewTargetAgent::Other(agent_name),
844 window,
845 cx,
846 )
847 });
848
849 (view, Some(sub))
850 } else {
851 (None, None)
852 };
853
854 this.update(cx, |this, cx| {
855 let description = err
856 .description
857 .map(|desc| cx.new(|cx| Markdown::new(desc.into(), None, None, cx)));
858 let auth_state = AuthState::Unauthenticated {
859 pending_auth_method: None,
860 configuration_view,
861 description,
862 _subscription: subscription,
863 };
864 if let Some(connected) = this.as_connected_mut() {
865 connected.auth_state = auth_state;
866 if let Some(view) = connected.active_view()
867 && view
868 .read(cx)
869 .message_editor
870 .focus_handle(cx)
871 .is_focused(window)
872 {
873 this.focus_handle.focus(window, cx)
874 }
875 } else {
876 this.set_server_state(
877 ServerState::Connected(ConnectedServerState {
878 auth_state,
879 active_id: None,
880 threads: HashMap::default(),
881 connection,
882 }),
883 cx,
884 );
885 }
886 cx.notify();
887 })
888 .ok();
889 }
890
891 fn handle_load_error(
892 &mut self,
893 err: anyhow::Error,
894 window: &mut Window,
895 cx: &mut Context<Self>,
896 ) {
897 if let Some(view) = self.active_thread() {
898 if view
899 .read(cx)
900 .message_editor
901 .focus_handle(cx)
902 .is_focused(window)
903 {
904 self.focus_handle.focus(window, cx)
905 }
906 }
907 let load_error = if let Some(load_err) = err.downcast_ref::<LoadError>() {
908 load_err.clone()
909 } else {
910 LoadError::Other(format!("{:#}", err).into())
911 };
912 self.emit_load_error_telemetry(&load_error);
913 self.set_server_state(ServerState::LoadError(load_error), cx);
914 }
915
916 fn handle_agent_servers_updated(
917 &mut self,
918 _agent_server_store: &Entity<project::AgentServerStore>,
919 _event: &project::AgentServersUpdated,
920 window: &mut Window,
921 cx: &mut Context<Self>,
922 ) {
923 // If we're in a LoadError state OR have a thread_error set (which can happen
924 // when agent.connect() fails during loading), retry loading the thread.
925 // This handles the case where a thread is restored before authentication completes.
926 let should_retry = match &self.server_state {
927 ServerState::Loading(_) => false,
928 ServerState::LoadError(_) => true,
929 ServerState::Connected(connected) => {
930 connected.auth_state.is_ok() && connected.has_thread_error(cx)
931 }
932 };
933
934 if should_retry {
935 if let Some(active) = self.active_thread() {
936 active.update(cx, |active, cx| {
937 active.clear_thread_error(cx);
938 });
939 }
940 self.reset(window, cx);
941 }
942 }
943
944 pub fn workspace(&self) -> &WeakEntity<Workspace> {
945 &self.workspace
946 }
947
948 pub fn title(&self, cx: &App) -> SharedString {
949 match &self.server_state {
950 ServerState::Connected(_) => "New Thread".into(),
951 ServerState::Loading(loading_view) => loading_view.read(cx).title.clone(),
952 ServerState::LoadError(error) => match error {
953 LoadError::Unsupported { .. } => format!("Upgrade {}", self.agent.name()).into(),
954 LoadError::FailedToInstall(_) => {
955 format!("Failed to Install {}", self.agent.name()).into()
956 }
957 LoadError::Exited { .. } => format!("{} Exited", self.agent.name()).into(),
958 LoadError::Other(_) => format!("Error Loading {}", self.agent.name()).into(),
959 },
960 }
961 }
962
963 pub fn cancel_generation(&mut self, cx: &mut Context<Self>) {
964 if let Some(active) = self.active_thread() {
965 active.update(cx, |active, cx| {
966 active.cancel_generation(cx);
967 });
968 }
969 }
970
971 pub fn is_loading(&self) -> bool {
972 matches!(self.server_state, ServerState::Loading { .. })
973 }
974
975 fn update_turn_tokens(&mut self, cx: &mut Context<Self>) {
976 if let Some(active) = self.active_thread() {
977 active.update(cx, |active, cx| {
978 active.update_turn_tokens(cx);
979 });
980 }
981 }
982
983 fn send_queued_message_at_index(
984 &mut self,
985 index: usize,
986 is_send_now: bool,
987 window: &mut Window,
988 cx: &mut Context<Self>,
989 ) {
990 if let Some(active) = self.active_thread() {
991 active.update(cx, |active, cx| {
992 active.send_queued_message_at_index(index, is_send_now, window, cx);
993 });
994 }
995 }
996
997 fn handle_thread_event(
998 &mut self,
999 thread: &Entity<AcpThread>,
1000 event: &AcpThreadEvent,
1001 window: &mut Window,
1002 cx: &mut Context<Self>,
1003 ) {
1004 let thread_id = thread.read(cx).session_id().clone();
1005 let is_subagent = thread.read(cx).parent_session_id().is_some();
1006 match event {
1007 AcpThreadEvent::NewEntry => {
1008 let len = thread.read(cx).entries().len();
1009 let index = len - 1;
1010 if let Some(active) = self.thread_view(&thread_id) {
1011 let entry_view_state = active.read(cx).entry_view_state.clone();
1012 let list_state = active.read(cx).list_state.clone();
1013 entry_view_state.update(cx, |view_state, cx| {
1014 view_state.sync_entry(index, thread, window, cx);
1015 list_state.splice_focusable(
1016 index..index,
1017 [view_state
1018 .entry(index)
1019 .and_then(|entry| entry.focus_handle(cx))],
1020 );
1021 });
1022 }
1023 }
1024 AcpThreadEvent::EntryUpdated(index) => {
1025 if let Some(entry_view_state) = self
1026 .thread_view(&thread_id)
1027 .map(|active| active.read(cx).entry_view_state.clone())
1028 {
1029 entry_view_state.update(cx, |view_state, cx| {
1030 view_state.sync_entry(*index, thread, window, cx)
1031 });
1032 }
1033 }
1034 AcpThreadEvent::EntriesRemoved(range) => {
1035 if let Some(active) = self.thread_view(&thread_id) {
1036 let entry_view_state = active.read(cx).entry_view_state.clone();
1037 let list_state = active.read(cx).list_state.clone();
1038 entry_view_state.update(cx, |view_state, _cx| view_state.remove(range.clone()));
1039 list_state.splice(range.clone(), 0);
1040 }
1041 }
1042 AcpThreadEvent::SubagentSpawned(session_id) => self.load_subagent_session(
1043 session_id.clone(),
1044 thread.read(cx).session_id().clone(),
1045 window,
1046 cx,
1047 ),
1048 AcpThreadEvent::ToolAuthorizationRequired => {
1049 self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
1050 }
1051 AcpThreadEvent::Retry(retry) => {
1052 if let Some(active) = self.thread_view(&thread_id) {
1053 active.update(cx, |active, _cx| {
1054 active.thread_retry_status = Some(retry.clone());
1055 });
1056 }
1057 }
1058 AcpThreadEvent::Stopped => {
1059 if let Some(active) = self.thread_view(&thread_id) {
1060 active.update(cx, |active, _cx| {
1061 active.thread_retry_status.take();
1062 });
1063 }
1064 if is_subagent {
1065 return;
1066 }
1067
1068 let used_tools = thread.read(cx).used_tools_since_last_user_message();
1069 self.notify_with_sound(
1070 if used_tools {
1071 "Finished running tools"
1072 } else {
1073 "New message"
1074 },
1075 IconName::ZedAssistant,
1076 window,
1077 cx,
1078 );
1079
1080 let should_send_queued = if let Some(active) = self.active_thread() {
1081 active.update(cx, |active, cx| {
1082 if active.skip_queue_processing_count > 0 {
1083 active.skip_queue_processing_count -= 1;
1084 false
1085 } else if active.user_interrupted_generation {
1086 // Manual interruption: don't auto-process queue.
1087 // Reset the flag so future completions can process normally.
1088 active.user_interrupted_generation = false;
1089 false
1090 } else {
1091 let has_queued = !active.local_queued_messages.is_empty();
1092 // Don't auto-send if the first message editor is currently focused
1093 let is_first_editor_focused = active
1094 .queued_message_editors
1095 .first()
1096 .is_some_and(|editor| editor.focus_handle(cx).is_focused(window));
1097 has_queued && !is_first_editor_focused
1098 }
1099 })
1100 } else {
1101 false
1102 };
1103 if should_send_queued {
1104 self.send_queued_message_at_index(0, false, window, cx);
1105 }
1106 }
1107 AcpThreadEvent::Refusal => {
1108 let error = ThreadError::Refusal;
1109 if let Some(active) = self.thread_view(&thread_id) {
1110 active.update(cx, |active, cx| {
1111 active.handle_thread_error(error, cx);
1112 active.thread_retry_status.take();
1113 });
1114 }
1115 if !is_subagent {
1116 let model_or_agent_name = self.current_model_name(cx);
1117 let notification_message =
1118 format!("{} refused to respond to this request", model_or_agent_name);
1119 self.notify_with_sound(¬ification_message, IconName::Warning, window, cx);
1120 }
1121 }
1122 AcpThreadEvent::Error => {
1123 if let Some(active) = self.thread_view(&thread_id) {
1124 active.update(cx, |active, _cx| {
1125 active.thread_retry_status.take();
1126 });
1127 }
1128 if !is_subagent {
1129 self.notify_with_sound(
1130 "Agent stopped due to an error",
1131 IconName::Warning,
1132 window,
1133 cx,
1134 );
1135 }
1136 }
1137 AcpThreadEvent::LoadError(error) => {
1138 if let Some(view) = self.active_thread() {
1139 if view
1140 .read(cx)
1141 .message_editor
1142 .focus_handle(cx)
1143 .is_focused(window)
1144 {
1145 self.focus_handle.focus(window, cx)
1146 }
1147 }
1148 self.set_server_state(ServerState::LoadError(error.clone()), cx);
1149 }
1150 AcpThreadEvent::TitleUpdated => {
1151 let title = thread.read(cx).title();
1152 if let Some(active_thread) = self.thread_view(&thread_id) {
1153 let title_editor = active_thread.read(cx).title_editor.clone();
1154 title_editor.update(cx, |editor, cx| {
1155 if editor.text(cx) != title {
1156 editor.set_text(title, window, cx);
1157 }
1158 });
1159 }
1160 }
1161 AcpThreadEvent::PromptCapabilitiesUpdated => {
1162 if let Some(active) = self.thread_view(&thread_id) {
1163 active.update(cx, |active, _cx| {
1164 active
1165 .prompt_capabilities
1166 .replace(thread.read(_cx).prompt_capabilities());
1167 });
1168 }
1169 }
1170 AcpThreadEvent::TokenUsageUpdated => {
1171 self.update_turn_tokens(cx);
1172 self.emit_token_limit_telemetry_if_needed(thread, cx);
1173 }
1174 AcpThreadEvent::AvailableCommandsUpdated(available_commands) => {
1175 let mut available_commands = available_commands.clone();
1176
1177 if thread
1178 .read(cx)
1179 .connection()
1180 .auth_methods()
1181 .iter()
1182 .any(|method| method.id.0.as_ref() == "claude-login")
1183 {
1184 available_commands.push(acp::AvailableCommand::new("login", "Authenticate"));
1185 available_commands.push(acp::AvailableCommand::new("logout", "Authenticate"));
1186 }
1187
1188 let has_commands = !available_commands.is_empty();
1189 if let Some(active) = self.active_thread() {
1190 active.update(cx, |active, _cx| {
1191 active.available_commands.replace(available_commands);
1192 });
1193 }
1194
1195 let agent_display_name = self
1196 .agent_server_store
1197 .read(cx)
1198 .agent_display_name(&ExternalAgentServerName(self.agent.name()))
1199 .unwrap_or_else(|| self.agent.name());
1200
1201 if let Some(active) = self.active_thread() {
1202 let new_placeholder =
1203 placeholder_text(agent_display_name.as_ref(), has_commands);
1204 active.update(cx, |active, cx| {
1205 active.message_editor.update(cx, |editor, cx| {
1206 editor.set_placeholder_text(&new_placeholder, window, cx);
1207 });
1208 });
1209 }
1210 }
1211 AcpThreadEvent::ModeUpdated(_mode) => {
1212 // The connection keeps track of the mode
1213 cx.notify();
1214 }
1215 AcpThreadEvent::ConfigOptionsUpdated(_) => {
1216 // The watch task in ConfigOptionsView handles rebuilding selectors
1217 cx.notify();
1218 }
1219 }
1220 cx.notify();
1221 }
1222
1223 fn authenticate(
1224 &mut self,
1225 method: acp::AuthMethodId,
1226 window: &mut Window,
1227 cx: &mut Context<Self>,
1228 ) {
1229 let Some(connected) = self.as_connected_mut() else {
1230 return;
1231 };
1232 let connection = connected.connection.clone();
1233
1234 let AuthState::Unauthenticated {
1235 configuration_view,
1236 pending_auth_method,
1237 ..
1238 } = &mut connected.auth_state
1239 else {
1240 return;
1241 };
1242
1243 let agent_telemetry_id = connection.telemetry_id();
1244
1245 // Check for the experimental "terminal-auth" _meta field
1246 let auth_method = connection.auth_methods().iter().find(|m| m.id == method);
1247
1248 if let Some(terminal_auth) = auth_method
1249 .and_then(|a| a.meta.as_ref())
1250 .and_then(|m| m.get("terminal-auth"))
1251 {
1252 // Extract terminal auth details from meta
1253 if let (Some(command), Some(label)) = (
1254 terminal_auth.get("command").and_then(|v| v.as_str()),
1255 terminal_auth.get("label").and_then(|v| v.as_str()),
1256 ) {
1257 let args = terminal_auth
1258 .get("args")
1259 .and_then(|v| v.as_array())
1260 .map(|arr| {
1261 arr.iter()
1262 .filter_map(|v| v.as_str().map(String::from))
1263 .collect()
1264 })
1265 .unwrap_or_default();
1266
1267 let env = terminal_auth
1268 .get("env")
1269 .and_then(|v| v.as_object())
1270 .map(|obj| {
1271 obj.iter()
1272 .filter_map(|(k, v)| v.as_str().map(|val| (k.clone(), val.to_string())))
1273 .collect::<HashMap<String, String>>()
1274 })
1275 .unwrap_or_default();
1276
1277 // Run SpawnInTerminal in the same dir as the ACP server
1278 let cwd = connected
1279 .connection
1280 .clone()
1281 .downcast::<agent_servers::AcpConnection>()
1282 .map(|acp_conn| acp_conn.root_dir().to_path_buf());
1283
1284 // Build SpawnInTerminal from _meta
1285 let login = task::SpawnInTerminal {
1286 id: task::TaskId(format!("external-agent-{}-login", label)),
1287 full_label: label.to_string(),
1288 label: label.to_string(),
1289 command: Some(command.to_string()),
1290 args,
1291 command_label: label.to_string(),
1292 cwd,
1293 env,
1294 use_new_terminal: true,
1295 allow_concurrent_runs: true,
1296 hide: task::HideStrategy::Always,
1297 ..Default::default()
1298 };
1299
1300 configuration_view.take();
1301 pending_auth_method.replace(method.clone());
1302
1303 if let Some(workspace) = self.workspace.upgrade() {
1304 let project = self.project.clone();
1305 let authenticate = Self::spawn_external_agent_login(
1306 login,
1307 workspace,
1308 project,
1309 method.clone(),
1310 false,
1311 window,
1312 cx,
1313 );
1314 cx.notify();
1315 self.auth_task = Some(cx.spawn_in(window, {
1316 async move |this, cx| {
1317 let result = authenticate.await;
1318
1319 match &result {
1320 Ok(_) => telemetry::event!(
1321 "Authenticate Agent Succeeded",
1322 agent = agent_telemetry_id
1323 ),
1324 Err(_) => {
1325 telemetry::event!(
1326 "Authenticate Agent Failed",
1327 agent = agent_telemetry_id,
1328 )
1329 }
1330 }
1331
1332 this.update_in(cx, |this, window, cx| {
1333 if let Err(err) = result {
1334 if let Some(ConnectedServerState {
1335 auth_state:
1336 AuthState::Unauthenticated {
1337 pending_auth_method,
1338 ..
1339 },
1340 ..
1341 }) = this.as_connected_mut()
1342 {
1343 pending_auth_method.take();
1344 }
1345 if let Some(active) = this.active_thread() {
1346 active.update(cx, |active, cx| {
1347 active.handle_any_thread_error(err, cx);
1348 })
1349 }
1350 } else {
1351 this.reset(window, cx);
1352 }
1353 this.auth_task.take()
1354 })
1355 .ok();
1356 }
1357 }));
1358 }
1359 return;
1360 }
1361 }
1362
1363 if method.0.as_ref() == "gemini-api-key" {
1364 let registry = LanguageModelRegistry::global(cx);
1365 let provider = registry
1366 .read(cx)
1367 .provider(&language_model::GOOGLE_PROVIDER_ID)
1368 .unwrap();
1369 if !provider.is_authenticated(cx) {
1370 let this = cx.weak_entity();
1371 let agent_name = self.agent.name();
1372 let connection = connection.clone();
1373 window.defer(cx, |window, cx| {
1374 Self::handle_auth_required(
1375 this,
1376 AuthRequired {
1377 description: Some("GEMINI_API_KEY must be set".to_owned()),
1378 provider_id: Some(language_model::GOOGLE_PROVIDER_ID),
1379 },
1380 agent_name,
1381 connection,
1382 window,
1383 cx,
1384 );
1385 });
1386 return;
1387 }
1388 } else if method.0.as_ref() == "vertex-ai"
1389 && std::env::var("GOOGLE_API_KEY").is_err()
1390 && (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()
1391 || (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()))
1392 {
1393 let this = cx.weak_entity();
1394 let agent_name = self.agent.name();
1395 let connection = connection.clone();
1396
1397 window.defer(cx, |window, cx| {
1398 Self::handle_auth_required(
1399 this,
1400 AuthRequired {
1401 description: Some(
1402 "GOOGLE_API_KEY must be set in the environment to use Vertex AI authentication for Gemini CLI. Please export it and restart Zed."
1403 .to_owned(),
1404 ),
1405 provider_id: None,
1406 },
1407 agent_name,
1408 connection,
1409 window,
1410 cx,
1411 )
1412 });
1413 return;
1414 }
1415
1416 configuration_view.take();
1417 pending_auth_method.replace(method.clone());
1418 let authenticate = if let Some(login) = self.login.clone() {
1419 if let Some(workspace) = self.workspace.upgrade() {
1420 let project = self.project.clone();
1421 Self::spawn_external_agent_login(
1422 login,
1423 workspace,
1424 project,
1425 method.clone(),
1426 false,
1427 window,
1428 cx,
1429 )
1430 } else {
1431 Task::ready(Ok(()))
1432 }
1433 } else {
1434 connection.authenticate(method, cx)
1435 };
1436 cx.notify();
1437 self.auth_task = Some(cx.spawn_in(window, {
1438 async move |this, cx| {
1439 let result = authenticate.await;
1440
1441 match &result {
1442 Ok(_) => telemetry::event!(
1443 "Authenticate Agent Succeeded",
1444 agent = agent_telemetry_id
1445 ),
1446 Err(_) => {
1447 telemetry::event!("Authenticate Agent Failed", agent = agent_telemetry_id,)
1448 }
1449 }
1450
1451 this.update_in(cx, |this, window, cx| {
1452 if let Err(err) = result {
1453 if let Some(ConnectedServerState {
1454 auth_state:
1455 AuthState::Unauthenticated {
1456 pending_auth_method,
1457 ..
1458 },
1459 ..
1460 }) = this.as_connected_mut()
1461 {
1462 pending_auth_method.take();
1463 }
1464 if let Some(active) = this.active_thread() {
1465 active.update(cx, |active, cx| active.handle_any_thread_error(err, cx));
1466 }
1467 } else {
1468 this.reset(window, cx);
1469 }
1470 this.auth_task.take()
1471 })
1472 .ok();
1473 }
1474 }));
1475 }
1476
1477 fn load_subagent_session(
1478 &mut self,
1479 subagent_id: acp::SessionId,
1480 parent_id: acp::SessionId,
1481 window: &mut Window,
1482 cx: &mut Context<Self>,
1483 ) {
1484 let Some(connected) = self.as_connected() else {
1485 return;
1486 };
1487 if connected.threads.contains_key(&subagent_id)
1488 || !connected.connection.supports_load_session()
1489 {
1490 return;
1491 }
1492 let root_dir = self
1493 .project
1494 .read(cx)
1495 .worktrees(cx)
1496 .filter_map(|worktree| {
1497 if worktree.read(cx).is_single_file() {
1498 Some(worktree.read(cx).abs_path().parent()?.into())
1499 } else {
1500 Some(worktree.read(cx).abs_path())
1501 }
1502 })
1503 .next();
1504 let cwd = root_dir.unwrap_or_else(|| paths::home_dir().as_path().into());
1505
1506 let subagent_thread_task = connected.connection.clone().load_session(
1507 AgentSessionInfo::new(subagent_id.clone()),
1508 self.project.clone(),
1509 &cwd,
1510 cx,
1511 );
1512
1513 cx.spawn_in(window, async move |this, cx| {
1514 let subagent_thread = subagent_thread_task.await?;
1515 this.update_in(cx, |this, window, cx| {
1516 let view = this.new_thread_view(
1517 Some(parent_id),
1518 subagent_thread,
1519 false,
1520 None,
1521 None,
1522 window,
1523 cx,
1524 );
1525 let Some(connected) = this.as_connected_mut() else {
1526 return;
1527 };
1528 connected.threads.insert(subagent_id, view);
1529 })
1530 })
1531 .detach();
1532 }
1533
1534 fn spawn_external_agent_login(
1535 login: task::SpawnInTerminal,
1536 workspace: Entity<Workspace>,
1537 project: Entity<Project>,
1538 method: acp::AuthMethodId,
1539 previous_attempt: bool,
1540 window: &mut Window,
1541 cx: &mut App,
1542 ) -> Task<Result<()>> {
1543 let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
1544 return Task::ready(Ok(()));
1545 };
1546
1547 window.spawn(cx, async move |cx| {
1548 let mut task = login.clone();
1549 if let Some(cmd) = &task.command {
1550 // Have "node" command use Zed's managed Node runtime by default
1551 if cmd == "node" {
1552 let resolved_node_runtime = project
1553 .update(cx, |project, cx| {
1554 let agent_server_store = project.agent_server_store().clone();
1555 agent_server_store.update(cx, |store, cx| {
1556 store.node_runtime().map(|node_runtime| {
1557 cx.background_spawn(async move {
1558 node_runtime.binary_path().await
1559 })
1560 })
1561 })
1562 });
1563
1564 if let Some(resolve_task) = resolved_node_runtime {
1565 if let Ok(node_path) = resolve_task.await {
1566 task.command = Some(node_path.to_string_lossy().to_string());
1567 }
1568 }
1569 }
1570 }
1571 task.shell = task::Shell::WithArguments {
1572 program: task.command.take().expect("login command should be set"),
1573 args: std::mem::take(&mut task.args),
1574 title_override: None
1575 };
1576 task.full_label = task.label.clone();
1577 task.id = task::TaskId(format!("external-agent-{}-login", task.label));
1578 task.command_label = task.label.clone();
1579 task.use_new_terminal = true;
1580 task.allow_concurrent_runs = true;
1581 task.hide = task::HideStrategy::Always;
1582
1583 let terminal = terminal_panel
1584 .update_in(cx, |terminal_panel, window, cx| {
1585 terminal_panel.spawn_task(&task, window, cx)
1586 })?
1587 .await?;
1588
1589 let success_patterns = match method.0.as_ref() {
1590 "claude-login" | "spawn-gemini-cli" => vec![
1591 "Login successful".to_string(),
1592 "Type your message".to_string(),
1593 ],
1594 _ => Vec::new(),
1595 };
1596 if success_patterns.is_empty() {
1597 // No success patterns specified: wait for the process to exit and check exit code
1598 let exit_status = terminal
1599 .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1600 .await;
1601
1602 match exit_status {
1603 Some(status) if status.success() => Ok(()),
1604 Some(status) => Err(anyhow!(
1605 "Login command failed with exit code: {:?}",
1606 status.code()
1607 )),
1608 None => Err(anyhow!("Login command terminated without exit status")),
1609 }
1610 } else {
1611 // Look for specific output patterns to detect successful login
1612 let mut exit_status = terminal
1613 .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1614 .fuse();
1615
1616 let logged_in = cx
1617 .spawn({
1618 let terminal = terminal.clone();
1619 async move |cx| {
1620 loop {
1621 cx.background_executor().timer(Duration::from_secs(1)).await;
1622 let content =
1623 terminal.update(cx, |terminal, _cx| terminal.get_content())?;
1624 if success_patterns.iter().any(|pattern| content.contains(pattern))
1625 {
1626 return anyhow::Ok(());
1627 }
1628 }
1629 }
1630 })
1631 .fuse();
1632 futures::pin_mut!(logged_in);
1633 futures::select_biased! {
1634 result = logged_in => {
1635 if let Err(e) = result {
1636 log::error!("{e}");
1637 return Err(anyhow!("exited before logging in"));
1638 }
1639 }
1640 _ = exit_status => {
1641 if !previous_attempt && project.read_with(cx, |project, _| project.is_via_remote_server()) && login.label.contains("gemini") {
1642 return cx.update(|window, cx| Self::spawn_external_agent_login(login, workspace, project.clone(), method, true, window, cx))?.await
1643 }
1644 return Err(anyhow!("exited before logging in"));
1645 }
1646 }
1647 terminal.update(cx, |terminal, _| terminal.kill_active_task())?;
1648 Ok(())
1649 }
1650 })
1651 }
1652
1653 pub fn has_user_submitted_prompt(&self, cx: &App) -> bool {
1654 self.active_thread().is_some_and(|active| {
1655 active
1656 .read(cx)
1657 .thread
1658 .read(cx)
1659 .entries()
1660 .iter()
1661 .any(|entry| {
1662 matches!(
1663 entry,
1664 AgentThreadEntry::UserMessage(user_message) if user_message.id.is_some()
1665 )
1666 })
1667 })
1668 }
1669
1670 fn render_auth_required_state(
1671 &self,
1672 connection: &Rc<dyn AgentConnection>,
1673 description: Option<&Entity<Markdown>>,
1674 configuration_view: Option<&AnyView>,
1675 pending_auth_method: Option<&acp::AuthMethodId>,
1676 window: &mut Window,
1677 cx: &Context<Self>,
1678 ) -> impl IntoElement {
1679 let auth_methods = connection.auth_methods();
1680
1681 let agent_display_name = self
1682 .agent_server_store
1683 .read(cx)
1684 .agent_display_name(&ExternalAgentServerName(self.agent.name()))
1685 .unwrap_or_else(|| self.agent.name());
1686
1687 let show_fallback_description = auth_methods.len() > 1
1688 && configuration_view.is_none()
1689 && description.is_none()
1690 && pending_auth_method.is_none();
1691
1692 let auth_buttons = || {
1693 h_flex().justify_end().flex_wrap().gap_1().children(
1694 connection
1695 .auth_methods()
1696 .iter()
1697 .enumerate()
1698 .rev()
1699 .map(|(ix, method)| {
1700 let (method_id, name) = if self.project.read(cx).is_via_remote_server()
1701 && method.id.0.as_ref() == "oauth-personal"
1702 && method.name == "Log in with Google"
1703 {
1704 ("spawn-gemini-cli".into(), "Log in with Gemini CLI".into())
1705 } else {
1706 (method.id.0.clone(), method.name.clone())
1707 };
1708
1709 let agent_telemetry_id = connection.telemetry_id();
1710
1711 Button::new(method_id.clone(), name)
1712 .label_size(LabelSize::Small)
1713 .map(|this| {
1714 if ix == 0 {
1715 this.style(ButtonStyle::Tinted(TintColor::Accent))
1716 } else {
1717 this.style(ButtonStyle::Outlined)
1718 }
1719 })
1720 .when_some(method.description.clone(), |this, description| {
1721 this.tooltip(Tooltip::text(description))
1722 })
1723 .on_click({
1724 cx.listener(move |this, _, window, cx| {
1725 telemetry::event!(
1726 "Authenticate Agent Started",
1727 agent = agent_telemetry_id,
1728 method = method_id
1729 );
1730
1731 this.authenticate(
1732 acp::AuthMethodId::new(method_id.clone()),
1733 window,
1734 cx,
1735 )
1736 })
1737 })
1738 }),
1739 )
1740 };
1741
1742 if pending_auth_method.is_some() {
1743 return Callout::new()
1744 .icon(IconName::Info)
1745 .title(format!("Authenticating to {}…", agent_display_name))
1746 .actions_slot(
1747 Icon::new(IconName::ArrowCircle)
1748 .size(IconSize::Small)
1749 .color(Color::Muted)
1750 .with_rotate_animation(2)
1751 .into_any_element(),
1752 )
1753 .into_any_element();
1754 }
1755
1756 Callout::new()
1757 .icon(IconName::Info)
1758 .title(format!("Authenticate to {}", agent_display_name))
1759 .when(auth_methods.len() == 1, |this| {
1760 this.actions_slot(auth_buttons())
1761 })
1762 .description_slot(
1763 v_flex()
1764 .text_ui(cx)
1765 .map(|this| {
1766 if show_fallback_description {
1767 this.child(
1768 Label::new("Choose one of the following authentication options:")
1769 .size(LabelSize::Small)
1770 .color(Color::Muted),
1771 )
1772 } else {
1773 this.children(
1774 configuration_view
1775 .cloned()
1776 .map(|view| div().w_full().child(view)),
1777 )
1778 .children(description.map(|desc| {
1779 self.render_markdown(
1780 desc.clone(),
1781 MarkdownStyle::themed(MarkdownFont::Agent, window, cx),
1782 )
1783 }))
1784 }
1785 })
1786 .when(auth_methods.len() > 1, |this| {
1787 this.gap_1().child(auth_buttons())
1788 }),
1789 )
1790 .into_any_element()
1791 }
1792
1793 fn emit_token_limit_telemetry_if_needed(
1794 &mut self,
1795 thread: &Entity<AcpThread>,
1796 cx: &mut Context<Self>,
1797 ) {
1798 let Some(active_thread) = self.active_thread() else {
1799 return;
1800 };
1801
1802 let (ratio, agent_telemetry_id, session_id) = {
1803 let thread_data = thread.read(cx);
1804 let Some(token_usage) = thread_data.token_usage() else {
1805 return;
1806 };
1807 (
1808 token_usage.ratio(),
1809 thread_data.connection().telemetry_id(),
1810 thread_data.session_id().clone(),
1811 )
1812 };
1813
1814 let kind = match ratio {
1815 acp_thread::TokenUsageRatio::Normal => {
1816 active_thread.update(cx, |active, _cx| {
1817 active.last_token_limit_telemetry = None;
1818 });
1819 return;
1820 }
1821 acp_thread::TokenUsageRatio::Warning => "warning",
1822 acp_thread::TokenUsageRatio::Exceeded => "exceeded",
1823 };
1824
1825 let should_skip = active_thread
1826 .read(cx)
1827 .last_token_limit_telemetry
1828 .as_ref()
1829 .is_some_and(|last| *last >= ratio);
1830 if should_skip {
1831 return;
1832 }
1833
1834 active_thread.update(cx, |active, _cx| {
1835 active.last_token_limit_telemetry = Some(ratio);
1836 });
1837
1838 telemetry::event!(
1839 "Agent Token Limit Warning",
1840 agent = agent_telemetry_id,
1841 session_id = session_id,
1842 kind = kind,
1843 );
1844 }
1845
1846 fn emit_load_error_telemetry(&self, error: &LoadError) {
1847 let error_kind = match error {
1848 LoadError::Unsupported { .. } => "unsupported",
1849 LoadError::FailedToInstall(_) => "failed_to_install",
1850 LoadError::Exited { .. } => "exited",
1851 LoadError::Other(_) => "other",
1852 };
1853
1854 let agent_name = self.agent.name();
1855
1856 telemetry::event!(
1857 "Agent Panel Error Shown",
1858 agent = agent_name,
1859 kind = error_kind,
1860 message = error.to_string(),
1861 );
1862 }
1863
1864 fn render_load_error(
1865 &self,
1866 e: &LoadError,
1867 window: &mut Window,
1868 cx: &mut Context<Self>,
1869 ) -> AnyElement {
1870 let (title, message, action_slot): (_, SharedString, _) = match e {
1871 LoadError::Unsupported {
1872 command: path,
1873 current_version,
1874 minimum_version,
1875 } => {
1876 return self.render_unsupported(path, current_version, minimum_version, window, cx);
1877 }
1878 LoadError::FailedToInstall(msg) => (
1879 "Failed to Install",
1880 msg.into(),
1881 Some(self.create_copy_button(msg.to_string()).into_any_element()),
1882 ),
1883 LoadError::Exited { status } => (
1884 "Failed to Launch",
1885 format!("Server exited with status {status}").into(),
1886 None,
1887 ),
1888 LoadError::Other(msg) => (
1889 "Failed to Launch",
1890 msg.into(),
1891 Some(self.create_copy_button(msg.to_string()).into_any_element()),
1892 ),
1893 };
1894
1895 Callout::new()
1896 .severity(Severity::Error)
1897 .icon(IconName::XCircleFilled)
1898 .title(title)
1899 .description(message)
1900 .actions_slot(div().children(action_slot))
1901 .into_any_element()
1902 }
1903
1904 fn render_unsupported(
1905 &self,
1906 path: &SharedString,
1907 version: &SharedString,
1908 minimum_version: &SharedString,
1909 _window: &mut Window,
1910 cx: &mut Context<Self>,
1911 ) -> AnyElement {
1912 let (heading_label, description_label) = (
1913 format!("Upgrade {} to work with Zed", self.agent.name()),
1914 if version.is_empty() {
1915 format!(
1916 "Currently using {}, which does not report a valid --version",
1917 path,
1918 )
1919 } else {
1920 format!(
1921 "Currently using {}, which is only version {} (need at least {minimum_version})",
1922 path, version
1923 )
1924 },
1925 );
1926
1927 v_flex()
1928 .w_full()
1929 .p_3p5()
1930 .gap_2p5()
1931 .border_t_1()
1932 .border_color(cx.theme().colors().border)
1933 .bg(linear_gradient(
1934 180.,
1935 linear_color_stop(cx.theme().colors().editor_background.opacity(0.4), 4.),
1936 linear_color_stop(cx.theme().status().info_background.opacity(0.), 0.),
1937 ))
1938 .child(
1939 v_flex().gap_0p5().child(Label::new(heading_label)).child(
1940 Label::new(description_label)
1941 .size(LabelSize::Small)
1942 .color(Color::Muted),
1943 ),
1944 )
1945 .into_any_element()
1946 }
1947
1948 pub(crate) fn as_native_connection(
1949 &self,
1950 cx: &App,
1951 ) -> Option<Rc<agent::NativeAgentConnection>> {
1952 let acp_thread = self.active_thread()?.read(cx).thread.read(cx);
1953 acp_thread.connection().clone().downcast()
1954 }
1955
1956 pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
1957 let acp_thread = self.active_thread()?.read(cx).thread.read(cx);
1958 self.as_native_connection(cx)?
1959 .thread(acp_thread.session_id(), cx)
1960 }
1961
1962 fn queued_messages_len(&self, cx: &App) -> usize {
1963 self.active_thread()
1964 .map(|thread| thread.read(cx).local_queued_messages.len())
1965 .unwrap_or_default()
1966 }
1967
1968 fn update_queued_message(
1969 &mut self,
1970 index: usize,
1971 content: Vec<acp::ContentBlock>,
1972 tracked_buffers: Vec<Entity<Buffer>>,
1973 cx: &mut Context<Self>,
1974 ) -> bool {
1975 match self.active_thread() {
1976 Some(thread) => thread.update(cx, |thread, _cx| {
1977 if index < thread.local_queued_messages.len() {
1978 thread.local_queued_messages[index] = QueuedMessage {
1979 content,
1980 tracked_buffers,
1981 };
1982 true
1983 } else {
1984 false
1985 }
1986 }),
1987 None => false,
1988 }
1989 }
1990
1991 fn queued_message_contents(&self, cx: &App) -> Vec<Vec<acp::ContentBlock>> {
1992 match self.active_thread() {
1993 None => Vec::new(),
1994 Some(thread) => thread
1995 .read(cx)
1996 .local_queued_messages
1997 .iter()
1998 .map(|q| q.content.clone())
1999 .collect(),
2000 }
2001 }
2002
2003 fn save_queued_message_at_index(&mut self, index: usize, cx: &mut Context<Self>) {
2004 let editor = match self.active_thread() {
2005 Some(thread) => thread.read(cx).queued_message_editors.get(index).cloned(),
2006 None => None,
2007 };
2008 let Some(editor) = editor else {
2009 return;
2010 };
2011
2012 let contents_task = editor.update(cx, |editor, cx| editor.contents(false, cx));
2013
2014 cx.spawn(async move |this, cx| {
2015 let Ok((content, tracked_buffers)) = contents_task.await else {
2016 return Ok::<(), anyhow::Error>(());
2017 };
2018
2019 this.update(cx, |this, cx| {
2020 this.update_queued_message(index, content, tracked_buffers, cx);
2021 cx.notify();
2022 })?;
2023
2024 Ok(())
2025 })
2026 .detach_and_log_err(cx);
2027 }
2028
2029 fn sync_queued_message_editors(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2030 let needed_count = self.queued_messages_len(cx);
2031 let queued_messages = self.queued_message_contents(cx);
2032
2033 let agent_name = self.agent.name();
2034 let workspace = self.workspace.clone();
2035 let project = self.project.downgrade();
2036 let history = self.history.downgrade();
2037
2038 let Some(thread) = self.active_thread() else {
2039 return;
2040 };
2041 let prompt_capabilities = thread.read(cx).prompt_capabilities.clone();
2042 let available_commands = thread.read(cx).available_commands.clone();
2043
2044 let current_count = thread.read(cx).queued_message_editors.len();
2045 let last_synced = thread.read(cx).last_synced_queue_length;
2046
2047 if current_count == needed_count && needed_count == last_synced {
2048 return;
2049 }
2050
2051 if current_count > needed_count {
2052 thread.update(cx, |thread, _cx| {
2053 thread.queued_message_editors.truncate(needed_count);
2054 thread
2055 .queued_message_editor_subscriptions
2056 .truncate(needed_count);
2057 });
2058
2059 let editors = thread.read(cx).queued_message_editors.clone();
2060 for (index, editor) in editors.into_iter().enumerate() {
2061 if let Some(content) = queued_messages.get(index) {
2062 editor.update(cx, |editor, cx| {
2063 editor.set_message(content.clone(), window, cx);
2064 });
2065 }
2066 }
2067 }
2068
2069 while thread.read(cx).queued_message_editors.len() < needed_count {
2070 let index = thread.read(cx).queued_message_editors.len();
2071 let content = queued_messages.get(index).cloned().unwrap_or_default();
2072
2073 let editor = cx.new(|cx| {
2074 let mut editor = MessageEditor::new(
2075 workspace.clone(),
2076 project.clone(),
2077 None,
2078 history.clone(),
2079 None,
2080 prompt_capabilities.clone(),
2081 available_commands.clone(),
2082 agent_name.clone(),
2083 "",
2084 EditorMode::AutoHeight {
2085 min_lines: 1,
2086 max_lines: Some(10),
2087 },
2088 window,
2089 cx,
2090 );
2091 editor.set_message(content, window, cx);
2092 editor
2093 });
2094
2095 let subscription = cx.subscribe_in(
2096 &editor,
2097 window,
2098 move |this, _editor, event, window, cx| match event {
2099 MessageEditorEvent::LostFocus => {
2100 this.save_queued_message_at_index(index, cx);
2101 }
2102 MessageEditorEvent::Cancel => {
2103 window.focus(&this.focus_handle(cx), cx);
2104 }
2105 MessageEditorEvent::Send => {
2106 window.focus(&this.focus_handle(cx), cx);
2107 }
2108 MessageEditorEvent::SendImmediately => {
2109 this.send_queued_message_at_index(index, true, window, cx);
2110 }
2111 _ => {}
2112 },
2113 );
2114
2115 thread.update(cx, |thread, _cx| {
2116 thread.queued_message_editors.push(editor);
2117 thread
2118 .queued_message_editor_subscriptions
2119 .push(subscription);
2120 });
2121 }
2122
2123 if let Some(active) = self.active_thread() {
2124 active.update(cx, |active, _cx| {
2125 active.last_synced_queue_length = needed_count;
2126 });
2127 }
2128 }
2129
2130 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
2131 let workspace = self.workspace.clone();
2132 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
2133 crate::acp::thread_view::active_thread::open_link(text, &workspace, window, cx);
2134 })
2135 }
2136
2137 fn notify_with_sound(
2138 &mut self,
2139 caption: impl Into<SharedString>,
2140 icon: IconName,
2141 window: &mut Window,
2142 cx: &mut Context<Self>,
2143 ) {
2144 self.play_notification_sound(window, cx);
2145 self.show_notification(caption, icon, window, cx);
2146 }
2147
2148 fn agent_panel_visible(&self, multi_workspace: &Entity<MultiWorkspace>, cx: &App) -> bool {
2149 let Some(workspace) = self.workspace.upgrade() else {
2150 return false;
2151 };
2152
2153 multi_workspace.read(cx).workspace() == &workspace && AgentPanel::is_visible(&workspace, cx)
2154 }
2155
2156 fn agent_status_visible(&self, window: &Window, cx: &App) -> bool {
2157 if !window.is_window_active() {
2158 return false;
2159 }
2160
2161 if let Some(multi_workspace) = window.root::<MultiWorkspace>().flatten() {
2162 multi_workspace.read(cx).is_sidebar_open()
2163 || self.agent_panel_visible(&multi_workspace, cx)
2164 } else {
2165 self.workspace
2166 .upgrade()
2167 .is_some_and(|workspace| AgentPanel::is_visible(&workspace, cx))
2168 }
2169 }
2170
2171 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
2172 let settings = AgentSettings::get_global(cx);
2173 let visible = window.is_window_active()
2174 && if let Some(mw) = window.root::<MultiWorkspace>().flatten() {
2175 self.agent_panel_visible(&mw, cx)
2176 } else {
2177 self.workspace
2178 .upgrade()
2179 .is_some_and(|workspace| AgentPanel::is_visible(&workspace, cx))
2180 };
2181 if settings.play_sound_when_agent_done && !visible {
2182 Audio::play_sound(Sound::AgentDone, cx);
2183 }
2184 }
2185
2186 fn show_notification(
2187 &mut self,
2188 caption: impl Into<SharedString>,
2189 icon: IconName,
2190 window: &mut Window,
2191 cx: &mut Context<Self>,
2192 ) {
2193 if !self.notifications.is_empty() {
2194 return;
2195 }
2196
2197 let settings = AgentSettings::get_global(cx);
2198
2199 let should_notify = !self.agent_status_visible(window, cx);
2200
2201 if !should_notify {
2202 return;
2203 }
2204
2205 // TODO: Change this once we have title summarization for external agents.
2206 let title = self.agent.name();
2207
2208 match settings.notify_when_agent_waiting {
2209 NotifyWhenAgentWaiting::PrimaryScreen => {
2210 if let Some(primary) = cx.primary_display() {
2211 self.pop_up(icon, caption.into(), title, window, primary, cx);
2212 }
2213 }
2214 NotifyWhenAgentWaiting::AllScreens => {
2215 let caption = caption.into();
2216 for screen in cx.displays() {
2217 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
2218 }
2219 }
2220 NotifyWhenAgentWaiting::Never => {
2221 // Don't show anything
2222 }
2223 }
2224 }
2225
2226 fn pop_up(
2227 &mut self,
2228 icon: IconName,
2229 caption: SharedString,
2230 title: SharedString,
2231 window: &mut Window,
2232 screen: Rc<dyn PlatformDisplay>,
2233 cx: &mut Context<Self>,
2234 ) {
2235 let options = AgentNotification::window_options(screen, cx);
2236
2237 let project_name = self.workspace.upgrade().and_then(|workspace| {
2238 workspace
2239 .read(cx)
2240 .project()
2241 .read(cx)
2242 .visible_worktrees(cx)
2243 .next()
2244 .map(|worktree| worktree.read(cx).root_name_str().to_string())
2245 });
2246
2247 if let Some(screen_window) = cx
2248 .open_window(options, |_window, cx| {
2249 cx.new(|_cx| {
2250 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
2251 })
2252 })
2253 .log_err()
2254 && let Some(pop_up) = screen_window.entity(cx).log_err()
2255 {
2256 self.notification_subscriptions
2257 .entry(screen_window)
2258 .or_insert_with(Vec::new)
2259 .push(cx.subscribe_in(&pop_up, window, {
2260 |this, _, event, window, cx| match event {
2261 AgentNotificationEvent::Accepted => {
2262 let Some(handle) = window.window_handle().downcast::<MultiWorkspace>()
2263 else {
2264 log::error!("root view should be a MultiWorkspace");
2265 return;
2266 };
2267 cx.activate(true);
2268
2269 let workspace_handle = this.workspace.clone();
2270
2271 cx.defer(move |cx| {
2272 handle
2273 .update(cx, |multi_workspace, window, cx| {
2274 window.activate_window();
2275 if let Some(workspace) = workspace_handle.upgrade() {
2276 multi_workspace.activate(workspace.clone(), cx);
2277 workspace.update(cx, |workspace, cx| {
2278 workspace.focus_panel::<AgentPanel>(window, cx);
2279 });
2280 }
2281 })
2282 .log_err();
2283 });
2284
2285 this.dismiss_notifications(cx);
2286 }
2287 AgentNotificationEvent::Dismissed => {
2288 this.dismiss_notifications(cx);
2289 }
2290 }
2291 }));
2292
2293 self.notifications.push(screen_window);
2294
2295 // If the user manually refocuses the original window, dismiss the popup.
2296 self.notification_subscriptions
2297 .entry(screen_window)
2298 .or_insert_with(Vec::new)
2299 .push({
2300 let pop_up_weak = pop_up.downgrade();
2301
2302 cx.observe_window_activation(window, move |this, window, cx| {
2303 if this.agent_status_visible(window, cx)
2304 && let Some(pop_up) = pop_up_weak.upgrade()
2305 {
2306 pop_up.update(cx, |notification, cx| {
2307 notification.dismiss(cx);
2308 });
2309 }
2310 })
2311 });
2312 }
2313 }
2314
2315 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
2316 for window in self.notifications.drain(..) {
2317 window
2318 .update(cx, |_, window, _| {
2319 window.remove_window();
2320 })
2321 .ok();
2322
2323 self.notification_subscriptions.remove(&window);
2324 }
2325 }
2326
2327 fn agent_ui_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
2328 if let Some(entry_view_state) = self
2329 .active_thread()
2330 .map(|active| active.read(cx).entry_view_state.clone())
2331 {
2332 entry_view_state.update(cx, |entry_view_state, cx| {
2333 entry_view_state.agent_ui_font_size_changed(cx);
2334 });
2335 }
2336 }
2337
2338 pub(crate) fn insert_dragged_files(
2339 &self,
2340 paths: Vec<project::ProjectPath>,
2341 added_worktrees: Vec<Entity<project::Worktree>>,
2342 window: &mut Window,
2343 cx: &mut Context<Self>,
2344 ) {
2345 if let Some(active_thread) = self.active_thread() {
2346 active_thread.update(cx, |thread, cx| {
2347 thread.message_editor.update(cx, |editor, cx| {
2348 editor.insert_dragged_files(paths, added_worktrees, window, cx);
2349 editor.focus_handle(cx).focus(window, cx);
2350 })
2351 });
2352 }
2353 }
2354
2355 /// Inserts the selected text into the message editor or the message being
2356 /// edited, if any.
2357 pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
2358 if let Some(active_thread) = self.active_thread() {
2359 active_thread.update(cx, |thread, cx| {
2360 thread.active_editor(cx).update(cx, |editor, cx| {
2361 editor.insert_selections(window, cx);
2362 })
2363 });
2364 }
2365 }
2366
2367 /// Inserts terminal text as a crease into the message editor.
2368 pub(crate) fn insert_terminal_text(
2369 &self,
2370 text: String,
2371 window: &mut Window,
2372 cx: &mut Context<Self>,
2373 ) {
2374 if let Some(active_thread) = self.active_thread() {
2375 active_thread.update(cx, |thread, cx| {
2376 thread.message_editor.update(cx, |editor, cx| {
2377 editor.insert_terminal_crease(text, window, cx);
2378 })
2379 });
2380 }
2381 }
2382
2383 fn current_model_name(&self, cx: &App) -> SharedString {
2384 // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
2385 // For ACP agents, use the agent name (e.g., "Claude Agent", "Gemini CLI")
2386 // This provides better clarity about what refused the request
2387 if self.as_native_connection(cx).is_some() {
2388 self.active_thread()
2389 .and_then(|active| active.read(cx).model_selector.clone())
2390 .and_then(|selector| selector.read(cx).active_model(cx))
2391 .map(|model| model.name.clone())
2392 .unwrap_or_else(|| SharedString::from("The model"))
2393 } else {
2394 // ACP agent - use the agent name (e.g., "Claude Agent", "Gemini CLI")
2395 self.agent.name()
2396 }
2397 }
2398
2399 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
2400 let message = message.into();
2401
2402 CopyButton::new("copy-error-message", message).tooltip_label("Copy Error Message")
2403 }
2404
2405 pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2406 let agent_name = self.agent.name();
2407 if let Some(active) = self.active_thread() {
2408 active.update(cx, |active, cx| active.clear_thread_error(cx));
2409 }
2410 let this = cx.weak_entity();
2411 let Some(connection) = self.as_connected().map(|c| c.connection.clone()) else {
2412 debug_panic!("This should not be possible");
2413 return;
2414 };
2415 window.defer(cx, |window, cx| {
2416 Self::handle_auth_required(
2417 this,
2418 AuthRequired::new(),
2419 agent_name,
2420 connection,
2421 window,
2422 cx,
2423 );
2424 })
2425 }
2426
2427 pub fn delete_history_entry(&mut self, entry: AgentSessionInfo, cx: &mut Context<Self>) {
2428 let task = self.history.update(cx, |history, cx| {
2429 history.delete_session(&entry.session_id, cx)
2430 });
2431 task.detach_and_log_err(cx);
2432 }
2433}
2434
2435fn loading_contents_spinner(size: IconSize) -> AnyElement {
2436 Icon::new(IconName::LoadCircle)
2437 .size(size)
2438 .color(Color::Accent)
2439 .with_rotate_animation(3)
2440 .into_any_element()
2441}
2442
2443fn placeholder_text(agent_name: &str, has_commands: bool) -> String {
2444 if agent_name == "Zed Agent" {
2445 format!("Message the {} — @ to include context", agent_name)
2446 } else if has_commands {
2447 format!(
2448 "Message {} — @ to include context, / for commands",
2449 agent_name
2450 )
2451 } else {
2452 format!("Message {} — @ to include context", agent_name)
2453 }
2454}
2455
2456impl Focusable for AcpServerView {
2457 fn focus_handle(&self, cx: &App) -> FocusHandle {
2458 match self.active_thread() {
2459 Some(thread) => thread.read(cx).focus_handle(cx),
2460 None => self.focus_handle.clone(),
2461 }
2462 }
2463}
2464
2465#[cfg(any(test, feature = "test-support"))]
2466impl AcpServerView {
2467 /// Expands a tool call so its content is visible.
2468 /// This is primarily useful for visual testing.
2469 pub fn expand_tool_call(&mut self, tool_call_id: acp::ToolCallId, cx: &mut Context<Self>) {
2470 if let Some(active) = self.active_thread() {
2471 active.update(cx, |active, _cx| {
2472 active.expanded_tool_calls.insert(tool_call_id);
2473 });
2474 cx.notify();
2475 }
2476 }
2477
2478 /// Expands a subagent card so its content is visible.
2479 /// This is primarily useful for visual testing.
2480 pub fn expand_subagent(&mut self, session_id: acp::SessionId, cx: &mut Context<Self>) {
2481 if let Some(active) = self.active_thread() {
2482 active.update(cx, |active, _cx| {
2483 active.expanded_subagents.insert(session_id);
2484 });
2485 cx.notify();
2486 }
2487 }
2488}
2489
2490impl Render for AcpServerView {
2491 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2492 self.sync_queued_message_editors(window, cx);
2493
2494 v_flex()
2495 .track_focus(&self.focus_handle)
2496 .size_full()
2497 .bg(cx.theme().colors().panel_background)
2498 .child(match &self.server_state {
2499 ServerState::Loading { .. } => v_flex()
2500 .flex_1()
2501 // .child(self.render_recent_history(cx))
2502 .into_any(),
2503 ServerState::LoadError(e) => v_flex()
2504 .flex_1()
2505 .size_full()
2506 .items_center()
2507 .justify_end()
2508 .child(self.render_load_error(e, window, cx))
2509 .into_any(),
2510 ServerState::Connected(ConnectedServerState {
2511 connection,
2512 auth_state:
2513 AuthState::Unauthenticated {
2514 description,
2515 configuration_view,
2516 pending_auth_method,
2517 _subscription,
2518 },
2519 ..
2520 }) => v_flex()
2521 .flex_1()
2522 .size_full()
2523 .justify_end()
2524 .child(self.render_auth_required_state(
2525 connection,
2526 description.as_ref(),
2527 configuration_view.as_ref(),
2528 pending_auth_method.as_ref(),
2529 window,
2530 cx,
2531 ))
2532 .into_any_element(),
2533 ServerState::Connected(connected) => {
2534 if let Some(view) = connected.active_view() {
2535 view.clone().into_any_element()
2536 } else {
2537 debug_panic!("This state should never be reached");
2538 div().into_any_element()
2539 }
2540 }
2541 })
2542 }
2543}
2544
2545fn plan_label_markdown_style(
2546 status: &acp::PlanEntryStatus,
2547 window: &Window,
2548 cx: &App,
2549) -> MarkdownStyle {
2550 let default_md_style = MarkdownStyle::themed(MarkdownFont::Agent, window, cx);
2551
2552 MarkdownStyle {
2553 base_text_style: TextStyle {
2554 color: cx.theme().colors().text_muted,
2555 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
2556 Some(gpui::StrikethroughStyle {
2557 thickness: px(1.),
2558 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
2559 })
2560 } else {
2561 None
2562 },
2563 ..default_md_style.base_text_style
2564 },
2565 ..default_md_style
2566 }
2567}
2568
2569#[cfg(test)]
2570pub(crate) mod tests {
2571 use acp_thread::{
2572 AgentSessionList, AgentSessionListRequest, AgentSessionListResponse, StubAgentConnection,
2573 };
2574 use action_log::ActionLog;
2575 use agent::{AgentTool, EditFileTool, FetchTool, TerminalTool, ToolPermissionContext};
2576 use agent_client_protocol::SessionId;
2577 use assistant_text_thread::TextThreadStore;
2578 use editor::MultiBufferOffset;
2579 use fs::FakeFs;
2580 use gpui::{EventEmitter, TestAppContext, VisualTestContext};
2581 use parking_lot::Mutex;
2582 use project::Project;
2583 use serde_json::json;
2584 use settings::SettingsStore;
2585 use std::any::Any;
2586 use std::path::{Path, PathBuf};
2587 use std::rc::Rc;
2588 use std::sync::Arc;
2589 use workspace::{Item, MultiWorkspace};
2590
2591 use crate::agent_panel;
2592
2593 use super::*;
2594
2595 #[gpui::test]
2596 async fn test_drop(cx: &mut TestAppContext) {
2597 init_test(cx);
2598
2599 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
2600 let weak_view = thread_view.downgrade();
2601 drop(thread_view);
2602 assert!(!weak_view.is_upgradable());
2603 }
2604
2605 #[gpui::test]
2606 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
2607 init_test(cx);
2608
2609 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
2610
2611 let message_editor = message_editor(&thread_view, cx);
2612 message_editor.update_in(cx, |editor, window, cx| {
2613 editor.set_text("Hello", window, cx);
2614 });
2615
2616 cx.deactivate_window();
2617
2618 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
2619
2620 cx.run_until_parked();
2621
2622 assert!(
2623 cx.windows()
2624 .iter()
2625 .any(|window| window.downcast::<AgentNotification>().is_some())
2626 );
2627 }
2628
2629 #[gpui::test]
2630 async fn test_notification_for_error(cx: &mut TestAppContext) {
2631 init_test(cx);
2632
2633 let (thread_view, cx) =
2634 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
2635
2636 let message_editor = message_editor(&thread_view, cx);
2637 message_editor.update_in(cx, |editor, window, cx| {
2638 editor.set_text("Hello", window, cx);
2639 });
2640
2641 cx.deactivate_window();
2642
2643 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
2644
2645 cx.run_until_parked();
2646
2647 assert!(
2648 cx.windows()
2649 .iter()
2650 .any(|window| window.downcast::<AgentNotification>().is_some())
2651 );
2652 }
2653
2654 #[gpui::test]
2655 async fn test_recent_history_refreshes_when_history_cache_updated(cx: &mut TestAppContext) {
2656 init_test(cx);
2657
2658 let session_a = AgentSessionInfo::new(SessionId::new("session-a"));
2659 let session_b = AgentSessionInfo::new(SessionId::new("session-b"));
2660
2661 let fs = FakeFs::new(cx.executor());
2662 let project = Project::test(fs, [], cx).await;
2663 let (multi_workspace, cx) =
2664 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2665 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2666
2667 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
2668 // Create history without an initial session list - it will be set after connection
2669 let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
2670
2671 let thread_view = cx.update(|window, cx| {
2672 cx.new(|cx| {
2673 AcpServerView::new(
2674 Rc::new(StubAgentServer::default_response()),
2675 None,
2676 None,
2677 workspace.downgrade(),
2678 project,
2679 Some(thread_store),
2680 None,
2681 history.clone(),
2682 window,
2683 cx,
2684 )
2685 })
2686 });
2687
2688 // Wait for connection to establish
2689 cx.run_until_parked();
2690
2691 // Initially empty because StubAgentConnection.session_list() returns None
2692 active_thread(&thread_view, cx).read_with(cx, |view, _cx| {
2693 assert_eq!(view.recent_history_entries.len(), 0);
2694 });
2695
2696 // Now set the session list - this simulates external agents providing their history
2697 let list_a: Rc<dyn AgentSessionList> =
2698 Rc::new(StubSessionList::new(vec![session_a.clone()]));
2699 history.update(cx, |history, cx| {
2700 history.set_session_list(Some(list_a), cx);
2701 });
2702 cx.run_until_parked();
2703
2704 active_thread(&thread_view, cx).read_with(cx, |view, _cx| {
2705 assert_eq!(view.recent_history_entries.len(), 1);
2706 assert_eq!(
2707 view.recent_history_entries[0].session_id,
2708 session_a.session_id
2709 );
2710 });
2711
2712 // Update to a different session list
2713 let list_b: Rc<dyn AgentSessionList> =
2714 Rc::new(StubSessionList::new(vec![session_b.clone()]));
2715 history.update(cx, |history, cx| {
2716 history.set_session_list(Some(list_b), cx);
2717 });
2718 cx.run_until_parked();
2719
2720 active_thread(&thread_view, cx).read_with(cx, |view, _cx| {
2721 assert_eq!(view.recent_history_entries.len(), 1);
2722 assert_eq!(
2723 view.recent_history_entries[0].session_id,
2724 session_b.session_id
2725 );
2726 });
2727 }
2728
2729 #[gpui::test]
2730 async fn test_resume_without_history_adds_notice(cx: &mut TestAppContext) {
2731 init_test(cx);
2732
2733 let session = AgentSessionInfo::new(SessionId::new("resume-session"));
2734 let fs = FakeFs::new(cx.executor());
2735 let project = Project::test(fs, [], cx).await;
2736 let (multi_workspace, cx) =
2737 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2738 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2739
2740 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
2741 let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
2742
2743 let thread_view = cx.update(|window, cx| {
2744 cx.new(|cx| {
2745 AcpServerView::new(
2746 Rc::new(StubAgentServer::new(ResumeOnlyAgentConnection)),
2747 Some(session),
2748 None,
2749 workspace.downgrade(),
2750 project,
2751 Some(thread_store),
2752 None,
2753 history,
2754 window,
2755 cx,
2756 )
2757 })
2758 });
2759
2760 cx.run_until_parked();
2761
2762 thread_view.read_with(cx, |view, cx| {
2763 let state = view.active_thread().unwrap();
2764 assert!(state.read(cx).resumed_without_history);
2765 assert_eq!(state.read(cx).list_state.item_count(), 0);
2766 });
2767 }
2768
2769 #[gpui::test]
2770 async fn test_resume_thread_uses_session_cwd_when_inside_project(cx: &mut TestAppContext) {
2771 init_test(cx);
2772
2773 let fs = FakeFs::new(cx.executor());
2774 fs.insert_tree(
2775 "/project",
2776 json!({
2777 "subdir": {
2778 "file.txt": "hello"
2779 }
2780 }),
2781 )
2782 .await;
2783 let project = Project::test(fs, [Path::new("/project")], cx).await;
2784 let (multi_workspace, cx) =
2785 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2786 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2787
2788 let connection = CwdCapturingConnection::new();
2789 let captured_cwd = connection.captured_cwd.clone();
2790
2791 let mut session = AgentSessionInfo::new(SessionId::new("session-1"));
2792 session.cwd = Some(PathBuf::from("/project/subdir"));
2793
2794 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
2795 let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
2796
2797 let _thread_view = cx.update(|window, cx| {
2798 cx.new(|cx| {
2799 AcpServerView::new(
2800 Rc::new(StubAgentServer::new(connection)),
2801 Some(session),
2802 None,
2803 workspace.downgrade(),
2804 project,
2805 Some(thread_store),
2806 None,
2807 history,
2808 window,
2809 cx,
2810 )
2811 })
2812 });
2813
2814 cx.run_until_parked();
2815
2816 assert_eq!(
2817 captured_cwd.lock().as_deref(),
2818 Some(Path::new("/project/subdir")),
2819 "Should use session cwd when it's inside the project"
2820 );
2821 }
2822
2823 #[gpui::test]
2824 async fn test_resume_thread_uses_fallback_cwd_when_outside_project(cx: &mut TestAppContext) {
2825 init_test(cx);
2826
2827 let fs = FakeFs::new(cx.executor());
2828 fs.insert_tree(
2829 "/project",
2830 json!({
2831 "file.txt": "hello"
2832 }),
2833 )
2834 .await;
2835 let project = Project::test(fs, [Path::new("/project")], cx).await;
2836 let (multi_workspace, cx) =
2837 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2838 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2839
2840 let connection = CwdCapturingConnection::new();
2841 let captured_cwd = connection.captured_cwd.clone();
2842
2843 let mut session = AgentSessionInfo::new(SessionId::new("session-1"));
2844 session.cwd = Some(PathBuf::from("/some/other/path"));
2845
2846 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
2847 let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
2848
2849 let _thread_view = cx.update(|window, cx| {
2850 cx.new(|cx| {
2851 AcpServerView::new(
2852 Rc::new(StubAgentServer::new(connection)),
2853 Some(session),
2854 None,
2855 workspace.downgrade(),
2856 project,
2857 Some(thread_store),
2858 None,
2859 history,
2860 window,
2861 cx,
2862 )
2863 })
2864 });
2865
2866 cx.run_until_parked();
2867
2868 assert_eq!(
2869 captured_cwd.lock().as_deref(),
2870 Some(Path::new("/project")),
2871 "Should use fallback project cwd when session cwd is outside the project"
2872 );
2873 }
2874
2875 #[gpui::test]
2876 async fn test_resume_thread_rejects_unnormalized_cwd_outside_project(cx: &mut TestAppContext) {
2877 init_test(cx);
2878
2879 let fs = FakeFs::new(cx.executor());
2880 fs.insert_tree(
2881 "/project",
2882 json!({
2883 "file.txt": "hello"
2884 }),
2885 )
2886 .await;
2887 let project = Project::test(fs, [Path::new("/project")], cx).await;
2888 let (multi_workspace, cx) =
2889 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2890 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2891
2892 let connection = CwdCapturingConnection::new();
2893 let captured_cwd = connection.captured_cwd.clone();
2894
2895 let mut session = AgentSessionInfo::new(SessionId::new("session-1"));
2896 session.cwd = Some(PathBuf::from("/project/../outside"));
2897
2898 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
2899 let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
2900
2901 let _thread_view = cx.update(|window, cx| {
2902 cx.new(|cx| {
2903 AcpServerView::new(
2904 Rc::new(StubAgentServer::new(connection)),
2905 Some(session),
2906 None,
2907 workspace.downgrade(),
2908 project,
2909 Some(thread_store),
2910 None,
2911 history,
2912 window,
2913 cx,
2914 )
2915 })
2916 });
2917
2918 cx.run_until_parked();
2919
2920 assert_eq!(
2921 captured_cwd.lock().as_deref(),
2922 Some(Path::new("/project")),
2923 "Should reject unnormalized cwd that resolves outside the project and use fallback cwd"
2924 );
2925 }
2926
2927 #[gpui::test]
2928 async fn test_refusal_handling(cx: &mut TestAppContext) {
2929 init_test(cx);
2930
2931 let (thread_view, cx) =
2932 setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
2933
2934 let message_editor = message_editor(&thread_view, cx);
2935 message_editor.update_in(cx, |editor, window, cx| {
2936 editor.set_text("Do something harmful", window, cx);
2937 });
2938
2939 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
2940
2941 cx.run_until_parked();
2942
2943 // Check that the refusal error is set
2944 thread_view.read_with(cx, |thread_view, cx| {
2945 let state = thread_view.active_thread().unwrap();
2946 assert!(
2947 matches!(state.read(cx).thread_error, Some(ThreadError::Refusal)),
2948 "Expected refusal error to be set"
2949 );
2950 });
2951 }
2952
2953 #[gpui::test]
2954 async fn test_auth_required_on_initial_connect(cx: &mut TestAppContext) {
2955 init_test(cx);
2956
2957 let connection = AuthGatedAgentConnection::new();
2958 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
2959
2960 // When new_session returns AuthRequired, the server should transition
2961 // to Connected + Unauthenticated rather than getting stuck in Loading.
2962 thread_view.read_with(cx, |view, _cx| {
2963 let connected = view
2964 .as_connected()
2965 .expect("Should be in Connected state even though auth is required");
2966 assert!(
2967 !connected.auth_state.is_ok(),
2968 "Auth state should be Unauthenticated"
2969 );
2970 assert!(
2971 connected.active_id.is_none(),
2972 "There should be no active thread since no session was created"
2973 );
2974 assert!(
2975 connected.threads.is_empty(),
2976 "There should be no threads since no session was created"
2977 );
2978 });
2979
2980 thread_view.read_with(cx, |view, _cx| {
2981 assert!(
2982 view.active_thread().is_none(),
2983 "active_thread() should be None when unauthenticated without a session"
2984 );
2985 });
2986
2987 // Authenticate using the real authenticate flow on AcpServerView.
2988 // This calls connection.authenticate(), which flips the internal flag,
2989 // then on success triggers reset() -> new_session() which now succeeds.
2990 thread_view.update_in(cx, |view, window, cx| {
2991 view.authenticate(
2992 acp::AuthMethodId::new(AuthGatedAgentConnection::AUTH_METHOD_ID),
2993 window,
2994 cx,
2995 );
2996 });
2997 cx.run_until_parked();
2998
2999 // After auth, the server should have an active thread in the Ok state.
3000 thread_view.read_with(cx, |view, cx| {
3001 let connected = view
3002 .as_connected()
3003 .expect("Should still be in Connected state after auth");
3004 assert!(connected.auth_state.is_ok(), "Auth state should be Ok");
3005 assert!(
3006 connected.active_id.is_some(),
3007 "There should be an active thread after successful auth"
3008 );
3009 assert_eq!(
3010 connected.threads.len(),
3011 1,
3012 "There should be exactly one thread"
3013 );
3014
3015 let active = view
3016 .active_thread()
3017 .expect("active_thread() should return the new thread");
3018 assert!(
3019 active.read(cx).thread_error.is_none(),
3020 "The new thread should have no errors"
3021 );
3022 });
3023 }
3024
3025 #[gpui::test]
3026 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
3027 init_test(cx);
3028
3029 let tool_call_id = acp::ToolCallId::new("1");
3030 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Label")
3031 .kind(acp::ToolKind::Edit)
3032 .content(vec!["hi".into()]);
3033 let connection =
3034 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
3035 tool_call_id,
3036 PermissionOptions::Flat(vec![acp::PermissionOption::new(
3037 "1",
3038 "Allow",
3039 acp::PermissionOptionKind::AllowOnce,
3040 )]),
3041 )]));
3042
3043 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
3044
3045 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
3046
3047 let message_editor = message_editor(&thread_view, cx);
3048 message_editor.update_in(cx, |editor, window, cx| {
3049 editor.set_text("Hello", window, cx);
3050 });
3051
3052 cx.deactivate_window();
3053
3054 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
3055
3056 cx.run_until_parked();
3057
3058 assert!(
3059 cx.windows()
3060 .iter()
3061 .any(|window| window.downcast::<AgentNotification>().is_some())
3062 );
3063 }
3064
3065 #[gpui::test]
3066 async fn test_notification_when_panel_hidden(cx: &mut TestAppContext) {
3067 init_test(cx);
3068
3069 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
3070
3071 add_to_workspace(thread_view.clone(), cx);
3072
3073 let message_editor = message_editor(&thread_view, cx);
3074
3075 message_editor.update_in(cx, |editor, window, cx| {
3076 editor.set_text("Hello", window, cx);
3077 });
3078
3079 // Window is active (don't deactivate), but panel will be hidden
3080 // Note: In the test environment, the panel is not actually added to the dock,
3081 // so is_agent_panel_hidden will return true
3082
3083 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
3084
3085 cx.run_until_parked();
3086
3087 // Should show notification because window is active but panel is hidden
3088 assert!(
3089 cx.windows()
3090 .iter()
3091 .any(|window| window.downcast::<AgentNotification>().is_some()),
3092 "Expected notification when panel is hidden"
3093 );
3094 }
3095
3096 #[gpui::test]
3097 async fn test_notification_still_works_when_window_inactive(cx: &mut TestAppContext) {
3098 init_test(cx);
3099
3100 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
3101
3102 let message_editor = message_editor(&thread_view, cx);
3103 message_editor.update_in(cx, |editor, window, cx| {
3104 editor.set_text("Hello", window, cx);
3105 });
3106
3107 // Deactivate window - should show notification regardless of setting
3108 cx.deactivate_window();
3109
3110 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
3111
3112 cx.run_until_parked();
3113
3114 // Should still show notification when window is inactive (existing behavior)
3115 assert!(
3116 cx.windows()
3117 .iter()
3118 .any(|window| window.downcast::<AgentNotification>().is_some()),
3119 "Expected notification when window is inactive"
3120 );
3121 }
3122
3123 #[gpui::test]
3124 async fn test_notification_when_workspace_is_background_in_multi_workspace(
3125 cx: &mut TestAppContext,
3126 ) {
3127 init_test(cx);
3128
3129 // Enable multi-workspace feature flag and init globals needed by AgentPanel
3130 let fs = FakeFs::new(cx.executor());
3131
3132 cx.update(|cx| {
3133 cx.update_flags(true, vec!["agent-v2".to_string()]);
3134 agent::ThreadStore::init_global(cx);
3135 language_model::LanguageModelRegistry::test(cx);
3136 <dyn Fs>::set_global(fs.clone(), cx);
3137 });
3138
3139 let project1 = Project::test(fs.clone(), [], cx).await;
3140
3141 // Create a MultiWorkspace window with one workspace
3142 let multi_workspace_handle =
3143 cx.add_window(|window, cx| MultiWorkspace::test_new(project1.clone(), window, cx));
3144
3145 // Get workspace 1 (the initial workspace)
3146 let workspace1 = multi_workspace_handle
3147 .read_with(cx, |mw, _cx| mw.workspace().clone())
3148 .unwrap();
3149
3150 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
3151
3152 workspace1.update_in(cx, |workspace, window, cx| {
3153 let text_thread_store =
3154 cx.new(|cx| TextThreadStore::fake(workspace.project().clone(), cx));
3155 let panel =
3156 cx.new(|cx| crate::AgentPanel::new(workspace, text_thread_store, None, window, cx));
3157 workspace.add_panel(panel, window, cx);
3158
3159 // Open the dock and activate the agent panel so it's visible
3160 workspace.focus_panel::<crate::AgentPanel>(window, cx);
3161 });
3162
3163 cx.run_until_parked();
3164
3165 cx.read(|cx| {
3166 assert!(
3167 crate::AgentPanel::is_visible(&workspace1, cx),
3168 "AgentPanel should be visible in workspace1's dock"
3169 );
3170 });
3171
3172 // Set up thread view in workspace 1
3173 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3174 let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
3175
3176 let agent = StubAgentServer::default_response();
3177 let thread_view = cx.update(|window, cx| {
3178 cx.new(|cx| {
3179 AcpServerView::new(
3180 Rc::new(agent),
3181 None,
3182 None,
3183 workspace1.downgrade(),
3184 project1.clone(),
3185 Some(thread_store),
3186 None,
3187 history,
3188 window,
3189 cx,
3190 )
3191 })
3192 });
3193 cx.run_until_parked();
3194
3195 let message_editor = message_editor(&thread_view, cx);
3196 message_editor.update_in(cx, |editor, window, cx| {
3197 editor.set_text("Hello", window, cx);
3198 });
3199
3200 // Create a second workspace and switch to it.
3201 // This makes workspace1 the "background" workspace.
3202 let project2 = Project::test(fs, [], cx).await;
3203 multi_workspace_handle
3204 .update(cx, |mw, window, cx| {
3205 mw.test_add_workspace(project2, window, cx);
3206 })
3207 .unwrap();
3208
3209 cx.run_until_parked();
3210
3211 // Verify workspace1 is no longer the active workspace
3212 multi_workspace_handle
3213 .read_with(cx, |mw, _cx| {
3214 assert_eq!(mw.active_workspace_index(), 1);
3215 assert_ne!(mw.workspace(), &workspace1);
3216 })
3217 .unwrap();
3218
3219 // Window is active, agent panel is visible in workspace1, but workspace1
3220 // is in the background. The notification should show because the user
3221 // can't actually see the agent panel.
3222 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
3223
3224 cx.run_until_parked();
3225
3226 assert!(
3227 cx.windows()
3228 .iter()
3229 .any(|window| window.downcast::<AgentNotification>().is_some()),
3230 "Expected notification when workspace is in background within MultiWorkspace"
3231 );
3232
3233 // Also verify: clicking "View Panel" should switch to workspace1.
3234 cx.windows()
3235 .iter()
3236 .find_map(|window| window.downcast::<AgentNotification>())
3237 .unwrap()
3238 .update(cx, |window, _, cx| window.accept(cx))
3239 .unwrap();
3240
3241 cx.run_until_parked();
3242
3243 multi_workspace_handle
3244 .read_with(cx, |mw, _cx| {
3245 assert_eq!(
3246 mw.workspace(),
3247 &workspace1,
3248 "Expected workspace1 to become the active workspace after accepting notification"
3249 );
3250 })
3251 .unwrap();
3252 }
3253
3254 #[gpui::test]
3255 async fn test_notification_respects_never_setting(cx: &mut TestAppContext) {
3256 init_test(cx);
3257
3258 // Set notify_when_agent_waiting to Never
3259 cx.update(|cx| {
3260 AgentSettings::override_global(
3261 AgentSettings {
3262 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
3263 ..AgentSettings::get_global(cx).clone()
3264 },
3265 cx,
3266 );
3267 });
3268
3269 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
3270
3271 let message_editor = message_editor(&thread_view, cx);
3272 message_editor.update_in(cx, |editor, window, cx| {
3273 editor.set_text("Hello", window, cx);
3274 });
3275
3276 // Window is active
3277
3278 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
3279
3280 cx.run_until_parked();
3281
3282 // Should NOT show notification because notify_when_agent_waiting is Never
3283 assert!(
3284 !cx.windows()
3285 .iter()
3286 .any(|window| window.downcast::<AgentNotification>().is_some()),
3287 "Expected no notification when notify_when_agent_waiting is Never"
3288 );
3289 }
3290
3291 #[gpui::test]
3292 async fn test_notification_closed_when_thread_view_dropped(cx: &mut TestAppContext) {
3293 init_test(cx);
3294
3295 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
3296
3297 let weak_view = thread_view.downgrade();
3298
3299 let message_editor = message_editor(&thread_view, cx);
3300 message_editor.update_in(cx, |editor, window, cx| {
3301 editor.set_text("Hello", window, cx);
3302 });
3303
3304 cx.deactivate_window();
3305
3306 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
3307
3308 cx.run_until_parked();
3309
3310 // Verify notification is shown
3311 assert!(
3312 cx.windows()
3313 .iter()
3314 .any(|window| window.downcast::<AgentNotification>().is_some()),
3315 "Expected notification to be shown"
3316 );
3317
3318 // Drop the thread view (simulating navigation to a new thread)
3319 drop(thread_view);
3320 drop(message_editor);
3321 // Trigger an update to flush effects, which will call release_dropped_entities
3322 cx.update(|_window, _cx| {});
3323 cx.run_until_parked();
3324
3325 // Verify the entity was actually released
3326 assert!(
3327 !weak_view.is_upgradable(),
3328 "Thread view entity should be released after dropping"
3329 );
3330
3331 // The notification should be automatically closed via on_release
3332 assert!(
3333 !cx.windows()
3334 .iter()
3335 .any(|window| window.downcast::<AgentNotification>().is_some()),
3336 "Notification should be closed when thread view is dropped"
3337 );
3338 }
3339
3340 async fn setup_thread_view(
3341 agent: impl AgentServer + 'static,
3342 cx: &mut TestAppContext,
3343 ) -> (Entity<AcpServerView>, &mut VisualTestContext) {
3344 let fs = FakeFs::new(cx.executor());
3345 let project = Project::test(fs, [], cx).await;
3346 let (multi_workspace, cx) =
3347 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3348 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3349
3350 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3351 let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
3352
3353 let thread_view = cx.update(|window, cx| {
3354 cx.new(|cx| {
3355 AcpServerView::new(
3356 Rc::new(agent),
3357 None,
3358 None,
3359 workspace.downgrade(),
3360 project,
3361 Some(thread_store),
3362 None,
3363 history,
3364 window,
3365 cx,
3366 )
3367 })
3368 });
3369 cx.run_until_parked();
3370 (thread_view, cx)
3371 }
3372
3373 fn add_to_workspace(thread_view: Entity<AcpServerView>, cx: &mut VisualTestContext) {
3374 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
3375
3376 workspace
3377 .update_in(cx, |workspace, window, cx| {
3378 workspace.add_item_to_active_pane(
3379 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
3380 None,
3381 true,
3382 window,
3383 cx,
3384 );
3385 })
3386 .unwrap();
3387 }
3388
3389 struct ThreadViewItem(Entity<AcpServerView>);
3390
3391 impl Item for ThreadViewItem {
3392 type Event = ();
3393
3394 fn include_in_nav_history() -> bool {
3395 false
3396 }
3397
3398 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
3399 "Test".into()
3400 }
3401 }
3402
3403 impl EventEmitter<()> for ThreadViewItem {}
3404
3405 impl Focusable for ThreadViewItem {
3406 fn focus_handle(&self, cx: &App) -> FocusHandle {
3407 self.0.read(cx).focus_handle(cx)
3408 }
3409 }
3410
3411 impl Render for ThreadViewItem {
3412 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3413 self.0.clone().into_any_element()
3414 }
3415 }
3416
3417 pub(crate) struct StubAgentServer<C> {
3418 connection: C,
3419 }
3420
3421 impl<C> StubAgentServer<C> {
3422 pub(crate) fn new(connection: C) -> Self {
3423 Self { connection }
3424 }
3425 }
3426
3427 impl StubAgentServer<StubAgentConnection> {
3428 pub(crate) fn default_response() -> Self {
3429 let conn = StubAgentConnection::new();
3430 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3431 acp::ContentChunk::new("Default response".into()),
3432 )]);
3433 Self::new(conn)
3434 }
3435 }
3436
3437 impl<C> AgentServer for StubAgentServer<C>
3438 where
3439 C: 'static + AgentConnection + Send + Clone,
3440 {
3441 fn logo(&self) -> ui::IconName {
3442 ui::IconName::Ai
3443 }
3444
3445 fn name(&self) -> SharedString {
3446 "Test".into()
3447 }
3448
3449 fn connect(
3450 &self,
3451 _root_dir: Option<&Path>,
3452 _delegate: AgentServerDelegate,
3453 _cx: &mut App,
3454 ) -> Task<gpui::Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
3455 Task::ready(Ok((Rc::new(self.connection.clone()), None)))
3456 }
3457
3458 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3459 self
3460 }
3461 }
3462
3463 #[derive(Clone)]
3464 struct StubSessionList {
3465 sessions: Vec<AgentSessionInfo>,
3466 }
3467
3468 impl StubSessionList {
3469 fn new(sessions: Vec<AgentSessionInfo>) -> Self {
3470 Self { sessions }
3471 }
3472 }
3473
3474 impl AgentSessionList for StubSessionList {
3475 fn list_sessions(
3476 &self,
3477 _request: AgentSessionListRequest,
3478 _cx: &mut App,
3479 ) -> Task<anyhow::Result<AgentSessionListResponse>> {
3480 Task::ready(Ok(AgentSessionListResponse::new(self.sessions.clone())))
3481 }
3482 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3483 self
3484 }
3485 }
3486
3487 #[derive(Clone)]
3488 struct ResumeOnlyAgentConnection;
3489
3490 impl AgentConnection for ResumeOnlyAgentConnection {
3491 fn telemetry_id(&self) -> SharedString {
3492 "resume-only".into()
3493 }
3494
3495 fn new_session(
3496 self: Rc<Self>,
3497 project: Entity<Project>,
3498 _cwd: &Path,
3499 cx: &mut gpui::App,
3500 ) -> Task<gpui::Result<Entity<AcpThread>>> {
3501 let action_log = cx.new(|_| ActionLog::new(project.clone()));
3502 let thread = cx.new(|cx| {
3503 AcpThread::new(
3504 None,
3505 "ResumeOnlyAgentConnection",
3506 self.clone(),
3507 project,
3508 action_log,
3509 SessionId::new("new-session"),
3510 watch::Receiver::constant(
3511 acp::PromptCapabilities::new()
3512 .image(true)
3513 .audio(true)
3514 .embedded_context(true),
3515 ),
3516 cx,
3517 )
3518 });
3519 Task::ready(Ok(thread))
3520 }
3521
3522 fn supports_resume_session(&self) -> bool {
3523 true
3524 }
3525
3526 fn resume_session(
3527 self: Rc<Self>,
3528 session: AgentSessionInfo,
3529 project: Entity<Project>,
3530 _cwd: &Path,
3531 cx: &mut App,
3532 ) -> Task<gpui::Result<Entity<AcpThread>>> {
3533 let action_log = cx.new(|_| ActionLog::new(project.clone()));
3534 let thread = cx.new(|cx| {
3535 AcpThread::new(
3536 None,
3537 "ResumeOnlyAgentConnection",
3538 self.clone(),
3539 project,
3540 action_log,
3541 session.session_id,
3542 watch::Receiver::constant(
3543 acp::PromptCapabilities::new()
3544 .image(true)
3545 .audio(true)
3546 .embedded_context(true),
3547 ),
3548 cx,
3549 )
3550 });
3551 Task::ready(Ok(thread))
3552 }
3553
3554 fn auth_methods(&self) -> &[acp::AuthMethod] {
3555 &[]
3556 }
3557
3558 fn authenticate(
3559 &self,
3560 _method_id: acp::AuthMethodId,
3561 _cx: &mut App,
3562 ) -> Task<gpui::Result<()>> {
3563 Task::ready(Ok(()))
3564 }
3565
3566 fn prompt(
3567 &self,
3568 _id: Option<acp_thread::UserMessageId>,
3569 _params: acp::PromptRequest,
3570 _cx: &mut App,
3571 ) -> Task<gpui::Result<acp::PromptResponse>> {
3572 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
3573 }
3574
3575 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
3576
3577 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3578 self
3579 }
3580 }
3581
3582 /// Simulates an agent that requires authentication before a session can be
3583 /// created. `new_session` returns `AuthRequired` until `authenticate` is
3584 /// called with the correct method, after which sessions are created normally.
3585 #[derive(Clone)]
3586 struct AuthGatedAgentConnection {
3587 authenticated: Arc<Mutex<bool>>,
3588 auth_method: acp::AuthMethod,
3589 }
3590
3591 impl AuthGatedAgentConnection {
3592 const AUTH_METHOD_ID: &str = "test-login";
3593
3594 fn new() -> Self {
3595 Self {
3596 authenticated: Arc::new(Mutex::new(false)),
3597 auth_method: acp::AuthMethod::new(Self::AUTH_METHOD_ID, "Test Login"),
3598 }
3599 }
3600 }
3601
3602 impl AgentConnection for AuthGatedAgentConnection {
3603 fn telemetry_id(&self) -> SharedString {
3604 "auth-gated".into()
3605 }
3606
3607 fn new_session(
3608 self: Rc<Self>,
3609 project: Entity<Project>,
3610 _cwd: &Path,
3611 cx: &mut gpui::App,
3612 ) -> Task<gpui::Result<Entity<AcpThread>>> {
3613 if !*self.authenticated.lock() {
3614 return Task::ready(Err(acp_thread::AuthRequired::new()
3615 .with_description("Sign in to continue".to_string())
3616 .into()));
3617 }
3618
3619 let session_id = acp::SessionId::new("auth-gated-session");
3620 let action_log = cx.new(|_| ActionLog::new(project.clone()));
3621 Task::ready(Ok(cx.new(|cx| {
3622 AcpThread::new(
3623 None,
3624 "AuthGatedAgent",
3625 self,
3626 project,
3627 action_log,
3628 session_id,
3629 watch::Receiver::constant(
3630 acp::PromptCapabilities::new()
3631 .image(true)
3632 .audio(true)
3633 .embedded_context(true),
3634 ),
3635 cx,
3636 )
3637 })))
3638 }
3639
3640 fn auth_methods(&self) -> &[acp::AuthMethod] {
3641 std::slice::from_ref(&self.auth_method)
3642 }
3643
3644 fn authenticate(
3645 &self,
3646 method_id: acp::AuthMethodId,
3647 _cx: &mut App,
3648 ) -> Task<gpui::Result<()>> {
3649 if method_id == self.auth_method.id {
3650 *self.authenticated.lock() = true;
3651 Task::ready(Ok(()))
3652 } else {
3653 Task::ready(Err(anyhow::anyhow!("Unknown auth method")))
3654 }
3655 }
3656
3657 fn prompt(
3658 &self,
3659 _id: Option<acp_thread::UserMessageId>,
3660 _params: acp::PromptRequest,
3661 _cx: &mut App,
3662 ) -> Task<gpui::Result<acp::PromptResponse>> {
3663 unimplemented!()
3664 }
3665
3666 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
3667 unimplemented!()
3668 }
3669
3670 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3671 self
3672 }
3673 }
3674
3675 #[derive(Clone)]
3676 struct SaboteurAgentConnection;
3677
3678 impl AgentConnection for SaboteurAgentConnection {
3679 fn telemetry_id(&self) -> SharedString {
3680 "saboteur".into()
3681 }
3682
3683 fn new_session(
3684 self: Rc<Self>,
3685 project: Entity<Project>,
3686 _cwd: &Path,
3687 cx: &mut gpui::App,
3688 ) -> Task<gpui::Result<Entity<AcpThread>>> {
3689 Task::ready(Ok(cx.new(|cx| {
3690 let action_log = cx.new(|_| ActionLog::new(project.clone()));
3691 AcpThread::new(
3692 None,
3693 "SaboteurAgentConnection",
3694 self,
3695 project,
3696 action_log,
3697 SessionId::new("test"),
3698 watch::Receiver::constant(
3699 acp::PromptCapabilities::new()
3700 .image(true)
3701 .audio(true)
3702 .embedded_context(true),
3703 ),
3704 cx,
3705 )
3706 })))
3707 }
3708
3709 fn auth_methods(&self) -> &[acp::AuthMethod] {
3710 &[]
3711 }
3712
3713 fn authenticate(
3714 &self,
3715 _method_id: acp::AuthMethodId,
3716 _cx: &mut App,
3717 ) -> Task<gpui::Result<()>> {
3718 unimplemented!()
3719 }
3720
3721 fn prompt(
3722 &self,
3723 _id: Option<acp_thread::UserMessageId>,
3724 _params: acp::PromptRequest,
3725 _cx: &mut App,
3726 ) -> Task<gpui::Result<acp::PromptResponse>> {
3727 Task::ready(Err(anyhow::anyhow!("Error prompting")))
3728 }
3729
3730 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
3731 unimplemented!()
3732 }
3733
3734 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3735 self
3736 }
3737 }
3738
3739 /// Simulates a model which always returns a refusal response
3740 #[derive(Clone)]
3741 struct RefusalAgentConnection;
3742
3743 impl AgentConnection for RefusalAgentConnection {
3744 fn telemetry_id(&self) -> SharedString {
3745 "refusal".into()
3746 }
3747
3748 fn new_session(
3749 self: Rc<Self>,
3750 project: Entity<Project>,
3751 _cwd: &Path,
3752 cx: &mut gpui::App,
3753 ) -> Task<gpui::Result<Entity<AcpThread>>> {
3754 Task::ready(Ok(cx.new(|cx| {
3755 let action_log = cx.new(|_| ActionLog::new(project.clone()));
3756 AcpThread::new(
3757 None,
3758 "RefusalAgentConnection",
3759 self,
3760 project,
3761 action_log,
3762 SessionId::new("test"),
3763 watch::Receiver::constant(
3764 acp::PromptCapabilities::new()
3765 .image(true)
3766 .audio(true)
3767 .embedded_context(true),
3768 ),
3769 cx,
3770 )
3771 })))
3772 }
3773
3774 fn auth_methods(&self) -> &[acp::AuthMethod] {
3775 &[]
3776 }
3777
3778 fn authenticate(
3779 &self,
3780 _method_id: acp::AuthMethodId,
3781 _cx: &mut App,
3782 ) -> Task<gpui::Result<()>> {
3783 unimplemented!()
3784 }
3785
3786 fn prompt(
3787 &self,
3788 _id: Option<acp_thread::UserMessageId>,
3789 _params: acp::PromptRequest,
3790 _cx: &mut App,
3791 ) -> Task<gpui::Result<acp::PromptResponse>> {
3792 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::Refusal)))
3793 }
3794
3795 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
3796 unimplemented!()
3797 }
3798
3799 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3800 self
3801 }
3802 }
3803
3804 #[derive(Clone)]
3805 struct CwdCapturingConnection {
3806 captured_cwd: Arc<Mutex<Option<PathBuf>>>,
3807 }
3808
3809 impl CwdCapturingConnection {
3810 fn new() -> Self {
3811 Self {
3812 captured_cwd: Arc::new(Mutex::new(None)),
3813 }
3814 }
3815 }
3816
3817 impl AgentConnection for CwdCapturingConnection {
3818 fn telemetry_id(&self) -> SharedString {
3819 "cwd-capturing".into()
3820 }
3821
3822 fn new_session(
3823 self: Rc<Self>,
3824 project: Entity<Project>,
3825 cwd: &Path,
3826 cx: &mut gpui::App,
3827 ) -> Task<gpui::Result<Entity<AcpThread>>> {
3828 *self.captured_cwd.lock() = Some(cwd.to_path_buf());
3829 let action_log = cx.new(|_| ActionLog::new(project.clone()));
3830 let thread = cx.new(|cx| {
3831 AcpThread::new(
3832 None,
3833 "CwdCapturingConnection",
3834 self.clone(),
3835 project,
3836 action_log,
3837 SessionId::new("new-session"),
3838 watch::Receiver::constant(
3839 acp::PromptCapabilities::new()
3840 .image(true)
3841 .audio(true)
3842 .embedded_context(true),
3843 ),
3844 cx,
3845 )
3846 });
3847 Task::ready(Ok(thread))
3848 }
3849
3850 fn supports_load_session(&self) -> bool {
3851 true
3852 }
3853
3854 fn load_session(
3855 self: Rc<Self>,
3856 session: AgentSessionInfo,
3857 project: Entity<Project>,
3858 cwd: &Path,
3859 cx: &mut App,
3860 ) -> Task<gpui::Result<Entity<AcpThread>>> {
3861 *self.captured_cwd.lock() = Some(cwd.to_path_buf());
3862 let action_log = cx.new(|_| ActionLog::new(project.clone()));
3863 let thread = cx.new(|cx| {
3864 AcpThread::new(
3865 None,
3866 "CwdCapturingConnection",
3867 self.clone(),
3868 project,
3869 action_log,
3870 session.session_id,
3871 watch::Receiver::constant(
3872 acp::PromptCapabilities::new()
3873 .image(true)
3874 .audio(true)
3875 .embedded_context(true),
3876 ),
3877 cx,
3878 )
3879 });
3880 Task::ready(Ok(thread))
3881 }
3882
3883 fn auth_methods(&self) -> &[acp::AuthMethod] {
3884 &[]
3885 }
3886
3887 fn authenticate(
3888 &self,
3889 _method_id: acp::AuthMethodId,
3890 _cx: &mut App,
3891 ) -> Task<gpui::Result<()>> {
3892 Task::ready(Ok(()))
3893 }
3894
3895 fn prompt(
3896 &self,
3897 _id: Option<acp_thread::UserMessageId>,
3898 _params: acp::PromptRequest,
3899 _cx: &mut App,
3900 ) -> Task<gpui::Result<acp::PromptResponse>> {
3901 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
3902 }
3903
3904 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
3905
3906 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3907 self
3908 }
3909 }
3910
3911 pub(crate) fn init_test(cx: &mut TestAppContext) {
3912 cx.update(|cx| {
3913 let settings_store = SettingsStore::test(cx);
3914 cx.set_global(settings_store);
3915 theme::init(theme::LoadThemes::JustBase, cx);
3916 editor::init(cx);
3917 agent_panel::init(cx);
3918 release_channel::init(semver::Version::new(0, 0, 0), cx);
3919 prompt_store::init(cx)
3920 });
3921 }
3922
3923 fn active_thread(
3924 thread_view: &Entity<AcpServerView>,
3925 cx: &TestAppContext,
3926 ) -> Entity<AcpThreadView> {
3927 cx.read(|cx| {
3928 thread_view
3929 .read(cx)
3930 .active_thread()
3931 .expect("No active thread")
3932 .clone()
3933 })
3934 }
3935
3936 fn message_editor(
3937 thread_view: &Entity<AcpServerView>,
3938 cx: &TestAppContext,
3939 ) -> Entity<MessageEditor> {
3940 let thread = active_thread(thread_view, cx);
3941 cx.read(|cx| thread.read(cx).message_editor.clone())
3942 }
3943
3944 #[gpui::test]
3945 async fn test_rewind_views(cx: &mut TestAppContext) {
3946 init_test(cx);
3947
3948 let fs = FakeFs::new(cx.executor());
3949 fs.insert_tree(
3950 "/project",
3951 json!({
3952 "test1.txt": "old content 1",
3953 "test2.txt": "old content 2"
3954 }),
3955 )
3956 .await;
3957 let project = Project::test(fs, [Path::new("/project")], cx).await;
3958 let (multi_workspace, cx) =
3959 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3960 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3961
3962 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3963 let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
3964
3965 let connection = Rc::new(StubAgentConnection::new());
3966 let thread_view = cx.update(|window, cx| {
3967 cx.new(|cx| {
3968 AcpServerView::new(
3969 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
3970 None,
3971 None,
3972 workspace.downgrade(),
3973 project.clone(),
3974 Some(thread_store.clone()),
3975 None,
3976 history,
3977 window,
3978 cx,
3979 )
3980 })
3981 });
3982
3983 cx.run_until_parked();
3984
3985 let thread = thread_view
3986 .read_with(cx, |view, cx| {
3987 view.active_thread().map(|r| r.read(cx).thread.clone())
3988 })
3989 .unwrap();
3990
3991 // First user message
3992 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
3993 acp::ToolCall::new("tool1", "Edit file 1")
3994 .kind(acp::ToolKind::Edit)
3995 .status(acp::ToolCallStatus::Completed)
3996 .content(vec![acp::ToolCallContent::Diff(
3997 acp::Diff::new("/project/test1.txt", "new content 1").old_text("old content 1"),
3998 )]),
3999 )]);
4000
4001 thread
4002 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
4003 .await
4004 .unwrap();
4005 cx.run_until_parked();
4006
4007 thread.read_with(cx, |thread, _cx| {
4008 assert_eq!(thread.entries().len(), 2);
4009 });
4010
4011 thread_view.read_with(cx, |view, cx| {
4012 let entry_view_state = view
4013 .active_thread()
4014 .map(|active| active.read(cx).entry_view_state.clone())
4015 .unwrap();
4016 entry_view_state.read_with(cx, |entry_view_state, _| {
4017 assert!(
4018 entry_view_state
4019 .entry(0)
4020 .unwrap()
4021 .message_editor()
4022 .is_some()
4023 );
4024 assert!(entry_view_state.entry(1).unwrap().has_content());
4025 });
4026 });
4027
4028 // Second user message
4029 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
4030 acp::ToolCall::new("tool2", "Edit file 2")
4031 .kind(acp::ToolKind::Edit)
4032 .status(acp::ToolCallStatus::Completed)
4033 .content(vec![acp::ToolCallContent::Diff(
4034 acp::Diff::new("/project/test2.txt", "new content 2").old_text("old content 2"),
4035 )]),
4036 )]);
4037
4038 thread
4039 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
4040 .await
4041 .unwrap();
4042 cx.run_until_parked();
4043
4044 let second_user_message_id = thread.read_with(cx, |thread, _| {
4045 assert_eq!(thread.entries().len(), 4);
4046 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
4047 panic!();
4048 };
4049 user_message.id.clone().unwrap()
4050 });
4051
4052 thread_view.read_with(cx, |view, cx| {
4053 let entry_view_state = view
4054 .active_thread()
4055 .unwrap()
4056 .read(cx)
4057 .entry_view_state
4058 .clone();
4059 entry_view_state.read_with(cx, |entry_view_state, _| {
4060 assert!(
4061 entry_view_state
4062 .entry(0)
4063 .unwrap()
4064 .message_editor()
4065 .is_some()
4066 );
4067 assert!(entry_view_state.entry(1).unwrap().has_content());
4068 assert!(
4069 entry_view_state
4070 .entry(2)
4071 .unwrap()
4072 .message_editor()
4073 .is_some()
4074 );
4075 assert!(entry_view_state.entry(3).unwrap().has_content());
4076 });
4077 });
4078
4079 // Rewind to first message
4080 thread
4081 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
4082 .await
4083 .unwrap();
4084
4085 cx.run_until_parked();
4086
4087 thread.read_with(cx, |thread, _| {
4088 assert_eq!(thread.entries().len(), 2);
4089 });
4090
4091 thread_view.read_with(cx, |view, cx| {
4092 let active = view.active_thread().unwrap();
4093 active
4094 .read(cx)
4095 .entry_view_state
4096 .read_with(cx, |entry_view_state, _| {
4097 assert!(
4098 entry_view_state
4099 .entry(0)
4100 .unwrap()
4101 .message_editor()
4102 .is_some()
4103 );
4104 assert!(entry_view_state.entry(1).unwrap().has_content());
4105
4106 // Old views should be dropped
4107 assert!(entry_view_state.entry(2).is_none());
4108 assert!(entry_view_state.entry(3).is_none());
4109 });
4110 });
4111 }
4112
4113 #[gpui::test]
4114 async fn test_scroll_to_most_recent_user_prompt(cx: &mut TestAppContext) {
4115 init_test(cx);
4116
4117 let connection = StubAgentConnection::new();
4118
4119 // Each user prompt will result in a user message entry plus an agent message entry.
4120 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4121 acp::ContentChunk::new("Response 1".into()),
4122 )]);
4123
4124 let (thread_view, cx) =
4125 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4126
4127 let thread = thread_view
4128 .read_with(cx, |view, cx| {
4129 view.active_thread().map(|r| r.read(cx).thread.clone())
4130 })
4131 .unwrap();
4132
4133 thread
4134 .update(cx, |thread, cx| thread.send_raw("Prompt 1", cx))
4135 .await
4136 .unwrap();
4137 cx.run_until_parked();
4138
4139 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4140 acp::ContentChunk::new("Response 2".into()),
4141 )]);
4142
4143 thread
4144 .update(cx, |thread, cx| thread.send_raw("Prompt 2", cx))
4145 .await
4146 .unwrap();
4147 cx.run_until_parked();
4148
4149 // Move somewhere else first so we're not trivially already on the last user prompt.
4150 active_thread(&thread_view, cx).update(cx, |view, cx| {
4151 view.scroll_to_top(cx);
4152 });
4153 cx.run_until_parked();
4154
4155 active_thread(&thread_view, cx).update(cx, |view, cx| {
4156 view.scroll_to_most_recent_user_prompt(cx);
4157 let scroll_top = view.list_state.logical_scroll_top();
4158 // Entries layout is: [User1, Assistant1, User2, Assistant2]
4159 assert_eq!(scroll_top.item_ix, 2);
4160 });
4161 }
4162
4163 #[gpui::test]
4164 async fn test_scroll_to_most_recent_user_prompt_falls_back_to_bottom_without_user_messages(
4165 cx: &mut TestAppContext,
4166 ) {
4167 init_test(cx);
4168
4169 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
4170
4171 // With no entries, scrolling should be a no-op and must not panic.
4172 active_thread(&thread_view, cx).update(cx, |view, cx| {
4173 view.scroll_to_most_recent_user_prompt(cx);
4174 let scroll_top = view.list_state.logical_scroll_top();
4175 assert_eq!(scroll_top.item_ix, 0);
4176 });
4177 }
4178
4179 #[gpui::test]
4180 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
4181 init_test(cx);
4182
4183 let connection = StubAgentConnection::new();
4184
4185 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4186 acp::ContentChunk::new("Response".into()),
4187 )]);
4188
4189 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4190 add_to_workspace(thread_view.clone(), cx);
4191
4192 let message_editor = message_editor(&thread_view, cx);
4193 message_editor.update_in(cx, |editor, window, cx| {
4194 editor.set_text("Original message to edit", window, cx);
4195 });
4196 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4197
4198 cx.run_until_parked();
4199
4200 let user_message_editor = thread_view.read_with(cx, |view, cx| {
4201 assert_eq!(
4202 view.active_thread()
4203 .and_then(|active| active.read(cx).editing_message),
4204 None
4205 );
4206
4207 view.active_thread()
4208 .map(|active| &active.read(cx).entry_view_state)
4209 .as_ref()
4210 .unwrap()
4211 .read(cx)
4212 .entry(0)
4213 .unwrap()
4214 .message_editor()
4215 .unwrap()
4216 .clone()
4217 });
4218
4219 // Focus
4220 cx.focus(&user_message_editor);
4221 thread_view.read_with(cx, |view, cx| {
4222 assert_eq!(
4223 view.active_thread()
4224 .and_then(|active| active.read(cx).editing_message),
4225 Some(0)
4226 );
4227 });
4228
4229 // Edit
4230 user_message_editor.update_in(cx, |editor, window, cx| {
4231 editor.set_text("Edited message content", window, cx);
4232 });
4233
4234 // Cancel
4235 user_message_editor.update_in(cx, |_editor, window, cx| {
4236 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
4237 });
4238
4239 thread_view.read_with(cx, |view, cx| {
4240 assert_eq!(
4241 view.active_thread()
4242 .and_then(|active| active.read(cx).editing_message),
4243 None
4244 );
4245 });
4246
4247 user_message_editor.read_with(cx, |editor, cx| {
4248 assert_eq!(editor.text(cx), "Original message to edit");
4249 });
4250 }
4251
4252 #[gpui::test]
4253 async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
4254 init_test(cx);
4255
4256 let connection = StubAgentConnection::new();
4257
4258 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4259 add_to_workspace(thread_view.clone(), cx);
4260
4261 let message_editor = message_editor(&thread_view, cx);
4262 message_editor.update_in(cx, |editor, window, cx| {
4263 editor.set_text("", window, cx);
4264 });
4265
4266 let thread = cx.read(|cx| {
4267 thread_view
4268 .read(cx)
4269 .active_thread()
4270 .unwrap()
4271 .read(cx)
4272 .thread
4273 .clone()
4274 });
4275 let entries_before = cx.read(|cx| thread.read(cx).entries().len());
4276
4277 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| {
4278 view.send(window, cx);
4279 });
4280 cx.run_until_parked();
4281
4282 let entries_after = cx.read(|cx| thread.read(cx).entries().len());
4283 assert_eq!(
4284 entries_before, entries_after,
4285 "No message should be sent when editor is empty"
4286 );
4287 }
4288
4289 #[gpui::test]
4290 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
4291 init_test(cx);
4292
4293 let connection = StubAgentConnection::new();
4294
4295 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4296 acp::ContentChunk::new("Response".into()),
4297 )]);
4298
4299 let (thread_view, cx) =
4300 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4301 add_to_workspace(thread_view.clone(), cx);
4302
4303 let message_editor = message_editor(&thread_view, cx);
4304 message_editor.update_in(cx, |editor, window, cx| {
4305 editor.set_text("Original message to edit", window, cx);
4306 });
4307 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4308
4309 cx.run_until_parked();
4310
4311 let user_message_editor = thread_view.read_with(cx, |view, cx| {
4312 assert_eq!(
4313 view.active_thread()
4314 .and_then(|active| active.read(cx).editing_message),
4315 None
4316 );
4317 assert_eq!(
4318 view.active_thread()
4319 .unwrap()
4320 .read(cx)
4321 .thread
4322 .read(cx)
4323 .entries()
4324 .len(),
4325 2
4326 );
4327
4328 view.active_thread()
4329 .map(|active| &active.read(cx).entry_view_state)
4330 .as_ref()
4331 .unwrap()
4332 .read(cx)
4333 .entry(0)
4334 .unwrap()
4335 .message_editor()
4336 .unwrap()
4337 .clone()
4338 });
4339
4340 // Focus
4341 cx.focus(&user_message_editor);
4342
4343 // Edit
4344 user_message_editor.update_in(cx, |editor, window, cx| {
4345 editor.set_text("Edited message content", window, cx);
4346 });
4347
4348 // Send
4349 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4350 acp::ContentChunk::new("New Response".into()),
4351 )]);
4352
4353 user_message_editor.update_in(cx, |_editor, window, cx| {
4354 window.dispatch_action(Box::new(Chat), cx);
4355 });
4356
4357 cx.run_until_parked();
4358
4359 thread_view.read_with(cx, |view, cx| {
4360 assert_eq!(
4361 view.active_thread()
4362 .and_then(|active| active.read(cx).editing_message),
4363 None
4364 );
4365
4366 let entries = view
4367 .active_thread()
4368 .unwrap()
4369 .read(cx)
4370 .thread
4371 .read(cx)
4372 .entries();
4373 assert_eq!(entries.len(), 2);
4374 assert_eq!(
4375 entries[0].to_markdown(cx),
4376 "## User\n\nEdited message content\n\n"
4377 );
4378 assert_eq!(
4379 entries[1].to_markdown(cx),
4380 "## Assistant\n\nNew Response\n\n"
4381 );
4382
4383 let entry_view_state = view
4384 .active_thread()
4385 .map(|active| &active.read(cx).entry_view_state)
4386 .unwrap();
4387 let new_editor = entry_view_state.read_with(cx, |state, _cx| {
4388 assert!(!state.entry(1).unwrap().has_content());
4389 state.entry(0).unwrap().message_editor().unwrap().clone()
4390 });
4391
4392 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
4393 })
4394 }
4395
4396 #[gpui::test]
4397 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
4398 init_test(cx);
4399
4400 let connection = StubAgentConnection::new();
4401
4402 let (thread_view, cx) =
4403 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4404 add_to_workspace(thread_view.clone(), cx);
4405
4406 let message_editor = message_editor(&thread_view, cx);
4407 message_editor.update_in(cx, |editor, window, cx| {
4408 editor.set_text("Original message to edit", window, cx);
4409 });
4410 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4411
4412 cx.run_until_parked();
4413
4414 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
4415 let thread = view.active_thread().unwrap().read(cx).thread.read(cx);
4416 assert_eq!(thread.entries().len(), 1);
4417
4418 let editor = view
4419 .active_thread()
4420 .map(|active| &active.read(cx).entry_view_state)
4421 .as_ref()
4422 .unwrap()
4423 .read(cx)
4424 .entry(0)
4425 .unwrap()
4426 .message_editor()
4427 .unwrap()
4428 .clone();
4429
4430 (editor, thread.session_id().clone())
4431 });
4432
4433 // Focus
4434 cx.focus(&user_message_editor);
4435
4436 thread_view.read_with(cx, |view, cx| {
4437 assert_eq!(
4438 view.active_thread()
4439 .and_then(|active| active.read(cx).editing_message),
4440 Some(0)
4441 );
4442 });
4443
4444 // Edit
4445 user_message_editor.update_in(cx, |editor, window, cx| {
4446 editor.set_text("Edited message content", window, cx);
4447 });
4448
4449 thread_view.read_with(cx, |view, cx| {
4450 assert_eq!(
4451 view.active_thread()
4452 .and_then(|active| active.read(cx).editing_message),
4453 Some(0)
4454 );
4455 });
4456
4457 // Finish streaming response
4458 cx.update(|_, cx| {
4459 connection.send_update(
4460 session_id.clone(),
4461 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("Response".into())),
4462 cx,
4463 );
4464 connection.end_turn(session_id, acp::StopReason::EndTurn);
4465 });
4466
4467 thread_view.read_with(cx, |view, cx| {
4468 assert_eq!(
4469 view.active_thread()
4470 .and_then(|active| active.read(cx).editing_message),
4471 Some(0)
4472 );
4473 });
4474
4475 cx.run_until_parked();
4476
4477 // Should still be editing
4478 cx.update(|window, cx| {
4479 assert!(user_message_editor.focus_handle(cx).is_focused(window));
4480 assert_eq!(
4481 thread_view
4482 .read(cx)
4483 .active_thread()
4484 .and_then(|active| active.read(cx).editing_message),
4485 Some(0)
4486 );
4487 assert_eq!(
4488 user_message_editor.read(cx).text(cx),
4489 "Edited message content"
4490 );
4491 });
4492 }
4493
4494 struct GeneratingThreadSetup {
4495 thread_view: Entity<AcpServerView>,
4496 thread: Entity<AcpThread>,
4497 message_editor: Entity<MessageEditor>,
4498 }
4499
4500 async fn setup_generating_thread(
4501 cx: &mut TestAppContext,
4502 ) -> (GeneratingThreadSetup, &mut VisualTestContext) {
4503 let connection = StubAgentConnection::new();
4504
4505 let (thread_view, cx) =
4506 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4507 add_to_workspace(thread_view.clone(), cx);
4508
4509 let message_editor = message_editor(&thread_view, cx);
4510 message_editor.update_in(cx, |editor, window, cx| {
4511 editor.set_text("Hello", window, cx);
4512 });
4513 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4514
4515 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
4516 let thread = view
4517 .active_thread()
4518 .as_ref()
4519 .unwrap()
4520 .read(cx)
4521 .thread
4522 .clone();
4523 (thread.clone(), thread.read(cx).session_id().clone())
4524 });
4525
4526 cx.run_until_parked();
4527
4528 cx.update(|_, cx| {
4529 connection.send_update(
4530 session_id.clone(),
4531 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
4532 "Response chunk".into(),
4533 )),
4534 cx,
4535 );
4536 });
4537
4538 cx.run_until_parked();
4539
4540 thread.read_with(cx, |thread, _cx| {
4541 assert_eq!(thread.status(), ThreadStatus::Generating);
4542 });
4543
4544 (
4545 GeneratingThreadSetup {
4546 thread_view,
4547 thread,
4548 message_editor,
4549 },
4550 cx,
4551 )
4552 }
4553
4554 #[gpui::test]
4555 async fn test_escape_cancels_generation_from_conversation_focus(cx: &mut TestAppContext) {
4556 init_test(cx);
4557
4558 let (setup, cx) = setup_generating_thread(cx).await;
4559
4560 let focus_handle = setup
4561 .thread_view
4562 .read_with(cx, |view, cx| view.focus_handle(cx));
4563 cx.update(|window, cx| {
4564 window.focus(&focus_handle, cx);
4565 });
4566
4567 setup.thread_view.update_in(cx, |_, window, cx| {
4568 window.dispatch_action(menu::Cancel.boxed_clone(), cx);
4569 });
4570
4571 cx.run_until_parked();
4572
4573 setup.thread.read_with(cx, |thread, _cx| {
4574 assert_eq!(thread.status(), ThreadStatus::Idle);
4575 });
4576 }
4577
4578 #[gpui::test]
4579 async fn test_escape_cancels_generation_from_editor_focus(cx: &mut TestAppContext) {
4580 init_test(cx);
4581
4582 let (setup, cx) = setup_generating_thread(cx).await;
4583
4584 let editor_focus_handle = setup
4585 .message_editor
4586 .read_with(cx, |editor, cx| editor.focus_handle(cx));
4587 cx.update(|window, cx| {
4588 window.focus(&editor_focus_handle, cx);
4589 });
4590
4591 setup.message_editor.update_in(cx, |_, window, cx| {
4592 window.dispatch_action(editor::actions::Cancel.boxed_clone(), cx);
4593 });
4594
4595 cx.run_until_parked();
4596
4597 setup.thread.read_with(cx, |thread, _cx| {
4598 assert_eq!(thread.status(), ThreadStatus::Idle);
4599 });
4600 }
4601
4602 #[gpui::test]
4603 async fn test_escape_when_idle_is_noop(cx: &mut TestAppContext) {
4604 init_test(cx);
4605
4606 let (thread_view, cx) =
4607 setup_thread_view(StubAgentServer::new(StubAgentConnection::new()), cx).await;
4608 add_to_workspace(thread_view.clone(), cx);
4609
4610 let thread = thread_view.read_with(cx, |view, cx| {
4611 view.active_thread().unwrap().read(cx).thread.clone()
4612 });
4613
4614 thread.read_with(cx, |thread, _cx| {
4615 assert_eq!(thread.status(), ThreadStatus::Idle);
4616 });
4617
4618 let focus_handle = thread_view.read_with(cx, |view, _cx| view.focus_handle.clone());
4619 cx.update(|window, cx| {
4620 window.focus(&focus_handle, cx);
4621 });
4622
4623 thread_view.update_in(cx, |_, window, cx| {
4624 window.dispatch_action(menu::Cancel.boxed_clone(), cx);
4625 });
4626
4627 cx.run_until_parked();
4628
4629 thread.read_with(cx, |thread, _cx| {
4630 assert_eq!(thread.status(), ThreadStatus::Idle);
4631 });
4632 }
4633
4634 #[gpui::test]
4635 async fn test_interrupt(cx: &mut TestAppContext) {
4636 init_test(cx);
4637
4638 let connection = StubAgentConnection::new();
4639
4640 let (thread_view, cx) =
4641 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4642 add_to_workspace(thread_view.clone(), cx);
4643
4644 let message_editor = message_editor(&thread_view, cx);
4645 message_editor.update_in(cx, |editor, window, cx| {
4646 editor.set_text("Message 1", window, cx);
4647 });
4648 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4649
4650 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
4651 let thread = view.active_thread().unwrap().read(cx).thread.clone();
4652
4653 (thread.clone(), thread.read(cx).session_id().clone())
4654 });
4655
4656 cx.run_until_parked();
4657
4658 cx.update(|_, cx| {
4659 connection.send_update(
4660 session_id.clone(),
4661 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
4662 "Message 1 resp".into(),
4663 )),
4664 cx,
4665 );
4666 });
4667
4668 cx.run_until_parked();
4669
4670 thread.read_with(cx, |thread, cx| {
4671 assert_eq!(
4672 thread.to_markdown(cx),
4673 indoc::indoc! {"
4674 ## User
4675
4676 Message 1
4677
4678 ## Assistant
4679
4680 Message 1 resp
4681
4682 "}
4683 )
4684 });
4685
4686 message_editor.update_in(cx, |editor, window, cx| {
4687 editor.set_text("Message 2", window, cx);
4688 });
4689 active_thread(&thread_view, cx)
4690 .update_in(cx, |view, window, cx| view.interrupt_and_send(window, cx));
4691
4692 cx.update(|_, cx| {
4693 // Simulate a response sent after beginning to cancel
4694 connection.send_update(
4695 session_id.clone(),
4696 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("onse".into())),
4697 cx,
4698 );
4699 });
4700
4701 cx.run_until_parked();
4702
4703 // Last Message 1 response should appear before Message 2
4704 thread.read_with(cx, |thread, cx| {
4705 assert_eq!(
4706 thread.to_markdown(cx),
4707 indoc::indoc! {"
4708 ## User
4709
4710 Message 1
4711
4712 ## Assistant
4713
4714 Message 1 response
4715
4716 ## User
4717
4718 Message 2
4719
4720 "}
4721 )
4722 });
4723
4724 cx.update(|_, cx| {
4725 connection.send_update(
4726 session_id.clone(),
4727 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
4728 "Message 2 response".into(),
4729 )),
4730 cx,
4731 );
4732 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
4733 });
4734
4735 cx.run_until_parked();
4736
4737 thread.read_with(cx, |thread, cx| {
4738 assert_eq!(
4739 thread.to_markdown(cx),
4740 indoc::indoc! {"
4741 ## User
4742
4743 Message 1
4744
4745 ## Assistant
4746
4747 Message 1 response
4748
4749 ## User
4750
4751 Message 2
4752
4753 ## Assistant
4754
4755 Message 2 response
4756
4757 "}
4758 )
4759 });
4760 }
4761
4762 #[gpui::test]
4763 async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
4764 init_test(cx);
4765
4766 let connection = StubAgentConnection::new();
4767 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4768 acp::ContentChunk::new("Response".into()),
4769 )]);
4770
4771 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4772 add_to_workspace(thread_view.clone(), cx);
4773
4774 let message_editor = message_editor(&thread_view, cx);
4775 message_editor.update_in(cx, |editor, window, cx| {
4776 editor.set_text("Original message to edit", window, cx)
4777 });
4778 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4779 cx.run_until_parked();
4780
4781 let user_message_editor = thread_view.read_with(cx, |thread_view, cx| {
4782 thread_view
4783 .active_thread()
4784 .map(|active| &active.read(cx).entry_view_state)
4785 .as_ref()
4786 .unwrap()
4787 .read(cx)
4788 .entry(0)
4789 .expect("Should have at least one entry")
4790 .message_editor()
4791 .expect("Should have message editor")
4792 .clone()
4793 });
4794
4795 cx.focus(&user_message_editor);
4796 thread_view.read_with(cx, |view, cx| {
4797 assert_eq!(
4798 view.active_thread()
4799 .and_then(|active| active.read(cx).editing_message),
4800 Some(0)
4801 );
4802 });
4803
4804 // Ensure to edit the focused message before proceeding otherwise, since
4805 // its content is not different from what was sent, focus will be lost.
4806 user_message_editor.update_in(cx, |editor, window, cx| {
4807 editor.set_text("Original message to edit with ", window, cx)
4808 });
4809
4810 // Create a simple buffer with some text so we can create a selection
4811 // that will then be added to the message being edited.
4812 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
4813 (thread_view.workspace.clone(), thread_view.project.clone())
4814 });
4815 let buffer = project.update(cx, |project, cx| {
4816 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
4817 });
4818
4819 workspace
4820 .update_in(cx, |workspace, window, cx| {
4821 let editor = cx.new(|cx| {
4822 let mut editor =
4823 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
4824
4825 editor.change_selections(Default::default(), window, cx, |selections| {
4826 selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
4827 });
4828
4829 editor
4830 });
4831 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
4832 })
4833 .unwrap();
4834
4835 thread_view.update_in(cx, |view, window, cx| {
4836 assert_eq!(
4837 view.active_thread()
4838 .and_then(|active| active.read(cx).editing_message),
4839 Some(0)
4840 );
4841 view.insert_selections(window, cx);
4842 });
4843
4844 user_message_editor.read_with(cx, |editor, cx| {
4845 let text = editor.editor().read(cx).text(cx);
4846 let expected_text = String::from("Original message to edit with selection ");
4847
4848 assert_eq!(text, expected_text);
4849 });
4850 }
4851
4852 #[gpui::test]
4853 async fn test_insert_selections(cx: &mut TestAppContext) {
4854 init_test(cx);
4855
4856 let connection = StubAgentConnection::new();
4857 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4858 acp::ContentChunk::new("Response".into()),
4859 )]);
4860
4861 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4862 add_to_workspace(thread_view.clone(), cx);
4863
4864 let message_editor = message_editor(&thread_view, cx);
4865 message_editor.update_in(cx, |editor, window, cx| {
4866 editor.set_text("Can you review this snippet ", window, cx)
4867 });
4868
4869 // Create a simple buffer with some text so we can create a selection
4870 // that will then be added to the message being edited.
4871 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
4872 (thread_view.workspace.clone(), thread_view.project.clone())
4873 });
4874 let buffer = project.update(cx, |project, cx| {
4875 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
4876 });
4877
4878 workspace
4879 .update_in(cx, |workspace, window, cx| {
4880 let editor = cx.new(|cx| {
4881 let mut editor =
4882 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
4883
4884 editor.change_selections(Default::default(), window, cx, |selections| {
4885 selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
4886 });
4887
4888 editor
4889 });
4890 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
4891 })
4892 .unwrap();
4893
4894 thread_view.update_in(cx, |view, window, cx| {
4895 assert_eq!(
4896 view.active_thread()
4897 .and_then(|active| active.read(cx).editing_message),
4898 None
4899 );
4900 view.insert_selections(window, cx);
4901 });
4902
4903 message_editor.read_with(cx, |editor, cx| {
4904 let text = editor.text(cx);
4905 let expected_txt = String::from("Can you review this snippet selection ");
4906
4907 assert_eq!(text, expected_txt);
4908 })
4909 }
4910
4911 #[gpui::test]
4912 async fn test_tool_permission_buttons_terminal_with_pattern(cx: &mut TestAppContext) {
4913 init_test(cx);
4914
4915 let tool_call_id = acp::ToolCallId::new("terminal-1");
4916 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build --release`")
4917 .kind(acp::ToolKind::Edit);
4918
4919 let permission_options = ToolPermissionContext::new(
4920 TerminalTool::NAME,
4921 vec!["cargo build --release".to_string()],
4922 )
4923 .build_permission_options();
4924
4925 let connection =
4926 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
4927 tool_call_id.clone(),
4928 permission_options,
4929 )]));
4930
4931 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
4932
4933 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4934
4935 // Disable notifications to avoid popup windows
4936 cx.update(|_window, cx| {
4937 AgentSettings::override_global(
4938 AgentSettings {
4939 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
4940 ..AgentSettings::get_global(cx).clone()
4941 },
4942 cx,
4943 );
4944 });
4945
4946 let message_editor = message_editor(&thread_view, cx);
4947 message_editor.update_in(cx, |editor, window, cx| {
4948 editor.set_text("Run cargo build", window, cx);
4949 });
4950
4951 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4952
4953 cx.run_until_parked();
4954
4955 // Verify the tool call is in WaitingForConfirmation state with the expected options
4956 thread_view.read_with(cx, |thread_view, cx| {
4957 let thread = thread_view
4958 .active_thread()
4959 .expect("Thread should exist")
4960 .read(cx)
4961 .thread
4962 .clone();
4963 let thread = thread.read(cx);
4964
4965 let tool_call = thread.entries().iter().find_map(|entry| {
4966 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
4967 Some(call)
4968 } else {
4969 None
4970 }
4971 });
4972
4973 assert!(tool_call.is_some(), "Expected a tool call entry");
4974 let tool_call = tool_call.unwrap();
4975
4976 // Verify it's waiting for confirmation
4977 assert!(
4978 matches!(
4979 tool_call.status,
4980 acp_thread::ToolCallStatus::WaitingForConfirmation { .. }
4981 ),
4982 "Expected WaitingForConfirmation status, got {:?}",
4983 tool_call.status
4984 );
4985
4986 // Verify the options count (granularity options only, no separate Deny option)
4987 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
4988 &tool_call.status
4989 {
4990 let PermissionOptions::Dropdown(choices) = options else {
4991 panic!("Expected dropdown permission options");
4992 };
4993
4994 assert_eq!(
4995 choices.len(),
4996 3,
4997 "Expected 3 permission options (granularity only)"
4998 );
4999
5000 // Verify specific button labels (now using neutral names)
5001 let labels: Vec<&str> = choices
5002 .iter()
5003 .map(|choice| choice.allow.name.as_ref())
5004 .collect();
5005 assert!(
5006 labels.contains(&"Always for terminal"),
5007 "Missing 'Always for terminal' option"
5008 );
5009 assert!(
5010 labels.contains(&"Always for `cargo build` commands"),
5011 "Missing pattern option"
5012 );
5013 assert!(
5014 labels.contains(&"Only this time"),
5015 "Missing 'Only this time' option"
5016 );
5017 }
5018 });
5019 }
5020
5021 #[gpui::test]
5022 async fn test_tool_permission_buttons_edit_file_with_path_pattern(cx: &mut TestAppContext) {
5023 init_test(cx);
5024
5025 let tool_call_id = acp::ToolCallId::new("edit-file-1");
5026 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Edit `src/main.rs`")
5027 .kind(acp::ToolKind::Edit);
5028
5029 let permission_options =
5030 ToolPermissionContext::new(EditFileTool::NAME, vec!["src/main.rs".to_string()])
5031 .build_permission_options();
5032
5033 let connection =
5034 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5035 tool_call_id.clone(),
5036 permission_options,
5037 )]));
5038
5039 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5040
5041 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5042
5043 // Disable notifications
5044 cx.update(|_window, cx| {
5045 AgentSettings::override_global(
5046 AgentSettings {
5047 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5048 ..AgentSettings::get_global(cx).clone()
5049 },
5050 cx,
5051 );
5052 });
5053
5054 let message_editor = message_editor(&thread_view, cx);
5055 message_editor.update_in(cx, |editor, window, cx| {
5056 editor.set_text("Edit the main file", window, cx);
5057 });
5058
5059 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5060
5061 cx.run_until_parked();
5062
5063 // Verify the options
5064 thread_view.read_with(cx, |thread_view, cx| {
5065 let thread = thread_view
5066 .active_thread()
5067 .expect("Thread should exist")
5068 .read(cx)
5069 .thread
5070 .clone();
5071 let thread = thread.read(cx);
5072
5073 let tool_call = thread.entries().iter().find_map(|entry| {
5074 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5075 Some(call)
5076 } else {
5077 None
5078 }
5079 });
5080
5081 assert!(tool_call.is_some(), "Expected a tool call entry");
5082 let tool_call = tool_call.unwrap();
5083
5084 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5085 &tool_call.status
5086 {
5087 let PermissionOptions::Dropdown(choices) = options else {
5088 panic!("Expected dropdown permission options");
5089 };
5090
5091 let labels: Vec<&str> = choices
5092 .iter()
5093 .map(|choice| choice.allow.name.as_ref())
5094 .collect();
5095 assert!(
5096 labels.contains(&"Always for edit file"),
5097 "Missing 'Always for edit file' option"
5098 );
5099 assert!(
5100 labels.contains(&"Always for `src/`"),
5101 "Missing path pattern option"
5102 );
5103 } else {
5104 panic!("Expected WaitingForConfirmation status");
5105 }
5106 });
5107 }
5108
5109 #[gpui::test]
5110 async fn test_tool_permission_buttons_fetch_with_domain_pattern(cx: &mut TestAppContext) {
5111 init_test(cx);
5112
5113 let tool_call_id = acp::ToolCallId::new("fetch-1");
5114 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Fetch `https://docs.rs/gpui`")
5115 .kind(acp::ToolKind::Fetch);
5116
5117 let permission_options =
5118 ToolPermissionContext::new(FetchTool::NAME, vec!["https://docs.rs/gpui".to_string()])
5119 .build_permission_options();
5120
5121 let connection =
5122 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5123 tool_call_id.clone(),
5124 permission_options,
5125 )]));
5126
5127 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5128
5129 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5130
5131 // Disable notifications
5132 cx.update(|_window, cx| {
5133 AgentSettings::override_global(
5134 AgentSettings {
5135 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5136 ..AgentSettings::get_global(cx).clone()
5137 },
5138 cx,
5139 );
5140 });
5141
5142 let message_editor = message_editor(&thread_view, cx);
5143 message_editor.update_in(cx, |editor, window, cx| {
5144 editor.set_text("Fetch the docs", window, cx);
5145 });
5146
5147 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5148
5149 cx.run_until_parked();
5150
5151 // Verify the options
5152 thread_view.read_with(cx, |thread_view, cx| {
5153 let thread = thread_view
5154 .active_thread()
5155 .expect("Thread should exist")
5156 .read(cx)
5157 .thread
5158 .clone();
5159 let thread = thread.read(cx);
5160
5161 let tool_call = thread.entries().iter().find_map(|entry| {
5162 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5163 Some(call)
5164 } else {
5165 None
5166 }
5167 });
5168
5169 assert!(tool_call.is_some(), "Expected a tool call entry");
5170 let tool_call = tool_call.unwrap();
5171
5172 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5173 &tool_call.status
5174 {
5175 let PermissionOptions::Dropdown(choices) = options else {
5176 panic!("Expected dropdown permission options");
5177 };
5178
5179 let labels: Vec<&str> = choices
5180 .iter()
5181 .map(|choice| choice.allow.name.as_ref())
5182 .collect();
5183 assert!(
5184 labels.contains(&"Always for fetch"),
5185 "Missing 'Always for fetch' option"
5186 );
5187 assert!(
5188 labels.contains(&"Always for `docs.rs`"),
5189 "Missing domain pattern option"
5190 );
5191 } else {
5192 panic!("Expected WaitingForConfirmation status");
5193 }
5194 });
5195 }
5196
5197 #[gpui::test]
5198 async fn test_tool_permission_buttons_without_pattern(cx: &mut TestAppContext) {
5199 init_test(cx);
5200
5201 let tool_call_id = acp::ToolCallId::new("terminal-no-pattern-1");
5202 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `./deploy.sh --production`")
5203 .kind(acp::ToolKind::Edit);
5204
5205 // No pattern button since ./deploy.sh doesn't match the alphanumeric pattern
5206 let permission_options = ToolPermissionContext::new(
5207 TerminalTool::NAME,
5208 vec!["./deploy.sh --production".to_string()],
5209 )
5210 .build_permission_options();
5211
5212 let connection =
5213 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5214 tool_call_id.clone(),
5215 permission_options,
5216 )]));
5217
5218 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5219
5220 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5221
5222 // Disable notifications
5223 cx.update(|_window, cx| {
5224 AgentSettings::override_global(
5225 AgentSettings {
5226 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5227 ..AgentSettings::get_global(cx).clone()
5228 },
5229 cx,
5230 );
5231 });
5232
5233 let message_editor = message_editor(&thread_view, cx);
5234 message_editor.update_in(cx, |editor, window, cx| {
5235 editor.set_text("Run the deploy script", window, cx);
5236 });
5237
5238 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5239
5240 cx.run_until_parked();
5241
5242 // Verify only 2 options (no pattern button when command doesn't match pattern)
5243 thread_view.read_with(cx, |thread_view, cx| {
5244 let thread = thread_view
5245 .active_thread()
5246 .expect("Thread should exist")
5247 .read(cx)
5248 .thread
5249 .clone();
5250 let thread = thread.read(cx);
5251
5252 let tool_call = thread.entries().iter().find_map(|entry| {
5253 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5254 Some(call)
5255 } else {
5256 None
5257 }
5258 });
5259
5260 assert!(tool_call.is_some(), "Expected a tool call entry");
5261 let tool_call = tool_call.unwrap();
5262
5263 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5264 &tool_call.status
5265 {
5266 let PermissionOptions::Dropdown(choices) = options else {
5267 panic!("Expected dropdown permission options");
5268 };
5269
5270 assert_eq!(
5271 choices.len(),
5272 2,
5273 "Expected 2 permission options (no pattern option)"
5274 );
5275
5276 let labels: Vec<&str> = choices
5277 .iter()
5278 .map(|choice| choice.allow.name.as_ref())
5279 .collect();
5280 assert!(
5281 labels.contains(&"Always for terminal"),
5282 "Missing 'Always for terminal' option"
5283 );
5284 assert!(
5285 labels.contains(&"Only this time"),
5286 "Missing 'Only this time' option"
5287 );
5288 // Should NOT contain a pattern option
5289 assert!(
5290 !labels.iter().any(|l| l.contains("commands")),
5291 "Should not have pattern option"
5292 );
5293 } else {
5294 panic!("Expected WaitingForConfirmation status");
5295 }
5296 });
5297 }
5298
5299 #[gpui::test]
5300 async fn test_authorize_tool_call_action_triggers_authorization(cx: &mut TestAppContext) {
5301 init_test(cx);
5302
5303 let tool_call_id = acp::ToolCallId::new("action-test-1");
5304 let tool_call =
5305 acp::ToolCall::new(tool_call_id.clone(), "Run `cargo test`").kind(acp::ToolKind::Edit);
5306
5307 let permission_options =
5308 ToolPermissionContext::new(TerminalTool::NAME, vec!["cargo test".to_string()])
5309 .build_permission_options();
5310
5311 let connection =
5312 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5313 tool_call_id.clone(),
5314 permission_options,
5315 )]));
5316
5317 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5318
5319 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5320 add_to_workspace(thread_view.clone(), cx);
5321
5322 cx.update(|_window, cx| {
5323 AgentSettings::override_global(
5324 AgentSettings {
5325 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5326 ..AgentSettings::get_global(cx).clone()
5327 },
5328 cx,
5329 );
5330 });
5331
5332 let message_editor = message_editor(&thread_view, cx);
5333 message_editor.update_in(cx, |editor, window, cx| {
5334 editor.set_text("Run tests", window, cx);
5335 });
5336
5337 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5338
5339 cx.run_until_parked();
5340
5341 // Verify tool call is waiting for confirmation
5342 thread_view.read_with(cx, |thread_view, cx| {
5343 let thread = thread_view
5344 .active_thread()
5345 .expect("Thread should exist")
5346 .read(cx)
5347 .thread
5348 .clone();
5349 let thread = thread.read(cx);
5350 let tool_call = thread.first_tool_awaiting_confirmation();
5351 assert!(
5352 tool_call.is_some(),
5353 "Expected a tool call waiting for confirmation"
5354 );
5355 });
5356
5357 // Dispatch the AuthorizeToolCall action (simulating dropdown menu selection)
5358 thread_view.update_in(cx, |_, window, cx| {
5359 window.dispatch_action(
5360 crate::AuthorizeToolCall {
5361 tool_call_id: "action-test-1".to_string(),
5362 option_id: "allow".to_string(),
5363 option_kind: "AllowOnce".to_string(),
5364 }
5365 .boxed_clone(),
5366 cx,
5367 );
5368 });
5369
5370 cx.run_until_parked();
5371
5372 // Verify tool call is no longer waiting for confirmation (was authorized)
5373 thread_view.read_with(cx, |thread_view, cx| {
5374 let thread = thread_view.active_thread().expect("Thread should exist").read(cx).thread.clone();
5375 let thread = thread.read(cx);
5376 let tool_call = thread.first_tool_awaiting_confirmation();
5377 assert!(
5378 tool_call.is_none(),
5379 "Tool call should no longer be waiting for confirmation after AuthorizeToolCall action"
5380 );
5381 });
5382 }
5383
5384 #[gpui::test]
5385 async fn test_authorize_tool_call_action_with_pattern_option(cx: &mut TestAppContext) {
5386 init_test(cx);
5387
5388 let tool_call_id = acp::ToolCallId::new("pattern-action-test-1");
5389 let tool_call =
5390 acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
5391
5392 let permission_options =
5393 ToolPermissionContext::new(TerminalTool::NAME, vec!["npm install".to_string()])
5394 .build_permission_options();
5395
5396 let connection =
5397 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5398 tool_call_id.clone(),
5399 permission_options.clone(),
5400 )]));
5401
5402 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5403
5404 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5405 add_to_workspace(thread_view.clone(), cx);
5406
5407 cx.update(|_window, cx| {
5408 AgentSettings::override_global(
5409 AgentSettings {
5410 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5411 ..AgentSettings::get_global(cx).clone()
5412 },
5413 cx,
5414 );
5415 });
5416
5417 let message_editor = message_editor(&thread_view, cx);
5418 message_editor.update_in(cx, |editor, window, cx| {
5419 editor.set_text("Install dependencies", window, cx);
5420 });
5421
5422 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5423
5424 cx.run_until_parked();
5425
5426 // Find the pattern option ID
5427 let pattern_option = match &permission_options {
5428 PermissionOptions::Dropdown(choices) => choices
5429 .iter()
5430 .find(|choice| {
5431 choice
5432 .allow
5433 .option_id
5434 .0
5435 .starts_with("always_allow_pattern:")
5436 })
5437 .map(|choice| &choice.allow)
5438 .expect("Should have a pattern option for npm command"),
5439 _ => panic!("Expected dropdown permission options"),
5440 };
5441
5442 // Dispatch action with the pattern option (simulating "Always allow `npm` commands")
5443 thread_view.update_in(cx, |_, window, cx| {
5444 window.dispatch_action(
5445 crate::AuthorizeToolCall {
5446 tool_call_id: "pattern-action-test-1".to_string(),
5447 option_id: pattern_option.option_id.0.to_string(),
5448 option_kind: "AllowAlways".to_string(),
5449 }
5450 .boxed_clone(),
5451 cx,
5452 );
5453 });
5454
5455 cx.run_until_parked();
5456
5457 // Verify tool call was authorized
5458 thread_view.read_with(cx, |thread_view, cx| {
5459 let thread = thread_view
5460 .active_thread()
5461 .expect("Thread should exist")
5462 .read(cx)
5463 .thread
5464 .clone();
5465 let thread = thread.read(cx);
5466 let tool_call = thread.first_tool_awaiting_confirmation();
5467 assert!(
5468 tool_call.is_none(),
5469 "Tool call should be authorized after selecting pattern option"
5470 );
5471 });
5472 }
5473
5474 #[gpui::test]
5475 async fn test_granularity_selection_updates_state(cx: &mut TestAppContext) {
5476 init_test(cx);
5477
5478 let tool_call_id = acp::ToolCallId::new("granularity-test-1");
5479 let tool_call =
5480 acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build`").kind(acp::ToolKind::Edit);
5481
5482 let permission_options =
5483 ToolPermissionContext::new(TerminalTool::NAME, vec!["cargo build".to_string()])
5484 .build_permission_options();
5485
5486 let connection =
5487 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5488 tool_call_id.clone(),
5489 permission_options.clone(),
5490 )]));
5491
5492 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5493
5494 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5495 add_to_workspace(thread_view.clone(), cx);
5496
5497 cx.update(|_window, cx| {
5498 AgentSettings::override_global(
5499 AgentSettings {
5500 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5501 ..AgentSettings::get_global(cx).clone()
5502 },
5503 cx,
5504 );
5505 });
5506
5507 let message_editor = message_editor(&thread_view, cx);
5508 message_editor.update_in(cx, |editor, window, cx| {
5509 editor.set_text("Build the project", window, cx);
5510 });
5511
5512 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5513
5514 cx.run_until_parked();
5515
5516 // Verify default granularity is the last option (index 2 = "Only this time")
5517 thread_view.read_with(cx, |thread_view, cx| {
5518 let state = thread_view.active_thread().unwrap();
5519 let selected = state
5520 .read(cx)
5521 .selected_permission_granularity
5522 .get(&tool_call_id);
5523 assert!(
5524 selected.is_none(),
5525 "Should have no selection initially (defaults to last)"
5526 );
5527 });
5528
5529 // Select the first option (index 0 = "Always for terminal")
5530 thread_view.update_in(cx, |_, window, cx| {
5531 window.dispatch_action(
5532 crate::SelectPermissionGranularity {
5533 tool_call_id: "granularity-test-1".to_string(),
5534 index: 0,
5535 }
5536 .boxed_clone(),
5537 cx,
5538 );
5539 });
5540
5541 cx.run_until_parked();
5542
5543 // Verify the selection was updated
5544 thread_view.read_with(cx, |thread_view, cx| {
5545 let state = thread_view.active_thread().unwrap();
5546 let selected = state
5547 .read(cx)
5548 .selected_permission_granularity
5549 .get(&tool_call_id);
5550 assert_eq!(selected, Some(&0), "Should have selected index 0");
5551 });
5552 }
5553
5554 #[gpui::test]
5555 async fn test_allow_button_uses_selected_granularity(cx: &mut TestAppContext) {
5556 init_test(cx);
5557
5558 let tool_call_id = acp::ToolCallId::new("allow-granularity-test-1");
5559 let tool_call =
5560 acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
5561
5562 let permission_options =
5563 ToolPermissionContext::new(TerminalTool::NAME, vec!["npm install".to_string()])
5564 .build_permission_options();
5565
5566 // Verify we have the expected options
5567 let PermissionOptions::Dropdown(choices) = &permission_options else {
5568 panic!("Expected dropdown permission options");
5569 };
5570
5571 assert_eq!(choices.len(), 3);
5572 assert!(
5573 choices[0]
5574 .allow
5575 .option_id
5576 .0
5577 .contains("always_allow:terminal")
5578 );
5579 assert!(
5580 choices[1]
5581 .allow
5582 .option_id
5583 .0
5584 .contains("always_allow_pattern:terminal")
5585 );
5586 assert_eq!(choices[2].allow.option_id.0.as_ref(), "allow");
5587
5588 let connection =
5589 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5590 tool_call_id.clone(),
5591 permission_options.clone(),
5592 )]));
5593
5594 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5595
5596 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5597 add_to_workspace(thread_view.clone(), cx);
5598
5599 cx.update(|_window, cx| {
5600 AgentSettings::override_global(
5601 AgentSettings {
5602 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5603 ..AgentSettings::get_global(cx).clone()
5604 },
5605 cx,
5606 );
5607 });
5608
5609 let message_editor = message_editor(&thread_view, cx);
5610 message_editor.update_in(cx, |editor, window, cx| {
5611 editor.set_text("Install dependencies", window, cx);
5612 });
5613
5614 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5615
5616 cx.run_until_parked();
5617
5618 // Select the pattern option (index 1 = "Always for `npm` commands")
5619 thread_view.update_in(cx, |_, window, cx| {
5620 window.dispatch_action(
5621 crate::SelectPermissionGranularity {
5622 tool_call_id: "allow-granularity-test-1".to_string(),
5623 index: 1,
5624 }
5625 .boxed_clone(),
5626 cx,
5627 );
5628 });
5629
5630 cx.run_until_parked();
5631
5632 // Simulate clicking the Allow button by dispatching AllowOnce action
5633 // which should use the selected granularity
5634 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| {
5635 view.allow_once(&AllowOnce, window, cx)
5636 });
5637
5638 cx.run_until_parked();
5639
5640 // Verify tool call was authorized
5641 thread_view.read_with(cx, |thread_view, cx| {
5642 let thread = thread_view
5643 .active_thread()
5644 .expect("Thread should exist")
5645 .read(cx)
5646 .thread
5647 .clone();
5648 let thread = thread.read(cx);
5649 let tool_call = thread.first_tool_awaiting_confirmation();
5650 assert!(
5651 tool_call.is_none(),
5652 "Tool call should be authorized after Allow with pattern granularity"
5653 );
5654 });
5655 }
5656
5657 #[gpui::test]
5658 async fn test_deny_button_uses_selected_granularity(cx: &mut TestAppContext) {
5659 init_test(cx);
5660
5661 let tool_call_id = acp::ToolCallId::new("deny-granularity-test-1");
5662 let tool_call =
5663 acp::ToolCall::new(tool_call_id.clone(), "Run `git push`").kind(acp::ToolKind::Edit);
5664
5665 let permission_options =
5666 ToolPermissionContext::new(TerminalTool::NAME, vec!["git push".to_string()])
5667 .build_permission_options();
5668
5669 let connection =
5670 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5671 tool_call_id.clone(),
5672 permission_options.clone(),
5673 )]));
5674
5675 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5676
5677 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5678 add_to_workspace(thread_view.clone(), cx);
5679
5680 cx.update(|_window, cx| {
5681 AgentSettings::override_global(
5682 AgentSettings {
5683 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5684 ..AgentSettings::get_global(cx).clone()
5685 },
5686 cx,
5687 );
5688 });
5689
5690 let message_editor = message_editor(&thread_view, cx);
5691 message_editor.update_in(cx, |editor, window, cx| {
5692 editor.set_text("Push changes", window, cx);
5693 });
5694
5695 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5696
5697 cx.run_until_parked();
5698
5699 // Use default granularity (last option = "Only this time")
5700 // Simulate clicking the Deny button
5701 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| {
5702 view.reject_once(&RejectOnce, window, cx)
5703 });
5704
5705 cx.run_until_parked();
5706
5707 // Verify tool call was rejected (no longer waiting for confirmation)
5708 thread_view.read_with(cx, |thread_view, cx| {
5709 let thread = thread_view
5710 .active_thread()
5711 .expect("Thread should exist")
5712 .read(cx)
5713 .thread
5714 .clone();
5715 let thread = thread.read(cx);
5716 let tool_call = thread.first_tool_awaiting_confirmation();
5717 assert!(
5718 tool_call.is_none(),
5719 "Tool call should be rejected after Deny"
5720 );
5721 });
5722 }
5723
5724 #[gpui::test]
5725 async fn test_option_id_transformation_for_allow() {
5726 let permission_options = ToolPermissionContext::new(
5727 TerminalTool::NAME,
5728 vec!["cargo build --release".to_string()],
5729 )
5730 .build_permission_options();
5731
5732 let PermissionOptions::Dropdown(choices) = permission_options else {
5733 panic!("Expected dropdown permission options");
5734 };
5735
5736 let allow_ids: Vec<String> = choices
5737 .iter()
5738 .map(|choice| choice.allow.option_id.0.to_string())
5739 .collect();
5740
5741 assert!(allow_ids.contains(&"always_allow:terminal".to_string()));
5742 assert!(allow_ids.contains(&"allow".to_string()));
5743 assert!(
5744 allow_ids
5745 .iter()
5746 .any(|id| id.starts_with("always_allow_pattern:terminal\n")),
5747 "Missing allow pattern option"
5748 );
5749 }
5750
5751 #[gpui::test]
5752 async fn test_option_id_transformation_for_deny() {
5753 let permission_options = ToolPermissionContext::new(
5754 TerminalTool::NAME,
5755 vec!["cargo build --release".to_string()],
5756 )
5757 .build_permission_options();
5758
5759 let PermissionOptions::Dropdown(choices) = permission_options else {
5760 panic!("Expected dropdown permission options");
5761 };
5762
5763 let deny_ids: Vec<String> = choices
5764 .iter()
5765 .map(|choice| choice.deny.option_id.0.to_string())
5766 .collect();
5767
5768 assert!(deny_ids.contains(&"always_deny:terminal".to_string()));
5769 assert!(deny_ids.contains(&"deny".to_string()));
5770 assert!(
5771 deny_ids
5772 .iter()
5773 .any(|id| id.starts_with("always_deny_pattern:terminal\n")),
5774 "Missing deny pattern option"
5775 );
5776 }
5777
5778 #[gpui::test]
5779 async fn test_manually_editing_title_updates_acp_thread_title(cx: &mut TestAppContext) {
5780 init_test(cx);
5781
5782 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5783
5784 let active = active_thread(&thread_view, cx);
5785 let title_editor = cx.read(|cx| active.read(cx).title_editor.clone());
5786 let thread = cx.read(|cx| active.read(cx).thread.clone());
5787
5788 title_editor.read_with(cx, |editor, cx| {
5789 assert!(!editor.read_only(cx));
5790 });
5791
5792 title_editor.update_in(cx, |editor, window, cx| {
5793 editor.set_text("My Custom Title", window, cx);
5794 });
5795 cx.run_until_parked();
5796
5797 title_editor.read_with(cx, |editor, cx| {
5798 assert_eq!(editor.text(cx), "My Custom Title");
5799 });
5800 thread.read_with(cx, |thread, _cx| {
5801 assert_eq!(thread.title().as_ref(), "My Custom Title");
5802 });
5803 }
5804
5805 #[gpui::test]
5806 async fn test_title_editor_is_read_only_when_set_title_unsupported(cx: &mut TestAppContext) {
5807 init_test(cx);
5808
5809 let (thread_view, cx) =
5810 setup_thread_view(StubAgentServer::new(ResumeOnlyAgentConnection), cx).await;
5811
5812 let active = active_thread(&thread_view, cx);
5813 let title_editor = cx.read(|cx| active.read(cx).title_editor.clone());
5814
5815 title_editor.read_with(cx, |editor, cx| {
5816 assert!(
5817 editor.read_only(cx),
5818 "Title editor should be read-only when the connection does not support set_title"
5819 );
5820 });
5821 }
5822
5823 #[gpui::test]
5824 async fn test_max_tokens_error_is_rendered(cx: &mut TestAppContext) {
5825 init_test(cx);
5826
5827 let connection = StubAgentConnection::new();
5828
5829 let (thread_view, cx) =
5830 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5831
5832 let message_editor = message_editor(&thread_view, cx);
5833 message_editor.update_in(cx, |editor, window, cx| {
5834 editor.set_text("Some prompt", window, cx);
5835 });
5836 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5837
5838 let session_id = thread_view.read_with(cx, |view, cx| {
5839 view.active_thread()
5840 .unwrap()
5841 .read(cx)
5842 .thread
5843 .read(cx)
5844 .session_id()
5845 .clone()
5846 });
5847
5848 cx.run_until_parked();
5849
5850 cx.update(|_, _cx| {
5851 connection.end_turn(session_id, acp::StopReason::MaxTokens);
5852 });
5853
5854 cx.run_until_parked();
5855
5856 thread_view.read_with(cx, |thread_view, cx| {
5857 let state = thread_view.active_thread().unwrap();
5858 let error = &state.read(cx).thread_error;
5859 match error {
5860 Some(ThreadError::Other { message, .. }) => {
5861 assert!(
5862 message.contains("Max tokens reached"),
5863 "Expected 'Max tokens reached' error, got: {}",
5864 message
5865 );
5866 }
5867 other => panic!(
5868 "Expected ThreadError::Other with 'Max tokens reached', got: {:?}",
5869 other.is_some()
5870 ),
5871 }
5872 });
5873 }
5874}