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