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