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