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