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