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