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