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 crate::agent_panel::sidebar_is_open(window, cx)
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 // Render the title editor in the element tree too. In the real app
3787 // it is part of the agent panel
3788 let title_editor = self
3789 .0
3790 .read(cx)
3791 .active_thread()
3792 .map(|t| t.read(cx).title_editor.clone());
3793
3794 v_flex().children(title_editor).child(self.0.clone())
3795 }
3796 }
3797
3798 pub(crate) struct StubAgentServer<C> {
3799 connection: C,
3800 }
3801
3802 impl<C> StubAgentServer<C> {
3803 pub(crate) fn new(connection: C) -> Self {
3804 Self { connection }
3805 }
3806 }
3807
3808 impl StubAgentServer<StubAgentConnection> {
3809 pub(crate) fn default_response() -> Self {
3810 let conn = StubAgentConnection::new();
3811 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3812 acp::ContentChunk::new("Default response".into()),
3813 )]);
3814 Self::new(conn)
3815 }
3816 }
3817
3818 impl<C> AgentServer for StubAgentServer<C>
3819 where
3820 C: 'static + AgentConnection + Send + Clone,
3821 {
3822 fn logo(&self) -> ui::IconName {
3823 ui::IconName::Ai
3824 }
3825
3826 fn name(&self) -> SharedString {
3827 "Test".into()
3828 }
3829
3830 fn connect(
3831 &self,
3832 _delegate: AgentServerDelegate,
3833 _cx: &mut App,
3834 ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
3835 Task::ready(Ok(Rc::new(self.connection.clone())))
3836 }
3837
3838 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3839 self
3840 }
3841 }
3842
3843 struct FailingAgentServer;
3844
3845 impl AgentServer for FailingAgentServer {
3846 fn logo(&self) -> ui::IconName {
3847 ui::IconName::AiOpenAi
3848 }
3849
3850 fn name(&self) -> SharedString {
3851 "Codex CLI".into()
3852 }
3853
3854 fn connect(
3855 &self,
3856 _delegate: AgentServerDelegate,
3857 _cx: &mut App,
3858 ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
3859 Task::ready(Err(anyhow!(
3860 "extracting downloaded asset for \
3861 https://github.com/zed-industries/codex-acp/releases/download/v0.9.4/\
3862 codex-acp-0.9.4-aarch64-pc-windows-msvc.zip: \
3863 failed to iterate over archive: Invalid gzip header"
3864 )))
3865 }
3866
3867 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3868 self
3869 }
3870 }
3871
3872 #[derive(Clone)]
3873 struct StubSessionList {
3874 sessions: Vec<AgentSessionInfo>,
3875 }
3876
3877 impl StubSessionList {
3878 fn new(sessions: Vec<AgentSessionInfo>) -> Self {
3879 Self { sessions }
3880 }
3881 }
3882
3883 impl AgentSessionList for StubSessionList {
3884 fn list_sessions(
3885 &self,
3886 _request: AgentSessionListRequest,
3887 _cx: &mut App,
3888 ) -> Task<anyhow::Result<AgentSessionListResponse>> {
3889 Task::ready(Ok(AgentSessionListResponse::new(self.sessions.clone())))
3890 }
3891
3892 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3893 self
3894 }
3895 }
3896
3897 #[derive(Clone)]
3898 struct SessionHistoryConnection {
3899 sessions: Vec<AgentSessionInfo>,
3900 }
3901
3902 impl SessionHistoryConnection {
3903 fn new(sessions: Vec<AgentSessionInfo>) -> Self {
3904 Self { sessions }
3905 }
3906 }
3907
3908 fn build_test_thread(
3909 connection: Rc<dyn AgentConnection>,
3910 project: Entity<Project>,
3911 name: &'static str,
3912 session_id: SessionId,
3913 cx: &mut App,
3914 ) -> Entity<AcpThread> {
3915 let action_log = cx.new(|_| ActionLog::new(project.clone()));
3916 cx.new(|cx| {
3917 AcpThread::new(
3918 None,
3919 name,
3920 None,
3921 connection,
3922 project,
3923 action_log,
3924 session_id,
3925 watch::Receiver::constant(
3926 acp::PromptCapabilities::new()
3927 .image(true)
3928 .audio(true)
3929 .embedded_context(true),
3930 ),
3931 cx,
3932 )
3933 })
3934 }
3935
3936 impl AgentConnection for SessionHistoryConnection {
3937 fn telemetry_id(&self) -> SharedString {
3938 "history-connection".into()
3939 }
3940
3941 fn new_session(
3942 self: Rc<Self>,
3943 project: Entity<Project>,
3944 _cwd: &Path,
3945 cx: &mut App,
3946 ) -> Task<anyhow::Result<Entity<AcpThread>>> {
3947 let thread = build_test_thread(
3948 self,
3949 project,
3950 "SessionHistoryConnection",
3951 SessionId::new("history-session"),
3952 cx,
3953 );
3954 Task::ready(Ok(thread))
3955 }
3956
3957 fn supports_load_session(&self) -> bool {
3958 true
3959 }
3960
3961 fn session_list(&self, _cx: &mut App) -> Option<Rc<dyn AgentSessionList>> {
3962 Some(Rc::new(StubSessionList::new(self.sessions.clone())))
3963 }
3964
3965 fn auth_methods(&self) -> &[acp::AuthMethod] {
3966 &[]
3967 }
3968
3969 fn authenticate(
3970 &self,
3971 _method_id: acp::AuthMethodId,
3972 _cx: &mut App,
3973 ) -> Task<anyhow::Result<()>> {
3974 Task::ready(Ok(()))
3975 }
3976
3977 fn prompt(
3978 &self,
3979 _id: Option<acp_thread::UserMessageId>,
3980 _params: acp::PromptRequest,
3981 _cx: &mut App,
3982 ) -> Task<anyhow::Result<acp::PromptResponse>> {
3983 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
3984 }
3985
3986 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
3987
3988 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3989 self
3990 }
3991 }
3992
3993 #[derive(Clone)]
3994 struct ResumeOnlyAgentConnection;
3995
3996 impl AgentConnection for ResumeOnlyAgentConnection {
3997 fn telemetry_id(&self) -> SharedString {
3998 "resume-only".into()
3999 }
4000
4001 fn new_session(
4002 self: Rc<Self>,
4003 project: Entity<Project>,
4004 _cwd: &Path,
4005 cx: &mut gpui::App,
4006 ) -> Task<gpui::Result<Entity<AcpThread>>> {
4007 let thread = build_test_thread(
4008 self,
4009 project,
4010 "ResumeOnlyAgentConnection",
4011 SessionId::new("new-session"),
4012 cx,
4013 );
4014 Task::ready(Ok(thread))
4015 }
4016
4017 fn supports_resume_session(&self) -> bool {
4018 true
4019 }
4020
4021 fn resume_session(
4022 self: Rc<Self>,
4023 session_id: acp::SessionId,
4024 project: Entity<Project>,
4025 _cwd: &Path,
4026 _title: Option<SharedString>,
4027 cx: &mut App,
4028 ) -> Task<gpui::Result<Entity<AcpThread>>> {
4029 let thread =
4030 build_test_thread(self, project, "ResumeOnlyAgentConnection", session_id, cx);
4031 Task::ready(Ok(thread))
4032 }
4033
4034 fn auth_methods(&self) -> &[acp::AuthMethod] {
4035 &[]
4036 }
4037
4038 fn authenticate(
4039 &self,
4040 _method_id: acp::AuthMethodId,
4041 _cx: &mut App,
4042 ) -> Task<gpui::Result<()>> {
4043 Task::ready(Ok(()))
4044 }
4045
4046 fn prompt(
4047 &self,
4048 _id: Option<acp_thread::UserMessageId>,
4049 _params: acp::PromptRequest,
4050 _cx: &mut App,
4051 ) -> Task<gpui::Result<acp::PromptResponse>> {
4052 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
4053 }
4054
4055 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
4056
4057 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4058 self
4059 }
4060 }
4061
4062 /// Simulates an agent that requires authentication before a session can be
4063 /// created. `new_session` returns `AuthRequired` until `authenticate` is
4064 /// called with the correct method, after which sessions are created normally.
4065 #[derive(Clone)]
4066 struct AuthGatedAgentConnection {
4067 authenticated: Arc<Mutex<bool>>,
4068 auth_method: acp::AuthMethod,
4069 }
4070
4071 impl AuthGatedAgentConnection {
4072 const AUTH_METHOD_ID: &str = "test-login";
4073
4074 fn new() -> Self {
4075 Self {
4076 authenticated: Arc::new(Mutex::new(false)),
4077 auth_method: acp::AuthMethod::new(Self::AUTH_METHOD_ID, "Test Login"),
4078 }
4079 }
4080 }
4081
4082 impl AgentConnection for AuthGatedAgentConnection {
4083 fn telemetry_id(&self) -> SharedString {
4084 "auth-gated".into()
4085 }
4086
4087 fn new_session(
4088 self: Rc<Self>,
4089 project: Entity<Project>,
4090 cwd: &Path,
4091 cx: &mut gpui::App,
4092 ) -> Task<gpui::Result<Entity<AcpThread>>> {
4093 if !*self.authenticated.lock() {
4094 return Task::ready(Err(acp_thread::AuthRequired::new()
4095 .with_description("Sign in to continue".to_string())
4096 .into()));
4097 }
4098
4099 let session_id = acp::SessionId::new("auth-gated-session");
4100 let action_log = cx.new(|_| ActionLog::new(project.clone()));
4101 Task::ready(Ok(cx.new(|cx| {
4102 AcpThread::new(
4103 None,
4104 "AuthGatedAgent",
4105 Some(cwd.to_path_buf()),
4106 self,
4107 project,
4108 action_log,
4109 session_id,
4110 watch::Receiver::constant(
4111 acp::PromptCapabilities::new()
4112 .image(true)
4113 .audio(true)
4114 .embedded_context(true),
4115 ),
4116 cx,
4117 )
4118 })))
4119 }
4120
4121 fn auth_methods(&self) -> &[acp::AuthMethod] {
4122 std::slice::from_ref(&self.auth_method)
4123 }
4124
4125 fn authenticate(
4126 &self,
4127 method_id: acp::AuthMethodId,
4128 _cx: &mut App,
4129 ) -> Task<gpui::Result<()>> {
4130 if method_id == self.auth_method.id {
4131 *self.authenticated.lock() = true;
4132 Task::ready(Ok(()))
4133 } else {
4134 Task::ready(Err(anyhow::anyhow!("Unknown auth method")))
4135 }
4136 }
4137
4138 fn prompt(
4139 &self,
4140 _id: Option<acp_thread::UserMessageId>,
4141 _params: acp::PromptRequest,
4142 _cx: &mut App,
4143 ) -> Task<gpui::Result<acp::PromptResponse>> {
4144 unimplemented!()
4145 }
4146
4147 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
4148 unimplemented!()
4149 }
4150
4151 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4152 self
4153 }
4154 }
4155
4156 #[derive(Clone)]
4157 struct SaboteurAgentConnection;
4158
4159 impl AgentConnection for SaboteurAgentConnection {
4160 fn telemetry_id(&self) -> SharedString {
4161 "saboteur".into()
4162 }
4163
4164 fn new_session(
4165 self: Rc<Self>,
4166 project: Entity<Project>,
4167 cwd: &Path,
4168 cx: &mut gpui::App,
4169 ) -> Task<gpui::Result<Entity<AcpThread>>> {
4170 Task::ready(Ok(cx.new(|cx| {
4171 let action_log = cx.new(|_| ActionLog::new(project.clone()));
4172 AcpThread::new(
4173 None,
4174 "SaboteurAgentConnection",
4175 Some(cwd.to_path_buf()),
4176 self,
4177 project,
4178 action_log,
4179 SessionId::new("test"),
4180 watch::Receiver::constant(
4181 acp::PromptCapabilities::new()
4182 .image(true)
4183 .audio(true)
4184 .embedded_context(true),
4185 ),
4186 cx,
4187 )
4188 })))
4189 }
4190
4191 fn auth_methods(&self) -> &[acp::AuthMethod] {
4192 &[]
4193 }
4194
4195 fn authenticate(
4196 &self,
4197 _method_id: acp::AuthMethodId,
4198 _cx: &mut App,
4199 ) -> Task<gpui::Result<()>> {
4200 unimplemented!()
4201 }
4202
4203 fn prompt(
4204 &self,
4205 _id: Option<acp_thread::UserMessageId>,
4206 _params: acp::PromptRequest,
4207 _cx: &mut App,
4208 ) -> Task<gpui::Result<acp::PromptResponse>> {
4209 Task::ready(Err(anyhow::anyhow!("Error prompting")))
4210 }
4211
4212 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
4213 unimplemented!()
4214 }
4215
4216 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4217 self
4218 }
4219 }
4220
4221 /// Simulates a model which always returns a refusal response
4222 #[derive(Clone)]
4223 struct RefusalAgentConnection;
4224
4225 impl AgentConnection for RefusalAgentConnection {
4226 fn telemetry_id(&self) -> SharedString {
4227 "refusal".into()
4228 }
4229
4230 fn new_session(
4231 self: Rc<Self>,
4232 project: Entity<Project>,
4233 cwd: &Path,
4234 cx: &mut gpui::App,
4235 ) -> Task<gpui::Result<Entity<AcpThread>>> {
4236 Task::ready(Ok(cx.new(|cx| {
4237 let action_log = cx.new(|_| ActionLog::new(project.clone()));
4238 AcpThread::new(
4239 None,
4240 "RefusalAgentConnection",
4241 Some(cwd.to_path_buf()),
4242 self,
4243 project,
4244 action_log,
4245 SessionId::new("test"),
4246 watch::Receiver::constant(
4247 acp::PromptCapabilities::new()
4248 .image(true)
4249 .audio(true)
4250 .embedded_context(true),
4251 ),
4252 cx,
4253 )
4254 })))
4255 }
4256
4257 fn auth_methods(&self) -> &[acp::AuthMethod] {
4258 &[]
4259 }
4260
4261 fn authenticate(
4262 &self,
4263 _method_id: acp::AuthMethodId,
4264 _cx: &mut App,
4265 ) -> Task<gpui::Result<()>> {
4266 unimplemented!()
4267 }
4268
4269 fn prompt(
4270 &self,
4271 _id: Option<acp_thread::UserMessageId>,
4272 _params: acp::PromptRequest,
4273 _cx: &mut App,
4274 ) -> Task<gpui::Result<acp::PromptResponse>> {
4275 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::Refusal)))
4276 }
4277
4278 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
4279 unimplemented!()
4280 }
4281
4282 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4283 self
4284 }
4285 }
4286
4287 #[derive(Clone)]
4288 struct CwdCapturingConnection {
4289 captured_cwd: Arc<Mutex<Option<PathBuf>>>,
4290 }
4291
4292 impl CwdCapturingConnection {
4293 fn new() -> Self {
4294 Self {
4295 captured_cwd: Arc::new(Mutex::new(None)),
4296 }
4297 }
4298 }
4299
4300 impl AgentConnection for CwdCapturingConnection {
4301 fn telemetry_id(&self) -> SharedString {
4302 "cwd-capturing".into()
4303 }
4304
4305 fn new_session(
4306 self: Rc<Self>,
4307 project: Entity<Project>,
4308 cwd: &Path,
4309 cx: &mut gpui::App,
4310 ) -> Task<gpui::Result<Entity<AcpThread>>> {
4311 *self.captured_cwd.lock() = Some(cwd.to_path_buf());
4312 let action_log = cx.new(|_| ActionLog::new(project.clone()));
4313 let thread = cx.new(|cx| {
4314 AcpThread::new(
4315 None,
4316 "CwdCapturingConnection",
4317 Some(cwd.to_path_buf()),
4318 self.clone(),
4319 project,
4320 action_log,
4321 SessionId::new("new-session"),
4322 watch::Receiver::constant(
4323 acp::PromptCapabilities::new()
4324 .image(true)
4325 .audio(true)
4326 .embedded_context(true),
4327 ),
4328 cx,
4329 )
4330 });
4331 Task::ready(Ok(thread))
4332 }
4333
4334 fn supports_load_session(&self) -> bool {
4335 true
4336 }
4337
4338 fn load_session(
4339 self: Rc<Self>,
4340 session_id: acp::SessionId,
4341 project: Entity<Project>,
4342 cwd: &Path,
4343 _title: Option<SharedString>,
4344 cx: &mut App,
4345 ) -> Task<gpui::Result<Entity<AcpThread>>> {
4346 *self.captured_cwd.lock() = Some(cwd.to_path_buf());
4347 let action_log = cx.new(|_| ActionLog::new(project.clone()));
4348 let thread = cx.new(|cx| {
4349 AcpThread::new(
4350 None,
4351 "CwdCapturingConnection",
4352 Some(cwd.to_path_buf()),
4353 self.clone(),
4354 project,
4355 action_log,
4356 session_id,
4357 watch::Receiver::constant(
4358 acp::PromptCapabilities::new()
4359 .image(true)
4360 .audio(true)
4361 .embedded_context(true),
4362 ),
4363 cx,
4364 )
4365 });
4366 Task::ready(Ok(thread))
4367 }
4368
4369 fn auth_methods(&self) -> &[acp::AuthMethod] {
4370 &[]
4371 }
4372
4373 fn authenticate(
4374 &self,
4375 _method_id: acp::AuthMethodId,
4376 _cx: &mut App,
4377 ) -> Task<gpui::Result<()>> {
4378 Task::ready(Ok(()))
4379 }
4380
4381 fn prompt(
4382 &self,
4383 _id: Option<acp_thread::UserMessageId>,
4384 _params: acp::PromptRequest,
4385 _cx: &mut App,
4386 ) -> Task<gpui::Result<acp::PromptResponse>> {
4387 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
4388 }
4389
4390 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
4391
4392 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4393 self
4394 }
4395 }
4396
4397 pub(crate) fn init_test(cx: &mut TestAppContext) {
4398 cx.update(|cx| {
4399 let settings_store = SettingsStore::test(cx);
4400 cx.set_global(settings_store);
4401 theme::init(theme::LoadThemes::JustBase, cx);
4402 editor::init(cx);
4403 agent_panel::init(cx);
4404 release_channel::init(semver::Version::new(0, 0, 0), cx);
4405 prompt_store::init(cx)
4406 });
4407 }
4408
4409 fn active_thread(
4410 thread_view: &Entity<ConnectionView>,
4411 cx: &TestAppContext,
4412 ) -> Entity<ThreadView> {
4413 cx.read(|cx| {
4414 thread_view
4415 .read(cx)
4416 .active_thread()
4417 .expect("No active thread")
4418 .clone()
4419 })
4420 }
4421
4422 fn message_editor(
4423 thread_view: &Entity<ConnectionView>,
4424 cx: &TestAppContext,
4425 ) -> Entity<MessageEditor> {
4426 let thread = active_thread(thread_view, cx);
4427 cx.read(|cx| thread.read(cx).message_editor.clone())
4428 }
4429
4430 #[gpui::test]
4431 async fn test_rewind_views(cx: &mut TestAppContext) {
4432 init_test(cx);
4433
4434 let fs = FakeFs::new(cx.executor());
4435 fs.insert_tree(
4436 "/project",
4437 json!({
4438 "test1.txt": "old content 1",
4439 "test2.txt": "old content 2"
4440 }),
4441 )
4442 .await;
4443 let project = Project::test(fs, [Path::new("/project")], cx).await;
4444 let (multi_workspace, cx) =
4445 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
4446 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
4447
4448 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
4449 let history = cx.update(|window, cx| cx.new(|cx| ThreadHistory::new(None, window, cx)));
4450 let connection_store =
4451 cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
4452
4453 let connection = Rc::new(StubAgentConnection::new());
4454 let thread_view = cx.update(|window, cx| {
4455 cx.new(|cx| {
4456 ConnectionView::new(
4457 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
4458 connection_store,
4459 ExternalAgent::Custom {
4460 name: "Test".into(),
4461 },
4462 None,
4463 None,
4464 None,
4465 None,
4466 workspace.downgrade(),
4467 project.clone(),
4468 Some(thread_store.clone()),
4469 None,
4470 history,
4471 window,
4472 cx,
4473 )
4474 })
4475 });
4476
4477 cx.run_until_parked();
4478
4479 let thread = thread_view
4480 .read_with(cx, |view, cx| {
4481 view.active_thread().map(|r| r.read(cx).thread.clone())
4482 })
4483 .unwrap();
4484
4485 // First user message
4486 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
4487 acp::ToolCall::new("tool1", "Edit file 1")
4488 .kind(acp::ToolKind::Edit)
4489 .status(acp::ToolCallStatus::Completed)
4490 .content(vec![acp::ToolCallContent::Diff(
4491 acp::Diff::new("/project/test1.txt", "new content 1").old_text("old content 1"),
4492 )]),
4493 )]);
4494
4495 thread
4496 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
4497 .await
4498 .unwrap();
4499 cx.run_until_parked();
4500
4501 thread.read_with(cx, |thread, _cx| {
4502 assert_eq!(thread.entries().len(), 2);
4503 });
4504
4505 thread_view.read_with(cx, |view, cx| {
4506 let entry_view_state = view
4507 .active_thread()
4508 .map(|active| active.read(cx).entry_view_state.clone())
4509 .unwrap();
4510 entry_view_state.read_with(cx, |entry_view_state, _| {
4511 assert!(
4512 entry_view_state
4513 .entry(0)
4514 .unwrap()
4515 .message_editor()
4516 .is_some()
4517 );
4518 assert!(entry_view_state.entry(1).unwrap().has_content());
4519 });
4520 });
4521
4522 // Second user message
4523 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
4524 acp::ToolCall::new("tool2", "Edit file 2")
4525 .kind(acp::ToolKind::Edit)
4526 .status(acp::ToolCallStatus::Completed)
4527 .content(vec![acp::ToolCallContent::Diff(
4528 acp::Diff::new("/project/test2.txt", "new content 2").old_text("old content 2"),
4529 )]),
4530 )]);
4531
4532 thread
4533 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
4534 .await
4535 .unwrap();
4536 cx.run_until_parked();
4537
4538 let second_user_message_id = thread.read_with(cx, |thread, _| {
4539 assert_eq!(thread.entries().len(), 4);
4540 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
4541 panic!();
4542 };
4543 user_message.id.clone().unwrap()
4544 });
4545
4546 thread_view.read_with(cx, |view, cx| {
4547 let entry_view_state = view
4548 .active_thread()
4549 .unwrap()
4550 .read(cx)
4551 .entry_view_state
4552 .clone();
4553 entry_view_state.read_with(cx, |entry_view_state, _| {
4554 assert!(
4555 entry_view_state
4556 .entry(0)
4557 .unwrap()
4558 .message_editor()
4559 .is_some()
4560 );
4561 assert!(entry_view_state.entry(1).unwrap().has_content());
4562 assert!(
4563 entry_view_state
4564 .entry(2)
4565 .unwrap()
4566 .message_editor()
4567 .is_some()
4568 );
4569 assert!(entry_view_state.entry(3).unwrap().has_content());
4570 });
4571 });
4572
4573 // Rewind to first message
4574 thread
4575 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
4576 .await
4577 .unwrap();
4578
4579 cx.run_until_parked();
4580
4581 thread.read_with(cx, |thread, _| {
4582 assert_eq!(thread.entries().len(), 2);
4583 });
4584
4585 thread_view.read_with(cx, |view, cx| {
4586 let active = view.active_thread().unwrap();
4587 active
4588 .read(cx)
4589 .entry_view_state
4590 .read_with(cx, |entry_view_state, _| {
4591 assert!(
4592 entry_view_state
4593 .entry(0)
4594 .unwrap()
4595 .message_editor()
4596 .is_some()
4597 );
4598 assert!(entry_view_state.entry(1).unwrap().has_content());
4599
4600 // Old views should be dropped
4601 assert!(entry_view_state.entry(2).is_none());
4602 assert!(entry_view_state.entry(3).is_none());
4603 });
4604 });
4605 }
4606
4607 #[gpui::test]
4608 async fn test_scroll_to_most_recent_user_prompt(cx: &mut TestAppContext) {
4609 init_test(cx);
4610
4611 let connection = StubAgentConnection::new();
4612
4613 // Each user prompt will result in a user message entry plus an agent message entry.
4614 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4615 acp::ContentChunk::new("Response 1".into()),
4616 )]);
4617
4618 let (thread_view, cx) =
4619 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4620
4621 let thread = thread_view
4622 .read_with(cx, |view, cx| {
4623 view.active_thread().map(|r| r.read(cx).thread.clone())
4624 })
4625 .unwrap();
4626
4627 thread
4628 .update(cx, |thread, cx| thread.send_raw("Prompt 1", cx))
4629 .await
4630 .unwrap();
4631 cx.run_until_parked();
4632
4633 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4634 acp::ContentChunk::new("Response 2".into()),
4635 )]);
4636
4637 thread
4638 .update(cx, |thread, cx| thread.send_raw("Prompt 2", cx))
4639 .await
4640 .unwrap();
4641 cx.run_until_parked();
4642
4643 // Move somewhere else first so we're not trivially already on the last user prompt.
4644 active_thread(&thread_view, cx).update(cx, |view, cx| {
4645 view.scroll_to_top(cx);
4646 });
4647 cx.run_until_parked();
4648
4649 active_thread(&thread_view, cx).update(cx, |view, cx| {
4650 view.scroll_to_most_recent_user_prompt(cx);
4651 let scroll_top = view.list_state.logical_scroll_top();
4652 // Entries layout is: [User1, Assistant1, User2, Assistant2]
4653 assert_eq!(scroll_top.item_ix, 2);
4654 });
4655 }
4656
4657 #[gpui::test]
4658 async fn test_scroll_to_most_recent_user_prompt_falls_back_to_bottom_without_user_messages(
4659 cx: &mut TestAppContext,
4660 ) {
4661 init_test(cx);
4662
4663 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
4664
4665 // With no entries, scrolling should be a no-op and must not panic.
4666 active_thread(&thread_view, cx).update(cx, |view, cx| {
4667 view.scroll_to_most_recent_user_prompt(cx);
4668 let scroll_top = view.list_state.logical_scroll_top();
4669 assert_eq!(scroll_top.item_ix, 0);
4670 });
4671 }
4672
4673 #[gpui::test]
4674 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
4675 init_test(cx);
4676
4677 let connection = StubAgentConnection::new();
4678
4679 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4680 acp::ContentChunk::new("Response".into()),
4681 )]);
4682
4683 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4684 add_to_workspace(thread_view.clone(), cx);
4685
4686 let message_editor = message_editor(&thread_view, cx);
4687 message_editor.update_in(cx, |editor, window, cx| {
4688 editor.set_text("Original message to edit", window, cx);
4689 });
4690 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4691
4692 cx.run_until_parked();
4693
4694 let user_message_editor = thread_view.read_with(cx, |view, cx| {
4695 assert_eq!(
4696 view.active_thread()
4697 .and_then(|active| active.read(cx).editing_message),
4698 None
4699 );
4700
4701 view.active_thread()
4702 .map(|active| &active.read(cx).entry_view_state)
4703 .as_ref()
4704 .unwrap()
4705 .read(cx)
4706 .entry(0)
4707 .unwrap()
4708 .message_editor()
4709 .unwrap()
4710 .clone()
4711 });
4712
4713 // Focus
4714 cx.focus(&user_message_editor);
4715 thread_view.read_with(cx, |view, cx| {
4716 assert_eq!(
4717 view.active_thread()
4718 .and_then(|active| active.read(cx).editing_message),
4719 Some(0)
4720 );
4721 });
4722
4723 // Edit
4724 user_message_editor.update_in(cx, |editor, window, cx| {
4725 editor.set_text("Edited message content", window, cx);
4726 });
4727
4728 // Cancel
4729 user_message_editor.update_in(cx, |_editor, window, cx| {
4730 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
4731 });
4732
4733 thread_view.read_with(cx, |view, cx| {
4734 assert_eq!(
4735 view.active_thread()
4736 .and_then(|active| active.read(cx).editing_message),
4737 None
4738 );
4739 });
4740
4741 user_message_editor.read_with(cx, |editor, cx| {
4742 assert_eq!(editor.text(cx), "Original message to edit");
4743 });
4744 }
4745
4746 #[gpui::test]
4747 async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
4748 init_test(cx);
4749
4750 let connection = StubAgentConnection::new();
4751
4752 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4753 add_to_workspace(thread_view.clone(), cx);
4754
4755 let message_editor = message_editor(&thread_view, cx);
4756 message_editor.update_in(cx, |editor, window, cx| {
4757 editor.set_text("", window, cx);
4758 });
4759
4760 let thread = cx.read(|cx| {
4761 thread_view
4762 .read(cx)
4763 .active_thread()
4764 .unwrap()
4765 .read(cx)
4766 .thread
4767 .clone()
4768 });
4769 let entries_before = cx.read(|cx| thread.read(cx).entries().len());
4770
4771 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| {
4772 view.send(window, cx);
4773 });
4774 cx.run_until_parked();
4775
4776 let entries_after = cx.read(|cx| thread.read(cx).entries().len());
4777 assert_eq!(
4778 entries_before, entries_after,
4779 "No message should be sent when editor is empty"
4780 );
4781 }
4782
4783 #[gpui::test]
4784 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
4785 init_test(cx);
4786
4787 let connection = StubAgentConnection::new();
4788
4789 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4790 acp::ContentChunk::new("Response".into()),
4791 )]);
4792
4793 let (thread_view, cx) =
4794 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4795 add_to_workspace(thread_view.clone(), cx);
4796
4797 let message_editor = message_editor(&thread_view, cx);
4798 message_editor.update_in(cx, |editor, window, cx| {
4799 editor.set_text("Original message to edit", window, cx);
4800 });
4801 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4802
4803 cx.run_until_parked();
4804
4805 let user_message_editor = thread_view.read_with(cx, |view, cx| {
4806 assert_eq!(
4807 view.active_thread()
4808 .and_then(|active| active.read(cx).editing_message),
4809 None
4810 );
4811 assert_eq!(
4812 view.active_thread()
4813 .unwrap()
4814 .read(cx)
4815 .thread
4816 .read(cx)
4817 .entries()
4818 .len(),
4819 2
4820 );
4821
4822 view.active_thread()
4823 .map(|active| &active.read(cx).entry_view_state)
4824 .as_ref()
4825 .unwrap()
4826 .read(cx)
4827 .entry(0)
4828 .unwrap()
4829 .message_editor()
4830 .unwrap()
4831 .clone()
4832 });
4833
4834 // Focus
4835 cx.focus(&user_message_editor);
4836
4837 // Edit
4838 user_message_editor.update_in(cx, |editor, window, cx| {
4839 editor.set_text("Edited message content", window, cx);
4840 });
4841
4842 // Send
4843 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4844 acp::ContentChunk::new("New Response".into()),
4845 )]);
4846
4847 user_message_editor.update_in(cx, |_editor, window, cx| {
4848 window.dispatch_action(Box::new(Chat), cx);
4849 });
4850
4851 cx.run_until_parked();
4852
4853 thread_view.read_with(cx, |view, cx| {
4854 assert_eq!(
4855 view.active_thread()
4856 .and_then(|active| active.read(cx).editing_message),
4857 None
4858 );
4859
4860 let entries = view
4861 .active_thread()
4862 .unwrap()
4863 .read(cx)
4864 .thread
4865 .read(cx)
4866 .entries();
4867 assert_eq!(entries.len(), 2);
4868 assert_eq!(
4869 entries[0].to_markdown(cx),
4870 "## User\n\nEdited message content\n\n"
4871 );
4872 assert_eq!(
4873 entries[1].to_markdown(cx),
4874 "## Assistant\n\nNew Response\n\n"
4875 );
4876
4877 let entry_view_state = view
4878 .active_thread()
4879 .map(|active| &active.read(cx).entry_view_state)
4880 .unwrap();
4881 let new_editor = entry_view_state.read_with(cx, |state, _cx| {
4882 assert!(!state.entry(1).unwrap().has_content());
4883 state.entry(0).unwrap().message_editor().unwrap().clone()
4884 });
4885
4886 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
4887 })
4888 }
4889
4890 #[gpui::test]
4891 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
4892 init_test(cx);
4893
4894 let connection = StubAgentConnection::new();
4895
4896 let (thread_view, cx) =
4897 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4898 add_to_workspace(thread_view.clone(), cx);
4899
4900 let message_editor = message_editor(&thread_view, cx);
4901 message_editor.update_in(cx, |editor, window, cx| {
4902 editor.set_text("Original message to edit", window, cx);
4903 });
4904 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
4905
4906 cx.run_until_parked();
4907
4908 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
4909 let thread = view.active_thread().unwrap().read(cx).thread.read(cx);
4910 assert_eq!(thread.entries().len(), 1);
4911
4912 let editor = view
4913 .active_thread()
4914 .map(|active| &active.read(cx).entry_view_state)
4915 .as_ref()
4916 .unwrap()
4917 .read(cx)
4918 .entry(0)
4919 .unwrap()
4920 .message_editor()
4921 .unwrap()
4922 .clone();
4923
4924 (editor, thread.session_id().clone())
4925 });
4926
4927 // Focus
4928 cx.focus(&user_message_editor);
4929
4930 thread_view.read_with(cx, |view, cx| {
4931 assert_eq!(
4932 view.active_thread()
4933 .and_then(|active| active.read(cx).editing_message),
4934 Some(0)
4935 );
4936 });
4937
4938 // Edit
4939 user_message_editor.update_in(cx, |editor, window, cx| {
4940 editor.set_text("Edited message content", window, cx);
4941 });
4942
4943 thread_view.read_with(cx, |view, cx| {
4944 assert_eq!(
4945 view.active_thread()
4946 .and_then(|active| active.read(cx).editing_message),
4947 Some(0)
4948 );
4949 });
4950
4951 // Finish streaming response
4952 cx.update(|_, cx| {
4953 connection.send_update(
4954 session_id.clone(),
4955 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("Response".into())),
4956 cx,
4957 );
4958 connection.end_turn(session_id, acp::StopReason::EndTurn);
4959 });
4960
4961 thread_view.read_with(cx, |view, cx| {
4962 assert_eq!(
4963 view.active_thread()
4964 .and_then(|active| active.read(cx).editing_message),
4965 Some(0)
4966 );
4967 });
4968
4969 cx.run_until_parked();
4970
4971 // Should still be editing
4972 cx.update(|window, cx| {
4973 assert!(user_message_editor.focus_handle(cx).is_focused(window));
4974 assert_eq!(
4975 thread_view
4976 .read(cx)
4977 .active_thread()
4978 .and_then(|active| active.read(cx).editing_message),
4979 Some(0)
4980 );
4981 assert_eq!(
4982 user_message_editor.read(cx).text(cx),
4983 "Edited message content"
4984 );
4985 });
4986 }
4987
4988 struct GeneratingThreadSetup {
4989 thread_view: Entity<ConnectionView>,
4990 thread: Entity<AcpThread>,
4991 message_editor: Entity<MessageEditor>,
4992 }
4993
4994 async fn setup_generating_thread(
4995 cx: &mut TestAppContext,
4996 ) -> (GeneratingThreadSetup, &mut VisualTestContext) {
4997 let connection = StubAgentConnection::new();
4998
4999 let (thread_view, cx) =
5000 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5001 add_to_workspace(thread_view.clone(), cx);
5002
5003 let message_editor = message_editor(&thread_view, cx);
5004 message_editor.update_in(cx, |editor, window, cx| {
5005 editor.set_text("Hello", window, cx);
5006 });
5007 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5008
5009 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
5010 let thread = view
5011 .active_thread()
5012 .as_ref()
5013 .unwrap()
5014 .read(cx)
5015 .thread
5016 .clone();
5017 (thread.clone(), thread.read(cx).session_id().clone())
5018 });
5019
5020 cx.run_until_parked();
5021
5022 cx.update(|_, cx| {
5023 connection.send_update(
5024 session_id.clone(),
5025 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
5026 "Response chunk".into(),
5027 )),
5028 cx,
5029 );
5030 });
5031
5032 cx.run_until_parked();
5033
5034 thread.read_with(cx, |thread, _cx| {
5035 assert_eq!(thread.status(), ThreadStatus::Generating);
5036 });
5037
5038 (
5039 GeneratingThreadSetup {
5040 thread_view,
5041 thread,
5042 message_editor,
5043 },
5044 cx,
5045 )
5046 }
5047
5048 #[gpui::test]
5049 async fn test_escape_cancels_generation_from_conversation_focus(cx: &mut TestAppContext) {
5050 init_test(cx);
5051
5052 let (setup, cx) = setup_generating_thread(cx).await;
5053
5054 let focus_handle = setup
5055 .thread_view
5056 .read_with(cx, |view, cx| view.focus_handle(cx));
5057 cx.update(|window, cx| {
5058 window.focus(&focus_handle, cx);
5059 });
5060
5061 setup.thread_view.update_in(cx, |_, window, cx| {
5062 window.dispatch_action(menu::Cancel.boxed_clone(), cx);
5063 });
5064
5065 cx.run_until_parked();
5066
5067 setup.thread.read_with(cx, |thread, _cx| {
5068 assert_eq!(thread.status(), ThreadStatus::Idle);
5069 });
5070 }
5071
5072 #[gpui::test]
5073 async fn test_escape_cancels_generation_from_editor_focus(cx: &mut TestAppContext) {
5074 init_test(cx);
5075
5076 let (setup, cx) = setup_generating_thread(cx).await;
5077
5078 let editor_focus_handle = setup
5079 .message_editor
5080 .read_with(cx, |editor, cx| editor.focus_handle(cx));
5081 cx.update(|window, cx| {
5082 window.focus(&editor_focus_handle, cx);
5083 });
5084
5085 setup.message_editor.update_in(cx, |_, window, cx| {
5086 window.dispatch_action(editor::actions::Cancel.boxed_clone(), cx);
5087 });
5088
5089 cx.run_until_parked();
5090
5091 setup.thread.read_with(cx, |thread, _cx| {
5092 assert_eq!(thread.status(), ThreadStatus::Idle);
5093 });
5094 }
5095
5096 #[gpui::test]
5097 async fn test_escape_when_idle_is_noop(cx: &mut TestAppContext) {
5098 init_test(cx);
5099
5100 let (thread_view, cx) =
5101 setup_thread_view(StubAgentServer::new(StubAgentConnection::new()), cx).await;
5102 add_to_workspace(thread_view.clone(), cx);
5103
5104 let thread = thread_view.read_with(cx, |view, cx| {
5105 view.active_thread().unwrap().read(cx).thread.clone()
5106 });
5107
5108 thread.read_with(cx, |thread, _cx| {
5109 assert_eq!(thread.status(), ThreadStatus::Idle);
5110 });
5111
5112 let focus_handle = thread_view.read_with(cx, |view, _cx| view.focus_handle.clone());
5113 cx.update(|window, cx| {
5114 window.focus(&focus_handle, cx);
5115 });
5116
5117 thread_view.update_in(cx, |_, window, cx| {
5118 window.dispatch_action(menu::Cancel.boxed_clone(), cx);
5119 });
5120
5121 cx.run_until_parked();
5122
5123 thread.read_with(cx, |thread, _cx| {
5124 assert_eq!(thread.status(), ThreadStatus::Idle);
5125 });
5126 }
5127
5128 #[gpui::test]
5129 async fn test_interrupt(cx: &mut TestAppContext) {
5130 init_test(cx);
5131
5132 let connection = StubAgentConnection::new();
5133
5134 let (thread_view, cx) =
5135 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5136 add_to_workspace(thread_view.clone(), cx);
5137
5138 let message_editor = message_editor(&thread_view, cx);
5139 message_editor.update_in(cx, |editor, window, cx| {
5140 editor.set_text("Message 1", window, cx);
5141 });
5142 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5143
5144 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
5145 let thread = view.active_thread().unwrap().read(cx).thread.clone();
5146
5147 (thread.clone(), thread.read(cx).session_id().clone())
5148 });
5149
5150 cx.run_until_parked();
5151
5152 cx.update(|_, cx| {
5153 connection.send_update(
5154 session_id.clone(),
5155 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
5156 "Message 1 resp".into(),
5157 )),
5158 cx,
5159 );
5160 });
5161
5162 cx.run_until_parked();
5163
5164 thread.read_with(cx, |thread, cx| {
5165 assert_eq!(
5166 thread.to_markdown(cx),
5167 indoc::indoc! {"
5168 ## User
5169
5170 Message 1
5171
5172 ## Assistant
5173
5174 Message 1 resp
5175
5176 "}
5177 )
5178 });
5179
5180 message_editor.update_in(cx, |editor, window, cx| {
5181 editor.set_text("Message 2", window, cx);
5182 });
5183 active_thread(&thread_view, cx)
5184 .update_in(cx, |view, window, cx| view.interrupt_and_send(window, cx));
5185
5186 cx.update(|_, cx| {
5187 // Simulate a response sent after beginning to cancel
5188 connection.send_update(
5189 session_id.clone(),
5190 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("onse".into())),
5191 cx,
5192 );
5193 });
5194
5195 cx.run_until_parked();
5196
5197 // Last Message 1 response should appear before Message 2
5198 thread.read_with(cx, |thread, cx| {
5199 assert_eq!(
5200 thread.to_markdown(cx),
5201 indoc::indoc! {"
5202 ## User
5203
5204 Message 1
5205
5206 ## Assistant
5207
5208 Message 1 response
5209
5210 ## User
5211
5212 Message 2
5213
5214 "}
5215 )
5216 });
5217
5218 cx.update(|_, cx| {
5219 connection.send_update(
5220 session_id.clone(),
5221 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
5222 "Message 2 response".into(),
5223 )),
5224 cx,
5225 );
5226 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
5227 });
5228
5229 cx.run_until_parked();
5230
5231 thread.read_with(cx, |thread, cx| {
5232 assert_eq!(
5233 thread.to_markdown(cx),
5234 indoc::indoc! {"
5235 ## User
5236
5237 Message 1
5238
5239 ## Assistant
5240
5241 Message 1 response
5242
5243 ## User
5244
5245 Message 2
5246
5247 ## Assistant
5248
5249 Message 2 response
5250
5251 "}
5252 )
5253 });
5254 }
5255
5256 #[gpui::test]
5257 async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
5258 init_test(cx);
5259
5260 let connection = StubAgentConnection::new();
5261 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5262 acp::ContentChunk::new("Response".into()),
5263 )]);
5264
5265 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5266 add_to_workspace(thread_view.clone(), cx);
5267
5268 let message_editor = message_editor(&thread_view, cx);
5269 message_editor.update_in(cx, |editor, window, cx| {
5270 editor.set_text("Original message to edit", window, cx)
5271 });
5272 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5273 cx.run_until_parked();
5274
5275 let user_message_editor = thread_view.read_with(cx, |thread_view, cx| {
5276 thread_view
5277 .active_thread()
5278 .map(|active| &active.read(cx).entry_view_state)
5279 .as_ref()
5280 .unwrap()
5281 .read(cx)
5282 .entry(0)
5283 .expect("Should have at least one entry")
5284 .message_editor()
5285 .expect("Should have message editor")
5286 .clone()
5287 });
5288
5289 cx.focus(&user_message_editor);
5290 thread_view.read_with(cx, |view, cx| {
5291 assert_eq!(
5292 view.active_thread()
5293 .and_then(|active| active.read(cx).editing_message),
5294 Some(0)
5295 );
5296 });
5297
5298 // Ensure to edit the focused message before proceeding otherwise, since
5299 // its content is not different from what was sent, focus will be lost.
5300 user_message_editor.update_in(cx, |editor, window, cx| {
5301 editor.set_text("Original message to edit with ", window, cx)
5302 });
5303
5304 // Create a simple buffer with some text so we can create a selection
5305 // that will then be added to the message being edited.
5306 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
5307 (thread_view.workspace.clone(), thread_view.project.clone())
5308 });
5309 let buffer = project.update(cx, |project, cx| {
5310 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
5311 });
5312
5313 workspace
5314 .update_in(cx, |workspace, window, cx| {
5315 let editor = cx.new(|cx| {
5316 let mut editor =
5317 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
5318
5319 editor.change_selections(Default::default(), window, cx, |selections| {
5320 selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
5321 });
5322
5323 editor
5324 });
5325 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
5326 })
5327 .unwrap();
5328
5329 thread_view.update_in(cx, |view, window, cx| {
5330 assert_eq!(
5331 view.active_thread()
5332 .and_then(|active| active.read(cx).editing_message),
5333 Some(0)
5334 );
5335 view.insert_selections(window, cx);
5336 });
5337
5338 user_message_editor.read_with(cx, |editor, cx| {
5339 let text = editor.editor().read(cx).text(cx);
5340 let expected_text = String::from("Original message to edit with selection ");
5341
5342 assert_eq!(text, expected_text);
5343 });
5344 }
5345
5346 #[gpui::test]
5347 async fn test_insert_selections(cx: &mut TestAppContext) {
5348 init_test(cx);
5349
5350 let connection = StubAgentConnection::new();
5351 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5352 acp::ContentChunk::new("Response".into()),
5353 )]);
5354
5355 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5356 add_to_workspace(thread_view.clone(), cx);
5357
5358 let message_editor = message_editor(&thread_view, cx);
5359 message_editor.update_in(cx, |editor, window, cx| {
5360 editor.set_text("Can you review this snippet ", window, cx)
5361 });
5362
5363 // Create a simple buffer with some text so we can create a selection
5364 // that will then be added to the message being edited.
5365 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
5366 (thread_view.workspace.clone(), thread_view.project.clone())
5367 });
5368 let buffer = project.update(cx, |project, cx| {
5369 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
5370 });
5371
5372 workspace
5373 .update_in(cx, |workspace, window, cx| {
5374 let editor = cx.new(|cx| {
5375 let mut editor =
5376 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
5377
5378 editor.change_selections(Default::default(), window, cx, |selections| {
5379 selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
5380 });
5381
5382 editor
5383 });
5384 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
5385 })
5386 .unwrap();
5387
5388 thread_view.update_in(cx, |view, window, cx| {
5389 assert_eq!(
5390 view.active_thread()
5391 .and_then(|active| active.read(cx).editing_message),
5392 None
5393 );
5394 view.insert_selections(window, cx);
5395 });
5396
5397 message_editor.read_with(cx, |editor, cx| {
5398 let text = editor.text(cx);
5399 let expected_txt = String::from("Can you review this snippet selection ");
5400
5401 assert_eq!(text, expected_txt);
5402 })
5403 }
5404
5405 #[gpui::test]
5406 async fn test_tool_permission_buttons_terminal_with_pattern(cx: &mut TestAppContext) {
5407 init_test(cx);
5408
5409 let tool_call_id = acp::ToolCallId::new("terminal-1");
5410 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build --release`")
5411 .kind(acp::ToolKind::Edit);
5412
5413 let permission_options = ToolPermissionContext::new(
5414 TerminalTool::NAME,
5415 vec!["cargo build --release".to_string()],
5416 )
5417 .build_permission_options();
5418
5419 let connection =
5420 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5421 tool_call_id.clone(),
5422 permission_options,
5423 )]));
5424
5425 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5426
5427 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5428
5429 // Disable notifications to avoid popup windows
5430 cx.update(|_window, cx| {
5431 AgentSettings::override_global(
5432 AgentSettings {
5433 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5434 ..AgentSettings::get_global(cx).clone()
5435 },
5436 cx,
5437 );
5438 });
5439
5440 let message_editor = message_editor(&thread_view, cx);
5441 message_editor.update_in(cx, |editor, window, cx| {
5442 editor.set_text("Run cargo build", window, cx);
5443 });
5444
5445 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5446
5447 cx.run_until_parked();
5448
5449 // Verify the tool call is in WaitingForConfirmation state with the expected options
5450 thread_view.read_with(cx, |thread_view, cx| {
5451 let thread = thread_view
5452 .active_thread()
5453 .expect("Thread should exist")
5454 .read(cx)
5455 .thread
5456 .clone();
5457 let thread = thread.read(cx);
5458
5459 let tool_call = thread.entries().iter().find_map(|entry| {
5460 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5461 Some(call)
5462 } else {
5463 None
5464 }
5465 });
5466
5467 assert!(tool_call.is_some(), "Expected a tool call entry");
5468 let tool_call = tool_call.unwrap();
5469
5470 // Verify it's waiting for confirmation
5471 assert!(
5472 matches!(
5473 tool_call.status,
5474 acp_thread::ToolCallStatus::WaitingForConfirmation { .. }
5475 ),
5476 "Expected WaitingForConfirmation status, got {:?}",
5477 tool_call.status
5478 );
5479
5480 // Verify the options count (granularity options only, no separate Deny option)
5481 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5482 &tool_call.status
5483 {
5484 let PermissionOptions::Dropdown(choices) = options else {
5485 panic!("Expected dropdown permission options");
5486 };
5487
5488 assert_eq!(
5489 choices.len(),
5490 3,
5491 "Expected 3 permission options (granularity only)"
5492 );
5493
5494 // Verify specific button labels (now using neutral names)
5495 let labels: Vec<&str> = choices
5496 .iter()
5497 .map(|choice| choice.allow.name.as_ref())
5498 .collect();
5499 assert!(
5500 labels.contains(&"Always for terminal"),
5501 "Missing 'Always for terminal' option"
5502 );
5503 assert!(
5504 labels.contains(&"Always for `cargo build` commands"),
5505 "Missing pattern option"
5506 );
5507 assert!(
5508 labels.contains(&"Only this time"),
5509 "Missing 'Only this time' option"
5510 );
5511 }
5512 });
5513 }
5514
5515 #[gpui::test]
5516 async fn test_tool_permission_buttons_edit_file_with_path_pattern(cx: &mut TestAppContext) {
5517 init_test(cx);
5518
5519 let tool_call_id = acp::ToolCallId::new("edit-file-1");
5520 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Edit `src/main.rs`")
5521 .kind(acp::ToolKind::Edit);
5522
5523 let permission_options =
5524 ToolPermissionContext::new(EditFileTool::NAME, vec!["src/main.rs".to_string()])
5525 .build_permission_options();
5526
5527 let connection =
5528 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5529 tool_call_id.clone(),
5530 permission_options,
5531 )]));
5532
5533 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5534
5535 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5536
5537 // Disable notifications
5538 cx.update(|_window, cx| {
5539 AgentSettings::override_global(
5540 AgentSettings {
5541 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5542 ..AgentSettings::get_global(cx).clone()
5543 },
5544 cx,
5545 );
5546 });
5547
5548 let message_editor = message_editor(&thread_view, cx);
5549 message_editor.update_in(cx, |editor, window, cx| {
5550 editor.set_text("Edit the main file", window, cx);
5551 });
5552
5553 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5554
5555 cx.run_until_parked();
5556
5557 // Verify the options
5558 thread_view.read_with(cx, |thread_view, cx| {
5559 let thread = thread_view
5560 .active_thread()
5561 .expect("Thread should exist")
5562 .read(cx)
5563 .thread
5564 .clone();
5565 let thread = thread.read(cx);
5566
5567 let tool_call = thread.entries().iter().find_map(|entry| {
5568 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5569 Some(call)
5570 } else {
5571 None
5572 }
5573 });
5574
5575 assert!(tool_call.is_some(), "Expected a tool call entry");
5576 let tool_call = tool_call.unwrap();
5577
5578 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5579 &tool_call.status
5580 {
5581 let PermissionOptions::Dropdown(choices) = options else {
5582 panic!("Expected dropdown permission options");
5583 };
5584
5585 let labels: Vec<&str> = choices
5586 .iter()
5587 .map(|choice| choice.allow.name.as_ref())
5588 .collect();
5589 assert!(
5590 labels.contains(&"Always for edit file"),
5591 "Missing 'Always for edit file' option"
5592 );
5593 assert!(
5594 labels.contains(&"Always for `src/`"),
5595 "Missing path pattern option"
5596 );
5597 } else {
5598 panic!("Expected WaitingForConfirmation status");
5599 }
5600 });
5601 }
5602
5603 #[gpui::test]
5604 async fn test_tool_permission_buttons_fetch_with_domain_pattern(cx: &mut TestAppContext) {
5605 init_test(cx);
5606
5607 let tool_call_id = acp::ToolCallId::new("fetch-1");
5608 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Fetch `https://docs.rs/gpui`")
5609 .kind(acp::ToolKind::Fetch);
5610
5611 let permission_options =
5612 ToolPermissionContext::new(FetchTool::NAME, vec!["https://docs.rs/gpui".to_string()])
5613 .build_permission_options();
5614
5615 let connection =
5616 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5617 tool_call_id.clone(),
5618 permission_options,
5619 )]));
5620
5621 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5622
5623 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5624
5625 // Disable notifications
5626 cx.update(|_window, cx| {
5627 AgentSettings::override_global(
5628 AgentSettings {
5629 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5630 ..AgentSettings::get_global(cx).clone()
5631 },
5632 cx,
5633 );
5634 });
5635
5636 let message_editor = message_editor(&thread_view, cx);
5637 message_editor.update_in(cx, |editor, window, cx| {
5638 editor.set_text("Fetch the docs", window, cx);
5639 });
5640
5641 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5642
5643 cx.run_until_parked();
5644
5645 // Verify the options
5646 thread_view.read_with(cx, |thread_view, cx| {
5647 let thread = thread_view
5648 .active_thread()
5649 .expect("Thread should exist")
5650 .read(cx)
5651 .thread
5652 .clone();
5653 let thread = thread.read(cx);
5654
5655 let tool_call = thread.entries().iter().find_map(|entry| {
5656 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5657 Some(call)
5658 } else {
5659 None
5660 }
5661 });
5662
5663 assert!(tool_call.is_some(), "Expected a tool call entry");
5664 let tool_call = tool_call.unwrap();
5665
5666 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5667 &tool_call.status
5668 {
5669 let PermissionOptions::Dropdown(choices) = options else {
5670 panic!("Expected dropdown permission options");
5671 };
5672
5673 let labels: Vec<&str> = choices
5674 .iter()
5675 .map(|choice| choice.allow.name.as_ref())
5676 .collect();
5677 assert!(
5678 labels.contains(&"Always for fetch"),
5679 "Missing 'Always for fetch' option"
5680 );
5681 assert!(
5682 labels.contains(&"Always for `docs.rs`"),
5683 "Missing domain pattern option"
5684 );
5685 } else {
5686 panic!("Expected WaitingForConfirmation status");
5687 }
5688 });
5689 }
5690
5691 #[gpui::test]
5692 async fn test_tool_permission_buttons_without_pattern(cx: &mut TestAppContext) {
5693 init_test(cx);
5694
5695 let tool_call_id = acp::ToolCallId::new("terminal-no-pattern-1");
5696 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `./deploy.sh --production`")
5697 .kind(acp::ToolKind::Edit);
5698
5699 // No pattern button since ./deploy.sh doesn't match the alphanumeric pattern
5700 let permission_options = ToolPermissionContext::new(
5701 TerminalTool::NAME,
5702 vec!["./deploy.sh --production".to_string()],
5703 )
5704 .build_permission_options();
5705
5706 let connection =
5707 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5708 tool_call_id.clone(),
5709 permission_options,
5710 )]));
5711
5712 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5713
5714 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5715
5716 // Disable notifications
5717 cx.update(|_window, cx| {
5718 AgentSettings::override_global(
5719 AgentSettings {
5720 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5721 ..AgentSettings::get_global(cx).clone()
5722 },
5723 cx,
5724 );
5725 });
5726
5727 let message_editor = message_editor(&thread_view, cx);
5728 message_editor.update_in(cx, |editor, window, cx| {
5729 editor.set_text("Run the deploy script", window, cx);
5730 });
5731
5732 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5733
5734 cx.run_until_parked();
5735
5736 // Verify only 2 options (no pattern button when command doesn't match pattern)
5737 thread_view.read_with(cx, |thread_view, cx| {
5738 let thread = thread_view
5739 .active_thread()
5740 .expect("Thread should exist")
5741 .read(cx)
5742 .thread
5743 .clone();
5744 let thread = thread.read(cx);
5745
5746 let tool_call = thread.entries().iter().find_map(|entry| {
5747 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5748 Some(call)
5749 } else {
5750 None
5751 }
5752 });
5753
5754 assert!(tool_call.is_some(), "Expected a tool call entry");
5755 let tool_call = tool_call.unwrap();
5756
5757 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5758 &tool_call.status
5759 {
5760 let PermissionOptions::Dropdown(choices) = options else {
5761 panic!("Expected dropdown permission options");
5762 };
5763
5764 assert_eq!(
5765 choices.len(),
5766 2,
5767 "Expected 2 permission options (no pattern option)"
5768 );
5769
5770 let labels: Vec<&str> = choices
5771 .iter()
5772 .map(|choice| choice.allow.name.as_ref())
5773 .collect();
5774 assert!(
5775 labels.contains(&"Always for terminal"),
5776 "Missing 'Always for terminal' option"
5777 );
5778 assert!(
5779 labels.contains(&"Only this time"),
5780 "Missing 'Only this time' option"
5781 );
5782 // Should NOT contain a pattern option
5783 assert!(
5784 !labels.iter().any(|l| l.contains("commands")),
5785 "Should not have pattern option"
5786 );
5787 } else {
5788 panic!("Expected WaitingForConfirmation status");
5789 }
5790 });
5791 }
5792
5793 #[gpui::test]
5794 async fn test_authorize_tool_call_action_triggers_authorization(cx: &mut TestAppContext) {
5795 init_test(cx);
5796
5797 let tool_call_id = acp::ToolCallId::new("action-test-1");
5798 let tool_call =
5799 acp::ToolCall::new(tool_call_id.clone(), "Run `cargo test`").kind(acp::ToolKind::Edit);
5800
5801 let permission_options =
5802 ToolPermissionContext::new(TerminalTool::NAME, vec!["cargo test".to_string()])
5803 .build_permission_options();
5804
5805 let connection =
5806 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5807 tool_call_id.clone(),
5808 permission_options,
5809 )]));
5810
5811 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5812
5813 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5814 add_to_workspace(thread_view.clone(), cx);
5815
5816 cx.update(|_window, cx| {
5817 AgentSettings::override_global(
5818 AgentSettings {
5819 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5820 ..AgentSettings::get_global(cx).clone()
5821 },
5822 cx,
5823 );
5824 });
5825
5826 let message_editor = message_editor(&thread_view, cx);
5827 message_editor.update_in(cx, |editor, window, cx| {
5828 editor.set_text("Run tests", window, cx);
5829 });
5830
5831 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5832
5833 cx.run_until_parked();
5834
5835 // Verify tool call is waiting for confirmation
5836 thread_view.read_with(cx, |thread_view, cx| {
5837 let tool_call = thread_view.pending_tool_call(cx);
5838 assert!(
5839 tool_call.is_some(),
5840 "Expected a tool call waiting for confirmation"
5841 );
5842 });
5843
5844 // Dispatch the AuthorizeToolCall action (simulating dropdown menu selection)
5845 thread_view.update_in(cx, |_, window, cx| {
5846 window.dispatch_action(
5847 crate::AuthorizeToolCall {
5848 tool_call_id: "action-test-1".to_string(),
5849 option_id: "allow".to_string(),
5850 option_kind: "AllowOnce".to_string(),
5851 }
5852 .boxed_clone(),
5853 cx,
5854 );
5855 });
5856
5857 cx.run_until_parked();
5858
5859 // Verify tool call is no longer waiting for confirmation (was authorized)
5860 thread_view.read_with(cx, |thread_view, cx| {
5861 let tool_call = thread_view.pending_tool_call(cx);
5862 assert!(
5863 tool_call.is_none(),
5864 "Tool call should no longer be waiting for confirmation after AuthorizeToolCall action"
5865 );
5866 });
5867 }
5868
5869 #[gpui::test]
5870 async fn test_authorize_tool_call_action_with_pattern_option(cx: &mut TestAppContext) {
5871 init_test(cx);
5872
5873 let tool_call_id = acp::ToolCallId::new("pattern-action-test-1");
5874 let tool_call =
5875 acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
5876
5877 let permission_options =
5878 ToolPermissionContext::new(TerminalTool::NAME, vec!["npm install".to_string()])
5879 .build_permission_options();
5880
5881 let connection =
5882 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5883 tool_call_id.clone(),
5884 permission_options.clone(),
5885 )]));
5886
5887 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5888
5889 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5890 add_to_workspace(thread_view.clone(), cx);
5891
5892 cx.update(|_window, cx| {
5893 AgentSettings::override_global(
5894 AgentSettings {
5895 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5896 ..AgentSettings::get_global(cx).clone()
5897 },
5898 cx,
5899 );
5900 });
5901
5902 let message_editor = message_editor(&thread_view, cx);
5903 message_editor.update_in(cx, |editor, window, cx| {
5904 editor.set_text("Install dependencies", window, cx);
5905 });
5906
5907 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5908
5909 cx.run_until_parked();
5910
5911 // Find the pattern option ID
5912 let pattern_option = match &permission_options {
5913 PermissionOptions::Dropdown(choices) => choices
5914 .iter()
5915 .find(|choice| {
5916 choice
5917 .allow
5918 .option_id
5919 .0
5920 .starts_with("always_allow_pattern:")
5921 })
5922 .map(|choice| &choice.allow)
5923 .expect("Should have a pattern option for npm command"),
5924 _ => panic!("Expected dropdown permission options"),
5925 };
5926
5927 // Dispatch action with the pattern option (simulating "Always allow `npm` commands")
5928 thread_view.update_in(cx, |_, window, cx| {
5929 window.dispatch_action(
5930 crate::AuthorizeToolCall {
5931 tool_call_id: "pattern-action-test-1".to_string(),
5932 option_id: pattern_option.option_id.0.to_string(),
5933 option_kind: "AllowAlways".to_string(),
5934 }
5935 .boxed_clone(),
5936 cx,
5937 );
5938 });
5939
5940 cx.run_until_parked();
5941
5942 // Verify tool call was authorized
5943 thread_view.read_with(cx, |thread_view, cx| {
5944 let tool_call = thread_view.pending_tool_call(cx);
5945 assert!(
5946 tool_call.is_none(),
5947 "Tool call should be authorized after selecting pattern option"
5948 );
5949 });
5950 }
5951
5952 #[gpui::test]
5953 async fn test_deny_button_uses_selected_granularity(cx: &mut TestAppContext) {
5954 init_test(cx);
5955
5956 let tool_call_id = acp::ToolCallId::new("deny-granularity-test-1");
5957 let tool_call =
5958 acp::ToolCall::new(tool_call_id.clone(), "Run `git push`").kind(acp::ToolKind::Edit);
5959
5960 let permission_options =
5961 ToolPermissionContext::new(TerminalTool::NAME, vec!["git push".to_string()])
5962 .build_permission_options();
5963
5964 let connection =
5965 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5966 tool_call_id.clone(),
5967 permission_options.clone(),
5968 )]));
5969
5970 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5971
5972 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5973 add_to_workspace(thread_view.clone(), cx);
5974
5975 cx.update(|_window, cx| {
5976 AgentSettings::override_global(
5977 AgentSettings {
5978 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5979 ..AgentSettings::get_global(cx).clone()
5980 },
5981 cx,
5982 );
5983 });
5984
5985 let message_editor = message_editor(&thread_view, cx);
5986 message_editor.update_in(cx, |editor, window, cx| {
5987 editor.set_text("Push changes", window, cx);
5988 });
5989
5990 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
5991
5992 cx.run_until_parked();
5993
5994 // Use default granularity (last option = "Only this time")
5995 // Simulate clicking the Deny button
5996 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| {
5997 view.reject_once(&RejectOnce, window, cx)
5998 });
5999
6000 cx.run_until_parked();
6001
6002 // Verify tool call was rejected (no longer waiting for confirmation)
6003 thread_view.read_with(cx, |thread_view, cx| {
6004 let tool_call = thread_view.pending_tool_call(cx);
6005 assert!(
6006 tool_call.is_none(),
6007 "Tool call should be rejected after Deny"
6008 );
6009 });
6010 }
6011
6012 #[gpui::test]
6013 async fn test_option_id_transformation_for_allow() {
6014 let permission_options = ToolPermissionContext::new(
6015 TerminalTool::NAME,
6016 vec!["cargo build --release".to_string()],
6017 )
6018 .build_permission_options();
6019
6020 let PermissionOptions::Dropdown(choices) = permission_options else {
6021 panic!("Expected dropdown permission options");
6022 };
6023
6024 let allow_ids: Vec<String> = choices
6025 .iter()
6026 .map(|choice| choice.allow.option_id.0.to_string())
6027 .collect();
6028
6029 assert!(allow_ids.contains(&"always_allow:terminal".to_string()));
6030 assert!(allow_ids.contains(&"allow".to_string()));
6031 assert!(
6032 allow_ids
6033 .iter()
6034 .any(|id| id.starts_with("always_allow_pattern:terminal\n")),
6035 "Missing allow pattern option"
6036 );
6037 }
6038
6039 #[gpui::test]
6040 async fn test_option_id_transformation_for_deny() {
6041 let permission_options = ToolPermissionContext::new(
6042 TerminalTool::NAME,
6043 vec!["cargo build --release".to_string()],
6044 )
6045 .build_permission_options();
6046
6047 let PermissionOptions::Dropdown(choices) = permission_options else {
6048 panic!("Expected dropdown permission options");
6049 };
6050
6051 let deny_ids: Vec<String> = choices
6052 .iter()
6053 .map(|choice| choice.deny.option_id.0.to_string())
6054 .collect();
6055
6056 assert!(deny_ids.contains(&"always_deny:terminal".to_string()));
6057 assert!(deny_ids.contains(&"deny".to_string()));
6058 assert!(
6059 deny_ids
6060 .iter()
6061 .any(|id| id.starts_with("always_deny_pattern:terminal\n")),
6062 "Missing deny pattern option"
6063 );
6064 }
6065
6066 #[gpui::test]
6067 async fn test_manually_editing_title_updates_acp_thread_title(cx: &mut TestAppContext) {
6068 init_test(cx);
6069
6070 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6071 add_to_workspace(thread_view.clone(), cx);
6072
6073 let active = active_thread(&thread_view, cx);
6074 let title_editor = cx.read(|cx| active.read(cx).title_editor.clone());
6075 let thread = cx.read(|cx| active.read(cx).thread.clone());
6076
6077 title_editor.read_with(cx, |editor, cx| {
6078 assert!(!editor.read_only(cx));
6079 });
6080
6081 cx.focus(&thread_view);
6082 cx.focus(&title_editor);
6083
6084 cx.dispatch_action(editor::actions::DeleteLine);
6085 cx.simulate_input("My Custom Title");
6086
6087 cx.run_until_parked();
6088
6089 title_editor.read_with(cx, |editor, cx| {
6090 assert_eq!(editor.text(cx), "My Custom Title");
6091 });
6092 thread.read_with(cx, |thread, _cx| {
6093 assert_eq!(thread.title().as_ref(), "My Custom Title");
6094 });
6095 }
6096
6097 #[gpui::test]
6098 async fn test_title_editor_is_read_only_when_set_title_unsupported(cx: &mut TestAppContext) {
6099 init_test(cx);
6100
6101 let (thread_view, cx) =
6102 setup_thread_view(StubAgentServer::new(ResumeOnlyAgentConnection), cx).await;
6103
6104 let active = active_thread(&thread_view, cx);
6105 let title_editor = cx.read(|cx| active.read(cx).title_editor.clone());
6106
6107 title_editor.read_with(cx, |editor, cx| {
6108 assert!(
6109 editor.read_only(cx),
6110 "Title editor should be read-only when the connection does not support set_title"
6111 );
6112 });
6113 }
6114
6115 #[gpui::test]
6116 async fn test_max_tokens_error_is_rendered(cx: &mut TestAppContext) {
6117 init_test(cx);
6118
6119 let connection = StubAgentConnection::new();
6120
6121 let (thread_view, cx) =
6122 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6123
6124 let message_editor = message_editor(&thread_view, cx);
6125 message_editor.update_in(cx, |editor, window, cx| {
6126 editor.set_text("Some prompt", window, cx);
6127 });
6128 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
6129
6130 let session_id = thread_view.read_with(cx, |view, cx| {
6131 view.active_thread()
6132 .unwrap()
6133 .read(cx)
6134 .thread
6135 .read(cx)
6136 .session_id()
6137 .clone()
6138 });
6139
6140 cx.run_until_parked();
6141
6142 cx.update(|_, _cx| {
6143 connection.end_turn(session_id, acp::StopReason::MaxTokens);
6144 });
6145
6146 cx.run_until_parked();
6147
6148 thread_view.read_with(cx, |thread_view, cx| {
6149 let state = thread_view.active_thread().unwrap();
6150 let error = &state.read(cx).thread_error;
6151 match error {
6152 Some(ThreadError::Other { message, .. }) => {
6153 assert!(
6154 message.contains("Max tokens reached"),
6155 "Expected 'Max tokens reached' error, got: {}",
6156 message
6157 );
6158 }
6159 other => panic!(
6160 "Expected ThreadError::Other with 'Max tokens reached', got: {:?}",
6161 other.is_some()
6162 ),
6163 }
6164 });
6165 }
6166
6167 fn create_test_acp_thread(
6168 parent_session_id: Option<acp::SessionId>,
6169 session_id: &str,
6170 connection: Rc<dyn AgentConnection>,
6171 project: Entity<Project>,
6172 cx: &mut App,
6173 ) -> Entity<AcpThread> {
6174 let action_log = cx.new(|_| ActionLog::new(project.clone()));
6175 cx.new(|cx| {
6176 AcpThread::new(
6177 parent_session_id,
6178 "Test Thread",
6179 None,
6180 connection,
6181 project,
6182 action_log,
6183 acp::SessionId::new(session_id),
6184 watch::Receiver::constant(acp::PromptCapabilities::new()),
6185 cx,
6186 )
6187 })
6188 }
6189
6190 fn request_test_tool_authorization(
6191 thread: &Entity<AcpThread>,
6192 tool_call_id: &str,
6193 option_id: &str,
6194 cx: &mut TestAppContext,
6195 ) -> Task<acp::RequestPermissionOutcome> {
6196 let tool_call_id = acp::ToolCallId::new(tool_call_id);
6197 let label = format!("Tool {tool_call_id}");
6198 let option_id = acp::PermissionOptionId::new(option_id);
6199 cx.update(|cx| {
6200 thread.update(cx, |thread, cx| {
6201 thread
6202 .request_tool_call_authorization(
6203 acp::ToolCall::new(tool_call_id, label)
6204 .kind(acp::ToolKind::Edit)
6205 .into(),
6206 PermissionOptions::Flat(vec![acp::PermissionOption::new(
6207 option_id,
6208 "Allow",
6209 acp::PermissionOptionKind::AllowOnce,
6210 )]),
6211 cx,
6212 )
6213 .unwrap()
6214 })
6215 })
6216 }
6217
6218 #[gpui::test]
6219 async fn test_conversation_multiple_tool_calls_fifo_ordering(cx: &mut TestAppContext) {
6220 init_test(cx);
6221
6222 let fs = FakeFs::new(cx.executor());
6223 let project = Project::test(fs, [], cx).await;
6224 let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
6225
6226 let (thread, conversation) = cx.update(|cx| {
6227 let thread =
6228 create_test_acp_thread(None, "session-1", connection.clone(), project.clone(), cx);
6229 let conversation = cx.new(|cx| {
6230 let mut conversation = Conversation::default();
6231 conversation.register_thread(thread.clone(), cx);
6232 conversation
6233 });
6234 (thread, conversation)
6235 });
6236
6237 let _task1 = request_test_tool_authorization(&thread, "tc-1", "allow-1", cx);
6238 let _task2 = request_test_tool_authorization(&thread, "tc-2", "allow-2", cx);
6239
6240 cx.read(|cx| {
6241 let session_id = acp::SessionId::new("session-1");
6242 let (_, tool_call_id, _) = conversation
6243 .read(cx)
6244 .pending_tool_call(&session_id, cx)
6245 .expect("Expected a pending tool call");
6246 assert_eq!(tool_call_id, acp::ToolCallId::new("tc-1"));
6247 });
6248
6249 cx.update(|cx| {
6250 conversation.update(cx, |conversation, cx| {
6251 conversation.authorize_tool_call(
6252 acp::SessionId::new("session-1"),
6253 acp::ToolCallId::new("tc-1"),
6254 acp::PermissionOptionId::new("allow-1"),
6255 acp::PermissionOptionKind::AllowOnce,
6256 cx,
6257 );
6258 });
6259 });
6260
6261 cx.run_until_parked();
6262
6263 cx.read(|cx| {
6264 let session_id = acp::SessionId::new("session-1");
6265 let (_, tool_call_id, _) = conversation
6266 .read(cx)
6267 .pending_tool_call(&session_id, cx)
6268 .expect("Expected tc-2 to be pending after tc-1 was authorized");
6269 assert_eq!(tool_call_id, acp::ToolCallId::new("tc-2"));
6270 });
6271
6272 cx.update(|cx| {
6273 conversation.update(cx, |conversation, cx| {
6274 conversation.authorize_tool_call(
6275 acp::SessionId::new("session-1"),
6276 acp::ToolCallId::new("tc-2"),
6277 acp::PermissionOptionId::new("allow-2"),
6278 acp::PermissionOptionKind::AllowOnce,
6279 cx,
6280 );
6281 });
6282 });
6283
6284 cx.run_until_parked();
6285
6286 cx.read(|cx| {
6287 let session_id = acp::SessionId::new("session-1");
6288 assert!(
6289 conversation
6290 .read(cx)
6291 .pending_tool_call(&session_id, cx)
6292 .is_none(),
6293 "Expected no pending tool calls after both were authorized"
6294 );
6295 });
6296 }
6297
6298 #[gpui::test]
6299 async fn test_conversation_subagent_scoped_pending_tool_call(cx: &mut TestAppContext) {
6300 init_test(cx);
6301
6302 let fs = FakeFs::new(cx.executor());
6303 let project = Project::test(fs, [], cx).await;
6304 let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
6305
6306 let (parent_thread, subagent_thread, conversation) = cx.update(|cx| {
6307 let parent_thread =
6308 create_test_acp_thread(None, "parent", connection.clone(), project.clone(), cx);
6309 let subagent_thread = create_test_acp_thread(
6310 Some(acp::SessionId::new("parent")),
6311 "subagent",
6312 connection.clone(),
6313 project.clone(),
6314 cx,
6315 );
6316 let conversation = cx.new(|cx| {
6317 let mut conversation = Conversation::default();
6318 conversation.register_thread(parent_thread.clone(), cx);
6319 conversation.register_thread(subagent_thread.clone(), cx);
6320 conversation
6321 });
6322 (parent_thread, subagent_thread, conversation)
6323 });
6324
6325 let _parent_task =
6326 request_test_tool_authorization(&parent_thread, "parent-tc", "allow-parent", cx);
6327 let _subagent_task =
6328 request_test_tool_authorization(&subagent_thread, "subagent-tc", "allow-subagent", cx);
6329
6330 // Querying with the subagent's session ID returns only the
6331 // subagent's own tool call (subagent path is scoped to its session)
6332 cx.read(|cx| {
6333 let subagent_id = acp::SessionId::new("subagent");
6334 let (session_id, tool_call_id, _) = conversation
6335 .read(cx)
6336 .pending_tool_call(&subagent_id, cx)
6337 .expect("Expected subagent's pending tool call");
6338 assert_eq!(session_id, acp::SessionId::new("subagent"));
6339 assert_eq!(tool_call_id, acp::ToolCallId::new("subagent-tc"));
6340 });
6341
6342 // Querying with the parent's session ID returns the first pending
6343 // request in FIFO order across all sessions
6344 cx.read(|cx| {
6345 let parent_id = acp::SessionId::new("parent");
6346 let (session_id, tool_call_id, _) = conversation
6347 .read(cx)
6348 .pending_tool_call(&parent_id, cx)
6349 .expect("Expected a pending tool call from parent query");
6350 assert_eq!(session_id, acp::SessionId::new("parent"));
6351 assert_eq!(tool_call_id, acp::ToolCallId::new("parent-tc"));
6352 });
6353 }
6354
6355 #[gpui::test]
6356 async fn test_conversation_parent_pending_tool_call_returns_first_across_threads(
6357 cx: &mut TestAppContext,
6358 ) {
6359 init_test(cx);
6360
6361 let fs = FakeFs::new(cx.executor());
6362 let project = Project::test(fs, [], cx).await;
6363 let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
6364
6365 let (thread_a, thread_b, conversation) = cx.update(|cx| {
6366 let thread_a =
6367 create_test_acp_thread(None, "thread-a", connection.clone(), project.clone(), cx);
6368 let thread_b =
6369 create_test_acp_thread(None, "thread-b", connection.clone(), project.clone(), cx);
6370 let conversation = cx.new(|cx| {
6371 let mut conversation = Conversation::default();
6372 conversation.register_thread(thread_a.clone(), cx);
6373 conversation.register_thread(thread_b.clone(), cx);
6374 conversation
6375 });
6376 (thread_a, thread_b, conversation)
6377 });
6378
6379 let _task_a = request_test_tool_authorization(&thread_a, "tc-a", "allow-a", cx);
6380 let _task_b = request_test_tool_authorization(&thread_b, "tc-b", "allow-b", cx);
6381
6382 // Both threads are non-subagent, so pending_tool_call always returns
6383 // the first entry from permission_requests (FIFO across all sessions)
6384 cx.read(|cx| {
6385 let session_a = acp::SessionId::new("thread-a");
6386 let (session_id, tool_call_id, _) = conversation
6387 .read(cx)
6388 .pending_tool_call(&session_a, cx)
6389 .expect("Expected a pending tool call");
6390 assert_eq!(session_id, acp::SessionId::new("thread-a"));
6391 assert_eq!(tool_call_id, acp::ToolCallId::new("tc-a"));
6392 });
6393
6394 // Querying with thread-b also returns thread-a's tool call,
6395 // because non-subagent queries always use permission_requests.first()
6396 cx.read(|cx| {
6397 let session_b = acp::SessionId::new("thread-b");
6398 let (session_id, tool_call_id, _) = conversation
6399 .read(cx)
6400 .pending_tool_call(&session_b, cx)
6401 .expect("Expected a pending tool call from thread-b query");
6402 assert_eq!(
6403 session_id,
6404 acp::SessionId::new("thread-a"),
6405 "Non-subagent queries always return the first pending request in FIFO order"
6406 );
6407 assert_eq!(tool_call_id, acp::ToolCallId::new("tc-a"));
6408 });
6409
6410 // After authorizing thread-a's tool call, thread-b's becomes first
6411 cx.update(|cx| {
6412 conversation.update(cx, |conversation, cx| {
6413 conversation.authorize_tool_call(
6414 acp::SessionId::new("thread-a"),
6415 acp::ToolCallId::new("tc-a"),
6416 acp::PermissionOptionId::new("allow-a"),
6417 acp::PermissionOptionKind::AllowOnce,
6418 cx,
6419 );
6420 });
6421 });
6422
6423 cx.run_until_parked();
6424
6425 cx.read(|cx| {
6426 let session_b = acp::SessionId::new("thread-b");
6427 let (session_id, tool_call_id, _) = conversation
6428 .read(cx)
6429 .pending_tool_call(&session_b, cx)
6430 .expect("Expected thread-b's tool call after thread-a's was authorized");
6431 assert_eq!(session_id, acp::SessionId::new("thread-b"));
6432 assert_eq!(tool_call_id, acp::ToolCallId::new("tc-b"));
6433 });
6434 }
6435
6436 #[gpui::test]
6437 async fn test_move_queued_message_to_empty_main_editor(cx: &mut TestAppContext) {
6438 init_test(cx);
6439
6440 let (connection_view, cx) =
6441 setup_thread_view(StubAgentServer::default_response(), cx).await;
6442
6443 // Add a plain-text message to the queue directly.
6444 active_thread(&connection_view, cx).update_in(cx, |thread, window, cx| {
6445 thread.add_to_queue(
6446 vec![acp::ContentBlock::Text(acp::TextContent::new(
6447 "queued message".to_string(),
6448 ))],
6449 vec![],
6450 cx,
6451 );
6452 // Main editor must be empty for this path — it is by default, but
6453 // assert to make the precondition explicit.
6454 assert!(thread.message_editor.read(cx).is_empty(cx));
6455 thread.move_queued_message_to_main_editor(0, None, window, cx);
6456 });
6457
6458 cx.run_until_parked();
6459
6460 // Queue should now be empty.
6461 let queue_len = active_thread(&connection_view, cx)
6462 .read_with(cx, |thread, _cx| thread.local_queued_messages.len());
6463 assert_eq!(queue_len, 0, "Queue should be empty after move");
6464
6465 // Main editor should contain the queued message text.
6466 let text = message_editor(&connection_view, cx).update(cx, |editor, cx| editor.text(cx));
6467 assert_eq!(
6468 text, "queued message",
6469 "Main editor should contain the moved queued message"
6470 );
6471 }
6472
6473 #[gpui::test]
6474 async fn test_move_queued_message_to_non_empty_main_editor(cx: &mut TestAppContext) {
6475 init_test(cx);
6476
6477 let (connection_view, cx) =
6478 setup_thread_view(StubAgentServer::default_response(), cx).await;
6479
6480 // Seed the main editor with existing content.
6481 message_editor(&connection_view, cx).update_in(cx, |editor, window, cx| {
6482 editor.set_message(
6483 vec![acp::ContentBlock::Text(acp::TextContent::new(
6484 "existing content".to_string(),
6485 ))],
6486 window,
6487 cx,
6488 );
6489 });
6490
6491 // Add a plain-text message to the queue.
6492 active_thread(&connection_view, cx).update_in(cx, |thread, window, cx| {
6493 thread.add_to_queue(
6494 vec![acp::ContentBlock::Text(acp::TextContent::new(
6495 "queued message".to_string(),
6496 ))],
6497 vec![],
6498 cx,
6499 );
6500 thread.move_queued_message_to_main_editor(0, None, window, cx);
6501 });
6502
6503 cx.run_until_parked();
6504
6505 // Queue should now be empty.
6506 let queue_len = active_thread(&connection_view, cx)
6507 .read_with(cx, |thread, _cx| thread.local_queued_messages.len());
6508 assert_eq!(queue_len, 0, "Queue should be empty after move");
6509
6510 // Main editor should contain existing content + separator + queued content.
6511 let text = message_editor(&connection_view, cx).update(cx, |editor, cx| editor.text(cx));
6512 assert_eq!(
6513 text, "existing content\n\nqueued message",
6514 "Main editor should have existing content and queued message separated by two newlines"
6515 );
6516 }
6517}