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