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