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