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 if AgentSettings::get_global(cx).enable_feedback
4944 && self.thread.read(cx).connection().telemetry().is_some()
4945 {
4946 let feedback = self.thread_feedback.feedback;
4947
4948 let tooltip_meta = || {
4949 SharedString::new(
4950 "Rating the thread sends all of your current conversation to the Zed team.",
4951 )
4952 };
4953
4954 container = container
4955 .child(
4956 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
4957 .shape(ui::IconButtonShape::Square)
4958 .icon_size(IconSize::Small)
4959 .icon_color(match feedback {
4960 Some(ThreadFeedback::Positive) => Color::Accent,
4961 _ => Color::Ignored,
4962 })
4963 .tooltip(move |window, cx| match feedback {
4964 Some(ThreadFeedback::Positive) => {
4965 Tooltip::text("Thanks for your feedback!")(window, cx)
4966 }
4967 _ => {
4968 Tooltip::with_meta("Helpful Response", None, tooltip_meta(), cx)
4969 }
4970 })
4971 .on_click(cx.listener(move |this, _, window, cx| {
4972 this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
4973 })),
4974 )
4975 .child(
4976 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
4977 .shape(ui::IconButtonShape::Square)
4978 .icon_size(IconSize::Small)
4979 .icon_color(match feedback {
4980 Some(ThreadFeedback::Negative) => Color::Accent,
4981 _ => Color::Ignored,
4982 })
4983 .tooltip(move |window, cx| match feedback {
4984 Some(ThreadFeedback::Negative) => {
4985 Tooltip::text(
4986 "We appreciate your feedback and will use it to improve in the future.",
4987 )(window, cx)
4988 }
4989 _ => {
4990 Tooltip::with_meta(
4991 "Not Helpful Response",
4992 None,
4993 tooltip_meta(),
4994 cx,
4995 )
4996 }
4997 })
4998 .on_click(cx.listener(move |this, _, window, cx| {
4999 this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
5000 })),
5001 );
5002 }
5003
5004 if let Some(project) = self.project.upgrade()
5005 && let Some(server_view) = self.server_view.upgrade()
5006 && cx.has_flag::<AgentSharingFeatureFlag>()
5007 && project.read(cx).client().status().borrow().is_connected()
5008 {
5009 let button = if self.is_imported_thread(cx) {
5010 IconButton::new("sync-thread", IconName::ArrowCircle)
5011 .shape(ui::IconButtonShape::Square)
5012 .icon_size(IconSize::Small)
5013 .icon_color(Color::Ignored)
5014 .tooltip(Tooltip::text("Sync with source thread"))
5015 .on_click(cx.listener(move |this, _, window, cx| {
5016 this.sync_thread(project.clone(), server_view.clone(), window, cx);
5017 }))
5018 } else {
5019 IconButton::new("share-thread", IconName::ArrowUpRight)
5020 .shape(ui::IconButtonShape::Square)
5021 .icon_size(IconSize::Small)
5022 .icon_color(Color::Ignored)
5023 .tooltip(Tooltip::text("Share Thread"))
5024 .on_click(cx.listener(move |this, _, window, cx| {
5025 this.share_thread(window, cx);
5026 }))
5027 };
5028
5029 container = container.child(button);
5030 }
5031
5032 container
5033 .child(open_as_markdown)
5034 .child(scroll_to_recent_user_prompt)
5035 .child(scroll_to_top)
5036 .into_any_element()
5037 }
5038
5039 pub(crate) fn scroll_to_most_recent_user_prompt(&mut self, cx: &mut Context<Self>) {
5040 let entries = self.thread.read(cx).entries();
5041 if entries.is_empty() {
5042 return;
5043 }
5044
5045 // Find the most recent user message and scroll it to the top of the viewport.
5046 // (Fallback: if no user message exists, scroll to the bottom.)
5047 if let Some(ix) = entries
5048 .iter()
5049 .rposition(|entry| matches!(entry, AgentThreadEntry::UserMessage(_)))
5050 {
5051 self.list_state.scroll_to(ListOffset {
5052 item_ix: ix,
5053 offset_in_item: px(0.0),
5054 });
5055 cx.notify();
5056 } else {
5057 self.scroll_to_end(cx);
5058 }
5059 }
5060
5061 pub fn scroll_to_end(&mut self, cx: &mut Context<Self>) {
5062 self.list_state.scroll_to_end();
5063 cx.notify();
5064 }
5065
5066 fn handle_feedback_click(
5067 &mut self,
5068 feedback: ThreadFeedback,
5069 window: &mut Window,
5070 cx: &mut Context<Self>,
5071 ) {
5072 self.thread_feedback
5073 .submit(self.thread.clone(), feedback, window, cx);
5074 cx.notify();
5075 }
5076
5077 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
5078 let thread = self.thread.clone();
5079 self.thread_feedback.submit_comments(thread, cx);
5080 cx.notify();
5081 }
5082
5083 pub(crate) fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
5084 self.list_state.scroll_to(ListOffset::default());
5085 cx.notify();
5086 }
5087
5088 fn scroll_output_page_up(
5089 &mut self,
5090 _: &ScrollOutputPageUp,
5091 _window: &mut Window,
5092 cx: &mut Context<Self>,
5093 ) {
5094 let page_height = self.list_state.viewport_bounds().size.height;
5095 self.list_state.scroll_by(-page_height * 0.9);
5096 cx.notify();
5097 }
5098
5099 fn scroll_output_page_down(
5100 &mut self,
5101 _: &ScrollOutputPageDown,
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_line_up(
5111 &mut self,
5112 _: &ScrollOutputLineUp,
5113 window: &mut Window,
5114 cx: &mut Context<Self>,
5115 ) {
5116 self.list_state.scroll_by(-window.line_height() * 3.);
5117 cx.notify();
5118 }
5119
5120 fn scroll_output_line_down(
5121 &mut self,
5122 _: &ScrollOutputLineDown,
5123 window: &mut Window,
5124 cx: &mut Context<Self>,
5125 ) {
5126 self.list_state.scroll_by(window.line_height() * 3.);
5127 cx.notify();
5128 }
5129
5130 fn scroll_output_to_top(
5131 &mut self,
5132 _: &ScrollOutputToTop,
5133 _window: &mut Window,
5134 cx: &mut Context<Self>,
5135 ) {
5136 self.scroll_to_top(cx);
5137 }
5138
5139 fn scroll_output_to_bottom(
5140 &mut self,
5141 _: &ScrollOutputToBottom,
5142 _window: &mut Window,
5143 cx: &mut Context<Self>,
5144 ) {
5145 self.scroll_to_end(cx);
5146 }
5147
5148 fn scroll_output_to_previous_message(
5149 &mut self,
5150 _: &ScrollOutputToPreviousMessage,
5151 _window: &mut Window,
5152 cx: &mut Context<Self>,
5153 ) {
5154 let entries = self.thread.read(cx).entries();
5155 let current_ix = self.list_state.logical_scroll_top().item_ix;
5156 if let Some(target_ix) = (0..current_ix)
5157 .rev()
5158 .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
5159 {
5160 self.list_state.scroll_to(ListOffset {
5161 item_ix: target_ix,
5162 offset_in_item: px(0.),
5163 });
5164 cx.notify();
5165 }
5166 }
5167
5168 fn scroll_output_to_next_message(
5169 &mut self,
5170 _: &ScrollOutputToNextMessage,
5171 _window: &mut Window,
5172 cx: &mut Context<Self>,
5173 ) {
5174 let entries = self.thread.read(cx).entries();
5175 let current_ix = self.list_state.logical_scroll_top().item_ix;
5176 if let Some(target_ix) = (current_ix + 1..entries.len())
5177 .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
5178 {
5179 self.list_state.scroll_to(ListOffset {
5180 item_ix: target_ix,
5181 offset_in_item: px(0.),
5182 });
5183 cx.notify();
5184 }
5185 }
5186
5187 pub fn open_thread_as_markdown(
5188 &self,
5189 workspace: Entity<Workspace>,
5190 window: &mut Window,
5191 cx: &mut App,
5192 ) -> Task<Result<()>> {
5193 let markdown_language_task = workspace
5194 .read(cx)
5195 .app_state()
5196 .languages
5197 .language_for_name("Markdown");
5198
5199 let thread = self.thread.read(cx);
5200 let thread_title = thread
5201 .title()
5202 .unwrap_or_else(|| DEFAULT_THREAD_TITLE.into())
5203 .to_string();
5204 let markdown = thread.to_markdown(cx);
5205
5206 let project = workspace.read(cx).project().clone();
5207 window.spawn(cx, async move |cx| {
5208 let markdown_language = markdown_language_task.await?;
5209
5210 let buffer = project
5211 .update(cx, |project, cx| {
5212 project.create_buffer(Some(markdown_language), false, cx)
5213 })
5214 .await?;
5215
5216 buffer.update(cx, |buffer, cx| {
5217 buffer.set_text(markdown, cx);
5218 buffer.set_capability(language::Capability::ReadWrite, cx);
5219 });
5220
5221 workspace.update_in(cx, |workspace, window, cx| {
5222 let buffer = cx
5223 .new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_title.clone()));
5224
5225 workspace.add_item_to_active_pane(
5226 Box::new(cx.new(|cx| {
5227 let mut editor =
5228 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
5229 editor.set_breadcrumb_header(thread_title);
5230 editor
5231 })),
5232 None,
5233 true,
5234 window,
5235 cx,
5236 );
5237 })?;
5238 anyhow::Ok(())
5239 })
5240 }
5241
5242 pub(crate) fn sync_editor_mode_for_empty_state(&mut self, cx: &mut Context<Self>) {
5243 let has_messages = self.list_state.item_count() > 0;
5244 let v2_empty_state = !has_messages;
5245
5246 let mode = if v2_empty_state {
5247 EditorMode::Full {
5248 scale_ui_elements_with_buffer_font_size: false,
5249 show_active_line_background: false,
5250 sizing_behavior: SizingBehavior::Default,
5251 }
5252 } else {
5253 EditorMode::AutoHeight {
5254 min_lines: AgentSettings::get_global(cx).message_editor_min_lines,
5255 max_lines: Some(AgentSettings::get_global(cx).set_message_editor_max_lines()),
5256 }
5257 };
5258 self.message_editor.update(cx, |editor, cx| {
5259 editor.set_mode(mode, cx);
5260 });
5261 }
5262
5263 /// Ensures the list item count includes (or excludes) an extra item for the generating indicator
5264 pub(crate) fn sync_generating_indicator(&mut self, cx: &App) {
5265 let is_generating = matches!(self.thread.read(cx).status(), ThreadStatus::Generating);
5266
5267 if is_generating && !self.generating_indicator_in_list {
5268 let entries_count = self.thread.read(cx).entries().len();
5269 self.list_state.splice(entries_count..entries_count, 1);
5270 self.generating_indicator_in_list = true;
5271 } else if !is_generating && self.generating_indicator_in_list {
5272 let entries_count = self.thread.read(cx).entries().len();
5273 self.list_state.splice(entries_count..entries_count + 1, 0);
5274 self.generating_indicator_in_list = false;
5275 }
5276 }
5277
5278 fn render_generating(&self, confirmation: bool, cx: &App) -> impl IntoElement {
5279 let show_stats = AgentSettings::get_global(cx).show_turn_stats;
5280 let elapsed_label = show_stats
5281 .then(|| {
5282 self.turn_fields.turn_started_at.and_then(|started_at| {
5283 let elapsed = started_at.elapsed();
5284 (elapsed > STOPWATCH_THRESHOLD).then(|| duration_alt_display(elapsed))
5285 })
5286 })
5287 .flatten();
5288
5289 let is_blocked_on_terminal_command =
5290 !confirmation && self.is_blocked_on_terminal_command(cx);
5291 let is_waiting = confirmation || self.thread.read(cx).has_in_progress_tool_calls();
5292
5293 let turn_tokens_label = elapsed_label
5294 .is_some()
5295 .then(|| {
5296 self.turn_fields
5297 .turn_tokens
5298 .filter(|&tokens| tokens > TOKEN_THRESHOLD)
5299 .map(|tokens| crate::humanize_token_count(tokens))
5300 })
5301 .flatten();
5302
5303 let arrow_icon = if is_waiting {
5304 IconName::ArrowUp
5305 } else {
5306 IconName::ArrowDown
5307 };
5308
5309 h_flex()
5310 .id("generating-spinner")
5311 .py_2()
5312 .px(rems_from_px(22.))
5313 .gap_2()
5314 .map(|this| {
5315 if confirmation {
5316 this.child(
5317 h_flex()
5318 .w_2()
5319 .justify_center()
5320 .child(GeneratingSpinnerElement::new(SpinnerVariant::Sand)),
5321 )
5322 .child(
5323 div().min_w(rems(8.)).child(
5324 LoadingLabel::new("Awaiting Confirmation")
5325 .size(LabelSize::Small)
5326 .color(Color::Muted),
5327 ),
5328 )
5329 } else if is_blocked_on_terminal_command {
5330 this
5331 } else {
5332 this.child(
5333 h_flex()
5334 .w_2()
5335 .justify_center()
5336 .child(GeneratingSpinnerElement::new(SpinnerVariant::Dots)),
5337 )
5338 }
5339 })
5340 .when_some(elapsed_label, |this, elapsed| {
5341 this.child(
5342 Label::new(elapsed)
5343 .size(LabelSize::Small)
5344 .color(Color::Muted),
5345 )
5346 })
5347 .when_some(turn_tokens_label, |this, tokens| {
5348 this.child(
5349 h_flex()
5350 .gap_0p5()
5351 .child(
5352 Icon::new(arrow_icon)
5353 .size(IconSize::XSmall)
5354 .color(Color::Muted),
5355 )
5356 .child(
5357 Label::new(format!("{} tokens", tokens))
5358 .size(LabelSize::Small)
5359 .color(Color::Muted),
5360 ),
5361 )
5362 })
5363 .into_any_element()
5364 }
5365
5366 pub(crate) fn auto_expand_streaming_thought(&mut self, cx: &mut Context<Self>) {
5367 let thinking_display = AgentSettings::get_global(cx).thinking_display;
5368
5369 if !matches!(
5370 thinking_display,
5371 ThinkingBlockDisplay::Auto | ThinkingBlockDisplay::Preview
5372 ) {
5373 return;
5374 }
5375
5376 let key = {
5377 let thread = self.thread.read(cx);
5378 if thread.status() != ThreadStatus::Generating {
5379 return;
5380 }
5381 let entries = thread.entries();
5382 let last_ix = entries.len().saturating_sub(1);
5383 match entries.get(last_ix) {
5384 Some(AgentThreadEntry::AssistantMessage(msg)) => match msg.chunks.last() {
5385 Some(AssistantMessageChunk::Thought { .. }) => {
5386 Some((last_ix, msg.chunks.len() - 1))
5387 }
5388 _ => None,
5389 },
5390 _ => None,
5391 }
5392 };
5393
5394 if let Some(key) = key {
5395 if self.auto_expanded_thinking_block != Some(key) {
5396 self.auto_expanded_thinking_block = Some(key);
5397 self.expanded_thinking_blocks.insert(key);
5398 cx.notify();
5399 }
5400 } else if self.auto_expanded_thinking_block.is_some() {
5401 if thinking_display == ThinkingBlockDisplay::Auto {
5402 if let Some(key) = self.auto_expanded_thinking_block {
5403 if !self.user_toggled_thinking_blocks.contains(&key) {
5404 self.expanded_thinking_blocks.remove(&key);
5405 }
5406 }
5407 }
5408 self.auto_expanded_thinking_block = None;
5409 cx.notify();
5410 }
5411 }
5412
5413 pub(crate) fn clear_auto_expand_tracking(&mut self) {
5414 self.auto_expanded_thinking_block = None;
5415 }
5416
5417 fn toggle_thinking_block_expansion(&mut self, key: (usize, usize), cx: &mut Context<Self>) {
5418 let thinking_display = AgentSettings::get_global(cx).thinking_display;
5419
5420 match thinking_display {
5421 ThinkingBlockDisplay::Auto => {
5422 let is_open = self.expanded_thinking_blocks.contains(&key)
5423 || self.user_toggled_thinking_blocks.contains(&key);
5424
5425 if is_open {
5426 self.expanded_thinking_blocks.remove(&key);
5427 self.user_toggled_thinking_blocks.remove(&key);
5428 } else {
5429 self.expanded_thinking_blocks.insert(key);
5430 self.user_toggled_thinking_blocks.insert(key);
5431 }
5432 }
5433 ThinkingBlockDisplay::Preview => {
5434 let is_user_expanded = self.user_toggled_thinking_blocks.contains(&key);
5435 let is_in_expanded_set = self.expanded_thinking_blocks.contains(&key);
5436
5437 if is_user_expanded {
5438 self.user_toggled_thinking_blocks.remove(&key);
5439 self.expanded_thinking_blocks.remove(&key);
5440 } else if is_in_expanded_set {
5441 self.user_toggled_thinking_blocks.insert(key);
5442 } else {
5443 self.expanded_thinking_blocks.insert(key);
5444 self.user_toggled_thinking_blocks.insert(key);
5445 }
5446 }
5447 ThinkingBlockDisplay::AlwaysExpanded => {
5448 if self.user_toggled_thinking_blocks.contains(&key) {
5449 self.user_toggled_thinking_blocks.remove(&key);
5450 } else {
5451 self.user_toggled_thinking_blocks.insert(key);
5452 }
5453 }
5454 ThinkingBlockDisplay::AlwaysCollapsed => {
5455 if self.user_toggled_thinking_blocks.contains(&key) {
5456 self.user_toggled_thinking_blocks.remove(&key);
5457 self.expanded_thinking_blocks.remove(&key);
5458 } else {
5459 self.expanded_thinking_blocks.insert(key);
5460 self.user_toggled_thinking_blocks.insert(key);
5461 }
5462 }
5463 }
5464
5465 cx.notify();
5466 }
5467
5468 fn render_thinking_block(
5469 &self,
5470 entry_ix: usize,
5471 chunk_ix: usize,
5472 chunk: Entity<Markdown>,
5473 window: &Window,
5474 cx: &Context<Self>,
5475 ) -> AnyElement {
5476 let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
5477 let card_header_id = SharedString::from("inner-card-header");
5478
5479 let key = (entry_ix, chunk_ix);
5480
5481 let thinking_display = AgentSettings::get_global(cx).thinking_display;
5482 let is_user_toggled = self.user_toggled_thinking_blocks.contains(&key);
5483 let is_in_expanded_set = self.expanded_thinking_blocks.contains(&key);
5484
5485 let (is_open, is_constrained) = match thinking_display {
5486 ThinkingBlockDisplay::Auto => {
5487 let is_open = is_user_toggled || is_in_expanded_set;
5488 (is_open, false)
5489 }
5490 ThinkingBlockDisplay::Preview => {
5491 let is_open = is_user_toggled || is_in_expanded_set;
5492 let is_constrained = is_in_expanded_set && !is_user_toggled;
5493 (is_open, is_constrained)
5494 }
5495 ThinkingBlockDisplay::AlwaysExpanded => (!is_user_toggled, false),
5496 ThinkingBlockDisplay::AlwaysCollapsed => (is_user_toggled, false),
5497 };
5498
5499 let should_auto_scroll = self.auto_expanded_thinking_block == Some(key);
5500
5501 let scroll_handle = self
5502 .entry_view_state
5503 .read(cx)
5504 .entry(entry_ix)
5505 .and_then(|entry| entry.scroll_handle_for_assistant_message_chunk(chunk_ix));
5506
5507 if should_auto_scroll {
5508 if let Some(ref handle) = scroll_handle {
5509 handle.scroll_to_bottom();
5510 }
5511 }
5512
5513 let panel_bg = cx.theme().colors().panel_background;
5514
5515 v_flex()
5516 .gap_1()
5517 .child(
5518 h_flex()
5519 .id(header_id)
5520 .group(&card_header_id)
5521 .relative()
5522 .w_full()
5523 .pr_1()
5524 .justify_between()
5525 .child(
5526 h_flex()
5527 .h(window.line_height() - px(2.))
5528 .gap_1p5()
5529 .overflow_hidden()
5530 .child(
5531 Icon::new(IconName::ToolThink)
5532 .size(IconSize::Small)
5533 .color(Color::Muted),
5534 )
5535 .child(
5536 div()
5537 .text_size(self.tool_name_font_size())
5538 .text_color(cx.theme().colors().text_muted)
5539 .child("Thinking"),
5540 ),
5541 )
5542 .child(
5543 Disclosure::new(("expand", entry_ix), is_open)
5544 .opened_icon(IconName::ChevronUp)
5545 .closed_icon(IconName::ChevronDown)
5546 .visible_on_hover(&card_header_id)
5547 .on_click(cx.listener(
5548 move |this, _event: &ClickEvent, _window, cx| {
5549 this.toggle_thinking_block_expansion(key, cx);
5550 },
5551 )),
5552 )
5553 .on_click(cx.listener(move |this, _event: &ClickEvent, _window, cx| {
5554 this.toggle_thinking_block_expansion(key, cx);
5555 })),
5556 )
5557 .when(is_open, |this| {
5558 this.child(
5559 div()
5560 .when(is_constrained, |this| this.relative())
5561 .child(
5562 div()
5563 .id(("thinking-content", chunk_ix))
5564 .ml_1p5()
5565 .pl_3p5()
5566 .border_l_1()
5567 .border_color(self.tool_card_border_color(cx))
5568 .when(is_constrained, |this| this.max_h_64())
5569 .when_some(scroll_handle, |this, scroll_handle| {
5570 this.track_scroll(&scroll_handle)
5571 })
5572 .overflow_hidden()
5573 .child(self.render_markdown(
5574 chunk,
5575 MarkdownStyle::themed(MarkdownFont::Agent, window, cx),
5576 )),
5577 )
5578 .when(is_constrained, |this| {
5579 this.child(
5580 div()
5581 .absolute()
5582 .inset_0()
5583 .size_full()
5584 .bg(linear_gradient(
5585 180.,
5586 linear_color_stop(panel_bg.opacity(0.8), 0.),
5587 linear_color_stop(panel_bg.opacity(0.), 0.1),
5588 ))
5589 .block_mouse_except_scroll(),
5590 )
5591 }),
5592 )
5593 })
5594 .into_any_element()
5595 }
5596
5597 fn render_message_context_menu(
5598 &self,
5599 entry_ix: usize,
5600 message_body: AnyElement,
5601 cx: &Context<Self>,
5602 ) -> AnyElement {
5603 let entity = cx.entity();
5604 let workspace = self.workspace.clone();
5605
5606 right_click_menu(format!("agent_context_menu-{}", entry_ix))
5607 .trigger(move |_, _, _| message_body)
5608 .menu(move |window, cx| {
5609 let focus = window.focused(cx);
5610 let entity = entity.clone();
5611 let workspace = workspace.clone();
5612
5613 ContextMenu::build(window, cx, move |menu, _, cx| {
5614 let this = entity.read(cx);
5615 let is_at_top = this.list_state.logical_scroll_top().item_ix == 0;
5616
5617 let has_selection = this
5618 .thread
5619 .read(cx)
5620 .entries()
5621 .get(entry_ix)
5622 .and_then(|entry| match &entry {
5623 AgentThreadEntry::AssistantMessage(msg) => Some(&msg.chunks),
5624 _ => None,
5625 })
5626 .map(|chunks| {
5627 chunks.iter().any(|chunk| {
5628 let md = match chunk {
5629 AssistantMessageChunk::Message { block } => block.markdown(),
5630 AssistantMessageChunk::Thought { block } => block.markdown(),
5631 };
5632 md.map_or(false, |m| m.read(cx).selected_text().is_some())
5633 })
5634 })
5635 .unwrap_or(false);
5636
5637 let copy_this_agent_response =
5638 ContextMenuEntry::new("Copy This Agent Response").handler({
5639 let entity = entity.clone();
5640 move |_, cx| {
5641 entity.update(cx, |this, cx| {
5642 let entries = this.thread.read(cx).entries();
5643 if let Some(text) =
5644 Self::get_agent_message_content(entries, entry_ix, cx)
5645 {
5646 cx.write_to_clipboard(ClipboardItem::new_string(text));
5647 }
5648 });
5649 }
5650 });
5651
5652 let scroll_item = if is_at_top {
5653 ContextMenuEntry::new("Scroll to Bottom").handler({
5654 let entity = entity.clone();
5655 move |_, cx| {
5656 entity.update(cx, |this, cx| {
5657 this.scroll_to_end(cx);
5658 });
5659 }
5660 })
5661 } else {
5662 ContextMenuEntry::new("Scroll to Top").handler({
5663 let entity = entity.clone();
5664 move |_, cx| {
5665 entity.update(cx, |this, cx| {
5666 this.scroll_to_top(cx);
5667 });
5668 }
5669 })
5670 };
5671
5672 let open_thread_as_markdown = ContextMenuEntry::new("Open Thread as Markdown")
5673 .handler({
5674 let entity = entity.clone();
5675 let workspace = workspace.clone();
5676 move |window, cx| {
5677 if let Some(workspace) = workspace.upgrade() {
5678 entity
5679 .update(cx, |this, cx| {
5680 this.open_thread_as_markdown(workspace, window, cx)
5681 })
5682 .detach_and_log_err(cx);
5683 }
5684 }
5685 });
5686
5687 menu.when_some(focus, |menu, focus| menu.context(focus))
5688 .action_disabled_when(
5689 !has_selection,
5690 "Copy Selection",
5691 Box::new(markdown::CopyAsMarkdown),
5692 )
5693 .item(copy_this_agent_response)
5694 .separator()
5695 .item(scroll_item)
5696 .item(open_thread_as_markdown)
5697 })
5698 })
5699 .into_any_element()
5700 }
5701
5702 fn get_agent_message_content(
5703 entries: &[AgentThreadEntry],
5704 entry_index: usize,
5705 cx: &App,
5706 ) -> Option<String> {
5707 let entry = entries.get(entry_index)?;
5708 if matches!(entry, AgentThreadEntry::UserMessage(_)) {
5709 return None;
5710 }
5711
5712 let start_index = (0..entry_index)
5713 .rev()
5714 .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
5715 .map(|i| i + 1)
5716 .unwrap_or(0);
5717
5718 let end_index = (entry_index + 1..entries.len())
5719 .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
5720 .map(|i| i - 1)
5721 .unwrap_or(entries.len() - 1);
5722
5723 let parts: Vec<String> = (start_index..=end_index)
5724 .filter_map(|i| entries.get(i))
5725 .filter_map(|entry| {
5726 if let AgentThreadEntry::AssistantMessage(message) = entry {
5727 let text: String = message
5728 .chunks
5729 .iter()
5730 .filter_map(|chunk| match chunk {
5731 AssistantMessageChunk::Message { block } => {
5732 let markdown = block.to_markdown(cx);
5733 if markdown.trim().is_empty() {
5734 None
5735 } else {
5736 Some(markdown.to_string())
5737 }
5738 }
5739 AssistantMessageChunk::Thought { .. } => None,
5740 })
5741 .collect::<Vec<_>>()
5742 .join("\n\n");
5743
5744 if text.is_empty() { None } else { Some(text) }
5745 } else {
5746 None
5747 }
5748 })
5749 .collect();
5750
5751 let text = parts.join("\n\n");
5752 if text.is_empty() { None } else { Some(text) }
5753 }
5754
5755 fn is_blocked_on_terminal_command(&self, cx: &App) -> bool {
5756 let thread = self.thread.read(cx);
5757 if !matches!(thread.status(), ThreadStatus::Generating) {
5758 return false;
5759 }
5760
5761 let mut has_running_terminal_call = false;
5762
5763 for entry in thread.entries().iter().rev() {
5764 match entry {
5765 AgentThreadEntry::UserMessage(_) => break,
5766 AgentThreadEntry::ToolCall(tool_call)
5767 if matches!(
5768 tool_call.status,
5769 ToolCallStatus::InProgress | ToolCallStatus::Pending
5770 ) =>
5771 {
5772 if matches!(tool_call.kind, acp::ToolKind::Execute) {
5773 has_running_terminal_call = true;
5774 } else {
5775 return false;
5776 }
5777 }
5778 AgentThreadEntry::ToolCall(_)
5779 | AgentThreadEntry::AssistantMessage(_)
5780 | AgentThreadEntry::CompletedPlan(_) => {}
5781 }
5782 }
5783
5784 has_running_terminal_call
5785 }
5786
5787 fn render_collapsible_command(
5788 &self,
5789 group: SharedString,
5790 is_preview: bool,
5791 command_source: &str,
5792 cx: &Context<Self>,
5793 ) -> Div {
5794 v_flex()
5795 .group(group.clone())
5796 .p_1p5()
5797 .bg(self.tool_card_header_bg(cx))
5798 .when(is_preview, |this| {
5799 this.pt_1().child(
5800 // Wrapping this label on a container with 24px height to avoid
5801 // layout shift when it changes from being a preview label
5802 // to the actual path where the command will run in
5803 h_flex().h_6().child(
5804 Label::new("Run Command")
5805 .buffer_font(cx)
5806 .size(LabelSize::XSmall)
5807 .color(Color::Muted),
5808 ),
5809 )
5810 })
5811 .children(command_source.lines().map(|line| {
5812 let text: SharedString = if line.is_empty() {
5813 " ".into()
5814 } else {
5815 line.to_string().into()
5816 };
5817
5818 Label::new(text).buffer_font(cx).size(LabelSize::Small)
5819 }))
5820 .child(
5821 div().absolute().top_1().right_1().child(
5822 CopyButton::new("copy-command", command_source.to_string())
5823 .tooltip_label("Copy Command")
5824 .visible_on_hover(group),
5825 ),
5826 )
5827 }
5828
5829 fn render_terminal_tool_call(
5830 &self,
5831 active_session_id: &acp::SessionId,
5832 entry_ix: usize,
5833 terminal: &Entity<acp_thread::Terminal>,
5834 tool_call: &ToolCall,
5835 focus_handle: &FocusHandle,
5836 is_subagent: bool,
5837 window: &Window,
5838 cx: &Context<Self>,
5839 ) -> AnyElement {
5840 let terminal_data = terminal.read(cx);
5841 let working_dir = terminal_data.working_dir();
5842 let command = terminal_data.command();
5843 let started_at = terminal_data.started_at();
5844
5845 let tool_failed = matches!(
5846 &tool_call.status,
5847 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed
5848 );
5849
5850 let confirmation_options = match &tool_call.status {
5851 ToolCallStatus::WaitingForConfirmation { options, .. } => Some(options),
5852 _ => None,
5853 };
5854 let needs_confirmation = confirmation_options.is_some();
5855
5856 let output = terminal_data.output();
5857 let command_finished = output.is_some()
5858 && !matches!(
5859 tool_call.status,
5860 ToolCallStatus::InProgress | ToolCallStatus::Pending
5861 );
5862 let truncated_output =
5863 output.is_some_and(|output| output.original_content_len > output.content.len());
5864 let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
5865
5866 let command_failed = command_finished
5867 && output.is_some_and(|o| o.exit_status.is_some_and(|status| !status.success()));
5868
5869 let time_elapsed = if let Some(output) = output {
5870 output.ended_at.duration_since(started_at)
5871 } else {
5872 started_at.elapsed()
5873 };
5874
5875 let header_id =
5876 SharedString::from(format!("terminal-tool-header-{}", terminal.entity_id()));
5877 let header_group = SharedString::from(format!(
5878 "terminal-tool-header-group-{}",
5879 terminal.entity_id()
5880 ));
5881 let header_bg = cx
5882 .theme()
5883 .colors()
5884 .element_background
5885 .blend(cx.theme().colors().editor_foreground.opacity(0.025));
5886 let border_color = cx.theme().colors().border.opacity(0.6);
5887
5888 let working_dir = working_dir
5889 .as_ref()
5890 .map(|path| path.display().to_string())
5891 .unwrap_or_else(|| "current directory".to_string());
5892
5893 // Since the command's source is wrapped in a markdown code block
5894 // (```\n...\n```), we need to strip that so we're left with only the
5895 // command's content.
5896 let command_source = command.read(cx).source();
5897 let command_content = command_source
5898 .strip_prefix("```\n")
5899 .and_then(|s| s.strip_suffix("\n```"))
5900 .unwrap_or(&command_source);
5901
5902 let command_element =
5903 self.render_collapsible_command(header_group.clone(), false, command_content, cx);
5904
5905 let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
5906
5907 let header = h_flex()
5908 .id(header_id)
5909 .pt_1()
5910 .pl_1p5()
5911 .pr_1()
5912 .flex_none()
5913 .gap_1()
5914 .justify_between()
5915 .rounded_t_md()
5916 .child(
5917 div()
5918 .id(("command-target-path", terminal.entity_id()))
5919 .w_full()
5920 .max_w_full()
5921 .overflow_x_scroll()
5922 .child(
5923 Label::new(working_dir)
5924 .buffer_font(cx)
5925 .size(LabelSize::XSmall)
5926 .color(Color::Muted),
5927 ),
5928 )
5929 .child(
5930 Disclosure::new(
5931 SharedString::from(format!(
5932 "terminal-tool-disclosure-{}",
5933 terminal.entity_id()
5934 )),
5935 is_expanded,
5936 )
5937 .opened_icon(IconName::ChevronUp)
5938 .closed_icon(IconName::ChevronDown)
5939 .visible_on_hover(&header_group)
5940 .on_click(cx.listener({
5941 let id = tool_call.id.clone();
5942 move |this, _event, _window, cx| {
5943 if is_expanded {
5944 this.expanded_tool_calls.remove(&id);
5945 } else {
5946 this.expanded_tool_calls.insert(id.clone());
5947 }
5948 cx.notify();
5949 }
5950 })),
5951 )
5952 .when(time_elapsed > Duration::from_secs(10), |header| {
5953 header.child(
5954 Label::new(format!("({})", duration_alt_display(time_elapsed)))
5955 .buffer_font(cx)
5956 .color(Color::Muted)
5957 .size(LabelSize::XSmall),
5958 )
5959 })
5960 .when(!command_finished && !needs_confirmation, |header| {
5961 header
5962 .gap_1p5()
5963 .child(
5964 Icon::new(IconName::ArrowCircle)
5965 .size(IconSize::XSmall)
5966 .color(Color::Muted)
5967 .with_rotate_animation(2)
5968 )
5969 .child(div().h(relative(0.6)).ml_1p5().child(Divider::vertical().color(DividerColor::Border)))
5970 .child(
5971 IconButton::new(
5972 SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
5973 IconName::Stop
5974 )
5975 .icon_size(IconSize::Small)
5976 .icon_color(Color::Error)
5977 .tooltip(move |_window, cx| {
5978 Tooltip::with_meta(
5979 "Stop This Command",
5980 None,
5981 "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
5982 cx,
5983 )
5984 })
5985 .on_click({
5986 let terminal = terminal.clone();
5987 cx.listener(move |this, _event, _window, cx| {
5988 terminal.update(cx, |terminal, cx| {
5989 terminal.stop_by_user(cx);
5990 });
5991 if AgentSettings::get_global(cx).cancel_generation_on_terminal_stop {
5992 this.cancel_generation(cx);
5993 }
5994 })
5995 }),
5996 )
5997 })
5998 .when(truncated_output, |header| {
5999 let tooltip = if let Some(output) = output {
6000 if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
6001 format!("Output exceeded terminal max lines and was \
6002 truncated, the model received the first {}.", format_file_size(output.content.len() as u64, true))
6003 } else {
6004 format!(
6005 "Output is {} long, and to avoid unexpected token usage, \
6006 only {} was sent back to the agent.",
6007 format_file_size(output.original_content_len as u64, true),
6008 format_file_size(output.content.len() as u64, true)
6009 )
6010 }
6011 } else {
6012 "Output was truncated".to_string()
6013 };
6014
6015 header.child(
6016 h_flex()
6017 .id(("terminal-tool-truncated-label", terminal.entity_id()))
6018 .gap_1()
6019 .child(
6020 Icon::new(IconName::Info)
6021 .size(IconSize::XSmall)
6022 .color(Color::Ignored),
6023 )
6024 .child(
6025 Label::new("Truncated")
6026 .color(Color::Muted)
6027 .size(LabelSize::XSmall),
6028 )
6029 .tooltip(Tooltip::text(tooltip)),
6030 )
6031 })
6032 .when(tool_failed || command_failed, |header| {
6033 header.child(
6034 div()
6035 .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
6036 .child(
6037 Icon::new(IconName::Close)
6038 .size(IconSize::Small)
6039 .color(Color::Error),
6040 )
6041 .when_some(output.and_then(|o| o.exit_status), |this, status| {
6042 this.tooltip(Tooltip::text(format!(
6043 "Exited with code {}",
6044 status.code().unwrap_or(-1),
6045 )))
6046 }),
6047 )
6048 })
6049;
6050
6051 let terminal_view = self
6052 .entry_view_state
6053 .read(cx)
6054 .entry(entry_ix)
6055 .and_then(|entry| entry.terminal(terminal));
6056
6057 v_flex()
6058 .when(!is_subagent, |this| {
6059 this.my_1p5()
6060 .mx_5()
6061 .border_1()
6062 .when(tool_failed || command_failed, |card| card.border_dashed())
6063 .border_color(border_color)
6064 .rounded_md()
6065 })
6066 .overflow_hidden()
6067 .child(
6068 v_flex()
6069 .group(&header_group)
6070 .bg(header_bg)
6071 .text_xs()
6072 .child(header)
6073 .child(command_element),
6074 )
6075 .when(is_expanded && terminal_view.is_some(), |this| {
6076 this.child(
6077 div()
6078 .pt_2()
6079 .border_t_1()
6080 .when(tool_failed || command_failed, |card| card.border_dashed())
6081 .border_color(border_color)
6082 .bg(cx.theme().colors().editor_background)
6083 .rounded_b_md()
6084 .text_ui_sm(cx)
6085 .h_full()
6086 .children(terminal_view.map(|terminal_view| {
6087 let element = if terminal_view
6088 .read(cx)
6089 .content_mode(window, cx)
6090 .is_scrollable()
6091 {
6092 div().h_72().child(terminal_view).into_any_element()
6093 } else {
6094 terminal_view.into_any_element()
6095 };
6096
6097 div()
6098 .on_action(cx.listener(|_this, _: &NewTerminal, window, cx| {
6099 window.dispatch_action(NewThread.boxed_clone(), cx);
6100 cx.stop_propagation();
6101 }))
6102 .child(element)
6103 .into_any_element()
6104 })),
6105 )
6106 })
6107 .when_some(confirmation_options, |this, options| {
6108 let is_first = self.is_first_tool_call(active_session_id, &tool_call.id, cx);
6109 this.child(self.render_permission_buttons(
6110 self.id.clone(),
6111 is_first,
6112 options,
6113 entry_ix,
6114 tool_call.id.clone(),
6115 focus_handle,
6116 cx,
6117 ))
6118 })
6119 .into_any()
6120 }
6121
6122 fn is_first_tool_call(
6123 &self,
6124 active_session_id: &acp::SessionId,
6125 tool_call_id: &acp::ToolCallId,
6126 cx: &App,
6127 ) -> bool {
6128 self.conversation
6129 .read(cx)
6130 .pending_tool_call(active_session_id, cx)
6131 .map_or(false, |(pending_session_id, pending_tool_call_id, _)| {
6132 self.id == pending_session_id && tool_call_id == &pending_tool_call_id
6133 })
6134 }
6135
6136 fn render_any_tool_call(
6137 &self,
6138 active_session_id: &acp::SessionId,
6139 entry_ix: usize,
6140 tool_call: &ToolCall,
6141 focus_handle: &FocusHandle,
6142 is_subagent: bool,
6143 window: &Window,
6144 cx: &Context<Self>,
6145 ) -> Div {
6146 let has_terminals = tool_call.terminals().next().is_some();
6147
6148 div().w_full().map(|this| {
6149 if tool_call.is_subagent() {
6150 this.child(
6151 self.render_subagent_tool_call(
6152 active_session_id,
6153 entry_ix,
6154 tool_call,
6155 tool_call
6156 .subagent_session_info
6157 .as_ref()
6158 .map(|i| i.session_id.clone()),
6159 focus_handle,
6160 window,
6161 cx,
6162 ),
6163 )
6164 } else if has_terminals {
6165 this.children(tool_call.terminals().map(|terminal| {
6166 self.render_terminal_tool_call(
6167 active_session_id,
6168 entry_ix,
6169 terminal,
6170 tool_call,
6171 focus_handle,
6172 is_subagent,
6173 window,
6174 cx,
6175 )
6176 }))
6177 } else {
6178 this.child(self.render_tool_call(
6179 active_session_id,
6180 entry_ix,
6181 tool_call,
6182 focus_handle,
6183 is_subagent,
6184 window,
6185 cx,
6186 ))
6187 }
6188 })
6189 }
6190
6191 fn render_tool_call(
6192 &self,
6193 active_session_id: &acp::SessionId,
6194 entry_ix: usize,
6195 tool_call: &ToolCall,
6196 focus_handle: &FocusHandle,
6197 is_subagent: bool,
6198 window: &Window,
6199 cx: &Context<Self>,
6200 ) -> Div {
6201 let has_location = tool_call.locations.len() == 1;
6202 let card_header_id = SharedString::from("inner-tool-call-header");
6203
6204 let failed_or_canceled = match &tool_call.status {
6205 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed => true,
6206 _ => false,
6207 };
6208
6209 let needs_confirmation = matches!(
6210 tool_call.status,
6211 ToolCallStatus::WaitingForConfirmation { .. }
6212 );
6213 let is_terminal_tool = matches!(tool_call.kind, acp::ToolKind::Execute);
6214
6215 let is_edit =
6216 matches!(tool_call.kind, acp::ToolKind::Edit) || tool_call.diffs().next().is_some();
6217
6218 let is_cancelled_edit = is_edit && matches!(tool_call.status, ToolCallStatus::Canceled);
6219 let (has_revealed_diff, tool_call_output_focus, tool_call_output_focus_handle) = tool_call
6220 .diffs()
6221 .next()
6222 .and_then(|diff| {
6223 let editor = self
6224 .entry_view_state
6225 .read(cx)
6226 .entry(entry_ix)
6227 .and_then(|entry| entry.editor_for_diff(diff))?;
6228 let has_revealed_diff = diff.read(cx).has_revealed_range(cx);
6229 let has_focus = editor.read(cx).is_focused(window);
6230 let focus_handle = editor.focus_handle(cx);
6231 Some((has_revealed_diff, has_focus, focus_handle))
6232 })
6233 .unwrap_or_else(|| (false, false, focus_handle.clone()));
6234
6235 let use_card_layout = needs_confirmation || is_edit || is_terminal_tool;
6236
6237 let has_image_content = tool_call.content.iter().any(|c| c.image().is_some());
6238 let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
6239 let mut is_open = self.expanded_tool_calls.contains(&tool_call.id);
6240
6241 is_open |= needs_confirmation;
6242
6243 let should_show_raw_input = !is_terminal_tool && !is_edit && !has_image_content;
6244
6245 let input_output_header = |label: SharedString| {
6246 Label::new(label)
6247 .size(LabelSize::XSmall)
6248 .color(Color::Muted)
6249 .buffer_font(cx)
6250 };
6251
6252 let tool_output_display = if is_open {
6253 match &tool_call.status {
6254 ToolCallStatus::WaitingForConfirmation { options, .. } => v_flex()
6255 .w_full()
6256 .children(
6257 tool_call
6258 .content
6259 .iter()
6260 .enumerate()
6261 .map(|(content_ix, content)| {
6262 div()
6263 .child(self.render_tool_call_content(
6264 active_session_id,
6265 entry_ix,
6266 content,
6267 content_ix,
6268 tool_call,
6269 use_card_layout,
6270 has_image_content,
6271 failed_or_canceled,
6272 focus_handle,
6273 window,
6274 cx,
6275 ))
6276 .into_any_element()
6277 }),
6278 )
6279 .when(should_show_raw_input, |this| {
6280 let is_raw_input_expanded =
6281 self.expanded_tool_call_raw_inputs.contains(&tool_call.id);
6282
6283 let input_header = if is_raw_input_expanded {
6284 "Raw Input:"
6285 } else {
6286 "View Raw Input"
6287 };
6288
6289 this.child(
6290 v_flex()
6291 .p_2()
6292 .gap_1()
6293 .border_t_1()
6294 .border_color(self.tool_card_border_color(cx))
6295 .child(
6296 h_flex()
6297 .id("disclosure_container")
6298 .pl_0p5()
6299 .gap_1()
6300 .justify_between()
6301 .rounded_xs()
6302 .hover(|s| s.bg(cx.theme().colors().element_hover))
6303 .child(input_output_header(input_header.into()))
6304 .child(
6305 Disclosure::new(
6306 ("raw-input-disclosure", entry_ix),
6307 is_raw_input_expanded,
6308 )
6309 .opened_icon(IconName::ChevronUp)
6310 .closed_icon(IconName::ChevronDown),
6311 )
6312 .on_click(cx.listener({
6313 let id = tool_call.id.clone();
6314
6315 move |this: &mut Self, _, _, cx| {
6316 if this.expanded_tool_call_raw_inputs.contains(&id)
6317 {
6318 this.expanded_tool_call_raw_inputs.remove(&id);
6319 } else {
6320 this.expanded_tool_call_raw_inputs
6321 .insert(id.clone());
6322 }
6323 cx.notify();
6324 }
6325 })),
6326 )
6327 .when(is_raw_input_expanded, |this| {
6328 this.children(tool_call.raw_input_markdown.clone().map(
6329 |input| {
6330 self.render_markdown(
6331 input,
6332 MarkdownStyle::themed(
6333 MarkdownFont::Agent,
6334 window,
6335 cx,
6336 ),
6337 )
6338 },
6339 ))
6340 }),
6341 )
6342 })
6343 .child(self.render_permission_buttons(
6344 self.id.clone(),
6345 self.is_first_tool_call(active_session_id, &tool_call.id, cx),
6346 options,
6347 entry_ix,
6348 tool_call.id.clone(),
6349 focus_handle,
6350 cx,
6351 ))
6352 .into_any(),
6353 ToolCallStatus::Pending | ToolCallStatus::InProgress
6354 if is_edit
6355 && tool_call.content.is_empty()
6356 && self.as_native_connection(cx).is_some() =>
6357 {
6358 self.render_diff_loading(cx)
6359 }
6360 ToolCallStatus::Pending
6361 | ToolCallStatus::InProgress
6362 | ToolCallStatus::Completed
6363 | ToolCallStatus::Failed
6364 | ToolCallStatus::Canceled => v_flex()
6365 .when(should_show_raw_input, |this| {
6366 this.mt_1p5().w_full().child(
6367 v_flex()
6368 .ml(rems(0.4))
6369 .px_3p5()
6370 .pb_1()
6371 .gap_1()
6372 .border_l_1()
6373 .border_color(self.tool_card_border_color(cx))
6374 .child(input_output_header("Raw Input:".into()))
6375 .children(tool_call.raw_input_markdown.clone().map(|input| {
6376 div().id(("tool-call-raw-input-markdown", entry_ix)).child(
6377 self.render_markdown(
6378 input,
6379 MarkdownStyle::themed(MarkdownFont::Agent, window, cx),
6380 ),
6381 )
6382 }))
6383 .child(input_output_header("Output:".into())),
6384 )
6385 })
6386 .children(
6387 tool_call
6388 .content
6389 .iter()
6390 .enumerate()
6391 .map(|(content_ix, content)| {
6392 div().id(("tool-call-output", entry_ix)).child(
6393 self.render_tool_call_content(
6394 active_session_id,
6395 entry_ix,
6396 content,
6397 content_ix,
6398 tool_call,
6399 use_card_layout,
6400 has_image_content,
6401 failed_or_canceled,
6402 focus_handle,
6403 window,
6404 cx,
6405 ),
6406 )
6407 }),
6408 )
6409 .into_any(),
6410 ToolCallStatus::Rejected => Empty.into_any(),
6411 }
6412 .into()
6413 } else {
6414 None
6415 };
6416
6417 v_flex()
6418 .map(|this| {
6419 if is_subagent {
6420 this
6421 } else if use_card_layout {
6422 this.my_1p5()
6423 .rounded_md()
6424 .border_1()
6425 .when(failed_or_canceled, |this| this.border_dashed())
6426 .border_color(self.tool_card_border_color(cx))
6427 .bg(cx.theme().colors().editor_background)
6428 .overflow_hidden()
6429 } else {
6430 this.my_1()
6431 }
6432 })
6433 .when(!is_subagent, |this| {
6434 this.map(|this| {
6435 if has_location && !use_card_layout {
6436 this.ml_4()
6437 } else {
6438 this.ml_5()
6439 }
6440 })
6441 .mr_5()
6442 })
6443 .map(|this| {
6444 if is_terminal_tool {
6445 let label_source = tool_call.label.read(cx).source();
6446 this.child(self.render_collapsible_command(
6447 card_header_id.clone(),
6448 true,
6449 label_source,
6450 cx,
6451 ))
6452 } else {
6453 this.child(
6454 h_flex()
6455 .group(&card_header_id)
6456 .relative()
6457 .w_full()
6458 .justify_between()
6459 .when(use_card_layout, |this| {
6460 this.p_0p5()
6461 .rounded_t(rems_from_px(5.))
6462 .bg(self.tool_card_header_bg(cx))
6463 })
6464 .child(self.render_tool_call_label(
6465 entry_ix,
6466 tool_call,
6467 is_edit,
6468 is_cancelled_edit,
6469 has_revealed_diff,
6470 use_card_layout,
6471 window,
6472 cx,
6473 ))
6474 .child(
6475 h_flex()
6476 .when(is_collapsible || failed_or_canceled, |this| {
6477 let diff_for_discard = if has_revealed_diff
6478 && is_cancelled_edit
6479 {
6480 tool_call.diffs().next().cloned()
6481 } else {
6482 None
6483 };
6484
6485 this.child(
6486 h_flex()
6487 .pr_0p5()
6488 .gap_1()
6489 .when(is_collapsible, |this| {
6490 this.child(
6491 Disclosure::new(
6492 ("expand-output", entry_ix),
6493 is_open,
6494 )
6495 .opened_icon(IconName::ChevronUp)
6496 .closed_icon(IconName::ChevronDown)
6497 .visible_on_hover(&card_header_id)
6498 .on_click(cx.listener({
6499 let id = tool_call.id.clone();
6500 move |this: &mut Self,
6501 _,
6502 _,
6503 cx: &mut Context<Self>| {
6504 if is_open {
6505 this.expanded_tool_calls
6506 .remove(&id);
6507 } else {
6508 this.expanded_tool_calls
6509 .insert(id.clone());
6510 }
6511 cx.notify();
6512 }
6513 })),
6514 )
6515 })
6516 .when(failed_or_canceled, |this| {
6517 if is_cancelled_edit && !has_revealed_diff {
6518 this.child(
6519 div()
6520 .id(entry_ix)
6521 .tooltip(Tooltip::text(
6522 "Interrupted Edit",
6523 ))
6524 .child(
6525 Icon::new(IconName::XCircle)
6526 .color(Color::Muted)
6527 .size(IconSize::Small),
6528 ),
6529 )
6530 } else if is_cancelled_edit {
6531 this
6532 } else {
6533 this.child(
6534 Icon::new(IconName::Close)
6535 .color(Color::Error)
6536 .size(IconSize::Small),
6537 )
6538 }
6539 })
6540 .when_some(diff_for_discard, |this, diff| {
6541 let tool_call_id = tool_call.id.clone();
6542 let is_discarded = self
6543 .discarded_partial_edits
6544 .contains(&tool_call_id);
6545
6546 this.when(!is_discarded, |this| {
6547 this.child(
6548 IconButton::new(
6549 ("discard-partial-edit", entry_ix),
6550 IconName::Undo,
6551 )
6552 .icon_size(IconSize::Small)
6553 .tooltip(move |_, cx| {
6554 Tooltip::with_meta(
6555 "Discard Interrupted Edit",
6556 None,
6557 "You can discard this interrupted partial edit and restore the original file content.",
6558 cx,
6559 )
6560 })
6561 .on_click(cx.listener({
6562 let tool_call_id =
6563 tool_call_id.clone();
6564 move |this, _, _window, cx| {
6565 let diff_data = diff.read(cx);
6566 let base_text = diff_data
6567 .base_text()
6568 .clone();
6569 let buffer =
6570 diff_data.buffer().clone();
6571 buffer.update(
6572 cx,
6573 |buffer, cx| {
6574 buffer.set_text(
6575 base_text.as_ref(),
6576 cx,
6577 );
6578 },
6579 );
6580 this.discarded_partial_edits
6581 .insert(
6582 tool_call_id.clone(),
6583 );
6584 cx.notify();
6585 }
6586 })),
6587 )
6588 })
6589 }),
6590 )
6591 })
6592 .when(tool_call_output_focus, |this| {
6593 this.child(
6594 Button::new("open-file-button", "Open File")
6595 .style(ButtonStyle::Outlined)
6596 .label_size(LabelSize::Small)
6597 .key_binding(
6598 KeyBinding::for_action_in(&OpenExcerpts, &tool_call_output_focus_handle, cx)
6599 .map(|s| s.size(rems_from_px(12.))),
6600 )
6601 .on_click(|_, window, cx| {
6602 window.dispatch_action(
6603 Box::new(OpenExcerpts),
6604 cx,
6605 )
6606 }),
6607 )
6608 }),
6609 )
6610
6611 )
6612 }
6613 })
6614 .children(tool_output_display)
6615 }
6616
6617 fn render_permission_buttons(
6618 &self,
6619 session_id: acp::SessionId,
6620 is_first: bool,
6621 options: &PermissionOptions,
6622 entry_ix: usize,
6623 tool_call_id: acp::ToolCallId,
6624 focus_handle: &FocusHandle,
6625 cx: &Context<Self>,
6626 ) -> Div {
6627 match options {
6628 PermissionOptions::Flat(options) => self.render_permission_buttons_flat(
6629 session_id,
6630 is_first,
6631 options,
6632 entry_ix,
6633 tool_call_id,
6634 focus_handle,
6635 cx,
6636 ),
6637 PermissionOptions::Dropdown(choices) => self.render_permission_buttons_with_dropdown(
6638 is_first,
6639 choices,
6640 None,
6641 entry_ix,
6642 tool_call_id,
6643 focus_handle,
6644 cx,
6645 ),
6646 PermissionOptions::DropdownWithPatterns {
6647 choices,
6648 patterns,
6649 tool_name,
6650 } => self.render_permission_buttons_with_dropdown(
6651 is_first,
6652 choices,
6653 Some((patterns, tool_name)),
6654 entry_ix,
6655 tool_call_id,
6656 focus_handle,
6657 cx,
6658 ),
6659 }
6660 }
6661
6662 fn render_permission_buttons_with_dropdown(
6663 &self,
6664 is_first: bool,
6665 choices: &[PermissionOptionChoice],
6666 patterns: Option<(&[PermissionPattern], &str)>,
6667 entry_ix: usize,
6668 tool_call_id: acp::ToolCallId,
6669 focus_handle: &FocusHandle,
6670 cx: &Context<Self>,
6671 ) -> Div {
6672 let selection = self.permission_selections.get(&tool_call_id);
6673
6674 let selected_index = selection
6675 .and_then(|s| s.choice_index())
6676 .unwrap_or_else(|| choices.len().saturating_sub(1));
6677
6678 let dropdown_label: SharedString =
6679 if matches!(selection, Some(PermissionSelection::SelectedPatterns(_))) {
6680 "Always for selected commands".into()
6681 } else {
6682 choices
6683 .get(selected_index)
6684 .or(choices.last())
6685 .map(|choice| choice.label())
6686 .unwrap_or_else(|| "Only this time".into())
6687 };
6688
6689 let dropdown = if let Some((pattern_list, tool_name)) = patterns {
6690 self.render_permission_granularity_dropdown_with_patterns(
6691 choices,
6692 pattern_list,
6693 tool_name,
6694 dropdown_label,
6695 entry_ix,
6696 tool_call_id.clone(),
6697 is_first,
6698 cx,
6699 )
6700 } else {
6701 self.render_permission_granularity_dropdown(
6702 choices,
6703 dropdown_label,
6704 entry_ix,
6705 tool_call_id.clone(),
6706 selected_index,
6707 is_first,
6708 cx,
6709 )
6710 };
6711
6712 h_flex()
6713 .w_full()
6714 .p_1()
6715 .gap_2()
6716 .justify_between()
6717 .border_t_1()
6718 .border_color(self.tool_card_border_color(cx))
6719 .child(
6720 h_flex()
6721 .gap_0p5()
6722 .child(
6723 Button::new(("allow-btn", entry_ix), "Allow")
6724 .start_icon(
6725 Icon::new(IconName::Check)
6726 .size(IconSize::XSmall)
6727 .color(Color::Success),
6728 )
6729 .label_size(LabelSize::Small)
6730 .when(is_first, |this| {
6731 this.key_binding(
6732 KeyBinding::for_action_in(
6733 &AllowOnce as &dyn Action,
6734 focus_handle,
6735 cx,
6736 )
6737 .map(|kb| kb.size(rems_from_px(12.))),
6738 )
6739 })
6740 .on_click(cx.listener({
6741 move |this, _, window, cx| {
6742 this.authorize_pending_with_granularity(true, window, cx);
6743 }
6744 })),
6745 )
6746 .child(
6747 Button::new(("deny-btn", entry_ix), "Deny")
6748 .start_icon(
6749 Icon::new(IconName::Close)
6750 .size(IconSize::XSmall)
6751 .color(Color::Error),
6752 )
6753 .label_size(LabelSize::Small)
6754 .when(is_first, |this| {
6755 this.key_binding(
6756 KeyBinding::for_action_in(
6757 &RejectOnce as &dyn Action,
6758 focus_handle,
6759 cx,
6760 )
6761 .map(|kb| kb.size(rems_from_px(12.))),
6762 )
6763 })
6764 .on_click(cx.listener({
6765 move |this, _, window, cx| {
6766 this.authorize_pending_with_granularity(false, window, cx);
6767 }
6768 })),
6769 ),
6770 )
6771 .child(dropdown)
6772 }
6773
6774 fn render_permission_granularity_dropdown(
6775 &self,
6776 choices: &[PermissionOptionChoice],
6777 current_label: SharedString,
6778 entry_ix: usize,
6779 tool_call_id: acp::ToolCallId,
6780 selected_index: usize,
6781 is_first: bool,
6782 cx: &Context<Self>,
6783 ) -> AnyElement {
6784 let menu_options: Vec<(usize, SharedString)> = choices
6785 .iter()
6786 .enumerate()
6787 .map(|(i, choice)| (i, choice.label()))
6788 .collect();
6789
6790 let permission_dropdown_handle = self.permission_dropdown_handle.clone();
6791
6792 PopoverMenu::new(("permission-granularity", entry_ix))
6793 .with_handle(permission_dropdown_handle)
6794 .trigger(
6795 Button::new(("granularity-trigger", entry_ix), current_label)
6796 .end_icon(
6797 Icon::new(IconName::ChevronDown)
6798 .size(IconSize::XSmall)
6799 .color(Color::Muted),
6800 )
6801 .label_size(LabelSize::Small)
6802 .when(is_first, |this| {
6803 this.key_binding(
6804 KeyBinding::for_action_in(
6805 &crate::OpenPermissionDropdown as &dyn Action,
6806 &self.focus_handle(cx),
6807 cx,
6808 )
6809 .map(|kb| kb.size(rems_from_px(12.))),
6810 )
6811 }),
6812 )
6813 .menu(move |window, cx| {
6814 let tool_call_id = tool_call_id.clone();
6815 let options = menu_options.clone();
6816
6817 Some(ContextMenu::build(window, cx, move |mut menu, _, _| {
6818 for (index, display_name) in options.iter() {
6819 let display_name = display_name.clone();
6820 let index = *index;
6821 let tool_call_id_for_entry = tool_call_id.clone();
6822 let is_selected = index == selected_index;
6823 menu = menu.toggleable_entry(
6824 display_name,
6825 is_selected,
6826 IconPosition::End,
6827 None,
6828 move |window, cx| {
6829 window.dispatch_action(
6830 SelectPermissionGranularity {
6831 tool_call_id: tool_call_id_for_entry.0.to_string(),
6832 index,
6833 }
6834 .boxed_clone(),
6835 cx,
6836 );
6837 },
6838 );
6839 }
6840
6841 menu
6842 }))
6843 })
6844 .into_any_element()
6845 }
6846
6847 fn render_permission_granularity_dropdown_with_patterns(
6848 &self,
6849 choices: &[PermissionOptionChoice],
6850 patterns: &[PermissionPattern],
6851 _tool_name: &str,
6852 current_label: SharedString,
6853 entry_ix: usize,
6854 tool_call_id: acp::ToolCallId,
6855 is_first: bool,
6856 cx: &Context<Self>,
6857 ) -> AnyElement {
6858 let default_choice_index = choices.len().saturating_sub(1);
6859 let menu_options: Vec<(usize, SharedString)> = choices
6860 .iter()
6861 .enumerate()
6862 .map(|(i, choice)| (i, choice.label()))
6863 .collect();
6864
6865 let pattern_options: Vec<(usize, SharedString)> = patterns
6866 .iter()
6867 .enumerate()
6868 .map(|(i, cp)| {
6869 (
6870 i,
6871 SharedString::from(format!("Always for `{}` commands", cp.display_name)),
6872 )
6873 })
6874 .collect();
6875
6876 let pattern_count = patterns.len();
6877 let permission_dropdown_handle = self.permission_dropdown_handle.clone();
6878 let view = cx.entity().downgrade();
6879
6880 PopoverMenu::new(("permission-granularity", entry_ix))
6881 .with_handle(permission_dropdown_handle.clone())
6882 .anchor(Corner::TopRight)
6883 .attach(Corner::BottomRight)
6884 .trigger(
6885 Button::new(("granularity-trigger", entry_ix), current_label)
6886 .end_icon(
6887 Icon::new(IconName::ChevronDown)
6888 .size(IconSize::XSmall)
6889 .color(Color::Muted),
6890 )
6891 .label_size(LabelSize::Small)
6892 .when(is_first, |this| {
6893 this.key_binding(
6894 KeyBinding::for_action_in(
6895 &crate::OpenPermissionDropdown as &dyn Action,
6896 &self.focus_handle(cx),
6897 cx,
6898 )
6899 .map(|kb| kb.size(rems_from_px(12.))),
6900 )
6901 }),
6902 )
6903 .menu(move |window, cx| {
6904 let tool_call_id = tool_call_id.clone();
6905 let options = menu_options.clone();
6906 let patterns = pattern_options.clone();
6907 let view = view.clone();
6908 let dropdown_handle = permission_dropdown_handle.clone();
6909
6910 Some(ContextMenu::build_persistent(
6911 window,
6912 cx,
6913 move |menu, _window, cx| {
6914 let mut menu = menu;
6915
6916 // Read fresh selection state from the view on each rebuild.
6917 let selection: Option<PermissionSelection> = view.upgrade().and_then(|v| {
6918 let view = v.read(cx);
6919 view.permission_selections.get(&tool_call_id).cloned()
6920 });
6921
6922 let is_pattern_mode =
6923 matches!(selection, Some(PermissionSelection::SelectedPatterns(_)));
6924
6925 // Granularity choices: "Always for terminal", "Only this time"
6926 for (index, display_name) in options.iter() {
6927 let display_name = display_name.clone();
6928 let index = *index;
6929 let tool_call_id_for_entry = tool_call_id.clone();
6930 let is_selected = !is_pattern_mode
6931 && selection
6932 .as_ref()
6933 .and_then(|s| s.choice_index())
6934 .map_or(index == default_choice_index, |ci| ci == index);
6935
6936 let view = view.clone();
6937 menu = menu.toggleable_entry(
6938 display_name,
6939 is_selected,
6940 IconPosition::End,
6941 None,
6942 move |_window, cx| {
6943 view.update(cx, |this, cx| {
6944 this.permission_selections.insert(
6945 tool_call_id_for_entry.clone(),
6946 PermissionSelection::Choice(index),
6947 );
6948 cx.notify();
6949 })
6950 .log_err();
6951 },
6952 );
6953 }
6954
6955 menu = menu.separator().header("Select Options…");
6956
6957 for (pattern_index, label) in patterns.iter() {
6958 let label = label.clone();
6959 let pattern_index = *pattern_index;
6960 let tool_call_id_for_pattern = tool_call_id.clone();
6961 let is_checked = selection
6962 .as_ref()
6963 .is_some_and(|s| s.is_pattern_checked(pattern_index));
6964
6965 let view = view.clone();
6966 menu = menu.toggleable_entry(
6967 label,
6968 is_checked,
6969 IconPosition::End,
6970 None,
6971 move |_window, cx| {
6972 view.update(cx, |this, cx| {
6973 let selection = this
6974 .permission_selections
6975 .get_mut(&tool_call_id_for_pattern);
6976
6977 match selection {
6978 Some(PermissionSelection::SelectedPatterns(_)) => {
6979 // Already in pattern mode — toggle.
6980 this.permission_selections
6981 .get_mut(&tool_call_id_for_pattern)
6982 .expect("just matched above")
6983 .toggle_pattern(pattern_index);
6984 }
6985 _ => {
6986 // First click: activate pattern mode
6987 // with all patterns checked.
6988 this.permission_selections.insert(
6989 tool_call_id_for_pattern.clone(),
6990 PermissionSelection::SelectedPatterns(
6991 (0..pattern_count).collect(),
6992 ),
6993 );
6994 }
6995 }
6996 cx.notify();
6997 })
6998 .log_err();
6999 },
7000 );
7001 }
7002
7003 let any_patterns_checked = selection
7004 .as_ref()
7005 .is_some_and(|s| s.has_any_checked_patterns());
7006 let dropdown_handle = dropdown_handle.clone();
7007 menu = menu.custom_row(move |_window, _cx| {
7008 div()
7009 .py_1()
7010 .w_full()
7011 .child(
7012 Button::new("apply-patterns", "Apply")
7013 .full_width()
7014 .style(ButtonStyle::Outlined)
7015 .label_size(LabelSize::Small)
7016 .disabled(!any_patterns_checked)
7017 .on_click({
7018 let dropdown_handle = dropdown_handle.clone();
7019 move |_event, _window, cx| {
7020 dropdown_handle.hide(cx);
7021 }
7022 }),
7023 )
7024 .into_any_element()
7025 });
7026
7027 menu
7028 },
7029 ))
7030 })
7031 .into_any_element()
7032 }
7033
7034 fn render_permission_buttons_flat(
7035 &self,
7036 session_id: acp::SessionId,
7037 is_first: bool,
7038 options: &[acp::PermissionOption],
7039 entry_ix: usize,
7040 tool_call_id: acp::ToolCallId,
7041 focus_handle: &FocusHandle,
7042 cx: &Context<Self>,
7043 ) -> Div {
7044 let mut seen_kinds: ArrayVec<acp::PermissionOptionKind, 3, u8> = ArrayVec::new();
7045
7046 div()
7047 .p_1()
7048 .border_t_1()
7049 .border_color(self.tool_card_border_color(cx))
7050 .w_full()
7051 .v_flex()
7052 .gap_0p5()
7053 .children(options.iter().map(move |option| {
7054 let option_id = SharedString::from(option.option_id.0.clone());
7055 Button::new((option_id, entry_ix), option.name.clone())
7056 .map(|this| {
7057 let (icon, action) = match option.kind {
7058 acp::PermissionOptionKind::AllowOnce => (
7059 Icon::new(IconName::Check)
7060 .size(IconSize::XSmall)
7061 .color(Color::Success),
7062 Some(&AllowOnce as &dyn Action),
7063 ),
7064 acp::PermissionOptionKind::AllowAlways => (
7065 Icon::new(IconName::CheckDouble)
7066 .size(IconSize::XSmall)
7067 .color(Color::Success),
7068 Some(&AllowAlways as &dyn Action),
7069 ),
7070 acp::PermissionOptionKind::RejectOnce => (
7071 Icon::new(IconName::Close)
7072 .size(IconSize::XSmall)
7073 .color(Color::Error),
7074 Some(&RejectOnce as &dyn Action),
7075 ),
7076 acp::PermissionOptionKind::RejectAlways | _ => (
7077 Icon::new(IconName::Close)
7078 .size(IconSize::XSmall)
7079 .color(Color::Error),
7080 None,
7081 ),
7082 };
7083
7084 let this = this.start_icon(icon);
7085
7086 let Some(action) = action else {
7087 return this;
7088 };
7089
7090 if !is_first || seen_kinds.contains(&option.kind) {
7091 return this;
7092 }
7093
7094 seen_kinds.push(option.kind).unwrap();
7095
7096 this.key_binding(
7097 KeyBinding::for_action_in(action, focus_handle, cx)
7098 .map(|kb| kb.size(rems_from_px(12.))),
7099 )
7100 })
7101 .label_size(LabelSize::Small)
7102 .on_click(cx.listener({
7103 let session_id = session_id.clone();
7104 let tool_call_id = tool_call_id.clone();
7105 let option_id = option.option_id.clone();
7106 let option_kind = option.kind;
7107 move |this, _, window, cx| {
7108 this.authorize_tool_call(
7109 session_id.clone(),
7110 tool_call_id.clone(),
7111 SelectedPermissionOutcome::new(option_id.clone(), option_kind),
7112 window,
7113 cx,
7114 );
7115 }
7116 }))
7117 }))
7118 }
7119
7120 fn render_diff_loading(&self, cx: &Context<Self>) -> AnyElement {
7121 let bar = |n: u64, width_class: &str| {
7122 let bg_color = cx.theme().colors().element_active;
7123 let base = h_flex().h_1().rounded_full();
7124
7125 let modified = match width_class {
7126 "w_4_5" => base.w_3_4(),
7127 "w_1_4" => base.w_1_4(),
7128 "w_2_4" => base.w_2_4(),
7129 "w_3_5" => base.w_3_5(),
7130 "w_2_5" => base.w_2_5(),
7131 _ => base.w_1_2(),
7132 };
7133
7134 modified.with_animation(
7135 ElementId::Integer(n),
7136 Animation::new(Duration::from_secs(2)).repeat(),
7137 move |tab, delta| {
7138 let delta = (delta - 0.15 * n as f32) / 0.7;
7139 let delta = 1.0 - (0.5 - delta).abs() * 2.;
7140 let delta = ease_in_out(delta.clamp(0., 1.));
7141 let delta = 0.1 + 0.9 * delta;
7142
7143 tab.bg(bg_color.opacity(delta))
7144 },
7145 )
7146 };
7147
7148 v_flex()
7149 .p_3()
7150 .gap_1()
7151 .rounded_b_md()
7152 .bg(cx.theme().colors().editor_background)
7153 .child(bar(0, "w_4_5"))
7154 .child(bar(1, "w_1_4"))
7155 .child(bar(2, "w_2_4"))
7156 .child(bar(3, "w_3_5"))
7157 .child(bar(4, "w_2_5"))
7158 .into_any_element()
7159 }
7160
7161 fn render_tool_call_label(
7162 &self,
7163 entry_ix: usize,
7164 tool_call: &ToolCall,
7165 is_edit: bool,
7166 has_failed: bool,
7167 has_revealed_diff: bool,
7168 use_card_layout: bool,
7169 window: &Window,
7170 cx: &Context<Self>,
7171 ) -> Div {
7172 let has_location = tool_call.locations.len() == 1;
7173 let is_file = tool_call.kind == acp::ToolKind::Edit && has_location;
7174 let is_subagent_tool_call = tool_call.is_subagent();
7175
7176 let file_icon = if has_location {
7177 FileIcons::get_icon(&tool_call.locations[0].path, cx)
7178 .map(|from_path| Icon::from_path(from_path).color(Color::Muted))
7179 .unwrap_or(Icon::new(IconName::ToolPencil).color(Color::Muted))
7180 } else {
7181 Icon::new(IconName::ToolPencil).color(Color::Muted)
7182 };
7183
7184 let tool_icon = if is_file && has_failed && has_revealed_diff {
7185 div()
7186 .id(entry_ix)
7187 .tooltip(Tooltip::text("Interrupted Edit"))
7188 .child(DecoratedIcon::new(
7189 file_icon,
7190 Some(
7191 IconDecoration::new(
7192 IconDecorationKind::Triangle,
7193 self.tool_card_header_bg(cx),
7194 cx,
7195 )
7196 .color(cx.theme().status().warning)
7197 .position(gpui::Point {
7198 x: px(-2.),
7199 y: px(-2.),
7200 }),
7201 ),
7202 ))
7203 .into_any_element()
7204 } else if is_file {
7205 div().child(file_icon).into_any_element()
7206 } else if is_subagent_tool_call {
7207 Icon::new(self.agent_icon)
7208 .size(IconSize::Small)
7209 .color(Color::Muted)
7210 .into_any_element()
7211 } else {
7212 Icon::new(match tool_call.kind {
7213 acp::ToolKind::Read => IconName::ToolSearch,
7214 acp::ToolKind::Edit => IconName::ToolPencil,
7215 acp::ToolKind::Delete => IconName::ToolDeleteFile,
7216 acp::ToolKind::Move => IconName::ArrowRightLeft,
7217 acp::ToolKind::Search => IconName::ToolSearch,
7218 acp::ToolKind::Execute => IconName::ToolTerminal,
7219 acp::ToolKind::Think => IconName::ToolThink,
7220 acp::ToolKind::Fetch => IconName::ToolWeb,
7221 acp::ToolKind::SwitchMode => IconName::ArrowRightLeft,
7222 acp::ToolKind::Other | _ => IconName::ToolHammer,
7223 })
7224 .size(IconSize::Small)
7225 .color(Color::Muted)
7226 .into_any_element()
7227 };
7228
7229 let gradient_overlay = {
7230 div()
7231 .absolute()
7232 .top_0()
7233 .right_0()
7234 .w_12()
7235 .h_full()
7236 .map(|this| {
7237 if use_card_layout {
7238 this.bg(linear_gradient(
7239 90.,
7240 linear_color_stop(self.tool_card_header_bg(cx), 1.),
7241 linear_color_stop(self.tool_card_header_bg(cx).opacity(0.2), 0.),
7242 ))
7243 } else {
7244 this.bg(linear_gradient(
7245 90.,
7246 linear_color_stop(cx.theme().colors().panel_background, 1.),
7247 linear_color_stop(
7248 cx.theme().colors().panel_background.opacity(0.2),
7249 0.,
7250 ),
7251 ))
7252 }
7253 })
7254 };
7255
7256 h_flex()
7257 .relative()
7258 .w_full()
7259 .h(window.line_height() - px(2.))
7260 .text_size(self.tool_name_font_size())
7261 .gap_1p5()
7262 .when(has_location || use_card_layout, |this| this.px_1())
7263 .when(has_location, |this| {
7264 this.cursor(CursorStyle::PointingHand)
7265 .rounded(rems_from_px(3.)) // Concentric border radius
7266 .hover(|s| s.bg(cx.theme().colors().element_hover.opacity(0.5)))
7267 })
7268 .overflow_hidden()
7269 .child(tool_icon)
7270 .child(if has_location {
7271 h_flex()
7272 .id(("open-tool-call-location", entry_ix))
7273 .w_full()
7274 .map(|this| {
7275 if use_card_layout {
7276 this.text_color(cx.theme().colors().text)
7277 } else {
7278 this.text_color(cx.theme().colors().text_muted)
7279 }
7280 })
7281 .child(
7282 self.render_markdown(
7283 tool_call.label.clone(),
7284 MarkdownStyle {
7285 prevent_mouse_interaction: true,
7286 ..MarkdownStyle::themed(MarkdownFont::Agent, window, cx)
7287 .with_muted_text(cx)
7288 },
7289 ),
7290 )
7291 .tooltip(Tooltip::text("Go to File"))
7292 .on_click(cx.listener(move |this, _, window, cx| {
7293 this.open_tool_call_location(entry_ix, 0, window, cx);
7294 }))
7295 .into_any_element()
7296 } else {
7297 h_flex()
7298 .w_full()
7299 .child(self.render_markdown(
7300 tool_call.label.clone(),
7301 MarkdownStyle::themed(MarkdownFont::Agent, window, cx).with_muted_text(cx),
7302 ))
7303 .into_any()
7304 })
7305 .when(!is_edit, |this| this.child(gradient_overlay))
7306 }
7307
7308 fn open_tool_call_location(
7309 &self,
7310 entry_ix: usize,
7311 location_ix: usize,
7312 window: &mut Window,
7313 cx: &mut Context<Self>,
7314 ) -> Option<()> {
7315 let (tool_call_location, agent_location) = self
7316 .thread
7317 .read(cx)
7318 .entries()
7319 .get(entry_ix)?
7320 .location(location_ix)?;
7321
7322 let project_path = self
7323 .project
7324 .upgrade()?
7325 .read(cx)
7326 .find_project_path(&tool_call_location.path, cx)?;
7327
7328 let open_task = self
7329 .workspace
7330 .update(cx, |workspace, cx| {
7331 workspace.open_path(project_path, None, true, window, cx)
7332 })
7333 .log_err()?;
7334 window
7335 .spawn(cx, async move |cx| {
7336 let item = open_task.await?;
7337
7338 let Some(active_editor) = item.downcast::<Editor>() else {
7339 return anyhow::Ok(());
7340 };
7341
7342 active_editor.update_in(cx, |editor, window, cx| {
7343 let snapshot = editor.buffer().read(cx).snapshot(cx);
7344 if snapshot.as_singleton().is_some()
7345 && let Some(anchor) = snapshot.anchor_in_excerpt(agent_location.position)
7346 {
7347 editor.change_selections(Default::default(), window, cx, |selections| {
7348 selections.select_anchor_ranges([anchor..anchor]);
7349 })
7350 } else {
7351 let row = tool_call_location.line.unwrap_or_default();
7352 editor.change_selections(Default::default(), window, cx, |selections| {
7353 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
7354 })
7355 }
7356 })?;
7357
7358 anyhow::Ok(())
7359 })
7360 .detach_and_log_err(cx);
7361
7362 None
7363 }
7364
7365 fn render_tool_call_content(
7366 &self,
7367 session_id: &acp::SessionId,
7368 entry_ix: usize,
7369 content: &ToolCallContent,
7370 context_ix: usize,
7371 tool_call: &ToolCall,
7372 card_layout: bool,
7373 is_image_tool_call: bool,
7374 has_failed: bool,
7375 focus_handle: &FocusHandle,
7376 window: &Window,
7377 cx: &Context<Self>,
7378 ) -> AnyElement {
7379 match content {
7380 ToolCallContent::ContentBlock(content) => {
7381 if let Some(resource_link) = content.resource_link() {
7382 self.render_resource_link(resource_link, cx)
7383 } else if let Some(markdown) = content.markdown() {
7384 self.render_markdown_output(
7385 markdown.clone(),
7386 tool_call.id.clone(),
7387 context_ix,
7388 card_layout,
7389 window,
7390 cx,
7391 )
7392 } else if let Some(image) = content.image() {
7393 let location = tool_call.locations.first().cloned();
7394 self.render_image_output(
7395 entry_ix,
7396 image.clone(),
7397 location,
7398 card_layout,
7399 is_image_tool_call,
7400 cx,
7401 )
7402 } else {
7403 Empty.into_any_element()
7404 }
7405 }
7406 ToolCallContent::Diff(diff) => {
7407 self.render_diff_editor(entry_ix, diff, tool_call, has_failed, cx)
7408 }
7409 ToolCallContent::Terminal(terminal) => self.render_terminal_tool_call(
7410 session_id,
7411 entry_ix,
7412 terminal,
7413 tool_call,
7414 focus_handle,
7415 false,
7416 window,
7417 cx,
7418 ),
7419 }
7420 }
7421
7422 fn render_resource_link(
7423 &self,
7424 resource_link: &acp::ResourceLink,
7425 cx: &Context<Self>,
7426 ) -> AnyElement {
7427 let uri: SharedString = resource_link.uri.clone().into();
7428 let is_file = resource_link.uri.strip_prefix("file://");
7429
7430 let Some(project) = self.project.upgrade() else {
7431 return Empty.into_any_element();
7432 };
7433
7434 let label: SharedString = if let Some(abs_path) = is_file {
7435 if let Some(project_path) = project
7436 .read(cx)
7437 .project_path_for_absolute_path(&Path::new(abs_path), cx)
7438 && let Some(worktree) = project
7439 .read(cx)
7440 .worktree_for_id(project_path.worktree_id, cx)
7441 {
7442 worktree
7443 .read(cx)
7444 .full_path(&project_path.path)
7445 .to_string_lossy()
7446 .to_string()
7447 .into()
7448 } else {
7449 abs_path.to_string().into()
7450 }
7451 } else {
7452 uri.clone()
7453 };
7454
7455 let button_id = SharedString::from(format!("item-{}", uri));
7456
7457 div()
7458 .ml(rems(0.4))
7459 .pl_2p5()
7460 .border_l_1()
7461 .border_color(self.tool_card_border_color(cx))
7462 .overflow_hidden()
7463 .child(
7464 Button::new(button_id, label)
7465 .label_size(LabelSize::Small)
7466 .color(Color::Muted)
7467 .truncate(true)
7468 .when(is_file.is_none(), |this| {
7469 this.end_icon(
7470 Icon::new(IconName::ArrowUpRight)
7471 .size(IconSize::XSmall)
7472 .color(Color::Muted),
7473 )
7474 })
7475 .on_click(cx.listener({
7476 let workspace = self.workspace.clone();
7477 move |_, _, window, cx: &mut Context<Self>| {
7478 open_link(uri.clone(), &workspace, window, cx);
7479 }
7480 })),
7481 )
7482 .into_any_element()
7483 }
7484
7485 fn render_diff_editor(
7486 &self,
7487 entry_ix: usize,
7488 diff: &Entity<acp_thread::Diff>,
7489 tool_call: &ToolCall,
7490 has_failed: bool,
7491 cx: &Context<Self>,
7492 ) -> AnyElement {
7493 let tool_progress = matches!(
7494 &tool_call.status,
7495 ToolCallStatus::InProgress | ToolCallStatus::Pending
7496 );
7497
7498 let revealed_diff_editor = if let Some(entry) =
7499 self.entry_view_state.read(cx).entry(entry_ix)
7500 && let Some(editor) = entry.editor_for_diff(diff)
7501 && diff.read(cx).has_revealed_range(cx)
7502 {
7503 Some(editor)
7504 } else {
7505 None
7506 };
7507
7508 let show_top_border = !has_failed || revealed_diff_editor.is_some();
7509
7510 v_flex()
7511 .h_full()
7512 .when(show_top_border, |this| {
7513 this.border_t_1()
7514 .when(has_failed, |this| this.border_dashed())
7515 .border_color(self.tool_card_border_color(cx))
7516 })
7517 .child(if let Some(editor) = revealed_diff_editor {
7518 editor.into_any_element()
7519 } else if tool_progress && self.as_native_connection(cx).is_some() {
7520 self.render_diff_loading(cx)
7521 } else {
7522 Empty.into_any()
7523 })
7524 .into_any()
7525 }
7526
7527 fn render_markdown_output(
7528 &self,
7529 markdown: Entity<Markdown>,
7530 tool_call_id: acp::ToolCallId,
7531 context_ix: usize,
7532 card_layout: bool,
7533 window: &Window,
7534 cx: &Context<Self>,
7535 ) -> AnyElement {
7536 let button_id = SharedString::from(format!("tool_output-{:?}", tool_call_id));
7537
7538 v_flex()
7539 .gap_2()
7540 .map(|this| {
7541 if card_layout {
7542 this.p_2().when(context_ix > 0, |this| {
7543 this.border_t_1()
7544 .border_color(self.tool_card_border_color(cx))
7545 })
7546 } else {
7547 this.ml(rems(0.4))
7548 .px_3p5()
7549 .border_l_1()
7550 .border_color(self.tool_card_border_color(cx))
7551 }
7552 })
7553 .text_xs()
7554 .text_color(cx.theme().colors().text_muted)
7555 .child(self.render_markdown(
7556 markdown,
7557 MarkdownStyle::themed(MarkdownFont::Agent, window, cx),
7558 ))
7559 .when(!card_layout, |this| {
7560 this.child(
7561 IconButton::new(button_id, IconName::ChevronUp)
7562 .full_width()
7563 .style(ButtonStyle::Outlined)
7564 .icon_color(Color::Muted)
7565 .on_click(cx.listener({
7566 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
7567 this.expanded_tool_calls.remove(&tool_call_id);
7568 cx.notify();
7569 }
7570 })),
7571 )
7572 })
7573 .into_any_element()
7574 }
7575
7576 fn render_image_output(
7577 &self,
7578 entry_ix: usize,
7579 image: Arc<gpui::Image>,
7580 location: Option<acp::ToolCallLocation>,
7581 card_layout: bool,
7582 show_dimensions: bool,
7583 cx: &Context<Self>,
7584 ) -> AnyElement {
7585 let dimensions_label = if show_dimensions {
7586 let format_name = match image.format() {
7587 gpui::ImageFormat::Png => "PNG",
7588 gpui::ImageFormat::Jpeg => "JPEG",
7589 gpui::ImageFormat::Webp => "WebP",
7590 gpui::ImageFormat::Gif => "GIF",
7591 gpui::ImageFormat::Svg => "SVG",
7592 gpui::ImageFormat::Bmp => "BMP",
7593 gpui::ImageFormat::Tiff => "TIFF",
7594 gpui::ImageFormat::Ico => "ICO",
7595 };
7596 let dimensions = image::ImageReader::new(std::io::Cursor::new(image.bytes()))
7597 .with_guessed_format()
7598 .ok()
7599 .and_then(|reader| reader.into_dimensions().ok());
7600 dimensions.map(|(w, h)| format!("{}×{} {}", w, h, format_name))
7601 } else {
7602 None
7603 };
7604
7605 v_flex()
7606 .gap_2()
7607 .map(|this| {
7608 if card_layout {
7609 this
7610 } else {
7611 this.ml(rems(0.4))
7612 .px_3p5()
7613 .border_l_1()
7614 .border_color(self.tool_card_border_color(cx))
7615 }
7616 })
7617 .when(dimensions_label.is_some() || location.is_some(), |this| {
7618 this.child(
7619 h_flex()
7620 .w_full()
7621 .justify_between()
7622 .items_center()
7623 .children(dimensions_label.map(|label| {
7624 Label::new(label)
7625 .size(LabelSize::XSmall)
7626 .color(Color::Muted)
7627 .buffer_font(cx)
7628 }))
7629 .when_some(location, |this, _loc| {
7630 this.child(
7631 Button::new(("go-to-file", entry_ix), "Go to File")
7632 .label_size(LabelSize::Small)
7633 .on_click(cx.listener(move |this, _, window, cx| {
7634 this.open_tool_call_location(entry_ix, 0, window, cx);
7635 })),
7636 )
7637 }),
7638 )
7639 })
7640 .child(
7641 img(image)
7642 .max_w_96()
7643 .max_h_96()
7644 .object_fit(ObjectFit::ScaleDown),
7645 )
7646 .into_any_element()
7647 }
7648
7649 fn render_subagent_tool_call(
7650 &self,
7651 active_session_id: &acp::SessionId,
7652 entry_ix: usize,
7653 tool_call: &ToolCall,
7654 subagent_session_id: Option<acp::SessionId>,
7655 focus_handle: &FocusHandle,
7656 window: &Window,
7657 cx: &Context<Self>,
7658 ) -> Div {
7659 let subagent_thread_view = subagent_session_id.and_then(|id| {
7660 self.server_view
7661 .upgrade()
7662 .and_then(|server_view| server_view.read(cx).as_connected())
7663 .and_then(|connected| connected.threads.get(&id))
7664 });
7665
7666 let content = self.render_subagent_card(
7667 active_session_id,
7668 entry_ix,
7669 subagent_thread_view,
7670 tool_call,
7671 focus_handle,
7672 window,
7673 cx,
7674 );
7675
7676 v_flex().mx_5().my_1p5().gap_3().child(content)
7677 }
7678
7679 fn render_subagent_card(
7680 &self,
7681 active_session_id: &acp::SessionId,
7682 entry_ix: usize,
7683 thread_view: Option<&Entity<ThreadView>>,
7684 tool_call: &ToolCall,
7685 focus_handle: &FocusHandle,
7686 window: &Window,
7687 cx: &Context<Self>,
7688 ) -> AnyElement {
7689 let thread = thread_view
7690 .as_ref()
7691 .map(|view| view.read(cx).thread.clone());
7692 let subagent_session_id = thread
7693 .as_ref()
7694 .map(|thread| thread.read(cx).session_id().clone());
7695 let action_log = thread.as_ref().map(|thread| thread.read(cx).action_log());
7696 let changed_buffers = action_log
7697 .map(|log| log.read(cx).changed_buffers(cx))
7698 .unwrap_or_default();
7699
7700 let is_pending_tool_call = thread
7701 .as_ref()
7702 .and_then(|thread| {
7703 self.conversation
7704 .read(cx)
7705 .pending_tool_call(thread.read(cx).session_id(), cx)
7706 })
7707 .is_some();
7708
7709 let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
7710 let files_changed = changed_buffers.len();
7711 let diff_stats = DiffStats::all_files(&changed_buffers, cx);
7712
7713 let is_running = matches!(
7714 tool_call.status,
7715 ToolCallStatus::Pending
7716 | ToolCallStatus::InProgress
7717 | ToolCallStatus::WaitingForConfirmation { .. }
7718 );
7719
7720 let is_failed = matches!(
7721 tool_call.status,
7722 ToolCallStatus::Failed | ToolCallStatus::Rejected
7723 );
7724
7725 let is_cancelled = matches!(tool_call.status, ToolCallStatus::Canceled)
7726 || tool_call.content.iter().any(|c| match c {
7727 ToolCallContent::ContentBlock(ContentBlock::Markdown { markdown }) => {
7728 markdown.read(cx).source() == "User canceled"
7729 }
7730 _ => false,
7731 });
7732
7733 let thread_title = thread
7734 .as_ref()
7735 .and_then(|t| t.read(cx).title())
7736 .filter(|t| !t.is_empty());
7737 let tool_call_label = tool_call.label.read(cx).source().to_string();
7738 let has_tool_call_label = !tool_call_label.is_empty();
7739
7740 let has_title = thread_title.is_some() || has_tool_call_label;
7741 let has_no_title_or_canceled = !has_title || is_failed || is_cancelled;
7742
7743 let title: SharedString = if let Some(thread_title) = thread_title {
7744 thread_title
7745 } else if !tool_call_label.is_empty() {
7746 tool_call_label.into()
7747 } else if is_cancelled {
7748 "Subagent Canceled".into()
7749 } else if is_failed {
7750 "Subagent Failed".into()
7751 } else {
7752 "Spawning Agent…".into()
7753 };
7754
7755 let card_header_id = format!("subagent-header-{}", entry_ix);
7756 let status_icon = format!("status-icon-{}", entry_ix);
7757 let diff_stat_id = format!("subagent-diff-{}", entry_ix);
7758
7759 let icon = h_flex().w_4().justify_center().child(if is_running {
7760 SpinnerLabel::new()
7761 .size(LabelSize::Small)
7762 .into_any_element()
7763 } else if is_cancelled {
7764 div()
7765 .id(status_icon)
7766 .child(
7767 Icon::new(IconName::Circle)
7768 .size(IconSize::Small)
7769 .color(Color::Custom(
7770 cx.theme().colors().icon_disabled.opacity(0.5),
7771 )),
7772 )
7773 .tooltip(Tooltip::text("Subagent Cancelled"))
7774 .into_any_element()
7775 } else if is_failed {
7776 div()
7777 .id(status_icon)
7778 .child(
7779 Icon::new(IconName::Close)
7780 .size(IconSize::Small)
7781 .color(Color::Error),
7782 )
7783 .tooltip(Tooltip::text("Subagent Failed"))
7784 .into_any_element()
7785 } else {
7786 Icon::new(IconName::Check)
7787 .size(IconSize::Small)
7788 .color(Color::Success)
7789 .into_any_element()
7790 });
7791
7792 let has_expandable_content = thread
7793 .as_ref()
7794 .map_or(false, |thread| !thread.read(cx).entries().is_empty());
7795
7796 let tooltip_meta_description = if is_expanded {
7797 "Click to Collapse"
7798 } else {
7799 "Click to Preview"
7800 };
7801
7802 let error_message = self.subagent_error_message(&tool_call.status, tool_call, cx);
7803
7804 v_flex()
7805 .w_full()
7806 .rounded_md()
7807 .border_1()
7808 .when(has_no_title_or_canceled, |this| this.border_dashed())
7809 .border_color(self.tool_card_border_color(cx))
7810 .overflow_hidden()
7811 .child(
7812 h_flex()
7813 .group(&card_header_id)
7814 .h_8()
7815 .p_1()
7816 .w_full()
7817 .justify_between()
7818 .when(!has_no_title_or_canceled, |this| {
7819 this.bg(self.tool_card_header_bg(cx))
7820 })
7821 .child(
7822 h_flex()
7823 .id(format!("subagent-title-{}", entry_ix))
7824 .px_1()
7825 .min_w_0()
7826 .size_full()
7827 .gap_2()
7828 .justify_between()
7829 .rounded_sm()
7830 .overflow_hidden()
7831 .child(
7832 h_flex()
7833 .min_w_0()
7834 .w_full()
7835 .gap_1p5()
7836 .child(icon)
7837 .child(
7838 Label::new(title.to_string())
7839 .size(LabelSize::Custom(self.tool_name_font_size()))
7840 .truncate(),
7841 )
7842 .when(files_changed > 0, |this| {
7843 this.child(
7844 Label::new(format!(
7845 "— {} {} changed",
7846 files_changed,
7847 if files_changed == 1 { "file" } else { "files" }
7848 ))
7849 .size(LabelSize::Custom(self.tool_name_font_size()))
7850 .color(Color::Muted),
7851 )
7852 .child(
7853 DiffStat::new(
7854 diff_stat_id.clone(),
7855 diff_stats.lines_added as usize,
7856 diff_stats.lines_removed as usize,
7857 )
7858 .label_size(LabelSize::Custom(
7859 self.tool_name_font_size(),
7860 )),
7861 )
7862 }),
7863 )
7864 .when(!has_no_title_or_canceled && !is_pending_tool_call, |this| {
7865 this.tooltip(move |_, cx| {
7866 Tooltip::with_meta(
7867 title.to_string(),
7868 None,
7869 tooltip_meta_description,
7870 cx,
7871 )
7872 })
7873 })
7874 .when(has_expandable_content && !is_pending_tool_call, |this| {
7875 this.cursor_pointer()
7876 .hover(|s| s.bg(cx.theme().colors().element_hover))
7877 .child(
7878 div().visible_on_hover(card_header_id).child(
7879 Icon::new(if is_expanded {
7880 IconName::ChevronUp
7881 } else {
7882 IconName::ChevronDown
7883 })
7884 .color(Color::Muted)
7885 .size(IconSize::Small),
7886 ),
7887 )
7888 .on_click(cx.listener({
7889 let tool_call_id = tool_call.id.clone();
7890 move |this, _, _, cx| {
7891 if this.expanded_tool_calls.contains(&tool_call_id) {
7892 this.expanded_tool_calls.remove(&tool_call_id);
7893 } else {
7894 this.expanded_tool_calls
7895 .insert(tool_call_id.clone());
7896 }
7897 let expanded =
7898 this.expanded_tool_calls.contains(&tool_call_id);
7899 telemetry::event!("Subagent Toggled", expanded);
7900 cx.notify();
7901 }
7902 }))
7903 }),
7904 )
7905 .when(is_running && subagent_session_id.is_some(), |buttons| {
7906 buttons.child(
7907 IconButton::new(format!("stop-subagent-{}", entry_ix), IconName::Stop)
7908 .icon_size(IconSize::Small)
7909 .icon_color(Color::Error)
7910 .tooltip(Tooltip::text("Stop Subagent"))
7911 .when_some(
7912 thread_view
7913 .as_ref()
7914 .map(|view| view.read(cx).thread.clone()),
7915 |this, thread| {
7916 this.on_click(cx.listener(
7917 move |_this, _event, _window, cx| {
7918 telemetry::event!("Subagent Stopped");
7919 thread.update(cx, |thread, cx| {
7920 thread.cancel(cx).detach();
7921 });
7922 },
7923 ))
7924 },
7925 ),
7926 )
7927 }),
7928 )
7929 .when_some(thread_view, |this, thread_view| {
7930 let thread = &thread_view.read(cx).thread;
7931 let pending_tool_call = self
7932 .conversation
7933 .read(cx)
7934 .pending_tool_call(thread.read(cx).session_id(), cx);
7935
7936 let session_id = thread.read(cx).session_id().clone();
7937
7938 let fullscreen_toggle = h_flex()
7939 .id(entry_ix)
7940 .py_1()
7941 .w_full()
7942 .justify_center()
7943 .border_t_1()
7944 .when(is_failed, |this| this.border_dashed())
7945 .border_color(self.tool_card_border_color(cx))
7946 .cursor_pointer()
7947 .hover(|s| s.bg(cx.theme().colors().element_hover))
7948 .child(
7949 Icon::new(IconName::Maximize)
7950 .color(Color::Muted)
7951 .size(IconSize::Small),
7952 )
7953 .tooltip(Tooltip::text("Make Subagent Full Screen"))
7954 .on_click(cx.listener(move |this, _event, window, cx| {
7955 telemetry::event!("Subagent Maximized");
7956 this.server_view
7957 .update(cx, |this, cx| {
7958 this.navigate_to_session(session_id.clone(), window, cx);
7959 })
7960 .ok();
7961 }));
7962
7963 if is_running && let Some((_, subagent_tool_call_id, _)) = pending_tool_call {
7964 if let Some((entry_ix, tool_call)) =
7965 thread.read(cx).tool_call(&subagent_tool_call_id)
7966 {
7967 this.child(Divider::horizontal().color(DividerColor::Border))
7968 .child(thread_view.read(cx).render_any_tool_call(
7969 active_session_id,
7970 entry_ix,
7971 tool_call,
7972 focus_handle,
7973 true,
7974 window,
7975 cx,
7976 ))
7977 .child(fullscreen_toggle)
7978 } else {
7979 this
7980 }
7981 } else {
7982 this.when(is_expanded, |this| {
7983 this.child(self.render_subagent_expanded_content(
7984 thread_view,
7985 tool_call,
7986 window,
7987 cx,
7988 ))
7989 .when_some(error_message, |this, message| {
7990 this.child(
7991 Callout::new()
7992 .severity(Severity::Error)
7993 .icon(IconName::XCircle)
7994 .title(message),
7995 )
7996 })
7997 .child(fullscreen_toggle)
7998 })
7999 }
8000 })
8001 .into_any_element()
8002 }
8003
8004 fn render_subagent_expanded_content(
8005 &self,
8006 thread_view: &Entity<ThreadView>,
8007 tool_call: &ToolCall,
8008 window: &Window,
8009 cx: &Context<Self>,
8010 ) -> impl IntoElement {
8011 const MAX_PREVIEW_ENTRIES: usize = 8;
8012
8013 let subagent_view = thread_view.read(cx);
8014 let session_id = subagent_view.thread.read(cx).session_id().clone();
8015
8016 let is_canceled_or_failed = matches!(
8017 tool_call.status,
8018 ToolCallStatus::Canceled | ToolCallStatus::Failed | ToolCallStatus::Rejected
8019 );
8020
8021 let editor_bg = cx.theme().colors().editor_background;
8022 let overlay = {
8023 div()
8024 .absolute()
8025 .inset_0()
8026 .size_full()
8027 .bg(linear_gradient(
8028 180.,
8029 linear_color_stop(editor_bg.opacity(0.5), 0.),
8030 linear_color_stop(editor_bg.opacity(0.), 0.1),
8031 ))
8032 .block_mouse_except_scroll()
8033 };
8034
8035 let entries = subagent_view.thread.read(cx).entries();
8036 let total_entries = entries.len();
8037 let mut entry_range = if let Some(info) = tool_call.subagent_session_info.as_ref() {
8038 info.message_start_index
8039 ..info
8040 .message_end_index
8041 .map(|i| (i + 1).min(total_entries))
8042 .unwrap_or(total_entries)
8043 } else {
8044 0..total_entries
8045 };
8046 entry_range.start = entry_range
8047 .end
8048 .saturating_sub(MAX_PREVIEW_ENTRIES)
8049 .max(entry_range.start);
8050 let start_ix = entry_range.start;
8051
8052 let scroll_handle = self
8053 .subagent_scroll_handles
8054 .borrow_mut()
8055 .entry(session_id.clone())
8056 .or_default()
8057 .clone();
8058
8059 scroll_handle.scroll_to_bottom();
8060
8061 let rendered_entries: Vec<AnyElement> = entries
8062 .get(entry_range)
8063 .unwrap_or_default()
8064 .iter()
8065 .enumerate()
8066 .map(|(i, entry)| {
8067 let actual_ix = start_ix + i;
8068 subagent_view.render_entry(actual_ix, total_entries, entry, window, cx)
8069 })
8070 .collect();
8071
8072 v_flex()
8073 .w_full()
8074 .border_t_1()
8075 .when(is_canceled_or_failed, |this| this.border_dashed())
8076 .border_color(self.tool_card_border_color(cx))
8077 .overflow_hidden()
8078 .child(
8079 div()
8080 .pb_1()
8081 .min_h_0()
8082 .id(format!("subagent-entries-{}", session_id))
8083 .track_scroll(&scroll_handle)
8084 .children(rendered_entries),
8085 )
8086 .h_56()
8087 .child(overlay)
8088 .into_any_element()
8089 }
8090
8091 fn subagent_error_message(
8092 &self,
8093 status: &ToolCallStatus,
8094 tool_call: &ToolCall,
8095 cx: &App,
8096 ) -> Option<SharedString> {
8097 if matches!(status, ToolCallStatus::Failed) {
8098 tool_call.content.iter().find_map(|content| {
8099 if let ToolCallContent::ContentBlock(block) = content {
8100 if let acp_thread::ContentBlock::Markdown { markdown } = block {
8101 let source = markdown.read(cx).source().to_string();
8102 if !source.is_empty() {
8103 if source == "User canceled" {
8104 return None;
8105 } else {
8106 return Some(SharedString::from(source));
8107 }
8108 }
8109 }
8110 }
8111 None
8112 })
8113 } else {
8114 None
8115 }
8116 }
8117
8118 fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
8119 cx.theme()
8120 .colors()
8121 .element_background
8122 .blend(cx.theme().colors().editor_foreground.opacity(0.025))
8123 }
8124
8125 fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
8126 cx.theme().colors().border.opacity(0.8)
8127 }
8128
8129 fn tool_name_font_size(&self) -> Rems {
8130 rems_from_px(13.)
8131 }
8132
8133 pub(crate) fn render_thread_error(
8134 &mut self,
8135 window: &mut Window,
8136 cx: &mut Context<Self>,
8137 ) -> Option<Div> {
8138 let content = match self.thread_error.as_ref()? {
8139 ThreadError::Other { message, .. } => {
8140 self.render_any_thread_error(message.clone(), window, cx)
8141 }
8142 ThreadError::Refusal => self.render_refusal_error(cx),
8143 ThreadError::AuthenticationRequired(error) => {
8144 self.render_authentication_required_error(error.clone(), cx)
8145 }
8146 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
8147 ThreadError::RateLimitExceeded { provider } => self.render_error_callout(
8148 "Rate Limit Reached",
8149 format!(
8150 "{provider}'s rate limit was reached. Zed will retry automatically. \
8151 You can also wait a moment and try again."
8152 )
8153 .into(),
8154 true,
8155 true,
8156 cx,
8157 ),
8158 ThreadError::ServerOverloaded { provider } => self.render_error_callout(
8159 "Provider Unavailable",
8160 format!(
8161 "{provider}'s servers are temporarily unavailable. Zed will retry \
8162 automatically. If the problem persists, check the provider's status page."
8163 )
8164 .into(),
8165 true,
8166 true,
8167 cx,
8168 ),
8169 ThreadError::PromptTooLarge => self.render_prompt_too_large_error(cx),
8170 ThreadError::NoApiKey { provider } => self.render_error_callout(
8171 "API Key Missing",
8172 format!(
8173 "No API key is configured for {provider}. \
8174 Add your key via the Agent Panel settings to continue."
8175 )
8176 .into(),
8177 false,
8178 true,
8179 cx,
8180 ),
8181 ThreadError::StreamError { provider } => self.render_error_callout(
8182 "Connection Interrupted",
8183 format!(
8184 "The connection to {provider}'s API was interrupted. Zed will retry \
8185 automatically. If the problem persists, check your network connection."
8186 )
8187 .into(),
8188 true,
8189 true,
8190 cx,
8191 ),
8192 ThreadError::InvalidApiKey { provider } => self.render_error_callout(
8193 "Invalid API Key",
8194 format!(
8195 "The API key for {provider} is invalid or has expired. \
8196 Update your key via the Agent Panel settings to continue."
8197 )
8198 .into(),
8199 false,
8200 false,
8201 cx,
8202 ),
8203 ThreadError::PermissionDenied { provider } => self.render_error_callout(
8204 "Permission Denied",
8205 format!(
8206 "{provider}'s API rejected the request due to insufficient permissions. \
8207 Check that your API key has access to this model."
8208 )
8209 .into(),
8210 false,
8211 false,
8212 cx,
8213 ),
8214 ThreadError::RequestFailed => self.render_error_callout(
8215 "Request Failed",
8216 "The request could not be completed after multiple attempts. \
8217 Try again in a moment."
8218 .into(),
8219 true,
8220 false,
8221 cx,
8222 ),
8223 ThreadError::MaxOutputTokens => self.render_error_callout(
8224 "Output Limit Reached",
8225 "The model stopped because it reached its maximum output length. \
8226 You can ask it to continue where it left off."
8227 .into(),
8228 false,
8229 false,
8230 cx,
8231 ),
8232 ThreadError::NoModelSelected => self.render_error_callout(
8233 "No Model Selected",
8234 "Select a model from the model picker below to get started.".into(),
8235 false,
8236 false,
8237 cx,
8238 ),
8239 ThreadError::ApiError { provider } => self.render_error_callout(
8240 "API Error",
8241 format!(
8242 "{provider}'s API returned an unexpected error. \
8243 If the problem persists, try switching models or restarting Zed."
8244 )
8245 .into(),
8246 true,
8247 true,
8248 cx,
8249 ),
8250 };
8251
8252 Some(div().child(content))
8253 }
8254
8255 fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
8256 let model_or_agent_name = self.current_model_name(cx);
8257 let refusal_message = format!(
8258 "{} refused to respond to this prompt. \
8259 This can happen when a model believes the prompt violates its content policy \
8260 or safety guidelines, so rephrasing it can sometimes address the issue.",
8261 model_or_agent_name
8262 );
8263
8264 Callout::new()
8265 .severity(Severity::Error)
8266 .title("Request Refused")
8267 .icon(IconName::XCircle)
8268 .description(refusal_message.clone())
8269 .actions_slot(self.create_copy_button(&refusal_message))
8270 .dismiss_action(self.dismiss_error_button(cx))
8271 }
8272
8273 fn render_authentication_required_error(
8274 &self,
8275 error: SharedString,
8276 cx: &mut Context<Self>,
8277 ) -> Callout {
8278 Callout::new()
8279 .severity(Severity::Error)
8280 .title("Authentication Required")
8281 .icon(IconName::XCircle)
8282 .description(error.clone())
8283 .actions_slot(
8284 h_flex()
8285 .gap_0p5()
8286 .child(self.authenticate_button(cx))
8287 .child(self.create_copy_button(error)),
8288 )
8289 .dismiss_action(self.dismiss_error_button(cx))
8290 }
8291
8292 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
8293 const ERROR_MESSAGE: &str =
8294 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
8295
8296 Callout::new()
8297 .severity(Severity::Error)
8298 .icon(IconName::XCircle)
8299 .title("Free Usage Exceeded")
8300 .description(ERROR_MESSAGE)
8301 .actions_slot(
8302 h_flex()
8303 .gap_0p5()
8304 .child(self.upgrade_button(cx))
8305 .child(self.create_copy_button(ERROR_MESSAGE)),
8306 )
8307 .dismiss_action(self.dismiss_error_button(cx))
8308 }
8309
8310 fn render_error_callout(
8311 &self,
8312 title: &'static str,
8313 message: SharedString,
8314 show_retry: bool,
8315 show_copy: bool,
8316 cx: &mut Context<Self>,
8317 ) -> Callout {
8318 let can_resume = show_retry && self.thread.read(cx).can_retry(cx);
8319 let show_actions = can_resume || show_copy;
8320
8321 Callout::new()
8322 .severity(Severity::Error)
8323 .icon(IconName::XCircle)
8324 .title(title)
8325 .description(message.clone())
8326 .when(show_actions, |callout| {
8327 callout.actions_slot(
8328 h_flex()
8329 .gap_0p5()
8330 .when(can_resume, |this| this.child(self.retry_button(cx)))
8331 .when(show_copy, |this| {
8332 this.child(self.create_copy_button(message.clone()))
8333 }),
8334 )
8335 })
8336 .dismiss_action(self.dismiss_error_button(cx))
8337 }
8338
8339 fn render_prompt_too_large_error(&self, cx: &mut Context<Self>) -> Callout {
8340 const MESSAGE: &str = "This conversation is too long for the model's context window. \
8341 Start a new thread or remove some attached files to continue.";
8342
8343 Callout::new()
8344 .severity(Severity::Error)
8345 .icon(IconName::XCircle)
8346 .title("Context Too Large")
8347 .description(MESSAGE)
8348 .actions_slot(
8349 h_flex()
8350 .gap_0p5()
8351 .child(self.new_thread_button(cx))
8352 .child(self.create_copy_button(MESSAGE)),
8353 )
8354 .dismiss_action(self.dismiss_error_button(cx))
8355 }
8356
8357 fn retry_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
8358 Button::new("retry", "Retry")
8359 .label_size(LabelSize::Small)
8360 .style(ButtonStyle::Filled)
8361 .on_click(cx.listener(|this, _, _, cx| {
8362 this.retry_generation(cx);
8363 }))
8364 }
8365
8366 fn new_thread_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
8367 Button::new("new_thread", "New Thread")
8368 .label_size(LabelSize::Small)
8369 .style(ButtonStyle::Filled)
8370 .on_click(cx.listener(|this, _, window, cx| {
8371 this.clear_thread_error(cx);
8372 window.dispatch_action(NewThread.boxed_clone(), cx);
8373 }))
8374 }
8375
8376 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
8377 Button::new("upgrade", "Upgrade")
8378 .label_size(LabelSize::Small)
8379 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
8380 .on_click(cx.listener({
8381 move |this, _, _, cx| {
8382 this.clear_thread_error(cx);
8383 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
8384 }
8385 }))
8386 }
8387
8388 fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
8389 Button::new("authenticate", "Authenticate")
8390 .label_size(LabelSize::Small)
8391 .style(ButtonStyle::Filled)
8392 .on_click(cx.listener({
8393 move |this, _, window, cx| {
8394 let server_view = this.server_view.clone();
8395 let agent_name = this.agent_id.clone();
8396
8397 this.clear_thread_error(cx);
8398 if let Some(message) = this.in_flight_prompt.take() {
8399 this.message_editor.update(cx, |editor, cx| {
8400 editor.set_message(message, window, cx);
8401 });
8402 }
8403 let connection = this.thread.read(cx).connection().clone();
8404 window.defer(cx, |window, cx| {
8405 ConversationView::handle_auth_required(
8406 server_view,
8407 AuthRequired::new(),
8408 agent_name,
8409 connection,
8410 window,
8411 cx,
8412 );
8413 })
8414 }
8415 }))
8416 }
8417
8418 fn current_model_name(&self, cx: &App) -> SharedString {
8419 // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
8420 // For ACP agents, use the agent name (e.g., "Claude Agent", "Gemini CLI")
8421 // This provides better clarity about what refused the request
8422 if self.as_native_connection(cx).is_some() {
8423 self.model_selector
8424 .clone()
8425 .and_then(|selector| selector.read(cx).active_model(cx))
8426 .map(|model| model.name.clone())
8427 .unwrap_or_else(|| SharedString::from("The model"))
8428 } else {
8429 // ACP agent - use the agent name (e.g., "Claude Agent", "Gemini CLI")
8430 self.agent_id.0.clone()
8431 }
8432 }
8433
8434 fn render_any_thread_error(
8435 &mut self,
8436 error: SharedString,
8437 window: &mut Window,
8438 cx: &mut Context<'_, Self>,
8439 ) -> Callout {
8440 let can_resume = self.thread.read(cx).can_retry(cx);
8441
8442 let markdown = if let Some(markdown) = &self.thread_error_markdown {
8443 markdown.clone()
8444 } else {
8445 let markdown = cx.new(|cx| Markdown::new(error.clone(), None, None, cx));
8446 self.thread_error_markdown = Some(markdown.clone());
8447 markdown
8448 };
8449
8450 let markdown_style =
8451 MarkdownStyle::themed(MarkdownFont::Agent, window, cx).with_muted_text(cx);
8452 let description = self
8453 .render_markdown(markdown, markdown_style)
8454 .into_any_element();
8455
8456 Callout::new()
8457 .severity(Severity::Error)
8458 .icon(IconName::XCircle)
8459 .title("An Error Happened")
8460 .description_slot(description)
8461 .actions_slot(
8462 h_flex()
8463 .gap_0p5()
8464 .when(can_resume, |this| {
8465 this.child(
8466 IconButton::new("retry", IconName::RotateCw)
8467 .icon_size(IconSize::Small)
8468 .tooltip(Tooltip::text("Retry Generation"))
8469 .on_click(cx.listener(|this, _, _window, cx| {
8470 this.retry_generation(cx);
8471 })),
8472 )
8473 })
8474 .child(self.create_copy_button(error.to_string())),
8475 )
8476 .dismiss_action(self.dismiss_error_button(cx))
8477 }
8478
8479 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
8480 let workspace = self.workspace.clone();
8481 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
8482 open_link(text, &workspace, window, cx);
8483 })
8484 }
8485
8486 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
8487 let message = message.into();
8488
8489 CopyButton::new("copy-error-message", message).tooltip_label("Copy Error Message")
8490 }
8491
8492 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
8493 IconButton::new("dismiss", IconName::Close)
8494 .icon_size(IconSize::Small)
8495 .tooltip(Tooltip::text("Dismiss"))
8496 .on_click(cx.listener({
8497 move |this, _, _, cx| {
8498 this.clear_thread_error(cx);
8499 cx.notify();
8500 }
8501 }))
8502 }
8503
8504 fn render_resume_notice(_cx: &Context<Self>) -> AnyElement {
8505 let description = "This agent does not support viewing previous messages. However, your session will still continue from where you last left off.";
8506
8507 Callout::new()
8508 .border_position(ui::BorderPosition::Bottom)
8509 .severity(Severity::Info)
8510 .icon(IconName::Info)
8511 .title("Resumed Session")
8512 .description(description)
8513 .into_any_element()
8514 }
8515
8516 fn update_recent_history_from_cache(
8517 &mut self,
8518 history: &Entity<ThreadHistory>,
8519 cx: &mut Context<Self>,
8520 ) {
8521 self.recent_history_entries = history.read(cx).get_recent_sessions(3);
8522 self.hovered_recent_history_item = None;
8523 cx.notify();
8524 }
8525
8526 fn render_codex_windows_warning(&self, cx: &mut Context<Self>) -> Callout {
8527 Callout::new()
8528 .icon(IconName::Warning)
8529 .severity(Severity::Warning)
8530 .title("Codex on Windows")
8531 .description("For best performance, run Codex in Windows Subsystem for Linux (WSL2)")
8532 .actions_slot(
8533 Button::new("open-wsl-modal", "Open in WSL").on_click(cx.listener({
8534 move |_, _, _window, cx| {
8535 #[cfg(windows)]
8536 _window.dispatch_action(
8537 zed_actions::wsl_actions::OpenWsl::default().boxed_clone(),
8538 cx,
8539 );
8540 cx.notify();
8541 }
8542 })),
8543 )
8544 .dismiss_action(
8545 IconButton::new("dismiss", IconName::Close)
8546 .icon_size(IconSize::Small)
8547 .icon_color(Color::Muted)
8548 .tooltip(Tooltip::text("Dismiss Warning"))
8549 .on_click(cx.listener({
8550 move |this, _, _, cx| {
8551 this.show_codex_windows_warning = false;
8552 cx.notify();
8553 }
8554 })),
8555 )
8556 }
8557
8558 fn render_external_source_prompt_warning(&self, cx: &mut Context<Self>) -> Callout {
8559 Callout::new()
8560 .icon(IconName::Warning)
8561 .severity(Severity::Warning)
8562 .title("Review before sending")
8563 .description("This prompt was pre-filled by an external link. Read it carefully before you send it.")
8564 .dismiss_action(
8565 IconButton::new("dismiss-external-source-prompt-warning", IconName::Close)
8566 .icon_size(IconSize::Small)
8567 .icon_color(Color::Muted)
8568 .tooltip(Tooltip::text("Dismiss Warning"))
8569 .on_click(cx.listener({
8570 move |this, _, _, cx| {
8571 this.show_external_source_prompt_warning = false;
8572 cx.notify();
8573 }
8574 })),
8575 )
8576 }
8577
8578 fn render_multi_root_callout(&self, cx: &mut Context<Self>) -> Option<Callout> {
8579 if self.multi_root_callout_dismissed {
8580 return None;
8581 }
8582
8583 if self.as_native_connection(cx).is_some() {
8584 return None;
8585 }
8586
8587 let project = self.project.upgrade()?;
8588 let worktree_count = project.read(cx).visible_worktrees(cx).count();
8589 if worktree_count <= 1 {
8590 return None;
8591 }
8592
8593 let work_dirs = self.thread.read(cx).work_dirs()?;
8594 let active_dir = work_dirs
8595 .ordered_paths()
8596 .next()
8597 .and_then(|p| p.file_name())
8598 .map(|name| name.to_string_lossy().to_string())
8599 .unwrap_or_else(|| "one folder".to_string());
8600
8601 let description = format!(
8602 "This agent only operates on \"{}\". Other folders in this workspace are not accessible to it.",
8603 active_dir
8604 );
8605
8606 Some(
8607 Callout::new()
8608 .severity(Severity::Warning)
8609 .icon(IconName::Warning)
8610 .title("External Agents currently don't support multi-root workspaces")
8611 .description(description)
8612 .border_position(ui::BorderPosition::Bottom)
8613 .dismiss_action(
8614 IconButton::new("dismiss-multi-root-callout", IconName::Close)
8615 .icon_size(IconSize::Small)
8616 .tooltip(Tooltip::text("Dismiss"))
8617 .on_click(cx.listener(|this, _, _, cx| {
8618 this.multi_root_callout_dismissed = true;
8619 cx.notify();
8620 })),
8621 ),
8622 )
8623 }
8624
8625 fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
8626 let server_view = self.server_view.clone();
8627 let has_version = !version.is_empty();
8628 let title = if has_version {
8629 "New version available"
8630 } else {
8631 "Agent update available"
8632 };
8633 let button_label = if has_version {
8634 format!("Update to v{}", version)
8635 } else {
8636 "Reconnect".to_string()
8637 };
8638
8639 v_flex().w_full().justify_end().child(
8640 h_flex()
8641 .p_2()
8642 .pr_3()
8643 .w_full()
8644 .gap_1p5()
8645 .border_t_1()
8646 .border_color(cx.theme().colors().border)
8647 .bg(cx.theme().colors().element_background)
8648 .child(
8649 h_flex()
8650 .flex_1()
8651 .gap_1p5()
8652 .child(
8653 Icon::new(IconName::Download)
8654 .color(Color::Accent)
8655 .size(IconSize::Small),
8656 )
8657 .child(Label::new(title).size(LabelSize::Small)),
8658 )
8659 .child(
8660 Button::new("update-button", button_label)
8661 .label_size(LabelSize::Small)
8662 .style(ButtonStyle::Tinted(TintColor::Accent))
8663 .on_click(move |_, window, cx| {
8664 server_view
8665 .update(cx, |view, cx| view.reset(window, cx))
8666 .ok();
8667 }),
8668 ),
8669 )
8670 }
8671
8672 fn render_token_limit_callout(&self, cx: &mut Context<Self>) -> Option<Callout> {
8673 if self.token_limit_callout_dismissed {
8674 return None;
8675 }
8676
8677 let token_usage = self.thread.read(cx).token_usage()?;
8678 let ratio = token_usage.ratio();
8679
8680 let (severity, icon, title) = match ratio {
8681 acp_thread::TokenUsageRatio::Normal => return None,
8682 acp_thread::TokenUsageRatio::Warning => (
8683 Severity::Warning,
8684 IconName::Warning,
8685 "Thread reaching the token limit soon",
8686 ),
8687 acp_thread::TokenUsageRatio::Exceeded => (
8688 Severity::Error,
8689 IconName::XCircle,
8690 "Thread reached the token limit",
8691 ),
8692 };
8693
8694 let description = "To continue, start a new thread from a summary.";
8695
8696 Some(
8697 Callout::new()
8698 .severity(severity)
8699 .icon(icon)
8700 .title(title)
8701 .description(description)
8702 .actions_slot(
8703 h_flex().gap_0p5().child(
8704 Button::new("start-new-thread", "Start New Thread")
8705 .label_size(LabelSize::Small)
8706 .on_click(cx.listener(|this, _, window, cx| {
8707 let session_id = this.thread.read(cx).session_id().clone();
8708 window.dispatch_action(
8709 crate::NewNativeAgentThreadFromSummary {
8710 from_session_id: session_id,
8711 }
8712 .boxed_clone(),
8713 cx,
8714 );
8715 })),
8716 ),
8717 )
8718 .dismiss_action(self.dismiss_error_button(cx)),
8719 )
8720 }
8721
8722 fn open_permission_dropdown(
8723 &mut self,
8724 _: &crate::OpenPermissionDropdown,
8725 window: &mut Window,
8726 cx: &mut Context<Self>,
8727 ) {
8728 let menu_handle = self.permission_dropdown_handle.clone();
8729 window.defer(cx, move |window, cx| {
8730 menu_handle.toggle(window, cx);
8731 });
8732 }
8733
8734 fn open_add_context_menu(
8735 &mut self,
8736 _action: &OpenAddContextMenu,
8737 window: &mut Window,
8738 cx: &mut Context<Self>,
8739 ) {
8740 let menu_handle = self.add_context_menu_handle.clone();
8741 window.defer(cx, move |window, cx| {
8742 menu_handle.toggle(window, cx);
8743 });
8744 }
8745
8746 fn toggle_fast_mode(&mut self, cx: &mut Context<Self>) {
8747 if !self.fast_mode_available(cx) {
8748 return;
8749 }
8750 let Some(thread) = self.as_native_thread(cx) else {
8751 return;
8752 };
8753 thread.update(cx, |thread, cx| {
8754 let new_speed = thread
8755 .speed()
8756 .map(|speed| speed.toggle())
8757 .unwrap_or(Speed::Fast);
8758 thread.set_speed(new_speed, cx);
8759
8760 let fs = thread.project().read(cx).fs().clone();
8761 update_settings_file(fs, cx, move |settings, _| {
8762 if let Some(agent) = settings.agent.as_mut()
8763 && let Some(default_model) = agent.default_model.as_mut()
8764 {
8765 default_model.speed = Some(new_speed);
8766 }
8767 });
8768 });
8769 }
8770
8771 fn cycle_thinking_effort(&mut self, cx: &mut Context<Self>) {
8772 let Some(thread) = self.as_native_thread(cx) else {
8773 return;
8774 };
8775
8776 let (effort_levels, current_effort) = {
8777 let thread_ref = thread.read(cx);
8778 let Some(model) = thread_ref.model() else {
8779 return;
8780 };
8781 if !model.supports_thinking() || !thread_ref.thinking_enabled() {
8782 return;
8783 }
8784 let effort_levels = model.supported_effort_levels();
8785 if effort_levels.is_empty() {
8786 return;
8787 }
8788 let current_effort = thread_ref.thinking_effort().cloned();
8789 (effort_levels, current_effort)
8790 };
8791
8792 let current_index = current_effort.and_then(|current| {
8793 effort_levels
8794 .iter()
8795 .position(|level| level.value == current)
8796 });
8797 let next_index = match current_index {
8798 Some(index) => (index + 1) % effort_levels.len(),
8799 None => 0,
8800 };
8801 let next_effort = effort_levels[next_index].value.to_string();
8802
8803 thread.update(cx, |thread, cx| {
8804 thread.set_thinking_effort(Some(next_effort.clone()), cx);
8805
8806 let fs = thread.project().read(cx).fs().clone();
8807 update_settings_file(fs, cx, move |settings, _| {
8808 if let Some(agent) = settings.agent.as_mut()
8809 && let Some(default_model) = agent.default_model.as_mut()
8810 {
8811 default_model.effort = Some(next_effort);
8812 }
8813 });
8814 });
8815 }
8816
8817 fn toggle_thinking_effort_menu(
8818 &mut self,
8819 _action: &ToggleThinkingEffortMenu,
8820 window: &mut Window,
8821 cx: &mut Context<Self>,
8822 ) {
8823 let menu_handle = self.thinking_effort_menu_handle.clone();
8824 window.defer(cx, move |window, cx| {
8825 menu_handle.toggle(window, cx);
8826 });
8827 }
8828}
8829
8830impl Render for ThreadView {
8831 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8832 let has_messages = self.list_state.item_count() > 0;
8833 let list_state = self.list_state.clone();
8834
8835 let conversation = v_flex()
8836 .when(self.resumed_without_history, |this| {
8837 this.child(Self::render_resume_notice(cx))
8838 })
8839 .map(|this| {
8840 if has_messages {
8841 this.flex_1()
8842 .size_full()
8843 .child(self.render_entries(cx))
8844 .vertical_scrollbar_for(&list_state, window, cx)
8845 .into_any()
8846 } else {
8847 this.into_any()
8848 }
8849 });
8850
8851 v_flex()
8852 .key_context("AcpThread")
8853 .track_focus(&self.focus_handle)
8854 .on_action(cx.listener(|this, _: &menu::Cancel, _, cx| {
8855 if this.parent_id.is_none() {
8856 this.cancel_generation(cx);
8857 }
8858 }))
8859 .on_action(cx.listener(|this, _: &workspace::GoBack, window, cx| {
8860 if let Some(parent_session_id) = this.parent_id.clone() {
8861 this.server_view
8862 .update(cx, |view, cx| {
8863 view.navigate_to_session(parent_session_id, window, cx);
8864 })
8865 .ok();
8866 }
8867 }))
8868 .on_action(cx.listener(Self::keep_all))
8869 .on_action(cx.listener(Self::reject_all))
8870 .on_action(cx.listener(Self::undo_last_reject))
8871 .on_action(cx.listener(Self::allow_always))
8872 .on_action(cx.listener(Self::allow_once))
8873 .on_action(cx.listener(Self::reject_once))
8874 .on_action(cx.listener(Self::handle_authorize_tool_call))
8875 .on_action(cx.listener(Self::handle_select_permission_granularity))
8876 .on_action(cx.listener(Self::handle_toggle_command_pattern))
8877 .on_action(cx.listener(Self::open_permission_dropdown))
8878 .on_action(cx.listener(Self::open_add_context_menu))
8879 .on_action(cx.listener(Self::scroll_output_page_up))
8880 .on_action(cx.listener(Self::scroll_output_page_down))
8881 .on_action(cx.listener(Self::scroll_output_line_up))
8882 .on_action(cx.listener(Self::scroll_output_line_down))
8883 .on_action(cx.listener(Self::scroll_output_to_top))
8884 .on_action(cx.listener(Self::scroll_output_to_bottom))
8885 .on_action(cx.listener(Self::scroll_output_to_previous_message))
8886 .on_action(cx.listener(Self::scroll_output_to_next_message))
8887 .on_action(cx.listener(|this, _: &ToggleFastMode, _window, cx| {
8888 this.toggle_fast_mode(cx);
8889 }))
8890 .on_action(cx.listener(|this, _: &ToggleThinkingMode, _window, cx| {
8891 if this.thread.read(cx).status() != ThreadStatus::Idle {
8892 return;
8893 }
8894 if let Some(thread) = this.as_native_thread(cx) {
8895 thread.update(cx, |thread, cx| {
8896 thread.set_thinking_enabled(!thread.thinking_enabled(), cx);
8897 });
8898 }
8899 }))
8900 .on_action(cx.listener(|this, _: &CycleThinkingEffort, _window, cx| {
8901 if this.thread.read(cx).status() != ThreadStatus::Idle {
8902 return;
8903 }
8904 this.cycle_thinking_effort(cx);
8905 }))
8906 .on_action(
8907 cx.listener(|this, action: &ToggleThinkingEffortMenu, window, cx| {
8908 if this.thread.read(cx).status() != ThreadStatus::Idle {
8909 return;
8910 }
8911 this.toggle_thinking_effort_menu(action, window, cx);
8912 }),
8913 )
8914 .on_action(cx.listener(|this, _: &SendNextQueuedMessage, window, cx| {
8915 this.send_queued_message_at_index(0, true, window, cx);
8916 }))
8917 .on_action(cx.listener(|this, _: &RemoveFirstQueuedMessage, _, cx| {
8918 this.remove_from_queue(0, cx);
8919 cx.notify();
8920 }))
8921 .on_action(cx.listener(|this, _: &EditFirstQueuedMessage, window, cx| {
8922 this.move_queued_message_to_main_editor(0, None, None, window, cx);
8923 }))
8924 .on_action(cx.listener(|this, _: &ClearMessageQueue, _, cx| {
8925 this.local_queued_messages.clear();
8926 this.sync_queue_flag_to_native_thread(cx);
8927 this.can_fast_track_queue = false;
8928 cx.notify();
8929 }))
8930 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
8931 if this.thread.read(cx).status() != ThreadStatus::Idle {
8932 return;
8933 }
8934 if let Some(config_options_view) = this.config_options_view.clone() {
8935 let handled = config_options_view.update(cx, |view, cx| {
8936 view.toggle_category_picker(
8937 acp::SessionConfigOptionCategory::Mode,
8938 window,
8939 cx,
8940 )
8941 });
8942 if handled {
8943 return;
8944 }
8945 }
8946
8947 if let Some(profile_selector) = this.profile_selector.clone() {
8948 profile_selector.read(cx).menu_handle().toggle(window, cx);
8949 } else if let Some(mode_selector) = this.mode_selector.clone() {
8950 mode_selector.read(cx).menu_handle().toggle(window, cx);
8951 }
8952 }))
8953 .on_action(cx.listener(|this, _: &CycleModeSelector, window, cx| {
8954 if this.thread.read(cx).status() != ThreadStatus::Idle {
8955 return;
8956 }
8957 if let Some(config_options_view) = this.config_options_view.clone() {
8958 let handled = config_options_view.update(cx, |view, cx| {
8959 view.cycle_category_option(
8960 acp::SessionConfigOptionCategory::Mode,
8961 false,
8962 cx,
8963 )
8964 });
8965 if handled {
8966 return;
8967 }
8968 }
8969
8970 if let Some(profile_selector) = this.profile_selector.clone() {
8971 profile_selector.update(cx, |profile_selector, cx| {
8972 profile_selector.cycle_profile(cx);
8973 });
8974 } else if let Some(mode_selector) = this.mode_selector.clone() {
8975 mode_selector.update(cx, |mode_selector, cx| {
8976 mode_selector.cycle_mode(window, cx);
8977 });
8978 }
8979 }))
8980 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
8981 if this.thread.read(cx).status() != ThreadStatus::Idle {
8982 return;
8983 }
8984 if let Some(config_options_view) = this.config_options_view.clone() {
8985 let handled = config_options_view.update(cx, |view, cx| {
8986 view.toggle_category_picker(
8987 acp::SessionConfigOptionCategory::Model,
8988 window,
8989 cx,
8990 )
8991 });
8992 if handled {
8993 return;
8994 }
8995 }
8996
8997 if let Some(model_selector) = this.model_selector.clone() {
8998 model_selector
8999 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
9000 }
9001 }))
9002 .on_action(cx.listener(|this, _: &CycleFavoriteModels, window, cx| {
9003 if this.thread.read(cx).status() != ThreadStatus::Idle {
9004 return;
9005 }
9006 if let Some(config_options_view) = this.config_options_view.clone() {
9007 let handled = config_options_view.update(cx, |view, cx| {
9008 view.cycle_category_option(
9009 acp::SessionConfigOptionCategory::Model,
9010 true,
9011 cx,
9012 )
9013 });
9014 if handled {
9015 return;
9016 }
9017 }
9018
9019 if let Some(model_selector) = this.model_selector.clone() {
9020 model_selector.update(cx, |model_selector, cx| {
9021 model_selector.cycle_favorite_models(window, cx);
9022 });
9023 }
9024 }))
9025 .size_full()
9026 .children(self.render_subagent_titlebar(cx))
9027 .child(conversation)
9028 .children(self.render_multi_root_callout(cx))
9029 .children(self.render_activity_bar(window, cx))
9030 .when(self.show_external_source_prompt_warning, |this| {
9031 this.child(self.render_external_source_prompt_warning(cx))
9032 })
9033 .when(self.show_codex_windows_warning, |this| {
9034 this.child(self.render_codex_windows_warning(cx))
9035 })
9036 .children(self.render_thread_retry_status_callout())
9037 .children(self.render_thread_error(window, cx))
9038 .when_some(
9039 match has_messages {
9040 true => None,
9041 false => self.new_server_version_available.clone(),
9042 },
9043 |this, version| this.child(self.render_new_version_callout(&version, cx)),
9044 )
9045 .children(self.render_token_limit_callout(cx))
9046 .child(self.render_message_editor(window, cx))
9047 }
9048}
9049
9050pub(crate) fn open_link(
9051 url: SharedString,
9052 workspace: &WeakEntity<Workspace>,
9053 window: &mut Window,
9054 cx: &mut App,
9055) {
9056 let Some(workspace) = workspace.upgrade() else {
9057 cx.open_url(&url);
9058 return;
9059 };
9060
9061 if let Some(mention) = MentionUri::parse(&url, workspace.read(cx).path_style(cx)).log_err() {
9062 workspace.update(cx, |workspace, cx| match mention {
9063 MentionUri::File { abs_path } => {
9064 let project = workspace.project();
9065 let Some(path) =
9066 project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
9067 else {
9068 return;
9069 };
9070
9071 workspace
9072 .open_path(path, None, true, window, cx)
9073 .detach_and_log_err(cx);
9074 }
9075 MentionUri::PastedImage { .. } => {}
9076 MentionUri::Directory { abs_path } => {
9077 let project = workspace.project();
9078 let Some(entry_id) = project.update(cx, |project, cx| {
9079 let path = project.find_project_path(abs_path, cx)?;
9080 project.entry_for_path(&path, cx).map(|entry| entry.id)
9081 }) else {
9082 return;
9083 };
9084
9085 project.update(cx, |_, cx| {
9086 cx.emit(project::Event::RevealInProjectPanel(entry_id));
9087 });
9088 }
9089 MentionUri::Symbol {
9090 abs_path: path,
9091 line_range,
9092 ..
9093 }
9094 | MentionUri::Selection {
9095 abs_path: Some(path),
9096 line_range,
9097 } => {
9098 let project = workspace.project();
9099 let Some(path) =
9100 project.update(cx, |project, cx| project.find_project_path(path, cx))
9101 else {
9102 return;
9103 };
9104
9105 let item = workspace.open_path(path, None, true, window, cx);
9106 window
9107 .spawn(cx, async move |cx| {
9108 let Some(editor) = item.await?.downcast::<Editor>() else {
9109 return Ok(());
9110 };
9111 let range =
9112 Point::new(*line_range.start(), 0)..Point::new(*line_range.start(), 0);
9113 editor
9114 .update_in(cx, |editor, window, cx| {
9115 editor.change_selections(
9116 SelectionEffects::scroll(Autoscroll::center()),
9117 window,
9118 cx,
9119 |s| s.select_ranges(vec![range]),
9120 );
9121 })
9122 .ok();
9123 anyhow::Ok(())
9124 })
9125 .detach_and_log_err(cx);
9126 }
9127 MentionUri::Selection { abs_path: None, .. } => {}
9128 MentionUri::Thread { id, name } => {
9129 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
9130 panel.update(cx, |panel, cx| {
9131 panel.open_thread(id, None, Some(name.into()), window, cx)
9132 });
9133 }
9134 }
9135 MentionUri::Rule { id, .. } => {
9136 let PromptId::User { uuid } = id else {
9137 return;
9138 };
9139 window.dispatch_action(
9140 Box::new(OpenRulesLibrary {
9141 prompt_to_select: Some(uuid.0),
9142 }),
9143 cx,
9144 )
9145 }
9146 MentionUri::Fetch { url } => {
9147 cx.open_url(url.as_str());
9148 }
9149 MentionUri::Diagnostics { .. } => {}
9150 MentionUri::TerminalSelection { .. } => {}
9151 MentionUri::GitDiff { .. } => {}
9152 MentionUri::MergeConflict { .. } => {}
9153 })
9154 } else {
9155 cx.open_url(&url);
9156 }
9157}