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