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