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