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