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};
9use agent::{NativeAgentServer, NativeAgentSessionList, SharedThread, ThreadStore};
10use agent_client_protocol::{self as acp, PromptCapabilities};
11use agent_servers::{AgentServer, AgentServerDelegate};
12use agent_settings::{AgentProfileId, AgentSettings};
13use anyhow::{Result, anyhow};
14use arrayvec::ArrayVec;
15use audio::{Audio, Sound};
16use buffer_diff::BufferDiff;
17use client::zed_urls;
18use collections::{HashMap, HashSet};
19use editor::scroll::Autoscroll;
20use editor::{
21 Editor, EditorEvent, EditorMode, MultiBuffer, PathKey, SelectionEffects, SizingBehavior,
22};
23use feature_flags::{
24 AgentSharingFeatureFlag, AgentV2FeatureFlag, CloudThinkingToggleFeatureFlag,
25 FeatureFlagAppExt as _, UserSlashCommandsFeatureFlag,
26};
27use file_icons::FileIcons;
28use fs::Fs;
29use futures::FutureExt as _;
30use gpui::{
31 Action, Animation, AnimationExt, AnyView, App, BorderStyle, ClickEvent, ClipboardItem,
32 CursorStyle, EdgesRefinement, ElementId, Empty, Entity, FocusHandle, Focusable, Hsla, Length,
33 ListOffset, ListState, ObjectFit, PlatformDisplay, ScrollHandle, SharedString, StyleRefinement,
34 Subscription, Task, TextStyle, TextStyleRefinement, UnderlineStyle, WeakEntity, Window,
35 WindowHandle, div, ease_in_out, img, linear_color_stop, linear_gradient, list, point,
36 pulsating_between,
37};
38use language::Buffer;
39use language_model::LanguageModelRegistry;
40use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
41use project::{AgentServerStore, ExternalAgentServerName, Project, ProjectEntryId};
42use prompt_store::{PromptId, PromptStore};
43use rope::Point;
44use settings::{NotifyWhenAgentWaiting, Settings as _, SettingsStore};
45use std::cell::RefCell;
46use std::path::Path;
47use std::sync::Arc;
48use std::time::Instant;
49use std::{collections::BTreeMap, rc::Rc, time::Duration};
50use terminal_view::terminal_panel::TerminalPanel;
51use text::{Anchor, ToPoint as _};
52use theme::{AgentFontSize, ThemeSettings};
53use ui::{
54 Callout, CommonAnimationExt, ContextMenu, ContextMenuEntry, CopyButton, DecoratedIcon,
55 DiffStat, Disclosure, Divider, DividerColor, IconButtonShape, IconDecoration,
56 IconDecorationKind, KeyBinding, PopoverMenu, PopoverMenuHandle, SpinnerLabel, TintColor,
57 Tooltip, WithScrollbar, prelude::*, right_click_menu,
58};
59use util::defer;
60use util::{ResultExt, size::format_file_size, time::duration_alt_display};
61use workspace::{
62 CollaboratorId, NewTerminal, OpenOptions, Toast, Workspace, notifications::NotificationId,
63};
64use zed_actions::agent::{Chat, ToggleModelSelector};
65use zed_actions::assistant::OpenRulesLibrary;
66
67use super::config_options::ConfigOptionsView;
68use super::entry_view_state::EntryViewState;
69use super::thread_history::AcpThreadHistory;
70use crate::acp::AcpModelSelectorPopover;
71use crate::acp::ModeSelector;
72use crate::acp::entry_view_state::{EntryViewEvent, ViewEvent};
73use crate::acp::message_editor::{MessageEditor, MessageEditorEvent};
74use crate::agent_diff::AgentDiff;
75use crate::profile_selector::{ProfileProvider, ProfileSelector};
76use crate::ui::{AgentNotification, AgentNotificationEvent};
77use crate::user_slash_command::{
78 self, CommandLoadError, SlashCommandRegistry, SlashCommandRegistryEvent, UserSlashCommand,
79};
80use crate::{
81 AgentDiffPane, AgentPanel, AllowAlways, AllowOnce, AuthorizeToolCall, ClearMessageQueue,
82 CycleFavoriteModels, CycleModeSelector, EditFirstQueuedMessage, ExpandMessageEditor, Follow,
83 KeepAll, NewThread, OpenAddContextMenu, OpenAgentDiff, OpenHistory, RejectAll, RejectOnce,
84 RemoveFirstQueuedMessage, SelectPermissionGranularity, SendImmediately, SendNextQueuedMessage,
85 ToggleProfileSelector,
86};
87
88const STOPWATCH_THRESHOLD: Duration = Duration::from_secs(30);
89const TOKEN_THRESHOLD: u64 = 250;
90
91pub struct QueuedMessage {
92 pub content: Vec<acp::ContentBlock>,
93 pub tracked_buffers: Vec<Entity<Buffer>>,
94}
95
96#[derive(Copy, Clone, Debug, PartialEq, Eq)]
97enum ThreadFeedback {
98 Positive,
99 Negative,
100}
101
102#[derive(Debug)]
103enum ThreadError {
104 PaymentRequired,
105 Refusal,
106 AuthenticationRequired(SharedString),
107 Other {
108 message: SharedString,
109 acp_error_code: Option<SharedString>,
110 },
111}
112
113impl ThreadError {
114 fn from_err(error: anyhow::Error, agent: &Rc<dyn AgentServer>) -> Self {
115 if error.is::<language_model::PaymentRequiredError>() {
116 Self::PaymentRequired
117 } else if let Some(acp_error) = error.downcast_ref::<acp::Error>()
118 && acp_error.code == acp::ErrorCode::AuthRequired
119 {
120 Self::AuthenticationRequired(acp_error.message.clone().into())
121 } else {
122 let message: SharedString = format!("{:#}", error).into();
123
124 // Extract ACP error code if available
125 let acp_error_code = error
126 .downcast_ref::<acp::Error>()
127 .map(|acp_error| SharedString::from(acp_error.code.to_string()));
128
129 // TODO: we should have Gemini return better errors here.
130 if agent.clone().downcast::<agent_servers::Gemini>().is_some()
131 && message.contains("Could not load the default credentials")
132 || message.contains("API key not valid")
133 || message.contains("Request had invalid authentication credentials")
134 {
135 Self::AuthenticationRequired(message)
136 } else {
137 Self::Other {
138 message,
139 acp_error_code,
140 }
141 }
142 }
143 }
144}
145
146impl ProfileProvider for Entity<agent::Thread> {
147 fn profile_id(&self, cx: &App) -> AgentProfileId {
148 self.read(cx).profile().clone()
149 }
150
151 fn set_profile(&self, profile_id: AgentProfileId, cx: &mut App) {
152 self.update(cx, |thread, cx| {
153 // Apply the profile and let the thread swap to its default model.
154 thread.set_profile(profile_id, cx);
155 });
156 }
157
158 fn profiles_supported(&self, cx: &App) -> bool {
159 self.read(cx)
160 .model()
161 .is_some_and(|model| model.supports_tools())
162 }
163}
164
165#[derive(Default)]
166struct ThreadFeedbackState {
167 feedback: Option<ThreadFeedback>,
168 comments_editor: Option<Entity<Editor>>,
169}
170
171impl ThreadFeedbackState {
172 pub fn submit(
173 &mut self,
174 thread: Entity<AcpThread>,
175 feedback: ThreadFeedback,
176 window: &mut Window,
177 cx: &mut App,
178 ) {
179 let Some(telemetry) = thread.read(cx).connection().telemetry() else {
180 return;
181 };
182
183 if self.feedback == Some(feedback) {
184 return;
185 }
186
187 self.feedback = Some(feedback);
188 match feedback {
189 ThreadFeedback::Positive => {
190 self.comments_editor = None;
191 }
192 ThreadFeedback::Negative => {
193 self.comments_editor = Some(Self::build_feedback_comments_editor(window, cx));
194 }
195 }
196 let session_id = thread.read(cx).session_id().clone();
197 let agent_telemetry_id = thread.read(cx).connection().telemetry_id();
198 let task = telemetry.thread_data(&session_id, cx);
199 let rating = match feedback {
200 ThreadFeedback::Positive => "positive",
201 ThreadFeedback::Negative => "negative",
202 };
203 cx.background_spawn(async move {
204 let thread = task.await?;
205 telemetry::event!(
206 "Agent Thread Rated",
207 agent = agent_telemetry_id,
208 session_id = session_id,
209 rating = rating,
210 thread = thread
211 );
212 anyhow::Ok(())
213 })
214 .detach_and_log_err(cx);
215 }
216
217 pub fn submit_comments(&mut self, thread: Entity<AcpThread>, cx: &mut App) {
218 let Some(telemetry) = thread.read(cx).connection().telemetry() else {
219 return;
220 };
221
222 let Some(comments) = self
223 .comments_editor
224 .as_ref()
225 .map(|editor| editor.read(cx).text(cx))
226 .filter(|text| !text.trim().is_empty())
227 else {
228 return;
229 };
230
231 self.comments_editor.take();
232
233 let session_id = thread.read(cx).session_id().clone();
234 let agent_telemetry_id = thread.read(cx).connection().telemetry_id();
235 let task = telemetry.thread_data(&session_id, cx);
236 cx.background_spawn(async move {
237 let thread = task.await?;
238 telemetry::event!(
239 "Agent Thread Feedback Comments",
240 agent = agent_telemetry_id,
241 session_id = session_id,
242 comments = comments,
243 thread = thread
244 );
245 anyhow::Ok(())
246 })
247 .detach_and_log_err(cx);
248 }
249
250 pub fn clear(&mut self) {
251 *self = Self::default()
252 }
253
254 pub fn dismiss_comments(&mut self) {
255 self.comments_editor.take();
256 }
257
258 fn build_feedback_comments_editor(window: &mut Window, cx: &mut App) -> Entity<Editor> {
259 let buffer = cx.new(|cx| {
260 let empty_string = String::new();
261 MultiBuffer::singleton(cx.new(|cx| Buffer::local(empty_string, cx)), cx)
262 });
263
264 let editor = cx.new(|cx| {
265 let mut editor = Editor::new(
266 editor::EditorMode::AutoHeight {
267 min_lines: 1,
268 max_lines: Some(4),
269 },
270 buffer,
271 None,
272 window,
273 cx,
274 );
275 editor.set_placeholder_text(
276 "What went wrong? Share your feedback so we can improve.",
277 window,
278 cx,
279 );
280 editor
281 });
282
283 editor.read(cx).focus_handle(cx).focus(window, cx);
284 editor
285 }
286}
287
288#[derive(Default, Clone, Copy)]
289struct DiffStats {
290 lines_added: u32,
291 lines_removed: u32,
292}
293
294impl DiffStats {
295 fn single_file(buffer: &Buffer, diff: &BufferDiff, cx: &App) -> Self {
296 let mut stats = DiffStats::default();
297 let diff_snapshot = diff.snapshot(cx);
298 let buffer_snapshot = buffer.snapshot();
299 let base_text = diff_snapshot.base_text();
300
301 for hunk in diff_snapshot.hunks(&buffer_snapshot) {
302 let added_rows = hunk.range.end.row.saturating_sub(hunk.range.start.row);
303 stats.lines_added += added_rows;
304
305 let base_start = hunk.diff_base_byte_range.start.to_point(base_text).row;
306 let base_end = hunk.diff_base_byte_range.end.to_point(base_text).row;
307 let removed_rows = base_end.saturating_sub(base_start);
308 stats.lines_removed += removed_rows;
309 }
310
311 stats
312 }
313
314 fn all_files(changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>, cx: &App) -> Self {
315 let mut total = DiffStats::default();
316 for (buffer, diff) in changed_buffers {
317 let stats = DiffStats::single_file(buffer.read(cx), diff.read(cx), cx);
318 total.lines_added += stats.lines_added;
319 total.lines_removed += stats.lines_removed;
320 }
321 total
322 }
323}
324
325pub struct AcpThreadView {
326 agent: Rc<dyn AgentServer>,
327 agent_server_store: Entity<AgentServerStore>,
328 workspace: WeakEntity<Workspace>,
329 project: Entity<Project>,
330 thread_state: ThreadState,
331 permission_dropdown_handle: PopoverMenuHandle<ContextMenu>,
332 /// Tracks the selected granularity index for each tool call's permission dropdown.
333 /// The index corresponds to the position in the allow_options list.
334 /// Default is the last option (index pointing to "Only this time").
335 selected_permission_granularity: HashMap<acp::ToolCallId, usize>,
336 login: Option<task::SpawnInTerminal>,
337 recent_history_entries: Vec<AgentSessionInfo>,
338 history: Entity<AcpThreadHistory>,
339 _history_subscription: Subscription,
340 hovered_recent_history_item: Option<usize>,
341 entry_view_state: Entity<EntryViewState>,
342 message_editor: Entity<MessageEditor>,
343 focus_handle: FocusHandle,
344 model_selector: Option<Entity<AcpModelSelectorPopover>>,
345 config_options_view: Option<Entity<ConfigOptionsView>>,
346 profile_selector: Option<Entity<ProfileSelector>>,
347 notifications: Vec<WindowHandle<AgentNotification>>,
348 notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
349 thread_retry_status: Option<RetryStatus>,
350 thread_error: Option<ThreadError>,
351 thread_error_markdown: Option<Entity<Markdown>>,
352 command_load_errors: Vec<CommandLoadError>,
353 command_load_errors_dismissed: bool,
354 slash_command_registry: Option<Entity<SlashCommandRegistry>>,
355 token_limit_callout_dismissed: bool,
356 thread_feedback: ThreadFeedbackState,
357 list_state: ListState,
358 auth_task: Option<Task<()>>,
359 /// Tracks which tool calls have their content/output expanded.
360 /// Used for showing/hiding tool call results, terminal output, etc.
361 expanded_tool_calls: HashSet<acp::ToolCallId>,
362 expanded_tool_call_raw_inputs: HashSet<acp::ToolCallId>,
363 expanded_thinking_blocks: HashSet<(usize, usize)>,
364 expanded_subagents: HashSet<acp::SessionId>,
365 subagent_scroll_handles: RefCell<HashMap<acp::SessionId, ScrollHandle>>,
366 edits_expanded: bool,
367 plan_expanded: bool,
368 queue_expanded: bool,
369 editor_expanded: bool,
370 should_be_following: bool,
371 editing_message: Option<usize>,
372 local_queued_messages: Vec<QueuedMessage>,
373 queued_message_editors: Vec<Entity<MessageEditor>>,
374 queued_message_editor_subscriptions: Vec<Subscription>,
375 last_synced_queue_length: usize,
376 discarded_partial_edits: HashSet<acp::ToolCallId>,
377 prompt_capabilities: Rc<RefCell<PromptCapabilities>>,
378 available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
379 cached_user_commands: Rc<RefCell<HashMap<String, UserSlashCommand>>>,
380 cached_user_command_errors: Rc<RefCell<Vec<CommandLoadError>>>,
381 is_loading_contents: bool,
382 new_server_version_available: Option<SharedString>,
383 resume_thread_metadata: Option<AgentSessionInfo>,
384 resumed_without_history: bool,
385 _cancel_task: Option<Task<()>>,
386 _subscriptions: [Subscription; 5],
387 show_codex_windows_warning: bool,
388 in_flight_prompt: Option<Vec<acp::ContentBlock>>,
389 skip_queue_processing_count: usize,
390 user_interrupted_generation: bool,
391 can_fast_track_queue: bool,
392 turn_tokens: Option<u64>,
393 last_turn_tokens: Option<u64>,
394 turn_started_at: Option<Instant>,
395 last_turn_duration: Option<Duration>,
396 turn_generation: usize,
397 _turn_timer_task: Option<Task<()>>,
398 hovered_edited_file_buttons: Option<usize>,
399 add_context_menu_handle: PopoverMenuHandle<ContextMenu>,
400}
401
402enum ThreadState {
403 Loading(Entity<LoadingView>),
404 Ready {
405 thread: Entity<AcpThread>,
406 title_editor: Option<Entity<Editor>>,
407 mode_selector: Option<Entity<ModeSelector>>,
408 _subscriptions: Vec<Subscription>,
409 },
410 LoadError(LoadError),
411 Unauthenticated {
412 connection: Rc<dyn AgentConnection>,
413 description: Option<Entity<Markdown>>,
414 configuration_view: Option<AnyView>,
415 pending_auth_method: Option<acp::AuthMethodId>,
416 _subscription: Option<Subscription>,
417 },
418}
419
420struct LoadingView {
421 title: SharedString,
422 _load_task: Task<()>,
423 _update_title_task: Task<anyhow::Result<()>>,
424}
425
426impl AcpThreadView {
427 pub fn new(
428 agent: Rc<dyn AgentServer>,
429 resume_thread: Option<AgentSessionInfo>,
430 summarize_thread: Option<AgentSessionInfo>,
431 workspace: WeakEntity<Workspace>,
432 project: Entity<Project>,
433 thread_store: Option<Entity<ThreadStore>>,
434 prompt_store: Option<Entity<PromptStore>>,
435 history: Entity<AcpThreadHistory>,
436 window: &mut Window,
437 cx: &mut Context<Self>,
438 ) -> Self {
439 let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
440 let available_commands = Rc::new(RefCell::new(vec![]));
441 let cached_user_commands = Rc::new(RefCell::new(collections::HashMap::default()));
442 let cached_user_command_errors = Rc::new(RefCell::new(Vec::new()));
443 let mut command_load_errors = Vec::new();
444
445 let agent_server_store = project.read(cx).agent_server_store().clone();
446 let agent_display_name = agent_server_store
447 .read(cx)
448 .agent_display_name(&ExternalAgentServerName(agent.name()))
449 .unwrap_or_else(|| agent.name());
450
451 let placeholder = placeholder_text(agent_display_name.as_ref(), false);
452
453 let message_editor = cx.new(|cx| {
454 let mut editor = MessageEditor::new_with_cache(
455 workspace.clone(),
456 project.downgrade(),
457 thread_store.clone(),
458 history.downgrade(),
459 prompt_store.clone(),
460 prompt_capabilities.clone(),
461 available_commands.clone(),
462 cached_user_commands.clone(),
463 cached_user_command_errors.clone(),
464 agent.name(),
465 &placeholder,
466 editor::EditorMode::AutoHeight {
467 min_lines: AgentSettings::get_global(cx).message_editor_min_lines,
468 max_lines: Some(AgentSettings::get_global(cx).set_message_editor_max_lines()),
469 },
470 window,
471 cx,
472 );
473 if let Some(entry) = summarize_thread {
474 editor.insert_thread_summary(entry, window, cx);
475 }
476 editor
477 });
478
479 let list_state = ListState::new(0, gpui::ListAlignment::Bottom, px(2048.0));
480
481 let entry_view_state = cx.new(|_| {
482 EntryViewState::new(
483 workspace.clone(),
484 project.downgrade(),
485 thread_store.clone(),
486 history.downgrade(),
487 prompt_store.clone(),
488 prompt_capabilities.clone(),
489 available_commands.clone(),
490 cached_user_commands.clone(),
491 cached_user_command_errors.clone(),
492 agent.name(),
493 )
494 });
495
496 let subscriptions = [
497 cx.observe_global_in::<SettingsStore>(window, Self::agent_ui_font_size_changed),
498 cx.observe_global_in::<AgentFontSize>(window, Self::agent_ui_font_size_changed),
499 cx.subscribe_in(&message_editor, window, Self::handle_message_editor_event),
500 cx.subscribe_in(&entry_view_state, window, Self::handle_entry_view_event),
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 for window in this.notifications.drain(..) {
510 window
511 .update(cx, |_, window, _| {
512 window.remove_window();
513 })
514 .ok();
515 }
516 })
517 .detach();
518
519 let show_codex_windows_warning = cfg!(windows)
520 && project.read(cx).is_local()
521 && agent.clone().downcast::<agent_servers::Codex>().is_some();
522
523 // Create SlashCommandRegistry to cache user-defined slash commands and watch for changes
524 let slash_command_registry = if cx.has_flag::<UserSlashCommandsFeatureFlag>() {
525 let fs = project.read(cx).fs().clone();
526 let worktree_roots: Vec<std::path::PathBuf> = project
527 .read(cx)
528 .visible_worktrees(cx)
529 .map(|worktree| worktree.read(cx).abs_path().to_path_buf())
530 .collect();
531 let registry = cx.new(|cx| SlashCommandRegistry::new(fs, worktree_roots, cx));
532
533 // Subscribe to registry changes to update error display and cached commands
534 cx.subscribe(®istry, move |this, registry, event, cx| match event {
535 SlashCommandRegistryEvent::CommandsChanged => {
536 this.refresh_cached_user_commands_from_registry(®istry, cx);
537 }
538 })
539 .detach();
540
541 // Initialize cached commands and errors from registry
542 let mut commands = registry.read(cx).commands().clone();
543 let mut errors = registry.read(cx).errors().to_vec();
544 let server_command_names = available_commands
545 .borrow()
546 .iter()
547 .map(|command| command.name.clone())
548 .collect::<HashSet<_>>();
549 user_slash_command::apply_server_command_conflicts_to_map(
550 &mut commands,
551 &mut errors,
552 &server_command_names,
553 );
554 command_load_errors = errors.clone();
555 *cached_user_commands.borrow_mut() = commands;
556 *cached_user_command_errors.borrow_mut() = errors;
557
558 Some(registry)
559 } else {
560 None
561 };
562
563 let recent_history_entries = history.read(cx).get_recent_sessions(3);
564 let history_subscription = cx.observe(&history, |this, history, cx| {
565 this.update_recent_history_from_cache(&history, cx);
566 });
567
568 Self {
569 agent: agent.clone(),
570 agent_server_store,
571 workspace: workspace.clone(),
572 project: project.clone(),
573 entry_view_state,
574 permission_dropdown_handle: PopoverMenuHandle::default(),
575 selected_permission_granularity: HashMap::default(),
576 thread_state: Self::initial_state(
577 agent.clone(),
578 resume_thread.clone(),
579 workspace.clone(),
580 project.clone(),
581 window,
582 cx,
583 ),
584 login: None,
585 message_editor,
586 model_selector: None,
587 config_options_view: None,
588 profile_selector: None,
589 notifications: Vec::new(),
590 notification_subscriptions: HashMap::default(),
591 list_state,
592 thread_retry_status: None,
593 thread_error: None,
594 thread_error_markdown: None,
595 command_load_errors,
596 command_load_errors_dismissed: false,
597 slash_command_registry,
598 token_limit_callout_dismissed: false,
599 thread_feedback: Default::default(),
600 auth_task: None,
601 expanded_tool_calls: HashSet::default(),
602 expanded_tool_call_raw_inputs: HashSet::default(),
603 expanded_thinking_blocks: HashSet::default(),
604 expanded_subagents: HashSet::default(),
605 subagent_scroll_handles: RefCell::new(HashMap::default()),
606 editing_message: None,
607 local_queued_messages: Vec::new(),
608 queued_message_editors: Vec::new(),
609 queued_message_editor_subscriptions: Vec::new(),
610 last_synced_queue_length: 0,
611 edits_expanded: false,
612 plan_expanded: false,
613 queue_expanded: true,
614 discarded_partial_edits: HashSet::default(),
615 prompt_capabilities,
616 available_commands,
617 cached_user_commands,
618 cached_user_command_errors,
619 editor_expanded: false,
620 should_be_following: false,
621 recent_history_entries,
622 history,
623 _history_subscription: history_subscription,
624 hovered_recent_history_item: None,
625 is_loading_contents: false,
626 _subscriptions: subscriptions,
627 _cancel_task: None,
628 focus_handle: cx.focus_handle(),
629 new_server_version_available: None,
630 resume_thread_metadata: resume_thread,
631 resumed_without_history: false,
632 show_codex_windows_warning,
633 in_flight_prompt: None,
634 skip_queue_processing_count: 0,
635 user_interrupted_generation: false,
636 can_fast_track_queue: false,
637 turn_tokens: None,
638 last_turn_tokens: None,
639 turn_started_at: None,
640 last_turn_duration: None,
641 turn_generation: 0,
642 _turn_timer_task: None,
643 hovered_edited_file_buttons: None,
644 add_context_menu_handle: PopoverMenuHandle::default(),
645 }
646 }
647
648 fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
649 self.thread_state = Self::initial_state(
650 self.agent.clone(),
651 self.resume_thread_metadata.clone(),
652 self.workspace.clone(),
653 self.project.clone(),
654 window,
655 cx,
656 );
657 self.available_commands.replace(vec![]);
658 self.refresh_cached_user_commands(cx);
659 self.new_server_version_available.take();
660 self.recent_history_entries.clear();
661 self.turn_tokens = None;
662 self.last_turn_tokens = None;
663 self.turn_started_at = None;
664 self.last_turn_duration = None;
665 self._turn_timer_task = None;
666 self.resumed_without_history = false;
667 cx.notify();
668 }
669
670 fn initial_state(
671 agent: Rc<dyn AgentServer>,
672 resume_thread: Option<AgentSessionInfo>,
673 workspace: WeakEntity<Workspace>,
674 project: Entity<Project>,
675 window: &mut Window,
676 cx: &mut Context<Self>,
677 ) -> ThreadState {
678 if project.read(cx).is_via_collab()
679 && agent.clone().downcast::<NativeAgentServer>().is_none()
680 {
681 return ThreadState::LoadError(LoadError::Other(
682 "External agents are not yet supported in shared projects.".into(),
683 ));
684 }
685 let mut worktrees = project.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
686 // Pick the first non-single-file worktree for the root directory if there are any,
687 // and otherwise the parent of a single-file worktree, falling back to $HOME if there are no visible worktrees.
688 worktrees.sort_by(|l, r| {
689 l.read(cx)
690 .is_single_file()
691 .cmp(&r.read(cx).is_single_file())
692 });
693 let root_dir = worktrees
694 .into_iter()
695 .filter_map(|worktree| {
696 if worktree.read(cx).is_single_file() {
697 Some(worktree.read(cx).abs_path().parent()?.into())
698 } else {
699 Some(worktree.read(cx).abs_path())
700 }
701 })
702 .next();
703 let fallback_cwd = root_dir
704 .clone()
705 .unwrap_or_else(|| paths::home_dir().as_path().into());
706 let (status_tx, mut status_rx) = watch::channel("Loading…".into());
707 let (new_version_available_tx, mut new_version_available_rx) = watch::channel(None);
708 let delegate = AgentServerDelegate::new(
709 project.read(cx).agent_server_store().clone(),
710 project.clone(),
711 Some(status_tx),
712 Some(new_version_available_tx),
713 );
714
715 let connect_task = agent.connect(root_dir.as_deref(), delegate, cx);
716 let load_task = cx.spawn_in(window, async move |this, cx| {
717 let connection = match connect_task.await {
718 Ok((connection, login)) => {
719 this.update(cx, |this, _| this.login = login).ok();
720 connection
721 }
722 Err(err) => {
723 this.update_in(cx, |this, window, cx| {
724 if err.downcast_ref::<LoadError>().is_some() {
725 this.handle_load_error(err, window, cx);
726 } else {
727 this.handle_thread_error(err, cx);
728 }
729 cx.notify();
730 })
731 .log_err();
732 return;
733 }
734 };
735
736 telemetry::event!("Agent Thread Started", agent = connection.telemetry_id());
737
738 let mut resumed_without_history = false;
739 let result = if let Some(resume) = resume_thread.clone() {
740 cx.update(|_, cx| {
741 let session_cwd = resume
742 .cwd
743 .clone()
744 .unwrap_or_else(|| fallback_cwd.as_ref().to_path_buf());
745 if connection.supports_load_session(cx) {
746 connection.clone().load_session(
747 resume,
748 project.clone(),
749 session_cwd.as_path(),
750 cx,
751 )
752 } else if connection.supports_resume_session(cx) {
753 resumed_without_history = true;
754 connection.clone().resume_session(
755 resume,
756 project.clone(),
757 session_cwd.as_path(),
758 cx,
759 )
760 } else {
761 Task::ready(Err(anyhow!(LoadError::Other(
762 "Loading or resuming sessions is not supported by this agent.".into()
763 ))))
764 }
765 })
766 .log_err()
767 } else {
768 cx.update(|_, cx| {
769 connection
770 .clone()
771 .new_thread(project.clone(), fallback_cwd.as_ref(), cx)
772 })
773 .log_err()
774 };
775
776 let Some(result) = result else {
777 return;
778 };
779
780 let result = match result.await {
781 Err(e) => match e.downcast::<acp_thread::AuthRequired>() {
782 Ok(err) => {
783 cx.update(|window, cx| {
784 Self::handle_auth_required(this, err, agent, connection, window, cx)
785 })
786 .log_err();
787 return;
788 }
789 Err(err) => Err(err),
790 },
791 Ok(thread) => Ok(thread),
792 };
793
794 this.update_in(cx, |this, window, cx| {
795 match result {
796 Ok(thread) => {
797 let action_log = thread.read(cx).action_log().clone();
798
799 this.resumed_without_history = resumed_without_history;
800 this.prompt_capabilities
801 .replace(thread.read(cx).prompt_capabilities());
802
803 let count = thread.read(cx).entries().len();
804 this.entry_view_state.update(cx, |view_state, cx| {
805 for ix in 0..count {
806 view_state.sync_entry(ix, &thread, window, cx);
807 }
808 this.list_state.splice_focusable(
809 0..0,
810 (0..count).map(|ix| view_state.entry(ix)?.focus_handle(cx)),
811 );
812 });
813
814 AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
815
816 let connection = thread.read(cx).connection().clone();
817 let session_id = thread.read(cx).session_id().clone();
818 let session_list = if connection.supports_session_history(cx) {
819 connection.session_list(cx)
820 } else {
821 None
822 };
823 this.history.update(cx, |history, cx| {
824 history.set_session_list(session_list, cx);
825 });
826
827 // Check for config options first
828 // Config options take precedence over legacy mode/model selectors
829 // (feature flag gating happens at the data layer)
830 let config_options_provider =
831 connection.session_config_options(&session_id, cx);
832
833 let mode_selector;
834 if let Some(config_options) = config_options_provider {
835 // Use config options - don't create mode_selector or model_selector
836 let agent_server = this.agent.clone();
837 let fs = this.project.read(cx).fs().clone();
838 this.config_options_view = Some(cx.new(|cx| {
839 ConfigOptionsView::new(config_options, agent_server, fs, window, cx)
840 }));
841 this.model_selector = None;
842 mode_selector = None;
843 } else {
844 // Fall back to legacy mode/model selectors
845 this.config_options_view = None;
846 this.model_selector =
847 connection.model_selector(&session_id).map(|selector| {
848 let agent_server = this.agent.clone();
849 let fs = this.project.read(cx).fs().clone();
850 cx.new(|cx| {
851 AcpModelSelectorPopover::new(
852 selector,
853 agent_server,
854 fs,
855 PopoverMenuHandle::default(),
856 this.focus_handle(cx),
857 window,
858 cx,
859 )
860 })
861 });
862
863 mode_selector =
864 connection
865 .session_modes(&session_id, cx)
866 .map(|session_modes| {
867 let fs = this.project.read(cx).fs().clone();
868 let focus_handle = this.focus_handle(cx);
869 cx.new(|_cx| {
870 ModeSelector::new(
871 session_modes,
872 this.agent.clone(),
873 fs,
874 focus_handle,
875 )
876 })
877 });
878 }
879
880 let mut subscriptions = vec![
881 cx.subscribe_in(&thread, window, Self::handle_thread_event),
882 cx.observe(&action_log, |_, _, cx| cx.notify()),
883 ];
884
885 let title_editor =
886 if thread.update(cx, |thread, cx| thread.can_set_title(cx)) {
887 let editor = cx.new(|cx| {
888 let mut editor = Editor::single_line(window, cx);
889 editor.set_text(thread.read(cx).title(), window, cx);
890 editor
891 });
892 subscriptions.push(cx.subscribe_in(
893 &editor,
894 window,
895 Self::handle_title_editor_event,
896 ));
897 Some(editor)
898 } else {
899 None
900 };
901
902 this.thread_state = ThreadState::Ready {
903 thread,
904 title_editor,
905 mode_selector,
906 _subscriptions: subscriptions,
907 };
908
909 this.profile_selector = this.as_native_thread(cx).map(|thread| {
910 cx.new(|cx| {
911 ProfileSelector::new(
912 <dyn Fs>::global(cx),
913 Arc::new(thread.clone()),
914 this.focus_handle(cx),
915 cx,
916 )
917 })
918 });
919
920 if this.focus_handle.contains_focused(window, cx) {
921 this.message_editor.focus_handle(cx).focus(window, cx);
922 }
923
924 cx.notify();
925 }
926 Err(err) => {
927 this.handle_load_error(err, window, cx);
928 }
929 };
930 })
931 .log_err();
932 });
933
934 cx.spawn(async move |this, cx| {
935 while let Ok(new_version) = new_version_available_rx.recv().await {
936 if let Some(new_version) = new_version {
937 this.update(cx, |this, cx| {
938 this.new_server_version_available = Some(new_version.into());
939 cx.notify();
940 })
941 .ok();
942 }
943 }
944 })
945 .detach();
946
947 let loading_view = cx.new(|cx| {
948 let update_title_task = cx.spawn(async move |this, cx| {
949 loop {
950 let status = status_rx.recv().await?;
951 this.update(cx, |this: &mut LoadingView, cx| {
952 this.title = status;
953 cx.notify();
954 })?;
955 }
956 });
957
958 LoadingView {
959 title: "Loading…".into(),
960 _load_task: load_task,
961 _update_title_task: update_title_task,
962 }
963 });
964
965 ThreadState::Loading(loading_view)
966 }
967
968 fn handle_auth_required(
969 this: WeakEntity<Self>,
970 err: AuthRequired,
971 agent: Rc<dyn AgentServer>,
972 connection: Rc<dyn AgentConnection>,
973 window: &mut Window,
974 cx: &mut App,
975 ) {
976 let agent_name = agent.name();
977 let (configuration_view, subscription) = if let Some(provider_id) = &err.provider_id {
978 let registry = LanguageModelRegistry::global(cx);
979
980 let sub = window.subscribe(®istry, cx, {
981 let provider_id = provider_id.clone();
982 let this = this.clone();
983 move |_, ev, window, cx| {
984 if let language_model::Event::ProviderStateChanged(updated_provider_id) = &ev
985 && &provider_id == updated_provider_id
986 && LanguageModelRegistry::global(cx)
987 .read(cx)
988 .provider(&provider_id)
989 .map_or(false, |provider| provider.is_authenticated(cx))
990 {
991 this.update(cx, |this, cx| {
992 this.reset(window, cx);
993 })
994 .ok();
995 }
996 }
997 });
998
999 let view = registry.read(cx).provider(&provider_id).map(|provider| {
1000 provider.configuration_view(
1001 language_model::ConfigurationViewTargetAgent::Other(agent_name.clone()),
1002 window,
1003 cx,
1004 )
1005 });
1006
1007 (view, Some(sub))
1008 } else {
1009 (None, None)
1010 };
1011
1012 this.update(cx, |this, cx| {
1013 this.thread_state = ThreadState::Unauthenticated {
1014 pending_auth_method: None,
1015 connection,
1016 configuration_view,
1017 description: err
1018 .description
1019 .map(|desc| cx.new(|cx| Markdown::new(desc.into(), None, None, cx))),
1020 _subscription: subscription,
1021 };
1022 if this.message_editor.focus_handle(cx).is_focused(window) {
1023 this.focus_handle.focus(window, cx)
1024 }
1025 cx.notify();
1026 })
1027 .ok();
1028 }
1029
1030 fn handle_load_error(
1031 &mut self,
1032 err: anyhow::Error,
1033 window: &mut Window,
1034 cx: &mut Context<Self>,
1035 ) {
1036 if let Some(load_err) = err.downcast_ref::<LoadError>() {
1037 self.thread_state = ThreadState::LoadError(load_err.clone());
1038 } else {
1039 self.thread_state =
1040 ThreadState::LoadError(LoadError::Other(format!("{:#}", err).into()))
1041 }
1042 if self.message_editor.focus_handle(cx).is_focused(window) {
1043 self.focus_handle.focus(window, cx)
1044 }
1045 cx.notify();
1046 }
1047
1048 fn handle_agent_servers_updated(
1049 &mut self,
1050 _agent_server_store: &Entity<project::AgentServerStore>,
1051 _event: &project::AgentServersUpdated,
1052 window: &mut Window,
1053 cx: &mut Context<Self>,
1054 ) {
1055 // If we're in a LoadError state OR have a thread_error set (which can happen
1056 // when agent.connect() fails during loading), retry loading the thread.
1057 // This handles the case where a thread is restored before authentication completes.
1058 let should_retry =
1059 matches!(&self.thread_state, ThreadState::LoadError(_)) || self.thread_error.is_some();
1060
1061 if should_retry {
1062 self.thread_error = None;
1063 self.thread_error_markdown = None;
1064 self.reset(window, cx);
1065 }
1066 }
1067
1068 pub fn workspace(&self) -> &WeakEntity<Workspace> {
1069 &self.workspace
1070 }
1071
1072 pub fn thread(&self) -> Option<&Entity<AcpThread>> {
1073 match &self.thread_state {
1074 ThreadState::Ready { thread, .. } => Some(thread),
1075 ThreadState::Unauthenticated { .. }
1076 | ThreadState::Loading { .. }
1077 | ThreadState::LoadError { .. } => None,
1078 }
1079 }
1080
1081 pub fn mode_selector(&self) -> Option<&Entity<ModeSelector>> {
1082 match &self.thread_state {
1083 ThreadState::Ready { mode_selector, .. } => mode_selector.as_ref(),
1084 ThreadState::Unauthenticated { .. }
1085 | ThreadState::Loading { .. }
1086 | ThreadState::LoadError { .. } => None,
1087 }
1088 }
1089
1090 pub fn title(&self, cx: &App) -> SharedString {
1091 match &self.thread_state {
1092 ThreadState::Ready { .. } | ThreadState::Unauthenticated { .. } => "New Thread".into(),
1093 ThreadState::Loading(loading_view) => loading_view.read(cx).title.clone(),
1094 ThreadState::LoadError(error) => match error {
1095 LoadError::Unsupported { .. } => format!("Upgrade {}", self.agent.name()).into(),
1096 LoadError::FailedToInstall(_) => {
1097 format!("Failed to Install {}", self.agent.name()).into()
1098 }
1099 LoadError::Exited { .. } => format!("{} Exited", self.agent.name()).into(),
1100 LoadError::Other(_) => format!("Error Loading {}", self.agent.name()).into(),
1101 },
1102 }
1103 }
1104
1105 pub fn title_editor(&self) -> Option<Entity<Editor>> {
1106 if let ThreadState::Ready { title_editor, .. } = &self.thread_state {
1107 title_editor.clone()
1108 } else {
1109 None
1110 }
1111 }
1112
1113 pub fn cancel_generation(&mut self, cx: &mut Context<Self>) {
1114 self.thread_error.take();
1115 self.thread_retry_status.take();
1116 self.user_interrupted_generation = true;
1117
1118 if let Some(thread) = self.thread() {
1119 self._cancel_task = Some(thread.update(cx, |thread, cx| thread.cancel(cx)));
1120 }
1121 }
1122
1123 fn share_thread(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1124 let Some(thread) = self.as_native_thread(cx) else {
1125 return;
1126 };
1127
1128 let client = self.project.read(cx).client();
1129 let workspace = self.workspace.clone();
1130 let session_id = thread.read(cx).id().to_string();
1131
1132 let load_task = thread.read(cx).to_db(cx);
1133
1134 cx.spawn(async move |_this, cx| {
1135 let db_thread = load_task.await;
1136
1137 let shared_thread = SharedThread::from_db_thread(&db_thread);
1138 let thread_data = shared_thread.to_bytes()?;
1139 let title = shared_thread.title.to_string();
1140
1141 client
1142 .request(proto::ShareAgentThread {
1143 session_id: session_id.clone(),
1144 title,
1145 thread_data,
1146 })
1147 .await?;
1148
1149 let share_url = client::zed_urls::shared_agent_thread_url(&session_id);
1150
1151 cx.update(|cx| {
1152 if let Some(workspace) = workspace.upgrade() {
1153 workspace.update(cx, |workspace, cx| {
1154 struct ThreadSharedToast;
1155 workspace.show_toast(
1156 Toast::new(
1157 NotificationId::unique::<ThreadSharedToast>(),
1158 "Thread shared!",
1159 )
1160 .on_click(
1161 "Copy URL",
1162 move |_window, cx| {
1163 cx.write_to_clipboard(ClipboardItem::new_string(
1164 share_url.clone(),
1165 ));
1166 },
1167 ),
1168 cx,
1169 );
1170 });
1171 }
1172 });
1173
1174 anyhow::Ok(())
1175 })
1176 .detach_and_log_err(cx);
1177 }
1178
1179 fn sync_thread(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1180 if !self.is_imported_thread(cx) {
1181 return;
1182 }
1183
1184 let Some(thread) = self.thread() else {
1185 return;
1186 };
1187
1188 let Some(session_list) = self
1189 .as_native_connection(cx)
1190 .and_then(|connection| connection.session_list(cx))
1191 .and_then(|list| list.downcast::<NativeAgentSessionList>())
1192 else {
1193 return;
1194 };
1195 let thread_store = session_list.thread_store().clone();
1196
1197 let client = self.project.read(cx).client();
1198 let session_id = thread.read(cx).session_id().clone();
1199
1200 cx.spawn_in(window, async move |this, cx| {
1201 let response = client
1202 .request(proto::GetSharedAgentThread {
1203 session_id: session_id.to_string(),
1204 })
1205 .await?;
1206
1207 let shared_thread = SharedThread::from_bytes(&response.thread_data)?;
1208
1209 let db_thread = shared_thread.to_db_thread();
1210
1211 thread_store
1212 .update(&mut cx.clone(), |store, cx| {
1213 store.save_thread(session_id.clone(), db_thread, cx)
1214 })
1215 .await?;
1216
1217 let thread_metadata = AgentSessionInfo {
1218 session_id,
1219 cwd: None,
1220 title: Some(format!("🔗 {}", response.title).into()),
1221 updated_at: Some(chrono::Utc::now()),
1222 meta: None,
1223 };
1224
1225 this.update_in(cx, |this, window, cx| {
1226 this.resume_thread_metadata = Some(thread_metadata);
1227 this.reset(window, cx);
1228 })?;
1229
1230 this.update_in(cx, |this, _window, cx| {
1231 if let Some(workspace) = this.workspace.upgrade() {
1232 workspace.update(cx, |workspace, cx| {
1233 struct ThreadSyncedToast;
1234 workspace.show_toast(
1235 Toast::new(
1236 NotificationId::unique::<ThreadSyncedToast>(),
1237 "Thread synced with latest version",
1238 )
1239 .autohide(),
1240 cx,
1241 );
1242 });
1243 }
1244 })?;
1245
1246 anyhow::Ok(())
1247 })
1248 .detach_and_log_err(cx);
1249 }
1250
1251 pub fn expand_message_editor(
1252 &mut self,
1253 _: &ExpandMessageEditor,
1254 _window: &mut Window,
1255 cx: &mut Context<Self>,
1256 ) {
1257 self.set_editor_is_expanded(!self.editor_expanded, cx);
1258 cx.stop_propagation();
1259 cx.notify();
1260 }
1261
1262 fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
1263 self.editor_expanded = is_expanded;
1264 self.message_editor.update(cx, |editor, cx| {
1265 if is_expanded {
1266 editor.set_mode(
1267 EditorMode::Full {
1268 scale_ui_elements_with_buffer_font_size: false,
1269 show_active_line_background: false,
1270 sizing_behavior: SizingBehavior::ExcludeOverscrollMargin,
1271 },
1272 cx,
1273 )
1274 } else {
1275 let agent_settings = AgentSettings::get_global(cx);
1276 editor.set_mode(
1277 EditorMode::AutoHeight {
1278 min_lines: agent_settings.message_editor_min_lines,
1279 max_lines: Some(agent_settings.set_message_editor_max_lines()),
1280 },
1281 cx,
1282 )
1283 }
1284 });
1285 cx.notify();
1286 }
1287
1288 pub fn handle_title_editor_event(
1289 &mut self,
1290 title_editor: &Entity<Editor>,
1291 event: &EditorEvent,
1292 window: &mut Window,
1293 cx: &mut Context<Self>,
1294 ) {
1295 let Some(thread) = self.thread() else { return };
1296
1297 match event {
1298 EditorEvent::BufferEdited => {
1299 let new_title = title_editor.read(cx).text(cx);
1300 thread.update(cx, |thread, cx| {
1301 thread
1302 .set_title(new_title.into(), cx)
1303 .detach_and_log_err(cx);
1304 })
1305 }
1306 EditorEvent::Blurred => {
1307 if title_editor.read(cx).text(cx).is_empty() {
1308 title_editor.update(cx, |editor, cx| {
1309 editor.set_text("New Thread", window, cx);
1310 });
1311 }
1312 }
1313 _ => {}
1314 }
1315 }
1316
1317 pub fn handle_message_editor_event(
1318 &mut self,
1319 _: &Entity<MessageEditor>,
1320 event: &MessageEditorEvent,
1321 window: &mut Window,
1322 cx: &mut Context<Self>,
1323 ) {
1324 match event {
1325 MessageEditorEvent::Send => self.send(window, cx),
1326 MessageEditorEvent::SendImmediately => self.interrupt_and_send(window, cx),
1327 MessageEditorEvent::Cancel => self.cancel_generation(cx),
1328 MessageEditorEvent::Focus => {
1329 self.cancel_editing(&Default::default(), window, cx);
1330 }
1331 MessageEditorEvent::LostFocus => {}
1332 }
1333 }
1334
1335 pub fn handle_entry_view_event(
1336 &mut self,
1337 _: &Entity<EntryViewState>,
1338 event: &EntryViewEvent,
1339 window: &mut Window,
1340 cx: &mut Context<Self>,
1341 ) {
1342 match &event.view_event {
1343 ViewEvent::NewDiff(tool_call_id) => {
1344 if AgentSettings::get_global(cx).expand_edit_card {
1345 self.expanded_tool_calls.insert(tool_call_id.clone());
1346 }
1347 }
1348 ViewEvent::NewTerminal(tool_call_id) => {
1349 if AgentSettings::get_global(cx).expand_terminal_card {
1350 self.expanded_tool_calls.insert(tool_call_id.clone());
1351 }
1352 }
1353 ViewEvent::TerminalMovedToBackground(tool_call_id) => {
1354 self.expanded_tool_calls.remove(tool_call_id);
1355 }
1356 ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Focus) => {
1357 if let Some(thread) = self.thread()
1358 && let Some(AgentThreadEntry::UserMessage(user_message)) =
1359 thread.read(cx).entries().get(event.entry_index)
1360 && user_message.id.is_some()
1361 {
1362 self.editing_message = Some(event.entry_index);
1363 cx.notify();
1364 }
1365 }
1366 ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::LostFocus) => {
1367 if let Some(thread) = self.thread()
1368 && let Some(AgentThreadEntry::UserMessage(user_message)) =
1369 thread.read(cx).entries().get(event.entry_index)
1370 && user_message.id.is_some()
1371 {
1372 if editor.read(cx).text(cx).as_str() == user_message.content.to_markdown(cx) {
1373 self.editing_message = None;
1374 cx.notify();
1375 }
1376 }
1377 }
1378 ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::SendImmediately) => {}
1379 ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::Send) => {
1380 self.regenerate(event.entry_index, editor.clone(), window, cx);
1381 }
1382 ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Cancel) => {
1383 self.cancel_editing(&Default::default(), window, cx);
1384 }
1385 }
1386 }
1387
1388 pub fn is_loading(&self) -> bool {
1389 matches!(self.thread_state, ThreadState::Loading { .. })
1390 }
1391
1392 fn retry_generation(&mut self, cx: &mut Context<Self>) {
1393 self.thread_error.take();
1394 let Some(thread) = self.thread() else {
1395 return;
1396 };
1397 if !thread.read(cx).can_retry(cx) {
1398 return;
1399 }
1400
1401 let task = thread.update(cx, |thread, cx| thread.retry(cx));
1402 cx.spawn(async move |this, cx| {
1403 let result = task.await;
1404
1405 this.update(cx, |this, cx| {
1406 if let Err(err) = result {
1407 this.handle_thread_error(err, cx);
1408 }
1409 })
1410 })
1411 .detach();
1412 }
1413
1414 fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1415 let Some(thread) = self.thread() else { return };
1416
1417 if self.is_loading_contents {
1418 return;
1419 }
1420
1421 let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
1422 let is_generating = thread.read(cx).status() != ThreadStatus::Idle;
1423
1424 let has_queued = self.has_queued_messages();
1425 if is_editor_empty && self.can_fast_track_queue && has_queued {
1426 self.can_fast_track_queue = false;
1427 self.send_queued_message_at_index(0, true, window, cx);
1428 return;
1429 }
1430
1431 if is_editor_empty {
1432 return;
1433 }
1434
1435 if is_generating {
1436 self.queue_message(window, cx);
1437 return;
1438 }
1439
1440 let text = self.message_editor.read(cx).text(cx);
1441 let text = text.trim();
1442 if text == "/login" || text == "/logout" {
1443 let ThreadState::Ready { thread, .. } = &self.thread_state else {
1444 return;
1445 };
1446
1447 let connection = thread.read(cx).connection().clone();
1448 let can_login = !connection.auth_methods().is_empty() || self.login.is_some();
1449 // Does the agent have a specific logout command? Prefer that in case they need to reset internal state.
1450 let logout_supported = text == "/logout"
1451 && self
1452 .available_commands
1453 .borrow()
1454 .iter()
1455 .any(|command| command.name == "logout");
1456 if can_login && !logout_supported {
1457 self.message_editor
1458 .update(cx, |editor, cx| editor.clear(window, cx));
1459
1460 let this = cx.weak_entity();
1461 let agent = self.agent.clone();
1462 window.defer(cx, |window, cx| {
1463 Self::handle_auth_required(
1464 this,
1465 AuthRequired::new(),
1466 agent,
1467 connection,
1468 window,
1469 cx,
1470 );
1471 });
1472 cx.notify();
1473 return;
1474 }
1475 }
1476
1477 self.send_impl(self.message_editor.clone(), window, cx)
1478 }
1479
1480 fn interrupt_and_send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1481 let Some(thread) = self.thread() else {
1482 return;
1483 };
1484
1485 if self.is_loading_contents {
1486 return;
1487 }
1488
1489 if thread.read(cx).status() == ThreadStatus::Idle {
1490 self.send_impl(self.message_editor.clone(), window, cx);
1491 return;
1492 }
1493
1494 self.stop_current_and_send_new_message(window, cx);
1495 }
1496
1497 fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1498 let Some(thread) = self.thread().cloned() else {
1499 return;
1500 };
1501
1502 self.skip_queue_processing_count = 0;
1503 self.user_interrupted_generation = true;
1504
1505 let cancelled = thread.update(cx, |thread, cx| thread.cancel(cx));
1506
1507 cx.spawn_in(window, async move |this, cx| {
1508 cancelled.await;
1509
1510 this.update_in(cx, |this, window, cx| {
1511 this.send_impl(this.message_editor.clone(), window, cx);
1512 })
1513 .ok();
1514 })
1515 .detach();
1516 }
1517
1518 fn start_turn(&mut self, cx: &mut Context<Self>) -> usize {
1519 self.turn_generation += 1;
1520 let generation = self.turn_generation;
1521 self.turn_started_at = Some(Instant::now());
1522 self.last_turn_duration = None;
1523 self.last_turn_tokens = None;
1524 self.turn_tokens = Some(0);
1525 self._turn_timer_task = Some(cx.spawn(async move |this, cx| {
1526 loop {
1527 cx.background_executor().timer(Duration::from_secs(1)).await;
1528 if this.update(cx, |_, cx| cx.notify()).is_err() {
1529 break;
1530 }
1531 }
1532 }));
1533 generation
1534 }
1535
1536 fn stop_turn(&mut self, generation: usize) {
1537 if self.turn_generation != generation {
1538 return;
1539 }
1540 self.last_turn_duration = self.turn_started_at.take().map(|started| started.elapsed());
1541 self.last_turn_tokens = self.turn_tokens.take();
1542 self._turn_timer_task = None;
1543 }
1544
1545 fn update_turn_tokens(&mut self, cx: &App) {
1546 if let Some(thread) = self.thread() {
1547 if let Some(usage) = thread.read(cx).token_usage() {
1548 if let Some(ref mut tokens) = self.turn_tokens {
1549 *tokens += usage.output_tokens;
1550 }
1551 }
1552 }
1553 }
1554
1555 fn send_impl(
1556 &mut self,
1557 message_editor: Entity<MessageEditor>,
1558 window: &mut Window,
1559 cx: &mut Context<Self>,
1560 ) {
1561 let full_mention_content = self.as_native_thread(cx).is_some_and(|thread| {
1562 // Include full contents when using minimal profile
1563 let thread = thread.read(cx);
1564 AgentSettings::get_global(cx)
1565 .profiles
1566 .get(thread.profile())
1567 .is_some_and(|profile| profile.tools.is_empty())
1568 });
1569
1570 let cached_commands = self.cached_slash_commands(cx);
1571 let cached_errors = self.cached_slash_command_errors(cx);
1572 let contents = message_editor.update(cx, |message_editor, cx| {
1573 message_editor.contents_with_cache(
1574 full_mention_content,
1575 Some(cached_commands),
1576 Some(cached_errors),
1577 cx,
1578 )
1579 });
1580
1581 self.thread_error.take();
1582 self.editing_message.take();
1583 self.thread_feedback.clear();
1584
1585 if self.should_be_following {
1586 self.workspace
1587 .update(cx, |workspace, cx| {
1588 workspace.follow(CollaboratorId::Agent, window, cx);
1589 })
1590 .ok();
1591 }
1592
1593 let contents_task = cx.spawn_in(window, async move |this, cx| {
1594 let (contents, tracked_buffers) = contents.await?;
1595
1596 if contents.is_empty() {
1597 return Ok(None);
1598 }
1599
1600 this.update_in(cx, |this, window, cx| {
1601 this.message_editor.update(cx, |message_editor, cx| {
1602 message_editor.clear(window, cx);
1603 });
1604 })?;
1605
1606 Ok(Some((contents, tracked_buffers)))
1607 });
1608
1609 self.send_content(contents_task, window, cx);
1610 }
1611
1612 fn send_content(
1613 &mut self,
1614 contents_task: Task<anyhow::Result<Option<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>>>,
1615 window: &mut Window,
1616 cx: &mut Context<Self>,
1617 ) {
1618 let Some(thread) = self.thread() else {
1619 return;
1620 };
1621 let session_id = thread.read(cx).session_id().clone();
1622 let agent_telemetry_id = thread.read(cx).connection().telemetry_id();
1623 let thread = thread.downgrade();
1624
1625 self.is_loading_contents = true;
1626 let model_id = self.current_model_id(cx);
1627 let mode_id = self.current_mode_id(cx);
1628 let guard = cx.new(|_| ());
1629 cx.observe_release(&guard, |this, _guard, cx| {
1630 this.is_loading_contents = false;
1631 cx.notify();
1632 })
1633 .detach();
1634
1635 let task = cx.spawn_in(window, async move |this, cx| {
1636 let Some((contents, tracked_buffers)) = contents_task.await? else {
1637 return Ok(());
1638 };
1639
1640 let generation = this.update_in(cx, |this, _window, cx| {
1641 this.in_flight_prompt = Some(contents.clone());
1642 let generation = this.start_turn(cx);
1643 this.set_editor_is_expanded(false, cx);
1644 this.scroll_to_bottom(cx);
1645 generation
1646 })?;
1647
1648 let _stop_turn = defer({
1649 let this = this.clone();
1650 let mut cx = cx.clone();
1651 move || {
1652 this.update(&mut cx, |this, cx| {
1653 this.stop_turn(generation);
1654 cx.notify();
1655 })
1656 .ok();
1657 }
1658 });
1659 let turn_start_time = Instant::now();
1660 let send = thread.update(cx, |thread, cx| {
1661 thread.action_log().update(cx, |action_log, cx| {
1662 for buffer in tracked_buffers {
1663 action_log.buffer_read(buffer, cx)
1664 }
1665 });
1666 drop(guard);
1667
1668 telemetry::event!(
1669 "Agent Message Sent",
1670 agent = agent_telemetry_id,
1671 session = session_id,
1672 model = model_id,
1673 mode = mode_id
1674 );
1675
1676 thread.send(contents, cx)
1677 })?;
1678 let res = send.await;
1679 let turn_time_ms = turn_start_time.elapsed().as_millis();
1680 drop(_stop_turn);
1681 let status = if res.is_ok() {
1682 this.update(cx, |this, _| this.in_flight_prompt.take()).ok();
1683 "success"
1684 } else {
1685 "failure"
1686 };
1687 telemetry::event!(
1688 "Agent Turn Completed",
1689 agent = agent_telemetry_id,
1690 session = session_id,
1691 model = model_id,
1692 mode = mode_id,
1693 status,
1694 turn_time_ms,
1695 );
1696 res
1697 });
1698
1699 cx.spawn(async move |this, cx| {
1700 if let Err(err) = task.await {
1701 this.update(cx, |this, cx| {
1702 this.handle_thread_error(err, cx);
1703 })
1704 .ok();
1705 } else {
1706 this.update(cx, |this, cx| {
1707 this.should_be_following = this
1708 .workspace
1709 .update(cx, |workspace, _| {
1710 workspace.is_being_followed(CollaboratorId::Agent)
1711 })
1712 .unwrap_or_default();
1713 })
1714 .ok();
1715 }
1716 })
1717 .detach();
1718 }
1719
1720 fn queue_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1721 let is_idle = self
1722 .thread()
1723 .map(|t| t.read(cx).status() == acp_thread::ThreadStatus::Idle)
1724 .unwrap_or(true);
1725
1726 if is_idle {
1727 self.send_impl(self.message_editor.clone(), window, cx);
1728 return;
1729 }
1730
1731 let full_mention_content = self.as_native_thread(cx).is_some_and(|thread| {
1732 let thread = thread.read(cx);
1733 AgentSettings::get_global(cx)
1734 .profiles
1735 .get(thread.profile())
1736 .is_some_and(|profile| profile.tools.is_empty())
1737 });
1738
1739 let cached_commands = self.cached_slash_commands(cx);
1740 let cached_errors = self.cached_slash_command_errors(cx);
1741 let contents = self.message_editor.update(cx, |message_editor, cx| {
1742 message_editor.contents_with_cache(
1743 full_mention_content,
1744 Some(cached_commands),
1745 Some(cached_errors),
1746 cx,
1747 )
1748 });
1749
1750 let message_editor = self.message_editor.clone();
1751
1752 cx.spawn_in(window, async move |this, cx| {
1753 let (content, tracked_buffers) = contents.await?;
1754
1755 if content.is_empty() {
1756 return Ok::<(), anyhow::Error>(());
1757 }
1758
1759 this.update_in(cx, |this, window, cx| {
1760 this.add_to_queue(content, tracked_buffers, cx);
1761 // Enable fast-track: user can press Enter again to send this queued message immediately
1762 this.can_fast_track_queue = true;
1763 message_editor.update(cx, |message_editor, cx| {
1764 message_editor.clear(window, cx);
1765 });
1766 cx.notify();
1767 })?;
1768 Ok(())
1769 })
1770 .detach_and_log_err(cx);
1771 }
1772
1773 fn send_queued_message_at_index(
1774 &mut self,
1775 index: usize,
1776 is_send_now: bool,
1777 window: &mut Window,
1778 cx: &mut Context<Self>,
1779 ) {
1780 let Some(queued) = self.remove_from_queue(index, cx) else {
1781 return;
1782 };
1783 let content = queued.content;
1784 let tracked_buffers = queued.tracked_buffers;
1785
1786 let Some(thread) = self.thread().cloned() else {
1787 return;
1788 };
1789
1790 // Only increment skip count for "Send Now" operations (out-of-order sends)
1791 // Normal auto-processing from the Stopped handler doesn't need to skip.
1792 // We only skip the Stopped event from the cancelled generation, NOT the
1793 // Stopped event from the newly sent message (which should trigger queue processing).
1794 if is_send_now {
1795 let is_generating = thread.read(cx).status() == acp_thread::ThreadStatus::Generating;
1796 self.skip_queue_processing_count += if is_generating { 1 } else { 0 };
1797 }
1798
1799 let cancelled = thread.update(cx, |thread, cx| thread.cancel(cx));
1800
1801 let should_be_following = self.should_be_following;
1802 let workspace = self.workspace.clone();
1803
1804 let contents_task = cx.spawn_in(window, async move |_this, cx| {
1805 cancelled.await;
1806 if should_be_following {
1807 workspace
1808 .update_in(cx, |workspace, window, cx| {
1809 workspace.follow(CollaboratorId::Agent, window, cx);
1810 })
1811 .ok();
1812 }
1813
1814 Ok(Some((content, tracked_buffers)))
1815 });
1816
1817 self.send_content(contents_task, window, cx);
1818 }
1819
1820 fn cancel_editing(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1821 let Some(thread) = self.thread().cloned() else {
1822 return;
1823 };
1824
1825 if let Some(index) = self.editing_message.take()
1826 && let Some(editor) = self
1827 .entry_view_state
1828 .read(cx)
1829 .entry(index)
1830 .and_then(|e| e.message_editor())
1831 .cloned()
1832 {
1833 editor.update(cx, |editor, cx| {
1834 if let Some(user_message) = thread
1835 .read(cx)
1836 .entries()
1837 .get(index)
1838 .and_then(|e| e.user_message())
1839 {
1840 editor.set_message(user_message.chunks.clone(), window, cx);
1841 }
1842 })
1843 };
1844 self.focus_handle(cx).focus(window, cx);
1845 cx.notify();
1846 }
1847
1848 fn regenerate(
1849 &mut self,
1850 entry_ix: usize,
1851 message_editor: Entity<MessageEditor>,
1852 window: &mut Window,
1853 cx: &mut Context<Self>,
1854 ) {
1855 let Some(thread) = self.thread().cloned() else {
1856 return;
1857 };
1858 if self.is_loading_contents {
1859 return;
1860 }
1861
1862 let Some(user_message_id) = thread.update(cx, |thread, _| {
1863 thread.entries().get(entry_ix)?.user_message()?.id.clone()
1864 }) else {
1865 return;
1866 };
1867
1868 cx.spawn_in(window, async move |this, cx| {
1869 // Check if there are any edits from prompts before the one being regenerated.
1870 //
1871 // If there are, we keep/accept them since we're not regenerating the prompt that created them.
1872 //
1873 // If editing the prompt that generated the edits, they are auto-rejected
1874 // through the `rewind` function in the `acp_thread`.
1875 let has_earlier_edits = thread.read_with(cx, |thread, _| {
1876 thread
1877 .entries()
1878 .iter()
1879 .take(entry_ix)
1880 .any(|entry| entry.diffs().next().is_some())
1881 });
1882
1883 if has_earlier_edits {
1884 thread.update(cx, |thread, cx| {
1885 thread.action_log().update(cx, |action_log, cx| {
1886 action_log.keep_all_edits(None, cx);
1887 });
1888 });
1889 }
1890
1891 thread
1892 .update(cx, |thread, cx| thread.rewind(user_message_id, cx))
1893 .await?;
1894 this.update_in(cx, |this, window, cx| {
1895 this.send_impl(message_editor, window, cx);
1896 this.focus_handle(cx).focus(window, cx);
1897 })?;
1898 anyhow::Ok(())
1899 })
1900 .detach_and_log_err(cx);
1901 }
1902
1903 fn open_edited_buffer(
1904 &mut self,
1905 buffer: &Entity<Buffer>,
1906 window: &mut Window,
1907 cx: &mut Context<Self>,
1908 ) {
1909 let Some(thread) = self.thread() else {
1910 return;
1911 };
1912
1913 let Some(diff) =
1914 AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
1915 else {
1916 return;
1917 };
1918
1919 diff.update(cx, |diff, cx| {
1920 diff.move_to_path(PathKey::for_buffer(buffer, cx), window, cx)
1921 })
1922 }
1923
1924 fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1925 let Some(thread) = self.as_native_thread(cx) else {
1926 return;
1927 };
1928 let project_context = thread.read(cx).project_context().read(cx);
1929
1930 let project_entry_ids = project_context
1931 .worktrees
1932 .iter()
1933 .flat_map(|worktree| worktree.rules_file.as_ref())
1934 .map(|rules_file| ProjectEntryId::from_usize(rules_file.project_entry_id))
1935 .collect::<Vec<_>>();
1936
1937 self.workspace
1938 .update(cx, move |workspace, cx| {
1939 // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
1940 // files clear. For example, if rules file 1 is already open but rules file 2 is not,
1941 // this would open and focus rules file 2 in a tab that is not next to rules file 1.
1942 let project = workspace.project().read(cx);
1943 let project_paths = project_entry_ids
1944 .into_iter()
1945 .flat_map(|entry_id| project.path_for_entry(entry_id, cx))
1946 .collect::<Vec<_>>();
1947 for project_path in project_paths {
1948 workspace
1949 .open_path(project_path, None, true, window, cx)
1950 .detach_and_log_err(cx);
1951 }
1952 })
1953 .ok();
1954 }
1955
1956 fn handle_thread_error(&mut self, error: anyhow::Error, cx: &mut Context<Self>) {
1957 let thread_error = ThreadError::from_err(error, &self.agent);
1958 self.emit_thread_error_telemetry(&thread_error, cx);
1959 self.thread_error = Some(thread_error);
1960 cx.notify();
1961 }
1962
1963 fn emit_thread_error_telemetry(&self, error: &ThreadError, cx: &mut Context<Self>) {
1964 let (error_kind, acp_error_code, message): (&str, Option<SharedString>, SharedString) =
1965 match error {
1966 ThreadError::PaymentRequired => (
1967 "payment_required",
1968 None,
1969 "You reached your free usage limit. Upgrade to Zed Pro for more prompts."
1970 .into(),
1971 ),
1972 ThreadError::Refusal => {
1973 let model_or_agent_name = self.current_model_name(cx);
1974 let message = format!(
1975 "{} refused to respond to this prompt. This can happen when a model believes the prompt violates its content policy or safety guidelines, so rephrasing it can sometimes address the issue.",
1976 model_or_agent_name
1977 );
1978 ("refusal", None, message.into())
1979 }
1980 ThreadError::AuthenticationRequired(message) => {
1981 ("authentication_required", None, message.clone())
1982 }
1983 ThreadError::Other {
1984 acp_error_code,
1985 message,
1986 } => ("other", acp_error_code.clone(), message.clone()),
1987 };
1988
1989 let (agent_telemetry_id, session_id) = self
1990 .thread()
1991 .map(|t| {
1992 let thread = t.read(cx);
1993 (
1994 thread.connection().telemetry_id(),
1995 thread.session_id().clone(),
1996 )
1997 })
1998 .unzip();
1999
2000 telemetry::event!(
2001 "Agent Panel Error Shown",
2002 agent = agent_telemetry_id,
2003 session_id = session_id,
2004 kind = error_kind,
2005 acp_error_code = acp_error_code,
2006 message = message,
2007 );
2008 }
2009
2010 fn clear_thread_error(&mut self, cx: &mut Context<Self>) {
2011 self.thread_error = None;
2012 self.thread_error_markdown = None;
2013 self.token_limit_callout_dismissed = true;
2014 cx.notify();
2015 }
2016
2017 fn handle_thread_event(
2018 &mut self,
2019 thread: &Entity<AcpThread>,
2020 event: &AcpThreadEvent,
2021 window: &mut Window,
2022 cx: &mut Context<Self>,
2023 ) {
2024 match event {
2025 AcpThreadEvent::NewEntry => {
2026 let len = thread.read(cx).entries().len();
2027 let index = len - 1;
2028 self.entry_view_state.update(cx, |view_state, cx| {
2029 view_state.sync_entry(index, thread, window, cx);
2030 self.list_state.splice_focusable(
2031 index..index,
2032 [view_state
2033 .entry(index)
2034 .and_then(|entry| entry.focus_handle(cx))],
2035 );
2036 });
2037 }
2038 AcpThreadEvent::EntryUpdated(index) => {
2039 self.entry_view_state.update(cx, |view_state, cx| {
2040 view_state.sync_entry(*index, thread, window, cx)
2041 });
2042 }
2043 AcpThreadEvent::EntriesRemoved(range) => {
2044 self.entry_view_state
2045 .update(cx, |view_state, _cx| view_state.remove(range.clone()));
2046 self.list_state.splice(range.clone(), 0);
2047 }
2048 AcpThreadEvent::ToolAuthorizationRequired => {
2049 self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
2050 }
2051 AcpThreadEvent::Retry(retry) => {
2052 self.thread_retry_status = Some(retry.clone());
2053 }
2054 AcpThreadEvent::Stopped => {
2055 self.thread_retry_status.take();
2056 let used_tools = thread.read(cx).used_tools_since_last_user_message();
2057 self.notify_with_sound(
2058 if used_tools {
2059 "Finished running tools"
2060 } else {
2061 "New message"
2062 },
2063 IconName::ZedAssistant,
2064 window,
2065 cx,
2066 );
2067
2068 if self.skip_queue_processing_count > 0 {
2069 self.skip_queue_processing_count -= 1;
2070 } else if self.user_interrupted_generation {
2071 // Manual interruption: don't auto-process queue.
2072 // Reset the flag so future completions can process normally.
2073 self.user_interrupted_generation = false;
2074 } else {
2075 let has_queued = self.has_queued_messages();
2076 // Don't auto-send if the first message editor is currently focused
2077 let is_first_editor_focused = self
2078 .queued_message_editors
2079 .first()
2080 .is_some_and(|editor| editor.focus_handle(cx).is_focused(window));
2081 if has_queued && !is_first_editor_focused {
2082 self.send_queued_message_at_index(0, false, window, cx);
2083 }
2084 }
2085
2086 self.history.update(cx, |history, cx| history.refresh(cx));
2087 }
2088 AcpThreadEvent::Refusal => {
2089 self.thread_retry_status.take();
2090 let thread_error = ThreadError::Refusal;
2091 self.emit_thread_error_telemetry(&thread_error, cx);
2092 self.thread_error = Some(thread_error);
2093 let model_or_agent_name = self.current_model_name(cx);
2094 let notification_message =
2095 format!("{} refused to respond to this request", model_or_agent_name);
2096 self.notify_with_sound(¬ification_message, IconName::Warning, window, cx);
2097 }
2098 AcpThreadEvent::Error => {
2099 self.thread_retry_status.take();
2100 self.notify_with_sound(
2101 "Agent stopped due to an error",
2102 IconName::Warning,
2103 window,
2104 cx,
2105 );
2106 }
2107 AcpThreadEvent::LoadError(error) => {
2108 self.thread_retry_status.take();
2109 self.thread_state = ThreadState::LoadError(error.clone());
2110 if self.message_editor.focus_handle(cx).is_focused(window) {
2111 self.focus_handle.focus(window, cx)
2112 }
2113 }
2114 AcpThreadEvent::TitleUpdated => {
2115 let title = thread.read(cx).title();
2116 if let Some(title_editor) = self.title_editor() {
2117 title_editor.update(cx, |editor, cx| {
2118 if editor.text(cx) != title {
2119 editor.set_text(title, window, cx);
2120 }
2121 });
2122 }
2123 self.history.update(cx, |history, cx| history.refresh(cx));
2124 }
2125 AcpThreadEvent::PromptCapabilitiesUpdated => {
2126 self.prompt_capabilities
2127 .replace(thread.read(cx).prompt_capabilities());
2128 }
2129 AcpThreadEvent::TokenUsageUpdated => {
2130 self.update_turn_tokens(cx);
2131 }
2132 AcpThreadEvent::AvailableCommandsUpdated(available_commands) => {
2133 let mut available_commands = available_commands.clone();
2134
2135 if thread
2136 .read(cx)
2137 .connection()
2138 .auth_methods()
2139 .iter()
2140 .any(|method| method.id.0.as_ref() == "claude-login")
2141 {
2142 available_commands.push(acp::AvailableCommand::new("login", "Authenticate"));
2143 available_commands.push(acp::AvailableCommand::new("logout", "Authenticate"));
2144 }
2145
2146 let has_commands = !available_commands.is_empty();
2147 self.available_commands.replace(available_commands);
2148 self.refresh_cached_user_commands(cx);
2149
2150 let agent_display_name = self
2151 .agent_server_store
2152 .read(cx)
2153 .agent_display_name(&ExternalAgentServerName(self.agent.name()))
2154 .unwrap_or_else(|| self.agent.name());
2155
2156 let new_placeholder = placeholder_text(agent_display_name.as_ref(), has_commands);
2157
2158 self.message_editor.update(cx, |editor, cx| {
2159 editor.set_placeholder_text(&new_placeholder, window, cx);
2160 });
2161 }
2162 AcpThreadEvent::ModeUpdated(_mode) => {
2163 // The connection keeps track of the mode
2164 cx.notify();
2165 }
2166 AcpThreadEvent::ConfigOptionsUpdated(_) => {
2167 // The watch task in ConfigOptionsView handles rebuilding selectors
2168 cx.notify();
2169 }
2170 }
2171 cx.notify();
2172 }
2173
2174 fn authenticate(
2175 &mut self,
2176 method: acp::AuthMethodId,
2177 window: &mut Window,
2178 cx: &mut Context<Self>,
2179 ) {
2180 let ThreadState::Unauthenticated {
2181 connection,
2182 pending_auth_method,
2183 configuration_view,
2184 ..
2185 } = &mut self.thread_state
2186 else {
2187 return;
2188 };
2189 let agent_telemetry_id = connection.telemetry_id();
2190
2191 // Check for the experimental "terminal-auth" _meta field
2192 let auth_method = connection.auth_methods().iter().find(|m| m.id == method);
2193
2194 if let Some(auth_method) = auth_method {
2195 if let Some(meta) = &auth_method.meta {
2196 if let Some(terminal_auth) = meta.get("terminal-auth") {
2197 // Extract terminal auth details from meta
2198 if let (Some(command), Some(label)) = (
2199 terminal_auth.get("command").and_then(|v| v.as_str()),
2200 terminal_auth.get("label").and_then(|v| v.as_str()),
2201 ) {
2202 let args = terminal_auth
2203 .get("args")
2204 .and_then(|v| v.as_array())
2205 .map(|arr| {
2206 arr.iter()
2207 .filter_map(|v| v.as_str().map(String::from))
2208 .collect()
2209 })
2210 .unwrap_or_default();
2211
2212 let env = terminal_auth
2213 .get("env")
2214 .and_then(|v| v.as_object())
2215 .map(|obj| {
2216 obj.iter()
2217 .filter_map(|(k, v)| {
2218 v.as_str().map(|val| (k.clone(), val.to_string()))
2219 })
2220 .collect::<HashMap<String, String>>()
2221 })
2222 .unwrap_or_default();
2223
2224 // Run SpawnInTerminal in the same dir as the ACP server
2225 let cwd = connection
2226 .clone()
2227 .downcast::<agent_servers::AcpConnection>()
2228 .map(|acp_conn| acp_conn.root_dir().to_path_buf());
2229
2230 // Build SpawnInTerminal from _meta
2231 let login = task::SpawnInTerminal {
2232 id: task::TaskId(format!("external-agent-{}-login", label)),
2233 full_label: label.to_string(),
2234 label: label.to_string(),
2235 command: Some(command.to_string()),
2236 args,
2237 command_label: label.to_string(),
2238 cwd,
2239 env,
2240 use_new_terminal: true,
2241 allow_concurrent_runs: true,
2242 hide: task::HideStrategy::Always,
2243 ..Default::default()
2244 };
2245
2246 self.thread_error.take();
2247 configuration_view.take();
2248 pending_auth_method.replace(method.clone());
2249
2250 if let Some(workspace) = self.workspace.upgrade() {
2251 let project = self.project.clone();
2252 let authenticate = Self::spawn_external_agent_login(
2253 login,
2254 workspace,
2255 project,
2256 method.clone(),
2257 false,
2258 window,
2259 cx,
2260 );
2261 cx.notify();
2262 self.auth_task = Some(cx.spawn_in(window, {
2263 async move |this, cx| {
2264 let result = authenticate.await;
2265
2266 match &result {
2267 Ok(_) => telemetry::event!(
2268 "Authenticate Agent Succeeded",
2269 agent = agent_telemetry_id
2270 ),
2271 Err(_) => {
2272 telemetry::event!(
2273 "Authenticate Agent Failed",
2274 agent = agent_telemetry_id,
2275 )
2276 }
2277 }
2278
2279 this.update_in(cx, |this, window, cx| {
2280 if let Err(err) = result {
2281 if let ThreadState::Unauthenticated {
2282 pending_auth_method,
2283 ..
2284 } = &mut this.thread_state
2285 {
2286 pending_auth_method.take();
2287 }
2288 this.handle_thread_error(err, cx);
2289 } else {
2290 this.reset(window, cx);
2291 }
2292 this.auth_task.take()
2293 })
2294 .ok();
2295 }
2296 }));
2297 }
2298 return;
2299 }
2300 }
2301 }
2302 }
2303
2304 if method.0.as_ref() == "gemini-api-key" {
2305 let registry = LanguageModelRegistry::global(cx);
2306 let provider = registry
2307 .read(cx)
2308 .provider(&language_model::GOOGLE_PROVIDER_ID)
2309 .unwrap();
2310 if !provider.is_authenticated(cx) {
2311 let this = cx.weak_entity();
2312 let agent = self.agent.clone();
2313 let connection = connection.clone();
2314 window.defer(cx, |window, cx| {
2315 Self::handle_auth_required(
2316 this,
2317 AuthRequired {
2318 description: Some("GEMINI_API_KEY must be set".to_owned()),
2319 provider_id: Some(language_model::GOOGLE_PROVIDER_ID),
2320 },
2321 agent,
2322 connection,
2323 window,
2324 cx,
2325 );
2326 });
2327 return;
2328 }
2329 } else if method.0.as_ref() == "vertex-ai"
2330 && std::env::var("GOOGLE_API_KEY").is_err()
2331 && (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()
2332 || (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()))
2333 {
2334 let this = cx.weak_entity();
2335 let agent = self.agent.clone();
2336 let connection = connection.clone();
2337
2338 window.defer(cx, |window, cx| {
2339 Self::handle_auth_required(
2340 this,
2341 AuthRequired {
2342 description: Some(
2343 "GOOGLE_API_KEY must be set in the environment to use Vertex AI authentication for Gemini CLI. Please export it and restart Zed."
2344 .to_owned(),
2345 ),
2346 provider_id: None,
2347 },
2348 agent,
2349 connection,
2350 window,
2351 cx,
2352 )
2353 });
2354 return;
2355 }
2356
2357 self.thread_error.take();
2358 configuration_view.take();
2359 pending_auth_method.replace(method.clone());
2360 let authenticate = if let Some(login) = self.login.clone() {
2361 if let Some(workspace) = self.workspace.upgrade() {
2362 let project = self.project.clone();
2363 Self::spawn_external_agent_login(
2364 login,
2365 workspace,
2366 project,
2367 method.clone(),
2368 false,
2369 window,
2370 cx,
2371 )
2372 } else {
2373 Task::ready(Ok(()))
2374 }
2375 } else {
2376 connection.authenticate(method, cx)
2377 };
2378 cx.notify();
2379 self.auth_task = Some(cx.spawn_in(window, {
2380 async move |this, cx| {
2381 let result = authenticate.await;
2382
2383 match &result {
2384 Ok(_) => telemetry::event!(
2385 "Authenticate Agent Succeeded",
2386 agent = agent_telemetry_id
2387 ),
2388 Err(_) => {
2389 telemetry::event!("Authenticate Agent Failed", agent = agent_telemetry_id,)
2390 }
2391 }
2392
2393 this.update_in(cx, |this, window, cx| {
2394 if let Err(err) = result {
2395 if let ThreadState::Unauthenticated {
2396 pending_auth_method,
2397 ..
2398 } = &mut this.thread_state
2399 {
2400 pending_auth_method.take();
2401 }
2402 this.handle_thread_error(err, cx);
2403 } else {
2404 this.reset(window, cx);
2405 }
2406 this.auth_task.take()
2407 })
2408 .ok();
2409 }
2410 }));
2411 }
2412
2413 fn spawn_external_agent_login(
2414 login: task::SpawnInTerminal,
2415 workspace: Entity<Workspace>,
2416 project: Entity<Project>,
2417 method: acp::AuthMethodId,
2418 previous_attempt: bool,
2419 window: &mut Window,
2420 cx: &mut App,
2421 ) -> Task<Result<()>> {
2422 let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
2423 return Task::ready(Ok(()));
2424 };
2425
2426 window.spawn(cx, async move |cx| {
2427 let mut task = login.clone();
2428 if let Some(cmd) = &task.command {
2429 // Have "node" command use Zed's managed Node runtime by default
2430 if cmd == "node" {
2431 let resolved_node_runtime = project
2432 .update(cx, |project, cx| {
2433 let agent_server_store = project.agent_server_store().clone();
2434 agent_server_store.update(cx, |store, cx| {
2435 store.node_runtime().map(|node_runtime| {
2436 cx.background_spawn(async move {
2437 node_runtime.binary_path().await
2438 })
2439 })
2440 })
2441 });
2442
2443 if let Some(resolve_task) = resolved_node_runtime {
2444 if let Ok(node_path) = resolve_task.await {
2445 task.command = Some(node_path.to_string_lossy().to_string());
2446 }
2447 }
2448 }
2449 }
2450 task.shell = task::Shell::WithArguments {
2451 program: task.command.take().expect("login command should be set"),
2452 args: std::mem::take(&mut task.args),
2453 title_override: None
2454 };
2455 task.full_label = task.label.clone();
2456 task.id = task::TaskId(format!("external-agent-{}-login", task.label));
2457 task.command_label = task.label.clone();
2458 task.use_new_terminal = true;
2459 task.allow_concurrent_runs = true;
2460 task.hide = task::HideStrategy::Always;
2461
2462 let terminal = terminal_panel
2463 .update_in(cx, |terminal_panel, window, cx| {
2464 terminal_panel.spawn_task(&task, window, cx)
2465 })?
2466 .await?;
2467
2468 let success_patterns = match method.0.as_ref() {
2469 "claude-login" | "spawn-gemini-cli" => vec![
2470 "Login successful".to_string(),
2471 "Type your message".to_string(),
2472 ],
2473 _ => Vec::new(),
2474 };
2475 if success_patterns.is_empty() {
2476 // No success patterns specified: wait for the process to exit and check exit code
2477 let exit_status = terminal
2478 .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
2479 .await;
2480
2481 match exit_status {
2482 Some(status) if status.success() => Ok(()),
2483 Some(status) => Err(anyhow!(
2484 "Login command failed with exit code: {:?}",
2485 status.code()
2486 )),
2487 None => Err(anyhow!("Login command terminated without exit status")),
2488 }
2489 } else {
2490 // Look for specific output patterns to detect successful login
2491 let mut exit_status = terminal
2492 .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
2493 .fuse();
2494
2495 let logged_in = cx
2496 .spawn({
2497 let terminal = terminal.clone();
2498 async move |cx| {
2499 loop {
2500 cx.background_executor().timer(Duration::from_secs(1)).await;
2501 let content =
2502 terminal.update(cx, |terminal, _cx| terminal.get_content())?;
2503 if success_patterns.iter().any(|pattern| content.contains(pattern))
2504 {
2505 return anyhow::Ok(());
2506 }
2507 }
2508 }
2509 })
2510 .fuse();
2511 futures::pin_mut!(logged_in);
2512 futures::select_biased! {
2513 result = logged_in => {
2514 if let Err(e) = result {
2515 log::error!("{e}");
2516 return Err(anyhow!("exited before logging in"));
2517 }
2518 }
2519 _ = exit_status => {
2520 if !previous_attempt && project.read_with(cx, |project, _| project.is_via_remote_server()) && login.label.contains("gemini") {
2521 return cx.update(|window, cx| Self::spawn_external_agent_login(login, workspace, project.clone(), method, true, window, cx))?.await
2522 }
2523 return Err(anyhow!("exited before logging in"));
2524 }
2525 }
2526 terminal.update(cx, |terminal, _| terminal.kill_active_task())?;
2527 Ok(())
2528 }
2529 })
2530 }
2531
2532 pub fn has_user_submitted_prompt(&self, cx: &App) -> bool {
2533 self.thread().is_some_and(|thread| {
2534 thread.read(cx).entries().iter().any(|entry| {
2535 matches!(
2536 entry,
2537 AgentThreadEntry::UserMessage(user_message) if user_message.id.is_some()
2538 )
2539 })
2540 })
2541 }
2542
2543 fn authorize_tool_call(
2544 &mut self,
2545 tool_call_id: acp::ToolCallId,
2546 option_id: acp::PermissionOptionId,
2547 option_kind: acp::PermissionOptionKind,
2548 window: &mut Window,
2549 cx: &mut Context<Self>,
2550 ) {
2551 let Some(thread) = self.thread() else {
2552 return;
2553 };
2554 let agent_telemetry_id = thread.read(cx).connection().telemetry_id();
2555
2556 telemetry::event!(
2557 "Agent Tool Call Authorized",
2558 agent = agent_telemetry_id,
2559 session = thread.read(cx).session_id(),
2560 option = option_kind
2561 );
2562
2563 thread.update(cx, |thread, cx| {
2564 thread.authorize_tool_call(tool_call_id, option_id, option_kind, cx);
2565 });
2566 if self.should_be_following {
2567 self.workspace
2568 .update(cx, |workspace, cx| {
2569 workspace.follow(CollaboratorId::Agent, window, cx);
2570 })
2571 .ok();
2572 }
2573 cx.notify();
2574 }
2575
2576 fn restore_checkpoint(&mut self, message_id: &UserMessageId, cx: &mut Context<Self>) {
2577 let Some(thread) = self.thread() else {
2578 return;
2579 };
2580
2581 thread
2582 .update(cx, |thread, cx| {
2583 thread.restore_checkpoint(message_id.clone(), cx)
2584 })
2585 .detach_and_log_err(cx);
2586 }
2587
2588 fn render_entry(
2589 &self,
2590 entry_ix: usize,
2591 total_entries: usize,
2592 entry: &AgentThreadEntry,
2593 window: &mut Window,
2594 cx: &Context<Self>,
2595 ) -> AnyElement {
2596 let is_indented = entry.is_indented();
2597 let is_first_indented = is_indented
2598 && self.thread().is_some_and(|thread| {
2599 thread
2600 .read(cx)
2601 .entries()
2602 .get(entry_ix.saturating_sub(1))
2603 .is_none_or(|entry| !entry.is_indented())
2604 });
2605
2606 let primary = match &entry {
2607 AgentThreadEntry::UserMessage(message) => {
2608 let Some(editor) = self
2609 .entry_view_state
2610 .read(cx)
2611 .entry(entry_ix)
2612 .and_then(|entry| entry.message_editor())
2613 .cloned()
2614 else {
2615 return Empty.into_any_element();
2616 };
2617
2618 let editing = self.editing_message == Some(entry_ix);
2619 let editor_focus = editor.focus_handle(cx).is_focused(window);
2620 let focus_border = cx.theme().colors().border_focused;
2621
2622 let rules_item = if entry_ix == 0 {
2623 self.render_rules_item(cx)
2624 } else {
2625 None
2626 };
2627
2628 let has_checkpoint_button = message
2629 .checkpoint
2630 .as_ref()
2631 .is_some_and(|checkpoint| checkpoint.show);
2632
2633 let agent_name = self.agent.name();
2634
2635 v_flex()
2636 .id(("user_message", entry_ix))
2637 .map(|this| {
2638 if is_first_indented {
2639 this.pt_0p5()
2640 } else if entry_ix == 0 && !has_checkpoint_button && rules_item.is_none() {
2641 this.pt(rems_from_px(18.))
2642 } else if rules_item.is_some() {
2643 this.pt_3()
2644 } else {
2645 this.pt_2()
2646 }
2647 })
2648 .pb_3()
2649 .px_2()
2650 .gap_1p5()
2651 .w_full()
2652 .children(rules_item)
2653 .children(message.id.clone().and_then(|message_id| {
2654 message.checkpoint.as_ref()?.show.then(|| {
2655 h_flex()
2656 .px_3()
2657 .gap_2()
2658 .child(Divider::horizontal())
2659 .child(
2660 Button::new("restore-checkpoint", "Restore Checkpoint")
2661 .icon(IconName::Undo)
2662 .icon_size(IconSize::XSmall)
2663 .icon_position(IconPosition::Start)
2664 .label_size(LabelSize::XSmall)
2665 .icon_color(Color::Muted)
2666 .color(Color::Muted)
2667 .tooltip(Tooltip::text("Restores all files in the project to the content they had at this point in the conversation."))
2668 .on_click(cx.listener(move |this, _, _window, cx| {
2669 this.restore_checkpoint(&message_id, cx);
2670 }))
2671 )
2672 .child(Divider::horizontal())
2673 })
2674 }))
2675 .child(
2676 div()
2677 .relative()
2678 .child(
2679 div()
2680 .py_3()
2681 .px_2()
2682 .rounded_md()
2683 .shadow_md()
2684 .bg(cx.theme().colors().editor_background)
2685 .border_1()
2686 .when(is_indented, |this| {
2687 this.py_2().px_2().shadow_sm()
2688 })
2689 .when(editing && !editor_focus, |this| this.border_dashed())
2690 .border_color(cx.theme().colors().border)
2691 .map(|this|{
2692 if editing && editor_focus {
2693 this.border_color(focus_border)
2694 } else if message.id.is_some() {
2695 this.hover(|s| s.border_color(focus_border.opacity(0.8)))
2696 } else {
2697 this
2698 }
2699 })
2700 .text_xs()
2701 .child(editor.clone().into_any_element())
2702 )
2703 .when(editor_focus, |this| {
2704 let base_container = h_flex()
2705 .absolute()
2706 .top_neg_3p5()
2707 .right_3()
2708 .gap_1()
2709 .rounded_sm()
2710 .border_1()
2711 .border_color(cx.theme().colors().border)
2712 .bg(cx.theme().colors().editor_background)
2713 .overflow_hidden();
2714
2715 if message.id.is_some() {
2716 this.child(
2717 base_container
2718 .child(
2719 IconButton::new("cancel", IconName::Close)
2720 .disabled(self.is_loading_contents)
2721 .icon_color(Color::Error)
2722 .icon_size(IconSize::XSmall)
2723 .on_click(cx.listener(Self::cancel_editing))
2724 )
2725 .child(
2726 if self.is_loading_contents {
2727 div()
2728 .id("loading-edited-message-content")
2729 .tooltip(Tooltip::text("Loading Added Context…"))
2730 .child(loading_contents_spinner(IconSize::XSmall))
2731 .into_any_element()
2732 } else {
2733 IconButton::new("regenerate", IconName::Return)
2734 .icon_color(Color::Muted)
2735 .icon_size(IconSize::XSmall)
2736 .tooltip(Tooltip::text(
2737 "Editing will restart the thread from this point."
2738 ))
2739 .on_click(cx.listener({
2740 let editor = editor.clone();
2741 move |this, _, window, cx| {
2742 this.regenerate(
2743 entry_ix, editor.clone(), window, cx,
2744 );
2745 }
2746 })).into_any_element()
2747 }
2748 )
2749 )
2750 } else {
2751 this.child(
2752 base_container
2753 .border_dashed()
2754 .child(
2755 IconButton::new("editing_unavailable", IconName::PencilUnavailable)
2756 .icon_size(IconSize::Small)
2757 .icon_color(Color::Muted)
2758 .style(ButtonStyle::Transparent)
2759 .tooltip(Tooltip::element({
2760 move |_, _| {
2761 v_flex()
2762 .gap_1()
2763 .child(Label::new("Unavailable Editing")).child(
2764 div().max_w_64().child(
2765 Label::new(format!(
2766 "Editing previous messages is not available for {} yet.",
2767 agent_name.clone()
2768 ))
2769 .size(LabelSize::Small)
2770 .color(Color::Muted),
2771 ),
2772 )
2773 .into_any_element()
2774 }
2775 }))
2776 )
2777 )
2778 }
2779 }),
2780 )
2781 .into_any()
2782 }
2783 AgentThreadEntry::AssistantMessage(AssistantMessage {
2784 chunks,
2785 indented: _,
2786 }) => {
2787 let mut is_blank = true;
2788 let is_last = entry_ix + 1 == total_entries;
2789
2790 let style = default_markdown_style(false, false, window, cx);
2791 let message_body = v_flex()
2792 .w_full()
2793 .gap_3()
2794 .children(chunks.iter().enumerate().filter_map(
2795 |(chunk_ix, chunk)| match chunk {
2796 AssistantMessageChunk::Message { block } => {
2797 block.markdown().and_then(|md| {
2798 let this_is_blank = md.read(cx).source().trim().is_empty();
2799 is_blank = is_blank && this_is_blank;
2800 if this_is_blank {
2801 return None;
2802 }
2803
2804 Some(
2805 self.render_markdown(md.clone(), style.clone())
2806 .into_any_element(),
2807 )
2808 })
2809 }
2810 AssistantMessageChunk::Thought { block } => {
2811 block.markdown().and_then(|md| {
2812 let this_is_blank = md.read(cx).source().trim().is_empty();
2813 is_blank = is_blank && this_is_blank;
2814 if this_is_blank {
2815 return None;
2816 }
2817 Some(
2818 self.render_thinking_block(
2819 entry_ix,
2820 chunk_ix,
2821 md.clone(),
2822 window,
2823 cx,
2824 )
2825 .into_any_element(),
2826 )
2827 })
2828 }
2829 },
2830 ))
2831 .into_any();
2832
2833 if is_blank {
2834 Empty.into_any()
2835 } else {
2836 v_flex()
2837 .px_5()
2838 .py_1p5()
2839 .when(is_last, |this| this.pb_4())
2840 .w_full()
2841 .text_ui(cx)
2842 .child(self.render_message_context_menu(entry_ix, message_body, cx))
2843 .into_any()
2844 }
2845 }
2846 AgentThreadEntry::ToolCall(tool_call) => {
2847 let has_terminals = tool_call.terminals().next().is_some();
2848
2849 div()
2850 .w_full()
2851 .map(|this| {
2852 if has_terminals {
2853 this.children(tool_call.terminals().map(|terminal| {
2854 self.render_terminal_tool_call(
2855 entry_ix, terminal, tool_call, window, cx,
2856 )
2857 }))
2858 } else {
2859 this.child(self.render_tool_call(entry_ix, tool_call, window, cx))
2860 }
2861 })
2862 .into_any()
2863 }
2864 };
2865
2866 let primary = if is_indented {
2867 let line_top = if is_first_indented {
2868 rems_from_px(-12.0)
2869 } else {
2870 rems_from_px(0.0)
2871 };
2872
2873 div()
2874 .relative()
2875 .w_full()
2876 .pl_5()
2877 .bg(cx.theme().colors().panel_background.opacity(0.2))
2878 .child(
2879 div()
2880 .absolute()
2881 .left(rems_from_px(18.0))
2882 .top(line_top)
2883 .bottom_0()
2884 .w_px()
2885 .bg(cx.theme().colors().border.opacity(0.6)),
2886 )
2887 .child(primary)
2888 .into_any_element()
2889 } else {
2890 primary
2891 };
2892
2893 let needs_confirmation = if let AgentThreadEntry::ToolCall(tool_call) = entry {
2894 matches!(
2895 tool_call.status,
2896 ToolCallStatus::WaitingForConfirmation { .. }
2897 )
2898 } else {
2899 false
2900 };
2901
2902 let Some(thread) = self.thread() else {
2903 return primary;
2904 };
2905
2906 let primary = if entry_ix == total_entries - 1 {
2907 v_flex()
2908 .w_full()
2909 .child(primary)
2910 .map(|this| {
2911 if needs_confirmation {
2912 this.child(self.render_generating(true, cx))
2913 } else {
2914 this.child(self.render_thread_controls(&thread, cx))
2915 }
2916 })
2917 .when_some(
2918 self.thread_feedback.comments_editor.clone(),
2919 |this, editor| this.child(Self::render_feedback_feedback_editor(editor, cx)),
2920 )
2921 .into_any_element()
2922 } else {
2923 primary
2924 };
2925
2926 if let Some(editing_index) = self.editing_message.as_ref()
2927 && *editing_index < entry_ix
2928 {
2929 let backdrop = div()
2930 .id(("backdrop", entry_ix))
2931 .size_full()
2932 .absolute()
2933 .inset_0()
2934 .bg(cx.theme().colors().panel_background)
2935 .opacity(0.8)
2936 .block_mouse_except_scroll()
2937 .on_click(cx.listener(Self::cancel_editing));
2938
2939 div()
2940 .relative()
2941 .child(primary)
2942 .child(backdrop)
2943 .into_any_element()
2944 } else {
2945 primary
2946 }
2947 }
2948
2949 fn render_message_context_menu(
2950 &self,
2951 entry_ix: usize,
2952 message_body: AnyElement,
2953 cx: &Context<Self>,
2954 ) -> AnyElement {
2955 let entity = cx.entity();
2956 let workspace = self.workspace.clone();
2957
2958 right_click_menu(format!("agent_context_menu-{}", entry_ix))
2959 .trigger(move |_, _, _| message_body)
2960 .menu(move |window, cx| {
2961 let focus = window.focused(cx);
2962 let entity = entity.clone();
2963 let workspace = workspace.clone();
2964
2965 ContextMenu::build(window, cx, move |menu, _, cx| {
2966 let is_at_top = entity.read(cx).list_state.logical_scroll_top().item_ix == 0;
2967
2968 let copy_this_agent_response =
2969 ContextMenuEntry::new("Copy This Agent Response").handler({
2970 let entity = entity.clone();
2971 move |_, cx| {
2972 entity.update(cx, |this, cx| {
2973 if let Some(thread) = this.thread() {
2974 let entries = thread.read(cx).entries();
2975 if let Some(text) =
2976 Self::get_agent_message_content(entries, entry_ix, cx)
2977 {
2978 cx.write_to_clipboard(ClipboardItem::new_string(text));
2979 }
2980 }
2981 });
2982 }
2983 });
2984
2985 let scroll_item = if is_at_top {
2986 ContextMenuEntry::new("Scroll to Bottom").handler({
2987 let entity = entity.clone();
2988 move |_, cx| {
2989 entity.update(cx, |this, cx| {
2990 this.scroll_to_bottom(cx);
2991 });
2992 }
2993 })
2994 } else {
2995 ContextMenuEntry::new("Scroll to Top").handler({
2996 let entity = entity.clone();
2997 move |_, cx| {
2998 entity.update(cx, |this, cx| {
2999 this.scroll_to_top(cx);
3000 });
3001 }
3002 })
3003 };
3004
3005 let open_thread_as_markdown = ContextMenuEntry::new("Open Thread as Markdown")
3006 .handler({
3007 let entity = entity.clone();
3008 let workspace = workspace.clone();
3009 move |window, cx| {
3010 if let Some(workspace) = workspace.upgrade() {
3011 entity
3012 .update(cx, |this, cx| {
3013 this.open_thread_as_markdown(workspace, window, cx)
3014 })
3015 .detach_and_log_err(cx);
3016 }
3017 }
3018 });
3019
3020 menu.when_some(focus, |menu, focus| menu.context(focus))
3021 .action("Copy Selection", Box::new(markdown::CopyAsMarkdown))
3022 .item(copy_this_agent_response)
3023 .separator()
3024 .item(scroll_item)
3025 .item(open_thread_as_markdown)
3026 })
3027 })
3028 .into_any_element()
3029 }
3030
3031 fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
3032 cx.theme()
3033 .colors()
3034 .element_background
3035 .blend(cx.theme().colors().editor_foreground.opacity(0.025))
3036 }
3037
3038 fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
3039 cx.theme().colors().border.opacity(0.8)
3040 }
3041
3042 fn tool_name_font_size(&self) -> Rems {
3043 rems_from_px(13.)
3044 }
3045
3046 fn render_thinking_block(
3047 &self,
3048 entry_ix: usize,
3049 chunk_ix: usize,
3050 chunk: Entity<Markdown>,
3051 window: &Window,
3052 cx: &Context<Self>,
3053 ) -> AnyElement {
3054 let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
3055 let card_header_id = SharedString::from("inner-card-header");
3056
3057 let key = (entry_ix, chunk_ix);
3058
3059 let is_open = self.expanded_thinking_blocks.contains(&key);
3060
3061 let scroll_handle = self
3062 .entry_view_state
3063 .read(cx)
3064 .entry(entry_ix)
3065 .and_then(|entry| entry.scroll_handle_for_assistant_message_chunk(chunk_ix));
3066
3067 let thinking_content = {
3068 div()
3069 .id(("thinking-content", chunk_ix))
3070 .when_some(scroll_handle, |this, scroll_handle| {
3071 this.track_scroll(&scroll_handle)
3072 })
3073 .text_ui_sm(cx)
3074 .overflow_hidden()
3075 .child(
3076 self.render_markdown(chunk, default_markdown_style(false, false, window, cx)),
3077 )
3078 };
3079
3080 v_flex()
3081 .gap_1()
3082 .child(
3083 h_flex()
3084 .id(header_id)
3085 .group(&card_header_id)
3086 .relative()
3087 .w_full()
3088 .pr_1()
3089 .justify_between()
3090 .child(
3091 h_flex()
3092 .h(window.line_height() - px(2.))
3093 .gap_1p5()
3094 .overflow_hidden()
3095 .child(
3096 Icon::new(IconName::ToolThink)
3097 .size(IconSize::Small)
3098 .color(Color::Muted),
3099 )
3100 .child(
3101 div()
3102 .text_size(self.tool_name_font_size())
3103 .text_color(cx.theme().colors().text_muted)
3104 .child("Thinking"),
3105 ),
3106 )
3107 .child(
3108 Disclosure::new(("expand", entry_ix), is_open)
3109 .opened_icon(IconName::ChevronUp)
3110 .closed_icon(IconName::ChevronDown)
3111 .visible_on_hover(&card_header_id)
3112 .on_click(cx.listener({
3113 move |this, _event, _window, cx| {
3114 if is_open {
3115 this.expanded_thinking_blocks.remove(&key);
3116 } else {
3117 this.expanded_thinking_blocks.insert(key);
3118 }
3119 cx.notify();
3120 }
3121 })),
3122 )
3123 .on_click(cx.listener({
3124 move |this, _event, _window, cx| {
3125 if is_open {
3126 this.expanded_thinking_blocks.remove(&key);
3127 } else {
3128 this.expanded_thinking_blocks.insert(key);
3129 }
3130 cx.notify();
3131 }
3132 })),
3133 )
3134 .when(is_open, |this| {
3135 this.child(
3136 div()
3137 .ml_1p5()
3138 .pl_3p5()
3139 .border_l_1()
3140 .border_color(self.tool_card_border_color(cx))
3141 .child(thinking_content),
3142 )
3143 })
3144 .into_any_element()
3145 }
3146
3147 fn render_tool_call(
3148 &self,
3149 entry_ix: usize,
3150 tool_call: &ToolCall,
3151 window: &Window,
3152 cx: &Context<Self>,
3153 ) -> Div {
3154 let has_location = tool_call.locations.len() == 1;
3155 let card_header_id = SharedString::from("inner-tool-call-header");
3156
3157 let failed_or_canceled = match &tool_call.status {
3158 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed => true,
3159 _ => false,
3160 };
3161
3162 let needs_confirmation = matches!(
3163 tool_call.status,
3164 ToolCallStatus::WaitingForConfirmation { .. }
3165 );
3166 let is_terminal_tool = matches!(tool_call.kind, acp::ToolKind::Execute);
3167
3168 let is_edit =
3169 matches!(tool_call.kind, acp::ToolKind::Edit) || tool_call.diffs().next().is_some();
3170 let is_subagent = tool_call.is_subagent();
3171
3172 // For subagent tool calls, render the subagent cards directly without wrapper
3173 if is_subagent {
3174 return self.render_subagent_tool_call(entry_ix, tool_call, window, cx);
3175 }
3176
3177 let is_cancelled_edit = is_edit && matches!(tool_call.status, ToolCallStatus::Canceled);
3178 let has_revealed_diff = tool_call.diffs().next().is_some_and(|diff| {
3179 self.entry_view_state
3180 .read(cx)
3181 .entry(entry_ix)
3182 .and_then(|entry| entry.editor_for_diff(diff))
3183 .is_some()
3184 && diff.read(cx).has_revealed_range(cx)
3185 });
3186
3187 let use_card_layout = needs_confirmation || is_edit || is_terminal_tool;
3188
3189 let has_image_content = tool_call.content.iter().any(|c| c.image().is_some());
3190 let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
3191 let is_open = needs_confirmation || self.expanded_tool_calls.contains(&tool_call.id);
3192
3193 let should_show_raw_input = !is_terminal_tool && !is_edit && !has_image_content;
3194
3195 let input_output_header = |label: SharedString| {
3196 Label::new(label)
3197 .size(LabelSize::XSmall)
3198 .color(Color::Muted)
3199 .buffer_font(cx)
3200 };
3201
3202 let tool_output_display = if is_open {
3203 match &tool_call.status {
3204 ToolCallStatus::WaitingForConfirmation { options, .. } => v_flex()
3205 .w_full()
3206 .children(
3207 tool_call
3208 .content
3209 .iter()
3210 .enumerate()
3211 .map(|(content_ix, content)| {
3212 div()
3213 .child(self.render_tool_call_content(
3214 entry_ix,
3215 content,
3216 content_ix,
3217 tool_call,
3218 use_card_layout,
3219 has_image_content,
3220 failed_or_canceled,
3221 window,
3222 cx,
3223 ))
3224 .into_any_element()
3225 }),
3226 )
3227 .when(should_show_raw_input, |this| {
3228 let is_raw_input_expanded =
3229 self.expanded_tool_call_raw_inputs.contains(&tool_call.id);
3230
3231 let input_header = if is_raw_input_expanded {
3232 "Raw Input:"
3233 } else {
3234 "View Raw Input"
3235 };
3236
3237 this.child(
3238 v_flex()
3239 .p_2()
3240 .gap_1()
3241 .border_t_1()
3242 .border_color(self.tool_card_border_color(cx))
3243 .child(
3244 h_flex()
3245 .id("disclosure_container")
3246 .pl_0p5()
3247 .gap_1()
3248 .justify_between()
3249 .rounded_xs()
3250 .hover(|s| s.bg(cx.theme().colors().element_hover))
3251 .child(input_output_header(input_header.into()))
3252 .child(
3253 Disclosure::new(
3254 ("raw-input-disclosure", entry_ix),
3255 is_raw_input_expanded,
3256 )
3257 .opened_icon(IconName::ChevronUp)
3258 .closed_icon(IconName::ChevronDown),
3259 )
3260 .on_click(cx.listener({
3261 let id = tool_call.id.clone();
3262
3263 move |this: &mut Self, _, _, cx| {
3264 if this.expanded_tool_call_raw_inputs.contains(&id)
3265 {
3266 this.expanded_tool_call_raw_inputs.remove(&id);
3267 } else {
3268 this.expanded_tool_call_raw_inputs
3269 .insert(id.clone());
3270 }
3271 cx.notify();
3272 }
3273 })),
3274 )
3275 .when(is_raw_input_expanded, |this| {
3276 this.children(tool_call.raw_input_markdown.clone().map(
3277 |input| {
3278 self.render_markdown(
3279 input,
3280 default_markdown_style(false, false, window, cx),
3281 )
3282 },
3283 ))
3284 }),
3285 )
3286 })
3287 .child(self.render_permission_buttons(
3288 options,
3289 entry_ix,
3290 tool_call.id.clone(),
3291 cx,
3292 ))
3293 .into_any(),
3294 ToolCallStatus::Pending | ToolCallStatus::InProgress
3295 if is_edit
3296 && tool_call.content.is_empty()
3297 && self.as_native_connection(cx).is_some() =>
3298 {
3299 self.render_diff_loading(cx).into_any()
3300 }
3301 ToolCallStatus::Pending
3302 | ToolCallStatus::InProgress
3303 | ToolCallStatus::Completed
3304 | ToolCallStatus::Failed
3305 | ToolCallStatus::Canceled => {
3306 v_flex()
3307 .when(should_show_raw_input, |this| {
3308 this.mt_1p5().w_full().child(
3309 v_flex()
3310 .ml(rems(0.4))
3311 .px_3p5()
3312 .pb_1()
3313 .gap_1()
3314 .border_l_1()
3315 .border_color(self.tool_card_border_color(cx))
3316 .child(input_output_header("Raw Input:".into()))
3317 .children(tool_call.raw_input_markdown.clone().map(|input| {
3318 div().id(("tool-call-raw-input-markdown", entry_ix)).child(
3319 self.render_markdown(
3320 input,
3321 default_markdown_style(false, false, window, cx),
3322 ),
3323 )
3324 }))
3325 .child(input_output_header("Output:".into())),
3326 )
3327 })
3328 .children(tool_call.content.iter().enumerate().map(
3329 |(content_ix, content)| {
3330 div().id(("tool-call-output", entry_ix)).child(
3331 self.render_tool_call_content(
3332 entry_ix,
3333 content,
3334 content_ix,
3335 tool_call,
3336 use_card_layout,
3337 has_image_content,
3338 failed_or_canceled,
3339 window,
3340 cx,
3341 ),
3342 )
3343 },
3344 ))
3345 .into_any()
3346 }
3347 ToolCallStatus::Rejected => Empty.into_any(),
3348 }
3349 .into()
3350 } else {
3351 None
3352 };
3353
3354 v_flex()
3355 .map(|this| {
3356 if use_card_layout {
3357 this.my_1p5()
3358 .rounded_md()
3359 .border_1()
3360 .when(failed_or_canceled, |this| this.border_dashed())
3361 .border_color(self.tool_card_border_color(cx))
3362 .bg(cx.theme().colors().editor_background)
3363 .overflow_hidden()
3364 } else {
3365 this.my_1()
3366 }
3367 })
3368 .map(|this| {
3369 if has_location && !use_card_layout {
3370 this.ml_4()
3371 } else {
3372 this.ml_5()
3373 }
3374 })
3375 .mr_5()
3376 .map(|this| {
3377 if is_terminal_tool {
3378 let label_source = tool_call.label.read(cx).source();
3379 this.child(self.render_collapsible_command(true, label_source, &tool_call.id, cx))
3380 } else {
3381 this.child(
3382 h_flex()
3383 .group(&card_header_id)
3384 .relative()
3385 .w_full()
3386 .gap_1()
3387 .justify_between()
3388 .when(use_card_layout, |this| {
3389 this.p_0p5()
3390 .rounded_t(rems_from_px(5.))
3391 .bg(self.tool_card_header_bg(cx))
3392 })
3393 .child(self.render_tool_call_label(
3394 entry_ix,
3395 tool_call,
3396 is_edit,
3397 is_cancelled_edit,
3398 has_revealed_diff,
3399 use_card_layout,
3400 window,
3401 cx,
3402 ))
3403 .when(is_collapsible || failed_or_canceled, |this| {
3404 let diff_for_discard =
3405 if has_revealed_diff && is_cancelled_edit && cx.has_flag::<AgentV2FeatureFlag>() {
3406 tool_call.diffs().next().cloned()
3407 } else {
3408 None
3409 };
3410 this.child(
3411 h_flex()
3412 .px_1()
3413 .when_some(diff_for_discard.clone(), |this, _| this.pr_0p5())
3414 .gap_1()
3415 .when(is_collapsible, |this| {
3416 this.child(
3417 Disclosure::new(("expand-output", entry_ix), is_open)
3418 .opened_icon(IconName::ChevronUp)
3419 .closed_icon(IconName::ChevronDown)
3420 .visible_on_hover(&card_header_id)
3421 .on_click(cx.listener({
3422 let id = tool_call.id.clone();
3423 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
3424 if is_open {
3425 this.expanded_tool_calls.remove(&id);
3426 } else {
3427 this.expanded_tool_calls.insert(id.clone());
3428 }
3429 cx.notify();
3430 }
3431 })),
3432 )
3433 })
3434 .when(failed_or_canceled, |this| {
3435 if is_cancelled_edit && !has_revealed_diff {
3436 this.child(
3437 div()
3438 .id(entry_ix)
3439 .tooltip(Tooltip::text(
3440 "Interrupted Edit",
3441 ))
3442 .child(
3443 Icon::new(IconName::XCircle)
3444 .color(Color::Muted)
3445 .size(IconSize::Small),
3446 ),
3447 )
3448 } else if is_cancelled_edit {
3449 this
3450 } else {
3451 this.child(
3452 Icon::new(IconName::Close)
3453 .color(Color::Error)
3454 .size(IconSize::Small),
3455 )
3456 }
3457 })
3458 .when_some(diff_for_discard, |this, diff| {
3459 let tool_call_id = tool_call.id.clone();
3460 let is_discarded = self.discarded_partial_edits.contains(&tool_call_id);
3461 this.when(!is_discarded, |this| {
3462 this.child(
3463 IconButton::new(
3464 ("discard-partial-edit", entry_ix),
3465 IconName::Undo,
3466 )
3467 .icon_size(IconSize::Small)
3468 .tooltip(move |_, cx| Tooltip::with_meta(
3469 "Discard Interrupted Edit",
3470 None,
3471 "You can discard this interrupted partial edit and restore the original file content.",
3472 cx
3473 ))
3474 .on_click(cx.listener({
3475 let tool_call_id = tool_call_id.clone();
3476 move |this, _, _window, cx| {
3477 let diff_data = diff.read(cx);
3478 let base_text = diff_data.base_text().clone();
3479 let buffer = diff_data.buffer().clone();
3480 buffer.update(cx, |buffer, cx| {
3481 buffer.set_text(base_text.as_ref(), cx);
3482 });
3483 this.discarded_partial_edits.insert(tool_call_id.clone());
3484 cx.notify();
3485 }
3486 })),
3487 )
3488 })
3489 })
3490
3491 )
3492 }),
3493 )
3494 }
3495 })
3496 .children(tool_output_display)
3497 }
3498
3499 fn render_tool_call_label(
3500 &self,
3501 entry_ix: usize,
3502 tool_call: &ToolCall,
3503 is_edit: bool,
3504 has_failed: bool,
3505 has_revealed_diff: bool,
3506 use_card_layout: bool,
3507 window: &Window,
3508 cx: &Context<Self>,
3509 ) -> Div {
3510 let has_location = tool_call.locations.len() == 1;
3511 let is_file = tool_call.kind == acp::ToolKind::Edit && has_location;
3512
3513 let file_icon = if has_location {
3514 FileIcons::get_icon(&tool_call.locations[0].path, cx)
3515 .map(Icon::from_path)
3516 .unwrap_or(Icon::new(IconName::ToolPencil))
3517 } else {
3518 Icon::new(IconName::ToolPencil)
3519 };
3520
3521 let tool_icon = if is_file && has_failed && has_revealed_diff {
3522 div()
3523 .id(entry_ix)
3524 .tooltip(Tooltip::text("Interrupted Edit"))
3525 .child(DecoratedIcon::new(
3526 file_icon,
3527 Some(
3528 IconDecoration::new(
3529 IconDecorationKind::Triangle,
3530 self.tool_card_header_bg(cx),
3531 cx,
3532 )
3533 .color(cx.theme().status().warning)
3534 .position(gpui::Point {
3535 x: px(-2.),
3536 y: px(-2.),
3537 }),
3538 ),
3539 ))
3540 .into_any_element()
3541 } else if is_file {
3542 div().child(file_icon).into_any_element()
3543 } else {
3544 div()
3545 .child(
3546 Icon::new(match tool_call.kind {
3547 acp::ToolKind::Read => IconName::ToolSearch,
3548 acp::ToolKind::Edit => IconName::ToolPencil,
3549 acp::ToolKind::Delete => IconName::ToolDeleteFile,
3550 acp::ToolKind::Move => IconName::ArrowRightLeft,
3551 acp::ToolKind::Search => IconName::ToolSearch,
3552 acp::ToolKind::Execute => IconName::ToolTerminal,
3553 acp::ToolKind::Think => IconName::ToolThink,
3554 acp::ToolKind::Fetch => IconName::ToolWeb,
3555 acp::ToolKind::SwitchMode => IconName::ArrowRightLeft,
3556 acp::ToolKind::Other | _ => IconName::ToolHammer,
3557 })
3558 .size(IconSize::Small)
3559 .color(Color::Muted),
3560 )
3561 .into_any_element()
3562 };
3563
3564 let gradient_overlay = {
3565 div()
3566 .absolute()
3567 .top_0()
3568 .right_0()
3569 .w_12()
3570 .h_full()
3571 .map(|this| {
3572 if use_card_layout {
3573 this.bg(linear_gradient(
3574 90.,
3575 linear_color_stop(self.tool_card_header_bg(cx), 1.),
3576 linear_color_stop(self.tool_card_header_bg(cx).opacity(0.2), 0.),
3577 ))
3578 } else {
3579 this.bg(linear_gradient(
3580 90.,
3581 linear_color_stop(cx.theme().colors().panel_background, 1.),
3582 linear_color_stop(
3583 cx.theme().colors().panel_background.opacity(0.2),
3584 0.,
3585 ),
3586 ))
3587 }
3588 })
3589 };
3590
3591 h_flex()
3592 .relative()
3593 .w_full()
3594 .h(window.line_height() - px(2.))
3595 .text_size(self.tool_name_font_size())
3596 .gap_1p5()
3597 .when(has_location || use_card_layout, |this| this.px_1())
3598 .when(has_location, |this| {
3599 this.cursor(CursorStyle::PointingHand)
3600 .rounded(rems_from_px(3.)) // Concentric border radius
3601 .hover(|s| s.bg(cx.theme().colors().element_hover.opacity(0.5)))
3602 })
3603 .overflow_hidden()
3604 .child(tool_icon)
3605 .child(if has_location {
3606 h_flex()
3607 .id(("open-tool-call-location", entry_ix))
3608 .w_full()
3609 .map(|this| {
3610 if use_card_layout {
3611 this.text_color(cx.theme().colors().text)
3612 } else {
3613 this.text_color(cx.theme().colors().text_muted)
3614 }
3615 })
3616 .child(self.render_markdown(
3617 tool_call.label.clone(),
3618 MarkdownStyle {
3619 prevent_mouse_interaction: true,
3620 ..default_markdown_style(false, true, window, cx)
3621 },
3622 ))
3623 .tooltip(Tooltip::text("Go to File"))
3624 .on_click(cx.listener(move |this, _, window, cx| {
3625 this.open_tool_call_location(entry_ix, 0, window, cx);
3626 }))
3627 .into_any_element()
3628 } else {
3629 h_flex()
3630 .w_full()
3631 .child(self.render_markdown(
3632 tool_call.label.clone(),
3633 default_markdown_style(false, true, window, cx),
3634 ))
3635 .into_any()
3636 })
3637 .when(!is_edit, |this| this.child(gradient_overlay))
3638 }
3639
3640 fn render_tool_call_content(
3641 &self,
3642 entry_ix: usize,
3643 content: &ToolCallContent,
3644 context_ix: usize,
3645 tool_call: &ToolCall,
3646 card_layout: bool,
3647 is_image_tool_call: bool,
3648 has_failed: bool,
3649 window: &Window,
3650 cx: &Context<Self>,
3651 ) -> AnyElement {
3652 match content {
3653 ToolCallContent::ContentBlock(content) => {
3654 if let Some(resource_link) = content.resource_link() {
3655 self.render_resource_link(resource_link, cx)
3656 } else if let Some(markdown) = content.markdown() {
3657 self.render_markdown_output(
3658 markdown.clone(),
3659 tool_call.id.clone(),
3660 context_ix,
3661 card_layout,
3662 window,
3663 cx,
3664 )
3665 } else if let Some(image) = content.image() {
3666 let location = tool_call.locations.first().cloned();
3667 self.render_image_output(
3668 entry_ix,
3669 image.clone(),
3670 location,
3671 card_layout,
3672 is_image_tool_call,
3673 cx,
3674 )
3675 } else {
3676 Empty.into_any_element()
3677 }
3678 }
3679 ToolCallContent::Diff(diff) => {
3680 self.render_diff_editor(entry_ix, diff, tool_call, has_failed, cx)
3681 }
3682 ToolCallContent::Terminal(terminal) => {
3683 self.render_terminal_tool_call(entry_ix, terminal, tool_call, window, cx)
3684 }
3685 ToolCallContent::SubagentThread(_thread) => {
3686 // Subagent threads are rendered by render_subagent_tool_call, not here
3687 Empty.into_any_element()
3688 }
3689 }
3690 }
3691
3692 fn render_subagent_tool_call(
3693 &self,
3694 entry_ix: usize,
3695 tool_call: &ToolCall,
3696 window: &Window,
3697 cx: &Context<Self>,
3698 ) -> Div {
3699 let subagent_threads: Vec<_> = tool_call
3700 .content
3701 .iter()
3702 .filter_map(|c| c.subagent_thread().cloned())
3703 .collect();
3704
3705 let tool_call_status = &tool_call.status;
3706
3707 v_flex()
3708 .mx_5()
3709 .my_1p5()
3710 .gap_3()
3711 .children(
3712 subagent_threads
3713 .into_iter()
3714 .enumerate()
3715 .map(|(context_ix, thread)| {
3716 self.render_subagent_card(
3717 entry_ix,
3718 context_ix,
3719 &thread,
3720 tool_call_status,
3721 window,
3722 cx,
3723 )
3724 }),
3725 )
3726 }
3727
3728 fn render_subagent_card(
3729 &self,
3730 entry_ix: usize,
3731 context_ix: usize,
3732 thread: &Entity<AcpThread>,
3733 tool_call_status: &ToolCallStatus,
3734 window: &Window,
3735 cx: &Context<Self>,
3736 ) -> AnyElement {
3737 let thread_read = thread.read(cx);
3738 let session_id = thread_read.session_id().clone();
3739 let title = thread_read.title();
3740 let action_log = thread_read.action_log();
3741 let changed_buffers = action_log.read(cx).changed_buffers(cx);
3742
3743 let is_expanded = self.expanded_subagents.contains(&session_id);
3744 let files_changed = changed_buffers.len();
3745 let diff_stats = DiffStats::all_files(&changed_buffers, cx);
3746
3747 let is_running = matches!(
3748 tool_call_status,
3749 ToolCallStatus::Pending | ToolCallStatus::InProgress
3750 );
3751 let is_canceled_or_failed = matches!(
3752 tool_call_status,
3753 ToolCallStatus::Canceled | ToolCallStatus::Failed | ToolCallStatus::Rejected
3754 );
3755
3756 let card_header_id =
3757 SharedString::from(format!("subagent-header-{}-{}", entry_ix, context_ix));
3758 let diff_stat_id = SharedString::from(format!("subagent-diff-{}-{}", entry_ix, context_ix));
3759
3760 let icon = h_flex().w_4().justify_center().child(if is_running {
3761 SpinnerLabel::new()
3762 .size(LabelSize::Small)
3763 .into_any_element()
3764 } else if is_canceled_or_failed {
3765 Icon::new(IconName::Close)
3766 .size(IconSize::Small)
3767 .color(Color::Error)
3768 .into_any_element()
3769 } else {
3770 Icon::new(IconName::Check)
3771 .size(IconSize::Small)
3772 .color(Color::Success)
3773 .into_any_element()
3774 });
3775
3776 let has_expandable_content = thread_read.entries().iter().rev().any(|entry| {
3777 if let AgentThreadEntry::AssistantMessage(msg) = entry {
3778 msg.chunks.iter().any(|chunk| match chunk {
3779 AssistantMessageChunk::Message { block } => block.markdown().is_some(),
3780 AssistantMessageChunk::Thought { block } => block.markdown().is_some(),
3781 })
3782 } else {
3783 false
3784 }
3785 });
3786
3787 v_flex()
3788 .w_full()
3789 .rounded_md()
3790 .border_1()
3791 .border_color(self.tool_card_border_color(cx))
3792 .overflow_hidden()
3793 .child(
3794 h_flex()
3795 .group(&card_header_id)
3796 .py_1()
3797 .px_1p5()
3798 .w_full()
3799 .gap_1()
3800 .justify_between()
3801 .bg(self.tool_card_header_bg(cx))
3802 .child(
3803 h_flex()
3804 .gap_1p5()
3805 .child(icon)
3806 .child(
3807 Label::new(title.to_string())
3808 .size(LabelSize::Small)
3809 .color(Color::Default),
3810 )
3811 .when(files_changed > 0, |this| {
3812 this.child(
3813 h_flex()
3814 .gap_1()
3815 .child(
3816 Label::new(format!(
3817 "— {} {} changed",
3818 files_changed,
3819 if files_changed == 1 { "file" } else { "files" }
3820 ))
3821 .size(LabelSize::Small)
3822 .color(Color::Muted),
3823 )
3824 .child(DiffStat::new(
3825 diff_stat_id.clone(),
3826 diff_stats.lines_added as usize,
3827 diff_stats.lines_removed as usize,
3828 )),
3829 )
3830 }),
3831 )
3832 .child(
3833 h_flex()
3834 .gap_1p5()
3835 .when(is_running, |buttons| {
3836 buttons.child(
3837 Button::new(
3838 SharedString::from(format!(
3839 "stop-subagent-{}-{}",
3840 entry_ix, context_ix
3841 )),
3842 "Stop",
3843 )
3844 .icon(IconName::Stop)
3845 .icon_position(IconPosition::Start)
3846 .icon_size(IconSize::Small)
3847 .icon_color(Color::Error)
3848 .label_size(LabelSize::Small)
3849 .tooltip(Tooltip::text("Stop this subagent"))
3850 .on_click({
3851 let thread = thread.clone();
3852 cx.listener(move |_this, _event, _window, cx| {
3853 thread.update(cx, |thread, _cx| {
3854 thread.stop_by_user();
3855 });
3856 })
3857 }),
3858 )
3859 })
3860 .child(
3861 IconButton::new(
3862 SharedString::from(format!(
3863 "subagent-disclosure-{}-{}",
3864 entry_ix, context_ix
3865 )),
3866 if is_expanded {
3867 IconName::ChevronUp
3868 } else {
3869 IconName::ChevronDown
3870 },
3871 )
3872 .shape(IconButtonShape::Square)
3873 .icon_color(Color::Muted)
3874 .icon_size(IconSize::Small)
3875 .disabled(!has_expandable_content)
3876 .when(has_expandable_content, |button| {
3877 button.on_click(cx.listener({
3878 move |this, _, _, cx| {
3879 if this.expanded_subagents.contains(&session_id) {
3880 this.expanded_subagents.remove(&session_id);
3881 } else {
3882 this.expanded_subagents.insert(session_id.clone());
3883 }
3884 cx.notify();
3885 }
3886 }))
3887 })
3888 .when(
3889 !has_expandable_content,
3890 |button| {
3891 button.tooltip(Tooltip::text("Waiting for content..."))
3892 },
3893 ),
3894 ),
3895 ),
3896 )
3897 .when(is_expanded, |this| {
3898 this.child(
3899 self.render_subagent_expanded_content(entry_ix, context_ix, thread, window, cx),
3900 )
3901 })
3902 .into_any_element()
3903 }
3904
3905 fn render_subagent_expanded_content(
3906 &self,
3907 _entry_ix: usize,
3908 _context_ix: usize,
3909 thread: &Entity<AcpThread>,
3910 window: &Window,
3911 cx: &Context<Self>,
3912 ) -> impl IntoElement {
3913 let thread_read = thread.read(cx);
3914 let session_id = thread_read.session_id().clone();
3915 let entries = thread_read.entries();
3916
3917 // Find the most recent agent message with any content (message or thought)
3918 let last_assistant_markdown = entries.iter().rev().find_map(|entry| {
3919 if let AgentThreadEntry::AssistantMessage(msg) = entry {
3920 msg.chunks.iter().find_map(|chunk| match chunk {
3921 AssistantMessageChunk::Message { block } => block.markdown().cloned(),
3922 AssistantMessageChunk::Thought { block } => block.markdown().cloned(),
3923 })
3924 } else {
3925 None
3926 }
3927 });
3928
3929 let scroll_handle = self
3930 .subagent_scroll_handles
3931 .borrow_mut()
3932 .entry(session_id.clone())
3933 .or_default()
3934 .clone();
3935
3936 scroll_handle.scroll_to_bottom();
3937 let editor_bg = cx.theme().colors().editor_background;
3938
3939 let gradient_overlay = {
3940 div().absolute().inset_0().bg(linear_gradient(
3941 180.,
3942 linear_color_stop(editor_bg, 0.),
3943 linear_color_stop(editor_bg.opacity(0.), 0.15),
3944 ))
3945 };
3946
3947 div()
3948 .relative()
3949 .w_full()
3950 .max_h_56()
3951 .p_2p5()
3952 .text_ui(cx)
3953 .border_t_1()
3954 .border_color(self.tool_card_border_color(cx))
3955 .bg(editor_bg.opacity(0.4))
3956 .overflow_hidden()
3957 .child(
3958 div()
3959 .id(format!("subagent-content-{}", session_id))
3960 .size_full()
3961 .track_scroll(&scroll_handle)
3962 .when_some(last_assistant_markdown, |this, markdown| {
3963 this.child(self.render_markdown(
3964 markdown,
3965 default_markdown_style(false, false, window, cx),
3966 ))
3967 }),
3968 )
3969 .child(gradient_overlay)
3970 }
3971
3972 fn render_markdown_output(
3973 &self,
3974 markdown: Entity<Markdown>,
3975 tool_call_id: acp::ToolCallId,
3976 context_ix: usize,
3977 card_layout: bool,
3978 window: &Window,
3979 cx: &Context<Self>,
3980 ) -> AnyElement {
3981 let button_id = SharedString::from(format!("tool_output-{:?}", tool_call_id));
3982
3983 v_flex()
3984 .gap_2()
3985 .map(|this| {
3986 if card_layout {
3987 this.when(context_ix > 0, |this| {
3988 this.pt_2()
3989 .border_t_1()
3990 .border_color(self.tool_card_border_color(cx))
3991 })
3992 } else {
3993 this.ml(rems(0.4))
3994 .px_3p5()
3995 .border_l_1()
3996 .border_color(self.tool_card_border_color(cx))
3997 }
3998 })
3999 .text_xs()
4000 .text_color(cx.theme().colors().text_muted)
4001 .child(self.render_markdown(markdown, default_markdown_style(false, false, window, cx)))
4002 .when(!card_layout, |this| {
4003 this.child(
4004 IconButton::new(button_id, IconName::ChevronUp)
4005 .full_width()
4006 .style(ButtonStyle::Outlined)
4007 .icon_color(Color::Muted)
4008 .on_click(cx.listener({
4009 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
4010 this.expanded_tool_calls.remove(&tool_call_id);
4011 cx.notify();
4012 }
4013 })),
4014 )
4015 })
4016 .into_any_element()
4017 }
4018
4019 fn render_image_output(
4020 &self,
4021 entry_ix: usize,
4022 image: Arc<gpui::Image>,
4023 location: Option<acp::ToolCallLocation>,
4024 card_layout: bool,
4025 show_dimensions: bool,
4026 cx: &Context<Self>,
4027 ) -> AnyElement {
4028 let dimensions_label = if show_dimensions {
4029 let format_name = match image.format() {
4030 gpui::ImageFormat::Png => "PNG",
4031 gpui::ImageFormat::Jpeg => "JPEG",
4032 gpui::ImageFormat::Webp => "WebP",
4033 gpui::ImageFormat::Gif => "GIF",
4034 gpui::ImageFormat::Svg => "SVG",
4035 gpui::ImageFormat::Bmp => "BMP",
4036 gpui::ImageFormat::Tiff => "TIFF",
4037 gpui::ImageFormat::Ico => "ICO",
4038 };
4039 let dimensions = image::ImageReader::new(std::io::Cursor::new(image.bytes()))
4040 .with_guessed_format()
4041 .ok()
4042 .and_then(|reader| reader.into_dimensions().ok());
4043 dimensions.map(|(w, h)| format!("{}×{} {}", w, h, format_name))
4044 } else {
4045 None
4046 };
4047
4048 v_flex()
4049 .gap_2()
4050 .map(|this| {
4051 if card_layout {
4052 this
4053 } else {
4054 this.ml(rems(0.4))
4055 .px_3p5()
4056 .border_l_1()
4057 .border_color(self.tool_card_border_color(cx))
4058 }
4059 })
4060 .when(dimensions_label.is_some() || location.is_some(), |this| {
4061 this.child(
4062 h_flex()
4063 .w_full()
4064 .justify_between()
4065 .items_center()
4066 .children(dimensions_label.map(|label| {
4067 Label::new(label)
4068 .size(LabelSize::XSmall)
4069 .color(Color::Muted)
4070 .buffer_font(cx)
4071 }))
4072 .when_some(location, |this, _loc| {
4073 this.child(
4074 Button::new(("go-to-file", entry_ix), "Go to File")
4075 .label_size(LabelSize::Small)
4076 .on_click(cx.listener(move |this, _, window, cx| {
4077 this.open_tool_call_location(entry_ix, 0, window, cx);
4078 })),
4079 )
4080 }),
4081 )
4082 })
4083 .child(
4084 img(image)
4085 .max_w_96()
4086 .max_h_96()
4087 .object_fit(ObjectFit::ScaleDown),
4088 )
4089 .into_any_element()
4090 }
4091
4092 fn render_resource_link(
4093 &self,
4094 resource_link: &acp::ResourceLink,
4095 cx: &Context<Self>,
4096 ) -> AnyElement {
4097 let uri: SharedString = resource_link.uri.clone().into();
4098 let is_file = resource_link.uri.strip_prefix("file://");
4099
4100 let label: SharedString = if let Some(abs_path) = is_file {
4101 if let Some(project_path) = self
4102 .project
4103 .read(cx)
4104 .project_path_for_absolute_path(&Path::new(abs_path), cx)
4105 && let Some(worktree) = self
4106 .project
4107 .read(cx)
4108 .worktree_for_id(project_path.worktree_id, cx)
4109 {
4110 worktree
4111 .read(cx)
4112 .full_path(&project_path.path)
4113 .to_string_lossy()
4114 .to_string()
4115 .into()
4116 } else {
4117 abs_path.to_string().into()
4118 }
4119 } else {
4120 uri.clone()
4121 };
4122
4123 let button_id = SharedString::from(format!("item-{}", uri));
4124
4125 div()
4126 .ml(rems(0.4))
4127 .pl_2p5()
4128 .border_l_1()
4129 .border_color(self.tool_card_border_color(cx))
4130 .overflow_hidden()
4131 .child(
4132 Button::new(button_id, label)
4133 .label_size(LabelSize::Small)
4134 .color(Color::Muted)
4135 .truncate(true)
4136 .when(is_file.is_none(), |this| {
4137 this.icon(IconName::ArrowUpRight)
4138 .icon_size(IconSize::XSmall)
4139 .icon_color(Color::Muted)
4140 })
4141 .on_click(cx.listener({
4142 let workspace = self.workspace.clone();
4143 move |_, _, window, cx: &mut Context<Self>| {
4144 Self::open_link(uri.clone(), &workspace, window, cx);
4145 }
4146 })),
4147 )
4148 .into_any_element()
4149 }
4150
4151 fn render_permission_buttons(
4152 &self,
4153 options: &PermissionOptions,
4154 entry_ix: usize,
4155 tool_call_id: acp::ToolCallId,
4156 cx: &Context<Self>,
4157 ) -> Div {
4158 match options {
4159 PermissionOptions::Flat(options) => {
4160 self.render_permission_buttons_flat(options, entry_ix, tool_call_id, cx)
4161 }
4162 PermissionOptions::Dropdown(options) => {
4163 self.render_permission_buttons_dropdown(options, entry_ix, tool_call_id, cx)
4164 }
4165 }
4166 }
4167
4168 fn render_permission_buttons_dropdown(
4169 &self,
4170 choices: &[PermissionOptionChoice],
4171 entry_ix: usize,
4172 tool_call_id: acp::ToolCallId,
4173 cx: &Context<Self>,
4174 ) -> Div {
4175 let is_first = self.thread().is_some_and(|thread| {
4176 thread
4177 .read(cx)
4178 .first_tool_awaiting_confirmation()
4179 .is_some_and(|call| call.id == tool_call_id)
4180 });
4181
4182 // Get the selected granularity index, defaulting to the last option ("Only this time")
4183 let selected_index = self
4184 .selected_permission_granularity
4185 .get(&tool_call_id)
4186 .copied()
4187 .unwrap_or_else(|| choices.len().saturating_sub(1));
4188
4189 let selected_choice = choices.get(selected_index).or(choices.last());
4190
4191 let dropdown_label: SharedString = selected_choice
4192 .map(|choice| choice.label())
4193 .unwrap_or_else(|| "Only this time".into());
4194
4195 let (allow_option_id, allow_option_kind, deny_option_id, deny_option_kind) =
4196 if let Some(choice) = selected_choice {
4197 (
4198 choice.allow.option_id.clone(),
4199 choice.allow.kind,
4200 choice.deny.option_id.clone(),
4201 choice.deny.kind,
4202 )
4203 } else {
4204 (
4205 acp::PermissionOptionId::new("allow"),
4206 acp::PermissionOptionKind::AllowOnce,
4207 acp::PermissionOptionId::new("deny"),
4208 acp::PermissionOptionKind::RejectOnce,
4209 )
4210 };
4211
4212 h_flex()
4213 .w_full()
4214 .p_1()
4215 .gap_2()
4216 .justify_between()
4217 .border_t_1()
4218 .border_color(self.tool_card_border_color(cx))
4219 .child(
4220 h_flex()
4221 .gap_0p5()
4222 .child(
4223 Button::new(("allow-btn", entry_ix), "Allow")
4224 .icon(IconName::Check)
4225 .icon_color(Color::Success)
4226 .icon_position(IconPosition::Start)
4227 .icon_size(IconSize::XSmall)
4228 .label_size(LabelSize::Small)
4229 .when(is_first, |this| {
4230 this.key_binding(
4231 KeyBinding::for_action_in(
4232 &AllowOnce as &dyn Action,
4233 &self.focus_handle,
4234 cx,
4235 )
4236 .map(|kb| kb.size(rems_from_px(10.))),
4237 )
4238 })
4239 .on_click(cx.listener({
4240 let tool_call_id = tool_call_id.clone();
4241 let option_id = allow_option_id;
4242 let option_kind = allow_option_kind;
4243 move |this, _, window, cx| {
4244 this.authorize_tool_call(
4245 tool_call_id.clone(),
4246 option_id.clone(),
4247 option_kind,
4248 window,
4249 cx,
4250 );
4251 }
4252 })),
4253 )
4254 .child(
4255 Button::new(("deny-btn", entry_ix), "Deny")
4256 .icon(IconName::Close)
4257 .icon_color(Color::Error)
4258 .icon_position(IconPosition::Start)
4259 .icon_size(IconSize::XSmall)
4260 .label_size(LabelSize::Small)
4261 .when(is_first, |this| {
4262 this.key_binding(
4263 KeyBinding::for_action_in(
4264 &RejectOnce as &dyn Action,
4265 &self.focus_handle,
4266 cx,
4267 )
4268 .map(|kb| kb.size(rems_from_px(10.))),
4269 )
4270 })
4271 .on_click(cx.listener({
4272 let tool_call_id = tool_call_id.clone();
4273 let option_id = deny_option_id;
4274 let option_kind = deny_option_kind;
4275 move |this, _, window, cx| {
4276 this.authorize_tool_call(
4277 tool_call_id.clone(),
4278 option_id.clone(),
4279 option_kind,
4280 window,
4281 cx,
4282 );
4283 }
4284 })),
4285 ),
4286 )
4287 .child(self.render_permission_granularity_dropdown(
4288 choices,
4289 dropdown_label,
4290 entry_ix,
4291 tool_call_id,
4292 selected_index,
4293 is_first,
4294 cx,
4295 ))
4296 }
4297
4298 fn render_permission_granularity_dropdown(
4299 &self,
4300 choices: &[PermissionOptionChoice],
4301 current_label: SharedString,
4302 entry_ix: usize,
4303 tool_call_id: acp::ToolCallId,
4304 selected_index: usize,
4305 is_first: bool,
4306 cx: &Context<Self>,
4307 ) -> impl IntoElement {
4308 let menu_options: Vec<(usize, SharedString)> = choices
4309 .iter()
4310 .enumerate()
4311 .map(|(i, choice)| (i, choice.label()))
4312 .collect();
4313
4314 PopoverMenu::new(("permission-granularity", entry_ix))
4315 .with_handle(self.permission_dropdown_handle.clone())
4316 .trigger(
4317 Button::new(("granularity-trigger", entry_ix), current_label)
4318 .icon(IconName::ChevronDown)
4319 .icon_size(IconSize::XSmall)
4320 .icon_color(Color::Muted)
4321 .label_size(LabelSize::Small)
4322 .when(is_first, |this| {
4323 this.key_binding(
4324 KeyBinding::for_action_in(
4325 &crate::OpenPermissionDropdown as &dyn Action,
4326 &self.focus_handle,
4327 cx,
4328 )
4329 .map(|kb| kb.size(rems_from_px(10.))),
4330 )
4331 }),
4332 )
4333 .menu(move |window, cx| {
4334 let tool_call_id = tool_call_id.clone();
4335 let options = menu_options.clone();
4336
4337 Some(ContextMenu::build(window, cx, move |mut menu, _, _| {
4338 for (index, display_name) in options.iter() {
4339 let display_name = display_name.clone();
4340 let index = *index;
4341 let tool_call_id_for_entry = tool_call_id.clone();
4342 let is_selected = index == selected_index;
4343
4344 menu = menu.toggleable_entry(
4345 display_name,
4346 is_selected,
4347 IconPosition::End,
4348 None,
4349 move |window, cx| {
4350 window.dispatch_action(
4351 SelectPermissionGranularity {
4352 tool_call_id: tool_call_id_for_entry.0.to_string(),
4353 index,
4354 }
4355 .boxed_clone(),
4356 cx,
4357 );
4358 },
4359 );
4360 }
4361
4362 menu
4363 }))
4364 })
4365 }
4366
4367 fn render_permission_buttons_flat(
4368 &self,
4369 options: &[acp::PermissionOption],
4370 entry_ix: usize,
4371 tool_call_id: acp::ToolCallId,
4372 cx: &Context<Self>,
4373 ) -> Div {
4374 let is_first = self.thread().is_some_and(|thread| {
4375 thread
4376 .read(cx)
4377 .first_tool_awaiting_confirmation()
4378 .is_some_and(|call| call.id == tool_call_id)
4379 });
4380 let mut seen_kinds: ArrayVec<acp::PermissionOptionKind, 3> = ArrayVec::new();
4381
4382 div()
4383 .p_1()
4384 .border_t_1()
4385 .border_color(self.tool_card_border_color(cx))
4386 .w_full()
4387 .v_flex()
4388 .gap_0p5()
4389 .children(options.iter().map(move |option| {
4390 let option_id = SharedString::from(option.option_id.0.clone());
4391 Button::new((option_id, entry_ix), option.name.clone())
4392 .map(|this| {
4393 let (this, action) = match option.kind {
4394 acp::PermissionOptionKind::AllowOnce => (
4395 this.icon(IconName::Check).icon_color(Color::Success),
4396 Some(&AllowOnce as &dyn Action),
4397 ),
4398 acp::PermissionOptionKind::AllowAlways => (
4399 this.icon(IconName::CheckDouble).icon_color(Color::Success),
4400 Some(&AllowAlways as &dyn Action),
4401 ),
4402 acp::PermissionOptionKind::RejectOnce => (
4403 this.icon(IconName::Close).icon_color(Color::Error),
4404 Some(&RejectOnce as &dyn Action),
4405 ),
4406 acp::PermissionOptionKind::RejectAlways | _ => {
4407 (this.icon(IconName::Close).icon_color(Color::Error), None)
4408 }
4409 };
4410
4411 let Some(action) = action else {
4412 return this;
4413 };
4414
4415 if !is_first || seen_kinds.contains(&option.kind) {
4416 return this;
4417 }
4418
4419 seen_kinds.push(option.kind);
4420
4421 this.key_binding(
4422 KeyBinding::for_action_in(action, &self.focus_handle, cx)
4423 .map(|kb| kb.size(rems_from_px(10.))),
4424 )
4425 })
4426 .icon_position(IconPosition::Start)
4427 .icon_size(IconSize::XSmall)
4428 .label_size(LabelSize::Small)
4429 .on_click(cx.listener({
4430 let tool_call_id = tool_call_id.clone();
4431 let option_id = option.option_id.clone();
4432 let option_kind = option.kind;
4433 move |this, _, window, cx| {
4434 this.authorize_tool_call(
4435 tool_call_id.clone(),
4436 option_id.clone(),
4437 option_kind,
4438 window,
4439 cx,
4440 );
4441 }
4442 }))
4443 }))
4444 }
4445
4446 fn render_diff_loading(&self, cx: &Context<Self>) -> AnyElement {
4447 let bar = |n: u64, width_class: &str| {
4448 let bg_color = cx.theme().colors().element_active;
4449 let base = h_flex().h_1().rounded_full();
4450
4451 let modified = match width_class {
4452 "w_4_5" => base.w_3_4(),
4453 "w_1_4" => base.w_1_4(),
4454 "w_2_4" => base.w_2_4(),
4455 "w_3_5" => base.w_3_5(),
4456 "w_2_5" => base.w_2_5(),
4457 _ => base.w_1_2(),
4458 };
4459
4460 modified.with_animation(
4461 ElementId::Integer(n),
4462 Animation::new(Duration::from_secs(2)).repeat(),
4463 move |tab, delta| {
4464 let delta = (delta - 0.15 * n as f32) / 0.7;
4465 let delta = 1.0 - (0.5 - delta).abs() * 2.;
4466 let delta = ease_in_out(delta.clamp(0., 1.));
4467 let delta = 0.1 + 0.9 * delta;
4468
4469 tab.bg(bg_color.opacity(delta))
4470 },
4471 )
4472 };
4473
4474 v_flex()
4475 .p_3()
4476 .gap_1()
4477 .rounded_b_md()
4478 .bg(cx.theme().colors().editor_background)
4479 .child(bar(0, "w_4_5"))
4480 .child(bar(1, "w_1_4"))
4481 .child(bar(2, "w_2_4"))
4482 .child(bar(3, "w_3_5"))
4483 .child(bar(4, "w_2_5"))
4484 .into_any_element()
4485 }
4486
4487 fn render_diff_editor(
4488 &self,
4489 entry_ix: usize,
4490 diff: &Entity<acp_thread::Diff>,
4491 tool_call: &ToolCall,
4492 has_failed: bool,
4493 cx: &Context<Self>,
4494 ) -> AnyElement {
4495 let tool_progress = matches!(
4496 &tool_call.status,
4497 ToolCallStatus::InProgress | ToolCallStatus::Pending
4498 );
4499
4500 let revealed_diff_editor = if let Some(entry) =
4501 self.entry_view_state.read(cx).entry(entry_ix)
4502 && let Some(editor) = entry.editor_for_diff(diff)
4503 && diff.read(cx).has_revealed_range(cx)
4504 {
4505 Some(editor)
4506 } else {
4507 None
4508 };
4509
4510 let show_top_border = !has_failed || revealed_diff_editor.is_some();
4511
4512 v_flex()
4513 .h_full()
4514 .when(show_top_border, |this| {
4515 this.border_t_1()
4516 .when(has_failed, |this| this.border_dashed())
4517 .border_color(self.tool_card_border_color(cx))
4518 })
4519 .child(if let Some(editor) = revealed_diff_editor {
4520 editor.into_any_element()
4521 } else if tool_progress && self.as_native_connection(cx).is_some() {
4522 self.render_diff_loading(cx)
4523 } else {
4524 Empty.into_any()
4525 })
4526 .into_any()
4527 }
4528
4529 fn render_collapsible_command(
4530 &self,
4531 is_preview: bool,
4532 command_source: &str,
4533 tool_call_id: &acp::ToolCallId,
4534 cx: &Context<Self>,
4535 ) -> Div {
4536 let command_group =
4537 SharedString::from(format!("collapsible-command-group-{}", tool_call_id));
4538
4539 v_flex()
4540 .group(command_group.clone())
4541 .bg(self.tool_card_header_bg(cx))
4542 .child(
4543 v_flex()
4544 .p_1p5()
4545 .when(is_preview, |this| {
4546 this.pt_1().child(
4547 // Wrapping this label on a container with 24px height to avoid
4548 // layout shift when it changes from being a preview label
4549 // to the actual path where the command will run in
4550 h_flex().h_6().child(
4551 Label::new("Run Command")
4552 .buffer_font(cx)
4553 .size(LabelSize::XSmall)
4554 .color(Color::Muted),
4555 ),
4556 )
4557 })
4558 .children(command_source.lines().map(|line| {
4559 let text: SharedString = if line.is_empty() {
4560 " ".into()
4561 } else {
4562 line.to_string().into()
4563 };
4564
4565 Label::new(text).buffer_font(cx).size(LabelSize::Small)
4566 }))
4567 .child(
4568 div().absolute().top_1().right_1().child(
4569 CopyButton::new("copy-command", command_source.to_string())
4570 .tooltip_label("Copy Command")
4571 .visible_on_hover(command_group),
4572 ),
4573 ),
4574 )
4575 }
4576
4577 fn render_terminal_tool_call(
4578 &self,
4579 entry_ix: usize,
4580 terminal: &Entity<acp_thread::Terminal>,
4581 tool_call: &ToolCall,
4582 window: &Window,
4583 cx: &Context<Self>,
4584 ) -> AnyElement {
4585 let terminal_data = terminal.read(cx);
4586 let working_dir = terminal_data.working_dir();
4587 let command = terminal_data.command();
4588 let started_at = terminal_data.started_at();
4589
4590 let tool_failed = matches!(
4591 &tool_call.status,
4592 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed
4593 );
4594
4595 let output = terminal_data.output();
4596 let command_finished = output.is_some();
4597 let truncated_output =
4598 output.is_some_and(|output| output.original_content_len > output.content.len());
4599 let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
4600
4601 let command_failed = command_finished
4602 && output.is_some_and(|o| o.exit_status.is_some_and(|status| !status.success()));
4603
4604 let time_elapsed = if let Some(output) = output {
4605 output.ended_at.duration_since(started_at)
4606 } else {
4607 started_at.elapsed()
4608 };
4609
4610 let header_id =
4611 SharedString::from(format!("terminal-tool-header-{}", terminal.entity_id()));
4612 let header_group = SharedString::from(format!(
4613 "terminal-tool-header-group-{}",
4614 terminal.entity_id()
4615 ));
4616 let header_bg = cx
4617 .theme()
4618 .colors()
4619 .element_background
4620 .blend(cx.theme().colors().editor_foreground.opacity(0.025));
4621 let border_color = cx.theme().colors().border.opacity(0.6);
4622
4623 let working_dir = working_dir
4624 .as_ref()
4625 .map(|path| path.display().to_string())
4626 .unwrap_or_else(|| "current directory".to_string());
4627
4628 // Since the command's source is wrapped in a markdown code block
4629 // (```\n...\n```), we need to strip that so we're left with only the
4630 // command's content.
4631 let command_source = command.read(cx).source();
4632 let command_content = command_source
4633 .strip_prefix("```\n")
4634 .and_then(|s| s.strip_suffix("\n```"))
4635 .unwrap_or(&command_source);
4636
4637 let command_element =
4638 self.render_collapsible_command(false, command_content, &tool_call.id, cx);
4639
4640 let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
4641
4642 let header = h_flex()
4643 .id(header_id)
4644 .px_1p5()
4645 .pt_1()
4646 .flex_none()
4647 .gap_1()
4648 .justify_between()
4649 .rounded_t_md()
4650 .child(
4651 div()
4652 .id(("command-target-path", terminal.entity_id()))
4653 .w_full()
4654 .max_w_full()
4655 .overflow_x_scroll()
4656 .child(
4657 Label::new(working_dir)
4658 .buffer_font(cx)
4659 .size(LabelSize::XSmall)
4660 .color(Color::Muted),
4661 ),
4662 )
4663 .when(!command_finished, |header| {
4664 header
4665 .gap_1p5()
4666 .child(
4667 Button::new(
4668 SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
4669 "Stop",
4670 )
4671 .icon(IconName::Stop)
4672 .icon_position(IconPosition::Start)
4673 .icon_size(IconSize::Small)
4674 .icon_color(Color::Error)
4675 .label_size(LabelSize::Small)
4676 .tooltip(move |_window, cx| {
4677 Tooltip::with_meta(
4678 "Stop This Command",
4679 None,
4680 "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
4681 cx,
4682 )
4683 })
4684 .on_click({
4685 let terminal = terminal.clone();
4686 cx.listener(move |this, _event, _window, cx| {
4687 terminal.update(cx, |terminal, cx| {
4688 terminal.stop_by_user(cx);
4689 });
4690 if AgentSettings::get_global(cx).cancel_generation_on_terminal_stop {
4691 this.cancel_generation(cx);
4692 }
4693 })
4694 }),
4695 )
4696 .child(Divider::vertical())
4697 .child(
4698 Icon::new(IconName::ArrowCircle)
4699 .size(IconSize::XSmall)
4700 .color(Color::Info)
4701 .with_rotate_animation(2)
4702 )
4703 })
4704 .when(truncated_output, |header| {
4705 let tooltip = if let Some(output) = output {
4706 if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
4707 format!("Output exceeded terminal max lines and was \
4708 truncated, the model received the first {}.", format_file_size(output.content.len() as u64, true))
4709 } else {
4710 format!(
4711 "Output is {} long, and to avoid unexpected token usage, \
4712 only {} was sent back to the agent.",
4713 format_file_size(output.original_content_len as u64, true),
4714 format_file_size(output.content.len() as u64, true)
4715 )
4716 }
4717 } else {
4718 "Output was truncated".to_string()
4719 };
4720
4721 header.child(
4722 h_flex()
4723 .id(("terminal-tool-truncated-label", terminal.entity_id()))
4724 .gap_1()
4725 .child(
4726 Icon::new(IconName::Info)
4727 .size(IconSize::XSmall)
4728 .color(Color::Ignored),
4729 )
4730 .child(
4731 Label::new("Truncated")
4732 .color(Color::Muted)
4733 .size(LabelSize::XSmall),
4734 )
4735 .tooltip(Tooltip::text(tooltip)),
4736 )
4737 })
4738 .when(time_elapsed > Duration::from_secs(10), |header| {
4739 header.child(
4740 Label::new(format!("({})", duration_alt_display(time_elapsed)))
4741 .buffer_font(cx)
4742 .color(Color::Muted)
4743 .size(LabelSize::XSmall),
4744 )
4745 })
4746 .when(tool_failed || command_failed, |header| {
4747 header.child(
4748 div()
4749 .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
4750 .child(
4751 Icon::new(IconName::Close)
4752 .size(IconSize::Small)
4753 .color(Color::Error),
4754 )
4755 .when_some(output.and_then(|o| o.exit_status), |this, status| {
4756 this.tooltip(Tooltip::text(format!(
4757 "Exited with code {}",
4758 status.code().unwrap_or(-1),
4759 )))
4760 }),
4761 )
4762 })
4763 .child(
4764 Disclosure::new(
4765 SharedString::from(format!(
4766 "terminal-tool-disclosure-{}",
4767 terminal.entity_id()
4768 )),
4769 is_expanded,
4770 )
4771 .opened_icon(IconName::ChevronUp)
4772 .closed_icon(IconName::ChevronDown)
4773 .visible_on_hover(&header_group)
4774 .on_click(cx.listener({
4775 let id = tool_call.id.clone();
4776 move |this, _event, _window, _cx| {
4777 if is_expanded {
4778 this.expanded_tool_calls.remove(&id);
4779 } else {
4780 this.expanded_tool_calls.insert(id.clone());
4781 }
4782 }
4783 })),
4784 );
4785
4786 let terminal_view = self
4787 .entry_view_state
4788 .read(cx)
4789 .entry(entry_ix)
4790 .and_then(|entry| entry.terminal(terminal));
4791
4792 v_flex()
4793 .my_1p5()
4794 .mx_5()
4795 .border_1()
4796 .when(tool_failed || command_failed, |card| card.border_dashed())
4797 .border_color(border_color)
4798 .rounded_md()
4799 .overflow_hidden()
4800 .child(
4801 v_flex()
4802 .group(&header_group)
4803 .bg(header_bg)
4804 .text_xs()
4805 .child(header)
4806 .child(command_element),
4807 )
4808 .when(is_expanded && terminal_view.is_some(), |this| {
4809 this.child(
4810 div()
4811 .pt_2()
4812 .border_t_1()
4813 .when(tool_failed || command_failed, |card| card.border_dashed())
4814 .border_color(border_color)
4815 .bg(cx.theme().colors().editor_background)
4816 .rounded_b_md()
4817 .text_ui_sm(cx)
4818 .h_full()
4819 .children(terminal_view.map(|terminal_view| {
4820 let element = if terminal_view
4821 .read(cx)
4822 .content_mode(window, cx)
4823 .is_scrollable()
4824 {
4825 div().h_72().child(terminal_view).into_any_element()
4826 } else {
4827 terminal_view.into_any_element()
4828 };
4829
4830 div()
4831 .on_action(cx.listener(|_this, _: &NewTerminal, window, cx| {
4832 window.dispatch_action(NewThread.boxed_clone(), cx);
4833 cx.stop_propagation();
4834 }))
4835 .child(element)
4836 .into_any_element()
4837 })),
4838 )
4839 })
4840 .into_any()
4841 }
4842
4843 fn render_rules_item(&self, cx: &Context<Self>) -> Option<AnyElement> {
4844 let project_context = self
4845 .as_native_thread(cx)?
4846 .read(cx)
4847 .project_context()
4848 .read(cx);
4849
4850 let user_rules_text = if project_context.user_rules.is_empty() {
4851 None
4852 } else if project_context.user_rules.len() == 1 {
4853 let user_rules = &project_context.user_rules[0];
4854
4855 match user_rules.title.as_ref() {
4856 Some(title) => Some(format!("Using \"{title}\" user rule")),
4857 None => Some("Using user rule".into()),
4858 }
4859 } else {
4860 Some(format!(
4861 "Using {} user rules",
4862 project_context.user_rules.len()
4863 ))
4864 };
4865
4866 let first_user_rules_id = project_context
4867 .user_rules
4868 .first()
4869 .map(|user_rules| user_rules.uuid.0);
4870
4871 let rules_files = project_context
4872 .worktrees
4873 .iter()
4874 .filter_map(|worktree| worktree.rules_file.as_ref())
4875 .collect::<Vec<_>>();
4876
4877 let rules_file_text = match rules_files.as_slice() {
4878 &[] => None,
4879 &[rules_file] => Some(format!(
4880 "Using project {:?} file",
4881 rules_file.path_in_worktree
4882 )),
4883 rules_files => Some(format!("Using {} project rules files", rules_files.len())),
4884 };
4885
4886 if user_rules_text.is_none() && rules_file_text.is_none() {
4887 return None;
4888 }
4889
4890 let has_both = user_rules_text.is_some() && rules_file_text.is_some();
4891
4892 Some(
4893 h_flex()
4894 .px_2p5()
4895 .child(
4896 Icon::new(IconName::Attach)
4897 .size(IconSize::XSmall)
4898 .color(Color::Disabled),
4899 )
4900 .when_some(user_rules_text, |parent, user_rules_text| {
4901 parent.child(
4902 h_flex()
4903 .id("user-rules")
4904 .ml_1()
4905 .mr_1p5()
4906 .child(
4907 Label::new(user_rules_text)
4908 .size(LabelSize::XSmall)
4909 .color(Color::Muted)
4910 .truncate(),
4911 )
4912 .hover(|s| s.bg(cx.theme().colors().element_hover))
4913 .tooltip(Tooltip::text("View User Rules"))
4914 .on_click(move |_event, window, cx| {
4915 window.dispatch_action(
4916 Box::new(OpenRulesLibrary {
4917 prompt_to_select: first_user_rules_id,
4918 }),
4919 cx,
4920 )
4921 }),
4922 )
4923 })
4924 .when(has_both, |this| {
4925 this.child(
4926 Label::new("•")
4927 .size(LabelSize::XSmall)
4928 .color(Color::Disabled),
4929 )
4930 })
4931 .when_some(rules_file_text, |parent, rules_file_text| {
4932 parent.child(
4933 h_flex()
4934 .id("project-rules")
4935 .ml_1p5()
4936 .child(
4937 Label::new(rules_file_text)
4938 .size(LabelSize::XSmall)
4939 .color(Color::Muted),
4940 )
4941 .hover(|s| s.bg(cx.theme().colors().element_hover))
4942 .tooltip(Tooltip::text("View Project Rules"))
4943 .on_click(cx.listener(Self::handle_open_rules)),
4944 )
4945 })
4946 .into_any(),
4947 )
4948 }
4949
4950 fn render_empty_state_section_header(
4951 &self,
4952 label: impl Into<SharedString>,
4953 action_slot: Option<AnyElement>,
4954 cx: &mut Context<Self>,
4955 ) -> impl IntoElement {
4956 div().pl_1().pr_1p5().child(
4957 h_flex()
4958 .mt_2()
4959 .pl_1p5()
4960 .pb_1()
4961 .w_full()
4962 .justify_between()
4963 .border_b_1()
4964 .border_color(cx.theme().colors().border_variant)
4965 .child(
4966 Label::new(label.into())
4967 .size(LabelSize::Small)
4968 .color(Color::Muted),
4969 )
4970 .children(action_slot),
4971 )
4972 }
4973
4974 fn render_resume_notice(&self, _cx: &Context<Self>) -> AnyElement {
4975 let description = "This agent does not support viewing previous messages. However, your session will still continue from where you last left off.";
4976
4977 div()
4978 .px_2()
4979 .pt_2()
4980 .pb_3()
4981 .w_full()
4982 .child(
4983 Callout::new()
4984 .severity(Severity::Info)
4985 .icon(IconName::Info)
4986 .title("Resumed Session")
4987 .description(description),
4988 )
4989 .into_any_element()
4990 }
4991
4992 fn update_recent_history_from_cache(
4993 &mut self,
4994 history: &Entity<AcpThreadHistory>,
4995 cx: &mut Context<Self>,
4996 ) {
4997 self.recent_history_entries = history.read(cx).get_recent_sessions(3);
4998 self.hovered_recent_history_item = None;
4999 cx.notify();
5000 }
5001
5002 fn render_recent_history(&self, cx: &mut Context<Self>) -> AnyElement {
5003 let render_history = !self.recent_history_entries.is_empty();
5004
5005 v_flex()
5006 .size_full()
5007 .when(render_history, |this| {
5008 let recent_history = self.recent_history_entries.clone();
5009 this.justify_end().child(
5010 v_flex()
5011 .child(
5012 self.render_empty_state_section_header(
5013 "Recent",
5014 Some(
5015 Button::new("view-history", "View All")
5016 .style(ButtonStyle::Subtle)
5017 .label_size(LabelSize::Small)
5018 .key_binding(
5019 KeyBinding::for_action_in(
5020 &OpenHistory,
5021 &self.focus_handle(cx),
5022 cx,
5023 )
5024 .map(|kb| kb.size(rems_from_px(12.))),
5025 )
5026 .on_click(move |_event, window, cx| {
5027 window.dispatch_action(OpenHistory.boxed_clone(), cx);
5028 })
5029 .into_any_element(),
5030 ),
5031 cx,
5032 ),
5033 )
5034 .child(v_flex().p_1().pr_1p5().gap_1().children({
5035 let supports_delete = self.history.read(cx).supports_delete();
5036 recent_history
5037 .into_iter()
5038 .enumerate()
5039 .map(move |(index, entry)| {
5040 // TODO: Add keyboard navigation.
5041 let is_hovered =
5042 self.hovered_recent_history_item == Some(index);
5043 crate::acp::thread_history::AcpHistoryEntryElement::new(
5044 entry,
5045 cx.entity().downgrade(),
5046 )
5047 .hovered(is_hovered)
5048 .supports_delete(supports_delete)
5049 .on_hover(cx.listener(move |this, is_hovered, _window, cx| {
5050 if *is_hovered {
5051 this.hovered_recent_history_item = Some(index);
5052 } else if this.hovered_recent_history_item == Some(index) {
5053 this.hovered_recent_history_item = None;
5054 }
5055 cx.notify();
5056 }))
5057 .into_any_element()
5058 })
5059 })),
5060 )
5061 })
5062 .into_any()
5063 }
5064
5065 fn render_auth_required_state(
5066 &self,
5067 connection: &Rc<dyn AgentConnection>,
5068 description: Option<&Entity<Markdown>>,
5069 configuration_view: Option<&AnyView>,
5070 pending_auth_method: Option<&acp::AuthMethodId>,
5071 window: &mut Window,
5072 cx: &Context<Self>,
5073 ) -> impl IntoElement {
5074 let auth_methods = connection.auth_methods();
5075
5076 let agent_display_name = self
5077 .agent_server_store
5078 .read(cx)
5079 .agent_display_name(&ExternalAgentServerName(self.agent.name()))
5080 .unwrap_or_else(|| self.agent.name());
5081
5082 let show_fallback_description = auth_methods.len() > 1
5083 && configuration_view.is_none()
5084 && description.is_none()
5085 && pending_auth_method.is_none();
5086
5087 let auth_buttons = || {
5088 h_flex().justify_end().flex_wrap().gap_1().children(
5089 connection
5090 .auth_methods()
5091 .iter()
5092 .enumerate()
5093 .rev()
5094 .map(|(ix, method)| {
5095 let (method_id, name) = if self.project.read(cx).is_via_remote_server()
5096 && method.id.0.as_ref() == "oauth-personal"
5097 && method.name == "Log in with Google"
5098 {
5099 ("spawn-gemini-cli".into(), "Log in with Gemini CLI".into())
5100 } else {
5101 (method.id.0.clone(), method.name.clone())
5102 };
5103
5104 let agent_telemetry_id = connection.telemetry_id();
5105
5106 Button::new(method_id.clone(), name)
5107 .label_size(LabelSize::Small)
5108 .map(|this| {
5109 if ix == 0 {
5110 this.style(ButtonStyle::Tinted(TintColor::Accent))
5111 } else {
5112 this.style(ButtonStyle::Outlined)
5113 }
5114 })
5115 .when_some(method.description.clone(), |this, description| {
5116 this.tooltip(Tooltip::text(description))
5117 })
5118 .on_click({
5119 cx.listener(move |this, _, window, cx| {
5120 telemetry::event!(
5121 "Authenticate Agent Started",
5122 agent = agent_telemetry_id,
5123 method = method_id
5124 );
5125
5126 this.authenticate(
5127 acp::AuthMethodId::new(method_id.clone()),
5128 window,
5129 cx,
5130 )
5131 })
5132 })
5133 }),
5134 )
5135 };
5136
5137 if pending_auth_method.is_some() {
5138 return Callout::new()
5139 .icon(IconName::Info)
5140 .title(format!("Authenticating to {}…", agent_display_name))
5141 .actions_slot(
5142 Icon::new(IconName::ArrowCircle)
5143 .size(IconSize::Small)
5144 .color(Color::Muted)
5145 .with_rotate_animation(2)
5146 .into_any_element(),
5147 )
5148 .into_any_element();
5149 }
5150
5151 Callout::new()
5152 .icon(IconName::Info)
5153 .title(format!("Authenticate to {}", agent_display_name))
5154 .when(auth_methods.len() == 1, |this| {
5155 this.actions_slot(auth_buttons())
5156 })
5157 .description_slot(
5158 v_flex()
5159 .text_ui(cx)
5160 .map(|this| {
5161 if show_fallback_description {
5162 this.child(
5163 Label::new("Choose one of the following authentication options:")
5164 .size(LabelSize::Small)
5165 .color(Color::Muted),
5166 )
5167 } else {
5168 this.children(
5169 configuration_view
5170 .cloned()
5171 .map(|view| div().w_full().child(view)),
5172 )
5173 .children(description.map(|desc| {
5174 self.render_markdown(
5175 desc.clone(),
5176 default_markdown_style(false, false, window, cx),
5177 )
5178 }))
5179 }
5180 })
5181 .when(auth_methods.len() > 1, |this| {
5182 this.gap_1().child(auth_buttons())
5183 }),
5184 )
5185 .into_any_element()
5186 }
5187
5188 fn render_load_error(
5189 &self,
5190 e: &LoadError,
5191 window: &mut Window,
5192 cx: &mut Context<Self>,
5193 ) -> AnyElement {
5194 let (title, message, action_slot): (_, SharedString, _) = match e {
5195 LoadError::Unsupported {
5196 command: path,
5197 current_version,
5198 minimum_version,
5199 } => {
5200 return self.render_unsupported(path, current_version, minimum_version, window, cx);
5201 }
5202 LoadError::FailedToInstall(msg) => (
5203 "Failed to Install",
5204 msg.into(),
5205 Some(self.create_copy_button(msg.to_string()).into_any_element()),
5206 ),
5207 LoadError::Exited { status } => (
5208 "Failed to Launch",
5209 format!("Server exited with status {status}").into(),
5210 None,
5211 ),
5212 LoadError::Other(msg) => (
5213 "Failed to Launch",
5214 msg.into(),
5215 Some(self.create_copy_button(msg.to_string()).into_any_element()),
5216 ),
5217 };
5218
5219 Callout::new()
5220 .severity(Severity::Error)
5221 .icon(IconName::XCircleFilled)
5222 .title(title)
5223 .description(message)
5224 .actions_slot(div().children(action_slot))
5225 .into_any_element()
5226 }
5227
5228 fn render_unsupported(
5229 &self,
5230 path: &SharedString,
5231 version: &SharedString,
5232 minimum_version: &SharedString,
5233 _window: &mut Window,
5234 cx: &mut Context<Self>,
5235 ) -> AnyElement {
5236 let (heading_label, description_label) = (
5237 format!("Upgrade {} to work with Zed", self.agent.name()),
5238 if version.is_empty() {
5239 format!(
5240 "Currently using {}, which does not report a valid --version",
5241 path,
5242 )
5243 } else {
5244 format!(
5245 "Currently using {}, which is only version {} (need at least {minimum_version})",
5246 path, version
5247 )
5248 },
5249 );
5250
5251 v_flex()
5252 .w_full()
5253 .p_3p5()
5254 .gap_2p5()
5255 .border_t_1()
5256 .border_color(cx.theme().colors().border)
5257 .bg(linear_gradient(
5258 180.,
5259 linear_color_stop(cx.theme().colors().editor_background.opacity(0.4), 4.),
5260 linear_color_stop(cx.theme().status().info_background.opacity(0.), 0.),
5261 ))
5262 .child(
5263 v_flex().gap_0p5().child(Label::new(heading_label)).child(
5264 Label::new(description_label)
5265 .size(LabelSize::Small)
5266 .color(Color::Muted),
5267 ),
5268 )
5269 .into_any_element()
5270 }
5271
5272 fn activity_bar_bg(&self, cx: &Context<Self>) -> Hsla {
5273 let editor_bg_color = cx.theme().colors().editor_background;
5274 let active_color = cx.theme().colors().element_selected;
5275 editor_bg_color.blend(active_color.opacity(0.3))
5276 }
5277
5278 fn render_activity_bar(
5279 &self,
5280 thread_entity: &Entity<AcpThread>,
5281 window: &mut Window,
5282 cx: &Context<Self>,
5283 ) -> Option<AnyElement> {
5284 let thread = thread_entity.read(cx);
5285 let action_log = thread.action_log();
5286 let telemetry = ActionLogTelemetry::from(thread);
5287 let changed_buffers = action_log.read(cx).changed_buffers(cx);
5288 let plan = thread.plan();
5289 let queue_is_empty = !self.has_queued_messages();
5290
5291 if changed_buffers.is_empty() && plan.is_empty() && queue_is_empty {
5292 return None;
5293 }
5294
5295 // Temporarily always enable ACP edit controls. This is temporary, to lessen the
5296 // impact of a nasty bug that causes them to sometimes be disabled when they shouldn't
5297 // be, which blocks you from being able to accept or reject edits. This switches the
5298 // bug to be that sometimes it's enabled when it shouldn't be, which at least doesn't
5299 // block you from using the panel.
5300 let pending_edits = false;
5301
5302 v_flex()
5303 .mt_1()
5304 .mx_2()
5305 .bg(self.activity_bar_bg(cx))
5306 .border_1()
5307 .border_b_0()
5308 .border_color(cx.theme().colors().border)
5309 .rounded_t_md()
5310 .shadow(vec![gpui::BoxShadow {
5311 color: gpui::black().opacity(0.15),
5312 offset: point(px(1.), px(-1.)),
5313 blur_radius: px(3.),
5314 spread_radius: px(0.),
5315 }])
5316 .when(!plan.is_empty(), |this| {
5317 this.child(self.render_plan_summary(plan, window, cx))
5318 .when(self.plan_expanded, |parent| {
5319 parent.child(self.render_plan_entries(plan, window, cx))
5320 })
5321 })
5322 .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
5323 this.child(Divider::horizontal().color(DividerColor::Border))
5324 })
5325 .when(!changed_buffers.is_empty(), |this| {
5326 this.child(self.render_edits_summary(
5327 &changed_buffers,
5328 self.edits_expanded,
5329 pending_edits,
5330 cx,
5331 ))
5332 .when(self.edits_expanded, |parent| {
5333 parent.child(self.render_edited_files(
5334 action_log,
5335 telemetry.clone(),
5336 &changed_buffers,
5337 pending_edits,
5338 cx,
5339 ))
5340 })
5341 })
5342 .when(!queue_is_empty, |this| {
5343 this.when(!plan.is_empty() || !changed_buffers.is_empty(), |this| {
5344 this.child(Divider::horizontal().color(DividerColor::Border))
5345 })
5346 .child(self.render_message_queue_summary(window, cx))
5347 .when(self.queue_expanded, |parent| {
5348 parent.child(self.render_message_queue_entries(window, cx))
5349 })
5350 })
5351 .into_any()
5352 .into()
5353 }
5354
5355 fn render_plan_summary(
5356 &self,
5357 plan: &Plan,
5358 window: &mut Window,
5359 cx: &Context<Self>,
5360 ) -> impl IntoElement {
5361 let stats = plan.stats();
5362
5363 let title = if let Some(entry) = stats.in_progress_entry
5364 && !self.plan_expanded
5365 {
5366 h_flex()
5367 .cursor_default()
5368 .relative()
5369 .w_full()
5370 .gap_1()
5371 .truncate()
5372 .child(
5373 Label::new("Current:")
5374 .size(LabelSize::Small)
5375 .color(Color::Muted),
5376 )
5377 .child(
5378 div()
5379 .text_xs()
5380 .text_color(cx.theme().colors().text_muted)
5381 .line_clamp(1)
5382 .child(MarkdownElement::new(
5383 entry.content.clone(),
5384 plan_label_markdown_style(&entry.status, window, cx),
5385 )),
5386 )
5387 .when(stats.pending > 0, |this| {
5388 this.child(
5389 h_flex()
5390 .absolute()
5391 .top_0()
5392 .right_0()
5393 .h_full()
5394 .child(div().min_w_8().h_full().bg(linear_gradient(
5395 90.,
5396 linear_color_stop(self.activity_bar_bg(cx), 1.),
5397 linear_color_stop(self.activity_bar_bg(cx).opacity(0.2), 0.),
5398 )))
5399 .child(
5400 div().pr_0p5().bg(self.activity_bar_bg(cx)).child(
5401 Label::new(format!("{} left", stats.pending))
5402 .size(LabelSize::Small)
5403 .color(Color::Muted),
5404 ),
5405 ),
5406 )
5407 })
5408 } else {
5409 let status_label = if stats.pending == 0 {
5410 "All Done".to_string()
5411 } else if stats.completed == 0 {
5412 format!("{} Tasks", plan.entries.len())
5413 } else {
5414 format!("{}/{}", stats.completed, plan.entries.len())
5415 };
5416
5417 h_flex()
5418 .w_full()
5419 .gap_1()
5420 .justify_between()
5421 .child(
5422 Label::new("Plan")
5423 .size(LabelSize::Small)
5424 .color(Color::Muted),
5425 )
5426 .child(
5427 Label::new(status_label)
5428 .size(LabelSize::Small)
5429 .color(Color::Muted)
5430 .mr_1(),
5431 )
5432 };
5433
5434 h_flex()
5435 .id("plan_summary")
5436 .p_1()
5437 .w_full()
5438 .gap_1()
5439 .when(self.plan_expanded, |this| {
5440 this.border_b_1().border_color(cx.theme().colors().border)
5441 })
5442 .child(Disclosure::new("plan_disclosure", self.plan_expanded))
5443 .child(title)
5444 .on_click(cx.listener(|this, _, _, cx| {
5445 this.plan_expanded = !this.plan_expanded;
5446 cx.notify();
5447 }))
5448 }
5449
5450 fn render_plan_entries(
5451 &self,
5452 plan: &Plan,
5453 window: &mut Window,
5454 cx: &Context<Self>,
5455 ) -> impl IntoElement {
5456 v_flex()
5457 .id("plan_items_list")
5458 .max_h_40()
5459 .overflow_y_scroll()
5460 .children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
5461 let element = h_flex()
5462 .py_1()
5463 .px_2()
5464 .gap_2()
5465 .justify_between()
5466 .bg(cx.theme().colors().editor_background)
5467 .when(index < plan.entries.len() - 1, |parent| {
5468 parent.border_color(cx.theme().colors().border).border_b_1()
5469 })
5470 .child(
5471 h_flex()
5472 .id(("plan_entry", index))
5473 .gap_1p5()
5474 .max_w_full()
5475 .overflow_x_scroll()
5476 .text_xs()
5477 .text_color(cx.theme().colors().text_muted)
5478 .child(match entry.status {
5479 acp::PlanEntryStatus::InProgress => {
5480 Icon::new(IconName::TodoProgress)
5481 .size(IconSize::Small)
5482 .color(Color::Accent)
5483 .with_rotate_animation(2)
5484 .into_any_element()
5485 }
5486 acp::PlanEntryStatus::Completed => {
5487 Icon::new(IconName::TodoComplete)
5488 .size(IconSize::Small)
5489 .color(Color::Success)
5490 .into_any_element()
5491 }
5492 acp::PlanEntryStatus::Pending | _ => {
5493 Icon::new(IconName::TodoPending)
5494 .size(IconSize::Small)
5495 .color(Color::Muted)
5496 .into_any_element()
5497 }
5498 })
5499 .child(MarkdownElement::new(
5500 entry.content.clone(),
5501 plan_label_markdown_style(&entry.status, window, cx),
5502 )),
5503 );
5504
5505 Some(element)
5506 }))
5507 .into_any_element()
5508 }
5509
5510 fn render_edits_summary(
5511 &self,
5512 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
5513 expanded: bool,
5514 pending_edits: bool,
5515 cx: &Context<Self>,
5516 ) -> Div {
5517 const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
5518
5519 let focus_handle = self.focus_handle(cx);
5520
5521 h_flex()
5522 .p_1()
5523 .justify_between()
5524 .flex_wrap()
5525 .when(expanded, |this| {
5526 this.border_b_1().border_color(cx.theme().colors().border)
5527 })
5528 .child(
5529 h_flex()
5530 .id("edits-container")
5531 .cursor_pointer()
5532 .gap_1()
5533 .child(Disclosure::new("edits-disclosure", expanded))
5534 .map(|this| {
5535 if pending_edits {
5536 this.child(
5537 Label::new(format!(
5538 "Editing {} {}…",
5539 changed_buffers.len(),
5540 if changed_buffers.len() == 1 {
5541 "file"
5542 } else {
5543 "files"
5544 }
5545 ))
5546 .color(Color::Muted)
5547 .size(LabelSize::Small)
5548 .with_animation(
5549 "edit-label",
5550 Animation::new(Duration::from_secs(2))
5551 .repeat()
5552 .with_easing(pulsating_between(0.3, 0.7)),
5553 |label, delta| label.alpha(delta),
5554 ),
5555 )
5556 } else {
5557 let stats = DiffStats::all_files(changed_buffers, cx);
5558 let dot_divider = || {
5559 Label::new("•")
5560 .size(LabelSize::XSmall)
5561 .color(Color::Disabled)
5562 };
5563
5564 this.child(
5565 Label::new("Edits")
5566 .size(LabelSize::Small)
5567 .color(Color::Muted),
5568 )
5569 .child(dot_divider())
5570 .child(
5571 Label::new(format!(
5572 "{} {}",
5573 changed_buffers.len(),
5574 if changed_buffers.len() == 1 {
5575 "file"
5576 } else {
5577 "files"
5578 }
5579 ))
5580 .size(LabelSize::Small)
5581 .color(Color::Muted),
5582 )
5583 .child(dot_divider())
5584 .child(DiffStat::new(
5585 "total",
5586 stats.lines_added as usize,
5587 stats.lines_removed as usize,
5588 ))
5589 }
5590 })
5591 .on_click(cx.listener(|this, _, _, cx| {
5592 this.edits_expanded = !this.edits_expanded;
5593 cx.notify();
5594 })),
5595 )
5596 .child(
5597 h_flex()
5598 .gap_1()
5599 .child(
5600 IconButton::new("review-changes", IconName::ListTodo)
5601 .icon_size(IconSize::Small)
5602 .tooltip({
5603 let focus_handle = focus_handle.clone();
5604 move |_window, cx| {
5605 Tooltip::for_action_in(
5606 "Review Changes",
5607 &OpenAgentDiff,
5608 &focus_handle,
5609 cx,
5610 )
5611 }
5612 })
5613 .on_click(cx.listener(|_, _, window, cx| {
5614 window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
5615 })),
5616 )
5617 .child(Divider::vertical().color(DividerColor::Border))
5618 .child(
5619 Button::new("reject-all-changes", "Reject All")
5620 .label_size(LabelSize::Small)
5621 .disabled(pending_edits)
5622 .when(pending_edits, |this| {
5623 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
5624 })
5625 .key_binding(
5626 KeyBinding::for_action_in(&RejectAll, &focus_handle.clone(), cx)
5627 .map(|kb| kb.size(rems_from_px(10.))),
5628 )
5629 .on_click(cx.listener(move |this, _, window, cx| {
5630 this.reject_all(&RejectAll, window, cx);
5631 })),
5632 )
5633 .child(
5634 Button::new("keep-all-changes", "Keep All")
5635 .label_size(LabelSize::Small)
5636 .disabled(pending_edits)
5637 .when(pending_edits, |this| {
5638 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
5639 })
5640 .key_binding(
5641 KeyBinding::for_action_in(&KeepAll, &focus_handle, cx)
5642 .map(|kb| kb.size(rems_from_px(10.))),
5643 )
5644 .on_click(cx.listener(move |this, _, window, cx| {
5645 this.keep_all(&KeepAll, window, cx);
5646 })),
5647 ),
5648 )
5649 }
5650
5651 fn render_edited_files_buttons(
5652 &self,
5653 index: usize,
5654 buffer: &Entity<Buffer>,
5655 action_log: &Entity<ActionLog>,
5656 telemetry: &ActionLogTelemetry,
5657 pending_edits: bool,
5658 editor_bg_color: Hsla,
5659 cx: &Context<Self>,
5660 ) -> impl IntoElement {
5661 h_flex()
5662 .id("edited-buttons-container")
5663 .visible_on_hover("edited-code")
5664 .absolute()
5665 .right_0()
5666 .px_1()
5667 .gap_1()
5668 .bg(editor_bg_color)
5669 .on_hover(cx.listener(move |this, is_hovered, _window, cx| {
5670 if *is_hovered {
5671 this.hovered_edited_file_buttons = Some(index);
5672 } else if this.hovered_edited_file_buttons == Some(index) {
5673 this.hovered_edited_file_buttons = None;
5674 }
5675 cx.notify();
5676 }))
5677 .child(
5678 Button::new("review", "Review")
5679 .label_size(LabelSize::Small)
5680 .on_click({
5681 let buffer = buffer.clone();
5682 cx.listener(move |this, _, window, cx| {
5683 this.open_edited_buffer(&buffer, window, cx);
5684 })
5685 }),
5686 )
5687 .child(Divider::vertical().color(DividerColor::BorderVariant))
5688 .child(
5689 Button::new(("reject-file", index), "Reject")
5690 .label_size(LabelSize::Small)
5691 .disabled(pending_edits)
5692 .on_click({
5693 let buffer = buffer.clone();
5694 let action_log = action_log.clone();
5695 let telemetry = telemetry.clone();
5696 move |_, _, cx| {
5697 action_log.update(cx, |action_log, cx| {
5698 action_log
5699 .reject_edits_in_ranges(
5700 buffer.clone(),
5701 vec![Anchor::min_max_range_for_buffer(
5702 buffer.read(cx).remote_id(),
5703 )],
5704 Some(telemetry.clone()),
5705 cx,
5706 )
5707 .detach_and_log_err(cx);
5708 })
5709 }
5710 }),
5711 )
5712 .child(
5713 Button::new(("keep-file", index), "Keep")
5714 .label_size(LabelSize::Small)
5715 .disabled(pending_edits)
5716 .on_click({
5717 let buffer = buffer.clone();
5718 let action_log = action_log.clone();
5719 let telemetry = telemetry.clone();
5720 move |_, _, cx| {
5721 action_log.update(cx, |action_log, cx| {
5722 action_log.keep_edits_in_range(
5723 buffer.clone(),
5724 Anchor::min_max_range_for_buffer(buffer.read(cx).remote_id()),
5725 Some(telemetry.clone()),
5726 cx,
5727 );
5728 })
5729 }
5730 }),
5731 )
5732 }
5733
5734 fn render_edited_files(
5735 &self,
5736 action_log: &Entity<ActionLog>,
5737 telemetry: ActionLogTelemetry,
5738 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
5739 pending_edits: bool,
5740 cx: &Context<Self>,
5741 ) -> impl IntoElement {
5742 let editor_bg_color = cx.theme().colors().editor_background;
5743
5744 // Sort edited files alphabetically for consistency with Git diff view
5745 let mut sorted_buffers: Vec<_> = changed_buffers.iter().collect();
5746 sorted_buffers.sort_by(|(buffer_a, _), (buffer_b, _)| {
5747 let path_a = buffer_a.read(cx).file().map(|f| f.path().clone());
5748 let path_b = buffer_b.read(cx).file().map(|f| f.path().clone());
5749 path_a.cmp(&path_b)
5750 });
5751
5752 v_flex()
5753 .id("edited_files_list")
5754 .max_h_40()
5755 .overflow_y_scroll()
5756 .children(
5757 sorted_buffers
5758 .into_iter()
5759 .enumerate()
5760 .flat_map(|(index, (buffer, diff))| {
5761 let file = buffer.read(cx).file()?;
5762 let path = file.path();
5763 let path_style = file.path_style(cx);
5764 let separator = file.path_style(cx).primary_separator();
5765
5766 let file_path = path.parent().and_then(|parent| {
5767 if parent.is_empty() {
5768 None
5769 } else {
5770 Some(
5771 Label::new(format!(
5772 "{}{separator}",
5773 parent.display(path_style)
5774 ))
5775 .color(Color::Muted)
5776 .size(LabelSize::XSmall)
5777 .buffer_font(cx),
5778 )
5779 }
5780 });
5781
5782 let file_name = path.file_name().map(|name| {
5783 Label::new(name.to_string())
5784 .size(LabelSize::XSmall)
5785 .buffer_font(cx)
5786 .ml_1()
5787 });
5788
5789 let full_path = path.display(path_style).to_string();
5790
5791 let file_icon = FileIcons::get_icon(path.as_std_path(), cx)
5792 .map(Icon::from_path)
5793 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
5794 .unwrap_or_else(|| {
5795 Icon::new(IconName::File)
5796 .color(Color::Muted)
5797 .size(IconSize::Small)
5798 });
5799
5800 let file_stats = DiffStats::single_file(buffer.read(cx), diff.read(cx), cx);
5801
5802 let buttons = self.render_edited_files_buttons(
5803 index,
5804 buffer,
5805 action_log,
5806 &telemetry,
5807 pending_edits,
5808 editor_bg_color,
5809 cx,
5810 );
5811
5812 let element = h_flex()
5813 .group("edited-code")
5814 .id(("file-container", index))
5815 .relative()
5816 .min_w_0()
5817 .p_1p5()
5818 .gap_2()
5819 .justify_between()
5820 .bg(editor_bg_color)
5821 .when(index < changed_buffers.len() - 1, |parent| {
5822 parent.border_color(cx.theme().colors().border).border_b_1()
5823 })
5824 .child(
5825 h_flex()
5826 .id(("file-name-path", index))
5827 .cursor_pointer()
5828 .pr_0p5()
5829 .gap_0p5()
5830 .rounded_xs()
5831 .child(file_icon)
5832 .children(file_name)
5833 .children(file_path)
5834 .child(
5835 DiffStat::new(
5836 "file",
5837 file_stats.lines_added as usize,
5838 file_stats.lines_removed as usize,
5839 )
5840 .label_size(LabelSize::XSmall),
5841 )
5842 .when(
5843 self.hovered_edited_file_buttons != Some(index),
5844 |this| {
5845 let full_path = full_path.clone();
5846 this.hover(|s| s.bg(cx.theme().colors().element_hover))
5847 .tooltip(move |_, cx| {
5848 Tooltip::with_meta(
5849 "Go to File",
5850 None,
5851 full_path.clone(),
5852 cx,
5853 )
5854 })
5855 .on_click({
5856 let buffer = buffer.clone();
5857 cx.listener(move |this, _, window, cx| {
5858 this.open_edited_buffer(
5859 &buffer, window, cx,
5860 );
5861 })
5862 })
5863 },
5864 ),
5865 )
5866 .child(buttons);
5867
5868 Some(element)
5869 }),
5870 )
5871 .into_any_element()
5872 }
5873
5874 fn render_message_queue_summary(
5875 &self,
5876 _window: &mut Window,
5877 cx: &Context<Self>,
5878 ) -> impl IntoElement {
5879 let queue_count = self.queued_messages_len();
5880 let title: SharedString = if queue_count == 1 {
5881 "1 Queued Message".into()
5882 } else {
5883 format!("{} Queued Messages", queue_count).into()
5884 };
5885
5886 h_flex()
5887 .p_1()
5888 .w_full()
5889 .gap_1()
5890 .justify_between()
5891 .when(self.queue_expanded, |this| {
5892 this.border_b_1().border_color(cx.theme().colors().border)
5893 })
5894 .child(
5895 h_flex()
5896 .id("queue_summary")
5897 .gap_1()
5898 .child(Disclosure::new("queue_disclosure", self.queue_expanded))
5899 .child(Label::new(title).size(LabelSize::Small).color(Color::Muted))
5900 .on_click(cx.listener(|this, _, _, cx| {
5901 this.queue_expanded = !this.queue_expanded;
5902 cx.notify();
5903 })),
5904 )
5905 .child(
5906 Button::new("clear_queue", "Clear All")
5907 .label_size(LabelSize::Small)
5908 .key_binding(KeyBinding::for_action(&ClearMessageQueue, cx))
5909 .on_click(cx.listener(|this, _, _, cx| {
5910 this.clear_queue(cx);
5911 this.can_fast_track_queue = false;
5912 cx.notify();
5913 })),
5914 )
5915 }
5916
5917 fn render_message_queue_entries(
5918 &self,
5919 _window: &mut Window,
5920 cx: &Context<Self>,
5921 ) -> impl IntoElement {
5922 let message_editor = self.message_editor.read(cx);
5923 let focus_handle = message_editor.focus_handle(cx);
5924
5925 let queue_len = self.queued_message_editors.len();
5926 let can_fast_track = self.can_fast_track_queue && queue_len > 0;
5927
5928 v_flex()
5929 .id("message_queue_list")
5930 .max_h_40()
5931 .overflow_y_scroll()
5932 .children(
5933 self.queued_message_editors
5934 .iter()
5935 .enumerate()
5936 .map(|(index, editor)| {
5937 let is_next = index == 0;
5938 let (icon_color, tooltip_text) = if is_next {
5939 (Color::Accent, "Next in Queue")
5940 } else {
5941 (Color::Muted, "In Queue")
5942 };
5943
5944 let editor_focused = editor.focus_handle(cx).is_focused(_window);
5945 let keybinding_size = rems_from_px(12.);
5946
5947 h_flex()
5948 .group("queue_entry")
5949 .w_full()
5950 .p_1p5()
5951 .gap_1()
5952 .bg(cx.theme().colors().editor_background)
5953 .when(index < queue_len - 1, |this| {
5954 this.border_b_1()
5955 .border_color(cx.theme().colors().border_variant)
5956 })
5957 .child(
5958 div()
5959 .id("next_in_queue")
5960 .child(
5961 Icon::new(IconName::Circle)
5962 .size(IconSize::Small)
5963 .color(icon_color),
5964 )
5965 .tooltip(Tooltip::text(tooltip_text)),
5966 )
5967 .child(editor.clone())
5968 .child(if editor_focused {
5969 h_flex()
5970 .gap_1()
5971 .min_w_40()
5972 .child(
5973 IconButton::new(("cancel_edit", index), IconName::Close)
5974 .icon_size(IconSize::Small)
5975 .icon_color(Color::Error)
5976 .tooltip({
5977 let focus_handle = editor.focus_handle(cx);
5978 move |_window, cx| {
5979 Tooltip::for_action_in(
5980 "Cancel Edit",
5981 &editor::actions::Cancel,
5982 &focus_handle,
5983 cx,
5984 )
5985 }
5986 })
5987 .on_click({
5988 let main_editor = self.message_editor.clone();
5989 cx.listener(move |_, _, window, cx| {
5990 window.focus(&main_editor.focus_handle(cx), cx);
5991 })
5992 }),
5993 )
5994 .child(
5995 IconButton::new(("save_edit", index), IconName::Check)
5996 .icon_size(IconSize::Small)
5997 .icon_color(Color::Success)
5998 .tooltip({
5999 let focus_handle = editor.focus_handle(cx);
6000 move |_window, cx| {
6001 Tooltip::for_action_in(
6002 "Save Edit",
6003 &Chat,
6004 &focus_handle,
6005 cx,
6006 )
6007 }
6008 })
6009 .on_click({
6010 let main_editor = self.message_editor.clone();
6011 cx.listener(move |_, _, window, cx| {
6012 window.focus(&main_editor.focus_handle(cx), cx);
6013 })
6014 }),
6015 )
6016 .child(
6017 Button::new(("send_now_focused", index), "Send Now")
6018 .label_size(LabelSize::Small)
6019 .style(ButtonStyle::Outlined)
6020 .key_binding(
6021 KeyBinding::for_action_in(
6022 &SendImmediately,
6023 &editor.focus_handle(cx),
6024 cx,
6025 )
6026 .map(|kb| kb.size(keybinding_size)),
6027 )
6028 .on_click(cx.listener(move |this, _, window, cx| {
6029 this.send_queued_message_at_index(
6030 index, true, window, cx,
6031 );
6032 })),
6033 )
6034 } else {
6035 h_flex()
6036 .gap_1()
6037 .when(!is_next, |this| this.visible_on_hover("queue_entry"))
6038 .child(
6039 IconButton::new(("edit", index), IconName::Pencil)
6040 .icon_size(IconSize::Small)
6041 .tooltip({
6042 let focus_handle = focus_handle.clone();
6043 move |_window, cx| {
6044 if is_next {
6045 Tooltip::for_action_in(
6046 "Edit",
6047 &EditFirstQueuedMessage,
6048 &focus_handle,
6049 cx,
6050 )
6051 } else {
6052 Tooltip::simple("Edit", cx)
6053 }
6054 }
6055 })
6056 .on_click({
6057 let editor = editor.clone();
6058 cx.listener(move |_, _, window, cx| {
6059 window.focus(&editor.focus_handle(cx), cx);
6060 })
6061 }),
6062 )
6063 .child(
6064 IconButton::new(("delete", index), IconName::Trash)
6065 .icon_size(IconSize::Small)
6066 .tooltip({
6067 let focus_handle = focus_handle.clone();
6068 move |_window, cx| {
6069 if is_next {
6070 Tooltip::for_action_in(
6071 "Remove Message from Queue",
6072 &RemoveFirstQueuedMessage,
6073 &focus_handle,
6074 cx,
6075 )
6076 } else {
6077 Tooltip::simple(
6078 "Remove Message from Queue",
6079 cx,
6080 )
6081 }
6082 }
6083 })
6084 .on_click(cx.listener(move |this, _, _, cx| {
6085 this.remove_from_queue(index, cx);
6086 cx.notify();
6087 })),
6088 )
6089 .child(
6090 Button::new(("send_now", index), "Send Now")
6091 .label_size(LabelSize::Small)
6092 .when(is_next && message_editor.is_empty(cx), |this| {
6093 let action: Box<dyn gpui::Action> =
6094 if can_fast_track {
6095 Box::new(Chat)
6096 } else {
6097 Box::new(SendNextQueuedMessage)
6098 };
6099
6100 this.style(ButtonStyle::Outlined).key_binding(
6101 KeyBinding::for_action_in(
6102 action.as_ref(),
6103 &focus_handle.clone(),
6104 cx,
6105 )
6106 .map(|kb| kb.size(keybinding_size)),
6107 )
6108 })
6109 .when(is_next && !message_editor.is_empty(cx), |this| {
6110 this.style(ButtonStyle::Outlined)
6111 })
6112 .on_click(cx.listener(move |this, _, window, cx| {
6113 this.send_queued_message_at_index(
6114 index, true, window, cx,
6115 );
6116 })),
6117 )
6118 })
6119 }),
6120 )
6121 .into_any_element()
6122 }
6123
6124 fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
6125 let focus_handle = self.message_editor.focus_handle(cx);
6126 let editor_bg_color = cx.theme().colors().editor_background;
6127 let (expand_icon, expand_tooltip) = if self.editor_expanded {
6128 (IconName::Minimize, "Minimize Message Editor")
6129 } else {
6130 (IconName::Maximize, "Expand Message Editor")
6131 };
6132
6133 let backdrop = div()
6134 .size_full()
6135 .absolute()
6136 .inset_0()
6137 .bg(cx.theme().colors().panel_background)
6138 .opacity(0.8)
6139 .block_mouse_except_scroll();
6140
6141 let enable_editor = match self.thread_state {
6142 ThreadState::Ready { .. } => true,
6143 ThreadState::Loading { .. }
6144 | ThreadState::Unauthenticated { .. }
6145 | ThreadState::LoadError(..) => false,
6146 };
6147
6148 v_flex()
6149 .on_action(cx.listener(Self::expand_message_editor))
6150 .p_2()
6151 .gap_2()
6152 .border_t_1()
6153 .border_color(cx.theme().colors().border)
6154 .bg(editor_bg_color)
6155 .when(self.editor_expanded, |this| {
6156 this.h(vh(0.8, window)).size_full().justify_between()
6157 })
6158 .child(
6159 v_flex()
6160 .relative()
6161 .size_full()
6162 .pt_1()
6163 .pr_2p5()
6164 .child(self.message_editor.clone())
6165 .child(
6166 h_flex()
6167 .absolute()
6168 .top_0()
6169 .right_0()
6170 .opacity(0.5)
6171 .hover(|this| this.opacity(1.0))
6172 .child(
6173 IconButton::new("toggle-height", expand_icon)
6174 .icon_size(IconSize::Small)
6175 .icon_color(Color::Muted)
6176 .tooltip({
6177 move |_window, cx| {
6178 Tooltip::for_action_in(
6179 expand_tooltip,
6180 &ExpandMessageEditor,
6181 &focus_handle,
6182 cx,
6183 )
6184 }
6185 })
6186 .on_click(cx.listener(|this, _, window, cx| {
6187 this.expand_message_editor(
6188 &ExpandMessageEditor,
6189 window,
6190 cx,
6191 );
6192 })),
6193 ),
6194 ),
6195 )
6196 .child(
6197 h_flex()
6198 .flex_none()
6199 .flex_wrap()
6200 .justify_between()
6201 .child(
6202 h_flex()
6203 .gap_0p5()
6204 .child(self.render_add_context_button(cx))
6205 .child(self.render_follow_toggle(cx)),
6206 )
6207 .child(
6208 h_flex()
6209 .gap_1()
6210 .children(self.render_token_usage(cx))
6211 .children(self.render_thinking_toggle(cx))
6212 .children(self.profile_selector.clone())
6213 // Either config_options_view OR (mode_selector + model_selector)
6214 .children(self.config_options_view.clone())
6215 .when(self.config_options_view.is_none(), |this| {
6216 this.children(self.mode_selector().cloned())
6217 .children(self.model_selector.clone())
6218 })
6219 .child(self.render_send_button(cx)),
6220 ),
6221 )
6222 .when(!enable_editor, |this| this.child(backdrop))
6223 .into_any()
6224 }
6225
6226 pub(crate) fn as_native_connection(
6227 &self,
6228 cx: &App,
6229 ) -> Option<Rc<agent::NativeAgentConnection>> {
6230 let acp_thread = self.thread()?.read(cx);
6231 acp_thread.connection().clone().downcast()
6232 }
6233
6234 pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
6235 let acp_thread = self.thread()?.read(cx);
6236 self.as_native_connection(cx)?
6237 .thread(acp_thread.session_id(), cx)
6238 }
6239
6240 fn queued_messages_len(&self) -> usize {
6241 self.local_queued_messages.len()
6242 }
6243
6244 fn has_queued_messages(&self) -> bool {
6245 !self.local_queued_messages.is_empty()
6246 }
6247
6248 /// Syncs the has_queued_message flag to the native thread (if applicable).
6249 /// This flag tells the native thread to end its turn at the next message boundary.
6250 fn sync_queue_flag_to_native_thread(&self, cx: &mut Context<Self>) {
6251 if let Some(native_thread) = self.as_native_thread(cx) {
6252 let has_queued = !self.local_queued_messages.is_empty();
6253 native_thread.update(cx, |thread, _| {
6254 thread.set_has_queued_message(has_queued);
6255 });
6256 }
6257 }
6258
6259 fn add_to_queue(
6260 &mut self,
6261 content: Vec<acp::ContentBlock>,
6262 tracked_buffers: Vec<Entity<Buffer>>,
6263 cx: &mut Context<Self>,
6264 ) {
6265 self.local_queued_messages.push(QueuedMessage {
6266 content,
6267 tracked_buffers,
6268 });
6269 self.sync_queue_flag_to_native_thread(cx);
6270 }
6271
6272 fn remove_from_queue(&mut self, index: usize, cx: &mut Context<Self>) -> Option<QueuedMessage> {
6273 if index < self.local_queued_messages.len() {
6274 let removed = self.local_queued_messages.remove(index);
6275 self.sync_queue_flag_to_native_thread(cx);
6276 Some(removed)
6277 } else {
6278 None
6279 }
6280 }
6281
6282 fn update_queued_message(
6283 &mut self,
6284 index: usize,
6285 content: Vec<acp::ContentBlock>,
6286 tracked_buffers: Vec<Entity<Buffer>>,
6287 _cx: &mut Context<Self>,
6288 ) -> bool {
6289 if index < self.local_queued_messages.len() {
6290 self.local_queued_messages[index] = QueuedMessage {
6291 content,
6292 tracked_buffers,
6293 };
6294 true
6295 } else {
6296 false
6297 }
6298 }
6299
6300 fn clear_queue(&mut self, cx: &mut Context<Self>) {
6301 self.local_queued_messages.clear();
6302 self.sync_queue_flag_to_native_thread(cx);
6303 }
6304
6305 fn queued_message_contents(&self) -> Vec<Vec<acp::ContentBlock>> {
6306 self.local_queued_messages
6307 .iter()
6308 .map(|q| q.content.clone())
6309 .collect()
6310 }
6311
6312 fn save_queued_message_at_index(&mut self, index: usize, cx: &mut Context<Self>) {
6313 let Some(editor) = self.queued_message_editors.get(index) else {
6314 return;
6315 };
6316
6317 let contents_task = editor.update(cx, |editor, cx| editor.contents(false, cx));
6318
6319 cx.spawn(async move |this, cx| {
6320 let Ok((content, tracked_buffers)) = contents_task.await else {
6321 return Ok::<(), anyhow::Error>(());
6322 };
6323
6324 this.update(cx, |this, cx| {
6325 this.update_queued_message(index, content, tracked_buffers, cx);
6326 cx.notify();
6327 })?;
6328
6329 Ok(())
6330 })
6331 .detach_and_log_err(cx);
6332 }
6333
6334 fn sync_queued_message_editors(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6335 let needed_count = self.queued_messages_len();
6336 let current_count = self.queued_message_editors.len();
6337
6338 if current_count == needed_count && needed_count == self.last_synced_queue_length {
6339 return;
6340 }
6341
6342 let queued_messages = self.queued_message_contents();
6343
6344 if current_count > needed_count {
6345 self.queued_message_editors.truncate(needed_count);
6346 self.queued_message_editor_subscriptions
6347 .truncate(needed_count);
6348
6349 for (index, editor) in self.queued_message_editors.iter().enumerate() {
6350 if let Some(content) = queued_messages.get(index) {
6351 editor.update(cx, |editor, cx| {
6352 editor.set_message(content.clone(), window, cx);
6353 });
6354 }
6355 }
6356 }
6357
6358 while self.queued_message_editors.len() < needed_count {
6359 let agent_name = self.agent.name();
6360 let index = self.queued_message_editors.len();
6361 let content = queued_messages.get(index).cloned().unwrap_or_default();
6362
6363 let editor = cx.new(|cx| {
6364 let mut editor = MessageEditor::new(
6365 self.workspace.clone(),
6366 self.project.downgrade(),
6367 None,
6368 self.history.downgrade(),
6369 None,
6370 self.prompt_capabilities.clone(),
6371 self.available_commands.clone(),
6372 agent_name.clone(),
6373 "",
6374 EditorMode::AutoHeight {
6375 min_lines: 1,
6376 max_lines: Some(10),
6377 },
6378 window,
6379 cx,
6380 );
6381 editor.set_message(content, window, cx);
6382 editor
6383 });
6384
6385 let main_editor = self.message_editor.clone();
6386 let subscription = cx.subscribe_in(
6387 &editor,
6388 window,
6389 move |this, _editor, event, window, cx| match event {
6390 MessageEditorEvent::LostFocus => {
6391 this.save_queued_message_at_index(index, cx);
6392 }
6393 MessageEditorEvent::Cancel => {
6394 window.focus(&main_editor.focus_handle(cx), cx);
6395 }
6396 MessageEditorEvent::Send => {
6397 window.focus(&main_editor.focus_handle(cx), cx);
6398 }
6399 MessageEditorEvent::SendImmediately => {
6400 this.send_queued_message_at_index(index, true, window, cx);
6401 }
6402 _ => {}
6403 },
6404 );
6405
6406 self.queued_message_editors.push(editor);
6407 self.queued_message_editor_subscriptions.push(subscription);
6408 }
6409
6410 self.last_synced_queue_length = needed_count;
6411 }
6412
6413 fn is_imported_thread(&self, cx: &App) -> bool {
6414 let Some(thread) = self.as_native_thread(cx) else {
6415 return false;
6416 };
6417 thread.read(cx).is_imported()
6418 }
6419
6420 fn supports_split_token_display(&self, cx: &App) -> bool {
6421 self.as_native_thread(cx)
6422 .and_then(|thread| thread.read(cx).model())
6423 .is_some_and(|model| model.supports_split_token_display())
6424 }
6425
6426 fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
6427 let thread = self.thread()?.read(cx);
6428 let usage = thread.token_usage()?;
6429 let is_generating = thread.status() != ThreadStatus::Idle;
6430 let show_split = self.supports_split_token_display(cx);
6431
6432 let separator_color = Color::Custom(cx.theme().colors().text_muted.opacity(0.5));
6433 let token_label = |text: String, animation_id: &'static str| {
6434 Label::new(text)
6435 .size(LabelSize::Small)
6436 .color(Color::Muted)
6437 .map(|label| {
6438 if is_generating {
6439 label
6440 .with_animation(
6441 animation_id,
6442 Animation::new(Duration::from_secs(2))
6443 .repeat()
6444 .with_easing(pulsating_between(0.3, 0.8)),
6445 |label, delta| label.alpha(delta),
6446 )
6447 .into_any()
6448 } else {
6449 label.into_any_element()
6450 }
6451 })
6452 };
6453
6454 if show_split {
6455 let max_output_tokens = self
6456 .as_native_thread(cx)
6457 .and_then(|thread| thread.read(cx).model())
6458 .and_then(|model| model.max_output_tokens())
6459 .unwrap_or(0);
6460
6461 let input = crate::text_thread_editor::humanize_token_count(usage.input_tokens);
6462 let input_max = crate::text_thread_editor::humanize_token_count(
6463 usage.max_tokens.saturating_sub(max_output_tokens),
6464 );
6465 let output = crate::text_thread_editor::humanize_token_count(usage.output_tokens);
6466 let output_max = crate::text_thread_editor::humanize_token_count(max_output_tokens);
6467
6468 Some(
6469 h_flex()
6470 .flex_shrink_0()
6471 .gap_1()
6472 .mr_1p5()
6473 .child(
6474 h_flex()
6475 .gap_0p5()
6476 .child(
6477 Icon::new(IconName::ArrowUp)
6478 .size(IconSize::XSmall)
6479 .color(Color::Muted),
6480 )
6481 .child(token_label(input, "input-tokens-label"))
6482 .child(
6483 Label::new("/")
6484 .size(LabelSize::Small)
6485 .color(separator_color),
6486 )
6487 .child(
6488 Label::new(input_max)
6489 .size(LabelSize::Small)
6490 .color(Color::Muted),
6491 ),
6492 )
6493 .child(
6494 h_flex()
6495 .gap_0p5()
6496 .child(
6497 Icon::new(IconName::ArrowDown)
6498 .size(IconSize::XSmall)
6499 .color(Color::Muted),
6500 )
6501 .child(token_label(output, "output-tokens-label"))
6502 .child(
6503 Label::new("/")
6504 .size(LabelSize::Small)
6505 .color(separator_color),
6506 )
6507 .child(
6508 Label::new(output_max)
6509 .size(LabelSize::Small)
6510 .color(Color::Muted),
6511 ),
6512 ),
6513 )
6514 } else {
6515 let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
6516 let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
6517
6518 Some(
6519 h_flex()
6520 .flex_shrink_0()
6521 .gap_0p5()
6522 .mr_1p5()
6523 .child(token_label(used, "used-tokens-label"))
6524 .child(
6525 Label::new("/")
6526 .size(LabelSize::Small)
6527 .color(separator_color),
6528 )
6529 .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
6530 )
6531 }
6532 }
6533
6534 fn render_thinking_toggle(&self, cx: &mut Context<Self>) -> Option<IconButton> {
6535 if !cx.has_flag::<CloudThinkingToggleFeatureFlag>() {
6536 return None;
6537 }
6538
6539 let thread = self.as_native_thread(cx)?.read(cx);
6540
6541 let supports_thinking = thread.model()?.supports_thinking();
6542 if !supports_thinking {
6543 return None;
6544 }
6545
6546 let thinking = thread.thinking_enabled();
6547
6548 let tooltip_label = if thinking {
6549 "Disable Thinking Mode".to_string()
6550 } else {
6551 "Enable Thinking Mode".to_string()
6552 };
6553
6554 Some(
6555 IconButton::new("thinking-mode", IconName::ToolThink)
6556 .icon_size(IconSize::Small)
6557 .icon_color(Color::Muted)
6558 .toggle_state(thinking)
6559 .tooltip(Tooltip::text(tooltip_label))
6560 .on_click(cx.listener(move |this, _, _window, cx| {
6561 if let Some(thread) = this.as_native_thread(cx) {
6562 thread.update(cx, |thread, cx| {
6563 thread.set_thinking_enabled(!thread.thinking_enabled(), cx);
6564 });
6565 }
6566 })),
6567 )
6568 }
6569
6570 fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
6571 let Some(thread) = self.thread() else {
6572 return;
6573 };
6574 let telemetry = ActionLogTelemetry::from(thread.read(cx));
6575 let action_log = thread.read(cx).action_log().clone();
6576 action_log.update(cx, |action_log, cx| {
6577 action_log.keep_all_edits(Some(telemetry), cx)
6578 });
6579 }
6580
6581 fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
6582 let Some(thread) = self.thread() else {
6583 return;
6584 };
6585 let telemetry = ActionLogTelemetry::from(thread.read(cx));
6586 let action_log = thread.read(cx).action_log().clone();
6587 action_log
6588 .update(cx, |action_log, cx| {
6589 action_log.reject_all_edits(Some(telemetry), cx)
6590 })
6591 .detach();
6592 }
6593
6594 fn allow_always(&mut self, _: &AllowAlways, window: &mut Window, cx: &mut Context<Self>) {
6595 self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowAlways, window, cx);
6596 }
6597
6598 fn allow_once(&mut self, _: &AllowOnce, window: &mut Window, cx: &mut Context<Self>) {
6599 self.authorize_pending_with_granularity(true, window, cx);
6600 }
6601
6602 fn reject_once(&mut self, _: &RejectOnce, window: &mut Window, cx: &mut Context<Self>) {
6603 self.authorize_pending_with_granularity(false, window, cx);
6604 }
6605
6606 fn authorize_pending_with_granularity(
6607 &mut self,
6608 is_allow: bool,
6609 window: &mut Window,
6610 cx: &mut Context<Self>,
6611 ) -> Option<()> {
6612 let thread = self.thread()?.read(cx);
6613 let tool_call = thread.first_tool_awaiting_confirmation()?;
6614 let ToolCallStatus::WaitingForConfirmation { options, .. } = &tool_call.status else {
6615 return None;
6616 };
6617 let tool_call_id = tool_call.id.clone();
6618
6619 let PermissionOptions::Dropdown(choices) = options else {
6620 let kind = if is_allow {
6621 acp::PermissionOptionKind::AllowOnce
6622 } else {
6623 acp::PermissionOptionKind::RejectOnce
6624 };
6625 return self.authorize_pending_tool_call(kind, window, cx);
6626 };
6627
6628 // Get selected index, defaulting to last option ("Only this time")
6629 let selected_index = self
6630 .selected_permission_granularity
6631 .get(&tool_call_id)
6632 .copied()
6633 .unwrap_or_else(|| choices.len().saturating_sub(1));
6634
6635 let selected_choice = choices.get(selected_index).or(choices.last())?;
6636
6637 let selected_option = if is_allow {
6638 &selected_choice.allow
6639 } else {
6640 &selected_choice.deny
6641 };
6642
6643 self.authorize_tool_call(
6644 tool_call_id,
6645 selected_option.option_id.clone(),
6646 selected_option.kind,
6647 window,
6648 cx,
6649 );
6650
6651 Some(())
6652 }
6653
6654 fn open_permission_dropdown(
6655 &mut self,
6656 _: &crate::OpenPermissionDropdown,
6657 window: &mut Window,
6658 cx: &mut Context<Self>,
6659 ) {
6660 self.permission_dropdown_handle.toggle(window, cx);
6661 }
6662
6663 fn handle_select_permission_granularity(
6664 &mut self,
6665 action: &SelectPermissionGranularity,
6666 _window: &mut Window,
6667 cx: &mut Context<Self>,
6668 ) {
6669 let tool_call_id = acp::ToolCallId::new(action.tool_call_id.clone());
6670 self.selected_permission_granularity
6671 .insert(tool_call_id, action.index);
6672 cx.notify();
6673 }
6674
6675 fn handle_authorize_tool_call(
6676 &mut self,
6677 action: &AuthorizeToolCall,
6678 window: &mut Window,
6679 cx: &mut Context<Self>,
6680 ) {
6681 let tool_call_id = acp::ToolCallId::new(action.tool_call_id.clone());
6682 let option_id = acp::PermissionOptionId::new(action.option_id.clone());
6683 let option_kind = match action.option_kind.as_str() {
6684 "AllowOnce" => acp::PermissionOptionKind::AllowOnce,
6685 "AllowAlways" => acp::PermissionOptionKind::AllowAlways,
6686 "RejectOnce" => acp::PermissionOptionKind::RejectOnce,
6687 "RejectAlways" => acp::PermissionOptionKind::RejectAlways,
6688 _ => acp::PermissionOptionKind::AllowOnce,
6689 };
6690
6691 self.authorize_tool_call(tool_call_id, option_id, option_kind, window, cx);
6692 }
6693
6694 fn authorize_pending_tool_call(
6695 &mut self,
6696 kind: acp::PermissionOptionKind,
6697 window: &mut Window,
6698 cx: &mut Context<Self>,
6699 ) -> Option<()> {
6700 let thread = self.thread()?.read(cx);
6701 let tool_call = thread.first_tool_awaiting_confirmation()?;
6702 let ToolCallStatus::WaitingForConfirmation { options, .. } = &tool_call.status else {
6703 return None;
6704 };
6705 let option = options.first_option_of_kind(kind)?;
6706
6707 self.authorize_tool_call(
6708 tool_call.id.clone(),
6709 option.option_id.clone(),
6710 option.kind,
6711 window,
6712 cx,
6713 );
6714
6715 Some(())
6716 }
6717
6718 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
6719 let message_editor = self.message_editor.read(cx);
6720 let is_editor_empty = message_editor.is_empty(cx);
6721 let focus_handle = message_editor.focus_handle(cx);
6722
6723 let is_generating = self
6724 .thread()
6725 .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
6726
6727 if self.is_loading_contents {
6728 div()
6729 .id("loading-message-content")
6730 .px_1()
6731 .tooltip(Tooltip::text("Loading Added Context…"))
6732 .child(loading_contents_spinner(IconSize::default()))
6733 .into_any_element()
6734 } else if is_generating && is_editor_empty {
6735 IconButton::new("stop-generation", IconName::Stop)
6736 .icon_color(Color::Error)
6737 .style(ButtonStyle::Tinted(TintColor::Error))
6738 .tooltip(move |_window, cx| {
6739 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, cx)
6740 })
6741 .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
6742 .into_any_element()
6743 } else {
6744 IconButton::new("send-message", IconName::Send)
6745 .style(ButtonStyle::Filled)
6746 .map(|this| {
6747 if is_editor_empty && !is_generating {
6748 this.disabled(true).icon_color(Color::Muted)
6749 } else {
6750 this.icon_color(Color::Accent)
6751 }
6752 })
6753 .tooltip(move |_window, cx| {
6754 if is_editor_empty && !is_generating {
6755 Tooltip::for_action("Type to Send", &Chat, cx)
6756 } else if is_generating {
6757 let focus_handle = focus_handle.clone();
6758
6759 Tooltip::element(move |_window, cx| {
6760 v_flex()
6761 .gap_1()
6762 .child(
6763 h_flex()
6764 .gap_2()
6765 .justify_between()
6766 .child(Label::new("Queue and Send"))
6767 .child(KeyBinding::for_action_in(&Chat, &focus_handle, cx)),
6768 )
6769 .child(
6770 h_flex()
6771 .pt_1()
6772 .gap_2()
6773 .justify_between()
6774 .border_t_1()
6775 .border_color(cx.theme().colors().border_variant)
6776 .child(Label::new("Send Immediately"))
6777 .child(KeyBinding::for_action_in(
6778 &SendImmediately,
6779 &focus_handle,
6780 cx,
6781 )),
6782 )
6783 .into_any_element()
6784 })(_window, cx)
6785 } else {
6786 Tooltip::for_action("Send Message", &Chat, cx)
6787 }
6788 })
6789 .on_click(cx.listener(|this, _, window, cx| {
6790 this.send(window, cx);
6791 }))
6792 .into_any_element()
6793 }
6794 }
6795
6796 fn is_following(&self, cx: &App) -> bool {
6797 match self.thread().map(|thread| thread.read(cx).status()) {
6798 Some(ThreadStatus::Generating) => self
6799 .workspace
6800 .read_with(cx, |workspace, _| {
6801 workspace.is_being_followed(CollaboratorId::Agent)
6802 })
6803 .unwrap_or(false),
6804 _ => self.should_be_following,
6805 }
6806 }
6807
6808 fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6809 let following = self.is_following(cx);
6810
6811 self.should_be_following = !following;
6812 if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
6813 self.workspace
6814 .update(cx, |workspace, cx| {
6815 if following {
6816 workspace.unfollow(CollaboratorId::Agent, window, cx);
6817 } else {
6818 workspace.follow(CollaboratorId::Agent, window, cx);
6819 }
6820 })
6821 .ok();
6822 }
6823
6824 telemetry::event!("Follow Agent Selected", following = !following);
6825 }
6826
6827 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
6828 let following = self.is_following(cx);
6829
6830 let tooltip_label = if following {
6831 if self.agent.name() == "Zed Agent" {
6832 format!("Stop Following the {}", self.agent.name())
6833 } else {
6834 format!("Stop Following {}", self.agent.name())
6835 }
6836 } else {
6837 if self.agent.name() == "Zed Agent" {
6838 format!("Follow the {}", self.agent.name())
6839 } else {
6840 format!("Follow {}", self.agent.name())
6841 }
6842 };
6843
6844 IconButton::new("follow-agent", IconName::Crosshair)
6845 .icon_size(IconSize::Small)
6846 .icon_color(Color::Muted)
6847 .toggle_state(following)
6848 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
6849 .tooltip(move |_window, cx| {
6850 if following {
6851 Tooltip::for_action(tooltip_label.clone(), &Follow, cx)
6852 } else {
6853 Tooltip::with_meta(
6854 tooltip_label.clone(),
6855 Some(&Follow),
6856 "Track the agent's location as it reads and edits files.",
6857 cx,
6858 )
6859 }
6860 })
6861 .on_click(cx.listener(move |this, _, window, cx| {
6862 this.toggle_following(window, cx);
6863 }))
6864 }
6865
6866 fn render_add_context_button(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
6867 let focus_handle = self.message_editor.focus_handle(cx);
6868 let weak_self = cx.weak_entity();
6869
6870 PopoverMenu::new("add-context-menu")
6871 .trigger_with_tooltip(
6872 IconButton::new("add-context", IconName::Plus)
6873 .icon_size(IconSize::Small)
6874 .icon_color(Color::Muted),
6875 {
6876 move |_window, cx| {
6877 Tooltip::for_action_in(
6878 "Add Context",
6879 &OpenAddContextMenu,
6880 &focus_handle,
6881 cx,
6882 )
6883 }
6884 },
6885 )
6886 .anchor(gpui::Corner::BottomLeft)
6887 .with_handle(self.add_context_menu_handle.clone())
6888 .offset(gpui::Point {
6889 x: px(0.0),
6890 y: px(-2.0),
6891 })
6892 .menu(move |window, cx| {
6893 weak_self
6894 .update(cx, |this, cx| this.build_add_context_menu(window, cx))
6895 .ok()
6896 })
6897 }
6898
6899 fn build_add_context_menu(
6900 &self,
6901 window: &mut Window,
6902 cx: &mut Context<Self>,
6903 ) -> Entity<ContextMenu> {
6904 let message_editor = self.message_editor.clone();
6905 let workspace = self.workspace.clone();
6906 let supports_images = self.prompt_capabilities.borrow().image;
6907
6908 let has_selection = workspace
6909 .upgrade()
6910 .and_then(|ws| {
6911 ws.read(cx)
6912 .active_item(cx)
6913 .and_then(|item| item.downcast::<Editor>())
6914 })
6915 .is_some_and(|editor| {
6916 editor.update(cx, |editor, cx| {
6917 editor.has_non_empty_selection(&editor.display_snapshot(cx))
6918 })
6919 });
6920
6921 ContextMenu::build(window, cx, move |menu, _window, _cx| {
6922 menu.key_context("AddContextMenu")
6923 .header("Context")
6924 .item(
6925 ContextMenuEntry::new("Files & Directories")
6926 .icon(IconName::File)
6927 .icon_color(Color::Muted)
6928 .icon_size(IconSize::XSmall)
6929 .handler({
6930 let message_editor = message_editor.clone();
6931 move |window, cx| {
6932 message_editor.focus_handle(cx).focus(window, cx);
6933 message_editor.update(cx, |editor, cx| {
6934 editor.insert_context_type("file", window, cx);
6935 });
6936 }
6937 }),
6938 )
6939 .item(
6940 ContextMenuEntry::new("Symbols")
6941 .icon(IconName::Code)
6942 .icon_color(Color::Muted)
6943 .icon_size(IconSize::XSmall)
6944 .handler({
6945 let message_editor = message_editor.clone();
6946 move |window, cx| {
6947 message_editor.focus_handle(cx).focus(window, cx);
6948 message_editor.update(cx, |editor, cx| {
6949 editor.insert_context_type("symbol", window, cx);
6950 });
6951 }
6952 }),
6953 )
6954 .item(
6955 ContextMenuEntry::new("Threads")
6956 .icon(IconName::Thread)
6957 .icon_color(Color::Muted)
6958 .icon_size(IconSize::XSmall)
6959 .handler({
6960 let message_editor = message_editor.clone();
6961 move |window, cx| {
6962 message_editor.focus_handle(cx).focus(window, cx);
6963 message_editor.update(cx, |editor, cx| {
6964 editor.insert_context_type("thread", window, cx);
6965 });
6966 }
6967 }),
6968 )
6969 .item(
6970 ContextMenuEntry::new("Rules")
6971 .icon(IconName::Reader)
6972 .icon_color(Color::Muted)
6973 .icon_size(IconSize::XSmall)
6974 .handler({
6975 let message_editor = message_editor.clone();
6976 move |window, cx| {
6977 message_editor.focus_handle(cx).focus(window, cx);
6978 message_editor.update(cx, |editor, cx| {
6979 editor.insert_context_type("rule", window, cx);
6980 });
6981 }
6982 }),
6983 )
6984 .item(
6985 ContextMenuEntry::new("Image")
6986 .icon(IconName::Image)
6987 .icon_color(Color::Muted)
6988 .icon_size(IconSize::XSmall)
6989 .disabled(!supports_images)
6990 .handler({
6991 let message_editor = message_editor.clone();
6992 move |window, cx| {
6993 message_editor.focus_handle(cx).focus(window, cx);
6994 message_editor.update(cx, |editor, cx| {
6995 editor.add_images_from_picker(window, cx);
6996 });
6997 }
6998 }),
6999 )
7000 .item(
7001 ContextMenuEntry::new("Selection")
7002 .icon(IconName::CursorIBeam)
7003 .icon_color(Color::Muted)
7004 .icon_size(IconSize::XSmall)
7005 .disabled(!has_selection)
7006 .handler({
7007 move |window, cx| {
7008 message_editor.focus_handle(cx).focus(window, cx);
7009 message_editor.update(cx, |editor, cx| {
7010 editor.insert_selections(window, cx);
7011 });
7012 }
7013 }),
7014 )
7015 })
7016 }
7017
7018 fn open_add_context_menu(
7019 &mut self,
7020 _action: &OpenAddContextMenu,
7021 window: &mut Window,
7022 cx: &mut Context<Self>,
7023 ) {
7024 let menu_handle = self.add_context_menu_handle.clone();
7025 window.defer(cx, move |window, cx| {
7026 menu_handle.toggle(window, cx);
7027 });
7028 }
7029
7030 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
7031 let workspace = self.workspace.clone();
7032 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
7033 Self::open_link(text, &workspace, window, cx);
7034 })
7035 }
7036
7037 fn open_link(
7038 url: SharedString,
7039 workspace: &WeakEntity<Workspace>,
7040 window: &mut Window,
7041 cx: &mut App,
7042 ) {
7043 let Some(workspace) = workspace.upgrade() else {
7044 cx.open_url(&url);
7045 return;
7046 };
7047
7048 if let Some(mention) = MentionUri::parse(&url, workspace.read(cx).path_style(cx)).log_err()
7049 {
7050 workspace.update(cx, |workspace, cx| match mention {
7051 MentionUri::File { abs_path } => {
7052 let project = workspace.project();
7053 let Some(path) =
7054 project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
7055 else {
7056 return;
7057 };
7058
7059 workspace
7060 .open_path(path, None, true, window, cx)
7061 .detach_and_log_err(cx);
7062 }
7063 MentionUri::PastedImage => {}
7064 MentionUri::Directory { abs_path } => {
7065 let project = workspace.project();
7066 let Some(entry_id) = project.update(cx, |project, cx| {
7067 let path = project.find_project_path(abs_path, cx)?;
7068 project.entry_for_path(&path, cx).map(|entry| entry.id)
7069 }) else {
7070 return;
7071 };
7072
7073 project.update(cx, |_, cx| {
7074 cx.emit(project::Event::RevealInProjectPanel(entry_id));
7075 });
7076 }
7077 MentionUri::Symbol {
7078 abs_path: path,
7079 line_range,
7080 ..
7081 }
7082 | MentionUri::Selection {
7083 abs_path: Some(path),
7084 line_range,
7085 } => {
7086 let project = workspace.project();
7087 let Some(path) =
7088 project.update(cx, |project, cx| project.find_project_path(path, cx))
7089 else {
7090 return;
7091 };
7092
7093 let item = workspace.open_path(path, None, true, window, cx);
7094 window
7095 .spawn(cx, async move |cx| {
7096 let Some(editor) = item.await?.downcast::<Editor>() else {
7097 return Ok(());
7098 };
7099 let range = Point::new(*line_range.start(), 0)
7100 ..Point::new(*line_range.start(), 0);
7101 editor
7102 .update_in(cx, |editor, window, cx| {
7103 editor.change_selections(
7104 SelectionEffects::scroll(Autoscroll::center()),
7105 window,
7106 cx,
7107 |s| s.select_ranges(vec![range]),
7108 );
7109 })
7110 .ok();
7111 anyhow::Ok(())
7112 })
7113 .detach_and_log_err(cx);
7114 }
7115 MentionUri::Selection { abs_path: None, .. } => {}
7116 MentionUri::Thread { id, name } => {
7117 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
7118 panel.update(cx, |panel, cx| {
7119 panel.open_thread(
7120 AgentSessionInfo {
7121 session_id: id,
7122 cwd: None,
7123 title: Some(name.into()),
7124 updated_at: None,
7125 meta: None,
7126 },
7127 window,
7128 cx,
7129 )
7130 });
7131 }
7132 }
7133 MentionUri::TextThread { path, .. } => {
7134 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
7135 panel.update(cx, |panel, cx| {
7136 panel
7137 .open_saved_text_thread(path.as_path().into(), window, cx)
7138 .detach_and_log_err(cx);
7139 });
7140 }
7141 }
7142 MentionUri::Rule { id, .. } => {
7143 let PromptId::User { uuid } = id else {
7144 return;
7145 };
7146 window.dispatch_action(
7147 Box::new(OpenRulesLibrary {
7148 prompt_to_select: Some(uuid.0),
7149 }),
7150 cx,
7151 )
7152 }
7153 MentionUri::Fetch { url } => {
7154 cx.open_url(url.as_str());
7155 }
7156 MentionUri::Diagnostics { .. } => {}
7157 })
7158 } else {
7159 cx.open_url(&url);
7160 }
7161 }
7162
7163 fn open_tool_call_location(
7164 &self,
7165 entry_ix: usize,
7166 location_ix: usize,
7167 window: &mut Window,
7168 cx: &mut Context<Self>,
7169 ) -> Option<()> {
7170 let (tool_call_location, agent_location) = self
7171 .thread()?
7172 .read(cx)
7173 .entries()
7174 .get(entry_ix)?
7175 .location(location_ix)?;
7176
7177 let project_path = self
7178 .project
7179 .read(cx)
7180 .find_project_path(&tool_call_location.path, cx)?;
7181
7182 let open_task = self
7183 .workspace
7184 .update(cx, |workspace, cx| {
7185 workspace.open_path(project_path, None, true, window, cx)
7186 })
7187 .log_err()?;
7188 window
7189 .spawn(cx, async move |cx| {
7190 let item = open_task.await?;
7191
7192 let Some(active_editor) = item.downcast::<Editor>() else {
7193 return anyhow::Ok(());
7194 };
7195
7196 active_editor.update_in(cx, |editor, window, cx| {
7197 let multibuffer = editor.buffer().read(cx);
7198 let buffer = multibuffer.as_singleton();
7199 if agent_location.buffer.upgrade() == buffer {
7200 let excerpt_id = multibuffer.excerpt_ids().first().cloned();
7201 let anchor =
7202 editor::Anchor::in_buffer(excerpt_id.unwrap(), agent_location.position);
7203 editor.change_selections(Default::default(), window, cx, |selections| {
7204 selections.select_anchor_ranges([anchor..anchor]);
7205 })
7206 } else {
7207 let row = tool_call_location.line.unwrap_or_default();
7208 editor.change_selections(Default::default(), window, cx, |selections| {
7209 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
7210 })
7211 }
7212 })?;
7213
7214 anyhow::Ok(())
7215 })
7216 .detach_and_log_err(cx);
7217
7218 None
7219 }
7220
7221 pub fn open_thread_as_markdown(
7222 &self,
7223 workspace: Entity<Workspace>,
7224 window: &mut Window,
7225 cx: &mut App,
7226 ) -> Task<Result<()>> {
7227 let markdown_language_task = workspace
7228 .read(cx)
7229 .app_state()
7230 .languages
7231 .language_for_name("Markdown");
7232
7233 let (thread_title, markdown) = if let Some(thread) = self.thread() {
7234 let thread = thread.read(cx);
7235 (thread.title().to_string(), thread.to_markdown(cx))
7236 } else {
7237 return Task::ready(Ok(()));
7238 };
7239
7240 let project = workspace.read(cx).project().clone();
7241 window.spawn(cx, async move |cx| {
7242 let markdown_language = markdown_language_task.await?;
7243
7244 let buffer = project
7245 .update(cx, |project, cx| {
7246 project.create_buffer(Some(markdown_language), false, cx)
7247 })
7248 .await?;
7249
7250 buffer.update(cx, |buffer, cx| {
7251 buffer.set_text(markdown, cx);
7252 buffer.set_capability(language::Capability::ReadWrite, cx);
7253 });
7254
7255 workspace.update_in(cx, |workspace, window, cx| {
7256 let buffer = cx
7257 .new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_title.clone()));
7258
7259 workspace.add_item_to_active_pane(
7260 Box::new(cx.new(|cx| {
7261 let mut editor =
7262 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
7263 editor.set_breadcrumb_header(thread_title);
7264 editor
7265 })),
7266 None,
7267 true,
7268 window,
7269 cx,
7270 );
7271 })?;
7272 anyhow::Ok(())
7273 })
7274 }
7275
7276 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
7277 self.list_state.scroll_to(ListOffset::default());
7278 cx.notify();
7279 }
7280
7281 fn scroll_to_most_recent_user_prompt(&mut self, cx: &mut Context<Self>) {
7282 let Some(thread) = self.thread() else {
7283 return;
7284 };
7285
7286 let entries = thread.read(cx).entries();
7287 if entries.is_empty() {
7288 return;
7289 }
7290
7291 // Find the most recent user message and scroll it to the top of the viewport.
7292 // (Fallback: if no user message exists, scroll to the bottom.)
7293 if let Some(ix) = entries
7294 .iter()
7295 .rposition(|entry| matches!(entry, AgentThreadEntry::UserMessage(_)))
7296 {
7297 self.list_state.scroll_to(ListOffset {
7298 item_ix: ix,
7299 offset_in_item: px(0.0),
7300 });
7301 cx.notify();
7302 } else {
7303 self.scroll_to_bottom(cx);
7304 }
7305 }
7306
7307 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
7308 if let Some(thread) = self.thread() {
7309 let entry_count = thread.read(cx).entries().len();
7310 self.list_state.reset(entry_count);
7311 cx.notify();
7312 }
7313 }
7314
7315 fn notify_with_sound(
7316 &mut self,
7317 caption: impl Into<SharedString>,
7318 icon: IconName,
7319 window: &mut Window,
7320 cx: &mut Context<Self>,
7321 ) {
7322 self.play_notification_sound(window, cx);
7323 self.show_notification(caption, icon, window, cx);
7324 }
7325
7326 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
7327 let settings = AgentSettings::get_global(cx);
7328 if settings.play_sound_when_agent_done && !window.is_window_active() {
7329 Audio::play_sound(Sound::AgentDone, cx);
7330 }
7331 }
7332
7333 fn show_notification(
7334 &mut self,
7335 caption: impl Into<SharedString>,
7336 icon: IconName,
7337 window: &mut Window,
7338 cx: &mut Context<Self>,
7339 ) {
7340 if !self.notifications.is_empty() {
7341 return;
7342 }
7343
7344 let settings = AgentSettings::get_global(cx);
7345
7346 let window_is_inactive = !window.is_window_active();
7347 let panel_is_hidden = self
7348 .workspace
7349 .upgrade()
7350 .map(|workspace| AgentPanel::is_hidden(&workspace, cx))
7351 .unwrap_or(true);
7352
7353 let should_notify = window_is_inactive || panel_is_hidden;
7354
7355 if !should_notify {
7356 return;
7357 }
7358
7359 // TODO: Change this once we have title summarization for external agents.
7360 let title = self.agent.name();
7361
7362 match settings.notify_when_agent_waiting {
7363 NotifyWhenAgentWaiting::PrimaryScreen => {
7364 if let Some(primary) = cx.primary_display() {
7365 self.pop_up(icon, caption.into(), title, window, primary, cx);
7366 }
7367 }
7368 NotifyWhenAgentWaiting::AllScreens => {
7369 let caption = caption.into();
7370 for screen in cx.displays() {
7371 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
7372 }
7373 }
7374 NotifyWhenAgentWaiting::Never => {
7375 // Don't show anything
7376 }
7377 }
7378 }
7379
7380 fn pop_up(
7381 &mut self,
7382 icon: IconName,
7383 caption: SharedString,
7384 title: SharedString,
7385 window: &mut Window,
7386 screen: Rc<dyn PlatformDisplay>,
7387 cx: &mut Context<Self>,
7388 ) {
7389 let options = AgentNotification::window_options(screen, cx);
7390
7391 let project_name = self.workspace.upgrade().and_then(|workspace| {
7392 workspace
7393 .read(cx)
7394 .project()
7395 .read(cx)
7396 .visible_worktrees(cx)
7397 .next()
7398 .map(|worktree| worktree.read(cx).root_name_str().to_string())
7399 });
7400
7401 if let Some(screen_window) = cx
7402 .open_window(options, |_window, cx| {
7403 cx.new(|_cx| {
7404 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
7405 })
7406 })
7407 .log_err()
7408 && let Some(pop_up) = screen_window.entity(cx).log_err()
7409 {
7410 self.notification_subscriptions
7411 .entry(screen_window)
7412 .or_insert_with(Vec::new)
7413 .push(cx.subscribe_in(&pop_up, window, {
7414 |this, _, event, window, cx| match event {
7415 AgentNotificationEvent::Accepted => {
7416 let handle = window.window_handle();
7417 cx.activate(true);
7418
7419 let workspace_handle = this.workspace.clone();
7420
7421 // If there are multiple Zed windows, activate the correct one.
7422 cx.defer(move |cx| {
7423 handle
7424 .update(cx, |_view, window, _cx| {
7425 window.activate_window();
7426
7427 if let Some(workspace) = workspace_handle.upgrade() {
7428 workspace.update(_cx, |workspace, cx| {
7429 workspace.focus_panel::<AgentPanel>(window, cx);
7430 });
7431 }
7432 })
7433 .log_err();
7434 });
7435
7436 this.dismiss_notifications(cx);
7437 }
7438 AgentNotificationEvent::Dismissed => {
7439 this.dismiss_notifications(cx);
7440 }
7441 }
7442 }));
7443
7444 self.notifications.push(screen_window);
7445
7446 // If the user manually refocuses the original window, dismiss the popup.
7447 self.notification_subscriptions
7448 .entry(screen_window)
7449 .or_insert_with(Vec::new)
7450 .push({
7451 let pop_up_weak = pop_up.downgrade();
7452
7453 cx.observe_window_activation(window, move |_, window, cx| {
7454 if window.is_window_active()
7455 && let Some(pop_up) = pop_up_weak.upgrade()
7456 {
7457 pop_up.update(cx, |_, cx| {
7458 cx.emit(AgentNotificationEvent::Dismissed);
7459 });
7460 }
7461 })
7462 });
7463 }
7464 }
7465
7466 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
7467 for window in self.notifications.drain(..) {
7468 window
7469 .update(cx, |_, window, _| {
7470 window.remove_window();
7471 })
7472 .ok();
7473
7474 self.notification_subscriptions.remove(&window);
7475 }
7476 }
7477
7478 fn render_generating(&self, confirmation: bool, cx: &App) -> impl IntoElement {
7479 let show_stats = AgentSettings::get_global(cx).show_turn_stats;
7480 let elapsed_label = show_stats
7481 .then(|| {
7482 self.turn_started_at.and_then(|started_at| {
7483 let elapsed = started_at.elapsed();
7484 (elapsed > STOPWATCH_THRESHOLD).then(|| duration_alt_display(elapsed))
7485 })
7486 })
7487 .flatten();
7488
7489 let is_waiting = confirmation
7490 || self
7491 .thread()
7492 .is_some_and(|thread| thread.read(cx).has_in_progress_tool_calls());
7493
7494 let turn_tokens_label = elapsed_label
7495 .is_some()
7496 .then(|| {
7497 self.turn_tokens
7498 .filter(|&tokens| tokens > TOKEN_THRESHOLD)
7499 .map(|tokens| crate::text_thread_editor::humanize_token_count(tokens))
7500 })
7501 .flatten();
7502
7503 let arrow_icon = if is_waiting {
7504 IconName::ArrowUp
7505 } else {
7506 IconName::ArrowDown
7507 };
7508
7509 h_flex()
7510 .id("generating-spinner")
7511 .py_2()
7512 .px(rems_from_px(22.))
7513 .gap_2()
7514 .map(|this| {
7515 if confirmation {
7516 this.child(
7517 h_flex()
7518 .w_2()
7519 .child(SpinnerLabel::sand().size(LabelSize::Small)),
7520 )
7521 .child(
7522 div().min_w(rems(8.)).child(
7523 LoadingLabel::new("Waiting Confirmation")
7524 .size(LabelSize::Small)
7525 .color(Color::Muted),
7526 ),
7527 )
7528 } else {
7529 this.child(SpinnerLabel::new().size(LabelSize::Small))
7530 }
7531 })
7532 .when_some(elapsed_label, |this, elapsed| {
7533 this.child(
7534 Label::new(elapsed)
7535 .size(LabelSize::Small)
7536 .color(Color::Muted),
7537 )
7538 })
7539 .when_some(turn_tokens_label, |this, tokens| {
7540 this.child(
7541 h_flex()
7542 .gap_0p5()
7543 .child(
7544 Icon::new(arrow_icon)
7545 .size(IconSize::XSmall)
7546 .color(Color::Muted),
7547 )
7548 .child(
7549 Label::new(format!("{} tokens", tokens))
7550 .size(LabelSize::Small)
7551 .color(Color::Muted),
7552 ),
7553 )
7554 })
7555 .into_any_element()
7556 }
7557
7558 fn render_thread_controls(
7559 &self,
7560 thread: &Entity<AcpThread>,
7561 cx: &Context<Self>,
7562 ) -> impl IntoElement {
7563 let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
7564 if is_generating {
7565 return self.render_generating(false, cx).into_any_element();
7566 }
7567
7568 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
7569 .shape(ui::IconButtonShape::Square)
7570 .icon_size(IconSize::Small)
7571 .icon_color(Color::Ignored)
7572 .tooltip(Tooltip::text("Open Thread as Markdown"))
7573 .on_click(cx.listener(move |this, _, window, cx| {
7574 if let Some(workspace) = this.workspace.upgrade() {
7575 this.open_thread_as_markdown(workspace, window, cx)
7576 .detach_and_log_err(cx);
7577 }
7578 }));
7579
7580 let scroll_to_recent_user_prompt =
7581 IconButton::new("scroll_to_recent_user_prompt", IconName::ForwardArrow)
7582 .shape(ui::IconButtonShape::Square)
7583 .icon_size(IconSize::Small)
7584 .icon_color(Color::Ignored)
7585 .tooltip(Tooltip::text("Scroll To Most Recent User Prompt"))
7586 .on_click(cx.listener(move |this, _, _, cx| {
7587 this.scroll_to_most_recent_user_prompt(cx);
7588 }));
7589
7590 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
7591 .shape(ui::IconButtonShape::Square)
7592 .icon_size(IconSize::Small)
7593 .icon_color(Color::Ignored)
7594 .tooltip(Tooltip::text("Scroll To Top"))
7595 .on_click(cx.listener(move |this, _, _, cx| {
7596 this.scroll_to_top(cx);
7597 }));
7598
7599 let show_stats = AgentSettings::get_global(cx).show_turn_stats;
7600 let last_turn_clock = show_stats
7601 .then(|| {
7602 self.last_turn_duration
7603 .filter(|&duration| duration > STOPWATCH_THRESHOLD)
7604 .map(|duration| {
7605 Label::new(duration_alt_display(duration))
7606 .size(LabelSize::Small)
7607 .color(Color::Muted)
7608 })
7609 })
7610 .flatten();
7611
7612 let last_turn_tokens = last_turn_clock
7613 .is_some()
7614 .then(|| {
7615 self.last_turn_tokens
7616 .filter(|&tokens| tokens > TOKEN_THRESHOLD)
7617 .map(|tokens| {
7618 Label::new(format!(
7619 "{} tokens",
7620 crate::text_thread_editor::humanize_token_count(tokens)
7621 ))
7622 .size(LabelSize::Small)
7623 .color(Color::Muted)
7624 })
7625 })
7626 .flatten();
7627
7628 let mut container = h_flex()
7629 .w_full()
7630 .py_2()
7631 .px_5()
7632 .gap_px()
7633 .opacity(0.6)
7634 .hover(|s| s.opacity(1.))
7635 .justify_end()
7636 .when(
7637 last_turn_tokens.is_some() || last_turn_clock.is_some(),
7638 |this| {
7639 this.child(
7640 h_flex()
7641 .gap_1()
7642 .px_1()
7643 .when_some(last_turn_tokens, |this, label| this.child(label))
7644 .when_some(last_turn_clock, |this, label| this.child(label)),
7645 )
7646 },
7647 );
7648
7649 if AgentSettings::get_global(cx).enable_feedback
7650 && self
7651 .thread()
7652 .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
7653 {
7654 let feedback = self.thread_feedback.feedback;
7655
7656 let tooltip_meta = || {
7657 SharedString::new(
7658 "Rating the thread sends all of your current conversation to the Zed team.",
7659 )
7660 };
7661
7662 container = container
7663 .child(
7664 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
7665 .shape(ui::IconButtonShape::Square)
7666 .icon_size(IconSize::Small)
7667 .icon_color(match feedback {
7668 Some(ThreadFeedback::Positive) => Color::Accent,
7669 _ => Color::Ignored,
7670 })
7671 .tooltip(move |window, cx| match feedback {
7672 Some(ThreadFeedback::Positive) => {
7673 Tooltip::text("Thanks for your feedback!")(window, cx)
7674 }
7675 _ => Tooltip::with_meta("Helpful Response", None, tooltip_meta(), cx),
7676 })
7677 .on_click(cx.listener(move |this, _, window, cx| {
7678 this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
7679 })),
7680 )
7681 .child(
7682 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
7683 .shape(ui::IconButtonShape::Square)
7684 .icon_size(IconSize::Small)
7685 .icon_color(match feedback {
7686 Some(ThreadFeedback::Negative) => Color::Accent,
7687 _ => Color::Ignored,
7688 })
7689 .tooltip(move |window, cx| match feedback {
7690 Some(ThreadFeedback::Negative) => {
7691 Tooltip::text(
7692 "We appreciate your feedback and will use it to improve in the future.",
7693 )(window, cx)
7694 }
7695 _ => {
7696 Tooltip::with_meta("Not Helpful Response", None, tooltip_meta(), cx)
7697 }
7698 })
7699 .on_click(cx.listener(move |this, _, window, cx| {
7700 this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
7701 })),
7702 );
7703 }
7704
7705 if cx.has_flag::<AgentSharingFeatureFlag>()
7706 && self.is_imported_thread(cx)
7707 && self
7708 .project
7709 .read(cx)
7710 .client()
7711 .status()
7712 .borrow()
7713 .is_connected()
7714 {
7715 let sync_button = IconButton::new("sync-thread", IconName::ArrowCircle)
7716 .shape(ui::IconButtonShape::Square)
7717 .icon_size(IconSize::Small)
7718 .icon_color(Color::Ignored)
7719 .tooltip(Tooltip::text("Sync with source thread"))
7720 .on_click(cx.listener(move |this, _, window, cx| {
7721 this.sync_thread(window, cx);
7722 }));
7723
7724 container = container.child(sync_button);
7725 }
7726
7727 if cx.has_flag::<AgentSharingFeatureFlag>() && !self.is_imported_thread(cx) {
7728 let share_button = IconButton::new("share-thread", IconName::ArrowUpRight)
7729 .shape(ui::IconButtonShape::Square)
7730 .icon_size(IconSize::Small)
7731 .icon_color(Color::Ignored)
7732 .tooltip(Tooltip::text("Share Thread"))
7733 .on_click(cx.listener(move |this, _, window, cx| {
7734 this.share_thread(window, cx);
7735 }));
7736
7737 container = container.child(share_button);
7738 }
7739
7740 container
7741 .child(open_as_markdown)
7742 .child(scroll_to_recent_user_prompt)
7743 .child(scroll_to_top)
7744 .into_any_element()
7745 }
7746
7747 fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
7748 h_flex()
7749 .key_context("AgentFeedbackMessageEditor")
7750 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
7751 this.thread_feedback.dismiss_comments();
7752 cx.notify();
7753 }))
7754 .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
7755 this.submit_feedback_message(cx);
7756 }))
7757 .p_2()
7758 .mb_2()
7759 .mx_5()
7760 .gap_1()
7761 .rounded_md()
7762 .border_1()
7763 .border_color(cx.theme().colors().border)
7764 .bg(cx.theme().colors().editor_background)
7765 .child(div().w_full().child(editor))
7766 .child(
7767 h_flex()
7768 .child(
7769 IconButton::new("dismiss-feedback-message", IconName::Close)
7770 .icon_color(Color::Error)
7771 .icon_size(IconSize::XSmall)
7772 .shape(ui::IconButtonShape::Square)
7773 .on_click(cx.listener(move |this, _, _window, cx| {
7774 this.thread_feedback.dismiss_comments();
7775 cx.notify();
7776 })),
7777 )
7778 .child(
7779 IconButton::new("submit-feedback-message", IconName::Return)
7780 .icon_size(IconSize::XSmall)
7781 .shape(ui::IconButtonShape::Square)
7782 .on_click(cx.listener(move |this, _, _window, cx| {
7783 this.submit_feedback_message(cx);
7784 })),
7785 ),
7786 )
7787 }
7788
7789 fn handle_feedback_click(
7790 &mut self,
7791 feedback: ThreadFeedback,
7792 window: &mut Window,
7793 cx: &mut Context<Self>,
7794 ) {
7795 let Some(thread) = self.thread().cloned() else {
7796 return;
7797 };
7798
7799 self.thread_feedback.submit(thread, feedback, window, cx);
7800 cx.notify();
7801 }
7802
7803 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
7804 let Some(thread) = self.thread().cloned() else {
7805 return;
7806 };
7807
7808 self.thread_feedback.submit_comments(thread, cx);
7809 cx.notify();
7810 }
7811
7812 fn render_token_limit_callout(&self, cx: &mut Context<Self>) -> Option<Callout> {
7813 if self.token_limit_callout_dismissed {
7814 return None;
7815 }
7816
7817 let token_usage = self.thread()?.read(cx).token_usage()?;
7818 let ratio = token_usage.ratio();
7819
7820 let (severity, icon, title) = match ratio {
7821 acp_thread::TokenUsageRatio::Normal => return None,
7822 acp_thread::TokenUsageRatio::Warning => (
7823 Severity::Warning,
7824 IconName::Warning,
7825 "Thread reaching the token limit soon",
7826 ),
7827 acp_thread::TokenUsageRatio::Exceeded => (
7828 Severity::Error,
7829 IconName::XCircle,
7830 "Thread reached the token limit",
7831 ),
7832 };
7833
7834 let description = "To continue, start a new thread from a summary.";
7835
7836 Some(
7837 Callout::new()
7838 .severity(severity)
7839 .icon(icon)
7840 .title(title)
7841 .description(description)
7842 .actions_slot(
7843 h_flex().gap_0p5().child(
7844 Button::new("start-new-thread", "Start New Thread")
7845 .label_size(LabelSize::Small)
7846 .on_click(cx.listener(|this, _, window, cx| {
7847 let Some(thread) = this.thread() else {
7848 return;
7849 };
7850 let session_id = thread.read(cx).session_id().clone();
7851 window.dispatch_action(
7852 crate::NewNativeAgentThreadFromSummary {
7853 from_session_id: session_id,
7854 }
7855 .boxed_clone(),
7856 cx,
7857 );
7858 })),
7859 ),
7860 )
7861 .dismiss_action(self.dismiss_error_button(cx)),
7862 )
7863 }
7864
7865 fn agent_ui_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
7866 self.entry_view_state.update(cx, |entry_view_state, cx| {
7867 entry_view_state.agent_ui_font_size_changed(cx);
7868 });
7869 }
7870
7871 pub(crate) fn insert_dragged_files(
7872 &self,
7873 paths: Vec<project::ProjectPath>,
7874 added_worktrees: Vec<Entity<project::Worktree>>,
7875 window: &mut Window,
7876 cx: &mut Context<Self>,
7877 ) {
7878 self.message_editor.update(cx, |message_editor, cx| {
7879 message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
7880 })
7881 }
7882
7883 /// Inserts the selected text into the message editor or the message being
7884 /// edited, if any.
7885 pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
7886 self.active_editor(cx).update(cx, |editor, cx| {
7887 editor.insert_selections(window, cx);
7888 });
7889 }
7890
7891 /// Inserts code snippets as creases into the message editor.
7892 pub(crate) fn insert_code_crease(
7893 &self,
7894 creases: Vec<(String, String)>,
7895 window: &mut Window,
7896 cx: &mut Context<Self>,
7897 ) {
7898 self.message_editor.update(cx, |message_editor, cx| {
7899 message_editor.insert_code_creases(creases, window, cx);
7900 });
7901 }
7902
7903 fn render_thread_retry_status_callout(
7904 &self,
7905 _window: &mut Window,
7906 _cx: &mut Context<Self>,
7907 ) -> Option<Callout> {
7908 let state = self.thread_retry_status.as_ref()?;
7909
7910 let next_attempt_in = state
7911 .duration
7912 .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
7913 if next_attempt_in.is_zero() {
7914 return None;
7915 }
7916
7917 let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
7918
7919 let retry_message = if state.max_attempts == 1 {
7920 if next_attempt_in_secs == 1 {
7921 "Retrying. Next attempt in 1 second.".to_string()
7922 } else {
7923 format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
7924 }
7925 } else if next_attempt_in_secs == 1 {
7926 format!(
7927 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
7928 state.attempt, state.max_attempts,
7929 )
7930 } else {
7931 format!(
7932 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
7933 state.attempt, state.max_attempts,
7934 )
7935 };
7936
7937 Some(
7938 Callout::new()
7939 .severity(Severity::Warning)
7940 .title(state.last_error.clone())
7941 .description(retry_message),
7942 )
7943 }
7944
7945 fn render_codex_windows_warning(&self, cx: &mut Context<Self>) -> Callout {
7946 Callout::new()
7947 .icon(IconName::Warning)
7948 .severity(Severity::Warning)
7949 .title("Codex on Windows")
7950 .description("For best performance, run Codex in Windows Subsystem for Linux (WSL2)")
7951 .actions_slot(
7952 Button::new("open-wsl-modal", "Open in WSL")
7953 .icon_size(IconSize::Small)
7954 .icon_color(Color::Muted)
7955 .on_click(cx.listener({
7956 move |_, _, _window, cx| {
7957 #[cfg(windows)]
7958 _window.dispatch_action(
7959 zed_actions::wsl_actions::OpenWsl::default().boxed_clone(),
7960 cx,
7961 );
7962 cx.notify();
7963 }
7964 })),
7965 )
7966 .dismiss_action(
7967 IconButton::new("dismiss", IconName::Close)
7968 .icon_size(IconSize::Small)
7969 .icon_color(Color::Muted)
7970 .tooltip(Tooltip::text("Dismiss Warning"))
7971 .on_click(cx.listener({
7972 move |this, _, _, cx| {
7973 this.show_codex_windows_warning = false;
7974 cx.notify();
7975 }
7976 })),
7977 )
7978 }
7979
7980 fn render_command_load_errors(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
7981 if self.command_load_errors_dismissed || self.command_load_errors.is_empty() {
7982 return None;
7983 }
7984
7985 let error_count = self.command_load_errors.len();
7986 let title = if error_count == 1 {
7987 "Failed to load slash command"
7988 } else {
7989 "Failed to load slash commands"
7990 };
7991
7992 let workspace = self.workspace.clone();
7993
7994 Some(
7995 v_flex()
7996 .w_full()
7997 .p_2()
7998 .gap_1()
7999 .border_t_1()
8000 .border_color(cx.theme().colors().border)
8001 .bg(cx.theme().colors().surface_background)
8002 .child(
8003 h_flex()
8004 .justify_between()
8005 .child(
8006 h_flex()
8007 .gap_1()
8008 .child(
8009 Icon::new(IconName::Warning)
8010 .size(IconSize::Small)
8011 .color(Color::Warning),
8012 )
8013 .child(
8014 Label::new(title)
8015 .size(LabelSize::Small)
8016 .color(Color::Warning),
8017 ),
8018 )
8019 .child(
8020 IconButton::new("dismiss-command-errors", IconName::Close)
8021 .icon_size(IconSize::Small)
8022 .icon_color(Color::Muted)
8023 .tooltip(Tooltip::text("Dismiss"))
8024 .on_click(cx.listener(|this, _, _, cx| {
8025 this.clear_command_load_errors(cx);
8026 })),
8027 ),
8028 )
8029 .children(self.command_load_errors.iter().enumerate().map({
8030 move |(i, error)| {
8031 let path = error.path.clone();
8032 let workspace = workspace.clone();
8033 let file_name = error
8034 .path
8035 .file_name()
8036 .map(|n| n.to_string_lossy().to_string())
8037 .unwrap_or_else(|| error.path.display().to_string());
8038
8039 h_flex()
8040 .id(ElementId::Name(format!("command-error-{i}").into()))
8041 .gap_1()
8042 .px_1()
8043 .py_0p5()
8044 .rounded_sm()
8045 .cursor_pointer()
8046 .hover(|style| style.bg(cx.theme().colors().element_hover))
8047 .tooltip(Tooltip::text(format!(
8048 "Click to open {}\n\n{}",
8049 error.path.display(),
8050 error.message
8051 )))
8052 .on_click({
8053 move |_, window, cx| {
8054 if let Some(workspace) = workspace.upgrade() {
8055 workspace.update(cx, |workspace, cx| {
8056 workspace
8057 .open_abs_path(
8058 path.clone(),
8059 OpenOptions::default(),
8060 window,
8061 cx,
8062 )
8063 .detach_and_log_err(cx);
8064 });
8065 }
8066 }
8067 })
8068 .child(
8069 Label::new(format!("• {}: {}", file_name, error.message))
8070 .size(LabelSize::Small)
8071 .color(Color::Muted),
8072 )
8073 }
8074 })),
8075 )
8076 }
8077
8078 fn clear_command_load_errors(&mut self, cx: &mut Context<Self>) {
8079 self.command_load_errors_dismissed = true;
8080 cx.notify();
8081 }
8082
8083 fn refresh_cached_user_commands(&mut self, cx: &mut Context<Self>) {
8084 let Some(registry) = self.slash_command_registry.clone() else {
8085 return;
8086 };
8087 self.refresh_cached_user_commands_from_registry(®istry, cx);
8088 }
8089
8090 fn refresh_cached_user_commands_from_registry(
8091 &mut self,
8092 registry: &Entity<SlashCommandRegistry>,
8093 cx: &mut Context<Self>,
8094 ) {
8095 let (mut commands, mut errors) = registry.read_with(cx, |registry, _| {
8096 (registry.commands().clone(), registry.errors().to_vec())
8097 });
8098 let server_command_names = self
8099 .available_commands
8100 .borrow()
8101 .iter()
8102 .map(|command| command.name.clone())
8103 .collect::<HashSet<_>>();
8104 user_slash_command::apply_server_command_conflicts_to_map(
8105 &mut commands,
8106 &mut errors,
8107 &server_command_names,
8108 );
8109
8110 self.command_load_errors = errors.clone();
8111 self.command_load_errors_dismissed = false;
8112 *self.cached_user_commands.borrow_mut() = commands;
8113 *self.cached_user_command_errors.borrow_mut() = errors;
8114 cx.notify();
8115 }
8116
8117 /// Returns the cached slash commands, if available.
8118 pub fn cached_slash_commands(
8119 &self,
8120 _cx: &App,
8121 ) -> collections::HashMap<String, UserSlashCommand> {
8122 self.cached_user_commands.borrow().clone()
8123 }
8124
8125 /// Returns the cached slash command errors, if available.
8126 pub fn cached_slash_command_errors(&self, _cx: &App) -> Vec<CommandLoadError> {
8127 self.cached_user_command_errors.borrow().clone()
8128 }
8129
8130 fn render_thread_error(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
8131 let content = match self.thread_error.as_ref()? {
8132 ThreadError::Other { message, .. } => {
8133 self.render_any_thread_error(message.clone(), window, cx)
8134 }
8135 ThreadError::Refusal => self.render_refusal_error(cx),
8136 ThreadError::AuthenticationRequired(error) => {
8137 self.render_authentication_required_error(error.clone(), cx)
8138 }
8139 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
8140 };
8141
8142 Some(div().child(content))
8143 }
8144
8145 fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
8146 v_flex().w_full().justify_end().child(
8147 h_flex()
8148 .p_2()
8149 .pr_3()
8150 .w_full()
8151 .gap_1p5()
8152 .border_t_1()
8153 .border_color(cx.theme().colors().border)
8154 .bg(cx.theme().colors().element_background)
8155 .child(
8156 h_flex()
8157 .flex_1()
8158 .gap_1p5()
8159 .child(
8160 Icon::new(IconName::Download)
8161 .color(Color::Accent)
8162 .size(IconSize::Small),
8163 )
8164 .child(Label::new("New version available").size(LabelSize::Small)),
8165 )
8166 .child(
8167 Button::new("update-button", format!("Update to v{}", version))
8168 .label_size(LabelSize::Small)
8169 .style(ButtonStyle::Tinted(TintColor::Accent))
8170 .on_click(cx.listener(|this, _, window, cx| {
8171 this.reset(window, cx);
8172 })),
8173 ),
8174 )
8175 }
8176
8177 fn current_mode_id(&self, cx: &App) -> Option<Arc<str>> {
8178 if let Some(thread) = self.as_native_thread(cx) {
8179 Some(thread.read(cx).profile().0.clone())
8180 } else if let Some(mode_selector) = self.mode_selector() {
8181 Some(mode_selector.read(cx).mode().0)
8182 } else {
8183 None
8184 }
8185 }
8186
8187 fn current_model_id(&self, cx: &App) -> Option<String> {
8188 self.model_selector
8189 .as_ref()
8190 .and_then(|selector| selector.read(cx).active_model(cx).map(|m| m.id.to_string()))
8191 }
8192
8193 fn current_model_name(&self, cx: &App) -> SharedString {
8194 // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
8195 // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
8196 // This provides better clarity about what refused the request
8197 if self.as_native_connection(cx).is_some() {
8198 self.model_selector
8199 .as_ref()
8200 .and_then(|selector| selector.read(cx).active_model(cx))
8201 .map(|model| model.name.clone())
8202 .unwrap_or_else(|| SharedString::from("The model"))
8203 } else {
8204 // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
8205 self.agent.name()
8206 }
8207 }
8208
8209 fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
8210 let model_or_agent_name = self.current_model_name(cx);
8211 let refusal_message = format!(
8212 "{} refused to respond to this prompt. This can happen when a model believes the prompt violates its content policy or safety guidelines, so rephrasing it can sometimes address the issue.",
8213 model_or_agent_name
8214 );
8215
8216 Callout::new()
8217 .severity(Severity::Error)
8218 .title("Request Refused")
8219 .icon(IconName::XCircle)
8220 .description(refusal_message.clone())
8221 .actions_slot(self.create_copy_button(&refusal_message))
8222 .dismiss_action(self.dismiss_error_button(cx))
8223 }
8224
8225 fn render_any_thread_error(
8226 &mut self,
8227 error: SharedString,
8228 window: &mut Window,
8229 cx: &mut Context<'_, Self>,
8230 ) -> Callout {
8231 let can_resume = self
8232 .thread()
8233 .map_or(false, |thread| thread.read(cx).can_retry(cx));
8234
8235 let markdown = if let Some(markdown) = &self.thread_error_markdown {
8236 markdown.clone()
8237 } else {
8238 let markdown = cx.new(|cx| Markdown::new(error.clone(), None, None, cx));
8239 self.thread_error_markdown = Some(markdown.clone());
8240 markdown
8241 };
8242
8243 let markdown_style = default_markdown_style(false, true, window, cx);
8244 let description = self
8245 .render_markdown(markdown, markdown_style)
8246 .into_any_element();
8247
8248 Callout::new()
8249 .severity(Severity::Error)
8250 .icon(IconName::XCircle)
8251 .title("An Error Happened")
8252 .description_slot(description)
8253 .actions_slot(
8254 h_flex()
8255 .gap_0p5()
8256 .when(can_resume, |this| {
8257 this.child(
8258 IconButton::new("retry", IconName::RotateCw)
8259 .icon_size(IconSize::Small)
8260 .tooltip(Tooltip::text("Retry Generation"))
8261 .on_click(cx.listener(|this, _, _window, cx| {
8262 this.retry_generation(cx);
8263 })),
8264 )
8265 })
8266 .child(self.create_copy_button(error.to_string())),
8267 )
8268 .dismiss_action(self.dismiss_error_button(cx))
8269 }
8270
8271 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
8272 const ERROR_MESSAGE: &str =
8273 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
8274
8275 Callout::new()
8276 .severity(Severity::Error)
8277 .icon(IconName::XCircle)
8278 .title("Free Usage Exceeded")
8279 .description(ERROR_MESSAGE)
8280 .actions_slot(
8281 h_flex()
8282 .gap_0p5()
8283 .child(self.upgrade_button(cx))
8284 .child(self.create_copy_button(ERROR_MESSAGE)),
8285 )
8286 .dismiss_action(self.dismiss_error_button(cx))
8287 }
8288
8289 fn render_authentication_required_error(
8290 &self,
8291 error: SharedString,
8292 cx: &mut Context<Self>,
8293 ) -> Callout {
8294 Callout::new()
8295 .severity(Severity::Error)
8296 .title("Authentication Required")
8297 .icon(IconName::XCircle)
8298 .description(error.clone())
8299 .actions_slot(
8300 h_flex()
8301 .gap_0p5()
8302 .child(self.authenticate_button(cx))
8303 .child(self.create_copy_button(error)),
8304 )
8305 .dismiss_action(self.dismiss_error_button(cx))
8306 }
8307
8308 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
8309 let message = message.into();
8310
8311 CopyButton::new("copy-error-message", message).tooltip_label("Copy Error Message")
8312 }
8313
8314 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
8315 IconButton::new("dismiss", IconName::Close)
8316 .icon_size(IconSize::Small)
8317 .tooltip(Tooltip::text("Dismiss"))
8318 .on_click(cx.listener({
8319 move |this, _, _, cx| {
8320 this.clear_thread_error(cx);
8321 cx.notify();
8322 }
8323 }))
8324 }
8325
8326 fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
8327 Button::new("authenticate", "Authenticate")
8328 .label_size(LabelSize::Small)
8329 .style(ButtonStyle::Filled)
8330 .on_click(cx.listener({
8331 move |this, _, window, cx| {
8332 let agent = this.agent.clone();
8333 let ThreadState::Ready { thread, .. } = &this.thread_state else {
8334 return;
8335 };
8336
8337 let connection = thread.read(cx).connection().clone();
8338 this.clear_thread_error(cx);
8339 if let Some(message) = this.in_flight_prompt.take() {
8340 this.message_editor.update(cx, |editor, cx| {
8341 editor.set_message(message, window, cx);
8342 });
8343 }
8344 let this = cx.weak_entity();
8345 window.defer(cx, |window, cx| {
8346 Self::handle_auth_required(
8347 this,
8348 AuthRequired::new(),
8349 agent,
8350 connection,
8351 window,
8352 cx,
8353 );
8354 })
8355 }
8356 }))
8357 }
8358
8359 pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8360 let agent = self.agent.clone();
8361 let ThreadState::Ready { thread, .. } = &self.thread_state else {
8362 return;
8363 };
8364
8365 let connection = thread.read(cx).connection().clone();
8366 self.clear_thread_error(cx);
8367 let this = cx.weak_entity();
8368 window.defer(cx, |window, cx| {
8369 Self::handle_auth_required(this, AuthRequired::new(), agent, connection, window, cx);
8370 })
8371 }
8372
8373 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
8374 Button::new("upgrade", "Upgrade")
8375 .label_size(LabelSize::Small)
8376 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
8377 .on_click(cx.listener({
8378 move |this, _, _, cx| {
8379 this.clear_thread_error(cx);
8380 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
8381 }
8382 }))
8383 }
8384
8385 pub fn delete_history_entry(&mut self, entry: AgentSessionInfo, cx: &mut Context<Self>) {
8386 let task = self.history.update(cx, |history, cx| {
8387 history.delete_session(&entry.session_id, cx)
8388 });
8389 task.detach_and_log_err(cx);
8390 }
8391
8392 /// Returns the currently active editor, either for a message that is being
8393 /// edited or the editor for a new message.
8394 fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
8395 if let Some(index) = self.editing_message
8396 && let Some(editor) = self
8397 .entry_view_state
8398 .read(cx)
8399 .entry(index)
8400 .and_then(|e| e.message_editor())
8401 .cloned()
8402 {
8403 editor
8404 } else {
8405 self.message_editor.clone()
8406 }
8407 }
8408
8409 fn get_agent_message_content(
8410 entries: &[AgentThreadEntry],
8411 entry_index: usize,
8412 cx: &App,
8413 ) -> Option<String> {
8414 let entry = entries.get(entry_index)?;
8415 if matches!(entry, AgentThreadEntry::UserMessage(_)) {
8416 return None;
8417 }
8418
8419 let start_index = (0..entry_index)
8420 .rev()
8421 .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
8422 .map(|i| i + 1)
8423 .unwrap_or(0);
8424
8425 let end_index = (entry_index + 1..entries.len())
8426 .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
8427 .map(|i| i - 1)
8428 .unwrap_or(entries.len() - 1);
8429
8430 let parts: Vec<String> = (start_index..=end_index)
8431 .filter_map(|i| entries.get(i))
8432 .filter_map(|entry| {
8433 if let AgentThreadEntry::AssistantMessage(message) = entry {
8434 let text: String = message
8435 .chunks
8436 .iter()
8437 .filter_map(|chunk| match chunk {
8438 AssistantMessageChunk::Message { block } => {
8439 let markdown = block.to_markdown(cx);
8440 if markdown.trim().is_empty() {
8441 None
8442 } else {
8443 Some(markdown.to_string())
8444 }
8445 }
8446 AssistantMessageChunk::Thought { .. } => None,
8447 })
8448 .collect::<Vec<_>>()
8449 .join("\n\n");
8450
8451 if text.is_empty() { None } else { Some(text) }
8452 } else {
8453 None
8454 }
8455 })
8456 .collect();
8457
8458 let text = parts.join("\n\n");
8459 if text.is_empty() { None } else { Some(text) }
8460 }
8461}
8462
8463fn loading_contents_spinner(size: IconSize) -> AnyElement {
8464 Icon::new(IconName::LoadCircle)
8465 .size(size)
8466 .color(Color::Accent)
8467 .with_rotate_animation(3)
8468 .into_any_element()
8469}
8470
8471fn placeholder_text(agent_name: &str, has_commands: bool) -> String {
8472 if agent_name == "Zed Agent" {
8473 format!("Message the {} — @ to include context", agent_name)
8474 } else if has_commands {
8475 format!(
8476 "Message {} — @ to include context, / for commands",
8477 agent_name
8478 )
8479 } else {
8480 format!("Message {} — @ to include context", agent_name)
8481 }
8482}
8483
8484impl Focusable for AcpThreadView {
8485 fn focus_handle(&self, cx: &App) -> FocusHandle {
8486 match self.thread_state {
8487 ThreadState::Ready { .. } => self.active_editor(cx).focus_handle(cx),
8488 ThreadState::Loading { .. }
8489 | ThreadState::LoadError(_)
8490 | ThreadState::Unauthenticated { .. } => self.focus_handle.clone(),
8491 }
8492 }
8493}
8494
8495#[cfg(any(test, feature = "test-support"))]
8496impl AcpThreadView {
8497 /// Expands a tool call so its content is visible.
8498 /// This is primarily useful for visual testing.
8499 pub fn expand_tool_call(&mut self, tool_call_id: acp::ToolCallId, cx: &mut Context<Self>) {
8500 self.expanded_tool_calls.insert(tool_call_id);
8501 cx.notify();
8502 }
8503
8504 /// Expands a subagent card so its content is visible.
8505 /// This is primarily useful for visual testing.
8506 pub fn expand_subagent(&mut self, session_id: acp::SessionId, cx: &mut Context<Self>) {
8507 self.expanded_subagents.insert(session_id);
8508 cx.notify();
8509 }
8510}
8511
8512impl Render for AcpThreadView {
8513 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8514 self.sync_queued_message_editors(window, cx);
8515
8516 let has_messages = self.list_state.item_count() > 0;
8517
8518 v_flex()
8519 .size_full()
8520 .key_context("AcpThread")
8521 .on_action(cx.listener(|this, _: &menu::Cancel, _, cx| {
8522 this.cancel_generation(cx);
8523 }))
8524 .on_action(cx.listener(Self::keep_all))
8525 .on_action(cx.listener(Self::reject_all))
8526 .on_action(cx.listener(Self::allow_always))
8527 .on_action(cx.listener(Self::allow_once))
8528 .on_action(cx.listener(Self::reject_once))
8529 .on_action(cx.listener(Self::handle_authorize_tool_call))
8530 .on_action(cx.listener(Self::handle_select_permission_granularity))
8531 .on_action(cx.listener(Self::open_permission_dropdown))
8532 .on_action(cx.listener(Self::open_add_context_menu))
8533 .on_action(cx.listener(|this, _: &SendNextQueuedMessage, window, cx| {
8534 this.send_queued_message_at_index(0, true, window, cx);
8535 }))
8536 .on_action(cx.listener(|this, _: &RemoveFirstQueuedMessage, _, cx| {
8537 this.remove_from_queue(0, cx);
8538 cx.notify();
8539 }))
8540 .on_action(cx.listener(|this, _: &EditFirstQueuedMessage, window, cx| {
8541 if let Some(editor) = this.queued_message_editors.first() {
8542 window.focus(&editor.focus_handle(cx), cx);
8543 }
8544 }))
8545 .on_action(cx.listener(|this, _: &ClearMessageQueue, _, cx| {
8546 this.clear_queue(cx);
8547 this.can_fast_track_queue = false;
8548 cx.notify();
8549 }))
8550 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
8551 if let Some(config_options_view) = this.config_options_view.as_ref() {
8552 let handled = config_options_view.update(cx, |view, cx| {
8553 view.toggle_category_picker(
8554 acp::SessionConfigOptionCategory::Mode,
8555 window,
8556 cx,
8557 )
8558 });
8559 if handled {
8560 return;
8561 }
8562 }
8563
8564 if let Some(profile_selector) = this.profile_selector.as_ref() {
8565 profile_selector.read(cx).menu_handle().toggle(window, cx);
8566 } else if let Some(mode_selector) = this.mode_selector() {
8567 mode_selector.read(cx).menu_handle().toggle(window, cx);
8568 }
8569 }))
8570 .on_action(cx.listener(|this, _: &CycleModeSelector, window, cx| {
8571 if let Some(config_options_view) = this.config_options_view.as_ref() {
8572 let handled = config_options_view.update(cx, |view, cx| {
8573 view.cycle_category_option(
8574 acp::SessionConfigOptionCategory::Mode,
8575 false,
8576 cx,
8577 )
8578 });
8579 if handled {
8580 return;
8581 }
8582 }
8583
8584 if let Some(profile_selector) = this.profile_selector.as_ref() {
8585 profile_selector.update(cx, |profile_selector, cx| {
8586 profile_selector.cycle_profile(cx);
8587 });
8588 } else if let Some(mode_selector) = this.mode_selector() {
8589 mode_selector.update(cx, |mode_selector, cx| {
8590 mode_selector.cycle_mode(window, cx);
8591 });
8592 }
8593 }))
8594 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
8595 if let Some(config_options_view) = this.config_options_view.as_ref() {
8596 let handled = config_options_view.update(cx, |view, cx| {
8597 view.toggle_category_picker(
8598 acp::SessionConfigOptionCategory::Model,
8599 window,
8600 cx,
8601 )
8602 });
8603 if handled {
8604 return;
8605 }
8606 }
8607
8608 if let Some(model_selector) = this.model_selector.as_ref() {
8609 model_selector
8610 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
8611 }
8612 }))
8613 .on_action(cx.listener(|this, _: &CycleFavoriteModels, window, cx| {
8614 if let Some(config_options_view) = this.config_options_view.as_ref() {
8615 let handled = config_options_view.update(cx, |view, cx| {
8616 view.cycle_category_option(
8617 acp::SessionConfigOptionCategory::Model,
8618 true,
8619 cx,
8620 )
8621 });
8622 if handled {
8623 return;
8624 }
8625 }
8626
8627 if let Some(model_selector) = this.model_selector.as_ref() {
8628 model_selector.update(cx, |model_selector, cx| {
8629 model_selector.cycle_favorite_models(window, cx);
8630 });
8631 }
8632 }))
8633 .track_focus(&self.focus_handle)
8634 .bg(cx.theme().colors().panel_background)
8635 .child(match &self.thread_state {
8636 ThreadState::Unauthenticated {
8637 connection,
8638 description,
8639 configuration_view,
8640 pending_auth_method,
8641 ..
8642 } => v_flex()
8643 .flex_1()
8644 .size_full()
8645 .justify_end()
8646 .child(self.render_auth_required_state(
8647 connection,
8648 description.as_ref(),
8649 configuration_view.as_ref(),
8650 pending_auth_method.as_ref(),
8651 window,
8652 cx,
8653 ))
8654 .into_any_element(),
8655 ThreadState::Loading { .. } => v_flex()
8656 .flex_1()
8657 .child(self.render_recent_history(cx))
8658 .into_any(),
8659 ThreadState::LoadError(e) => v_flex()
8660 .flex_1()
8661 .size_full()
8662 .items_center()
8663 .justify_end()
8664 .child(self.render_load_error(e, window, cx))
8665 .into_any(),
8666 ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
8667 let this = this.when(self.resumed_without_history, |this| {
8668 this.child(self.render_resume_notice(cx))
8669 });
8670 if has_messages {
8671 this.child(
8672 list(
8673 self.list_state.clone(),
8674 cx.processor(|this, index: usize, window, cx| {
8675 let Some((entry, len)) = this.thread().and_then(|thread| {
8676 let entries = &thread.read(cx).entries();
8677 Some((entries.get(index)?, entries.len()))
8678 }) else {
8679 return Empty.into_any();
8680 };
8681 this.render_entry(index, len, entry, window, cx)
8682 }),
8683 )
8684 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
8685 .flex_grow()
8686 .into_any(),
8687 )
8688 .vertical_scrollbar_for(&self.list_state, window, cx)
8689 .into_any()
8690 } else {
8691 this.child(self.render_recent_history(cx)).into_any()
8692 }
8693 }),
8694 })
8695 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
8696 // above so that the scrollbar doesn't render behind it. The current setup allows
8697 // the scrollbar to stop exactly at the activity bar start.
8698 .when(has_messages, |this| match &self.thread_state {
8699 ThreadState::Ready { thread, .. } => {
8700 this.children(self.render_activity_bar(thread, window, cx))
8701 }
8702 _ => this,
8703 })
8704 .children(self.render_thread_retry_status_callout(window, cx))
8705 .when(self.show_codex_windows_warning, |this| {
8706 this.child(self.render_codex_windows_warning(cx))
8707 })
8708 .children(self.render_command_load_errors(cx))
8709 .children(self.render_thread_error(window, cx))
8710 .when_some(
8711 self.new_server_version_available.as_ref().filter(|_| {
8712 !has_messages || !matches!(self.thread_state, ThreadState::Ready { .. })
8713 }),
8714 |this, version| this.child(self.render_new_version_callout(&version, cx)),
8715 )
8716 .children(
8717 self.render_token_limit_callout(cx)
8718 .map(|token_limit_callout| token_limit_callout.into_any_element()),
8719 )
8720 .child(self.render_message_editor(window, cx))
8721 }
8722}
8723
8724fn default_markdown_style(
8725 buffer_font: bool,
8726 muted_text: bool,
8727 window: &Window,
8728 cx: &App,
8729) -> MarkdownStyle {
8730 let theme_settings = ThemeSettings::get_global(cx);
8731 let colors = cx.theme().colors();
8732
8733 let buffer_font_size = theme_settings.agent_buffer_font_size(cx);
8734
8735 let mut text_style = window.text_style();
8736 let line_height = buffer_font_size * 1.75;
8737
8738 let font_family = if buffer_font {
8739 theme_settings.buffer_font.family.clone()
8740 } else {
8741 theme_settings.ui_font.family.clone()
8742 };
8743
8744 let font_size = if buffer_font {
8745 theme_settings.agent_buffer_font_size(cx)
8746 } else {
8747 theme_settings.agent_ui_font_size(cx)
8748 };
8749
8750 let text_color = if muted_text {
8751 colors.text_muted
8752 } else {
8753 colors.text
8754 };
8755
8756 text_style.refine(&TextStyleRefinement {
8757 font_family: Some(font_family),
8758 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
8759 font_features: Some(theme_settings.ui_font.features.clone()),
8760 font_size: Some(font_size.into()),
8761 line_height: Some(line_height.into()),
8762 color: Some(text_color),
8763 ..Default::default()
8764 });
8765
8766 MarkdownStyle {
8767 base_text_style: text_style.clone(),
8768 syntax: cx.theme().syntax().clone(),
8769 selection_background_color: colors.element_selection_background,
8770 code_block_overflow_x_scroll: true,
8771 heading_level_styles: Some(HeadingLevelStyles {
8772 h1: Some(TextStyleRefinement {
8773 font_size: Some(rems(1.15).into()),
8774 ..Default::default()
8775 }),
8776 h2: Some(TextStyleRefinement {
8777 font_size: Some(rems(1.1).into()),
8778 ..Default::default()
8779 }),
8780 h3: Some(TextStyleRefinement {
8781 font_size: Some(rems(1.05).into()),
8782 ..Default::default()
8783 }),
8784 h4: Some(TextStyleRefinement {
8785 font_size: Some(rems(1.).into()),
8786 ..Default::default()
8787 }),
8788 h5: Some(TextStyleRefinement {
8789 font_size: Some(rems(0.95).into()),
8790 ..Default::default()
8791 }),
8792 h6: Some(TextStyleRefinement {
8793 font_size: Some(rems(0.875).into()),
8794 ..Default::default()
8795 }),
8796 }),
8797 code_block: StyleRefinement {
8798 padding: EdgesRefinement {
8799 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
8800 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
8801 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
8802 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
8803 },
8804 margin: EdgesRefinement {
8805 top: Some(Length::Definite(px(8.).into())),
8806 left: Some(Length::Definite(px(0.).into())),
8807 right: Some(Length::Definite(px(0.).into())),
8808 bottom: Some(Length::Definite(px(12.).into())),
8809 },
8810 border_style: Some(BorderStyle::Solid),
8811 border_widths: EdgesRefinement {
8812 top: Some(AbsoluteLength::Pixels(px(1.))),
8813 left: Some(AbsoluteLength::Pixels(px(1.))),
8814 right: Some(AbsoluteLength::Pixels(px(1.))),
8815 bottom: Some(AbsoluteLength::Pixels(px(1.))),
8816 },
8817 border_color: Some(colors.border_variant),
8818 background: Some(colors.editor_background.into()),
8819 text: TextStyleRefinement {
8820 font_family: Some(theme_settings.buffer_font.family.clone()),
8821 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
8822 font_features: Some(theme_settings.buffer_font.features.clone()),
8823 font_size: Some(buffer_font_size.into()),
8824 ..Default::default()
8825 },
8826 ..Default::default()
8827 },
8828 inline_code: TextStyleRefinement {
8829 font_family: Some(theme_settings.buffer_font.family.clone()),
8830 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
8831 font_features: Some(theme_settings.buffer_font.features.clone()),
8832 font_size: Some(buffer_font_size.into()),
8833 background_color: Some(colors.editor_foreground.opacity(0.08)),
8834 ..Default::default()
8835 },
8836 link: TextStyleRefinement {
8837 background_color: Some(colors.editor_foreground.opacity(0.025)),
8838 color: Some(colors.text_accent),
8839 underline: Some(UnderlineStyle {
8840 color: Some(colors.text_accent.opacity(0.5)),
8841 thickness: px(1.),
8842 ..Default::default()
8843 }),
8844 ..Default::default()
8845 },
8846 ..Default::default()
8847 }
8848}
8849
8850fn plan_label_markdown_style(
8851 status: &acp::PlanEntryStatus,
8852 window: &Window,
8853 cx: &App,
8854) -> MarkdownStyle {
8855 let default_md_style = default_markdown_style(false, false, window, cx);
8856
8857 MarkdownStyle {
8858 base_text_style: TextStyle {
8859 color: cx.theme().colors().text_muted,
8860 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
8861 Some(gpui::StrikethroughStyle {
8862 thickness: px(1.),
8863 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
8864 })
8865 } else {
8866 None
8867 },
8868 ..default_md_style.base_text_style
8869 },
8870 ..default_md_style
8871 }
8872}
8873
8874#[cfg(test)]
8875pub(crate) mod tests {
8876 use acp_thread::{
8877 AgentSessionList, AgentSessionListRequest, AgentSessionListResponse, StubAgentConnection,
8878 };
8879 use action_log::ActionLog;
8880 use agent::ToolPermissionContext;
8881 use agent_client_protocol::SessionId;
8882 use editor::MultiBufferOffset;
8883 use fs::FakeFs;
8884 use gpui::{EventEmitter, TestAppContext, VisualTestContext};
8885 use project::Project;
8886 use serde_json::json;
8887 use settings::SettingsStore;
8888 use std::any::Any;
8889 use std::path::Path;
8890 use std::rc::Rc;
8891 use workspace::Item;
8892
8893 use super::*;
8894
8895 #[gpui::test]
8896 async fn test_drop(cx: &mut TestAppContext) {
8897 init_test(cx);
8898
8899 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
8900 let weak_view = thread_view.downgrade();
8901 drop(thread_view);
8902 assert!(!weak_view.is_upgradable());
8903 }
8904
8905 #[gpui::test]
8906 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
8907 init_test(cx);
8908
8909 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
8910
8911 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8912 message_editor.update_in(cx, |editor, window, cx| {
8913 editor.set_text("Hello", window, cx);
8914 });
8915
8916 cx.deactivate_window();
8917
8918 thread_view.update_in(cx, |thread_view, window, cx| {
8919 thread_view.send(window, cx);
8920 });
8921
8922 cx.run_until_parked();
8923
8924 assert!(
8925 cx.windows()
8926 .iter()
8927 .any(|window| window.downcast::<AgentNotification>().is_some())
8928 );
8929 }
8930
8931 #[gpui::test]
8932 async fn test_notification_for_error(cx: &mut TestAppContext) {
8933 init_test(cx);
8934
8935 let (thread_view, cx) =
8936 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
8937
8938 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8939 message_editor.update_in(cx, |editor, window, cx| {
8940 editor.set_text("Hello", window, cx);
8941 });
8942
8943 cx.deactivate_window();
8944
8945 thread_view.update_in(cx, |thread_view, window, cx| {
8946 thread_view.send(window, cx);
8947 });
8948
8949 cx.run_until_parked();
8950
8951 assert!(
8952 cx.windows()
8953 .iter()
8954 .any(|window| window.downcast::<AgentNotification>().is_some())
8955 );
8956 }
8957
8958 #[gpui::test]
8959 async fn test_recent_history_refreshes_when_history_cache_updated(cx: &mut TestAppContext) {
8960 init_test(cx);
8961
8962 let session_a = AgentSessionInfo::new(SessionId::new("session-a"));
8963 let session_b = AgentSessionInfo::new(SessionId::new("session-b"));
8964
8965 let fs = FakeFs::new(cx.executor());
8966 let project = Project::test(fs, [], cx).await;
8967 let (workspace, cx) =
8968 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8969
8970 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
8971 // Create history without an initial session list - it will be set after connection
8972 let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
8973
8974 let thread_view = cx.update(|window, cx| {
8975 cx.new(|cx| {
8976 AcpThreadView::new(
8977 Rc::new(StubAgentServer::default_response()),
8978 None,
8979 None,
8980 workspace.downgrade(),
8981 project,
8982 Some(thread_store),
8983 None,
8984 history.clone(),
8985 window,
8986 cx,
8987 )
8988 })
8989 });
8990
8991 // Wait for connection to establish
8992 cx.run_until_parked();
8993
8994 // Initially empty because StubAgentConnection.session_list() returns None
8995 thread_view.read_with(cx, |view, _cx| {
8996 assert_eq!(view.recent_history_entries.len(), 0);
8997 });
8998
8999 // Now set the session list - this simulates external agents providing their history
9000 let list_a: Rc<dyn AgentSessionList> =
9001 Rc::new(StubSessionList::new(vec![session_a.clone()]));
9002 history.update(cx, |history, cx| {
9003 history.set_session_list(Some(list_a), cx);
9004 });
9005 cx.run_until_parked();
9006
9007 thread_view.read_with(cx, |view, _cx| {
9008 assert_eq!(view.recent_history_entries.len(), 1);
9009 assert_eq!(
9010 view.recent_history_entries[0].session_id,
9011 session_a.session_id
9012 );
9013 });
9014
9015 // Update to a different session list
9016 let list_b: Rc<dyn AgentSessionList> =
9017 Rc::new(StubSessionList::new(vec![session_b.clone()]));
9018 history.update(cx, |history, cx| {
9019 history.set_session_list(Some(list_b), cx);
9020 });
9021 cx.run_until_parked();
9022
9023 thread_view.read_with(cx, |view, _cx| {
9024 assert_eq!(view.recent_history_entries.len(), 1);
9025 assert_eq!(
9026 view.recent_history_entries[0].session_id,
9027 session_b.session_id
9028 );
9029 });
9030 }
9031
9032 #[gpui::test]
9033 async fn test_resume_without_history_adds_notice(cx: &mut TestAppContext) {
9034 init_test(cx);
9035
9036 let session = AgentSessionInfo::new(SessionId::new("resume-session"));
9037 let fs = FakeFs::new(cx.executor());
9038 let project = Project::test(fs, [], cx).await;
9039 let (workspace, cx) =
9040 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9041
9042 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
9043 let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
9044
9045 let thread_view = cx.update(|window, cx| {
9046 cx.new(|cx| {
9047 AcpThreadView::new(
9048 Rc::new(StubAgentServer::new(ResumeOnlyAgentConnection)),
9049 Some(session),
9050 None,
9051 workspace.downgrade(),
9052 project,
9053 Some(thread_store),
9054 None,
9055 history,
9056 window,
9057 cx,
9058 )
9059 })
9060 });
9061
9062 cx.run_until_parked();
9063
9064 thread_view.read_with(cx, |view, _cx| {
9065 assert!(view.resumed_without_history);
9066 assert_eq!(view.list_state.item_count(), 0);
9067 });
9068 }
9069
9070 #[gpui::test]
9071 async fn test_refusal_handling(cx: &mut TestAppContext) {
9072 init_test(cx);
9073
9074 let (thread_view, cx) =
9075 setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
9076
9077 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9078 message_editor.update_in(cx, |editor, window, cx| {
9079 editor.set_text("Do something harmful", window, cx);
9080 });
9081
9082 thread_view.update_in(cx, |thread_view, window, cx| {
9083 thread_view.send(window, cx);
9084 });
9085
9086 cx.run_until_parked();
9087
9088 // Check that the refusal error is set
9089 thread_view.read_with(cx, |thread_view, _cx| {
9090 assert!(
9091 matches!(thread_view.thread_error, Some(ThreadError::Refusal)),
9092 "Expected refusal error to be set"
9093 );
9094 });
9095 }
9096
9097 #[gpui::test]
9098 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
9099 init_test(cx);
9100
9101 let tool_call_id = acp::ToolCallId::new("1");
9102 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Label")
9103 .kind(acp::ToolKind::Edit)
9104 .content(vec!["hi".into()]);
9105 let connection =
9106 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
9107 tool_call_id,
9108 PermissionOptions::Flat(vec![acp::PermissionOption::new(
9109 "1",
9110 "Allow",
9111 acp::PermissionOptionKind::AllowOnce,
9112 )]),
9113 )]));
9114
9115 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
9116
9117 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
9118
9119 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9120 message_editor.update_in(cx, |editor, window, cx| {
9121 editor.set_text("Hello", window, cx);
9122 });
9123
9124 cx.deactivate_window();
9125
9126 thread_view.update_in(cx, |thread_view, window, cx| {
9127 thread_view.send(window, cx);
9128 });
9129
9130 cx.run_until_parked();
9131
9132 assert!(
9133 cx.windows()
9134 .iter()
9135 .any(|window| window.downcast::<AgentNotification>().is_some())
9136 );
9137 }
9138
9139 #[gpui::test]
9140 async fn test_notification_when_panel_hidden(cx: &mut TestAppContext) {
9141 init_test(cx);
9142
9143 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
9144
9145 add_to_workspace(thread_view.clone(), cx);
9146
9147 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9148
9149 message_editor.update_in(cx, |editor, window, cx| {
9150 editor.set_text("Hello", window, cx);
9151 });
9152
9153 // Window is active (don't deactivate), but panel will be hidden
9154 // Note: In the test environment, the panel is not actually added to the dock,
9155 // so is_agent_panel_hidden will return true
9156
9157 thread_view.update_in(cx, |thread_view, window, cx| {
9158 thread_view.send(window, cx);
9159 });
9160
9161 cx.run_until_parked();
9162
9163 // Should show notification because window is active but panel is hidden
9164 assert!(
9165 cx.windows()
9166 .iter()
9167 .any(|window| window.downcast::<AgentNotification>().is_some()),
9168 "Expected notification when panel is hidden"
9169 );
9170 }
9171
9172 #[gpui::test]
9173 async fn test_notification_still_works_when_window_inactive(cx: &mut TestAppContext) {
9174 init_test(cx);
9175
9176 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
9177
9178 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9179 message_editor.update_in(cx, |editor, window, cx| {
9180 editor.set_text("Hello", window, cx);
9181 });
9182
9183 // Deactivate window - should show notification regardless of setting
9184 cx.deactivate_window();
9185
9186 thread_view.update_in(cx, |thread_view, window, cx| {
9187 thread_view.send(window, cx);
9188 });
9189
9190 cx.run_until_parked();
9191
9192 // Should still show notification when window is inactive (existing behavior)
9193 assert!(
9194 cx.windows()
9195 .iter()
9196 .any(|window| window.downcast::<AgentNotification>().is_some()),
9197 "Expected notification when window is inactive"
9198 );
9199 }
9200
9201 #[gpui::test]
9202 async fn test_notification_respects_never_setting(cx: &mut TestAppContext) {
9203 init_test(cx);
9204
9205 // Set notify_when_agent_waiting to Never
9206 cx.update(|cx| {
9207 AgentSettings::override_global(
9208 AgentSettings {
9209 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
9210 ..AgentSettings::get_global(cx).clone()
9211 },
9212 cx,
9213 );
9214 });
9215
9216 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
9217
9218 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9219 message_editor.update_in(cx, |editor, window, cx| {
9220 editor.set_text("Hello", window, cx);
9221 });
9222
9223 // Window is active
9224
9225 thread_view.update_in(cx, |thread_view, window, cx| {
9226 thread_view.send(window, cx);
9227 });
9228
9229 cx.run_until_parked();
9230
9231 // Should NOT show notification because notify_when_agent_waiting is Never
9232 assert!(
9233 !cx.windows()
9234 .iter()
9235 .any(|window| window.downcast::<AgentNotification>().is_some()),
9236 "Expected no notification when notify_when_agent_waiting is Never"
9237 );
9238 }
9239
9240 #[gpui::test]
9241 async fn test_notification_closed_when_thread_view_dropped(cx: &mut TestAppContext) {
9242 init_test(cx);
9243
9244 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
9245
9246 let weak_view = thread_view.downgrade();
9247
9248 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9249 message_editor.update_in(cx, |editor, window, cx| {
9250 editor.set_text("Hello", window, cx);
9251 });
9252
9253 cx.deactivate_window();
9254
9255 thread_view.update_in(cx, |thread_view, window, cx| {
9256 thread_view.send(window, cx);
9257 });
9258
9259 cx.run_until_parked();
9260
9261 // Verify notification is shown
9262 assert!(
9263 cx.windows()
9264 .iter()
9265 .any(|window| window.downcast::<AgentNotification>().is_some()),
9266 "Expected notification to be shown"
9267 );
9268
9269 // Drop the thread view (simulating navigation to a new thread)
9270 drop(thread_view);
9271 drop(message_editor);
9272 // Trigger an update to flush effects, which will call release_dropped_entities
9273 cx.update(|_window, _cx| {});
9274 cx.run_until_parked();
9275
9276 // Verify the entity was actually released
9277 assert!(
9278 !weak_view.is_upgradable(),
9279 "Thread view entity should be released after dropping"
9280 );
9281
9282 // The notification should be automatically closed via on_release
9283 assert!(
9284 !cx.windows()
9285 .iter()
9286 .any(|window| window.downcast::<AgentNotification>().is_some()),
9287 "Notification should be closed when thread view is dropped"
9288 );
9289 }
9290
9291 async fn setup_thread_view(
9292 agent: impl AgentServer + 'static,
9293 cx: &mut TestAppContext,
9294 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
9295 let fs = FakeFs::new(cx.executor());
9296 let project = Project::test(fs, [], cx).await;
9297 let (workspace, cx) =
9298 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9299
9300 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
9301 let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
9302
9303 let thread_view = cx.update(|window, cx| {
9304 cx.new(|cx| {
9305 AcpThreadView::new(
9306 Rc::new(agent),
9307 None,
9308 None,
9309 workspace.downgrade(),
9310 project,
9311 Some(thread_store),
9312 None,
9313 history,
9314 window,
9315 cx,
9316 )
9317 })
9318 });
9319 cx.run_until_parked();
9320 (thread_view, cx)
9321 }
9322
9323 fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
9324 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
9325
9326 workspace
9327 .update_in(cx, |workspace, window, cx| {
9328 workspace.add_item_to_active_pane(
9329 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
9330 None,
9331 true,
9332 window,
9333 cx,
9334 );
9335 })
9336 .unwrap();
9337 }
9338
9339 struct ThreadViewItem(Entity<AcpThreadView>);
9340
9341 impl Item for ThreadViewItem {
9342 type Event = ();
9343
9344 fn include_in_nav_history() -> bool {
9345 false
9346 }
9347
9348 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
9349 "Test".into()
9350 }
9351 }
9352
9353 impl EventEmitter<()> for ThreadViewItem {}
9354
9355 impl Focusable for ThreadViewItem {
9356 fn focus_handle(&self, cx: &App) -> FocusHandle {
9357 self.0.read(cx).focus_handle(cx)
9358 }
9359 }
9360
9361 impl Render for ThreadViewItem {
9362 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
9363 self.0.clone().into_any_element()
9364 }
9365 }
9366
9367 struct StubAgentServer<C> {
9368 connection: C,
9369 }
9370
9371 impl<C> StubAgentServer<C> {
9372 fn new(connection: C) -> Self {
9373 Self { connection }
9374 }
9375 }
9376
9377 impl StubAgentServer<StubAgentConnection> {
9378 fn default_response() -> Self {
9379 let conn = StubAgentConnection::new();
9380 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
9381 acp::ContentChunk::new("Default response".into()),
9382 )]);
9383 Self::new(conn)
9384 }
9385 }
9386
9387 #[derive(Clone)]
9388 struct StubSessionList {
9389 sessions: Vec<AgentSessionInfo>,
9390 }
9391
9392 impl StubSessionList {
9393 fn new(sessions: Vec<AgentSessionInfo>) -> Self {
9394 Self { sessions }
9395 }
9396 }
9397
9398 impl AgentSessionList for StubSessionList {
9399 fn list_sessions(
9400 &self,
9401 _request: AgentSessionListRequest,
9402 _cx: &mut App,
9403 ) -> Task<anyhow::Result<AgentSessionListResponse>> {
9404 Task::ready(Ok(AgentSessionListResponse::new(self.sessions.clone())))
9405 }
9406 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
9407 self
9408 }
9409 }
9410
9411 #[derive(Clone)]
9412 struct ResumeOnlyAgentConnection;
9413
9414 impl AgentConnection for ResumeOnlyAgentConnection {
9415 fn telemetry_id(&self) -> SharedString {
9416 "resume-only".into()
9417 }
9418
9419 fn new_thread(
9420 self: Rc<Self>,
9421 project: Entity<Project>,
9422 _cwd: &Path,
9423 cx: &mut gpui::App,
9424 ) -> Task<gpui::Result<Entity<AcpThread>>> {
9425 let action_log = cx.new(|_| ActionLog::new(project.clone()));
9426 let thread = cx.new(|cx| {
9427 AcpThread::new(
9428 "ResumeOnlyAgentConnection",
9429 self.clone(),
9430 project,
9431 action_log,
9432 SessionId::new("new-session"),
9433 watch::Receiver::constant(
9434 acp::PromptCapabilities::new()
9435 .image(true)
9436 .audio(true)
9437 .embedded_context(true),
9438 ),
9439 cx,
9440 )
9441 });
9442 Task::ready(Ok(thread))
9443 }
9444
9445 fn supports_resume_session(&self, _cx: &App) -> bool {
9446 true
9447 }
9448
9449 fn resume_session(
9450 self: Rc<Self>,
9451 session: AgentSessionInfo,
9452 project: Entity<Project>,
9453 _cwd: &Path,
9454 cx: &mut App,
9455 ) -> Task<gpui::Result<Entity<AcpThread>>> {
9456 let action_log = cx.new(|_| ActionLog::new(project.clone()));
9457 let thread = cx.new(|cx| {
9458 AcpThread::new(
9459 "ResumeOnlyAgentConnection",
9460 self.clone(),
9461 project,
9462 action_log,
9463 session.session_id,
9464 watch::Receiver::constant(
9465 acp::PromptCapabilities::new()
9466 .image(true)
9467 .audio(true)
9468 .embedded_context(true),
9469 ),
9470 cx,
9471 )
9472 });
9473 Task::ready(Ok(thread))
9474 }
9475
9476 fn auth_methods(&self) -> &[acp::AuthMethod] {
9477 &[]
9478 }
9479
9480 fn authenticate(
9481 &self,
9482 _method_id: acp::AuthMethodId,
9483 _cx: &mut App,
9484 ) -> Task<gpui::Result<()>> {
9485 Task::ready(Ok(()))
9486 }
9487
9488 fn prompt(
9489 &self,
9490 _id: Option<acp_thread::UserMessageId>,
9491 _params: acp::PromptRequest,
9492 _cx: &mut App,
9493 ) -> Task<gpui::Result<acp::PromptResponse>> {
9494 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
9495 }
9496
9497 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
9498
9499 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
9500 self
9501 }
9502 }
9503
9504 impl<C> AgentServer for StubAgentServer<C>
9505 where
9506 C: 'static + AgentConnection + Send + Clone,
9507 {
9508 fn logo(&self) -> ui::IconName {
9509 ui::IconName::Ai
9510 }
9511
9512 fn name(&self) -> SharedString {
9513 "Test".into()
9514 }
9515
9516 fn connect(
9517 &self,
9518 _root_dir: Option<&Path>,
9519 _delegate: AgentServerDelegate,
9520 _cx: &mut App,
9521 ) -> Task<gpui::Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
9522 Task::ready(Ok((Rc::new(self.connection.clone()), None)))
9523 }
9524
9525 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
9526 self
9527 }
9528 }
9529
9530 #[derive(Clone)]
9531 struct SaboteurAgentConnection;
9532
9533 impl AgentConnection for SaboteurAgentConnection {
9534 fn telemetry_id(&self) -> SharedString {
9535 "saboteur".into()
9536 }
9537
9538 fn new_thread(
9539 self: Rc<Self>,
9540 project: Entity<Project>,
9541 _cwd: &Path,
9542 cx: &mut gpui::App,
9543 ) -> Task<gpui::Result<Entity<AcpThread>>> {
9544 Task::ready(Ok(cx.new(|cx| {
9545 let action_log = cx.new(|_| ActionLog::new(project.clone()));
9546 AcpThread::new(
9547 "SaboteurAgentConnection",
9548 self,
9549 project,
9550 action_log,
9551 SessionId::new("test"),
9552 watch::Receiver::constant(
9553 acp::PromptCapabilities::new()
9554 .image(true)
9555 .audio(true)
9556 .embedded_context(true),
9557 ),
9558 cx,
9559 )
9560 })))
9561 }
9562
9563 fn auth_methods(&self) -> &[acp::AuthMethod] {
9564 &[]
9565 }
9566
9567 fn authenticate(
9568 &self,
9569 _method_id: acp::AuthMethodId,
9570 _cx: &mut App,
9571 ) -> Task<gpui::Result<()>> {
9572 unimplemented!()
9573 }
9574
9575 fn prompt(
9576 &self,
9577 _id: Option<acp_thread::UserMessageId>,
9578 _params: acp::PromptRequest,
9579 _cx: &mut App,
9580 ) -> Task<gpui::Result<acp::PromptResponse>> {
9581 Task::ready(Err(anyhow::anyhow!("Error prompting")))
9582 }
9583
9584 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
9585 unimplemented!()
9586 }
9587
9588 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
9589 self
9590 }
9591 }
9592
9593 /// Simulates a model which always returns a refusal response
9594 #[derive(Clone)]
9595 struct RefusalAgentConnection;
9596
9597 impl AgentConnection for RefusalAgentConnection {
9598 fn telemetry_id(&self) -> SharedString {
9599 "refusal".into()
9600 }
9601
9602 fn new_thread(
9603 self: Rc<Self>,
9604 project: Entity<Project>,
9605 _cwd: &Path,
9606 cx: &mut gpui::App,
9607 ) -> Task<gpui::Result<Entity<AcpThread>>> {
9608 Task::ready(Ok(cx.new(|cx| {
9609 let action_log = cx.new(|_| ActionLog::new(project.clone()));
9610 AcpThread::new(
9611 "RefusalAgentConnection",
9612 self,
9613 project,
9614 action_log,
9615 SessionId::new("test"),
9616 watch::Receiver::constant(
9617 acp::PromptCapabilities::new()
9618 .image(true)
9619 .audio(true)
9620 .embedded_context(true),
9621 ),
9622 cx,
9623 )
9624 })))
9625 }
9626
9627 fn auth_methods(&self) -> &[acp::AuthMethod] {
9628 &[]
9629 }
9630
9631 fn authenticate(
9632 &self,
9633 _method_id: acp::AuthMethodId,
9634 _cx: &mut App,
9635 ) -> Task<gpui::Result<()>> {
9636 unimplemented!()
9637 }
9638
9639 fn prompt(
9640 &self,
9641 _id: Option<acp_thread::UserMessageId>,
9642 _params: acp::PromptRequest,
9643 _cx: &mut App,
9644 ) -> Task<gpui::Result<acp::PromptResponse>> {
9645 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::Refusal)))
9646 }
9647
9648 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
9649 unimplemented!()
9650 }
9651
9652 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
9653 self
9654 }
9655 }
9656
9657 pub(crate) fn init_test(cx: &mut TestAppContext) {
9658 cx.update(|cx| {
9659 let settings_store = SettingsStore::test(cx);
9660 cx.set_global(settings_store);
9661 theme::init(theme::LoadThemes::JustBase, cx);
9662 editor::init(cx);
9663 release_channel::init(semver::Version::new(0, 0, 0), cx);
9664 prompt_store::init(cx)
9665 });
9666 }
9667
9668 #[gpui::test]
9669 async fn test_rewind_views(cx: &mut TestAppContext) {
9670 init_test(cx);
9671
9672 let fs = FakeFs::new(cx.executor());
9673 fs.insert_tree(
9674 "/project",
9675 json!({
9676 "test1.txt": "old content 1",
9677 "test2.txt": "old content 2"
9678 }),
9679 )
9680 .await;
9681 let project = Project::test(fs, [Path::new("/project")], cx).await;
9682 let (workspace, cx) =
9683 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9684
9685 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
9686 let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
9687
9688 let connection = Rc::new(StubAgentConnection::new());
9689 let thread_view = cx.update(|window, cx| {
9690 cx.new(|cx| {
9691 AcpThreadView::new(
9692 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
9693 None,
9694 None,
9695 workspace.downgrade(),
9696 project.clone(),
9697 Some(thread_store.clone()),
9698 None,
9699 history,
9700 window,
9701 cx,
9702 )
9703 })
9704 });
9705
9706 cx.run_until_parked();
9707
9708 let thread = thread_view
9709 .read_with(cx, |view, _| view.thread().cloned())
9710 .unwrap();
9711
9712 // First user message
9713 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
9714 acp::ToolCall::new("tool1", "Edit file 1")
9715 .kind(acp::ToolKind::Edit)
9716 .status(acp::ToolCallStatus::Completed)
9717 .content(vec![acp::ToolCallContent::Diff(
9718 acp::Diff::new("/project/test1.txt", "new content 1").old_text("old content 1"),
9719 )]),
9720 )]);
9721
9722 thread
9723 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
9724 .await
9725 .unwrap();
9726 cx.run_until_parked();
9727
9728 thread.read_with(cx, |thread, _| {
9729 assert_eq!(thread.entries().len(), 2);
9730 });
9731
9732 thread_view.read_with(cx, |view, cx| {
9733 view.entry_view_state.read_with(cx, |entry_view_state, _| {
9734 assert!(
9735 entry_view_state
9736 .entry(0)
9737 .unwrap()
9738 .message_editor()
9739 .is_some()
9740 );
9741 assert!(entry_view_state.entry(1).unwrap().has_content());
9742 });
9743 });
9744
9745 // Second user message
9746 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
9747 acp::ToolCall::new("tool2", "Edit file 2")
9748 .kind(acp::ToolKind::Edit)
9749 .status(acp::ToolCallStatus::Completed)
9750 .content(vec![acp::ToolCallContent::Diff(
9751 acp::Diff::new("/project/test2.txt", "new content 2").old_text("old content 2"),
9752 )]),
9753 )]);
9754
9755 thread
9756 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
9757 .await
9758 .unwrap();
9759 cx.run_until_parked();
9760
9761 let second_user_message_id = thread.read_with(cx, |thread, _| {
9762 assert_eq!(thread.entries().len(), 4);
9763 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
9764 panic!();
9765 };
9766 user_message.id.clone().unwrap()
9767 });
9768
9769 thread_view.read_with(cx, |view, cx| {
9770 view.entry_view_state.read_with(cx, |entry_view_state, _| {
9771 assert!(
9772 entry_view_state
9773 .entry(0)
9774 .unwrap()
9775 .message_editor()
9776 .is_some()
9777 );
9778 assert!(entry_view_state.entry(1).unwrap().has_content());
9779 assert!(
9780 entry_view_state
9781 .entry(2)
9782 .unwrap()
9783 .message_editor()
9784 .is_some()
9785 );
9786 assert!(entry_view_state.entry(3).unwrap().has_content());
9787 });
9788 });
9789
9790 // Rewind to first message
9791 thread
9792 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
9793 .await
9794 .unwrap();
9795
9796 cx.run_until_parked();
9797
9798 thread.read_with(cx, |thread, _| {
9799 assert_eq!(thread.entries().len(), 2);
9800 });
9801
9802 thread_view.read_with(cx, |view, cx| {
9803 view.entry_view_state.read_with(cx, |entry_view_state, _| {
9804 assert!(
9805 entry_view_state
9806 .entry(0)
9807 .unwrap()
9808 .message_editor()
9809 .is_some()
9810 );
9811 assert!(entry_view_state.entry(1).unwrap().has_content());
9812
9813 // Old views should be dropped
9814 assert!(entry_view_state.entry(2).is_none());
9815 assert!(entry_view_state.entry(3).is_none());
9816 });
9817 });
9818 }
9819
9820 #[gpui::test]
9821 async fn test_scroll_to_most_recent_user_prompt(cx: &mut TestAppContext) {
9822 init_test(cx);
9823
9824 let connection = StubAgentConnection::new();
9825
9826 // Each user prompt will result in a user message entry plus an agent message entry.
9827 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
9828 acp::ContentChunk::new("Response 1".into()),
9829 )]);
9830
9831 let (thread_view, cx) =
9832 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
9833
9834 let thread = thread_view
9835 .read_with(cx, |view, _| view.thread().cloned())
9836 .unwrap();
9837
9838 thread
9839 .update(cx, |thread, cx| thread.send_raw("Prompt 1", cx))
9840 .await
9841 .unwrap();
9842 cx.run_until_parked();
9843
9844 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
9845 acp::ContentChunk::new("Response 2".into()),
9846 )]);
9847
9848 thread
9849 .update(cx, |thread, cx| thread.send_raw("Prompt 2", cx))
9850 .await
9851 .unwrap();
9852 cx.run_until_parked();
9853
9854 // Move somewhere else first so we're not trivially already on the last user prompt.
9855 thread_view.update(cx, |view, cx| {
9856 view.scroll_to_top(cx);
9857 });
9858 cx.run_until_parked();
9859
9860 thread_view.update(cx, |view, cx| {
9861 view.scroll_to_most_recent_user_prompt(cx);
9862 let scroll_top = view.list_state.logical_scroll_top();
9863 // Entries layout is: [User1, Assistant1, User2, Assistant2]
9864 assert_eq!(scroll_top.item_ix, 2);
9865 });
9866 }
9867
9868 #[gpui::test]
9869 async fn test_scroll_to_most_recent_user_prompt_falls_back_to_bottom_without_user_messages(
9870 cx: &mut TestAppContext,
9871 ) {
9872 init_test(cx);
9873
9874 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
9875
9876 // With no entries, scrolling should be a no-op and must not panic.
9877 thread_view.update(cx, |view, cx| {
9878 view.scroll_to_most_recent_user_prompt(cx);
9879 let scroll_top = view.list_state.logical_scroll_top();
9880 assert_eq!(scroll_top.item_ix, 0);
9881 });
9882 }
9883
9884 #[gpui::test]
9885 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
9886 init_test(cx);
9887
9888 let connection = StubAgentConnection::new();
9889
9890 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
9891 acp::ContentChunk::new("Response".into()),
9892 )]);
9893
9894 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
9895 add_to_workspace(thread_view.clone(), cx);
9896
9897 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9898 message_editor.update_in(cx, |editor, window, cx| {
9899 editor.set_text("Original message to edit", window, cx);
9900 });
9901 thread_view.update_in(cx, |thread_view, window, cx| {
9902 thread_view.send(window, cx);
9903 });
9904
9905 cx.run_until_parked();
9906
9907 let user_message_editor = thread_view.read_with(cx, |view, cx| {
9908 assert_eq!(view.editing_message, None);
9909
9910 view.entry_view_state
9911 .read(cx)
9912 .entry(0)
9913 .unwrap()
9914 .message_editor()
9915 .unwrap()
9916 .clone()
9917 });
9918
9919 // Focus
9920 cx.focus(&user_message_editor);
9921 thread_view.read_with(cx, |view, _cx| {
9922 assert_eq!(view.editing_message, Some(0));
9923 });
9924
9925 // Edit
9926 user_message_editor.update_in(cx, |editor, window, cx| {
9927 editor.set_text("Edited message content", window, cx);
9928 });
9929
9930 // Cancel
9931 user_message_editor.update_in(cx, |_editor, window, cx| {
9932 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
9933 });
9934
9935 thread_view.read_with(cx, |view, _cx| {
9936 assert_eq!(view.editing_message, None);
9937 });
9938
9939 user_message_editor.read_with(cx, |editor, cx| {
9940 assert_eq!(editor.text(cx), "Original message to edit");
9941 });
9942 }
9943
9944 #[gpui::test]
9945 async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
9946 init_test(cx);
9947
9948 let connection = StubAgentConnection::new();
9949
9950 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
9951 add_to_workspace(thread_view.clone(), cx);
9952
9953 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9954 message_editor.update_in(cx, |editor, window, cx| {
9955 editor.set_text("", window, cx);
9956 });
9957
9958 let thread = cx.read(|cx| thread_view.read(cx).thread().cloned().unwrap());
9959 let entries_before = cx.read(|cx| thread.read(cx).entries().len());
9960
9961 thread_view.update_in(cx, |view, window, cx| {
9962 view.send(window, cx);
9963 });
9964 cx.run_until_parked();
9965
9966 let entries_after = cx.read(|cx| thread.read(cx).entries().len());
9967 assert_eq!(
9968 entries_before, entries_after,
9969 "No message should be sent when editor is empty"
9970 );
9971 }
9972
9973 #[gpui::test]
9974 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
9975 init_test(cx);
9976
9977 let connection = StubAgentConnection::new();
9978
9979 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
9980 acp::ContentChunk::new("Response".into()),
9981 )]);
9982
9983 let (thread_view, cx) =
9984 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
9985 add_to_workspace(thread_view.clone(), cx);
9986
9987 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9988 message_editor.update_in(cx, |editor, window, cx| {
9989 editor.set_text("Original message to edit", window, cx);
9990 });
9991 thread_view.update_in(cx, |thread_view, window, cx| {
9992 thread_view.send(window, cx);
9993 });
9994
9995 cx.run_until_parked();
9996
9997 let user_message_editor = thread_view.read_with(cx, |view, cx| {
9998 assert_eq!(view.editing_message, None);
9999 assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
10000
10001 view.entry_view_state
10002 .read(cx)
10003 .entry(0)
10004 .unwrap()
10005 .message_editor()
10006 .unwrap()
10007 .clone()
10008 });
10009
10010 // Focus
10011 cx.focus(&user_message_editor);
10012
10013 // Edit
10014 user_message_editor.update_in(cx, |editor, window, cx| {
10015 editor.set_text("Edited message content", window, cx);
10016 });
10017
10018 // Send
10019 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
10020 acp::ContentChunk::new("New Response".into()),
10021 )]);
10022
10023 user_message_editor.update_in(cx, |_editor, window, cx| {
10024 window.dispatch_action(Box::new(Chat), cx);
10025 });
10026
10027 cx.run_until_parked();
10028
10029 thread_view.read_with(cx, |view, cx| {
10030 assert_eq!(view.editing_message, None);
10031
10032 let entries = view.thread().unwrap().read(cx).entries();
10033 assert_eq!(entries.len(), 2);
10034 assert_eq!(
10035 entries[0].to_markdown(cx),
10036 "## User\n\nEdited message content\n\n"
10037 );
10038 assert_eq!(
10039 entries[1].to_markdown(cx),
10040 "## Assistant\n\nNew Response\n\n"
10041 );
10042
10043 let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
10044 assert!(!state.entry(1).unwrap().has_content());
10045 state.entry(0).unwrap().message_editor().unwrap().clone()
10046 });
10047
10048 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
10049 })
10050 }
10051
10052 #[gpui::test]
10053 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
10054 init_test(cx);
10055
10056 let connection = StubAgentConnection::new();
10057
10058 let (thread_view, cx) =
10059 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
10060 add_to_workspace(thread_view.clone(), cx);
10061
10062 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10063 message_editor.update_in(cx, |editor, window, cx| {
10064 editor.set_text("Original message to edit", window, cx);
10065 });
10066 thread_view.update_in(cx, |thread_view, window, cx| {
10067 thread_view.send(window, cx);
10068 });
10069
10070 cx.run_until_parked();
10071
10072 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
10073 let thread = view.thread().unwrap().read(cx);
10074 assert_eq!(thread.entries().len(), 1);
10075
10076 let editor = view
10077 .entry_view_state
10078 .read(cx)
10079 .entry(0)
10080 .unwrap()
10081 .message_editor()
10082 .unwrap()
10083 .clone();
10084
10085 (editor, thread.session_id().clone())
10086 });
10087
10088 // Focus
10089 cx.focus(&user_message_editor);
10090
10091 thread_view.read_with(cx, |view, _cx| {
10092 assert_eq!(view.editing_message, Some(0));
10093 });
10094
10095 // Edit
10096 user_message_editor.update_in(cx, |editor, window, cx| {
10097 editor.set_text("Edited message content", window, cx);
10098 });
10099
10100 thread_view.read_with(cx, |view, _cx| {
10101 assert_eq!(view.editing_message, Some(0));
10102 });
10103
10104 // Finish streaming response
10105 cx.update(|_, cx| {
10106 connection.send_update(
10107 session_id.clone(),
10108 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("Response".into())),
10109 cx,
10110 );
10111 connection.end_turn(session_id, acp::StopReason::EndTurn);
10112 });
10113
10114 thread_view.read_with(cx, |view, _cx| {
10115 assert_eq!(view.editing_message, Some(0));
10116 });
10117
10118 cx.run_until_parked();
10119
10120 // Should still be editing
10121 cx.update(|window, cx| {
10122 assert!(user_message_editor.focus_handle(cx).is_focused(window));
10123 assert_eq!(thread_view.read(cx).editing_message, Some(0));
10124 assert_eq!(
10125 user_message_editor.read(cx).text(cx),
10126 "Edited message content"
10127 );
10128 });
10129 }
10130
10131 struct GeneratingThreadSetup {
10132 thread_view: Entity<AcpThreadView>,
10133 thread: Entity<AcpThread>,
10134 message_editor: Entity<MessageEditor>,
10135 }
10136
10137 async fn setup_generating_thread(
10138 cx: &mut TestAppContext,
10139 ) -> (GeneratingThreadSetup, &mut VisualTestContext) {
10140 let connection = StubAgentConnection::new();
10141
10142 let (thread_view, cx) =
10143 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
10144 add_to_workspace(thread_view.clone(), cx);
10145
10146 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10147 message_editor.update_in(cx, |editor, window, cx| {
10148 editor.set_text("Hello", window, cx);
10149 });
10150 thread_view.update_in(cx, |thread_view, window, cx| {
10151 thread_view.send(window, cx);
10152 });
10153
10154 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
10155 let thread = view.thread().unwrap();
10156 (thread.clone(), thread.read(cx).session_id().clone())
10157 });
10158
10159 cx.run_until_parked();
10160
10161 cx.update(|_, cx| {
10162 connection.send_update(
10163 session_id.clone(),
10164 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
10165 "Response chunk".into(),
10166 )),
10167 cx,
10168 );
10169 });
10170
10171 cx.run_until_parked();
10172
10173 thread.read_with(cx, |thread, _cx| {
10174 assert_eq!(thread.status(), ThreadStatus::Generating);
10175 });
10176
10177 (
10178 GeneratingThreadSetup {
10179 thread_view,
10180 thread,
10181 message_editor,
10182 },
10183 cx,
10184 )
10185 }
10186
10187 #[gpui::test]
10188 async fn test_escape_cancels_generation_from_conversation_focus(cx: &mut TestAppContext) {
10189 init_test(cx);
10190
10191 let (setup, cx) = setup_generating_thread(cx).await;
10192
10193 let focus_handle = setup
10194 .thread_view
10195 .read_with(cx, |view, _cx| view.focus_handle.clone());
10196 cx.update(|window, cx| {
10197 window.focus(&focus_handle, cx);
10198 });
10199
10200 setup.thread_view.update_in(cx, |_, window, cx| {
10201 window.dispatch_action(menu::Cancel.boxed_clone(), cx);
10202 });
10203
10204 cx.run_until_parked();
10205
10206 setup.thread.read_with(cx, |thread, _cx| {
10207 assert_eq!(thread.status(), ThreadStatus::Idle);
10208 });
10209 }
10210
10211 #[gpui::test]
10212 async fn test_escape_cancels_generation_from_editor_focus(cx: &mut TestAppContext) {
10213 init_test(cx);
10214
10215 let (setup, cx) = setup_generating_thread(cx).await;
10216
10217 let editor_focus_handle = setup
10218 .message_editor
10219 .read_with(cx, |editor, cx| editor.focus_handle(cx));
10220 cx.update(|window, cx| {
10221 window.focus(&editor_focus_handle, cx);
10222 });
10223
10224 setup.message_editor.update_in(cx, |_, window, cx| {
10225 window.dispatch_action(editor::actions::Cancel.boxed_clone(), cx);
10226 });
10227
10228 cx.run_until_parked();
10229
10230 setup.thread.read_with(cx, |thread, _cx| {
10231 assert_eq!(thread.status(), ThreadStatus::Idle);
10232 });
10233 }
10234
10235 #[gpui::test]
10236 async fn test_escape_when_idle_is_noop(cx: &mut TestAppContext) {
10237 init_test(cx);
10238
10239 let (thread_view, cx) =
10240 setup_thread_view(StubAgentServer::new(StubAgentConnection::new()), cx).await;
10241 add_to_workspace(thread_view.clone(), cx);
10242
10243 let thread = thread_view.read_with(cx, |view, _cx| view.thread().unwrap().clone());
10244
10245 thread.read_with(cx, |thread, _cx| {
10246 assert_eq!(thread.status(), ThreadStatus::Idle);
10247 });
10248
10249 let focus_handle = thread_view.read_with(cx, |view, _cx| view.focus_handle.clone());
10250 cx.update(|window, cx| {
10251 window.focus(&focus_handle, cx);
10252 });
10253
10254 thread_view.update_in(cx, |_, window, cx| {
10255 window.dispatch_action(menu::Cancel.boxed_clone(), cx);
10256 });
10257
10258 cx.run_until_parked();
10259
10260 thread.read_with(cx, |thread, _cx| {
10261 assert_eq!(thread.status(), ThreadStatus::Idle);
10262 });
10263 }
10264
10265 #[gpui::test]
10266 async fn test_interrupt(cx: &mut TestAppContext) {
10267 init_test(cx);
10268
10269 let connection = StubAgentConnection::new();
10270
10271 let (thread_view, cx) =
10272 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
10273 add_to_workspace(thread_view.clone(), cx);
10274
10275 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10276 message_editor.update_in(cx, |editor, window, cx| {
10277 editor.set_text("Message 1", window, cx);
10278 });
10279 thread_view.update_in(cx, |thread_view, window, cx| {
10280 thread_view.send(window, cx);
10281 });
10282
10283 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
10284 let thread = view.thread().unwrap();
10285
10286 (thread.clone(), thread.read(cx).session_id().clone())
10287 });
10288
10289 cx.run_until_parked();
10290
10291 cx.update(|_, cx| {
10292 connection.send_update(
10293 session_id.clone(),
10294 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
10295 "Message 1 resp".into(),
10296 )),
10297 cx,
10298 );
10299 });
10300
10301 cx.run_until_parked();
10302
10303 thread.read_with(cx, |thread, cx| {
10304 assert_eq!(
10305 thread.to_markdown(cx),
10306 indoc::indoc! {"
10307 ## User
10308
10309 Message 1
10310
10311 ## Assistant
10312
10313 Message 1 resp
10314
10315 "}
10316 )
10317 });
10318
10319 message_editor.update_in(cx, |editor, window, cx| {
10320 editor.set_text("Message 2", window, cx);
10321 });
10322 thread_view.update_in(cx, |thread_view, window, cx| {
10323 thread_view.interrupt_and_send(window, cx);
10324 });
10325
10326 cx.update(|_, cx| {
10327 // Simulate a response sent after beginning to cancel
10328 connection.send_update(
10329 session_id.clone(),
10330 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("onse".into())),
10331 cx,
10332 );
10333 });
10334
10335 cx.run_until_parked();
10336
10337 // Last Message 1 response should appear before Message 2
10338 thread.read_with(cx, |thread, cx| {
10339 assert_eq!(
10340 thread.to_markdown(cx),
10341 indoc::indoc! {"
10342 ## User
10343
10344 Message 1
10345
10346 ## Assistant
10347
10348 Message 1 response
10349
10350 ## User
10351
10352 Message 2
10353
10354 "}
10355 )
10356 });
10357
10358 cx.update(|_, cx| {
10359 connection.send_update(
10360 session_id.clone(),
10361 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
10362 "Message 2 response".into(),
10363 )),
10364 cx,
10365 );
10366 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
10367 });
10368
10369 cx.run_until_parked();
10370
10371 thread.read_with(cx, |thread, cx| {
10372 assert_eq!(
10373 thread.to_markdown(cx),
10374 indoc::indoc! {"
10375 ## User
10376
10377 Message 1
10378
10379 ## Assistant
10380
10381 Message 1 response
10382
10383 ## User
10384
10385 Message 2
10386
10387 ## Assistant
10388
10389 Message 2 response
10390
10391 "}
10392 )
10393 });
10394 }
10395
10396 #[gpui::test]
10397 async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
10398 init_test(cx);
10399
10400 let connection = StubAgentConnection::new();
10401 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
10402 acp::ContentChunk::new("Response".into()),
10403 )]);
10404
10405 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10406 add_to_workspace(thread_view.clone(), cx);
10407
10408 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10409 message_editor.update_in(cx, |editor, window, cx| {
10410 editor.set_text("Original message to edit", window, cx)
10411 });
10412 thread_view.update_in(cx, |thread_view, window, cx| thread_view.send(window, cx));
10413 cx.run_until_parked();
10414
10415 let user_message_editor = thread_view.read_with(cx, |thread_view, cx| {
10416 thread_view
10417 .entry_view_state
10418 .read(cx)
10419 .entry(0)
10420 .expect("Should have at least one entry")
10421 .message_editor()
10422 .expect("Should have message editor")
10423 .clone()
10424 });
10425
10426 cx.focus(&user_message_editor);
10427 thread_view.read_with(cx, |thread_view, _cx| {
10428 assert_eq!(thread_view.editing_message, Some(0));
10429 });
10430
10431 // Ensure to edit the focused message before proceeding otherwise, since
10432 // its content is not different from what was sent, focus will be lost.
10433 user_message_editor.update_in(cx, |editor, window, cx| {
10434 editor.set_text("Original message to edit with ", window, cx)
10435 });
10436
10437 // Create a simple buffer with some text so we can create a selection
10438 // that will then be added to the message being edited.
10439 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
10440 (thread_view.workspace.clone(), thread_view.project.clone())
10441 });
10442 let buffer = project.update(cx, |project, cx| {
10443 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
10444 });
10445
10446 workspace
10447 .update_in(cx, |workspace, window, cx| {
10448 let editor = cx.new(|cx| {
10449 let mut editor =
10450 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
10451
10452 editor.change_selections(Default::default(), window, cx, |selections| {
10453 selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
10454 });
10455
10456 editor
10457 });
10458 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
10459 })
10460 .unwrap();
10461
10462 thread_view.update_in(cx, |thread_view, window, cx| {
10463 assert_eq!(thread_view.editing_message, Some(0));
10464 thread_view.insert_selections(window, cx);
10465 });
10466
10467 user_message_editor.read_with(cx, |editor, cx| {
10468 let text = editor.editor().read(cx).text(cx);
10469 let expected_text = String::from("Original message to edit with selection ");
10470
10471 assert_eq!(text, expected_text);
10472 });
10473 }
10474
10475 #[gpui::test]
10476 async fn test_insert_selections(cx: &mut TestAppContext) {
10477 init_test(cx);
10478
10479 let connection = StubAgentConnection::new();
10480 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
10481 acp::ContentChunk::new("Response".into()),
10482 )]);
10483
10484 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10485 add_to_workspace(thread_view.clone(), cx);
10486
10487 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10488 message_editor.update_in(cx, |editor, window, cx| {
10489 editor.set_text("Can you review this snippet ", window, cx)
10490 });
10491
10492 // Create a simple buffer with some text so we can create a selection
10493 // that will then be added to the message being edited.
10494 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
10495 (thread_view.workspace.clone(), thread_view.project.clone())
10496 });
10497 let buffer = project.update(cx, |project, cx| {
10498 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
10499 });
10500
10501 workspace
10502 .update_in(cx, |workspace, window, cx| {
10503 let editor = cx.new(|cx| {
10504 let mut editor =
10505 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
10506
10507 editor.change_selections(Default::default(), window, cx, |selections| {
10508 selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
10509 });
10510
10511 editor
10512 });
10513 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
10514 })
10515 .unwrap();
10516
10517 thread_view.update_in(cx, |thread_view, window, cx| {
10518 assert_eq!(thread_view.editing_message, None);
10519 thread_view.insert_selections(window, cx);
10520 });
10521
10522 thread_view.read_with(cx, |thread_view, cx| {
10523 let text = thread_view.message_editor.read(cx).text(cx);
10524 let expected_txt = String::from("Can you review this snippet selection ");
10525
10526 assert_eq!(text, expected_txt);
10527 })
10528 }
10529
10530 #[gpui::test]
10531 async fn test_tool_permission_buttons_terminal_with_pattern(cx: &mut TestAppContext) {
10532 init_test(cx);
10533
10534 let tool_call_id = acp::ToolCallId::new("terminal-1");
10535 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build --release`")
10536 .kind(acp::ToolKind::Edit);
10537
10538 let permission_options = ToolPermissionContext::new("terminal", "cargo build --release")
10539 .build_permission_options();
10540
10541 let connection =
10542 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10543 tool_call_id.clone(),
10544 permission_options,
10545 )]));
10546
10547 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10548
10549 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10550
10551 // Disable notifications to avoid popup windows
10552 cx.update(|_window, cx| {
10553 AgentSettings::override_global(
10554 AgentSettings {
10555 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10556 ..AgentSettings::get_global(cx).clone()
10557 },
10558 cx,
10559 );
10560 });
10561
10562 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10563 message_editor.update_in(cx, |editor, window, cx| {
10564 editor.set_text("Run cargo build", window, cx);
10565 });
10566
10567 thread_view.update_in(cx, |thread_view, window, cx| {
10568 thread_view.send(window, cx);
10569 });
10570
10571 cx.run_until_parked();
10572
10573 // Verify the tool call is in WaitingForConfirmation state with the expected options
10574 thread_view.read_with(cx, |thread_view, cx| {
10575 let thread = thread_view.thread().expect("Thread should exist");
10576 let thread = thread.read(cx);
10577
10578 let tool_call = thread.entries().iter().find_map(|entry| {
10579 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
10580 Some(call)
10581 } else {
10582 None
10583 }
10584 });
10585
10586 assert!(tool_call.is_some(), "Expected a tool call entry");
10587 let tool_call = tool_call.unwrap();
10588
10589 // Verify it's waiting for confirmation
10590 assert!(
10591 matches!(
10592 tool_call.status,
10593 acp_thread::ToolCallStatus::WaitingForConfirmation { .. }
10594 ),
10595 "Expected WaitingForConfirmation status, got {:?}",
10596 tool_call.status
10597 );
10598
10599 // Verify the options count (granularity options only, no separate Deny option)
10600 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
10601 &tool_call.status
10602 {
10603 let PermissionOptions::Dropdown(choices) = options else {
10604 panic!("Expected dropdown permission options");
10605 };
10606
10607 assert_eq!(
10608 choices.len(),
10609 3,
10610 "Expected 3 permission options (granularity only)"
10611 );
10612
10613 // Verify specific button labels (now using neutral names)
10614 let labels: Vec<&str> = choices
10615 .iter()
10616 .map(|choice| choice.allow.name.as_ref())
10617 .collect();
10618 assert!(
10619 labels.contains(&"Always for terminal"),
10620 "Missing 'Always for terminal' option"
10621 );
10622 assert!(
10623 labels.contains(&"Always for `cargo` commands"),
10624 "Missing pattern option"
10625 );
10626 assert!(
10627 labels.contains(&"Only this time"),
10628 "Missing 'Only this time' option"
10629 );
10630 }
10631 });
10632 }
10633
10634 #[gpui::test]
10635 async fn test_tool_permission_buttons_edit_file_with_path_pattern(cx: &mut TestAppContext) {
10636 init_test(cx);
10637
10638 let tool_call_id = acp::ToolCallId::new("edit-file-1");
10639 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Edit `src/main.rs`")
10640 .kind(acp::ToolKind::Edit);
10641
10642 let permission_options =
10643 ToolPermissionContext::new("edit_file", "src/main.rs").build_permission_options();
10644
10645 let connection =
10646 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10647 tool_call_id.clone(),
10648 permission_options,
10649 )]));
10650
10651 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10652
10653 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10654
10655 // Disable notifications
10656 cx.update(|_window, cx| {
10657 AgentSettings::override_global(
10658 AgentSettings {
10659 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10660 ..AgentSettings::get_global(cx).clone()
10661 },
10662 cx,
10663 );
10664 });
10665
10666 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10667 message_editor.update_in(cx, |editor, window, cx| {
10668 editor.set_text("Edit the main file", window, cx);
10669 });
10670
10671 thread_view.update_in(cx, |thread_view, window, cx| {
10672 thread_view.send(window, cx);
10673 });
10674
10675 cx.run_until_parked();
10676
10677 // Verify the options
10678 thread_view.read_with(cx, |thread_view, cx| {
10679 let thread = thread_view.thread().expect("Thread should exist");
10680 let thread = thread.read(cx);
10681
10682 let tool_call = thread.entries().iter().find_map(|entry| {
10683 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
10684 Some(call)
10685 } else {
10686 None
10687 }
10688 });
10689
10690 assert!(tool_call.is_some(), "Expected a tool call entry");
10691 let tool_call = tool_call.unwrap();
10692
10693 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
10694 &tool_call.status
10695 {
10696 let PermissionOptions::Dropdown(choices) = options else {
10697 panic!("Expected dropdown permission options");
10698 };
10699
10700 let labels: Vec<&str> = choices
10701 .iter()
10702 .map(|choice| choice.allow.name.as_ref())
10703 .collect();
10704 assert!(
10705 labels.contains(&"Always for edit file"),
10706 "Missing 'Always for edit file' option"
10707 );
10708 assert!(
10709 labels.contains(&"Always for `src/`"),
10710 "Missing path pattern option"
10711 );
10712 } else {
10713 panic!("Expected WaitingForConfirmation status");
10714 }
10715 });
10716 }
10717
10718 #[gpui::test]
10719 async fn test_tool_permission_buttons_fetch_with_domain_pattern(cx: &mut TestAppContext) {
10720 init_test(cx);
10721
10722 let tool_call_id = acp::ToolCallId::new("fetch-1");
10723 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Fetch `https://docs.rs/gpui`")
10724 .kind(acp::ToolKind::Fetch);
10725
10726 let permission_options =
10727 ToolPermissionContext::new("fetch", "https://docs.rs/gpui").build_permission_options();
10728
10729 let connection =
10730 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10731 tool_call_id.clone(),
10732 permission_options,
10733 )]));
10734
10735 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10736
10737 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10738
10739 // Disable notifications
10740 cx.update(|_window, cx| {
10741 AgentSettings::override_global(
10742 AgentSettings {
10743 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10744 ..AgentSettings::get_global(cx).clone()
10745 },
10746 cx,
10747 );
10748 });
10749
10750 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10751 message_editor.update_in(cx, |editor, window, cx| {
10752 editor.set_text("Fetch the docs", window, cx);
10753 });
10754
10755 thread_view.update_in(cx, |thread_view, window, cx| {
10756 thread_view.send(window, cx);
10757 });
10758
10759 cx.run_until_parked();
10760
10761 // Verify the options
10762 thread_view.read_with(cx, |thread_view, cx| {
10763 let thread = thread_view.thread().expect("Thread should exist");
10764 let thread = thread.read(cx);
10765
10766 let tool_call = thread.entries().iter().find_map(|entry| {
10767 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
10768 Some(call)
10769 } else {
10770 None
10771 }
10772 });
10773
10774 assert!(tool_call.is_some(), "Expected a tool call entry");
10775 let tool_call = tool_call.unwrap();
10776
10777 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
10778 &tool_call.status
10779 {
10780 let PermissionOptions::Dropdown(choices) = options else {
10781 panic!("Expected dropdown permission options");
10782 };
10783
10784 let labels: Vec<&str> = choices
10785 .iter()
10786 .map(|choice| choice.allow.name.as_ref())
10787 .collect();
10788 assert!(
10789 labels.contains(&"Always for fetch"),
10790 "Missing 'Always for fetch' option"
10791 );
10792 assert!(
10793 labels.contains(&"Always for `docs.rs`"),
10794 "Missing domain pattern option"
10795 );
10796 } else {
10797 panic!("Expected WaitingForConfirmation status");
10798 }
10799 });
10800 }
10801
10802 #[gpui::test]
10803 async fn test_tool_permission_buttons_without_pattern(cx: &mut TestAppContext) {
10804 init_test(cx);
10805
10806 let tool_call_id = acp::ToolCallId::new("terminal-no-pattern-1");
10807 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `./deploy.sh --production`")
10808 .kind(acp::ToolKind::Edit);
10809
10810 // No pattern button since ./deploy.sh doesn't match the alphanumeric pattern
10811 let permission_options = ToolPermissionContext::new("terminal", "./deploy.sh --production")
10812 .build_permission_options();
10813
10814 let connection =
10815 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10816 tool_call_id.clone(),
10817 permission_options,
10818 )]));
10819
10820 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10821
10822 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10823
10824 // Disable notifications
10825 cx.update(|_window, cx| {
10826 AgentSettings::override_global(
10827 AgentSettings {
10828 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10829 ..AgentSettings::get_global(cx).clone()
10830 },
10831 cx,
10832 );
10833 });
10834
10835 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10836 message_editor.update_in(cx, |editor, window, cx| {
10837 editor.set_text("Run the deploy script", window, cx);
10838 });
10839
10840 thread_view.update_in(cx, |thread_view, window, cx| {
10841 thread_view.send(window, cx);
10842 });
10843
10844 cx.run_until_parked();
10845
10846 // Verify only 2 options (no pattern button when command doesn't match pattern)
10847 thread_view.read_with(cx, |thread_view, cx| {
10848 let thread = thread_view.thread().expect("Thread should exist");
10849 let thread = thread.read(cx);
10850
10851 let tool_call = thread.entries().iter().find_map(|entry| {
10852 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
10853 Some(call)
10854 } else {
10855 None
10856 }
10857 });
10858
10859 assert!(tool_call.is_some(), "Expected a tool call entry");
10860 let tool_call = tool_call.unwrap();
10861
10862 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
10863 &tool_call.status
10864 {
10865 let PermissionOptions::Dropdown(choices) = options else {
10866 panic!("Expected dropdown permission options");
10867 };
10868
10869 assert_eq!(
10870 choices.len(),
10871 2,
10872 "Expected 2 permission options (no pattern option)"
10873 );
10874
10875 let labels: Vec<&str> = choices
10876 .iter()
10877 .map(|choice| choice.allow.name.as_ref())
10878 .collect();
10879 assert!(
10880 labels.contains(&"Always for terminal"),
10881 "Missing 'Always for terminal' option"
10882 );
10883 assert!(
10884 labels.contains(&"Only this time"),
10885 "Missing 'Only this time' option"
10886 );
10887 // Should NOT contain a pattern option
10888 assert!(
10889 !labels.iter().any(|l| l.contains("commands")),
10890 "Should not have pattern option"
10891 );
10892 } else {
10893 panic!("Expected WaitingForConfirmation status");
10894 }
10895 });
10896 }
10897
10898 #[gpui::test]
10899 async fn test_authorize_tool_call_action_triggers_authorization(cx: &mut TestAppContext) {
10900 init_test(cx);
10901
10902 let tool_call_id = acp::ToolCallId::new("action-test-1");
10903 let tool_call =
10904 acp::ToolCall::new(tool_call_id.clone(), "Run `cargo test`").kind(acp::ToolKind::Edit);
10905
10906 let permission_options =
10907 ToolPermissionContext::new("terminal", "cargo test").build_permission_options();
10908
10909 let connection =
10910 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10911 tool_call_id.clone(),
10912 permission_options,
10913 )]));
10914
10915 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10916
10917 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10918 add_to_workspace(thread_view.clone(), cx);
10919
10920 cx.update(|_window, cx| {
10921 AgentSettings::override_global(
10922 AgentSettings {
10923 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10924 ..AgentSettings::get_global(cx).clone()
10925 },
10926 cx,
10927 );
10928 });
10929
10930 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10931 message_editor.update_in(cx, |editor, window, cx| {
10932 editor.set_text("Run tests", window, cx);
10933 });
10934
10935 thread_view.update_in(cx, |thread_view, window, cx| {
10936 thread_view.send(window, cx);
10937 });
10938
10939 cx.run_until_parked();
10940
10941 // Verify tool call is waiting for confirmation
10942 thread_view.read_with(cx, |thread_view, cx| {
10943 let thread = thread_view.thread().expect("Thread should exist");
10944 let thread = thread.read(cx);
10945 let tool_call = thread.first_tool_awaiting_confirmation();
10946 assert!(
10947 tool_call.is_some(),
10948 "Expected a tool call waiting for confirmation"
10949 );
10950 });
10951
10952 // Dispatch the AuthorizeToolCall action (simulating dropdown menu selection)
10953 thread_view.update_in(cx, |_, window, cx| {
10954 window.dispatch_action(
10955 crate::AuthorizeToolCall {
10956 tool_call_id: "action-test-1".to_string(),
10957 option_id: "allow".to_string(),
10958 option_kind: "AllowOnce".to_string(),
10959 }
10960 .boxed_clone(),
10961 cx,
10962 );
10963 });
10964
10965 cx.run_until_parked();
10966
10967 // Verify tool call is no longer waiting for confirmation (was authorized)
10968 thread_view.read_with(cx, |thread_view, cx| {
10969 let thread = thread_view.thread().expect("Thread should exist");
10970 let thread = thread.read(cx);
10971 let tool_call = thread.first_tool_awaiting_confirmation();
10972 assert!(
10973 tool_call.is_none(),
10974 "Tool call should no longer be waiting for confirmation after AuthorizeToolCall action"
10975 );
10976 });
10977 }
10978
10979 #[gpui::test]
10980 async fn test_authorize_tool_call_action_with_pattern_option(cx: &mut TestAppContext) {
10981 init_test(cx);
10982
10983 let tool_call_id = acp::ToolCallId::new("pattern-action-test-1");
10984 let tool_call =
10985 acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
10986
10987 let permission_options =
10988 ToolPermissionContext::new("terminal", "npm install").build_permission_options();
10989
10990 let connection =
10991 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10992 tool_call_id.clone(),
10993 permission_options.clone(),
10994 )]));
10995
10996 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10997
10998 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10999 add_to_workspace(thread_view.clone(), cx);
11000
11001 cx.update(|_window, cx| {
11002 AgentSettings::override_global(
11003 AgentSettings {
11004 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
11005 ..AgentSettings::get_global(cx).clone()
11006 },
11007 cx,
11008 );
11009 });
11010
11011 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
11012 message_editor.update_in(cx, |editor, window, cx| {
11013 editor.set_text("Install dependencies", window, cx);
11014 });
11015
11016 thread_view.update_in(cx, |thread_view, window, cx| {
11017 thread_view.send(window, cx);
11018 });
11019
11020 cx.run_until_parked();
11021
11022 // Find the pattern option ID
11023 let pattern_option = match &permission_options {
11024 PermissionOptions::Dropdown(choices) => choices
11025 .iter()
11026 .find(|choice| {
11027 choice
11028 .allow
11029 .option_id
11030 .0
11031 .starts_with("always_allow_pattern:")
11032 })
11033 .map(|choice| &choice.allow)
11034 .expect("Should have a pattern option for npm command"),
11035 _ => panic!("Expected dropdown permission options"),
11036 };
11037
11038 // Dispatch action with the pattern option (simulating "Always allow `npm` commands")
11039 thread_view.update_in(cx, |_, window, cx| {
11040 window.dispatch_action(
11041 crate::AuthorizeToolCall {
11042 tool_call_id: "pattern-action-test-1".to_string(),
11043 option_id: pattern_option.option_id.0.to_string(),
11044 option_kind: "AllowAlways".to_string(),
11045 }
11046 .boxed_clone(),
11047 cx,
11048 );
11049 });
11050
11051 cx.run_until_parked();
11052
11053 // Verify tool call was authorized
11054 thread_view.read_with(cx, |thread_view, cx| {
11055 let thread = thread_view.thread().expect("Thread should exist");
11056 let thread = thread.read(cx);
11057 let tool_call = thread.first_tool_awaiting_confirmation();
11058 assert!(
11059 tool_call.is_none(),
11060 "Tool call should be authorized after selecting pattern option"
11061 );
11062 });
11063 }
11064
11065 #[gpui::test]
11066 async fn test_granularity_selection_updates_state(cx: &mut TestAppContext) {
11067 init_test(cx);
11068
11069 let tool_call_id = acp::ToolCallId::new("granularity-test-1");
11070 let tool_call =
11071 acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build`").kind(acp::ToolKind::Edit);
11072
11073 let permission_options =
11074 ToolPermissionContext::new("terminal", "cargo build").build_permission_options();
11075
11076 let connection =
11077 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
11078 tool_call_id.clone(),
11079 permission_options.clone(),
11080 )]));
11081
11082 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
11083
11084 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
11085 add_to_workspace(thread_view.clone(), cx);
11086
11087 cx.update(|_window, cx| {
11088 AgentSettings::override_global(
11089 AgentSettings {
11090 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
11091 ..AgentSettings::get_global(cx).clone()
11092 },
11093 cx,
11094 );
11095 });
11096
11097 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
11098 message_editor.update_in(cx, |editor, window, cx| {
11099 editor.set_text("Build the project", window, cx);
11100 });
11101
11102 thread_view.update_in(cx, |thread_view, window, cx| {
11103 thread_view.send(window, cx);
11104 });
11105
11106 cx.run_until_parked();
11107
11108 // Verify default granularity is the last option (index 2 = "Only this time")
11109 thread_view.read_with(cx, |thread_view, _cx| {
11110 let selected = thread_view
11111 .selected_permission_granularity
11112 .get(&tool_call_id);
11113 assert!(
11114 selected.is_none(),
11115 "Should have no selection initially (defaults to last)"
11116 );
11117 });
11118
11119 // Select the first option (index 0 = "Always for terminal")
11120 thread_view.update_in(cx, |_, window, cx| {
11121 window.dispatch_action(
11122 crate::SelectPermissionGranularity {
11123 tool_call_id: "granularity-test-1".to_string(),
11124 index: 0,
11125 }
11126 .boxed_clone(),
11127 cx,
11128 );
11129 });
11130
11131 cx.run_until_parked();
11132
11133 // Verify the selection was updated
11134 thread_view.read_with(cx, |thread_view, _cx| {
11135 let selected = thread_view
11136 .selected_permission_granularity
11137 .get(&tool_call_id);
11138 assert_eq!(selected, Some(&0), "Should have selected index 0");
11139 });
11140 }
11141
11142 #[gpui::test]
11143 async fn test_allow_button_uses_selected_granularity(cx: &mut TestAppContext) {
11144 init_test(cx);
11145
11146 let tool_call_id = acp::ToolCallId::new("allow-granularity-test-1");
11147 let tool_call =
11148 acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
11149
11150 let permission_options =
11151 ToolPermissionContext::new("terminal", "npm install").build_permission_options();
11152
11153 // Verify we have the expected options
11154 let PermissionOptions::Dropdown(choices) = &permission_options else {
11155 panic!("Expected dropdown permission options");
11156 };
11157
11158 assert_eq!(choices.len(), 3);
11159 assert!(
11160 choices[0]
11161 .allow
11162 .option_id
11163 .0
11164 .contains("always_allow:terminal")
11165 );
11166 assert!(
11167 choices[1]
11168 .allow
11169 .option_id
11170 .0
11171 .contains("always_allow_pattern:terminal")
11172 );
11173 assert_eq!(choices[2].allow.option_id.0.as_ref(), "allow");
11174
11175 let connection =
11176 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
11177 tool_call_id.clone(),
11178 permission_options.clone(),
11179 )]));
11180
11181 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
11182
11183 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
11184 add_to_workspace(thread_view.clone(), cx);
11185
11186 cx.update(|_window, cx| {
11187 AgentSettings::override_global(
11188 AgentSettings {
11189 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
11190 ..AgentSettings::get_global(cx).clone()
11191 },
11192 cx,
11193 );
11194 });
11195
11196 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
11197 message_editor.update_in(cx, |editor, window, cx| {
11198 editor.set_text("Install dependencies", window, cx);
11199 });
11200
11201 thread_view.update_in(cx, |thread_view, window, cx| {
11202 thread_view.send(window, cx);
11203 });
11204
11205 cx.run_until_parked();
11206
11207 // Select the pattern option (index 1 = "Always for `npm` commands")
11208 thread_view.update_in(cx, |_, window, cx| {
11209 window.dispatch_action(
11210 crate::SelectPermissionGranularity {
11211 tool_call_id: "allow-granularity-test-1".to_string(),
11212 index: 1,
11213 }
11214 .boxed_clone(),
11215 cx,
11216 );
11217 });
11218
11219 cx.run_until_parked();
11220
11221 // Simulate clicking the Allow button by dispatching AllowOnce action
11222 // which should use the selected granularity
11223 thread_view.update_in(cx, |thread_view, window, cx| {
11224 thread_view.allow_once(&AllowOnce, window, cx);
11225 });
11226
11227 cx.run_until_parked();
11228
11229 // Verify tool call was authorized
11230 thread_view.read_with(cx, |thread_view, cx| {
11231 let thread = thread_view.thread().expect("Thread should exist");
11232 let thread = thread.read(cx);
11233 let tool_call = thread.first_tool_awaiting_confirmation();
11234 assert!(
11235 tool_call.is_none(),
11236 "Tool call should be authorized after Allow with pattern granularity"
11237 );
11238 });
11239 }
11240
11241 #[gpui::test]
11242 async fn test_deny_button_uses_selected_granularity(cx: &mut TestAppContext) {
11243 init_test(cx);
11244
11245 let tool_call_id = acp::ToolCallId::new("deny-granularity-test-1");
11246 let tool_call =
11247 acp::ToolCall::new(tool_call_id.clone(), "Run `git push`").kind(acp::ToolKind::Edit);
11248
11249 let permission_options =
11250 ToolPermissionContext::new("terminal", "git push").build_permission_options();
11251
11252 let connection =
11253 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
11254 tool_call_id.clone(),
11255 permission_options.clone(),
11256 )]));
11257
11258 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
11259
11260 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
11261 add_to_workspace(thread_view.clone(), cx);
11262
11263 cx.update(|_window, cx| {
11264 AgentSettings::override_global(
11265 AgentSettings {
11266 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
11267 ..AgentSettings::get_global(cx).clone()
11268 },
11269 cx,
11270 );
11271 });
11272
11273 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
11274 message_editor.update_in(cx, |editor, window, cx| {
11275 editor.set_text("Push changes", window, cx);
11276 });
11277
11278 thread_view.update_in(cx, |thread_view, window, cx| {
11279 thread_view.send(window, cx);
11280 });
11281
11282 cx.run_until_parked();
11283
11284 // Use default granularity (last option = "Only this time")
11285 // Simulate clicking the Deny button
11286 thread_view.update_in(cx, |thread_view, window, cx| {
11287 thread_view.reject_once(&RejectOnce, window, cx);
11288 });
11289
11290 cx.run_until_parked();
11291
11292 // Verify tool call was rejected (no longer waiting for confirmation)
11293 thread_view.read_with(cx, |thread_view, cx| {
11294 let thread = thread_view.thread().expect("Thread should exist");
11295 let thread = thread.read(cx);
11296 let tool_call = thread.first_tool_awaiting_confirmation();
11297 assert!(
11298 tool_call.is_none(),
11299 "Tool call should be rejected after Deny"
11300 );
11301 });
11302 }
11303
11304 #[gpui::test]
11305 async fn test_option_id_transformation_for_allow() {
11306 let permission_options = ToolPermissionContext::new("terminal", "cargo build --release")
11307 .build_permission_options();
11308
11309 let PermissionOptions::Dropdown(choices) = permission_options else {
11310 panic!("Expected dropdown permission options");
11311 };
11312
11313 let allow_ids: Vec<String> = choices
11314 .iter()
11315 .map(|choice| choice.allow.option_id.0.to_string())
11316 .collect();
11317
11318 assert!(allow_ids.contains(&"always_allow:terminal".to_string()));
11319 assert!(allow_ids.contains(&"allow".to_string()));
11320 assert!(
11321 allow_ids
11322 .iter()
11323 .any(|id| id.starts_with("always_allow_pattern:terminal:")),
11324 "Missing allow pattern option"
11325 );
11326 }
11327
11328 #[gpui::test]
11329 async fn test_option_id_transformation_for_deny() {
11330 let permission_options = ToolPermissionContext::new("terminal", "cargo build --release")
11331 .build_permission_options();
11332
11333 let PermissionOptions::Dropdown(choices) = permission_options else {
11334 panic!("Expected dropdown permission options");
11335 };
11336
11337 let deny_ids: Vec<String> = choices
11338 .iter()
11339 .map(|choice| choice.deny.option_id.0.to_string())
11340 .collect();
11341
11342 assert!(deny_ids.contains(&"always_deny:terminal".to_string()));
11343 assert!(deny_ids.contains(&"deny".to_string()));
11344 assert!(
11345 deny_ids
11346 .iter()
11347 .any(|id| id.starts_with("always_deny_pattern:terminal:")),
11348 "Missing deny pattern option"
11349 );
11350 }
11351}