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