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