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