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