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::Undo,
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 let granularity_options: Vec<_> = options
3898 .iter()
3899 .filter(|o| {
3900 matches!(
3901 o.kind,
3902 acp::PermissionOptionKind::AllowOnce | acp::PermissionOptionKind::AllowAlways
3903 )
3904 })
3905 .collect();
3906
3907 // Get the selected granularity index, defaulting to the last option ("Only this time")
3908 let selected_index = self
3909 .selected_permission_granularity
3910 .get(&tool_call_id)
3911 .copied()
3912 .unwrap_or_else(|| granularity_options.len().saturating_sub(1));
3913
3914 let selected_option = granularity_options
3915 .get(selected_index)
3916 .or(granularity_options.last())
3917 .copied();
3918
3919 let dropdown_label: SharedString = selected_option
3920 .map(|o| o.name.clone().into())
3921 .unwrap_or_else(|| "Only this time".into());
3922
3923 let (allow_option_id, allow_option_kind, deny_option_id, deny_option_kind) =
3924 if let Some(option) = selected_option {
3925 let option_id_str = option.option_id.0.to_string();
3926
3927 // Transform option_id for allow: "always:tool" -> "always_allow:tool", "once" -> "allow"
3928 let allow_id = if option_id_str == "once" {
3929 "allow".to_string()
3930 } else if let Some(rest) = option_id_str.strip_prefix("always:") {
3931 format!("always_allow:{}", rest)
3932 } else if let Some(rest) = option_id_str.strip_prefix("always_pattern:") {
3933 format!("always_allow_pattern:{}", rest)
3934 } else {
3935 option_id_str.clone()
3936 };
3937
3938 // Transform option_id for deny: "always:tool" -> "always_deny:tool", "once" -> "deny"
3939 let deny_id = if option_id_str == "once" {
3940 "deny".to_string()
3941 } else if let Some(rest) = option_id_str.strip_prefix("always:") {
3942 format!("always_deny:{}", rest)
3943 } else if let Some(rest) = option_id_str.strip_prefix("always_pattern:") {
3944 format!("always_deny_pattern:{}", rest)
3945 } else {
3946 option_id_str.replace("allow", "deny")
3947 };
3948
3949 let allow_kind = option.kind;
3950 let deny_kind = match option.kind {
3951 acp::PermissionOptionKind::AllowOnce => acp::PermissionOptionKind::RejectOnce,
3952 acp::PermissionOptionKind::AllowAlways => {
3953 acp::PermissionOptionKind::RejectAlways
3954 }
3955 other => other,
3956 };
3957
3958 (
3959 acp::PermissionOptionId::new(allow_id),
3960 allow_kind,
3961 acp::PermissionOptionId::new(deny_id),
3962 deny_kind,
3963 )
3964 } else {
3965 (
3966 acp::PermissionOptionId::new("allow"),
3967 acp::PermissionOptionKind::AllowOnce,
3968 acp::PermissionOptionId::new("deny"),
3969 acp::PermissionOptionKind::RejectOnce,
3970 )
3971 };
3972
3973 h_flex()
3974 .w_full()
3975 .p_1()
3976 .gap_2()
3977 .justify_between()
3978 .border_t_1()
3979 .border_color(self.tool_card_border_color(cx))
3980 .child(
3981 h_flex()
3982 .gap_0p5()
3983 .child(
3984 Button::new(("allow-btn", entry_ix), "Allow")
3985 .icon(IconName::Check)
3986 .icon_color(Color::Success)
3987 .icon_position(IconPosition::Start)
3988 .icon_size(IconSize::XSmall)
3989 .label_size(LabelSize::Small)
3990 .when(is_first, |this| {
3991 this.key_binding(
3992 KeyBinding::for_action_in(
3993 &AllowOnce as &dyn Action,
3994 &self.focus_handle,
3995 cx,
3996 )
3997 .map(|kb| kb.size(rems_from_px(10.))),
3998 )
3999 })
4000 .on_click(cx.listener({
4001 let tool_call_id = tool_call_id.clone();
4002 let option_id = allow_option_id;
4003 let option_kind = allow_option_kind;
4004 move |this, _, window, cx| {
4005 this.authorize_tool_call(
4006 tool_call_id.clone(),
4007 option_id.clone(),
4008 option_kind,
4009 window,
4010 cx,
4011 );
4012 }
4013 })),
4014 )
4015 .child(
4016 Button::new(("deny-btn", entry_ix), "Deny")
4017 .icon(IconName::Close)
4018 .icon_color(Color::Error)
4019 .icon_position(IconPosition::Start)
4020 .icon_size(IconSize::XSmall)
4021 .label_size(LabelSize::Small)
4022 .when(is_first, |this| {
4023 this.key_binding(
4024 KeyBinding::for_action_in(
4025 &RejectOnce as &dyn Action,
4026 &self.focus_handle,
4027 cx,
4028 )
4029 .map(|kb| kb.size(rems_from_px(10.))),
4030 )
4031 })
4032 .on_click(cx.listener({
4033 let tool_call_id = tool_call_id.clone();
4034 let option_id = deny_option_id;
4035 let option_kind = deny_option_kind;
4036 move |this, _, window, cx| {
4037 this.authorize_tool_call(
4038 tool_call_id.clone(),
4039 option_id.clone(),
4040 option_kind,
4041 window,
4042 cx,
4043 );
4044 }
4045 })),
4046 ),
4047 )
4048 .child(self.render_permission_granularity_dropdown(
4049 &granularity_options,
4050 dropdown_label,
4051 entry_ix,
4052 tool_call_id,
4053 selected_index,
4054 is_first,
4055 cx,
4056 ))
4057 }
4058
4059 fn render_permission_granularity_dropdown(
4060 &self,
4061 granularity_options: &[&acp::PermissionOption],
4062 current_label: SharedString,
4063 entry_ix: usize,
4064 tool_call_id: acp::ToolCallId,
4065 selected_index: usize,
4066 is_first: bool,
4067 cx: &Context<Self>,
4068 ) -> impl IntoElement {
4069 let menu_options: Vec<(usize, SharedString)> = granularity_options
4070 .iter()
4071 .enumerate()
4072 .map(|(i, o)| (i, o.name.clone().into()))
4073 .collect();
4074
4075 PopoverMenu::new(("permission-granularity", entry_ix))
4076 .with_handle(self.permission_dropdown_handle.clone())
4077 .trigger(
4078 Button::new(("granularity-trigger", entry_ix), current_label)
4079 .icon(IconName::ChevronDown)
4080 .icon_size(IconSize::XSmall)
4081 .icon_color(Color::Muted)
4082 .label_size(LabelSize::Small)
4083 .when(is_first, |this| {
4084 this.key_binding(
4085 KeyBinding::for_action_in(
4086 &crate::OpenPermissionDropdown as &dyn Action,
4087 &self.focus_handle,
4088 cx,
4089 )
4090 .map(|kb| kb.size(rems_from_px(10.))),
4091 )
4092 }),
4093 )
4094 .menu(move |window, cx| {
4095 let tool_call_id = tool_call_id.clone();
4096 let options = menu_options.clone();
4097
4098 Some(ContextMenu::build(window, cx, move |mut menu, _, _| {
4099 for (index, display_name) in options.iter() {
4100 let display_name = display_name.clone();
4101 let index = *index;
4102 let tool_call_id_for_entry = tool_call_id.clone();
4103 let is_selected = index == selected_index;
4104
4105 menu = menu.toggleable_entry(
4106 display_name,
4107 is_selected,
4108 IconPosition::End,
4109 None,
4110 move |window, cx| {
4111 window.dispatch_action(
4112 SelectPermissionGranularity {
4113 tool_call_id: tool_call_id_for_entry.0.to_string(),
4114 index,
4115 }
4116 .boxed_clone(),
4117 cx,
4118 );
4119 },
4120 );
4121 }
4122
4123 menu
4124 }))
4125 })
4126 }
4127
4128 fn render_permission_buttons_legacy(
4129 &self,
4130 options: &[acp::PermissionOption],
4131 entry_ix: usize,
4132 tool_call_id: acp::ToolCallId,
4133 cx: &Context<Self>,
4134 ) -> Div {
4135 let is_first = self.thread().is_some_and(|thread| {
4136 thread
4137 .read(cx)
4138 .first_tool_awaiting_confirmation()
4139 .is_some_and(|call| call.id == tool_call_id)
4140 });
4141 let mut seen_kinds: ArrayVec<acp::PermissionOptionKind, 3> = ArrayVec::new();
4142
4143 div()
4144 .p_1()
4145 .border_t_1()
4146 .border_color(self.tool_card_border_color(cx))
4147 .w_full()
4148 .v_flex()
4149 .gap_0p5()
4150 .children(options.iter().map(move |option| {
4151 let option_id = SharedString::from(option.option_id.0.clone());
4152 Button::new((option_id, entry_ix), option.name.clone())
4153 .map(|this| {
4154 let (this, action) = match option.kind {
4155 acp::PermissionOptionKind::AllowOnce => (
4156 this.icon(IconName::Check).icon_color(Color::Success),
4157 Some(&AllowOnce as &dyn Action),
4158 ),
4159 acp::PermissionOptionKind::AllowAlways => (
4160 this.icon(IconName::CheckDouble).icon_color(Color::Success),
4161 Some(&AllowAlways as &dyn Action),
4162 ),
4163 acp::PermissionOptionKind::RejectOnce => (
4164 this.icon(IconName::Close).icon_color(Color::Error),
4165 Some(&RejectOnce as &dyn Action),
4166 ),
4167 acp::PermissionOptionKind::RejectAlways | _ => {
4168 (this.icon(IconName::Close).icon_color(Color::Error), None)
4169 }
4170 };
4171
4172 let Some(action) = action else {
4173 return this;
4174 };
4175
4176 if !is_first || seen_kinds.contains(&option.kind) {
4177 return this;
4178 }
4179
4180 seen_kinds.push(option.kind);
4181
4182 this.key_binding(
4183 KeyBinding::for_action_in(action, &self.focus_handle, cx)
4184 .map(|kb| kb.size(rems_from_px(10.))),
4185 )
4186 })
4187 .icon_position(IconPosition::Start)
4188 .icon_size(IconSize::XSmall)
4189 .label_size(LabelSize::Small)
4190 .on_click(cx.listener({
4191 let tool_call_id = tool_call_id.clone();
4192 let option_id = option.option_id.clone();
4193 let option_kind = option.kind;
4194 move |this, _, window, cx| {
4195 this.authorize_tool_call(
4196 tool_call_id.clone(),
4197 option_id.clone(),
4198 option_kind,
4199 window,
4200 cx,
4201 );
4202 }
4203 }))
4204 }))
4205 }
4206
4207 fn render_diff_loading(&self, cx: &Context<Self>) -> AnyElement {
4208 let bar = |n: u64, width_class: &str| {
4209 let bg_color = cx.theme().colors().element_active;
4210 let base = h_flex().h_1().rounded_full();
4211
4212 let modified = match width_class {
4213 "w_4_5" => base.w_3_4(),
4214 "w_1_4" => base.w_1_4(),
4215 "w_2_4" => base.w_2_4(),
4216 "w_3_5" => base.w_3_5(),
4217 "w_2_5" => base.w_2_5(),
4218 _ => base.w_1_2(),
4219 };
4220
4221 modified.with_animation(
4222 ElementId::Integer(n),
4223 Animation::new(Duration::from_secs(2)).repeat(),
4224 move |tab, delta| {
4225 let delta = (delta - 0.15 * n as f32) / 0.7;
4226 let delta = 1.0 - (0.5 - delta).abs() * 2.;
4227 let delta = ease_in_out(delta.clamp(0., 1.));
4228 let delta = 0.1 + 0.9 * delta;
4229
4230 tab.bg(bg_color.opacity(delta))
4231 },
4232 )
4233 };
4234
4235 v_flex()
4236 .p_3()
4237 .gap_1()
4238 .rounded_b_md()
4239 .bg(cx.theme().colors().editor_background)
4240 .child(bar(0, "w_4_5"))
4241 .child(bar(1, "w_1_4"))
4242 .child(bar(2, "w_2_4"))
4243 .child(bar(3, "w_3_5"))
4244 .child(bar(4, "w_2_5"))
4245 .into_any_element()
4246 }
4247
4248 fn render_diff_editor(
4249 &self,
4250 entry_ix: usize,
4251 diff: &Entity<acp_thread::Diff>,
4252 tool_call: &ToolCall,
4253 has_failed: bool,
4254 cx: &Context<Self>,
4255 ) -> AnyElement {
4256 let tool_progress = matches!(
4257 &tool_call.status,
4258 ToolCallStatus::InProgress | ToolCallStatus::Pending
4259 );
4260
4261 let revealed_diff_editor = if let Some(entry) =
4262 self.entry_view_state.read(cx).entry(entry_ix)
4263 && let Some(editor) = entry.editor_for_diff(diff)
4264 && diff.read(cx).has_revealed_range(cx)
4265 {
4266 Some(editor)
4267 } else {
4268 None
4269 };
4270
4271 let show_top_border = !has_failed || revealed_diff_editor.is_some();
4272
4273 v_flex()
4274 .h_full()
4275 .when(show_top_border, |this| {
4276 this.border_t_1()
4277 .when(has_failed, |this| this.border_dashed())
4278 .border_color(self.tool_card_border_color(cx))
4279 })
4280 .child(if let Some(editor) = revealed_diff_editor {
4281 editor.into_any_element()
4282 } else if tool_progress && self.as_native_connection(cx).is_some() {
4283 self.render_diff_loading(cx)
4284 } else {
4285 Empty.into_any()
4286 })
4287 .into_any()
4288 }
4289
4290 /// Renders command lines with an optional expand/collapse button depending
4291 /// on the number of lines in `command_source`.
4292 fn render_collapsible_command(
4293 &self,
4294 is_preview: bool,
4295 command_source: &str,
4296 tool_call_id: &acp::ToolCallId,
4297 cx: &Context<Self>,
4298 ) -> Div {
4299 let expand_button_bg = self.tool_card_header_bg(cx);
4300 let expanded = self.expanded_terminal_commands.contains(tool_call_id);
4301
4302 let lines: Vec<&str> = command_source.lines().collect();
4303 let line_count = lines.len();
4304 let extra_lines = line_count.saturating_sub(MAX_COLLAPSED_LINES);
4305
4306 let show_expand_button = extra_lines > 0;
4307
4308 let max_lines = if expanded || !show_expand_button {
4309 usize::MAX
4310 } else {
4311 MAX_COLLAPSED_LINES
4312 };
4313
4314 let display_lines = lines.into_iter().take(max_lines);
4315
4316 let command_group =
4317 SharedString::from(format!("collapsible-command-group-{}", tool_call_id));
4318
4319 v_flex()
4320 .group(command_group.clone())
4321 .bg(self.tool_card_header_bg(cx))
4322 .child(
4323 v_flex()
4324 .p_1p5()
4325 .when(is_preview, |this| {
4326 this.pt_1().child(
4327 // Wrapping this label on a container with 24px height to avoid
4328 // layout shift when it changes from being a preview label
4329 // to the actual path where the command will run in
4330 h_flex().h_6().child(
4331 Label::new("Run Command")
4332 .buffer_font(cx)
4333 .size(LabelSize::XSmall)
4334 .color(Color::Muted),
4335 ),
4336 )
4337 })
4338 .children(display_lines.map(|line| {
4339 let text: SharedString = if line.is_empty() {
4340 " ".into()
4341 } else {
4342 line.to_string().into()
4343 };
4344
4345 Label::new(text).buffer_font(cx).size(LabelSize::Small)
4346 }))
4347 .child(
4348 div().absolute().top_1().right_1().child(
4349 CopyButton::new(command_source.to_string())
4350 .tooltip_label("Copy Command")
4351 .visible_on_hover(command_group),
4352 ),
4353 ),
4354 )
4355 .when(show_expand_button, |this| {
4356 let expand_icon = if expanded {
4357 IconName::ChevronUp
4358 } else {
4359 IconName::ChevronDown
4360 };
4361
4362 this.child(
4363 h_flex()
4364 .id(format!("expand-command-btn-{}", tool_call_id))
4365 .cursor_pointer()
4366 .when(!expanded, |s| s.absolute().bottom_0())
4367 .when(expanded, |s| s.mt_1())
4368 .w_full()
4369 .h_6()
4370 .gap_1()
4371 .justify_center()
4372 .border_t_1()
4373 .border_color(self.tool_card_border_color(cx))
4374 .bg(expand_button_bg.opacity(0.95))
4375 .hover(|s| s.bg(cx.theme().colors().element_hover))
4376 .when(!expanded, |this| {
4377 let label = match extra_lines {
4378 1 => "1 more line".to_string(),
4379 _ => format!("{} more lines", extra_lines),
4380 };
4381
4382 this.child(Label::new(label).size(LabelSize::Small).color(Color::Muted))
4383 })
4384 .child(
4385 Icon::new(expand_icon)
4386 .size(IconSize::Small)
4387 .color(Color::Muted),
4388 )
4389 .on_click(cx.listener({
4390 let tool_call_id = tool_call_id.clone();
4391 move |this, _event, _window, cx| {
4392 if expanded {
4393 this.expanded_terminal_commands.remove(&tool_call_id);
4394 } else {
4395 this.expanded_terminal_commands.insert(tool_call_id.clone());
4396 }
4397 cx.notify();
4398 }
4399 })),
4400 )
4401 })
4402 }
4403
4404 fn render_terminal_tool_call(
4405 &self,
4406 entry_ix: usize,
4407 terminal: &Entity<acp_thread::Terminal>,
4408 tool_call: &ToolCall,
4409 window: &Window,
4410 cx: &Context<Self>,
4411 ) -> AnyElement {
4412 let terminal_data = terminal.read(cx);
4413 let working_dir = terminal_data.working_dir();
4414 let command = terminal_data.command();
4415 let started_at = terminal_data.started_at();
4416
4417 let tool_failed = matches!(
4418 &tool_call.status,
4419 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed
4420 );
4421
4422 let output = terminal_data.output();
4423 let command_finished = output.is_some();
4424 let truncated_output =
4425 output.is_some_and(|output| output.original_content_len > output.content.len());
4426 let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
4427
4428 let command_failed = command_finished
4429 && output.is_some_and(|o| o.exit_status.is_some_and(|status| !status.success()));
4430
4431 let time_elapsed = if let Some(output) = output {
4432 output.ended_at.duration_since(started_at)
4433 } else {
4434 started_at.elapsed()
4435 };
4436
4437 let header_id =
4438 SharedString::from(format!("terminal-tool-header-{}", terminal.entity_id()));
4439 let header_group = SharedString::from(format!(
4440 "terminal-tool-header-group-{}",
4441 terminal.entity_id()
4442 ));
4443 let header_bg = cx
4444 .theme()
4445 .colors()
4446 .element_background
4447 .blend(cx.theme().colors().editor_foreground.opacity(0.025));
4448 let border_color = cx.theme().colors().border.opacity(0.6);
4449
4450 let working_dir = working_dir
4451 .as_ref()
4452 .map(|path| path.display().to_string())
4453 .unwrap_or_else(|| "current directory".to_string());
4454
4455 // Since the command's source is wrapped in a markdown code block
4456 // (```\n...\n```), we need to strip that so we're left with only the
4457 // command's content.
4458 let command_source = command.read(cx).source();
4459 let command_content = command_source
4460 .strip_prefix("```\n")
4461 .and_then(|s| s.strip_suffix("\n```"))
4462 .unwrap_or(&command_source);
4463
4464 let command_element =
4465 self.render_collapsible_command(false, command_content, &tool_call.id, cx);
4466
4467 let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
4468
4469 let header = h_flex()
4470 .id(header_id)
4471 .px_1p5()
4472 .pt_1()
4473 .flex_none()
4474 .gap_1()
4475 .justify_between()
4476 .rounded_t_md()
4477 .child(
4478 div()
4479 .id(("command-target-path", terminal.entity_id()))
4480 .w_full()
4481 .max_w_full()
4482 .overflow_x_scroll()
4483 .child(
4484 Label::new(working_dir)
4485 .buffer_font(cx)
4486 .size(LabelSize::XSmall)
4487 .color(Color::Muted),
4488 ),
4489 )
4490 .when(!command_finished, |header| {
4491 header
4492 .gap_1p5()
4493 .child(
4494 Button::new(
4495 SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
4496 "Stop",
4497 )
4498 .icon(IconName::Stop)
4499 .icon_position(IconPosition::Start)
4500 .icon_size(IconSize::Small)
4501 .icon_color(Color::Error)
4502 .label_size(LabelSize::Small)
4503 .tooltip(move |_window, cx| {
4504 Tooltip::with_meta(
4505 "Stop This Command",
4506 None,
4507 "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
4508 cx,
4509 )
4510 })
4511 .on_click({
4512 let terminal = terminal.clone();
4513 cx.listener(move |this, _event, _window, cx| {
4514 terminal.update(cx, |terminal, cx| {
4515 terminal.stop_by_user(cx);
4516 });
4517 this.cancel_generation(cx);
4518 })
4519 }),
4520 )
4521 .child(Divider::vertical())
4522 .child(
4523 Icon::new(IconName::ArrowCircle)
4524 .size(IconSize::XSmall)
4525 .color(Color::Info)
4526 .with_rotate_animation(2)
4527 )
4528 })
4529 .when(truncated_output, |header| {
4530 let tooltip = if let Some(output) = output {
4531 if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
4532 format!("Output exceeded terminal max lines and was \
4533 truncated, the model received the first {}.", format_file_size(output.content.len() as u64, true))
4534 } else {
4535 format!(
4536 "Output is {} long, and to avoid unexpected token usage, \
4537 only {} was sent back to the agent.",
4538 format_file_size(output.original_content_len as u64, true),
4539 format_file_size(output.content.len() as u64, true)
4540 )
4541 }
4542 } else {
4543 "Output was truncated".to_string()
4544 };
4545
4546 header.child(
4547 h_flex()
4548 .id(("terminal-tool-truncated-label", terminal.entity_id()))
4549 .gap_1()
4550 .child(
4551 Icon::new(IconName::Info)
4552 .size(IconSize::XSmall)
4553 .color(Color::Ignored),
4554 )
4555 .child(
4556 Label::new("Truncated")
4557 .color(Color::Muted)
4558 .size(LabelSize::XSmall),
4559 )
4560 .tooltip(Tooltip::text(tooltip)),
4561 )
4562 })
4563 .when(time_elapsed > Duration::from_secs(10), |header| {
4564 header.child(
4565 Label::new(format!("({})", duration_alt_display(time_elapsed)))
4566 .buffer_font(cx)
4567 .color(Color::Muted)
4568 .size(LabelSize::XSmall),
4569 )
4570 })
4571 .when(tool_failed || command_failed, |header| {
4572 header.child(
4573 div()
4574 .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
4575 .child(
4576 Icon::new(IconName::Close)
4577 .size(IconSize::Small)
4578 .color(Color::Error),
4579 )
4580 .when_some(output.and_then(|o| o.exit_status), |this, status| {
4581 this.tooltip(Tooltip::text(format!(
4582 "Exited with code {}",
4583 status.code().unwrap_or(-1),
4584 )))
4585 }),
4586 )
4587 })
4588 .child(
4589 Disclosure::new(
4590 SharedString::from(format!(
4591 "terminal-tool-disclosure-{}",
4592 terminal.entity_id()
4593 )),
4594 is_expanded,
4595 )
4596 .opened_icon(IconName::ChevronUp)
4597 .closed_icon(IconName::ChevronDown)
4598 .visible_on_hover(&header_group)
4599 .on_click(cx.listener({
4600 let id = tool_call.id.clone();
4601 move |this, _event, _window, _cx| {
4602 if is_expanded {
4603 this.expanded_tool_calls.remove(&id);
4604 } else {
4605 this.expanded_tool_calls.insert(id.clone());
4606 }
4607 }
4608 })),
4609 );
4610
4611 let terminal_view = self
4612 .entry_view_state
4613 .read(cx)
4614 .entry(entry_ix)
4615 .and_then(|entry| entry.terminal(terminal));
4616
4617 v_flex()
4618 .my_1p5()
4619 .mx_5()
4620 .border_1()
4621 .when(tool_failed || command_failed, |card| card.border_dashed())
4622 .border_color(border_color)
4623 .rounded_md()
4624 .overflow_hidden()
4625 .child(
4626 v_flex()
4627 .group(&header_group)
4628 .bg(header_bg)
4629 .text_xs()
4630 .child(header)
4631 .child(command_element),
4632 )
4633 .when(is_expanded && terminal_view.is_some(), |this| {
4634 this.child(
4635 div()
4636 .pt_2()
4637 .border_t_1()
4638 .when(tool_failed || command_failed, |card| card.border_dashed())
4639 .border_color(border_color)
4640 .bg(cx.theme().colors().editor_background)
4641 .rounded_b_md()
4642 .text_ui_sm(cx)
4643 .h_full()
4644 .children(terminal_view.map(|terminal_view| {
4645 let element = if terminal_view
4646 .read(cx)
4647 .content_mode(window, cx)
4648 .is_scrollable()
4649 {
4650 div().h_72().child(terminal_view).into_any_element()
4651 } else {
4652 terminal_view.into_any_element()
4653 };
4654
4655 div()
4656 .on_action(cx.listener(|_this, _: &NewTerminal, window, cx| {
4657 window.dispatch_action(NewThread.boxed_clone(), cx);
4658 cx.stop_propagation();
4659 }))
4660 .child(element)
4661 .into_any_element()
4662 })),
4663 )
4664 })
4665 .into_any()
4666 }
4667
4668 fn render_rules_item(&self, cx: &Context<Self>) -> Option<AnyElement> {
4669 let project_context = self
4670 .as_native_thread(cx)?
4671 .read(cx)
4672 .project_context()
4673 .read(cx);
4674
4675 let user_rules_text = if project_context.user_rules.is_empty() {
4676 None
4677 } else if project_context.user_rules.len() == 1 {
4678 let user_rules = &project_context.user_rules[0];
4679
4680 match user_rules.title.as_ref() {
4681 Some(title) => Some(format!("Using \"{title}\" user rule")),
4682 None => Some("Using user rule".into()),
4683 }
4684 } else {
4685 Some(format!(
4686 "Using {} user rules",
4687 project_context.user_rules.len()
4688 ))
4689 };
4690
4691 let first_user_rules_id = project_context
4692 .user_rules
4693 .first()
4694 .map(|user_rules| user_rules.uuid.0);
4695
4696 let rules_files = project_context
4697 .worktrees
4698 .iter()
4699 .filter_map(|worktree| worktree.rules_file.as_ref())
4700 .collect::<Vec<_>>();
4701
4702 let rules_file_text = match rules_files.as_slice() {
4703 &[] => None,
4704 &[rules_file] => Some(format!(
4705 "Using project {:?} file",
4706 rules_file.path_in_worktree
4707 )),
4708 rules_files => Some(format!("Using {} project rules files", rules_files.len())),
4709 };
4710
4711 if user_rules_text.is_none() && rules_file_text.is_none() {
4712 return None;
4713 }
4714
4715 let has_both = user_rules_text.is_some() && rules_file_text.is_some();
4716
4717 Some(
4718 h_flex()
4719 .px_2p5()
4720 .child(
4721 Icon::new(IconName::Attach)
4722 .size(IconSize::XSmall)
4723 .color(Color::Disabled),
4724 )
4725 .when_some(user_rules_text, |parent, user_rules_text| {
4726 parent.child(
4727 h_flex()
4728 .id("user-rules")
4729 .ml_1()
4730 .mr_1p5()
4731 .child(
4732 Label::new(user_rules_text)
4733 .size(LabelSize::XSmall)
4734 .color(Color::Muted)
4735 .truncate(),
4736 )
4737 .hover(|s| s.bg(cx.theme().colors().element_hover))
4738 .tooltip(Tooltip::text("View User Rules"))
4739 .on_click(move |_event, window, cx| {
4740 window.dispatch_action(
4741 Box::new(OpenRulesLibrary {
4742 prompt_to_select: first_user_rules_id,
4743 }),
4744 cx,
4745 )
4746 }),
4747 )
4748 })
4749 .when(has_both, |this| {
4750 this.child(
4751 Label::new("•")
4752 .size(LabelSize::XSmall)
4753 .color(Color::Disabled),
4754 )
4755 })
4756 .when_some(rules_file_text, |parent, rules_file_text| {
4757 parent.child(
4758 h_flex()
4759 .id("project-rules")
4760 .ml_1p5()
4761 .child(
4762 Label::new(rules_file_text)
4763 .size(LabelSize::XSmall)
4764 .color(Color::Muted),
4765 )
4766 .hover(|s| s.bg(cx.theme().colors().element_hover))
4767 .tooltip(Tooltip::text("View Project Rules"))
4768 .on_click(cx.listener(Self::handle_open_rules)),
4769 )
4770 })
4771 .into_any(),
4772 )
4773 }
4774
4775 fn render_empty_state_section_header(
4776 &self,
4777 label: impl Into<SharedString>,
4778 action_slot: Option<AnyElement>,
4779 cx: &mut Context<Self>,
4780 ) -> impl IntoElement {
4781 div().pl_1().pr_1p5().child(
4782 h_flex()
4783 .mt_2()
4784 .pl_1p5()
4785 .pb_1()
4786 .w_full()
4787 .justify_between()
4788 .border_b_1()
4789 .border_color(cx.theme().colors().border_variant)
4790 .child(
4791 Label::new(label.into())
4792 .size(LabelSize::Small)
4793 .color(Color::Muted),
4794 )
4795 .children(action_slot),
4796 )
4797 }
4798
4799 fn update_recent_history_from_cache(
4800 &mut self,
4801 history: &Entity<AcpThreadHistory>,
4802 cx: &mut Context<Self>,
4803 ) {
4804 self.recent_history_entries = history.read(cx).get_recent_sessions(3);
4805 self.hovered_recent_history_item = None;
4806 cx.notify();
4807 }
4808
4809 fn render_recent_history(&self, cx: &mut Context<Self>) -> AnyElement {
4810 let render_history = !self.recent_history_entries.is_empty();
4811
4812 v_flex()
4813 .size_full()
4814 .when(render_history, |this| {
4815 let recent_history = self.recent_history_entries.clone();
4816 this.justify_end().child(
4817 v_flex()
4818 .child(
4819 self.render_empty_state_section_header(
4820 "Recent",
4821 Some(
4822 Button::new("view-history", "View All")
4823 .style(ButtonStyle::Subtle)
4824 .label_size(LabelSize::Small)
4825 .key_binding(
4826 KeyBinding::for_action_in(
4827 &OpenHistory,
4828 &self.focus_handle(cx),
4829 cx,
4830 )
4831 .map(|kb| kb.size(rems_from_px(12.))),
4832 )
4833 .on_click(move |_event, window, cx| {
4834 window.dispatch_action(OpenHistory.boxed_clone(), cx);
4835 })
4836 .into_any_element(),
4837 ),
4838 cx,
4839 ),
4840 )
4841 .child(v_flex().p_1().pr_1p5().gap_1().children({
4842 let supports_delete = self.history.read(cx).supports_delete();
4843 recent_history
4844 .into_iter()
4845 .enumerate()
4846 .map(move |(index, entry)| {
4847 // TODO: Add keyboard navigation.
4848 let is_hovered =
4849 self.hovered_recent_history_item == Some(index);
4850 crate::acp::thread_history::AcpHistoryEntryElement::new(
4851 entry,
4852 cx.entity().downgrade(),
4853 )
4854 .hovered(is_hovered)
4855 .supports_delete(supports_delete)
4856 .on_hover(cx.listener(move |this, is_hovered, _window, cx| {
4857 if *is_hovered {
4858 this.hovered_recent_history_item = Some(index);
4859 } else if this.hovered_recent_history_item == Some(index) {
4860 this.hovered_recent_history_item = None;
4861 }
4862 cx.notify();
4863 }))
4864 .into_any_element()
4865 })
4866 })),
4867 )
4868 })
4869 .into_any()
4870 }
4871
4872 fn render_auth_required_state(
4873 &self,
4874 connection: &Rc<dyn AgentConnection>,
4875 description: Option<&Entity<Markdown>>,
4876 configuration_view: Option<&AnyView>,
4877 pending_auth_method: Option<&acp::AuthMethodId>,
4878 window: &mut Window,
4879 cx: &Context<Self>,
4880 ) -> impl IntoElement {
4881 let auth_methods = connection.auth_methods();
4882
4883 let agent_display_name = self
4884 .agent_server_store
4885 .read(cx)
4886 .agent_display_name(&ExternalAgentServerName(self.agent.name()))
4887 .unwrap_or_else(|| self.agent.name());
4888
4889 let show_fallback_description = auth_methods.len() > 1
4890 && configuration_view.is_none()
4891 && description.is_none()
4892 && pending_auth_method.is_none();
4893
4894 let auth_buttons = || {
4895 h_flex().justify_end().flex_wrap().gap_1().children(
4896 connection
4897 .auth_methods()
4898 .iter()
4899 .enumerate()
4900 .rev()
4901 .map(|(ix, method)| {
4902 let (method_id, name) = if self.project.read(cx).is_via_remote_server()
4903 && method.id.0.as_ref() == "oauth-personal"
4904 && method.name == "Log in with Google"
4905 {
4906 ("spawn-gemini-cli".into(), "Log in with Gemini CLI".into())
4907 } else {
4908 (method.id.0.clone(), method.name.clone())
4909 };
4910
4911 let agent_telemetry_id = connection.telemetry_id();
4912
4913 Button::new(method_id.clone(), name)
4914 .label_size(LabelSize::Small)
4915 .map(|this| {
4916 if ix == 0 {
4917 this.style(ButtonStyle::Tinted(TintColor::Accent))
4918 } else {
4919 this.style(ButtonStyle::Outlined)
4920 }
4921 })
4922 .when_some(method.description.clone(), |this, description| {
4923 this.tooltip(Tooltip::text(description))
4924 })
4925 .on_click({
4926 cx.listener(move |this, _, window, cx| {
4927 telemetry::event!(
4928 "Authenticate Agent Started",
4929 agent = agent_telemetry_id,
4930 method = method_id
4931 );
4932
4933 this.authenticate(
4934 acp::AuthMethodId::new(method_id.clone()),
4935 window,
4936 cx,
4937 )
4938 })
4939 })
4940 }),
4941 )
4942 };
4943
4944 if pending_auth_method.is_some() {
4945 return Callout::new()
4946 .icon(IconName::Info)
4947 .title(format!("Authenticating to {}…", agent_display_name))
4948 .actions_slot(
4949 Icon::new(IconName::ArrowCircle)
4950 .size(IconSize::Small)
4951 .color(Color::Muted)
4952 .with_rotate_animation(2)
4953 .into_any_element(),
4954 )
4955 .into_any_element();
4956 }
4957
4958 Callout::new()
4959 .icon(IconName::Info)
4960 .title(format!("Authenticate to {}", agent_display_name))
4961 .when(auth_methods.len() == 1, |this| {
4962 this.actions_slot(auth_buttons())
4963 })
4964 .description_slot(
4965 v_flex()
4966 .text_ui(cx)
4967 .map(|this| {
4968 if show_fallback_description {
4969 this.child(
4970 Label::new("Choose one of the following authentication options:")
4971 .size(LabelSize::Small)
4972 .color(Color::Muted),
4973 )
4974 } else {
4975 this.children(
4976 configuration_view
4977 .cloned()
4978 .map(|view| div().w_full().child(view)),
4979 )
4980 .children(description.map(|desc| {
4981 self.render_markdown(
4982 desc.clone(),
4983 default_markdown_style(false, false, window, cx),
4984 )
4985 }))
4986 }
4987 })
4988 .when(auth_methods.len() > 1, |this| {
4989 this.gap_1().child(auth_buttons())
4990 }),
4991 )
4992 .into_any_element()
4993 }
4994
4995 fn render_load_error(
4996 &self,
4997 e: &LoadError,
4998 window: &mut Window,
4999 cx: &mut Context<Self>,
5000 ) -> AnyElement {
5001 let (title, message, action_slot): (_, SharedString, _) = match e {
5002 LoadError::Unsupported {
5003 command: path,
5004 current_version,
5005 minimum_version,
5006 } => {
5007 return self.render_unsupported(path, current_version, minimum_version, window, cx);
5008 }
5009 LoadError::FailedToInstall(msg) => (
5010 "Failed to Install",
5011 msg.into(),
5012 Some(self.create_copy_button(msg.to_string()).into_any_element()),
5013 ),
5014 LoadError::Exited { status } => (
5015 "Failed to Launch",
5016 format!("Server exited with status {status}").into(),
5017 None,
5018 ),
5019 LoadError::Other(msg) => (
5020 "Failed to Launch",
5021 msg.into(),
5022 Some(self.create_copy_button(msg.to_string()).into_any_element()),
5023 ),
5024 };
5025
5026 Callout::new()
5027 .severity(Severity::Error)
5028 .icon(IconName::XCircleFilled)
5029 .title(title)
5030 .description(message)
5031 .actions_slot(div().children(action_slot))
5032 .into_any_element()
5033 }
5034
5035 fn render_unsupported(
5036 &self,
5037 path: &SharedString,
5038 version: &SharedString,
5039 minimum_version: &SharedString,
5040 _window: &mut Window,
5041 cx: &mut Context<Self>,
5042 ) -> AnyElement {
5043 let (heading_label, description_label) = (
5044 format!("Upgrade {} to work with Zed", self.agent.name()),
5045 if version.is_empty() {
5046 format!(
5047 "Currently using {}, which does not report a valid --version",
5048 path,
5049 )
5050 } else {
5051 format!(
5052 "Currently using {}, which is only version {} (need at least {minimum_version})",
5053 path, version
5054 )
5055 },
5056 );
5057
5058 v_flex()
5059 .w_full()
5060 .p_3p5()
5061 .gap_2p5()
5062 .border_t_1()
5063 .border_color(cx.theme().colors().border)
5064 .bg(linear_gradient(
5065 180.,
5066 linear_color_stop(cx.theme().colors().editor_background.opacity(0.4), 4.),
5067 linear_color_stop(cx.theme().status().info_background.opacity(0.), 0.),
5068 ))
5069 .child(
5070 v_flex().gap_0p5().child(Label::new(heading_label)).child(
5071 Label::new(description_label)
5072 .size(LabelSize::Small)
5073 .color(Color::Muted),
5074 ),
5075 )
5076 .into_any_element()
5077 }
5078
5079 fn activity_bar_bg(&self, cx: &Context<Self>) -> Hsla {
5080 let editor_bg_color = cx.theme().colors().editor_background;
5081 let active_color = cx.theme().colors().element_selected;
5082 editor_bg_color.blend(active_color.opacity(0.3))
5083 }
5084
5085 fn render_activity_bar(
5086 &self,
5087 thread_entity: &Entity<AcpThread>,
5088 window: &mut Window,
5089 cx: &Context<Self>,
5090 ) -> Option<AnyElement> {
5091 let thread = thread_entity.read(cx);
5092 let action_log = thread.action_log();
5093 let telemetry = ActionLogTelemetry::from(thread);
5094 let changed_buffers = action_log.read(cx).changed_buffers(cx);
5095 let plan = thread.plan();
5096
5097 if changed_buffers.is_empty() && plan.is_empty() && self.message_queue.is_empty() {
5098 return None;
5099 }
5100
5101 // Temporarily always enable ACP edit controls. This is temporary, to lessen the
5102 // impact of a nasty bug that causes them to sometimes be disabled when they shouldn't
5103 // be, which blocks you from being able to accept or reject edits. This switches the
5104 // bug to be that sometimes it's enabled when it shouldn't be, which at least doesn't
5105 // block you from using the panel.
5106 let pending_edits = false;
5107
5108 let use_keep_reject_buttons = !cx.has_flag::<AgentV2FeatureFlag>();
5109
5110 v_flex()
5111 .mt_1()
5112 .mx_2()
5113 .bg(self.activity_bar_bg(cx))
5114 .border_1()
5115 .border_b_0()
5116 .border_color(cx.theme().colors().border)
5117 .rounded_t_md()
5118 .shadow(vec![gpui::BoxShadow {
5119 color: gpui::black().opacity(0.15),
5120 offset: point(px(1.), px(-1.)),
5121 blur_radius: px(3.),
5122 spread_radius: px(0.),
5123 }])
5124 .when(!plan.is_empty(), |this| {
5125 this.child(self.render_plan_summary(plan, window, cx))
5126 .when(self.plan_expanded, |parent| {
5127 parent.child(self.render_plan_entries(plan, window, cx))
5128 })
5129 })
5130 .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
5131 this.child(Divider::horizontal().color(DividerColor::Border))
5132 })
5133 .when(!changed_buffers.is_empty(), |this| {
5134 this.child(self.render_edits_summary(
5135 &changed_buffers,
5136 self.edits_expanded,
5137 pending_edits,
5138 use_keep_reject_buttons,
5139 cx,
5140 ))
5141 .when(self.edits_expanded, |parent| {
5142 parent.child(self.render_edited_files(
5143 action_log,
5144 telemetry.clone(),
5145 &changed_buffers,
5146 pending_edits,
5147 use_keep_reject_buttons,
5148 cx,
5149 ))
5150 })
5151 })
5152 .when(!self.message_queue.is_empty(), |this| {
5153 this.when(!plan.is_empty() || !changed_buffers.is_empty(), |this| {
5154 this.child(Divider::horizontal().color(DividerColor::Border))
5155 })
5156 .child(self.render_message_queue_summary(window, cx))
5157 .when(self.queue_expanded, |parent| {
5158 parent.child(self.render_message_queue_entries(window, cx))
5159 })
5160 })
5161 .into_any()
5162 .into()
5163 }
5164
5165 fn render_plan_summary(
5166 &self,
5167 plan: &Plan,
5168 window: &mut Window,
5169 cx: &Context<Self>,
5170 ) -> impl IntoElement {
5171 let stats = plan.stats();
5172
5173 let title = if let Some(entry) = stats.in_progress_entry
5174 && !self.plan_expanded
5175 {
5176 h_flex()
5177 .cursor_default()
5178 .relative()
5179 .w_full()
5180 .gap_1()
5181 .truncate()
5182 .child(
5183 Label::new("Current:")
5184 .size(LabelSize::Small)
5185 .color(Color::Muted),
5186 )
5187 .child(
5188 div()
5189 .text_xs()
5190 .text_color(cx.theme().colors().text_muted)
5191 .line_clamp(1)
5192 .child(MarkdownElement::new(
5193 entry.content.clone(),
5194 plan_label_markdown_style(&entry.status, window, cx),
5195 )),
5196 )
5197 .when(stats.pending > 0, |this| {
5198 this.child(
5199 h_flex()
5200 .absolute()
5201 .top_0()
5202 .right_0()
5203 .h_full()
5204 .child(div().min_w_8().h_full().bg(linear_gradient(
5205 90.,
5206 linear_color_stop(self.activity_bar_bg(cx), 1.),
5207 linear_color_stop(self.activity_bar_bg(cx).opacity(0.2), 0.),
5208 )))
5209 .child(
5210 div().pr_0p5().bg(self.activity_bar_bg(cx)).child(
5211 Label::new(format!("{} left", stats.pending))
5212 .size(LabelSize::Small)
5213 .color(Color::Muted),
5214 ),
5215 ),
5216 )
5217 })
5218 } else {
5219 let status_label = if stats.pending == 0 {
5220 "All Done".to_string()
5221 } else if stats.completed == 0 {
5222 format!("{} Tasks", plan.entries.len())
5223 } else {
5224 format!("{}/{}", stats.completed, plan.entries.len())
5225 };
5226
5227 h_flex()
5228 .w_full()
5229 .gap_1()
5230 .justify_between()
5231 .child(
5232 Label::new("Plan")
5233 .size(LabelSize::Small)
5234 .color(Color::Muted),
5235 )
5236 .child(
5237 Label::new(status_label)
5238 .size(LabelSize::Small)
5239 .color(Color::Muted)
5240 .mr_1(),
5241 )
5242 };
5243
5244 h_flex()
5245 .id("plan_summary")
5246 .p_1()
5247 .w_full()
5248 .gap_1()
5249 .when(self.plan_expanded, |this| {
5250 this.border_b_1().border_color(cx.theme().colors().border)
5251 })
5252 .child(Disclosure::new("plan_disclosure", self.plan_expanded))
5253 .child(title)
5254 .on_click(cx.listener(|this, _, _, cx| {
5255 this.plan_expanded = !this.plan_expanded;
5256 cx.notify();
5257 }))
5258 }
5259
5260 fn render_plan_entries(
5261 &self,
5262 plan: &Plan,
5263 window: &mut Window,
5264 cx: &Context<Self>,
5265 ) -> impl IntoElement {
5266 v_flex()
5267 .id("plan_items_list")
5268 .max_h_40()
5269 .overflow_y_scroll()
5270 .children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
5271 let element = h_flex()
5272 .py_1()
5273 .px_2()
5274 .gap_2()
5275 .justify_between()
5276 .bg(cx.theme().colors().editor_background)
5277 .when(index < plan.entries.len() - 1, |parent| {
5278 parent.border_color(cx.theme().colors().border).border_b_1()
5279 })
5280 .child(
5281 h_flex()
5282 .id(("plan_entry", index))
5283 .gap_1p5()
5284 .max_w_full()
5285 .overflow_x_scroll()
5286 .text_xs()
5287 .text_color(cx.theme().colors().text_muted)
5288 .child(match entry.status {
5289 acp::PlanEntryStatus::InProgress => {
5290 Icon::new(IconName::TodoProgress)
5291 .size(IconSize::Small)
5292 .color(Color::Accent)
5293 .with_rotate_animation(2)
5294 .into_any_element()
5295 }
5296 acp::PlanEntryStatus::Completed => {
5297 Icon::new(IconName::TodoComplete)
5298 .size(IconSize::Small)
5299 .color(Color::Success)
5300 .into_any_element()
5301 }
5302 acp::PlanEntryStatus::Pending | _ => {
5303 Icon::new(IconName::TodoPending)
5304 .size(IconSize::Small)
5305 .color(Color::Muted)
5306 .into_any_element()
5307 }
5308 })
5309 .child(MarkdownElement::new(
5310 entry.content.clone(),
5311 plan_label_markdown_style(&entry.status, window, cx),
5312 )),
5313 );
5314
5315 Some(element)
5316 }))
5317 .into_any_element()
5318 }
5319
5320 fn render_edits_summary(
5321 &self,
5322 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
5323 expanded: bool,
5324 pending_edits: bool,
5325 use_keep_reject_buttons: bool,
5326 cx: &Context<Self>,
5327 ) -> Div {
5328 const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
5329
5330 let focus_handle = self.focus_handle(cx);
5331
5332 h_flex()
5333 .p_1()
5334 .justify_between()
5335 .flex_wrap()
5336 .when(expanded, |this| {
5337 this.border_b_1().border_color(cx.theme().colors().border)
5338 })
5339 .child(
5340 h_flex()
5341 .id("edits-container")
5342 .cursor_pointer()
5343 .gap_1()
5344 .child(Disclosure::new("edits-disclosure", expanded))
5345 .map(|this| {
5346 if pending_edits {
5347 this.child(
5348 Label::new(format!(
5349 "Editing {} {}…",
5350 changed_buffers.len(),
5351 if changed_buffers.len() == 1 {
5352 "file"
5353 } else {
5354 "files"
5355 }
5356 ))
5357 .color(Color::Muted)
5358 .size(LabelSize::Small)
5359 .with_animation(
5360 "edit-label",
5361 Animation::new(Duration::from_secs(2))
5362 .repeat()
5363 .with_easing(pulsating_between(0.3, 0.7)),
5364 |label, delta| label.alpha(delta),
5365 ),
5366 )
5367 } else {
5368 let stats = DiffStats::all_files(changed_buffers, cx);
5369 let dot_divider = || {
5370 Label::new("•")
5371 .size(LabelSize::XSmall)
5372 .color(Color::Disabled)
5373 };
5374
5375 this.child(
5376 Label::new("Edits")
5377 .size(LabelSize::Small)
5378 .color(Color::Muted),
5379 )
5380 .child(dot_divider())
5381 .child(
5382 Label::new(format!(
5383 "{} {}",
5384 changed_buffers.len(),
5385 if changed_buffers.len() == 1 {
5386 "file"
5387 } else {
5388 "files"
5389 }
5390 ))
5391 .size(LabelSize::Small)
5392 .color(Color::Muted),
5393 )
5394 .child(dot_divider())
5395 .child(DiffStat::new(
5396 "total",
5397 stats.lines_added as usize,
5398 stats.lines_removed as usize,
5399 ))
5400 }
5401 })
5402 .on_click(cx.listener(|this, _, _, cx| {
5403 this.edits_expanded = !this.edits_expanded;
5404 cx.notify();
5405 })),
5406 )
5407 .when(use_keep_reject_buttons, |this| {
5408 this.child(
5409 h_flex()
5410 .gap_1()
5411 .child(
5412 IconButton::new("review-changes", IconName::ListTodo)
5413 .icon_size(IconSize::Small)
5414 .tooltip({
5415 let focus_handle = focus_handle.clone();
5416 move |_window, cx| {
5417 Tooltip::for_action_in(
5418 "Review Changes",
5419 &OpenAgentDiff,
5420 &focus_handle,
5421 cx,
5422 )
5423 }
5424 })
5425 .on_click(cx.listener(|_, _, window, cx| {
5426 window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
5427 })),
5428 )
5429 .child(Divider::vertical().color(DividerColor::Border))
5430 .child(
5431 Button::new("reject-all-changes", "Reject All")
5432 .label_size(LabelSize::Small)
5433 .disabled(pending_edits)
5434 .when(pending_edits, |this| {
5435 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
5436 })
5437 .key_binding(
5438 KeyBinding::for_action_in(
5439 &RejectAll,
5440 &focus_handle.clone(),
5441 cx,
5442 )
5443 .map(|kb| kb.size(rems_from_px(10.))),
5444 )
5445 .on_click(cx.listener(move |this, _, window, cx| {
5446 this.reject_all(&RejectAll, window, cx);
5447 })),
5448 )
5449 .child(
5450 Button::new("keep-all-changes", "Keep All")
5451 .label_size(LabelSize::Small)
5452 .disabled(pending_edits)
5453 .when(pending_edits, |this| {
5454 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
5455 })
5456 .key_binding(
5457 KeyBinding::for_action_in(&KeepAll, &focus_handle, cx)
5458 .map(|kb| kb.size(rems_from_px(10.))),
5459 )
5460 .on_click(cx.listener(move |this, _, window, cx| {
5461 this.keep_all(&KeepAll, window, cx);
5462 })),
5463 ),
5464 )
5465 })
5466 .when(!use_keep_reject_buttons, |this| {
5467 this.child(
5468 Button::new("review-changes", "Review Changes")
5469 .label_size(LabelSize::Small)
5470 .key_binding(
5471 KeyBinding::for_action_in(
5472 &git_ui::project_diff::Diff,
5473 &focus_handle,
5474 cx,
5475 )
5476 .map(|kb| kb.size(rems_from_px(10.))),
5477 )
5478 .on_click(cx.listener(move |_, _, window, cx| {
5479 window.dispatch_action(git_ui::project_diff::Diff.boxed_clone(), cx);
5480 })),
5481 )
5482 })
5483 }
5484
5485 fn render_edited_files(
5486 &self,
5487 action_log: &Entity<ActionLog>,
5488 telemetry: ActionLogTelemetry,
5489 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
5490 pending_edits: bool,
5491 use_keep_reject_buttons: bool,
5492 cx: &Context<Self>,
5493 ) -> impl IntoElement {
5494 let editor_bg_color = cx.theme().colors().editor_background;
5495
5496 v_flex()
5497 .id("edited_files_list")
5498 .max_h_40()
5499 .overflow_y_scroll()
5500 .children(
5501 changed_buffers
5502 .iter()
5503 .enumerate()
5504 .flat_map(|(index, (buffer, diff))| {
5505 let file = buffer.read(cx).file()?;
5506 let path = file.path();
5507 let path_style = file.path_style(cx);
5508 let separator = file.path_style(cx).primary_separator();
5509
5510 let file_path = path.parent().and_then(|parent| {
5511 if parent.is_empty() {
5512 None
5513 } else {
5514 Some(
5515 Label::new(format!(
5516 "{}{separator}",
5517 parent.display(path_style)
5518 ))
5519 .color(Color::Muted)
5520 .size(LabelSize::XSmall)
5521 .buffer_font(cx),
5522 )
5523 }
5524 });
5525
5526 let file_name = path.file_name().map(|name| {
5527 Label::new(name.to_string())
5528 .size(LabelSize::XSmall)
5529 .buffer_font(cx)
5530 .ml_1()
5531 });
5532
5533 let full_path = path.display(path_style).to_string();
5534
5535 let file_icon = FileIcons::get_icon(path.as_std_path(), cx)
5536 .map(Icon::from_path)
5537 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
5538 .unwrap_or_else(|| {
5539 Icon::new(IconName::File)
5540 .color(Color::Muted)
5541 .size(IconSize::Small)
5542 });
5543
5544 let overlay_gradient = linear_gradient(
5545 90.,
5546 linear_color_stop(editor_bg_color, 1.),
5547 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
5548 );
5549
5550 let file_stats = DiffStats::single_file(buffer.read(cx), diff.read(cx), cx);
5551
5552 let element = h_flex()
5553 .group("edited-code")
5554 .id(("file-container", index))
5555 .py_1()
5556 .pl_2()
5557 .pr_1()
5558 .gap_2()
5559 .justify_between()
5560 .bg(editor_bg_color)
5561 .when(index < changed_buffers.len() - 1, |parent| {
5562 parent.border_color(cx.theme().colors().border).border_b_1()
5563 })
5564 .child(
5565 h_flex()
5566 .id(("file-name-row", index))
5567 .relative()
5568 .pr_8()
5569 .w_full()
5570 .child(
5571 h_flex()
5572 .id(("file-name-path", index))
5573 .cursor_pointer()
5574 .pr_0p5()
5575 .gap_0p5()
5576 .hover(|s| s.bg(cx.theme().colors().element_hover))
5577 .rounded_xs()
5578 .child(file_icon)
5579 .children(file_name)
5580 .children(file_path)
5581 .child(
5582 DiffStat::new(
5583 "file",
5584 file_stats.lines_added as usize,
5585 file_stats.lines_removed as usize,
5586 )
5587 .label_size(LabelSize::XSmall),
5588 )
5589 .tooltip(move |_, cx| {
5590 Tooltip::with_meta(
5591 "Go to File",
5592 None,
5593 full_path.clone(),
5594 cx,
5595 )
5596 })
5597 .on_click({
5598 let buffer = buffer.clone();
5599 cx.listener(move |this, _, window, cx| {
5600 this.open_edited_buffer(&buffer, window, cx);
5601 })
5602 }),
5603 )
5604 .child(
5605 div()
5606 .absolute()
5607 .h_full()
5608 .w_12()
5609 .top_0()
5610 .bottom_0()
5611 .right_0()
5612 .bg(overlay_gradient),
5613 ),
5614 )
5615 .when(use_keep_reject_buttons, |parent| {
5616 parent.child(
5617 h_flex()
5618 .gap_1()
5619 .visible_on_hover("edited-code")
5620 .child(
5621 Button::new("review", "Review")
5622 .label_size(LabelSize::Small)
5623 .on_click({
5624 let buffer = buffer.clone();
5625 let workspace = self.workspace.clone();
5626 cx.listener(move |_, _, window, cx| {
5627 let Some(workspace) = workspace.upgrade() else {
5628 return;
5629 };
5630 let Some(file) = buffer.read(cx).file() else {
5631 return;
5632 };
5633 let project_path = project::ProjectPath {
5634 worktree_id: file.worktree_id(cx),
5635 path: file.path().clone(),
5636 };
5637 workspace.update(cx, |workspace, cx| {
5638 git_ui::project_diff::ProjectDiff::deploy_at_project_path(
5639 workspace,
5640 project_path,
5641 window,
5642 cx,
5643 );
5644 });
5645 })
5646 }),
5647 )
5648 .child(Divider::vertical().color(DividerColor::BorderVariant))
5649 .child(
5650 Button::new("reject-file", "Reject")
5651 .label_size(LabelSize::Small)
5652 .disabled(pending_edits)
5653 .on_click({
5654 let buffer = buffer.clone();
5655 let action_log = action_log.clone();
5656 let telemetry = telemetry.clone();
5657 move |_, _, cx| {
5658 action_log.update(cx, |action_log, cx| {
5659 action_log
5660 .reject_edits_in_ranges(
5661 buffer.clone(),
5662 vec![Anchor::min_max_range_for_buffer(
5663 buffer.read(cx).remote_id(),
5664 )],
5665 Some(telemetry.clone()),
5666 cx,
5667 )
5668 .detach_and_log_err(cx);
5669 })
5670 }
5671 }),
5672 )
5673 .child(
5674 Button::new("keep-file", "Keep")
5675 .label_size(LabelSize::Small)
5676 .disabled(pending_edits)
5677 .on_click({
5678 let buffer = buffer.clone();
5679 let action_log = action_log.clone();
5680 let telemetry = telemetry.clone();
5681 move |_, _, cx| {
5682 action_log.update(cx, |action_log, cx| {
5683 action_log.keep_edits_in_range(
5684 buffer.clone(),
5685 Anchor::min_max_range_for_buffer(
5686 buffer.read(cx).remote_id(),
5687 ),
5688 Some(telemetry.clone()),
5689 cx,
5690 );
5691 })
5692 }
5693 }),
5694 ),
5695 )
5696 })
5697 .when(!use_keep_reject_buttons, |parent| {
5698 parent.child(
5699 h_flex()
5700 .gap_1()
5701 .visible_on_hover("edited-code")
5702 .child(
5703 Button::new("review", "Review")
5704 .label_size(LabelSize::Small)
5705 .on_click({
5706 let buffer = buffer.clone();
5707 let workspace = self.workspace.clone();
5708 cx.listener(move |_, _, window, cx| {
5709 let Some(workspace) = workspace.upgrade() else {
5710 return;
5711 };
5712 let Some(file) = buffer.read(cx).file() else {
5713 return;
5714 };
5715 let project_path = project::ProjectPath {
5716 worktree_id: file.worktree_id(cx),
5717 path: file.path().clone(),
5718 };
5719 workspace.update(cx, |workspace, cx| {
5720 git_ui::project_diff::ProjectDiff::deploy_at_project_path(
5721 workspace,
5722 project_path,
5723 window,
5724 cx,
5725 );
5726 });
5727 })
5728 }),
5729 ),
5730 )
5731 });
5732
5733 Some(element)
5734 }),
5735 )
5736 .into_any_element()
5737 }
5738
5739 fn render_message_queue_summary(
5740 &self,
5741 _window: &mut Window,
5742 cx: &Context<Self>,
5743 ) -> impl IntoElement {
5744 let queue_count = self.message_queue.len();
5745 let title: SharedString = if queue_count == 1 {
5746 "1 Queued Message".into()
5747 } else {
5748 format!("{} Queued Messages", queue_count).into()
5749 };
5750
5751 h_flex()
5752 .p_1()
5753 .w_full()
5754 .gap_1()
5755 .justify_between()
5756 .when(self.queue_expanded, |this| {
5757 this.border_b_1().border_color(cx.theme().colors().border)
5758 })
5759 .child(
5760 h_flex()
5761 .id("queue_summary")
5762 .gap_1()
5763 .child(Disclosure::new("queue_disclosure", self.queue_expanded))
5764 .child(Label::new(title).size(LabelSize::Small).color(Color::Muted))
5765 .on_click(cx.listener(|this, _, _, cx| {
5766 this.queue_expanded = !this.queue_expanded;
5767 cx.notify();
5768 })),
5769 )
5770 .child(
5771 Button::new("clear_queue", "Clear All")
5772 .label_size(LabelSize::Small)
5773 .key_binding(KeyBinding::for_action(&ClearMessageQueue, cx))
5774 .on_click(cx.listener(|this, _, _, cx| {
5775 this.message_queue.clear();
5776 cx.notify();
5777 })),
5778 )
5779 }
5780
5781 fn render_message_queue_entries(
5782 &self,
5783 _window: &mut Window,
5784 cx: &Context<Self>,
5785 ) -> impl IntoElement {
5786 let message_editor = self.message_editor.read(cx);
5787 let focus_handle = message_editor.focus_handle(cx);
5788
5789 v_flex()
5790 .id("message_queue_list")
5791 .max_h_40()
5792 .overflow_y_scroll()
5793 .children(
5794 self.message_queue
5795 .iter()
5796 .enumerate()
5797 .map(|(index, queued)| {
5798 let is_next = index == 0;
5799 let icon_color = if is_next { Color::Accent } else { Color::Muted };
5800 let queue_len = self.message_queue.len();
5801
5802 let preview = queued
5803 .content
5804 .iter()
5805 .find_map(|block| match block {
5806 acp::ContentBlock::Text(text) => {
5807 text.text.lines().next().map(str::to_owned)
5808 }
5809 _ => None,
5810 })
5811 .unwrap_or_default();
5812
5813 h_flex()
5814 .group("queue_entry")
5815 .w_full()
5816 .p_1()
5817 .pl_2()
5818 .gap_1()
5819 .justify_between()
5820 .bg(cx.theme().colors().editor_background)
5821 .when(index < queue_len - 1, |parent| {
5822 parent.border_color(cx.theme().colors().border).border_b_1()
5823 })
5824 .child(
5825 h_flex()
5826 .id(("queued_prompt", index))
5827 .min_w_0()
5828 .w_full()
5829 .gap_1p5()
5830 .child(
5831 Icon::new(IconName::Circle)
5832 .size(IconSize::Small)
5833 .color(icon_color),
5834 )
5835 .child(
5836 Label::new(preview)
5837 .size(LabelSize::XSmall)
5838 .color(Color::Muted)
5839 .buffer_font(cx)
5840 .truncate(),
5841 )
5842 .when(is_next, |this| {
5843 this.tooltip(Tooltip::text("Next Prompt in the Queue"))
5844 }),
5845 )
5846 .child(
5847 h_flex()
5848 .flex_none()
5849 .gap_1()
5850 .visible_on_hover("queue_entry")
5851 .child(
5852 Button::new(("delete", index), "Remove")
5853 .label_size(LabelSize::Small)
5854 .on_click(cx.listener(move |this, _, _, cx| {
5855 if index < this.message_queue.len() {
5856 this.message_queue.remove(index);
5857 cx.notify();
5858 }
5859 })),
5860 )
5861 .child(
5862 Button::new(("send_now", index), "Send Now")
5863 .style(ButtonStyle::Outlined)
5864 .label_size(LabelSize::Small)
5865 .when(is_next, |this| {
5866 this.key_binding(
5867 KeyBinding::for_action_in(
5868 &SendNextQueuedMessage,
5869 &focus_handle.clone(),
5870 cx,
5871 )
5872 .map(|kb| kb.size(rems_from_px(10.))),
5873 )
5874 })
5875 .on_click(cx.listener(move |this, _, window, cx| {
5876 this.send_queued_message_at_index(
5877 index, true, window, cx,
5878 );
5879 })),
5880 ),
5881 )
5882 }),
5883 )
5884 .into_any_element()
5885 }
5886
5887 fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
5888 let focus_handle = self.message_editor.focus_handle(cx);
5889 let editor_bg_color = cx.theme().colors().editor_background;
5890 let (expand_icon, expand_tooltip) = if self.editor_expanded {
5891 (IconName::Minimize, "Minimize Message Editor")
5892 } else {
5893 (IconName::Maximize, "Expand Message Editor")
5894 };
5895
5896 let backdrop = div()
5897 .size_full()
5898 .absolute()
5899 .inset_0()
5900 .bg(cx.theme().colors().panel_background)
5901 .opacity(0.8)
5902 .block_mouse_except_scroll();
5903
5904 let enable_editor = match self.thread_state {
5905 ThreadState::Ready { .. } => true,
5906 ThreadState::Loading { .. }
5907 | ThreadState::Unauthenticated { .. }
5908 | ThreadState::LoadError(..) => false,
5909 };
5910
5911 v_flex()
5912 .on_action(cx.listener(Self::expand_message_editor))
5913 .p_2()
5914 .gap_2()
5915 .border_t_1()
5916 .border_color(cx.theme().colors().border)
5917 .bg(editor_bg_color)
5918 .when(self.editor_expanded, |this| {
5919 this.h(vh(0.8, window)).size_full().justify_between()
5920 })
5921 .child(
5922 v_flex()
5923 .relative()
5924 .size_full()
5925 .pt_1()
5926 .pr_2p5()
5927 .child(self.message_editor.clone())
5928 .child(
5929 h_flex()
5930 .absolute()
5931 .top_0()
5932 .right_0()
5933 .opacity(0.5)
5934 .hover(|this| this.opacity(1.0))
5935 .child(
5936 IconButton::new("toggle-height", expand_icon)
5937 .icon_size(IconSize::Small)
5938 .icon_color(Color::Muted)
5939 .tooltip({
5940 move |_window, cx| {
5941 Tooltip::for_action_in(
5942 expand_tooltip,
5943 &ExpandMessageEditor,
5944 &focus_handle,
5945 cx,
5946 )
5947 }
5948 })
5949 .on_click(cx.listener(|this, _, window, cx| {
5950 this.expand_message_editor(
5951 &ExpandMessageEditor,
5952 window,
5953 cx,
5954 );
5955 })),
5956 ),
5957 ),
5958 )
5959 .child(
5960 h_flex()
5961 .flex_none()
5962 .flex_wrap()
5963 .justify_between()
5964 .child(
5965 h_flex()
5966 .gap_0p5()
5967 .child(self.render_add_context_button(cx))
5968 .child(self.render_follow_toggle(cx))
5969 .children(self.render_burn_mode_toggle(cx)),
5970 )
5971 .child(
5972 h_flex()
5973 .gap_1()
5974 .children(self.render_token_usage(cx))
5975 .children(self.profile_selector.clone())
5976 // Either config_options_view OR (mode_selector + model_selector)
5977 .children(self.config_options_view.clone())
5978 .when(self.config_options_view.is_none(), |this| {
5979 this.children(self.mode_selector().cloned())
5980 .children(self.model_selector.clone())
5981 })
5982 .child(self.render_send_button(cx)),
5983 ),
5984 )
5985 .when(!enable_editor, |this| this.child(backdrop))
5986 .into_any()
5987 }
5988
5989 pub(crate) fn as_native_connection(
5990 &self,
5991 cx: &App,
5992 ) -> Option<Rc<agent::NativeAgentConnection>> {
5993 let acp_thread = self.thread()?.read(cx);
5994 acp_thread.connection().clone().downcast()
5995 }
5996
5997 pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
5998 let acp_thread = self.thread()?.read(cx);
5999 self.as_native_connection(cx)?
6000 .thread(acp_thread.session_id(), cx)
6001 }
6002
6003 fn is_imported_thread(&self, cx: &App) -> bool {
6004 let Some(thread) = self.as_native_thread(cx) else {
6005 return false;
6006 };
6007 thread.read(cx).is_imported()
6008 }
6009
6010 fn is_using_zed_ai_models(&self, cx: &App) -> bool {
6011 self.as_native_thread(cx)
6012 .and_then(|thread| thread.read(cx).model())
6013 .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
6014 }
6015
6016 fn supports_split_token_display(&self, cx: &App) -> bool {
6017 self.as_native_thread(cx)
6018 .and_then(|thread| thread.read(cx).model())
6019 .is_some_and(|model| model.supports_split_token_display())
6020 }
6021
6022 fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
6023 let thread = self.thread()?.read(cx);
6024 let usage = thread.token_usage()?;
6025 let is_generating = thread.status() != ThreadStatus::Idle;
6026 let show_split = self.supports_split_token_display(cx);
6027
6028 let separator_color = Color::Custom(cx.theme().colors().text_muted.opacity(0.5));
6029 let token_label = |text: String, animation_id: &'static str| {
6030 Label::new(text)
6031 .size(LabelSize::Small)
6032 .color(Color::Muted)
6033 .map(|label| {
6034 if is_generating {
6035 label
6036 .with_animation(
6037 animation_id,
6038 Animation::new(Duration::from_secs(2))
6039 .repeat()
6040 .with_easing(pulsating_between(0.3, 0.8)),
6041 |label, delta| label.alpha(delta),
6042 )
6043 .into_any()
6044 } else {
6045 label.into_any_element()
6046 }
6047 })
6048 };
6049
6050 if show_split {
6051 let max_output_tokens = self
6052 .as_native_thread(cx)
6053 .and_then(|thread| thread.read(cx).model())
6054 .and_then(|model| model.max_output_tokens())
6055 .unwrap_or(0);
6056
6057 let input = crate::text_thread_editor::humanize_token_count(usage.input_tokens);
6058 let input_max = crate::text_thread_editor::humanize_token_count(
6059 usage.max_tokens.saturating_sub(max_output_tokens),
6060 );
6061 let output = crate::text_thread_editor::humanize_token_count(usage.output_tokens);
6062 let output_max = crate::text_thread_editor::humanize_token_count(max_output_tokens);
6063
6064 Some(
6065 h_flex()
6066 .flex_shrink_0()
6067 .gap_1()
6068 .mr_1p5()
6069 .child(
6070 h_flex()
6071 .gap_0p5()
6072 .child(
6073 Icon::new(IconName::ArrowUp)
6074 .size(IconSize::XSmall)
6075 .color(Color::Muted),
6076 )
6077 .child(token_label(input, "input-tokens-label"))
6078 .child(
6079 Label::new("/")
6080 .size(LabelSize::Small)
6081 .color(separator_color),
6082 )
6083 .child(
6084 Label::new(input_max)
6085 .size(LabelSize::Small)
6086 .color(Color::Muted),
6087 ),
6088 )
6089 .child(
6090 h_flex()
6091 .gap_0p5()
6092 .child(
6093 Icon::new(IconName::ArrowDown)
6094 .size(IconSize::XSmall)
6095 .color(Color::Muted),
6096 )
6097 .child(token_label(output, "output-tokens-label"))
6098 .child(
6099 Label::new("/")
6100 .size(LabelSize::Small)
6101 .color(separator_color),
6102 )
6103 .child(
6104 Label::new(output_max)
6105 .size(LabelSize::Small)
6106 .color(Color::Muted),
6107 ),
6108 ),
6109 )
6110 } else {
6111 let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
6112 let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
6113
6114 Some(
6115 h_flex()
6116 .flex_shrink_0()
6117 .gap_0p5()
6118 .mr_1p5()
6119 .child(token_label(used, "used-tokens-label"))
6120 .child(
6121 Label::new("/")
6122 .size(LabelSize::Small)
6123 .color(separator_color),
6124 )
6125 .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
6126 )
6127 }
6128 }
6129
6130 fn toggle_burn_mode(
6131 &mut self,
6132 _: &ToggleBurnMode,
6133 _window: &mut Window,
6134 cx: &mut Context<Self>,
6135 ) {
6136 let Some(thread) = self.as_native_thread(cx) else {
6137 return;
6138 };
6139
6140 thread.update(cx, |thread, cx| {
6141 let current_mode = thread.completion_mode();
6142 thread.set_completion_mode(
6143 match current_mode {
6144 CompletionMode::Burn => CompletionMode::Normal,
6145 CompletionMode::Normal => CompletionMode::Burn,
6146 },
6147 cx,
6148 );
6149 });
6150 }
6151
6152 fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
6153 let Some(thread) = self.thread() else {
6154 return;
6155 };
6156 let telemetry = ActionLogTelemetry::from(thread.read(cx));
6157 let action_log = thread.read(cx).action_log().clone();
6158 action_log.update(cx, |action_log, cx| {
6159 action_log.keep_all_edits(Some(telemetry), cx)
6160 });
6161 }
6162
6163 fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
6164 let Some(thread) = self.thread() else {
6165 return;
6166 };
6167 let telemetry = ActionLogTelemetry::from(thread.read(cx));
6168 let action_log = thread.read(cx).action_log().clone();
6169 action_log
6170 .update(cx, |action_log, cx| {
6171 action_log.reject_all_edits(Some(telemetry), cx)
6172 })
6173 .detach();
6174 }
6175
6176 fn allow_always(&mut self, _: &AllowAlways, window: &mut Window, cx: &mut Context<Self>) {
6177 self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowAlways, window, cx);
6178 }
6179
6180 fn allow_once(&mut self, _: &AllowOnce, window: &mut Window, cx: &mut Context<Self>) {
6181 self.authorize_pending_with_granularity(true, window, cx);
6182 }
6183
6184 fn reject_once(&mut self, _: &RejectOnce, window: &mut Window, cx: &mut Context<Self>) {
6185 self.authorize_pending_with_granularity(false, window, cx);
6186 }
6187
6188 fn authorize_pending_with_granularity(
6189 &mut self,
6190 is_allow: bool,
6191 window: &mut Window,
6192 cx: &mut Context<Self>,
6193 ) -> Option<()> {
6194 let thread = self.thread()?.read(cx);
6195 let tool_call = thread.first_tool_awaiting_confirmation()?;
6196 let ToolCallStatus::WaitingForConfirmation { options, .. } = &tool_call.status else {
6197 return None;
6198 };
6199 let tool_call_id = tool_call.id.clone();
6200
6201 // Get granularity options (all options except old deny option)
6202 let granularity_options: Vec<_> = options
6203 .iter()
6204 .filter(|o| {
6205 matches!(
6206 o.kind,
6207 acp::PermissionOptionKind::AllowOnce | acp::PermissionOptionKind::AllowAlways
6208 )
6209 })
6210 .collect();
6211
6212 // Get selected index, defaulting to last option ("Only this time")
6213 let selected_index = self
6214 .selected_permission_granularity
6215 .get(&tool_call_id)
6216 .copied()
6217 .unwrap_or_else(|| granularity_options.len().saturating_sub(1));
6218
6219 let selected_option = granularity_options
6220 .get(selected_index)
6221 .or(granularity_options.last())
6222 .copied()?;
6223
6224 let option_id_str = selected_option.option_id.0.to_string();
6225
6226 // Transform option_id based on allow/deny
6227 let (final_option_id, final_option_kind) = if is_allow {
6228 let allow_id = if option_id_str == "once" {
6229 "allow".to_string()
6230 } else if let Some(rest) = option_id_str.strip_prefix("always:") {
6231 format!("always_allow:{}", rest)
6232 } else if let Some(rest) = option_id_str.strip_prefix("always_pattern:") {
6233 format!("always_allow_pattern:{}", rest)
6234 } else {
6235 option_id_str
6236 };
6237 (acp::PermissionOptionId::new(allow_id), selected_option.kind)
6238 } else {
6239 let deny_id = if option_id_str == "once" {
6240 "deny".to_string()
6241 } else if let Some(rest) = option_id_str.strip_prefix("always:") {
6242 format!("always_deny:{}", rest)
6243 } else if let Some(rest) = option_id_str.strip_prefix("always_pattern:") {
6244 format!("always_deny_pattern:{}", rest)
6245 } else {
6246 option_id_str.replace("allow", "deny")
6247 };
6248 let deny_kind = match selected_option.kind {
6249 acp::PermissionOptionKind::AllowOnce => acp::PermissionOptionKind::RejectOnce,
6250 acp::PermissionOptionKind::AllowAlways => acp::PermissionOptionKind::RejectAlways,
6251 other => other,
6252 };
6253 (acp::PermissionOptionId::new(deny_id), deny_kind)
6254 };
6255
6256 self.authorize_tool_call(tool_call_id, final_option_id, final_option_kind, window, cx);
6257
6258 Some(())
6259 }
6260
6261 fn open_permission_dropdown(
6262 &mut self,
6263 _: &crate::OpenPermissionDropdown,
6264 window: &mut Window,
6265 cx: &mut Context<Self>,
6266 ) {
6267 self.permission_dropdown_handle.toggle(window, cx);
6268 }
6269
6270 fn handle_select_permission_granularity(
6271 &mut self,
6272 action: &SelectPermissionGranularity,
6273 _window: &mut Window,
6274 cx: &mut Context<Self>,
6275 ) {
6276 let tool_call_id = acp::ToolCallId::new(action.tool_call_id.clone());
6277 self.selected_permission_granularity
6278 .insert(tool_call_id, action.index);
6279 cx.notify();
6280 }
6281
6282 fn handle_authorize_tool_call(
6283 &mut self,
6284 action: &AuthorizeToolCall,
6285 window: &mut Window,
6286 cx: &mut Context<Self>,
6287 ) {
6288 let tool_call_id = acp::ToolCallId::new(action.tool_call_id.clone());
6289 let option_id = acp::PermissionOptionId::new(action.option_id.clone());
6290 let option_kind = match action.option_kind.as_str() {
6291 "AllowOnce" => acp::PermissionOptionKind::AllowOnce,
6292 "AllowAlways" => acp::PermissionOptionKind::AllowAlways,
6293 "RejectOnce" => acp::PermissionOptionKind::RejectOnce,
6294 "RejectAlways" => acp::PermissionOptionKind::RejectAlways,
6295 _ => acp::PermissionOptionKind::AllowOnce,
6296 };
6297
6298 self.authorize_tool_call(tool_call_id, option_id, option_kind, window, cx);
6299 }
6300
6301 fn authorize_pending_tool_call(
6302 &mut self,
6303 kind: acp::PermissionOptionKind,
6304 window: &mut Window,
6305 cx: &mut Context<Self>,
6306 ) -> Option<()> {
6307 let thread = self.thread()?.read(cx);
6308 let tool_call = thread.first_tool_awaiting_confirmation()?;
6309 let ToolCallStatus::WaitingForConfirmation { options, .. } = &tool_call.status else {
6310 return None;
6311 };
6312 let option = options.iter().find(|o| o.kind == kind)?;
6313
6314 self.authorize_tool_call(
6315 tool_call.id.clone(),
6316 option.option_id.clone(),
6317 option.kind,
6318 window,
6319 cx,
6320 );
6321
6322 Some(())
6323 }
6324
6325 fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
6326 let thread = self.as_native_thread(cx)?.read(cx);
6327
6328 if thread
6329 .model()
6330 .is_none_or(|model| !model.supports_burn_mode())
6331 {
6332 return None;
6333 }
6334
6335 let active_completion_mode = thread.completion_mode();
6336 let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
6337 let icon = if burn_mode_enabled {
6338 IconName::ZedBurnModeOn
6339 } else {
6340 IconName::ZedBurnMode
6341 };
6342
6343 Some(
6344 IconButton::new("burn-mode", icon)
6345 .icon_size(IconSize::Small)
6346 .icon_color(Color::Muted)
6347 .toggle_state(burn_mode_enabled)
6348 .selected_icon_color(Color::Error)
6349 .on_click(cx.listener(|this, _event, window, cx| {
6350 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
6351 }))
6352 .tooltip(move |_window, cx| {
6353 cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
6354 .into()
6355 })
6356 .into_any_element(),
6357 )
6358 }
6359
6360 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
6361 let message_editor = self.message_editor.read(cx);
6362 let is_editor_empty = message_editor.is_empty(cx);
6363 let focus_handle = message_editor.focus_handle(cx);
6364
6365 let is_generating = self
6366 .thread()
6367 .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
6368
6369 if self.is_loading_contents {
6370 div()
6371 .id("loading-message-content")
6372 .px_1()
6373 .tooltip(Tooltip::text("Loading Added Context…"))
6374 .child(loading_contents_spinner(IconSize::default()))
6375 .into_any_element()
6376 } else if is_generating && is_editor_empty {
6377 IconButton::new("stop-generation", IconName::Stop)
6378 .icon_color(Color::Error)
6379 .style(ButtonStyle::Tinted(TintColor::Error))
6380 .tooltip(move |_window, cx| {
6381 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, cx)
6382 })
6383 .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
6384 .into_any_element()
6385 } else {
6386 IconButton::new("send-message", IconName::Send)
6387 .style(ButtonStyle::Filled)
6388 .map(|this| {
6389 if is_editor_empty && !is_generating {
6390 this.disabled(true).icon_color(Color::Muted)
6391 } else {
6392 this.icon_color(Color::Accent)
6393 }
6394 })
6395 .tooltip(move |_window, cx| {
6396 if is_editor_empty && !is_generating {
6397 Tooltip::for_action("Type to Send", &Chat, cx)
6398 } else if is_generating {
6399 let focus_handle = focus_handle.clone();
6400
6401 Tooltip::element(move |_window, cx| {
6402 v_flex()
6403 .gap_1()
6404 .child(
6405 h_flex()
6406 .gap_2()
6407 .justify_between()
6408 .child(Label::new("Queue and Send"))
6409 .child(KeyBinding::for_action_in(&Chat, &focus_handle, cx)),
6410 )
6411 .child(
6412 h_flex()
6413 .pt_1()
6414 .gap_2()
6415 .justify_between()
6416 .border_t_1()
6417 .border_color(cx.theme().colors().border_variant)
6418 .child(Label::new("Send Immediately"))
6419 .child(KeyBinding::for_action_in(
6420 &SendImmediately,
6421 &focus_handle,
6422 cx,
6423 )),
6424 )
6425 .into_any_element()
6426 })(_window, cx)
6427 } else {
6428 Tooltip::for_action("Send Message", &Chat, cx)
6429 }
6430 })
6431 .on_click(cx.listener(|this, _, window, cx| {
6432 this.send(window, cx);
6433 }))
6434 .into_any_element()
6435 }
6436 }
6437
6438 fn is_following(&self, cx: &App) -> bool {
6439 match self.thread().map(|thread| thread.read(cx).status()) {
6440 Some(ThreadStatus::Generating) => self
6441 .workspace
6442 .read_with(cx, |workspace, _| {
6443 workspace.is_being_followed(CollaboratorId::Agent)
6444 })
6445 .unwrap_or(false),
6446 _ => self.should_be_following,
6447 }
6448 }
6449
6450 fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6451 let following = self.is_following(cx);
6452
6453 self.should_be_following = !following;
6454 if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
6455 self.workspace
6456 .update(cx, |workspace, cx| {
6457 if following {
6458 workspace.unfollow(CollaboratorId::Agent, window, cx);
6459 } else {
6460 workspace.follow(CollaboratorId::Agent, window, cx);
6461 }
6462 })
6463 .ok();
6464 }
6465
6466 telemetry::event!("Follow Agent Selected", following = !following);
6467 }
6468
6469 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
6470 let following = self.is_following(cx);
6471
6472 let tooltip_label = if following {
6473 if self.agent.name() == "Zed Agent" {
6474 format!("Stop Following the {}", self.agent.name())
6475 } else {
6476 format!("Stop Following {}", self.agent.name())
6477 }
6478 } else {
6479 if self.agent.name() == "Zed Agent" {
6480 format!("Follow the {}", self.agent.name())
6481 } else {
6482 format!("Follow {}", self.agent.name())
6483 }
6484 };
6485
6486 IconButton::new("follow-agent", IconName::Crosshair)
6487 .icon_size(IconSize::Small)
6488 .icon_color(Color::Muted)
6489 .toggle_state(following)
6490 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
6491 .tooltip(move |_window, cx| {
6492 if following {
6493 Tooltip::for_action(tooltip_label.clone(), &Follow, cx)
6494 } else {
6495 Tooltip::with_meta(
6496 tooltip_label.clone(),
6497 Some(&Follow),
6498 "Track the agent's location as it reads and edits files.",
6499 cx,
6500 )
6501 }
6502 })
6503 .on_click(cx.listener(move |this, _, window, cx| {
6504 this.toggle_following(window, cx);
6505 }))
6506 }
6507
6508 fn render_add_context_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
6509 let message_editor = self.message_editor.clone();
6510 let menu_visible = message_editor.read(cx).is_completions_menu_visible(cx);
6511
6512 IconButton::new("add-context", IconName::AtSign)
6513 .icon_size(IconSize::Small)
6514 .icon_color(Color::Muted)
6515 .when(!menu_visible, |this| {
6516 this.tooltip(move |_window, cx| {
6517 Tooltip::with_meta("Add Context", None, "Or type @ to include context", cx)
6518 })
6519 })
6520 .on_click(cx.listener(move |_this, _, window, cx| {
6521 let message_editor_clone = message_editor.clone();
6522
6523 window.defer(cx, move |window, cx| {
6524 message_editor_clone.update(cx, |message_editor, cx| {
6525 message_editor.trigger_completion_menu(window, cx);
6526 });
6527 });
6528 }))
6529 }
6530
6531 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
6532 let workspace = self.workspace.clone();
6533 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
6534 Self::open_link(text, &workspace, window, cx);
6535 })
6536 }
6537
6538 fn open_link(
6539 url: SharedString,
6540 workspace: &WeakEntity<Workspace>,
6541 window: &mut Window,
6542 cx: &mut App,
6543 ) {
6544 let Some(workspace) = workspace.upgrade() else {
6545 cx.open_url(&url);
6546 return;
6547 };
6548
6549 if let Some(mention) = MentionUri::parse(&url, workspace.read(cx).path_style(cx)).log_err()
6550 {
6551 workspace.update(cx, |workspace, cx| match mention {
6552 MentionUri::File { abs_path } => {
6553 let project = workspace.project();
6554 let Some(path) =
6555 project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
6556 else {
6557 return;
6558 };
6559
6560 workspace
6561 .open_path(path, None, true, window, cx)
6562 .detach_and_log_err(cx);
6563 }
6564 MentionUri::PastedImage => {}
6565 MentionUri::Directory { abs_path } => {
6566 let project = workspace.project();
6567 let Some(entry_id) = project.update(cx, |project, cx| {
6568 let path = project.find_project_path(abs_path, cx)?;
6569 project.entry_for_path(&path, cx).map(|entry| entry.id)
6570 }) else {
6571 return;
6572 };
6573
6574 project.update(cx, |_, cx| {
6575 cx.emit(project::Event::RevealInProjectPanel(entry_id));
6576 });
6577 }
6578 MentionUri::Symbol {
6579 abs_path: path,
6580 line_range,
6581 ..
6582 }
6583 | MentionUri::Selection {
6584 abs_path: Some(path),
6585 line_range,
6586 } => {
6587 let project = workspace.project();
6588 let Some(path) =
6589 project.update(cx, |project, cx| project.find_project_path(path, cx))
6590 else {
6591 return;
6592 };
6593
6594 let item = workspace.open_path(path, None, true, window, cx);
6595 window
6596 .spawn(cx, async move |cx| {
6597 let Some(editor) = item.await?.downcast::<Editor>() else {
6598 return Ok(());
6599 };
6600 let range = Point::new(*line_range.start(), 0)
6601 ..Point::new(*line_range.start(), 0);
6602 editor
6603 .update_in(cx, |editor, window, cx| {
6604 editor.change_selections(
6605 SelectionEffects::scroll(Autoscroll::center()),
6606 window,
6607 cx,
6608 |s| s.select_ranges(vec![range]),
6609 );
6610 })
6611 .ok();
6612 anyhow::Ok(())
6613 })
6614 .detach_and_log_err(cx);
6615 }
6616 MentionUri::Selection { abs_path: None, .. } => {}
6617 MentionUri::Thread { id, name } => {
6618 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
6619 panel.update(cx, |panel, cx| {
6620 panel.load_agent_thread(
6621 AgentSessionInfo {
6622 session_id: id,
6623 cwd: None,
6624 title: Some(name.into()),
6625 updated_at: None,
6626 meta: None,
6627 },
6628 window,
6629 cx,
6630 )
6631 });
6632 }
6633 }
6634 MentionUri::TextThread { path, .. } => {
6635 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
6636 panel.update(cx, |panel, cx| {
6637 panel
6638 .open_saved_text_thread(path.as_path().into(), window, cx)
6639 .detach_and_log_err(cx);
6640 });
6641 }
6642 }
6643 MentionUri::Rule { id, .. } => {
6644 let PromptId::User { uuid } = id else {
6645 return;
6646 };
6647 window.dispatch_action(
6648 Box::new(OpenRulesLibrary {
6649 prompt_to_select: Some(uuid.0),
6650 }),
6651 cx,
6652 )
6653 }
6654 MentionUri::Fetch { url } => {
6655 cx.open_url(url.as_str());
6656 }
6657 })
6658 } else {
6659 cx.open_url(&url);
6660 }
6661 }
6662
6663 fn open_tool_call_location(
6664 &self,
6665 entry_ix: usize,
6666 location_ix: usize,
6667 window: &mut Window,
6668 cx: &mut Context<Self>,
6669 ) -> Option<()> {
6670 let (tool_call_location, agent_location) = self
6671 .thread()?
6672 .read(cx)
6673 .entries()
6674 .get(entry_ix)?
6675 .location(location_ix)?;
6676
6677 let project_path = self
6678 .project
6679 .read(cx)
6680 .find_project_path(&tool_call_location.path, cx)?;
6681
6682 let open_task = self
6683 .workspace
6684 .update(cx, |workspace, cx| {
6685 workspace.open_path(project_path, None, true, window, cx)
6686 })
6687 .log_err()?;
6688 window
6689 .spawn(cx, async move |cx| {
6690 let item = open_task.await?;
6691
6692 let Some(active_editor) = item.downcast::<Editor>() else {
6693 return anyhow::Ok(());
6694 };
6695
6696 active_editor.update_in(cx, |editor, window, cx| {
6697 let multibuffer = editor.buffer().read(cx);
6698 let buffer = multibuffer.as_singleton();
6699 if agent_location.buffer.upgrade() == buffer {
6700 let excerpt_id = multibuffer.excerpt_ids().first().cloned();
6701 let anchor =
6702 editor::Anchor::in_buffer(excerpt_id.unwrap(), agent_location.position);
6703 editor.change_selections(Default::default(), window, cx, |selections| {
6704 selections.select_anchor_ranges([anchor..anchor]);
6705 })
6706 } else {
6707 let row = tool_call_location.line.unwrap_or_default();
6708 editor.change_selections(Default::default(), window, cx, |selections| {
6709 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
6710 })
6711 }
6712 })?;
6713
6714 anyhow::Ok(())
6715 })
6716 .detach_and_log_err(cx);
6717
6718 None
6719 }
6720
6721 pub fn open_thread_as_markdown(
6722 &self,
6723 workspace: Entity<Workspace>,
6724 window: &mut Window,
6725 cx: &mut App,
6726 ) -> Task<Result<()>> {
6727 let markdown_language_task = workspace
6728 .read(cx)
6729 .app_state()
6730 .languages
6731 .language_for_name("Markdown");
6732
6733 let (thread_title, markdown) = if let Some(thread) = self.thread() {
6734 let thread = thread.read(cx);
6735 (thread.title().to_string(), thread.to_markdown(cx))
6736 } else {
6737 return Task::ready(Ok(()));
6738 };
6739
6740 let project = workspace.read(cx).project().clone();
6741 window.spawn(cx, async move |cx| {
6742 let markdown_language = markdown_language_task.await?;
6743
6744 let buffer = project
6745 .update(cx, |project, cx| project.create_buffer(false, cx))
6746 .await?;
6747
6748 buffer.update(cx, |buffer, cx| {
6749 buffer.set_text(markdown, cx);
6750 buffer.set_language(Some(markdown_language), cx);
6751 buffer.set_capability(language::Capability::ReadWrite, cx);
6752 });
6753
6754 workspace.update_in(cx, |workspace, window, cx| {
6755 let buffer = cx
6756 .new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_title.clone()));
6757
6758 workspace.add_item_to_active_pane(
6759 Box::new(cx.new(|cx| {
6760 let mut editor =
6761 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
6762 editor.set_breadcrumb_header(thread_title);
6763 editor
6764 })),
6765 None,
6766 true,
6767 window,
6768 cx,
6769 );
6770 })?;
6771 anyhow::Ok(())
6772 })
6773 }
6774
6775 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
6776 self.list_state.scroll_to(ListOffset::default());
6777 cx.notify();
6778 }
6779
6780 fn scroll_to_most_recent_user_prompt(&mut self, cx: &mut Context<Self>) {
6781 let Some(thread) = self.thread() else {
6782 return;
6783 };
6784
6785 let entries = thread.read(cx).entries();
6786 if entries.is_empty() {
6787 return;
6788 }
6789
6790 // Find the most recent user message and scroll it to the top of the viewport.
6791 // (Fallback: if no user message exists, scroll to the bottom.)
6792 if let Some(ix) = entries
6793 .iter()
6794 .rposition(|entry| matches!(entry, AgentThreadEntry::UserMessage(_)))
6795 {
6796 self.list_state.scroll_to(ListOffset {
6797 item_ix: ix,
6798 offset_in_item: px(0.0),
6799 });
6800 cx.notify();
6801 } else {
6802 self.scroll_to_bottom(cx);
6803 }
6804 }
6805
6806 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
6807 if let Some(thread) = self.thread() {
6808 let entry_count = thread.read(cx).entries().len();
6809 self.list_state.reset(entry_count);
6810 cx.notify();
6811 }
6812 }
6813
6814 fn notify_with_sound(
6815 &mut self,
6816 caption: impl Into<SharedString>,
6817 icon: IconName,
6818 window: &mut Window,
6819 cx: &mut Context<Self>,
6820 ) {
6821 self.play_notification_sound(window, cx);
6822 self.show_notification(caption, icon, window, cx);
6823 }
6824
6825 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
6826 let settings = AgentSettings::get_global(cx);
6827 if settings.play_sound_when_agent_done && !window.is_window_active() {
6828 Audio::play_sound(Sound::AgentDone, cx);
6829 }
6830 }
6831
6832 fn show_notification(
6833 &mut self,
6834 caption: impl Into<SharedString>,
6835 icon: IconName,
6836 window: &mut Window,
6837 cx: &mut Context<Self>,
6838 ) {
6839 if !self.notifications.is_empty() {
6840 return;
6841 }
6842
6843 let settings = AgentSettings::get_global(cx);
6844
6845 let window_is_inactive = !window.is_window_active();
6846 let panel_is_hidden = self
6847 .workspace
6848 .upgrade()
6849 .map(|workspace| AgentPanel::is_hidden(&workspace, cx))
6850 .unwrap_or(true);
6851
6852 let should_notify = window_is_inactive || panel_is_hidden;
6853
6854 if !should_notify {
6855 return;
6856 }
6857
6858 // TODO: Change this once we have title summarization for external agents.
6859 let title = self.agent.name();
6860
6861 match settings.notify_when_agent_waiting {
6862 NotifyWhenAgentWaiting::PrimaryScreen => {
6863 if let Some(primary) = cx.primary_display() {
6864 self.pop_up(icon, caption.into(), title, window, primary, cx);
6865 }
6866 }
6867 NotifyWhenAgentWaiting::AllScreens => {
6868 let caption = caption.into();
6869 for screen in cx.displays() {
6870 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
6871 }
6872 }
6873 NotifyWhenAgentWaiting::Never => {
6874 // Don't show anything
6875 }
6876 }
6877 }
6878
6879 fn pop_up(
6880 &mut self,
6881 icon: IconName,
6882 caption: SharedString,
6883 title: SharedString,
6884 window: &mut Window,
6885 screen: Rc<dyn PlatformDisplay>,
6886 cx: &mut Context<Self>,
6887 ) {
6888 let options = AgentNotification::window_options(screen, cx);
6889
6890 let project_name = self.workspace.upgrade().and_then(|workspace| {
6891 workspace
6892 .read(cx)
6893 .project()
6894 .read(cx)
6895 .visible_worktrees(cx)
6896 .next()
6897 .map(|worktree| worktree.read(cx).root_name_str().to_string())
6898 });
6899
6900 if let Some(screen_window) = cx
6901 .open_window(options, |_window, cx| {
6902 cx.new(|_cx| {
6903 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
6904 })
6905 })
6906 .log_err()
6907 && let Some(pop_up) = screen_window.entity(cx).log_err()
6908 {
6909 self.notification_subscriptions
6910 .entry(screen_window)
6911 .or_insert_with(Vec::new)
6912 .push(cx.subscribe_in(&pop_up, window, {
6913 |this, _, event, window, cx| match event {
6914 AgentNotificationEvent::Accepted => {
6915 let handle = window.window_handle();
6916 cx.activate(true);
6917
6918 let workspace_handle = this.workspace.clone();
6919
6920 // If there are multiple Zed windows, activate the correct one.
6921 cx.defer(move |cx| {
6922 handle
6923 .update(cx, |_view, window, _cx| {
6924 window.activate_window();
6925
6926 if let Some(workspace) = workspace_handle.upgrade() {
6927 workspace.update(_cx, |workspace, cx| {
6928 workspace.focus_panel::<AgentPanel>(window, cx);
6929 });
6930 }
6931 })
6932 .log_err();
6933 });
6934
6935 this.dismiss_notifications(cx);
6936 }
6937 AgentNotificationEvent::Dismissed => {
6938 this.dismiss_notifications(cx);
6939 }
6940 }
6941 }));
6942
6943 self.notifications.push(screen_window);
6944
6945 // If the user manually refocuses the original window, dismiss the popup.
6946 self.notification_subscriptions
6947 .entry(screen_window)
6948 .or_insert_with(Vec::new)
6949 .push({
6950 let pop_up_weak = pop_up.downgrade();
6951
6952 cx.observe_window_activation(window, move |_, window, cx| {
6953 if window.is_window_active()
6954 && let Some(pop_up) = pop_up_weak.upgrade()
6955 {
6956 pop_up.update(cx, |_, cx| {
6957 cx.emit(AgentNotificationEvent::Dismissed);
6958 });
6959 }
6960 })
6961 });
6962 }
6963 }
6964
6965 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
6966 for window in self.notifications.drain(..) {
6967 window
6968 .update(cx, |_, window, _| {
6969 window.remove_window();
6970 })
6971 .ok();
6972
6973 self.notification_subscriptions.remove(&window);
6974 }
6975 }
6976
6977 fn render_generating(&self, confirmation: bool, cx: &App) -> impl IntoElement {
6978 let show_stats = AgentSettings::get_global(cx).show_turn_stats;
6979 let elapsed_label = show_stats
6980 .then(|| {
6981 self.turn_started_at.and_then(|started_at| {
6982 let elapsed = started_at.elapsed();
6983 (elapsed > STOPWATCH_THRESHOLD).then(|| duration_alt_display(elapsed))
6984 })
6985 })
6986 .flatten();
6987
6988 let is_waiting = confirmation
6989 || self
6990 .thread()
6991 .is_some_and(|thread| thread.read(cx).has_in_progress_tool_calls());
6992
6993 let turn_tokens_label = elapsed_label
6994 .is_some()
6995 .then(|| {
6996 self.turn_tokens
6997 .filter(|&tokens| tokens > TOKEN_THRESHOLD)
6998 .map(|tokens| crate::text_thread_editor::humanize_token_count(tokens))
6999 })
7000 .flatten();
7001
7002 let arrow_icon = if is_waiting {
7003 IconName::ArrowUp
7004 } else {
7005 IconName::ArrowDown
7006 };
7007
7008 h_flex()
7009 .id("generating-spinner")
7010 .py_2()
7011 .px(rems_from_px(22.))
7012 .gap_2()
7013 .map(|this| {
7014 if confirmation {
7015 this.child(
7016 h_flex()
7017 .w_2()
7018 .child(SpinnerLabel::sand().size(LabelSize::Small)),
7019 )
7020 .child(
7021 div().min_w(rems(8.)).child(
7022 LoadingLabel::new("Waiting Confirmation")
7023 .size(LabelSize::Small)
7024 .color(Color::Muted),
7025 ),
7026 )
7027 } else {
7028 this.child(SpinnerLabel::new().size(LabelSize::Small))
7029 }
7030 })
7031 .when_some(elapsed_label, |this, elapsed| {
7032 this.child(
7033 Label::new(elapsed)
7034 .size(LabelSize::Small)
7035 .color(Color::Muted),
7036 )
7037 })
7038 .when_some(turn_tokens_label, |this, tokens| {
7039 this.child(
7040 h_flex()
7041 .gap_0p5()
7042 .child(
7043 Icon::new(arrow_icon)
7044 .size(IconSize::XSmall)
7045 .color(Color::Muted),
7046 )
7047 .child(
7048 Label::new(format!("{} tokens", tokens))
7049 .size(LabelSize::Small)
7050 .color(Color::Muted),
7051 ),
7052 )
7053 })
7054 .into_any_element()
7055 }
7056
7057 fn render_thread_controls(
7058 &self,
7059 thread: &Entity<AcpThread>,
7060 cx: &Context<Self>,
7061 ) -> impl IntoElement {
7062 let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
7063 if is_generating {
7064 return self.render_generating(false, cx).into_any_element();
7065 }
7066
7067 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
7068 .shape(ui::IconButtonShape::Square)
7069 .icon_size(IconSize::Small)
7070 .icon_color(Color::Ignored)
7071 .tooltip(Tooltip::text("Open Thread as Markdown"))
7072 .on_click(cx.listener(move |this, _, window, cx| {
7073 if let Some(workspace) = this.workspace.upgrade() {
7074 this.open_thread_as_markdown(workspace, window, cx)
7075 .detach_and_log_err(cx);
7076 }
7077 }));
7078
7079 let scroll_to_recent_user_prompt =
7080 IconButton::new("scroll_to_recent_user_prompt", IconName::ForwardArrow)
7081 .shape(ui::IconButtonShape::Square)
7082 .icon_size(IconSize::Small)
7083 .icon_color(Color::Ignored)
7084 .tooltip(Tooltip::text("Scroll To Most Recent User Prompt"))
7085 .on_click(cx.listener(move |this, _, _, cx| {
7086 this.scroll_to_most_recent_user_prompt(cx);
7087 }));
7088
7089 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
7090 .shape(ui::IconButtonShape::Square)
7091 .icon_size(IconSize::Small)
7092 .icon_color(Color::Ignored)
7093 .tooltip(Tooltip::text("Scroll To Top"))
7094 .on_click(cx.listener(move |this, _, _, cx| {
7095 this.scroll_to_top(cx);
7096 }));
7097
7098 let show_stats = AgentSettings::get_global(cx).show_turn_stats;
7099 let last_turn_clock = show_stats
7100 .then(|| {
7101 self.last_turn_duration
7102 .filter(|&duration| duration > STOPWATCH_THRESHOLD)
7103 .map(|duration| {
7104 Label::new(duration_alt_display(duration))
7105 .size(LabelSize::Small)
7106 .color(Color::Muted)
7107 })
7108 })
7109 .flatten();
7110
7111 let last_turn_tokens = last_turn_clock
7112 .is_some()
7113 .then(|| {
7114 self.last_turn_tokens
7115 .filter(|&tokens| tokens > TOKEN_THRESHOLD)
7116 .map(|tokens| {
7117 Label::new(format!(
7118 "{} tokens",
7119 crate::text_thread_editor::humanize_token_count(tokens)
7120 ))
7121 .size(LabelSize::Small)
7122 .color(Color::Muted)
7123 })
7124 })
7125 .flatten();
7126
7127 let mut container = h_flex()
7128 .w_full()
7129 .py_2()
7130 .px_5()
7131 .gap_px()
7132 .opacity(0.6)
7133 .hover(|s| s.opacity(1.))
7134 .justify_end()
7135 .when(
7136 last_turn_tokens.is_some() || last_turn_clock.is_some(),
7137 |this| {
7138 this.child(
7139 h_flex()
7140 .gap_1()
7141 .px_1()
7142 .when_some(last_turn_tokens, |this, label| this.child(label))
7143 .when_some(last_turn_clock, |this, label| this.child(label)),
7144 )
7145 },
7146 );
7147
7148 if AgentSettings::get_global(cx).enable_feedback
7149 && self
7150 .thread()
7151 .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
7152 {
7153 let feedback = self.thread_feedback.feedback;
7154
7155 let tooltip_meta = || {
7156 SharedString::new(
7157 "Rating the thread sends all of your current conversation to the Zed team.",
7158 )
7159 };
7160
7161 container = container
7162 .child(
7163 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
7164 .shape(ui::IconButtonShape::Square)
7165 .icon_size(IconSize::Small)
7166 .icon_color(match feedback {
7167 Some(ThreadFeedback::Positive) => Color::Accent,
7168 _ => Color::Ignored,
7169 })
7170 .tooltip(move |window, cx| match feedback {
7171 Some(ThreadFeedback::Positive) => {
7172 Tooltip::text("Thanks for your feedback!")(window, cx)
7173 }
7174 _ => Tooltip::with_meta("Helpful Response", None, tooltip_meta(), cx),
7175 })
7176 .on_click(cx.listener(move |this, _, window, cx| {
7177 this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
7178 })),
7179 )
7180 .child(
7181 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
7182 .shape(ui::IconButtonShape::Square)
7183 .icon_size(IconSize::Small)
7184 .icon_color(match feedback {
7185 Some(ThreadFeedback::Negative) => Color::Accent,
7186 _ => Color::Ignored,
7187 })
7188 .tooltip(move |window, cx| match feedback {
7189 Some(ThreadFeedback::Negative) => {
7190 Tooltip::text(
7191 "We appreciate your feedback and will use it to improve in the future.",
7192 )(window, cx)
7193 }
7194 _ => {
7195 Tooltip::with_meta("Not Helpful Response", None, tooltip_meta(), cx)
7196 }
7197 })
7198 .on_click(cx.listener(move |this, _, window, cx| {
7199 this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
7200 })),
7201 );
7202 }
7203
7204 if cx.has_flag::<AgentSharingFeatureFlag>()
7205 && self.is_imported_thread(cx)
7206 && self
7207 .project
7208 .read(cx)
7209 .client()
7210 .status()
7211 .borrow()
7212 .is_connected()
7213 {
7214 let sync_button = IconButton::new("sync-thread", IconName::ArrowCircle)
7215 .shape(ui::IconButtonShape::Square)
7216 .icon_size(IconSize::Small)
7217 .icon_color(Color::Ignored)
7218 .tooltip(Tooltip::text("Sync with source thread"))
7219 .on_click(cx.listener(move |this, _, window, cx| {
7220 this.sync_thread(window, cx);
7221 }));
7222
7223 container = container.child(sync_button);
7224 }
7225
7226 if cx.has_flag::<AgentSharingFeatureFlag>() && !self.is_imported_thread(cx) {
7227 let share_button = IconButton::new("share-thread", IconName::ArrowUpRight)
7228 .shape(ui::IconButtonShape::Square)
7229 .icon_size(IconSize::Small)
7230 .icon_color(Color::Ignored)
7231 .tooltip(Tooltip::text("Share Thread"))
7232 .on_click(cx.listener(move |this, _, window, cx| {
7233 this.share_thread(window, cx);
7234 }));
7235
7236 container = container.child(share_button);
7237 }
7238
7239 container
7240 .child(open_as_markdown)
7241 .child(scroll_to_recent_user_prompt)
7242 .child(scroll_to_top)
7243 .into_any_element()
7244 }
7245
7246 fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
7247 h_flex()
7248 .key_context("AgentFeedbackMessageEditor")
7249 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
7250 this.thread_feedback.dismiss_comments();
7251 cx.notify();
7252 }))
7253 .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
7254 this.submit_feedback_message(cx);
7255 }))
7256 .p_2()
7257 .mb_2()
7258 .mx_5()
7259 .gap_1()
7260 .rounded_md()
7261 .border_1()
7262 .border_color(cx.theme().colors().border)
7263 .bg(cx.theme().colors().editor_background)
7264 .child(div().w_full().child(editor))
7265 .child(
7266 h_flex()
7267 .child(
7268 IconButton::new("dismiss-feedback-message", IconName::Close)
7269 .icon_color(Color::Error)
7270 .icon_size(IconSize::XSmall)
7271 .shape(ui::IconButtonShape::Square)
7272 .on_click(cx.listener(move |this, _, _window, cx| {
7273 this.thread_feedback.dismiss_comments();
7274 cx.notify();
7275 })),
7276 )
7277 .child(
7278 IconButton::new("submit-feedback-message", IconName::Return)
7279 .icon_size(IconSize::XSmall)
7280 .shape(ui::IconButtonShape::Square)
7281 .on_click(cx.listener(move |this, _, _window, cx| {
7282 this.submit_feedback_message(cx);
7283 })),
7284 ),
7285 )
7286 }
7287
7288 fn handle_feedback_click(
7289 &mut self,
7290 feedback: ThreadFeedback,
7291 window: &mut Window,
7292 cx: &mut Context<Self>,
7293 ) {
7294 let Some(thread) = self.thread().cloned() else {
7295 return;
7296 };
7297
7298 self.thread_feedback.submit(thread, feedback, window, cx);
7299 cx.notify();
7300 }
7301
7302 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
7303 let Some(thread) = self.thread().cloned() else {
7304 return;
7305 };
7306
7307 self.thread_feedback.submit_comments(thread, cx);
7308 cx.notify();
7309 }
7310
7311 fn render_token_limit_callout(&self, cx: &mut Context<Self>) -> Option<Callout> {
7312 if self.token_limit_callout_dismissed {
7313 return None;
7314 }
7315
7316 let token_usage = self.thread()?.read(cx).token_usage()?;
7317 let ratio = token_usage.ratio();
7318
7319 let (severity, icon, title) = match ratio {
7320 acp_thread::TokenUsageRatio::Normal => return None,
7321 acp_thread::TokenUsageRatio::Warning => (
7322 Severity::Warning,
7323 IconName::Warning,
7324 "Thread reaching the token limit soon",
7325 ),
7326 acp_thread::TokenUsageRatio::Exceeded => (
7327 Severity::Error,
7328 IconName::XCircle,
7329 "Thread reached the token limit",
7330 ),
7331 };
7332
7333 let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
7334 thread.read(cx).completion_mode() == CompletionMode::Normal
7335 && thread
7336 .read(cx)
7337 .model()
7338 .is_some_and(|model| model.supports_burn_mode())
7339 });
7340
7341 let description = if burn_mode_available {
7342 "To continue, start a new thread from a summary or turn Burn Mode on."
7343 } else {
7344 "To continue, start a new thread from a summary."
7345 };
7346
7347 Some(
7348 Callout::new()
7349 .severity(severity)
7350 .icon(icon)
7351 .title(title)
7352 .description(description)
7353 .actions_slot(
7354 h_flex()
7355 .gap_0p5()
7356 .child(
7357 Button::new("start-new-thread", "Start New Thread")
7358 .label_size(LabelSize::Small)
7359 .on_click(cx.listener(|this, _, window, cx| {
7360 let Some(thread) = this.thread() else {
7361 return;
7362 };
7363 let session_id = thread.read(cx).session_id().clone();
7364 window.dispatch_action(
7365 crate::NewNativeAgentThreadFromSummary {
7366 from_session_id: session_id,
7367 }
7368 .boxed_clone(),
7369 cx,
7370 );
7371 })),
7372 )
7373 .when(burn_mode_available, |this| {
7374 this.child(
7375 IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
7376 .icon_size(IconSize::XSmall)
7377 .on_click(cx.listener(|this, _event, window, cx| {
7378 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
7379 })),
7380 )
7381 }),
7382 )
7383 .dismiss_action(self.dismiss_error_button(cx)),
7384 )
7385 }
7386
7387 fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
7388 if !self.is_using_zed_ai_models(cx) {
7389 return None;
7390 }
7391
7392 let user_store = self.project.read(cx).user_store().read(cx);
7393 if user_store.is_usage_based_billing_enabled() {
7394 return None;
7395 }
7396
7397 let plan = user_store
7398 .plan()
7399 .unwrap_or(cloud_llm_client::Plan::V1(PlanV1::ZedFree));
7400
7401 let usage = user_store.model_request_usage()?;
7402
7403 Some(
7404 div()
7405 .child(UsageCallout::new(plan, usage))
7406 .line_height(line_height),
7407 )
7408 }
7409
7410 fn agent_ui_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
7411 self.entry_view_state.update(cx, |entry_view_state, cx| {
7412 entry_view_state.agent_ui_font_size_changed(cx);
7413 });
7414 }
7415
7416 pub(crate) fn insert_dragged_files(
7417 &self,
7418 paths: Vec<project::ProjectPath>,
7419 added_worktrees: Vec<Entity<project::Worktree>>,
7420 window: &mut Window,
7421 cx: &mut Context<Self>,
7422 ) {
7423 self.message_editor.update(cx, |message_editor, cx| {
7424 message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
7425 })
7426 }
7427
7428 /// Inserts the selected text into the message editor or the message being
7429 /// edited, if any.
7430 pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
7431 self.active_editor(cx).update(cx, |editor, cx| {
7432 editor.insert_selections(window, cx);
7433 });
7434 }
7435
7436 /// Inserts code snippets as creases into the message editor.
7437 pub(crate) fn insert_code_crease(
7438 &self,
7439 creases: Vec<(String, String)>,
7440 window: &mut Window,
7441 cx: &mut Context<Self>,
7442 ) {
7443 self.message_editor.update(cx, |message_editor, cx| {
7444 message_editor.insert_code_creases(creases, window, cx);
7445 });
7446 }
7447
7448 fn render_thread_retry_status_callout(
7449 &self,
7450 _window: &mut Window,
7451 _cx: &mut Context<Self>,
7452 ) -> Option<Callout> {
7453 let state = self.thread_retry_status.as_ref()?;
7454
7455 let next_attempt_in = state
7456 .duration
7457 .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
7458 if next_attempt_in.is_zero() {
7459 return None;
7460 }
7461
7462 let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
7463
7464 let retry_message = if state.max_attempts == 1 {
7465 if next_attempt_in_secs == 1 {
7466 "Retrying. Next attempt in 1 second.".to_string()
7467 } else {
7468 format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
7469 }
7470 } else if next_attempt_in_secs == 1 {
7471 format!(
7472 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
7473 state.attempt, state.max_attempts,
7474 )
7475 } else {
7476 format!(
7477 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
7478 state.attempt, state.max_attempts,
7479 )
7480 };
7481
7482 Some(
7483 Callout::new()
7484 .severity(Severity::Warning)
7485 .title(state.last_error.clone())
7486 .description(retry_message),
7487 )
7488 }
7489
7490 fn render_codex_windows_warning(&self, cx: &mut Context<Self>) -> Callout {
7491 Callout::new()
7492 .icon(IconName::Warning)
7493 .severity(Severity::Warning)
7494 .title("Codex on Windows")
7495 .description("For best performance, run Codex in Windows Subsystem for Linux (WSL2)")
7496 .actions_slot(
7497 Button::new("open-wsl-modal", "Open in WSL")
7498 .icon_size(IconSize::Small)
7499 .icon_color(Color::Muted)
7500 .on_click(cx.listener({
7501 move |_, _, _window, cx| {
7502 #[cfg(windows)]
7503 _window.dispatch_action(
7504 zed_actions::wsl_actions::OpenWsl::default().boxed_clone(),
7505 cx,
7506 );
7507 cx.notify();
7508 }
7509 })),
7510 )
7511 .dismiss_action(
7512 IconButton::new("dismiss", IconName::Close)
7513 .icon_size(IconSize::Small)
7514 .icon_color(Color::Muted)
7515 .tooltip(Tooltip::text("Dismiss Warning"))
7516 .on_click(cx.listener({
7517 move |this, _, _, cx| {
7518 this.show_codex_windows_warning = false;
7519 cx.notify();
7520 }
7521 })),
7522 )
7523 }
7524
7525 fn render_thread_error(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
7526 let content = match self.thread_error.as_ref()? {
7527 ThreadError::Other(error) => self.render_any_thread_error(error.clone(), window, cx),
7528 ThreadError::Refusal => self.render_refusal_error(cx),
7529 ThreadError::AuthenticationRequired(error) => {
7530 self.render_authentication_required_error(error.clone(), cx)
7531 }
7532 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
7533 ThreadError::ModelRequestLimitReached(plan) => {
7534 self.render_model_request_limit_reached_error(*plan, cx)
7535 }
7536 ThreadError::ToolUseLimitReached => self.render_tool_use_limit_reached_error(cx)?,
7537 };
7538
7539 Some(div().child(content))
7540 }
7541
7542 fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
7543 v_flex().w_full().justify_end().child(
7544 h_flex()
7545 .p_2()
7546 .pr_3()
7547 .w_full()
7548 .gap_1p5()
7549 .border_t_1()
7550 .border_color(cx.theme().colors().border)
7551 .bg(cx.theme().colors().element_background)
7552 .child(
7553 h_flex()
7554 .flex_1()
7555 .gap_1p5()
7556 .child(
7557 Icon::new(IconName::Download)
7558 .color(Color::Accent)
7559 .size(IconSize::Small),
7560 )
7561 .child(Label::new("New version available").size(LabelSize::Small)),
7562 )
7563 .child(
7564 Button::new("update-button", format!("Update to v{}", version))
7565 .label_size(LabelSize::Small)
7566 .style(ButtonStyle::Tinted(TintColor::Accent))
7567 .on_click(cx.listener(|this, _, window, cx| {
7568 this.reset(window, cx);
7569 })),
7570 ),
7571 )
7572 }
7573
7574 fn current_mode_id(&self, cx: &App) -> Option<Arc<str>> {
7575 if let Some(thread) = self.as_native_thread(cx) {
7576 Some(thread.read(cx).profile().0.clone())
7577 } else if let Some(mode_selector) = self.mode_selector() {
7578 Some(mode_selector.read(cx).mode().0)
7579 } else {
7580 None
7581 }
7582 }
7583
7584 fn current_model_id(&self, cx: &App) -> Option<String> {
7585 self.model_selector
7586 .as_ref()
7587 .and_then(|selector| selector.read(cx).active_model(cx).map(|m| m.id.to_string()))
7588 }
7589
7590 fn current_model_name(&self, cx: &App) -> SharedString {
7591 // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
7592 // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
7593 // This provides better clarity about what refused the request
7594 if self.as_native_connection(cx).is_some() {
7595 self.model_selector
7596 .as_ref()
7597 .and_then(|selector| selector.read(cx).active_model(cx))
7598 .map(|model| model.name.clone())
7599 .unwrap_or_else(|| SharedString::from("The model"))
7600 } else {
7601 // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
7602 self.agent.name()
7603 }
7604 }
7605
7606 fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
7607 let model_or_agent_name = self.current_model_name(cx);
7608 let refusal_message = format!(
7609 "{} 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.",
7610 model_or_agent_name
7611 );
7612
7613 Callout::new()
7614 .severity(Severity::Error)
7615 .title("Request Refused")
7616 .icon(IconName::XCircle)
7617 .description(refusal_message.clone())
7618 .actions_slot(self.create_copy_button(&refusal_message))
7619 .dismiss_action(self.dismiss_error_button(cx))
7620 }
7621
7622 fn render_any_thread_error(
7623 &mut self,
7624 error: SharedString,
7625 window: &mut Window,
7626 cx: &mut Context<'_, Self>,
7627 ) -> Callout {
7628 let can_resume = self
7629 .thread()
7630 .map_or(false, |thread| thread.read(cx).can_resume(cx));
7631
7632 let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
7633 let thread = thread.read(cx);
7634 let supports_burn_mode = thread
7635 .model()
7636 .map_or(false, |model| model.supports_burn_mode());
7637 supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
7638 });
7639
7640 let markdown = if let Some(markdown) = &self.thread_error_markdown {
7641 markdown.clone()
7642 } else {
7643 let markdown = cx.new(|cx| Markdown::new(error.clone(), None, None, cx));
7644 self.thread_error_markdown = Some(markdown.clone());
7645 markdown
7646 };
7647
7648 let markdown_style = default_markdown_style(false, true, window, cx);
7649 let description = self
7650 .render_markdown(markdown, markdown_style)
7651 .into_any_element();
7652
7653 Callout::new()
7654 .severity(Severity::Error)
7655 .icon(IconName::XCircle)
7656 .title("An Error Happened")
7657 .description_slot(description)
7658 .actions_slot(
7659 h_flex()
7660 .gap_0p5()
7661 .when(can_resume && can_enable_burn_mode, |this| {
7662 this.child(
7663 Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
7664 .icon(IconName::ZedBurnMode)
7665 .icon_position(IconPosition::Start)
7666 .icon_size(IconSize::Small)
7667 .label_size(LabelSize::Small)
7668 .on_click(cx.listener(|this, _, window, cx| {
7669 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
7670 this.resume_chat(cx);
7671 })),
7672 )
7673 })
7674 .when(can_resume, |this| {
7675 this.child(
7676 IconButton::new("retry", IconName::RotateCw)
7677 .icon_size(IconSize::Small)
7678 .tooltip(Tooltip::text("Retry Generation"))
7679 .on_click(cx.listener(|this, _, _window, cx| {
7680 this.resume_chat(cx);
7681 })),
7682 )
7683 })
7684 .child(self.create_copy_button(error.to_string())),
7685 )
7686 .dismiss_action(self.dismiss_error_button(cx))
7687 }
7688
7689 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
7690 const ERROR_MESSAGE: &str =
7691 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
7692
7693 Callout::new()
7694 .severity(Severity::Error)
7695 .icon(IconName::XCircle)
7696 .title("Free Usage Exceeded")
7697 .description(ERROR_MESSAGE)
7698 .actions_slot(
7699 h_flex()
7700 .gap_0p5()
7701 .child(self.upgrade_button(cx))
7702 .child(self.create_copy_button(ERROR_MESSAGE)),
7703 )
7704 .dismiss_action(self.dismiss_error_button(cx))
7705 }
7706
7707 fn render_authentication_required_error(
7708 &self,
7709 error: SharedString,
7710 cx: &mut Context<Self>,
7711 ) -> Callout {
7712 Callout::new()
7713 .severity(Severity::Error)
7714 .title("Authentication Required")
7715 .icon(IconName::XCircle)
7716 .description(error.clone())
7717 .actions_slot(
7718 h_flex()
7719 .gap_0p5()
7720 .child(self.authenticate_button(cx))
7721 .child(self.create_copy_button(error)),
7722 )
7723 .dismiss_action(self.dismiss_error_button(cx))
7724 }
7725
7726 fn render_model_request_limit_reached_error(
7727 &self,
7728 plan: cloud_llm_client::Plan,
7729 cx: &mut Context<Self>,
7730 ) -> Callout {
7731 let error_message = match plan {
7732 cloud_llm_client::Plan::V1(PlanV1::ZedPro) => {
7733 "Upgrade to usage-based billing for more prompts."
7734 }
7735 cloud_llm_client::Plan::V1(PlanV1::ZedProTrial)
7736 | cloud_llm_client::Plan::V1(PlanV1::ZedFree) => "Upgrade to Zed Pro for more prompts.",
7737 cloud_llm_client::Plan::V2(_) => "",
7738 };
7739
7740 Callout::new()
7741 .severity(Severity::Error)
7742 .title("Model Prompt Limit Reached")
7743 .icon(IconName::XCircle)
7744 .description(error_message)
7745 .actions_slot(
7746 h_flex()
7747 .gap_0p5()
7748 .child(self.upgrade_button(cx))
7749 .child(self.create_copy_button(error_message)),
7750 )
7751 .dismiss_action(self.dismiss_error_button(cx))
7752 }
7753
7754 fn render_tool_use_limit_reached_error(&self, cx: &mut Context<Self>) -> Option<Callout> {
7755 let thread = self.as_native_thread(cx)?;
7756 let supports_burn_mode = thread
7757 .read(cx)
7758 .model()
7759 .is_some_and(|model| model.supports_burn_mode());
7760
7761 let focus_handle = self.focus_handle(cx);
7762
7763 Some(
7764 Callout::new()
7765 .icon(IconName::Info)
7766 .title("Consecutive tool use limit reached.")
7767 .actions_slot(
7768 h_flex()
7769 .gap_0p5()
7770 .when(supports_burn_mode, |this| {
7771 this.child(
7772 Button::new("continue-burn-mode", "Continue with Burn Mode")
7773 .style(ButtonStyle::Filled)
7774 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
7775 .layer(ElevationIndex::ModalSurface)
7776 .label_size(LabelSize::Small)
7777 .key_binding(
7778 KeyBinding::for_action_in(
7779 &ContinueWithBurnMode,
7780 &focus_handle,
7781 cx,
7782 )
7783 .map(|kb| kb.size(rems_from_px(10.))),
7784 )
7785 .tooltip(Tooltip::text(
7786 "Enable Burn Mode for unlimited tool use.",
7787 ))
7788 .on_click({
7789 cx.listener(move |this, _, _window, cx| {
7790 thread.update(cx, |thread, cx| {
7791 thread
7792 .set_completion_mode(CompletionMode::Burn, cx);
7793 });
7794 this.resume_chat(cx);
7795 })
7796 }),
7797 )
7798 })
7799 .child(
7800 Button::new("continue-conversation", "Continue")
7801 .layer(ElevationIndex::ModalSurface)
7802 .label_size(LabelSize::Small)
7803 .key_binding(
7804 KeyBinding::for_action_in(&ContinueThread, &focus_handle, cx)
7805 .map(|kb| kb.size(rems_from_px(10.))),
7806 )
7807 .on_click(cx.listener(|this, _, _window, cx| {
7808 this.resume_chat(cx);
7809 })),
7810 ),
7811 ),
7812 )
7813 }
7814
7815 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
7816 let message = message.into();
7817
7818 CopyButton::new(message).tooltip_label("Copy Error Message")
7819 }
7820
7821 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
7822 IconButton::new("dismiss", IconName::Close)
7823 .icon_size(IconSize::Small)
7824 .tooltip(Tooltip::text("Dismiss"))
7825 .on_click(cx.listener({
7826 move |this, _, _, cx| {
7827 this.clear_thread_error(cx);
7828 cx.notify();
7829 }
7830 }))
7831 }
7832
7833 fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
7834 Button::new("authenticate", "Authenticate")
7835 .label_size(LabelSize::Small)
7836 .style(ButtonStyle::Filled)
7837 .on_click(cx.listener({
7838 move |this, _, window, cx| {
7839 let agent = this.agent.clone();
7840 let ThreadState::Ready { thread, .. } = &this.thread_state else {
7841 return;
7842 };
7843
7844 let connection = thread.read(cx).connection().clone();
7845 this.clear_thread_error(cx);
7846 if let Some(message) = this.in_flight_prompt.take() {
7847 this.message_editor.update(cx, |editor, cx| {
7848 editor.set_message(message, window, cx);
7849 });
7850 }
7851 let this = cx.weak_entity();
7852 window.defer(cx, |window, cx| {
7853 Self::handle_auth_required(
7854 this,
7855 AuthRequired::new(),
7856 agent,
7857 connection,
7858 window,
7859 cx,
7860 );
7861 })
7862 }
7863 }))
7864 }
7865
7866 pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7867 let agent = self.agent.clone();
7868 let ThreadState::Ready { thread, .. } = &self.thread_state else {
7869 return;
7870 };
7871
7872 let connection = thread.read(cx).connection().clone();
7873 self.clear_thread_error(cx);
7874 let this = cx.weak_entity();
7875 window.defer(cx, |window, cx| {
7876 Self::handle_auth_required(this, AuthRequired::new(), agent, connection, window, cx);
7877 })
7878 }
7879
7880 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
7881 Button::new("upgrade", "Upgrade")
7882 .label_size(LabelSize::Small)
7883 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
7884 .on_click(cx.listener({
7885 move |this, _, _, cx| {
7886 this.clear_thread_error(cx);
7887 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
7888 }
7889 }))
7890 }
7891
7892 pub fn delete_history_entry(&mut self, entry: AgentSessionInfo, cx: &mut Context<Self>) {
7893 let task = self.history.update(cx, |history, cx| {
7894 history.delete_session(&entry.session_id, cx)
7895 });
7896 task.detach_and_log_err(cx);
7897 }
7898
7899 /// Returns the currently active editor, either for a message that is being
7900 /// edited or the editor for a new message.
7901 fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
7902 if let Some(index) = self.editing_message
7903 && let Some(editor) = self
7904 .entry_view_state
7905 .read(cx)
7906 .entry(index)
7907 .and_then(|e| e.message_editor())
7908 .cloned()
7909 {
7910 editor
7911 } else {
7912 self.message_editor.clone()
7913 }
7914 }
7915
7916 fn get_agent_message_content(
7917 entries: &[AgentThreadEntry],
7918 entry_index: usize,
7919 cx: &App,
7920 ) -> Option<String> {
7921 let entry = entries.get(entry_index)?;
7922 if matches!(entry, AgentThreadEntry::UserMessage(_)) {
7923 return None;
7924 }
7925
7926 let start_index = (0..entry_index)
7927 .rev()
7928 .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
7929 .map(|i| i + 1)
7930 .unwrap_or(0);
7931
7932 let end_index = (entry_index + 1..entries.len())
7933 .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
7934 .map(|i| i - 1)
7935 .unwrap_or(entries.len() - 1);
7936
7937 let parts: Vec<String> = (start_index..=end_index)
7938 .filter_map(|i| entries.get(i))
7939 .filter_map(|entry| {
7940 if let AgentThreadEntry::AssistantMessage(message) = entry {
7941 let text: String = message
7942 .chunks
7943 .iter()
7944 .filter_map(|chunk| match chunk {
7945 AssistantMessageChunk::Message { block } => {
7946 let markdown = block.to_markdown(cx);
7947 if markdown.trim().is_empty() {
7948 None
7949 } else {
7950 Some(markdown.to_string())
7951 }
7952 }
7953 AssistantMessageChunk::Thought { .. } => None,
7954 })
7955 .collect::<Vec<_>>()
7956 .join("\n\n");
7957
7958 if text.is_empty() { None } else { Some(text) }
7959 } else {
7960 None
7961 }
7962 })
7963 .collect();
7964
7965 let text = parts.join("\n\n");
7966 if text.is_empty() { None } else { Some(text) }
7967 }
7968}
7969
7970fn loading_contents_spinner(size: IconSize) -> AnyElement {
7971 Icon::new(IconName::LoadCircle)
7972 .size(size)
7973 .color(Color::Accent)
7974 .with_rotate_animation(3)
7975 .into_any_element()
7976}
7977
7978fn placeholder_text(agent_name: &str, has_commands: bool) -> String {
7979 if agent_name == "Zed Agent" {
7980 format!("Message the {} — @ to include context", agent_name)
7981 } else if has_commands {
7982 format!(
7983 "Message {} — @ to include context, / for commands",
7984 agent_name
7985 )
7986 } else {
7987 format!("Message {} — @ to include context", agent_name)
7988 }
7989}
7990
7991impl Focusable for AcpThreadView {
7992 fn focus_handle(&self, cx: &App) -> FocusHandle {
7993 match self.thread_state {
7994 ThreadState::Ready { .. } => self.active_editor(cx).focus_handle(cx),
7995 ThreadState::Loading { .. }
7996 | ThreadState::LoadError(_)
7997 | ThreadState::Unauthenticated { .. } => self.focus_handle.clone(),
7998 }
7999 }
8000}
8001
8002#[cfg(any(test, feature = "test-support"))]
8003impl AcpThreadView {
8004 /// Expands a tool call so its content is visible.
8005 /// This is primarily useful for visual testing.
8006 pub fn expand_tool_call(&mut self, tool_call_id: acp::ToolCallId, cx: &mut Context<Self>) {
8007 self.expanded_tool_calls.insert(tool_call_id);
8008 cx.notify();
8009 }
8010
8011 /// Expands a subagent card so its content is visible.
8012 /// This is primarily useful for visual testing.
8013 pub fn expand_subagent(&mut self, session_id: acp::SessionId, cx: &mut Context<Self>) {
8014 self.expanded_subagents.insert(session_id);
8015 cx.notify();
8016 }
8017}
8018
8019impl Render for AcpThreadView {
8020 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8021 let has_messages = self.list_state.item_count() > 0;
8022 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
8023
8024 v_flex()
8025 .size_full()
8026 .key_context("AcpThread")
8027 .on_action(cx.listener(|this, _: &menu::Cancel, _, cx| {
8028 this.cancel_generation(cx);
8029 }))
8030 .on_action(cx.listener(Self::toggle_burn_mode))
8031 .on_action(cx.listener(Self::keep_all))
8032 .on_action(cx.listener(Self::reject_all))
8033 .on_action(cx.listener(Self::allow_always))
8034 .on_action(cx.listener(Self::allow_once))
8035 .on_action(cx.listener(Self::reject_once))
8036 .on_action(cx.listener(Self::handle_authorize_tool_call))
8037 .on_action(cx.listener(Self::handle_select_permission_granularity))
8038 .on_action(cx.listener(Self::open_permission_dropdown))
8039 .on_action(cx.listener(|this, _: &SendNextQueuedMessage, window, cx| {
8040 this.send_queued_message_at_index(0, true, window, cx);
8041 }))
8042 .on_action(cx.listener(|this, _: &ClearMessageQueue, _, cx| {
8043 this.message_queue.clear();
8044 cx.notify();
8045 }))
8046 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
8047 if let Some(config_options_view) = this.config_options_view.as_ref() {
8048 let handled = config_options_view.update(cx, |view, cx| {
8049 view.toggle_category_picker(
8050 acp::SessionConfigOptionCategory::Mode,
8051 window,
8052 cx,
8053 )
8054 });
8055 if handled {
8056 return;
8057 }
8058 }
8059
8060 if let Some(profile_selector) = this.profile_selector.as_ref() {
8061 profile_selector.read(cx).menu_handle().toggle(window, cx);
8062 } else if let Some(mode_selector) = this.mode_selector() {
8063 mode_selector.read(cx).menu_handle().toggle(window, cx);
8064 }
8065 }))
8066 .on_action(cx.listener(|this, _: &CycleModeSelector, window, cx| {
8067 if let Some(config_options_view) = this.config_options_view.as_ref() {
8068 let handled = config_options_view.update(cx, |view, cx| {
8069 view.cycle_category_option(
8070 acp::SessionConfigOptionCategory::Mode,
8071 false,
8072 cx,
8073 )
8074 });
8075 if handled {
8076 return;
8077 }
8078 }
8079
8080 if let Some(profile_selector) = this.profile_selector.as_ref() {
8081 profile_selector.update(cx, |profile_selector, cx| {
8082 profile_selector.cycle_profile(cx);
8083 });
8084 } else if let Some(mode_selector) = this.mode_selector() {
8085 mode_selector.update(cx, |mode_selector, cx| {
8086 mode_selector.cycle_mode(window, cx);
8087 });
8088 }
8089 }))
8090 .on_action(cx.listener(|this, _: &ToggleModelSelector, 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::Model,
8095 window,
8096 cx,
8097 )
8098 });
8099 if handled {
8100 return;
8101 }
8102 }
8103
8104 if let Some(model_selector) = this.model_selector.as_ref() {
8105 model_selector
8106 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
8107 }
8108 }))
8109 .on_action(cx.listener(|this, _: &CycleFavoriteModels, window, cx| {
8110 if let Some(config_options_view) = this.config_options_view.as_ref() {
8111 let handled = config_options_view.update(cx, |view, cx| {
8112 view.cycle_category_option(
8113 acp::SessionConfigOptionCategory::Model,
8114 true,
8115 cx,
8116 )
8117 });
8118 if handled {
8119 return;
8120 }
8121 }
8122
8123 if let Some(model_selector) = this.model_selector.as_ref() {
8124 model_selector.update(cx, |model_selector, cx| {
8125 model_selector.cycle_favorite_models(window, cx);
8126 });
8127 }
8128 }))
8129 .track_focus(&self.focus_handle)
8130 .bg(cx.theme().colors().panel_background)
8131 .child(match &self.thread_state {
8132 ThreadState::Unauthenticated {
8133 connection,
8134 description,
8135 configuration_view,
8136 pending_auth_method,
8137 ..
8138 } => v_flex()
8139 .flex_1()
8140 .size_full()
8141 .justify_end()
8142 .child(self.render_auth_required_state(
8143 connection,
8144 description.as_ref(),
8145 configuration_view.as_ref(),
8146 pending_auth_method.as_ref(),
8147 window,
8148 cx,
8149 ))
8150 .into_any_element(),
8151 ThreadState::Loading { .. } => v_flex()
8152 .flex_1()
8153 .child(self.render_recent_history(cx))
8154 .into_any(),
8155 ThreadState::LoadError(e) => v_flex()
8156 .flex_1()
8157 .size_full()
8158 .items_center()
8159 .justify_end()
8160 .child(self.render_load_error(e, window, cx))
8161 .into_any(),
8162 ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
8163 if has_messages {
8164 this.child(
8165 list(
8166 self.list_state.clone(),
8167 cx.processor(|this, index: usize, window, cx| {
8168 let Some((entry, len)) = this.thread().and_then(|thread| {
8169 let entries = &thread.read(cx).entries();
8170 Some((entries.get(index)?, entries.len()))
8171 }) else {
8172 return Empty.into_any();
8173 };
8174 this.render_entry(index, len, entry, window, cx)
8175 }),
8176 )
8177 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
8178 .flex_grow()
8179 .into_any(),
8180 )
8181 .vertical_scrollbar_for(&self.list_state, window, cx)
8182 .into_any()
8183 } else {
8184 this.child(self.render_recent_history(cx)).into_any()
8185 }
8186 }),
8187 })
8188 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
8189 // above so that the scrollbar doesn't render behind it. The current setup allows
8190 // the scrollbar to stop exactly at the activity bar start.
8191 .when(has_messages, |this| match &self.thread_state {
8192 ThreadState::Ready { thread, .. } => {
8193 this.children(self.render_activity_bar(thread, window, cx))
8194 }
8195 _ => this,
8196 })
8197 .children(self.render_thread_retry_status_callout(window, cx))
8198 .when(self.show_codex_windows_warning, |this| {
8199 this.child(self.render_codex_windows_warning(cx))
8200 })
8201 .children(self.render_thread_error(window, cx))
8202 .when_some(
8203 self.new_server_version_available.as_ref().filter(|_| {
8204 !has_messages || !matches!(self.thread_state, ThreadState::Ready { .. })
8205 }),
8206 |this, version| this.child(self.render_new_version_callout(&version, cx)),
8207 )
8208 .children(
8209 if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
8210 Some(usage_callout.into_any_element())
8211 } else {
8212 self.render_token_limit_callout(cx)
8213 .map(|token_limit_callout| token_limit_callout.into_any_element())
8214 },
8215 )
8216 .child(self.render_message_editor(window, cx))
8217 }
8218}
8219
8220fn default_markdown_style(
8221 buffer_font: bool,
8222 muted_text: bool,
8223 window: &Window,
8224 cx: &App,
8225) -> MarkdownStyle {
8226 let theme_settings = ThemeSettings::get_global(cx);
8227 let colors = cx.theme().colors();
8228
8229 let buffer_font_size = theme_settings.agent_buffer_font_size(cx);
8230
8231 let mut text_style = window.text_style();
8232 let line_height = buffer_font_size * 1.75;
8233
8234 let font_family = if buffer_font {
8235 theme_settings.buffer_font.family.clone()
8236 } else {
8237 theme_settings.ui_font.family.clone()
8238 };
8239
8240 let font_size = if buffer_font {
8241 theme_settings.agent_buffer_font_size(cx)
8242 } else {
8243 theme_settings.agent_ui_font_size(cx)
8244 };
8245
8246 let text_color = if muted_text {
8247 colors.text_muted
8248 } else {
8249 colors.text
8250 };
8251
8252 text_style.refine(&TextStyleRefinement {
8253 font_family: Some(font_family),
8254 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
8255 font_features: Some(theme_settings.ui_font.features.clone()),
8256 font_size: Some(font_size.into()),
8257 line_height: Some(line_height.into()),
8258 color: Some(text_color),
8259 ..Default::default()
8260 });
8261
8262 MarkdownStyle {
8263 base_text_style: text_style.clone(),
8264 syntax: cx.theme().syntax().clone(),
8265 selection_background_color: colors.element_selection_background,
8266 code_block_overflow_x_scroll: true,
8267 heading_level_styles: Some(HeadingLevelStyles {
8268 h1: Some(TextStyleRefinement {
8269 font_size: Some(rems(1.15).into()),
8270 ..Default::default()
8271 }),
8272 h2: Some(TextStyleRefinement {
8273 font_size: Some(rems(1.1).into()),
8274 ..Default::default()
8275 }),
8276 h3: Some(TextStyleRefinement {
8277 font_size: Some(rems(1.05).into()),
8278 ..Default::default()
8279 }),
8280 h4: Some(TextStyleRefinement {
8281 font_size: Some(rems(1.).into()),
8282 ..Default::default()
8283 }),
8284 h5: Some(TextStyleRefinement {
8285 font_size: Some(rems(0.95).into()),
8286 ..Default::default()
8287 }),
8288 h6: Some(TextStyleRefinement {
8289 font_size: Some(rems(0.875).into()),
8290 ..Default::default()
8291 }),
8292 }),
8293 code_block: StyleRefinement {
8294 padding: EdgesRefinement {
8295 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
8296 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
8297 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
8298 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
8299 },
8300 margin: EdgesRefinement {
8301 top: Some(Length::Definite(px(8.).into())),
8302 left: Some(Length::Definite(px(0.).into())),
8303 right: Some(Length::Definite(px(0.).into())),
8304 bottom: Some(Length::Definite(px(12.).into())),
8305 },
8306 border_style: Some(BorderStyle::Solid),
8307 border_widths: EdgesRefinement {
8308 top: Some(AbsoluteLength::Pixels(px(1.))),
8309 left: Some(AbsoluteLength::Pixels(px(1.))),
8310 right: Some(AbsoluteLength::Pixels(px(1.))),
8311 bottom: Some(AbsoluteLength::Pixels(px(1.))),
8312 },
8313 border_color: Some(colors.border_variant),
8314 background: Some(colors.editor_background.into()),
8315 text: TextStyleRefinement {
8316 font_family: Some(theme_settings.buffer_font.family.clone()),
8317 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
8318 font_features: Some(theme_settings.buffer_font.features.clone()),
8319 font_size: Some(buffer_font_size.into()),
8320 ..Default::default()
8321 },
8322 ..Default::default()
8323 },
8324 inline_code: TextStyleRefinement {
8325 font_family: Some(theme_settings.buffer_font.family.clone()),
8326 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
8327 font_features: Some(theme_settings.buffer_font.features.clone()),
8328 font_size: Some(buffer_font_size.into()),
8329 background_color: Some(colors.editor_foreground.opacity(0.08)),
8330 ..Default::default()
8331 },
8332 link: TextStyleRefinement {
8333 background_color: Some(colors.editor_foreground.opacity(0.025)),
8334 color: Some(colors.text_accent),
8335 underline: Some(UnderlineStyle {
8336 color: Some(colors.text_accent.opacity(0.5)),
8337 thickness: px(1.),
8338 ..Default::default()
8339 }),
8340 ..Default::default()
8341 },
8342 ..Default::default()
8343 }
8344}
8345
8346fn plan_label_markdown_style(
8347 status: &acp::PlanEntryStatus,
8348 window: &Window,
8349 cx: &App,
8350) -> MarkdownStyle {
8351 let default_md_style = default_markdown_style(false, false, window, cx);
8352
8353 MarkdownStyle {
8354 base_text_style: TextStyle {
8355 color: cx.theme().colors().text_muted,
8356 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
8357 Some(gpui::StrikethroughStyle {
8358 thickness: px(1.),
8359 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
8360 })
8361 } else {
8362 None
8363 },
8364 ..default_md_style.base_text_style
8365 },
8366 ..default_md_style
8367 }
8368}
8369
8370#[cfg(test)]
8371pub(crate) mod tests {
8372 use acp_thread::{
8373 AgentSessionList, AgentSessionListRequest, AgentSessionListResponse, StubAgentConnection,
8374 };
8375 use action_log::ActionLog;
8376 use agent::ToolPermissionContext;
8377 use agent_client_protocol::SessionId;
8378 use editor::MultiBufferOffset;
8379 use fs::FakeFs;
8380 use gpui::{EventEmitter, TestAppContext, VisualTestContext};
8381 use project::Project;
8382 use serde_json::json;
8383 use settings::SettingsStore;
8384 use std::any::Any;
8385 use std::path::Path;
8386 use std::rc::Rc;
8387 use workspace::Item;
8388
8389 use super::*;
8390
8391 #[gpui::test]
8392 async fn test_drop(cx: &mut TestAppContext) {
8393 init_test(cx);
8394
8395 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
8396 let weak_view = thread_view.downgrade();
8397 drop(thread_view);
8398 assert!(!weak_view.is_upgradable());
8399 }
8400
8401 #[gpui::test]
8402 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
8403 init_test(cx);
8404
8405 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
8406
8407 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8408 message_editor.update_in(cx, |editor, window, cx| {
8409 editor.set_text("Hello", window, cx);
8410 });
8411
8412 cx.deactivate_window();
8413
8414 thread_view.update_in(cx, |thread_view, window, cx| {
8415 thread_view.send(window, cx);
8416 });
8417
8418 cx.run_until_parked();
8419
8420 assert!(
8421 cx.windows()
8422 .iter()
8423 .any(|window| window.downcast::<AgentNotification>().is_some())
8424 );
8425 }
8426
8427 #[gpui::test]
8428 async fn test_notification_for_error(cx: &mut TestAppContext) {
8429 init_test(cx);
8430
8431 let (thread_view, cx) =
8432 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
8433
8434 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8435 message_editor.update_in(cx, |editor, window, cx| {
8436 editor.set_text("Hello", window, cx);
8437 });
8438
8439 cx.deactivate_window();
8440
8441 thread_view.update_in(cx, |thread_view, window, cx| {
8442 thread_view.send(window, cx);
8443 });
8444
8445 cx.run_until_parked();
8446
8447 assert!(
8448 cx.windows()
8449 .iter()
8450 .any(|window| window.downcast::<AgentNotification>().is_some())
8451 );
8452 }
8453
8454 #[gpui::test]
8455 async fn test_recent_history_refreshes_when_history_cache_updated(cx: &mut TestAppContext) {
8456 init_test(cx);
8457
8458 let session_a = AgentSessionInfo::new(SessionId::new("session-a"));
8459 let session_b = AgentSessionInfo::new(SessionId::new("session-b"));
8460
8461 let fs = FakeFs::new(cx.executor());
8462 let project = Project::test(fs, [], cx).await;
8463 let (workspace, cx) =
8464 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8465
8466 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
8467 // Create history without an initial session list - it will be set after connection
8468 let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
8469
8470 let thread_view = cx.update(|window, cx| {
8471 cx.new(|cx| {
8472 AcpThreadView::new(
8473 Rc::new(StubAgentServer::default_response()),
8474 None,
8475 None,
8476 workspace.downgrade(),
8477 project,
8478 Some(thread_store),
8479 None,
8480 history.clone(),
8481 false,
8482 window,
8483 cx,
8484 )
8485 })
8486 });
8487
8488 // Wait for connection to establish
8489 cx.run_until_parked();
8490
8491 // Initially empty because StubAgentConnection.session_list() returns None
8492 thread_view.read_with(cx, |view, _cx| {
8493 assert_eq!(view.recent_history_entries.len(), 0);
8494 });
8495
8496 // Now set the session list - this simulates external agents providing their history
8497 let list_a: Rc<dyn AgentSessionList> =
8498 Rc::new(StubSessionList::new(vec![session_a.clone()]));
8499 history.update(cx, |history, cx| {
8500 history.set_session_list(Some(list_a), cx);
8501 });
8502 cx.run_until_parked();
8503
8504 thread_view.read_with(cx, |view, _cx| {
8505 assert_eq!(view.recent_history_entries.len(), 1);
8506 assert_eq!(
8507 view.recent_history_entries[0].session_id,
8508 session_a.session_id
8509 );
8510 });
8511
8512 // Update to a different session list
8513 let list_b: Rc<dyn AgentSessionList> =
8514 Rc::new(StubSessionList::new(vec![session_b.clone()]));
8515 history.update(cx, |history, cx| {
8516 history.set_session_list(Some(list_b), cx);
8517 });
8518 cx.run_until_parked();
8519
8520 thread_view.read_with(cx, |view, _cx| {
8521 assert_eq!(view.recent_history_entries.len(), 1);
8522 assert_eq!(
8523 view.recent_history_entries[0].session_id,
8524 session_b.session_id
8525 );
8526 });
8527 }
8528
8529 #[gpui::test]
8530 async fn test_refusal_handling(cx: &mut TestAppContext) {
8531 init_test(cx);
8532
8533 let (thread_view, cx) =
8534 setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
8535
8536 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8537 message_editor.update_in(cx, |editor, window, cx| {
8538 editor.set_text("Do something harmful", window, cx);
8539 });
8540
8541 thread_view.update_in(cx, |thread_view, window, cx| {
8542 thread_view.send(window, cx);
8543 });
8544
8545 cx.run_until_parked();
8546
8547 // Check that the refusal error is set
8548 thread_view.read_with(cx, |thread_view, _cx| {
8549 assert!(
8550 matches!(thread_view.thread_error, Some(ThreadError::Refusal)),
8551 "Expected refusal error to be set"
8552 );
8553 });
8554 }
8555
8556 #[gpui::test]
8557 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
8558 init_test(cx);
8559
8560 let tool_call_id = acp::ToolCallId::new("1");
8561 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Label")
8562 .kind(acp::ToolKind::Edit)
8563 .content(vec!["hi".into()]);
8564 let connection =
8565 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
8566 tool_call_id,
8567 vec![acp::PermissionOption::new(
8568 "1",
8569 "Allow",
8570 acp::PermissionOptionKind::AllowOnce,
8571 )],
8572 )]));
8573
8574 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
8575
8576 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
8577
8578 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8579 message_editor.update_in(cx, |editor, window, cx| {
8580 editor.set_text("Hello", window, cx);
8581 });
8582
8583 cx.deactivate_window();
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 assert!(
8592 cx.windows()
8593 .iter()
8594 .any(|window| window.downcast::<AgentNotification>().is_some())
8595 );
8596 }
8597
8598 #[gpui::test]
8599 async fn test_notification_when_panel_hidden(cx: &mut TestAppContext) {
8600 init_test(cx);
8601
8602 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
8603
8604 add_to_workspace(thread_view.clone(), cx);
8605
8606 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8607
8608 message_editor.update_in(cx, |editor, window, cx| {
8609 editor.set_text("Hello", window, cx);
8610 });
8611
8612 // Window is active (don't deactivate), but panel will be hidden
8613 // Note: In the test environment, the panel is not actually added to the dock,
8614 // so is_agent_panel_hidden will return true
8615
8616 thread_view.update_in(cx, |thread_view, window, cx| {
8617 thread_view.send(window, cx);
8618 });
8619
8620 cx.run_until_parked();
8621
8622 // Should show notification because window is active but panel is hidden
8623 assert!(
8624 cx.windows()
8625 .iter()
8626 .any(|window| window.downcast::<AgentNotification>().is_some()),
8627 "Expected notification when panel is hidden"
8628 );
8629 }
8630
8631 #[gpui::test]
8632 async fn test_notification_still_works_when_window_inactive(cx: &mut TestAppContext) {
8633 init_test(cx);
8634
8635 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
8636
8637 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8638 message_editor.update_in(cx, |editor, window, cx| {
8639 editor.set_text("Hello", window, cx);
8640 });
8641
8642 // Deactivate window - should show notification regardless of setting
8643 cx.deactivate_window();
8644
8645 thread_view.update_in(cx, |thread_view, window, cx| {
8646 thread_view.send(window, cx);
8647 });
8648
8649 cx.run_until_parked();
8650
8651 // Should still show notification when window is inactive (existing behavior)
8652 assert!(
8653 cx.windows()
8654 .iter()
8655 .any(|window| window.downcast::<AgentNotification>().is_some()),
8656 "Expected notification when window is inactive"
8657 );
8658 }
8659
8660 #[gpui::test]
8661 async fn test_notification_respects_never_setting(cx: &mut TestAppContext) {
8662 init_test(cx);
8663
8664 // Set notify_when_agent_waiting to Never
8665 cx.update(|cx| {
8666 AgentSettings::override_global(
8667 AgentSettings {
8668 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
8669 ..AgentSettings::get_global(cx).clone()
8670 },
8671 cx,
8672 );
8673 });
8674
8675 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
8676
8677 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8678 message_editor.update_in(cx, |editor, window, cx| {
8679 editor.set_text("Hello", window, cx);
8680 });
8681
8682 // Window is active
8683
8684 thread_view.update_in(cx, |thread_view, window, cx| {
8685 thread_view.send(window, cx);
8686 });
8687
8688 cx.run_until_parked();
8689
8690 // Should NOT show notification because notify_when_agent_waiting is Never
8691 assert!(
8692 !cx.windows()
8693 .iter()
8694 .any(|window| window.downcast::<AgentNotification>().is_some()),
8695 "Expected no notification when notify_when_agent_waiting is Never"
8696 );
8697 }
8698
8699 #[gpui::test]
8700 async fn test_notification_closed_when_thread_view_dropped(cx: &mut TestAppContext) {
8701 init_test(cx);
8702
8703 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
8704
8705 let weak_view = thread_view.downgrade();
8706
8707 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8708 message_editor.update_in(cx, |editor, window, cx| {
8709 editor.set_text("Hello", window, cx);
8710 });
8711
8712 cx.deactivate_window();
8713
8714 thread_view.update_in(cx, |thread_view, window, cx| {
8715 thread_view.send(window, cx);
8716 });
8717
8718 cx.run_until_parked();
8719
8720 // Verify notification is shown
8721 assert!(
8722 cx.windows()
8723 .iter()
8724 .any(|window| window.downcast::<AgentNotification>().is_some()),
8725 "Expected notification to be shown"
8726 );
8727
8728 // Drop the thread view (simulating navigation to a new thread)
8729 drop(thread_view);
8730 drop(message_editor);
8731 // Trigger an update to flush effects, which will call release_dropped_entities
8732 cx.update(|_window, _cx| {});
8733 cx.run_until_parked();
8734
8735 // Verify the entity was actually released
8736 assert!(
8737 !weak_view.is_upgradable(),
8738 "Thread view entity should be released after dropping"
8739 );
8740
8741 // The notification should be automatically closed via on_release
8742 assert!(
8743 !cx.windows()
8744 .iter()
8745 .any(|window| window.downcast::<AgentNotification>().is_some()),
8746 "Notification should be closed when thread view is dropped"
8747 );
8748 }
8749
8750 async fn setup_thread_view(
8751 agent: impl AgentServer + 'static,
8752 cx: &mut TestAppContext,
8753 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
8754 let fs = FakeFs::new(cx.executor());
8755 let project = Project::test(fs, [], cx).await;
8756 let (workspace, cx) =
8757 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8758
8759 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
8760 let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
8761
8762 let thread_view = cx.update(|window, cx| {
8763 cx.new(|cx| {
8764 AcpThreadView::new(
8765 Rc::new(agent),
8766 None,
8767 None,
8768 workspace.downgrade(),
8769 project,
8770 Some(thread_store),
8771 None,
8772 history,
8773 false,
8774 window,
8775 cx,
8776 )
8777 })
8778 });
8779 cx.run_until_parked();
8780 (thread_view, cx)
8781 }
8782
8783 fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
8784 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
8785
8786 workspace
8787 .update_in(cx, |workspace, window, cx| {
8788 workspace.add_item_to_active_pane(
8789 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
8790 None,
8791 true,
8792 window,
8793 cx,
8794 );
8795 })
8796 .unwrap();
8797 }
8798
8799 struct ThreadViewItem(Entity<AcpThreadView>);
8800
8801 impl Item for ThreadViewItem {
8802 type Event = ();
8803
8804 fn include_in_nav_history() -> bool {
8805 false
8806 }
8807
8808 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
8809 "Test".into()
8810 }
8811 }
8812
8813 impl EventEmitter<()> for ThreadViewItem {}
8814
8815 impl Focusable for ThreadViewItem {
8816 fn focus_handle(&self, cx: &App) -> FocusHandle {
8817 self.0.read(cx).focus_handle(cx)
8818 }
8819 }
8820
8821 impl Render for ThreadViewItem {
8822 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8823 self.0.clone().into_any_element()
8824 }
8825 }
8826
8827 struct StubAgentServer<C> {
8828 connection: C,
8829 }
8830
8831 impl<C> StubAgentServer<C> {
8832 fn new(connection: C) -> Self {
8833 Self { connection }
8834 }
8835 }
8836
8837 impl StubAgentServer<StubAgentConnection> {
8838 fn default_response() -> Self {
8839 let conn = StubAgentConnection::new();
8840 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8841 acp::ContentChunk::new("Default response".into()),
8842 )]);
8843 Self::new(conn)
8844 }
8845 }
8846
8847 #[derive(Clone)]
8848 struct StubSessionList {
8849 sessions: Vec<AgentSessionInfo>,
8850 }
8851
8852 impl StubSessionList {
8853 fn new(sessions: Vec<AgentSessionInfo>) -> Self {
8854 Self { sessions }
8855 }
8856 }
8857
8858 impl AgentSessionList for StubSessionList {
8859 fn list_sessions(
8860 &self,
8861 _request: AgentSessionListRequest,
8862 _cx: &mut App,
8863 ) -> Task<anyhow::Result<AgentSessionListResponse>> {
8864 Task::ready(Ok(AgentSessionListResponse::new(self.sessions.clone())))
8865 }
8866 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
8867 self
8868 }
8869 }
8870
8871 impl<C> AgentServer for StubAgentServer<C>
8872 where
8873 C: 'static + AgentConnection + Send + Clone,
8874 {
8875 fn logo(&self) -> ui::IconName {
8876 ui::IconName::Ai
8877 }
8878
8879 fn name(&self) -> SharedString {
8880 "Test".into()
8881 }
8882
8883 fn connect(
8884 &self,
8885 _root_dir: Option<&Path>,
8886 _delegate: AgentServerDelegate,
8887 _cx: &mut App,
8888 ) -> Task<gpui::Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
8889 Task::ready(Ok((Rc::new(self.connection.clone()), None)))
8890 }
8891
8892 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
8893 self
8894 }
8895 }
8896
8897 #[derive(Clone)]
8898 struct SaboteurAgentConnection;
8899
8900 impl AgentConnection for SaboteurAgentConnection {
8901 fn telemetry_id(&self) -> SharedString {
8902 "saboteur".into()
8903 }
8904
8905 fn new_thread(
8906 self: Rc<Self>,
8907 project: Entity<Project>,
8908 _cwd: &Path,
8909 cx: &mut gpui::App,
8910 ) -> Task<gpui::Result<Entity<AcpThread>>> {
8911 Task::ready(Ok(cx.new(|cx| {
8912 let action_log = cx.new(|_| ActionLog::new(project.clone()));
8913 AcpThread::new(
8914 "SaboteurAgentConnection",
8915 self,
8916 project,
8917 action_log,
8918 SessionId::new("test"),
8919 watch::Receiver::constant(
8920 acp::PromptCapabilities::new()
8921 .image(true)
8922 .audio(true)
8923 .embedded_context(true),
8924 ),
8925 cx,
8926 )
8927 })))
8928 }
8929
8930 fn auth_methods(&self) -> &[acp::AuthMethod] {
8931 &[]
8932 }
8933
8934 fn authenticate(
8935 &self,
8936 _method_id: acp::AuthMethodId,
8937 _cx: &mut App,
8938 ) -> Task<gpui::Result<()>> {
8939 unimplemented!()
8940 }
8941
8942 fn prompt(
8943 &self,
8944 _id: Option<acp_thread::UserMessageId>,
8945 _params: acp::PromptRequest,
8946 _cx: &mut App,
8947 ) -> Task<gpui::Result<acp::PromptResponse>> {
8948 Task::ready(Err(anyhow::anyhow!("Error prompting")))
8949 }
8950
8951 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
8952 unimplemented!()
8953 }
8954
8955 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
8956 self
8957 }
8958 }
8959
8960 /// Simulates a model which always returns a refusal response
8961 #[derive(Clone)]
8962 struct RefusalAgentConnection;
8963
8964 impl AgentConnection for RefusalAgentConnection {
8965 fn telemetry_id(&self) -> SharedString {
8966 "refusal".into()
8967 }
8968
8969 fn new_thread(
8970 self: Rc<Self>,
8971 project: Entity<Project>,
8972 _cwd: &Path,
8973 cx: &mut gpui::App,
8974 ) -> Task<gpui::Result<Entity<AcpThread>>> {
8975 Task::ready(Ok(cx.new(|cx| {
8976 let action_log = cx.new(|_| ActionLog::new(project.clone()));
8977 AcpThread::new(
8978 "RefusalAgentConnection",
8979 self,
8980 project,
8981 action_log,
8982 SessionId::new("test"),
8983 watch::Receiver::constant(
8984 acp::PromptCapabilities::new()
8985 .image(true)
8986 .audio(true)
8987 .embedded_context(true),
8988 ),
8989 cx,
8990 )
8991 })))
8992 }
8993
8994 fn auth_methods(&self) -> &[acp::AuthMethod] {
8995 &[]
8996 }
8997
8998 fn authenticate(
8999 &self,
9000 _method_id: acp::AuthMethodId,
9001 _cx: &mut App,
9002 ) -> Task<gpui::Result<()>> {
9003 unimplemented!()
9004 }
9005
9006 fn prompt(
9007 &self,
9008 _id: Option<acp_thread::UserMessageId>,
9009 _params: acp::PromptRequest,
9010 _cx: &mut App,
9011 ) -> Task<gpui::Result<acp::PromptResponse>> {
9012 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::Refusal)))
9013 }
9014
9015 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
9016 unimplemented!()
9017 }
9018
9019 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
9020 self
9021 }
9022 }
9023
9024 pub(crate) fn init_test(cx: &mut TestAppContext) {
9025 cx.update(|cx| {
9026 let settings_store = SettingsStore::test(cx);
9027 cx.set_global(settings_store);
9028 theme::init(theme::LoadThemes::JustBase, cx);
9029 release_channel::init(semver::Version::new(0, 0, 0), cx);
9030 prompt_store::init(cx)
9031 });
9032 }
9033
9034 #[gpui::test]
9035 async fn test_rewind_views(cx: &mut TestAppContext) {
9036 init_test(cx);
9037
9038 let fs = FakeFs::new(cx.executor());
9039 fs.insert_tree(
9040 "/project",
9041 json!({
9042 "test1.txt": "old content 1",
9043 "test2.txt": "old content 2"
9044 }),
9045 )
9046 .await;
9047 let project = Project::test(fs, [Path::new("/project")], cx).await;
9048 let (workspace, cx) =
9049 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9050
9051 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
9052 let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
9053
9054 let connection = Rc::new(StubAgentConnection::new());
9055 let thread_view = cx.update(|window, cx| {
9056 cx.new(|cx| {
9057 AcpThreadView::new(
9058 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
9059 None,
9060 None,
9061 workspace.downgrade(),
9062 project.clone(),
9063 Some(thread_store.clone()),
9064 None,
9065 history,
9066 false,
9067 window,
9068 cx,
9069 )
9070 })
9071 });
9072
9073 cx.run_until_parked();
9074
9075 let thread = thread_view
9076 .read_with(cx, |view, _| view.thread().cloned())
9077 .unwrap();
9078
9079 // First user message
9080 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
9081 acp::ToolCall::new("tool1", "Edit file 1")
9082 .kind(acp::ToolKind::Edit)
9083 .status(acp::ToolCallStatus::Completed)
9084 .content(vec![acp::ToolCallContent::Diff(
9085 acp::Diff::new("/project/test1.txt", "new content 1").old_text("old content 1"),
9086 )]),
9087 )]);
9088
9089 thread
9090 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
9091 .await
9092 .unwrap();
9093 cx.run_until_parked();
9094
9095 thread.read_with(cx, |thread, _| {
9096 assert_eq!(thread.entries().len(), 2);
9097 });
9098
9099 thread_view.read_with(cx, |view, cx| {
9100 view.entry_view_state.read_with(cx, |entry_view_state, _| {
9101 assert!(
9102 entry_view_state
9103 .entry(0)
9104 .unwrap()
9105 .message_editor()
9106 .is_some()
9107 );
9108 assert!(entry_view_state.entry(1).unwrap().has_content());
9109 });
9110 });
9111
9112 // Second user message
9113 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
9114 acp::ToolCall::new("tool2", "Edit file 2")
9115 .kind(acp::ToolKind::Edit)
9116 .status(acp::ToolCallStatus::Completed)
9117 .content(vec![acp::ToolCallContent::Diff(
9118 acp::Diff::new("/project/test2.txt", "new content 2").old_text("old content 2"),
9119 )]),
9120 )]);
9121
9122 thread
9123 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
9124 .await
9125 .unwrap();
9126 cx.run_until_parked();
9127
9128 let second_user_message_id = thread.read_with(cx, |thread, _| {
9129 assert_eq!(thread.entries().len(), 4);
9130 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
9131 panic!();
9132 };
9133 user_message.id.clone().unwrap()
9134 });
9135
9136 thread_view.read_with(cx, |view, cx| {
9137 view.entry_view_state.read_with(cx, |entry_view_state, _| {
9138 assert!(
9139 entry_view_state
9140 .entry(0)
9141 .unwrap()
9142 .message_editor()
9143 .is_some()
9144 );
9145 assert!(entry_view_state.entry(1).unwrap().has_content());
9146 assert!(
9147 entry_view_state
9148 .entry(2)
9149 .unwrap()
9150 .message_editor()
9151 .is_some()
9152 );
9153 assert!(entry_view_state.entry(3).unwrap().has_content());
9154 });
9155 });
9156
9157 // Rewind to first message
9158 thread
9159 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
9160 .await
9161 .unwrap();
9162
9163 cx.run_until_parked();
9164
9165 thread.read_with(cx, |thread, _| {
9166 assert_eq!(thread.entries().len(), 2);
9167 });
9168
9169 thread_view.read_with(cx, |view, cx| {
9170 view.entry_view_state.read_with(cx, |entry_view_state, _| {
9171 assert!(
9172 entry_view_state
9173 .entry(0)
9174 .unwrap()
9175 .message_editor()
9176 .is_some()
9177 );
9178 assert!(entry_view_state.entry(1).unwrap().has_content());
9179
9180 // Old views should be dropped
9181 assert!(entry_view_state.entry(2).is_none());
9182 assert!(entry_view_state.entry(3).is_none());
9183 });
9184 });
9185 }
9186
9187 #[gpui::test]
9188 async fn test_scroll_to_most_recent_user_prompt(cx: &mut TestAppContext) {
9189 init_test(cx);
9190
9191 let connection = StubAgentConnection::new();
9192
9193 // Each user prompt will result in a user message entry plus an agent message entry.
9194 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
9195 acp::ContentChunk::new("Response 1".into()),
9196 )]);
9197
9198 let (thread_view, cx) =
9199 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
9200
9201 let thread = thread_view
9202 .read_with(cx, |view, _| view.thread().cloned())
9203 .unwrap();
9204
9205 thread
9206 .update(cx, |thread, cx| thread.send_raw("Prompt 1", cx))
9207 .await
9208 .unwrap();
9209 cx.run_until_parked();
9210
9211 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
9212 acp::ContentChunk::new("Response 2".into()),
9213 )]);
9214
9215 thread
9216 .update(cx, |thread, cx| thread.send_raw("Prompt 2", cx))
9217 .await
9218 .unwrap();
9219 cx.run_until_parked();
9220
9221 // Move somewhere else first so we're not trivially already on the last user prompt.
9222 thread_view.update(cx, |view, cx| {
9223 view.scroll_to_top(cx);
9224 });
9225 cx.run_until_parked();
9226
9227 thread_view.update(cx, |view, cx| {
9228 view.scroll_to_most_recent_user_prompt(cx);
9229 let scroll_top = view.list_state.logical_scroll_top();
9230 // Entries layout is: [User1, Assistant1, User2, Assistant2]
9231 assert_eq!(scroll_top.item_ix, 2);
9232 });
9233 }
9234
9235 #[gpui::test]
9236 async fn test_scroll_to_most_recent_user_prompt_falls_back_to_bottom_without_user_messages(
9237 cx: &mut TestAppContext,
9238 ) {
9239 init_test(cx);
9240
9241 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
9242
9243 // With no entries, scrolling should be a no-op and must not panic.
9244 thread_view.update(cx, |view, cx| {
9245 view.scroll_to_most_recent_user_prompt(cx);
9246 let scroll_top = view.list_state.logical_scroll_top();
9247 assert_eq!(scroll_top.item_ix, 0);
9248 });
9249 }
9250
9251 #[gpui::test]
9252 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
9253 init_test(cx);
9254
9255 let connection = StubAgentConnection::new();
9256
9257 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
9258 acp::ContentChunk::new("Response".into()),
9259 )]);
9260
9261 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
9262 add_to_workspace(thread_view.clone(), cx);
9263
9264 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9265 message_editor.update_in(cx, |editor, window, cx| {
9266 editor.set_text("Original message to edit", window, cx);
9267 });
9268 thread_view.update_in(cx, |thread_view, window, cx| {
9269 thread_view.send(window, cx);
9270 });
9271
9272 cx.run_until_parked();
9273
9274 let user_message_editor = thread_view.read_with(cx, |view, cx| {
9275 assert_eq!(view.editing_message, None);
9276
9277 view.entry_view_state
9278 .read(cx)
9279 .entry(0)
9280 .unwrap()
9281 .message_editor()
9282 .unwrap()
9283 .clone()
9284 });
9285
9286 // Focus
9287 cx.focus(&user_message_editor);
9288 thread_view.read_with(cx, |view, _cx| {
9289 assert_eq!(view.editing_message, Some(0));
9290 });
9291
9292 // Edit
9293 user_message_editor.update_in(cx, |editor, window, cx| {
9294 editor.set_text("Edited message content", window, cx);
9295 });
9296
9297 // Cancel
9298 user_message_editor.update_in(cx, |_editor, window, cx| {
9299 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
9300 });
9301
9302 thread_view.read_with(cx, |view, _cx| {
9303 assert_eq!(view.editing_message, None);
9304 });
9305
9306 user_message_editor.read_with(cx, |editor, cx| {
9307 assert_eq!(editor.text(cx), "Original message to edit");
9308 });
9309 }
9310
9311 #[gpui::test]
9312 async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
9313 init_test(cx);
9314
9315 let connection = StubAgentConnection::new();
9316
9317 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
9318 add_to_workspace(thread_view.clone(), cx);
9319
9320 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9321 let mut events = cx.events(&message_editor);
9322 message_editor.update_in(cx, |editor, window, cx| {
9323 editor.set_text("", window, cx);
9324 });
9325
9326 message_editor.update_in(cx, |_editor, window, cx| {
9327 window.dispatch_action(Box::new(Chat), cx);
9328 });
9329 cx.run_until_parked();
9330 // We shouldn't have received any messages
9331 assert!(matches!(
9332 events.try_next(),
9333 Err(futures::channel::mpsc::TryRecvError { .. })
9334 ));
9335 }
9336
9337 #[gpui::test]
9338 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
9339 init_test(cx);
9340
9341 let connection = StubAgentConnection::new();
9342
9343 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
9344 acp::ContentChunk::new("Response".into()),
9345 )]);
9346
9347 let (thread_view, cx) =
9348 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
9349 add_to_workspace(thread_view.clone(), cx);
9350
9351 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9352 message_editor.update_in(cx, |editor, window, cx| {
9353 editor.set_text("Original message to edit", window, cx);
9354 });
9355 thread_view.update_in(cx, |thread_view, window, cx| {
9356 thread_view.send(window, cx);
9357 });
9358
9359 cx.run_until_parked();
9360
9361 let user_message_editor = thread_view.read_with(cx, |view, cx| {
9362 assert_eq!(view.editing_message, None);
9363 assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
9364
9365 view.entry_view_state
9366 .read(cx)
9367 .entry(0)
9368 .unwrap()
9369 .message_editor()
9370 .unwrap()
9371 .clone()
9372 });
9373
9374 // Focus
9375 cx.focus(&user_message_editor);
9376
9377 // Edit
9378 user_message_editor.update_in(cx, |editor, window, cx| {
9379 editor.set_text("Edited message content", window, cx);
9380 });
9381
9382 // Send
9383 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
9384 acp::ContentChunk::new("New Response".into()),
9385 )]);
9386
9387 user_message_editor.update_in(cx, |_editor, window, cx| {
9388 window.dispatch_action(Box::new(Chat), cx);
9389 });
9390
9391 cx.run_until_parked();
9392
9393 thread_view.read_with(cx, |view, cx| {
9394 assert_eq!(view.editing_message, None);
9395
9396 let entries = view.thread().unwrap().read(cx).entries();
9397 assert_eq!(entries.len(), 2);
9398 assert_eq!(
9399 entries[0].to_markdown(cx),
9400 "## User\n\nEdited message content\n\n"
9401 );
9402 assert_eq!(
9403 entries[1].to_markdown(cx),
9404 "## Assistant\n\nNew Response\n\n"
9405 );
9406
9407 let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
9408 assert!(!state.entry(1).unwrap().has_content());
9409 state.entry(0).unwrap().message_editor().unwrap().clone()
9410 });
9411
9412 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
9413 })
9414 }
9415
9416 #[gpui::test]
9417 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
9418 init_test(cx);
9419
9420 let connection = StubAgentConnection::new();
9421
9422 let (thread_view, cx) =
9423 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
9424 add_to_workspace(thread_view.clone(), cx);
9425
9426 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9427 message_editor.update_in(cx, |editor, window, cx| {
9428 editor.set_text("Original message to edit", window, cx);
9429 });
9430 thread_view.update_in(cx, |thread_view, window, cx| {
9431 thread_view.send(window, cx);
9432 });
9433
9434 cx.run_until_parked();
9435
9436 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
9437 let thread = view.thread().unwrap().read(cx);
9438 assert_eq!(thread.entries().len(), 1);
9439
9440 let editor = view
9441 .entry_view_state
9442 .read(cx)
9443 .entry(0)
9444 .unwrap()
9445 .message_editor()
9446 .unwrap()
9447 .clone();
9448
9449 (editor, thread.session_id().clone())
9450 });
9451
9452 // Focus
9453 cx.focus(&user_message_editor);
9454
9455 thread_view.read_with(cx, |view, _cx| {
9456 assert_eq!(view.editing_message, Some(0));
9457 });
9458
9459 // Edit
9460 user_message_editor.update_in(cx, |editor, window, cx| {
9461 editor.set_text("Edited message content", window, cx);
9462 });
9463
9464 thread_view.read_with(cx, |view, _cx| {
9465 assert_eq!(view.editing_message, Some(0));
9466 });
9467
9468 // Finish streaming response
9469 cx.update(|_, cx| {
9470 connection.send_update(
9471 session_id.clone(),
9472 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("Response".into())),
9473 cx,
9474 );
9475 connection.end_turn(session_id, acp::StopReason::EndTurn);
9476 });
9477
9478 thread_view.read_with(cx, |view, _cx| {
9479 assert_eq!(view.editing_message, Some(0));
9480 });
9481
9482 cx.run_until_parked();
9483
9484 // Should still be editing
9485 cx.update(|window, cx| {
9486 assert!(user_message_editor.focus_handle(cx).is_focused(window));
9487 assert_eq!(thread_view.read(cx).editing_message, Some(0));
9488 assert_eq!(
9489 user_message_editor.read(cx).text(cx),
9490 "Edited message content"
9491 );
9492 });
9493 }
9494
9495 struct GeneratingThreadSetup {
9496 thread_view: Entity<AcpThreadView>,
9497 thread: Entity<AcpThread>,
9498 message_editor: Entity<MessageEditor>,
9499 }
9500
9501 async fn setup_generating_thread(
9502 cx: &mut TestAppContext,
9503 ) -> (GeneratingThreadSetup, &mut VisualTestContext) {
9504 let connection = StubAgentConnection::new();
9505
9506 let (thread_view, cx) =
9507 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
9508 add_to_workspace(thread_view.clone(), cx);
9509
9510 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9511 message_editor.update_in(cx, |editor, window, cx| {
9512 editor.set_text("Hello", window, cx);
9513 });
9514 thread_view.update_in(cx, |thread_view, window, cx| {
9515 thread_view.send(window, cx);
9516 });
9517
9518 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
9519 let thread = view.thread().unwrap();
9520 (thread.clone(), thread.read(cx).session_id().clone())
9521 });
9522
9523 cx.run_until_parked();
9524
9525 cx.update(|_, cx| {
9526 connection.send_update(
9527 session_id.clone(),
9528 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
9529 "Response chunk".into(),
9530 )),
9531 cx,
9532 );
9533 });
9534
9535 cx.run_until_parked();
9536
9537 thread.read_with(cx, |thread, _cx| {
9538 assert_eq!(thread.status(), ThreadStatus::Generating);
9539 });
9540
9541 (
9542 GeneratingThreadSetup {
9543 thread_view,
9544 thread,
9545 message_editor,
9546 },
9547 cx,
9548 )
9549 }
9550
9551 #[gpui::test]
9552 async fn test_escape_cancels_generation_from_conversation_focus(cx: &mut TestAppContext) {
9553 init_test(cx);
9554
9555 let (setup, cx) = setup_generating_thread(cx).await;
9556
9557 let focus_handle = setup
9558 .thread_view
9559 .read_with(cx, |view, _cx| view.focus_handle.clone());
9560 cx.update(|window, cx| {
9561 window.focus(&focus_handle, cx);
9562 });
9563
9564 setup.thread_view.update_in(cx, |_, window, cx| {
9565 window.dispatch_action(menu::Cancel.boxed_clone(), cx);
9566 });
9567
9568 cx.run_until_parked();
9569
9570 setup.thread.read_with(cx, |thread, _cx| {
9571 assert_eq!(thread.status(), ThreadStatus::Idle);
9572 });
9573 }
9574
9575 #[gpui::test]
9576 async fn test_escape_cancels_generation_from_editor_focus(cx: &mut TestAppContext) {
9577 init_test(cx);
9578
9579 let (setup, cx) = setup_generating_thread(cx).await;
9580
9581 let editor_focus_handle = setup
9582 .message_editor
9583 .read_with(cx, |editor, cx| editor.focus_handle(cx));
9584 cx.update(|window, cx| {
9585 window.focus(&editor_focus_handle, cx);
9586 });
9587
9588 setup.message_editor.update_in(cx, |_, window, cx| {
9589 window.dispatch_action(editor::actions::Cancel.boxed_clone(), cx);
9590 });
9591
9592 cx.run_until_parked();
9593
9594 setup.thread.read_with(cx, |thread, _cx| {
9595 assert_eq!(thread.status(), ThreadStatus::Idle);
9596 });
9597 }
9598
9599 #[gpui::test]
9600 async fn test_escape_when_idle_is_noop(cx: &mut TestAppContext) {
9601 init_test(cx);
9602
9603 let (thread_view, cx) =
9604 setup_thread_view(StubAgentServer::new(StubAgentConnection::new()), cx).await;
9605 add_to_workspace(thread_view.clone(), cx);
9606
9607 let thread = thread_view.read_with(cx, |view, _cx| view.thread().unwrap().clone());
9608
9609 thread.read_with(cx, |thread, _cx| {
9610 assert_eq!(thread.status(), ThreadStatus::Idle);
9611 });
9612
9613 let focus_handle = thread_view.read_with(cx, |view, _cx| view.focus_handle.clone());
9614 cx.update(|window, cx| {
9615 window.focus(&focus_handle, cx);
9616 });
9617
9618 thread_view.update_in(cx, |_, window, cx| {
9619 window.dispatch_action(menu::Cancel.boxed_clone(), cx);
9620 });
9621
9622 cx.run_until_parked();
9623
9624 thread.read_with(cx, |thread, _cx| {
9625 assert_eq!(thread.status(), ThreadStatus::Idle);
9626 });
9627 }
9628
9629 #[gpui::test]
9630 async fn test_interrupt(cx: &mut TestAppContext) {
9631 init_test(cx);
9632
9633 let connection = StubAgentConnection::new();
9634
9635 let (thread_view, cx) =
9636 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
9637 add_to_workspace(thread_view.clone(), cx);
9638
9639 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9640 message_editor.update_in(cx, |editor, window, cx| {
9641 editor.set_text("Message 1", window, cx);
9642 });
9643 thread_view.update_in(cx, |thread_view, window, cx| {
9644 thread_view.send(window, cx);
9645 });
9646
9647 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
9648 let thread = view.thread().unwrap();
9649
9650 (thread.clone(), thread.read(cx).session_id().clone())
9651 });
9652
9653 cx.run_until_parked();
9654
9655 cx.update(|_, cx| {
9656 connection.send_update(
9657 session_id.clone(),
9658 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
9659 "Message 1 resp".into(),
9660 )),
9661 cx,
9662 );
9663 });
9664
9665 cx.run_until_parked();
9666
9667 thread.read_with(cx, |thread, cx| {
9668 assert_eq!(
9669 thread.to_markdown(cx),
9670 indoc::indoc! {"
9671 ## User
9672
9673 Message 1
9674
9675 ## Assistant
9676
9677 Message 1 resp
9678
9679 "}
9680 )
9681 });
9682
9683 message_editor.update_in(cx, |editor, window, cx| {
9684 editor.set_text("Message 2", window, cx);
9685 });
9686 thread_view.update_in(cx, |thread_view, window, cx| {
9687 thread_view.interrupt_and_send(window, cx);
9688 });
9689
9690 cx.update(|_, cx| {
9691 // Simulate a response sent after beginning to cancel
9692 connection.send_update(
9693 session_id.clone(),
9694 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("onse".into())),
9695 cx,
9696 );
9697 });
9698
9699 cx.run_until_parked();
9700
9701 // Last Message 1 response should appear before Message 2
9702 thread.read_with(cx, |thread, cx| {
9703 assert_eq!(
9704 thread.to_markdown(cx),
9705 indoc::indoc! {"
9706 ## User
9707
9708 Message 1
9709
9710 ## Assistant
9711
9712 Message 1 response
9713
9714 ## User
9715
9716 Message 2
9717
9718 "}
9719 )
9720 });
9721
9722 cx.update(|_, cx| {
9723 connection.send_update(
9724 session_id.clone(),
9725 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
9726 "Message 2 response".into(),
9727 )),
9728 cx,
9729 );
9730 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
9731 });
9732
9733 cx.run_until_parked();
9734
9735 thread.read_with(cx, |thread, cx| {
9736 assert_eq!(
9737 thread.to_markdown(cx),
9738 indoc::indoc! {"
9739 ## User
9740
9741 Message 1
9742
9743 ## Assistant
9744
9745 Message 1 response
9746
9747 ## User
9748
9749 Message 2
9750
9751 ## Assistant
9752
9753 Message 2 response
9754
9755 "}
9756 )
9757 });
9758 }
9759
9760 #[gpui::test]
9761 async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
9762 init_test(cx);
9763
9764 let connection = StubAgentConnection::new();
9765 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
9766 acp::ContentChunk::new("Response".into()),
9767 )]);
9768
9769 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
9770 add_to_workspace(thread_view.clone(), cx);
9771
9772 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9773 message_editor.update_in(cx, |editor, window, cx| {
9774 editor.set_text("Original message to edit", window, cx)
9775 });
9776 thread_view.update_in(cx, |thread_view, window, cx| thread_view.send(window, cx));
9777 cx.run_until_parked();
9778
9779 let user_message_editor = thread_view.read_with(cx, |thread_view, cx| {
9780 thread_view
9781 .entry_view_state
9782 .read(cx)
9783 .entry(0)
9784 .expect("Should have at least one entry")
9785 .message_editor()
9786 .expect("Should have message editor")
9787 .clone()
9788 });
9789
9790 cx.focus(&user_message_editor);
9791 thread_view.read_with(cx, |thread_view, _cx| {
9792 assert_eq!(thread_view.editing_message, Some(0));
9793 });
9794
9795 // Ensure to edit the focused message before proceeding otherwise, since
9796 // its content is not different from what was sent, focus will be lost.
9797 user_message_editor.update_in(cx, |editor, window, cx| {
9798 editor.set_text("Original message to edit with ", window, cx)
9799 });
9800
9801 // Create a simple buffer with some text so we can create a selection
9802 // that will then be added to the message being edited.
9803 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
9804 (thread_view.workspace.clone(), thread_view.project.clone())
9805 });
9806 let buffer = project.update(cx, |project, cx| {
9807 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
9808 });
9809
9810 workspace
9811 .update_in(cx, |workspace, window, cx| {
9812 let editor = cx.new(|cx| {
9813 let mut editor =
9814 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
9815
9816 editor.change_selections(Default::default(), window, cx, |selections| {
9817 selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
9818 });
9819
9820 editor
9821 });
9822 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
9823 })
9824 .unwrap();
9825
9826 thread_view.update_in(cx, |thread_view, window, cx| {
9827 assert_eq!(thread_view.editing_message, Some(0));
9828 thread_view.insert_selections(window, cx);
9829 });
9830
9831 user_message_editor.read_with(cx, |editor, cx| {
9832 let text = editor.editor().read(cx).text(cx);
9833 let expected_text = String::from("Original message to edit with selection ");
9834
9835 assert_eq!(text, expected_text);
9836 });
9837 }
9838
9839 #[gpui::test]
9840 async fn test_insert_selections(cx: &mut TestAppContext) {
9841 init_test(cx);
9842
9843 let connection = StubAgentConnection::new();
9844 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
9845 acp::ContentChunk::new("Response".into()),
9846 )]);
9847
9848 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
9849 add_to_workspace(thread_view.clone(), cx);
9850
9851 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9852 message_editor.update_in(cx, |editor, window, cx| {
9853 editor.set_text("Can you review this snippet ", window, cx)
9854 });
9855
9856 // Create a simple buffer with some text so we can create a selection
9857 // that will then be added to the message being edited.
9858 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
9859 (thread_view.workspace.clone(), thread_view.project.clone())
9860 });
9861 let buffer = project.update(cx, |project, cx| {
9862 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
9863 });
9864
9865 workspace
9866 .update_in(cx, |workspace, window, cx| {
9867 let editor = cx.new(|cx| {
9868 let mut editor =
9869 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
9870
9871 editor.change_selections(Default::default(), window, cx, |selections| {
9872 selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
9873 });
9874
9875 editor
9876 });
9877 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
9878 })
9879 .unwrap();
9880
9881 thread_view.update_in(cx, |thread_view, window, cx| {
9882 assert_eq!(thread_view.editing_message, None);
9883 thread_view.insert_selections(window, cx);
9884 });
9885
9886 thread_view.read_with(cx, |thread_view, cx| {
9887 let text = thread_view.message_editor.read(cx).text(cx);
9888 let expected_txt = String::from("Can you review this snippet selection ");
9889
9890 assert_eq!(text, expected_txt);
9891 })
9892 }
9893
9894 #[gpui::test]
9895 async fn test_tool_permission_buttons_terminal_with_pattern(cx: &mut TestAppContext) {
9896 init_test(cx);
9897
9898 let tool_call_id = acp::ToolCallId::new("terminal-1");
9899 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build --release`")
9900 .kind(acp::ToolKind::Edit);
9901
9902 let permission_options = ToolPermissionContext::new("terminal", "cargo build --release")
9903 .build_permission_options();
9904
9905 let connection =
9906 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
9907 tool_call_id.clone(),
9908 permission_options,
9909 )]));
9910
9911 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
9912
9913 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
9914
9915 // Disable notifications to avoid popup windows
9916 cx.update(|_window, cx| {
9917 AgentSettings::override_global(
9918 AgentSettings {
9919 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
9920 ..AgentSettings::get_global(cx).clone()
9921 },
9922 cx,
9923 );
9924 });
9925
9926 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9927 message_editor.update_in(cx, |editor, window, cx| {
9928 editor.set_text("Run cargo build", window, cx);
9929 });
9930
9931 thread_view.update_in(cx, |thread_view, window, cx| {
9932 thread_view.send(window, cx);
9933 });
9934
9935 cx.run_until_parked();
9936
9937 // Verify the tool call is in WaitingForConfirmation state with the expected options
9938 thread_view.read_with(cx, |thread_view, cx| {
9939 let thread = thread_view.thread().expect("Thread should exist");
9940 let thread = thread.read(cx);
9941
9942 let tool_call = thread.entries().iter().find_map(|entry| {
9943 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
9944 Some(call)
9945 } else {
9946 None
9947 }
9948 });
9949
9950 assert!(tool_call.is_some(), "Expected a tool call entry");
9951 let tool_call = tool_call.unwrap();
9952
9953 // Verify it's waiting for confirmation
9954 assert!(
9955 matches!(
9956 tool_call.status,
9957 acp_thread::ToolCallStatus::WaitingForConfirmation { .. }
9958 ),
9959 "Expected WaitingForConfirmation status, got {:?}",
9960 tool_call.status
9961 );
9962
9963 // Verify the options count (granularity options only, no separate Deny option)
9964 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
9965 &tool_call.status
9966 {
9967 assert_eq!(
9968 options.len(),
9969 3,
9970 "Expected 3 permission options (granularity only)"
9971 );
9972
9973 // Verify specific button labels (now using neutral names)
9974 let labels: Vec<&str> = options.iter().map(|o| o.name.as_ref()).collect();
9975 assert!(
9976 labels.contains(&"Always for terminal"),
9977 "Missing 'Always for terminal' option"
9978 );
9979 assert!(
9980 labels.contains(&"Always for `cargo` commands"),
9981 "Missing pattern option"
9982 );
9983 assert!(
9984 labels.contains(&"Only this time"),
9985 "Missing 'Only this time' option"
9986 );
9987 }
9988 });
9989 }
9990
9991 #[gpui::test]
9992 async fn test_tool_permission_buttons_edit_file_with_path_pattern(cx: &mut TestAppContext) {
9993 init_test(cx);
9994
9995 let tool_call_id = acp::ToolCallId::new("edit-file-1");
9996 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Edit `src/main.rs`")
9997 .kind(acp::ToolKind::Edit);
9998
9999 let permission_options =
10000 ToolPermissionContext::new("edit_file", "src/main.rs").build_permission_options();
10001
10002 let connection =
10003 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10004 tool_call_id.clone(),
10005 permission_options,
10006 )]));
10007
10008 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10009
10010 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10011
10012 // Disable notifications
10013 cx.update(|_window, cx| {
10014 AgentSettings::override_global(
10015 AgentSettings {
10016 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10017 ..AgentSettings::get_global(cx).clone()
10018 },
10019 cx,
10020 );
10021 });
10022
10023 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10024 message_editor.update_in(cx, |editor, window, cx| {
10025 editor.set_text("Edit the main file", window, cx);
10026 });
10027
10028 thread_view.update_in(cx, |thread_view, window, cx| {
10029 thread_view.send(window, cx);
10030 });
10031
10032 cx.run_until_parked();
10033
10034 // Verify the options
10035 thread_view.read_with(cx, |thread_view, cx| {
10036 let thread = thread_view.thread().expect("Thread should exist");
10037 let thread = thread.read(cx);
10038
10039 let tool_call = thread.entries().iter().find_map(|entry| {
10040 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
10041 Some(call)
10042 } else {
10043 None
10044 }
10045 });
10046
10047 assert!(tool_call.is_some(), "Expected a tool call entry");
10048 let tool_call = tool_call.unwrap();
10049
10050 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
10051 &tool_call.status
10052 {
10053 let labels: Vec<&str> = options.iter().map(|o| o.name.as_ref()).collect();
10054 assert!(
10055 labels.contains(&"Always for edit file"),
10056 "Missing 'Always for edit file' option"
10057 );
10058 assert!(
10059 labels.contains(&"Always for `src/`"),
10060 "Missing path pattern option"
10061 );
10062 } else {
10063 panic!("Expected WaitingForConfirmation status");
10064 }
10065 });
10066 }
10067
10068 #[gpui::test]
10069 async fn test_tool_permission_buttons_fetch_with_domain_pattern(cx: &mut TestAppContext) {
10070 init_test(cx);
10071
10072 let tool_call_id = acp::ToolCallId::new("fetch-1");
10073 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Fetch `https://docs.rs/gpui`")
10074 .kind(acp::ToolKind::Fetch);
10075
10076 let permission_options =
10077 ToolPermissionContext::new("fetch", "https://docs.rs/gpui").build_permission_options();
10078
10079 let connection =
10080 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10081 tool_call_id.clone(),
10082 permission_options,
10083 )]));
10084
10085 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10086
10087 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10088
10089 // Disable notifications
10090 cx.update(|_window, cx| {
10091 AgentSettings::override_global(
10092 AgentSettings {
10093 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10094 ..AgentSettings::get_global(cx).clone()
10095 },
10096 cx,
10097 );
10098 });
10099
10100 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10101 message_editor.update_in(cx, |editor, window, cx| {
10102 editor.set_text("Fetch the docs", window, cx);
10103 });
10104
10105 thread_view.update_in(cx, |thread_view, window, cx| {
10106 thread_view.send(window, cx);
10107 });
10108
10109 cx.run_until_parked();
10110
10111 // Verify the options
10112 thread_view.read_with(cx, |thread_view, cx| {
10113 let thread = thread_view.thread().expect("Thread should exist");
10114 let thread = thread.read(cx);
10115
10116 let tool_call = thread.entries().iter().find_map(|entry| {
10117 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
10118 Some(call)
10119 } else {
10120 None
10121 }
10122 });
10123
10124 assert!(tool_call.is_some(), "Expected a tool call entry");
10125 let tool_call = tool_call.unwrap();
10126
10127 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
10128 &tool_call.status
10129 {
10130 let labels: Vec<&str> = options.iter().map(|o| o.name.as_ref()).collect();
10131 assert!(
10132 labels.contains(&"Always for fetch"),
10133 "Missing 'Always for fetch' option"
10134 );
10135 assert!(
10136 labels.contains(&"Always for `docs.rs`"),
10137 "Missing domain pattern option"
10138 );
10139 } else {
10140 panic!("Expected WaitingForConfirmation status");
10141 }
10142 });
10143 }
10144
10145 #[gpui::test]
10146 async fn test_tool_permission_buttons_without_pattern(cx: &mut TestAppContext) {
10147 init_test(cx);
10148
10149 let tool_call_id = acp::ToolCallId::new("terminal-no-pattern-1");
10150 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `./deploy.sh --production`")
10151 .kind(acp::ToolKind::Edit);
10152
10153 // No pattern button since ./deploy.sh doesn't match the alphanumeric pattern
10154 let permission_options = ToolPermissionContext::new("terminal", "./deploy.sh --production")
10155 .build_permission_options();
10156
10157 let connection =
10158 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10159 tool_call_id.clone(),
10160 permission_options,
10161 )]));
10162
10163 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10164
10165 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10166
10167 // Disable notifications
10168 cx.update(|_window, cx| {
10169 AgentSettings::override_global(
10170 AgentSettings {
10171 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10172 ..AgentSettings::get_global(cx).clone()
10173 },
10174 cx,
10175 );
10176 });
10177
10178 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10179 message_editor.update_in(cx, |editor, window, cx| {
10180 editor.set_text("Run the deploy script", window, cx);
10181 });
10182
10183 thread_view.update_in(cx, |thread_view, window, cx| {
10184 thread_view.send(window, cx);
10185 });
10186
10187 cx.run_until_parked();
10188
10189 // Verify only 2 options (no pattern button when command doesn't match pattern)
10190 thread_view.read_with(cx, |thread_view, cx| {
10191 let thread = thread_view.thread().expect("Thread should exist");
10192 let thread = thread.read(cx);
10193
10194 let tool_call = thread.entries().iter().find_map(|entry| {
10195 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
10196 Some(call)
10197 } else {
10198 None
10199 }
10200 });
10201
10202 assert!(tool_call.is_some(), "Expected a tool call entry");
10203 let tool_call = tool_call.unwrap();
10204
10205 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
10206 &tool_call.status
10207 {
10208 assert_eq!(
10209 options.len(),
10210 2,
10211 "Expected 2 permission options (no pattern option)"
10212 );
10213
10214 let labels: Vec<&str> = options.iter().map(|o| o.name.as_ref()).collect();
10215 assert!(
10216 labels.contains(&"Always for terminal"),
10217 "Missing 'Always for terminal' option"
10218 );
10219 assert!(
10220 labels.contains(&"Only this time"),
10221 "Missing 'Only this time' option"
10222 );
10223 // Should NOT contain a pattern option
10224 assert!(
10225 !labels.iter().any(|l| l.contains("commands")),
10226 "Should not have pattern option"
10227 );
10228 } else {
10229 panic!("Expected WaitingForConfirmation status");
10230 }
10231 });
10232 }
10233
10234 #[gpui::test]
10235 async fn test_authorize_tool_call_action_triggers_authorization(cx: &mut TestAppContext) {
10236 init_test(cx);
10237
10238 let tool_call_id = acp::ToolCallId::new("action-test-1");
10239 let tool_call =
10240 acp::ToolCall::new(tool_call_id.clone(), "Run `cargo test`").kind(acp::ToolKind::Edit);
10241
10242 let permission_options =
10243 ToolPermissionContext::new("terminal", "cargo test").build_permission_options();
10244
10245 let connection =
10246 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10247 tool_call_id.clone(),
10248 permission_options,
10249 )]));
10250
10251 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10252
10253 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10254 add_to_workspace(thread_view.clone(), cx);
10255
10256 cx.update(|_window, cx| {
10257 AgentSettings::override_global(
10258 AgentSettings {
10259 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10260 ..AgentSettings::get_global(cx).clone()
10261 },
10262 cx,
10263 );
10264 });
10265
10266 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10267 message_editor.update_in(cx, |editor, window, cx| {
10268 editor.set_text("Run tests", window, cx);
10269 });
10270
10271 thread_view.update_in(cx, |thread_view, window, cx| {
10272 thread_view.send(window, cx);
10273 });
10274
10275 cx.run_until_parked();
10276
10277 // Verify tool call is waiting for confirmation
10278 thread_view.read_with(cx, |thread_view, cx| {
10279 let thread = thread_view.thread().expect("Thread should exist");
10280 let thread = thread.read(cx);
10281 let tool_call = thread.first_tool_awaiting_confirmation();
10282 assert!(
10283 tool_call.is_some(),
10284 "Expected a tool call waiting for confirmation"
10285 );
10286 });
10287
10288 // Dispatch the AuthorizeToolCall action (simulating dropdown menu selection)
10289 thread_view.update_in(cx, |_, window, cx| {
10290 window.dispatch_action(
10291 crate::AuthorizeToolCall {
10292 tool_call_id: "action-test-1".to_string(),
10293 option_id: "allow".to_string(),
10294 option_kind: "AllowOnce".to_string(),
10295 }
10296 .boxed_clone(),
10297 cx,
10298 );
10299 });
10300
10301 cx.run_until_parked();
10302
10303 // Verify tool call is no longer waiting for confirmation (was authorized)
10304 thread_view.read_with(cx, |thread_view, cx| {
10305 let thread = thread_view.thread().expect("Thread should exist");
10306 let thread = thread.read(cx);
10307 let tool_call = thread.first_tool_awaiting_confirmation();
10308 assert!(
10309 tool_call.is_none(),
10310 "Tool call should no longer be waiting for confirmation after AuthorizeToolCall action"
10311 );
10312 });
10313 }
10314
10315 #[gpui::test]
10316 async fn test_authorize_tool_call_action_with_pattern_option(cx: &mut TestAppContext) {
10317 init_test(cx);
10318
10319 let tool_call_id = acp::ToolCallId::new("pattern-action-test-1");
10320 let tool_call =
10321 acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
10322
10323 let permission_options =
10324 ToolPermissionContext::new("terminal", "npm install").build_permission_options();
10325
10326 let connection =
10327 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10328 tool_call_id.clone(),
10329 permission_options.clone(),
10330 )]));
10331
10332 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10333
10334 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10335 add_to_workspace(thread_view.clone(), cx);
10336
10337 cx.update(|_window, cx| {
10338 AgentSettings::override_global(
10339 AgentSettings {
10340 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10341 ..AgentSettings::get_global(cx).clone()
10342 },
10343 cx,
10344 );
10345 });
10346
10347 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10348 message_editor.update_in(cx, |editor, window, cx| {
10349 editor.set_text("Install dependencies", window, cx);
10350 });
10351
10352 thread_view.update_in(cx, |thread_view, window, cx| {
10353 thread_view.send(window, cx);
10354 });
10355
10356 cx.run_until_parked();
10357
10358 // Find the pattern option ID
10359 let pattern_option = permission_options
10360 .iter()
10361 .find(|o| o.option_id.0.starts_with("always_pattern:"))
10362 .expect("Should have a pattern option for npm command");
10363
10364 // Dispatch action with the pattern option (simulating "Always allow `npm` commands")
10365 thread_view.update_in(cx, |_, window, cx| {
10366 window.dispatch_action(
10367 crate::AuthorizeToolCall {
10368 tool_call_id: "pattern-action-test-1".to_string(),
10369 option_id: pattern_option.option_id.0.to_string(),
10370 option_kind: "AllowAlways".to_string(),
10371 }
10372 .boxed_clone(),
10373 cx,
10374 );
10375 });
10376
10377 cx.run_until_parked();
10378
10379 // Verify tool call was authorized
10380 thread_view.read_with(cx, |thread_view, cx| {
10381 let thread = thread_view.thread().expect("Thread should exist");
10382 let thread = thread.read(cx);
10383 let tool_call = thread.first_tool_awaiting_confirmation();
10384 assert!(
10385 tool_call.is_none(),
10386 "Tool call should be authorized after selecting pattern option"
10387 );
10388 });
10389 }
10390
10391 #[gpui::test]
10392 async fn test_granularity_selection_updates_state(cx: &mut TestAppContext) {
10393 init_test(cx);
10394
10395 let tool_call_id = acp::ToolCallId::new("granularity-test-1");
10396 let tool_call =
10397 acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build`").kind(acp::ToolKind::Edit);
10398
10399 let permission_options =
10400 ToolPermissionContext::new("terminal", "cargo build").build_permission_options();
10401
10402 let connection =
10403 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10404 tool_call_id.clone(),
10405 permission_options.clone(),
10406 )]));
10407
10408 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10409
10410 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10411 add_to_workspace(thread_view.clone(), cx);
10412
10413 cx.update(|_window, cx| {
10414 AgentSettings::override_global(
10415 AgentSettings {
10416 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10417 ..AgentSettings::get_global(cx).clone()
10418 },
10419 cx,
10420 );
10421 });
10422
10423 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10424 message_editor.update_in(cx, |editor, window, cx| {
10425 editor.set_text("Build the project", window, cx);
10426 });
10427
10428 thread_view.update_in(cx, |thread_view, window, cx| {
10429 thread_view.send(window, cx);
10430 });
10431
10432 cx.run_until_parked();
10433
10434 // Verify default granularity is the last option (index 2 = "Only this time")
10435 thread_view.read_with(cx, |thread_view, _cx| {
10436 let selected = thread_view
10437 .selected_permission_granularity
10438 .get(&tool_call_id);
10439 assert!(
10440 selected.is_none(),
10441 "Should have no selection initially (defaults to last)"
10442 );
10443 });
10444
10445 // Select the first option (index 0 = "Always for terminal")
10446 thread_view.update_in(cx, |_, window, cx| {
10447 window.dispatch_action(
10448 crate::SelectPermissionGranularity {
10449 tool_call_id: "granularity-test-1".to_string(),
10450 index: 0,
10451 }
10452 .boxed_clone(),
10453 cx,
10454 );
10455 });
10456
10457 cx.run_until_parked();
10458
10459 // Verify the selection was updated
10460 thread_view.read_with(cx, |thread_view, _cx| {
10461 let selected = thread_view
10462 .selected_permission_granularity
10463 .get(&tool_call_id);
10464 assert_eq!(selected, Some(&0), "Should have selected index 0");
10465 });
10466 }
10467
10468 #[gpui::test]
10469 async fn test_allow_button_uses_selected_granularity(cx: &mut TestAppContext) {
10470 init_test(cx);
10471
10472 let tool_call_id = acp::ToolCallId::new("allow-granularity-test-1");
10473 let tool_call =
10474 acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
10475
10476 let permission_options =
10477 ToolPermissionContext::new("terminal", "npm install").build_permission_options();
10478
10479 // Verify we have the expected options
10480 assert_eq!(permission_options.len(), 3);
10481 assert!(
10482 permission_options[0]
10483 .option_id
10484 .0
10485 .contains("always:terminal")
10486 );
10487 assert!(
10488 permission_options[1]
10489 .option_id
10490 .0
10491 .contains("always_pattern:terminal")
10492 );
10493 assert_eq!(permission_options[2].option_id.0.as_ref(), "once");
10494
10495 let connection =
10496 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10497 tool_call_id.clone(),
10498 permission_options.clone(),
10499 )]));
10500
10501 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10502
10503 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10504 add_to_workspace(thread_view.clone(), cx);
10505
10506 cx.update(|_window, cx| {
10507 AgentSettings::override_global(
10508 AgentSettings {
10509 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10510 ..AgentSettings::get_global(cx).clone()
10511 },
10512 cx,
10513 );
10514 });
10515
10516 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10517 message_editor.update_in(cx, |editor, window, cx| {
10518 editor.set_text("Install dependencies", window, cx);
10519 });
10520
10521 thread_view.update_in(cx, |thread_view, window, cx| {
10522 thread_view.send(window, cx);
10523 });
10524
10525 cx.run_until_parked();
10526
10527 // Select the pattern option (index 1 = "Always for `npm` commands")
10528 thread_view.update_in(cx, |_, window, cx| {
10529 window.dispatch_action(
10530 crate::SelectPermissionGranularity {
10531 tool_call_id: "allow-granularity-test-1".to_string(),
10532 index: 1,
10533 }
10534 .boxed_clone(),
10535 cx,
10536 );
10537 });
10538
10539 cx.run_until_parked();
10540
10541 // Simulate clicking the Allow button by dispatching AllowOnce action
10542 // which should use the selected granularity
10543 thread_view.update_in(cx, |thread_view, window, cx| {
10544 thread_view.allow_once(&AllowOnce, window, cx);
10545 });
10546
10547 cx.run_until_parked();
10548
10549 // Verify tool call was authorized
10550 thread_view.read_with(cx, |thread_view, cx| {
10551 let thread = thread_view.thread().expect("Thread should exist");
10552 let thread = thread.read(cx);
10553 let tool_call = thread.first_tool_awaiting_confirmation();
10554 assert!(
10555 tool_call.is_none(),
10556 "Tool call should be authorized after Allow with pattern granularity"
10557 );
10558 });
10559 }
10560
10561 #[gpui::test]
10562 async fn test_deny_button_uses_selected_granularity(cx: &mut TestAppContext) {
10563 init_test(cx);
10564
10565 let tool_call_id = acp::ToolCallId::new("deny-granularity-test-1");
10566 let tool_call =
10567 acp::ToolCall::new(tool_call_id.clone(), "Run `git push`").kind(acp::ToolKind::Edit);
10568
10569 let permission_options =
10570 ToolPermissionContext::new("terminal", "git push").build_permission_options();
10571
10572 let connection =
10573 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10574 tool_call_id.clone(),
10575 permission_options.clone(),
10576 )]));
10577
10578 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10579
10580 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10581 add_to_workspace(thread_view.clone(), cx);
10582
10583 cx.update(|_window, cx| {
10584 AgentSettings::override_global(
10585 AgentSettings {
10586 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10587 ..AgentSettings::get_global(cx).clone()
10588 },
10589 cx,
10590 );
10591 });
10592
10593 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10594 message_editor.update_in(cx, |editor, window, cx| {
10595 editor.set_text("Push changes", window, cx);
10596 });
10597
10598 thread_view.update_in(cx, |thread_view, window, cx| {
10599 thread_view.send(window, cx);
10600 });
10601
10602 cx.run_until_parked();
10603
10604 // Use default granularity (last option = "Only this time")
10605 // Simulate clicking the Deny button
10606 thread_view.update_in(cx, |thread_view, window, cx| {
10607 thread_view.reject_once(&RejectOnce, window, cx);
10608 });
10609
10610 cx.run_until_parked();
10611
10612 // Verify tool call was rejected (no longer waiting for confirmation)
10613 thread_view.read_with(cx, |thread_view, cx| {
10614 let thread = thread_view.thread().expect("Thread should exist");
10615 let thread = thread.read(cx);
10616 let tool_call = thread.first_tool_awaiting_confirmation();
10617 assert!(
10618 tool_call.is_none(),
10619 "Tool call should be rejected after Deny"
10620 );
10621 });
10622 }
10623
10624 #[gpui::test]
10625 async fn test_option_id_transformation_for_allow() {
10626 // Test the option_id transformation logic directly
10627 // "once" -> "allow"
10628 // "always:terminal" -> "always_allow:terminal"
10629 // "always_pattern:terminal:^cargo\s" -> "always_allow_pattern:terminal:^cargo\s"
10630
10631 let test_cases = vec![
10632 ("once", "allow"),
10633 ("always:terminal", "always_allow:terminal"),
10634 (
10635 "always_pattern:terminal:^cargo\\s",
10636 "always_allow_pattern:terminal:^cargo\\s",
10637 ),
10638 ("always:fetch", "always_allow:fetch"),
10639 (
10640 "always_pattern:fetch:^https?://docs\\.rs",
10641 "always_allow_pattern:fetch:^https?://docs\\.rs",
10642 ),
10643 ];
10644
10645 for (input, expected) in test_cases {
10646 let result = if input == "once" {
10647 "allow".to_string()
10648 } else if let Some(rest) = input.strip_prefix("always:") {
10649 format!("always_allow:{}", rest)
10650 } else if let Some(rest) = input.strip_prefix("always_pattern:") {
10651 format!("always_allow_pattern:{}", rest)
10652 } else {
10653 input.to_string()
10654 };
10655 assert_eq!(result, expected, "Failed for input: {}", input);
10656 }
10657 }
10658
10659 #[gpui::test]
10660 async fn test_option_id_transformation_for_deny() {
10661 // Test the option_id transformation logic for deny
10662 // "once" -> "deny"
10663 // "always:terminal" -> "always_deny:terminal"
10664 // "always_pattern:terminal:^cargo\s" -> "always_deny_pattern:terminal:^cargo\s"
10665
10666 let test_cases = vec![
10667 ("once", "deny"),
10668 ("always:terminal", "always_deny:terminal"),
10669 (
10670 "always_pattern:terminal:^cargo\\s",
10671 "always_deny_pattern:terminal:^cargo\\s",
10672 ),
10673 ("always:fetch", "always_deny:fetch"),
10674 (
10675 "always_pattern:fetch:^https?://docs\\.rs",
10676 "always_deny_pattern:fetch:^https?://docs\\.rs",
10677 ),
10678 ];
10679
10680 for (input, expected) in test_cases {
10681 let result = if input == "once" {
10682 "deny".to_string()
10683 } else if let Some(rest) = input.strip_prefix("always:") {
10684 format!("always_deny:{}", rest)
10685 } else if let Some(rest) = input.strip_prefix("always_pattern:") {
10686 format!("always_deny_pattern:{}", rest)
10687 } else {
10688 input.replace("allow", "deny")
10689 };
10690 assert_eq!(result, expected, "Failed for input: {}", input);
10691 }
10692 }
10693}