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