1use crate::{
2 DEFAULT_THREAD_TITLE, SelectPermissionGranularity,
3 agent_configuration::configure_context_server_modal::default_markdown_style,
4};
5use std::cell::RefCell;
6
7use acp_thread::{ContentBlock, PlanEntry};
8use cloud_api_types::{SubmitAgentThreadFeedbackBody, SubmitAgentThreadFeedbackCommentsBody};
9use editor::actions::OpenExcerpts;
10
11use crate::StartThreadIn;
12use crate::message_editor::SharedSessionCapabilities;
13use gpui::{Corner, List};
14use heapless::Vec as ArrayVec;
15use language_model::{LanguageModelEffortLevel, Speed};
16use settings::update_settings_file;
17use ui::{ButtonLike, SplitButton, SplitButtonStyle, Tab};
18use workspace::SERIALIZATION_THROTTLE_TIME;
19
20use super::*;
21
22#[derive(Default)]
23struct ThreadFeedbackState {
24 feedback: Option<ThreadFeedback>,
25 comments_editor: Option<Entity<Editor>>,
26}
27
28impl ThreadFeedbackState {
29 pub fn submit(
30 &mut self,
31 thread: Entity<AcpThread>,
32 feedback: ThreadFeedback,
33 window: &mut Window,
34 cx: &mut App,
35 ) {
36 let Some(telemetry) = thread.read(cx).connection().telemetry() else {
37 return;
38 };
39
40 let project = thread.read(cx).project().read(cx);
41 let client = project.client();
42 let user_store = project.user_store();
43 let organization = user_store.read(cx).current_organization();
44
45 if self.feedback == Some(feedback) {
46 return;
47 }
48
49 self.feedback = Some(feedback);
50 match feedback {
51 ThreadFeedback::Positive => {
52 self.comments_editor = None;
53 }
54 ThreadFeedback::Negative => {
55 self.comments_editor = Some(Self::build_feedback_comments_editor(window, cx));
56 }
57 }
58 let session_id = thread.read(cx).session_id().clone();
59 let parent_session_id = thread.read(cx).parent_session_id().cloned();
60 let agent_telemetry_id = thread.read(cx).connection().telemetry_id();
61 let task = telemetry.thread_data(&session_id, cx);
62 let rating = match feedback {
63 ThreadFeedback::Positive => "positive",
64 ThreadFeedback::Negative => "negative",
65 };
66 cx.background_spawn(async move {
67 let thread = task.await?;
68
69 client
70 .cloud_client()
71 .submit_agent_feedback(SubmitAgentThreadFeedbackBody {
72 organization_id: organization.map(|organization| organization.id.clone()),
73 agent: agent_telemetry_id.to_string(),
74 session_id: session_id.to_string(),
75 parent_session_id: parent_session_id.map(|id| id.to_string()),
76 rating: rating.to_string(),
77 thread,
78 })
79 .await?;
80
81 anyhow::Ok(())
82 })
83 .detach_and_log_err(cx);
84 }
85
86 pub fn submit_comments(&mut self, thread: Entity<AcpThread>, cx: &mut App) {
87 let Some(telemetry) = thread.read(cx).connection().telemetry() else {
88 return;
89 };
90
91 let Some(comments) = self
92 .comments_editor
93 .as_ref()
94 .map(|editor| editor.read(cx).text(cx))
95 .filter(|text| !text.trim().is_empty())
96 else {
97 return;
98 };
99
100 self.comments_editor.take();
101
102 let project = thread.read(cx).project().read(cx);
103 let client = project.client();
104 let user_store = project.user_store();
105 let organization = user_store.read(cx).current_organization();
106
107 let session_id = thread.read(cx).session_id().clone();
108 let agent_telemetry_id = thread.read(cx).connection().telemetry_id();
109 let task = telemetry.thread_data(&session_id, cx);
110 cx.background_spawn(async move {
111 let thread = task.await?;
112
113 client
114 .cloud_client()
115 .submit_agent_feedback_comments(SubmitAgentThreadFeedbackCommentsBody {
116 organization_id: organization.map(|organization| organization.id.clone()),
117 agent: agent_telemetry_id.to_string(),
118 session_id: session_id.to_string(),
119 comments,
120 thread,
121 })
122 .await?;
123
124 anyhow::Ok(())
125 })
126 .detach_and_log_err(cx);
127 }
128
129 pub fn clear(&mut self) {
130 *self = Self::default()
131 }
132
133 pub fn dismiss_comments(&mut self) {
134 self.comments_editor.take();
135 }
136
137 fn build_feedback_comments_editor(window: &mut Window, cx: &mut App) -> Entity<Editor> {
138 let buffer = cx.new(|cx| {
139 let empty_string = String::new();
140 MultiBuffer::singleton(cx.new(|cx| Buffer::local(empty_string, cx)), cx)
141 });
142
143 let editor = cx.new(|cx| {
144 let mut editor = Editor::new(
145 editor::EditorMode::AutoHeight {
146 min_lines: 1,
147 max_lines: Some(4),
148 },
149 buffer,
150 None,
151 window,
152 cx,
153 );
154 editor.set_placeholder_text(
155 "What went wrong? Share your feedback so we can improve.",
156 window,
157 cx,
158 );
159 editor
160 });
161
162 editor.read(cx).focus_handle(cx).focus(window, cx);
163 editor
164 }
165}
166
167pub enum AcpThreadViewEvent {
168 FirstSendRequested { content: Vec<acp::ContentBlock> },
169 MessageSentOrQueued,
170}
171
172impl EventEmitter<AcpThreadViewEvent> for ThreadView {}
173
174/// Tracks the user's permission dropdown selection state for a specific tool call.
175///
176/// Default (no entry in the map) means the last dropdown choice is selected,
177/// which is typically "Only this time".
178#[derive(Clone)]
179pub(crate) enum PermissionSelection {
180 /// A specific choice from the dropdown (e.g., "Always for terminal", "Only this time").
181 /// The index corresponds to the position in the `choices` list from `PermissionOptions`.
182 Choice(usize),
183 /// "Select options…" mode where individual command patterns can be toggled.
184 /// Contains the indices of checked patterns in the `patterns` list.
185 /// All patterns start checked when this mode is first activated.
186 SelectedPatterns(Vec<usize>),
187}
188
189impl PermissionSelection {
190 /// Returns the choice index if a specific dropdown choice is selected,
191 /// or `None` if in per-command pattern mode.
192 pub(crate) fn choice_index(&self) -> Option<usize> {
193 match self {
194 Self::Choice(index) => Some(*index),
195 Self::SelectedPatterns(_) => None,
196 }
197 }
198
199 fn is_pattern_checked(&self, index: usize) -> bool {
200 match self {
201 Self::SelectedPatterns(checked) => checked.contains(&index),
202 _ => false,
203 }
204 }
205
206 fn has_any_checked_patterns(&self) -> bool {
207 match self {
208 Self::SelectedPatterns(checked) => !checked.is_empty(),
209 _ => false,
210 }
211 }
212
213 fn toggle_pattern(&mut self, index: usize) {
214 if let Self::SelectedPatterns(checked) = self {
215 if let Some(pos) = checked.iter().position(|&i| i == index) {
216 checked.swap_remove(pos);
217 } else {
218 checked.push(index);
219 }
220 }
221 }
222}
223
224pub struct ThreadView {
225 pub id: acp::SessionId,
226 pub parent_id: Option<acp::SessionId>,
227 pub thread: Entity<AcpThread>,
228 pub(crate) conversation: Entity<super::Conversation>,
229 pub server_view: WeakEntity<ConversationView>,
230 pub agent_icon: IconName,
231 pub agent_icon_from_external_svg: Option<SharedString>,
232 pub agent_id: AgentId,
233 pub focus_handle: FocusHandle,
234 pub workspace: WeakEntity<Workspace>,
235 pub entry_view_state: Entity<EntryViewState>,
236 pub title_editor: Entity<Editor>,
237 pub config_options_view: Option<Entity<ConfigOptionsView>>,
238 pub mode_selector: Option<Entity<ModeSelector>>,
239 pub model_selector: Option<Entity<ModelSelectorPopover>>,
240 pub profile_selector: Option<Entity<ProfileSelector>>,
241 pub permission_dropdown_handle: PopoverMenuHandle<ContextMenu>,
242 pub thread_retry_status: Option<RetryStatus>,
243 pub(super) thread_error: Option<ThreadError>,
244 pub thread_error_markdown: Option<Entity<Markdown>>,
245 pub token_limit_callout_dismissed: bool,
246 pub last_token_limit_telemetry: Option<acp_thread::TokenUsageRatio>,
247 thread_feedback: ThreadFeedbackState,
248 pub list_state: ListState,
249 pub session_capabilities: SharedSessionCapabilities,
250 /// Tracks which tool calls have their content/output expanded.
251 /// Used for showing/hiding tool call results, terminal output, etc.
252 pub expanded_tool_calls: HashSet<agent_client_protocol::ToolCallId>,
253 pub expanded_tool_call_raw_inputs: HashSet<agent_client_protocol::ToolCallId>,
254 pub expanded_thinking_blocks: HashSet<(usize, usize)>,
255 auto_expanded_thinking_block: Option<(usize, usize)>,
256 user_toggled_thinking_blocks: HashSet<(usize, usize)>,
257 pub subagent_scroll_handles: RefCell<HashMap<agent_client_protocol::SessionId, ScrollHandle>>,
258 pub edits_expanded: bool,
259 pub plan_expanded: bool,
260 pub queue_expanded: bool,
261 pub editor_expanded: bool,
262 pub should_be_following: bool,
263 pub editing_message: Option<usize>,
264 pub local_queued_messages: Vec<QueuedMessage>,
265 pub queued_message_editors: Vec<Entity<MessageEditor>>,
266 pub queued_message_editor_subscriptions: Vec<Subscription>,
267 pub last_synced_queue_length: usize,
268 pub turn_fields: TurnFields,
269 pub discarded_partial_edits: HashSet<agent_client_protocol::ToolCallId>,
270 pub is_loading_contents: bool,
271 pub new_server_version_available: Option<SharedString>,
272 pub resumed_without_history: bool,
273 pub(crate) permission_selections:
274 HashMap<agent_client_protocol::ToolCallId, PermissionSelection>,
275 pub resume_thread_metadata: Option<AgentSessionInfo>,
276 pub _cancel_task: Option<Task<()>>,
277 _save_task: Option<Task<()>>,
278 _draft_resolve_task: Option<Task<()>>,
279 pub skip_queue_processing_count: usize,
280 pub user_interrupted_generation: bool,
281 pub can_fast_track_queue: bool,
282 pub hovered_edited_file_buttons: Option<usize>,
283 pub in_flight_prompt: Option<Vec<acp::ContentBlock>>,
284 pub _subscriptions: Vec<Subscription>,
285 pub message_editor: Entity<MessageEditor>,
286 pub add_context_menu_handle: PopoverMenuHandle<ContextMenu>,
287 pub thinking_effort_menu_handle: PopoverMenuHandle<ContextMenu>,
288 pub project: WeakEntity<Project>,
289 pub recent_history_entries: Vec<AgentSessionInfo>,
290 pub hovered_recent_history_item: Option<usize>,
291 pub show_external_source_prompt_warning: bool,
292 pub show_codex_windows_warning: bool,
293 pub generating_indicator_in_list: bool,
294 pub history: Option<Entity<ThreadHistory>>,
295 pub _history_subscription: Option<Subscription>,
296}
297impl Focusable for ThreadView {
298 fn focus_handle(&self, cx: &App) -> FocusHandle {
299 if self.parent_id.is_some() {
300 self.focus_handle.clone()
301 } else {
302 self.active_editor(cx).focus_handle(cx)
303 }
304 }
305}
306
307#[derive(Default)]
308pub struct TurnFields {
309 pub _turn_timer_task: Option<Task<()>>,
310 pub last_turn_duration: Option<Duration>,
311 pub last_turn_tokens: Option<u64>,
312 pub turn_generation: usize,
313 pub turn_started_at: Option<Instant>,
314 pub turn_tokens: Option<u64>,
315}
316
317impl ThreadView {
318 pub(crate) fn new(
319 parent_id: Option<acp::SessionId>,
320 thread: Entity<AcpThread>,
321 conversation: Entity<super::Conversation>,
322 server_view: WeakEntity<ConversationView>,
323 agent_icon: IconName,
324 agent_icon_from_external_svg: Option<SharedString>,
325 agent_id: AgentId,
326 agent_display_name: SharedString,
327 workspace: WeakEntity<Workspace>,
328 entry_view_state: Entity<EntryViewState>,
329 config_options_view: Option<Entity<ConfigOptionsView>>,
330 mode_selector: Option<Entity<ModeSelector>>,
331 model_selector: Option<Entity<ModelSelectorPopover>>,
332 profile_selector: Option<Entity<ProfileSelector>>,
333 list_state: ListState,
334 session_capabilities: SharedSessionCapabilities,
335 resumed_without_history: bool,
336 project: WeakEntity<Project>,
337 thread_store: Option<Entity<ThreadStore>>,
338 history: Option<Entity<ThreadHistory>>,
339 prompt_store: Option<Entity<PromptStore>>,
340 initial_content: Option<AgentInitialContent>,
341 mut subscriptions: Vec<Subscription>,
342 window: &mut Window,
343 cx: &mut Context<Self>,
344 ) -> Self {
345 let id = thread.read(cx).session_id().clone();
346
347 let placeholder = placeholder_text(agent_display_name.as_ref(), false);
348
349 let history_subscription = history.as_ref().map(|h| {
350 cx.observe(h, |this, history, cx| {
351 this.update_recent_history_from_cache(&history, cx);
352 })
353 });
354
355 let mut should_auto_submit = false;
356 let mut show_external_source_prompt_warning = false;
357
358 let message_editor = cx.new(|cx| {
359 let mut editor = MessageEditor::new(
360 workspace.clone(),
361 project.clone(),
362 thread_store,
363 history.as_ref().map(|h| h.downgrade()),
364 prompt_store,
365 session_capabilities.clone(),
366 agent_id.clone(),
367 &placeholder,
368 editor::EditorMode::AutoHeight {
369 min_lines: AgentSettings::get_global(cx).message_editor_min_lines,
370 max_lines: Some(AgentSettings::get_global(cx).set_message_editor_max_lines()),
371 },
372 window,
373 cx,
374 );
375 if let Some(content) = initial_content {
376 match content {
377 AgentInitialContent::ThreadSummary { session_id, title } => {
378 editor.insert_thread_summary(session_id, title, window, cx);
379 }
380 AgentInitialContent::ContentBlock {
381 blocks,
382 auto_submit,
383 } => {
384 should_auto_submit = auto_submit;
385 editor.set_message(blocks, window, cx);
386 }
387 AgentInitialContent::FromExternalSource(prompt) => {
388 show_external_source_prompt_warning = true;
389 // SECURITY: Be explicit about not auto submitting prompt from external source.
390 should_auto_submit = false;
391 editor.set_message(
392 vec![acp::ContentBlock::Text(acp::TextContent::new(
393 prompt.into_string(),
394 ))],
395 window,
396 cx,
397 );
398 }
399 }
400 } else if let Some(draft) = thread.read(cx).draft_prompt() {
401 editor.set_message(draft.to_vec(), window, cx);
402 }
403 editor
404 });
405
406 let show_codex_windows_warning = cfg!(windows)
407 && project.upgrade().is_some_and(|p| p.read(cx).is_local())
408 && agent_id.as_ref() == "Codex";
409
410 let title_editor = {
411 let can_edit = thread.update(cx, |thread, cx| thread.can_set_title(cx));
412 let editor = cx.new(|cx| {
413 let mut editor = Editor::single_line(window, cx);
414 if let Some(title) = thread.read(cx).title() {
415 editor.set_text(title, window, cx);
416 } else {
417 editor.set_text(DEFAULT_THREAD_TITLE, window, cx);
418 }
419 editor.set_read_only(!can_edit);
420 editor
421 });
422 subscriptions.push(cx.subscribe_in(&editor, window, Self::handle_title_editor_event));
423 editor
424 };
425
426 subscriptions.push(cx.subscribe_in(
427 &entry_view_state,
428 window,
429 Self::handle_entry_view_event,
430 ));
431
432 subscriptions.push(cx.subscribe_in(
433 &message_editor,
434 window,
435 Self::handle_message_editor_event,
436 ));
437
438 subscriptions.push(cx.observe(&message_editor, |this, editor, cx| {
439 let is_empty = editor.read(cx).text(cx).is_empty();
440 let draft_contents_task = if is_empty {
441 None
442 } else {
443 Some(editor.update(cx, |editor, cx| editor.draft_contents(cx)))
444 };
445 this._draft_resolve_task = Some(cx.spawn(async move |this, cx| {
446 let draft = if let Some(task) = draft_contents_task {
447 let blocks = task.await.ok().filter(|b| !b.is_empty());
448 blocks
449 } else {
450 None
451 };
452 this.update(cx, |this, cx| {
453 this.thread.update(cx, |thread, _cx| {
454 thread.set_draft_prompt(draft);
455 });
456 this.schedule_save(cx);
457 })
458 .ok();
459 }));
460 }));
461
462 let recent_history_entries = history
463 .as_ref()
464 .map(|h| h.read(cx).get_recent_sessions(3))
465 .unwrap_or_default();
466
467 let mut this = Self {
468 id,
469 parent_id,
470 focus_handle: cx.focus_handle(),
471 thread,
472 conversation,
473 server_view,
474 agent_icon,
475 agent_icon_from_external_svg,
476 agent_id,
477 workspace,
478 entry_view_state,
479 title_editor,
480 config_options_view,
481 mode_selector,
482 model_selector,
483 profile_selector,
484 list_state,
485 session_capabilities,
486 resumed_without_history,
487 _subscriptions: subscriptions,
488 permission_dropdown_handle: PopoverMenuHandle::default(),
489 thread_retry_status: None,
490 thread_error: None,
491 thread_error_markdown: None,
492 token_limit_callout_dismissed: false,
493 last_token_limit_telemetry: None,
494 thread_feedback: Default::default(),
495 expanded_tool_calls: HashSet::default(),
496 expanded_tool_call_raw_inputs: HashSet::default(),
497 expanded_thinking_blocks: HashSet::default(),
498 auto_expanded_thinking_block: None,
499 user_toggled_thinking_blocks: HashSet::default(),
500 subagent_scroll_handles: RefCell::new(HashMap::default()),
501 edits_expanded: false,
502 plan_expanded: false,
503 queue_expanded: true,
504 editor_expanded: false,
505 should_be_following: false,
506 editing_message: None,
507 local_queued_messages: Vec::new(),
508 queued_message_editors: Vec::new(),
509 queued_message_editor_subscriptions: Vec::new(),
510 last_synced_queue_length: 0,
511 turn_fields: TurnFields::default(),
512 discarded_partial_edits: HashSet::default(),
513 is_loading_contents: false,
514 new_server_version_available: None,
515 permission_selections: HashMap::default(),
516 resume_thread_metadata: None,
517 _cancel_task: None,
518 _save_task: None,
519 _draft_resolve_task: None,
520 skip_queue_processing_count: 0,
521 user_interrupted_generation: false,
522 can_fast_track_queue: false,
523 hovered_edited_file_buttons: None,
524 in_flight_prompt: None,
525 message_editor,
526 add_context_menu_handle: PopoverMenuHandle::default(),
527 thinking_effort_menu_handle: PopoverMenuHandle::default(),
528 project,
529 recent_history_entries,
530 hovered_recent_history_item: None,
531 show_external_source_prompt_warning,
532 history,
533 _history_subscription: history_subscription,
534 show_codex_windows_warning,
535 generating_indicator_in_list: false,
536 };
537
538 this.sync_generating_indicator(cx);
539 this.sync_editor_mode_for_empty_state(cx);
540 let list_state_for_scroll = this.list_state.clone();
541 let thread_view = cx.entity().downgrade();
542
543 this.list_state
544 .set_scroll_handler(move |event, _window, cx| {
545 let list_state = list_state_for_scroll.clone();
546 let thread_view = thread_view.clone();
547 let is_following_tail = event.is_following_tail;
548 // N.B. We must defer because the scroll handler is called while the
549 // ListState's RefCell is mutably borrowed. Reading logical_scroll_top()
550 // directly would panic from a double borrow.
551 cx.defer(move |cx| {
552 let scroll_top = list_state.logical_scroll_top();
553 let _ = thread_view.update(cx, |this, cx| {
554 if !is_following_tail {
555 let is_generating =
556 matches!(this.thread.read(cx).status(), ThreadStatus::Generating);
557
558 if list_state.is_at_bottom() && is_generating {
559 list_state.set_follow_tail(true);
560 }
561 }
562 if let Some(thread) = this.as_native_thread(cx) {
563 thread.update(cx, |thread, _cx| {
564 thread.set_ui_scroll_position(Some(scroll_top));
565 });
566 }
567 this.schedule_save(cx);
568 });
569 });
570 });
571
572 if should_auto_submit {
573 this.send(window, cx);
574 }
575 this
576 }
577
578 /// Schedule a throttled save of the thread state (draft prompt, scroll position, etc.).
579 /// Multiple calls within `SERIALIZATION_THROTTLE_TIME` are coalesced into a single save.
580 fn schedule_save(&mut self, cx: &mut Context<Self>) {
581 self._save_task = Some(cx.spawn(async move |this, cx| {
582 cx.background_executor()
583 .timer(SERIALIZATION_THROTTLE_TIME)
584 .await;
585 this.update(cx, |this, cx| {
586 if let Some(thread) = this.as_native_thread(cx) {
587 thread.update(cx, |_thread, cx| cx.notify());
588 }
589 })
590 .ok();
591 }));
592 }
593
594 pub fn handle_message_editor_event(
595 &mut self,
596 _editor: &Entity<MessageEditor>,
597 event: &MessageEditorEvent,
598 window: &mut Window,
599 cx: &mut Context<Self>,
600 ) {
601 match event {
602 MessageEditorEvent::Send => self.send(window, cx),
603 MessageEditorEvent::SendImmediately => self.interrupt_and_send(window, cx),
604 MessageEditorEvent::Cancel => self.cancel_generation(cx),
605 MessageEditorEvent::Focus => {
606 self.cancel_editing(&Default::default(), window, cx);
607 }
608 MessageEditorEvent::LostFocus => {}
609 MessageEditorEvent::InputAttempted { .. } => {}
610 }
611 }
612
613 pub(crate) fn as_native_connection(
614 &self,
615 cx: &App,
616 ) -> Option<Rc<agent::NativeAgentConnection>> {
617 let acp_thread = self.thread.read(cx);
618 acp_thread.connection().clone().downcast()
619 }
620
621 pub fn as_native_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
622 let acp_thread = self.thread.read(cx);
623 self.as_native_connection(cx)?
624 .thread(acp_thread.session_id(), cx)
625 }
626
627 /// Resolves the message editor's contents into content blocks. For profiles
628 /// that do not enable any tools, directory mentions are expanded to inline
629 /// file contents since the agent can't read files on its own.
630 fn resolve_message_contents(
631 &self,
632 message_editor: &Entity<MessageEditor>,
633 cx: &mut App,
634 ) -> Task<Result<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>> {
635 let expand = self.as_native_thread(cx).is_some_and(|thread| {
636 let thread = thread.read(cx);
637 AgentSettings::get_global(cx)
638 .profiles
639 .get(thread.profile())
640 .is_some_and(|profile| profile.tools.is_empty())
641 });
642 message_editor.update(cx, |message_editor, cx| message_editor.contents(expand, cx))
643 }
644
645 pub fn current_model_id(&self, cx: &App) -> Option<String> {
646 let selector = self.model_selector.as_ref()?;
647 let model = selector.read(cx).active_model(cx)?;
648 Some(model.id.to_string())
649 }
650
651 pub fn current_mode_id(&self, cx: &App) -> Option<Arc<str>> {
652 if let Some(thread) = self.as_native_thread(cx) {
653 Some(thread.read(cx).profile().0.clone())
654 } else {
655 let mode_selector = self.mode_selector.as_ref()?;
656 Some(mode_selector.read(cx).mode().0)
657 }
658 }
659
660 fn is_subagent(&self) -> bool {
661 self.parent_id.is_some()
662 }
663
664 /// Returns the currently active editor, either for a message that is being
665 /// edited or the editor for a new message.
666 pub(crate) fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
667 if let Some(index) = self.editing_message
668 && let Some(editor) = self
669 .entry_view_state
670 .read(cx)
671 .entry(index)
672 .and_then(|entry| entry.message_editor())
673 .cloned()
674 {
675 editor
676 } else {
677 self.message_editor.clone()
678 }
679 }
680
681 pub fn has_queued_messages(&self) -> bool {
682 !self.local_queued_messages.is_empty()
683 }
684
685 pub fn is_imported_thread(&self, cx: &App) -> bool {
686 let Some(thread) = self.as_native_thread(cx) else {
687 return false;
688 };
689 thread.read(cx).is_imported()
690 }
691
692 // events
693
694 pub fn handle_entry_view_event(
695 &mut self,
696 _: &Entity<EntryViewState>,
697 event: &EntryViewEvent,
698 window: &mut Window,
699 cx: &mut Context<Self>,
700 ) {
701 match &event.view_event {
702 ViewEvent::NewDiff(tool_call_id) => {
703 if AgentSettings::get_global(cx).expand_edit_card {
704 self.expanded_tool_calls.insert(tool_call_id.clone());
705 }
706 }
707 ViewEvent::NewTerminal(tool_call_id) => {
708 if AgentSettings::get_global(cx).expand_terminal_card {
709 self.expanded_tool_calls.insert(tool_call_id.clone());
710 }
711 }
712 ViewEvent::TerminalMovedToBackground(tool_call_id) => {
713 self.expanded_tool_calls.remove(tool_call_id);
714 }
715 ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Focus) => {
716 if let Some(AgentThreadEntry::UserMessage(user_message)) =
717 self.thread.read(cx).entries().get(event.entry_index)
718 && user_message.id.is_some()
719 && !self.is_subagent()
720 {
721 self.editing_message = Some(event.entry_index);
722 cx.notify();
723 }
724 }
725 ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::LostFocus) => {
726 if let Some(AgentThreadEntry::UserMessage(user_message)) =
727 self.thread.read(cx).entries().get(event.entry_index)
728 && user_message.id.is_some()
729 && !self.is_subagent()
730 {
731 if editor.read(cx).text(cx).as_str() == user_message.content.to_markdown(cx) {
732 self.editing_message = None;
733 cx.notify();
734 }
735 }
736 }
737 ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::SendImmediately) => {}
738 ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::Send) => {
739 if !self.is_subagent() {
740 self.regenerate(event.entry_index, editor.clone(), window, cx);
741 }
742 }
743 ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Cancel) => {
744 self.cancel_editing(&Default::default(), window, cx);
745 }
746 ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::InputAttempted { .. }) => {}
747 ViewEvent::OpenDiffLocation {
748 path,
749 position,
750 split,
751 } => {
752 self.open_diff_location(path, *position, *split, window, cx);
753 }
754 }
755 }
756
757 fn open_diff_location(
758 &self,
759 path: &str,
760 position: Point,
761 split: bool,
762 window: &mut Window,
763 cx: &mut Context<Self>,
764 ) {
765 let Some(project) = self.project.upgrade() else {
766 return;
767 };
768 let Some(project_path) = project.read(cx).find_project_path(path, cx) else {
769 return;
770 };
771
772 let open_task = if split {
773 self.workspace
774 .update(cx, |workspace, cx| {
775 workspace.split_path(project_path, window, cx)
776 })
777 .log_err()
778 } else {
779 self.workspace
780 .update(cx, |workspace, cx| {
781 workspace.open_path(project_path, None, true, window, cx)
782 })
783 .log_err()
784 };
785
786 let Some(open_task) = open_task else {
787 return;
788 };
789
790 window
791 .spawn(cx, async move |cx| {
792 let item = open_task.await?;
793 let Some(editor) = item.downcast::<Editor>() else {
794 return anyhow::Ok(());
795 };
796 editor.update_in(cx, |editor, window, cx| {
797 editor.change_selections(
798 SelectionEffects::scroll(Autoscroll::center()),
799 window,
800 cx,
801 |selections| {
802 selections.select_ranges([position..position]);
803 },
804 );
805 })?;
806 anyhow::Ok(())
807 })
808 .detach_and_log_err(cx);
809 }
810
811 // turns
812
813 pub fn start_turn(&mut self, cx: &mut Context<Self>) -> usize {
814 self.turn_fields.turn_generation += 1;
815 let generation = self.turn_fields.turn_generation;
816 self.turn_fields.turn_started_at = Some(Instant::now());
817 self.turn_fields.last_turn_duration = None;
818 self.turn_fields.last_turn_tokens = None;
819 self.turn_fields.turn_tokens = Some(0);
820 self.turn_fields._turn_timer_task = Some(cx.spawn(async move |this, cx| {
821 loop {
822 cx.background_executor().timer(Duration::from_secs(1)).await;
823 if this.update(cx, |_, cx| cx.notify()).is_err() {
824 break;
825 }
826 }
827 }));
828 if self.parent_id.is_none() {
829 self.suppress_merge_conflict_notification(cx);
830 }
831 generation
832 }
833
834 pub fn stop_turn(&mut self, generation: usize, cx: &mut Context<Self>) {
835 if self.turn_fields.turn_generation != generation {
836 return;
837 }
838 self.turn_fields.last_turn_duration = self
839 .turn_fields
840 .turn_started_at
841 .take()
842 .map(|started| started.elapsed());
843 self.turn_fields.last_turn_tokens = self.turn_fields.turn_tokens.take();
844 self.turn_fields._turn_timer_task = None;
845 if self.parent_id.is_none() {
846 self.unsuppress_merge_conflict_notification(cx);
847 }
848 }
849
850 fn suppress_merge_conflict_notification(&self, cx: &mut Context<Self>) {
851 self.workspace
852 .update(cx, |workspace, cx| {
853 workspace.suppress_notification(&workspace::merge_conflict_notification_id(), cx);
854 })
855 .ok();
856 }
857
858 fn unsuppress_merge_conflict_notification(&self, cx: &mut Context<Self>) {
859 self.workspace
860 .update(cx, |workspace, _cx| {
861 workspace.unsuppress(workspace::merge_conflict_notification_id());
862 })
863 .ok();
864 }
865
866 pub fn update_turn_tokens(&mut self, cx: &App) {
867 if let Some(usage) = self.thread.read(cx).token_usage() {
868 if let Some(tokens) = &mut self.turn_fields.turn_tokens {
869 *tokens += usage.output_tokens;
870 }
871 }
872 }
873
874 // sending
875
876 fn clear_external_source_prompt_warning(&mut self, cx: &mut Context<Self>) {
877 if self.show_external_source_prompt_warning {
878 self.show_external_source_prompt_warning = false;
879 cx.notify();
880 }
881 }
882
883 pub fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
884 let thread = &self.thread;
885
886 if self.is_loading_contents {
887 return;
888 }
889
890 let message_editor = self.message_editor.clone();
891
892 // Intercept the first send so the agent panel can capture the full
893 // content blocks — needed for "Start thread in New Worktree",
894 // which must create a workspace before sending the message there.
895 let intercept_first_send = self.thread.read(cx).entries().is_empty()
896 && !message_editor.read(cx).is_empty(cx)
897 && self
898 .workspace
899 .upgrade()
900 .and_then(|workspace| workspace.read(cx).panel::<AgentPanel>(cx))
901 .is_some_and(|panel| {
902 panel.read(cx).start_thread_in() == &StartThreadIn::NewWorktree
903 });
904
905 if intercept_first_send {
906 cx.emit(AcpThreadViewEvent::MessageSentOrQueued);
907 let content_task = self.resolve_message_contents(&message_editor, cx);
908
909 cx.spawn(async move |this, cx| match content_task.await {
910 Ok((content, _tracked_buffers)) => {
911 if content.is_empty() {
912 return;
913 }
914
915 this.update(cx, |_, cx| {
916 cx.emit(AcpThreadViewEvent::FirstSendRequested { content });
917 })
918 .ok();
919 }
920 Err(error) => {
921 this.update(cx, |this, cx| {
922 this.handle_thread_error(error, cx);
923 })
924 .ok();
925 }
926 })
927 .detach();
928
929 return;
930 }
931
932 let is_editor_empty = message_editor.read(cx).is_empty(cx);
933 let is_generating = thread.read(cx).status() != ThreadStatus::Idle;
934
935 let has_queued = self.has_queued_messages();
936 if is_editor_empty && self.can_fast_track_queue && has_queued {
937 self.can_fast_track_queue = false;
938 cx.emit(AcpThreadViewEvent::MessageSentOrQueued);
939 self.send_queued_message_at_index(0, true, window, cx);
940 return;
941 }
942
943 if is_editor_empty {
944 return;
945 }
946
947 if is_generating {
948 cx.emit(AcpThreadViewEvent::MessageSentOrQueued);
949 self.queue_message(message_editor, window, cx);
950 return;
951 }
952
953 let text = message_editor.read(cx).text(cx);
954 let text = text.trim();
955 if text == "/login" || text == "/logout" {
956 let connection = thread.read(cx).connection().clone();
957 let can_login = !connection.auth_methods().is_empty();
958 // Does the agent have a specific logout command? Prefer that in case they need to reset internal state.
959 let logout_supported = text == "/logout"
960 && self
961 .session_capabilities
962 .read()
963 .available_commands()
964 .iter()
965 .any(|command| command.name == "logout");
966 if can_login && !logout_supported {
967 message_editor.update(cx, |editor, cx| editor.clear(window, cx));
968 self.clear_external_source_prompt_warning(cx);
969
970 let connection = self.thread.read(cx).connection().clone();
971 window.defer(cx, {
972 let agent_id = self.agent_id.clone();
973 let server_view = self.server_view.clone();
974 move |window, cx| {
975 ConversationView::handle_auth_required(
976 server_view.clone(),
977 AuthRequired::new(),
978 agent_id,
979 connection,
980 window,
981 cx,
982 );
983 }
984 });
985 cx.notify();
986 return;
987 }
988 }
989
990 cx.emit(AcpThreadViewEvent::MessageSentOrQueued);
991 self.send_impl(message_editor, window, cx)
992 }
993
994 pub fn send_impl(
995 &mut self,
996 message_editor: Entity<MessageEditor>,
997 window: &mut Window,
998 cx: &mut Context<Self>,
999 ) {
1000 let contents = self.resolve_message_contents(&message_editor, cx);
1001
1002 self.thread_error.take();
1003 self.thread_feedback.clear();
1004 self.editing_message.take();
1005
1006 if self.should_be_following {
1007 self.workspace
1008 .update(cx, |workspace, cx| {
1009 workspace.follow(CollaboratorId::Agent, window, cx);
1010 })
1011 .ok();
1012 }
1013
1014 let contents_task = cx.spawn_in(window, async move |_this, cx| {
1015 let (contents, tracked_buffers) = contents.await?;
1016
1017 if contents.is_empty() {
1018 return Ok(None);
1019 }
1020
1021 let _ = cx.update(|window, cx| {
1022 message_editor.update(cx, |message_editor, cx| {
1023 message_editor.clear(window, cx);
1024 });
1025 });
1026
1027 Ok(Some((contents, tracked_buffers)))
1028 });
1029
1030 self.send_content(contents_task, window, cx);
1031 }
1032
1033 pub fn send_content(
1034 &mut self,
1035 contents_task: Task<anyhow::Result<Option<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>>>,
1036 window: &mut Window,
1037 cx: &mut Context<Self>,
1038 ) {
1039 let session_id = self.thread.read(cx).session_id().clone();
1040 let parent_session_id = self.thread.read(cx).parent_session_id().cloned();
1041 let agent_telemetry_id = self.thread.read(cx).connection().telemetry_id();
1042 let is_first_message = self.thread.read(cx).entries().is_empty();
1043 let thread = self.thread.downgrade();
1044
1045 self.is_loading_contents = true;
1046
1047 let model_id = self.current_model_id(cx);
1048 let mode_id = self.current_mode_id(cx);
1049 let guard = cx.new(|_| ());
1050 cx.observe_release(&guard, |this, _guard, cx| {
1051 this.is_loading_contents = false;
1052 cx.notify();
1053 })
1054 .detach();
1055
1056 let task = cx.spawn_in(window, async move |this, cx| {
1057 let Some((contents, tracked_buffers)) = contents_task.await? else {
1058 return Ok(());
1059 };
1060
1061 let generation = this.update(cx, |this, cx| {
1062 this.clear_external_source_prompt_warning(cx);
1063 let generation = this.start_turn(cx);
1064 this.in_flight_prompt = Some(contents.clone());
1065 generation
1066 })?;
1067
1068 this.update_in(cx, |this, _window, cx| {
1069 this.set_editor_is_expanded(false, cx);
1070 })?;
1071
1072 let _ = this.update(cx, |this, cx| {
1073 this.list_state.set_follow_tail(true);
1074 cx.notify();
1075 });
1076
1077 let _stop_turn = defer({
1078 let this = this.clone();
1079 let mut cx = cx.clone();
1080 move || {
1081 this.update(&mut cx, |this, cx| {
1082 this.stop_turn(generation, cx);
1083 cx.notify();
1084 })
1085 .ok();
1086 }
1087 });
1088 if is_first_message && thread.read_with(cx, |thread, _cx| thread.title().is_none())? {
1089 let text: String = contents
1090 .iter()
1091 .filter_map(|block| match block {
1092 acp::ContentBlock::Text(text_content) => Some(text_content.text.clone()),
1093 acp::ContentBlock::ResourceLink(resource_link) => {
1094 Some(format!("@{}", resource_link.name))
1095 }
1096 _ => None,
1097 })
1098 .collect::<Vec<_>>()
1099 .join(" ");
1100 let text = text.lines().next().unwrap_or("").trim();
1101 if !text.is_empty() {
1102 let title: SharedString = util::truncate_and_trailoff(text, 200).into();
1103 thread.update(cx, |thread, cx| {
1104 thread.set_provisional_title(title, cx);
1105 })?;
1106 }
1107 }
1108
1109 let turn_start_time = Instant::now();
1110 let send = thread.update(cx, |thread, cx| {
1111 thread.action_log().update(cx, |action_log, cx| {
1112 for buffer in tracked_buffers {
1113 action_log.buffer_read(buffer, cx)
1114 }
1115 });
1116 drop(guard);
1117
1118 telemetry::event!(
1119 "Agent Message Sent",
1120 agent = agent_telemetry_id,
1121 session = session_id,
1122 parent_session_id = parent_session_id.as_ref().map(|id| id.to_string()),
1123 model = model_id,
1124 mode = mode_id
1125 );
1126
1127 thread.send(contents, cx)
1128 })?;
1129
1130 let _ = this.update(cx, |this, cx| {
1131 this.sync_generating_indicator(cx);
1132 cx.notify();
1133 });
1134
1135 let res = send.await;
1136 let turn_time_ms = turn_start_time.elapsed().as_millis();
1137 drop(_stop_turn);
1138 let status = if res.is_ok() {
1139 let _ = this.update(cx, |this, _| this.in_flight_prompt.take());
1140 "success"
1141 } else {
1142 "failure"
1143 };
1144 telemetry::event!(
1145 "Agent Turn Completed",
1146 agent = agent_telemetry_id,
1147 session = session_id,
1148 parent_session_id = parent_session_id.as_ref().map(|id| id.to_string()),
1149 model = model_id,
1150 mode = mode_id,
1151 status,
1152 turn_time_ms,
1153 );
1154 res.map(|_| ())
1155 });
1156
1157 cx.spawn(async move |this, cx| {
1158 if let Err(err) = task.await {
1159 this.update(cx, |this, cx| {
1160 this.handle_thread_error(err, cx);
1161 })
1162 .ok();
1163 } else {
1164 this.update(cx, |this, cx| {
1165 let should_be_following = this
1166 .workspace
1167 .update(cx, |workspace, _| {
1168 workspace.is_being_followed(CollaboratorId::Agent)
1169 })
1170 .unwrap_or_default();
1171 this.should_be_following = should_be_following;
1172 })
1173 .ok();
1174 }
1175 })
1176 .detach();
1177 }
1178
1179 pub fn interrupt_and_send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1180 let thread = &self.thread;
1181
1182 if self.is_loading_contents {
1183 return;
1184 }
1185
1186 let message_editor = self.message_editor.clone();
1187 if thread.read(cx).status() == ThreadStatus::Idle {
1188 self.send_impl(message_editor, window, cx);
1189 return;
1190 }
1191
1192 self.stop_current_and_send_new_message(message_editor, window, cx);
1193 }
1194
1195 fn stop_current_and_send_new_message(
1196 &mut self,
1197 message_editor: Entity<MessageEditor>,
1198 window: &mut Window,
1199 cx: &mut Context<Self>,
1200 ) {
1201 let thread = self.thread.clone();
1202 self.skip_queue_processing_count = 0;
1203 self.user_interrupted_generation = true;
1204
1205 let cancelled = thread.update(cx, |thread, cx| thread.cancel(cx));
1206
1207 cx.spawn_in(window, async move |this, cx| {
1208 cancelled.await;
1209
1210 this.update_in(cx, |this, window, cx| {
1211 this.send_impl(message_editor, window, cx);
1212 })
1213 .ok();
1214 })
1215 .detach();
1216 }
1217
1218 pub(crate) fn handle_thread_error(
1219 &mut self,
1220 error: impl Into<ThreadError>,
1221 cx: &mut Context<Self>,
1222 ) {
1223 let error = error.into();
1224 self.emit_thread_error_telemetry(&error, cx);
1225 self.thread_error = Some(error);
1226 cx.notify();
1227 }
1228
1229 fn emit_thread_error_telemetry(&self, error: &ThreadError, cx: &mut Context<Self>) {
1230 let (error_kind, acp_error_code, message): (&str, Option<SharedString>, SharedString) =
1231 match error {
1232 ThreadError::PaymentRequired => (
1233 "payment_required",
1234 None,
1235 "You reached your free usage limit. Upgrade to Zed Pro for more prompts."
1236 .into(),
1237 ),
1238 ThreadError::Refusal => {
1239 let model_or_agent_name = self.current_model_name(cx);
1240 let message = format!(
1241 "{} 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.",
1242 model_or_agent_name
1243 );
1244 ("refusal", None, message.into())
1245 }
1246 ThreadError::AuthenticationRequired(message) => {
1247 ("authentication_required", None, message.clone())
1248 }
1249 ThreadError::Other {
1250 acp_error_code,
1251 message,
1252 } => ("other", acp_error_code.clone(), message.clone()),
1253 };
1254
1255 let agent_telemetry_id = self.thread.read(cx).connection().telemetry_id();
1256 let session_id = self.thread.read(cx).session_id().clone();
1257 let parent_session_id = self
1258 .thread
1259 .read(cx)
1260 .parent_session_id()
1261 .map(|id| id.to_string());
1262
1263 telemetry::event!(
1264 "Agent Panel Error Shown",
1265 agent = agent_telemetry_id,
1266 session_id = session_id,
1267 parent_session_id = parent_session_id,
1268 kind = error_kind,
1269 acp_error_code = acp_error_code,
1270 message = message,
1271 );
1272 }
1273
1274 pub fn cancel_generation(&mut self, cx: &mut Context<Self>) {
1275 self.thread_retry_status.take();
1276 self.thread_error.take();
1277 self.user_interrupted_generation = true;
1278 self._cancel_task = Some(self.thread.update(cx, |thread, cx| thread.cancel(cx)));
1279 self.sync_generating_indicator(cx);
1280 cx.notify();
1281 }
1282
1283 pub fn retry_generation(&mut self, cx: &mut Context<Self>) {
1284 self.thread_error.take();
1285
1286 let thread = &self.thread;
1287 if !thread.read(cx).can_retry(cx) {
1288 return;
1289 }
1290
1291 let task = thread.update(cx, |thread, cx| thread.retry(cx));
1292 self.sync_generating_indicator(cx);
1293 cx.notify();
1294 cx.spawn(async move |this, cx| {
1295 let result = task.await;
1296
1297 this.update(cx, |this, cx| {
1298 if let Err(err) = result {
1299 this.handle_thread_error(err, cx);
1300 }
1301 })
1302 })
1303 .detach();
1304 }
1305
1306 pub fn regenerate(
1307 &mut self,
1308 entry_ix: usize,
1309 message_editor: Entity<MessageEditor>,
1310 window: &mut Window,
1311 cx: &mut Context<Self>,
1312 ) {
1313 if self.is_loading_contents {
1314 return;
1315 }
1316 let thread = self.thread.clone();
1317
1318 let Some(user_message_id) = thread.update(cx, |thread, _| {
1319 thread.entries().get(entry_ix)?.user_message()?.id.clone()
1320 }) else {
1321 return;
1322 };
1323
1324 cx.spawn_in(window, async move |this, cx| {
1325 // Check if there are any edits from prompts before the one being regenerated.
1326 //
1327 // If there are, we keep/accept them since we're not regenerating the prompt that created them.
1328 //
1329 // If editing the prompt that generated the edits, they are auto-rejected
1330 // through the `rewind` function in the `acp_thread`.
1331 let has_earlier_edits = thread.read_with(cx, |thread, _| {
1332 thread
1333 .entries()
1334 .iter()
1335 .take(entry_ix)
1336 .any(|entry| entry.diffs().next().is_some())
1337 });
1338
1339 if has_earlier_edits {
1340 thread.update(cx, |thread, cx| {
1341 thread.action_log().update(cx, |action_log, cx| {
1342 action_log.keep_all_edits(None, cx);
1343 });
1344 });
1345 }
1346
1347 thread
1348 .update(cx, |thread, cx| thread.rewind(user_message_id, cx))
1349 .await?;
1350 this.update_in(cx, |thread, window, cx| {
1351 thread.send_impl(message_editor, window, cx);
1352 thread.focus_handle(cx).focus(window, cx);
1353 })?;
1354 anyhow::Ok(())
1355 })
1356 .detach_and_log_err(cx);
1357 }
1358
1359 // message queueing
1360
1361 fn queue_message(
1362 &mut self,
1363 message_editor: Entity<MessageEditor>,
1364 window: &mut Window,
1365 cx: &mut Context<Self>,
1366 ) {
1367 let is_idle = self.thread.read(cx).status() == acp_thread::ThreadStatus::Idle;
1368
1369 if is_idle {
1370 self.send_impl(message_editor, window, cx);
1371 return;
1372 }
1373
1374 let contents = self.resolve_message_contents(&message_editor, cx);
1375
1376 cx.spawn_in(window, async move |this, cx| {
1377 let (content, tracked_buffers) = contents.await?;
1378
1379 if content.is_empty() {
1380 return Ok::<(), anyhow::Error>(());
1381 }
1382
1383 this.update_in(cx, |this, window, cx| {
1384 this.add_to_queue(content, tracked_buffers, cx);
1385 this.can_fast_track_queue = true;
1386 message_editor.update(cx, |message_editor, cx| {
1387 message_editor.clear(window, cx);
1388 });
1389 cx.notify();
1390 })?;
1391 Ok(())
1392 })
1393 .detach_and_log_err(cx);
1394 }
1395
1396 pub fn add_to_queue(
1397 &mut self,
1398 content: Vec<acp::ContentBlock>,
1399 tracked_buffers: Vec<Entity<Buffer>>,
1400 cx: &mut Context<Self>,
1401 ) {
1402 self.local_queued_messages.push(QueuedMessage {
1403 content,
1404 tracked_buffers,
1405 });
1406 self.sync_queue_flag_to_native_thread(cx);
1407 }
1408
1409 pub fn remove_from_queue(
1410 &mut self,
1411 index: usize,
1412 cx: &mut Context<Self>,
1413 ) -> Option<QueuedMessage> {
1414 if index < self.local_queued_messages.len() {
1415 let removed = self.local_queued_messages.remove(index);
1416 self.sync_queue_flag_to_native_thread(cx);
1417 Some(removed)
1418 } else {
1419 None
1420 }
1421 }
1422
1423 pub fn sync_queue_flag_to_native_thread(&self, cx: &mut Context<Self>) {
1424 if let Some(native_thread) = self.as_native_thread(cx) {
1425 let has_queued = self.has_queued_messages();
1426 native_thread.update(cx, |thread, _| {
1427 thread.set_has_queued_message(has_queued);
1428 });
1429 }
1430 }
1431
1432 pub fn send_queued_message_at_index(
1433 &mut self,
1434 index: usize,
1435 is_send_now: bool,
1436 window: &mut Window,
1437 cx: &mut Context<Self>,
1438 ) {
1439 let Some(queued) = self.remove_from_queue(index, cx) else {
1440 return;
1441 };
1442 let content = queued.content;
1443 let tracked_buffers = queued.tracked_buffers;
1444
1445 // Only increment skip count for "Send Now" operations (out-of-order sends)
1446 // Normal auto-processing from the Stopped handler doesn't need to skip.
1447 // We only skip the Stopped event from the cancelled generation, NOT the
1448 // Stopped event from the newly sent message (which should trigger queue processing).
1449 if is_send_now {
1450 let is_generating =
1451 self.thread.read(cx).status() == acp_thread::ThreadStatus::Generating;
1452 self.skip_queue_processing_count += if is_generating { 1 } else { 0 };
1453 }
1454
1455 let cancelled = self.thread.update(cx, |thread, cx| thread.cancel(cx));
1456
1457 let workspace = self.workspace.clone();
1458
1459 let should_be_following = self.should_be_following;
1460 let contents_task = cx.spawn_in(window, async move |_this, cx| {
1461 cancelled.await;
1462 if should_be_following {
1463 workspace
1464 .update_in(cx, |workspace, window, cx| {
1465 workspace.follow(CollaboratorId::Agent, window, cx);
1466 })
1467 .ok();
1468 }
1469
1470 Ok(Some((content, tracked_buffers)))
1471 });
1472
1473 self.send_content(contents_task, window, cx);
1474 }
1475
1476 pub fn move_queued_message_to_main_editor(
1477 &mut self,
1478 index: usize,
1479 inserted_text: Option<&str>,
1480 cursor_offset: Option<usize>,
1481 window: &mut Window,
1482 cx: &mut Context<Self>,
1483 ) -> bool {
1484 let Some(queued_message) = self.remove_from_queue(index, cx) else {
1485 return false;
1486 };
1487 let queued_content = queued_message.content;
1488 let message_editor = self.message_editor.clone();
1489 let inserted_text = inserted_text.map(ToOwned::to_owned);
1490
1491 window.focus(&message_editor.focus_handle(cx), cx);
1492
1493 if message_editor.read(cx).is_empty(cx) {
1494 message_editor.update(cx, |editor, cx| {
1495 editor.set_message(queued_content, window, cx);
1496 if let Some(offset) = cursor_offset {
1497 editor.set_cursor_offset(offset, window, cx);
1498 }
1499 if let Some(inserted_text) = inserted_text.as_deref() {
1500 editor.insert_text(inserted_text, window, cx);
1501 }
1502 });
1503 cx.notify();
1504 return true;
1505 }
1506
1507 // Adjust cursor offset accounting for existing content
1508 let existing_len = message_editor.read(cx).text(cx).len();
1509 let separator = "\n\n";
1510
1511 message_editor.update(cx, |editor, cx| {
1512 editor.append_message(queued_content, Some(separator), window, cx);
1513 if let Some(offset) = cursor_offset {
1514 let adjusted_offset = existing_len + separator.len() + offset;
1515 editor.set_cursor_offset(adjusted_offset, window, cx);
1516 }
1517 if let Some(inserted_text) = inserted_text.as_deref() {
1518 editor.insert_text(inserted_text, window, cx);
1519 }
1520 });
1521
1522 cx.notify();
1523 true
1524 }
1525
1526 // editor methods
1527
1528 pub fn expand_message_editor(
1529 &mut self,
1530 _: &ExpandMessageEditor,
1531 _window: &mut Window,
1532 cx: &mut Context<Self>,
1533 ) {
1534 self.set_editor_is_expanded(!self.editor_expanded, cx);
1535 cx.stop_propagation();
1536 cx.notify();
1537 }
1538
1539 pub fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
1540 self.editor_expanded = is_expanded;
1541 self.message_editor.update(cx, |editor, cx| {
1542 if is_expanded {
1543 editor.set_mode(
1544 EditorMode::Full {
1545 scale_ui_elements_with_buffer_font_size: false,
1546 show_active_line_background: false,
1547 sizing_behavior: SizingBehavior::ExcludeOverscrollMargin,
1548 },
1549 cx,
1550 )
1551 } else {
1552 let agent_settings = AgentSettings::get_global(cx);
1553 editor.set_mode(
1554 EditorMode::AutoHeight {
1555 min_lines: agent_settings.message_editor_min_lines,
1556 max_lines: Some(agent_settings.set_message_editor_max_lines()),
1557 },
1558 cx,
1559 )
1560 }
1561 });
1562 cx.notify();
1563 }
1564
1565 pub fn handle_title_editor_event(
1566 &mut self,
1567 title_editor: &Entity<Editor>,
1568 event: &EditorEvent,
1569 window: &mut Window,
1570 cx: &mut Context<Self>,
1571 ) {
1572 let thread = &self.thread;
1573
1574 match event {
1575 EditorEvent::BufferEdited => {
1576 // We only want to set the title if the user has actively edited
1577 // it. If the title editor is not focused, we programmatically
1578 // changed the text, so we don't want to set the title again.
1579 if !title_editor.read(cx).is_focused(window) {
1580 return;
1581 }
1582
1583 let new_title = title_editor.read(cx).text(cx);
1584 thread.update(cx, |thread, cx| {
1585 thread
1586 .set_title(new_title.into(), cx)
1587 .detach_and_log_err(cx);
1588 })
1589 }
1590 EditorEvent::Blurred => {
1591 if title_editor.read(cx).text(cx).is_empty() {
1592 title_editor.update(cx, |editor, cx| {
1593 editor.set_text(DEFAULT_THREAD_TITLE, window, cx);
1594 });
1595 }
1596 }
1597 _ => {}
1598 }
1599 }
1600
1601 pub fn cancel_editing(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1602 if let Some(index) = self.editing_message.take()
1603 && let Some(editor) = &self
1604 .entry_view_state
1605 .read(cx)
1606 .entry(index)
1607 .and_then(|e| e.message_editor())
1608 .cloned()
1609 {
1610 editor.update(cx, |editor, cx| {
1611 if let Some(user_message) = self
1612 .thread
1613 .read(cx)
1614 .entries()
1615 .get(index)
1616 .and_then(|e| e.user_message())
1617 {
1618 editor.set_message(user_message.chunks.clone(), window, cx);
1619 }
1620 })
1621 };
1622 self.message_editor.focus_handle(cx).focus(window, cx);
1623 cx.notify();
1624 }
1625
1626 pub fn authorize_tool_call(
1627 &mut self,
1628 session_id: acp::SessionId,
1629 tool_call_id: acp::ToolCallId,
1630 outcome: SelectedPermissionOutcome,
1631 window: &mut Window,
1632 cx: &mut Context<Self>,
1633 ) {
1634 self.conversation.update(cx, |conversation, cx| {
1635 conversation.authorize_tool_call(session_id, tool_call_id, outcome, cx);
1636 });
1637 if self.should_be_following {
1638 self.workspace
1639 .update(cx, |workspace, cx| {
1640 workspace.follow(CollaboratorId::Agent, window, cx);
1641 })
1642 .ok();
1643 }
1644 cx.notify();
1645 }
1646
1647 pub fn allow_always(&mut self, _: &AllowAlways, window: &mut Window, cx: &mut Context<Self>) {
1648 self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowAlways, window, cx);
1649 }
1650
1651 pub fn allow_once(&mut self, _: &AllowOnce, window: &mut Window, cx: &mut Context<Self>) {
1652 self.authorize_pending_with_granularity(true, window, cx);
1653 }
1654
1655 pub fn reject_once(&mut self, _: &RejectOnce, window: &mut Window, cx: &mut Context<Self>) {
1656 self.authorize_pending_with_granularity(false, window, cx);
1657 }
1658
1659 pub fn authorize_pending_tool_call(
1660 &mut self,
1661 kind: acp::PermissionOptionKind,
1662 window: &mut Window,
1663 cx: &mut Context<Self>,
1664 ) -> Option<()> {
1665 self.conversation.update(cx, |conversation, cx| {
1666 conversation.authorize_pending_tool_call(&self.id, kind, cx)
1667 })?;
1668 if self.should_be_following {
1669 self.workspace
1670 .update(cx, |workspace, cx| {
1671 workspace.follow(CollaboratorId::Agent, window, cx);
1672 })
1673 .ok();
1674 }
1675 cx.notify();
1676 Some(())
1677 }
1678
1679 fn is_waiting_for_confirmation(entry: &AgentThreadEntry) -> bool {
1680 if let AgentThreadEntry::ToolCall(tool_call) = entry {
1681 matches!(
1682 tool_call.status,
1683 ToolCallStatus::WaitingForConfirmation { .. }
1684 )
1685 } else {
1686 false
1687 }
1688 }
1689
1690 fn handle_authorize_tool_call(
1691 &mut self,
1692 action: &AuthorizeToolCall,
1693 window: &mut Window,
1694 cx: &mut Context<Self>,
1695 ) {
1696 let tool_call_id = acp::ToolCallId::new(action.tool_call_id.clone());
1697 let option_id = acp::PermissionOptionId::new(action.option_id.clone());
1698 let option_kind = match action.option_kind.as_str() {
1699 "AllowOnce" => acp::PermissionOptionKind::AllowOnce,
1700 "AllowAlways" => acp::PermissionOptionKind::AllowAlways,
1701 "RejectOnce" => acp::PermissionOptionKind::RejectOnce,
1702 "RejectAlways" => acp::PermissionOptionKind::RejectAlways,
1703 _ => acp::PermissionOptionKind::AllowOnce,
1704 };
1705
1706 self.authorize_tool_call(
1707 self.id.clone(),
1708 tool_call_id,
1709 SelectedPermissionOutcome::new(option_id, option_kind),
1710 window,
1711 cx,
1712 );
1713 }
1714
1715 pub fn handle_select_permission_granularity(
1716 &mut self,
1717 action: &SelectPermissionGranularity,
1718 _window: &mut Window,
1719 cx: &mut Context<Self>,
1720 ) {
1721 let tool_call_id = acp::ToolCallId::new(action.tool_call_id.clone());
1722 self.permission_selections
1723 .insert(tool_call_id, PermissionSelection::Choice(action.index));
1724
1725 cx.notify();
1726 }
1727
1728 pub fn handle_toggle_command_pattern(
1729 &mut self,
1730 action: &crate::ToggleCommandPattern,
1731 _window: &mut Window,
1732 cx: &mut Context<Self>,
1733 ) {
1734 let tool_call_id = acp::ToolCallId::new(action.tool_call_id.clone());
1735
1736 match self.permission_selections.get_mut(&tool_call_id) {
1737 Some(PermissionSelection::SelectedPatterns(checked)) => {
1738 // Already in pattern mode — toggle the individual pattern.
1739 if let Some(pos) = checked.iter().position(|&i| i == action.pattern_index) {
1740 checked.swap_remove(pos);
1741 } else {
1742 checked.push(action.pattern_index);
1743 }
1744 }
1745 _ => {
1746 // First click: activate "Select options" with all patterns checked.
1747 let thread = self.thread.read(cx);
1748 let pattern_count = thread
1749 .entries()
1750 .iter()
1751 .find_map(|entry| {
1752 if let AgentThreadEntry::ToolCall(call) = entry {
1753 if call.id == tool_call_id {
1754 if let ToolCallStatus::WaitingForConfirmation { options, .. } =
1755 &call.status
1756 {
1757 if let PermissionOptions::DropdownWithPatterns {
1758 patterns,
1759 ..
1760 } = options
1761 {
1762 return Some(patterns.len());
1763 }
1764 }
1765 }
1766 }
1767 None
1768 })
1769 .unwrap_or(0);
1770 self.permission_selections.insert(
1771 tool_call_id,
1772 PermissionSelection::SelectedPatterns((0..pattern_count).collect()),
1773 );
1774 }
1775 }
1776 cx.notify();
1777 }
1778
1779 fn authorize_pending_with_granularity(
1780 &mut self,
1781 is_allow: bool,
1782 window: &mut Window,
1783 cx: &mut Context<Self>,
1784 ) -> Option<()> {
1785 let (session_id, tool_call_id, options) =
1786 self.conversation.read(cx).pending_tool_call(&self.id, cx)?;
1787 let options = options.clone();
1788 self.authorize_with_granularity(session_id, tool_call_id, &options, is_allow, window, cx)
1789 }
1790
1791 fn authorize_with_granularity(
1792 &mut self,
1793 session_id: acp::SessionId,
1794 tool_call_id: acp::ToolCallId,
1795 options: &PermissionOptions,
1796 is_allow: bool,
1797 window: &mut Window,
1798 cx: &mut Context<Self>,
1799 ) -> Option<()> {
1800 let choices = match options {
1801 PermissionOptions::Dropdown(choices) => choices.as_slice(),
1802 PermissionOptions::DropdownWithPatterns { choices, .. } => choices.as_slice(),
1803 _ => {
1804 let kind = if is_allow {
1805 acp::PermissionOptionKind::AllowOnce
1806 } else {
1807 acp::PermissionOptionKind::RejectOnce
1808 };
1809 return self.authorize_pending_tool_call(kind, window, cx);
1810 }
1811 };
1812
1813 let selection = self.permission_selections.get(&tool_call_id);
1814
1815 // When in per-command pattern mode, use the checked patterns.
1816 if let Some(PermissionSelection::SelectedPatterns(checked)) = selection {
1817 if let Some(outcome) = options.build_outcome_for_checked_patterns(checked, is_allow) {
1818 self.authorize_tool_call(session_id, tool_call_id, outcome, window, cx);
1819 return Some(());
1820 }
1821 }
1822
1823 // Use the selected granularity choice ("Always for terminal" or "Only this time")
1824 let selected_index = selection
1825 .and_then(|s| s.choice_index())
1826 .unwrap_or_else(|| choices.len().saturating_sub(1));
1827
1828 let selected_choice = choices.get(selected_index).or(choices.last())?;
1829 let outcome = selected_choice.build_outcome(is_allow);
1830
1831 self.authorize_tool_call(session_id, tool_call_id, outcome, window, cx);
1832
1833 Some(())
1834 }
1835
1836 // edits
1837
1838 pub fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
1839 let thread = &self.thread;
1840 let telemetry = ActionLogTelemetry::from(thread.read(cx));
1841 let action_log = thread.read(cx).action_log().clone();
1842 action_log.update(cx, |action_log, cx| {
1843 action_log.keep_all_edits(Some(telemetry), cx)
1844 });
1845 }
1846
1847 pub fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
1848 let thread = &self.thread;
1849 let telemetry = ActionLogTelemetry::from(thread.read(cx));
1850 let action_log = thread.read(cx).action_log().clone();
1851 let has_changes = action_log.read(cx).changed_buffers(cx).len() > 0;
1852
1853 action_log
1854 .update(cx, |action_log, cx| {
1855 action_log.reject_all_edits(Some(telemetry), cx)
1856 })
1857 .detach();
1858
1859 if has_changes {
1860 if let Some(workspace) = self.workspace.upgrade() {
1861 workspace.update(cx, |workspace, cx| {
1862 crate::ui::show_undo_reject_toast(workspace, action_log, cx);
1863 });
1864 }
1865 }
1866 }
1867
1868 pub fn undo_last_reject(
1869 &mut self,
1870 _: &UndoLastReject,
1871 _window: &mut Window,
1872 cx: &mut Context<Self>,
1873 ) {
1874 let thread = &self.thread;
1875 let action_log = thread.read(cx).action_log().clone();
1876 action_log
1877 .update(cx, |action_log, cx| action_log.undo_last_reject(cx))
1878 .detach()
1879 }
1880
1881 pub fn open_edited_buffer(
1882 &mut self,
1883 buffer: &Entity<Buffer>,
1884 window: &mut Window,
1885 cx: &mut Context<Self>,
1886 ) {
1887 let thread = &self.thread;
1888
1889 let Some(diff) =
1890 AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
1891 else {
1892 return;
1893 };
1894
1895 diff.update(cx, |diff, cx| {
1896 diff.move_to_path(PathKey::for_buffer(buffer, cx), window, cx)
1897 })
1898 }
1899
1900 // thread stuff
1901
1902 fn share_thread(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1903 let Some((thread, project)) = self.as_native_thread(cx).zip(self.project.upgrade()) else {
1904 return;
1905 };
1906
1907 let client = project.read(cx).client();
1908 let workspace = self.workspace.clone();
1909 let session_id = thread.read(cx).id().to_string();
1910
1911 let load_task = thread.read(cx).to_db(cx);
1912
1913 cx.spawn(async move |_this, cx| {
1914 let db_thread = load_task.await;
1915
1916 let shared_thread = SharedThread::from_db_thread(&db_thread);
1917 let thread_data = shared_thread.to_bytes()?;
1918 let title = shared_thread.title.to_string();
1919
1920 client
1921 .request(proto::ShareAgentThread {
1922 session_id: session_id.clone(),
1923 title,
1924 thread_data,
1925 })
1926 .await?;
1927
1928 let share_url = client::zed_urls::shared_agent_thread_url(&session_id);
1929
1930 cx.update(|cx| {
1931 if let Some(workspace) = workspace.upgrade() {
1932 workspace.update(cx, |workspace, cx| {
1933 struct ThreadSharedToast;
1934 workspace.show_toast(
1935 Toast::new(
1936 NotificationId::unique::<ThreadSharedToast>(),
1937 "Thread shared!",
1938 )
1939 .on_click(
1940 "Copy URL",
1941 move |_window, cx| {
1942 cx.write_to_clipboard(ClipboardItem::new_string(
1943 share_url.clone(),
1944 ));
1945 },
1946 ),
1947 cx,
1948 );
1949 });
1950 }
1951 });
1952
1953 anyhow::Ok(())
1954 })
1955 .detach_and_log_err(cx);
1956 }
1957
1958 pub fn sync_thread(
1959 &mut self,
1960 project: Entity<Project>,
1961 server_view: Entity<ConversationView>,
1962 window: &mut Window,
1963 cx: &mut Context<Self>,
1964 ) {
1965 if !self.is_imported_thread(cx) {
1966 return;
1967 }
1968
1969 let Some(session_list) = self
1970 .as_native_connection(cx)
1971 .and_then(|connection| connection.session_list(cx))
1972 .and_then(|list| list.downcast::<NativeAgentSessionList>())
1973 else {
1974 return;
1975 };
1976 let thread_store = session_list.thread_store().clone();
1977
1978 let client = project.read(cx).client();
1979 let session_id = self.thread.read(cx).session_id().clone();
1980 cx.spawn_in(window, async move |this, cx| {
1981 let response = client
1982 .request(proto::GetSharedAgentThread {
1983 session_id: session_id.to_string(),
1984 })
1985 .await?;
1986
1987 let shared_thread = SharedThread::from_bytes(&response.thread_data)?;
1988
1989 let db_thread = shared_thread.to_db_thread();
1990
1991 thread_store
1992 .update(&mut cx.clone(), |store, cx| {
1993 store.save_thread(session_id.clone(), db_thread, Default::default(), cx)
1994 })
1995 .await?;
1996
1997 server_view.update_in(cx, |server_view, window, cx| server_view.reset(window, cx))?;
1998
1999 this.update_in(cx, |this, _window, cx| {
2000 if let Some(workspace) = this.workspace.upgrade() {
2001 workspace.update(cx, |workspace, cx| {
2002 struct ThreadSyncedToast;
2003 workspace.show_toast(
2004 Toast::new(
2005 NotificationId::unique::<ThreadSyncedToast>(),
2006 "Thread synced with latest version",
2007 )
2008 .autohide(),
2009 cx,
2010 );
2011 });
2012 }
2013 })?;
2014
2015 anyhow::Ok(())
2016 })
2017 .detach_and_log_err(cx);
2018 }
2019
2020 pub fn restore_checkpoint(&mut self, message_id: &UserMessageId, cx: &mut Context<Self>) {
2021 self.thread
2022 .update(cx, |thread, cx| {
2023 thread.restore_checkpoint(message_id.clone(), cx)
2024 })
2025 .detach_and_log_err(cx);
2026 }
2027
2028 pub fn clear_thread_error(&mut self, cx: &mut Context<Self>) {
2029 self.thread_error = None;
2030 self.thread_error_markdown = None;
2031 self.token_limit_callout_dismissed = true;
2032 cx.notify();
2033 }
2034
2035 fn is_following(&self, cx: &App) -> bool {
2036 match self.thread.read(cx).status() {
2037 ThreadStatus::Generating => self
2038 .workspace
2039 .read_with(cx, |workspace, _| {
2040 workspace.is_being_followed(CollaboratorId::Agent)
2041 })
2042 .unwrap_or(false),
2043 _ => self.should_be_following,
2044 }
2045 }
2046
2047 fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2048 let following = self.is_following(cx);
2049
2050 self.should_be_following = !following;
2051 if self.thread.read(cx).status() == ThreadStatus::Generating {
2052 self.workspace
2053 .update(cx, |workspace, cx| {
2054 if following {
2055 workspace.unfollow(CollaboratorId::Agent, window, cx);
2056 } else {
2057 workspace.follow(CollaboratorId::Agent, window, cx);
2058 }
2059 })
2060 .ok();
2061 }
2062
2063 telemetry::event!("Follow Agent Selected", following = !following);
2064 }
2065
2066 // other
2067
2068 pub fn render_thread_retry_status_callout(&self) -> Option<Callout> {
2069 let state = self.thread_retry_status.as_ref()?;
2070
2071 let next_attempt_in = state
2072 .duration
2073 .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
2074 if next_attempt_in.is_zero() {
2075 return None;
2076 }
2077
2078 let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
2079
2080 let retry_message = if state.max_attempts == 1 {
2081 if next_attempt_in_secs == 1 {
2082 "Retrying. Next attempt in 1 second.".to_string()
2083 } else {
2084 format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
2085 }
2086 } else if next_attempt_in_secs == 1 {
2087 format!(
2088 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
2089 state.attempt, state.max_attempts,
2090 )
2091 } else {
2092 format!(
2093 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
2094 state.attempt, state.max_attempts,
2095 )
2096 };
2097
2098 Some(
2099 Callout::new()
2100 .icon(IconName::Warning)
2101 .severity(Severity::Warning)
2102 .title(state.last_error.clone())
2103 .description(retry_message),
2104 )
2105 }
2106
2107 pub fn handle_open_rules(
2108 &mut self,
2109 _: &ClickEvent,
2110 window: &mut Window,
2111 cx: &mut Context<Self>,
2112 ) {
2113 let Some(thread) = self.as_native_thread(cx) else {
2114 return;
2115 };
2116 let project_context = thread.read(cx).project_context().read(cx);
2117
2118 let project_entry_ids = project_context
2119 .worktrees
2120 .iter()
2121 .flat_map(|worktree| worktree.rules_file.as_ref())
2122 .map(|rules_file| ProjectEntryId::from_usize(rules_file.project_entry_id))
2123 .collect::<Vec<_>>();
2124
2125 self.workspace
2126 .update(cx, move |workspace, cx| {
2127 // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
2128 // files clear. For example, if rules file 1 is already open but rules file 2 is not,
2129 // this would open and focus rules file 2 in a tab that is not next to rules file 1.
2130 let project = workspace.project().read(cx);
2131 let project_paths = project_entry_ids
2132 .into_iter()
2133 .flat_map(|entry_id| project.path_for_entry(entry_id, cx))
2134 .collect::<Vec<_>>();
2135 for project_path in project_paths {
2136 workspace
2137 .open_path(project_path, None, true, window, cx)
2138 .detach_and_log_err(cx);
2139 }
2140 })
2141 .ok();
2142 }
2143
2144 fn activity_bar_bg(&self, cx: &Context<Self>) -> Hsla {
2145 let editor_bg_color = cx.theme().colors().editor_background;
2146 let active_color = cx.theme().colors().element_selected;
2147 editor_bg_color.blend(active_color.opacity(0.3))
2148 }
2149
2150 pub fn render_activity_bar(
2151 &self,
2152 window: &mut Window,
2153 cx: &Context<Self>,
2154 ) -> Option<AnyElement> {
2155 let thread = self.thread.read(cx);
2156 let action_log = thread.action_log();
2157 let telemetry = ActionLogTelemetry::from(thread);
2158 let changed_buffers = action_log.read(cx).changed_buffers(cx);
2159 let plan = thread.plan();
2160 let queue_is_empty = !self.has_queued_messages();
2161
2162 let subagents_awaiting_permission = self.render_subagents_awaiting_permission(cx);
2163 let has_subagents_awaiting = subagents_awaiting_permission.is_some();
2164
2165 if changed_buffers.is_empty()
2166 && plan.is_empty()
2167 && queue_is_empty
2168 && !has_subagents_awaiting
2169 {
2170 return None;
2171 }
2172
2173 // Temporarily always enable ACP edit controls. This is temporary, to lessen the
2174 // impact of a nasty bug that causes them to sometimes be disabled when they shouldn't
2175 // be, which blocks you from being able to accept or reject edits. This switches the
2176 // bug to be that sometimes it's enabled when it shouldn't be, which at least doesn't
2177 // block you from using the panel.
2178 let pending_edits = false;
2179
2180 let plan_expanded = self.plan_expanded;
2181 let edits_expanded = self.edits_expanded;
2182 let queue_expanded = self.queue_expanded;
2183
2184 v_flex()
2185 .mx_2()
2186 .bg(self.activity_bar_bg(cx))
2187 .border_1()
2188 .border_b_0()
2189 .border_color(cx.theme().colors().border)
2190 .rounded_t_md()
2191 .shadow(vec![gpui::BoxShadow {
2192 color: gpui::black().opacity(0.12),
2193 offset: point(px(1.), px(-1.)),
2194 blur_radius: px(2.),
2195 spread_radius: px(0.),
2196 }])
2197 .when_some(subagents_awaiting_permission, |this, element| {
2198 this.child(element)
2199 })
2200 .when(
2201 has_subagents_awaiting
2202 && (!plan.is_empty() || !changed_buffers.is_empty() || !queue_is_empty),
2203 |this| this.child(Divider::horizontal().color(DividerColor::Border)),
2204 )
2205 .when(!plan.is_empty(), |this| {
2206 this.child(self.render_plan_summary(plan, window, cx))
2207 .when(plan_expanded, |parent| {
2208 parent.child(self.render_plan_entries(plan, window, cx))
2209 })
2210 })
2211 .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
2212 this.child(Divider::horizontal().color(DividerColor::Border))
2213 })
2214 .when(
2215 !changed_buffers.is_empty() && thread.parent_session_id().is_none(),
2216 |this| {
2217 this.child(self.render_edits_summary(
2218 &changed_buffers,
2219 edits_expanded,
2220 pending_edits,
2221 cx,
2222 ))
2223 .when(edits_expanded, |parent| {
2224 parent.child(self.render_edited_files(
2225 action_log,
2226 telemetry.clone(),
2227 &changed_buffers,
2228 pending_edits,
2229 cx,
2230 ))
2231 })
2232 },
2233 )
2234 .when(!queue_is_empty, |this| {
2235 this.when(!plan.is_empty() || !changed_buffers.is_empty(), |this| {
2236 this.child(Divider::horizontal().color(DividerColor::Border))
2237 })
2238 .child(self.render_message_queue_summary(window, cx))
2239 .when(queue_expanded, |parent| {
2240 parent.child(self.render_message_queue_entries(window, cx))
2241 })
2242 })
2243 .into_any()
2244 .into()
2245 }
2246
2247 fn render_edited_files(
2248 &self,
2249 action_log: &Entity<ActionLog>,
2250 telemetry: ActionLogTelemetry,
2251 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
2252 pending_edits: bool,
2253 cx: &Context<Self>,
2254 ) -> impl IntoElement {
2255 let editor_bg_color = cx.theme().colors().editor_background;
2256
2257 // Sort edited files alphabetically for consistency with Git diff view
2258 let mut sorted_buffers: Vec<_> = changed_buffers.iter().collect();
2259 sorted_buffers.sort_by(|(buffer_a, _), (buffer_b, _)| {
2260 let path_a = buffer_a.read(cx).file().map(|f| f.path().clone());
2261 let path_b = buffer_b.read(cx).file().map(|f| f.path().clone());
2262 path_a.cmp(&path_b)
2263 });
2264
2265 v_flex()
2266 .id("edited_files_list")
2267 .max_h_40()
2268 .overflow_y_scroll()
2269 .children(
2270 sorted_buffers
2271 .into_iter()
2272 .enumerate()
2273 .flat_map(|(index, (buffer, diff))| {
2274 let file = buffer.read(cx).file()?;
2275 let path = file.path();
2276 let path_style = file.path_style(cx);
2277 let separator = file.path_style(cx).primary_separator();
2278
2279 let file_path = path.parent().and_then(|parent| {
2280 if parent.is_empty() {
2281 None
2282 } else {
2283 Some(
2284 Label::new(format!(
2285 "{}{separator}",
2286 parent.display(path_style)
2287 ))
2288 .color(Color::Muted)
2289 .size(LabelSize::XSmall)
2290 .buffer_font(cx),
2291 )
2292 }
2293 });
2294
2295 let file_name = path.file_name().map(|name| {
2296 Label::new(name.to_string())
2297 .size(LabelSize::XSmall)
2298 .buffer_font(cx)
2299 .ml_1()
2300 });
2301
2302 let full_path = path.display(path_style).to_string();
2303
2304 let file_icon = FileIcons::get_icon(path.as_std_path(), cx)
2305 .map(Icon::from_path)
2306 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
2307 .unwrap_or_else(|| {
2308 Icon::new(IconName::File)
2309 .color(Color::Muted)
2310 .size(IconSize::Small)
2311 });
2312
2313 let file_stats = DiffStats::single_file(buffer.read(cx), diff.read(cx), cx);
2314
2315 let buttons = self.render_edited_files_buttons(
2316 index,
2317 buffer,
2318 action_log,
2319 &telemetry,
2320 pending_edits,
2321 editor_bg_color,
2322 cx,
2323 );
2324
2325 let element = h_flex()
2326 .group("edited-code")
2327 .id(("file-container", index))
2328 .relative()
2329 .min_w_0()
2330 .p_1p5()
2331 .gap_2()
2332 .justify_between()
2333 .bg(editor_bg_color)
2334 .when(index < changed_buffers.len() - 1, |parent| {
2335 parent.border_color(cx.theme().colors().border).border_b_1()
2336 })
2337 .child(
2338 h_flex()
2339 .id(("file-name-path", index))
2340 .cursor_pointer()
2341 .pr_0p5()
2342 .gap_0p5()
2343 .rounded_xs()
2344 .child(file_icon)
2345 .children(file_name)
2346 .children(file_path)
2347 .child(
2348 DiffStat::new(
2349 "file",
2350 file_stats.lines_added as usize,
2351 file_stats.lines_removed as usize,
2352 )
2353 .label_size(LabelSize::XSmall),
2354 )
2355 .hover(|s| s.bg(cx.theme().colors().element_hover))
2356 .tooltip({
2357 move |_, cx| {
2358 Tooltip::with_meta(
2359 "Go to File",
2360 None,
2361 full_path.clone(),
2362 cx,
2363 )
2364 }
2365 })
2366 .on_click({
2367 let buffer = buffer.clone();
2368 cx.listener(move |this, _, window, cx| {
2369 this.open_edited_buffer(&buffer, window, cx);
2370 })
2371 }),
2372 )
2373 .child(buttons);
2374
2375 Some(element)
2376 }),
2377 )
2378 .into_any_element()
2379 }
2380
2381 fn render_edited_files_buttons(
2382 &self,
2383 index: usize,
2384 buffer: &Entity<Buffer>,
2385 action_log: &Entity<ActionLog>,
2386 telemetry: &ActionLogTelemetry,
2387 pending_edits: bool,
2388 editor_bg_color: Hsla,
2389 cx: &Context<Self>,
2390 ) -> impl IntoElement {
2391 h_flex()
2392 .id("edited-buttons-container")
2393 .visible_on_hover("edited-code")
2394 .absolute()
2395 .right_0()
2396 .px_1()
2397 .gap_1()
2398 .bg(editor_bg_color)
2399 .on_hover(cx.listener(move |this, is_hovered, _window, cx| {
2400 if *is_hovered {
2401 this.hovered_edited_file_buttons = Some(index);
2402 } else if this.hovered_edited_file_buttons == Some(index) {
2403 this.hovered_edited_file_buttons = None;
2404 }
2405 cx.notify();
2406 }))
2407 .child(
2408 Button::new("review", "Review")
2409 .label_size(LabelSize::Small)
2410 .on_click({
2411 let buffer = buffer.clone();
2412 cx.listener(move |this, _, window, cx| {
2413 this.open_edited_buffer(&buffer, window, cx);
2414 })
2415 }),
2416 )
2417 .child(
2418 Button::new(("reject-file", index), "Reject")
2419 .label_size(LabelSize::Small)
2420 .disabled(pending_edits)
2421 .on_click({
2422 let buffer = buffer.clone();
2423 let action_log = action_log.clone();
2424 let telemetry = telemetry.clone();
2425 move |_, _, cx| {
2426 action_log.update(cx, |action_log, cx| {
2427 action_log
2428 .reject_edits_in_ranges(
2429 buffer.clone(),
2430 vec![Anchor::min_max_range_for_buffer(
2431 buffer.read(cx).remote_id(),
2432 )],
2433 Some(telemetry.clone()),
2434 cx,
2435 )
2436 .0
2437 .detach_and_log_err(cx);
2438 })
2439 }
2440 }),
2441 )
2442 .child(
2443 Button::new(("keep-file", index), "Keep")
2444 .label_size(LabelSize::Small)
2445 .disabled(pending_edits)
2446 .on_click({
2447 let buffer = buffer.clone();
2448 let action_log = action_log.clone();
2449 let telemetry = telemetry.clone();
2450 move |_, _, cx| {
2451 action_log.update(cx, |action_log, cx| {
2452 action_log.keep_edits_in_range(
2453 buffer.clone(),
2454 Anchor::min_max_range_for_buffer(buffer.read(cx).remote_id()),
2455 Some(telemetry.clone()),
2456 cx,
2457 );
2458 })
2459 }
2460 }),
2461 )
2462 }
2463
2464 fn render_subagents_awaiting_permission(&self, cx: &Context<Self>) -> Option<AnyElement> {
2465 let awaiting = self.conversation.read(cx).subagents_awaiting_permission(cx);
2466
2467 if awaiting.is_empty() {
2468 return None;
2469 }
2470
2471 let thread = self.thread.read(cx);
2472 let entries = thread.entries();
2473 let mut subagent_items: Vec<(SharedString, usize)> = Vec::new();
2474
2475 for (session_id, _) in &awaiting {
2476 for (entry_ix, entry) in entries.iter().enumerate() {
2477 if let AgentThreadEntry::ToolCall(tool_call) = entry {
2478 if let Some(info) = &tool_call.subagent_session_info {
2479 if &info.session_id == session_id {
2480 let subagent_summary: SharedString = {
2481 let summary_text = tool_call.label.read(cx).source().to_string();
2482 if !summary_text.is_empty() {
2483 summary_text.into()
2484 } else {
2485 "Subagent".into()
2486 }
2487 };
2488 subagent_items.push((subagent_summary, entry_ix));
2489 break;
2490 }
2491 }
2492 }
2493 }
2494 }
2495
2496 if subagent_items.is_empty() {
2497 return None;
2498 }
2499
2500 let item_count = subagent_items.len();
2501
2502 Some(
2503 v_flex()
2504 .child(
2505 h_flex()
2506 .py_1()
2507 .px_2()
2508 .w_full()
2509 .gap_1()
2510 .border_b_1()
2511 .border_color(cx.theme().colors().border)
2512 .child(
2513 Label::new("Subagents Awaiting Permission:")
2514 .size(LabelSize::Small)
2515 .color(Color::Muted),
2516 )
2517 .child(Label::new(item_count.to_string()).size(LabelSize::Small)),
2518 )
2519 .child(
2520 v_flex().children(subagent_items.into_iter().enumerate().map(
2521 |(ix, (label, entry_ix))| {
2522 let is_last = ix == item_count - 1;
2523 let group = format!("group-{}", entry_ix);
2524
2525 h_flex()
2526 .cursor_pointer()
2527 .id(format!("subagent-permission-{}", entry_ix))
2528 .group(&group)
2529 .p_1()
2530 .pl_2()
2531 .min_w_0()
2532 .w_full()
2533 .gap_1()
2534 .justify_between()
2535 .bg(cx.theme().colors().editor_background)
2536 .hover(|s| s.bg(cx.theme().colors().element_hover))
2537 .when(!is_last, |this| {
2538 this.border_b_1().border_color(cx.theme().colors().border)
2539 })
2540 .child(
2541 h_flex()
2542 .gap_1p5()
2543 .child(
2544 Icon::new(IconName::Circle)
2545 .size(IconSize::XSmall)
2546 .color(Color::Warning),
2547 )
2548 .child(
2549 Label::new(label)
2550 .size(LabelSize::Small)
2551 .color(Color::Muted)
2552 .truncate(),
2553 ),
2554 )
2555 .child(
2556 div().visible_on_hover(&group).child(
2557 Label::new("Scroll to Subagent")
2558 .size(LabelSize::Small)
2559 .color(Color::Muted)
2560 .truncate(),
2561 ),
2562 )
2563 .on_click(cx.listener(move |this, _, _, cx| {
2564 this.list_state.scroll_to(ListOffset {
2565 item_ix: entry_ix,
2566 offset_in_item: px(0.0),
2567 });
2568 cx.notify();
2569 }))
2570 },
2571 )),
2572 )
2573 .into_any(),
2574 )
2575 }
2576
2577 fn render_message_queue_summary(
2578 &self,
2579 _window: &mut Window,
2580 cx: &Context<Self>,
2581 ) -> impl IntoElement {
2582 let queue_count = self.local_queued_messages.len();
2583 let title: SharedString = if queue_count == 1 {
2584 "1 Queued Message".into()
2585 } else {
2586 format!("{} Queued Messages", queue_count).into()
2587 };
2588
2589 h_flex()
2590 .p_1()
2591 .w_full()
2592 .gap_1()
2593 .justify_between()
2594 .when(self.queue_expanded, |this| {
2595 this.border_b_1().border_color(cx.theme().colors().border)
2596 })
2597 .child(
2598 h_flex()
2599 .id("queue_summary")
2600 .gap_1()
2601 .child(Disclosure::new("queue_disclosure", self.queue_expanded))
2602 .child(Label::new(title).size(LabelSize::Small).color(Color::Muted))
2603 .on_click(cx.listener(|this, _, _, cx| {
2604 this.queue_expanded = !this.queue_expanded;
2605 cx.notify();
2606 })),
2607 )
2608 .child(
2609 Button::new("clear_queue", "Clear All")
2610 .label_size(LabelSize::Small)
2611 .key_binding(
2612 KeyBinding::for_action(&ClearMessageQueue, cx)
2613 .map(|kb| kb.size(rems_from_px(12.))),
2614 )
2615 .on_click(cx.listener(|this, _, _, cx| {
2616 this.clear_queue(cx);
2617 this.can_fast_track_queue = false;
2618 cx.notify();
2619 })),
2620 )
2621 .into_any_element()
2622 }
2623
2624 fn clear_queue(&mut self, cx: &mut Context<Self>) {
2625 self.local_queued_messages.clear();
2626 self.sync_queue_flag_to_native_thread(cx);
2627 }
2628
2629 fn render_plan_summary(
2630 &self,
2631 plan: &Plan,
2632 window: &mut Window,
2633 cx: &Context<Self>,
2634 ) -> impl IntoElement {
2635 let plan_expanded = self.plan_expanded;
2636 let stats = plan.stats();
2637
2638 let title = if let Some(entry) = stats.in_progress_entry
2639 && !plan_expanded
2640 {
2641 h_flex()
2642 .cursor_default()
2643 .relative()
2644 .w_full()
2645 .gap_1()
2646 .truncate()
2647 .child(
2648 Label::new("Current:")
2649 .size(LabelSize::Small)
2650 .color(Color::Muted),
2651 )
2652 .child(
2653 div()
2654 .text_xs()
2655 .text_color(cx.theme().colors().text_muted)
2656 .line_clamp(1)
2657 .child(MarkdownElement::new(
2658 entry.content.clone(),
2659 plan_label_markdown_style(&entry.status, window, cx),
2660 )),
2661 )
2662 .when(stats.pending > 0, |this| {
2663 this.child(
2664 h_flex()
2665 .absolute()
2666 .top_0()
2667 .right_0()
2668 .h_full()
2669 .child(div().min_w_8().h_full().bg(linear_gradient(
2670 90.,
2671 linear_color_stop(self.activity_bar_bg(cx), 1.),
2672 linear_color_stop(self.activity_bar_bg(cx).opacity(0.2), 0.),
2673 )))
2674 .child(
2675 div().pr_0p5().bg(self.activity_bar_bg(cx)).child(
2676 Label::new(format!("{} left", stats.pending))
2677 .size(LabelSize::Small)
2678 .color(Color::Muted),
2679 ),
2680 ),
2681 )
2682 })
2683 } else {
2684 let status_label = if stats.pending == 0 {
2685 "All Done".to_string()
2686 } else if stats.completed == 0 {
2687 format!("{} Tasks", plan.entries.len())
2688 } else {
2689 format!("{}/{}", stats.completed, plan.entries.len())
2690 };
2691
2692 h_flex()
2693 .w_full()
2694 .gap_1()
2695 .justify_between()
2696 .child(
2697 Label::new("Plan")
2698 .size(LabelSize::Small)
2699 .color(Color::Muted),
2700 )
2701 .child(
2702 Label::new(status_label)
2703 .size(LabelSize::Small)
2704 .color(Color::Muted)
2705 .mr_1(),
2706 )
2707 };
2708
2709 h_flex()
2710 .id("plan_summary")
2711 .p_1()
2712 .w_full()
2713 .gap_1()
2714 .when(plan_expanded, |this| {
2715 this.border_b_1().border_color(cx.theme().colors().border)
2716 })
2717 .child(Disclosure::new("plan_disclosure", plan_expanded))
2718 .child(title.flex_1())
2719 .child(
2720 IconButton::new("dismiss-plan", IconName::Close)
2721 .icon_size(IconSize::XSmall)
2722 .shape(ui::IconButtonShape::Square)
2723 .tooltip(Tooltip::text("Clear plan"))
2724 .on_click(cx.listener(|this, _, _, cx| {
2725 this.thread.update(cx, |thread, cx| thread.clear_plan(cx));
2726 cx.stop_propagation();
2727 })),
2728 )
2729 .on_click(cx.listener(|this, _, _, cx| {
2730 this.plan_expanded = !this.plan_expanded;
2731 cx.notify();
2732 }))
2733 .into_any_element()
2734 }
2735
2736 fn render_plan_entries(
2737 &self,
2738 plan: &Plan,
2739 window: &mut Window,
2740 cx: &Context<Self>,
2741 ) -> impl IntoElement {
2742 v_flex()
2743 .id("plan_items_list")
2744 .max_h_40()
2745 .overflow_y_scroll()
2746 .children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
2747 let element = h_flex()
2748 .py_1()
2749 .px_2()
2750 .gap_2()
2751 .justify_between()
2752 .bg(cx.theme().colors().editor_background)
2753 .when(index < plan.entries.len() - 1, |parent| {
2754 parent.border_color(cx.theme().colors().border).border_b_1()
2755 })
2756 .child(
2757 h_flex()
2758 .id(("plan_entry", index))
2759 .gap_1p5()
2760 .max_w_full()
2761 .overflow_x_scroll()
2762 .text_xs()
2763 .text_color(cx.theme().colors().text_muted)
2764 .child(match entry.status {
2765 acp::PlanEntryStatus::InProgress => {
2766 Icon::new(IconName::TodoProgress)
2767 .size(IconSize::Small)
2768 .color(Color::Accent)
2769 .with_rotate_animation(2)
2770 .into_any_element()
2771 }
2772 acp::PlanEntryStatus::Completed => {
2773 Icon::new(IconName::TodoComplete)
2774 .size(IconSize::Small)
2775 .color(Color::Success)
2776 .into_any_element()
2777 }
2778 acp::PlanEntryStatus::Pending | _ => {
2779 Icon::new(IconName::TodoPending)
2780 .size(IconSize::Small)
2781 .color(Color::Muted)
2782 .into_any_element()
2783 }
2784 })
2785 .child(MarkdownElement::new(
2786 entry.content.clone(),
2787 plan_label_markdown_style(&entry.status, window, cx),
2788 )),
2789 );
2790
2791 Some(element)
2792 }))
2793 .into_any_element()
2794 }
2795
2796 fn render_completed_plan(
2797 &self,
2798 entries: &[PlanEntry],
2799 window: &Window,
2800 cx: &Context<Self>,
2801 ) -> AnyElement {
2802 v_flex()
2803 .px_5()
2804 .py_1p5()
2805 .w_full()
2806 .child(
2807 v_flex()
2808 .w_full()
2809 .rounded_md()
2810 .border_1()
2811 .border_color(self.tool_card_border_color(cx))
2812 .child(
2813 h_flex()
2814 .px_2()
2815 .py_1()
2816 .gap_1()
2817 .bg(self.tool_card_header_bg(cx))
2818 .border_b_1()
2819 .border_color(self.tool_card_border_color(cx))
2820 .child(
2821 Label::new("Completed Plan")
2822 .size(LabelSize::Small)
2823 .color(Color::Muted),
2824 )
2825 .child(
2826 Label::new(format!(
2827 "— {} {}",
2828 entries.len(),
2829 if entries.len() == 1 { "step" } else { "steps" }
2830 ))
2831 .size(LabelSize::Small)
2832 .color(Color::Muted),
2833 ),
2834 )
2835 .child(
2836 v_flex().children(entries.iter().enumerate().map(|(index, entry)| {
2837 h_flex()
2838 .py_1()
2839 .px_2()
2840 .gap_1p5()
2841 .when(index < entries.len() - 1, |this| {
2842 this.border_b_1().border_color(cx.theme().colors().border)
2843 })
2844 .child(
2845 Icon::new(IconName::TodoComplete)
2846 .size(IconSize::Small)
2847 .color(Color::Success),
2848 )
2849 .child(
2850 div()
2851 .max_w_full()
2852 .overflow_x_hidden()
2853 .text_xs()
2854 .text_color(cx.theme().colors().text_muted)
2855 .child(MarkdownElement::new(
2856 entry.content.clone(),
2857 default_markdown_style(window, cx),
2858 )),
2859 )
2860 })),
2861 ),
2862 )
2863 .into_any()
2864 }
2865
2866 fn render_edits_summary(
2867 &self,
2868 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
2869 expanded: bool,
2870 pending_edits: bool,
2871 cx: &Context<Self>,
2872 ) -> Div {
2873 const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
2874
2875 let focus_handle = self.focus_handle(cx);
2876
2877 h_flex()
2878 .p_1()
2879 .justify_between()
2880 .flex_wrap()
2881 .when(expanded, |this| {
2882 this.border_b_1().border_color(cx.theme().colors().border)
2883 })
2884 .child(
2885 h_flex()
2886 .id("edits-container")
2887 .cursor_pointer()
2888 .gap_1()
2889 .child(Disclosure::new("edits-disclosure", expanded))
2890 .map(|this| {
2891 if pending_edits {
2892 this.child(
2893 Label::new(format!(
2894 "Editing {} {}…",
2895 changed_buffers.len(),
2896 if changed_buffers.len() == 1 {
2897 "file"
2898 } else {
2899 "files"
2900 }
2901 ))
2902 .color(Color::Muted)
2903 .size(LabelSize::Small)
2904 .with_animation(
2905 "edit-label",
2906 Animation::new(Duration::from_secs(2))
2907 .repeat()
2908 .with_easing(pulsating_between(0.3, 0.7)),
2909 |label, delta| label.alpha(delta),
2910 ),
2911 )
2912 } else {
2913 let stats = DiffStats::all_files(changed_buffers, cx);
2914 let dot_divider = || {
2915 Label::new("•")
2916 .size(LabelSize::XSmall)
2917 .color(Color::Disabled)
2918 };
2919
2920 this.child(
2921 Label::new("Edits")
2922 .size(LabelSize::Small)
2923 .color(Color::Muted),
2924 )
2925 .child(dot_divider())
2926 .child(
2927 Label::new(format!(
2928 "{} {}",
2929 changed_buffers.len(),
2930 if changed_buffers.len() == 1 {
2931 "file"
2932 } else {
2933 "files"
2934 }
2935 ))
2936 .size(LabelSize::Small)
2937 .color(Color::Muted),
2938 )
2939 .child(dot_divider())
2940 .child(DiffStat::new(
2941 "total",
2942 stats.lines_added as usize,
2943 stats.lines_removed as usize,
2944 ))
2945 }
2946 })
2947 .on_click(cx.listener(|this, _, _, cx| {
2948 this.edits_expanded = !this.edits_expanded;
2949 cx.notify();
2950 })),
2951 )
2952 .child(
2953 h_flex()
2954 .gap_1()
2955 .child(
2956 IconButton::new("review-changes", IconName::ListTodo)
2957 .icon_size(IconSize::Small)
2958 .tooltip({
2959 let focus_handle = focus_handle.clone();
2960 move |_window, cx| {
2961 Tooltip::for_action_in(
2962 "Review Changes",
2963 &OpenAgentDiff,
2964 &focus_handle,
2965 cx,
2966 )
2967 }
2968 })
2969 .on_click(cx.listener(|_, _, window, cx| {
2970 window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
2971 })),
2972 )
2973 .child(Divider::vertical().color(DividerColor::Border))
2974 .child(
2975 Button::new("reject-all-changes", "Reject All")
2976 .label_size(LabelSize::Small)
2977 .disabled(pending_edits)
2978 .when(pending_edits, |this| {
2979 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
2980 })
2981 .key_binding(
2982 KeyBinding::for_action_in(&RejectAll, &focus_handle.clone(), cx)
2983 .map(|kb| kb.size(rems_from_px(12.))),
2984 )
2985 .on_click(cx.listener(move |this, _, window, cx| {
2986 this.reject_all(&RejectAll, window, cx);
2987 })),
2988 )
2989 .child(
2990 Button::new("keep-all-changes", "Keep All")
2991 .label_size(LabelSize::Small)
2992 .disabled(pending_edits)
2993 .when(pending_edits, |this| {
2994 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
2995 })
2996 .key_binding(
2997 KeyBinding::for_action_in(&KeepAll, &focus_handle, cx)
2998 .map(|kb| kb.size(rems_from_px(12.))),
2999 )
3000 .on_click(cx.listener(move |this, _, window, cx| {
3001 this.keep_all(&KeepAll, window, cx);
3002 })),
3003 ),
3004 )
3005 }
3006
3007 fn is_subagent_canceled_or_failed(&self, cx: &App) -> bool {
3008 let Some(parent_session_id) = self.parent_id.as_ref() else {
3009 return false;
3010 };
3011
3012 let my_session_id = self.thread.read(cx).session_id().clone();
3013
3014 self.server_view
3015 .upgrade()
3016 .and_then(|sv| sv.read(cx).thread_view(parent_session_id))
3017 .is_some_and(|parent_view| {
3018 parent_view
3019 .read(cx)
3020 .thread
3021 .read(cx)
3022 .tool_call_for_subagent(&my_session_id)
3023 .is_some_and(|tc| {
3024 matches!(
3025 tc.status,
3026 ToolCallStatus::Canceled
3027 | ToolCallStatus::Failed
3028 | ToolCallStatus::Rejected
3029 )
3030 })
3031 })
3032 }
3033
3034 pub(crate) fn render_subagent_titlebar(&mut self, cx: &mut Context<Self>) -> Option<Div> {
3035 let Some(parent_session_id) = self.parent_id.clone() else {
3036 return None;
3037 };
3038
3039 let server_view = self.server_view.clone();
3040 let thread = self.thread.clone();
3041 let is_done = thread.read(cx).status() == ThreadStatus::Idle;
3042 let is_canceled_or_failed = self.is_subagent_canceled_or_failed(cx);
3043
3044 Some(
3045 h_flex()
3046 .h(Tab::container_height(cx))
3047 .pl_2()
3048 .pr_1p5()
3049 .w_full()
3050 .justify_between()
3051 .gap_1()
3052 .border_b_1()
3053 .when(is_done && is_canceled_or_failed, |this| {
3054 this.border_dashed()
3055 })
3056 .border_color(cx.theme().colors().border)
3057 .bg(cx.theme().colors().editor_background.opacity(0.2))
3058 .child(
3059 h_flex()
3060 .flex_1()
3061 .gap_2()
3062 .child(
3063 Icon::new(IconName::ForwardArrowUp)
3064 .size(IconSize::Small)
3065 .color(Color::Muted),
3066 )
3067 .child(self.title_editor.clone())
3068 .when(is_done && is_canceled_or_failed, |this| {
3069 this.child(Icon::new(IconName::Close).color(Color::Error))
3070 })
3071 .when(is_done && !is_canceled_or_failed, |this| {
3072 this.child(Icon::new(IconName::Check).color(Color::Success))
3073 }),
3074 )
3075 .child(
3076 h_flex()
3077 .gap_0p5()
3078 .when(!is_done, |this| {
3079 this.child(
3080 IconButton::new("stop_subagent", IconName::Stop)
3081 .icon_size(IconSize::Small)
3082 .icon_color(Color::Error)
3083 .tooltip(Tooltip::text("Stop Subagent"))
3084 .on_click(move |_, _, cx| {
3085 thread.update(cx, |thread, cx| {
3086 thread.cancel(cx).detach();
3087 });
3088 }),
3089 )
3090 })
3091 .child(
3092 IconButton::new("minimize_subagent", IconName::Minimize)
3093 .icon_size(IconSize::Small)
3094 .tooltip(Tooltip::text("Minimize Subagent"))
3095 .on_click(move |_, window, cx| {
3096 let _ = server_view.update(cx, |server_view, cx| {
3097 server_view.navigate_to_session(
3098 parent_session_id.clone(),
3099 window,
3100 cx,
3101 );
3102 });
3103 }),
3104 ),
3105 ),
3106 )
3107 }
3108
3109 pub(crate) fn render_message_editor(
3110 &mut self,
3111 window: &mut Window,
3112 cx: &mut Context<Self>,
3113 ) -> AnyElement {
3114 if self.is_subagent() {
3115 return div().into_any_element();
3116 }
3117
3118 let focus_handle = self.message_editor.focus_handle(cx);
3119 let editor_bg_color = cx.theme().colors().editor_background;
3120 let editor_expanded = self.editor_expanded;
3121 let has_messages = self.list_state.item_count() > 0;
3122 let v2_empty_state = cx.has_flag::<AgentV2FeatureFlag>() && !has_messages;
3123 let (expand_icon, expand_tooltip) = if editor_expanded {
3124 (IconName::Minimize, "Minimize Message Editor")
3125 } else {
3126 (IconName::Maximize, "Expand Message Editor")
3127 };
3128
3129 v_flex()
3130 .on_action(cx.listener(Self::expand_message_editor))
3131 .p_2()
3132 .gap_2()
3133 .when(!v2_empty_state, |this| {
3134 this.border_t_1().border_color(cx.theme().colors().border)
3135 })
3136 .bg(editor_bg_color)
3137 .when(v2_empty_state, |this| this.flex_1().size_full())
3138 .when(editor_expanded && !v2_empty_state, |this| {
3139 this.h(vh(0.8, window)).size_full().justify_between()
3140 })
3141 .child(
3142 v_flex()
3143 .relative()
3144 .size_full()
3145 .when(v2_empty_state, |this| this.flex_1())
3146 .pt_1()
3147 .pr_2p5()
3148 .child(self.message_editor.clone())
3149 .when(!v2_empty_state, |this| {
3150 this.child(
3151 h_flex()
3152 .absolute()
3153 .top_0()
3154 .right_0()
3155 .opacity(0.5)
3156 .hover(|this| this.opacity(1.0))
3157 .child(
3158 IconButton::new("toggle-height", expand_icon)
3159 .icon_size(IconSize::Small)
3160 .icon_color(Color::Muted)
3161 .tooltip({
3162 move |_window, cx| {
3163 Tooltip::for_action_in(
3164 expand_tooltip,
3165 &ExpandMessageEditor,
3166 &focus_handle,
3167 cx,
3168 )
3169 }
3170 })
3171 .on_click(cx.listener(|this, _, window, cx| {
3172 this.expand_message_editor(
3173 &ExpandMessageEditor,
3174 window,
3175 cx,
3176 );
3177 })),
3178 ),
3179 )
3180 }),
3181 )
3182 .child(
3183 h_flex()
3184 .flex_none()
3185 .flex_wrap()
3186 .justify_between()
3187 .child(
3188 h_flex()
3189 .gap_0p5()
3190 .child(self.render_add_context_button(cx))
3191 .child(self.render_follow_toggle(cx))
3192 .children(self.render_fast_mode_control(cx))
3193 .children(self.render_thinking_control(cx)),
3194 )
3195 .child(
3196 h_flex()
3197 .gap_1()
3198 .children(self.render_token_usage(cx))
3199 .children(self.profile_selector.clone())
3200 .map(|this| {
3201 // Either config_options_view OR (mode_selector + model_selector)
3202 match self.config_options_view.clone() {
3203 Some(config_view) => this.child(config_view),
3204 None => this
3205 .children(self.mode_selector.clone())
3206 .children(self.model_selector.clone()),
3207 }
3208 })
3209 .child(self.render_send_button(cx)),
3210 ),
3211 )
3212 .into_any()
3213 }
3214
3215 fn render_message_queue_entries(
3216 &self,
3217 _window: &mut Window,
3218 cx: &Context<Self>,
3219 ) -> impl IntoElement {
3220 let message_editor = self.message_editor.read(cx);
3221 let focus_handle = message_editor.focus_handle(cx);
3222
3223 let queued_message_editors = &self.queued_message_editors;
3224 let queue_len = queued_message_editors.len();
3225 let can_fast_track = self.can_fast_track_queue && queue_len > 0;
3226
3227 v_flex()
3228 .id("message_queue_list")
3229 .max_h_40()
3230 .overflow_y_scroll()
3231 .children(
3232 queued_message_editors
3233 .iter()
3234 .enumerate()
3235 .map(|(index, editor)| {
3236 let is_next = index == 0;
3237 let (icon_color, tooltip_text) = if is_next {
3238 (Color::Accent, "Next in Queue")
3239 } else {
3240 (Color::Muted, "In Queue")
3241 };
3242
3243 let editor_focused = editor.focus_handle(cx).is_focused(_window);
3244 let keybinding_size = rems_from_px(12.);
3245
3246 h_flex()
3247 .group("queue_entry")
3248 .w_full()
3249 .p_1p5()
3250 .gap_1()
3251 .bg(cx.theme().colors().editor_background)
3252 .when(index < queue_len - 1, |this| {
3253 this.border_b_1()
3254 .border_color(cx.theme().colors().border_variant)
3255 })
3256 .child(
3257 div()
3258 .id("next_in_queue")
3259 .child(
3260 Icon::new(IconName::Circle)
3261 .size(IconSize::Small)
3262 .color(icon_color),
3263 )
3264 .tooltip(Tooltip::text(tooltip_text)),
3265 )
3266 .child(editor.clone())
3267 .child(if editor_focused {
3268 h_flex()
3269 .gap_1()
3270 .min_w(rems_from_px(150.))
3271 .justify_end()
3272 .child(
3273 IconButton::new(("edit", index), IconName::Pencil)
3274 .icon_size(IconSize::Small)
3275 .tooltip(|_window, cx| {
3276 Tooltip::with_meta(
3277 "Edit Queued Message",
3278 None,
3279 "Type anything to edit",
3280 cx,
3281 )
3282 })
3283 .on_click(cx.listener(move |this, _, window, cx| {
3284 this.move_queued_message_to_main_editor(
3285 index, None, None, window, cx,
3286 );
3287 })),
3288 )
3289 .child(
3290 Button::new(("send_now_focused", index), "Send Now")
3291 .label_size(LabelSize::Small)
3292 .style(ButtonStyle::Outlined)
3293 .key_binding(
3294 KeyBinding::for_action_in(
3295 &SendImmediately,
3296 &editor.focus_handle(cx),
3297 cx,
3298 )
3299 .map(|kb| kb.size(keybinding_size)),
3300 )
3301 .on_click(cx.listener(move |this, _, window, cx| {
3302 this.send_queued_message_at_index(
3303 index, true, window, cx,
3304 );
3305 })),
3306 )
3307 } else {
3308 h_flex()
3309 .when(!is_next, |this| this.visible_on_hover("queue_entry"))
3310 .gap_1()
3311 .min_w(rems_from_px(150.))
3312 .justify_end()
3313 .child(
3314 IconButton::new(("delete", index), IconName::Trash)
3315 .icon_size(IconSize::Small)
3316 .tooltip({
3317 let focus_handle = focus_handle.clone();
3318 move |_window, cx| {
3319 if is_next {
3320 Tooltip::for_action_in(
3321 "Remove Message from Queue",
3322 &RemoveFirstQueuedMessage,
3323 &focus_handle,
3324 cx,
3325 )
3326 } else {
3327 Tooltip::simple(
3328 "Remove Message from Queue",
3329 cx,
3330 )
3331 }
3332 }
3333 })
3334 .on_click(cx.listener(move |this, _, _, cx| {
3335 this.remove_from_queue(index, cx);
3336 cx.notify();
3337 })),
3338 )
3339 .child(
3340 IconButton::new(("edit", index), IconName::Pencil)
3341 .icon_size(IconSize::Small)
3342 .tooltip({
3343 let focus_handle = focus_handle.clone();
3344 move |_window, cx| {
3345 if is_next {
3346 Tooltip::for_action_in(
3347 "Edit",
3348 &EditFirstQueuedMessage,
3349 &focus_handle,
3350 cx,
3351 )
3352 } else {
3353 Tooltip::simple("Edit", cx)
3354 }
3355 }
3356 })
3357 .on_click(cx.listener(move |this, _, window, cx| {
3358 this.move_queued_message_to_main_editor(
3359 index, None, None, window, cx,
3360 );
3361 })),
3362 )
3363 .child(
3364 Button::new(("send_now", index), "Send Now")
3365 .label_size(LabelSize::Small)
3366 .when(is_next, |this| this.style(ButtonStyle::Outlined))
3367 .when(is_next && message_editor.is_empty(cx), |this| {
3368 let action: Box<dyn gpui::Action> =
3369 if can_fast_track {
3370 Box::new(Chat)
3371 } else {
3372 Box::new(SendNextQueuedMessage)
3373 };
3374
3375 this.key_binding(
3376 KeyBinding::for_action_in(
3377 action.as_ref(),
3378 &focus_handle.clone(),
3379 cx,
3380 )
3381 .map(|kb| kb.size(keybinding_size)),
3382 )
3383 })
3384 .on_click(cx.listener(move |this, _, window, cx| {
3385 this.send_queued_message_at_index(
3386 index, true, window, cx,
3387 );
3388 })),
3389 )
3390 })
3391 }),
3392 )
3393 .into_any_element()
3394 }
3395
3396 fn supports_split_token_display(&self, cx: &App) -> bool {
3397 self.as_native_thread(cx)
3398 .and_then(|thread| thread.read(cx).model())
3399 .is_some_and(|model| model.supports_split_token_display())
3400 }
3401
3402 fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
3403 let thread = self.thread.read(cx);
3404 let usage = thread.token_usage()?;
3405 let show_split = self.supports_split_token_display(cx);
3406
3407 let progress_color = |ratio: f32| -> Hsla {
3408 if ratio >= 0.85 {
3409 cx.theme().status().warning
3410 } else {
3411 cx.theme().colors().text_muted
3412 }
3413 };
3414
3415 let used = crate::humanize_token_count(usage.used_tokens);
3416 let max = crate::humanize_token_count(usage.max_tokens);
3417 let input_tokens_label = crate::humanize_token_count(usage.input_tokens);
3418 let output_tokens_label = crate::humanize_token_count(usage.output_tokens);
3419
3420 let progress_ratio = if usage.max_tokens > 0 {
3421 usage.used_tokens as f32 / usage.max_tokens as f32
3422 } else {
3423 0.0
3424 };
3425
3426 let ring_size = px(16.0);
3427 let stroke_width = px(2.);
3428
3429 let percentage = format!("{}%", (progress_ratio * 100.0).round() as u32);
3430
3431 let tooltip_separator_color = Color::Custom(cx.theme().colors().text_disabled.opacity(0.6));
3432
3433 let (user_rules_count, first_user_rules_id, project_rules_count, project_entry_ids) = self
3434 .as_native_thread(cx)
3435 .map(|thread| {
3436 let project_context = thread.read(cx).project_context().read(cx);
3437 let user_rules_count = project_context.user_rules.len();
3438 let first_user_rules_id = project_context.user_rules.first().map(|r| r.uuid.0);
3439 let project_entry_ids = project_context
3440 .worktrees
3441 .iter()
3442 .filter_map(|wt| wt.rules_file.as_ref())
3443 .map(|rf| ProjectEntryId::from_usize(rf.project_entry_id))
3444 .collect::<Vec<_>>();
3445 let project_rules_count = project_entry_ids.len();
3446 (
3447 user_rules_count,
3448 first_user_rules_id,
3449 project_rules_count,
3450 project_entry_ids,
3451 )
3452 })
3453 .unwrap_or_default();
3454
3455 let workspace = self.workspace.clone();
3456
3457 let max_output_tokens = self
3458 .as_native_thread(cx)
3459 .and_then(|thread| thread.read(cx).model())
3460 .and_then(|model| model.max_output_tokens())
3461 .unwrap_or(0);
3462 let input_max_label =
3463 crate::humanize_token_count(usage.max_tokens.saturating_sub(max_output_tokens));
3464 let output_max_label = crate::humanize_token_count(max_output_tokens);
3465
3466 let build_tooltip = {
3467 move |_window: &mut Window, cx: &mut App| {
3468 let percentage = percentage.clone();
3469 let used = used.clone();
3470 let max = max.clone();
3471 let input_tokens_label = input_tokens_label.clone();
3472 let output_tokens_label = output_tokens_label.clone();
3473 let input_max_label = input_max_label.clone();
3474 let output_max_label = output_max_label.clone();
3475 let project_entry_ids = project_entry_ids.clone();
3476 let workspace = workspace.clone();
3477 cx.new(move |_cx| TokenUsageTooltip {
3478 percentage,
3479 used,
3480 max,
3481 input_tokens: input_tokens_label,
3482 output_tokens: output_tokens_label,
3483 input_max: input_max_label,
3484 output_max: output_max_label,
3485 show_split,
3486 separator_color: tooltip_separator_color,
3487 user_rules_count,
3488 first_user_rules_id,
3489 project_rules_count,
3490 project_entry_ids,
3491 workspace,
3492 })
3493 .into()
3494 }
3495 };
3496
3497 if show_split {
3498 let input_max_raw = usage.max_tokens.saturating_sub(max_output_tokens);
3499 let output_max_raw = max_output_tokens;
3500
3501 let input_ratio = if input_max_raw > 0 {
3502 usage.input_tokens as f32 / input_max_raw as f32
3503 } else {
3504 0.0
3505 };
3506 let output_ratio = if output_max_raw > 0 {
3507 usage.output_tokens as f32 / output_max_raw as f32
3508 } else {
3509 0.0
3510 };
3511
3512 Some(
3513 h_flex()
3514 .id("split_token_usage")
3515 .flex_shrink_0()
3516 .gap_1p5()
3517 .mr_1()
3518 .child(
3519 h_flex()
3520 .gap_0p5()
3521 .child(
3522 Icon::new(IconName::ArrowUp)
3523 .size(IconSize::XSmall)
3524 .color(Color::Muted),
3525 )
3526 .child(
3527 CircularProgress::new(
3528 usage.input_tokens as f32,
3529 input_max_raw as f32,
3530 ring_size,
3531 cx,
3532 )
3533 .stroke_width(stroke_width)
3534 .progress_color(progress_color(input_ratio)),
3535 ),
3536 )
3537 .child(
3538 h_flex()
3539 .gap_0p5()
3540 .child(
3541 Icon::new(IconName::ArrowDown)
3542 .size(IconSize::XSmall)
3543 .color(Color::Muted),
3544 )
3545 .child(
3546 CircularProgress::new(
3547 usage.output_tokens as f32,
3548 output_max_raw as f32,
3549 ring_size,
3550 cx,
3551 )
3552 .stroke_width(stroke_width)
3553 .progress_color(progress_color(output_ratio)),
3554 ),
3555 )
3556 .hoverable_tooltip(build_tooltip)
3557 .into_any_element(),
3558 )
3559 } else {
3560 Some(
3561 h_flex()
3562 .id("circular_progress_tokens")
3563 .mt_px()
3564 .mr_1()
3565 .child(
3566 CircularProgress::new(
3567 usage.used_tokens as f32,
3568 usage.max_tokens as f32,
3569 ring_size,
3570 cx,
3571 )
3572 .stroke_width(stroke_width)
3573 .progress_color(progress_color(progress_ratio)),
3574 )
3575 .hoverable_tooltip(build_tooltip)
3576 .into_any_element(),
3577 )
3578 }
3579 }
3580
3581 fn fast_mode_available(&self, cx: &Context<Self>) -> bool {
3582 if !cx.is_staff() {
3583 return false;
3584 }
3585 self.as_native_thread(cx)
3586 .and_then(|thread| thread.read(cx).model())
3587 .map(|model| model.supports_fast_mode())
3588 .unwrap_or(false)
3589 }
3590
3591 fn render_fast_mode_control(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3592 if !self.fast_mode_available(cx) {
3593 return None;
3594 }
3595
3596 let thread = self.as_native_thread(cx)?.read(cx);
3597
3598 let (tooltip_label, color, icon) = if matches!(thread.speed(), Some(Speed::Fast)) {
3599 ("Disable Fast Mode", Color::Muted, IconName::FastForward)
3600 } else {
3601 (
3602 "Enable Fast Mode",
3603 Color::Custom(cx.theme().colors().icon_disabled.opacity(0.8)),
3604 IconName::FastForwardOff,
3605 )
3606 };
3607
3608 let focus_handle = self.message_editor.focus_handle(cx);
3609
3610 Some(
3611 IconButton::new("fast-mode", icon)
3612 .icon_size(IconSize::Small)
3613 .icon_color(color)
3614 .tooltip(move |_, cx| {
3615 Tooltip::for_action_in(tooltip_label, &ToggleFastMode, &focus_handle, cx)
3616 })
3617 .on_click(cx.listener(move |this, _, _window, cx| {
3618 this.toggle_fast_mode(cx);
3619 }))
3620 .into_any_element(),
3621 )
3622 }
3623
3624 fn render_thinking_control(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3625 let thread = self.as_native_thread(cx)?.read(cx);
3626 let model = thread.model()?;
3627
3628 let supports_thinking = model.supports_thinking();
3629 if !supports_thinking {
3630 return None;
3631 }
3632
3633 let thinking = thread.thinking_enabled();
3634
3635 let (tooltip_label, icon, color) = if thinking {
3636 (
3637 "Disable Thinking Mode",
3638 IconName::ThinkingMode,
3639 Color::Muted,
3640 )
3641 } else {
3642 (
3643 "Enable Thinking Mode",
3644 IconName::ThinkingModeOff,
3645 Color::Custom(cx.theme().colors().icon_disabled.opacity(0.8)),
3646 )
3647 };
3648
3649 let focus_handle = self.message_editor.focus_handle(cx);
3650
3651 let thinking_toggle = IconButton::new("thinking-mode", icon)
3652 .icon_size(IconSize::Small)
3653 .icon_color(color)
3654 .tooltip(move |_, cx| {
3655 Tooltip::for_action_in(tooltip_label, &ToggleThinkingMode, &focus_handle, cx)
3656 })
3657 .on_click(cx.listener(move |this, _, _window, cx| {
3658 if let Some(thread) = this.as_native_thread(cx) {
3659 thread.update(cx, |thread, cx| {
3660 let enable_thinking = !thread.thinking_enabled();
3661 thread.set_thinking_enabled(enable_thinking, cx);
3662
3663 let fs = thread.project().read(cx).fs().clone();
3664 update_settings_file(fs, cx, move |settings, _| {
3665 if let Some(agent) = settings.agent.as_mut()
3666 && let Some(default_model) = agent.default_model.as_mut()
3667 {
3668 default_model.enable_thinking = enable_thinking;
3669 }
3670 });
3671 });
3672 }
3673 }));
3674
3675 if model.supported_effort_levels().is_empty() {
3676 return Some(thinking_toggle.into_any_element());
3677 }
3678
3679 if !model.supported_effort_levels().is_empty() && !thinking {
3680 return Some(thinking_toggle.into_any_element());
3681 }
3682
3683 let left_btn = thinking_toggle;
3684 let right_btn = self.render_effort_selector(
3685 model.supported_effort_levels(),
3686 thread.thinking_effort().cloned(),
3687 cx,
3688 );
3689
3690 Some(
3691 SplitButton::new(left_btn, right_btn.into_any_element())
3692 .style(SplitButtonStyle::Transparent)
3693 .into_any_element(),
3694 )
3695 }
3696
3697 fn render_effort_selector(
3698 &self,
3699 supported_effort_levels: Vec<LanguageModelEffortLevel>,
3700 selected_effort: Option<String>,
3701 cx: &Context<Self>,
3702 ) -> impl IntoElement {
3703 let weak_self = cx.weak_entity();
3704
3705 let default_effort_level = supported_effort_levels
3706 .iter()
3707 .find(|effort_level| effort_level.is_default)
3708 .cloned();
3709
3710 let selected = selected_effort.and_then(|effort| {
3711 supported_effort_levels
3712 .iter()
3713 .find(|level| level.value == effort)
3714 .cloned()
3715 });
3716
3717 let label = selected
3718 .clone()
3719 .or(default_effort_level)
3720 .map_or("Select Effort".into(), |effort| effort.name);
3721
3722 let (label_color, icon) = if self.thinking_effort_menu_handle.is_deployed() {
3723 (Color::Accent, IconName::ChevronUp)
3724 } else {
3725 (Color::Muted, IconName::ChevronDown)
3726 };
3727
3728 let focus_handle = self.message_editor.focus_handle(cx);
3729 let show_cycle_row = supported_effort_levels.len() > 1;
3730
3731 let tooltip = Tooltip::element({
3732 move |_, cx| {
3733 let mut content = v_flex().gap_1().child(
3734 h_flex()
3735 .gap_2()
3736 .justify_between()
3737 .child(Label::new("Change Thinking Effort"))
3738 .child(KeyBinding::for_action_in(
3739 &ToggleThinkingEffortMenu,
3740 &focus_handle,
3741 cx,
3742 )),
3743 );
3744
3745 if show_cycle_row {
3746 content = content.child(
3747 h_flex()
3748 .pt_1()
3749 .gap_2()
3750 .justify_between()
3751 .border_t_1()
3752 .border_color(cx.theme().colors().border_variant)
3753 .child(Label::new("Cycle Thinking Effort"))
3754 .child(KeyBinding::for_action_in(
3755 &CycleThinkingEffort,
3756 &focus_handle,
3757 cx,
3758 )),
3759 );
3760 }
3761
3762 content.into_any_element()
3763 }
3764 });
3765
3766 PopoverMenu::new("effort-selector")
3767 .trigger_with_tooltip(
3768 ButtonLike::new_rounded_right("effort-selector-trigger")
3769 .selected_style(ButtonStyle::Tinted(TintColor::Accent))
3770 .child(Label::new(label).size(LabelSize::Small).color(label_color))
3771 .child(Icon::new(icon).size(IconSize::XSmall).color(Color::Muted)),
3772 tooltip,
3773 )
3774 .menu(move |window, cx| {
3775 Some(ContextMenu::build(window, cx, |mut menu, _window, _cx| {
3776 menu = menu.header("Change Thinking Effort");
3777
3778 for effort_level in supported_effort_levels.clone() {
3779 let is_selected = selected
3780 .as_ref()
3781 .is_some_and(|selected| selected.value == effort_level.value);
3782 let entry = ContextMenuEntry::new(effort_level.name)
3783 .toggleable(IconPosition::End, is_selected);
3784
3785 menu.push_item(entry.handler({
3786 let effort = effort_level.value.clone();
3787 let weak_self = weak_self.clone();
3788 move |_window, cx| {
3789 let effort = effort.clone();
3790 weak_self
3791 .update(cx, |this, cx| {
3792 if let Some(thread) = this.as_native_thread(cx) {
3793 thread.update(cx, |thread, cx| {
3794 thread.set_thinking_effort(
3795 Some(effort.to_string()),
3796 cx,
3797 );
3798
3799 let fs = thread.project().read(cx).fs().clone();
3800 update_settings_file(fs, cx, move |settings, _| {
3801 if let Some(agent) = settings.agent.as_mut()
3802 && let Some(default_model) =
3803 agent.default_model.as_mut()
3804 {
3805 default_model.effort =
3806 Some(effort.to_string());
3807 }
3808 });
3809 });
3810 }
3811 })
3812 .ok();
3813 }
3814 }));
3815 }
3816
3817 menu
3818 }))
3819 })
3820 .with_handle(self.thinking_effort_menu_handle.clone())
3821 .offset(gpui::Point {
3822 x: px(0.0),
3823 y: px(-2.0),
3824 })
3825 .anchor(Corner::BottomLeft)
3826 }
3827
3828 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
3829 let message_editor = self.message_editor.read(cx);
3830 let is_editor_empty = message_editor.is_empty(cx);
3831 let focus_handle = message_editor.focus_handle(cx);
3832
3833 let is_generating = self.thread.read(cx).status() != ThreadStatus::Idle;
3834
3835 if self.is_loading_contents {
3836 div()
3837 .id("loading-message-content")
3838 .px_1()
3839 .tooltip(Tooltip::text("Loading Added Context…"))
3840 .child(loading_contents_spinner(IconSize::default()))
3841 .into_any_element()
3842 } else if is_generating && is_editor_empty {
3843 IconButton::new("stop-generation", IconName::Stop)
3844 .icon_color(Color::Error)
3845 .style(ButtonStyle::Tinted(TintColor::Error))
3846 .tooltip(move |_window, cx| {
3847 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, cx)
3848 })
3849 .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
3850 .into_any_element()
3851 } else {
3852 let send_icon = if is_generating {
3853 IconName::QueueMessage
3854 } else {
3855 IconName::Send
3856 };
3857 IconButton::new("send-message", send_icon)
3858 .style(ButtonStyle::Filled)
3859 .map(|this| {
3860 if is_editor_empty && !is_generating {
3861 this.disabled(true).icon_color(Color::Muted)
3862 } else {
3863 this.icon_color(Color::Accent)
3864 }
3865 })
3866 .tooltip(move |_window, cx| {
3867 if is_editor_empty && !is_generating {
3868 Tooltip::for_action("Type to Send", &Chat, cx)
3869 } else if is_generating {
3870 let focus_handle = focus_handle.clone();
3871
3872 Tooltip::element(move |_window, cx| {
3873 v_flex()
3874 .gap_1()
3875 .child(
3876 h_flex()
3877 .gap_2()
3878 .justify_between()
3879 .child(Label::new("Queue and Send"))
3880 .child(KeyBinding::for_action_in(&Chat, &focus_handle, cx)),
3881 )
3882 .child(
3883 h_flex()
3884 .pt_1()
3885 .gap_2()
3886 .justify_between()
3887 .border_t_1()
3888 .border_color(cx.theme().colors().border_variant)
3889 .child(Label::new("Send Immediately"))
3890 .child(KeyBinding::for_action_in(
3891 &SendImmediately,
3892 &focus_handle,
3893 cx,
3894 )),
3895 )
3896 .into_any_element()
3897 })(_window, cx)
3898 } else {
3899 Tooltip::for_action("Send Message", &Chat, cx)
3900 }
3901 })
3902 .on_click(cx.listener(|this, _, window, cx| {
3903 this.send(window, cx);
3904 }))
3905 .into_any_element()
3906 }
3907 }
3908
3909 fn render_add_context_button(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
3910 let focus_handle = self.message_editor.focus_handle(cx);
3911 let weak_self = cx.weak_entity();
3912
3913 PopoverMenu::new("add-context-menu")
3914 .trigger_with_tooltip(
3915 IconButton::new("add-context", IconName::Plus)
3916 .icon_size(IconSize::Small)
3917 .icon_color(Color::Muted),
3918 {
3919 move |_window, cx| {
3920 Tooltip::for_action_in(
3921 "Add Context",
3922 &OpenAddContextMenu,
3923 &focus_handle,
3924 cx,
3925 )
3926 }
3927 },
3928 )
3929 .anchor(Corner::BottomLeft)
3930 .with_handle(self.add_context_menu_handle.clone())
3931 .offset(gpui::Point {
3932 x: px(0.0),
3933 y: px(-2.0),
3934 })
3935 .menu(move |window, cx| {
3936 weak_self
3937 .update(cx, |this, cx| this.build_add_context_menu(window, cx))
3938 .ok()
3939 })
3940 }
3941
3942 fn build_add_context_menu(
3943 &self,
3944 window: &mut Window,
3945 cx: &mut Context<Self>,
3946 ) -> Entity<ContextMenu> {
3947 let message_editor = self.message_editor.clone();
3948 let workspace = self.workspace.clone();
3949 let session_capabilities = self.session_capabilities.read();
3950 let supports_images = session_capabilities.supports_images();
3951 let supports_embedded_context = session_capabilities.supports_embedded_context();
3952
3953 let has_editor_selection = workspace
3954 .upgrade()
3955 .and_then(|ws| {
3956 ws.read(cx)
3957 .active_item(cx)
3958 .and_then(|item| item.downcast::<Editor>())
3959 })
3960 .is_some_and(|editor| {
3961 editor.update(cx, |editor, cx| {
3962 editor.has_non_empty_selection(&editor.display_snapshot(cx))
3963 })
3964 });
3965
3966 let has_terminal_selection = workspace
3967 .upgrade()
3968 .and_then(|ws| ws.read(cx).panel::<TerminalPanel>(cx))
3969 .is_some_and(|panel| !panel.read(cx).terminal_selections(cx).is_empty());
3970
3971 let has_selection = has_editor_selection || has_terminal_selection;
3972
3973 ContextMenu::build(window, cx, move |menu, _window, _cx| {
3974 menu.key_context("AddContextMenu")
3975 .header("Context")
3976 .item(
3977 ContextMenuEntry::new("Files & Directories")
3978 .icon(IconName::File)
3979 .icon_color(Color::Muted)
3980 .icon_size(IconSize::XSmall)
3981 .handler({
3982 let message_editor = message_editor.clone();
3983 move |window, cx| {
3984 message_editor.focus_handle(cx).focus(window, cx);
3985 message_editor.update(cx, |editor, cx| {
3986 editor.insert_context_type("file", window, cx);
3987 });
3988 }
3989 }),
3990 )
3991 .item(
3992 ContextMenuEntry::new("Symbols")
3993 .icon(IconName::Code)
3994 .icon_color(Color::Muted)
3995 .icon_size(IconSize::XSmall)
3996 .handler({
3997 let message_editor = message_editor.clone();
3998 move |window, cx| {
3999 message_editor.focus_handle(cx).focus(window, cx);
4000 message_editor.update(cx, |editor, cx| {
4001 editor.insert_context_type("symbol", window, cx);
4002 });
4003 }
4004 }),
4005 )
4006 .item(
4007 ContextMenuEntry::new("Threads")
4008 .icon(IconName::Thread)
4009 .icon_color(Color::Muted)
4010 .icon_size(IconSize::XSmall)
4011 .handler({
4012 let message_editor = message_editor.clone();
4013 move |window, cx| {
4014 message_editor.focus_handle(cx).focus(window, cx);
4015 message_editor.update(cx, |editor, cx| {
4016 editor.insert_context_type("thread", window, cx);
4017 });
4018 }
4019 }),
4020 )
4021 .item(
4022 ContextMenuEntry::new("Rules")
4023 .icon(IconName::Reader)
4024 .icon_color(Color::Muted)
4025 .icon_size(IconSize::XSmall)
4026 .handler({
4027 let message_editor = message_editor.clone();
4028 move |window, cx| {
4029 message_editor.focus_handle(cx).focus(window, cx);
4030 message_editor.update(cx, |editor, cx| {
4031 editor.insert_context_type("rule", window, cx);
4032 });
4033 }
4034 }),
4035 )
4036 .item(
4037 ContextMenuEntry::new("Image")
4038 .icon(IconName::Image)
4039 .icon_color(Color::Muted)
4040 .icon_size(IconSize::XSmall)
4041 .disabled(!supports_images)
4042 .handler({
4043 let message_editor = message_editor.clone();
4044 move |window, cx| {
4045 message_editor.focus_handle(cx).focus(window, cx);
4046 message_editor.update(cx, |editor, cx| {
4047 editor.add_images_from_picker(window, cx);
4048 });
4049 }
4050 }),
4051 )
4052 .item(
4053 ContextMenuEntry::new("Selection")
4054 .icon(IconName::CursorIBeam)
4055 .icon_color(Color::Muted)
4056 .icon_size(IconSize::XSmall)
4057 .disabled(!has_selection)
4058 .handler({
4059 move |window, cx| {
4060 window.dispatch_action(
4061 zed_actions::agent::AddSelectionToThread.boxed_clone(),
4062 cx,
4063 );
4064 }
4065 }),
4066 )
4067 .item(
4068 ContextMenuEntry::new("Branch Diff")
4069 .icon(IconName::GitBranch)
4070 .icon_color(Color::Muted)
4071 .icon_size(IconSize::XSmall)
4072 .disabled(!supports_embedded_context)
4073 .handler({
4074 move |window, cx| {
4075 message_editor.update(cx, |editor, cx| {
4076 editor.insert_branch_diff_crease(window, cx);
4077 });
4078 }
4079 }),
4080 )
4081 })
4082 }
4083
4084 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
4085 let following = self.is_following(cx);
4086
4087 let tooltip_label = if following {
4088 if self.agent_id.as_ref() == agent::ZED_AGENT_ID.as_ref() {
4089 format!("Stop Following the {}", self.agent_id)
4090 } else {
4091 format!("Stop Following {}", self.agent_id)
4092 }
4093 } else {
4094 if self.agent_id.as_ref() == agent::ZED_AGENT_ID.as_ref() {
4095 format!("Follow the {}", self.agent_id)
4096 } else {
4097 format!("Follow {}", self.agent_id)
4098 }
4099 };
4100
4101 IconButton::new("follow-agent", IconName::Crosshair)
4102 .icon_size(IconSize::Small)
4103 .icon_color(Color::Muted)
4104 .toggle_state(following)
4105 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
4106 .tooltip(move |_window, cx| {
4107 if following {
4108 Tooltip::for_action(tooltip_label.clone(), &Follow, cx)
4109 } else {
4110 Tooltip::with_meta(
4111 tooltip_label.clone(),
4112 Some(&Follow),
4113 "Track the agent's location as it reads and edits files.",
4114 cx,
4115 )
4116 }
4117 })
4118 .on_click(cx.listener(move |this, _, window, cx| {
4119 this.toggle_following(window, cx);
4120 }))
4121 }
4122}
4123
4124struct TokenUsageTooltip {
4125 percentage: String,
4126 used: String,
4127 max: String,
4128 input_tokens: String,
4129 output_tokens: String,
4130 input_max: String,
4131 output_max: String,
4132 show_split: bool,
4133 separator_color: Color,
4134 user_rules_count: usize,
4135 first_user_rules_id: Option<uuid::Uuid>,
4136 project_rules_count: usize,
4137 project_entry_ids: Vec<ProjectEntryId>,
4138 workspace: WeakEntity<Workspace>,
4139}
4140
4141impl Render for TokenUsageTooltip {
4142 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4143 let separator_color = self.separator_color;
4144 let percentage = self.percentage.clone();
4145 let used = self.used.clone();
4146 let max = self.max.clone();
4147 let input_tokens = self.input_tokens.clone();
4148 let output_tokens = self.output_tokens.clone();
4149 let input_max = self.input_max.clone();
4150 let output_max = self.output_max.clone();
4151 let show_split = self.show_split;
4152 let user_rules_count = self.user_rules_count;
4153 let first_user_rules_id = self.first_user_rules_id;
4154 let project_rules_count = self.project_rules_count;
4155 let project_entry_ids = self.project_entry_ids.clone();
4156 let workspace = self.workspace.clone();
4157
4158 ui::tooltip_container(cx, move |container, cx| {
4159 container
4160 .min_w_40()
4161 .child(
4162 Label::new("Context")
4163 .color(Color::Muted)
4164 .size(LabelSize::Small),
4165 )
4166 .when(!show_split, |this| {
4167 this.child(
4168 h_flex()
4169 .gap_0p5()
4170 .child(Label::new(percentage.clone()))
4171 .child(Label::new("\u{2022}").color(separator_color).mx_1())
4172 .child(Label::new(used.clone()))
4173 .child(Label::new("/").color(separator_color))
4174 .child(Label::new(max.clone()).color(Color::Muted)),
4175 )
4176 })
4177 .when(show_split, |this| {
4178 this.child(
4179 v_flex()
4180 .gap_0p5()
4181 .child(
4182 h_flex()
4183 .gap_0p5()
4184 .child(Label::new("Input:").color(Color::Muted).mr_0p5())
4185 .child(Label::new(input_tokens))
4186 .child(Label::new("/").color(separator_color))
4187 .child(Label::new(input_max).color(Color::Muted)),
4188 )
4189 .child(
4190 h_flex()
4191 .gap_0p5()
4192 .child(Label::new("Output:").color(Color::Muted).mr_0p5())
4193 .child(Label::new(output_tokens))
4194 .child(Label::new("/").color(separator_color))
4195 .child(Label::new(output_max).color(Color::Muted)),
4196 ),
4197 )
4198 })
4199 .when(
4200 user_rules_count > 0 || project_rules_count > 0,
4201 move |this| {
4202 this.child(
4203 v_flex()
4204 .mt_1p5()
4205 .pt_1p5()
4206 .pb_0p5()
4207 .gap_0p5()
4208 .border_t_1()
4209 .border_color(cx.theme().colors().border_variant)
4210 .child(
4211 Label::new("Rules")
4212 .color(Color::Muted)
4213 .size(LabelSize::Small),
4214 )
4215 .child(
4216 v_flex()
4217 .mx_neg_1()
4218 .when(user_rules_count > 0, move |this| {
4219 this.child(
4220 Button::new(
4221 "open-user-rules",
4222 format!("{} user rules", user_rules_count),
4223 )
4224 .end_icon(
4225 Icon::new(IconName::ArrowUpRight)
4226 .color(Color::Muted)
4227 .size(IconSize::XSmall),
4228 )
4229 .on_click(move |_, window, cx| {
4230 window.dispatch_action(
4231 Box::new(OpenRulesLibrary {
4232 prompt_to_select: first_user_rules_id,
4233 }),
4234 cx,
4235 );
4236 }),
4237 )
4238 })
4239 .when(project_rules_count > 0, move |this| {
4240 let workspace = workspace.clone();
4241 let project_entry_ids = project_entry_ids.clone();
4242 this.child(
4243 Button::new(
4244 "open-project-rules",
4245 format!(
4246 "{} project rules",
4247 project_rules_count
4248 ),
4249 )
4250 .end_icon(
4251 Icon::new(IconName::ArrowUpRight)
4252 .color(Color::Muted)
4253 .size(IconSize::XSmall),
4254 )
4255 .on_click(move |_, window, cx| {
4256 let _ =
4257 workspace.update(cx, |workspace, cx| {
4258 let project =
4259 workspace.project().read(cx);
4260 let paths = project_entry_ids
4261 .iter()
4262 .flat_map(|id| {
4263 project.path_for_entry(*id, cx)
4264 })
4265 .collect::<Vec<_>>();
4266 for path in paths {
4267 workspace
4268 .open_path(
4269 path, None, true, window,
4270 cx,
4271 )
4272 .detach_and_log_err(cx);
4273 }
4274 });
4275 }),
4276 )
4277 }),
4278 ),
4279 )
4280 },
4281 )
4282 })
4283 }
4284}
4285
4286impl ThreadView {
4287 pub(crate) fn render_entries(&mut self, cx: &mut Context<Self>) -> List {
4288 list(
4289 self.list_state.clone(),
4290 cx.processor(|this, index: usize, window, cx| {
4291 let entries = this.thread.read(cx).entries();
4292 if let Some(entry) = entries.get(index) {
4293 this.render_entry(index, entries.len(), entry, window, cx)
4294 } else if this.generating_indicator_in_list {
4295 let confirmation = entries
4296 .last()
4297 .is_some_and(|entry| Self::is_waiting_for_confirmation(entry));
4298 this.render_generating(confirmation, cx).into_any_element()
4299 } else {
4300 Empty.into_any()
4301 }
4302 }),
4303 )
4304 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
4305 .flex_grow()
4306 }
4307
4308 fn render_entry(
4309 &self,
4310 entry_ix: usize,
4311 total_entries: usize,
4312 entry: &AgentThreadEntry,
4313 window: &Window,
4314 cx: &Context<Self>,
4315 ) -> AnyElement {
4316 let is_indented = entry.is_indented();
4317 let is_first_indented = is_indented
4318 && self
4319 .thread
4320 .read(cx)
4321 .entries()
4322 .get(entry_ix.saturating_sub(1))
4323 .is_none_or(|entry| !entry.is_indented());
4324
4325 let primary = match &entry {
4326 AgentThreadEntry::UserMessage(message) => {
4327 let Some(editor) = self
4328 .entry_view_state
4329 .read(cx)
4330 .entry(entry_ix)
4331 .and_then(|entry| entry.message_editor())
4332 .cloned()
4333 else {
4334 return Empty.into_any_element();
4335 };
4336
4337 let editing = self.editing_message == Some(entry_ix);
4338 let editor_focus = editor.focus_handle(cx).is_focused(window);
4339 let focus_border = cx.theme().colors().border_focused;
4340
4341 let has_checkpoint_button = message
4342 .checkpoint
4343 .as_ref()
4344 .is_some_and(|checkpoint| checkpoint.show);
4345
4346 let is_subagent = self.is_subagent();
4347 let is_editable = message.id.is_some() && !is_subagent;
4348 let agent_name = if is_subagent {
4349 "subagents".into()
4350 } else {
4351 self.agent_id.clone()
4352 };
4353
4354 v_flex()
4355 .id(("user_message", entry_ix))
4356 .map(|this| {
4357 if is_first_indented {
4358 this.pt_0p5()
4359 } else {
4360 this.pt_2()
4361 }
4362 })
4363 .pb_3()
4364 .px_2()
4365 .gap_1p5()
4366 .w_full()
4367 .when(is_editable && has_checkpoint_button, |this| {
4368 this.children(message.id.clone().map(|message_id| {
4369 h_flex()
4370 .px_3()
4371 .gap_2()
4372 .child(Divider::horizontal())
4373 .child(
4374 Button::new("restore-checkpoint", "Restore Checkpoint")
4375 .start_icon(Icon::new(IconName::Undo).size(IconSize::XSmall).color(Color::Muted))
4376 .label_size(LabelSize::XSmall)
4377 .color(Color::Muted)
4378 .tooltip(Tooltip::text("Restores all files in the project to the content they had at this point in the conversation."))
4379 .on_click(cx.listener(move |this, _, _window, cx| {
4380 this.restore_checkpoint(&message_id, cx);
4381 }))
4382 )
4383 .child(Divider::horizontal())
4384 }))
4385 })
4386 .child(
4387 div()
4388 .relative()
4389 .child(
4390 div()
4391 .py_3()
4392 .px_2()
4393 .rounded_md()
4394 .bg(cx.theme().colors().editor_background)
4395 .border_1()
4396 .when(is_indented, |this| {
4397 this.py_2().px_2().shadow_sm()
4398 })
4399 .border_color(cx.theme().colors().border)
4400 .map(|this| {
4401 if !is_editable {
4402 if is_subagent {
4403 return this.border_dashed();
4404 }
4405 return this;
4406 }
4407 if editing && editor_focus {
4408 return this.border_color(focus_border);
4409 }
4410 if editing && !editor_focus {
4411 return this.border_dashed()
4412 }
4413 this.shadow_md().hover(|s| {
4414 s.border_color(focus_border.opacity(0.8))
4415 })
4416 })
4417 .text_xs()
4418 .child(editor.clone().into_any_element())
4419 )
4420 .when(editor_focus, |this| {
4421 let base_container = h_flex()
4422 .absolute()
4423 .top_neg_3p5()
4424 .right_3()
4425 .gap_1()
4426 .rounded_sm()
4427 .border_1()
4428 .border_color(cx.theme().colors().border)
4429 .bg(cx.theme().colors().editor_background)
4430 .overflow_hidden();
4431
4432 let is_loading_contents = self.is_loading_contents;
4433 if is_editable {
4434 this.child(
4435 base_container
4436 .child(
4437 IconButton::new("cancel", IconName::Close)
4438 .disabled(is_loading_contents)
4439 .icon_color(Color::Error)
4440 .icon_size(IconSize::XSmall)
4441 .on_click(cx.listener(Self::cancel_editing))
4442 )
4443 .child(
4444 if is_loading_contents {
4445 div()
4446 .id("loading-edited-message-content")
4447 .tooltip(Tooltip::text("Loading Added Context…"))
4448 .child(loading_contents_spinner(IconSize::XSmall))
4449 .into_any_element()
4450 } else {
4451 IconButton::new("regenerate", IconName::Return)
4452 .icon_color(Color::Muted)
4453 .icon_size(IconSize::XSmall)
4454 .tooltip(Tooltip::text(
4455 "Editing will restart the thread from this point."
4456 ))
4457 .on_click(cx.listener({
4458 let editor = editor.clone();
4459 move |this, _, window, cx| {
4460 this.regenerate(
4461 entry_ix, editor.clone(), window, cx,
4462 );
4463 }
4464 })).into_any_element()
4465 }
4466 )
4467 )
4468 } else {
4469 this.child(
4470 base_container
4471 .border_dashed()
4472 .child(IconButton::new("non_editable", IconName::PencilUnavailable)
4473 .icon_size(IconSize::Small)
4474 .icon_color(Color::Muted)
4475 .style(ButtonStyle::Transparent)
4476 .tooltip(Tooltip::element({
4477 let agent_name = agent_name.clone();
4478 move |_, _| {
4479 v_flex()
4480 .gap_1()
4481 .child(Label::new("Unavailable Editing"))
4482 .child(
4483 div().max_w_64().child(
4484 Label::new(format!(
4485 "Editing previous messages is not available for {} yet.",
4486 agent_name
4487 ))
4488 .size(LabelSize::Small)
4489 .color(Color::Muted),
4490 ),
4491 )
4492 .into_any_element()
4493 }
4494 }))),
4495 )
4496 }
4497 }),
4498 )
4499 .into_any()
4500 }
4501 AgentThreadEntry::AssistantMessage(AssistantMessage {
4502 chunks,
4503 indented: _,
4504 is_subagent_output: _,
4505 }) => {
4506 let mut is_blank = true;
4507 let is_last = entry_ix + 1 == total_entries;
4508
4509 let style = MarkdownStyle::themed(MarkdownFont::Agent, window, cx);
4510 let message_body = v_flex()
4511 .w_full()
4512 .gap_3()
4513 .children(chunks.iter().enumerate().filter_map(
4514 |(chunk_ix, chunk)| match chunk {
4515 AssistantMessageChunk::Message { block } => {
4516 block.markdown().and_then(|md| {
4517 let this_is_blank = md.read(cx).source().trim().is_empty();
4518 is_blank = is_blank && this_is_blank;
4519 if this_is_blank {
4520 return None;
4521 }
4522
4523 Some(
4524 self.render_markdown(md.clone(), style.clone())
4525 .into_any_element(),
4526 )
4527 })
4528 }
4529 AssistantMessageChunk::Thought { block } => {
4530 block.markdown().and_then(|md| {
4531 let this_is_blank = md.read(cx).source().trim().is_empty();
4532 is_blank = is_blank && this_is_blank;
4533 if this_is_blank {
4534 return None;
4535 }
4536 Some(
4537 self.render_thinking_block(
4538 entry_ix,
4539 chunk_ix,
4540 md.clone(),
4541 window,
4542 cx,
4543 )
4544 .into_any_element(),
4545 )
4546 })
4547 }
4548 },
4549 ))
4550 .into_any();
4551
4552 if is_blank {
4553 Empty.into_any()
4554 } else {
4555 v_flex()
4556 .px_5()
4557 .py_1p5()
4558 .when(is_last, |this| this.pb_4())
4559 .w_full()
4560 .text_ui(cx)
4561 .child(self.render_message_context_menu(entry_ix, message_body, cx))
4562 .when_some(
4563 self.entry_view_state
4564 .read(cx)
4565 .entry(entry_ix)
4566 .and_then(|entry| entry.focus_handle(cx)),
4567 |this, handle| this.track_focus(&handle),
4568 )
4569 .into_any()
4570 }
4571 }
4572 AgentThreadEntry::ToolCall(tool_call) => self
4573 .render_any_tool_call(
4574 &self.id,
4575 entry_ix,
4576 tool_call,
4577 &self.focus_handle(cx),
4578 false,
4579 window,
4580 cx,
4581 )
4582 .into_any(),
4583 AgentThreadEntry::CompletedPlan(entries) => {
4584 self.render_completed_plan(entries, window, cx)
4585 }
4586 };
4587
4588 let is_subagent_output = self.is_subagent()
4589 && matches!(entry, AgentThreadEntry::AssistantMessage(msg) if msg.is_subagent_output);
4590
4591 let primary = if is_subagent_output {
4592 v_flex()
4593 .w_full()
4594 .child(
4595 h_flex()
4596 .id("subagent_output")
4597 .px_5()
4598 .py_1()
4599 .gap_2()
4600 .child(Divider::horizontal())
4601 .child(
4602 h_flex()
4603 .gap_1()
4604 .child(
4605 Icon::new(IconName::ForwardArrowUp)
4606 .color(Color::Muted)
4607 .size(IconSize::Small),
4608 )
4609 .child(
4610 Label::new("Subagent Output")
4611 .size(LabelSize::Custom(self.tool_name_font_size()))
4612 .color(Color::Muted),
4613 ),
4614 )
4615 .child(Divider::horizontal())
4616 .tooltip(Tooltip::text("Everything below this line was sent as output from this subagent to the main agent.")),
4617 )
4618 .child(primary)
4619 .into_any_element()
4620 } else {
4621 primary
4622 };
4623
4624 let thread = self.thread.clone();
4625
4626 let primary = if is_indented {
4627 let line_top = if is_first_indented {
4628 rems_from_px(-12.0)
4629 } else {
4630 rems_from_px(0.0)
4631 };
4632
4633 div()
4634 .relative()
4635 .w_full()
4636 .pl_5()
4637 .bg(cx.theme().colors().panel_background.opacity(0.2))
4638 .child(
4639 div()
4640 .absolute()
4641 .left(rems_from_px(18.0))
4642 .top(line_top)
4643 .bottom_0()
4644 .w_px()
4645 .bg(cx.theme().colors().border.opacity(0.6)),
4646 )
4647 .child(primary)
4648 .into_any_element()
4649 } else {
4650 primary
4651 };
4652
4653 let needs_confirmation = Self::is_waiting_for_confirmation(entry);
4654
4655 let comments_editor = self.thread_feedback.comments_editor.clone();
4656
4657 let primary = if entry_ix + 1 == total_entries {
4658 v_flex()
4659 .w_full()
4660 .child(primary)
4661 .when(!needs_confirmation, |this| {
4662 this.child(self.render_thread_controls(&thread, cx))
4663 })
4664 .when_some(comments_editor, |this, editor| {
4665 this.child(Self::render_feedback_feedback_editor(editor, cx))
4666 })
4667 .into_any_element()
4668 } else {
4669 primary
4670 };
4671
4672 if let Some(editing_index) = self.editing_message
4673 && editing_index < entry_ix
4674 {
4675 let is_subagent = self.is_subagent();
4676
4677 let backdrop = div()
4678 .id(("backdrop", entry_ix))
4679 .size_full()
4680 .absolute()
4681 .inset_0()
4682 .bg(cx.theme().colors().panel_background)
4683 .opacity(0.8)
4684 .block_mouse_except_scroll()
4685 .on_click(cx.listener(Self::cancel_editing));
4686
4687 div()
4688 .relative()
4689 .child(primary)
4690 .when(!is_subagent, |this| this.child(backdrop))
4691 .into_any_element()
4692 } else {
4693 primary
4694 }
4695 }
4696
4697 fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
4698 h_flex()
4699 .key_context("AgentFeedbackMessageEditor")
4700 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
4701 this.thread_feedback.dismiss_comments();
4702 cx.notify();
4703 }))
4704 .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
4705 this.submit_feedback_message(cx);
4706 }))
4707 .p_2()
4708 .mb_2()
4709 .mx_5()
4710 .gap_1()
4711 .rounded_md()
4712 .border_1()
4713 .border_color(cx.theme().colors().border)
4714 .bg(cx.theme().colors().editor_background)
4715 .child(div().w_full().child(editor))
4716 .child(
4717 h_flex()
4718 .child(
4719 IconButton::new("dismiss-feedback-message", IconName::Close)
4720 .icon_color(Color::Error)
4721 .icon_size(IconSize::XSmall)
4722 .shape(ui::IconButtonShape::Square)
4723 .on_click(cx.listener(move |this, _, _window, cx| {
4724 this.thread_feedback.dismiss_comments();
4725 cx.notify();
4726 })),
4727 )
4728 .child(
4729 IconButton::new("submit-feedback-message", IconName::Return)
4730 .icon_size(IconSize::XSmall)
4731 .shape(ui::IconButtonShape::Square)
4732 .on_click(cx.listener(move |this, _, _window, cx| {
4733 this.submit_feedback_message(cx);
4734 })),
4735 ),
4736 )
4737 }
4738
4739 fn render_thread_controls(
4740 &self,
4741 thread: &Entity<AcpThread>,
4742 cx: &Context<Self>,
4743 ) -> impl IntoElement {
4744 let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
4745 if is_generating {
4746 return Empty.into_any_element();
4747 }
4748
4749 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
4750 .shape(ui::IconButtonShape::Square)
4751 .icon_size(IconSize::Small)
4752 .icon_color(Color::Ignored)
4753 .tooltip(Tooltip::text("Open Thread as Markdown"))
4754 .on_click(cx.listener(move |this, _, window, cx| {
4755 if let Some(workspace) = this.workspace.upgrade() {
4756 this.open_thread_as_markdown(workspace, window, cx)
4757 .detach_and_log_err(cx);
4758 }
4759 }));
4760
4761 let scroll_to_recent_user_prompt =
4762 IconButton::new("scroll_to_recent_user_prompt", IconName::ForwardArrow)
4763 .shape(ui::IconButtonShape::Square)
4764 .icon_size(IconSize::Small)
4765 .icon_color(Color::Ignored)
4766 .tooltip(Tooltip::text("Scroll To Most Recent User Prompt"))
4767 .on_click(cx.listener(move |this, _, _, cx| {
4768 this.scroll_to_most_recent_user_prompt(cx);
4769 }));
4770
4771 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
4772 .shape(ui::IconButtonShape::Square)
4773 .icon_size(IconSize::Small)
4774 .icon_color(Color::Ignored)
4775 .tooltip(Tooltip::text("Scroll To Top"))
4776 .on_click(cx.listener(move |this, _, _, cx| {
4777 this.scroll_to_top(cx);
4778 }));
4779
4780 let show_stats = AgentSettings::get_global(cx).show_turn_stats;
4781 let last_turn_clock = show_stats
4782 .then(|| {
4783 self.turn_fields
4784 .last_turn_duration
4785 .filter(|&duration| duration > STOPWATCH_THRESHOLD)
4786 .map(|duration| {
4787 Label::new(duration_alt_display(duration))
4788 .size(LabelSize::Small)
4789 .color(Color::Muted)
4790 })
4791 })
4792 .flatten();
4793
4794 let last_turn_tokens_label = last_turn_clock
4795 .is_some()
4796 .then(|| {
4797 self.turn_fields
4798 .last_turn_tokens
4799 .filter(|&tokens| tokens > TOKEN_THRESHOLD)
4800 .map(|tokens| {
4801 Label::new(format!("{} tokens", crate::humanize_token_count(tokens)))
4802 .size(LabelSize::Small)
4803 .color(Color::Muted)
4804 })
4805 })
4806 .flatten();
4807
4808 let mut container = h_flex()
4809 .w_full()
4810 .py_2()
4811 .px_5()
4812 .gap_px()
4813 .opacity(0.6)
4814 .hover(|s| s.opacity(1.))
4815 .justify_end()
4816 .when(
4817 last_turn_tokens_label.is_some() || last_turn_clock.is_some(),
4818 |this| {
4819 this.child(
4820 h_flex()
4821 .gap_1()
4822 .px_1()
4823 .when_some(last_turn_tokens_label, |this, label| this.child(label))
4824 .when_some(last_turn_clock, |this, label| this.child(label)),
4825 )
4826 },
4827 );
4828
4829 if AgentSettings::get_global(cx).enable_feedback
4830 && self.thread.read(cx).connection().telemetry().is_some()
4831 {
4832 let feedback = self.thread_feedback.feedback;
4833
4834 let tooltip_meta = || {
4835 SharedString::new(
4836 "Rating the thread sends all of your current conversation to the Zed team.",
4837 )
4838 };
4839
4840 container = container
4841 .child(
4842 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
4843 .shape(ui::IconButtonShape::Square)
4844 .icon_size(IconSize::Small)
4845 .icon_color(match feedback {
4846 Some(ThreadFeedback::Positive) => Color::Accent,
4847 _ => Color::Ignored,
4848 })
4849 .tooltip(move |window, cx| match feedback {
4850 Some(ThreadFeedback::Positive) => {
4851 Tooltip::text("Thanks for your feedback!")(window, cx)
4852 }
4853 _ => {
4854 Tooltip::with_meta("Helpful Response", None, tooltip_meta(), cx)
4855 }
4856 })
4857 .on_click(cx.listener(move |this, _, window, cx| {
4858 this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
4859 })),
4860 )
4861 .child(
4862 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
4863 .shape(ui::IconButtonShape::Square)
4864 .icon_size(IconSize::Small)
4865 .icon_color(match feedback {
4866 Some(ThreadFeedback::Negative) => Color::Accent,
4867 _ => Color::Ignored,
4868 })
4869 .tooltip(move |window, cx| match feedback {
4870 Some(ThreadFeedback::Negative) => {
4871 Tooltip::text(
4872 "We appreciate your feedback and will use it to improve in the future.",
4873 )(window, cx)
4874 }
4875 _ => {
4876 Tooltip::with_meta(
4877 "Not Helpful Response",
4878 None,
4879 tooltip_meta(),
4880 cx,
4881 )
4882 }
4883 })
4884 .on_click(cx.listener(move |this, _, window, cx| {
4885 this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
4886 })),
4887 );
4888 }
4889
4890 if let Some(project) = self.project.upgrade()
4891 && let Some(server_view) = self.server_view.upgrade()
4892 && cx.has_flag::<AgentSharingFeatureFlag>()
4893 && project.read(cx).client().status().borrow().is_connected()
4894 {
4895 let button = if self.is_imported_thread(cx) {
4896 IconButton::new("sync-thread", IconName::ArrowCircle)
4897 .shape(ui::IconButtonShape::Square)
4898 .icon_size(IconSize::Small)
4899 .icon_color(Color::Ignored)
4900 .tooltip(Tooltip::text("Sync with source thread"))
4901 .on_click(cx.listener(move |this, _, window, cx| {
4902 this.sync_thread(project.clone(), server_view.clone(), window, cx);
4903 }))
4904 } else {
4905 IconButton::new("share-thread", IconName::ArrowUpRight)
4906 .shape(ui::IconButtonShape::Square)
4907 .icon_size(IconSize::Small)
4908 .icon_color(Color::Ignored)
4909 .tooltip(Tooltip::text("Share Thread"))
4910 .on_click(cx.listener(move |this, _, window, cx| {
4911 this.share_thread(window, cx);
4912 }))
4913 };
4914
4915 container = container.child(button);
4916 }
4917
4918 container
4919 .child(open_as_markdown)
4920 .child(scroll_to_recent_user_prompt)
4921 .child(scroll_to_top)
4922 .into_any_element()
4923 }
4924
4925 pub(crate) fn scroll_to_most_recent_user_prompt(&mut self, cx: &mut Context<Self>) {
4926 let entries = self.thread.read(cx).entries();
4927 if entries.is_empty() {
4928 return;
4929 }
4930
4931 // Find the most recent user message and scroll it to the top of the viewport.
4932 // (Fallback: if no user message exists, scroll to the bottom.)
4933 if let Some(ix) = entries
4934 .iter()
4935 .rposition(|entry| matches!(entry, AgentThreadEntry::UserMessage(_)))
4936 {
4937 self.list_state.scroll_to(ListOffset {
4938 item_ix: ix,
4939 offset_in_item: px(0.0),
4940 });
4941 cx.notify();
4942 } else {
4943 self.scroll_to_end(cx);
4944 }
4945 }
4946
4947 pub fn scroll_to_end(&mut self, cx: &mut Context<Self>) {
4948 self.list_state.set_follow_tail(true);
4949 cx.notify();
4950 }
4951
4952 fn handle_feedback_click(
4953 &mut self,
4954 feedback: ThreadFeedback,
4955 window: &mut Window,
4956 cx: &mut Context<Self>,
4957 ) {
4958 self.thread_feedback
4959 .submit(self.thread.clone(), feedback, window, cx);
4960 cx.notify();
4961 }
4962
4963 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
4964 let thread = self.thread.clone();
4965 self.thread_feedback.submit_comments(thread, cx);
4966 cx.notify();
4967 }
4968
4969 pub(crate) fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
4970 self.list_state.set_follow_tail(false);
4971 self.list_state.scroll_to(ListOffset::default());
4972 cx.notify();
4973 }
4974
4975 fn scroll_output_page_up(
4976 &mut self,
4977 _: &ScrollOutputPageUp,
4978 _window: &mut Window,
4979 cx: &mut Context<Self>,
4980 ) {
4981 let page_height = self.list_state.viewport_bounds().size.height;
4982 self.list_state.set_follow_tail(false);
4983 self.list_state.scroll_by(-page_height * 0.9);
4984 cx.notify();
4985 }
4986
4987 fn scroll_output_page_down(
4988 &mut self,
4989 _: &ScrollOutputPageDown,
4990 _window: &mut Window,
4991 cx: &mut Context<Self>,
4992 ) {
4993 let page_height = self.list_state.viewport_bounds().size.height;
4994 self.list_state.set_follow_tail(false);
4995 self.list_state.scroll_by(page_height * 0.9);
4996 if self.list_state.is_at_bottom() {
4997 self.list_state.set_follow_tail(true);
4998 }
4999 cx.notify();
5000 }
5001
5002 fn scroll_output_line_up(
5003 &mut self,
5004 _: &ScrollOutputLineUp,
5005 window: &mut Window,
5006 cx: &mut Context<Self>,
5007 ) {
5008 self.list_state.set_follow_tail(false);
5009 self.list_state.scroll_by(-window.line_height() * 3.);
5010 cx.notify();
5011 }
5012
5013 fn scroll_output_line_down(
5014 &mut self,
5015 _: &ScrollOutputLineDown,
5016 window: &mut Window,
5017 cx: &mut Context<Self>,
5018 ) {
5019 self.list_state.set_follow_tail(false);
5020 self.list_state.scroll_by(window.line_height() * 3.);
5021 if self.list_state.is_at_bottom() {
5022 self.list_state.set_follow_tail(true);
5023 }
5024 cx.notify();
5025 }
5026
5027 fn scroll_output_to_top(
5028 &mut self,
5029 _: &ScrollOutputToTop,
5030 _window: &mut Window,
5031 cx: &mut Context<Self>,
5032 ) {
5033 self.scroll_to_top(cx);
5034 }
5035
5036 fn scroll_output_to_bottom(
5037 &mut self,
5038 _: &ScrollOutputToBottom,
5039 _window: &mut Window,
5040 cx: &mut Context<Self>,
5041 ) {
5042 self.scroll_to_end(cx);
5043 }
5044
5045 fn scroll_output_to_previous_message(
5046 &mut self,
5047 _: &ScrollOutputToPreviousMessage,
5048 _window: &mut Window,
5049 cx: &mut Context<Self>,
5050 ) {
5051 let entries = self.thread.read(cx).entries();
5052 let current_ix = self.list_state.logical_scroll_top().item_ix;
5053 if let Some(target_ix) = (0..current_ix)
5054 .rev()
5055 .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
5056 {
5057 self.list_state.set_follow_tail(false);
5058 self.list_state.scroll_to(ListOffset {
5059 item_ix: target_ix,
5060 offset_in_item: px(0.),
5061 });
5062 cx.notify();
5063 }
5064 }
5065
5066 fn scroll_output_to_next_message(
5067 &mut self,
5068 _: &ScrollOutputToNextMessage,
5069 _window: &mut Window,
5070 cx: &mut Context<Self>,
5071 ) {
5072 let entries = self.thread.read(cx).entries();
5073 let current_ix = self.list_state.logical_scroll_top().item_ix;
5074 if let Some(target_ix) = (current_ix + 1..entries.len())
5075 .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
5076 {
5077 self.list_state.set_follow_tail(false);
5078 self.list_state.scroll_to(ListOffset {
5079 item_ix: target_ix,
5080 offset_in_item: px(0.),
5081 });
5082 cx.notify();
5083 }
5084 }
5085
5086 pub fn open_thread_as_markdown(
5087 &self,
5088 workspace: Entity<Workspace>,
5089 window: &mut Window,
5090 cx: &mut App,
5091 ) -> Task<Result<()>> {
5092 let markdown_language_task = workspace
5093 .read(cx)
5094 .app_state()
5095 .languages
5096 .language_for_name("Markdown");
5097
5098 let thread = self.thread.read(cx);
5099 let thread_title = thread
5100 .title()
5101 .unwrap_or_else(|| DEFAULT_THREAD_TITLE.into())
5102 .to_string();
5103 let markdown = thread.to_markdown(cx);
5104
5105 let project = workspace.read(cx).project().clone();
5106 window.spawn(cx, async move |cx| {
5107 let markdown_language = markdown_language_task.await?;
5108
5109 let buffer = project
5110 .update(cx, |project, cx| {
5111 project.create_buffer(Some(markdown_language), false, cx)
5112 })
5113 .await?;
5114
5115 buffer.update(cx, |buffer, cx| {
5116 buffer.set_text(markdown, cx);
5117 buffer.set_capability(language::Capability::ReadWrite, cx);
5118 });
5119
5120 workspace.update_in(cx, |workspace, window, cx| {
5121 let buffer = cx
5122 .new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_title.clone()));
5123
5124 workspace.add_item_to_active_pane(
5125 Box::new(cx.new(|cx| {
5126 let mut editor =
5127 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
5128 editor.set_breadcrumb_header(thread_title);
5129 editor
5130 })),
5131 None,
5132 true,
5133 window,
5134 cx,
5135 );
5136 })?;
5137 anyhow::Ok(())
5138 })
5139 }
5140
5141 pub(crate) fn sync_editor_mode_for_empty_state(&mut self, cx: &mut Context<Self>) {
5142 let has_messages = self.list_state.item_count() > 0;
5143 let v2_empty_state = cx.has_flag::<AgentV2FeatureFlag>() && !has_messages;
5144
5145 let mode = if v2_empty_state {
5146 EditorMode::Full {
5147 scale_ui_elements_with_buffer_font_size: false,
5148 show_active_line_background: false,
5149 sizing_behavior: SizingBehavior::Default,
5150 }
5151 } else {
5152 EditorMode::AutoHeight {
5153 min_lines: AgentSettings::get_global(cx).message_editor_min_lines,
5154 max_lines: Some(AgentSettings::get_global(cx).set_message_editor_max_lines()),
5155 }
5156 };
5157 self.message_editor.update(cx, |editor, cx| {
5158 editor.set_mode(mode, cx);
5159 });
5160 }
5161
5162 /// Ensures the list item count includes (or excludes) an extra item for the generating indicator
5163 pub(crate) fn sync_generating_indicator(&mut self, cx: &App) {
5164 let is_generating = matches!(self.thread.read(cx).status(), ThreadStatus::Generating);
5165
5166 if is_generating && !self.generating_indicator_in_list {
5167 let entries_count = self.thread.read(cx).entries().len();
5168 self.list_state.splice(entries_count..entries_count, 1);
5169 self.generating_indicator_in_list = true;
5170 } else if !is_generating && self.generating_indicator_in_list {
5171 let entries_count = self.thread.read(cx).entries().len();
5172 self.list_state.splice(entries_count..entries_count + 1, 0);
5173 self.generating_indicator_in_list = false;
5174 }
5175 }
5176
5177 fn render_generating(&self, confirmation: bool, cx: &App) -> impl IntoElement {
5178 let show_stats = AgentSettings::get_global(cx).show_turn_stats;
5179 let elapsed_label = show_stats
5180 .then(|| {
5181 self.turn_fields.turn_started_at.and_then(|started_at| {
5182 let elapsed = started_at.elapsed();
5183 (elapsed > STOPWATCH_THRESHOLD).then(|| duration_alt_display(elapsed))
5184 })
5185 })
5186 .flatten();
5187
5188 let is_blocked_on_terminal_command =
5189 !confirmation && self.is_blocked_on_terminal_command(cx);
5190 let is_waiting = confirmation || self.thread.read(cx).has_in_progress_tool_calls();
5191
5192 let turn_tokens_label = elapsed_label
5193 .is_some()
5194 .then(|| {
5195 self.turn_fields
5196 .turn_tokens
5197 .filter(|&tokens| tokens > TOKEN_THRESHOLD)
5198 .map(|tokens| crate::humanize_token_count(tokens))
5199 })
5200 .flatten();
5201
5202 let arrow_icon = if is_waiting {
5203 IconName::ArrowUp
5204 } else {
5205 IconName::ArrowDown
5206 };
5207
5208 h_flex()
5209 .id("generating-spinner")
5210 .py_2()
5211 .px(rems_from_px(22.))
5212 .gap_2()
5213 .map(|this| {
5214 if confirmation {
5215 this.child(
5216 h_flex()
5217 .w_2()
5218 .child(SpinnerLabel::sand().size(LabelSize::Small)),
5219 )
5220 .child(
5221 div().min_w(rems(8.)).child(
5222 LoadingLabel::new("Awaiting Confirmation")
5223 .size(LabelSize::Small)
5224 .color(Color::Muted),
5225 ),
5226 )
5227 } else if is_blocked_on_terminal_command {
5228 this
5229 } else {
5230 this.child(SpinnerLabel::new().size(LabelSize::Small))
5231 }
5232 })
5233 .when_some(elapsed_label, |this, elapsed| {
5234 this.child(
5235 Label::new(elapsed)
5236 .size(LabelSize::Small)
5237 .color(Color::Muted),
5238 )
5239 })
5240 .when_some(turn_tokens_label, |this, tokens| {
5241 this.child(
5242 h_flex()
5243 .gap_0p5()
5244 .child(
5245 Icon::new(arrow_icon)
5246 .size(IconSize::XSmall)
5247 .color(Color::Muted),
5248 )
5249 .child(
5250 Label::new(format!("{} tokens", tokens))
5251 .size(LabelSize::Small)
5252 .color(Color::Muted),
5253 ),
5254 )
5255 })
5256 .into_any_element()
5257 }
5258
5259 pub(crate) fn auto_expand_streaming_thought(&mut self, cx: &mut Context<Self>) {
5260 let thinking_display = AgentSettings::get_global(cx).thinking_display;
5261
5262 if !matches!(
5263 thinking_display,
5264 ThinkingBlockDisplay::Auto | ThinkingBlockDisplay::Preview
5265 ) {
5266 return;
5267 }
5268
5269 let key = {
5270 let thread = self.thread.read(cx);
5271 if thread.status() != ThreadStatus::Generating {
5272 return;
5273 }
5274 let entries = thread.entries();
5275 let last_ix = entries.len().saturating_sub(1);
5276 match entries.get(last_ix) {
5277 Some(AgentThreadEntry::AssistantMessage(msg)) => match msg.chunks.last() {
5278 Some(AssistantMessageChunk::Thought { .. }) => {
5279 Some((last_ix, msg.chunks.len() - 1))
5280 }
5281 _ => None,
5282 },
5283 _ => None,
5284 }
5285 };
5286
5287 if let Some(key) = key {
5288 if self.auto_expanded_thinking_block != Some(key) {
5289 self.auto_expanded_thinking_block = Some(key);
5290 self.expanded_thinking_blocks.insert(key);
5291 cx.notify();
5292 }
5293 } else if self.auto_expanded_thinking_block.is_some() {
5294 if thinking_display == ThinkingBlockDisplay::Auto {
5295 if let Some(key) = self.auto_expanded_thinking_block {
5296 if !self.user_toggled_thinking_blocks.contains(&key) {
5297 self.expanded_thinking_blocks.remove(&key);
5298 }
5299 }
5300 }
5301 self.auto_expanded_thinking_block = None;
5302 cx.notify();
5303 }
5304 }
5305
5306 pub(crate) fn clear_auto_expand_tracking(&mut self) {
5307 self.auto_expanded_thinking_block = None;
5308 }
5309
5310 fn toggle_thinking_block_expansion(&mut self, key: (usize, usize), cx: &mut Context<Self>) {
5311 let thinking_display = AgentSettings::get_global(cx).thinking_display;
5312
5313 match thinking_display {
5314 ThinkingBlockDisplay::Auto => {
5315 let is_open = self.expanded_thinking_blocks.contains(&key)
5316 || self.user_toggled_thinking_blocks.contains(&key);
5317
5318 if is_open {
5319 self.expanded_thinking_blocks.remove(&key);
5320 self.user_toggled_thinking_blocks.remove(&key);
5321 } else {
5322 self.expanded_thinking_blocks.insert(key);
5323 self.user_toggled_thinking_blocks.insert(key);
5324 }
5325 }
5326 ThinkingBlockDisplay::Preview => {
5327 let is_user_expanded = self.user_toggled_thinking_blocks.contains(&key);
5328 let is_in_expanded_set = self.expanded_thinking_blocks.contains(&key);
5329
5330 if is_user_expanded {
5331 self.user_toggled_thinking_blocks.remove(&key);
5332 self.expanded_thinking_blocks.remove(&key);
5333 } else if is_in_expanded_set {
5334 self.user_toggled_thinking_blocks.insert(key);
5335 } else {
5336 self.expanded_thinking_blocks.insert(key);
5337 self.user_toggled_thinking_blocks.insert(key);
5338 }
5339 }
5340 ThinkingBlockDisplay::AlwaysExpanded => {
5341 if self.user_toggled_thinking_blocks.contains(&key) {
5342 self.user_toggled_thinking_blocks.remove(&key);
5343 } else {
5344 self.user_toggled_thinking_blocks.insert(key);
5345 }
5346 }
5347 ThinkingBlockDisplay::AlwaysCollapsed => {
5348 if self.user_toggled_thinking_blocks.contains(&key) {
5349 self.user_toggled_thinking_blocks.remove(&key);
5350 self.expanded_thinking_blocks.remove(&key);
5351 } else {
5352 self.expanded_thinking_blocks.insert(key);
5353 self.user_toggled_thinking_blocks.insert(key);
5354 }
5355 }
5356 }
5357
5358 cx.notify();
5359 }
5360
5361 fn render_thinking_block(
5362 &self,
5363 entry_ix: usize,
5364 chunk_ix: usize,
5365 chunk: Entity<Markdown>,
5366 window: &Window,
5367 cx: &Context<Self>,
5368 ) -> AnyElement {
5369 let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
5370 let card_header_id = SharedString::from("inner-card-header");
5371
5372 let key = (entry_ix, chunk_ix);
5373
5374 let thinking_display = AgentSettings::get_global(cx).thinking_display;
5375 let is_user_toggled = self.user_toggled_thinking_blocks.contains(&key);
5376 let is_in_expanded_set = self.expanded_thinking_blocks.contains(&key);
5377
5378 let (is_open, is_constrained) = match thinking_display {
5379 ThinkingBlockDisplay::Auto => {
5380 let is_open = is_user_toggled || is_in_expanded_set;
5381 (is_open, false)
5382 }
5383 ThinkingBlockDisplay::Preview => {
5384 let is_open = is_user_toggled || is_in_expanded_set;
5385 let is_constrained = is_in_expanded_set && !is_user_toggled;
5386 (is_open, is_constrained)
5387 }
5388 ThinkingBlockDisplay::AlwaysExpanded => (!is_user_toggled, false),
5389 ThinkingBlockDisplay::AlwaysCollapsed => (is_user_toggled, false),
5390 };
5391
5392 let should_auto_scroll = self.auto_expanded_thinking_block == Some(key);
5393
5394 let scroll_handle = self
5395 .entry_view_state
5396 .read(cx)
5397 .entry(entry_ix)
5398 .and_then(|entry| entry.scroll_handle_for_assistant_message_chunk(chunk_ix));
5399
5400 if should_auto_scroll {
5401 if let Some(ref handle) = scroll_handle {
5402 handle.scroll_to_bottom();
5403 }
5404 }
5405
5406 let panel_bg = cx.theme().colors().panel_background;
5407
5408 v_flex()
5409 .gap_1()
5410 .child(
5411 h_flex()
5412 .id(header_id)
5413 .group(&card_header_id)
5414 .relative()
5415 .w_full()
5416 .pr_1()
5417 .justify_between()
5418 .child(
5419 h_flex()
5420 .h(window.line_height() - px(2.))
5421 .gap_1p5()
5422 .overflow_hidden()
5423 .child(
5424 Icon::new(IconName::ToolThink)
5425 .size(IconSize::Small)
5426 .color(Color::Muted),
5427 )
5428 .child(
5429 div()
5430 .text_size(self.tool_name_font_size())
5431 .text_color(cx.theme().colors().text_muted)
5432 .child("Thinking"),
5433 ),
5434 )
5435 .child(
5436 Disclosure::new(("expand", entry_ix), is_open)
5437 .opened_icon(IconName::ChevronUp)
5438 .closed_icon(IconName::ChevronDown)
5439 .visible_on_hover(&card_header_id)
5440 .on_click(cx.listener(
5441 move |this, _event: &ClickEvent, _window, cx| {
5442 this.toggle_thinking_block_expansion(key, cx);
5443 },
5444 )),
5445 )
5446 .on_click(cx.listener(move |this, _event: &ClickEvent, _window, cx| {
5447 this.toggle_thinking_block_expansion(key, cx);
5448 })),
5449 )
5450 .when(is_open, |this| {
5451 this.child(
5452 div()
5453 .when(is_constrained, |this| this.relative())
5454 .child(
5455 div()
5456 .id(("thinking-content", chunk_ix))
5457 .ml_1p5()
5458 .pl_3p5()
5459 .border_l_1()
5460 .border_color(self.tool_card_border_color(cx))
5461 .when(is_constrained, |this| this.max_h_64())
5462 .when_some(scroll_handle, |this, scroll_handle| {
5463 this.track_scroll(&scroll_handle)
5464 })
5465 .overflow_hidden()
5466 .child(self.render_markdown(
5467 chunk,
5468 MarkdownStyle::themed(MarkdownFont::Agent, window, cx),
5469 )),
5470 )
5471 .when(is_constrained, |this| {
5472 this.child(
5473 div()
5474 .absolute()
5475 .inset_0()
5476 .size_full()
5477 .bg(linear_gradient(
5478 180.,
5479 linear_color_stop(panel_bg.opacity(0.8), 0.),
5480 linear_color_stop(panel_bg.opacity(0.), 0.1),
5481 ))
5482 .block_mouse_except_scroll(),
5483 )
5484 }),
5485 )
5486 })
5487 .into_any_element()
5488 }
5489
5490 fn render_message_context_menu(
5491 &self,
5492 entry_ix: usize,
5493 message_body: AnyElement,
5494 cx: &Context<Self>,
5495 ) -> AnyElement {
5496 let entity = cx.entity();
5497 let workspace = self.workspace.clone();
5498
5499 right_click_menu(format!("agent_context_menu-{}", entry_ix))
5500 .trigger(move |_, _, _| message_body)
5501 .menu(move |window, cx| {
5502 let focus = window.focused(cx);
5503 let entity = entity.clone();
5504 let workspace = workspace.clone();
5505
5506 ContextMenu::build(window, cx, move |menu, _, cx| {
5507 let this = entity.read(cx);
5508 let is_at_top = this.list_state.logical_scroll_top().item_ix == 0;
5509
5510 let has_selection = this
5511 .thread
5512 .read(cx)
5513 .entries()
5514 .get(entry_ix)
5515 .and_then(|entry| match &entry {
5516 AgentThreadEntry::AssistantMessage(msg) => Some(&msg.chunks),
5517 _ => None,
5518 })
5519 .map(|chunks| {
5520 chunks.iter().any(|chunk| {
5521 let md = match chunk {
5522 AssistantMessageChunk::Message { block } => block.markdown(),
5523 AssistantMessageChunk::Thought { block } => block.markdown(),
5524 };
5525 md.map_or(false, |m| m.read(cx).selected_text().is_some())
5526 })
5527 })
5528 .unwrap_or(false);
5529
5530 let copy_this_agent_response =
5531 ContextMenuEntry::new("Copy This Agent Response").handler({
5532 let entity = entity.clone();
5533 move |_, cx| {
5534 entity.update(cx, |this, cx| {
5535 let entries = this.thread.read(cx).entries();
5536 if let Some(text) =
5537 Self::get_agent_message_content(entries, entry_ix, cx)
5538 {
5539 cx.write_to_clipboard(ClipboardItem::new_string(text));
5540 }
5541 });
5542 }
5543 });
5544
5545 let scroll_item = if is_at_top {
5546 ContextMenuEntry::new("Scroll to Bottom").handler({
5547 let entity = entity.clone();
5548 move |_, cx| {
5549 entity.update(cx, |this, cx| {
5550 this.scroll_to_end(cx);
5551 });
5552 }
5553 })
5554 } else {
5555 ContextMenuEntry::new("Scroll to Top").handler({
5556 let entity = entity.clone();
5557 move |_, cx| {
5558 entity.update(cx, |this, cx| {
5559 this.scroll_to_top(cx);
5560 });
5561 }
5562 })
5563 };
5564
5565 let open_thread_as_markdown = ContextMenuEntry::new("Open Thread as Markdown")
5566 .handler({
5567 let entity = entity.clone();
5568 let workspace = workspace.clone();
5569 move |window, cx| {
5570 if let Some(workspace) = workspace.upgrade() {
5571 entity
5572 .update(cx, |this, cx| {
5573 this.open_thread_as_markdown(workspace, window, cx)
5574 })
5575 .detach_and_log_err(cx);
5576 }
5577 }
5578 });
5579
5580 menu.when_some(focus, |menu, focus| menu.context(focus))
5581 .action_disabled_when(
5582 !has_selection,
5583 "Copy Selection",
5584 Box::new(markdown::CopyAsMarkdown),
5585 )
5586 .item(copy_this_agent_response)
5587 .separator()
5588 .item(scroll_item)
5589 .item(open_thread_as_markdown)
5590 })
5591 })
5592 .into_any_element()
5593 }
5594
5595 fn get_agent_message_content(
5596 entries: &[AgentThreadEntry],
5597 entry_index: usize,
5598 cx: &App,
5599 ) -> Option<String> {
5600 let entry = entries.get(entry_index)?;
5601 if matches!(entry, AgentThreadEntry::UserMessage(_)) {
5602 return None;
5603 }
5604
5605 let start_index = (0..entry_index)
5606 .rev()
5607 .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
5608 .map(|i| i + 1)
5609 .unwrap_or(0);
5610
5611 let end_index = (entry_index + 1..entries.len())
5612 .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
5613 .map(|i| i - 1)
5614 .unwrap_or(entries.len() - 1);
5615
5616 let parts: Vec<String> = (start_index..=end_index)
5617 .filter_map(|i| entries.get(i))
5618 .filter_map(|entry| {
5619 if let AgentThreadEntry::AssistantMessage(message) = entry {
5620 let text: String = message
5621 .chunks
5622 .iter()
5623 .filter_map(|chunk| match chunk {
5624 AssistantMessageChunk::Message { block } => {
5625 let markdown = block.to_markdown(cx);
5626 if markdown.trim().is_empty() {
5627 None
5628 } else {
5629 Some(markdown.to_string())
5630 }
5631 }
5632 AssistantMessageChunk::Thought { .. } => None,
5633 })
5634 .collect::<Vec<_>>()
5635 .join("\n\n");
5636
5637 if text.is_empty() { None } else { Some(text) }
5638 } else {
5639 None
5640 }
5641 })
5642 .collect();
5643
5644 let text = parts.join("\n\n");
5645 if text.is_empty() { None } else { Some(text) }
5646 }
5647
5648 fn is_blocked_on_terminal_command(&self, cx: &App) -> bool {
5649 let thread = self.thread.read(cx);
5650 if !matches!(thread.status(), ThreadStatus::Generating) {
5651 return false;
5652 }
5653
5654 let mut has_running_terminal_call = false;
5655
5656 for entry in thread.entries().iter().rev() {
5657 match entry {
5658 AgentThreadEntry::UserMessage(_) => break,
5659 AgentThreadEntry::ToolCall(tool_call)
5660 if matches!(
5661 tool_call.status,
5662 ToolCallStatus::InProgress | ToolCallStatus::Pending
5663 ) =>
5664 {
5665 if matches!(tool_call.kind, acp::ToolKind::Execute) {
5666 has_running_terminal_call = true;
5667 } else {
5668 return false;
5669 }
5670 }
5671 AgentThreadEntry::ToolCall(_)
5672 | AgentThreadEntry::AssistantMessage(_)
5673 | AgentThreadEntry::CompletedPlan(_) => {}
5674 }
5675 }
5676
5677 has_running_terminal_call
5678 }
5679
5680 fn render_collapsible_command(
5681 &self,
5682 group: SharedString,
5683 is_preview: bool,
5684 command_source: &str,
5685 cx: &Context<Self>,
5686 ) -> Div {
5687 v_flex()
5688 .group(group.clone())
5689 .p_1p5()
5690 .bg(self.tool_card_header_bg(cx))
5691 .when(is_preview, |this| {
5692 this.pt_1().child(
5693 // Wrapping this label on a container with 24px height to avoid
5694 // layout shift when it changes from being a preview label
5695 // to the actual path where the command will run in
5696 h_flex().h_6().child(
5697 Label::new("Run Command")
5698 .buffer_font(cx)
5699 .size(LabelSize::XSmall)
5700 .color(Color::Muted),
5701 ),
5702 )
5703 })
5704 .children(command_source.lines().map(|line| {
5705 let text: SharedString = if line.is_empty() {
5706 " ".into()
5707 } else {
5708 line.to_string().into()
5709 };
5710
5711 Label::new(text).buffer_font(cx).size(LabelSize::Small)
5712 }))
5713 .child(
5714 div().absolute().top_1().right_1().child(
5715 CopyButton::new("copy-command", command_source.to_string())
5716 .tooltip_label("Copy Command")
5717 .visible_on_hover(group),
5718 ),
5719 )
5720 }
5721
5722 fn render_terminal_tool_call(
5723 &self,
5724 active_session_id: &acp::SessionId,
5725 entry_ix: usize,
5726 terminal: &Entity<acp_thread::Terminal>,
5727 tool_call: &ToolCall,
5728 focus_handle: &FocusHandle,
5729 is_subagent: bool,
5730 window: &Window,
5731 cx: &Context<Self>,
5732 ) -> AnyElement {
5733 let terminal_data = terminal.read(cx);
5734 let working_dir = terminal_data.working_dir();
5735 let command = terminal_data.command();
5736 let started_at = terminal_data.started_at();
5737
5738 let tool_failed = matches!(
5739 &tool_call.status,
5740 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed
5741 );
5742
5743 let confirmation_options = match &tool_call.status {
5744 ToolCallStatus::WaitingForConfirmation { options, .. } => Some(options),
5745 _ => None,
5746 };
5747 let needs_confirmation = confirmation_options.is_some();
5748
5749 let output = terminal_data.output();
5750 let command_finished = output.is_some()
5751 && !matches!(
5752 tool_call.status,
5753 ToolCallStatus::InProgress | ToolCallStatus::Pending
5754 );
5755 let truncated_output =
5756 output.is_some_and(|output| output.original_content_len > output.content.len());
5757 let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
5758
5759 let command_failed = command_finished
5760 && output.is_some_and(|o| o.exit_status.is_some_and(|status| !status.success()));
5761
5762 let time_elapsed = if let Some(output) = output {
5763 output.ended_at.duration_since(started_at)
5764 } else {
5765 started_at.elapsed()
5766 };
5767
5768 let header_id =
5769 SharedString::from(format!("terminal-tool-header-{}", terminal.entity_id()));
5770 let header_group = SharedString::from(format!(
5771 "terminal-tool-header-group-{}",
5772 terminal.entity_id()
5773 ));
5774 let header_bg = cx
5775 .theme()
5776 .colors()
5777 .element_background
5778 .blend(cx.theme().colors().editor_foreground.opacity(0.025));
5779 let border_color = cx.theme().colors().border.opacity(0.6);
5780
5781 let working_dir = working_dir
5782 .as_ref()
5783 .map(|path| path.display().to_string())
5784 .unwrap_or_else(|| "current directory".to_string());
5785
5786 // Since the command's source is wrapped in a markdown code block
5787 // (```\n...\n```), we need to strip that so we're left with only the
5788 // command's content.
5789 let command_source = command.read(cx).source();
5790 let command_content = command_source
5791 .strip_prefix("```\n")
5792 .and_then(|s| s.strip_suffix("\n```"))
5793 .unwrap_or(&command_source);
5794
5795 let command_element =
5796 self.render_collapsible_command(header_group.clone(), false, command_content, cx);
5797
5798 let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
5799
5800 let header = h_flex()
5801 .id(header_id)
5802 .pt_1()
5803 .pl_1p5()
5804 .pr_1()
5805 .flex_none()
5806 .gap_1()
5807 .justify_between()
5808 .rounded_t_md()
5809 .child(
5810 div()
5811 .id(("command-target-path", terminal.entity_id()))
5812 .w_full()
5813 .max_w_full()
5814 .overflow_x_scroll()
5815 .child(
5816 Label::new(working_dir)
5817 .buffer_font(cx)
5818 .size(LabelSize::XSmall)
5819 .color(Color::Muted),
5820 ),
5821 )
5822 .child(
5823 Disclosure::new(
5824 SharedString::from(format!(
5825 "terminal-tool-disclosure-{}",
5826 terminal.entity_id()
5827 )),
5828 is_expanded,
5829 )
5830 .opened_icon(IconName::ChevronUp)
5831 .closed_icon(IconName::ChevronDown)
5832 .visible_on_hover(&header_group)
5833 .on_click(cx.listener({
5834 let id = tool_call.id.clone();
5835 move |this, _event, _window, cx| {
5836 if is_expanded {
5837 this.expanded_tool_calls.remove(&id);
5838 } else {
5839 this.expanded_tool_calls.insert(id.clone());
5840 }
5841 cx.notify();
5842 }
5843 })),
5844 )
5845 .when(time_elapsed > Duration::from_secs(10), |header| {
5846 header.child(
5847 Label::new(format!("({})", duration_alt_display(time_elapsed)))
5848 .buffer_font(cx)
5849 .color(Color::Muted)
5850 .size(LabelSize::XSmall),
5851 )
5852 })
5853 .when(!command_finished && !needs_confirmation, |header| {
5854 header
5855 .gap_1p5()
5856 .child(
5857 Icon::new(IconName::ArrowCircle)
5858 .size(IconSize::XSmall)
5859 .color(Color::Muted)
5860 .with_rotate_animation(2)
5861 )
5862 .child(div().h(relative(0.6)).ml_1p5().child(Divider::vertical().color(DividerColor::Border)))
5863 .child(
5864 IconButton::new(
5865 SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
5866 IconName::Stop
5867 )
5868 .icon_size(IconSize::Small)
5869 .icon_color(Color::Error)
5870 .tooltip(move |_window, cx| {
5871 Tooltip::with_meta(
5872 "Stop This Command",
5873 None,
5874 "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
5875 cx,
5876 )
5877 })
5878 .on_click({
5879 let terminal = terminal.clone();
5880 cx.listener(move |this, _event, _window, cx| {
5881 terminal.update(cx, |terminal, cx| {
5882 terminal.stop_by_user(cx);
5883 });
5884 if AgentSettings::get_global(cx).cancel_generation_on_terminal_stop {
5885 this.cancel_generation(cx);
5886 }
5887 })
5888 }),
5889 )
5890 })
5891 .when(truncated_output, |header| {
5892 let tooltip = if let Some(output) = output {
5893 if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
5894 format!("Output exceeded terminal max lines and was \
5895 truncated, the model received the first {}.", format_file_size(output.content.len() as u64, true))
5896 } else {
5897 format!(
5898 "Output is {} long, and to avoid unexpected token usage, \
5899 only {} was sent back to the agent.",
5900 format_file_size(output.original_content_len as u64, true),
5901 format_file_size(output.content.len() as u64, true)
5902 )
5903 }
5904 } else {
5905 "Output was truncated".to_string()
5906 };
5907
5908 header.child(
5909 h_flex()
5910 .id(("terminal-tool-truncated-label", terminal.entity_id()))
5911 .gap_1()
5912 .child(
5913 Icon::new(IconName::Info)
5914 .size(IconSize::XSmall)
5915 .color(Color::Ignored),
5916 )
5917 .child(
5918 Label::new("Truncated")
5919 .color(Color::Muted)
5920 .size(LabelSize::XSmall),
5921 )
5922 .tooltip(Tooltip::text(tooltip)),
5923 )
5924 })
5925 .when(tool_failed || command_failed, |header| {
5926 header.child(
5927 div()
5928 .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
5929 .child(
5930 Icon::new(IconName::Close)
5931 .size(IconSize::Small)
5932 .color(Color::Error),
5933 )
5934 .when_some(output.and_then(|o| o.exit_status), |this, status| {
5935 this.tooltip(Tooltip::text(format!(
5936 "Exited with code {}",
5937 status.code().unwrap_or(-1),
5938 )))
5939 }),
5940 )
5941 })
5942;
5943
5944 let terminal_view = self
5945 .entry_view_state
5946 .read(cx)
5947 .entry(entry_ix)
5948 .and_then(|entry| entry.terminal(terminal));
5949
5950 v_flex()
5951 .when(!is_subagent, |this| {
5952 this.my_1p5()
5953 .mx_5()
5954 .border_1()
5955 .when(tool_failed || command_failed, |card| card.border_dashed())
5956 .border_color(border_color)
5957 .rounded_md()
5958 })
5959 .overflow_hidden()
5960 .child(
5961 v_flex()
5962 .group(&header_group)
5963 .bg(header_bg)
5964 .text_xs()
5965 .child(header)
5966 .child(command_element),
5967 )
5968 .when(is_expanded && terminal_view.is_some(), |this| {
5969 this.child(
5970 div()
5971 .pt_2()
5972 .border_t_1()
5973 .when(tool_failed || command_failed, |card| card.border_dashed())
5974 .border_color(border_color)
5975 .bg(cx.theme().colors().editor_background)
5976 .rounded_b_md()
5977 .text_ui_sm(cx)
5978 .h_full()
5979 .children(terminal_view.map(|terminal_view| {
5980 let element = if terminal_view
5981 .read(cx)
5982 .content_mode(window, cx)
5983 .is_scrollable()
5984 {
5985 div().h_72().child(terminal_view).into_any_element()
5986 } else {
5987 terminal_view.into_any_element()
5988 };
5989
5990 div()
5991 .on_action(cx.listener(|_this, _: &NewTerminal, window, cx| {
5992 window.dispatch_action(NewThread.boxed_clone(), cx);
5993 cx.stop_propagation();
5994 }))
5995 .child(element)
5996 .into_any_element()
5997 })),
5998 )
5999 })
6000 .when_some(confirmation_options, |this, options| {
6001 let is_first = self.is_first_tool_call(active_session_id, &tool_call.id, cx);
6002 this.child(self.render_permission_buttons(
6003 self.id.clone(),
6004 is_first,
6005 options,
6006 entry_ix,
6007 tool_call.id.clone(),
6008 focus_handle,
6009 cx,
6010 ))
6011 })
6012 .into_any()
6013 }
6014
6015 fn is_first_tool_call(
6016 &self,
6017 active_session_id: &acp::SessionId,
6018 tool_call_id: &acp::ToolCallId,
6019 cx: &App,
6020 ) -> bool {
6021 self.conversation
6022 .read(cx)
6023 .pending_tool_call(active_session_id, cx)
6024 .map_or(false, |(pending_session_id, pending_tool_call_id, _)| {
6025 self.id == pending_session_id && tool_call_id == &pending_tool_call_id
6026 })
6027 }
6028
6029 fn render_any_tool_call(
6030 &self,
6031 active_session_id: &acp::SessionId,
6032 entry_ix: usize,
6033 tool_call: &ToolCall,
6034 focus_handle: &FocusHandle,
6035 is_subagent: bool,
6036 window: &Window,
6037 cx: &Context<Self>,
6038 ) -> Div {
6039 let has_terminals = tool_call.terminals().next().is_some();
6040
6041 div().w_full().map(|this| {
6042 if tool_call.is_subagent() {
6043 this.child(
6044 self.render_subagent_tool_call(
6045 active_session_id,
6046 entry_ix,
6047 tool_call,
6048 tool_call
6049 .subagent_session_info
6050 .as_ref()
6051 .map(|i| i.session_id.clone()),
6052 focus_handle,
6053 window,
6054 cx,
6055 ),
6056 )
6057 } else if has_terminals {
6058 this.children(tool_call.terminals().map(|terminal| {
6059 self.render_terminal_tool_call(
6060 active_session_id,
6061 entry_ix,
6062 terminal,
6063 tool_call,
6064 focus_handle,
6065 is_subagent,
6066 window,
6067 cx,
6068 )
6069 }))
6070 } else {
6071 this.child(self.render_tool_call(
6072 active_session_id,
6073 entry_ix,
6074 tool_call,
6075 focus_handle,
6076 is_subagent,
6077 window,
6078 cx,
6079 ))
6080 }
6081 })
6082 }
6083
6084 fn render_tool_call(
6085 &self,
6086 active_session_id: &acp::SessionId,
6087 entry_ix: usize,
6088 tool_call: &ToolCall,
6089 focus_handle: &FocusHandle,
6090 is_subagent: bool,
6091 window: &Window,
6092 cx: &Context<Self>,
6093 ) -> Div {
6094 let has_location = tool_call.locations.len() == 1;
6095 let card_header_id = SharedString::from("inner-tool-call-header");
6096
6097 let failed_or_canceled = match &tool_call.status {
6098 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed => true,
6099 _ => false,
6100 };
6101
6102 let needs_confirmation = matches!(
6103 tool_call.status,
6104 ToolCallStatus::WaitingForConfirmation { .. }
6105 );
6106 let is_terminal_tool = matches!(tool_call.kind, acp::ToolKind::Execute);
6107
6108 let is_edit =
6109 matches!(tool_call.kind, acp::ToolKind::Edit) || tool_call.diffs().next().is_some();
6110
6111 let is_cancelled_edit = is_edit && matches!(tool_call.status, ToolCallStatus::Canceled);
6112 let (has_revealed_diff, tool_call_output_focus, tool_call_output_focus_handle) = tool_call
6113 .diffs()
6114 .next()
6115 .and_then(|diff| {
6116 let editor = self
6117 .entry_view_state
6118 .read(cx)
6119 .entry(entry_ix)
6120 .and_then(|entry| entry.editor_for_diff(diff))?;
6121 let has_revealed_diff = diff.read(cx).has_revealed_range(cx);
6122 let has_focus = editor.read(cx).is_focused(window);
6123 let focus_handle = editor.focus_handle(cx);
6124 Some((has_revealed_diff, has_focus, focus_handle))
6125 })
6126 .unwrap_or_else(|| (false, false, focus_handle.clone()));
6127
6128 let use_card_layout = needs_confirmation || is_edit || is_terminal_tool;
6129
6130 let has_image_content = tool_call.content.iter().any(|c| c.image().is_some());
6131 let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
6132 let mut is_open = self.expanded_tool_calls.contains(&tool_call.id);
6133
6134 is_open |= needs_confirmation;
6135
6136 let should_show_raw_input = !is_terminal_tool && !is_edit && !has_image_content;
6137
6138 let input_output_header = |label: SharedString| {
6139 Label::new(label)
6140 .size(LabelSize::XSmall)
6141 .color(Color::Muted)
6142 .buffer_font(cx)
6143 };
6144
6145 let tool_output_display = if is_open {
6146 match &tool_call.status {
6147 ToolCallStatus::WaitingForConfirmation { options, .. } => v_flex()
6148 .w_full()
6149 .children(
6150 tool_call
6151 .content
6152 .iter()
6153 .enumerate()
6154 .map(|(content_ix, content)| {
6155 div()
6156 .child(self.render_tool_call_content(
6157 active_session_id,
6158 entry_ix,
6159 content,
6160 content_ix,
6161 tool_call,
6162 use_card_layout,
6163 has_image_content,
6164 failed_or_canceled,
6165 focus_handle,
6166 window,
6167 cx,
6168 ))
6169 .into_any_element()
6170 }),
6171 )
6172 .when(should_show_raw_input, |this| {
6173 let is_raw_input_expanded =
6174 self.expanded_tool_call_raw_inputs.contains(&tool_call.id);
6175
6176 let input_header = if is_raw_input_expanded {
6177 "Raw Input:"
6178 } else {
6179 "View Raw Input"
6180 };
6181
6182 this.child(
6183 v_flex()
6184 .p_2()
6185 .gap_1()
6186 .border_t_1()
6187 .border_color(self.tool_card_border_color(cx))
6188 .child(
6189 h_flex()
6190 .id("disclosure_container")
6191 .pl_0p5()
6192 .gap_1()
6193 .justify_between()
6194 .rounded_xs()
6195 .hover(|s| s.bg(cx.theme().colors().element_hover))
6196 .child(input_output_header(input_header.into()))
6197 .child(
6198 Disclosure::new(
6199 ("raw-input-disclosure", entry_ix),
6200 is_raw_input_expanded,
6201 )
6202 .opened_icon(IconName::ChevronUp)
6203 .closed_icon(IconName::ChevronDown),
6204 )
6205 .on_click(cx.listener({
6206 let id = tool_call.id.clone();
6207
6208 move |this: &mut Self, _, _, cx| {
6209 if this.expanded_tool_call_raw_inputs.contains(&id)
6210 {
6211 this.expanded_tool_call_raw_inputs.remove(&id);
6212 } else {
6213 this.expanded_tool_call_raw_inputs
6214 .insert(id.clone());
6215 }
6216 cx.notify();
6217 }
6218 })),
6219 )
6220 .when(is_raw_input_expanded, |this| {
6221 this.children(tool_call.raw_input_markdown.clone().map(
6222 |input| {
6223 self.render_markdown(
6224 input,
6225 MarkdownStyle::themed(
6226 MarkdownFont::Agent,
6227 window,
6228 cx,
6229 ),
6230 )
6231 },
6232 ))
6233 }),
6234 )
6235 })
6236 .child(self.render_permission_buttons(
6237 self.id.clone(),
6238 self.is_first_tool_call(active_session_id, &tool_call.id, cx),
6239 options,
6240 entry_ix,
6241 tool_call.id.clone(),
6242 focus_handle,
6243 cx,
6244 ))
6245 .into_any(),
6246 ToolCallStatus::Pending | ToolCallStatus::InProgress
6247 if is_edit
6248 && tool_call.content.is_empty()
6249 && self.as_native_connection(cx).is_some() =>
6250 {
6251 self.render_diff_loading(cx)
6252 }
6253 ToolCallStatus::Pending
6254 | ToolCallStatus::InProgress
6255 | ToolCallStatus::Completed
6256 | ToolCallStatus::Failed
6257 | ToolCallStatus::Canceled => v_flex()
6258 .when(should_show_raw_input, |this| {
6259 this.mt_1p5().w_full().child(
6260 v_flex()
6261 .ml(rems(0.4))
6262 .px_3p5()
6263 .pb_1()
6264 .gap_1()
6265 .border_l_1()
6266 .border_color(self.tool_card_border_color(cx))
6267 .child(input_output_header("Raw Input:".into()))
6268 .children(tool_call.raw_input_markdown.clone().map(|input| {
6269 div().id(("tool-call-raw-input-markdown", entry_ix)).child(
6270 self.render_markdown(
6271 input,
6272 MarkdownStyle::themed(MarkdownFont::Agent, window, cx),
6273 ),
6274 )
6275 }))
6276 .child(input_output_header("Output:".into())),
6277 )
6278 })
6279 .children(
6280 tool_call
6281 .content
6282 .iter()
6283 .enumerate()
6284 .map(|(content_ix, content)| {
6285 div().id(("tool-call-output", entry_ix)).child(
6286 self.render_tool_call_content(
6287 active_session_id,
6288 entry_ix,
6289 content,
6290 content_ix,
6291 tool_call,
6292 use_card_layout,
6293 has_image_content,
6294 failed_or_canceled,
6295 focus_handle,
6296 window,
6297 cx,
6298 ),
6299 )
6300 }),
6301 )
6302 .into_any(),
6303 ToolCallStatus::Rejected => Empty.into_any(),
6304 }
6305 .into()
6306 } else {
6307 None
6308 };
6309
6310 v_flex()
6311 .map(|this| {
6312 if is_subagent {
6313 this
6314 } else if use_card_layout {
6315 this.my_1p5()
6316 .rounded_md()
6317 .border_1()
6318 .when(failed_or_canceled, |this| this.border_dashed())
6319 .border_color(self.tool_card_border_color(cx))
6320 .bg(cx.theme().colors().editor_background)
6321 .overflow_hidden()
6322 } else {
6323 this.my_1()
6324 }
6325 })
6326 .when(!is_subagent, |this| {
6327 this.map(|this| {
6328 if has_location && !use_card_layout {
6329 this.ml_4()
6330 } else {
6331 this.ml_5()
6332 }
6333 })
6334 .mr_5()
6335 })
6336 .map(|this| {
6337 if is_terminal_tool {
6338 let label_source = tool_call.label.read(cx).source();
6339 this.child(self.render_collapsible_command(
6340 card_header_id.clone(),
6341 true,
6342 label_source,
6343 cx,
6344 ))
6345 } else {
6346 this.child(
6347 h_flex()
6348 .group(&card_header_id)
6349 .relative()
6350 .w_full()
6351 .justify_between()
6352 .when(use_card_layout, |this| {
6353 this.p_0p5()
6354 .rounded_t(rems_from_px(5.))
6355 .bg(self.tool_card_header_bg(cx))
6356 })
6357 .child(self.render_tool_call_label(
6358 entry_ix,
6359 tool_call,
6360 is_edit,
6361 is_cancelled_edit,
6362 has_revealed_diff,
6363 use_card_layout,
6364 window,
6365 cx,
6366 ))
6367 .child(
6368 h_flex()
6369 .when(is_collapsible || failed_or_canceled, |this| {
6370 let diff_for_discard = if has_revealed_diff
6371 && is_cancelled_edit
6372 && cx.has_flag::<AgentV2FeatureFlag>()
6373 {
6374 tool_call.diffs().next().cloned()
6375 } else {
6376 None
6377 };
6378
6379 this.child(
6380 h_flex()
6381 .pr_0p5()
6382 .gap_1()
6383 .when(is_collapsible, |this| {
6384 this.child(
6385 Disclosure::new(
6386 ("expand-output", entry_ix),
6387 is_open,
6388 )
6389 .opened_icon(IconName::ChevronUp)
6390 .closed_icon(IconName::ChevronDown)
6391 .visible_on_hover(&card_header_id)
6392 .on_click(cx.listener({
6393 let id = tool_call.id.clone();
6394 move |this: &mut Self,
6395 _,
6396 _,
6397 cx: &mut Context<Self>| {
6398 if is_open {
6399 this.expanded_tool_calls
6400 .remove(&id);
6401 } else {
6402 this.expanded_tool_calls
6403 .insert(id.clone());
6404 }
6405 cx.notify();
6406 }
6407 })),
6408 )
6409 })
6410 .when(failed_or_canceled, |this| {
6411 if is_cancelled_edit && !has_revealed_diff {
6412 this.child(
6413 div()
6414 .id(entry_ix)
6415 .tooltip(Tooltip::text(
6416 "Interrupted Edit",
6417 ))
6418 .child(
6419 Icon::new(IconName::XCircle)
6420 .color(Color::Muted)
6421 .size(IconSize::Small),
6422 ),
6423 )
6424 } else if is_cancelled_edit {
6425 this
6426 } else {
6427 this.child(
6428 Icon::new(IconName::Close)
6429 .color(Color::Error)
6430 .size(IconSize::Small),
6431 )
6432 }
6433 })
6434 .when_some(diff_for_discard, |this, diff| {
6435 let tool_call_id = tool_call.id.clone();
6436 let is_discarded = self
6437 .discarded_partial_edits
6438 .contains(&tool_call_id);
6439
6440 this.when(!is_discarded, |this| {
6441 this.child(
6442 IconButton::new(
6443 ("discard-partial-edit", entry_ix),
6444 IconName::Undo,
6445 )
6446 .icon_size(IconSize::Small)
6447 .tooltip(move |_, cx| {
6448 Tooltip::with_meta(
6449 "Discard Interrupted Edit",
6450 None,
6451 "You can discard this interrupted partial edit and restore the original file content.",
6452 cx,
6453 )
6454 })
6455 .on_click(cx.listener({
6456 let tool_call_id =
6457 tool_call_id.clone();
6458 move |this, _, _window, cx| {
6459 let diff_data = diff.read(cx);
6460 let base_text = diff_data
6461 .base_text()
6462 .clone();
6463 let buffer =
6464 diff_data.buffer().clone();
6465 buffer.update(
6466 cx,
6467 |buffer, cx| {
6468 buffer.set_text(
6469 base_text.as_ref(),
6470 cx,
6471 );
6472 },
6473 );
6474 this.discarded_partial_edits
6475 .insert(
6476 tool_call_id.clone(),
6477 );
6478 cx.notify();
6479 }
6480 })),
6481 )
6482 })
6483 }),
6484 )
6485 })
6486 .when(tool_call_output_focus, |this| {
6487 this.child(
6488 Button::new("open-file-button", "Open File")
6489 .style(ButtonStyle::Outlined)
6490 .label_size(LabelSize::Small)
6491 .key_binding(
6492 KeyBinding::for_action_in(&OpenExcerpts, &tool_call_output_focus_handle, cx)
6493 .map(|s| s.size(rems_from_px(12.))),
6494 )
6495 .on_click(|_, window, cx| {
6496 window.dispatch_action(
6497 Box::new(OpenExcerpts),
6498 cx,
6499 )
6500 }),
6501 )
6502 }),
6503 )
6504
6505 )
6506 }
6507 })
6508 .children(tool_output_display)
6509 }
6510
6511 fn render_permission_buttons(
6512 &self,
6513 session_id: acp::SessionId,
6514 is_first: bool,
6515 options: &PermissionOptions,
6516 entry_ix: usize,
6517 tool_call_id: acp::ToolCallId,
6518 focus_handle: &FocusHandle,
6519 cx: &Context<Self>,
6520 ) -> Div {
6521 match options {
6522 PermissionOptions::Flat(options) => self.render_permission_buttons_flat(
6523 session_id,
6524 is_first,
6525 options,
6526 entry_ix,
6527 tool_call_id,
6528 focus_handle,
6529 cx,
6530 ),
6531 PermissionOptions::Dropdown(choices) => self.render_permission_buttons_with_dropdown(
6532 is_first,
6533 choices,
6534 None,
6535 entry_ix,
6536 tool_call_id,
6537 focus_handle,
6538 cx,
6539 ),
6540 PermissionOptions::DropdownWithPatterns {
6541 choices,
6542 patterns,
6543 tool_name,
6544 } => self.render_permission_buttons_with_dropdown(
6545 is_first,
6546 choices,
6547 Some((patterns, tool_name)),
6548 entry_ix,
6549 tool_call_id,
6550 focus_handle,
6551 cx,
6552 ),
6553 }
6554 }
6555
6556 fn render_permission_buttons_with_dropdown(
6557 &self,
6558 is_first: bool,
6559 choices: &[PermissionOptionChoice],
6560 patterns: Option<(&[PermissionPattern], &str)>,
6561 entry_ix: usize,
6562 tool_call_id: acp::ToolCallId,
6563 focus_handle: &FocusHandle,
6564 cx: &Context<Self>,
6565 ) -> Div {
6566 let selection = self.permission_selections.get(&tool_call_id);
6567
6568 let selected_index = selection
6569 .and_then(|s| s.choice_index())
6570 .unwrap_or_else(|| choices.len().saturating_sub(1));
6571
6572 let dropdown_label: SharedString =
6573 if matches!(selection, Some(PermissionSelection::SelectedPatterns(_))) {
6574 "Always for selected commands".into()
6575 } else {
6576 choices
6577 .get(selected_index)
6578 .or(choices.last())
6579 .map(|choice| choice.label())
6580 .unwrap_or_else(|| "Only this time".into())
6581 };
6582
6583 let dropdown = if let Some((pattern_list, tool_name)) = patterns {
6584 self.render_permission_granularity_dropdown_with_patterns(
6585 choices,
6586 pattern_list,
6587 tool_name,
6588 dropdown_label,
6589 entry_ix,
6590 tool_call_id.clone(),
6591 is_first,
6592 cx,
6593 )
6594 } else {
6595 self.render_permission_granularity_dropdown(
6596 choices,
6597 dropdown_label,
6598 entry_ix,
6599 tool_call_id.clone(),
6600 selected_index,
6601 is_first,
6602 cx,
6603 )
6604 };
6605
6606 h_flex()
6607 .w_full()
6608 .p_1()
6609 .gap_2()
6610 .justify_between()
6611 .border_t_1()
6612 .border_color(self.tool_card_border_color(cx))
6613 .child(
6614 h_flex()
6615 .gap_0p5()
6616 .child(
6617 Button::new(("allow-btn", entry_ix), "Allow")
6618 .start_icon(
6619 Icon::new(IconName::Check)
6620 .size(IconSize::XSmall)
6621 .color(Color::Success),
6622 )
6623 .label_size(LabelSize::Small)
6624 .when(is_first, |this| {
6625 this.key_binding(
6626 KeyBinding::for_action_in(
6627 &AllowOnce as &dyn Action,
6628 focus_handle,
6629 cx,
6630 )
6631 .map(|kb| kb.size(rems_from_px(12.))),
6632 )
6633 })
6634 .on_click(cx.listener({
6635 move |this, _, window, cx| {
6636 this.authorize_pending_with_granularity(true, window, cx);
6637 }
6638 })),
6639 )
6640 .child(
6641 Button::new(("deny-btn", entry_ix), "Deny")
6642 .start_icon(
6643 Icon::new(IconName::Close)
6644 .size(IconSize::XSmall)
6645 .color(Color::Error),
6646 )
6647 .label_size(LabelSize::Small)
6648 .when(is_first, |this| {
6649 this.key_binding(
6650 KeyBinding::for_action_in(
6651 &RejectOnce as &dyn Action,
6652 focus_handle,
6653 cx,
6654 )
6655 .map(|kb| kb.size(rems_from_px(12.))),
6656 )
6657 })
6658 .on_click(cx.listener({
6659 move |this, _, window, cx| {
6660 this.authorize_pending_with_granularity(false, window, cx);
6661 }
6662 })),
6663 ),
6664 )
6665 .child(dropdown)
6666 }
6667
6668 fn render_permission_granularity_dropdown(
6669 &self,
6670 choices: &[PermissionOptionChoice],
6671 current_label: SharedString,
6672 entry_ix: usize,
6673 tool_call_id: acp::ToolCallId,
6674 selected_index: usize,
6675 is_first: bool,
6676 cx: &Context<Self>,
6677 ) -> AnyElement {
6678 let menu_options: Vec<(usize, SharedString)> = choices
6679 .iter()
6680 .enumerate()
6681 .map(|(i, choice)| (i, choice.label()))
6682 .collect();
6683
6684 let permission_dropdown_handle = self.permission_dropdown_handle.clone();
6685
6686 PopoverMenu::new(("permission-granularity", entry_ix))
6687 .with_handle(permission_dropdown_handle)
6688 .trigger(
6689 Button::new(("granularity-trigger", entry_ix), current_label)
6690 .end_icon(
6691 Icon::new(IconName::ChevronDown)
6692 .size(IconSize::XSmall)
6693 .color(Color::Muted),
6694 )
6695 .label_size(LabelSize::Small)
6696 .when(is_first, |this| {
6697 this.key_binding(
6698 KeyBinding::for_action_in(
6699 &crate::OpenPermissionDropdown as &dyn Action,
6700 &self.focus_handle(cx),
6701 cx,
6702 )
6703 .map(|kb| kb.size(rems_from_px(12.))),
6704 )
6705 }),
6706 )
6707 .menu(move |window, cx| {
6708 let tool_call_id = tool_call_id.clone();
6709 let options = menu_options.clone();
6710
6711 Some(ContextMenu::build(window, cx, move |mut menu, _, _| {
6712 for (index, display_name) in options.iter() {
6713 let display_name = display_name.clone();
6714 let index = *index;
6715 let tool_call_id_for_entry = tool_call_id.clone();
6716 let is_selected = index == selected_index;
6717 menu = menu.toggleable_entry(
6718 display_name,
6719 is_selected,
6720 IconPosition::End,
6721 None,
6722 move |window, cx| {
6723 window.dispatch_action(
6724 SelectPermissionGranularity {
6725 tool_call_id: tool_call_id_for_entry.0.to_string(),
6726 index,
6727 }
6728 .boxed_clone(),
6729 cx,
6730 );
6731 },
6732 );
6733 }
6734
6735 menu
6736 }))
6737 })
6738 .into_any_element()
6739 }
6740
6741 fn render_permission_granularity_dropdown_with_patterns(
6742 &self,
6743 choices: &[PermissionOptionChoice],
6744 patterns: &[PermissionPattern],
6745 _tool_name: &str,
6746 current_label: SharedString,
6747 entry_ix: usize,
6748 tool_call_id: acp::ToolCallId,
6749 is_first: bool,
6750 cx: &Context<Self>,
6751 ) -> AnyElement {
6752 let default_choice_index = choices.len().saturating_sub(1);
6753 let menu_options: Vec<(usize, SharedString)> = choices
6754 .iter()
6755 .enumerate()
6756 .map(|(i, choice)| (i, choice.label()))
6757 .collect();
6758
6759 let pattern_options: Vec<(usize, SharedString)> = patterns
6760 .iter()
6761 .enumerate()
6762 .map(|(i, cp)| {
6763 (
6764 i,
6765 SharedString::from(format!("Always for `{}` commands", cp.display_name)),
6766 )
6767 })
6768 .collect();
6769
6770 let pattern_count = patterns.len();
6771 let permission_dropdown_handle = self.permission_dropdown_handle.clone();
6772 let view = cx.entity().downgrade();
6773
6774 PopoverMenu::new(("permission-granularity", entry_ix))
6775 .with_handle(permission_dropdown_handle.clone())
6776 .anchor(Corner::TopRight)
6777 .attach(Corner::BottomRight)
6778 .trigger(
6779 Button::new(("granularity-trigger", entry_ix), current_label)
6780 .end_icon(
6781 Icon::new(IconName::ChevronDown)
6782 .size(IconSize::XSmall)
6783 .color(Color::Muted),
6784 )
6785 .label_size(LabelSize::Small)
6786 .when(is_first, |this| {
6787 this.key_binding(
6788 KeyBinding::for_action_in(
6789 &crate::OpenPermissionDropdown as &dyn Action,
6790 &self.focus_handle(cx),
6791 cx,
6792 )
6793 .map(|kb| kb.size(rems_from_px(12.))),
6794 )
6795 }),
6796 )
6797 .menu(move |window, cx| {
6798 let tool_call_id = tool_call_id.clone();
6799 let options = menu_options.clone();
6800 let patterns = pattern_options.clone();
6801 let view = view.clone();
6802 let dropdown_handle = permission_dropdown_handle.clone();
6803
6804 Some(ContextMenu::build_persistent(
6805 window,
6806 cx,
6807 move |menu, _window, cx| {
6808 let mut menu = menu;
6809
6810 // Read fresh selection state from the view on each rebuild.
6811 let selection: Option<PermissionSelection> = view.upgrade().and_then(|v| {
6812 let view = v.read(cx);
6813 view.permission_selections.get(&tool_call_id).cloned()
6814 });
6815
6816 let is_pattern_mode =
6817 matches!(selection, Some(PermissionSelection::SelectedPatterns(_)));
6818
6819 // Granularity choices: "Always for terminal", "Only this time"
6820 for (index, display_name) in options.iter() {
6821 let display_name = display_name.clone();
6822 let index = *index;
6823 let tool_call_id_for_entry = tool_call_id.clone();
6824 let is_selected = !is_pattern_mode
6825 && selection
6826 .as_ref()
6827 .and_then(|s| s.choice_index())
6828 .map_or(index == default_choice_index, |ci| ci == index);
6829
6830 let view = view.clone();
6831 menu = menu.toggleable_entry(
6832 display_name,
6833 is_selected,
6834 IconPosition::End,
6835 None,
6836 move |_window, cx| {
6837 view.update(cx, |this, cx| {
6838 this.permission_selections.insert(
6839 tool_call_id_for_entry.clone(),
6840 PermissionSelection::Choice(index),
6841 );
6842 cx.notify();
6843 })
6844 .log_err();
6845 },
6846 );
6847 }
6848
6849 menu = menu.separator().header("Select Options…");
6850
6851 for (pattern_index, label) in patterns.iter() {
6852 let label = label.clone();
6853 let pattern_index = *pattern_index;
6854 let tool_call_id_for_pattern = tool_call_id.clone();
6855 let is_checked = selection
6856 .as_ref()
6857 .is_some_and(|s| s.is_pattern_checked(pattern_index));
6858
6859 let view = view.clone();
6860 menu = menu.toggleable_entry(
6861 label,
6862 is_checked,
6863 IconPosition::End,
6864 None,
6865 move |_window, cx| {
6866 view.update(cx, |this, cx| {
6867 let selection = this
6868 .permission_selections
6869 .get_mut(&tool_call_id_for_pattern);
6870
6871 match selection {
6872 Some(PermissionSelection::SelectedPatterns(_)) => {
6873 // Already in pattern mode — toggle.
6874 this.permission_selections
6875 .get_mut(&tool_call_id_for_pattern)
6876 .expect("just matched above")
6877 .toggle_pattern(pattern_index);
6878 }
6879 _ => {
6880 // First click: activate pattern mode
6881 // with all patterns checked.
6882 this.permission_selections.insert(
6883 tool_call_id_for_pattern.clone(),
6884 PermissionSelection::SelectedPatterns(
6885 (0..pattern_count).collect(),
6886 ),
6887 );
6888 }
6889 }
6890 cx.notify();
6891 })
6892 .log_err();
6893 },
6894 );
6895 }
6896
6897 let any_patterns_checked = selection
6898 .as_ref()
6899 .is_some_and(|s| s.has_any_checked_patterns());
6900 let dropdown_handle = dropdown_handle.clone();
6901 menu = menu.custom_row(move |_window, _cx| {
6902 div()
6903 .py_1()
6904 .w_full()
6905 .child(
6906 Button::new("apply-patterns", "Apply")
6907 .full_width()
6908 .style(ButtonStyle::Outlined)
6909 .label_size(LabelSize::Small)
6910 .disabled(!any_patterns_checked)
6911 .on_click({
6912 let dropdown_handle = dropdown_handle.clone();
6913 move |_event, _window, cx| {
6914 dropdown_handle.hide(cx);
6915 }
6916 }),
6917 )
6918 .into_any_element()
6919 });
6920
6921 menu
6922 },
6923 ))
6924 })
6925 .into_any_element()
6926 }
6927
6928 fn render_permission_buttons_flat(
6929 &self,
6930 session_id: acp::SessionId,
6931 is_first: bool,
6932 options: &[acp::PermissionOption],
6933 entry_ix: usize,
6934 tool_call_id: acp::ToolCallId,
6935 focus_handle: &FocusHandle,
6936 cx: &Context<Self>,
6937 ) -> Div {
6938 let mut seen_kinds: ArrayVec<acp::PermissionOptionKind, 3, u8> = ArrayVec::new();
6939
6940 div()
6941 .p_1()
6942 .border_t_1()
6943 .border_color(self.tool_card_border_color(cx))
6944 .w_full()
6945 .v_flex()
6946 .gap_0p5()
6947 .children(options.iter().map(move |option| {
6948 let option_id = SharedString::from(option.option_id.0.clone());
6949 Button::new((option_id, entry_ix), option.name.clone())
6950 .map(|this| {
6951 let (icon, action) = match option.kind {
6952 acp::PermissionOptionKind::AllowOnce => (
6953 Icon::new(IconName::Check)
6954 .size(IconSize::XSmall)
6955 .color(Color::Success),
6956 Some(&AllowOnce as &dyn Action),
6957 ),
6958 acp::PermissionOptionKind::AllowAlways => (
6959 Icon::new(IconName::CheckDouble)
6960 .size(IconSize::XSmall)
6961 .color(Color::Success),
6962 Some(&AllowAlways as &dyn Action),
6963 ),
6964 acp::PermissionOptionKind::RejectOnce => (
6965 Icon::new(IconName::Close)
6966 .size(IconSize::XSmall)
6967 .color(Color::Error),
6968 Some(&RejectOnce as &dyn Action),
6969 ),
6970 acp::PermissionOptionKind::RejectAlways | _ => (
6971 Icon::new(IconName::Close)
6972 .size(IconSize::XSmall)
6973 .color(Color::Error),
6974 None,
6975 ),
6976 };
6977
6978 let this = this.start_icon(icon);
6979
6980 let Some(action) = action else {
6981 return this;
6982 };
6983
6984 if !is_first || seen_kinds.contains(&option.kind) {
6985 return this;
6986 }
6987
6988 seen_kinds.push(option.kind).unwrap();
6989
6990 this.key_binding(
6991 KeyBinding::for_action_in(action, focus_handle, cx)
6992 .map(|kb| kb.size(rems_from_px(12.))),
6993 )
6994 })
6995 .label_size(LabelSize::Small)
6996 .on_click(cx.listener({
6997 let session_id = session_id.clone();
6998 let tool_call_id = tool_call_id.clone();
6999 let option_id = option.option_id.clone();
7000 let option_kind = option.kind;
7001 move |this, _, window, cx| {
7002 this.authorize_tool_call(
7003 session_id.clone(),
7004 tool_call_id.clone(),
7005 SelectedPermissionOutcome::new(option_id.clone(), option_kind),
7006 window,
7007 cx,
7008 );
7009 }
7010 }))
7011 }))
7012 }
7013
7014 fn render_diff_loading(&self, cx: &Context<Self>) -> AnyElement {
7015 let bar = |n: u64, width_class: &str| {
7016 let bg_color = cx.theme().colors().element_active;
7017 let base = h_flex().h_1().rounded_full();
7018
7019 let modified = match width_class {
7020 "w_4_5" => base.w_3_4(),
7021 "w_1_4" => base.w_1_4(),
7022 "w_2_4" => base.w_2_4(),
7023 "w_3_5" => base.w_3_5(),
7024 "w_2_5" => base.w_2_5(),
7025 _ => base.w_1_2(),
7026 };
7027
7028 modified.with_animation(
7029 ElementId::Integer(n),
7030 Animation::new(Duration::from_secs(2)).repeat(),
7031 move |tab, delta| {
7032 let delta = (delta - 0.15 * n as f32) / 0.7;
7033 let delta = 1.0 - (0.5 - delta).abs() * 2.;
7034 let delta = ease_in_out(delta.clamp(0., 1.));
7035 let delta = 0.1 + 0.9 * delta;
7036
7037 tab.bg(bg_color.opacity(delta))
7038 },
7039 )
7040 };
7041
7042 v_flex()
7043 .p_3()
7044 .gap_1()
7045 .rounded_b_md()
7046 .bg(cx.theme().colors().editor_background)
7047 .child(bar(0, "w_4_5"))
7048 .child(bar(1, "w_1_4"))
7049 .child(bar(2, "w_2_4"))
7050 .child(bar(3, "w_3_5"))
7051 .child(bar(4, "w_2_5"))
7052 .into_any_element()
7053 }
7054
7055 fn render_tool_call_label(
7056 &self,
7057 entry_ix: usize,
7058 tool_call: &ToolCall,
7059 is_edit: bool,
7060 has_failed: bool,
7061 has_revealed_diff: bool,
7062 use_card_layout: bool,
7063 window: &Window,
7064 cx: &Context<Self>,
7065 ) -> Div {
7066 let has_location = tool_call.locations.len() == 1;
7067 let is_file = tool_call.kind == acp::ToolKind::Edit && has_location;
7068 let is_subagent_tool_call = tool_call.is_subagent();
7069
7070 let file_icon = if has_location {
7071 FileIcons::get_icon(&tool_call.locations[0].path, cx)
7072 .map(|from_path| Icon::from_path(from_path).color(Color::Muted))
7073 .unwrap_or(Icon::new(IconName::ToolPencil).color(Color::Muted))
7074 } else {
7075 Icon::new(IconName::ToolPencil).color(Color::Muted)
7076 };
7077
7078 let tool_icon = if is_file && has_failed && has_revealed_diff {
7079 div()
7080 .id(entry_ix)
7081 .tooltip(Tooltip::text("Interrupted Edit"))
7082 .child(DecoratedIcon::new(
7083 file_icon,
7084 Some(
7085 IconDecoration::new(
7086 IconDecorationKind::Triangle,
7087 self.tool_card_header_bg(cx),
7088 cx,
7089 )
7090 .color(cx.theme().status().warning)
7091 .position(gpui::Point {
7092 x: px(-2.),
7093 y: px(-2.),
7094 }),
7095 ),
7096 ))
7097 .into_any_element()
7098 } else if is_file {
7099 div().child(file_icon).into_any_element()
7100 } else if is_subagent_tool_call {
7101 Icon::new(self.agent_icon)
7102 .size(IconSize::Small)
7103 .color(Color::Muted)
7104 .into_any_element()
7105 } else {
7106 Icon::new(match tool_call.kind {
7107 acp::ToolKind::Read => IconName::ToolSearch,
7108 acp::ToolKind::Edit => IconName::ToolPencil,
7109 acp::ToolKind::Delete => IconName::ToolDeleteFile,
7110 acp::ToolKind::Move => IconName::ArrowRightLeft,
7111 acp::ToolKind::Search => IconName::ToolSearch,
7112 acp::ToolKind::Execute => IconName::ToolTerminal,
7113 acp::ToolKind::Think => IconName::ToolThink,
7114 acp::ToolKind::Fetch => IconName::ToolWeb,
7115 acp::ToolKind::SwitchMode => IconName::ArrowRightLeft,
7116 acp::ToolKind::Other | _ => IconName::ToolHammer,
7117 })
7118 .size(IconSize::Small)
7119 .color(Color::Muted)
7120 .into_any_element()
7121 };
7122
7123 let gradient_overlay = {
7124 div()
7125 .absolute()
7126 .top_0()
7127 .right_0()
7128 .w_12()
7129 .h_full()
7130 .map(|this| {
7131 if use_card_layout {
7132 this.bg(linear_gradient(
7133 90.,
7134 linear_color_stop(self.tool_card_header_bg(cx), 1.),
7135 linear_color_stop(self.tool_card_header_bg(cx).opacity(0.2), 0.),
7136 ))
7137 } else {
7138 this.bg(linear_gradient(
7139 90.,
7140 linear_color_stop(cx.theme().colors().panel_background, 1.),
7141 linear_color_stop(
7142 cx.theme().colors().panel_background.opacity(0.2),
7143 0.,
7144 ),
7145 ))
7146 }
7147 })
7148 };
7149
7150 h_flex()
7151 .relative()
7152 .w_full()
7153 .h(window.line_height() - px(2.))
7154 .text_size(self.tool_name_font_size())
7155 .gap_1p5()
7156 .when(has_location || use_card_layout, |this| this.px_1())
7157 .when(has_location, |this| {
7158 this.cursor(CursorStyle::PointingHand)
7159 .rounded(rems_from_px(3.)) // Concentric border radius
7160 .hover(|s| s.bg(cx.theme().colors().element_hover.opacity(0.5)))
7161 })
7162 .overflow_hidden()
7163 .child(tool_icon)
7164 .child(if has_location {
7165 h_flex()
7166 .id(("open-tool-call-location", entry_ix))
7167 .w_full()
7168 .map(|this| {
7169 if use_card_layout {
7170 this.text_color(cx.theme().colors().text)
7171 } else {
7172 this.text_color(cx.theme().colors().text_muted)
7173 }
7174 })
7175 .child(
7176 self.render_markdown(
7177 tool_call.label.clone(),
7178 MarkdownStyle {
7179 prevent_mouse_interaction: true,
7180 ..MarkdownStyle::themed(MarkdownFont::Agent, window, cx)
7181 .with_muted_text(cx)
7182 },
7183 ),
7184 )
7185 .tooltip(Tooltip::text("Go to File"))
7186 .on_click(cx.listener(move |this, _, window, cx| {
7187 this.open_tool_call_location(entry_ix, 0, window, cx);
7188 }))
7189 .into_any_element()
7190 } else {
7191 h_flex()
7192 .w_full()
7193 .child(self.render_markdown(
7194 tool_call.label.clone(),
7195 MarkdownStyle::themed(MarkdownFont::Agent, window, cx).with_muted_text(cx),
7196 ))
7197 .into_any()
7198 })
7199 .when(!is_edit, |this| this.child(gradient_overlay))
7200 }
7201
7202 fn open_tool_call_location(
7203 &self,
7204 entry_ix: usize,
7205 location_ix: usize,
7206 window: &mut Window,
7207 cx: &mut Context<Self>,
7208 ) -> Option<()> {
7209 let (tool_call_location, agent_location) = self
7210 .thread
7211 .read(cx)
7212 .entries()
7213 .get(entry_ix)?
7214 .location(location_ix)?;
7215
7216 let project_path = self
7217 .project
7218 .upgrade()?
7219 .read(cx)
7220 .find_project_path(&tool_call_location.path, cx)?;
7221
7222 let open_task = self
7223 .workspace
7224 .update(cx, |workspace, cx| {
7225 workspace.open_path(project_path, None, true, window, cx)
7226 })
7227 .log_err()?;
7228 window
7229 .spawn(cx, async move |cx| {
7230 let item = open_task.await?;
7231
7232 let Some(active_editor) = item.downcast::<Editor>() else {
7233 return anyhow::Ok(());
7234 };
7235
7236 active_editor.update_in(cx, |editor, window, cx| {
7237 let snapshot = editor.buffer().read(cx).snapshot(cx);
7238 if snapshot.as_singleton().is_some()
7239 && let Some(anchor) = snapshot.anchor_in_excerpt(agent_location.position)
7240 {
7241 editor.change_selections(Default::default(), window, cx, |selections| {
7242 selections.select_anchor_ranges([anchor..anchor]);
7243 })
7244 } else {
7245 let row = tool_call_location.line.unwrap_or_default();
7246 editor.change_selections(Default::default(), window, cx, |selections| {
7247 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
7248 })
7249 }
7250 })?;
7251
7252 anyhow::Ok(())
7253 })
7254 .detach_and_log_err(cx);
7255
7256 None
7257 }
7258
7259 fn render_tool_call_content(
7260 &self,
7261 session_id: &acp::SessionId,
7262 entry_ix: usize,
7263 content: &ToolCallContent,
7264 context_ix: usize,
7265 tool_call: &ToolCall,
7266 card_layout: bool,
7267 is_image_tool_call: bool,
7268 has_failed: bool,
7269 focus_handle: &FocusHandle,
7270 window: &Window,
7271 cx: &Context<Self>,
7272 ) -> AnyElement {
7273 match content {
7274 ToolCallContent::ContentBlock(content) => {
7275 if let Some(resource_link) = content.resource_link() {
7276 self.render_resource_link(resource_link, cx)
7277 } else if let Some(markdown) = content.markdown() {
7278 self.render_markdown_output(
7279 markdown.clone(),
7280 tool_call.id.clone(),
7281 context_ix,
7282 card_layout,
7283 window,
7284 cx,
7285 )
7286 } else if let Some(image) = content.image() {
7287 let location = tool_call.locations.first().cloned();
7288 self.render_image_output(
7289 entry_ix,
7290 image.clone(),
7291 location,
7292 card_layout,
7293 is_image_tool_call,
7294 cx,
7295 )
7296 } else {
7297 Empty.into_any_element()
7298 }
7299 }
7300 ToolCallContent::Diff(diff) => {
7301 self.render_diff_editor(entry_ix, diff, tool_call, has_failed, cx)
7302 }
7303 ToolCallContent::Terminal(terminal) => self.render_terminal_tool_call(
7304 session_id,
7305 entry_ix,
7306 terminal,
7307 tool_call,
7308 focus_handle,
7309 false,
7310 window,
7311 cx,
7312 ),
7313 }
7314 }
7315
7316 fn render_resource_link(
7317 &self,
7318 resource_link: &acp::ResourceLink,
7319 cx: &Context<Self>,
7320 ) -> AnyElement {
7321 let uri: SharedString = resource_link.uri.clone().into();
7322 let is_file = resource_link.uri.strip_prefix("file://");
7323
7324 let Some(project) = self.project.upgrade() else {
7325 return Empty.into_any_element();
7326 };
7327
7328 let label: SharedString = if let Some(abs_path) = is_file {
7329 if let Some(project_path) = project
7330 .read(cx)
7331 .project_path_for_absolute_path(&Path::new(abs_path), cx)
7332 && let Some(worktree) = project
7333 .read(cx)
7334 .worktree_for_id(project_path.worktree_id, cx)
7335 {
7336 worktree
7337 .read(cx)
7338 .full_path(&project_path.path)
7339 .to_string_lossy()
7340 .to_string()
7341 .into()
7342 } else {
7343 abs_path.to_string().into()
7344 }
7345 } else {
7346 uri.clone()
7347 };
7348
7349 let button_id = SharedString::from(format!("item-{}", uri));
7350
7351 div()
7352 .ml(rems(0.4))
7353 .pl_2p5()
7354 .border_l_1()
7355 .border_color(self.tool_card_border_color(cx))
7356 .overflow_hidden()
7357 .child(
7358 Button::new(button_id, label)
7359 .label_size(LabelSize::Small)
7360 .color(Color::Muted)
7361 .truncate(true)
7362 .when(is_file.is_none(), |this| {
7363 this.end_icon(
7364 Icon::new(IconName::ArrowUpRight)
7365 .size(IconSize::XSmall)
7366 .color(Color::Muted),
7367 )
7368 })
7369 .on_click(cx.listener({
7370 let workspace = self.workspace.clone();
7371 move |_, _, window, cx: &mut Context<Self>| {
7372 open_link(uri.clone(), &workspace, window, cx);
7373 }
7374 })),
7375 )
7376 .into_any_element()
7377 }
7378
7379 fn render_diff_editor(
7380 &self,
7381 entry_ix: usize,
7382 diff: &Entity<acp_thread::Diff>,
7383 tool_call: &ToolCall,
7384 has_failed: bool,
7385 cx: &Context<Self>,
7386 ) -> AnyElement {
7387 let tool_progress = matches!(
7388 &tool_call.status,
7389 ToolCallStatus::InProgress | ToolCallStatus::Pending
7390 );
7391
7392 let revealed_diff_editor = if let Some(entry) =
7393 self.entry_view_state.read(cx).entry(entry_ix)
7394 && let Some(editor) = entry.editor_for_diff(diff)
7395 && diff.read(cx).has_revealed_range(cx)
7396 {
7397 Some(editor)
7398 } else {
7399 None
7400 };
7401
7402 let show_top_border = !has_failed || revealed_diff_editor.is_some();
7403
7404 v_flex()
7405 .h_full()
7406 .when(show_top_border, |this| {
7407 this.border_t_1()
7408 .when(has_failed, |this| this.border_dashed())
7409 .border_color(self.tool_card_border_color(cx))
7410 })
7411 .child(if let Some(editor) = revealed_diff_editor {
7412 editor.into_any_element()
7413 } else if tool_progress && self.as_native_connection(cx).is_some() {
7414 self.render_diff_loading(cx)
7415 } else {
7416 Empty.into_any()
7417 })
7418 .into_any()
7419 }
7420
7421 fn render_markdown_output(
7422 &self,
7423 markdown: Entity<Markdown>,
7424 tool_call_id: acp::ToolCallId,
7425 context_ix: usize,
7426 card_layout: bool,
7427 window: &Window,
7428 cx: &Context<Self>,
7429 ) -> AnyElement {
7430 let button_id = SharedString::from(format!("tool_output-{:?}", tool_call_id));
7431
7432 v_flex()
7433 .gap_2()
7434 .map(|this| {
7435 if card_layout {
7436 this.when(context_ix > 0, |this| {
7437 this.pt_2()
7438 .border_t_1()
7439 .border_color(self.tool_card_border_color(cx))
7440 })
7441 } else {
7442 this.ml(rems(0.4))
7443 .px_3p5()
7444 .border_l_1()
7445 .border_color(self.tool_card_border_color(cx))
7446 }
7447 })
7448 .text_xs()
7449 .text_color(cx.theme().colors().text_muted)
7450 .child(self.render_markdown(
7451 markdown,
7452 MarkdownStyle::themed(MarkdownFont::Agent, window, cx),
7453 ))
7454 .when(!card_layout, |this| {
7455 this.child(
7456 IconButton::new(button_id, IconName::ChevronUp)
7457 .full_width()
7458 .style(ButtonStyle::Outlined)
7459 .icon_color(Color::Muted)
7460 .on_click(cx.listener({
7461 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
7462 this.expanded_tool_calls.remove(&tool_call_id);
7463 cx.notify();
7464 }
7465 })),
7466 )
7467 })
7468 .into_any_element()
7469 }
7470
7471 fn render_image_output(
7472 &self,
7473 entry_ix: usize,
7474 image: Arc<gpui::Image>,
7475 location: Option<acp::ToolCallLocation>,
7476 card_layout: bool,
7477 show_dimensions: bool,
7478 cx: &Context<Self>,
7479 ) -> AnyElement {
7480 let dimensions_label = if show_dimensions {
7481 let format_name = match image.format() {
7482 gpui::ImageFormat::Png => "PNG",
7483 gpui::ImageFormat::Jpeg => "JPEG",
7484 gpui::ImageFormat::Webp => "WebP",
7485 gpui::ImageFormat::Gif => "GIF",
7486 gpui::ImageFormat::Svg => "SVG",
7487 gpui::ImageFormat::Bmp => "BMP",
7488 gpui::ImageFormat::Tiff => "TIFF",
7489 gpui::ImageFormat::Ico => "ICO",
7490 };
7491 let dimensions = image::ImageReader::new(std::io::Cursor::new(image.bytes()))
7492 .with_guessed_format()
7493 .ok()
7494 .and_then(|reader| reader.into_dimensions().ok());
7495 dimensions.map(|(w, h)| format!("{}×{} {}", w, h, format_name))
7496 } else {
7497 None
7498 };
7499
7500 v_flex()
7501 .gap_2()
7502 .map(|this| {
7503 if card_layout {
7504 this
7505 } else {
7506 this.ml(rems(0.4))
7507 .px_3p5()
7508 .border_l_1()
7509 .border_color(self.tool_card_border_color(cx))
7510 }
7511 })
7512 .when(dimensions_label.is_some() || location.is_some(), |this| {
7513 this.child(
7514 h_flex()
7515 .w_full()
7516 .justify_between()
7517 .items_center()
7518 .children(dimensions_label.map(|label| {
7519 Label::new(label)
7520 .size(LabelSize::XSmall)
7521 .color(Color::Muted)
7522 .buffer_font(cx)
7523 }))
7524 .when_some(location, |this, _loc| {
7525 this.child(
7526 Button::new(("go-to-file", entry_ix), "Go to File")
7527 .label_size(LabelSize::Small)
7528 .on_click(cx.listener(move |this, _, window, cx| {
7529 this.open_tool_call_location(entry_ix, 0, window, cx);
7530 })),
7531 )
7532 }),
7533 )
7534 })
7535 .child(
7536 img(image)
7537 .max_w_96()
7538 .max_h_96()
7539 .object_fit(ObjectFit::ScaleDown),
7540 )
7541 .into_any_element()
7542 }
7543
7544 fn render_subagent_tool_call(
7545 &self,
7546 active_session_id: &acp::SessionId,
7547 entry_ix: usize,
7548 tool_call: &ToolCall,
7549 subagent_session_id: Option<acp::SessionId>,
7550 focus_handle: &FocusHandle,
7551 window: &Window,
7552 cx: &Context<Self>,
7553 ) -> Div {
7554 let subagent_thread_view = subagent_session_id.and_then(|id| {
7555 self.server_view
7556 .upgrade()
7557 .and_then(|server_view| server_view.read(cx).as_connected())
7558 .and_then(|connected| connected.threads.get(&id))
7559 });
7560
7561 let content = self.render_subagent_card(
7562 active_session_id,
7563 entry_ix,
7564 subagent_thread_view,
7565 tool_call,
7566 focus_handle,
7567 window,
7568 cx,
7569 );
7570
7571 v_flex().mx_5().my_1p5().gap_3().child(content)
7572 }
7573
7574 fn render_subagent_card(
7575 &self,
7576 active_session_id: &acp::SessionId,
7577 entry_ix: usize,
7578 thread_view: Option<&Entity<ThreadView>>,
7579 tool_call: &ToolCall,
7580 focus_handle: &FocusHandle,
7581 window: &Window,
7582 cx: &Context<Self>,
7583 ) -> AnyElement {
7584 let thread = thread_view
7585 .as_ref()
7586 .map(|view| view.read(cx).thread.clone());
7587 let subagent_session_id = thread
7588 .as_ref()
7589 .map(|thread| thread.read(cx).session_id().clone());
7590 let action_log = thread.as_ref().map(|thread| thread.read(cx).action_log());
7591 let changed_buffers = action_log
7592 .map(|log| log.read(cx).changed_buffers(cx))
7593 .unwrap_or_default();
7594
7595 let is_pending_tool_call = thread
7596 .as_ref()
7597 .and_then(|thread| {
7598 self.conversation
7599 .read(cx)
7600 .pending_tool_call(thread.read(cx).session_id(), cx)
7601 })
7602 .is_some();
7603
7604 let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
7605 let files_changed = changed_buffers.len();
7606 let diff_stats = DiffStats::all_files(&changed_buffers, cx);
7607
7608 let is_running = matches!(
7609 tool_call.status,
7610 ToolCallStatus::Pending
7611 | ToolCallStatus::InProgress
7612 | ToolCallStatus::WaitingForConfirmation { .. }
7613 );
7614
7615 let is_failed = matches!(
7616 tool_call.status,
7617 ToolCallStatus::Failed | ToolCallStatus::Rejected
7618 );
7619
7620 let is_cancelled = matches!(tool_call.status, ToolCallStatus::Canceled)
7621 || tool_call.content.iter().any(|c| match c {
7622 ToolCallContent::ContentBlock(ContentBlock::Markdown { markdown }) => {
7623 markdown.read(cx).source() == "User canceled"
7624 }
7625 _ => false,
7626 });
7627
7628 let thread_title = thread
7629 .as_ref()
7630 .and_then(|t| t.read(cx).title())
7631 .filter(|t| !t.is_empty());
7632 let tool_call_label = tool_call.label.read(cx).source().to_string();
7633 let has_tool_call_label = !tool_call_label.is_empty();
7634
7635 let has_title = thread_title.is_some() || has_tool_call_label;
7636 let has_no_title_or_canceled = !has_title || is_failed || is_cancelled;
7637
7638 let title: SharedString = if let Some(thread_title) = thread_title {
7639 thread_title
7640 } else if !tool_call_label.is_empty() {
7641 tool_call_label.into()
7642 } else if is_cancelled {
7643 "Subagent Canceled".into()
7644 } else if is_failed {
7645 "Subagent Failed".into()
7646 } else {
7647 "Spawning Agent…".into()
7648 };
7649
7650 let card_header_id = format!("subagent-header-{}", entry_ix);
7651 let status_icon = format!("status-icon-{}", entry_ix);
7652 let diff_stat_id = format!("subagent-diff-{}", entry_ix);
7653
7654 let icon = h_flex().w_4().justify_center().child(if is_running {
7655 SpinnerLabel::new()
7656 .size(LabelSize::Small)
7657 .into_any_element()
7658 } else if is_cancelled {
7659 div()
7660 .id(status_icon)
7661 .child(
7662 Icon::new(IconName::Circle)
7663 .size(IconSize::Small)
7664 .color(Color::Custom(
7665 cx.theme().colors().icon_disabled.opacity(0.5),
7666 )),
7667 )
7668 .tooltip(Tooltip::text("Subagent Cancelled"))
7669 .into_any_element()
7670 } else if is_failed {
7671 div()
7672 .id(status_icon)
7673 .child(
7674 Icon::new(IconName::Close)
7675 .size(IconSize::Small)
7676 .color(Color::Error),
7677 )
7678 .tooltip(Tooltip::text("Subagent Failed"))
7679 .into_any_element()
7680 } else {
7681 Icon::new(IconName::Check)
7682 .size(IconSize::Small)
7683 .color(Color::Success)
7684 .into_any_element()
7685 });
7686
7687 let has_expandable_content = thread
7688 .as_ref()
7689 .map_or(false, |thread| !thread.read(cx).entries().is_empty());
7690
7691 let tooltip_meta_description = if is_expanded {
7692 "Click to Collapse"
7693 } else {
7694 "Click to Preview"
7695 };
7696
7697 let error_message = self.subagent_error_message(&tool_call.status, tool_call, cx);
7698
7699 v_flex()
7700 .w_full()
7701 .rounded_md()
7702 .border_1()
7703 .when(has_no_title_or_canceled, |this| this.border_dashed())
7704 .border_color(self.tool_card_border_color(cx))
7705 .overflow_hidden()
7706 .child(
7707 h_flex()
7708 .group(&card_header_id)
7709 .h_8()
7710 .p_1()
7711 .w_full()
7712 .justify_between()
7713 .when(!has_no_title_or_canceled, |this| {
7714 this.bg(self.tool_card_header_bg(cx))
7715 })
7716 .child(
7717 h_flex()
7718 .id(format!("subagent-title-{}", entry_ix))
7719 .px_1()
7720 .min_w_0()
7721 .size_full()
7722 .gap_2()
7723 .justify_between()
7724 .rounded_sm()
7725 .overflow_hidden()
7726 .child(
7727 h_flex()
7728 .min_w_0()
7729 .w_full()
7730 .gap_1p5()
7731 .child(icon)
7732 .child(
7733 Label::new(title.to_string())
7734 .size(LabelSize::Custom(self.tool_name_font_size()))
7735 .truncate(),
7736 )
7737 .when(files_changed > 0, |this| {
7738 this.child(
7739 Label::new(format!(
7740 "— {} {} changed",
7741 files_changed,
7742 if files_changed == 1 { "file" } else { "files" }
7743 ))
7744 .size(LabelSize::Custom(self.tool_name_font_size()))
7745 .color(Color::Muted),
7746 )
7747 .child(
7748 DiffStat::new(
7749 diff_stat_id.clone(),
7750 diff_stats.lines_added as usize,
7751 diff_stats.lines_removed as usize,
7752 )
7753 .label_size(LabelSize::Custom(
7754 self.tool_name_font_size(),
7755 )),
7756 )
7757 }),
7758 )
7759 .when(!has_no_title_or_canceled && !is_pending_tool_call, |this| {
7760 this.tooltip(move |_, cx| {
7761 Tooltip::with_meta(
7762 title.to_string(),
7763 None,
7764 tooltip_meta_description,
7765 cx,
7766 )
7767 })
7768 })
7769 .when(has_expandable_content && !is_pending_tool_call, |this| {
7770 this.cursor_pointer()
7771 .hover(|s| s.bg(cx.theme().colors().element_hover))
7772 .child(
7773 div().visible_on_hover(card_header_id).child(
7774 Icon::new(if is_expanded {
7775 IconName::ChevronUp
7776 } else {
7777 IconName::ChevronDown
7778 })
7779 .color(Color::Muted)
7780 .size(IconSize::Small),
7781 ),
7782 )
7783 .on_click(cx.listener({
7784 let tool_call_id = tool_call.id.clone();
7785 move |this, _, _, cx| {
7786 if this.expanded_tool_calls.contains(&tool_call_id) {
7787 this.expanded_tool_calls.remove(&tool_call_id);
7788 } else {
7789 this.expanded_tool_calls
7790 .insert(tool_call_id.clone());
7791 }
7792 let expanded =
7793 this.expanded_tool_calls.contains(&tool_call_id);
7794 telemetry::event!("Subagent Toggled", expanded);
7795 cx.notify();
7796 }
7797 }))
7798 }),
7799 )
7800 .when(is_running && subagent_session_id.is_some(), |buttons| {
7801 buttons.child(
7802 IconButton::new(format!("stop-subagent-{}", entry_ix), IconName::Stop)
7803 .icon_size(IconSize::Small)
7804 .icon_color(Color::Error)
7805 .tooltip(Tooltip::text("Stop Subagent"))
7806 .when_some(
7807 thread_view
7808 .as_ref()
7809 .map(|view| view.read(cx).thread.clone()),
7810 |this, thread| {
7811 this.on_click(cx.listener(
7812 move |_this, _event, _window, cx| {
7813 telemetry::event!("Subagent Stopped");
7814 thread.update(cx, |thread, cx| {
7815 thread.cancel(cx).detach();
7816 });
7817 },
7818 ))
7819 },
7820 ),
7821 )
7822 }),
7823 )
7824 .when_some(thread_view, |this, thread_view| {
7825 let thread = &thread_view.read(cx).thread;
7826 let pending_tool_call = self
7827 .conversation
7828 .read(cx)
7829 .pending_tool_call(thread.read(cx).session_id(), cx);
7830
7831 let session_id = thread.read(cx).session_id().clone();
7832
7833 let fullscreen_toggle = h_flex()
7834 .id(entry_ix)
7835 .py_1()
7836 .w_full()
7837 .justify_center()
7838 .border_t_1()
7839 .when(is_failed, |this| this.border_dashed())
7840 .border_color(self.tool_card_border_color(cx))
7841 .cursor_pointer()
7842 .hover(|s| s.bg(cx.theme().colors().element_hover))
7843 .child(
7844 Icon::new(IconName::Maximize)
7845 .color(Color::Muted)
7846 .size(IconSize::Small),
7847 )
7848 .tooltip(Tooltip::text("Make Subagent Full Screen"))
7849 .on_click(cx.listener(move |this, _event, window, cx| {
7850 telemetry::event!("Subagent Maximized");
7851 this.server_view
7852 .update(cx, |this, cx| {
7853 this.navigate_to_session(session_id.clone(), window, cx);
7854 })
7855 .ok();
7856 }));
7857
7858 if is_running && let Some((_, subagent_tool_call_id, _)) = pending_tool_call {
7859 if let Some((entry_ix, tool_call)) =
7860 thread.read(cx).tool_call(&subagent_tool_call_id)
7861 {
7862 this.child(Divider::horizontal().color(DividerColor::Border))
7863 .child(thread_view.read(cx).render_any_tool_call(
7864 active_session_id,
7865 entry_ix,
7866 tool_call,
7867 focus_handle,
7868 true,
7869 window,
7870 cx,
7871 ))
7872 .child(fullscreen_toggle)
7873 } else {
7874 this
7875 }
7876 } else {
7877 this.when(is_expanded, |this| {
7878 this.child(self.render_subagent_expanded_content(
7879 thread_view,
7880 tool_call,
7881 window,
7882 cx,
7883 ))
7884 .when_some(error_message, |this, message| {
7885 this.child(
7886 Callout::new()
7887 .severity(Severity::Error)
7888 .icon(IconName::XCircle)
7889 .title(message),
7890 )
7891 })
7892 .child(fullscreen_toggle)
7893 })
7894 }
7895 })
7896 .into_any_element()
7897 }
7898
7899 fn render_subagent_expanded_content(
7900 &self,
7901 thread_view: &Entity<ThreadView>,
7902 tool_call: &ToolCall,
7903 window: &Window,
7904 cx: &Context<Self>,
7905 ) -> impl IntoElement {
7906 const MAX_PREVIEW_ENTRIES: usize = 8;
7907
7908 let subagent_view = thread_view.read(cx);
7909 let session_id = subagent_view.thread.read(cx).session_id().clone();
7910
7911 let is_canceled_or_failed = matches!(
7912 tool_call.status,
7913 ToolCallStatus::Canceled | ToolCallStatus::Failed | ToolCallStatus::Rejected
7914 );
7915
7916 let editor_bg = cx.theme().colors().editor_background;
7917 let overlay = {
7918 div()
7919 .absolute()
7920 .inset_0()
7921 .size_full()
7922 .bg(linear_gradient(
7923 180.,
7924 linear_color_stop(editor_bg.opacity(0.5), 0.),
7925 linear_color_stop(editor_bg.opacity(0.), 0.1),
7926 ))
7927 .block_mouse_except_scroll()
7928 };
7929
7930 let entries = subagent_view.thread.read(cx).entries();
7931 let total_entries = entries.len();
7932 let mut entry_range = if let Some(info) = tool_call.subagent_session_info.as_ref() {
7933 info.message_start_index
7934 ..info
7935 .message_end_index
7936 .map(|i| (i + 1).min(total_entries))
7937 .unwrap_or(total_entries)
7938 } else {
7939 0..total_entries
7940 };
7941 entry_range.start = entry_range
7942 .end
7943 .saturating_sub(MAX_PREVIEW_ENTRIES)
7944 .max(entry_range.start);
7945 let start_ix = entry_range.start;
7946
7947 let scroll_handle = self
7948 .subagent_scroll_handles
7949 .borrow_mut()
7950 .entry(session_id.clone())
7951 .or_default()
7952 .clone();
7953
7954 scroll_handle.scroll_to_bottom();
7955
7956 let rendered_entries: Vec<AnyElement> = entries
7957 .get(entry_range)
7958 .unwrap_or_default()
7959 .iter()
7960 .enumerate()
7961 .map(|(i, entry)| {
7962 let actual_ix = start_ix + i;
7963 subagent_view.render_entry(actual_ix, total_entries, entry, window, cx)
7964 })
7965 .collect();
7966
7967 v_flex()
7968 .w_full()
7969 .border_t_1()
7970 .when(is_canceled_or_failed, |this| this.border_dashed())
7971 .border_color(self.tool_card_border_color(cx))
7972 .overflow_hidden()
7973 .child(
7974 div()
7975 .pb_1()
7976 .min_h_0()
7977 .id(format!("subagent-entries-{}", session_id))
7978 .track_scroll(&scroll_handle)
7979 .children(rendered_entries),
7980 )
7981 .h_56()
7982 .child(overlay)
7983 .into_any_element()
7984 }
7985
7986 fn subagent_error_message(
7987 &self,
7988 status: &ToolCallStatus,
7989 tool_call: &ToolCall,
7990 cx: &App,
7991 ) -> Option<SharedString> {
7992 if matches!(status, ToolCallStatus::Failed) {
7993 tool_call.content.iter().find_map(|content| {
7994 if let ToolCallContent::ContentBlock(block) = content {
7995 if let acp_thread::ContentBlock::Markdown { markdown } = block {
7996 let source = markdown.read(cx).source().to_string();
7997 if !source.is_empty() {
7998 if source == "User canceled" {
7999 return None;
8000 } else {
8001 return Some(SharedString::from(source));
8002 }
8003 }
8004 }
8005 }
8006 None
8007 })
8008 } else {
8009 None
8010 }
8011 }
8012
8013 fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
8014 cx.theme()
8015 .colors()
8016 .element_background
8017 .blend(cx.theme().colors().editor_foreground.opacity(0.025))
8018 }
8019
8020 fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
8021 cx.theme().colors().border.opacity(0.8)
8022 }
8023
8024 fn tool_name_font_size(&self) -> Rems {
8025 rems_from_px(13.)
8026 }
8027
8028 pub(crate) fn render_thread_error(
8029 &mut self,
8030 window: &mut Window,
8031 cx: &mut Context<Self>,
8032 ) -> Option<Div> {
8033 let content = match self.thread_error.as_ref()? {
8034 ThreadError::Other { message, .. } => {
8035 self.render_any_thread_error(message.clone(), window, cx)
8036 }
8037 ThreadError::Refusal => self.render_refusal_error(cx),
8038 ThreadError::AuthenticationRequired(error) => {
8039 self.render_authentication_required_error(error.clone(), cx)
8040 }
8041 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
8042 };
8043
8044 Some(div().child(content))
8045 }
8046
8047 fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
8048 let model_or_agent_name = self.current_model_name(cx);
8049 let refusal_message = format!(
8050 "{} refused to respond to this prompt. \
8051 This can happen when a model believes the prompt violates its content policy \
8052 or safety guidelines, so rephrasing it can sometimes address the issue.",
8053 model_or_agent_name
8054 );
8055
8056 Callout::new()
8057 .severity(Severity::Error)
8058 .title("Request Refused")
8059 .icon(IconName::XCircle)
8060 .description(refusal_message.clone())
8061 .actions_slot(self.create_copy_button(&refusal_message))
8062 .dismiss_action(self.dismiss_error_button(cx))
8063 }
8064
8065 fn render_authentication_required_error(
8066 &self,
8067 error: SharedString,
8068 cx: &mut Context<Self>,
8069 ) -> Callout {
8070 Callout::new()
8071 .severity(Severity::Error)
8072 .title("Authentication Required")
8073 .icon(IconName::XCircle)
8074 .description(error.clone())
8075 .actions_slot(
8076 h_flex()
8077 .gap_0p5()
8078 .child(self.authenticate_button(cx))
8079 .child(self.create_copy_button(error)),
8080 )
8081 .dismiss_action(self.dismiss_error_button(cx))
8082 }
8083
8084 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
8085 const ERROR_MESSAGE: &str =
8086 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
8087
8088 Callout::new()
8089 .severity(Severity::Error)
8090 .icon(IconName::XCircle)
8091 .title("Free Usage Exceeded")
8092 .description(ERROR_MESSAGE)
8093 .actions_slot(
8094 h_flex()
8095 .gap_0p5()
8096 .child(self.upgrade_button(cx))
8097 .child(self.create_copy_button(ERROR_MESSAGE)),
8098 )
8099 .dismiss_action(self.dismiss_error_button(cx))
8100 }
8101
8102 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
8103 Button::new("upgrade", "Upgrade")
8104 .label_size(LabelSize::Small)
8105 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
8106 .on_click(cx.listener({
8107 move |this, _, _, cx| {
8108 this.clear_thread_error(cx);
8109 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
8110 }
8111 }))
8112 }
8113
8114 fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
8115 Button::new("authenticate", "Authenticate")
8116 .label_size(LabelSize::Small)
8117 .style(ButtonStyle::Filled)
8118 .on_click(cx.listener({
8119 move |this, _, window, cx| {
8120 let server_view = this.server_view.clone();
8121 let agent_name = this.agent_id.clone();
8122
8123 this.clear_thread_error(cx);
8124 if let Some(message) = this.in_flight_prompt.take() {
8125 this.message_editor.update(cx, |editor, cx| {
8126 editor.set_message(message, window, cx);
8127 });
8128 }
8129 let connection = this.thread.read(cx).connection().clone();
8130 window.defer(cx, |window, cx| {
8131 ConversationView::handle_auth_required(
8132 server_view,
8133 AuthRequired::new(),
8134 agent_name,
8135 connection,
8136 window,
8137 cx,
8138 );
8139 })
8140 }
8141 }))
8142 }
8143
8144 fn current_model_name(&self, cx: &App) -> SharedString {
8145 // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
8146 // For ACP agents, use the agent name (e.g., "Claude Agent", "Gemini CLI")
8147 // This provides better clarity about what refused the request
8148 if self.as_native_connection(cx).is_some() {
8149 self.model_selector
8150 .clone()
8151 .and_then(|selector| selector.read(cx).active_model(cx))
8152 .map(|model| model.name.clone())
8153 .unwrap_or_else(|| SharedString::from("The model"))
8154 } else {
8155 // ACP agent - use the agent name (e.g., "Claude Agent", "Gemini CLI")
8156 self.agent_id.0.clone()
8157 }
8158 }
8159
8160 fn render_any_thread_error(
8161 &mut self,
8162 error: SharedString,
8163 window: &mut Window,
8164 cx: &mut Context<'_, Self>,
8165 ) -> Callout {
8166 let can_resume = self.thread.read(cx).can_retry(cx);
8167
8168 let markdown = if let Some(markdown) = &self.thread_error_markdown {
8169 markdown.clone()
8170 } else {
8171 let markdown = cx.new(|cx| Markdown::new(error.clone(), None, None, cx));
8172 self.thread_error_markdown = Some(markdown.clone());
8173 markdown
8174 };
8175
8176 let markdown_style =
8177 MarkdownStyle::themed(MarkdownFont::Agent, window, cx).with_muted_text(cx);
8178 let description = self
8179 .render_markdown(markdown, markdown_style)
8180 .into_any_element();
8181
8182 Callout::new()
8183 .severity(Severity::Error)
8184 .icon(IconName::XCircle)
8185 .title("An Error Happened")
8186 .description_slot(description)
8187 .actions_slot(
8188 h_flex()
8189 .gap_0p5()
8190 .when(can_resume, |this| {
8191 this.child(
8192 IconButton::new("retry", IconName::RotateCw)
8193 .icon_size(IconSize::Small)
8194 .tooltip(Tooltip::text("Retry Generation"))
8195 .on_click(cx.listener(|this, _, _window, cx| {
8196 this.retry_generation(cx);
8197 })),
8198 )
8199 })
8200 .child(self.create_copy_button(error.to_string())),
8201 )
8202 .dismiss_action(self.dismiss_error_button(cx))
8203 }
8204
8205 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
8206 let workspace = self.workspace.clone();
8207 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
8208 open_link(text, &workspace, window, cx);
8209 })
8210 }
8211
8212 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
8213 let message = message.into();
8214
8215 CopyButton::new("copy-error-message", message).tooltip_label("Copy Error Message")
8216 }
8217
8218 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
8219 IconButton::new("dismiss", IconName::Close)
8220 .icon_size(IconSize::Small)
8221 .tooltip(Tooltip::text("Dismiss"))
8222 .on_click(cx.listener({
8223 move |this, _, _, cx| {
8224 this.clear_thread_error(cx);
8225 cx.notify();
8226 }
8227 }))
8228 }
8229
8230 fn render_resume_notice(_cx: &Context<Self>) -> AnyElement {
8231 let description = "This agent does not support viewing previous messages. However, your session will still continue from where you last left off.";
8232
8233 div()
8234 .px_2()
8235 .pt_2()
8236 .pb_3()
8237 .w_full()
8238 .child(
8239 Callout::new()
8240 .severity(Severity::Info)
8241 .icon(IconName::Info)
8242 .title("Resumed Session")
8243 .description(description),
8244 )
8245 .into_any_element()
8246 }
8247
8248 fn update_recent_history_from_cache(
8249 &mut self,
8250 history: &Entity<ThreadHistory>,
8251 cx: &mut Context<Self>,
8252 ) {
8253 self.recent_history_entries = history.read(cx).get_recent_sessions(3);
8254 self.hovered_recent_history_item = None;
8255 cx.notify();
8256 }
8257
8258 fn render_empty_state_section_header(
8259 &self,
8260 label: impl Into<SharedString>,
8261 action_slot: Option<AnyElement>,
8262 cx: &mut Context<Self>,
8263 ) -> impl IntoElement {
8264 div().pl_1().pr_1p5().child(
8265 h_flex()
8266 .mt_2()
8267 .pl_1p5()
8268 .pb_1()
8269 .w_full()
8270 .justify_between()
8271 .border_b_1()
8272 .border_color(cx.theme().colors().border_variant)
8273 .child(
8274 Label::new(label.into())
8275 .size(LabelSize::Small)
8276 .color(Color::Muted),
8277 )
8278 .children(action_slot),
8279 )
8280 }
8281
8282 fn render_recent_history(&self, cx: &mut Context<Self>) -> AnyElement {
8283 let render_history = !self.recent_history_entries.is_empty();
8284
8285 v_flex()
8286 .size_full()
8287 .when(render_history, |this| {
8288 let recent_history = self.recent_history_entries.clone();
8289 this.justify_end().child(
8290 v_flex()
8291 .child(
8292 self.render_empty_state_section_header(
8293 "Recent",
8294 Some(
8295 Button::new("view-history", "View All")
8296 .style(ButtonStyle::Subtle)
8297 .label_size(LabelSize::Small)
8298 .key_binding(
8299 KeyBinding::for_action_in(
8300 &OpenHistory,
8301 &self.focus_handle(cx),
8302 cx,
8303 )
8304 .map(|kb| kb.size(rems_from_px(12.))),
8305 )
8306 .on_click(move |_event, window, cx| {
8307 window.dispatch_action(OpenHistory.boxed_clone(), cx);
8308 })
8309 .into_any_element(),
8310 ),
8311 cx,
8312 ),
8313 )
8314 .child(v_flex().p_1().pr_1p5().gap_1().children({
8315 let supports_delete = self
8316 .history
8317 .as_ref()
8318 .map_or(false, |h| h.read(cx).supports_delete());
8319 recent_history
8320 .into_iter()
8321 .enumerate()
8322 .map(move |(index, entry)| {
8323 // TODO: Add keyboard navigation.
8324 let is_hovered =
8325 self.hovered_recent_history_item == Some(index);
8326 crate::thread_history_view::HistoryEntryElement::new(
8327 entry,
8328 self.server_view.clone(),
8329 )
8330 .hovered(is_hovered)
8331 .supports_delete(supports_delete)
8332 .on_hover(cx.listener(move |this, is_hovered, _window, cx| {
8333 if *is_hovered {
8334 this.hovered_recent_history_item = Some(index);
8335 } else if this.hovered_recent_history_item == Some(index) {
8336 this.hovered_recent_history_item = None;
8337 }
8338 cx.notify();
8339 }))
8340 .into_any_element()
8341 })
8342 })),
8343 )
8344 })
8345 .into_any()
8346 }
8347
8348 fn render_codex_windows_warning(&self, cx: &mut Context<Self>) -> Callout {
8349 Callout::new()
8350 .icon(IconName::Warning)
8351 .severity(Severity::Warning)
8352 .title("Codex on Windows")
8353 .description("For best performance, run Codex in Windows Subsystem for Linux (WSL2)")
8354 .actions_slot(
8355 Button::new("open-wsl-modal", "Open in WSL").on_click(cx.listener({
8356 move |_, _, _window, cx| {
8357 #[cfg(windows)]
8358 _window.dispatch_action(
8359 zed_actions::wsl_actions::OpenWsl::default().boxed_clone(),
8360 cx,
8361 );
8362 cx.notify();
8363 }
8364 })),
8365 )
8366 .dismiss_action(
8367 IconButton::new("dismiss", IconName::Close)
8368 .icon_size(IconSize::Small)
8369 .icon_color(Color::Muted)
8370 .tooltip(Tooltip::text("Dismiss Warning"))
8371 .on_click(cx.listener({
8372 move |this, _, _, cx| {
8373 this.show_codex_windows_warning = false;
8374 cx.notify();
8375 }
8376 })),
8377 )
8378 }
8379
8380 fn render_external_source_prompt_warning(&self, cx: &mut Context<Self>) -> Callout {
8381 Callout::new()
8382 .icon(IconName::Warning)
8383 .severity(Severity::Warning)
8384 .title("Review before sending")
8385 .description("This prompt was pre-filled by an external link. Read it carefully before you send it.")
8386 .dismiss_action(
8387 IconButton::new("dismiss-external-source-prompt-warning", IconName::Close)
8388 .icon_size(IconSize::Small)
8389 .icon_color(Color::Muted)
8390 .tooltip(Tooltip::text("Dismiss Warning"))
8391 .on_click(cx.listener({
8392 move |this, _, _, cx| {
8393 this.show_external_source_prompt_warning = false;
8394 cx.notify();
8395 }
8396 })),
8397 )
8398 }
8399
8400 fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
8401 let server_view = self.server_view.clone();
8402 let has_version = !version.is_empty();
8403 let title = if has_version {
8404 "New version available"
8405 } else {
8406 "Agent update available"
8407 };
8408 let button_label = if has_version {
8409 format!("Update to v{}", version)
8410 } else {
8411 "Reconnect".to_string()
8412 };
8413
8414 v_flex().w_full().justify_end().child(
8415 h_flex()
8416 .p_2()
8417 .pr_3()
8418 .w_full()
8419 .gap_1p5()
8420 .border_t_1()
8421 .border_color(cx.theme().colors().border)
8422 .bg(cx.theme().colors().element_background)
8423 .child(
8424 h_flex()
8425 .flex_1()
8426 .gap_1p5()
8427 .child(
8428 Icon::new(IconName::Download)
8429 .color(Color::Accent)
8430 .size(IconSize::Small),
8431 )
8432 .child(Label::new(title).size(LabelSize::Small)),
8433 )
8434 .child(
8435 Button::new("update-button", button_label)
8436 .label_size(LabelSize::Small)
8437 .style(ButtonStyle::Tinted(TintColor::Accent))
8438 .on_click(move |_, window, cx| {
8439 server_view
8440 .update(cx, |view, cx| view.reset(window, cx))
8441 .ok();
8442 }),
8443 ),
8444 )
8445 }
8446
8447 fn render_token_limit_callout(&self, cx: &mut Context<Self>) -> Option<Callout> {
8448 if self.token_limit_callout_dismissed {
8449 return None;
8450 }
8451
8452 let token_usage = self.thread.read(cx).token_usage()?;
8453 let ratio = token_usage.ratio();
8454
8455 let (severity, icon, title) = match ratio {
8456 acp_thread::TokenUsageRatio::Normal => return None,
8457 acp_thread::TokenUsageRatio::Warning => (
8458 Severity::Warning,
8459 IconName::Warning,
8460 "Thread reaching the token limit soon",
8461 ),
8462 acp_thread::TokenUsageRatio::Exceeded => (
8463 Severity::Error,
8464 IconName::XCircle,
8465 "Thread reached the token limit",
8466 ),
8467 };
8468
8469 let description = "To continue, start a new thread from a summary.";
8470
8471 Some(
8472 Callout::new()
8473 .severity(severity)
8474 .icon(icon)
8475 .title(title)
8476 .description(description)
8477 .actions_slot(
8478 h_flex().gap_0p5().child(
8479 Button::new("start-new-thread", "Start New Thread")
8480 .label_size(LabelSize::Small)
8481 .on_click(cx.listener(|this, _, window, cx| {
8482 let session_id = this.thread.read(cx).session_id().clone();
8483 window.dispatch_action(
8484 crate::NewNativeAgentThreadFromSummary {
8485 from_session_id: session_id,
8486 }
8487 .boxed_clone(),
8488 cx,
8489 );
8490 })),
8491 ),
8492 )
8493 .dismiss_action(self.dismiss_error_button(cx)),
8494 )
8495 }
8496
8497 fn open_permission_dropdown(
8498 &mut self,
8499 _: &crate::OpenPermissionDropdown,
8500 window: &mut Window,
8501 cx: &mut Context<Self>,
8502 ) {
8503 let menu_handle = self.permission_dropdown_handle.clone();
8504 window.defer(cx, move |window, cx| {
8505 menu_handle.toggle(window, cx);
8506 });
8507 }
8508
8509 fn open_add_context_menu(
8510 &mut self,
8511 _action: &OpenAddContextMenu,
8512 window: &mut Window,
8513 cx: &mut Context<Self>,
8514 ) {
8515 let menu_handle = self.add_context_menu_handle.clone();
8516 window.defer(cx, move |window, cx| {
8517 menu_handle.toggle(window, cx);
8518 });
8519 }
8520
8521 fn toggle_fast_mode(&mut self, cx: &mut Context<Self>) {
8522 if !self.fast_mode_available(cx) {
8523 return;
8524 }
8525 let Some(thread) = self.as_native_thread(cx) else {
8526 return;
8527 };
8528 thread.update(cx, |thread, cx| {
8529 thread.set_speed(
8530 thread
8531 .speed()
8532 .map(|speed| speed.toggle())
8533 .unwrap_or(Speed::Fast),
8534 cx,
8535 );
8536 });
8537 }
8538
8539 fn cycle_thinking_effort(&mut self, cx: &mut Context<Self>) {
8540 let Some(thread) = self.as_native_thread(cx) else {
8541 return;
8542 };
8543
8544 let (effort_levels, current_effort) = {
8545 let thread_ref = thread.read(cx);
8546 let Some(model) = thread_ref.model() else {
8547 return;
8548 };
8549 if !model.supports_thinking() || !thread_ref.thinking_enabled() {
8550 return;
8551 }
8552 let effort_levels = model.supported_effort_levels();
8553 if effort_levels.is_empty() {
8554 return;
8555 }
8556 let current_effort = thread_ref.thinking_effort().cloned();
8557 (effort_levels, current_effort)
8558 };
8559
8560 let current_index = current_effort.and_then(|current| {
8561 effort_levels
8562 .iter()
8563 .position(|level| level.value == current)
8564 });
8565 let next_index = match current_index {
8566 Some(index) => (index + 1) % effort_levels.len(),
8567 None => 0,
8568 };
8569 let next_effort = effort_levels[next_index].value.to_string();
8570
8571 thread.update(cx, |thread, cx| {
8572 thread.set_thinking_effort(Some(next_effort.clone()), cx);
8573
8574 let fs = thread.project().read(cx).fs().clone();
8575 update_settings_file(fs, cx, move |settings, _| {
8576 if let Some(agent) = settings.agent.as_mut()
8577 && let Some(default_model) = agent.default_model.as_mut()
8578 {
8579 default_model.effort = Some(next_effort);
8580 }
8581 });
8582 });
8583 }
8584
8585 fn toggle_thinking_effort_menu(
8586 &mut self,
8587 _action: &ToggleThinkingEffortMenu,
8588 window: &mut Window,
8589 cx: &mut Context<Self>,
8590 ) {
8591 let menu_handle = self.thinking_effort_menu_handle.clone();
8592 window.defer(cx, move |window, cx| {
8593 menu_handle.toggle(window, cx);
8594 });
8595 }
8596}
8597
8598impl Render for ThreadView {
8599 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8600 let has_messages = self.list_state.item_count() > 0;
8601 let v2_empty_state = cx.has_flag::<AgentV2FeatureFlag>() && !has_messages;
8602
8603 let conversation = v_flex()
8604 .when(!v2_empty_state, |this| this.flex_1())
8605 .map(|this| {
8606 let this = this.when(self.resumed_without_history, |this| {
8607 this.child(Self::render_resume_notice(cx))
8608 });
8609 if has_messages {
8610 let list_state = self.list_state.clone();
8611 this.child(self.render_entries(cx))
8612 .vertical_scrollbar_for(&list_state, window, cx)
8613 .into_any()
8614 } else if v2_empty_state {
8615 this.into_any()
8616 } else {
8617 this.child(self.render_recent_history(cx)).into_any()
8618 }
8619 });
8620
8621 v_flex()
8622 .key_context("AcpThread")
8623 .track_focus(&self.focus_handle)
8624 .on_action(cx.listener(|this, _: &menu::Cancel, _, cx| {
8625 if this.parent_id.is_none() {
8626 this.cancel_generation(cx);
8627 }
8628 }))
8629 .on_action(cx.listener(|this, _: &workspace::GoBack, window, cx| {
8630 if let Some(parent_session_id) = this.parent_id.clone() {
8631 this.server_view
8632 .update(cx, |view, cx| {
8633 view.navigate_to_session(parent_session_id, window, cx);
8634 })
8635 .ok();
8636 }
8637 }))
8638 .on_action(cx.listener(Self::keep_all))
8639 .on_action(cx.listener(Self::reject_all))
8640 .on_action(cx.listener(Self::undo_last_reject))
8641 .on_action(cx.listener(Self::allow_always))
8642 .on_action(cx.listener(Self::allow_once))
8643 .on_action(cx.listener(Self::reject_once))
8644 .on_action(cx.listener(Self::handle_authorize_tool_call))
8645 .on_action(cx.listener(Self::handle_select_permission_granularity))
8646 .on_action(cx.listener(Self::handle_toggle_command_pattern))
8647 .on_action(cx.listener(Self::open_permission_dropdown))
8648 .on_action(cx.listener(Self::open_add_context_menu))
8649 .on_action(cx.listener(Self::scroll_output_page_up))
8650 .on_action(cx.listener(Self::scroll_output_page_down))
8651 .on_action(cx.listener(Self::scroll_output_line_up))
8652 .on_action(cx.listener(Self::scroll_output_line_down))
8653 .on_action(cx.listener(Self::scroll_output_to_top))
8654 .on_action(cx.listener(Self::scroll_output_to_bottom))
8655 .on_action(cx.listener(Self::scroll_output_to_previous_message))
8656 .on_action(cx.listener(Self::scroll_output_to_next_message))
8657 .on_action(cx.listener(|this, _: &ToggleFastMode, _window, cx| {
8658 this.toggle_fast_mode(cx);
8659 }))
8660 .on_action(cx.listener(|this, _: &ToggleThinkingMode, _window, cx| {
8661 if this.thread.read(cx).status() != ThreadStatus::Idle {
8662 return;
8663 }
8664 if let Some(thread) = this.as_native_thread(cx) {
8665 thread.update(cx, |thread, cx| {
8666 thread.set_thinking_enabled(!thread.thinking_enabled(), cx);
8667 });
8668 }
8669 }))
8670 .on_action(cx.listener(|this, _: &CycleThinkingEffort, _window, cx| {
8671 if this.thread.read(cx).status() != ThreadStatus::Idle {
8672 return;
8673 }
8674 this.cycle_thinking_effort(cx);
8675 }))
8676 .on_action(
8677 cx.listener(|this, action: &ToggleThinkingEffortMenu, window, cx| {
8678 if this.thread.read(cx).status() != ThreadStatus::Idle {
8679 return;
8680 }
8681 this.toggle_thinking_effort_menu(action, window, cx);
8682 }),
8683 )
8684 .on_action(cx.listener(|this, _: &SendNextQueuedMessage, window, cx| {
8685 this.send_queued_message_at_index(0, true, window, cx);
8686 }))
8687 .on_action(cx.listener(|this, _: &RemoveFirstQueuedMessage, _, cx| {
8688 this.remove_from_queue(0, cx);
8689 cx.notify();
8690 }))
8691 .on_action(cx.listener(|this, _: &EditFirstQueuedMessage, window, cx| {
8692 this.move_queued_message_to_main_editor(0, None, None, window, cx);
8693 }))
8694 .on_action(cx.listener(|this, _: &ClearMessageQueue, _, cx| {
8695 this.local_queued_messages.clear();
8696 this.sync_queue_flag_to_native_thread(cx);
8697 this.can_fast_track_queue = false;
8698 cx.notify();
8699 }))
8700 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
8701 if this.thread.read(cx).status() != ThreadStatus::Idle {
8702 return;
8703 }
8704 if let Some(config_options_view) = this.config_options_view.clone() {
8705 let handled = config_options_view.update(cx, |view, cx| {
8706 view.toggle_category_picker(
8707 acp::SessionConfigOptionCategory::Mode,
8708 window,
8709 cx,
8710 )
8711 });
8712 if handled {
8713 return;
8714 }
8715 }
8716
8717 if let Some(profile_selector) = this.profile_selector.clone() {
8718 profile_selector.read(cx).menu_handle().toggle(window, cx);
8719 } else if let Some(mode_selector) = this.mode_selector.clone() {
8720 mode_selector.read(cx).menu_handle().toggle(window, cx);
8721 }
8722 }))
8723 .on_action(cx.listener(|this, _: &CycleModeSelector, window, cx| {
8724 if this.thread.read(cx).status() != ThreadStatus::Idle {
8725 return;
8726 }
8727 if let Some(config_options_view) = this.config_options_view.clone() {
8728 let handled = config_options_view.update(cx, |view, cx| {
8729 view.cycle_category_option(
8730 acp::SessionConfigOptionCategory::Mode,
8731 false,
8732 cx,
8733 )
8734 });
8735 if handled {
8736 return;
8737 }
8738 }
8739
8740 if let Some(profile_selector) = this.profile_selector.clone() {
8741 profile_selector.update(cx, |profile_selector, cx| {
8742 profile_selector.cycle_profile(cx);
8743 });
8744 } else if let Some(mode_selector) = this.mode_selector.clone() {
8745 mode_selector.update(cx, |mode_selector, cx| {
8746 mode_selector.cycle_mode(window, cx);
8747 });
8748 }
8749 }))
8750 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
8751 if this.thread.read(cx).status() != ThreadStatus::Idle {
8752 return;
8753 }
8754 if let Some(config_options_view) = this.config_options_view.clone() {
8755 let handled = config_options_view.update(cx, |view, cx| {
8756 view.toggle_category_picker(
8757 acp::SessionConfigOptionCategory::Model,
8758 window,
8759 cx,
8760 )
8761 });
8762 if handled {
8763 return;
8764 }
8765 }
8766
8767 if let Some(model_selector) = this.model_selector.clone() {
8768 model_selector
8769 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
8770 }
8771 }))
8772 .on_action(cx.listener(|this, _: &CycleFavoriteModels, window, cx| {
8773 if this.thread.read(cx).status() != ThreadStatus::Idle {
8774 return;
8775 }
8776 if let Some(config_options_view) = this.config_options_view.clone() {
8777 let handled = config_options_view.update(cx, |view, cx| {
8778 view.cycle_category_option(
8779 acp::SessionConfigOptionCategory::Model,
8780 true,
8781 cx,
8782 )
8783 });
8784 if handled {
8785 return;
8786 }
8787 }
8788
8789 if let Some(model_selector) = this.model_selector.clone() {
8790 model_selector.update(cx, |model_selector, cx| {
8791 model_selector.cycle_favorite_models(window, cx);
8792 });
8793 }
8794 }))
8795 .size_full()
8796 .children(self.render_subagent_titlebar(cx))
8797 .child(conversation)
8798 .children(self.render_activity_bar(window, cx))
8799 .when(self.show_external_source_prompt_warning, |this| {
8800 this.child(self.render_external_source_prompt_warning(cx))
8801 })
8802 .when(self.show_codex_windows_warning, |this| {
8803 this.child(self.render_codex_windows_warning(cx))
8804 })
8805 .children(self.render_thread_retry_status_callout())
8806 .children(self.render_thread_error(window, cx))
8807 .when_some(
8808 match has_messages {
8809 true => None,
8810 false => self.new_server_version_available.clone(),
8811 },
8812 |this, version| this.child(self.render_new_version_callout(&version, cx)),
8813 )
8814 .children(self.render_token_limit_callout(cx))
8815 .child(self.render_message_editor(window, cx))
8816 }
8817}
8818
8819pub(crate) fn open_link(
8820 url: SharedString,
8821 workspace: &WeakEntity<Workspace>,
8822 window: &mut Window,
8823 cx: &mut App,
8824) {
8825 let Some(workspace) = workspace.upgrade() else {
8826 cx.open_url(&url);
8827 return;
8828 };
8829
8830 if let Some(mention) = MentionUri::parse(&url, workspace.read(cx).path_style(cx)).log_err() {
8831 workspace.update(cx, |workspace, cx| match mention {
8832 MentionUri::File { abs_path } => {
8833 let project = workspace.project();
8834 let Some(path) =
8835 project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
8836 else {
8837 return;
8838 };
8839
8840 workspace
8841 .open_path(path, None, true, window, cx)
8842 .detach_and_log_err(cx);
8843 }
8844 MentionUri::PastedImage => {}
8845 MentionUri::Directory { abs_path } => {
8846 let project = workspace.project();
8847 let Some(entry_id) = project.update(cx, |project, cx| {
8848 let path = project.find_project_path(abs_path, cx)?;
8849 project.entry_for_path(&path, cx).map(|entry| entry.id)
8850 }) else {
8851 return;
8852 };
8853
8854 project.update(cx, |_, cx| {
8855 cx.emit(project::Event::RevealInProjectPanel(entry_id));
8856 });
8857 }
8858 MentionUri::Symbol {
8859 abs_path: path,
8860 line_range,
8861 ..
8862 }
8863 | MentionUri::Selection {
8864 abs_path: Some(path),
8865 line_range,
8866 } => {
8867 let project = workspace.project();
8868 let Some(path) =
8869 project.update(cx, |project, cx| project.find_project_path(path, cx))
8870 else {
8871 return;
8872 };
8873
8874 let item = workspace.open_path(path, None, true, window, cx);
8875 window
8876 .spawn(cx, async move |cx| {
8877 let Some(editor) = item.await?.downcast::<Editor>() else {
8878 return Ok(());
8879 };
8880 let range =
8881 Point::new(*line_range.start(), 0)..Point::new(*line_range.start(), 0);
8882 editor
8883 .update_in(cx, |editor, window, cx| {
8884 editor.change_selections(
8885 SelectionEffects::scroll(Autoscroll::center()),
8886 window,
8887 cx,
8888 |s| s.select_ranges(vec![range]),
8889 );
8890 })
8891 .ok();
8892 anyhow::Ok(())
8893 })
8894 .detach_and_log_err(cx);
8895 }
8896 MentionUri::Selection { abs_path: None, .. } => {}
8897 MentionUri::Thread { id, name } => {
8898 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
8899 panel.update(cx, |panel, cx| {
8900 panel.open_thread(id, None, Some(name.into()), window, cx)
8901 });
8902 }
8903 }
8904 MentionUri::Rule { id, .. } => {
8905 let PromptId::User { uuid } = id else {
8906 return;
8907 };
8908 window.dispatch_action(
8909 Box::new(OpenRulesLibrary {
8910 prompt_to_select: Some(uuid.0),
8911 }),
8912 cx,
8913 )
8914 }
8915 MentionUri::Fetch { url } => {
8916 cx.open_url(url.as_str());
8917 }
8918 MentionUri::Diagnostics { .. } => {}
8919 MentionUri::TerminalSelection { .. } => {}
8920 MentionUri::GitDiff { .. } => {}
8921 MentionUri::MergeConflict { .. } => {}
8922 })
8923 } else {
8924 cx.open_url(&url);
8925 }
8926}