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