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