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