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