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