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