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