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