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| {
6746 project.create_buffer(Some(markdown_language), false, cx)
6747 })
6748 .await?;
6749
6750 buffer.update(cx, |buffer, cx| {
6751 buffer.set_text(markdown, cx);
6752 buffer.set_capability(language::Capability::ReadWrite, cx);
6753 });
6754
6755 workspace.update_in(cx, |workspace, window, cx| {
6756 let buffer = cx
6757 .new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_title.clone()));
6758
6759 workspace.add_item_to_active_pane(
6760 Box::new(cx.new(|cx| {
6761 let mut editor =
6762 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
6763 editor.set_breadcrumb_header(thread_title);
6764 editor
6765 })),
6766 None,
6767 true,
6768 window,
6769 cx,
6770 );
6771 })?;
6772 anyhow::Ok(())
6773 })
6774 }
6775
6776 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
6777 self.list_state.scroll_to(ListOffset::default());
6778 cx.notify();
6779 }
6780
6781 fn scroll_to_most_recent_user_prompt(&mut self, cx: &mut Context<Self>) {
6782 let Some(thread) = self.thread() else {
6783 return;
6784 };
6785
6786 let entries = thread.read(cx).entries();
6787 if entries.is_empty() {
6788 return;
6789 }
6790
6791 // Find the most recent user message and scroll it to the top of the viewport.
6792 // (Fallback: if no user message exists, scroll to the bottom.)
6793 if let Some(ix) = entries
6794 .iter()
6795 .rposition(|entry| matches!(entry, AgentThreadEntry::UserMessage(_)))
6796 {
6797 self.list_state.scroll_to(ListOffset {
6798 item_ix: ix,
6799 offset_in_item: px(0.0),
6800 });
6801 cx.notify();
6802 } else {
6803 self.scroll_to_bottom(cx);
6804 }
6805 }
6806
6807 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
6808 if let Some(thread) = self.thread() {
6809 let entry_count = thread.read(cx).entries().len();
6810 self.list_state.reset(entry_count);
6811 cx.notify();
6812 }
6813 }
6814
6815 fn notify_with_sound(
6816 &mut self,
6817 caption: impl Into<SharedString>,
6818 icon: IconName,
6819 window: &mut Window,
6820 cx: &mut Context<Self>,
6821 ) {
6822 self.play_notification_sound(window, cx);
6823 self.show_notification(caption, icon, window, cx);
6824 }
6825
6826 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
6827 let settings = AgentSettings::get_global(cx);
6828 if settings.play_sound_when_agent_done && !window.is_window_active() {
6829 Audio::play_sound(Sound::AgentDone, cx);
6830 }
6831 }
6832
6833 fn show_notification(
6834 &mut self,
6835 caption: impl Into<SharedString>,
6836 icon: IconName,
6837 window: &mut Window,
6838 cx: &mut Context<Self>,
6839 ) {
6840 if !self.notifications.is_empty() {
6841 return;
6842 }
6843
6844 let settings = AgentSettings::get_global(cx);
6845
6846 let window_is_inactive = !window.is_window_active();
6847 let panel_is_hidden = self
6848 .workspace
6849 .upgrade()
6850 .map(|workspace| AgentPanel::is_hidden(&workspace, cx))
6851 .unwrap_or(true);
6852
6853 let should_notify = window_is_inactive || panel_is_hidden;
6854
6855 if !should_notify {
6856 return;
6857 }
6858
6859 // TODO: Change this once we have title summarization for external agents.
6860 let title = self.agent.name();
6861
6862 match settings.notify_when_agent_waiting {
6863 NotifyWhenAgentWaiting::PrimaryScreen => {
6864 if let Some(primary) = cx.primary_display() {
6865 self.pop_up(icon, caption.into(), title, window, primary, cx);
6866 }
6867 }
6868 NotifyWhenAgentWaiting::AllScreens => {
6869 let caption = caption.into();
6870 for screen in cx.displays() {
6871 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
6872 }
6873 }
6874 NotifyWhenAgentWaiting::Never => {
6875 // Don't show anything
6876 }
6877 }
6878 }
6879
6880 fn pop_up(
6881 &mut self,
6882 icon: IconName,
6883 caption: SharedString,
6884 title: SharedString,
6885 window: &mut Window,
6886 screen: Rc<dyn PlatformDisplay>,
6887 cx: &mut Context<Self>,
6888 ) {
6889 let options = AgentNotification::window_options(screen, cx);
6890
6891 let project_name = self.workspace.upgrade().and_then(|workspace| {
6892 workspace
6893 .read(cx)
6894 .project()
6895 .read(cx)
6896 .visible_worktrees(cx)
6897 .next()
6898 .map(|worktree| worktree.read(cx).root_name_str().to_string())
6899 });
6900
6901 if let Some(screen_window) = cx
6902 .open_window(options, |_window, cx| {
6903 cx.new(|_cx| {
6904 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
6905 })
6906 })
6907 .log_err()
6908 && let Some(pop_up) = screen_window.entity(cx).log_err()
6909 {
6910 self.notification_subscriptions
6911 .entry(screen_window)
6912 .or_insert_with(Vec::new)
6913 .push(cx.subscribe_in(&pop_up, window, {
6914 |this, _, event, window, cx| match event {
6915 AgentNotificationEvent::Accepted => {
6916 let handle = window.window_handle();
6917 cx.activate(true);
6918
6919 let workspace_handle = this.workspace.clone();
6920
6921 // If there are multiple Zed windows, activate the correct one.
6922 cx.defer(move |cx| {
6923 handle
6924 .update(cx, |_view, window, _cx| {
6925 window.activate_window();
6926
6927 if let Some(workspace) = workspace_handle.upgrade() {
6928 workspace.update(_cx, |workspace, cx| {
6929 workspace.focus_panel::<AgentPanel>(window, cx);
6930 });
6931 }
6932 })
6933 .log_err();
6934 });
6935
6936 this.dismiss_notifications(cx);
6937 }
6938 AgentNotificationEvent::Dismissed => {
6939 this.dismiss_notifications(cx);
6940 }
6941 }
6942 }));
6943
6944 self.notifications.push(screen_window);
6945
6946 // If the user manually refocuses the original window, dismiss the popup.
6947 self.notification_subscriptions
6948 .entry(screen_window)
6949 .or_insert_with(Vec::new)
6950 .push({
6951 let pop_up_weak = pop_up.downgrade();
6952
6953 cx.observe_window_activation(window, move |_, window, cx| {
6954 if window.is_window_active()
6955 && let Some(pop_up) = pop_up_weak.upgrade()
6956 {
6957 pop_up.update(cx, |_, cx| {
6958 cx.emit(AgentNotificationEvent::Dismissed);
6959 });
6960 }
6961 })
6962 });
6963 }
6964 }
6965
6966 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
6967 for window in self.notifications.drain(..) {
6968 window
6969 .update(cx, |_, window, _| {
6970 window.remove_window();
6971 })
6972 .ok();
6973
6974 self.notification_subscriptions.remove(&window);
6975 }
6976 }
6977
6978 fn render_generating(&self, confirmation: bool, cx: &App) -> impl IntoElement {
6979 let show_stats = AgentSettings::get_global(cx).show_turn_stats;
6980 let elapsed_label = show_stats
6981 .then(|| {
6982 self.turn_started_at.and_then(|started_at| {
6983 let elapsed = started_at.elapsed();
6984 (elapsed > STOPWATCH_THRESHOLD).then(|| duration_alt_display(elapsed))
6985 })
6986 })
6987 .flatten();
6988
6989 let is_waiting = confirmation
6990 || self
6991 .thread()
6992 .is_some_and(|thread| thread.read(cx).has_in_progress_tool_calls());
6993
6994 let turn_tokens_label = elapsed_label
6995 .is_some()
6996 .then(|| {
6997 self.turn_tokens
6998 .filter(|&tokens| tokens > TOKEN_THRESHOLD)
6999 .map(|tokens| crate::text_thread_editor::humanize_token_count(tokens))
7000 })
7001 .flatten();
7002
7003 let arrow_icon = if is_waiting {
7004 IconName::ArrowUp
7005 } else {
7006 IconName::ArrowDown
7007 };
7008
7009 h_flex()
7010 .id("generating-spinner")
7011 .py_2()
7012 .px(rems_from_px(22.))
7013 .gap_2()
7014 .map(|this| {
7015 if confirmation {
7016 this.child(
7017 h_flex()
7018 .w_2()
7019 .child(SpinnerLabel::sand().size(LabelSize::Small)),
7020 )
7021 .child(
7022 div().min_w(rems(8.)).child(
7023 LoadingLabel::new("Waiting Confirmation")
7024 .size(LabelSize::Small)
7025 .color(Color::Muted),
7026 ),
7027 )
7028 } else {
7029 this.child(SpinnerLabel::new().size(LabelSize::Small))
7030 }
7031 })
7032 .when_some(elapsed_label, |this, elapsed| {
7033 this.child(
7034 Label::new(elapsed)
7035 .size(LabelSize::Small)
7036 .color(Color::Muted),
7037 )
7038 })
7039 .when_some(turn_tokens_label, |this, tokens| {
7040 this.child(
7041 h_flex()
7042 .gap_0p5()
7043 .child(
7044 Icon::new(arrow_icon)
7045 .size(IconSize::XSmall)
7046 .color(Color::Muted),
7047 )
7048 .child(
7049 Label::new(format!("{} tokens", tokens))
7050 .size(LabelSize::Small)
7051 .color(Color::Muted),
7052 ),
7053 )
7054 })
7055 .into_any_element()
7056 }
7057
7058 fn render_thread_controls(
7059 &self,
7060 thread: &Entity<AcpThread>,
7061 cx: &Context<Self>,
7062 ) -> impl IntoElement {
7063 let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
7064 if is_generating {
7065 return self.render_generating(false, cx).into_any_element();
7066 }
7067
7068 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
7069 .shape(ui::IconButtonShape::Square)
7070 .icon_size(IconSize::Small)
7071 .icon_color(Color::Ignored)
7072 .tooltip(Tooltip::text("Open Thread as Markdown"))
7073 .on_click(cx.listener(move |this, _, window, cx| {
7074 if let Some(workspace) = this.workspace.upgrade() {
7075 this.open_thread_as_markdown(workspace, window, cx)
7076 .detach_and_log_err(cx);
7077 }
7078 }));
7079
7080 let scroll_to_recent_user_prompt =
7081 IconButton::new("scroll_to_recent_user_prompt", IconName::ForwardArrow)
7082 .shape(ui::IconButtonShape::Square)
7083 .icon_size(IconSize::Small)
7084 .icon_color(Color::Ignored)
7085 .tooltip(Tooltip::text("Scroll To Most Recent User Prompt"))
7086 .on_click(cx.listener(move |this, _, _, cx| {
7087 this.scroll_to_most_recent_user_prompt(cx);
7088 }));
7089
7090 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
7091 .shape(ui::IconButtonShape::Square)
7092 .icon_size(IconSize::Small)
7093 .icon_color(Color::Ignored)
7094 .tooltip(Tooltip::text("Scroll To Top"))
7095 .on_click(cx.listener(move |this, _, _, cx| {
7096 this.scroll_to_top(cx);
7097 }));
7098
7099 let show_stats = AgentSettings::get_global(cx).show_turn_stats;
7100 let last_turn_clock = show_stats
7101 .then(|| {
7102 self.last_turn_duration
7103 .filter(|&duration| duration > STOPWATCH_THRESHOLD)
7104 .map(|duration| {
7105 Label::new(duration_alt_display(duration))
7106 .size(LabelSize::Small)
7107 .color(Color::Muted)
7108 })
7109 })
7110 .flatten();
7111
7112 let last_turn_tokens = last_turn_clock
7113 .is_some()
7114 .then(|| {
7115 self.last_turn_tokens
7116 .filter(|&tokens| tokens > TOKEN_THRESHOLD)
7117 .map(|tokens| {
7118 Label::new(format!(
7119 "{} tokens",
7120 crate::text_thread_editor::humanize_token_count(tokens)
7121 ))
7122 .size(LabelSize::Small)
7123 .color(Color::Muted)
7124 })
7125 })
7126 .flatten();
7127
7128 let mut container = h_flex()
7129 .w_full()
7130 .py_2()
7131 .px_5()
7132 .gap_px()
7133 .opacity(0.6)
7134 .hover(|s| s.opacity(1.))
7135 .justify_end()
7136 .when(
7137 last_turn_tokens.is_some() || last_turn_clock.is_some(),
7138 |this| {
7139 this.child(
7140 h_flex()
7141 .gap_1()
7142 .px_1()
7143 .when_some(last_turn_tokens, |this, label| this.child(label))
7144 .when_some(last_turn_clock, |this, label| this.child(label)),
7145 )
7146 },
7147 );
7148
7149 if AgentSettings::get_global(cx).enable_feedback
7150 && self
7151 .thread()
7152 .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
7153 {
7154 let feedback = self.thread_feedback.feedback;
7155
7156 let tooltip_meta = || {
7157 SharedString::new(
7158 "Rating the thread sends all of your current conversation to the Zed team.",
7159 )
7160 };
7161
7162 container = container
7163 .child(
7164 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
7165 .shape(ui::IconButtonShape::Square)
7166 .icon_size(IconSize::Small)
7167 .icon_color(match feedback {
7168 Some(ThreadFeedback::Positive) => Color::Accent,
7169 _ => Color::Ignored,
7170 })
7171 .tooltip(move |window, cx| match feedback {
7172 Some(ThreadFeedback::Positive) => {
7173 Tooltip::text("Thanks for your feedback!")(window, cx)
7174 }
7175 _ => Tooltip::with_meta("Helpful Response", None, tooltip_meta(), cx),
7176 })
7177 .on_click(cx.listener(move |this, _, window, cx| {
7178 this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
7179 })),
7180 )
7181 .child(
7182 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
7183 .shape(ui::IconButtonShape::Square)
7184 .icon_size(IconSize::Small)
7185 .icon_color(match feedback {
7186 Some(ThreadFeedback::Negative) => Color::Accent,
7187 _ => Color::Ignored,
7188 })
7189 .tooltip(move |window, cx| match feedback {
7190 Some(ThreadFeedback::Negative) => {
7191 Tooltip::text(
7192 "We appreciate your feedback and will use it to improve in the future.",
7193 )(window, cx)
7194 }
7195 _ => {
7196 Tooltip::with_meta("Not Helpful Response", None, tooltip_meta(), cx)
7197 }
7198 })
7199 .on_click(cx.listener(move |this, _, window, cx| {
7200 this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
7201 })),
7202 );
7203 }
7204
7205 if cx.has_flag::<AgentSharingFeatureFlag>()
7206 && self.is_imported_thread(cx)
7207 && self
7208 .project
7209 .read(cx)
7210 .client()
7211 .status()
7212 .borrow()
7213 .is_connected()
7214 {
7215 let sync_button = IconButton::new("sync-thread", IconName::ArrowCircle)
7216 .shape(ui::IconButtonShape::Square)
7217 .icon_size(IconSize::Small)
7218 .icon_color(Color::Ignored)
7219 .tooltip(Tooltip::text("Sync with source thread"))
7220 .on_click(cx.listener(move |this, _, window, cx| {
7221 this.sync_thread(window, cx);
7222 }));
7223
7224 container = container.child(sync_button);
7225 }
7226
7227 if cx.has_flag::<AgentSharingFeatureFlag>() && !self.is_imported_thread(cx) {
7228 let share_button = IconButton::new("share-thread", IconName::ArrowUpRight)
7229 .shape(ui::IconButtonShape::Square)
7230 .icon_size(IconSize::Small)
7231 .icon_color(Color::Ignored)
7232 .tooltip(Tooltip::text("Share Thread"))
7233 .on_click(cx.listener(move |this, _, window, cx| {
7234 this.share_thread(window, cx);
7235 }));
7236
7237 container = container.child(share_button);
7238 }
7239
7240 container
7241 .child(open_as_markdown)
7242 .child(scroll_to_recent_user_prompt)
7243 .child(scroll_to_top)
7244 .into_any_element()
7245 }
7246
7247 fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
7248 h_flex()
7249 .key_context("AgentFeedbackMessageEditor")
7250 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
7251 this.thread_feedback.dismiss_comments();
7252 cx.notify();
7253 }))
7254 .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
7255 this.submit_feedback_message(cx);
7256 }))
7257 .p_2()
7258 .mb_2()
7259 .mx_5()
7260 .gap_1()
7261 .rounded_md()
7262 .border_1()
7263 .border_color(cx.theme().colors().border)
7264 .bg(cx.theme().colors().editor_background)
7265 .child(div().w_full().child(editor))
7266 .child(
7267 h_flex()
7268 .child(
7269 IconButton::new("dismiss-feedback-message", IconName::Close)
7270 .icon_color(Color::Error)
7271 .icon_size(IconSize::XSmall)
7272 .shape(ui::IconButtonShape::Square)
7273 .on_click(cx.listener(move |this, _, _window, cx| {
7274 this.thread_feedback.dismiss_comments();
7275 cx.notify();
7276 })),
7277 )
7278 .child(
7279 IconButton::new("submit-feedback-message", IconName::Return)
7280 .icon_size(IconSize::XSmall)
7281 .shape(ui::IconButtonShape::Square)
7282 .on_click(cx.listener(move |this, _, _window, cx| {
7283 this.submit_feedback_message(cx);
7284 })),
7285 ),
7286 )
7287 }
7288
7289 fn handle_feedback_click(
7290 &mut self,
7291 feedback: ThreadFeedback,
7292 window: &mut Window,
7293 cx: &mut Context<Self>,
7294 ) {
7295 let Some(thread) = self.thread().cloned() else {
7296 return;
7297 };
7298
7299 self.thread_feedback.submit(thread, feedback, window, cx);
7300 cx.notify();
7301 }
7302
7303 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
7304 let Some(thread) = self.thread().cloned() else {
7305 return;
7306 };
7307
7308 self.thread_feedback.submit_comments(thread, cx);
7309 cx.notify();
7310 }
7311
7312 fn render_token_limit_callout(&self, cx: &mut Context<Self>) -> Option<Callout> {
7313 if self.token_limit_callout_dismissed {
7314 return None;
7315 }
7316
7317 let token_usage = self.thread()?.read(cx).token_usage()?;
7318 let ratio = token_usage.ratio();
7319
7320 let (severity, icon, title) = match ratio {
7321 acp_thread::TokenUsageRatio::Normal => return None,
7322 acp_thread::TokenUsageRatio::Warning => (
7323 Severity::Warning,
7324 IconName::Warning,
7325 "Thread reaching the token limit soon",
7326 ),
7327 acp_thread::TokenUsageRatio::Exceeded => (
7328 Severity::Error,
7329 IconName::XCircle,
7330 "Thread reached the token limit",
7331 ),
7332 };
7333
7334 let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
7335 thread.read(cx).completion_mode() == CompletionMode::Normal
7336 && thread
7337 .read(cx)
7338 .model()
7339 .is_some_and(|model| model.supports_burn_mode())
7340 });
7341
7342 let description = if burn_mode_available {
7343 "To continue, start a new thread from a summary or turn Burn Mode on."
7344 } else {
7345 "To continue, start a new thread from a summary."
7346 };
7347
7348 Some(
7349 Callout::new()
7350 .severity(severity)
7351 .icon(icon)
7352 .title(title)
7353 .description(description)
7354 .actions_slot(
7355 h_flex()
7356 .gap_0p5()
7357 .child(
7358 Button::new("start-new-thread", "Start New Thread")
7359 .label_size(LabelSize::Small)
7360 .on_click(cx.listener(|this, _, window, cx| {
7361 let Some(thread) = this.thread() else {
7362 return;
7363 };
7364 let session_id = thread.read(cx).session_id().clone();
7365 window.dispatch_action(
7366 crate::NewNativeAgentThreadFromSummary {
7367 from_session_id: session_id,
7368 }
7369 .boxed_clone(),
7370 cx,
7371 );
7372 })),
7373 )
7374 .when(burn_mode_available, |this| {
7375 this.child(
7376 IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
7377 .icon_size(IconSize::XSmall)
7378 .on_click(cx.listener(|this, _event, window, cx| {
7379 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
7380 })),
7381 )
7382 }),
7383 )
7384 .dismiss_action(self.dismiss_error_button(cx)),
7385 )
7386 }
7387
7388 fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
7389 if !self.is_using_zed_ai_models(cx) {
7390 return None;
7391 }
7392
7393 let user_store = self.project.read(cx).user_store().read(cx);
7394 if user_store.is_usage_based_billing_enabled() {
7395 return None;
7396 }
7397
7398 let plan = user_store
7399 .plan()
7400 .unwrap_or(cloud_llm_client::Plan::V1(PlanV1::ZedFree));
7401
7402 let usage = user_store.model_request_usage()?;
7403
7404 Some(
7405 div()
7406 .child(UsageCallout::new(plan, usage))
7407 .line_height(line_height),
7408 )
7409 }
7410
7411 fn agent_ui_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
7412 self.entry_view_state.update(cx, |entry_view_state, cx| {
7413 entry_view_state.agent_ui_font_size_changed(cx);
7414 });
7415 }
7416
7417 pub(crate) fn insert_dragged_files(
7418 &self,
7419 paths: Vec<project::ProjectPath>,
7420 added_worktrees: Vec<Entity<project::Worktree>>,
7421 window: &mut Window,
7422 cx: &mut Context<Self>,
7423 ) {
7424 self.message_editor.update(cx, |message_editor, cx| {
7425 message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
7426 })
7427 }
7428
7429 /// Inserts the selected text into the message editor or the message being
7430 /// edited, if any.
7431 pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
7432 self.active_editor(cx).update(cx, |editor, cx| {
7433 editor.insert_selections(window, cx);
7434 });
7435 }
7436
7437 /// Inserts code snippets as creases into the message editor.
7438 pub(crate) fn insert_code_crease(
7439 &self,
7440 creases: Vec<(String, String)>,
7441 window: &mut Window,
7442 cx: &mut Context<Self>,
7443 ) {
7444 self.message_editor.update(cx, |message_editor, cx| {
7445 message_editor.insert_code_creases(creases, window, cx);
7446 });
7447 }
7448
7449 fn render_thread_retry_status_callout(
7450 &self,
7451 _window: &mut Window,
7452 _cx: &mut Context<Self>,
7453 ) -> Option<Callout> {
7454 let state = self.thread_retry_status.as_ref()?;
7455
7456 let next_attempt_in = state
7457 .duration
7458 .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
7459 if next_attempt_in.is_zero() {
7460 return None;
7461 }
7462
7463 let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
7464
7465 let retry_message = if state.max_attempts == 1 {
7466 if next_attempt_in_secs == 1 {
7467 "Retrying. Next attempt in 1 second.".to_string()
7468 } else {
7469 format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
7470 }
7471 } else if next_attempt_in_secs == 1 {
7472 format!(
7473 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
7474 state.attempt, state.max_attempts,
7475 )
7476 } else {
7477 format!(
7478 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
7479 state.attempt, state.max_attempts,
7480 )
7481 };
7482
7483 Some(
7484 Callout::new()
7485 .severity(Severity::Warning)
7486 .title(state.last_error.clone())
7487 .description(retry_message),
7488 )
7489 }
7490
7491 fn render_codex_windows_warning(&self, cx: &mut Context<Self>) -> Callout {
7492 Callout::new()
7493 .icon(IconName::Warning)
7494 .severity(Severity::Warning)
7495 .title("Codex on Windows")
7496 .description("For best performance, run Codex in Windows Subsystem for Linux (WSL2)")
7497 .actions_slot(
7498 Button::new("open-wsl-modal", "Open in WSL")
7499 .icon_size(IconSize::Small)
7500 .icon_color(Color::Muted)
7501 .on_click(cx.listener({
7502 move |_, _, _window, cx| {
7503 #[cfg(windows)]
7504 _window.dispatch_action(
7505 zed_actions::wsl_actions::OpenWsl::default().boxed_clone(),
7506 cx,
7507 );
7508 cx.notify();
7509 }
7510 })),
7511 )
7512 .dismiss_action(
7513 IconButton::new("dismiss", IconName::Close)
7514 .icon_size(IconSize::Small)
7515 .icon_color(Color::Muted)
7516 .tooltip(Tooltip::text("Dismiss Warning"))
7517 .on_click(cx.listener({
7518 move |this, _, _, cx| {
7519 this.show_codex_windows_warning = false;
7520 cx.notify();
7521 }
7522 })),
7523 )
7524 }
7525
7526 fn render_thread_error(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
7527 let content = match self.thread_error.as_ref()? {
7528 ThreadError::Other(error) => self.render_any_thread_error(error.clone(), window, cx),
7529 ThreadError::Refusal => self.render_refusal_error(cx),
7530 ThreadError::AuthenticationRequired(error) => {
7531 self.render_authentication_required_error(error.clone(), cx)
7532 }
7533 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
7534 ThreadError::ModelRequestLimitReached(plan) => {
7535 self.render_model_request_limit_reached_error(*plan, cx)
7536 }
7537 ThreadError::ToolUseLimitReached => self.render_tool_use_limit_reached_error(cx)?,
7538 };
7539
7540 Some(div().child(content))
7541 }
7542
7543 fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
7544 v_flex().w_full().justify_end().child(
7545 h_flex()
7546 .p_2()
7547 .pr_3()
7548 .w_full()
7549 .gap_1p5()
7550 .border_t_1()
7551 .border_color(cx.theme().colors().border)
7552 .bg(cx.theme().colors().element_background)
7553 .child(
7554 h_flex()
7555 .flex_1()
7556 .gap_1p5()
7557 .child(
7558 Icon::new(IconName::Download)
7559 .color(Color::Accent)
7560 .size(IconSize::Small),
7561 )
7562 .child(Label::new("New version available").size(LabelSize::Small)),
7563 )
7564 .child(
7565 Button::new("update-button", format!("Update to v{}", version))
7566 .label_size(LabelSize::Small)
7567 .style(ButtonStyle::Tinted(TintColor::Accent))
7568 .on_click(cx.listener(|this, _, window, cx| {
7569 this.reset(window, cx);
7570 })),
7571 ),
7572 )
7573 }
7574
7575 fn current_mode_id(&self, cx: &App) -> Option<Arc<str>> {
7576 if let Some(thread) = self.as_native_thread(cx) {
7577 Some(thread.read(cx).profile().0.clone())
7578 } else if let Some(mode_selector) = self.mode_selector() {
7579 Some(mode_selector.read(cx).mode().0)
7580 } else {
7581 None
7582 }
7583 }
7584
7585 fn current_model_id(&self, cx: &App) -> Option<String> {
7586 self.model_selector
7587 .as_ref()
7588 .and_then(|selector| selector.read(cx).active_model(cx).map(|m| m.id.to_string()))
7589 }
7590
7591 fn current_model_name(&self, cx: &App) -> SharedString {
7592 // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
7593 // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
7594 // This provides better clarity about what refused the request
7595 if self.as_native_connection(cx).is_some() {
7596 self.model_selector
7597 .as_ref()
7598 .and_then(|selector| selector.read(cx).active_model(cx))
7599 .map(|model| model.name.clone())
7600 .unwrap_or_else(|| SharedString::from("The model"))
7601 } else {
7602 // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
7603 self.agent.name()
7604 }
7605 }
7606
7607 fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
7608 let model_or_agent_name = self.current_model_name(cx);
7609 let refusal_message = format!(
7610 "{} 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.",
7611 model_or_agent_name
7612 );
7613
7614 Callout::new()
7615 .severity(Severity::Error)
7616 .title("Request Refused")
7617 .icon(IconName::XCircle)
7618 .description(refusal_message.clone())
7619 .actions_slot(self.create_copy_button(&refusal_message))
7620 .dismiss_action(self.dismiss_error_button(cx))
7621 }
7622
7623 fn render_any_thread_error(
7624 &mut self,
7625 error: SharedString,
7626 window: &mut Window,
7627 cx: &mut Context<'_, Self>,
7628 ) -> Callout {
7629 let can_resume = self
7630 .thread()
7631 .map_or(false, |thread| thread.read(cx).can_resume(cx));
7632
7633 let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
7634 let thread = thread.read(cx);
7635 let supports_burn_mode = thread
7636 .model()
7637 .map_or(false, |model| model.supports_burn_mode());
7638 supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
7639 });
7640
7641 let markdown = if let Some(markdown) = &self.thread_error_markdown {
7642 markdown.clone()
7643 } else {
7644 let markdown = cx.new(|cx| Markdown::new(error.clone(), None, None, cx));
7645 self.thread_error_markdown = Some(markdown.clone());
7646 markdown
7647 };
7648
7649 let markdown_style = default_markdown_style(false, true, window, cx);
7650 let description = self
7651 .render_markdown(markdown, markdown_style)
7652 .into_any_element();
7653
7654 Callout::new()
7655 .severity(Severity::Error)
7656 .icon(IconName::XCircle)
7657 .title("An Error Happened")
7658 .description_slot(description)
7659 .actions_slot(
7660 h_flex()
7661 .gap_0p5()
7662 .when(can_resume && can_enable_burn_mode, |this| {
7663 this.child(
7664 Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
7665 .icon(IconName::ZedBurnMode)
7666 .icon_position(IconPosition::Start)
7667 .icon_size(IconSize::Small)
7668 .label_size(LabelSize::Small)
7669 .on_click(cx.listener(|this, _, window, cx| {
7670 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
7671 this.resume_chat(cx);
7672 })),
7673 )
7674 })
7675 .when(can_resume, |this| {
7676 this.child(
7677 IconButton::new("retry", IconName::RotateCw)
7678 .icon_size(IconSize::Small)
7679 .tooltip(Tooltip::text("Retry Generation"))
7680 .on_click(cx.listener(|this, _, _window, cx| {
7681 this.resume_chat(cx);
7682 })),
7683 )
7684 })
7685 .child(self.create_copy_button(error.to_string())),
7686 )
7687 .dismiss_action(self.dismiss_error_button(cx))
7688 }
7689
7690 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
7691 const ERROR_MESSAGE: &str =
7692 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
7693
7694 Callout::new()
7695 .severity(Severity::Error)
7696 .icon(IconName::XCircle)
7697 .title("Free Usage Exceeded")
7698 .description(ERROR_MESSAGE)
7699 .actions_slot(
7700 h_flex()
7701 .gap_0p5()
7702 .child(self.upgrade_button(cx))
7703 .child(self.create_copy_button(ERROR_MESSAGE)),
7704 )
7705 .dismiss_action(self.dismiss_error_button(cx))
7706 }
7707
7708 fn render_authentication_required_error(
7709 &self,
7710 error: SharedString,
7711 cx: &mut Context<Self>,
7712 ) -> Callout {
7713 Callout::new()
7714 .severity(Severity::Error)
7715 .title("Authentication Required")
7716 .icon(IconName::XCircle)
7717 .description(error.clone())
7718 .actions_slot(
7719 h_flex()
7720 .gap_0p5()
7721 .child(self.authenticate_button(cx))
7722 .child(self.create_copy_button(error)),
7723 )
7724 .dismiss_action(self.dismiss_error_button(cx))
7725 }
7726
7727 fn render_model_request_limit_reached_error(
7728 &self,
7729 plan: cloud_llm_client::Plan,
7730 cx: &mut Context<Self>,
7731 ) -> Callout {
7732 let error_message = match plan {
7733 cloud_llm_client::Plan::V1(PlanV1::ZedPro) => {
7734 "Upgrade to usage-based billing for more prompts."
7735 }
7736 cloud_llm_client::Plan::V1(PlanV1::ZedProTrial)
7737 | cloud_llm_client::Plan::V1(PlanV1::ZedFree) => "Upgrade to Zed Pro for more prompts.",
7738 cloud_llm_client::Plan::V2(_) => "",
7739 };
7740
7741 Callout::new()
7742 .severity(Severity::Error)
7743 .title("Model Prompt Limit Reached")
7744 .icon(IconName::XCircle)
7745 .description(error_message)
7746 .actions_slot(
7747 h_flex()
7748 .gap_0p5()
7749 .child(self.upgrade_button(cx))
7750 .child(self.create_copy_button(error_message)),
7751 )
7752 .dismiss_action(self.dismiss_error_button(cx))
7753 }
7754
7755 fn render_tool_use_limit_reached_error(&self, cx: &mut Context<Self>) -> Option<Callout> {
7756 let thread = self.as_native_thread(cx)?;
7757 let supports_burn_mode = thread
7758 .read(cx)
7759 .model()
7760 .is_some_and(|model| model.supports_burn_mode());
7761
7762 let focus_handle = self.focus_handle(cx);
7763
7764 Some(
7765 Callout::new()
7766 .icon(IconName::Info)
7767 .title("Consecutive tool use limit reached.")
7768 .actions_slot(
7769 h_flex()
7770 .gap_0p5()
7771 .when(supports_burn_mode, |this| {
7772 this.child(
7773 Button::new("continue-burn-mode", "Continue with Burn Mode")
7774 .style(ButtonStyle::Filled)
7775 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
7776 .layer(ElevationIndex::ModalSurface)
7777 .label_size(LabelSize::Small)
7778 .key_binding(
7779 KeyBinding::for_action_in(
7780 &ContinueWithBurnMode,
7781 &focus_handle,
7782 cx,
7783 )
7784 .map(|kb| kb.size(rems_from_px(10.))),
7785 )
7786 .tooltip(Tooltip::text(
7787 "Enable Burn Mode for unlimited tool use.",
7788 ))
7789 .on_click({
7790 cx.listener(move |this, _, _window, cx| {
7791 thread.update(cx, |thread, cx| {
7792 thread
7793 .set_completion_mode(CompletionMode::Burn, cx);
7794 });
7795 this.resume_chat(cx);
7796 })
7797 }),
7798 )
7799 })
7800 .child(
7801 Button::new("continue-conversation", "Continue")
7802 .layer(ElevationIndex::ModalSurface)
7803 .label_size(LabelSize::Small)
7804 .key_binding(
7805 KeyBinding::for_action_in(&ContinueThread, &focus_handle, cx)
7806 .map(|kb| kb.size(rems_from_px(10.))),
7807 )
7808 .on_click(cx.listener(|this, _, _window, cx| {
7809 this.resume_chat(cx);
7810 })),
7811 ),
7812 ),
7813 )
7814 }
7815
7816 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
7817 let message = message.into();
7818
7819 CopyButton::new(message).tooltip_label("Copy Error Message")
7820 }
7821
7822 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
7823 IconButton::new("dismiss", IconName::Close)
7824 .icon_size(IconSize::Small)
7825 .tooltip(Tooltip::text("Dismiss"))
7826 .on_click(cx.listener({
7827 move |this, _, _, cx| {
7828 this.clear_thread_error(cx);
7829 cx.notify();
7830 }
7831 }))
7832 }
7833
7834 fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
7835 Button::new("authenticate", "Authenticate")
7836 .label_size(LabelSize::Small)
7837 .style(ButtonStyle::Filled)
7838 .on_click(cx.listener({
7839 move |this, _, window, cx| {
7840 let agent = this.agent.clone();
7841 let ThreadState::Ready { thread, .. } = &this.thread_state else {
7842 return;
7843 };
7844
7845 let connection = thread.read(cx).connection().clone();
7846 this.clear_thread_error(cx);
7847 if let Some(message) = this.in_flight_prompt.take() {
7848 this.message_editor.update(cx, |editor, cx| {
7849 editor.set_message(message, window, cx);
7850 });
7851 }
7852 let this = cx.weak_entity();
7853 window.defer(cx, |window, cx| {
7854 Self::handle_auth_required(
7855 this,
7856 AuthRequired::new(),
7857 agent,
7858 connection,
7859 window,
7860 cx,
7861 );
7862 })
7863 }
7864 }))
7865 }
7866
7867 pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7868 let agent = self.agent.clone();
7869 let ThreadState::Ready { thread, .. } = &self.thread_state else {
7870 return;
7871 };
7872
7873 let connection = thread.read(cx).connection().clone();
7874 self.clear_thread_error(cx);
7875 let this = cx.weak_entity();
7876 window.defer(cx, |window, cx| {
7877 Self::handle_auth_required(this, AuthRequired::new(), agent, connection, window, cx);
7878 })
7879 }
7880
7881 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
7882 Button::new("upgrade", "Upgrade")
7883 .label_size(LabelSize::Small)
7884 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
7885 .on_click(cx.listener({
7886 move |this, _, _, cx| {
7887 this.clear_thread_error(cx);
7888 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
7889 }
7890 }))
7891 }
7892
7893 pub fn delete_history_entry(&mut self, entry: AgentSessionInfo, cx: &mut Context<Self>) {
7894 let task = self.history.update(cx, |history, cx| {
7895 history.delete_session(&entry.session_id, cx)
7896 });
7897 task.detach_and_log_err(cx);
7898 }
7899
7900 /// Returns the currently active editor, either for a message that is being
7901 /// edited or the editor for a new message.
7902 fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
7903 if let Some(index) = self.editing_message
7904 && let Some(editor) = self
7905 .entry_view_state
7906 .read(cx)
7907 .entry(index)
7908 .and_then(|e| e.message_editor())
7909 .cloned()
7910 {
7911 editor
7912 } else {
7913 self.message_editor.clone()
7914 }
7915 }
7916
7917 fn get_agent_message_content(
7918 entries: &[AgentThreadEntry],
7919 entry_index: usize,
7920 cx: &App,
7921 ) -> Option<String> {
7922 let entry = entries.get(entry_index)?;
7923 if matches!(entry, AgentThreadEntry::UserMessage(_)) {
7924 return None;
7925 }
7926
7927 let start_index = (0..entry_index)
7928 .rev()
7929 .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
7930 .map(|i| i + 1)
7931 .unwrap_or(0);
7932
7933 let end_index = (entry_index + 1..entries.len())
7934 .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
7935 .map(|i| i - 1)
7936 .unwrap_or(entries.len() - 1);
7937
7938 let parts: Vec<String> = (start_index..=end_index)
7939 .filter_map(|i| entries.get(i))
7940 .filter_map(|entry| {
7941 if let AgentThreadEntry::AssistantMessage(message) = entry {
7942 let text: String = message
7943 .chunks
7944 .iter()
7945 .filter_map(|chunk| match chunk {
7946 AssistantMessageChunk::Message { block } => {
7947 let markdown = block.to_markdown(cx);
7948 if markdown.trim().is_empty() {
7949 None
7950 } else {
7951 Some(markdown.to_string())
7952 }
7953 }
7954 AssistantMessageChunk::Thought { .. } => None,
7955 })
7956 .collect::<Vec<_>>()
7957 .join("\n\n");
7958
7959 if text.is_empty() { None } else { Some(text) }
7960 } else {
7961 None
7962 }
7963 })
7964 .collect();
7965
7966 let text = parts.join("\n\n");
7967 if text.is_empty() { None } else { Some(text) }
7968 }
7969}
7970
7971fn loading_contents_spinner(size: IconSize) -> AnyElement {
7972 Icon::new(IconName::LoadCircle)
7973 .size(size)
7974 .color(Color::Accent)
7975 .with_rotate_animation(3)
7976 .into_any_element()
7977}
7978
7979fn placeholder_text(agent_name: &str, has_commands: bool) -> String {
7980 if agent_name == "Zed Agent" {
7981 format!("Message the {} — @ to include context", agent_name)
7982 } else if has_commands {
7983 format!(
7984 "Message {} — @ to include context, / for commands",
7985 agent_name
7986 )
7987 } else {
7988 format!("Message {} — @ to include context", agent_name)
7989 }
7990}
7991
7992impl Focusable for AcpThreadView {
7993 fn focus_handle(&self, cx: &App) -> FocusHandle {
7994 match self.thread_state {
7995 ThreadState::Ready { .. } => self.active_editor(cx).focus_handle(cx),
7996 ThreadState::Loading { .. }
7997 | ThreadState::LoadError(_)
7998 | ThreadState::Unauthenticated { .. } => self.focus_handle.clone(),
7999 }
8000 }
8001}
8002
8003#[cfg(any(test, feature = "test-support"))]
8004impl AcpThreadView {
8005 /// Expands a tool call so its content is visible.
8006 /// This is primarily useful for visual testing.
8007 pub fn expand_tool_call(&mut self, tool_call_id: acp::ToolCallId, cx: &mut Context<Self>) {
8008 self.expanded_tool_calls.insert(tool_call_id);
8009 cx.notify();
8010 }
8011
8012 /// Expands a subagent card so its content is visible.
8013 /// This is primarily useful for visual testing.
8014 pub fn expand_subagent(&mut self, session_id: acp::SessionId, cx: &mut Context<Self>) {
8015 self.expanded_subagents.insert(session_id);
8016 cx.notify();
8017 }
8018}
8019
8020impl Render for AcpThreadView {
8021 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8022 let has_messages = self.list_state.item_count() > 0;
8023 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
8024
8025 v_flex()
8026 .size_full()
8027 .key_context("AcpThread")
8028 .on_action(cx.listener(|this, _: &menu::Cancel, _, cx| {
8029 this.cancel_generation(cx);
8030 }))
8031 .on_action(cx.listener(Self::toggle_burn_mode))
8032 .on_action(cx.listener(Self::keep_all))
8033 .on_action(cx.listener(Self::reject_all))
8034 .on_action(cx.listener(Self::allow_always))
8035 .on_action(cx.listener(Self::allow_once))
8036 .on_action(cx.listener(Self::reject_once))
8037 .on_action(cx.listener(Self::handle_authorize_tool_call))
8038 .on_action(cx.listener(Self::handle_select_permission_granularity))
8039 .on_action(cx.listener(Self::open_permission_dropdown))
8040 .on_action(cx.listener(|this, _: &SendNextQueuedMessage, window, cx| {
8041 this.send_queued_message_at_index(0, true, window, cx);
8042 }))
8043 .on_action(cx.listener(|this, _: &ClearMessageQueue, _, cx| {
8044 this.message_queue.clear();
8045 cx.notify();
8046 }))
8047 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
8048 if let Some(config_options_view) = this.config_options_view.as_ref() {
8049 let handled = config_options_view.update(cx, |view, cx| {
8050 view.toggle_category_picker(
8051 acp::SessionConfigOptionCategory::Mode,
8052 window,
8053 cx,
8054 )
8055 });
8056 if handled {
8057 return;
8058 }
8059 }
8060
8061 if let Some(profile_selector) = this.profile_selector.as_ref() {
8062 profile_selector.read(cx).menu_handle().toggle(window, cx);
8063 } else if let Some(mode_selector) = this.mode_selector() {
8064 mode_selector.read(cx).menu_handle().toggle(window, cx);
8065 }
8066 }))
8067 .on_action(cx.listener(|this, _: &CycleModeSelector, window, cx| {
8068 if let Some(config_options_view) = this.config_options_view.as_ref() {
8069 let handled = config_options_view.update(cx, |view, cx| {
8070 view.cycle_category_option(
8071 acp::SessionConfigOptionCategory::Mode,
8072 false,
8073 cx,
8074 )
8075 });
8076 if handled {
8077 return;
8078 }
8079 }
8080
8081 if let Some(profile_selector) = this.profile_selector.as_ref() {
8082 profile_selector.update(cx, |profile_selector, cx| {
8083 profile_selector.cycle_profile(cx);
8084 });
8085 } else if let Some(mode_selector) = this.mode_selector() {
8086 mode_selector.update(cx, |mode_selector, cx| {
8087 mode_selector.cycle_mode(window, cx);
8088 });
8089 }
8090 }))
8091 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
8092 if let Some(config_options_view) = this.config_options_view.as_ref() {
8093 let handled = config_options_view.update(cx, |view, cx| {
8094 view.toggle_category_picker(
8095 acp::SessionConfigOptionCategory::Model,
8096 window,
8097 cx,
8098 )
8099 });
8100 if handled {
8101 return;
8102 }
8103 }
8104
8105 if let Some(model_selector) = this.model_selector.as_ref() {
8106 model_selector
8107 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
8108 }
8109 }))
8110 .on_action(cx.listener(|this, _: &CycleFavoriteModels, window, cx| {
8111 if let Some(config_options_view) = this.config_options_view.as_ref() {
8112 let handled = config_options_view.update(cx, |view, cx| {
8113 view.cycle_category_option(
8114 acp::SessionConfigOptionCategory::Model,
8115 true,
8116 cx,
8117 )
8118 });
8119 if handled {
8120 return;
8121 }
8122 }
8123
8124 if let Some(model_selector) = this.model_selector.as_ref() {
8125 model_selector.update(cx, |model_selector, cx| {
8126 model_selector.cycle_favorite_models(window, cx);
8127 });
8128 }
8129 }))
8130 .track_focus(&self.focus_handle)
8131 .bg(cx.theme().colors().panel_background)
8132 .child(match &self.thread_state {
8133 ThreadState::Unauthenticated {
8134 connection,
8135 description,
8136 configuration_view,
8137 pending_auth_method,
8138 ..
8139 } => v_flex()
8140 .flex_1()
8141 .size_full()
8142 .justify_end()
8143 .child(self.render_auth_required_state(
8144 connection,
8145 description.as_ref(),
8146 configuration_view.as_ref(),
8147 pending_auth_method.as_ref(),
8148 window,
8149 cx,
8150 ))
8151 .into_any_element(),
8152 ThreadState::Loading { .. } => v_flex()
8153 .flex_1()
8154 .child(self.render_recent_history(cx))
8155 .into_any(),
8156 ThreadState::LoadError(e) => v_flex()
8157 .flex_1()
8158 .size_full()
8159 .items_center()
8160 .justify_end()
8161 .child(self.render_load_error(e, window, cx))
8162 .into_any(),
8163 ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
8164 if has_messages {
8165 this.child(
8166 list(
8167 self.list_state.clone(),
8168 cx.processor(|this, index: usize, window, cx| {
8169 let Some((entry, len)) = this.thread().and_then(|thread| {
8170 let entries = &thread.read(cx).entries();
8171 Some((entries.get(index)?, entries.len()))
8172 }) else {
8173 return Empty.into_any();
8174 };
8175 this.render_entry(index, len, entry, window, cx)
8176 }),
8177 )
8178 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
8179 .flex_grow()
8180 .into_any(),
8181 )
8182 .vertical_scrollbar_for(&self.list_state, window, cx)
8183 .into_any()
8184 } else {
8185 this.child(self.render_recent_history(cx)).into_any()
8186 }
8187 }),
8188 })
8189 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
8190 // above so that the scrollbar doesn't render behind it. The current setup allows
8191 // the scrollbar to stop exactly at the activity bar start.
8192 .when(has_messages, |this| match &self.thread_state {
8193 ThreadState::Ready { thread, .. } => {
8194 this.children(self.render_activity_bar(thread, window, cx))
8195 }
8196 _ => this,
8197 })
8198 .children(self.render_thread_retry_status_callout(window, cx))
8199 .when(self.show_codex_windows_warning, |this| {
8200 this.child(self.render_codex_windows_warning(cx))
8201 })
8202 .children(self.render_thread_error(window, cx))
8203 .when_some(
8204 self.new_server_version_available.as_ref().filter(|_| {
8205 !has_messages || !matches!(self.thread_state, ThreadState::Ready { .. })
8206 }),
8207 |this, version| this.child(self.render_new_version_callout(&version, cx)),
8208 )
8209 .children(
8210 if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
8211 Some(usage_callout.into_any_element())
8212 } else {
8213 self.render_token_limit_callout(cx)
8214 .map(|token_limit_callout| token_limit_callout.into_any_element())
8215 },
8216 )
8217 .child(self.render_message_editor(window, cx))
8218 }
8219}
8220
8221fn default_markdown_style(
8222 buffer_font: bool,
8223 muted_text: bool,
8224 window: &Window,
8225 cx: &App,
8226) -> MarkdownStyle {
8227 let theme_settings = ThemeSettings::get_global(cx);
8228 let colors = cx.theme().colors();
8229
8230 let buffer_font_size = theme_settings.agent_buffer_font_size(cx);
8231
8232 let mut text_style = window.text_style();
8233 let line_height = buffer_font_size * 1.75;
8234
8235 let font_family = if buffer_font {
8236 theme_settings.buffer_font.family.clone()
8237 } else {
8238 theme_settings.ui_font.family.clone()
8239 };
8240
8241 let font_size = if buffer_font {
8242 theme_settings.agent_buffer_font_size(cx)
8243 } else {
8244 theme_settings.agent_ui_font_size(cx)
8245 };
8246
8247 let text_color = if muted_text {
8248 colors.text_muted
8249 } else {
8250 colors.text
8251 };
8252
8253 text_style.refine(&TextStyleRefinement {
8254 font_family: Some(font_family),
8255 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
8256 font_features: Some(theme_settings.ui_font.features.clone()),
8257 font_size: Some(font_size.into()),
8258 line_height: Some(line_height.into()),
8259 color: Some(text_color),
8260 ..Default::default()
8261 });
8262
8263 MarkdownStyle {
8264 base_text_style: text_style.clone(),
8265 syntax: cx.theme().syntax().clone(),
8266 selection_background_color: colors.element_selection_background,
8267 code_block_overflow_x_scroll: true,
8268 heading_level_styles: Some(HeadingLevelStyles {
8269 h1: Some(TextStyleRefinement {
8270 font_size: Some(rems(1.15).into()),
8271 ..Default::default()
8272 }),
8273 h2: Some(TextStyleRefinement {
8274 font_size: Some(rems(1.1).into()),
8275 ..Default::default()
8276 }),
8277 h3: Some(TextStyleRefinement {
8278 font_size: Some(rems(1.05).into()),
8279 ..Default::default()
8280 }),
8281 h4: Some(TextStyleRefinement {
8282 font_size: Some(rems(1.).into()),
8283 ..Default::default()
8284 }),
8285 h5: Some(TextStyleRefinement {
8286 font_size: Some(rems(0.95).into()),
8287 ..Default::default()
8288 }),
8289 h6: Some(TextStyleRefinement {
8290 font_size: Some(rems(0.875).into()),
8291 ..Default::default()
8292 }),
8293 }),
8294 code_block: StyleRefinement {
8295 padding: EdgesRefinement {
8296 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
8297 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
8298 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
8299 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
8300 },
8301 margin: EdgesRefinement {
8302 top: Some(Length::Definite(px(8.).into())),
8303 left: Some(Length::Definite(px(0.).into())),
8304 right: Some(Length::Definite(px(0.).into())),
8305 bottom: Some(Length::Definite(px(12.).into())),
8306 },
8307 border_style: Some(BorderStyle::Solid),
8308 border_widths: EdgesRefinement {
8309 top: Some(AbsoluteLength::Pixels(px(1.))),
8310 left: Some(AbsoluteLength::Pixels(px(1.))),
8311 right: Some(AbsoluteLength::Pixels(px(1.))),
8312 bottom: Some(AbsoluteLength::Pixels(px(1.))),
8313 },
8314 border_color: Some(colors.border_variant),
8315 background: Some(colors.editor_background.into()),
8316 text: TextStyleRefinement {
8317 font_family: Some(theme_settings.buffer_font.family.clone()),
8318 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
8319 font_features: Some(theme_settings.buffer_font.features.clone()),
8320 font_size: Some(buffer_font_size.into()),
8321 ..Default::default()
8322 },
8323 ..Default::default()
8324 },
8325 inline_code: TextStyleRefinement {
8326 font_family: Some(theme_settings.buffer_font.family.clone()),
8327 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
8328 font_features: Some(theme_settings.buffer_font.features.clone()),
8329 font_size: Some(buffer_font_size.into()),
8330 background_color: Some(colors.editor_foreground.opacity(0.08)),
8331 ..Default::default()
8332 },
8333 link: TextStyleRefinement {
8334 background_color: Some(colors.editor_foreground.opacity(0.025)),
8335 color: Some(colors.text_accent),
8336 underline: Some(UnderlineStyle {
8337 color: Some(colors.text_accent.opacity(0.5)),
8338 thickness: px(1.),
8339 ..Default::default()
8340 }),
8341 ..Default::default()
8342 },
8343 ..Default::default()
8344 }
8345}
8346
8347fn plan_label_markdown_style(
8348 status: &acp::PlanEntryStatus,
8349 window: &Window,
8350 cx: &App,
8351) -> MarkdownStyle {
8352 let default_md_style = default_markdown_style(false, false, window, cx);
8353
8354 MarkdownStyle {
8355 base_text_style: TextStyle {
8356 color: cx.theme().colors().text_muted,
8357 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
8358 Some(gpui::StrikethroughStyle {
8359 thickness: px(1.),
8360 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
8361 })
8362 } else {
8363 None
8364 },
8365 ..default_md_style.base_text_style
8366 },
8367 ..default_md_style
8368 }
8369}
8370
8371#[cfg(test)]
8372pub(crate) mod tests {
8373 use acp_thread::{
8374 AgentSessionList, AgentSessionListRequest, AgentSessionListResponse, StubAgentConnection,
8375 };
8376 use action_log::ActionLog;
8377 use agent::ToolPermissionContext;
8378 use agent_client_protocol::SessionId;
8379 use editor::MultiBufferOffset;
8380 use fs::FakeFs;
8381 use gpui::{EventEmitter, TestAppContext, VisualTestContext};
8382 use project::Project;
8383 use serde_json::json;
8384 use settings::SettingsStore;
8385 use std::any::Any;
8386 use std::path::Path;
8387 use std::rc::Rc;
8388 use workspace::Item;
8389
8390 use super::*;
8391
8392 #[gpui::test]
8393 async fn test_drop(cx: &mut TestAppContext) {
8394 init_test(cx);
8395
8396 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
8397 let weak_view = thread_view.downgrade();
8398 drop(thread_view);
8399 assert!(!weak_view.is_upgradable());
8400 }
8401
8402 #[gpui::test]
8403 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
8404 init_test(cx);
8405
8406 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
8407
8408 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8409 message_editor.update_in(cx, |editor, window, cx| {
8410 editor.set_text("Hello", window, cx);
8411 });
8412
8413 cx.deactivate_window();
8414
8415 thread_view.update_in(cx, |thread_view, window, cx| {
8416 thread_view.send(window, cx);
8417 });
8418
8419 cx.run_until_parked();
8420
8421 assert!(
8422 cx.windows()
8423 .iter()
8424 .any(|window| window.downcast::<AgentNotification>().is_some())
8425 );
8426 }
8427
8428 #[gpui::test]
8429 async fn test_notification_for_error(cx: &mut TestAppContext) {
8430 init_test(cx);
8431
8432 let (thread_view, cx) =
8433 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
8434
8435 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8436 message_editor.update_in(cx, |editor, window, cx| {
8437 editor.set_text("Hello", window, cx);
8438 });
8439
8440 cx.deactivate_window();
8441
8442 thread_view.update_in(cx, |thread_view, window, cx| {
8443 thread_view.send(window, cx);
8444 });
8445
8446 cx.run_until_parked();
8447
8448 assert!(
8449 cx.windows()
8450 .iter()
8451 .any(|window| window.downcast::<AgentNotification>().is_some())
8452 );
8453 }
8454
8455 #[gpui::test]
8456 async fn test_recent_history_refreshes_when_history_cache_updated(cx: &mut TestAppContext) {
8457 init_test(cx);
8458
8459 let session_a = AgentSessionInfo::new(SessionId::new("session-a"));
8460 let session_b = AgentSessionInfo::new(SessionId::new("session-b"));
8461
8462 let fs = FakeFs::new(cx.executor());
8463 let project = Project::test(fs, [], cx).await;
8464 let (workspace, cx) =
8465 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8466
8467 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
8468 // Create history without an initial session list - it will be set after connection
8469 let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
8470
8471 let thread_view = cx.update(|window, cx| {
8472 cx.new(|cx| {
8473 AcpThreadView::new(
8474 Rc::new(StubAgentServer::default_response()),
8475 None,
8476 None,
8477 workspace.downgrade(),
8478 project,
8479 Some(thread_store),
8480 None,
8481 history.clone(),
8482 false,
8483 window,
8484 cx,
8485 )
8486 })
8487 });
8488
8489 // Wait for connection to establish
8490 cx.run_until_parked();
8491
8492 // Initially empty because StubAgentConnection.session_list() returns None
8493 thread_view.read_with(cx, |view, _cx| {
8494 assert_eq!(view.recent_history_entries.len(), 0);
8495 });
8496
8497 // Now set the session list - this simulates external agents providing their history
8498 let list_a: Rc<dyn AgentSessionList> =
8499 Rc::new(StubSessionList::new(vec![session_a.clone()]));
8500 history.update(cx, |history, cx| {
8501 history.set_session_list(Some(list_a), cx);
8502 });
8503 cx.run_until_parked();
8504
8505 thread_view.read_with(cx, |view, _cx| {
8506 assert_eq!(view.recent_history_entries.len(), 1);
8507 assert_eq!(
8508 view.recent_history_entries[0].session_id,
8509 session_a.session_id
8510 );
8511 });
8512
8513 // Update to a different session list
8514 let list_b: Rc<dyn AgentSessionList> =
8515 Rc::new(StubSessionList::new(vec![session_b.clone()]));
8516 history.update(cx, |history, cx| {
8517 history.set_session_list(Some(list_b), cx);
8518 });
8519 cx.run_until_parked();
8520
8521 thread_view.read_with(cx, |view, _cx| {
8522 assert_eq!(view.recent_history_entries.len(), 1);
8523 assert_eq!(
8524 view.recent_history_entries[0].session_id,
8525 session_b.session_id
8526 );
8527 });
8528 }
8529
8530 #[gpui::test]
8531 async fn test_refusal_handling(cx: &mut TestAppContext) {
8532 init_test(cx);
8533
8534 let (thread_view, cx) =
8535 setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
8536
8537 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8538 message_editor.update_in(cx, |editor, window, cx| {
8539 editor.set_text("Do something harmful", window, cx);
8540 });
8541
8542 thread_view.update_in(cx, |thread_view, window, cx| {
8543 thread_view.send(window, cx);
8544 });
8545
8546 cx.run_until_parked();
8547
8548 // Check that the refusal error is set
8549 thread_view.read_with(cx, |thread_view, _cx| {
8550 assert!(
8551 matches!(thread_view.thread_error, Some(ThreadError::Refusal)),
8552 "Expected refusal error to be set"
8553 );
8554 });
8555 }
8556
8557 #[gpui::test]
8558 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
8559 init_test(cx);
8560
8561 let tool_call_id = acp::ToolCallId::new("1");
8562 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Label")
8563 .kind(acp::ToolKind::Edit)
8564 .content(vec!["hi".into()]);
8565 let connection =
8566 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
8567 tool_call_id,
8568 vec![acp::PermissionOption::new(
8569 "1",
8570 "Allow",
8571 acp::PermissionOptionKind::AllowOnce,
8572 )],
8573 )]));
8574
8575 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
8576
8577 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
8578
8579 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8580 message_editor.update_in(cx, |editor, window, cx| {
8581 editor.set_text("Hello", window, cx);
8582 });
8583
8584 cx.deactivate_window();
8585
8586 thread_view.update_in(cx, |thread_view, window, cx| {
8587 thread_view.send(window, cx);
8588 });
8589
8590 cx.run_until_parked();
8591
8592 assert!(
8593 cx.windows()
8594 .iter()
8595 .any(|window| window.downcast::<AgentNotification>().is_some())
8596 );
8597 }
8598
8599 #[gpui::test]
8600 async fn test_notification_when_panel_hidden(cx: &mut TestAppContext) {
8601 init_test(cx);
8602
8603 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
8604
8605 add_to_workspace(thread_view.clone(), cx);
8606
8607 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8608
8609 message_editor.update_in(cx, |editor, window, cx| {
8610 editor.set_text("Hello", window, cx);
8611 });
8612
8613 // Window is active (don't deactivate), but panel will be hidden
8614 // Note: In the test environment, the panel is not actually added to the dock,
8615 // so is_agent_panel_hidden will return true
8616
8617 thread_view.update_in(cx, |thread_view, window, cx| {
8618 thread_view.send(window, cx);
8619 });
8620
8621 cx.run_until_parked();
8622
8623 // Should show notification because window is active but panel is hidden
8624 assert!(
8625 cx.windows()
8626 .iter()
8627 .any(|window| window.downcast::<AgentNotification>().is_some()),
8628 "Expected notification when panel is hidden"
8629 );
8630 }
8631
8632 #[gpui::test]
8633 async fn test_notification_still_works_when_window_inactive(cx: &mut TestAppContext) {
8634 init_test(cx);
8635
8636 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
8637
8638 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8639 message_editor.update_in(cx, |editor, window, cx| {
8640 editor.set_text("Hello", window, cx);
8641 });
8642
8643 // Deactivate window - should show notification regardless of setting
8644 cx.deactivate_window();
8645
8646 thread_view.update_in(cx, |thread_view, window, cx| {
8647 thread_view.send(window, cx);
8648 });
8649
8650 cx.run_until_parked();
8651
8652 // Should still show notification when window is inactive (existing behavior)
8653 assert!(
8654 cx.windows()
8655 .iter()
8656 .any(|window| window.downcast::<AgentNotification>().is_some()),
8657 "Expected notification when window is inactive"
8658 );
8659 }
8660
8661 #[gpui::test]
8662 async fn test_notification_respects_never_setting(cx: &mut TestAppContext) {
8663 init_test(cx);
8664
8665 // Set notify_when_agent_waiting to Never
8666 cx.update(|cx| {
8667 AgentSettings::override_global(
8668 AgentSettings {
8669 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
8670 ..AgentSettings::get_global(cx).clone()
8671 },
8672 cx,
8673 );
8674 });
8675
8676 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
8677
8678 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8679 message_editor.update_in(cx, |editor, window, cx| {
8680 editor.set_text("Hello", window, cx);
8681 });
8682
8683 // Window is active
8684
8685 thread_view.update_in(cx, |thread_view, window, cx| {
8686 thread_view.send(window, cx);
8687 });
8688
8689 cx.run_until_parked();
8690
8691 // Should NOT show notification because notify_when_agent_waiting is Never
8692 assert!(
8693 !cx.windows()
8694 .iter()
8695 .any(|window| window.downcast::<AgentNotification>().is_some()),
8696 "Expected no notification when notify_when_agent_waiting is Never"
8697 );
8698 }
8699
8700 #[gpui::test]
8701 async fn test_notification_closed_when_thread_view_dropped(cx: &mut TestAppContext) {
8702 init_test(cx);
8703
8704 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
8705
8706 let weak_view = thread_view.downgrade();
8707
8708 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8709 message_editor.update_in(cx, |editor, window, cx| {
8710 editor.set_text("Hello", window, cx);
8711 });
8712
8713 cx.deactivate_window();
8714
8715 thread_view.update_in(cx, |thread_view, window, cx| {
8716 thread_view.send(window, cx);
8717 });
8718
8719 cx.run_until_parked();
8720
8721 // Verify notification is shown
8722 assert!(
8723 cx.windows()
8724 .iter()
8725 .any(|window| window.downcast::<AgentNotification>().is_some()),
8726 "Expected notification to be shown"
8727 );
8728
8729 // Drop the thread view (simulating navigation to a new thread)
8730 drop(thread_view);
8731 drop(message_editor);
8732 // Trigger an update to flush effects, which will call release_dropped_entities
8733 cx.update(|_window, _cx| {});
8734 cx.run_until_parked();
8735
8736 // Verify the entity was actually released
8737 assert!(
8738 !weak_view.is_upgradable(),
8739 "Thread view entity should be released after dropping"
8740 );
8741
8742 // The notification should be automatically closed via on_release
8743 assert!(
8744 !cx.windows()
8745 .iter()
8746 .any(|window| window.downcast::<AgentNotification>().is_some()),
8747 "Notification should be closed when thread view is dropped"
8748 );
8749 }
8750
8751 async fn setup_thread_view(
8752 agent: impl AgentServer + 'static,
8753 cx: &mut TestAppContext,
8754 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
8755 let fs = FakeFs::new(cx.executor());
8756 let project = Project::test(fs, [], cx).await;
8757 let (workspace, cx) =
8758 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8759
8760 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
8761 let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
8762
8763 let thread_view = cx.update(|window, cx| {
8764 cx.new(|cx| {
8765 AcpThreadView::new(
8766 Rc::new(agent),
8767 None,
8768 None,
8769 workspace.downgrade(),
8770 project,
8771 Some(thread_store),
8772 None,
8773 history,
8774 false,
8775 window,
8776 cx,
8777 )
8778 })
8779 });
8780 cx.run_until_parked();
8781 (thread_view, cx)
8782 }
8783
8784 fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
8785 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
8786
8787 workspace
8788 .update_in(cx, |workspace, window, cx| {
8789 workspace.add_item_to_active_pane(
8790 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
8791 None,
8792 true,
8793 window,
8794 cx,
8795 );
8796 })
8797 .unwrap();
8798 }
8799
8800 struct ThreadViewItem(Entity<AcpThreadView>);
8801
8802 impl Item for ThreadViewItem {
8803 type Event = ();
8804
8805 fn include_in_nav_history() -> bool {
8806 false
8807 }
8808
8809 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
8810 "Test".into()
8811 }
8812 }
8813
8814 impl EventEmitter<()> for ThreadViewItem {}
8815
8816 impl Focusable for ThreadViewItem {
8817 fn focus_handle(&self, cx: &App) -> FocusHandle {
8818 self.0.read(cx).focus_handle(cx)
8819 }
8820 }
8821
8822 impl Render for ThreadViewItem {
8823 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8824 self.0.clone().into_any_element()
8825 }
8826 }
8827
8828 struct StubAgentServer<C> {
8829 connection: C,
8830 }
8831
8832 impl<C> StubAgentServer<C> {
8833 fn new(connection: C) -> Self {
8834 Self { connection }
8835 }
8836 }
8837
8838 impl StubAgentServer<StubAgentConnection> {
8839 fn default_response() -> Self {
8840 let conn = StubAgentConnection::new();
8841 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8842 acp::ContentChunk::new("Default response".into()),
8843 )]);
8844 Self::new(conn)
8845 }
8846 }
8847
8848 #[derive(Clone)]
8849 struct StubSessionList {
8850 sessions: Vec<AgentSessionInfo>,
8851 }
8852
8853 impl StubSessionList {
8854 fn new(sessions: Vec<AgentSessionInfo>) -> Self {
8855 Self { sessions }
8856 }
8857 }
8858
8859 impl AgentSessionList for StubSessionList {
8860 fn list_sessions(
8861 &self,
8862 _request: AgentSessionListRequest,
8863 _cx: &mut App,
8864 ) -> Task<anyhow::Result<AgentSessionListResponse>> {
8865 Task::ready(Ok(AgentSessionListResponse::new(self.sessions.clone())))
8866 }
8867 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
8868 self
8869 }
8870 }
8871
8872 impl<C> AgentServer for StubAgentServer<C>
8873 where
8874 C: 'static + AgentConnection + Send + Clone,
8875 {
8876 fn logo(&self) -> ui::IconName {
8877 ui::IconName::Ai
8878 }
8879
8880 fn name(&self) -> SharedString {
8881 "Test".into()
8882 }
8883
8884 fn connect(
8885 &self,
8886 _root_dir: Option<&Path>,
8887 _delegate: AgentServerDelegate,
8888 _cx: &mut App,
8889 ) -> Task<gpui::Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
8890 Task::ready(Ok((Rc::new(self.connection.clone()), None)))
8891 }
8892
8893 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
8894 self
8895 }
8896 }
8897
8898 #[derive(Clone)]
8899 struct SaboteurAgentConnection;
8900
8901 impl AgentConnection for SaboteurAgentConnection {
8902 fn telemetry_id(&self) -> SharedString {
8903 "saboteur".into()
8904 }
8905
8906 fn new_thread(
8907 self: Rc<Self>,
8908 project: Entity<Project>,
8909 _cwd: &Path,
8910 cx: &mut gpui::App,
8911 ) -> Task<gpui::Result<Entity<AcpThread>>> {
8912 Task::ready(Ok(cx.new(|cx| {
8913 let action_log = cx.new(|_| ActionLog::new(project.clone()));
8914 AcpThread::new(
8915 "SaboteurAgentConnection",
8916 self,
8917 project,
8918 action_log,
8919 SessionId::new("test"),
8920 watch::Receiver::constant(
8921 acp::PromptCapabilities::new()
8922 .image(true)
8923 .audio(true)
8924 .embedded_context(true),
8925 ),
8926 cx,
8927 )
8928 })))
8929 }
8930
8931 fn auth_methods(&self) -> &[acp::AuthMethod] {
8932 &[]
8933 }
8934
8935 fn authenticate(
8936 &self,
8937 _method_id: acp::AuthMethodId,
8938 _cx: &mut App,
8939 ) -> Task<gpui::Result<()>> {
8940 unimplemented!()
8941 }
8942
8943 fn prompt(
8944 &self,
8945 _id: Option<acp_thread::UserMessageId>,
8946 _params: acp::PromptRequest,
8947 _cx: &mut App,
8948 ) -> Task<gpui::Result<acp::PromptResponse>> {
8949 Task::ready(Err(anyhow::anyhow!("Error prompting")))
8950 }
8951
8952 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
8953 unimplemented!()
8954 }
8955
8956 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
8957 self
8958 }
8959 }
8960
8961 /// Simulates a model which always returns a refusal response
8962 #[derive(Clone)]
8963 struct RefusalAgentConnection;
8964
8965 impl AgentConnection for RefusalAgentConnection {
8966 fn telemetry_id(&self) -> SharedString {
8967 "refusal".into()
8968 }
8969
8970 fn new_thread(
8971 self: Rc<Self>,
8972 project: Entity<Project>,
8973 _cwd: &Path,
8974 cx: &mut gpui::App,
8975 ) -> Task<gpui::Result<Entity<AcpThread>>> {
8976 Task::ready(Ok(cx.new(|cx| {
8977 let action_log = cx.new(|_| ActionLog::new(project.clone()));
8978 AcpThread::new(
8979 "RefusalAgentConnection",
8980 self,
8981 project,
8982 action_log,
8983 SessionId::new("test"),
8984 watch::Receiver::constant(
8985 acp::PromptCapabilities::new()
8986 .image(true)
8987 .audio(true)
8988 .embedded_context(true),
8989 ),
8990 cx,
8991 )
8992 })))
8993 }
8994
8995 fn auth_methods(&self) -> &[acp::AuthMethod] {
8996 &[]
8997 }
8998
8999 fn authenticate(
9000 &self,
9001 _method_id: acp::AuthMethodId,
9002 _cx: &mut App,
9003 ) -> Task<gpui::Result<()>> {
9004 unimplemented!()
9005 }
9006
9007 fn prompt(
9008 &self,
9009 _id: Option<acp_thread::UserMessageId>,
9010 _params: acp::PromptRequest,
9011 _cx: &mut App,
9012 ) -> Task<gpui::Result<acp::PromptResponse>> {
9013 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::Refusal)))
9014 }
9015
9016 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
9017 unimplemented!()
9018 }
9019
9020 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
9021 self
9022 }
9023 }
9024
9025 pub(crate) fn init_test(cx: &mut TestAppContext) {
9026 cx.update(|cx| {
9027 let settings_store = SettingsStore::test(cx);
9028 cx.set_global(settings_store);
9029 theme::init(theme::LoadThemes::JustBase, cx);
9030 release_channel::init(semver::Version::new(0, 0, 0), cx);
9031 prompt_store::init(cx)
9032 });
9033 }
9034
9035 #[gpui::test]
9036 async fn test_rewind_views(cx: &mut TestAppContext) {
9037 init_test(cx);
9038
9039 let fs = FakeFs::new(cx.executor());
9040 fs.insert_tree(
9041 "/project",
9042 json!({
9043 "test1.txt": "old content 1",
9044 "test2.txt": "old content 2"
9045 }),
9046 )
9047 .await;
9048 let project = Project::test(fs, [Path::new("/project")], cx).await;
9049 let (workspace, cx) =
9050 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9051
9052 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
9053 let history = cx.update(|window, cx| cx.new(|cx| AcpThreadHistory::new(None, window, cx)));
9054
9055 let connection = Rc::new(StubAgentConnection::new());
9056 let thread_view = cx.update(|window, cx| {
9057 cx.new(|cx| {
9058 AcpThreadView::new(
9059 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
9060 None,
9061 None,
9062 workspace.downgrade(),
9063 project.clone(),
9064 Some(thread_store.clone()),
9065 None,
9066 history,
9067 false,
9068 window,
9069 cx,
9070 )
9071 })
9072 });
9073
9074 cx.run_until_parked();
9075
9076 let thread = thread_view
9077 .read_with(cx, |view, _| view.thread().cloned())
9078 .unwrap();
9079
9080 // First user message
9081 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
9082 acp::ToolCall::new("tool1", "Edit file 1")
9083 .kind(acp::ToolKind::Edit)
9084 .status(acp::ToolCallStatus::Completed)
9085 .content(vec![acp::ToolCallContent::Diff(
9086 acp::Diff::new("/project/test1.txt", "new content 1").old_text("old content 1"),
9087 )]),
9088 )]);
9089
9090 thread
9091 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
9092 .await
9093 .unwrap();
9094 cx.run_until_parked();
9095
9096 thread.read_with(cx, |thread, _| {
9097 assert_eq!(thread.entries().len(), 2);
9098 });
9099
9100 thread_view.read_with(cx, |view, cx| {
9101 view.entry_view_state.read_with(cx, |entry_view_state, _| {
9102 assert!(
9103 entry_view_state
9104 .entry(0)
9105 .unwrap()
9106 .message_editor()
9107 .is_some()
9108 );
9109 assert!(entry_view_state.entry(1).unwrap().has_content());
9110 });
9111 });
9112
9113 // Second user message
9114 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
9115 acp::ToolCall::new("tool2", "Edit file 2")
9116 .kind(acp::ToolKind::Edit)
9117 .status(acp::ToolCallStatus::Completed)
9118 .content(vec![acp::ToolCallContent::Diff(
9119 acp::Diff::new("/project/test2.txt", "new content 2").old_text("old content 2"),
9120 )]),
9121 )]);
9122
9123 thread
9124 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
9125 .await
9126 .unwrap();
9127 cx.run_until_parked();
9128
9129 let second_user_message_id = thread.read_with(cx, |thread, _| {
9130 assert_eq!(thread.entries().len(), 4);
9131 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
9132 panic!();
9133 };
9134 user_message.id.clone().unwrap()
9135 });
9136
9137 thread_view.read_with(cx, |view, cx| {
9138 view.entry_view_state.read_with(cx, |entry_view_state, _| {
9139 assert!(
9140 entry_view_state
9141 .entry(0)
9142 .unwrap()
9143 .message_editor()
9144 .is_some()
9145 );
9146 assert!(entry_view_state.entry(1).unwrap().has_content());
9147 assert!(
9148 entry_view_state
9149 .entry(2)
9150 .unwrap()
9151 .message_editor()
9152 .is_some()
9153 );
9154 assert!(entry_view_state.entry(3).unwrap().has_content());
9155 });
9156 });
9157
9158 // Rewind to first message
9159 thread
9160 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
9161 .await
9162 .unwrap();
9163
9164 cx.run_until_parked();
9165
9166 thread.read_with(cx, |thread, _| {
9167 assert_eq!(thread.entries().len(), 2);
9168 });
9169
9170 thread_view.read_with(cx, |view, cx| {
9171 view.entry_view_state.read_with(cx, |entry_view_state, _| {
9172 assert!(
9173 entry_view_state
9174 .entry(0)
9175 .unwrap()
9176 .message_editor()
9177 .is_some()
9178 );
9179 assert!(entry_view_state.entry(1).unwrap().has_content());
9180
9181 // Old views should be dropped
9182 assert!(entry_view_state.entry(2).is_none());
9183 assert!(entry_view_state.entry(3).is_none());
9184 });
9185 });
9186 }
9187
9188 #[gpui::test]
9189 async fn test_scroll_to_most_recent_user_prompt(cx: &mut TestAppContext) {
9190 init_test(cx);
9191
9192 let connection = StubAgentConnection::new();
9193
9194 // Each user prompt will result in a user message entry plus an agent message entry.
9195 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
9196 acp::ContentChunk::new("Response 1".into()),
9197 )]);
9198
9199 let (thread_view, cx) =
9200 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
9201
9202 let thread = thread_view
9203 .read_with(cx, |view, _| view.thread().cloned())
9204 .unwrap();
9205
9206 thread
9207 .update(cx, |thread, cx| thread.send_raw("Prompt 1", cx))
9208 .await
9209 .unwrap();
9210 cx.run_until_parked();
9211
9212 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
9213 acp::ContentChunk::new("Response 2".into()),
9214 )]);
9215
9216 thread
9217 .update(cx, |thread, cx| thread.send_raw("Prompt 2", cx))
9218 .await
9219 .unwrap();
9220 cx.run_until_parked();
9221
9222 // Move somewhere else first so we're not trivially already on the last user prompt.
9223 thread_view.update(cx, |view, cx| {
9224 view.scroll_to_top(cx);
9225 });
9226 cx.run_until_parked();
9227
9228 thread_view.update(cx, |view, cx| {
9229 view.scroll_to_most_recent_user_prompt(cx);
9230 let scroll_top = view.list_state.logical_scroll_top();
9231 // Entries layout is: [User1, Assistant1, User2, Assistant2]
9232 assert_eq!(scroll_top.item_ix, 2);
9233 });
9234 }
9235
9236 #[gpui::test]
9237 async fn test_scroll_to_most_recent_user_prompt_falls_back_to_bottom_without_user_messages(
9238 cx: &mut TestAppContext,
9239 ) {
9240 init_test(cx);
9241
9242 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
9243
9244 // With no entries, scrolling should be a no-op and must not panic.
9245 thread_view.update(cx, |view, cx| {
9246 view.scroll_to_most_recent_user_prompt(cx);
9247 let scroll_top = view.list_state.logical_scroll_top();
9248 assert_eq!(scroll_top.item_ix, 0);
9249 });
9250 }
9251
9252 #[gpui::test]
9253 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
9254 init_test(cx);
9255
9256 let connection = StubAgentConnection::new();
9257
9258 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
9259 acp::ContentChunk::new("Response".into()),
9260 )]);
9261
9262 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
9263 add_to_workspace(thread_view.clone(), cx);
9264
9265 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9266 message_editor.update_in(cx, |editor, window, cx| {
9267 editor.set_text("Original message to edit", window, cx);
9268 });
9269 thread_view.update_in(cx, |thread_view, window, cx| {
9270 thread_view.send(window, cx);
9271 });
9272
9273 cx.run_until_parked();
9274
9275 let user_message_editor = thread_view.read_with(cx, |view, cx| {
9276 assert_eq!(view.editing_message, None);
9277
9278 view.entry_view_state
9279 .read(cx)
9280 .entry(0)
9281 .unwrap()
9282 .message_editor()
9283 .unwrap()
9284 .clone()
9285 });
9286
9287 // Focus
9288 cx.focus(&user_message_editor);
9289 thread_view.read_with(cx, |view, _cx| {
9290 assert_eq!(view.editing_message, Some(0));
9291 });
9292
9293 // Edit
9294 user_message_editor.update_in(cx, |editor, window, cx| {
9295 editor.set_text("Edited message content", window, cx);
9296 });
9297
9298 // Cancel
9299 user_message_editor.update_in(cx, |_editor, window, cx| {
9300 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
9301 });
9302
9303 thread_view.read_with(cx, |view, _cx| {
9304 assert_eq!(view.editing_message, None);
9305 });
9306
9307 user_message_editor.read_with(cx, |editor, cx| {
9308 assert_eq!(editor.text(cx), "Original message to edit");
9309 });
9310 }
9311
9312 #[gpui::test]
9313 async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
9314 init_test(cx);
9315
9316 let connection = StubAgentConnection::new();
9317
9318 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
9319 add_to_workspace(thread_view.clone(), cx);
9320
9321 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9322 let mut events = cx.events(&message_editor);
9323 message_editor.update_in(cx, |editor, window, cx| {
9324 editor.set_text("", window, cx);
9325 });
9326
9327 message_editor.update_in(cx, |_editor, window, cx| {
9328 window.dispatch_action(Box::new(Chat), cx);
9329 });
9330 cx.run_until_parked();
9331 // We shouldn't have received any messages
9332 assert!(matches!(
9333 events.try_next(),
9334 Err(futures::channel::mpsc::TryRecvError { .. })
9335 ));
9336 }
9337
9338 #[gpui::test]
9339 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
9340 init_test(cx);
9341
9342 let connection = StubAgentConnection::new();
9343
9344 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
9345 acp::ContentChunk::new("Response".into()),
9346 )]);
9347
9348 let (thread_view, cx) =
9349 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
9350 add_to_workspace(thread_view.clone(), cx);
9351
9352 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9353 message_editor.update_in(cx, |editor, window, cx| {
9354 editor.set_text("Original message to edit", window, cx);
9355 });
9356 thread_view.update_in(cx, |thread_view, window, cx| {
9357 thread_view.send(window, cx);
9358 });
9359
9360 cx.run_until_parked();
9361
9362 let user_message_editor = thread_view.read_with(cx, |view, cx| {
9363 assert_eq!(view.editing_message, None);
9364 assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
9365
9366 view.entry_view_state
9367 .read(cx)
9368 .entry(0)
9369 .unwrap()
9370 .message_editor()
9371 .unwrap()
9372 .clone()
9373 });
9374
9375 // Focus
9376 cx.focus(&user_message_editor);
9377
9378 // Edit
9379 user_message_editor.update_in(cx, |editor, window, cx| {
9380 editor.set_text("Edited message content", window, cx);
9381 });
9382
9383 // Send
9384 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
9385 acp::ContentChunk::new("New Response".into()),
9386 )]);
9387
9388 user_message_editor.update_in(cx, |_editor, window, cx| {
9389 window.dispatch_action(Box::new(Chat), cx);
9390 });
9391
9392 cx.run_until_parked();
9393
9394 thread_view.read_with(cx, |view, cx| {
9395 assert_eq!(view.editing_message, None);
9396
9397 let entries = view.thread().unwrap().read(cx).entries();
9398 assert_eq!(entries.len(), 2);
9399 assert_eq!(
9400 entries[0].to_markdown(cx),
9401 "## User\n\nEdited message content\n\n"
9402 );
9403 assert_eq!(
9404 entries[1].to_markdown(cx),
9405 "## Assistant\n\nNew Response\n\n"
9406 );
9407
9408 let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
9409 assert!(!state.entry(1).unwrap().has_content());
9410 state.entry(0).unwrap().message_editor().unwrap().clone()
9411 });
9412
9413 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
9414 })
9415 }
9416
9417 #[gpui::test]
9418 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
9419 init_test(cx);
9420
9421 let connection = StubAgentConnection::new();
9422
9423 let (thread_view, cx) =
9424 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
9425 add_to_workspace(thread_view.clone(), cx);
9426
9427 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9428 message_editor.update_in(cx, |editor, window, cx| {
9429 editor.set_text("Original message to edit", window, cx);
9430 });
9431 thread_view.update_in(cx, |thread_view, window, cx| {
9432 thread_view.send(window, cx);
9433 });
9434
9435 cx.run_until_parked();
9436
9437 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
9438 let thread = view.thread().unwrap().read(cx);
9439 assert_eq!(thread.entries().len(), 1);
9440
9441 let editor = view
9442 .entry_view_state
9443 .read(cx)
9444 .entry(0)
9445 .unwrap()
9446 .message_editor()
9447 .unwrap()
9448 .clone();
9449
9450 (editor, thread.session_id().clone())
9451 });
9452
9453 // Focus
9454 cx.focus(&user_message_editor);
9455
9456 thread_view.read_with(cx, |view, _cx| {
9457 assert_eq!(view.editing_message, Some(0));
9458 });
9459
9460 // Edit
9461 user_message_editor.update_in(cx, |editor, window, cx| {
9462 editor.set_text("Edited message content", window, cx);
9463 });
9464
9465 thread_view.read_with(cx, |view, _cx| {
9466 assert_eq!(view.editing_message, Some(0));
9467 });
9468
9469 // Finish streaming response
9470 cx.update(|_, cx| {
9471 connection.send_update(
9472 session_id.clone(),
9473 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("Response".into())),
9474 cx,
9475 );
9476 connection.end_turn(session_id, acp::StopReason::EndTurn);
9477 });
9478
9479 thread_view.read_with(cx, |view, _cx| {
9480 assert_eq!(view.editing_message, Some(0));
9481 });
9482
9483 cx.run_until_parked();
9484
9485 // Should still be editing
9486 cx.update(|window, cx| {
9487 assert!(user_message_editor.focus_handle(cx).is_focused(window));
9488 assert_eq!(thread_view.read(cx).editing_message, Some(0));
9489 assert_eq!(
9490 user_message_editor.read(cx).text(cx),
9491 "Edited message content"
9492 );
9493 });
9494 }
9495
9496 struct GeneratingThreadSetup {
9497 thread_view: Entity<AcpThreadView>,
9498 thread: Entity<AcpThread>,
9499 message_editor: Entity<MessageEditor>,
9500 }
9501
9502 async fn setup_generating_thread(
9503 cx: &mut TestAppContext,
9504 ) -> (GeneratingThreadSetup, &mut VisualTestContext) {
9505 let connection = StubAgentConnection::new();
9506
9507 let (thread_view, cx) =
9508 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
9509 add_to_workspace(thread_view.clone(), cx);
9510
9511 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9512 message_editor.update_in(cx, |editor, window, cx| {
9513 editor.set_text("Hello", window, cx);
9514 });
9515 thread_view.update_in(cx, |thread_view, window, cx| {
9516 thread_view.send(window, cx);
9517 });
9518
9519 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
9520 let thread = view.thread().unwrap();
9521 (thread.clone(), thread.read(cx).session_id().clone())
9522 });
9523
9524 cx.run_until_parked();
9525
9526 cx.update(|_, cx| {
9527 connection.send_update(
9528 session_id.clone(),
9529 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
9530 "Response chunk".into(),
9531 )),
9532 cx,
9533 );
9534 });
9535
9536 cx.run_until_parked();
9537
9538 thread.read_with(cx, |thread, _cx| {
9539 assert_eq!(thread.status(), ThreadStatus::Generating);
9540 });
9541
9542 (
9543 GeneratingThreadSetup {
9544 thread_view,
9545 thread,
9546 message_editor,
9547 },
9548 cx,
9549 )
9550 }
9551
9552 #[gpui::test]
9553 async fn test_escape_cancels_generation_from_conversation_focus(cx: &mut TestAppContext) {
9554 init_test(cx);
9555
9556 let (setup, cx) = setup_generating_thread(cx).await;
9557
9558 let focus_handle = setup
9559 .thread_view
9560 .read_with(cx, |view, _cx| view.focus_handle.clone());
9561 cx.update(|window, cx| {
9562 window.focus(&focus_handle, cx);
9563 });
9564
9565 setup.thread_view.update_in(cx, |_, window, cx| {
9566 window.dispatch_action(menu::Cancel.boxed_clone(), cx);
9567 });
9568
9569 cx.run_until_parked();
9570
9571 setup.thread.read_with(cx, |thread, _cx| {
9572 assert_eq!(thread.status(), ThreadStatus::Idle);
9573 });
9574 }
9575
9576 #[gpui::test]
9577 async fn test_escape_cancels_generation_from_editor_focus(cx: &mut TestAppContext) {
9578 init_test(cx);
9579
9580 let (setup, cx) = setup_generating_thread(cx).await;
9581
9582 let editor_focus_handle = setup
9583 .message_editor
9584 .read_with(cx, |editor, cx| editor.focus_handle(cx));
9585 cx.update(|window, cx| {
9586 window.focus(&editor_focus_handle, cx);
9587 });
9588
9589 setup.message_editor.update_in(cx, |_, window, cx| {
9590 window.dispatch_action(editor::actions::Cancel.boxed_clone(), cx);
9591 });
9592
9593 cx.run_until_parked();
9594
9595 setup.thread.read_with(cx, |thread, _cx| {
9596 assert_eq!(thread.status(), ThreadStatus::Idle);
9597 });
9598 }
9599
9600 #[gpui::test]
9601 async fn test_escape_when_idle_is_noop(cx: &mut TestAppContext) {
9602 init_test(cx);
9603
9604 let (thread_view, cx) =
9605 setup_thread_view(StubAgentServer::new(StubAgentConnection::new()), cx).await;
9606 add_to_workspace(thread_view.clone(), cx);
9607
9608 let thread = thread_view.read_with(cx, |view, _cx| view.thread().unwrap().clone());
9609
9610 thread.read_with(cx, |thread, _cx| {
9611 assert_eq!(thread.status(), ThreadStatus::Idle);
9612 });
9613
9614 let focus_handle = thread_view.read_with(cx, |view, _cx| view.focus_handle.clone());
9615 cx.update(|window, cx| {
9616 window.focus(&focus_handle, cx);
9617 });
9618
9619 thread_view.update_in(cx, |_, window, cx| {
9620 window.dispatch_action(menu::Cancel.boxed_clone(), cx);
9621 });
9622
9623 cx.run_until_parked();
9624
9625 thread.read_with(cx, |thread, _cx| {
9626 assert_eq!(thread.status(), ThreadStatus::Idle);
9627 });
9628 }
9629
9630 #[gpui::test]
9631 async fn test_interrupt(cx: &mut TestAppContext) {
9632 init_test(cx);
9633
9634 let connection = StubAgentConnection::new();
9635
9636 let (thread_view, cx) =
9637 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
9638 add_to_workspace(thread_view.clone(), cx);
9639
9640 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9641 message_editor.update_in(cx, |editor, window, cx| {
9642 editor.set_text("Message 1", window, cx);
9643 });
9644 thread_view.update_in(cx, |thread_view, window, cx| {
9645 thread_view.send(window, cx);
9646 });
9647
9648 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
9649 let thread = view.thread().unwrap();
9650
9651 (thread.clone(), thread.read(cx).session_id().clone())
9652 });
9653
9654 cx.run_until_parked();
9655
9656 cx.update(|_, cx| {
9657 connection.send_update(
9658 session_id.clone(),
9659 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
9660 "Message 1 resp".into(),
9661 )),
9662 cx,
9663 );
9664 });
9665
9666 cx.run_until_parked();
9667
9668 thread.read_with(cx, |thread, cx| {
9669 assert_eq!(
9670 thread.to_markdown(cx),
9671 indoc::indoc! {"
9672 ## User
9673
9674 Message 1
9675
9676 ## Assistant
9677
9678 Message 1 resp
9679
9680 "}
9681 )
9682 });
9683
9684 message_editor.update_in(cx, |editor, window, cx| {
9685 editor.set_text("Message 2", window, cx);
9686 });
9687 thread_view.update_in(cx, |thread_view, window, cx| {
9688 thread_view.interrupt_and_send(window, cx);
9689 });
9690
9691 cx.update(|_, cx| {
9692 // Simulate a response sent after beginning to cancel
9693 connection.send_update(
9694 session_id.clone(),
9695 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("onse".into())),
9696 cx,
9697 );
9698 });
9699
9700 cx.run_until_parked();
9701
9702 // Last Message 1 response should appear before Message 2
9703 thread.read_with(cx, |thread, cx| {
9704 assert_eq!(
9705 thread.to_markdown(cx),
9706 indoc::indoc! {"
9707 ## User
9708
9709 Message 1
9710
9711 ## Assistant
9712
9713 Message 1 response
9714
9715 ## User
9716
9717 Message 2
9718
9719 "}
9720 )
9721 });
9722
9723 cx.update(|_, cx| {
9724 connection.send_update(
9725 session_id.clone(),
9726 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
9727 "Message 2 response".into(),
9728 )),
9729 cx,
9730 );
9731 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
9732 });
9733
9734 cx.run_until_parked();
9735
9736 thread.read_with(cx, |thread, cx| {
9737 assert_eq!(
9738 thread.to_markdown(cx),
9739 indoc::indoc! {"
9740 ## User
9741
9742 Message 1
9743
9744 ## Assistant
9745
9746 Message 1 response
9747
9748 ## User
9749
9750 Message 2
9751
9752 ## Assistant
9753
9754 Message 2 response
9755
9756 "}
9757 )
9758 });
9759 }
9760
9761 #[gpui::test]
9762 async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
9763 init_test(cx);
9764
9765 let connection = StubAgentConnection::new();
9766 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
9767 acp::ContentChunk::new("Response".into()),
9768 )]);
9769
9770 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
9771 add_to_workspace(thread_view.clone(), cx);
9772
9773 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9774 message_editor.update_in(cx, |editor, window, cx| {
9775 editor.set_text("Original message to edit", window, cx)
9776 });
9777 thread_view.update_in(cx, |thread_view, window, cx| thread_view.send(window, cx));
9778 cx.run_until_parked();
9779
9780 let user_message_editor = thread_view.read_with(cx, |thread_view, cx| {
9781 thread_view
9782 .entry_view_state
9783 .read(cx)
9784 .entry(0)
9785 .expect("Should have at least one entry")
9786 .message_editor()
9787 .expect("Should have message editor")
9788 .clone()
9789 });
9790
9791 cx.focus(&user_message_editor);
9792 thread_view.read_with(cx, |thread_view, _cx| {
9793 assert_eq!(thread_view.editing_message, Some(0));
9794 });
9795
9796 // Ensure to edit the focused message before proceeding otherwise, since
9797 // its content is not different from what was sent, focus will be lost.
9798 user_message_editor.update_in(cx, |editor, window, cx| {
9799 editor.set_text("Original message to edit with ", window, cx)
9800 });
9801
9802 // Create a simple buffer with some text so we can create a selection
9803 // that will then be added to the message being edited.
9804 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
9805 (thread_view.workspace.clone(), thread_view.project.clone())
9806 });
9807 let buffer = project.update(cx, |project, cx| {
9808 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
9809 });
9810
9811 workspace
9812 .update_in(cx, |workspace, window, cx| {
9813 let editor = cx.new(|cx| {
9814 let mut editor =
9815 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
9816
9817 editor.change_selections(Default::default(), window, cx, |selections| {
9818 selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
9819 });
9820
9821 editor
9822 });
9823 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
9824 })
9825 .unwrap();
9826
9827 thread_view.update_in(cx, |thread_view, window, cx| {
9828 assert_eq!(thread_view.editing_message, Some(0));
9829 thread_view.insert_selections(window, cx);
9830 });
9831
9832 user_message_editor.read_with(cx, |editor, cx| {
9833 let text = editor.editor().read(cx).text(cx);
9834 let expected_text = String::from("Original message to edit with selection ");
9835
9836 assert_eq!(text, expected_text);
9837 });
9838 }
9839
9840 #[gpui::test]
9841 async fn test_insert_selections(cx: &mut TestAppContext) {
9842 init_test(cx);
9843
9844 let connection = StubAgentConnection::new();
9845 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
9846 acp::ContentChunk::new("Response".into()),
9847 )]);
9848
9849 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
9850 add_to_workspace(thread_view.clone(), cx);
9851
9852 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9853 message_editor.update_in(cx, |editor, window, cx| {
9854 editor.set_text("Can you review this snippet ", window, cx)
9855 });
9856
9857 // Create a simple buffer with some text so we can create a selection
9858 // that will then be added to the message being edited.
9859 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
9860 (thread_view.workspace.clone(), thread_view.project.clone())
9861 });
9862 let buffer = project.update(cx, |project, cx| {
9863 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
9864 });
9865
9866 workspace
9867 .update_in(cx, |workspace, window, cx| {
9868 let editor = cx.new(|cx| {
9869 let mut editor =
9870 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
9871
9872 editor.change_selections(Default::default(), window, cx, |selections| {
9873 selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
9874 });
9875
9876 editor
9877 });
9878 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
9879 })
9880 .unwrap();
9881
9882 thread_view.update_in(cx, |thread_view, window, cx| {
9883 assert_eq!(thread_view.editing_message, None);
9884 thread_view.insert_selections(window, cx);
9885 });
9886
9887 thread_view.read_with(cx, |thread_view, cx| {
9888 let text = thread_view.message_editor.read(cx).text(cx);
9889 let expected_txt = String::from("Can you review this snippet selection ");
9890
9891 assert_eq!(text, expected_txt);
9892 })
9893 }
9894
9895 #[gpui::test]
9896 async fn test_tool_permission_buttons_terminal_with_pattern(cx: &mut TestAppContext) {
9897 init_test(cx);
9898
9899 let tool_call_id = acp::ToolCallId::new("terminal-1");
9900 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build --release`")
9901 .kind(acp::ToolKind::Edit);
9902
9903 let permission_options = ToolPermissionContext::new("terminal", "cargo build --release")
9904 .build_permission_options();
9905
9906 let connection =
9907 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
9908 tool_call_id.clone(),
9909 permission_options,
9910 )]));
9911
9912 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
9913
9914 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
9915
9916 // Disable notifications to avoid popup windows
9917 cx.update(|_window, cx| {
9918 AgentSettings::override_global(
9919 AgentSettings {
9920 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
9921 ..AgentSettings::get_global(cx).clone()
9922 },
9923 cx,
9924 );
9925 });
9926
9927 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
9928 message_editor.update_in(cx, |editor, window, cx| {
9929 editor.set_text("Run cargo build", window, cx);
9930 });
9931
9932 thread_view.update_in(cx, |thread_view, window, cx| {
9933 thread_view.send(window, cx);
9934 });
9935
9936 cx.run_until_parked();
9937
9938 // Verify the tool call is in WaitingForConfirmation state with the expected options
9939 thread_view.read_with(cx, |thread_view, cx| {
9940 let thread = thread_view.thread().expect("Thread should exist");
9941 let thread = thread.read(cx);
9942
9943 let tool_call = thread.entries().iter().find_map(|entry| {
9944 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
9945 Some(call)
9946 } else {
9947 None
9948 }
9949 });
9950
9951 assert!(tool_call.is_some(), "Expected a tool call entry");
9952 let tool_call = tool_call.unwrap();
9953
9954 // Verify it's waiting for confirmation
9955 assert!(
9956 matches!(
9957 tool_call.status,
9958 acp_thread::ToolCallStatus::WaitingForConfirmation { .. }
9959 ),
9960 "Expected WaitingForConfirmation status, got {:?}",
9961 tool_call.status
9962 );
9963
9964 // Verify the options count (granularity options only, no separate Deny option)
9965 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
9966 &tool_call.status
9967 {
9968 assert_eq!(
9969 options.len(),
9970 3,
9971 "Expected 3 permission options (granularity only)"
9972 );
9973
9974 // Verify specific button labels (now using neutral names)
9975 let labels: Vec<&str> = options.iter().map(|o| o.name.as_ref()).collect();
9976 assert!(
9977 labels.contains(&"Always for terminal"),
9978 "Missing 'Always for terminal' option"
9979 );
9980 assert!(
9981 labels.contains(&"Always for `cargo` commands"),
9982 "Missing pattern option"
9983 );
9984 assert!(
9985 labels.contains(&"Only this time"),
9986 "Missing 'Only this time' option"
9987 );
9988 }
9989 });
9990 }
9991
9992 #[gpui::test]
9993 async fn test_tool_permission_buttons_edit_file_with_path_pattern(cx: &mut TestAppContext) {
9994 init_test(cx);
9995
9996 let tool_call_id = acp::ToolCallId::new("edit-file-1");
9997 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Edit `src/main.rs`")
9998 .kind(acp::ToolKind::Edit);
9999
10000 let permission_options =
10001 ToolPermissionContext::new("edit_file", "src/main.rs").build_permission_options();
10002
10003 let connection =
10004 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10005 tool_call_id.clone(),
10006 permission_options,
10007 )]));
10008
10009 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10010
10011 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10012
10013 // Disable notifications
10014 cx.update(|_window, cx| {
10015 AgentSettings::override_global(
10016 AgentSettings {
10017 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10018 ..AgentSettings::get_global(cx).clone()
10019 },
10020 cx,
10021 );
10022 });
10023
10024 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10025 message_editor.update_in(cx, |editor, window, cx| {
10026 editor.set_text("Edit the main file", window, cx);
10027 });
10028
10029 thread_view.update_in(cx, |thread_view, window, cx| {
10030 thread_view.send(window, cx);
10031 });
10032
10033 cx.run_until_parked();
10034
10035 // Verify the options
10036 thread_view.read_with(cx, |thread_view, cx| {
10037 let thread = thread_view.thread().expect("Thread should exist");
10038 let thread = thread.read(cx);
10039
10040 let tool_call = thread.entries().iter().find_map(|entry| {
10041 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
10042 Some(call)
10043 } else {
10044 None
10045 }
10046 });
10047
10048 assert!(tool_call.is_some(), "Expected a tool call entry");
10049 let tool_call = tool_call.unwrap();
10050
10051 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
10052 &tool_call.status
10053 {
10054 let labels: Vec<&str> = options.iter().map(|o| o.name.as_ref()).collect();
10055 assert!(
10056 labels.contains(&"Always for edit file"),
10057 "Missing 'Always for edit file' option"
10058 );
10059 assert!(
10060 labels.contains(&"Always for `src/`"),
10061 "Missing path pattern option"
10062 );
10063 } else {
10064 panic!("Expected WaitingForConfirmation status");
10065 }
10066 });
10067 }
10068
10069 #[gpui::test]
10070 async fn test_tool_permission_buttons_fetch_with_domain_pattern(cx: &mut TestAppContext) {
10071 init_test(cx);
10072
10073 let tool_call_id = acp::ToolCallId::new("fetch-1");
10074 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Fetch `https://docs.rs/gpui`")
10075 .kind(acp::ToolKind::Fetch);
10076
10077 let permission_options =
10078 ToolPermissionContext::new("fetch", "https://docs.rs/gpui").build_permission_options();
10079
10080 let connection =
10081 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10082 tool_call_id.clone(),
10083 permission_options,
10084 )]));
10085
10086 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10087
10088 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10089
10090 // Disable notifications
10091 cx.update(|_window, cx| {
10092 AgentSettings::override_global(
10093 AgentSettings {
10094 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10095 ..AgentSettings::get_global(cx).clone()
10096 },
10097 cx,
10098 );
10099 });
10100
10101 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10102 message_editor.update_in(cx, |editor, window, cx| {
10103 editor.set_text("Fetch the docs", window, cx);
10104 });
10105
10106 thread_view.update_in(cx, |thread_view, window, cx| {
10107 thread_view.send(window, cx);
10108 });
10109
10110 cx.run_until_parked();
10111
10112 // Verify the options
10113 thread_view.read_with(cx, |thread_view, cx| {
10114 let thread = thread_view.thread().expect("Thread should exist");
10115 let thread = thread.read(cx);
10116
10117 let tool_call = thread.entries().iter().find_map(|entry| {
10118 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
10119 Some(call)
10120 } else {
10121 None
10122 }
10123 });
10124
10125 assert!(tool_call.is_some(), "Expected a tool call entry");
10126 let tool_call = tool_call.unwrap();
10127
10128 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
10129 &tool_call.status
10130 {
10131 let labels: Vec<&str> = options.iter().map(|o| o.name.as_ref()).collect();
10132 assert!(
10133 labels.contains(&"Always for fetch"),
10134 "Missing 'Always for fetch' option"
10135 );
10136 assert!(
10137 labels.contains(&"Always for `docs.rs`"),
10138 "Missing domain pattern option"
10139 );
10140 } else {
10141 panic!("Expected WaitingForConfirmation status");
10142 }
10143 });
10144 }
10145
10146 #[gpui::test]
10147 async fn test_tool_permission_buttons_without_pattern(cx: &mut TestAppContext) {
10148 init_test(cx);
10149
10150 let tool_call_id = acp::ToolCallId::new("terminal-no-pattern-1");
10151 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `./deploy.sh --production`")
10152 .kind(acp::ToolKind::Edit);
10153
10154 // No pattern button since ./deploy.sh doesn't match the alphanumeric pattern
10155 let permission_options = ToolPermissionContext::new("terminal", "./deploy.sh --production")
10156 .build_permission_options();
10157
10158 let connection =
10159 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10160 tool_call_id.clone(),
10161 permission_options,
10162 )]));
10163
10164 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10165
10166 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10167
10168 // Disable notifications
10169 cx.update(|_window, cx| {
10170 AgentSettings::override_global(
10171 AgentSettings {
10172 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10173 ..AgentSettings::get_global(cx).clone()
10174 },
10175 cx,
10176 );
10177 });
10178
10179 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10180 message_editor.update_in(cx, |editor, window, cx| {
10181 editor.set_text("Run the deploy script", window, cx);
10182 });
10183
10184 thread_view.update_in(cx, |thread_view, window, cx| {
10185 thread_view.send(window, cx);
10186 });
10187
10188 cx.run_until_parked();
10189
10190 // Verify only 2 options (no pattern button when command doesn't match pattern)
10191 thread_view.read_with(cx, |thread_view, cx| {
10192 let thread = thread_view.thread().expect("Thread should exist");
10193 let thread = thread.read(cx);
10194
10195 let tool_call = thread.entries().iter().find_map(|entry| {
10196 if let acp_thread::AgentThreadEntry::ToolCall(call) = entry {
10197 Some(call)
10198 } else {
10199 None
10200 }
10201 });
10202
10203 assert!(tool_call.is_some(), "Expected a tool call entry");
10204 let tool_call = tool_call.unwrap();
10205
10206 if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =
10207 &tool_call.status
10208 {
10209 assert_eq!(
10210 options.len(),
10211 2,
10212 "Expected 2 permission options (no pattern option)"
10213 );
10214
10215 let labels: Vec<&str> = options.iter().map(|o| o.name.as_ref()).collect();
10216 assert!(
10217 labels.contains(&"Always for terminal"),
10218 "Missing 'Always for terminal' option"
10219 );
10220 assert!(
10221 labels.contains(&"Only this time"),
10222 "Missing 'Only this time' option"
10223 );
10224 // Should NOT contain a pattern option
10225 assert!(
10226 !labels.iter().any(|l| l.contains("commands")),
10227 "Should not have pattern option"
10228 );
10229 } else {
10230 panic!("Expected WaitingForConfirmation status");
10231 }
10232 });
10233 }
10234
10235 #[gpui::test]
10236 async fn test_authorize_tool_call_action_triggers_authorization(cx: &mut TestAppContext) {
10237 init_test(cx);
10238
10239 let tool_call_id = acp::ToolCallId::new("action-test-1");
10240 let tool_call =
10241 acp::ToolCall::new(tool_call_id.clone(), "Run `cargo test`").kind(acp::ToolKind::Edit);
10242
10243 let permission_options =
10244 ToolPermissionContext::new("terminal", "cargo test").build_permission_options();
10245
10246 let connection =
10247 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10248 tool_call_id.clone(),
10249 permission_options,
10250 )]));
10251
10252 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10253
10254 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10255 add_to_workspace(thread_view.clone(), cx);
10256
10257 cx.update(|_window, cx| {
10258 AgentSettings::override_global(
10259 AgentSettings {
10260 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10261 ..AgentSettings::get_global(cx).clone()
10262 },
10263 cx,
10264 );
10265 });
10266
10267 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10268 message_editor.update_in(cx, |editor, window, cx| {
10269 editor.set_text("Run tests", window, cx);
10270 });
10271
10272 thread_view.update_in(cx, |thread_view, window, cx| {
10273 thread_view.send(window, cx);
10274 });
10275
10276 cx.run_until_parked();
10277
10278 // Verify tool call is waiting for confirmation
10279 thread_view.read_with(cx, |thread_view, cx| {
10280 let thread = thread_view.thread().expect("Thread should exist");
10281 let thread = thread.read(cx);
10282 let tool_call = thread.first_tool_awaiting_confirmation();
10283 assert!(
10284 tool_call.is_some(),
10285 "Expected a tool call waiting for confirmation"
10286 );
10287 });
10288
10289 // Dispatch the AuthorizeToolCall action (simulating dropdown menu selection)
10290 thread_view.update_in(cx, |_, window, cx| {
10291 window.dispatch_action(
10292 crate::AuthorizeToolCall {
10293 tool_call_id: "action-test-1".to_string(),
10294 option_id: "allow".to_string(),
10295 option_kind: "AllowOnce".to_string(),
10296 }
10297 .boxed_clone(),
10298 cx,
10299 );
10300 });
10301
10302 cx.run_until_parked();
10303
10304 // Verify tool call is no longer waiting for confirmation (was authorized)
10305 thread_view.read_with(cx, |thread_view, cx| {
10306 let thread = thread_view.thread().expect("Thread should exist");
10307 let thread = thread.read(cx);
10308 let tool_call = thread.first_tool_awaiting_confirmation();
10309 assert!(
10310 tool_call.is_none(),
10311 "Tool call should no longer be waiting for confirmation after AuthorizeToolCall action"
10312 );
10313 });
10314 }
10315
10316 #[gpui::test]
10317 async fn test_authorize_tool_call_action_with_pattern_option(cx: &mut TestAppContext) {
10318 init_test(cx);
10319
10320 let tool_call_id = acp::ToolCallId::new("pattern-action-test-1");
10321 let tool_call =
10322 acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
10323
10324 let permission_options =
10325 ToolPermissionContext::new("terminal", "npm install").build_permission_options();
10326
10327 let connection =
10328 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10329 tool_call_id.clone(),
10330 permission_options.clone(),
10331 )]));
10332
10333 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10334
10335 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10336 add_to_workspace(thread_view.clone(), cx);
10337
10338 cx.update(|_window, cx| {
10339 AgentSettings::override_global(
10340 AgentSettings {
10341 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10342 ..AgentSettings::get_global(cx).clone()
10343 },
10344 cx,
10345 );
10346 });
10347
10348 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10349 message_editor.update_in(cx, |editor, window, cx| {
10350 editor.set_text("Install dependencies", window, cx);
10351 });
10352
10353 thread_view.update_in(cx, |thread_view, window, cx| {
10354 thread_view.send(window, cx);
10355 });
10356
10357 cx.run_until_parked();
10358
10359 // Find the pattern option ID
10360 let pattern_option = permission_options
10361 .iter()
10362 .find(|o| o.option_id.0.starts_with("always_pattern:"))
10363 .expect("Should have a pattern option for npm command");
10364
10365 // Dispatch action with the pattern option (simulating "Always allow `npm` commands")
10366 thread_view.update_in(cx, |_, window, cx| {
10367 window.dispatch_action(
10368 crate::AuthorizeToolCall {
10369 tool_call_id: "pattern-action-test-1".to_string(),
10370 option_id: pattern_option.option_id.0.to_string(),
10371 option_kind: "AllowAlways".to_string(),
10372 }
10373 .boxed_clone(),
10374 cx,
10375 );
10376 });
10377
10378 cx.run_until_parked();
10379
10380 // Verify tool call was authorized
10381 thread_view.read_with(cx, |thread_view, cx| {
10382 let thread = thread_view.thread().expect("Thread should exist");
10383 let thread = thread.read(cx);
10384 let tool_call = thread.first_tool_awaiting_confirmation();
10385 assert!(
10386 tool_call.is_none(),
10387 "Tool call should be authorized after selecting pattern option"
10388 );
10389 });
10390 }
10391
10392 #[gpui::test]
10393 async fn test_granularity_selection_updates_state(cx: &mut TestAppContext) {
10394 init_test(cx);
10395
10396 let tool_call_id = acp::ToolCallId::new("granularity-test-1");
10397 let tool_call =
10398 acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build`").kind(acp::ToolKind::Edit);
10399
10400 let permission_options =
10401 ToolPermissionContext::new("terminal", "cargo build").build_permission_options();
10402
10403 let connection =
10404 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10405 tool_call_id.clone(),
10406 permission_options.clone(),
10407 )]));
10408
10409 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10410
10411 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10412 add_to_workspace(thread_view.clone(), cx);
10413
10414 cx.update(|_window, cx| {
10415 AgentSettings::override_global(
10416 AgentSettings {
10417 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10418 ..AgentSettings::get_global(cx).clone()
10419 },
10420 cx,
10421 );
10422 });
10423
10424 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10425 message_editor.update_in(cx, |editor, window, cx| {
10426 editor.set_text("Build the project", window, cx);
10427 });
10428
10429 thread_view.update_in(cx, |thread_view, window, cx| {
10430 thread_view.send(window, cx);
10431 });
10432
10433 cx.run_until_parked();
10434
10435 // Verify default granularity is the last option (index 2 = "Only this time")
10436 thread_view.read_with(cx, |thread_view, _cx| {
10437 let selected = thread_view
10438 .selected_permission_granularity
10439 .get(&tool_call_id);
10440 assert!(
10441 selected.is_none(),
10442 "Should have no selection initially (defaults to last)"
10443 );
10444 });
10445
10446 // Select the first option (index 0 = "Always for terminal")
10447 thread_view.update_in(cx, |_, window, cx| {
10448 window.dispatch_action(
10449 crate::SelectPermissionGranularity {
10450 tool_call_id: "granularity-test-1".to_string(),
10451 index: 0,
10452 }
10453 .boxed_clone(),
10454 cx,
10455 );
10456 });
10457
10458 cx.run_until_parked();
10459
10460 // Verify the selection was updated
10461 thread_view.read_with(cx, |thread_view, _cx| {
10462 let selected = thread_view
10463 .selected_permission_granularity
10464 .get(&tool_call_id);
10465 assert_eq!(selected, Some(&0), "Should have selected index 0");
10466 });
10467 }
10468
10469 #[gpui::test]
10470 async fn test_allow_button_uses_selected_granularity(cx: &mut TestAppContext) {
10471 init_test(cx);
10472
10473 let tool_call_id = acp::ToolCallId::new("allow-granularity-test-1");
10474 let tool_call =
10475 acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
10476
10477 let permission_options =
10478 ToolPermissionContext::new("terminal", "npm install").build_permission_options();
10479
10480 // Verify we have the expected options
10481 assert_eq!(permission_options.len(), 3);
10482 assert!(
10483 permission_options[0]
10484 .option_id
10485 .0
10486 .contains("always:terminal")
10487 );
10488 assert!(
10489 permission_options[1]
10490 .option_id
10491 .0
10492 .contains("always_pattern:terminal")
10493 );
10494 assert_eq!(permission_options[2].option_id.0.as_ref(), "once");
10495
10496 let connection =
10497 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10498 tool_call_id.clone(),
10499 permission_options.clone(),
10500 )]));
10501
10502 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10503
10504 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10505 add_to_workspace(thread_view.clone(), cx);
10506
10507 cx.update(|_window, cx| {
10508 AgentSettings::override_global(
10509 AgentSettings {
10510 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10511 ..AgentSettings::get_global(cx).clone()
10512 },
10513 cx,
10514 );
10515 });
10516
10517 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10518 message_editor.update_in(cx, |editor, window, cx| {
10519 editor.set_text("Install dependencies", window, cx);
10520 });
10521
10522 thread_view.update_in(cx, |thread_view, window, cx| {
10523 thread_view.send(window, cx);
10524 });
10525
10526 cx.run_until_parked();
10527
10528 // Select the pattern option (index 1 = "Always for `npm` commands")
10529 thread_view.update_in(cx, |_, window, cx| {
10530 window.dispatch_action(
10531 crate::SelectPermissionGranularity {
10532 tool_call_id: "allow-granularity-test-1".to_string(),
10533 index: 1,
10534 }
10535 .boxed_clone(),
10536 cx,
10537 );
10538 });
10539
10540 cx.run_until_parked();
10541
10542 // Simulate clicking the Allow button by dispatching AllowOnce action
10543 // which should use the selected granularity
10544 thread_view.update_in(cx, |thread_view, window, cx| {
10545 thread_view.allow_once(&AllowOnce, window, cx);
10546 });
10547
10548 cx.run_until_parked();
10549
10550 // Verify tool call was authorized
10551 thread_view.read_with(cx, |thread_view, cx| {
10552 let thread = thread_view.thread().expect("Thread should exist");
10553 let thread = thread.read(cx);
10554 let tool_call = thread.first_tool_awaiting_confirmation();
10555 assert!(
10556 tool_call.is_none(),
10557 "Tool call should be authorized after Allow with pattern granularity"
10558 );
10559 });
10560 }
10561
10562 #[gpui::test]
10563 async fn test_deny_button_uses_selected_granularity(cx: &mut TestAppContext) {
10564 init_test(cx);
10565
10566 let tool_call_id = acp::ToolCallId::new("deny-granularity-test-1");
10567 let tool_call =
10568 acp::ToolCall::new(tool_call_id.clone(), "Run `git push`").kind(acp::ToolKind::Edit);
10569
10570 let permission_options =
10571 ToolPermissionContext::new("terminal", "git push").build_permission_options();
10572
10573 let connection =
10574 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
10575 tool_call_id.clone(),
10576 permission_options.clone(),
10577 )]));
10578
10579 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
10580
10581 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
10582 add_to_workspace(thread_view.clone(), cx);
10583
10584 cx.update(|_window, cx| {
10585 AgentSettings::override_global(
10586 AgentSettings {
10587 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
10588 ..AgentSettings::get_global(cx).clone()
10589 },
10590 cx,
10591 );
10592 });
10593
10594 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
10595 message_editor.update_in(cx, |editor, window, cx| {
10596 editor.set_text("Push changes", window, cx);
10597 });
10598
10599 thread_view.update_in(cx, |thread_view, window, cx| {
10600 thread_view.send(window, cx);
10601 });
10602
10603 cx.run_until_parked();
10604
10605 // Use default granularity (last option = "Only this time")
10606 // Simulate clicking the Deny button
10607 thread_view.update_in(cx, |thread_view, window, cx| {
10608 thread_view.reject_once(&RejectOnce, window, cx);
10609 });
10610
10611 cx.run_until_parked();
10612
10613 // Verify tool call was rejected (no longer waiting for confirmation)
10614 thread_view.read_with(cx, |thread_view, cx| {
10615 let thread = thread_view.thread().expect("Thread should exist");
10616 let thread = thread.read(cx);
10617 let tool_call = thread.first_tool_awaiting_confirmation();
10618 assert!(
10619 tool_call.is_none(),
10620 "Tool call should be rejected after Deny"
10621 );
10622 });
10623 }
10624
10625 #[gpui::test]
10626 async fn test_option_id_transformation_for_allow() {
10627 // Test the option_id transformation logic directly
10628 // "once" -> "allow"
10629 // "always:terminal" -> "always_allow:terminal"
10630 // "always_pattern:terminal:^cargo\s" -> "always_allow_pattern:terminal:^cargo\s"
10631
10632 let test_cases = vec![
10633 ("once", "allow"),
10634 ("always:terminal", "always_allow:terminal"),
10635 (
10636 "always_pattern:terminal:^cargo\\s",
10637 "always_allow_pattern:terminal:^cargo\\s",
10638 ),
10639 ("always:fetch", "always_allow:fetch"),
10640 (
10641 "always_pattern:fetch:^https?://docs\\.rs",
10642 "always_allow_pattern:fetch:^https?://docs\\.rs",
10643 ),
10644 ];
10645
10646 for (input, expected) in test_cases {
10647 let result = if input == "once" {
10648 "allow".to_string()
10649 } else if let Some(rest) = input.strip_prefix("always:") {
10650 format!("always_allow:{}", rest)
10651 } else if let Some(rest) = input.strip_prefix("always_pattern:") {
10652 format!("always_allow_pattern:{}", rest)
10653 } else {
10654 input.to_string()
10655 };
10656 assert_eq!(result, expected, "Failed for input: {}", input);
10657 }
10658 }
10659
10660 #[gpui::test]
10661 async fn test_option_id_transformation_for_deny() {
10662 // Test the option_id transformation logic for deny
10663 // "once" -> "deny"
10664 // "always:terminal" -> "always_deny:terminal"
10665 // "always_pattern:terminal:^cargo\s" -> "always_deny_pattern:terminal:^cargo\s"
10666
10667 let test_cases = vec![
10668 ("once", "deny"),
10669 ("always:terminal", "always_deny:terminal"),
10670 (
10671 "always_pattern:terminal:^cargo\\s",
10672 "always_deny_pattern:terminal:^cargo\\s",
10673 ),
10674 ("always:fetch", "always_deny:fetch"),
10675 (
10676 "always_pattern:fetch:^https?://docs\\.rs",
10677 "always_deny_pattern:fetch:^https?://docs\\.rs",
10678 ),
10679 ];
10680
10681 for (input, expected) in test_cases {
10682 let result = if input == "once" {
10683 "deny".to_string()
10684 } else if let Some(rest) = input.strip_prefix("always:") {
10685 format!("always_deny:{}", rest)
10686 } else if let Some(rest) = input.strip_prefix("always_pattern:") {
10687 format!("always_deny_pattern:{}", rest)
10688 } else {
10689 input.replace("allow", "deny")
10690 };
10691 assert_eq!(result, expected, "Failed for input: {}", input);
10692 }
10693 }
10694}