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