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