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 let session_id = session_id.clone();
2589 cx.spawn(async move |_this, cx| {
2590 crate::thread_worktree_archive::cleanup_thread_archived_worktrees(&session_id, cx)
2591 .await;
2592 })
2593 .detach();
2594 }
2595}
2596
2597fn loading_contents_spinner(size: IconSize) -> AnyElement {
2598 Icon::new(IconName::LoadCircle)
2599 .size(size)
2600 .color(Color::Accent)
2601 .with_rotate_animation(3)
2602 .into_any_element()
2603}
2604
2605fn placeholder_text(agent_name: &str, has_commands: bool) -> String {
2606 if agent_name == agent::ZED_AGENT_ID.as_ref() {
2607 format!("Message the {} — @ to include context", agent_name)
2608 } else if has_commands {
2609 format!(
2610 "Message {} — @ to include context, / for commands",
2611 agent_name
2612 )
2613 } else {
2614 format!("Message {} — @ to include context", agent_name)
2615 }
2616}
2617
2618impl Focusable for ConversationView {
2619 fn focus_handle(&self, cx: &App) -> FocusHandle {
2620 match self.active_thread() {
2621 Some(thread) => thread.read(cx).focus_handle(cx),
2622 None => self.focus_handle.clone(),
2623 }
2624 }
2625}
2626
2627#[cfg(any(test, feature = "test-support"))]
2628impl ConversationView {
2629 /// Expands a tool call so its content is visible.
2630 /// This is primarily useful for visual testing.
2631 pub fn expand_tool_call(&mut self, tool_call_id: acp::ToolCallId, cx: &mut Context<Self>) {
2632 if let Some(active) = self.active_thread() {
2633 active.update(cx, |active, _cx| {
2634 active.expanded_tool_calls.insert(tool_call_id);
2635 });
2636 cx.notify();
2637 }
2638 }
2639
2640 #[cfg(any(test, feature = "test-support"))]
2641 pub fn set_updated_at(&mut self, updated_at: Instant, cx: &mut Context<Self>) {
2642 let Some(connected) = self.as_connected_mut() else {
2643 return;
2644 };
2645
2646 connected.conversation.update(cx, |conversation, _cx| {
2647 conversation.updated_at = Some(updated_at);
2648 });
2649 }
2650}
2651
2652impl Render for ConversationView {
2653 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2654 self.sync_queued_message_editors(window, cx);
2655
2656 v_flex()
2657 .track_focus(&self.focus_handle)
2658 .size_full()
2659 .bg(cx.theme().colors().panel_background)
2660 .child(match &self.server_state {
2661 ServerState::Loading { .. } => v_flex()
2662 .flex_1()
2663 .size_full()
2664 .items_center()
2665 .justify_center()
2666 .child(
2667 Label::new("Loading…").color(Color::Muted).with_animation(
2668 "loading-agent-label",
2669 Animation::new(Duration::from_secs(2))
2670 .repeat()
2671 .with_easing(pulsating_between(0.3, 0.7)),
2672 |label, delta| label.alpha(delta),
2673 ),
2674 )
2675 .into_any(),
2676 ServerState::LoadError { error: e, .. } => v_flex()
2677 .flex_1()
2678 .size_full()
2679 .items_center()
2680 .justify_end()
2681 .child(self.render_load_error(e, window, cx))
2682 .into_any(),
2683 ServerState::Connected(ConnectedServerState {
2684 connection,
2685 auth_state:
2686 AuthState::Unauthenticated {
2687 description,
2688 configuration_view,
2689 pending_auth_method,
2690 _subscription,
2691 },
2692 ..
2693 }) => v_flex()
2694 .flex_1()
2695 .size_full()
2696 .justify_end()
2697 .child(self.render_auth_required_state(
2698 connection,
2699 description.as_ref(),
2700 configuration_view.as_ref(),
2701 pending_auth_method.as_ref(),
2702 window,
2703 cx,
2704 ))
2705 .into_any_element(),
2706 ServerState::Connected(connected) => {
2707 if let Some(view) = connected.active_view() {
2708 view.clone().into_any_element()
2709 } else {
2710 debug_panic!("This state should never be reached");
2711 div().into_any_element()
2712 }
2713 }
2714 })
2715 }
2716}
2717
2718fn plan_label_markdown_style(
2719 status: &acp::PlanEntryStatus,
2720 window: &Window,
2721 cx: &App,
2722) -> MarkdownStyle {
2723 let default_md_style = MarkdownStyle::themed(MarkdownFont::Agent, window, cx);
2724
2725 MarkdownStyle {
2726 base_text_style: TextStyle {
2727 color: cx.theme().colors().text_muted,
2728 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
2729 Some(gpui::StrikethroughStyle {
2730 thickness: px(1.),
2731 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
2732 })
2733 } else {
2734 None
2735 },
2736 ..default_md_style.base_text_style
2737 },
2738 ..default_md_style
2739 }
2740}
2741
2742#[cfg(test)]
2743pub(crate) mod tests {
2744 use acp_thread::{
2745 AgentSessionList, AgentSessionListRequest, AgentSessionListResponse, StubAgentConnection,
2746 };
2747 use action_log::ActionLog;
2748 use agent::{AgentTool, EditFileTool, FetchTool, TerminalTool, ToolPermissionContext};
2749 use agent_client_protocol::SessionId;
2750 use editor::MultiBufferOffset;
2751 use fs::FakeFs;
2752 use gpui::{EventEmitter, TestAppContext, VisualTestContext};
2753 use parking_lot::Mutex;
2754 use project::Project;
2755 use serde_json::json;
2756 use settings::SettingsStore;
2757 use std::any::Any;
2758 use std::path::{Path, PathBuf};
2759 use std::rc::Rc;
2760 use std::sync::Arc;
2761 use workspace::{Item, MultiWorkspace};
2762
2763 use crate::agent_panel;
2764
2765 use super::*;
2766
2767 #[gpui::test]
2768 async fn test_drop(cx: &mut TestAppContext) {
2769 init_test(cx);
2770
2771 let (conversation_view, _cx) =
2772 setup_conversation_view(StubAgentServer::default_response(), cx).await;
2773 let weak_view = conversation_view.downgrade();
2774 drop(conversation_view);
2775 assert!(!weak_view.is_upgradable());
2776 }
2777
2778 #[gpui::test]
2779 async fn test_external_source_prompt_requires_manual_send(cx: &mut TestAppContext) {
2780 init_test(cx);
2781
2782 let Some(prompt) = crate::ExternalSourcePrompt::new("Write me a script") else {
2783 panic!("expected prompt from external source to sanitize successfully");
2784 };
2785 let initial_content = AgentInitialContent::FromExternalSource(prompt);
2786
2787 let (conversation_view, cx) = setup_conversation_view_with_initial_content(
2788 StubAgentServer::default_response(),
2789 initial_content,
2790 cx,
2791 )
2792 .await;
2793
2794 active_thread(&conversation_view, cx).read_with(cx, |view, cx| {
2795 assert!(view.show_external_source_prompt_warning);
2796 assert_eq!(view.thread.read(cx).entries().len(), 0);
2797 assert_eq!(view.message_editor.read(cx).text(cx), "Write me a script");
2798 });
2799 }
2800
2801 #[gpui::test]
2802 async fn test_external_source_prompt_warning_clears_after_send(cx: &mut TestAppContext) {
2803 init_test(cx);
2804
2805 let Some(prompt) = crate::ExternalSourcePrompt::new("Write me a script") else {
2806 panic!("expected prompt from external source to sanitize successfully");
2807 };
2808 let initial_content = AgentInitialContent::FromExternalSource(prompt);
2809
2810 let (conversation_view, cx) = setup_conversation_view_with_initial_content(
2811 StubAgentServer::default_response(),
2812 initial_content,
2813 cx,
2814 )
2815 .await;
2816
2817 active_thread(&conversation_view, cx)
2818 .update_in(cx, |view, window, cx| view.send(window, cx));
2819 cx.run_until_parked();
2820
2821 active_thread(&conversation_view, cx).read_with(cx, |view, cx| {
2822 assert!(!view.show_external_source_prompt_warning);
2823 assert_eq!(view.message_editor.read(cx).text(cx), "");
2824 assert_eq!(view.thread.read(cx).entries().len(), 2);
2825 });
2826 }
2827
2828 #[gpui::test]
2829 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
2830 init_test(cx);
2831
2832 let (conversation_view, cx) =
2833 setup_conversation_view(StubAgentServer::default_response(), cx).await;
2834
2835 let message_editor = message_editor(&conversation_view, cx);
2836 message_editor.update_in(cx, |editor, window, cx| {
2837 editor.set_text("Hello", window, cx);
2838 });
2839
2840 cx.deactivate_window();
2841
2842 active_thread(&conversation_view, cx)
2843 .update_in(cx, |view, window, cx| view.send(window, cx));
2844
2845 cx.run_until_parked();
2846
2847 assert!(
2848 cx.windows()
2849 .iter()
2850 .any(|window| window.downcast::<AgentNotification>().is_some())
2851 );
2852 }
2853
2854 #[gpui::test]
2855 async fn test_notification_for_error(cx: &mut TestAppContext) {
2856 init_test(cx);
2857
2858 let (conversation_view, cx) =
2859 setup_conversation_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
2860
2861 let message_editor = message_editor(&conversation_view, cx);
2862 message_editor.update_in(cx, |editor, window, cx| {
2863 editor.set_text("Hello", window, cx);
2864 });
2865
2866 cx.deactivate_window();
2867
2868 active_thread(&conversation_view, cx)
2869 .update_in(cx, |view, window, cx| view.send(window, cx));
2870
2871 cx.run_until_parked();
2872
2873 assert!(
2874 cx.windows()
2875 .iter()
2876 .any(|window| window.downcast::<AgentNotification>().is_some())
2877 );
2878 }
2879
2880 #[gpui::test]
2881 async fn test_recent_history_refreshes_when_history_cache_updated(cx: &mut TestAppContext) {
2882 init_test(cx);
2883
2884 let session_a = AgentSessionInfo::new(SessionId::new("session-a"));
2885 let session_b = AgentSessionInfo::new(SessionId::new("session-b"));
2886
2887 // Use a connection that provides a session list so ThreadHistory is created
2888 let (conversation_view, history, cx) = setup_thread_view_with_history(
2889 StubAgentServer::new(SessionHistoryConnection::new(vec![session_a.clone()])),
2890 cx,
2891 )
2892 .await;
2893
2894 // Initially has session_a from the connection's session list
2895 active_thread(&conversation_view, cx).read_with(cx, |view, _cx| {
2896 assert_eq!(view.recent_history_entries.len(), 1);
2897 assert_eq!(
2898 view.recent_history_entries[0].session_id,
2899 session_a.session_id
2900 );
2901 });
2902
2903 // Swap to a different session list
2904 let list_b: Rc<dyn AgentSessionList> =
2905 Rc::new(StubSessionList::new(vec![session_b.clone()]));
2906 history.update(cx, |history, cx| {
2907 history.set_session_list(list_b, cx);
2908 });
2909 cx.run_until_parked();
2910
2911 active_thread(&conversation_view, cx).read_with(cx, |view, _cx| {
2912 assert_eq!(view.recent_history_entries.len(), 1);
2913 assert_eq!(
2914 view.recent_history_entries[0].session_id,
2915 session_b.session_id
2916 );
2917 });
2918 }
2919
2920 #[gpui::test]
2921 async fn test_new_thread_creation_triggers_session_list_refresh(cx: &mut TestAppContext) {
2922 init_test(cx);
2923
2924 let session = AgentSessionInfo::new(SessionId::new("history-session"));
2925 let (conversation_view, _history, cx) = setup_thread_view_with_history(
2926 StubAgentServer::new(SessionHistoryConnection::new(vec![session.clone()])),
2927 cx,
2928 )
2929 .await;
2930
2931 active_thread(&conversation_view, cx).read_with(cx, |view, _cx| {
2932 assert_eq!(view.recent_history_entries.len(), 1);
2933 assert_eq!(
2934 view.recent_history_entries[0].session_id,
2935 session.session_id
2936 );
2937 });
2938 }
2939
2940 #[gpui::test]
2941 async fn test_resume_without_history_adds_notice(cx: &mut TestAppContext) {
2942 init_test(cx);
2943
2944 let fs = FakeFs::new(cx.executor());
2945 let project = Project::test(fs, [], cx).await;
2946 let (multi_workspace, cx) =
2947 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2948 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2949
2950 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
2951 let connection_store =
2952 cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
2953
2954 let conversation_view = cx.update(|window, cx| {
2955 cx.new(|cx| {
2956 ConversationView::new(
2957 Rc::new(StubAgentServer::new(ResumeOnlyAgentConnection)),
2958 connection_store,
2959 Agent::Custom { id: "Test".into() },
2960 Some(SessionId::new("resume-session")),
2961 None,
2962 None,
2963 None,
2964 workspace.downgrade(),
2965 project,
2966 Some(thread_store),
2967 None,
2968 window,
2969 cx,
2970 )
2971 })
2972 });
2973
2974 cx.run_until_parked();
2975
2976 conversation_view.read_with(cx, |view, cx| {
2977 let state = view.active_thread().unwrap();
2978 assert!(state.read(cx).resumed_without_history);
2979 assert_eq!(state.read(cx).list_state.item_count(), 0);
2980 });
2981 }
2982
2983 #[derive(Clone)]
2984 struct RestoredAvailableCommandsConnection;
2985
2986 impl AgentConnection for RestoredAvailableCommandsConnection {
2987 fn agent_id(&self) -> AgentId {
2988 AgentId::new("restored-available-commands")
2989 }
2990
2991 fn telemetry_id(&self) -> SharedString {
2992 "restored-available-commands".into()
2993 }
2994
2995 fn new_session(
2996 self: Rc<Self>,
2997 project: Entity<Project>,
2998 _work_dirs: PathList,
2999 cx: &mut App,
3000 ) -> Task<gpui::Result<Entity<AcpThread>>> {
3001 let thread = build_test_thread(
3002 self,
3003 project,
3004 "RestoredAvailableCommandsConnection",
3005 SessionId::new("new-session"),
3006 cx,
3007 );
3008 Task::ready(Ok(thread))
3009 }
3010
3011 fn supports_load_session(&self) -> bool {
3012 true
3013 }
3014
3015 fn load_session(
3016 self: Rc<Self>,
3017 session_id: acp::SessionId,
3018 project: Entity<Project>,
3019 _work_dirs: PathList,
3020 _title: Option<SharedString>,
3021 cx: &mut App,
3022 ) -> Task<gpui::Result<Entity<AcpThread>>> {
3023 let thread = build_test_thread(
3024 self,
3025 project,
3026 "RestoredAvailableCommandsConnection",
3027 session_id,
3028 cx,
3029 );
3030
3031 thread
3032 .update(cx, |thread, cx| {
3033 thread.handle_session_update(
3034 acp::SessionUpdate::AvailableCommandsUpdate(
3035 acp::AvailableCommandsUpdate::new(vec![acp::AvailableCommand::new(
3036 "help", "Get help",
3037 )]),
3038 ),
3039 cx,
3040 )
3041 })
3042 .expect("available commands update should succeed");
3043
3044 Task::ready(Ok(thread))
3045 }
3046
3047 fn auth_methods(&self) -> &[acp::AuthMethod] {
3048 &[]
3049 }
3050
3051 fn authenticate(
3052 &self,
3053 _method_id: acp::AuthMethodId,
3054 _cx: &mut App,
3055 ) -> Task<gpui::Result<()>> {
3056 Task::ready(Ok(()))
3057 }
3058
3059 fn prompt(
3060 &self,
3061 _id: Option<acp_thread::UserMessageId>,
3062 _params: acp::PromptRequest,
3063 _cx: &mut App,
3064 ) -> Task<gpui::Result<acp::PromptResponse>> {
3065 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
3066 }
3067
3068 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
3069
3070 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3071 self
3072 }
3073 }
3074
3075 #[gpui::test]
3076 async fn test_restored_threads_keep_available_commands(cx: &mut TestAppContext) {
3077 init_test(cx);
3078
3079 let fs = FakeFs::new(cx.executor());
3080 let project = Project::test(fs, [], cx).await;
3081 let (multi_workspace, cx) =
3082 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3083 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3084
3085 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3086 let connection_store =
3087 cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
3088
3089 let conversation_view = cx.update(|window, cx| {
3090 cx.new(|cx| {
3091 ConversationView::new(
3092 Rc::new(StubAgentServer::new(RestoredAvailableCommandsConnection)),
3093 connection_store,
3094 Agent::Custom { id: "Test".into() },
3095 Some(SessionId::new("restored-session")),
3096 None,
3097 None,
3098 None,
3099 workspace.downgrade(),
3100 project,
3101 Some(thread_store),
3102 None,
3103 window,
3104 cx,
3105 )
3106 })
3107 });
3108
3109 cx.run_until_parked();
3110
3111 let message_editor = message_editor(&conversation_view, cx);
3112 let editor =
3113 message_editor.update(cx, |message_editor, _cx| message_editor.editor().clone());
3114 let placeholder = editor.update(cx, |editor, cx| editor.placeholder_text(cx));
3115
3116 active_thread(&conversation_view, cx).read_with(cx, |view, _cx| {
3117 let available_commands = view
3118 .session_capabilities
3119 .read()
3120 .available_commands()
3121 .to_vec();
3122 assert_eq!(available_commands.len(), 1);
3123 assert_eq!(available_commands[0].name.as_str(), "help");
3124 assert_eq!(available_commands[0].description.as_str(), "Get help");
3125 });
3126
3127 assert_eq!(
3128 placeholder,
3129 Some("Message Test — @ to include context, / for commands".to_string())
3130 );
3131
3132 message_editor.update_in(cx, |editor, window, cx| {
3133 editor.set_text("/help", window, cx);
3134 });
3135
3136 let contents_result = message_editor
3137 .update(cx, |editor, cx| editor.contents(false, cx))
3138 .await;
3139
3140 assert!(contents_result.is_ok());
3141 }
3142
3143 #[gpui::test]
3144 async fn test_resume_thread_uses_session_cwd_when_inside_project(cx: &mut TestAppContext) {
3145 init_test(cx);
3146
3147 let fs = FakeFs::new(cx.executor());
3148 fs.insert_tree(
3149 "/project",
3150 json!({
3151 "subdir": {
3152 "file.txt": "hello"
3153 }
3154 }),
3155 )
3156 .await;
3157 let project = Project::test(fs, [Path::new("/project")], cx).await;
3158 let (multi_workspace, cx) =
3159 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3160 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3161
3162 let connection = CwdCapturingConnection::new();
3163 let captured_cwd = connection.captured_work_dirs.clone();
3164
3165 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3166 let connection_store =
3167 cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
3168
3169 let _conversation_view = cx.update(|window, cx| {
3170 cx.new(|cx| {
3171 ConversationView::new(
3172 Rc::new(StubAgentServer::new(connection)),
3173 connection_store,
3174 Agent::Custom { id: "Test".into() },
3175 Some(SessionId::new("session-1")),
3176 Some(PathList::new(&[PathBuf::from("/project/subdir")])),
3177 None,
3178 None,
3179 workspace.downgrade(),
3180 project,
3181 Some(thread_store),
3182 None,
3183 window,
3184 cx,
3185 )
3186 })
3187 });
3188
3189 cx.run_until_parked();
3190
3191 assert_eq!(
3192 captured_cwd.lock().as_ref().unwrap(),
3193 &PathList::new(&[Path::new("/project/subdir")]),
3194 "Should use session cwd when it's inside the project"
3195 );
3196 }
3197
3198 #[gpui::test]
3199 async fn test_refusal_handling(cx: &mut TestAppContext) {
3200 init_test(cx);
3201
3202 let (conversation_view, cx) =
3203 setup_conversation_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
3204
3205 let message_editor = message_editor(&conversation_view, cx);
3206 message_editor.update_in(cx, |editor, window, cx| {
3207 editor.set_text("Do something harmful", window, cx);
3208 });
3209
3210 active_thread(&conversation_view, cx)
3211 .update_in(cx, |view, window, cx| view.send(window, cx));
3212
3213 cx.run_until_parked();
3214
3215 // Check that the refusal error is set
3216 conversation_view.read_with(cx, |thread_view, cx| {
3217 let state = thread_view.active_thread().unwrap();
3218 assert!(
3219 matches!(state.read(cx).thread_error, Some(ThreadError::Refusal)),
3220 "Expected refusal error to be set"
3221 );
3222 });
3223 }
3224
3225 #[gpui::test]
3226 async fn test_connect_failure_transitions_to_load_error(cx: &mut TestAppContext) {
3227 init_test(cx);
3228
3229 let (conversation_view, cx) = setup_conversation_view(FailingAgentServer, cx).await;
3230
3231 conversation_view.read_with(cx, |view, cx| {
3232 let title = view.title(cx);
3233 assert_eq!(
3234 title.as_ref(),
3235 "Error Loading Codex CLI",
3236 "Tab title should show the agent name with an error prefix"
3237 );
3238 match &view.server_state {
3239 ServerState::LoadError {
3240 error: LoadError::Other(msg),
3241 ..
3242 } => {
3243 assert!(
3244 msg.contains("Invalid gzip header"),
3245 "Error callout should contain the underlying extraction error, got: {msg}"
3246 );
3247 }
3248 other => panic!(
3249 "Expected LoadError::Other, got: {}",
3250 match other {
3251 ServerState::Loading(_) => "Loading (stuck!)",
3252 ServerState::LoadError { .. } => "LoadError (wrong variant)",
3253 ServerState::Connected(_) => "Connected",
3254 }
3255 ),
3256 }
3257 });
3258 }
3259
3260 #[gpui::test]
3261 async fn test_auth_required_on_initial_connect(cx: &mut TestAppContext) {
3262 init_test(cx);
3263
3264 let connection = AuthGatedAgentConnection::new();
3265 let (conversation_view, cx) =
3266 setup_conversation_view(StubAgentServer::new(connection), cx).await;
3267
3268 // When new_session returns AuthRequired, the server should transition
3269 // to Connected + Unauthenticated rather than getting stuck in Loading.
3270 conversation_view.read_with(cx, |view, _cx| {
3271 let connected = view
3272 .as_connected()
3273 .expect("Should be in Connected state even though auth is required");
3274 assert!(
3275 !connected.auth_state.is_ok(),
3276 "Auth state should be Unauthenticated"
3277 );
3278 assert!(
3279 connected.active_id.is_none(),
3280 "There should be no active thread since no session was created"
3281 );
3282 assert!(
3283 connected.threads.is_empty(),
3284 "There should be no threads since no session was created"
3285 );
3286 });
3287
3288 conversation_view.read_with(cx, |view, _cx| {
3289 assert!(
3290 view.active_thread().is_none(),
3291 "active_thread() should be None when unauthenticated without a session"
3292 );
3293 });
3294
3295 // Authenticate using the real authenticate flow on ConnectionView.
3296 // This calls connection.authenticate(), which flips the internal flag,
3297 // then on success triggers reset() -> new_session() which now succeeds.
3298 conversation_view.update_in(cx, |view, window, cx| {
3299 view.authenticate(
3300 acp::AuthMethodId::new(AuthGatedAgentConnection::AUTH_METHOD_ID),
3301 window,
3302 cx,
3303 );
3304 });
3305 cx.run_until_parked();
3306
3307 // After auth, the server should have an active thread in the Ok state.
3308 conversation_view.read_with(cx, |view, cx| {
3309 let connected = view
3310 .as_connected()
3311 .expect("Should still be in Connected state after auth");
3312 assert!(connected.auth_state.is_ok(), "Auth state should be Ok");
3313 assert!(
3314 connected.active_id.is_some(),
3315 "There should be an active thread after successful auth"
3316 );
3317 assert_eq!(
3318 connected.threads.len(),
3319 1,
3320 "There should be exactly one thread"
3321 );
3322
3323 let active = view
3324 .active_thread()
3325 .expect("active_thread() should return the new thread");
3326 assert!(
3327 active.read(cx).thread_error.is_none(),
3328 "The new thread should have no errors"
3329 );
3330 });
3331 }
3332
3333 #[gpui::test]
3334 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
3335 init_test(cx);
3336
3337 let tool_call_id = acp::ToolCallId::new("1");
3338 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Label")
3339 .kind(acp::ToolKind::Edit)
3340 .content(vec!["hi".into()]);
3341 let connection =
3342 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
3343 tool_call_id,
3344 PermissionOptions::Flat(vec![acp::PermissionOption::new(
3345 "1",
3346 "Allow",
3347 acp::PermissionOptionKind::AllowOnce,
3348 )]),
3349 )]));
3350
3351 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
3352
3353 let (conversation_view, cx) =
3354 setup_conversation_view(StubAgentServer::new(connection), cx).await;
3355
3356 let message_editor = message_editor(&conversation_view, cx);
3357 message_editor.update_in(cx, |editor, window, cx| {
3358 editor.set_text("Hello", window, cx);
3359 });
3360
3361 cx.deactivate_window();
3362
3363 active_thread(&conversation_view, cx)
3364 .update_in(cx, |view, window, cx| view.send(window, cx));
3365
3366 cx.run_until_parked();
3367
3368 assert!(
3369 cx.windows()
3370 .iter()
3371 .any(|window| window.downcast::<AgentNotification>().is_some())
3372 );
3373 }
3374
3375 #[gpui::test]
3376 async fn test_notification_when_panel_hidden(cx: &mut TestAppContext) {
3377 init_test(cx);
3378
3379 let (conversation_view, cx) =
3380 setup_conversation_view(StubAgentServer::default_response(), cx).await;
3381
3382 add_to_workspace(conversation_view.clone(), cx);
3383
3384 let message_editor = message_editor(&conversation_view, cx);
3385
3386 message_editor.update_in(cx, |editor, window, cx| {
3387 editor.set_text("Hello", window, cx);
3388 });
3389
3390 // Window is active (don't deactivate), but panel will be hidden
3391 // Note: In the test environment, the panel is not actually added to the dock,
3392 // so is_agent_panel_hidden will return true
3393
3394 active_thread(&conversation_view, cx)
3395 .update_in(cx, |view, window, cx| view.send(window, cx));
3396
3397 cx.run_until_parked();
3398
3399 // Should show notification because window is active but panel is hidden
3400 assert!(
3401 cx.windows()
3402 .iter()
3403 .any(|window| window.downcast::<AgentNotification>().is_some()),
3404 "Expected notification when panel is hidden"
3405 );
3406 }
3407
3408 #[gpui::test]
3409 async fn test_notification_still_works_when_window_inactive(cx: &mut TestAppContext) {
3410 init_test(cx);
3411
3412 let (conversation_view, cx) =
3413 setup_conversation_view(StubAgentServer::default_response(), cx).await;
3414
3415 let message_editor = message_editor(&conversation_view, cx);
3416 message_editor.update_in(cx, |editor, window, cx| {
3417 editor.set_text("Hello", window, cx);
3418 });
3419
3420 // Deactivate window - should show notification regardless of setting
3421 cx.deactivate_window();
3422
3423 active_thread(&conversation_view, cx)
3424 .update_in(cx, |view, window, cx| view.send(window, cx));
3425
3426 cx.run_until_parked();
3427
3428 // Should still show notification when window is inactive (existing behavior)
3429 assert!(
3430 cx.windows()
3431 .iter()
3432 .any(|window| window.downcast::<AgentNotification>().is_some()),
3433 "Expected notification when window is inactive"
3434 );
3435 }
3436
3437 #[gpui::test]
3438 async fn test_notification_when_workspace_is_background_in_multi_workspace(
3439 cx: &mut TestAppContext,
3440 ) {
3441 init_test(cx);
3442
3443 // Enable multi-workspace feature flag and init globals needed by AgentPanel
3444 let fs = FakeFs::new(cx.executor());
3445
3446 cx.update(|cx| {
3447 agent::ThreadStore::init_global(cx);
3448 language_model::LanguageModelRegistry::test(cx);
3449 <dyn Fs>::set_global(fs.clone(), cx);
3450 });
3451
3452 let project1 = Project::test(fs.clone(), [], cx).await;
3453
3454 // Create a MultiWorkspace window with one workspace
3455 let multi_workspace_handle =
3456 cx.add_window(|window, cx| MultiWorkspace::test_new(project1.clone(), window, cx));
3457
3458 // Get workspace 1 (the initial workspace)
3459 let workspace1 = multi_workspace_handle
3460 .read_with(cx, |mw, _cx| mw.workspace().clone())
3461 .unwrap();
3462
3463 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
3464
3465 workspace1.update_in(cx, |workspace, window, cx| {
3466 let panel = cx.new(|cx| crate::AgentPanel::new(workspace, None, window, cx));
3467 workspace.add_panel(panel, window, cx);
3468
3469 // Open the dock and activate the agent panel so it's visible
3470 workspace.focus_panel::<crate::AgentPanel>(window, cx);
3471 });
3472
3473 cx.run_until_parked();
3474
3475 cx.read(|cx| {
3476 assert!(
3477 crate::AgentPanel::is_visible(&workspace1, cx),
3478 "AgentPanel should be visible in workspace1's dock"
3479 );
3480 });
3481
3482 // Set up thread view in workspace 1
3483 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3484 let connection_store =
3485 cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project1.clone(), cx)));
3486
3487 let agent = StubAgentServer::default_response();
3488 let conversation_view = cx.update(|window, cx| {
3489 cx.new(|cx| {
3490 ConversationView::new(
3491 Rc::new(agent),
3492 connection_store,
3493 Agent::Custom { id: "Test".into() },
3494 None,
3495 None,
3496 None,
3497 None,
3498 workspace1.downgrade(),
3499 project1.clone(),
3500 Some(thread_store),
3501 None,
3502 window,
3503 cx,
3504 )
3505 })
3506 });
3507 cx.run_until_parked();
3508
3509 let message_editor = message_editor(&conversation_view, cx);
3510 message_editor.update_in(cx, |editor, window, cx| {
3511 editor.set_text("Hello", window, cx);
3512 });
3513
3514 // Create a second workspace and switch to it.
3515 // This makes workspace1 the "background" workspace.
3516 let project2 = Project::test(fs, [], cx).await;
3517 multi_workspace_handle
3518 .update(cx, |mw, window, cx| {
3519 mw.test_add_workspace(project2, window, cx);
3520 })
3521 .unwrap();
3522
3523 cx.run_until_parked();
3524
3525 // Verify workspace1 is no longer the active workspace
3526 multi_workspace_handle
3527 .read_with(cx, |mw, _cx| {
3528 assert_ne!(mw.workspace(), &workspace1);
3529 })
3530 .unwrap();
3531
3532 // Window is active, agent panel is visible in workspace1, but workspace1
3533 // is in the background. The notification should show because the user
3534 // can't actually see the agent panel.
3535 active_thread(&conversation_view, cx)
3536 .update_in(cx, |view, window, cx| view.send(window, cx));
3537
3538 cx.run_until_parked();
3539
3540 assert!(
3541 cx.windows()
3542 .iter()
3543 .any(|window| window.downcast::<AgentNotification>().is_some()),
3544 "Expected notification when workspace is in background within MultiWorkspace"
3545 );
3546
3547 // Also verify: clicking "View Panel" should switch to workspace1.
3548 cx.windows()
3549 .iter()
3550 .find_map(|window| window.downcast::<AgentNotification>())
3551 .unwrap()
3552 .update(cx, |window, _, cx| window.accept(cx))
3553 .unwrap();
3554
3555 cx.run_until_parked();
3556
3557 multi_workspace_handle
3558 .read_with(cx, |mw, _cx| {
3559 assert_eq!(
3560 mw.workspace(),
3561 &workspace1,
3562 "Expected workspace1 to become the active workspace after accepting notification"
3563 );
3564 })
3565 .unwrap();
3566 }
3567
3568 #[gpui::test]
3569 async fn test_notification_respects_never_setting(cx: &mut TestAppContext) {
3570 init_test(cx);
3571
3572 // Set notify_when_agent_waiting to Never
3573 cx.update(|cx| {
3574 AgentSettings::override_global(
3575 AgentSettings {
3576 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
3577 ..AgentSettings::get_global(cx).clone()
3578 },
3579 cx,
3580 );
3581 });
3582
3583 let (conversation_view, cx) =
3584 setup_conversation_view(StubAgentServer::default_response(), cx).await;
3585
3586 let message_editor = message_editor(&conversation_view, cx);
3587 message_editor.update_in(cx, |editor, window, cx| {
3588 editor.set_text("Hello", window, cx);
3589 });
3590
3591 // Window is active
3592
3593 active_thread(&conversation_view, cx)
3594 .update_in(cx, |view, window, cx| view.send(window, cx));
3595
3596 cx.run_until_parked();
3597
3598 // Should NOT show notification because notify_when_agent_waiting is Never
3599 assert!(
3600 !cx.windows()
3601 .iter()
3602 .any(|window| window.downcast::<AgentNotification>().is_some()),
3603 "Expected no notification when notify_when_agent_waiting is Never"
3604 );
3605 }
3606
3607 #[gpui::test]
3608 async fn test_notification_closed_when_thread_view_dropped(cx: &mut TestAppContext) {
3609 init_test(cx);
3610
3611 let (conversation_view, cx) =
3612 setup_conversation_view(StubAgentServer::default_response(), cx).await;
3613
3614 let weak_view = conversation_view.downgrade();
3615
3616 let message_editor = message_editor(&conversation_view, cx);
3617 message_editor.update_in(cx, |editor, window, cx| {
3618 editor.set_text("Hello", window, cx);
3619 });
3620
3621 cx.deactivate_window();
3622
3623 active_thread(&conversation_view, cx)
3624 .update_in(cx, |view, window, cx| view.send(window, cx));
3625
3626 cx.run_until_parked();
3627
3628 // Verify notification is shown
3629 assert!(
3630 cx.windows()
3631 .iter()
3632 .any(|window| window.downcast::<AgentNotification>().is_some()),
3633 "Expected notification to be shown"
3634 );
3635
3636 // Drop the thread view (simulating navigation to a new thread)
3637 drop(conversation_view);
3638 drop(message_editor);
3639 // Trigger an update to flush effects, which will call release_dropped_entities
3640 cx.update(|_window, _cx| {});
3641 cx.run_until_parked();
3642
3643 // Verify the entity was actually released
3644 assert!(
3645 !weak_view.is_upgradable(),
3646 "Thread view entity should be released after dropping"
3647 );
3648
3649 // The notification should be automatically closed via on_release
3650 assert!(
3651 !cx.windows()
3652 .iter()
3653 .any(|window| window.downcast::<AgentNotification>().is_some()),
3654 "Notification should be closed when thread view is dropped"
3655 );
3656 }
3657
3658 async fn setup_conversation_view(
3659 agent: impl AgentServer + 'static,
3660 cx: &mut TestAppContext,
3661 ) -> (Entity<ConversationView>, &mut VisualTestContext) {
3662 let (conversation_view, _history, cx) =
3663 setup_conversation_view_with_history_and_initial_content(agent, None, cx).await;
3664 (conversation_view, cx)
3665 }
3666
3667 async fn setup_thread_view_with_history(
3668 agent: impl AgentServer + 'static,
3669 cx: &mut TestAppContext,
3670 ) -> (
3671 Entity<ConversationView>,
3672 Entity<ThreadHistory>,
3673 &mut VisualTestContext,
3674 ) {
3675 let (conversation_view, history, cx) =
3676 setup_conversation_view_with_history_and_initial_content(agent, None, cx).await;
3677 (conversation_view, history.expect("Missing history"), cx)
3678 }
3679
3680 async fn setup_conversation_view_with_initial_content(
3681 agent: impl AgentServer + 'static,
3682 initial_content: AgentInitialContent,
3683 cx: &mut TestAppContext,
3684 ) -> (Entity<ConversationView>, &mut VisualTestContext) {
3685 let (conversation_view, _history, cx) =
3686 setup_conversation_view_with_history_and_initial_content(
3687 agent,
3688 Some(initial_content),
3689 cx,
3690 )
3691 .await;
3692 (conversation_view, cx)
3693 }
3694
3695 async fn setup_conversation_view_with_history_and_initial_content(
3696 agent: impl AgentServer + 'static,
3697 initial_content: Option<AgentInitialContent>,
3698 cx: &mut TestAppContext,
3699 ) -> (
3700 Entity<ConversationView>,
3701 Option<Entity<ThreadHistory>>,
3702 &mut VisualTestContext,
3703 ) {
3704 let fs = FakeFs::new(cx.executor());
3705 let project = Project::test(fs, [], cx).await;
3706 let (multi_workspace, cx) =
3707 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3708 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
3709
3710 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
3711 let connection_store =
3712 cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
3713
3714 let agent_key = Agent::Custom { id: "Test".into() };
3715
3716 let conversation_view = cx.update(|window, cx| {
3717 cx.new(|cx| {
3718 ConversationView::new(
3719 Rc::new(agent),
3720 connection_store.clone(),
3721 agent_key.clone(),
3722 None,
3723 None,
3724 None,
3725 initial_content,
3726 workspace.downgrade(),
3727 project,
3728 Some(thread_store),
3729 None,
3730 window,
3731 cx,
3732 )
3733 })
3734 });
3735 cx.run_until_parked();
3736
3737 let history = cx.update(|_window, cx| {
3738 connection_store
3739 .read(cx)
3740 .entry(&agent_key)
3741 .and_then(|e| e.read(cx).history().cloned())
3742 });
3743
3744 (conversation_view, history, cx)
3745 }
3746
3747 fn add_to_workspace(conversation_view: Entity<ConversationView>, cx: &mut VisualTestContext) {
3748 let workspace =
3749 conversation_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
3750
3751 workspace
3752 .update_in(cx, |workspace, window, cx| {
3753 workspace.add_item_to_active_pane(
3754 Box::new(cx.new(|_| ThreadViewItem(conversation_view.clone()))),
3755 None,
3756 true,
3757 window,
3758 cx,
3759 );
3760 })
3761 .unwrap();
3762 }
3763
3764 struct ThreadViewItem(Entity<ConversationView>);
3765
3766 impl Item for ThreadViewItem {
3767 type Event = ();
3768
3769 fn include_in_nav_history() -> bool {
3770 false
3771 }
3772
3773 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
3774 "Test".into()
3775 }
3776 }
3777
3778 impl EventEmitter<()> for ThreadViewItem {}
3779
3780 impl Focusable for ThreadViewItem {
3781 fn focus_handle(&self, cx: &App) -> FocusHandle {
3782 self.0.read(cx).focus_handle(cx)
3783 }
3784 }
3785
3786 impl Render for ThreadViewItem {
3787 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3788 // Render the title editor in the element tree too. In the real app
3789 // it is part of the agent panel
3790 let title_editor = self
3791 .0
3792 .read(cx)
3793 .active_thread()
3794 .map(|t| t.read(cx).title_editor.clone());
3795
3796 v_flex().children(title_editor).child(self.0.clone())
3797 }
3798 }
3799
3800 pub(crate) struct StubAgentServer<C> {
3801 connection: C,
3802 }
3803
3804 impl<C> StubAgentServer<C> {
3805 pub(crate) fn new(connection: C) -> Self {
3806 Self { connection }
3807 }
3808 }
3809
3810 impl StubAgentServer<StubAgentConnection> {
3811 pub(crate) fn default_response() -> Self {
3812 let conn = StubAgentConnection::new();
3813 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
3814 acp::ContentChunk::new("Default response".into()),
3815 )]);
3816 Self::new(conn)
3817 }
3818 }
3819
3820 impl<C> AgentServer for StubAgentServer<C>
3821 where
3822 C: 'static + AgentConnection + Send + Clone,
3823 {
3824 fn logo(&self) -> ui::IconName {
3825 ui::IconName::ZedAgent
3826 }
3827
3828 fn agent_id(&self) -> AgentId {
3829 "Test".into()
3830 }
3831
3832 fn connect(
3833 &self,
3834 _delegate: AgentServerDelegate,
3835 _project: Entity<Project>,
3836 _cx: &mut App,
3837 ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
3838 Task::ready(Ok(Rc::new(self.connection.clone())))
3839 }
3840
3841 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3842 self
3843 }
3844 }
3845
3846 struct FailingAgentServer;
3847
3848 impl AgentServer for FailingAgentServer {
3849 fn logo(&self) -> ui::IconName {
3850 ui::IconName::AiOpenAi
3851 }
3852
3853 fn agent_id(&self) -> AgentId {
3854 AgentId::new("Codex CLI")
3855 }
3856
3857 fn connect(
3858 &self,
3859 _delegate: AgentServerDelegate,
3860 _project: Entity<Project>,
3861 _cx: &mut App,
3862 ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
3863 Task::ready(Err(anyhow!(
3864 "extracting downloaded asset for \
3865 https://github.com/zed-industries/codex-acp/releases/download/v0.9.4/\
3866 codex-acp-0.9.4-aarch64-pc-windows-msvc.zip: \
3867 failed to iterate over archive: Invalid gzip header"
3868 )))
3869 }
3870
3871 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3872 self
3873 }
3874 }
3875
3876 #[derive(Clone)]
3877 struct StubSessionList {
3878 sessions: Vec<AgentSessionInfo>,
3879 }
3880
3881 impl StubSessionList {
3882 fn new(sessions: Vec<AgentSessionInfo>) -> Self {
3883 Self { sessions }
3884 }
3885 }
3886
3887 impl AgentSessionList for StubSessionList {
3888 fn list_sessions(
3889 &self,
3890 _request: AgentSessionListRequest,
3891 _cx: &mut App,
3892 ) -> Task<anyhow::Result<AgentSessionListResponse>> {
3893 Task::ready(Ok(AgentSessionListResponse::new(self.sessions.clone())))
3894 }
3895
3896 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3897 self
3898 }
3899 }
3900
3901 #[derive(Clone)]
3902 struct SessionHistoryConnection {
3903 sessions: Vec<AgentSessionInfo>,
3904 }
3905
3906 impl SessionHistoryConnection {
3907 fn new(sessions: Vec<AgentSessionInfo>) -> Self {
3908 Self { sessions }
3909 }
3910 }
3911
3912 fn build_test_thread(
3913 connection: Rc<dyn AgentConnection>,
3914 project: Entity<Project>,
3915 name: &'static str,
3916 session_id: SessionId,
3917 cx: &mut App,
3918 ) -> Entity<AcpThread> {
3919 let action_log = cx.new(|_| ActionLog::new(project.clone()));
3920 cx.new(|cx| {
3921 AcpThread::new(
3922 None,
3923 Some(name.into()),
3924 None,
3925 connection,
3926 project,
3927 action_log,
3928 session_id,
3929 watch::Receiver::constant(
3930 acp::PromptCapabilities::new()
3931 .image(true)
3932 .audio(true)
3933 .embedded_context(true),
3934 ),
3935 cx,
3936 )
3937 })
3938 }
3939
3940 impl AgentConnection for SessionHistoryConnection {
3941 fn agent_id(&self) -> AgentId {
3942 AgentId::new("history-connection")
3943 }
3944
3945 fn telemetry_id(&self) -> SharedString {
3946 "history-connection".into()
3947 }
3948
3949 fn new_session(
3950 self: Rc<Self>,
3951 project: Entity<Project>,
3952 _work_dirs: PathList,
3953 cx: &mut App,
3954 ) -> Task<anyhow::Result<Entity<AcpThread>>> {
3955 let thread = build_test_thread(
3956 self,
3957 project,
3958 "SessionHistoryConnection",
3959 SessionId::new("history-session"),
3960 cx,
3961 );
3962 Task::ready(Ok(thread))
3963 }
3964
3965 fn supports_load_session(&self) -> bool {
3966 true
3967 }
3968
3969 fn session_list(&self, _cx: &mut App) -> Option<Rc<dyn AgentSessionList>> {
3970 Some(Rc::new(StubSessionList::new(self.sessions.clone())))
3971 }
3972
3973 fn auth_methods(&self) -> &[acp::AuthMethod] {
3974 &[]
3975 }
3976
3977 fn authenticate(
3978 &self,
3979 _method_id: acp::AuthMethodId,
3980 _cx: &mut App,
3981 ) -> Task<anyhow::Result<()>> {
3982 Task::ready(Ok(()))
3983 }
3984
3985 fn prompt(
3986 &self,
3987 _id: Option<acp_thread::UserMessageId>,
3988 _params: acp::PromptRequest,
3989 _cx: &mut App,
3990 ) -> Task<anyhow::Result<acp::PromptResponse>> {
3991 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
3992 }
3993
3994 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
3995
3996 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3997 self
3998 }
3999 }
4000
4001 #[derive(Clone)]
4002 struct ResumeOnlyAgentConnection;
4003
4004 impl AgentConnection for ResumeOnlyAgentConnection {
4005 fn agent_id(&self) -> AgentId {
4006 AgentId::new("resume-only")
4007 }
4008
4009 fn telemetry_id(&self) -> SharedString {
4010 "resume-only".into()
4011 }
4012
4013 fn new_session(
4014 self: Rc<Self>,
4015 project: Entity<Project>,
4016 _work_dirs: PathList,
4017 cx: &mut gpui::App,
4018 ) -> Task<gpui::Result<Entity<AcpThread>>> {
4019 let thread = build_test_thread(
4020 self,
4021 project,
4022 "ResumeOnlyAgentConnection",
4023 SessionId::new("new-session"),
4024 cx,
4025 );
4026 Task::ready(Ok(thread))
4027 }
4028
4029 fn supports_resume_session(&self) -> bool {
4030 true
4031 }
4032
4033 fn resume_session(
4034 self: Rc<Self>,
4035 session_id: acp::SessionId,
4036 project: Entity<Project>,
4037 _work_dirs: PathList,
4038 _title: Option<SharedString>,
4039 cx: &mut App,
4040 ) -> Task<gpui::Result<Entity<AcpThread>>> {
4041 let thread =
4042 build_test_thread(self, project, "ResumeOnlyAgentConnection", session_id, cx);
4043 Task::ready(Ok(thread))
4044 }
4045
4046 fn auth_methods(&self) -> &[acp::AuthMethod] {
4047 &[]
4048 }
4049
4050 fn authenticate(
4051 &self,
4052 _method_id: acp::AuthMethodId,
4053 _cx: &mut App,
4054 ) -> Task<gpui::Result<()>> {
4055 Task::ready(Ok(()))
4056 }
4057
4058 fn prompt(
4059 &self,
4060 _id: Option<acp_thread::UserMessageId>,
4061 _params: acp::PromptRequest,
4062 _cx: &mut App,
4063 ) -> Task<gpui::Result<acp::PromptResponse>> {
4064 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
4065 }
4066
4067 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
4068
4069 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4070 self
4071 }
4072 }
4073
4074 /// Simulates an agent that requires authentication before a session can be
4075 /// created. `new_session` returns `AuthRequired` until `authenticate` is
4076 /// called with the correct method, after which sessions are created normally.
4077 #[derive(Clone)]
4078 struct AuthGatedAgentConnection {
4079 authenticated: Arc<Mutex<bool>>,
4080 auth_method: acp::AuthMethod,
4081 }
4082
4083 impl AuthGatedAgentConnection {
4084 const AUTH_METHOD_ID: &str = "test-login";
4085
4086 fn new() -> Self {
4087 Self {
4088 authenticated: Arc::new(Mutex::new(false)),
4089 auth_method: acp::AuthMethod::Agent(acp::AuthMethodAgent::new(
4090 Self::AUTH_METHOD_ID,
4091 "Test Login",
4092 )),
4093 }
4094 }
4095 }
4096
4097 impl AgentConnection for AuthGatedAgentConnection {
4098 fn agent_id(&self) -> AgentId {
4099 AgentId::new("auth-gated")
4100 }
4101
4102 fn telemetry_id(&self) -> SharedString {
4103 "auth-gated".into()
4104 }
4105
4106 fn new_session(
4107 self: Rc<Self>,
4108 project: Entity<Project>,
4109 work_dirs: PathList,
4110 cx: &mut gpui::App,
4111 ) -> Task<gpui::Result<Entity<AcpThread>>> {
4112 if !*self.authenticated.lock() {
4113 return Task::ready(Err(acp_thread::AuthRequired::new()
4114 .with_description("Sign in to continue".to_string())
4115 .into()));
4116 }
4117
4118 let session_id = acp::SessionId::new("auth-gated-session");
4119 let action_log = cx.new(|_| ActionLog::new(project.clone()));
4120 Task::ready(Ok(cx.new(|cx| {
4121 AcpThread::new(
4122 None,
4123 None,
4124 Some(work_dirs),
4125 self,
4126 project,
4127 action_log,
4128 session_id,
4129 watch::Receiver::constant(
4130 acp::PromptCapabilities::new()
4131 .image(true)
4132 .audio(true)
4133 .embedded_context(true),
4134 ),
4135 cx,
4136 )
4137 })))
4138 }
4139
4140 fn auth_methods(&self) -> &[acp::AuthMethod] {
4141 std::slice::from_ref(&self.auth_method)
4142 }
4143
4144 fn authenticate(
4145 &self,
4146 method_id: acp::AuthMethodId,
4147 _cx: &mut App,
4148 ) -> Task<gpui::Result<()>> {
4149 if &method_id == self.auth_method.id() {
4150 *self.authenticated.lock() = true;
4151 Task::ready(Ok(()))
4152 } else {
4153 Task::ready(Err(anyhow::anyhow!("Unknown auth method")))
4154 }
4155 }
4156
4157 fn prompt(
4158 &self,
4159 _id: Option<acp_thread::UserMessageId>,
4160 _params: acp::PromptRequest,
4161 _cx: &mut App,
4162 ) -> Task<gpui::Result<acp::PromptResponse>> {
4163 unimplemented!()
4164 }
4165
4166 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
4167 unimplemented!()
4168 }
4169
4170 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4171 self
4172 }
4173 }
4174
4175 #[derive(Clone)]
4176 struct SaboteurAgentConnection;
4177
4178 impl AgentConnection for SaboteurAgentConnection {
4179 fn agent_id(&self) -> AgentId {
4180 AgentId::new("saboteur")
4181 }
4182
4183 fn telemetry_id(&self) -> SharedString {
4184 "saboteur".into()
4185 }
4186
4187 fn new_session(
4188 self: Rc<Self>,
4189 project: Entity<Project>,
4190 work_dirs: PathList,
4191 cx: &mut gpui::App,
4192 ) -> Task<gpui::Result<Entity<AcpThread>>> {
4193 Task::ready(Ok(cx.new(|cx| {
4194 let action_log = cx.new(|_| ActionLog::new(project.clone()));
4195 AcpThread::new(
4196 None,
4197 None,
4198 Some(work_dirs),
4199 self,
4200 project,
4201 action_log,
4202 SessionId::new("test"),
4203 watch::Receiver::constant(
4204 acp::PromptCapabilities::new()
4205 .image(true)
4206 .audio(true)
4207 .embedded_context(true),
4208 ),
4209 cx,
4210 )
4211 })))
4212 }
4213
4214 fn auth_methods(&self) -> &[acp::AuthMethod] {
4215 &[]
4216 }
4217
4218 fn authenticate(
4219 &self,
4220 _method_id: acp::AuthMethodId,
4221 _cx: &mut App,
4222 ) -> Task<gpui::Result<()>> {
4223 unimplemented!()
4224 }
4225
4226 fn prompt(
4227 &self,
4228 _id: Option<acp_thread::UserMessageId>,
4229 _params: acp::PromptRequest,
4230 _cx: &mut App,
4231 ) -> Task<gpui::Result<acp::PromptResponse>> {
4232 Task::ready(Err(anyhow::anyhow!("Error prompting")))
4233 }
4234
4235 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
4236 unimplemented!()
4237 }
4238
4239 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4240 self
4241 }
4242 }
4243
4244 /// Simulates a model which always returns a refusal response
4245 #[derive(Clone)]
4246 struct RefusalAgentConnection;
4247
4248 impl AgentConnection for RefusalAgentConnection {
4249 fn agent_id(&self) -> AgentId {
4250 AgentId::new("refusal")
4251 }
4252
4253 fn telemetry_id(&self) -> SharedString {
4254 "refusal".into()
4255 }
4256
4257 fn new_session(
4258 self: Rc<Self>,
4259 project: Entity<Project>,
4260 work_dirs: PathList,
4261 cx: &mut gpui::App,
4262 ) -> Task<gpui::Result<Entity<AcpThread>>> {
4263 Task::ready(Ok(cx.new(|cx| {
4264 let action_log = cx.new(|_| ActionLog::new(project.clone()));
4265 AcpThread::new(
4266 None,
4267 None,
4268 Some(work_dirs),
4269 self,
4270 project,
4271 action_log,
4272 SessionId::new("test"),
4273 watch::Receiver::constant(
4274 acp::PromptCapabilities::new()
4275 .image(true)
4276 .audio(true)
4277 .embedded_context(true),
4278 ),
4279 cx,
4280 )
4281 })))
4282 }
4283
4284 fn auth_methods(&self) -> &[acp::AuthMethod] {
4285 &[]
4286 }
4287
4288 fn authenticate(
4289 &self,
4290 _method_id: acp::AuthMethodId,
4291 _cx: &mut App,
4292 ) -> Task<gpui::Result<()>> {
4293 unimplemented!()
4294 }
4295
4296 fn prompt(
4297 &self,
4298 _id: Option<acp_thread::UserMessageId>,
4299 _params: acp::PromptRequest,
4300 _cx: &mut App,
4301 ) -> Task<gpui::Result<acp::PromptResponse>> {
4302 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::Refusal)))
4303 }
4304
4305 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
4306 unimplemented!()
4307 }
4308
4309 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4310 self
4311 }
4312 }
4313
4314 #[derive(Clone)]
4315 struct CwdCapturingConnection {
4316 captured_work_dirs: Arc<Mutex<Option<PathList>>>,
4317 }
4318
4319 impl CwdCapturingConnection {
4320 fn new() -> Self {
4321 Self {
4322 captured_work_dirs: Arc::new(Mutex::new(None)),
4323 }
4324 }
4325 }
4326
4327 impl AgentConnection for CwdCapturingConnection {
4328 fn agent_id(&self) -> AgentId {
4329 AgentId::new("cwd-capturing")
4330 }
4331
4332 fn telemetry_id(&self) -> SharedString {
4333 "cwd-capturing".into()
4334 }
4335
4336 fn new_session(
4337 self: Rc<Self>,
4338 project: Entity<Project>,
4339 work_dirs: PathList,
4340 cx: &mut gpui::App,
4341 ) -> Task<gpui::Result<Entity<AcpThread>>> {
4342 *self.captured_work_dirs.lock() = Some(work_dirs.clone());
4343 let action_log = cx.new(|_| ActionLog::new(project.clone()));
4344 let thread = cx.new(|cx| {
4345 AcpThread::new(
4346 None,
4347 None,
4348 Some(work_dirs),
4349 self.clone(),
4350 project,
4351 action_log,
4352 SessionId::new("new-session"),
4353 watch::Receiver::constant(
4354 acp::PromptCapabilities::new()
4355 .image(true)
4356 .audio(true)
4357 .embedded_context(true),
4358 ),
4359 cx,
4360 )
4361 });
4362 Task::ready(Ok(thread))
4363 }
4364
4365 fn supports_load_session(&self) -> bool {
4366 true
4367 }
4368
4369 fn load_session(
4370 self: Rc<Self>,
4371 session_id: acp::SessionId,
4372 project: Entity<Project>,
4373 work_dirs: PathList,
4374 _title: Option<SharedString>,
4375 cx: &mut App,
4376 ) -> Task<gpui::Result<Entity<AcpThread>>> {
4377 *self.captured_work_dirs.lock() = Some(work_dirs.clone());
4378 let action_log = cx.new(|_| ActionLog::new(project.clone()));
4379 let thread = cx.new(|cx| {
4380 AcpThread::new(
4381 None,
4382 None,
4383 Some(work_dirs),
4384 self.clone(),
4385 project,
4386 action_log,
4387 session_id,
4388 watch::Receiver::constant(
4389 acp::PromptCapabilities::new()
4390 .image(true)
4391 .audio(true)
4392 .embedded_context(true),
4393 ),
4394 cx,
4395 )
4396 });
4397 Task::ready(Ok(thread))
4398 }
4399
4400 fn auth_methods(&self) -> &[acp::AuthMethod] {
4401 &[]
4402 }
4403
4404 fn authenticate(
4405 &self,
4406 _method_id: acp::AuthMethodId,
4407 _cx: &mut App,
4408 ) -> Task<gpui::Result<()>> {
4409 Task::ready(Ok(()))
4410 }
4411
4412 fn prompt(
4413 &self,
4414 _id: Option<acp_thread::UserMessageId>,
4415 _params: acp::PromptRequest,
4416 _cx: &mut App,
4417 ) -> Task<gpui::Result<acp::PromptResponse>> {
4418 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
4419 }
4420
4421 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
4422
4423 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4424 self
4425 }
4426 }
4427
4428 pub(crate) fn init_test(cx: &mut TestAppContext) {
4429 cx.update(|cx| {
4430 let settings_store = SettingsStore::test(cx);
4431 cx.set_global(settings_store);
4432 ThreadMetadataStore::init_global(cx);
4433 theme_settings::init(theme::LoadThemes::JustBase, cx);
4434 editor::init(cx);
4435 agent_panel::init(cx);
4436 release_channel::init(semver::Version::new(0, 0, 0), cx);
4437 prompt_store::init(cx)
4438 });
4439 }
4440
4441 fn active_thread(
4442 conversation_view: &Entity<ConversationView>,
4443 cx: &TestAppContext,
4444 ) -> Entity<ThreadView> {
4445 cx.read(|cx| {
4446 conversation_view
4447 .read(cx)
4448 .active_thread()
4449 .expect("No active thread")
4450 .clone()
4451 })
4452 }
4453
4454 fn message_editor(
4455 conversation_view: &Entity<ConversationView>,
4456 cx: &TestAppContext,
4457 ) -> Entity<MessageEditor> {
4458 let thread = active_thread(conversation_view, cx);
4459 cx.read(|cx| thread.read(cx).message_editor.clone())
4460 }
4461
4462 #[gpui::test]
4463 async fn test_rewind_views(cx: &mut TestAppContext) {
4464 init_test(cx);
4465
4466 let fs = FakeFs::new(cx.executor());
4467 fs.insert_tree(
4468 "/project",
4469 json!({
4470 "test1.txt": "old content 1",
4471 "test2.txt": "old content 2"
4472 }),
4473 )
4474 .await;
4475 let project = Project::test(fs, [Path::new("/project")], cx).await;
4476 let (multi_workspace, cx) =
4477 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
4478 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
4479
4480 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
4481 let connection_store =
4482 cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
4483
4484 let connection = Rc::new(StubAgentConnection::new());
4485 let conversation_view = cx.update(|window, cx| {
4486 cx.new(|cx| {
4487 ConversationView::new(
4488 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
4489 connection_store,
4490 Agent::Custom { id: "Test".into() },
4491 None,
4492 None,
4493 None,
4494 None,
4495 workspace.downgrade(),
4496 project.clone(),
4497 Some(thread_store.clone()),
4498 None,
4499 window,
4500 cx,
4501 )
4502 })
4503 });
4504
4505 cx.run_until_parked();
4506
4507 let thread = conversation_view
4508 .read_with(cx, |view, cx| {
4509 view.active_thread().map(|r| r.read(cx).thread.clone())
4510 })
4511 .unwrap();
4512
4513 // First user message
4514 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
4515 acp::ToolCall::new("tool1", "Edit file 1")
4516 .kind(acp::ToolKind::Edit)
4517 .status(acp::ToolCallStatus::Completed)
4518 .content(vec![acp::ToolCallContent::Diff(
4519 acp::Diff::new("/project/test1.txt", "new content 1").old_text("old content 1"),
4520 )]),
4521 )]);
4522
4523 thread
4524 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
4525 .await
4526 .unwrap();
4527 cx.run_until_parked();
4528
4529 thread.read_with(cx, |thread, _cx| {
4530 assert_eq!(thread.entries().len(), 2);
4531 });
4532
4533 conversation_view.read_with(cx, |view, cx| {
4534 let entry_view_state = view
4535 .active_thread()
4536 .map(|active| active.read(cx).entry_view_state.clone())
4537 .unwrap();
4538 entry_view_state.read_with(cx, |entry_view_state, _| {
4539 assert!(
4540 entry_view_state
4541 .entry(0)
4542 .unwrap()
4543 .message_editor()
4544 .is_some()
4545 );
4546 assert!(entry_view_state.entry(1).unwrap().has_content());
4547 });
4548 });
4549
4550 // Second user message
4551 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
4552 acp::ToolCall::new("tool2", "Edit file 2")
4553 .kind(acp::ToolKind::Edit)
4554 .status(acp::ToolCallStatus::Completed)
4555 .content(vec![acp::ToolCallContent::Diff(
4556 acp::Diff::new("/project/test2.txt", "new content 2").old_text("old content 2"),
4557 )]),
4558 )]);
4559
4560 thread
4561 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
4562 .await
4563 .unwrap();
4564 cx.run_until_parked();
4565
4566 let second_user_message_id = thread.read_with(cx, |thread, _| {
4567 assert_eq!(thread.entries().len(), 4);
4568 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
4569 panic!();
4570 };
4571 user_message.id.clone().unwrap()
4572 });
4573
4574 conversation_view.read_with(cx, |view, cx| {
4575 let entry_view_state = view
4576 .active_thread()
4577 .unwrap()
4578 .read(cx)
4579 .entry_view_state
4580 .clone();
4581 entry_view_state.read_with(cx, |entry_view_state, _| {
4582 assert!(
4583 entry_view_state
4584 .entry(0)
4585 .unwrap()
4586 .message_editor()
4587 .is_some()
4588 );
4589 assert!(entry_view_state.entry(1).unwrap().has_content());
4590 assert!(
4591 entry_view_state
4592 .entry(2)
4593 .unwrap()
4594 .message_editor()
4595 .is_some()
4596 );
4597 assert!(entry_view_state.entry(3).unwrap().has_content());
4598 });
4599 });
4600
4601 // Rewind to first message
4602 thread
4603 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
4604 .await
4605 .unwrap();
4606
4607 cx.run_until_parked();
4608
4609 thread.read_with(cx, |thread, _| {
4610 assert_eq!(thread.entries().len(), 2);
4611 });
4612
4613 conversation_view.read_with(cx, |view, cx| {
4614 let active = view.active_thread().unwrap();
4615 active
4616 .read(cx)
4617 .entry_view_state
4618 .read_with(cx, |entry_view_state, _| {
4619 assert!(
4620 entry_view_state
4621 .entry(0)
4622 .unwrap()
4623 .message_editor()
4624 .is_some()
4625 );
4626 assert!(entry_view_state.entry(1).unwrap().has_content());
4627
4628 // Old views should be dropped
4629 assert!(entry_view_state.entry(2).is_none());
4630 assert!(entry_view_state.entry(3).is_none());
4631 });
4632 });
4633 }
4634
4635 #[gpui::test]
4636 async fn test_scroll_to_most_recent_user_prompt(cx: &mut TestAppContext) {
4637 init_test(cx);
4638
4639 let connection = StubAgentConnection::new();
4640
4641 // Each user prompt will result in a user message entry plus an agent message entry.
4642 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4643 acp::ContentChunk::new("Response 1".into()),
4644 )]);
4645
4646 let (conversation_view, cx) =
4647 setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
4648
4649 let thread = conversation_view
4650 .read_with(cx, |view, cx| {
4651 view.active_thread().map(|r| r.read(cx).thread.clone())
4652 })
4653 .unwrap();
4654
4655 thread
4656 .update(cx, |thread, cx| thread.send_raw("Prompt 1", cx))
4657 .await
4658 .unwrap();
4659 cx.run_until_parked();
4660
4661 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4662 acp::ContentChunk::new("Response 2".into()),
4663 )]);
4664
4665 thread
4666 .update(cx, |thread, cx| thread.send_raw("Prompt 2", cx))
4667 .await
4668 .unwrap();
4669 cx.run_until_parked();
4670
4671 // Move somewhere else first so we're not trivially already on the last user prompt.
4672 active_thread(&conversation_view, cx).update(cx, |view, cx| {
4673 view.scroll_to_top(cx);
4674 });
4675 cx.run_until_parked();
4676
4677 active_thread(&conversation_view, cx).update(cx, |view, cx| {
4678 view.scroll_to_most_recent_user_prompt(cx);
4679 let scroll_top = view.list_state.logical_scroll_top();
4680 // Entries layout is: [User1, Assistant1, User2, Assistant2]
4681 assert_eq!(scroll_top.item_ix, 2);
4682 });
4683 }
4684
4685 #[gpui::test]
4686 async fn test_scroll_to_most_recent_user_prompt_falls_back_to_bottom_without_user_messages(
4687 cx: &mut TestAppContext,
4688 ) {
4689 init_test(cx);
4690
4691 let (conversation_view, cx) =
4692 setup_conversation_view(StubAgentServer::default_response(), cx).await;
4693
4694 // With no entries, scrolling should be a no-op and must not panic.
4695 active_thread(&conversation_view, cx).update(cx, |view, cx| {
4696 view.scroll_to_most_recent_user_prompt(cx);
4697 let scroll_top = view.list_state.logical_scroll_top();
4698 assert_eq!(scroll_top.item_ix, 0);
4699 });
4700 }
4701
4702 #[gpui::test]
4703 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
4704 init_test(cx);
4705
4706 let connection = StubAgentConnection::new();
4707
4708 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4709 acp::ContentChunk::new("Response".into()),
4710 )]);
4711
4712 let (conversation_view, cx) =
4713 setup_conversation_view(StubAgentServer::new(connection), cx).await;
4714 add_to_workspace(conversation_view.clone(), cx);
4715
4716 let message_editor = message_editor(&conversation_view, cx);
4717 message_editor.update_in(cx, |editor, window, cx| {
4718 editor.set_text("Original message to edit", window, cx);
4719 });
4720 active_thread(&conversation_view, cx)
4721 .update_in(cx, |view, window, cx| view.send(window, cx));
4722
4723 cx.run_until_parked();
4724
4725 let user_message_editor = conversation_view.read_with(cx, |view, cx| {
4726 assert_eq!(
4727 view.active_thread()
4728 .and_then(|active| active.read(cx).editing_message),
4729 None
4730 );
4731
4732 view.active_thread()
4733 .map(|active| &active.read(cx).entry_view_state)
4734 .as_ref()
4735 .unwrap()
4736 .read(cx)
4737 .entry(0)
4738 .unwrap()
4739 .message_editor()
4740 .unwrap()
4741 .clone()
4742 });
4743
4744 // Focus
4745 cx.focus(&user_message_editor);
4746 conversation_view.read_with(cx, |view, cx| {
4747 assert_eq!(
4748 view.active_thread()
4749 .and_then(|active| active.read(cx).editing_message),
4750 Some(0)
4751 );
4752 });
4753
4754 // Edit
4755 user_message_editor.update_in(cx, |editor, window, cx| {
4756 editor.set_text("Edited message content", window, cx);
4757 });
4758
4759 // Cancel
4760 user_message_editor.update_in(cx, |_editor, window, cx| {
4761 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
4762 });
4763
4764 conversation_view.read_with(cx, |view, cx| {
4765 assert_eq!(
4766 view.active_thread()
4767 .and_then(|active| active.read(cx).editing_message),
4768 None
4769 );
4770 });
4771
4772 user_message_editor.read_with(cx, |editor, cx| {
4773 assert_eq!(editor.text(cx), "Original message to edit");
4774 });
4775 }
4776
4777 #[gpui::test]
4778 async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
4779 init_test(cx);
4780
4781 let connection = StubAgentConnection::new();
4782
4783 let (conversation_view, cx) =
4784 setup_conversation_view(StubAgentServer::new(connection), cx).await;
4785 add_to_workspace(conversation_view.clone(), cx);
4786
4787 let message_editor = message_editor(&conversation_view, cx);
4788 message_editor.update_in(cx, |editor, window, cx| {
4789 editor.set_text("", window, cx);
4790 });
4791
4792 let thread = cx.read(|cx| {
4793 conversation_view
4794 .read(cx)
4795 .active_thread()
4796 .unwrap()
4797 .read(cx)
4798 .thread
4799 .clone()
4800 });
4801 let entries_before = cx.read(|cx| thread.read(cx).entries().len());
4802
4803 active_thread(&conversation_view, cx).update_in(cx, |view, window, cx| {
4804 view.send(window, cx);
4805 });
4806 cx.run_until_parked();
4807
4808 let entries_after = cx.read(|cx| thread.read(cx).entries().len());
4809 assert_eq!(
4810 entries_before, entries_after,
4811 "No message should be sent when editor is empty"
4812 );
4813 }
4814
4815 #[gpui::test]
4816 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
4817 init_test(cx);
4818
4819 let connection = StubAgentConnection::new();
4820
4821 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4822 acp::ContentChunk::new("Response".into()),
4823 )]);
4824
4825 let (conversation_view, cx) =
4826 setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
4827 add_to_workspace(conversation_view.clone(), cx);
4828
4829 let message_editor = message_editor(&conversation_view, cx);
4830 message_editor.update_in(cx, |editor, window, cx| {
4831 editor.set_text("Original message to edit", window, cx);
4832 });
4833 active_thread(&conversation_view, cx)
4834 .update_in(cx, |view, window, cx| view.send(window, cx));
4835
4836 cx.run_until_parked();
4837
4838 let user_message_editor = conversation_view.read_with(cx, |view, cx| {
4839 assert_eq!(
4840 view.active_thread()
4841 .and_then(|active| active.read(cx).editing_message),
4842 None
4843 );
4844 assert_eq!(
4845 view.active_thread()
4846 .unwrap()
4847 .read(cx)
4848 .thread
4849 .read(cx)
4850 .entries()
4851 .len(),
4852 2
4853 );
4854
4855 view.active_thread()
4856 .map(|active| &active.read(cx).entry_view_state)
4857 .as_ref()
4858 .unwrap()
4859 .read(cx)
4860 .entry(0)
4861 .unwrap()
4862 .message_editor()
4863 .unwrap()
4864 .clone()
4865 });
4866
4867 // Focus
4868 cx.focus(&user_message_editor);
4869
4870 // Edit
4871 user_message_editor.update_in(cx, |editor, window, cx| {
4872 editor.set_text("Edited message content", window, cx);
4873 });
4874
4875 // Send
4876 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
4877 acp::ContentChunk::new("New Response".into()),
4878 )]);
4879
4880 user_message_editor.update_in(cx, |_editor, window, cx| {
4881 window.dispatch_action(Box::new(Chat), cx);
4882 });
4883
4884 cx.run_until_parked();
4885
4886 conversation_view.read_with(cx, |view, cx| {
4887 assert_eq!(
4888 view.active_thread()
4889 .and_then(|active| active.read(cx).editing_message),
4890 None
4891 );
4892
4893 let entries = view
4894 .active_thread()
4895 .unwrap()
4896 .read(cx)
4897 .thread
4898 .read(cx)
4899 .entries();
4900 assert_eq!(entries.len(), 2);
4901 assert_eq!(
4902 entries[0].to_markdown(cx),
4903 "## User\n\nEdited message content\n\n"
4904 );
4905 assert_eq!(
4906 entries[1].to_markdown(cx),
4907 "## Assistant\n\nNew Response\n\n"
4908 );
4909
4910 let entry_view_state = view
4911 .active_thread()
4912 .map(|active| &active.read(cx).entry_view_state)
4913 .unwrap();
4914 let new_editor = entry_view_state.read_with(cx, |state, _cx| {
4915 assert!(!state.entry(1).unwrap().has_content());
4916 state.entry(0).unwrap().message_editor().unwrap().clone()
4917 });
4918
4919 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
4920 })
4921 }
4922
4923 #[gpui::test]
4924 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
4925 init_test(cx);
4926
4927 let connection = StubAgentConnection::new();
4928
4929 let (conversation_view, cx) =
4930 setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
4931 add_to_workspace(conversation_view.clone(), cx);
4932
4933 let message_editor = message_editor(&conversation_view, cx);
4934 message_editor.update_in(cx, |editor, window, cx| {
4935 editor.set_text("Original message to edit", window, cx);
4936 });
4937 active_thread(&conversation_view, cx)
4938 .update_in(cx, |view, window, cx| view.send(window, cx));
4939
4940 cx.run_until_parked();
4941
4942 let (user_message_editor, session_id) = conversation_view.read_with(cx, |view, cx| {
4943 let thread = view.active_thread().unwrap().read(cx).thread.read(cx);
4944 assert_eq!(thread.entries().len(), 1);
4945
4946 let editor = view
4947 .active_thread()
4948 .map(|active| &active.read(cx).entry_view_state)
4949 .as_ref()
4950 .unwrap()
4951 .read(cx)
4952 .entry(0)
4953 .unwrap()
4954 .message_editor()
4955 .unwrap()
4956 .clone();
4957
4958 (editor, thread.session_id().clone())
4959 });
4960
4961 // Focus
4962 cx.focus(&user_message_editor);
4963
4964 conversation_view.read_with(cx, |view, cx| {
4965 assert_eq!(
4966 view.active_thread()
4967 .and_then(|active| active.read(cx).editing_message),
4968 Some(0)
4969 );
4970 });
4971
4972 // Edit
4973 user_message_editor.update_in(cx, |editor, window, cx| {
4974 editor.set_text("Edited message content", window, cx);
4975 });
4976
4977 conversation_view.read_with(cx, |view, cx| {
4978 assert_eq!(
4979 view.active_thread()
4980 .and_then(|active| active.read(cx).editing_message),
4981 Some(0)
4982 );
4983 });
4984
4985 // Finish streaming response
4986 cx.update(|_, cx| {
4987 connection.send_update(
4988 session_id.clone(),
4989 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("Response".into())),
4990 cx,
4991 );
4992 connection.end_turn(session_id, acp::StopReason::EndTurn);
4993 });
4994
4995 conversation_view.read_with(cx, |view, cx| {
4996 assert_eq!(
4997 view.active_thread()
4998 .and_then(|active| active.read(cx).editing_message),
4999 Some(0)
5000 );
5001 });
5002
5003 cx.run_until_parked();
5004
5005 // Should still be editing
5006 cx.update(|window, cx| {
5007 assert!(user_message_editor.focus_handle(cx).is_focused(window));
5008 assert_eq!(
5009 conversation_view
5010 .read(cx)
5011 .active_thread()
5012 .and_then(|active| active.read(cx).editing_message),
5013 Some(0)
5014 );
5015 assert_eq!(
5016 user_message_editor.read(cx).text(cx),
5017 "Edited message content"
5018 );
5019 });
5020 }
5021
5022 #[gpui::test]
5023 async fn test_stale_stop_does_not_disable_follow_tail_during_regenerate(
5024 cx: &mut TestAppContext,
5025 ) {
5026 init_test(cx);
5027
5028 let connection = StubAgentConnection::new();
5029
5030 let (conversation_view, cx) =
5031 setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
5032 add_to_workspace(conversation_view.clone(), cx);
5033
5034 let message_editor = message_editor(&conversation_view, cx);
5035 message_editor.update_in(cx, |editor, window, cx| {
5036 editor.set_text("Original message to edit", window, cx);
5037 });
5038 active_thread(&conversation_view, cx)
5039 .update_in(cx, |view, window, cx| view.send(window, cx));
5040
5041 cx.run_until_parked();
5042
5043 let user_message_editor = conversation_view.read_with(cx, |view, cx| {
5044 view.active_thread()
5045 .map(|active| &active.read(cx).entry_view_state)
5046 .as_ref()
5047 .unwrap()
5048 .read(cx)
5049 .entry(0)
5050 .unwrap()
5051 .message_editor()
5052 .unwrap()
5053 .clone()
5054 });
5055
5056 cx.focus(&user_message_editor);
5057 user_message_editor.update_in(cx, |editor, window, cx| {
5058 editor.set_text("Edited message content", window, cx);
5059 });
5060
5061 user_message_editor.update_in(cx, |_editor, window, cx| {
5062 window.dispatch_action(Box::new(Chat), cx);
5063 });
5064
5065 cx.run_until_parked();
5066
5067 conversation_view.read_with(cx, |view, cx| {
5068 let active = view.active_thread().unwrap();
5069 let active = active.read(cx);
5070
5071 assert_eq!(active.thread.read(cx).status(), ThreadStatus::Generating);
5072 assert!(
5073 active.list_state.is_following_tail(),
5074 "stale stop events from the cancelled turn must not disable follow-tail for the new turn"
5075 );
5076 });
5077 }
5078
5079 struct GeneratingThreadSetup {
5080 conversation_view: Entity<ConversationView>,
5081 thread: Entity<AcpThread>,
5082 message_editor: Entity<MessageEditor>,
5083 }
5084
5085 async fn setup_generating_thread(
5086 cx: &mut TestAppContext,
5087 ) -> (GeneratingThreadSetup, &mut VisualTestContext) {
5088 let connection = StubAgentConnection::new();
5089
5090 let (conversation_view, cx) =
5091 setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
5092 add_to_workspace(conversation_view.clone(), cx);
5093
5094 let message_editor = message_editor(&conversation_view, cx);
5095 message_editor.update_in(cx, |editor, window, cx| {
5096 editor.set_text("Hello", window, cx);
5097 });
5098 active_thread(&conversation_view, cx)
5099 .update_in(cx, |view, window, cx| view.send(window, cx));
5100
5101 let (thread, session_id) = conversation_view.read_with(cx, |view, cx| {
5102 let thread = view
5103 .active_thread()
5104 .as_ref()
5105 .unwrap()
5106 .read(cx)
5107 .thread
5108 .clone();
5109 (thread.clone(), thread.read(cx).session_id().clone())
5110 });
5111
5112 cx.run_until_parked();
5113
5114 cx.update(|_, cx| {
5115 connection.send_update(
5116 session_id.clone(),
5117 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
5118 "Response chunk".into(),
5119 )),
5120 cx,
5121 );
5122 });
5123
5124 cx.run_until_parked();
5125
5126 thread.read_with(cx, |thread, _cx| {
5127 assert_eq!(thread.status(), ThreadStatus::Generating);
5128 });
5129
5130 (
5131 GeneratingThreadSetup {
5132 conversation_view,
5133 thread,
5134 message_editor,
5135 },
5136 cx,
5137 )
5138 }
5139
5140 #[gpui::test]
5141 async fn test_escape_cancels_generation_from_conversation_focus(cx: &mut TestAppContext) {
5142 init_test(cx);
5143
5144 let (setup, cx) = setup_generating_thread(cx).await;
5145
5146 let focus_handle = setup
5147 .conversation_view
5148 .read_with(cx, |view, cx| view.focus_handle(cx));
5149 cx.update(|window, cx| {
5150 window.focus(&focus_handle, cx);
5151 });
5152
5153 setup.conversation_view.update_in(cx, |_, window, cx| {
5154 window.dispatch_action(menu::Cancel.boxed_clone(), cx);
5155 });
5156
5157 cx.run_until_parked();
5158
5159 setup.thread.read_with(cx, |thread, _cx| {
5160 assert_eq!(thread.status(), ThreadStatus::Idle);
5161 });
5162 }
5163
5164 #[gpui::test]
5165 async fn test_escape_cancels_generation_from_editor_focus(cx: &mut TestAppContext) {
5166 init_test(cx);
5167
5168 let (setup, cx) = setup_generating_thread(cx).await;
5169
5170 let editor_focus_handle = setup
5171 .message_editor
5172 .read_with(cx, |editor, cx| editor.focus_handle(cx));
5173 cx.update(|window, cx| {
5174 window.focus(&editor_focus_handle, cx);
5175 });
5176
5177 setup.message_editor.update_in(cx, |_, window, cx| {
5178 window.dispatch_action(editor::actions::Cancel.boxed_clone(), cx);
5179 });
5180
5181 cx.run_until_parked();
5182
5183 setup.thread.read_with(cx, |thread, _cx| {
5184 assert_eq!(thread.status(), ThreadStatus::Idle);
5185 });
5186 }
5187
5188 #[gpui::test]
5189 async fn test_escape_when_idle_is_noop(cx: &mut TestAppContext) {
5190 init_test(cx);
5191
5192 let (conversation_view, cx) =
5193 setup_conversation_view(StubAgentServer::new(StubAgentConnection::new()), cx).await;
5194 add_to_workspace(conversation_view.clone(), cx);
5195
5196 let thread = conversation_view.read_with(cx, |view, cx| {
5197 view.active_thread().unwrap().read(cx).thread.clone()
5198 });
5199
5200 thread.read_with(cx, |thread, _cx| {
5201 assert_eq!(thread.status(), ThreadStatus::Idle);
5202 });
5203
5204 let focus_handle = conversation_view.read_with(cx, |view, _cx| view.focus_handle.clone());
5205 cx.update(|window, cx| {
5206 window.focus(&focus_handle, cx);
5207 });
5208
5209 conversation_view.update_in(cx, |_, window, cx| {
5210 window.dispatch_action(menu::Cancel.boxed_clone(), cx);
5211 });
5212
5213 cx.run_until_parked();
5214
5215 thread.read_with(cx, |thread, _cx| {
5216 assert_eq!(thread.status(), ThreadStatus::Idle);
5217 });
5218 }
5219
5220 #[gpui::test]
5221 async fn test_interrupt(cx: &mut TestAppContext) {
5222 init_test(cx);
5223
5224 let connection = StubAgentConnection::new();
5225
5226 let (conversation_view, cx) =
5227 setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
5228 add_to_workspace(conversation_view.clone(), cx);
5229
5230 let message_editor = message_editor(&conversation_view, cx);
5231 message_editor.update_in(cx, |editor, window, cx| {
5232 editor.set_text("Message 1", window, cx);
5233 });
5234 active_thread(&conversation_view, cx)
5235 .update_in(cx, |view, window, cx| view.send(window, cx));
5236
5237 let (thread, session_id) = conversation_view.read_with(cx, |view, cx| {
5238 let thread = view.active_thread().unwrap().read(cx).thread.clone();
5239
5240 (thread.clone(), thread.read(cx).session_id().clone())
5241 });
5242
5243 cx.run_until_parked();
5244
5245 cx.update(|_, cx| {
5246 connection.send_update(
5247 session_id.clone(),
5248 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
5249 "Message 1 resp".into(),
5250 )),
5251 cx,
5252 );
5253 });
5254
5255 cx.run_until_parked();
5256
5257 thread.read_with(cx, |thread, cx| {
5258 assert_eq!(
5259 thread.to_markdown(cx),
5260 indoc::indoc! {"
5261 ## User
5262
5263 Message 1
5264
5265 ## Assistant
5266
5267 Message 1 resp
5268
5269 "}
5270 )
5271 });
5272
5273 message_editor.update_in(cx, |editor, window, cx| {
5274 editor.set_text("Message 2", window, cx);
5275 });
5276 active_thread(&conversation_view, cx)
5277 .update_in(cx, |view, window, cx| view.interrupt_and_send(window, cx));
5278
5279 cx.update(|_, cx| {
5280 // Simulate a response sent after beginning to cancel
5281 connection.send_update(
5282 session_id.clone(),
5283 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("onse".into())),
5284 cx,
5285 );
5286 });
5287
5288 cx.run_until_parked();
5289
5290 // Last Message 1 response should appear before Message 2
5291 thread.read_with(cx, |thread, cx| {
5292 assert_eq!(
5293 thread.to_markdown(cx),
5294 indoc::indoc! {"
5295 ## User
5296
5297 Message 1
5298
5299 ## Assistant
5300
5301 Message 1 response
5302
5303 ## User
5304
5305 Message 2
5306
5307 "}
5308 )
5309 });
5310
5311 cx.update(|_, cx| {
5312 connection.send_update(
5313 session_id.clone(),
5314 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
5315 "Message 2 response".into(),
5316 )),
5317 cx,
5318 );
5319 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
5320 });
5321
5322 cx.run_until_parked();
5323
5324 thread.read_with(cx, |thread, cx| {
5325 assert_eq!(
5326 thread.to_markdown(cx),
5327 indoc::indoc! {"
5328 ## User
5329
5330 Message 1
5331
5332 ## Assistant
5333
5334 Message 1 response
5335
5336 ## User
5337
5338 Message 2
5339
5340 ## Assistant
5341
5342 Message 2 response
5343
5344 "}
5345 )
5346 });
5347 }
5348
5349 #[gpui::test]
5350 async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
5351 init_test(cx);
5352
5353 let connection = StubAgentConnection::new();
5354 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5355 acp::ContentChunk::new("Response".into()),
5356 )]);
5357
5358 let (conversation_view, cx) =
5359 setup_conversation_view(StubAgentServer::new(connection), cx).await;
5360 add_to_workspace(conversation_view.clone(), cx);
5361
5362 let message_editor = message_editor(&conversation_view, cx);
5363 message_editor.update_in(cx, |editor, window, cx| {
5364 editor.set_text("Original message to edit", window, cx)
5365 });
5366 active_thread(&conversation_view, cx)
5367 .update_in(cx, |view, window, cx| view.send(window, cx));
5368 cx.run_until_parked();
5369
5370 let user_message_editor = conversation_view.read_with(cx, |conversation_view, cx| {
5371 conversation_view
5372 .active_thread()
5373 .map(|active| &active.read(cx).entry_view_state)
5374 .as_ref()
5375 .unwrap()
5376 .read(cx)
5377 .entry(0)
5378 .expect("Should have at least one entry")
5379 .message_editor()
5380 .expect("Should have message editor")
5381 .clone()
5382 });
5383
5384 cx.focus(&user_message_editor);
5385 conversation_view.read_with(cx, |view, cx| {
5386 assert_eq!(
5387 view.active_thread()
5388 .and_then(|active| active.read(cx).editing_message),
5389 Some(0)
5390 );
5391 });
5392
5393 // Ensure to edit the focused message before proceeding otherwise, since
5394 // its content is not different from what was sent, focus will be lost.
5395 user_message_editor.update_in(cx, |editor, window, cx| {
5396 editor.set_text("Original message to edit with ", window, cx)
5397 });
5398
5399 // Create a simple buffer with some text so we can create a selection
5400 // that will then be added to the message being edited.
5401 let (workspace, project) = conversation_view.read_with(cx, |conversation_view, _cx| {
5402 (
5403 conversation_view.workspace.clone(),
5404 conversation_view.project.clone(),
5405 )
5406 });
5407 let buffer = project.update(cx, |project, cx| {
5408 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
5409 });
5410
5411 workspace
5412 .update_in(cx, |workspace, window, cx| {
5413 let editor = cx.new(|cx| {
5414 let mut editor =
5415 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
5416
5417 editor.change_selections(Default::default(), window, cx, |selections| {
5418 selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
5419 });
5420
5421 editor
5422 });
5423 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
5424 })
5425 .unwrap();
5426
5427 conversation_view.update_in(cx, |view, window, cx| {
5428 assert_eq!(
5429 view.active_thread()
5430 .and_then(|active| active.read(cx).editing_message),
5431 Some(0)
5432 );
5433 view.insert_selections(window, cx);
5434 });
5435
5436 user_message_editor.read_with(cx, |editor, cx| {
5437 let text = editor.editor().read(cx).text(cx);
5438 let expected_text = String::from("Original message to edit with selection ");
5439
5440 assert_eq!(text, expected_text);
5441 });
5442 }
5443
5444 #[gpui::test]
5445 async fn test_insert_selections(cx: &mut TestAppContext) {
5446 init_test(cx);
5447
5448 let connection = StubAgentConnection::new();
5449 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5450 acp::ContentChunk::new("Response".into()),
5451 )]);
5452
5453 let (conversation_view, cx) =
5454 setup_conversation_view(StubAgentServer::new(connection), cx).await;
5455 add_to_workspace(conversation_view.clone(), cx);
5456
5457 let message_editor = message_editor(&conversation_view, cx);
5458 message_editor.update_in(cx, |editor, window, cx| {
5459 editor.set_text("Can you review this snippet ", window, cx)
5460 });
5461
5462 // Create a simple buffer with some text so we can create a selection
5463 // that will then be added to the message being edited.
5464 let (workspace, project) = conversation_view.read_with(cx, |conversation_view, _cx| {
5465 (
5466 conversation_view.workspace.clone(),
5467 conversation_view.project.clone(),
5468 )
5469 });
5470 let buffer = project.update(cx, |project, cx| {
5471 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
5472 });
5473
5474 workspace
5475 .update_in(cx, |workspace, window, cx| {
5476 let editor = cx.new(|cx| {
5477 let mut editor =
5478 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
5479
5480 editor.change_selections(Default::default(), window, cx, |selections| {
5481 selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
5482 });
5483
5484 editor
5485 });
5486 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
5487 })
5488 .unwrap();
5489
5490 conversation_view.update_in(cx, |view, window, cx| {
5491 assert_eq!(
5492 view.active_thread()
5493 .and_then(|active| active.read(cx).editing_message),
5494 None
5495 );
5496 view.insert_selections(window, cx);
5497 });
5498
5499 message_editor.read_with(cx, |editor, cx| {
5500 let text = editor.text(cx);
5501 let expected_txt = String::from("Can you review this snippet selection ");
5502
5503 assert_eq!(text, expected_txt);
5504 })
5505 }
5506
5507 #[gpui::test]
5508 async fn test_tool_permission_buttons_terminal_with_pattern(cx: &mut TestAppContext) {
5509 init_test(cx);
5510
5511 let tool_call_id = acp::ToolCallId::new("terminal-1");
5512 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build --release`")
5513 .kind(acp::ToolKind::Edit);
5514
5515 let permission_options = ToolPermissionContext::new(
5516 TerminalTool::NAME,
5517 vec!["cargo build --release".to_string()],
5518 )
5519 .build_permission_options();
5520
5521 let connection =
5522 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5523 tool_call_id.clone(),
5524 permission_options,
5525 )]));
5526
5527 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5528
5529 let (conversation_view, cx) =
5530 setup_conversation_view(StubAgentServer::new(connection), cx).await;
5531
5532 // Disable notifications to avoid popup windows
5533 cx.update(|_window, cx| {
5534 AgentSettings::override_global(
5535 AgentSettings {
5536 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5537 ..AgentSettings::get_global(cx).clone()
5538 },
5539 cx,
5540 );
5541 });
5542
5543 let message_editor = message_editor(&conversation_view, cx);
5544 message_editor.update_in(cx, |editor, window, cx| {
5545 editor.set_text("Run cargo build", window, cx);
5546 });
5547
5548 active_thread(&conversation_view, cx)
5549 .update_in(cx, |view, window, cx| view.send(window, cx));
5550
5551 cx.run_until_parked();
5552
5553 // Verify the tool call is in WaitingForConfirmation state with the expected options
5554 conversation_view.read_with(cx, |conversation_view, cx| {
5555 let thread = conversation_view
5556 .active_thread()
5557 .expect("Thread should exist")
5558 .read(cx)
5559 .thread
5560 .clone();
5561 let thread = thread.read(cx);
5562
5563 let tool_call = thread.entries().iter().find_map(|entry| {
5564 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5565 Some(call)
5566 } else {
5567 None
5568 }
5569 });
5570
5571 assert!(tool_call.is_some(), "Expected a tool call entry");
5572 let tool_call = tool_call.unwrap();
5573
5574 // Verify it's waiting for confirmation
5575 assert!(
5576 matches!(
5577 tool_call.status,
5578 acp_thread::ToolCallStatus::WaitingForConfirmation { .. }
5579 ),
5580 "Expected WaitingForConfirmation status, got {:?}",
5581 tool_call.status
5582 );
5583
5584 // Verify the options count (granularity options only, no separate Deny option)
5585 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5586 &tool_call.status
5587 {
5588 let PermissionOptions::Dropdown(choices) = options else {
5589 panic!("Expected dropdown permission options");
5590 };
5591
5592 assert_eq!(
5593 choices.len(),
5594 3,
5595 "Expected 3 permission options (granularity only)"
5596 );
5597
5598 // Verify specific button labels (now using neutral names)
5599 let labels: Vec<&str> = choices
5600 .iter()
5601 .map(|choice| choice.allow.name.as_ref())
5602 .collect();
5603 assert!(
5604 labels.contains(&"Always for terminal"),
5605 "Missing 'Always for terminal' option"
5606 );
5607 assert!(
5608 labels.contains(&"Always for `cargo build` commands"),
5609 "Missing pattern option"
5610 );
5611 assert!(
5612 labels.contains(&"Only this time"),
5613 "Missing 'Only this time' option"
5614 );
5615 }
5616 });
5617 }
5618
5619 #[gpui::test]
5620 async fn test_tool_permission_buttons_edit_file_with_path_pattern(cx: &mut TestAppContext) {
5621 init_test(cx);
5622
5623 let tool_call_id = acp::ToolCallId::new("edit-file-1");
5624 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Edit `src/main.rs`")
5625 .kind(acp::ToolKind::Edit);
5626
5627 let permission_options =
5628 ToolPermissionContext::new(EditFileTool::NAME, vec!["src/main.rs".to_string()])
5629 .build_permission_options();
5630
5631 let connection =
5632 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5633 tool_call_id.clone(),
5634 permission_options,
5635 )]));
5636
5637 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5638
5639 let (conversation_view, cx) =
5640 setup_conversation_view(StubAgentServer::new(connection), cx).await;
5641
5642 // Disable notifications
5643 cx.update(|_window, cx| {
5644 AgentSettings::override_global(
5645 AgentSettings {
5646 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5647 ..AgentSettings::get_global(cx).clone()
5648 },
5649 cx,
5650 );
5651 });
5652
5653 let message_editor = message_editor(&conversation_view, cx);
5654 message_editor.update_in(cx, |editor, window, cx| {
5655 editor.set_text("Edit the main file", window, cx);
5656 });
5657
5658 active_thread(&conversation_view, cx)
5659 .update_in(cx, |view, window, cx| view.send(window, cx));
5660
5661 cx.run_until_parked();
5662
5663 // Verify the options
5664 conversation_view.read_with(cx, |conversation_view, cx| {
5665 let thread = conversation_view
5666 .active_thread()
5667 .expect("Thread should exist")
5668 .read(cx)
5669 .thread
5670 .clone();
5671 let thread = thread.read(cx);
5672
5673 let tool_call = thread.entries().iter().find_map(|entry| {
5674 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5675 Some(call)
5676 } else {
5677 None
5678 }
5679 });
5680
5681 assert!(tool_call.is_some(), "Expected a tool call entry");
5682 let tool_call = tool_call.unwrap();
5683
5684 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5685 &tool_call.status
5686 {
5687 let PermissionOptions::Dropdown(choices) = options else {
5688 panic!("Expected dropdown permission options");
5689 };
5690
5691 let labels: Vec<&str> = choices
5692 .iter()
5693 .map(|choice| choice.allow.name.as_ref())
5694 .collect();
5695 assert!(
5696 labels.contains(&"Always for edit file"),
5697 "Missing 'Always for edit file' option"
5698 );
5699 assert!(
5700 labels.contains(&"Always for `src/`"),
5701 "Missing path pattern option"
5702 );
5703 } else {
5704 panic!("Expected WaitingForConfirmation status");
5705 }
5706 });
5707 }
5708
5709 #[gpui::test]
5710 async fn test_tool_permission_buttons_fetch_with_domain_pattern(cx: &mut TestAppContext) {
5711 init_test(cx);
5712
5713 let tool_call_id = acp::ToolCallId::new("fetch-1");
5714 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Fetch `https://docs.rs/gpui`")
5715 .kind(acp::ToolKind::Fetch);
5716
5717 let permission_options =
5718 ToolPermissionContext::new(FetchTool::NAME, vec!["https://docs.rs/gpui".to_string()])
5719 .build_permission_options();
5720
5721 let connection =
5722 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5723 tool_call_id.clone(),
5724 permission_options,
5725 )]));
5726
5727 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5728
5729 let (conversation_view, cx) =
5730 setup_conversation_view(StubAgentServer::new(connection), cx).await;
5731
5732 // Disable notifications
5733 cx.update(|_window, cx| {
5734 AgentSettings::override_global(
5735 AgentSettings {
5736 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5737 ..AgentSettings::get_global(cx).clone()
5738 },
5739 cx,
5740 );
5741 });
5742
5743 let message_editor = message_editor(&conversation_view, cx);
5744 message_editor.update_in(cx, |editor, window, cx| {
5745 editor.set_text("Fetch the docs", window, cx);
5746 });
5747
5748 active_thread(&conversation_view, cx)
5749 .update_in(cx, |view, window, cx| view.send(window, cx));
5750
5751 cx.run_until_parked();
5752
5753 // Verify the options
5754 conversation_view.read_with(cx, |conversation_view, cx| {
5755 let thread = conversation_view
5756 .active_thread()
5757 .expect("Thread should exist")
5758 .read(cx)
5759 .thread
5760 .clone();
5761 let thread = thread.read(cx);
5762
5763 let tool_call = thread.entries().iter().find_map(|entry| {
5764 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5765 Some(call)
5766 } else {
5767 None
5768 }
5769 });
5770
5771 assert!(tool_call.is_some(), "Expected a tool call entry");
5772 let tool_call = tool_call.unwrap();
5773
5774 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5775 &tool_call.status
5776 {
5777 let PermissionOptions::Dropdown(choices) = options else {
5778 panic!("Expected dropdown permission options");
5779 };
5780
5781 let labels: Vec<&str> = choices
5782 .iter()
5783 .map(|choice| choice.allow.name.as_ref())
5784 .collect();
5785 assert!(
5786 labels.contains(&"Always for fetch"),
5787 "Missing 'Always for fetch' option"
5788 );
5789 assert!(
5790 labels.contains(&"Always for `docs.rs`"),
5791 "Missing domain pattern option"
5792 );
5793 } else {
5794 panic!("Expected WaitingForConfirmation status");
5795 }
5796 });
5797 }
5798
5799 #[gpui::test]
5800 async fn test_tool_permission_buttons_without_pattern(cx: &mut TestAppContext) {
5801 init_test(cx);
5802
5803 let tool_call_id = acp::ToolCallId::new("terminal-no-pattern-1");
5804 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `./deploy.sh --production`")
5805 .kind(acp::ToolKind::Edit);
5806
5807 // No pattern button since ./deploy.sh doesn't match the alphanumeric pattern
5808 let permission_options = ToolPermissionContext::new(
5809 TerminalTool::NAME,
5810 vec!["./deploy.sh --production".to_string()],
5811 )
5812 .build_permission_options();
5813
5814 let connection =
5815 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5816 tool_call_id.clone(),
5817 permission_options,
5818 )]));
5819
5820 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5821
5822 let (conversation_view, cx) =
5823 setup_conversation_view(StubAgentServer::new(connection), cx).await;
5824
5825 // Disable notifications
5826 cx.update(|_window, cx| {
5827 AgentSettings::override_global(
5828 AgentSettings {
5829 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5830 ..AgentSettings::get_global(cx).clone()
5831 },
5832 cx,
5833 );
5834 });
5835
5836 let message_editor = message_editor(&conversation_view, cx);
5837 message_editor.update_in(cx, |editor, window, cx| {
5838 editor.set_text("Run the deploy script", window, cx);
5839 });
5840
5841 active_thread(&conversation_view, cx)
5842 .update_in(cx, |view, window, cx| view.send(window, cx));
5843
5844 cx.run_until_parked();
5845
5846 // Verify only 2 options (no pattern button when command doesn't match pattern)
5847 conversation_view.read_with(cx, |conversation_view, cx| {
5848 let thread = conversation_view
5849 .active_thread()
5850 .expect("Thread should exist")
5851 .read(cx)
5852 .thread
5853 .clone();
5854 let thread = thread.read(cx);
5855
5856 let tool_call = thread.entries().iter().find_map(|entry| {
5857 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
5858 Some(call)
5859 } else {
5860 None
5861 }
5862 });
5863
5864 assert!(tool_call.is_some(), "Expected a tool call entry");
5865 let tool_call = tool_call.unwrap();
5866
5867 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
5868 &tool_call.status
5869 {
5870 let PermissionOptions::Dropdown(choices) = options else {
5871 panic!("Expected dropdown permission options");
5872 };
5873
5874 assert_eq!(
5875 choices.len(),
5876 2,
5877 "Expected 2 permission options (no pattern option)"
5878 );
5879
5880 let labels: Vec<&str> = choices
5881 .iter()
5882 .map(|choice| choice.allow.name.as_ref())
5883 .collect();
5884 assert!(
5885 labels.contains(&"Always for terminal"),
5886 "Missing 'Always for terminal' option"
5887 );
5888 assert!(
5889 labels.contains(&"Only this time"),
5890 "Missing 'Only this time' option"
5891 );
5892 // Should NOT contain a pattern option
5893 assert!(
5894 !labels.iter().any(|l| l.contains("commands")),
5895 "Should not have pattern option"
5896 );
5897 } else {
5898 panic!("Expected WaitingForConfirmation status");
5899 }
5900 });
5901 }
5902
5903 #[gpui::test]
5904 async fn test_authorize_tool_call_action_triggers_authorization(cx: &mut TestAppContext) {
5905 init_test(cx);
5906
5907 let tool_call_id = acp::ToolCallId::new("action-test-1");
5908 let tool_call =
5909 acp::ToolCall::new(tool_call_id.clone(), "Run `cargo test`").kind(acp::ToolKind::Edit);
5910
5911 let permission_options =
5912 ToolPermissionContext::new(TerminalTool::NAME, vec!["cargo test".to_string()])
5913 .build_permission_options();
5914
5915 let connection =
5916 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5917 tool_call_id.clone(),
5918 permission_options,
5919 )]));
5920
5921 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5922
5923 let (conversation_view, cx) =
5924 setup_conversation_view(StubAgentServer::new(connection), cx).await;
5925 add_to_workspace(conversation_view.clone(), cx);
5926
5927 cx.update(|_window, cx| {
5928 AgentSettings::override_global(
5929 AgentSettings {
5930 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
5931 ..AgentSettings::get_global(cx).clone()
5932 },
5933 cx,
5934 );
5935 });
5936
5937 let message_editor = message_editor(&conversation_view, cx);
5938 message_editor.update_in(cx, |editor, window, cx| {
5939 editor.set_text("Run tests", window, cx);
5940 });
5941
5942 active_thread(&conversation_view, cx)
5943 .update_in(cx, |view, window, cx| view.send(window, cx));
5944
5945 cx.run_until_parked();
5946
5947 // Verify tool call is waiting for confirmation
5948 conversation_view.read_with(cx, |conversation_view, cx| {
5949 let tool_call = conversation_view.pending_tool_call(cx);
5950 assert!(
5951 tool_call.is_some(),
5952 "Expected a tool call waiting for confirmation"
5953 );
5954 });
5955
5956 // Dispatch the AuthorizeToolCall action (simulating dropdown menu selection)
5957 conversation_view.update_in(cx, |_, window, cx| {
5958 window.dispatch_action(
5959 crate::AuthorizeToolCall {
5960 tool_call_id: "action-test-1".to_string(),
5961 option_id: "allow".to_string(),
5962 option_kind: "AllowOnce".to_string(),
5963 }
5964 .boxed_clone(),
5965 cx,
5966 );
5967 });
5968
5969 cx.run_until_parked();
5970
5971 // Verify tool call is no longer waiting for confirmation (was authorized)
5972 conversation_view.read_with(cx, |conversation_view, cx| {
5973 let tool_call = conversation_view.pending_tool_call(cx);
5974 assert!(
5975 tool_call.is_none(),
5976 "Tool call should no longer be waiting for confirmation after AuthorizeToolCall action"
5977 );
5978 });
5979 }
5980
5981 #[gpui::test]
5982 async fn test_authorize_tool_call_action_with_pattern_option(cx: &mut TestAppContext) {
5983 init_test(cx);
5984
5985 let tool_call_id = acp::ToolCallId::new("pattern-action-test-1");
5986 let tool_call =
5987 acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
5988
5989 let permission_options =
5990 ToolPermissionContext::new(TerminalTool::NAME, vec!["npm install".to_string()])
5991 .build_permission_options();
5992
5993 let connection =
5994 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5995 tool_call_id.clone(),
5996 permission_options.clone(),
5997 )]));
5998
5999 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
6000
6001 let (conversation_view, cx) =
6002 setup_conversation_view(StubAgentServer::new(connection), cx).await;
6003 add_to_workspace(conversation_view.clone(), cx);
6004
6005 cx.update(|_window, cx| {
6006 AgentSettings::override_global(
6007 AgentSettings {
6008 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
6009 ..AgentSettings::get_global(cx).clone()
6010 },
6011 cx,
6012 );
6013 });
6014
6015 let message_editor = message_editor(&conversation_view, cx);
6016 message_editor.update_in(cx, |editor, window, cx| {
6017 editor.set_text("Install dependencies", window, cx);
6018 });
6019
6020 active_thread(&conversation_view, cx)
6021 .update_in(cx, |view, window, cx| view.send(window, cx));
6022
6023 cx.run_until_parked();
6024
6025 // Find the pattern option ID (the choice with non-empty sub_patterns)
6026 let pattern_option = match &permission_options {
6027 PermissionOptions::Dropdown(choices) => choices
6028 .iter()
6029 .find(|choice| !choice.sub_patterns.is_empty())
6030 .map(|choice| &choice.allow)
6031 .expect("Should have a pattern option for npm command"),
6032 _ => panic!("Expected dropdown permission options"),
6033 };
6034
6035 // Dispatch action with the pattern option (simulating "Always allow `npm` commands")
6036 conversation_view.update_in(cx, |_, window, cx| {
6037 window.dispatch_action(
6038 crate::AuthorizeToolCall {
6039 tool_call_id: "pattern-action-test-1".to_string(),
6040 option_id: pattern_option.option_id.0.to_string(),
6041 option_kind: "AllowAlways".to_string(),
6042 }
6043 .boxed_clone(),
6044 cx,
6045 );
6046 });
6047
6048 cx.run_until_parked();
6049
6050 // Verify tool call was authorized
6051 conversation_view.read_with(cx, |conversation_view, cx| {
6052 let tool_call = conversation_view.pending_tool_call(cx);
6053 assert!(
6054 tool_call.is_none(),
6055 "Tool call should be authorized after selecting pattern option"
6056 );
6057 });
6058 }
6059
6060 #[gpui::test]
6061 async fn test_granularity_selection_updates_state(cx: &mut TestAppContext) {
6062 init_test(cx);
6063
6064 let tool_call_id = acp::ToolCallId::new("granularity-test-1");
6065 let tool_call =
6066 acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build`").kind(acp::ToolKind::Edit);
6067
6068 let permission_options =
6069 ToolPermissionContext::new(TerminalTool::NAME, vec!["cargo build".to_string()])
6070 .build_permission_options();
6071
6072 let connection =
6073 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
6074 tool_call_id.clone(),
6075 permission_options.clone(),
6076 )]));
6077
6078 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
6079
6080 let (thread_view, cx) = setup_conversation_view(StubAgentServer::new(connection), cx).await;
6081 add_to_workspace(thread_view.clone(), cx);
6082
6083 cx.update(|_window, cx| {
6084 AgentSettings::override_global(
6085 AgentSettings {
6086 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
6087 ..AgentSettings::get_global(cx).clone()
6088 },
6089 cx,
6090 );
6091 });
6092
6093 let message_editor = message_editor(&thread_view, cx);
6094 message_editor.update_in(cx, |editor, window, cx| {
6095 editor.set_text("Build the project", window, cx);
6096 });
6097
6098 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
6099
6100 cx.run_until_parked();
6101
6102 // Verify default granularity is the last option (index 2 = "Only this time")
6103 thread_view.read_with(cx, |thread_view, cx| {
6104 let state = thread_view.active_thread().unwrap();
6105 let selected = state.read(cx).permission_selections.get(&tool_call_id);
6106 assert!(
6107 selected.is_none(),
6108 "Should have no selection initially (defaults to last)"
6109 );
6110 });
6111
6112 // Select the first option (index 0 = "Always for terminal")
6113 thread_view.update_in(cx, |_, window, cx| {
6114 window.dispatch_action(
6115 crate::SelectPermissionGranularity {
6116 tool_call_id: "granularity-test-1".to_string(),
6117 index: 0,
6118 }
6119 .boxed_clone(),
6120 cx,
6121 );
6122 });
6123
6124 cx.run_until_parked();
6125
6126 // Verify the selection was updated
6127 thread_view.read_with(cx, |thread_view, cx| {
6128 let state = thread_view.active_thread().unwrap();
6129 let selected = state.read(cx).permission_selections.get(&tool_call_id);
6130 assert_eq!(
6131 selected.and_then(|s| s.choice_index()),
6132 Some(0),
6133 "Should have selected index 0"
6134 );
6135 });
6136 }
6137
6138 #[gpui::test]
6139 async fn test_allow_button_uses_selected_granularity(cx: &mut TestAppContext) {
6140 init_test(cx);
6141
6142 let tool_call_id = acp::ToolCallId::new("allow-granularity-test-1");
6143 let tool_call =
6144 acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
6145
6146 let permission_options =
6147 ToolPermissionContext::new(TerminalTool::NAME, vec!["npm install".to_string()])
6148 .build_permission_options();
6149
6150 // Verify we have the expected options
6151 let PermissionOptions::Dropdown(choices) = &permission_options else {
6152 panic!("Expected dropdown permission options");
6153 };
6154
6155 assert_eq!(choices.len(), 3);
6156 assert!(
6157 choices[0]
6158 .allow
6159 .option_id
6160 .0
6161 .contains("always_allow:terminal")
6162 );
6163 assert!(
6164 choices[1]
6165 .allow
6166 .option_id
6167 .0
6168 .contains("always_allow:terminal")
6169 );
6170 assert!(!choices[1].sub_patterns.is_empty());
6171 assert_eq!(choices[2].allow.option_id.0.as_ref(), "allow");
6172
6173 let connection =
6174 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
6175 tool_call_id.clone(),
6176 permission_options.clone(),
6177 )]));
6178
6179 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
6180
6181 let (thread_view, cx) = setup_conversation_view(StubAgentServer::new(connection), cx).await;
6182 add_to_workspace(thread_view.clone(), cx);
6183
6184 cx.update(|_window, cx| {
6185 AgentSettings::override_global(
6186 AgentSettings {
6187 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
6188 ..AgentSettings::get_global(cx).clone()
6189 },
6190 cx,
6191 );
6192 });
6193
6194 let message_editor = message_editor(&thread_view, cx);
6195 message_editor.update_in(cx, |editor, window, cx| {
6196 editor.set_text("Install dependencies", window, cx);
6197 });
6198
6199 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| view.send(window, cx));
6200
6201 cx.run_until_parked();
6202
6203 // Select the pattern option (index 1 = "Always for `npm` commands")
6204 thread_view.update_in(cx, |_, window, cx| {
6205 window.dispatch_action(
6206 crate::SelectPermissionGranularity {
6207 tool_call_id: "allow-granularity-test-1".to_string(),
6208 index: 1,
6209 }
6210 .boxed_clone(),
6211 cx,
6212 );
6213 });
6214
6215 cx.run_until_parked();
6216
6217 // Simulate clicking the Allow button by dispatching AllowOnce action
6218 // which should use the selected granularity
6219 active_thread(&thread_view, cx).update_in(cx, |view, window, cx| {
6220 view.allow_once(&AllowOnce, window, cx)
6221 });
6222
6223 cx.run_until_parked();
6224
6225 // Verify tool call was authorized
6226 thread_view.read_with(cx, |thread_view, cx| {
6227 let tool_call = thread_view.pending_tool_call(cx);
6228 assert!(
6229 tool_call.is_none(),
6230 "Tool call should be authorized after Allow with pattern granularity"
6231 );
6232 });
6233 }
6234
6235 #[gpui::test]
6236 async fn test_deny_button_uses_selected_granularity(cx: &mut TestAppContext) {
6237 init_test(cx);
6238
6239 let tool_call_id = acp::ToolCallId::new("deny-granularity-test-1");
6240 let tool_call =
6241 acp::ToolCall::new(tool_call_id.clone(), "Run `git push`").kind(acp::ToolKind::Edit);
6242
6243 let permission_options =
6244 ToolPermissionContext::new(TerminalTool::NAME, vec!["git push".to_string()])
6245 .build_permission_options();
6246
6247 let connection =
6248 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
6249 tool_call_id.clone(),
6250 permission_options.clone(),
6251 )]));
6252
6253 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
6254
6255 let (conversation_view, cx) =
6256 setup_conversation_view(StubAgentServer::new(connection), cx).await;
6257 add_to_workspace(conversation_view.clone(), cx);
6258
6259 cx.update(|_window, cx| {
6260 AgentSettings::override_global(
6261 AgentSettings {
6262 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
6263 ..AgentSettings::get_global(cx).clone()
6264 },
6265 cx,
6266 );
6267 });
6268
6269 let message_editor = message_editor(&conversation_view, cx);
6270 message_editor.update_in(cx, |editor, window, cx| {
6271 editor.set_text("Push changes", window, cx);
6272 });
6273
6274 active_thread(&conversation_view, cx)
6275 .update_in(cx, |view, window, cx| view.send(window, cx));
6276
6277 cx.run_until_parked();
6278
6279 // Use default granularity (last option = "Only this time")
6280 // Simulate clicking the Deny button
6281 active_thread(&conversation_view, cx).update_in(cx, |view, window, cx| {
6282 view.reject_once(&RejectOnce, window, cx)
6283 });
6284
6285 cx.run_until_parked();
6286
6287 // Verify tool call was rejected (no longer waiting for confirmation)
6288 conversation_view.read_with(cx, |conversation_view, cx| {
6289 let tool_call = conversation_view.pending_tool_call(cx);
6290 assert!(
6291 tool_call.is_none(),
6292 "Tool call should be rejected after Deny"
6293 );
6294 });
6295 }
6296
6297 #[gpui::test]
6298 async fn test_option_id_transformation_for_allow() {
6299 let permission_options = ToolPermissionContext::new(
6300 TerminalTool::NAME,
6301 vec!["cargo build --release".to_string()],
6302 )
6303 .build_permission_options();
6304
6305 let PermissionOptions::Dropdown(choices) = permission_options else {
6306 panic!("Expected dropdown permission options");
6307 };
6308
6309 let allow_ids: Vec<String> = choices
6310 .iter()
6311 .map(|choice| choice.allow.option_id.0.to_string())
6312 .collect();
6313
6314 assert!(allow_ids.contains(&"allow".to_string()));
6315 assert_eq!(
6316 allow_ids
6317 .iter()
6318 .filter(|id| *id == "always_allow:terminal")
6319 .count(),
6320 2,
6321 "Expected two always_allow:terminal IDs (one whole-tool, one pattern with sub_patterns)"
6322 );
6323 }
6324
6325 #[gpui::test]
6326 async fn test_option_id_transformation_for_deny() {
6327 let permission_options = ToolPermissionContext::new(
6328 TerminalTool::NAME,
6329 vec!["cargo build --release".to_string()],
6330 )
6331 .build_permission_options();
6332
6333 let PermissionOptions::Dropdown(choices) = permission_options else {
6334 panic!("Expected dropdown permission options");
6335 };
6336
6337 let deny_ids: Vec<String> = choices
6338 .iter()
6339 .map(|choice| choice.deny.option_id.0.to_string())
6340 .collect();
6341
6342 assert!(deny_ids.contains(&"deny".to_string()));
6343 assert_eq!(
6344 deny_ids
6345 .iter()
6346 .filter(|id| *id == "always_deny:terminal")
6347 .count(),
6348 2,
6349 "Expected two always_deny:terminal IDs (one whole-tool, one pattern with sub_patterns)"
6350 );
6351 }
6352
6353 #[gpui::test]
6354 async fn test_manually_editing_title_updates_acp_thread_title(cx: &mut TestAppContext) {
6355 init_test(cx);
6356
6357 let (conversation_view, cx) =
6358 setup_conversation_view(StubAgentServer::default_response(), cx).await;
6359 add_to_workspace(conversation_view.clone(), cx);
6360
6361 let active = active_thread(&conversation_view, cx);
6362 let title_editor = cx.read(|cx| active.read(cx).title_editor.clone());
6363 let thread = cx.read(|cx| active.read(cx).thread.clone());
6364
6365 title_editor.read_with(cx, |editor, cx| {
6366 assert!(!editor.read_only(cx));
6367 });
6368
6369 cx.focus(&conversation_view);
6370 cx.focus(&title_editor);
6371
6372 cx.dispatch_action(editor::actions::DeleteLine);
6373 cx.simulate_input("My Custom Title");
6374
6375 cx.run_until_parked();
6376
6377 title_editor.read_with(cx, |editor, cx| {
6378 assert_eq!(editor.text(cx), "My Custom Title");
6379 });
6380 thread.read_with(cx, |thread, _cx| {
6381 assert_eq!(thread.title(), Some("My Custom Title".into()));
6382 });
6383 }
6384
6385 #[gpui::test]
6386 async fn test_title_editor_is_read_only_when_set_title_unsupported(cx: &mut TestAppContext) {
6387 init_test(cx);
6388
6389 let (conversation_view, cx) =
6390 setup_conversation_view(StubAgentServer::new(ResumeOnlyAgentConnection), cx).await;
6391
6392 let active = active_thread(&conversation_view, cx);
6393 let title_editor = cx.read(|cx| active.read(cx).title_editor.clone());
6394
6395 title_editor.read_with(cx, |editor, cx| {
6396 assert!(
6397 editor.read_only(cx),
6398 "Title editor should be read-only when the connection does not support set_title"
6399 );
6400 });
6401 }
6402
6403 #[gpui::test]
6404 async fn test_max_tokens_error_is_rendered(cx: &mut TestAppContext) {
6405 init_test(cx);
6406
6407 let connection = StubAgentConnection::new();
6408
6409 let (conversation_view, cx) =
6410 setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
6411
6412 let message_editor = message_editor(&conversation_view, cx);
6413 message_editor.update_in(cx, |editor, window, cx| {
6414 editor.set_text("Some prompt", window, cx);
6415 });
6416 active_thread(&conversation_view, cx)
6417 .update_in(cx, |view, window, cx| view.send(window, cx));
6418
6419 let session_id = conversation_view.read_with(cx, |view, cx| {
6420 view.active_thread()
6421 .unwrap()
6422 .read(cx)
6423 .thread
6424 .read(cx)
6425 .session_id()
6426 .clone()
6427 });
6428
6429 cx.run_until_parked();
6430
6431 cx.update(|_, _cx| {
6432 connection.end_turn(session_id, acp::StopReason::MaxTokens);
6433 });
6434
6435 cx.run_until_parked();
6436
6437 conversation_view.read_with(cx, |conversation_view, cx| {
6438 let state = conversation_view.active_thread().unwrap();
6439 let error = &state.read(cx).thread_error;
6440 match error {
6441 Some(ThreadError::Other { message, .. }) => {
6442 assert!(
6443 message.contains("Maximum tokens reached"),
6444 "Expected 'Maximum tokens reached' error, got: {}",
6445 message
6446 );
6447 }
6448 other => panic!(
6449 "Expected ThreadError::Other with 'Maximum tokens reached', got: {:?}",
6450 other.is_some()
6451 ),
6452 }
6453 });
6454 }
6455
6456 fn create_test_acp_thread(
6457 parent_session_id: Option<acp::SessionId>,
6458 session_id: &str,
6459 connection: Rc<dyn AgentConnection>,
6460 project: Entity<Project>,
6461 cx: &mut App,
6462 ) -> Entity<AcpThread> {
6463 let action_log = cx.new(|_| ActionLog::new(project.clone()));
6464 cx.new(|cx| {
6465 AcpThread::new(
6466 parent_session_id,
6467 None,
6468 None,
6469 connection,
6470 project,
6471 action_log,
6472 acp::SessionId::new(session_id),
6473 watch::Receiver::constant(acp::PromptCapabilities::new()),
6474 cx,
6475 )
6476 })
6477 }
6478
6479 fn request_test_tool_authorization(
6480 thread: &Entity<AcpThread>,
6481 tool_call_id: &str,
6482 option_id: &str,
6483 cx: &mut TestAppContext,
6484 ) -> Task<acp_thread::RequestPermissionOutcome> {
6485 let tool_call_id = acp::ToolCallId::new(tool_call_id);
6486 let label = format!("Tool {tool_call_id}");
6487 let option_id = acp::PermissionOptionId::new(option_id);
6488 cx.update(|cx| {
6489 thread.update(cx, |thread, cx| {
6490 thread
6491 .request_tool_call_authorization(
6492 acp::ToolCall::new(tool_call_id, label)
6493 .kind(acp::ToolKind::Edit)
6494 .into(),
6495 PermissionOptions::Flat(vec![acp::PermissionOption::new(
6496 option_id,
6497 "Allow",
6498 acp::PermissionOptionKind::AllowOnce,
6499 )]),
6500 cx,
6501 )
6502 .unwrap()
6503 })
6504 })
6505 }
6506
6507 #[gpui::test]
6508 async fn test_conversation_multiple_tool_calls_fifo_ordering(cx: &mut TestAppContext) {
6509 init_test(cx);
6510
6511 let fs = FakeFs::new(cx.executor());
6512 let project = Project::test(fs, [], cx).await;
6513 let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
6514
6515 let (thread, conversation) = cx.update(|cx| {
6516 let thread =
6517 create_test_acp_thread(None, "session-1", connection.clone(), project.clone(), cx);
6518 let conversation = cx.new(|cx| {
6519 let mut conversation = Conversation::default();
6520 conversation.register_thread(thread.clone(), cx);
6521 conversation
6522 });
6523 (thread, conversation)
6524 });
6525
6526 let _task1 = request_test_tool_authorization(&thread, "tc-1", "allow-1", cx);
6527 let _task2 = request_test_tool_authorization(&thread, "tc-2", "allow-2", cx);
6528
6529 cx.read(|cx| {
6530 let session_id = acp::SessionId::new("session-1");
6531 let (_, tool_call_id, _) = conversation
6532 .read(cx)
6533 .pending_tool_call(&session_id, cx)
6534 .expect("Expected a pending tool call");
6535 assert_eq!(tool_call_id, acp::ToolCallId::new("tc-1"));
6536 });
6537
6538 cx.update(|cx| {
6539 conversation.update(cx, |conversation, cx| {
6540 conversation.authorize_tool_call(
6541 acp::SessionId::new("session-1"),
6542 acp::ToolCallId::new("tc-1"),
6543 SelectedPermissionOutcome::new(
6544 acp::PermissionOptionId::new("allow-1"),
6545 acp::PermissionOptionKind::AllowOnce,
6546 ),
6547 cx,
6548 );
6549 });
6550 });
6551
6552 cx.run_until_parked();
6553
6554 cx.read(|cx| {
6555 let session_id = acp::SessionId::new("session-1");
6556 let (_, tool_call_id, _) = conversation
6557 .read(cx)
6558 .pending_tool_call(&session_id, cx)
6559 .expect("Expected tc-2 to be pending after tc-1 was authorized");
6560 assert_eq!(tool_call_id, acp::ToolCallId::new("tc-2"));
6561 });
6562
6563 cx.update(|cx| {
6564 conversation.update(cx, |conversation, cx| {
6565 conversation.authorize_tool_call(
6566 acp::SessionId::new("session-1"),
6567 acp::ToolCallId::new("tc-2"),
6568 SelectedPermissionOutcome::new(
6569 acp::PermissionOptionId::new("allow-2"),
6570 acp::PermissionOptionKind::AllowOnce,
6571 ),
6572 cx,
6573 );
6574 });
6575 });
6576
6577 cx.run_until_parked();
6578
6579 cx.read(|cx| {
6580 let session_id = acp::SessionId::new("session-1");
6581 assert!(
6582 conversation
6583 .read(cx)
6584 .pending_tool_call(&session_id, cx)
6585 .is_none(),
6586 "Expected no pending tool calls after both were authorized"
6587 );
6588 });
6589 }
6590
6591 #[gpui::test]
6592 async fn test_conversation_subagent_scoped_pending_tool_call(cx: &mut TestAppContext) {
6593 init_test(cx);
6594
6595 let fs = FakeFs::new(cx.executor());
6596 let project = Project::test(fs, [], cx).await;
6597 let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
6598
6599 let (parent_thread, subagent_thread, conversation) = cx.update(|cx| {
6600 let parent_thread =
6601 create_test_acp_thread(None, "parent", connection.clone(), project.clone(), cx);
6602 let subagent_thread = create_test_acp_thread(
6603 Some(acp::SessionId::new("parent")),
6604 "subagent",
6605 connection.clone(),
6606 project.clone(),
6607 cx,
6608 );
6609 let conversation = cx.new(|cx| {
6610 let mut conversation = Conversation::default();
6611 conversation.register_thread(parent_thread.clone(), cx);
6612 conversation.register_thread(subagent_thread.clone(), cx);
6613 conversation
6614 });
6615 (parent_thread, subagent_thread, conversation)
6616 });
6617
6618 let _parent_task =
6619 request_test_tool_authorization(&parent_thread, "parent-tc", "allow-parent", cx);
6620 let _subagent_task =
6621 request_test_tool_authorization(&subagent_thread, "subagent-tc", "allow-subagent", cx);
6622
6623 // Querying with the subagent's session ID returns only the
6624 // subagent's own tool call (subagent path is scoped to its session)
6625 cx.read(|cx| {
6626 let subagent_id = acp::SessionId::new("subagent");
6627 let (session_id, tool_call_id, _) = conversation
6628 .read(cx)
6629 .pending_tool_call(&subagent_id, cx)
6630 .expect("Expected subagent's pending tool call");
6631 assert_eq!(session_id, acp::SessionId::new("subagent"));
6632 assert_eq!(tool_call_id, acp::ToolCallId::new("subagent-tc"));
6633 });
6634
6635 // Querying with the parent's session ID returns the first pending
6636 // request in FIFO order across all sessions
6637 cx.read(|cx| {
6638 let parent_id = acp::SessionId::new("parent");
6639 let (session_id, tool_call_id, _) = conversation
6640 .read(cx)
6641 .pending_tool_call(&parent_id, cx)
6642 .expect("Expected a pending tool call from parent query");
6643 assert_eq!(session_id, acp::SessionId::new("parent"));
6644 assert_eq!(tool_call_id, acp::ToolCallId::new("parent-tc"));
6645 });
6646 }
6647
6648 #[gpui::test]
6649 async fn test_conversation_parent_pending_tool_call_returns_first_across_threads(
6650 cx: &mut TestAppContext,
6651 ) {
6652 init_test(cx);
6653
6654 let fs = FakeFs::new(cx.executor());
6655 let project = Project::test(fs, [], cx).await;
6656 let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
6657
6658 let (thread_a, thread_b, conversation) = cx.update(|cx| {
6659 let thread_a =
6660 create_test_acp_thread(None, "thread-a", connection.clone(), project.clone(), cx);
6661 let thread_b =
6662 create_test_acp_thread(None, "thread-b", connection.clone(), project.clone(), cx);
6663 let conversation = cx.new(|cx| {
6664 let mut conversation = Conversation::default();
6665 conversation.register_thread(thread_a.clone(), cx);
6666 conversation.register_thread(thread_b.clone(), cx);
6667 conversation
6668 });
6669 (thread_a, thread_b, conversation)
6670 });
6671
6672 let _task_a = request_test_tool_authorization(&thread_a, "tc-a", "allow-a", cx);
6673 let _task_b = request_test_tool_authorization(&thread_b, "tc-b", "allow-b", cx);
6674
6675 // Both threads are non-subagent, so pending_tool_call always returns
6676 // the first entry from permission_requests (FIFO across all sessions)
6677 cx.read(|cx| {
6678 let session_a = acp::SessionId::new("thread-a");
6679 let (session_id, tool_call_id, _) = conversation
6680 .read(cx)
6681 .pending_tool_call(&session_a, cx)
6682 .expect("Expected a pending tool call");
6683 assert_eq!(session_id, acp::SessionId::new("thread-a"));
6684 assert_eq!(tool_call_id, acp::ToolCallId::new("tc-a"));
6685 });
6686
6687 // Querying with thread-b also returns thread-a's tool call,
6688 // because non-subagent queries always use permission_requests.first()
6689 cx.read(|cx| {
6690 let session_b = acp::SessionId::new("thread-b");
6691 let (session_id, tool_call_id, _) = conversation
6692 .read(cx)
6693 .pending_tool_call(&session_b, cx)
6694 .expect("Expected a pending tool call from thread-b query");
6695 assert_eq!(
6696 session_id,
6697 acp::SessionId::new("thread-a"),
6698 "Non-subagent queries always return the first pending request in FIFO order"
6699 );
6700 assert_eq!(tool_call_id, acp::ToolCallId::new("tc-a"));
6701 });
6702
6703 // After authorizing thread-a's tool call, thread-b's becomes first
6704 cx.update(|cx| {
6705 conversation.update(cx, |conversation, cx| {
6706 conversation.authorize_tool_call(
6707 acp::SessionId::new("thread-a"),
6708 acp::ToolCallId::new("tc-a"),
6709 SelectedPermissionOutcome::new(
6710 acp::PermissionOptionId::new("allow-a"),
6711 acp::PermissionOptionKind::AllowOnce,
6712 ),
6713 cx,
6714 );
6715 });
6716 });
6717
6718 cx.run_until_parked();
6719
6720 cx.read(|cx| {
6721 let session_b = acp::SessionId::new("thread-b");
6722 let (session_id, tool_call_id, _) = conversation
6723 .read(cx)
6724 .pending_tool_call(&session_b, cx)
6725 .expect("Expected thread-b's tool call after thread-a's was authorized");
6726 assert_eq!(session_id, acp::SessionId::new("thread-b"));
6727 assert_eq!(tool_call_id, acp::ToolCallId::new("tc-b"));
6728 });
6729 }
6730
6731 #[gpui::test]
6732 async fn test_move_queued_message_to_empty_main_editor(cx: &mut TestAppContext) {
6733 init_test(cx);
6734
6735 let (conversation_view, cx) =
6736 setup_conversation_view(StubAgentServer::default_response(), cx).await;
6737
6738 // Add a plain-text message to the queue directly.
6739 active_thread(&conversation_view, cx).update_in(cx, |thread, window, cx| {
6740 thread.add_to_queue(
6741 vec![acp::ContentBlock::Text(acp::TextContent::new(
6742 "queued message".to_string(),
6743 ))],
6744 vec![],
6745 cx,
6746 );
6747 // Main editor must be empty for this path — it is by default, but
6748 // assert to make the precondition explicit.
6749 assert!(thread.message_editor.read(cx).is_empty(cx));
6750 thread.move_queued_message_to_main_editor(0, None, None, window, cx);
6751 });
6752
6753 cx.run_until_parked();
6754
6755 // Queue should now be empty.
6756 let queue_len = active_thread(&conversation_view, cx)
6757 .read_with(cx, |thread, _cx| thread.local_queued_messages.len());
6758 assert_eq!(queue_len, 0, "Queue should be empty after move");
6759
6760 // Main editor should contain the queued message text.
6761 let text = message_editor(&conversation_view, cx).update(cx, |editor, cx| editor.text(cx));
6762 assert_eq!(
6763 text, "queued message",
6764 "Main editor should contain the moved queued message"
6765 );
6766 }
6767
6768 #[gpui::test]
6769 async fn test_move_queued_message_to_non_empty_main_editor(cx: &mut TestAppContext) {
6770 init_test(cx);
6771
6772 let (conversation_view, cx) =
6773 setup_conversation_view(StubAgentServer::default_response(), cx).await;
6774
6775 // Seed the main editor with existing content.
6776 message_editor(&conversation_view, cx).update_in(cx, |editor, window, cx| {
6777 editor.set_message(
6778 vec![acp::ContentBlock::Text(acp::TextContent::new(
6779 "existing content".to_string(),
6780 ))],
6781 window,
6782 cx,
6783 );
6784 });
6785
6786 // Add a plain-text message to the queue.
6787 active_thread(&conversation_view, cx).update_in(cx, |thread, window, cx| {
6788 thread.add_to_queue(
6789 vec![acp::ContentBlock::Text(acp::TextContent::new(
6790 "queued message".to_string(),
6791 ))],
6792 vec![],
6793 cx,
6794 );
6795 thread.move_queued_message_to_main_editor(0, None, None, window, cx);
6796 });
6797
6798 cx.run_until_parked();
6799
6800 // Queue should now be empty.
6801 let queue_len = active_thread(&conversation_view, cx)
6802 .read_with(cx, |thread, _cx| thread.local_queued_messages.len());
6803 assert_eq!(queue_len, 0, "Queue should be empty after move");
6804
6805 // Main editor should contain existing content + separator + queued content.
6806 let text = message_editor(&conversation_view, cx).update(cx, |editor, cx| editor.text(cx));
6807 assert_eq!(
6808 text, "existing content\n\nqueued message",
6809 "Main editor should have existing content and queued message separated by two newlines"
6810 );
6811 }
6812
6813 #[gpui::test]
6814 async fn test_close_all_sessions_skips_when_unsupported(cx: &mut TestAppContext) {
6815 init_test(cx);
6816
6817 let fs = FakeFs::new(cx.executor());
6818 let project = Project::test(fs, [], cx).await;
6819 let (multi_workspace, cx) =
6820 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6821 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
6822
6823 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
6824 let connection_store =
6825 cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
6826
6827 // StubAgentConnection defaults to supports_close_session() -> false
6828 let conversation_view = cx.update(|window, cx| {
6829 cx.new(|cx| {
6830 ConversationView::new(
6831 Rc::new(StubAgentServer::default_response()),
6832 connection_store,
6833 Agent::Custom { id: "Test".into() },
6834 None,
6835 None,
6836 None,
6837 None,
6838 workspace.downgrade(),
6839 project,
6840 Some(thread_store),
6841 None,
6842 window,
6843 cx,
6844 )
6845 })
6846 });
6847
6848 cx.run_until_parked();
6849
6850 conversation_view.read_with(cx, |view, _cx| {
6851 let connected = view.as_connected().expect("Should be connected");
6852 assert!(
6853 !connected.threads.is_empty(),
6854 "There should be at least one thread"
6855 );
6856 assert!(
6857 !connected.connection.supports_close_session(),
6858 "StubAgentConnection should not support close"
6859 );
6860 });
6861
6862 conversation_view
6863 .update(cx, |view, cx| {
6864 view.as_connected()
6865 .expect("Should be connected")
6866 .close_all_sessions(cx)
6867 })
6868 .await;
6869 }
6870
6871 #[gpui::test]
6872 async fn test_close_all_sessions_calls_close_when_supported(cx: &mut TestAppContext) {
6873 init_test(cx);
6874
6875 let (conversation_view, cx) =
6876 setup_conversation_view(StubAgentServer::new(CloseCapableConnection::new()), cx).await;
6877
6878 cx.run_until_parked();
6879
6880 let close_capable = conversation_view.read_with(cx, |view, _cx| {
6881 let connected = view.as_connected().expect("Should be connected");
6882 assert!(
6883 !connected.threads.is_empty(),
6884 "There should be at least one thread"
6885 );
6886 assert!(
6887 connected.connection.supports_close_session(),
6888 "CloseCapableConnection should support close"
6889 );
6890 connected
6891 .connection
6892 .clone()
6893 .into_any()
6894 .downcast::<CloseCapableConnection>()
6895 .expect("Should be CloseCapableConnection")
6896 });
6897
6898 conversation_view
6899 .update(cx, |view, cx| {
6900 view.as_connected()
6901 .expect("Should be connected")
6902 .close_all_sessions(cx)
6903 })
6904 .await;
6905
6906 let closed_count = close_capable.closed_sessions.lock().len();
6907 assert!(
6908 closed_count > 0,
6909 "close_session should have been called for each thread"
6910 );
6911 }
6912
6913 #[gpui::test]
6914 async fn test_close_session_returns_error_when_unsupported(cx: &mut TestAppContext) {
6915 init_test(cx);
6916
6917 let (conversation_view, cx) =
6918 setup_conversation_view(StubAgentServer::default_response(), cx).await;
6919
6920 cx.run_until_parked();
6921
6922 let result = conversation_view
6923 .update(cx, |view, cx| {
6924 let connected = view.as_connected().expect("Should be connected");
6925 assert!(
6926 !connected.connection.supports_close_session(),
6927 "StubAgentConnection should not support close"
6928 );
6929 let session_id = connected
6930 .threads
6931 .keys()
6932 .next()
6933 .expect("Should have at least one thread")
6934 .clone();
6935 connected.connection.clone().close_session(&session_id, cx)
6936 })
6937 .await;
6938
6939 assert!(
6940 result.is_err(),
6941 "close_session should return an error when close is not supported"
6942 );
6943 assert!(
6944 result.unwrap_err().to_string().contains("not supported"),
6945 "Error message should indicate that closing is not supported"
6946 );
6947 }
6948
6949 #[derive(Clone)]
6950 struct CloseCapableConnection {
6951 closed_sessions: Arc<Mutex<Vec<acp::SessionId>>>,
6952 }
6953
6954 impl CloseCapableConnection {
6955 fn new() -> Self {
6956 Self {
6957 closed_sessions: Arc::new(Mutex::new(Vec::new())),
6958 }
6959 }
6960 }
6961
6962 impl AgentConnection for CloseCapableConnection {
6963 fn agent_id(&self) -> AgentId {
6964 AgentId::new("close-capable")
6965 }
6966
6967 fn telemetry_id(&self) -> SharedString {
6968 "close-capable".into()
6969 }
6970
6971 fn new_session(
6972 self: Rc<Self>,
6973 project: Entity<Project>,
6974 work_dirs: PathList,
6975 cx: &mut gpui::App,
6976 ) -> Task<gpui::Result<Entity<AcpThread>>> {
6977 let action_log = cx.new(|_| ActionLog::new(project.clone()));
6978 let thread = cx.new(|cx| {
6979 AcpThread::new(
6980 None,
6981 Some("CloseCapableConnection".into()),
6982 Some(work_dirs),
6983 self,
6984 project,
6985 action_log,
6986 SessionId::new("close-capable-session"),
6987 watch::Receiver::constant(
6988 acp::PromptCapabilities::new()
6989 .image(true)
6990 .audio(true)
6991 .embedded_context(true),
6992 ),
6993 cx,
6994 )
6995 });
6996 Task::ready(Ok(thread))
6997 }
6998
6999 fn supports_close_session(&self) -> bool {
7000 true
7001 }
7002
7003 fn close_session(
7004 self: Rc<Self>,
7005 session_id: &acp::SessionId,
7006 _cx: &mut App,
7007 ) -> Task<Result<()>> {
7008 self.closed_sessions.lock().push(session_id.clone());
7009 Task::ready(Ok(()))
7010 }
7011
7012 fn auth_methods(&self) -> &[acp::AuthMethod] {
7013 &[]
7014 }
7015
7016 fn authenticate(
7017 &self,
7018 _method_id: acp::AuthMethodId,
7019 _cx: &mut App,
7020 ) -> Task<gpui::Result<()>> {
7021 Task::ready(Ok(()))
7022 }
7023
7024 fn prompt(
7025 &self,
7026 _id: Option<acp_thread::UserMessageId>,
7027 _params: acp::PromptRequest,
7028 _cx: &mut App,
7029 ) -> Task<gpui::Result<acp::PromptResponse>> {
7030 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
7031 }
7032
7033 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
7034
7035 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
7036 self
7037 }
7038 }
7039}