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