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