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