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