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