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