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