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