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