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