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, Default::default(), 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 is_subagent_output: _,
3715 }) => {
3716 let mut is_blank = true;
3717 let is_last = entry_ix + 1 == total_entries;
3718
3719 let style = MarkdownStyle::themed(MarkdownFont::Agent, window, cx);
3720 let message_body = v_flex()
3721 .w_full()
3722 .gap_3()
3723 .children(chunks.iter().enumerate().filter_map(
3724 |(chunk_ix, chunk)| match chunk {
3725 AssistantMessageChunk::Message { block } => {
3726 block.markdown().and_then(|md| {
3727 let this_is_blank = md.read(cx).source().trim().is_empty();
3728 is_blank = is_blank && this_is_blank;
3729 if this_is_blank {
3730 return None;
3731 }
3732
3733 Some(
3734 self.render_markdown(md.clone(), style.clone())
3735 .into_any_element(),
3736 )
3737 })
3738 }
3739 AssistantMessageChunk::Thought { block } => {
3740 block.markdown().and_then(|md| {
3741 let this_is_blank = md.read(cx).source().trim().is_empty();
3742 is_blank = is_blank && this_is_blank;
3743 if this_is_blank {
3744 return None;
3745 }
3746 Some(
3747 self.render_thinking_block(
3748 entry_ix,
3749 chunk_ix,
3750 md.clone(),
3751 window,
3752 cx,
3753 )
3754 .into_any_element(),
3755 )
3756 })
3757 }
3758 },
3759 ))
3760 .into_any();
3761
3762 if is_blank {
3763 Empty.into_any()
3764 } else {
3765 v_flex()
3766 .px_5()
3767 .py_1p5()
3768 .when(is_last, |this| this.pb_4())
3769 .w_full()
3770 .text_ui(cx)
3771 .child(self.render_message_context_menu(entry_ix, message_body, cx))
3772 .into_any()
3773 }
3774 }
3775 AgentThreadEntry::ToolCall(tool_call) => self
3776 .render_any_tool_call(
3777 &self.id,
3778 entry_ix,
3779 tool_call,
3780 &self.focus_handle(cx),
3781 window,
3782 cx,
3783 )
3784 .into_any(),
3785 };
3786
3787 let is_subagent_output = self.is_subagent()
3788 && matches!(entry, AgentThreadEntry::AssistantMessage(msg) if msg.is_subagent_output);
3789
3790 let primary = if is_subagent_output {
3791 v_flex()
3792 .w_full()
3793 .child(
3794 h_flex()
3795 .id("subagent_output")
3796 .px_5()
3797 .py_1()
3798 .gap_2()
3799 .child(Divider::horizontal())
3800 .child(
3801 h_flex()
3802 .gap_1()
3803 .child(
3804 Icon::new(IconName::ForwardArrowUp)
3805 .color(Color::Muted)
3806 .size(IconSize::Small),
3807 )
3808 .child(
3809 Label::new("Subagent Output")
3810 .size(LabelSize::Custom(self.tool_name_font_size()))
3811 .color(Color::Muted),
3812 ),
3813 )
3814 .child(Divider::horizontal())
3815 .tooltip(Tooltip::text("Everything below this line was sent as output from this subagent to the main agent.")),
3816 )
3817 .child(primary)
3818 .into_any_element()
3819 } else {
3820 primary
3821 };
3822
3823 let primary = if is_indented {
3824 let line_top = if is_first_indented {
3825 rems_from_px(-12.0)
3826 } else {
3827 rems_from_px(0.0)
3828 };
3829
3830 div()
3831 .relative()
3832 .w_full()
3833 .pl_5()
3834 .bg(cx.theme().colors().panel_background.opacity(0.2))
3835 .child(
3836 div()
3837 .absolute()
3838 .left(rems_from_px(18.0))
3839 .top(line_top)
3840 .bottom_0()
3841 .w_px()
3842 .bg(cx.theme().colors().border.opacity(0.6)),
3843 )
3844 .child(primary)
3845 .into_any_element()
3846 } else {
3847 primary
3848 };
3849
3850 let needs_confirmation = if let AgentThreadEntry::ToolCall(tool_call) = entry {
3851 matches!(
3852 tool_call.status,
3853 ToolCallStatus::WaitingForConfirmation { .. }
3854 )
3855 } else {
3856 false
3857 };
3858
3859 let thread = self.thread.clone();
3860 let comments_editor = self.thread_feedback.comments_editor.clone();
3861
3862 let primary = if entry_ix == total_entries - 1 {
3863 v_flex()
3864 .w_full()
3865 .child(primary)
3866 .map(|this| {
3867 if needs_confirmation {
3868 this.child(self.render_generating(true, cx))
3869 } else {
3870 this.child(self.render_thread_controls(&thread, cx))
3871 }
3872 })
3873 .when_some(comments_editor, |this, editor| {
3874 this.child(Self::render_feedback_feedback_editor(editor, cx))
3875 })
3876 .into_any_element()
3877 } else {
3878 primary
3879 };
3880
3881 if let Some(editing_index) = self.editing_message
3882 && editing_index < entry_ix
3883 {
3884 let is_subagent = self.is_subagent();
3885
3886 let backdrop = div()
3887 .id(("backdrop", entry_ix))
3888 .size_full()
3889 .absolute()
3890 .inset_0()
3891 .bg(cx.theme().colors().panel_background)
3892 .opacity(0.8)
3893 .block_mouse_except_scroll()
3894 .on_click(cx.listener(Self::cancel_editing));
3895
3896 div()
3897 .relative()
3898 .child(primary)
3899 .when(!is_subagent, |this| this.child(backdrop))
3900 .into_any_element()
3901 } else {
3902 primary
3903 }
3904 }
3905
3906 fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
3907 h_flex()
3908 .key_context("AgentFeedbackMessageEditor")
3909 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
3910 this.thread_feedback.dismiss_comments();
3911 cx.notify();
3912 }))
3913 .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
3914 this.submit_feedback_message(cx);
3915 }))
3916 .p_2()
3917 .mb_2()
3918 .mx_5()
3919 .gap_1()
3920 .rounded_md()
3921 .border_1()
3922 .border_color(cx.theme().colors().border)
3923 .bg(cx.theme().colors().editor_background)
3924 .child(div().w_full().child(editor))
3925 .child(
3926 h_flex()
3927 .child(
3928 IconButton::new("dismiss-feedback-message", IconName::Close)
3929 .icon_color(Color::Error)
3930 .icon_size(IconSize::XSmall)
3931 .shape(ui::IconButtonShape::Square)
3932 .on_click(cx.listener(move |this, _, _window, cx| {
3933 this.thread_feedback.dismiss_comments();
3934 cx.notify();
3935 })),
3936 )
3937 .child(
3938 IconButton::new("submit-feedback-message", IconName::Return)
3939 .icon_size(IconSize::XSmall)
3940 .shape(ui::IconButtonShape::Square)
3941 .on_click(cx.listener(move |this, _, _window, cx| {
3942 this.submit_feedback_message(cx);
3943 })),
3944 ),
3945 )
3946 }
3947
3948 fn render_thread_controls(
3949 &self,
3950 thread: &Entity<AcpThread>,
3951 cx: &Context<Self>,
3952 ) -> impl IntoElement {
3953 let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
3954 if is_generating {
3955 return self.render_generating(false, cx).into_any_element();
3956 }
3957
3958 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
3959 .shape(ui::IconButtonShape::Square)
3960 .icon_size(IconSize::Small)
3961 .icon_color(Color::Ignored)
3962 .tooltip(Tooltip::text("Open Thread as Markdown"))
3963 .on_click(cx.listener(move |this, _, window, cx| {
3964 if let Some(workspace) = this.workspace.upgrade() {
3965 this.open_thread_as_markdown(workspace, window, cx)
3966 .detach_and_log_err(cx);
3967 }
3968 }));
3969
3970 let scroll_to_recent_user_prompt =
3971 IconButton::new("scroll_to_recent_user_prompt", IconName::ForwardArrow)
3972 .shape(ui::IconButtonShape::Square)
3973 .icon_size(IconSize::Small)
3974 .icon_color(Color::Ignored)
3975 .tooltip(Tooltip::text("Scroll To Most Recent User Prompt"))
3976 .on_click(cx.listener(move |this, _, _, cx| {
3977 this.scroll_to_most_recent_user_prompt(cx);
3978 }));
3979
3980 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
3981 .shape(ui::IconButtonShape::Square)
3982 .icon_size(IconSize::Small)
3983 .icon_color(Color::Ignored)
3984 .tooltip(Tooltip::text("Scroll To Top"))
3985 .on_click(cx.listener(move |this, _, _, cx| {
3986 this.scroll_to_top(cx);
3987 }));
3988
3989 let show_stats = AgentSettings::get_global(cx).show_turn_stats;
3990 let last_turn_clock = show_stats
3991 .then(|| {
3992 self.turn_fields
3993 .last_turn_duration
3994 .filter(|&duration| duration > STOPWATCH_THRESHOLD)
3995 .map(|duration| {
3996 Label::new(duration_alt_display(duration))
3997 .size(LabelSize::Small)
3998 .color(Color::Muted)
3999 })
4000 })
4001 .flatten();
4002
4003 let last_turn_tokens_label = last_turn_clock
4004 .is_some()
4005 .then(|| {
4006 self.turn_fields
4007 .last_turn_tokens
4008 .filter(|&tokens| tokens > TOKEN_THRESHOLD)
4009 .map(|tokens| {
4010 Label::new(format!(
4011 "{} tokens",
4012 crate::text_thread_editor::humanize_token_count(tokens)
4013 ))
4014 .size(LabelSize::Small)
4015 .color(Color::Muted)
4016 })
4017 })
4018 .flatten();
4019
4020 let mut container = h_flex()
4021 .w_full()
4022 .py_2()
4023 .px_5()
4024 .gap_px()
4025 .opacity(0.6)
4026 .hover(|s| s.opacity(1.))
4027 .justify_end()
4028 .when(
4029 last_turn_tokens_label.is_some() || last_turn_clock.is_some(),
4030 |this| {
4031 this.child(
4032 h_flex()
4033 .gap_1()
4034 .px_1()
4035 .when_some(last_turn_tokens_label, |this, label| this.child(label))
4036 .when_some(last_turn_clock, |this, label| this.child(label)),
4037 )
4038 },
4039 );
4040
4041 if AgentSettings::get_global(cx).enable_feedback
4042 && self.thread.read(cx).connection().telemetry().is_some()
4043 {
4044 let feedback = self.thread_feedback.feedback;
4045
4046 let tooltip_meta = || {
4047 SharedString::new(
4048 "Rating the thread sends all of your current conversation to the Zed team.",
4049 )
4050 };
4051
4052 container = container
4053 .child(
4054 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
4055 .shape(ui::IconButtonShape::Square)
4056 .icon_size(IconSize::Small)
4057 .icon_color(match feedback {
4058 Some(ThreadFeedback::Positive) => Color::Accent,
4059 _ => Color::Ignored,
4060 })
4061 .tooltip(move |window, cx| match feedback {
4062 Some(ThreadFeedback::Positive) => {
4063 Tooltip::text("Thanks for your feedback!")(window, cx)
4064 }
4065 _ => {
4066 Tooltip::with_meta("Helpful Response", None, tooltip_meta(), cx)
4067 }
4068 })
4069 .on_click(cx.listener(move |this, _, window, cx| {
4070 this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
4071 })),
4072 )
4073 .child(
4074 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
4075 .shape(ui::IconButtonShape::Square)
4076 .icon_size(IconSize::Small)
4077 .icon_color(match feedback {
4078 Some(ThreadFeedback::Negative) => Color::Accent,
4079 _ => Color::Ignored,
4080 })
4081 .tooltip(move |window, cx| match feedback {
4082 Some(ThreadFeedback::Negative) => {
4083 Tooltip::text(
4084 "We appreciate your feedback and will use it to improve in the future.",
4085 )(window, cx)
4086 }
4087 _ => {
4088 Tooltip::with_meta(
4089 "Not Helpful Response",
4090 None,
4091 tooltip_meta(),
4092 cx,
4093 )
4094 }
4095 })
4096 .on_click(cx.listener(move |this, _, window, cx| {
4097 this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
4098 })),
4099 );
4100 }
4101
4102 if let Some(project) = self.project.upgrade()
4103 && let Some(server_view) = self.server_view.upgrade()
4104 && cx.has_flag::<AgentSharingFeatureFlag>()
4105 && project.read(cx).client().status().borrow().is_connected()
4106 {
4107 let button = if self.is_imported_thread(cx) {
4108 IconButton::new("sync-thread", IconName::ArrowCircle)
4109 .shape(ui::IconButtonShape::Square)
4110 .icon_size(IconSize::Small)
4111 .icon_color(Color::Ignored)
4112 .tooltip(Tooltip::text("Sync with source thread"))
4113 .on_click(cx.listener(move |this, _, window, cx| {
4114 this.sync_thread(project.clone(), server_view.clone(), window, cx);
4115 }))
4116 } else {
4117 IconButton::new("share-thread", IconName::ArrowUpRight)
4118 .shape(ui::IconButtonShape::Square)
4119 .icon_size(IconSize::Small)
4120 .icon_color(Color::Ignored)
4121 .tooltip(Tooltip::text("Share Thread"))
4122 .on_click(cx.listener(move |this, _, window, cx| {
4123 this.share_thread(window, cx);
4124 }))
4125 };
4126
4127 container = container.child(button);
4128 }
4129
4130 container
4131 .child(open_as_markdown)
4132 .child(scroll_to_recent_user_prompt)
4133 .child(scroll_to_top)
4134 .into_any_element()
4135 }
4136
4137 pub(crate) fn scroll_to_most_recent_user_prompt(&mut self, cx: &mut Context<Self>) {
4138 let entries = self.thread.read(cx).entries();
4139 if entries.is_empty() {
4140 return;
4141 }
4142
4143 // Find the most recent user message and scroll it to the top of the viewport.
4144 // (Fallback: if no user message exists, scroll to the bottom.)
4145 if let Some(ix) = entries
4146 .iter()
4147 .rposition(|entry| matches!(entry, AgentThreadEntry::UserMessage(_)))
4148 {
4149 self.list_state.scroll_to(ListOffset {
4150 item_ix: ix,
4151 offset_in_item: px(0.0),
4152 });
4153 cx.notify();
4154 } else {
4155 self.scroll_to_bottom(cx);
4156 }
4157 }
4158
4159 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
4160 let entry_count = self.thread.read(cx).entries().len();
4161 self.list_state.reset(entry_count);
4162 cx.notify();
4163 }
4164
4165 fn handle_feedback_click(
4166 &mut self,
4167 feedback: ThreadFeedback,
4168 window: &mut Window,
4169 cx: &mut Context<Self>,
4170 ) {
4171 self.thread_feedback
4172 .submit(self.thread.clone(), feedback, window, cx);
4173 cx.notify();
4174 }
4175
4176 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
4177 let thread = self.thread.clone();
4178 self.thread_feedback.submit_comments(thread, cx);
4179 cx.notify();
4180 }
4181
4182 pub(crate) fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
4183 self.list_state.scroll_to(ListOffset::default());
4184 cx.notify();
4185 }
4186
4187 pub fn open_thread_as_markdown(
4188 &self,
4189 workspace: Entity<Workspace>,
4190 window: &mut Window,
4191 cx: &mut App,
4192 ) -> Task<Result<()>> {
4193 let markdown_language_task = workspace
4194 .read(cx)
4195 .app_state()
4196 .languages
4197 .language_for_name("Markdown");
4198
4199 let thread = self.thread.read(cx);
4200 let thread_title = thread.title().to_string();
4201 let markdown = thread.to_markdown(cx);
4202
4203 let project = workspace.read(cx).project().clone();
4204 window.spawn(cx, async move |cx| {
4205 let markdown_language = markdown_language_task.await?;
4206
4207 let buffer = project
4208 .update(cx, |project, cx| {
4209 project.create_buffer(Some(markdown_language), false, cx)
4210 })
4211 .await?;
4212
4213 buffer.update(cx, |buffer, cx| {
4214 buffer.set_text(markdown, cx);
4215 buffer.set_capability(language::Capability::ReadWrite, cx);
4216 });
4217
4218 workspace.update_in(cx, |workspace, window, cx| {
4219 let buffer = cx
4220 .new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_title.clone()));
4221
4222 workspace.add_item_to_active_pane(
4223 Box::new(cx.new(|cx| {
4224 let mut editor =
4225 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4226 editor.set_breadcrumb_header(thread_title);
4227 editor
4228 })),
4229 None,
4230 true,
4231 window,
4232 cx,
4233 );
4234 })?;
4235 anyhow::Ok(())
4236 })
4237 }
4238
4239 fn render_generating(&self, confirmation: bool, cx: &App) -> impl IntoElement {
4240 let show_stats = AgentSettings::get_global(cx).show_turn_stats;
4241 let elapsed_label = show_stats
4242 .then(|| {
4243 self.turn_fields.turn_started_at.and_then(|started_at| {
4244 let elapsed = started_at.elapsed();
4245 (elapsed > STOPWATCH_THRESHOLD).then(|| duration_alt_display(elapsed))
4246 })
4247 })
4248 .flatten();
4249
4250 let is_waiting = confirmation || self.thread.read(cx).has_in_progress_tool_calls();
4251
4252 let turn_tokens_label = elapsed_label
4253 .is_some()
4254 .then(|| {
4255 self.turn_fields
4256 .turn_tokens
4257 .filter(|&tokens| tokens > TOKEN_THRESHOLD)
4258 .map(|tokens| crate::text_thread_editor::humanize_token_count(tokens))
4259 })
4260 .flatten();
4261
4262 let arrow_icon = if is_waiting {
4263 IconName::ArrowUp
4264 } else {
4265 IconName::ArrowDown
4266 };
4267
4268 h_flex()
4269 .id("generating-spinner")
4270 .py_2()
4271 .px(rems_from_px(22.))
4272 .gap_2()
4273 .map(|this| {
4274 if confirmation {
4275 this.child(
4276 h_flex()
4277 .w_2()
4278 .child(SpinnerLabel::sand().size(LabelSize::Small)),
4279 )
4280 .child(
4281 div().min_w(rems(8.)).child(
4282 LoadingLabel::new("Awaiting Confirmation")
4283 .size(LabelSize::Small)
4284 .color(Color::Muted),
4285 ),
4286 )
4287 } else {
4288 this.child(SpinnerLabel::new().size(LabelSize::Small))
4289 }
4290 })
4291 .when_some(elapsed_label, |this, elapsed| {
4292 this.child(
4293 Label::new(elapsed)
4294 .size(LabelSize::Small)
4295 .color(Color::Muted),
4296 )
4297 })
4298 .when_some(turn_tokens_label, |this, tokens| {
4299 this.child(
4300 h_flex()
4301 .gap_0p5()
4302 .child(
4303 Icon::new(arrow_icon)
4304 .size(IconSize::XSmall)
4305 .color(Color::Muted),
4306 )
4307 .child(
4308 Label::new(format!("{} tokens", tokens))
4309 .size(LabelSize::Small)
4310 .color(Color::Muted),
4311 ),
4312 )
4313 })
4314 .into_any_element()
4315 }
4316
4317 fn render_thinking_block(
4318 &self,
4319 entry_ix: usize,
4320 chunk_ix: usize,
4321 chunk: Entity<Markdown>,
4322 window: &Window,
4323 cx: &Context<Self>,
4324 ) -> AnyElement {
4325 let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
4326 let card_header_id = SharedString::from("inner-card-header");
4327
4328 let key = (entry_ix, chunk_ix);
4329
4330 let is_open = self.expanded_thinking_blocks.contains(&key);
4331
4332 let scroll_handle = self
4333 .entry_view_state
4334 .read(cx)
4335 .entry(entry_ix)
4336 .and_then(|entry| entry.scroll_handle_for_assistant_message_chunk(chunk_ix));
4337
4338 let thinking_content = {
4339 div()
4340 .id(("thinking-content", chunk_ix))
4341 .when_some(scroll_handle, |this, scroll_handle| {
4342 this.track_scroll(&scroll_handle)
4343 })
4344 .text_ui_sm(cx)
4345 .overflow_hidden()
4346 .child(self.render_markdown(
4347 chunk,
4348 MarkdownStyle::themed(MarkdownFont::Agent, window, cx),
4349 ))
4350 };
4351
4352 v_flex()
4353 .gap_1()
4354 .child(
4355 h_flex()
4356 .id(header_id)
4357 .group(&card_header_id)
4358 .relative()
4359 .w_full()
4360 .pr_1()
4361 .justify_between()
4362 .child(
4363 h_flex()
4364 .h(window.line_height() - px(2.))
4365 .gap_1p5()
4366 .overflow_hidden()
4367 .child(
4368 Icon::new(IconName::ToolThink)
4369 .size(IconSize::Small)
4370 .color(Color::Muted),
4371 )
4372 .child(
4373 div()
4374 .text_size(self.tool_name_font_size())
4375 .text_color(cx.theme().colors().text_muted)
4376 .child("Thinking"),
4377 ),
4378 )
4379 .child(
4380 Disclosure::new(("expand", entry_ix), is_open)
4381 .opened_icon(IconName::ChevronUp)
4382 .closed_icon(IconName::ChevronDown)
4383 .visible_on_hover(&card_header_id)
4384 .on_click(cx.listener({
4385 move |this, _event, _window, cx| {
4386 if is_open {
4387 this.expanded_thinking_blocks.remove(&key);
4388 } else {
4389 this.expanded_thinking_blocks.insert(key);
4390 }
4391 cx.notify();
4392 }
4393 })),
4394 )
4395 .on_click(cx.listener(move |this, _event, _window, cx| {
4396 if is_open {
4397 this.expanded_thinking_blocks.remove(&key);
4398 } else {
4399 this.expanded_thinking_blocks.insert(key);
4400 }
4401 cx.notify();
4402 })),
4403 )
4404 .when(is_open, |this| {
4405 this.child(
4406 div()
4407 .ml_1p5()
4408 .pl_3p5()
4409 .border_l_1()
4410 .border_color(self.tool_card_border_color(cx))
4411 .child(thinking_content),
4412 )
4413 })
4414 .into_any_element()
4415 }
4416
4417 fn render_message_context_menu(
4418 &self,
4419 entry_ix: usize,
4420 message_body: AnyElement,
4421 cx: &Context<Self>,
4422 ) -> AnyElement {
4423 let entity = cx.entity();
4424 let workspace = self.workspace.clone();
4425
4426 right_click_menu(format!("agent_context_menu-{}", entry_ix))
4427 .trigger(move |_, _, _| message_body)
4428 .menu(move |window, cx| {
4429 let focus = window.focused(cx);
4430 let entity = entity.clone();
4431 let workspace = workspace.clone();
4432
4433 ContextMenu::build(window, cx, move |menu, _, cx| {
4434 let this = entity.read(cx);
4435 let is_at_top = this.list_state.logical_scroll_top().item_ix == 0;
4436
4437 let has_selection = this
4438 .thread
4439 .read(cx)
4440 .entries()
4441 .get(entry_ix)
4442 .and_then(|entry| match &entry {
4443 AgentThreadEntry::AssistantMessage(msg) => Some(&msg.chunks),
4444 _ => None,
4445 })
4446 .map(|chunks| {
4447 chunks.iter().any(|chunk| {
4448 let md = match chunk {
4449 AssistantMessageChunk::Message { block } => block.markdown(),
4450 AssistantMessageChunk::Thought { block } => block.markdown(),
4451 };
4452 md.map_or(false, |m| m.read(cx).selected_text().is_some())
4453 })
4454 })
4455 .unwrap_or(false);
4456
4457 let copy_this_agent_response =
4458 ContextMenuEntry::new("Copy This Agent Response").handler({
4459 let entity = entity.clone();
4460 move |_, cx| {
4461 entity.update(cx, |this, cx| {
4462 let entries = this.thread.read(cx).entries();
4463 if let Some(text) =
4464 Self::get_agent_message_content(entries, entry_ix, cx)
4465 {
4466 cx.write_to_clipboard(ClipboardItem::new_string(text));
4467 }
4468 });
4469 }
4470 });
4471
4472 let scroll_item = if is_at_top {
4473 ContextMenuEntry::new("Scroll to Bottom").handler({
4474 let entity = entity.clone();
4475 move |_, cx| {
4476 entity.update(cx, |this, cx| {
4477 this.scroll_to_bottom(cx);
4478 });
4479 }
4480 })
4481 } else {
4482 ContextMenuEntry::new("Scroll to Top").handler({
4483 let entity = entity.clone();
4484 move |_, cx| {
4485 entity.update(cx, |this, cx| {
4486 this.scroll_to_top(cx);
4487 });
4488 }
4489 })
4490 };
4491
4492 let open_thread_as_markdown = ContextMenuEntry::new("Open Thread as Markdown")
4493 .handler({
4494 let entity = entity.clone();
4495 let workspace = workspace.clone();
4496 move |window, cx| {
4497 if let Some(workspace) = workspace.upgrade() {
4498 entity
4499 .update(cx, |this, cx| {
4500 this.open_thread_as_markdown(workspace, window, cx)
4501 })
4502 .detach_and_log_err(cx);
4503 }
4504 }
4505 });
4506
4507 menu.when_some(focus, |menu, focus| menu.context(focus))
4508 .action_disabled_when(
4509 !has_selection,
4510 "Copy Selection",
4511 Box::new(markdown::CopyAsMarkdown),
4512 )
4513 .item(copy_this_agent_response)
4514 .separator()
4515 .item(scroll_item)
4516 .item(open_thread_as_markdown)
4517 })
4518 })
4519 .into_any_element()
4520 }
4521
4522 fn get_agent_message_content(
4523 entries: &[AgentThreadEntry],
4524 entry_index: usize,
4525 cx: &App,
4526 ) -> Option<String> {
4527 let entry = entries.get(entry_index)?;
4528 if matches!(entry, AgentThreadEntry::UserMessage(_)) {
4529 return None;
4530 }
4531
4532 let start_index = (0..entry_index)
4533 .rev()
4534 .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
4535 .map(|i| i + 1)
4536 .unwrap_or(0);
4537
4538 let end_index = (entry_index + 1..entries.len())
4539 .find(|&i| matches!(entries.get(i), Some(AgentThreadEntry::UserMessage(_))))
4540 .map(|i| i - 1)
4541 .unwrap_or(entries.len() - 1);
4542
4543 let parts: Vec<String> = (start_index..=end_index)
4544 .filter_map(|i| entries.get(i))
4545 .filter_map(|entry| {
4546 if let AgentThreadEntry::AssistantMessage(message) = entry {
4547 let text: String = message
4548 .chunks
4549 .iter()
4550 .filter_map(|chunk| match chunk {
4551 AssistantMessageChunk::Message { block } => {
4552 let markdown = block.to_markdown(cx);
4553 if markdown.trim().is_empty() {
4554 None
4555 } else {
4556 Some(markdown.to_string())
4557 }
4558 }
4559 AssistantMessageChunk::Thought { .. } => None,
4560 })
4561 .collect::<Vec<_>>()
4562 .join("\n\n");
4563
4564 if text.is_empty() { None } else { Some(text) }
4565 } else {
4566 None
4567 }
4568 })
4569 .collect();
4570
4571 let text = parts.join("\n\n");
4572 if text.is_empty() { None } else { Some(text) }
4573 }
4574
4575 fn render_collapsible_command(
4576 &self,
4577 is_preview: bool,
4578 command_source: &str,
4579 tool_call_id: &acp::ToolCallId,
4580 cx: &Context<Self>,
4581 ) -> Div {
4582 let command_group =
4583 SharedString::from(format!("collapsible-command-group-{}", tool_call_id));
4584
4585 v_flex()
4586 .group(command_group.clone())
4587 .bg(self.tool_card_header_bg(cx))
4588 .child(
4589 v_flex()
4590 .p_1p5()
4591 .when(is_preview, |this| {
4592 this.pt_1().child(
4593 // Wrapping this label on a container with 24px height to avoid
4594 // layout shift when it changes from being a preview label
4595 // to the actual path where the command will run in
4596 h_flex().h_6().child(
4597 Label::new("Run Command")
4598 .buffer_font(cx)
4599 .size(LabelSize::XSmall)
4600 .color(Color::Muted),
4601 ),
4602 )
4603 })
4604 .children(command_source.lines().map(|line| {
4605 let text: SharedString = if line.is_empty() {
4606 " ".into()
4607 } else {
4608 line.to_string().into()
4609 };
4610
4611 Label::new(text).buffer_font(cx).size(LabelSize::Small)
4612 }))
4613 .child(
4614 div().absolute().top_1().right_1().child(
4615 CopyButton::new("copy-command", command_source.to_string())
4616 .tooltip_label("Copy Command")
4617 .visible_on_hover(command_group),
4618 ),
4619 ),
4620 )
4621 }
4622
4623 fn render_terminal_tool_call(
4624 &self,
4625 active_session_id: &acp::SessionId,
4626 entry_ix: usize,
4627 terminal: &Entity<acp_thread::Terminal>,
4628 tool_call: &ToolCall,
4629 focus_handle: &FocusHandle,
4630 window: &Window,
4631 cx: &Context<Self>,
4632 ) -> AnyElement {
4633 let terminal_data = terminal.read(cx);
4634 let working_dir = terminal_data.working_dir();
4635 let command = terminal_data.command();
4636 let started_at = terminal_data.started_at();
4637
4638 let tool_failed = matches!(
4639 &tool_call.status,
4640 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed
4641 );
4642
4643 let confirmation_options = match &tool_call.status {
4644 ToolCallStatus::WaitingForConfirmation { options, .. } => Some(options),
4645 _ => None,
4646 };
4647 let needs_confirmation = confirmation_options.is_some();
4648
4649 let output = terminal_data.output();
4650 let command_finished = output.is_some();
4651 let truncated_output =
4652 output.is_some_and(|output| output.original_content_len > output.content.len());
4653 let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
4654
4655 let command_failed = command_finished
4656 && output.is_some_and(|o| o.exit_status.is_some_and(|status| !status.success()));
4657
4658 let time_elapsed = if let Some(output) = output {
4659 output.ended_at.duration_since(started_at)
4660 } else {
4661 started_at.elapsed()
4662 };
4663
4664 let header_id =
4665 SharedString::from(format!("terminal-tool-header-{}", terminal.entity_id()));
4666 let header_group = SharedString::from(format!(
4667 "terminal-tool-header-group-{}",
4668 terminal.entity_id()
4669 ));
4670 let header_bg = cx
4671 .theme()
4672 .colors()
4673 .element_background
4674 .blend(cx.theme().colors().editor_foreground.opacity(0.025));
4675 let border_color = cx.theme().colors().border.opacity(0.6);
4676
4677 let working_dir = working_dir
4678 .as_ref()
4679 .map(|path| path.display().to_string())
4680 .unwrap_or_else(|| "current directory".to_string());
4681
4682 // Since the command's source is wrapped in a markdown code block
4683 // (```\n...\n```), we need to strip that so we're left with only the
4684 // command's content.
4685 let command_source = command.read(cx).source();
4686 let command_content = command_source
4687 .strip_prefix("```\n")
4688 .and_then(|s| s.strip_suffix("\n```"))
4689 .unwrap_or(&command_source);
4690
4691 let command_element =
4692 self.render_collapsible_command(false, command_content, &tool_call.id, cx);
4693
4694 let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
4695
4696 let header = h_flex()
4697 .id(header_id)
4698 .px_1p5()
4699 .pt_1()
4700 .flex_none()
4701 .gap_1()
4702 .justify_between()
4703 .rounded_t_md()
4704 .child(
4705 div()
4706 .id(("command-target-path", terminal.entity_id()))
4707 .w_full()
4708 .max_w_full()
4709 .overflow_x_scroll()
4710 .child(
4711 Label::new(working_dir)
4712 .buffer_font(cx)
4713 .size(LabelSize::XSmall)
4714 .color(Color::Muted),
4715 ),
4716 )
4717 .when(!command_finished && !needs_confirmation, |header| {
4718 header
4719 .gap_1p5()
4720 .child(
4721 Button::new(
4722 SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
4723 "Stop",
4724 )
4725 .icon(IconName::Stop)
4726 .icon_position(IconPosition::Start)
4727 .icon_size(IconSize::Small)
4728 .icon_color(Color::Error)
4729 .label_size(LabelSize::Small)
4730 .tooltip(move |_window, cx| {
4731 Tooltip::with_meta(
4732 "Stop This Command",
4733 None,
4734 "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
4735 cx,
4736 )
4737 })
4738 .on_click({
4739 let terminal = terminal.clone();
4740 cx.listener(move |this, _event, _window, cx| {
4741 terminal.update(cx, |terminal, cx| {
4742 terminal.stop_by_user(cx);
4743 });
4744 if AgentSettings::get_global(cx).cancel_generation_on_terminal_stop {
4745 this.cancel_generation(cx);
4746 }
4747 })
4748 }),
4749 )
4750 .child(Divider::vertical())
4751 .child(
4752 Icon::new(IconName::ArrowCircle)
4753 .size(IconSize::XSmall)
4754 .color(Color::Info)
4755 .with_rotate_animation(2)
4756 )
4757 })
4758 .when(truncated_output, |header| {
4759 let tooltip = if let Some(output) = output {
4760 if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
4761 format!("Output exceeded terminal max lines and was \
4762 truncated, the model received the first {}.", format_file_size(output.content.len() as u64, true))
4763 } else {
4764 format!(
4765 "Output is {} long, and to avoid unexpected token usage, \
4766 only {} was sent back to the agent.",
4767 format_file_size(output.original_content_len as u64, true),
4768 format_file_size(output.content.len() as u64, true)
4769 )
4770 }
4771 } else {
4772 "Output was truncated".to_string()
4773 };
4774
4775 header.child(
4776 h_flex()
4777 .id(("terminal-tool-truncated-label", terminal.entity_id()))
4778 .gap_1()
4779 .child(
4780 Icon::new(IconName::Info)
4781 .size(IconSize::XSmall)
4782 .color(Color::Ignored),
4783 )
4784 .child(
4785 Label::new("Truncated")
4786 .color(Color::Muted)
4787 .size(LabelSize::XSmall),
4788 )
4789 .tooltip(Tooltip::text(tooltip)),
4790 )
4791 })
4792 .when(time_elapsed > Duration::from_secs(10), |header| {
4793 header.child(
4794 Label::new(format!("({})", duration_alt_display(time_elapsed)))
4795 .buffer_font(cx)
4796 .color(Color::Muted)
4797 .size(LabelSize::XSmall),
4798 )
4799 })
4800 .when(tool_failed || command_failed, |header| {
4801 header.child(
4802 div()
4803 .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
4804 .child(
4805 Icon::new(IconName::Close)
4806 .size(IconSize::Small)
4807 .color(Color::Error),
4808 )
4809 .when_some(output.and_then(|o| o.exit_status), |this, status| {
4810 this.tooltip(Tooltip::text(format!(
4811 "Exited with code {}",
4812 status.code().unwrap_or(-1),
4813 )))
4814 }),
4815 )
4816 })
4817 .child(
4818 Disclosure::new(
4819 SharedString::from(format!(
4820 "terminal-tool-disclosure-{}",
4821 terminal.entity_id()
4822 )),
4823 is_expanded,
4824 )
4825 .opened_icon(IconName::ChevronUp)
4826 .closed_icon(IconName::ChevronDown)
4827 .visible_on_hover(&header_group)
4828 .on_click(cx.listener({
4829 let id = tool_call.id.clone();
4830 move |this, _event, _window, cx| {
4831 if is_expanded {
4832 this.expanded_tool_calls.remove(&id);
4833 } else {
4834 this.expanded_tool_calls.insert(id.clone());
4835 }
4836 cx.notify();
4837 }
4838 })),
4839 );
4840
4841 let terminal_view = self
4842 .entry_view_state
4843 .read(cx)
4844 .entry(entry_ix)
4845 .and_then(|entry| entry.terminal(terminal));
4846
4847 v_flex()
4848 .my_1p5()
4849 .mx_5()
4850 .border_1()
4851 .when(tool_failed || command_failed, |card| card.border_dashed())
4852 .border_color(border_color)
4853 .rounded_md()
4854 .overflow_hidden()
4855 .child(
4856 v_flex()
4857 .group(&header_group)
4858 .bg(header_bg)
4859 .text_xs()
4860 .child(header)
4861 .child(command_element),
4862 )
4863 .when(is_expanded && terminal_view.is_some(), |this| {
4864 this.child(
4865 div()
4866 .pt_2()
4867 .border_t_1()
4868 .when(tool_failed || command_failed, |card| card.border_dashed())
4869 .border_color(border_color)
4870 .bg(cx.theme().colors().editor_background)
4871 .rounded_b_md()
4872 .text_ui_sm(cx)
4873 .h_full()
4874 .children(terminal_view.map(|terminal_view| {
4875 let element = if terminal_view
4876 .read(cx)
4877 .content_mode(window, cx)
4878 .is_scrollable()
4879 {
4880 div().h_72().child(terminal_view).into_any_element()
4881 } else {
4882 terminal_view.into_any_element()
4883 };
4884
4885 div()
4886 .on_action(cx.listener(|_this, _: &NewTerminal, window, cx| {
4887 window.dispatch_action(NewThread.boxed_clone(), cx);
4888 cx.stop_propagation();
4889 }))
4890 .child(element)
4891 .into_any_element()
4892 })),
4893 )
4894 })
4895 .when_some(confirmation_options, |this, options| {
4896 let is_first = self.is_first_tool_call(active_session_id, &tool_call.id, cx);
4897 this.child(self.render_permission_buttons(
4898 self.id.clone(),
4899 is_first,
4900 options,
4901 entry_ix,
4902 tool_call.id.clone(),
4903 focus_handle,
4904 cx,
4905 ))
4906 })
4907 .into_any()
4908 }
4909
4910 fn is_first_tool_call(
4911 &self,
4912 active_session_id: &acp::SessionId,
4913 tool_call_id: &acp::ToolCallId,
4914 cx: &App,
4915 ) -> bool {
4916 self.conversation
4917 .read(cx)
4918 .pending_tool_call(active_session_id, cx)
4919 .map_or(false, |(pending_session_id, pending_tool_call_id, _)| {
4920 self.id == pending_session_id && tool_call_id == &pending_tool_call_id
4921 })
4922 }
4923
4924 fn render_any_tool_call(
4925 &self,
4926 active_session_id: &acp::SessionId,
4927 entry_ix: usize,
4928 tool_call: &ToolCall,
4929 focus_handle: &FocusHandle,
4930 window: &Window,
4931 cx: &Context<Self>,
4932 ) -> Div {
4933 let has_terminals = tool_call.terminals().next().is_some();
4934
4935 div().w_full().map(|this| {
4936 if tool_call.is_subagent() {
4937 this.child(self.render_subagent_tool_call(
4938 active_session_id,
4939 entry_ix,
4940 tool_call,
4941 tool_call.subagent_session_id.clone(),
4942 focus_handle,
4943 window,
4944 cx,
4945 ))
4946 } else if has_terminals {
4947 this.children(tool_call.terminals().map(|terminal| {
4948 self.render_terminal_tool_call(
4949 active_session_id,
4950 entry_ix,
4951 terminal,
4952 tool_call,
4953 focus_handle,
4954 window,
4955 cx,
4956 )
4957 }))
4958 } else {
4959 this.child(self.render_tool_call(
4960 active_session_id,
4961 entry_ix,
4962 tool_call,
4963 focus_handle,
4964 window,
4965 cx,
4966 ))
4967 }
4968 })
4969 }
4970
4971 fn render_tool_call(
4972 &self,
4973 active_session_id: &acp::SessionId,
4974 entry_ix: usize,
4975 tool_call: &ToolCall,
4976 focus_handle: &FocusHandle,
4977 window: &Window,
4978 cx: &Context<Self>,
4979 ) -> Div {
4980 let has_location = tool_call.locations.len() == 1;
4981 let card_header_id = SharedString::from("inner-tool-call-header");
4982
4983 let failed_or_canceled = match &tool_call.status {
4984 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed => true,
4985 _ => false,
4986 };
4987
4988 let needs_confirmation = matches!(
4989 tool_call.status,
4990 ToolCallStatus::WaitingForConfirmation { .. }
4991 );
4992 let is_terminal_tool = matches!(tool_call.kind, acp::ToolKind::Execute);
4993
4994 let is_edit =
4995 matches!(tool_call.kind, acp::ToolKind::Edit) || tool_call.diffs().next().is_some();
4996
4997 let is_cancelled_edit = is_edit && matches!(tool_call.status, ToolCallStatus::Canceled);
4998 let has_revealed_diff = tool_call.diffs().next().is_some_and(|diff| {
4999 self.entry_view_state
5000 .read(cx)
5001 .entry(entry_ix)
5002 .and_then(|entry| entry.editor_for_diff(diff))
5003 .is_some()
5004 && diff.read(cx).has_revealed_range(cx)
5005 });
5006
5007 let use_card_layout = needs_confirmation || is_edit || is_terminal_tool;
5008
5009 let has_image_content = tool_call.content.iter().any(|c| c.image().is_some());
5010 let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
5011 let mut is_open = self.expanded_tool_calls.contains(&tool_call.id);
5012
5013 is_open |= needs_confirmation;
5014
5015 let should_show_raw_input = !is_terminal_tool && !is_edit && !has_image_content;
5016
5017 let input_output_header = |label: SharedString| {
5018 Label::new(label)
5019 .size(LabelSize::XSmall)
5020 .color(Color::Muted)
5021 .buffer_font(cx)
5022 };
5023
5024 let tool_output_display = if is_open {
5025 match &tool_call.status {
5026 ToolCallStatus::WaitingForConfirmation { options, .. } => v_flex()
5027 .w_full()
5028 .children(
5029 tool_call
5030 .content
5031 .iter()
5032 .enumerate()
5033 .map(|(content_ix, content)| {
5034 div()
5035 .child(self.render_tool_call_content(
5036 active_session_id,
5037 entry_ix,
5038 content,
5039 content_ix,
5040 tool_call,
5041 use_card_layout,
5042 has_image_content,
5043 failed_or_canceled,
5044 focus_handle,
5045 window,
5046 cx,
5047 ))
5048 .into_any_element()
5049 }),
5050 )
5051 .when(should_show_raw_input, |this| {
5052 let is_raw_input_expanded =
5053 self.expanded_tool_call_raw_inputs.contains(&tool_call.id);
5054
5055 let input_header = if is_raw_input_expanded {
5056 "Raw Input:"
5057 } else {
5058 "View Raw Input"
5059 };
5060
5061 this.child(
5062 v_flex()
5063 .p_2()
5064 .gap_1()
5065 .border_t_1()
5066 .border_color(self.tool_card_border_color(cx))
5067 .child(
5068 h_flex()
5069 .id("disclosure_container")
5070 .pl_0p5()
5071 .gap_1()
5072 .justify_between()
5073 .rounded_xs()
5074 .hover(|s| s.bg(cx.theme().colors().element_hover))
5075 .child(input_output_header(input_header.into()))
5076 .child(
5077 Disclosure::new(
5078 ("raw-input-disclosure", entry_ix),
5079 is_raw_input_expanded,
5080 )
5081 .opened_icon(IconName::ChevronUp)
5082 .closed_icon(IconName::ChevronDown),
5083 )
5084 .on_click(cx.listener({
5085 let id = tool_call.id.clone();
5086
5087 move |this: &mut Self, _, _, cx| {
5088 if this.expanded_tool_call_raw_inputs.contains(&id)
5089 {
5090 this.expanded_tool_call_raw_inputs.remove(&id);
5091 } else {
5092 this.expanded_tool_call_raw_inputs
5093 .insert(id.clone());
5094 }
5095 cx.notify();
5096 }
5097 })),
5098 )
5099 .when(is_raw_input_expanded, |this| {
5100 this.children(tool_call.raw_input_markdown.clone().map(
5101 |input| {
5102 self.render_markdown(
5103 input,
5104 MarkdownStyle::themed(
5105 MarkdownFont::Agent,
5106 window,
5107 cx,
5108 ),
5109 )
5110 },
5111 ))
5112 }),
5113 )
5114 })
5115 .child(self.render_permission_buttons(
5116 self.id.clone(),
5117 self.is_first_tool_call(active_session_id, &tool_call.id, cx),
5118 options,
5119 entry_ix,
5120 tool_call.id.clone(),
5121 focus_handle,
5122 cx,
5123 ))
5124 .into_any(),
5125 ToolCallStatus::Pending | ToolCallStatus::InProgress
5126 if is_edit
5127 && tool_call.content.is_empty()
5128 && self.as_native_connection(cx).is_some() =>
5129 {
5130 self.render_diff_loading(cx)
5131 }
5132 ToolCallStatus::Pending
5133 | ToolCallStatus::InProgress
5134 | ToolCallStatus::Completed
5135 | ToolCallStatus::Failed
5136 | ToolCallStatus::Canceled => v_flex()
5137 .when(should_show_raw_input, |this| {
5138 this.mt_1p5().w_full().child(
5139 v_flex()
5140 .ml(rems(0.4))
5141 .px_3p5()
5142 .pb_1()
5143 .gap_1()
5144 .border_l_1()
5145 .border_color(self.tool_card_border_color(cx))
5146 .child(input_output_header("Raw Input:".into()))
5147 .children(tool_call.raw_input_markdown.clone().map(|input| {
5148 div().id(("tool-call-raw-input-markdown", entry_ix)).child(
5149 self.render_markdown(
5150 input,
5151 MarkdownStyle::themed(MarkdownFont::Agent, window, cx),
5152 ),
5153 )
5154 }))
5155 .child(input_output_header("Output:".into())),
5156 )
5157 })
5158 .children(
5159 tool_call
5160 .content
5161 .iter()
5162 .enumerate()
5163 .map(|(content_ix, content)| {
5164 div().id(("tool-call-output", entry_ix)).child(
5165 self.render_tool_call_content(
5166 active_session_id,
5167 entry_ix,
5168 content,
5169 content_ix,
5170 tool_call,
5171 use_card_layout,
5172 has_image_content,
5173 failed_or_canceled,
5174 focus_handle,
5175 window,
5176 cx,
5177 ),
5178 )
5179 }),
5180 )
5181 .into_any(),
5182 ToolCallStatus::Rejected => Empty.into_any(),
5183 }
5184 .into()
5185 } else {
5186 None
5187 };
5188
5189 v_flex()
5190 .map(|this| {
5191 if use_card_layout {
5192 this.my_1p5()
5193 .rounded_md()
5194 .border_1()
5195 .when(failed_or_canceled, |this| this.border_dashed())
5196 .border_color(self.tool_card_border_color(cx))
5197 .bg(cx.theme().colors().editor_background)
5198 .overflow_hidden()
5199 } else {
5200 this.my_1()
5201 }
5202 })
5203 .map(|this| {
5204 if has_location && !use_card_layout {
5205 this.ml_4()
5206 } else {
5207 this.ml_5()
5208 }
5209 })
5210 .mr_5()
5211 .map(|this| {
5212 if is_terminal_tool {
5213 let label_source = tool_call.label.read(cx).source();
5214 this.child(self.render_collapsible_command(true, label_source, &tool_call.id, cx))
5215 } else {
5216 this.child(
5217 h_flex()
5218 .group(&card_header_id)
5219 .relative()
5220 .w_full()
5221 .gap_1()
5222 .justify_between()
5223 .when(use_card_layout, |this| {
5224 this.p_0p5()
5225 .rounded_t(rems_from_px(5.))
5226 .bg(self.tool_card_header_bg(cx))
5227 })
5228 .child(self.render_tool_call_label(
5229 entry_ix,
5230 tool_call,
5231 is_edit,
5232 is_cancelled_edit,
5233 has_revealed_diff,
5234 use_card_layout,
5235 window,
5236 cx,
5237 ))
5238 .when(is_collapsible || failed_or_canceled, |this| {
5239 let diff_for_discard =
5240 if has_revealed_diff && is_cancelled_edit && cx.has_flag::<AgentV2FeatureFlag>() {
5241 tool_call.diffs().next().cloned()
5242 } else {
5243 None
5244 };
5245 this.child(
5246 h_flex()
5247 .px_1()
5248 .when_some(diff_for_discard.clone(), |this, _| this.pr_0p5())
5249 .gap_1()
5250 .when(is_collapsible, |this| {
5251 this.child(
5252 Disclosure::new(("expand-output", entry_ix), is_open)
5253 .opened_icon(IconName::ChevronUp)
5254 .closed_icon(IconName::ChevronDown)
5255 .visible_on_hover(&card_header_id)
5256 .on_click(cx.listener({
5257 let id = tool_call.id.clone();
5258 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
5259 if is_open {
5260 this
5261 .expanded_tool_calls.remove(&id);
5262 } else {
5263 this.expanded_tool_calls.insert(id.clone());
5264 }
5265 cx.notify();
5266 }
5267 })),
5268 )
5269 })
5270 .when(failed_or_canceled, |this| {
5271 if is_cancelled_edit && !has_revealed_diff {
5272 this.child(
5273 div()
5274 .id(entry_ix)
5275 .tooltip(Tooltip::text(
5276 "Interrupted Edit",
5277 ))
5278 .child(
5279 Icon::new(IconName::XCircle)
5280 .color(Color::Muted)
5281 .size(IconSize::Small),
5282 ),
5283 )
5284 } else if is_cancelled_edit {
5285 this
5286 } else {
5287 this.child(
5288 Icon::new(IconName::Close)
5289 .color(Color::Error)
5290 .size(IconSize::Small),
5291 )
5292 }
5293 })
5294 .when_some(diff_for_discard, |this, diff| {
5295 let tool_call_id = tool_call.id.clone();
5296 let is_discarded = self.discarded_partial_edits.contains(&tool_call_id);
5297 this.when(!is_discarded, |this| {
5298 this.child(
5299 IconButton::new(
5300 ("discard-partial-edit", entry_ix),
5301 IconName::Undo,
5302 )
5303 .icon_size(IconSize::Small)
5304 .tooltip(move |_, cx| Tooltip::with_meta(
5305 "Discard Interrupted Edit",
5306 None,
5307 "You can discard this interrupted partial edit and restore the original file content.",
5308 cx
5309 ))
5310 .on_click(cx.listener({
5311 let tool_call_id = tool_call_id.clone();
5312 move |this, _, _window, cx| {
5313 let diff_data = diff.read(cx);
5314 let base_text = diff_data.base_text().clone();
5315 let buffer = diff_data.buffer().clone();
5316 buffer.update(cx, |buffer, cx| {
5317 buffer.set_text(base_text.as_ref(), cx);
5318 });
5319 this.discarded_partial_edits.insert(tool_call_id.clone());
5320 cx.notify();
5321 }
5322 })),
5323 )
5324 })
5325 })
5326
5327 )
5328 }),
5329 )
5330 }
5331 })
5332 .children(tool_output_display)
5333 }
5334
5335 fn render_permission_buttons(
5336 &self,
5337 session_id: acp::SessionId,
5338 is_first: bool,
5339 options: &PermissionOptions,
5340 entry_ix: usize,
5341 tool_call_id: acp::ToolCallId,
5342 focus_handle: &FocusHandle,
5343 cx: &Context<Self>,
5344 ) -> Div {
5345 match options {
5346 PermissionOptions::Flat(options) => self.render_permission_buttons_flat(
5347 session_id,
5348 is_first,
5349 options,
5350 entry_ix,
5351 tool_call_id,
5352 focus_handle,
5353 cx,
5354 ),
5355 PermissionOptions::Dropdown(options) => self.render_permission_buttons_dropdown(
5356 session_id,
5357 is_first,
5358 options,
5359 entry_ix,
5360 tool_call_id,
5361 focus_handle,
5362 cx,
5363 ),
5364 }
5365 }
5366
5367 fn render_permission_buttons_dropdown(
5368 &self,
5369 session_id: acp::SessionId,
5370 is_first: bool,
5371 choices: &[PermissionOptionChoice],
5372 entry_ix: usize,
5373 tool_call_id: acp::ToolCallId,
5374 focus_handle: &FocusHandle,
5375 cx: &Context<Self>,
5376 ) -> Div {
5377 // Get the selected granularity index, defaulting to the last option ("Only this time")
5378 let selected_index = self
5379 .selected_permission_granularity
5380 .get(&tool_call_id)
5381 .copied()
5382 .unwrap_or_else(|| choices.len().saturating_sub(1));
5383
5384 let selected_choice = choices.get(selected_index).or(choices.last());
5385
5386 let dropdown_label: SharedString = selected_choice
5387 .map(|choice| choice.label())
5388 .unwrap_or_else(|| "Only this time".into());
5389
5390 let (allow_option_id, allow_option_kind, deny_option_id, deny_option_kind) =
5391 if let Some(choice) = selected_choice {
5392 (
5393 choice.allow.option_id.clone(),
5394 choice.allow.kind,
5395 choice.deny.option_id.clone(),
5396 choice.deny.kind,
5397 )
5398 } else {
5399 (
5400 acp::PermissionOptionId::new("allow"),
5401 acp::PermissionOptionKind::AllowOnce,
5402 acp::PermissionOptionId::new("deny"),
5403 acp::PermissionOptionKind::RejectOnce,
5404 )
5405 };
5406
5407 h_flex()
5408 .w_full()
5409 .p_1()
5410 .gap_2()
5411 .justify_between()
5412 .border_t_1()
5413 .border_color(self.tool_card_border_color(cx))
5414 .child(
5415 h_flex()
5416 .gap_0p5()
5417 .child(
5418 Button::new(("allow-btn", entry_ix), "Allow")
5419 .icon(IconName::Check)
5420 .icon_color(Color::Success)
5421 .icon_position(IconPosition::Start)
5422 .icon_size(IconSize::XSmall)
5423 .label_size(LabelSize::Small)
5424 .when(is_first, |this| {
5425 this.key_binding(
5426 KeyBinding::for_action_in(
5427 &AllowOnce as &dyn Action,
5428 focus_handle,
5429 cx,
5430 )
5431 .map(|kb| kb.size(rems_from_px(10.))),
5432 )
5433 })
5434 .on_click(cx.listener({
5435 let session_id = session_id.clone();
5436 let tool_call_id = tool_call_id.clone();
5437 let option_id = allow_option_id;
5438 let option_kind = allow_option_kind;
5439 move |this, _, window, cx| {
5440 this.authorize_tool_call(
5441 session_id.clone(),
5442 tool_call_id.clone(),
5443 option_id.clone(),
5444 option_kind,
5445 window,
5446 cx,
5447 );
5448 }
5449 })),
5450 )
5451 .child(
5452 Button::new(("deny-btn", entry_ix), "Deny")
5453 .icon(IconName::Close)
5454 .icon_color(Color::Error)
5455 .icon_position(IconPosition::Start)
5456 .icon_size(IconSize::XSmall)
5457 .label_size(LabelSize::Small)
5458 .when(is_first, |this| {
5459 this.key_binding(
5460 KeyBinding::for_action_in(
5461 &RejectOnce as &dyn Action,
5462 focus_handle,
5463 cx,
5464 )
5465 .map(|kb| kb.size(rems_from_px(10.))),
5466 )
5467 })
5468 .on_click(cx.listener({
5469 let tool_call_id = tool_call_id.clone();
5470 let option_id = deny_option_id;
5471 let option_kind = deny_option_kind;
5472 move |this, _, window, cx| {
5473 this.authorize_tool_call(
5474 session_id.clone(),
5475 tool_call_id.clone(),
5476 option_id.clone(),
5477 option_kind,
5478 window,
5479 cx,
5480 );
5481 }
5482 })),
5483 ),
5484 )
5485 .child(self.render_permission_granularity_dropdown(
5486 choices,
5487 dropdown_label,
5488 entry_ix,
5489 tool_call_id,
5490 selected_index,
5491 is_first,
5492 cx,
5493 ))
5494 }
5495
5496 fn render_permission_granularity_dropdown(
5497 &self,
5498 choices: &[PermissionOptionChoice],
5499 current_label: SharedString,
5500 entry_ix: usize,
5501 tool_call_id: acp::ToolCallId,
5502 selected_index: usize,
5503 is_first: bool,
5504 cx: &Context<Self>,
5505 ) -> AnyElement {
5506 let menu_options: Vec<(usize, SharedString)> = choices
5507 .iter()
5508 .enumerate()
5509 .map(|(i, choice)| (i, choice.label()))
5510 .collect();
5511
5512 let permission_dropdown_handle = self.permission_dropdown_handle.clone();
5513
5514 PopoverMenu::new(("permission-granularity", entry_ix))
5515 .with_handle(permission_dropdown_handle)
5516 .trigger(
5517 Button::new(("granularity-trigger", entry_ix), current_label)
5518 .icon(IconName::ChevronDown)
5519 .icon_size(IconSize::XSmall)
5520 .icon_color(Color::Muted)
5521 .label_size(LabelSize::Small)
5522 .when(is_first, |this| {
5523 this.key_binding(
5524 KeyBinding::for_action_in(
5525 &crate::OpenPermissionDropdown as &dyn Action,
5526 &self.focus_handle(cx),
5527 cx,
5528 )
5529 .map(|kb| kb.size(rems_from_px(10.))),
5530 )
5531 }),
5532 )
5533 .menu(move |window, cx| {
5534 let tool_call_id = tool_call_id.clone();
5535 let options = menu_options.clone();
5536
5537 Some(ContextMenu::build(window, cx, move |mut menu, _, _| {
5538 for (index, display_name) in options.iter() {
5539 let display_name = display_name.clone();
5540 let index = *index;
5541 let tool_call_id_for_entry = tool_call_id.clone();
5542 let is_selected = index == selected_index;
5543
5544 menu = menu.toggleable_entry(
5545 display_name,
5546 is_selected,
5547 IconPosition::End,
5548 None,
5549 move |window, cx| {
5550 window.dispatch_action(
5551 SelectPermissionGranularity {
5552 tool_call_id: tool_call_id_for_entry.0.to_string(),
5553 index,
5554 }
5555 .boxed_clone(),
5556 cx,
5557 );
5558 },
5559 );
5560 }
5561
5562 menu
5563 }))
5564 })
5565 .into_any_element()
5566 }
5567
5568 fn render_permission_buttons_flat(
5569 &self,
5570 session_id: acp::SessionId,
5571 is_first: bool,
5572 options: &[acp::PermissionOption],
5573 entry_ix: usize,
5574 tool_call_id: acp::ToolCallId,
5575 focus_handle: &FocusHandle,
5576 cx: &Context<Self>,
5577 ) -> Div {
5578 let mut seen_kinds: ArrayVec<acp::PermissionOptionKind, 3> = ArrayVec::new();
5579
5580 div()
5581 .p_1()
5582 .border_t_1()
5583 .border_color(self.tool_card_border_color(cx))
5584 .w_full()
5585 .v_flex()
5586 .gap_0p5()
5587 .children(options.iter().map(move |option| {
5588 let option_id = SharedString::from(option.option_id.0.clone());
5589 Button::new((option_id, entry_ix), option.name.clone())
5590 .map(|this| {
5591 let (this, action) = match option.kind {
5592 acp::PermissionOptionKind::AllowOnce => (
5593 this.icon(IconName::Check).icon_color(Color::Success),
5594 Some(&AllowOnce as &dyn Action),
5595 ),
5596 acp::PermissionOptionKind::AllowAlways => (
5597 this.icon(IconName::CheckDouble).icon_color(Color::Success),
5598 Some(&AllowAlways as &dyn Action),
5599 ),
5600 acp::PermissionOptionKind::RejectOnce => (
5601 this.icon(IconName::Close).icon_color(Color::Error),
5602 Some(&RejectOnce as &dyn Action),
5603 ),
5604 acp::PermissionOptionKind::RejectAlways | _ => {
5605 (this.icon(IconName::Close).icon_color(Color::Error), None)
5606 }
5607 };
5608
5609 let Some(action) = action else {
5610 return this;
5611 };
5612
5613 if !is_first || seen_kinds.contains(&option.kind) {
5614 return this;
5615 }
5616
5617 seen_kinds.push(option.kind);
5618
5619 this.key_binding(
5620 KeyBinding::for_action_in(action, focus_handle, cx)
5621 .map(|kb| kb.size(rems_from_px(10.))),
5622 )
5623 })
5624 .icon_position(IconPosition::Start)
5625 .icon_size(IconSize::XSmall)
5626 .label_size(LabelSize::Small)
5627 .on_click(cx.listener({
5628 let session_id = session_id.clone();
5629 let tool_call_id = tool_call_id.clone();
5630 let option_id = option.option_id.clone();
5631 let option_kind = option.kind;
5632 move |this, _, window, cx| {
5633 this.authorize_tool_call(
5634 session_id.clone(),
5635 tool_call_id.clone(),
5636 option_id.clone(),
5637 option_kind,
5638 window,
5639 cx,
5640 );
5641 }
5642 }))
5643 }))
5644 }
5645
5646 fn render_diff_loading(&self, cx: &Context<Self>) -> AnyElement {
5647 let bar = |n: u64, width_class: &str| {
5648 let bg_color = cx.theme().colors().element_active;
5649 let base = h_flex().h_1().rounded_full();
5650
5651 let modified = match width_class {
5652 "w_4_5" => base.w_3_4(),
5653 "w_1_4" => base.w_1_4(),
5654 "w_2_4" => base.w_2_4(),
5655 "w_3_5" => base.w_3_5(),
5656 "w_2_5" => base.w_2_5(),
5657 _ => base.w_1_2(),
5658 };
5659
5660 modified.with_animation(
5661 ElementId::Integer(n),
5662 Animation::new(Duration::from_secs(2)).repeat(),
5663 move |tab, delta| {
5664 let delta = (delta - 0.15 * n as f32) / 0.7;
5665 let delta = 1.0 - (0.5 - delta).abs() * 2.;
5666 let delta = ease_in_out(delta.clamp(0., 1.));
5667 let delta = 0.1 + 0.9 * delta;
5668
5669 tab.bg(bg_color.opacity(delta))
5670 },
5671 )
5672 };
5673
5674 v_flex()
5675 .p_3()
5676 .gap_1()
5677 .rounded_b_md()
5678 .bg(cx.theme().colors().editor_background)
5679 .child(bar(0, "w_4_5"))
5680 .child(bar(1, "w_1_4"))
5681 .child(bar(2, "w_2_4"))
5682 .child(bar(3, "w_3_5"))
5683 .child(bar(4, "w_2_5"))
5684 .into_any_element()
5685 }
5686
5687 fn render_tool_call_label(
5688 &self,
5689 entry_ix: usize,
5690 tool_call: &ToolCall,
5691 is_edit: bool,
5692 has_failed: bool,
5693 has_revealed_diff: bool,
5694 use_card_layout: bool,
5695 window: &Window,
5696 cx: &Context<Self>,
5697 ) -> Div {
5698 let has_location = tool_call.locations.len() == 1;
5699 let is_file = tool_call.kind == acp::ToolKind::Edit && has_location;
5700 let is_subagent_tool_call = tool_call.is_subagent();
5701
5702 let file_icon = if has_location {
5703 FileIcons::get_icon(&tool_call.locations[0].path, cx)
5704 .map(Icon::from_path)
5705 .unwrap_or(Icon::new(IconName::ToolPencil))
5706 } else {
5707 Icon::new(IconName::ToolPencil)
5708 };
5709
5710 let tool_icon = if is_file && has_failed && has_revealed_diff {
5711 div()
5712 .id(entry_ix)
5713 .tooltip(Tooltip::text("Interrupted Edit"))
5714 .child(DecoratedIcon::new(
5715 file_icon,
5716 Some(
5717 IconDecoration::new(
5718 IconDecorationKind::Triangle,
5719 self.tool_card_header_bg(cx),
5720 cx,
5721 )
5722 .color(cx.theme().status().warning)
5723 .position(gpui::Point {
5724 x: px(-2.),
5725 y: px(-2.),
5726 }),
5727 ),
5728 ))
5729 .into_any_element()
5730 } else if is_file {
5731 div().child(file_icon).into_any_element()
5732 } else if is_subagent_tool_call {
5733 Icon::new(self.agent_icon)
5734 .size(IconSize::Small)
5735 .color(Color::Muted)
5736 .into_any_element()
5737 } else {
5738 Icon::new(match tool_call.kind {
5739 acp::ToolKind::Read => IconName::ToolSearch,
5740 acp::ToolKind::Edit => IconName::ToolPencil,
5741 acp::ToolKind::Delete => IconName::ToolDeleteFile,
5742 acp::ToolKind::Move => IconName::ArrowRightLeft,
5743 acp::ToolKind::Search => IconName::ToolSearch,
5744 acp::ToolKind::Execute => IconName::ToolTerminal,
5745 acp::ToolKind::Think => IconName::ToolThink,
5746 acp::ToolKind::Fetch => IconName::ToolWeb,
5747 acp::ToolKind::SwitchMode => IconName::ArrowRightLeft,
5748 acp::ToolKind::Other | _ => IconName::ToolHammer,
5749 })
5750 .size(IconSize::Small)
5751 .color(Color::Muted)
5752 .into_any_element()
5753 };
5754
5755 let gradient_overlay = {
5756 div()
5757 .absolute()
5758 .top_0()
5759 .right_0()
5760 .w_12()
5761 .h_full()
5762 .map(|this| {
5763 if use_card_layout {
5764 this.bg(linear_gradient(
5765 90.,
5766 linear_color_stop(self.tool_card_header_bg(cx), 1.),
5767 linear_color_stop(self.tool_card_header_bg(cx).opacity(0.2), 0.),
5768 ))
5769 } else {
5770 this.bg(linear_gradient(
5771 90.,
5772 linear_color_stop(cx.theme().colors().panel_background, 1.),
5773 linear_color_stop(
5774 cx.theme().colors().panel_background.opacity(0.2),
5775 0.,
5776 ),
5777 ))
5778 }
5779 })
5780 };
5781
5782 h_flex()
5783 .relative()
5784 .w_full()
5785 .h(window.line_height() - px(2.))
5786 .text_size(self.tool_name_font_size())
5787 .gap_1p5()
5788 .when(has_location || use_card_layout, |this| this.px_1())
5789 .when(has_location, |this| {
5790 this.cursor(CursorStyle::PointingHand)
5791 .rounded(rems_from_px(3.)) // Concentric border radius
5792 .hover(|s| s.bg(cx.theme().colors().element_hover.opacity(0.5)))
5793 })
5794 .overflow_hidden()
5795 .child(tool_icon)
5796 .child(if has_location {
5797 h_flex()
5798 .id(("open-tool-call-location", entry_ix))
5799 .w_full()
5800 .map(|this| {
5801 if use_card_layout {
5802 this.text_color(cx.theme().colors().text)
5803 } else {
5804 this.text_color(cx.theme().colors().text_muted)
5805 }
5806 })
5807 .child(
5808 self.render_markdown(
5809 tool_call.label.clone(),
5810 MarkdownStyle {
5811 prevent_mouse_interaction: true,
5812 ..MarkdownStyle::themed(MarkdownFont::Agent, window, cx)
5813 .with_muted_text(cx)
5814 },
5815 ),
5816 )
5817 .tooltip(Tooltip::text("Go to File"))
5818 .on_click(cx.listener(move |this, _, window, cx| {
5819 this.open_tool_call_location(entry_ix, 0, window, cx);
5820 }))
5821 .into_any_element()
5822 } else {
5823 h_flex()
5824 .w_full()
5825 .child(self.render_markdown(
5826 tool_call.label.clone(),
5827 MarkdownStyle::themed(MarkdownFont::Agent, window, cx).with_muted_text(cx),
5828 ))
5829 .into_any()
5830 })
5831 .when(!is_edit, |this| this.child(gradient_overlay))
5832 }
5833
5834 fn open_tool_call_location(
5835 &self,
5836 entry_ix: usize,
5837 location_ix: usize,
5838 window: &mut Window,
5839 cx: &mut Context<Self>,
5840 ) -> Option<()> {
5841 let (tool_call_location, agent_location) = self
5842 .thread
5843 .read(cx)
5844 .entries()
5845 .get(entry_ix)?
5846 .location(location_ix)?;
5847
5848 let project_path = self
5849 .project
5850 .upgrade()?
5851 .read(cx)
5852 .find_project_path(&tool_call_location.path, cx)?;
5853
5854 let open_task = self
5855 .workspace
5856 .update(cx, |workspace, cx| {
5857 workspace.open_path(project_path, None, true, window, cx)
5858 })
5859 .log_err()?;
5860 window
5861 .spawn(cx, async move |cx| {
5862 let item = open_task.await?;
5863
5864 let Some(active_editor) = item.downcast::<Editor>() else {
5865 return anyhow::Ok(());
5866 };
5867
5868 active_editor.update_in(cx, |editor, window, cx| {
5869 let singleton = editor
5870 .buffer()
5871 .read(cx)
5872 .read(cx)
5873 .as_singleton()
5874 .map(|(a, b, _)| (a, b));
5875 if let Some((excerpt_id, buffer_id)) = singleton
5876 && let Some(agent_buffer) = agent_location.buffer.upgrade()
5877 && agent_buffer.read(cx).remote_id() == buffer_id
5878 {
5879 let anchor = editor::Anchor::in_buffer(excerpt_id, agent_location.position);
5880 editor.change_selections(Default::default(), window, cx, |selections| {
5881 selections.select_anchor_ranges([anchor..anchor]);
5882 })
5883 } else {
5884 let row = tool_call_location.line.unwrap_or_default();
5885 editor.change_selections(Default::default(), window, cx, |selections| {
5886 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
5887 })
5888 }
5889 })?;
5890
5891 anyhow::Ok(())
5892 })
5893 .detach_and_log_err(cx);
5894
5895 None
5896 }
5897
5898 fn render_tool_call_content(
5899 &self,
5900 session_id: &acp::SessionId,
5901 entry_ix: usize,
5902 content: &ToolCallContent,
5903 context_ix: usize,
5904 tool_call: &ToolCall,
5905 card_layout: bool,
5906 is_image_tool_call: bool,
5907 has_failed: bool,
5908 focus_handle: &FocusHandle,
5909 window: &Window,
5910 cx: &Context<Self>,
5911 ) -> AnyElement {
5912 match content {
5913 ToolCallContent::ContentBlock(content) => {
5914 if let Some(resource_link) = content.resource_link() {
5915 self.render_resource_link(resource_link, cx)
5916 } else if let Some(markdown) = content.markdown() {
5917 self.render_markdown_output(
5918 markdown.clone(),
5919 tool_call.id.clone(),
5920 context_ix,
5921 card_layout,
5922 window,
5923 cx,
5924 )
5925 } else if let Some(image) = content.image() {
5926 let location = tool_call.locations.first().cloned();
5927 self.render_image_output(
5928 entry_ix,
5929 image.clone(),
5930 location,
5931 card_layout,
5932 is_image_tool_call,
5933 cx,
5934 )
5935 } else {
5936 Empty.into_any_element()
5937 }
5938 }
5939 ToolCallContent::Diff(diff) => {
5940 self.render_diff_editor(entry_ix, diff, tool_call, has_failed, cx)
5941 }
5942 ToolCallContent::Terminal(terminal) => self.render_terminal_tool_call(
5943 session_id,
5944 entry_ix,
5945 terminal,
5946 tool_call,
5947 focus_handle,
5948 window,
5949 cx,
5950 ),
5951 }
5952 }
5953
5954 fn render_resource_link(
5955 &self,
5956 resource_link: &acp::ResourceLink,
5957 cx: &Context<Self>,
5958 ) -> AnyElement {
5959 let uri: SharedString = resource_link.uri.clone().into();
5960 let is_file = resource_link.uri.strip_prefix("file://");
5961
5962 let Some(project) = self.project.upgrade() else {
5963 return Empty.into_any_element();
5964 };
5965
5966 let label: SharedString = if let Some(abs_path) = is_file {
5967 if let Some(project_path) = project
5968 .read(cx)
5969 .project_path_for_absolute_path(&Path::new(abs_path), cx)
5970 && let Some(worktree) = project
5971 .read(cx)
5972 .worktree_for_id(project_path.worktree_id, cx)
5973 {
5974 worktree
5975 .read(cx)
5976 .full_path(&project_path.path)
5977 .to_string_lossy()
5978 .to_string()
5979 .into()
5980 } else {
5981 abs_path.to_string().into()
5982 }
5983 } else {
5984 uri.clone()
5985 };
5986
5987 let button_id = SharedString::from(format!("item-{}", uri));
5988
5989 div()
5990 .ml(rems(0.4))
5991 .pl_2p5()
5992 .border_l_1()
5993 .border_color(self.tool_card_border_color(cx))
5994 .overflow_hidden()
5995 .child(
5996 Button::new(button_id, label)
5997 .label_size(LabelSize::Small)
5998 .color(Color::Muted)
5999 .truncate(true)
6000 .when(is_file.is_none(), |this| {
6001 this.icon(IconName::ArrowUpRight)
6002 .icon_size(IconSize::XSmall)
6003 .icon_color(Color::Muted)
6004 })
6005 .on_click(cx.listener({
6006 let workspace = self.workspace.clone();
6007 move |_, _, window, cx: &mut Context<Self>| {
6008 open_link(uri.clone(), &workspace, window, cx);
6009 }
6010 })),
6011 )
6012 .into_any_element()
6013 }
6014
6015 fn render_diff_editor(
6016 &self,
6017 entry_ix: usize,
6018 diff: &Entity<acp_thread::Diff>,
6019 tool_call: &ToolCall,
6020 has_failed: bool,
6021 cx: &Context<Self>,
6022 ) -> AnyElement {
6023 let tool_progress = matches!(
6024 &tool_call.status,
6025 ToolCallStatus::InProgress | ToolCallStatus::Pending
6026 );
6027
6028 let revealed_diff_editor = if let Some(entry) =
6029 self.entry_view_state.read(cx).entry(entry_ix)
6030 && let Some(editor) = entry.editor_for_diff(diff)
6031 && diff.read(cx).has_revealed_range(cx)
6032 {
6033 Some(editor)
6034 } else {
6035 None
6036 };
6037
6038 let show_top_border = !has_failed || revealed_diff_editor.is_some();
6039
6040 v_flex()
6041 .h_full()
6042 .when(show_top_border, |this| {
6043 this.border_t_1()
6044 .when(has_failed, |this| this.border_dashed())
6045 .border_color(self.tool_card_border_color(cx))
6046 })
6047 .child(if let Some(editor) = revealed_diff_editor {
6048 editor.into_any_element()
6049 } else if tool_progress && self.as_native_connection(cx).is_some() {
6050 self.render_diff_loading(cx)
6051 } else {
6052 Empty.into_any()
6053 })
6054 .into_any()
6055 }
6056
6057 fn render_markdown_output(
6058 &self,
6059 markdown: Entity<Markdown>,
6060 tool_call_id: acp::ToolCallId,
6061 context_ix: usize,
6062 card_layout: bool,
6063 window: &Window,
6064 cx: &Context<Self>,
6065 ) -> AnyElement {
6066 let button_id = SharedString::from(format!("tool_output-{:?}", tool_call_id));
6067
6068 v_flex()
6069 .gap_2()
6070 .map(|this| {
6071 if card_layout {
6072 this.when(context_ix > 0, |this| {
6073 this.pt_2()
6074 .border_t_1()
6075 .border_color(self.tool_card_border_color(cx))
6076 })
6077 } else {
6078 this.ml(rems(0.4))
6079 .px_3p5()
6080 .border_l_1()
6081 .border_color(self.tool_card_border_color(cx))
6082 }
6083 })
6084 .text_xs()
6085 .text_color(cx.theme().colors().text_muted)
6086 .child(self.render_markdown(
6087 markdown,
6088 MarkdownStyle::themed(MarkdownFont::Agent, window, cx),
6089 ))
6090 .when(!card_layout, |this| {
6091 this.child(
6092 IconButton::new(button_id, IconName::ChevronUp)
6093 .full_width()
6094 .style(ButtonStyle::Outlined)
6095 .icon_color(Color::Muted)
6096 .on_click(cx.listener({
6097 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
6098 this.expanded_tool_calls.remove(&tool_call_id);
6099 cx.notify();
6100 }
6101 })),
6102 )
6103 })
6104 .into_any_element()
6105 }
6106
6107 fn render_image_output(
6108 &self,
6109 entry_ix: usize,
6110 image: Arc<gpui::Image>,
6111 location: Option<acp::ToolCallLocation>,
6112 card_layout: bool,
6113 show_dimensions: bool,
6114 cx: &Context<Self>,
6115 ) -> AnyElement {
6116 let dimensions_label = if show_dimensions {
6117 let format_name = match image.format() {
6118 gpui::ImageFormat::Png => "PNG",
6119 gpui::ImageFormat::Jpeg => "JPEG",
6120 gpui::ImageFormat::Webp => "WebP",
6121 gpui::ImageFormat::Gif => "GIF",
6122 gpui::ImageFormat::Svg => "SVG",
6123 gpui::ImageFormat::Bmp => "BMP",
6124 gpui::ImageFormat::Tiff => "TIFF",
6125 gpui::ImageFormat::Ico => "ICO",
6126 };
6127 let dimensions = image::ImageReader::new(std::io::Cursor::new(image.bytes()))
6128 .with_guessed_format()
6129 .ok()
6130 .and_then(|reader| reader.into_dimensions().ok());
6131 dimensions.map(|(w, h)| format!("{}×{} {}", w, h, format_name))
6132 } else {
6133 None
6134 };
6135
6136 v_flex()
6137 .gap_2()
6138 .map(|this| {
6139 if card_layout {
6140 this
6141 } else {
6142 this.ml(rems(0.4))
6143 .px_3p5()
6144 .border_l_1()
6145 .border_color(self.tool_card_border_color(cx))
6146 }
6147 })
6148 .when(dimensions_label.is_some() || location.is_some(), |this| {
6149 this.child(
6150 h_flex()
6151 .w_full()
6152 .justify_between()
6153 .items_center()
6154 .children(dimensions_label.map(|label| {
6155 Label::new(label)
6156 .size(LabelSize::XSmall)
6157 .color(Color::Muted)
6158 .buffer_font(cx)
6159 }))
6160 .when_some(location, |this, _loc| {
6161 this.child(
6162 Button::new(("go-to-file", entry_ix), "Go to File")
6163 .label_size(LabelSize::Small)
6164 .on_click(cx.listener(move |this, _, window, cx| {
6165 this.open_tool_call_location(entry_ix, 0, window, cx);
6166 })),
6167 )
6168 }),
6169 )
6170 })
6171 .child(
6172 img(image)
6173 .max_w_96()
6174 .max_h_96()
6175 .object_fit(ObjectFit::ScaleDown),
6176 )
6177 .into_any_element()
6178 }
6179
6180 fn render_subagent_tool_call(
6181 &self,
6182 active_session_id: &acp::SessionId,
6183 entry_ix: usize,
6184 tool_call: &ToolCall,
6185 subagent_session_id: Option<acp::SessionId>,
6186 focus_handle: &FocusHandle,
6187 window: &Window,
6188 cx: &Context<Self>,
6189 ) -> Div {
6190 let subagent_thread_view = subagent_session_id.and_then(|id| {
6191 self.server_view
6192 .upgrade()
6193 .and_then(|server_view| server_view.read(cx).as_connected())
6194 .and_then(|connected| connected.threads.get(&id))
6195 });
6196
6197 let content = self.render_subagent_card(
6198 active_session_id,
6199 entry_ix,
6200 subagent_thread_view,
6201 tool_call,
6202 focus_handle,
6203 window,
6204 cx,
6205 );
6206
6207 v_flex().mx_5().my_1p5().gap_3().child(content)
6208 }
6209
6210 fn render_subagent_card(
6211 &self,
6212 active_session_id: &acp::SessionId,
6213 entry_ix: usize,
6214 thread_view: Option<&Entity<ThreadView>>,
6215 tool_call: &ToolCall,
6216 focus_handle: &FocusHandle,
6217 window: &Window,
6218 cx: &Context<Self>,
6219 ) -> AnyElement {
6220 let thread = thread_view
6221 .as_ref()
6222 .map(|view| view.read(cx).thread.clone());
6223 let subagent_session_id = thread
6224 .as_ref()
6225 .map(|thread| thread.read(cx).session_id().clone());
6226 let action_log = thread.as_ref().map(|thread| thread.read(cx).action_log());
6227 let changed_buffers = action_log
6228 .map(|log| log.read(cx).changed_buffers(cx))
6229 .unwrap_or_default();
6230
6231 let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
6232 let files_changed = changed_buffers.len();
6233 let diff_stats = DiffStats::all_files(&changed_buffers, cx);
6234
6235 let is_running = matches!(
6236 tool_call.status,
6237 ToolCallStatus::Pending | ToolCallStatus::InProgress
6238 );
6239 let is_canceled_or_failed = matches!(
6240 tool_call.status,
6241 ToolCallStatus::Canceled | ToolCallStatus::Failed | ToolCallStatus::Rejected
6242 );
6243
6244 let has_title = thread
6245 .as_ref()
6246 .is_some_and(|t| !t.read(cx).title().is_empty());
6247 let has_no_title_or_canceled = !has_title || is_canceled_or_failed;
6248
6249 let title = thread
6250 .as_ref()
6251 .map(|t| t.read(cx).title())
6252 .unwrap_or_else(|| {
6253 if is_canceled_or_failed {
6254 "Subagent Canceled"
6255 } else {
6256 "Spawning Subagent…"
6257 }
6258 .into()
6259 });
6260
6261 let card_header_id = format!("subagent-header-{}", entry_ix);
6262 let diff_stat_id = format!("subagent-diff-{}", entry_ix);
6263
6264 let icon = h_flex().w_4().justify_center().child(if is_running {
6265 SpinnerLabel::new()
6266 .size(LabelSize::Small)
6267 .into_any_element()
6268 } else if is_canceled_or_failed {
6269 Icon::new(IconName::Close)
6270 .size(IconSize::Small)
6271 .color(Color::Error)
6272 .into_any_element()
6273 } else {
6274 Icon::new(IconName::Check)
6275 .size(IconSize::Small)
6276 .color(Color::Success)
6277 .into_any_element()
6278 });
6279
6280 let has_expandable_content = thread
6281 .as_ref()
6282 .map_or(false, |thread| !thread.read(cx).entries().is_empty());
6283
6284 let tooltip_meta_description = if is_expanded {
6285 "Click to Collapse"
6286 } else {
6287 "Click to Preview"
6288 };
6289
6290 v_flex()
6291 .w_full()
6292 .rounded_md()
6293 .border_1()
6294 .when(has_no_title_or_canceled, |this| this.border_dashed())
6295 .border_color(self.tool_card_border_color(cx))
6296 .overflow_hidden()
6297 .child(
6298 h_flex()
6299 .group(&card_header_id)
6300 .h_8()
6301 .p_1()
6302 .w_full()
6303 .justify_between()
6304 .when(!has_no_title_or_canceled, |this| {
6305 this.bg(self.tool_card_header_bg(cx))
6306 })
6307 .child(
6308 h_flex()
6309 .id(format!("subagent-title-{}", entry_ix))
6310 .px_1()
6311 .min_w_0()
6312 .size_full()
6313 .gap_2()
6314 .justify_between()
6315 .rounded_sm()
6316 .overflow_hidden()
6317 .child(
6318 h_flex()
6319 .min_w_0()
6320 .w_full()
6321 .gap_1p5()
6322 .child(icon)
6323 .child(
6324 Label::new(title.to_string())
6325 .size(LabelSize::Custom(self.tool_name_font_size()))
6326 .truncate(),
6327 )
6328 .when(files_changed > 0, |this| {
6329 this.child(
6330 Label::new(format!(
6331 "— {} {} changed",
6332 files_changed,
6333 if files_changed == 1 { "file" } else { "files" }
6334 ))
6335 .size(LabelSize::Custom(self.tool_name_font_size()))
6336 .color(Color::Muted),
6337 )
6338 .child(
6339 DiffStat::new(
6340 diff_stat_id.clone(),
6341 diff_stats.lines_added as usize,
6342 diff_stats.lines_removed as usize,
6343 )
6344 .label_size(LabelSize::Custom(
6345 self.tool_name_font_size(),
6346 )),
6347 )
6348 }),
6349 )
6350 .when(!has_no_title_or_canceled, |this| {
6351 this.tooltip(move |_, cx| {
6352 Tooltip::with_meta(
6353 title.to_string(),
6354 None,
6355 tooltip_meta_description,
6356 cx,
6357 )
6358 })
6359 })
6360 .when(has_expandable_content, |this| {
6361 this.cursor_pointer()
6362 .hover(|s| s.bg(cx.theme().colors().element_hover))
6363 .child(
6364 div().visible_on_hover(card_header_id).child(
6365 Icon::new(if is_expanded {
6366 IconName::ChevronUp
6367 } else {
6368 IconName::ChevronDown
6369 })
6370 .color(Color::Muted)
6371 .size(IconSize::Small),
6372 ),
6373 )
6374 .on_click(cx.listener({
6375 let tool_call_id = tool_call.id.clone();
6376 move |this, _, _, cx| {
6377 if this.expanded_tool_calls.contains(&tool_call_id) {
6378 this.expanded_tool_calls.remove(&tool_call_id);
6379 } else {
6380 this.expanded_tool_calls
6381 .insert(tool_call_id.clone());
6382 }
6383 cx.notify();
6384 }
6385 }))
6386 }),
6387 )
6388 .when(is_running && subagent_session_id.is_some(), |buttons| {
6389 buttons.child(
6390 IconButton::new(format!("stop-subagent-{}", entry_ix), IconName::Stop)
6391 .icon_size(IconSize::Small)
6392 .icon_color(Color::Error)
6393 .tooltip(Tooltip::text("Stop Subagent"))
6394 .when_some(
6395 thread_view
6396 .as_ref()
6397 .map(|view| view.read(cx).thread.clone()),
6398 |this, thread| {
6399 this.on_click(cx.listener(
6400 move |_this, _event, _window, cx| {
6401 thread.update(cx, |thread, cx| {
6402 thread.cancel(cx).detach();
6403 });
6404 },
6405 ))
6406 },
6407 ),
6408 )
6409 }),
6410 )
6411 .when_some(thread_view, |this, thread_view| {
6412 let thread = &thread_view.read(cx).thread;
6413 let pending_tool_call = self
6414 .conversation
6415 .read(cx)
6416 .pending_tool_call(thread.read(cx).session_id(), cx);
6417
6418 if let Some((_, subagent_tool_call_id, _)) = pending_tool_call {
6419 if let Some((entry_ix, tool_call)) =
6420 thread.read(cx).tool_call(&subagent_tool_call_id)
6421 {
6422 this.child(thread_view.read(cx).render_any_tool_call(
6423 active_session_id,
6424 entry_ix,
6425 tool_call,
6426 focus_handle,
6427 window,
6428 cx,
6429 ))
6430 } else {
6431 this
6432 }
6433 } else {
6434 let session_id = thread.read(cx).session_id().clone();
6435 this.when(is_expanded, |this| {
6436 this.child(self.render_subagent_expanded_content(
6437 thread_view,
6438 is_running,
6439 tool_call,
6440 window,
6441 cx,
6442 ))
6443 .child(
6444 h_flex()
6445 .id(entry_ix)
6446 .py_1()
6447 .w_full()
6448 .justify_center()
6449 .border_t_1()
6450 .when(is_canceled_or_failed, |this| this.border_dashed())
6451 .border_color(cx.theme().colors().border_variant)
6452 .hover(|s| s.bg(cx.theme().colors().element_hover))
6453 .child(
6454 Icon::new(IconName::Maximize)
6455 .color(Color::Muted)
6456 .size(IconSize::Small),
6457 )
6458 .tooltip(Tooltip::text("Make Subagent Full Screen"))
6459 .on_click(cx.listener(move |this, _event, window, cx| {
6460 this.server_view
6461 .update(cx, |this, cx| {
6462 this.navigate_to_session(
6463 session_id.clone(),
6464 window,
6465 cx,
6466 );
6467 })
6468 .ok();
6469 })),
6470 )
6471 })
6472 }
6473 })
6474 .into_any_element()
6475 }
6476
6477 fn render_subagent_expanded_content(
6478 &self,
6479 thread_view: &Entity<ThreadView>,
6480 is_running: bool,
6481 tool_call: &ToolCall,
6482 window: &Window,
6483 cx: &Context<Self>,
6484 ) -> impl IntoElement {
6485 const MAX_PREVIEW_ENTRIES: usize = 8;
6486
6487 let subagent_view = thread_view.read(cx);
6488 let session_id = subagent_view.thread.read(cx).session_id().clone();
6489
6490 let is_canceled_or_failed = matches!(
6491 tool_call.status,
6492 ToolCallStatus::Canceled | ToolCallStatus::Failed | ToolCallStatus::Rejected
6493 );
6494
6495 let editor_bg = cx.theme().colors().editor_background;
6496 let overlay = {
6497 div()
6498 .absolute()
6499 .inset_0()
6500 .size_full()
6501 .bg(linear_gradient(
6502 180.,
6503 linear_color_stop(editor_bg.opacity(0.5), 0.),
6504 linear_color_stop(editor_bg.opacity(0.), 0.1),
6505 ))
6506 .block_mouse_except_scroll()
6507 };
6508
6509 let entries = subagent_view.thread.read(cx).entries();
6510 let total_entries = entries.len();
6511 let start_ix = total_entries.saturating_sub(MAX_PREVIEW_ENTRIES);
6512
6513 let scroll_handle = self
6514 .subagent_scroll_handles
6515 .borrow_mut()
6516 .entry(session_id.clone())
6517 .or_default()
6518 .clone();
6519 if is_running {
6520 scroll_handle.scroll_to_bottom();
6521 }
6522
6523 let rendered_entries: Vec<AnyElement> = entries[start_ix..]
6524 .iter()
6525 .enumerate()
6526 .map(|(i, entry)| {
6527 let actual_ix = start_ix + i;
6528 subagent_view.render_entry(actual_ix, total_entries + 1, entry, window, cx)
6529 })
6530 .collect();
6531
6532 let error_message =
6533 self.subagent_error_message(subagent_view, &tool_call.status, tool_call, cx);
6534
6535 let parent_thread = self.thread.read(cx);
6536 let mut started_subagent_count = 0usize;
6537 let mut turn_has_our_call = false;
6538 for entry in parent_thread.entries().iter() {
6539 match entry {
6540 AgentThreadEntry::UserMessage(_) => {
6541 if turn_has_our_call {
6542 break;
6543 }
6544 started_subagent_count = 0;
6545 turn_has_our_call = false;
6546 }
6547 AgentThreadEntry::ToolCall(tc)
6548 if tc.is_subagent() && !matches!(tc.status, ToolCallStatus::Pending) =>
6549 {
6550 started_subagent_count += 1;
6551 if tc.id == tool_call.id {
6552 turn_has_our_call = true;
6553 }
6554 }
6555 _ => {}
6556 }
6557 }
6558
6559 v_flex()
6560 .relative()
6561 .w_full()
6562 .border_t_1()
6563 .when(is_canceled_or_failed, |this| this.border_dashed())
6564 .border_color(self.tool_card_border_color(cx))
6565 .overflow_hidden()
6566 .child(
6567 div()
6568 .id(format!("subagent-entries-{}", session_id))
6569 .flex_1()
6570 .min_h_0()
6571 .pb_1()
6572 .overflow_hidden()
6573 .track_scroll(&scroll_handle)
6574 .children(rendered_entries),
6575 )
6576 .when_some(error_message, |this, message| {
6577 this.child(
6578 Callout::new()
6579 .severity(Severity::Error)
6580 .icon(IconName::XCircle)
6581 .title(message),
6582 )
6583 })
6584 .when(started_subagent_count > 1, |this| {
6585 this.h_56().child(overlay)
6586 })
6587 .into_any_element()
6588 }
6589
6590 fn subagent_error_message(
6591 &self,
6592 subagent_view: &ThreadView,
6593 status: &ToolCallStatus,
6594 tool_call: &ToolCall,
6595 cx: &App,
6596 ) -> Option<SharedString> {
6597 if matches!(status, ToolCallStatus::Canceled | ToolCallStatus::Rejected) {
6598 return None;
6599 }
6600
6601 subagent_view
6602 .thread_error
6603 .as_ref()
6604 .and_then(|e| match e {
6605 ThreadError::Refusal => Some("The agent refused to respond to this prompt.".into()),
6606 ThreadError::Other { message, .. } => Some(message.clone()),
6607 ThreadError::PaymentRequired | ThreadError::AuthenticationRequired(_) => None,
6608 })
6609 .or_else(|| {
6610 tool_call.content.iter().find_map(|content| {
6611 if let ToolCallContent::ContentBlock(block) = content {
6612 if let acp_thread::ContentBlock::Markdown { markdown } = block {
6613 let source = markdown.read(cx).source().to_string();
6614 if !source.is_empty() {
6615 return Some(SharedString::from(source));
6616 }
6617 }
6618 }
6619 None
6620 })
6621 })
6622 }
6623 fn render_rules_item(&self, cx: &Context<Self>) -> Option<AnyElement> {
6624 let project_context = self
6625 .as_native_thread(cx)?
6626 .read(cx)
6627 .project_context()
6628 .read(cx);
6629
6630 let user_rules_text = if project_context.user_rules.is_empty() {
6631 None
6632 } else if project_context.user_rules.len() == 1 {
6633 let user_rules = &project_context.user_rules[0];
6634
6635 match user_rules.title.as_ref() {
6636 Some(title) => Some(format!("Using \"{title}\" user rule")),
6637 None => Some("Using user rule".into()),
6638 }
6639 } else {
6640 Some(format!(
6641 "Using {} user rules",
6642 project_context.user_rules.len()
6643 ))
6644 };
6645
6646 let first_user_rules_id = project_context
6647 .user_rules
6648 .first()
6649 .map(|user_rules| user_rules.uuid.0);
6650
6651 let rules_files = project_context
6652 .worktrees
6653 .iter()
6654 .filter_map(|worktree| worktree.rules_file.as_ref())
6655 .collect::<Vec<_>>();
6656
6657 let rules_file_text = match rules_files.as_slice() {
6658 &[] => None,
6659 &[rules_file] => Some(format!(
6660 "Using project {:?} file",
6661 rules_file.path_in_worktree
6662 )),
6663 rules_files => Some(format!("Using {} project rules files", rules_files.len())),
6664 };
6665
6666 if user_rules_text.is_none() && rules_file_text.is_none() {
6667 return None;
6668 }
6669
6670 let has_both = user_rules_text.is_some() && rules_file_text.is_some();
6671
6672 Some(
6673 h_flex()
6674 .px_2p5()
6675 .child(
6676 Icon::new(IconName::Attach)
6677 .size(IconSize::XSmall)
6678 .color(Color::Disabled),
6679 )
6680 .when_some(user_rules_text, |parent, user_rules_text| {
6681 parent.child(
6682 h_flex()
6683 .id("user-rules")
6684 .ml_1()
6685 .mr_1p5()
6686 .child(
6687 Label::new(user_rules_text)
6688 .size(LabelSize::XSmall)
6689 .color(Color::Muted)
6690 .truncate(),
6691 )
6692 .hover(|s| s.bg(cx.theme().colors().element_hover))
6693 .tooltip(Tooltip::text("View User Rules"))
6694 .on_click(move |_event, window, cx| {
6695 window.dispatch_action(
6696 Box::new(OpenRulesLibrary {
6697 prompt_to_select: first_user_rules_id,
6698 }),
6699 cx,
6700 )
6701 }),
6702 )
6703 })
6704 .when(has_both, |this| {
6705 this.child(
6706 Label::new("•")
6707 .size(LabelSize::XSmall)
6708 .color(Color::Disabled),
6709 )
6710 })
6711 .when_some(rules_file_text, |parent, rules_file_text| {
6712 parent.child(
6713 h_flex()
6714 .id("project-rules")
6715 .ml_1p5()
6716 .child(
6717 Label::new(rules_file_text)
6718 .size(LabelSize::XSmall)
6719 .color(Color::Muted),
6720 )
6721 .hover(|s| s.bg(cx.theme().colors().element_hover))
6722 .tooltip(Tooltip::text("View Project Rules"))
6723 .on_click(cx.listener(Self::handle_open_rules)),
6724 )
6725 })
6726 .into_any(),
6727 )
6728 }
6729
6730 fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
6731 cx.theme()
6732 .colors()
6733 .element_background
6734 .blend(cx.theme().colors().editor_foreground.opacity(0.025))
6735 }
6736
6737 fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
6738 cx.theme().colors().border.opacity(0.8)
6739 }
6740
6741 fn tool_name_font_size(&self) -> Rems {
6742 rems_from_px(13.)
6743 }
6744
6745 pub(crate) fn render_thread_error(
6746 &mut self,
6747 window: &mut Window,
6748 cx: &mut Context<Self>,
6749 ) -> Option<Div> {
6750 let content = match self.thread_error.as_ref()? {
6751 ThreadError::Other { message, .. } => {
6752 self.render_any_thread_error(message.clone(), window, cx)
6753 }
6754 ThreadError::Refusal => self.render_refusal_error(cx),
6755 ThreadError::AuthenticationRequired(error) => {
6756 self.render_authentication_required_error(error.clone(), cx)
6757 }
6758 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
6759 };
6760
6761 Some(div().child(content))
6762 }
6763
6764 fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
6765 let model_or_agent_name = self.current_model_name(cx);
6766 let refusal_message = format!(
6767 "{} refused to respond to this prompt. \
6768 This can happen when a model believes the prompt violates its content policy \
6769 or safety guidelines, so rephrasing it can sometimes address the issue.",
6770 model_or_agent_name
6771 );
6772
6773 Callout::new()
6774 .severity(Severity::Error)
6775 .title("Request Refused")
6776 .icon(IconName::XCircle)
6777 .description(refusal_message.clone())
6778 .actions_slot(self.create_copy_button(&refusal_message))
6779 .dismiss_action(self.dismiss_error_button(cx))
6780 }
6781
6782 fn render_authentication_required_error(
6783 &self,
6784 error: SharedString,
6785 cx: &mut Context<Self>,
6786 ) -> Callout {
6787 Callout::new()
6788 .severity(Severity::Error)
6789 .title("Authentication Required")
6790 .icon(IconName::XCircle)
6791 .description(error.clone())
6792 .actions_slot(
6793 h_flex()
6794 .gap_0p5()
6795 .child(self.authenticate_button(cx))
6796 .child(self.create_copy_button(error)),
6797 )
6798 .dismiss_action(self.dismiss_error_button(cx))
6799 }
6800
6801 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
6802 const ERROR_MESSAGE: &str =
6803 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
6804
6805 Callout::new()
6806 .severity(Severity::Error)
6807 .icon(IconName::XCircle)
6808 .title("Free Usage Exceeded")
6809 .description(ERROR_MESSAGE)
6810 .actions_slot(
6811 h_flex()
6812 .gap_0p5()
6813 .child(self.upgrade_button(cx))
6814 .child(self.create_copy_button(ERROR_MESSAGE)),
6815 )
6816 .dismiss_action(self.dismiss_error_button(cx))
6817 }
6818
6819 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
6820 Button::new("upgrade", "Upgrade")
6821 .label_size(LabelSize::Small)
6822 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
6823 .on_click(cx.listener({
6824 move |this, _, _, cx| {
6825 this.clear_thread_error(cx);
6826 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
6827 }
6828 }))
6829 }
6830
6831 fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
6832 Button::new("authenticate", "Authenticate")
6833 .label_size(LabelSize::Small)
6834 .style(ButtonStyle::Filled)
6835 .on_click(cx.listener({
6836 move |this, _, window, cx| {
6837 let server_view = this.server_view.clone();
6838 let agent_name = this.agent_name.clone();
6839
6840 this.clear_thread_error(cx);
6841 if let Some(message) = this.in_flight_prompt.take() {
6842 this.message_editor.update(cx, |editor, cx| {
6843 editor.set_message(message, window, cx);
6844 });
6845 }
6846 let connection = this.thread.read(cx).connection().clone();
6847 window.defer(cx, |window, cx| {
6848 ConnectionView::handle_auth_required(
6849 server_view,
6850 AuthRequired::new(),
6851 agent_name,
6852 connection,
6853 window,
6854 cx,
6855 );
6856 })
6857 }
6858 }))
6859 }
6860
6861 fn current_model_name(&self, cx: &App) -> SharedString {
6862 // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
6863 // For ACP agents, use the agent name (e.g., "Claude Agent", "Gemini CLI")
6864 // This provides better clarity about what refused the request
6865 if self.as_native_connection(cx).is_some() {
6866 self.model_selector
6867 .clone()
6868 .and_then(|selector| selector.read(cx).active_model(cx))
6869 .map(|model| model.name.clone())
6870 .unwrap_or_else(|| SharedString::from("The model"))
6871 } else {
6872 // ACP agent - use the agent name (e.g., "Claude Agent", "Gemini CLI")
6873 self.agent_name.clone()
6874 }
6875 }
6876
6877 fn render_any_thread_error(
6878 &mut self,
6879 error: SharedString,
6880 window: &mut Window,
6881 cx: &mut Context<'_, Self>,
6882 ) -> Callout {
6883 let can_resume = self.thread.read(cx).can_retry(cx);
6884
6885 let markdown = if let Some(markdown) = &self.thread_error_markdown {
6886 markdown.clone()
6887 } else {
6888 let markdown = cx.new(|cx| Markdown::new(error.clone(), None, None, cx));
6889 self.thread_error_markdown = Some(markdown.clone());
6890 markdown
6891 };
6892
6893 let markdown_style =
6894 MarkdownStyle::themed(MarkdownFont::Agent, window, cx).with_muted_text(cx);
6895 let description = self
6896 .render_markdown(markdown, markdown_style)
6897 .into_any_element();
6898
6899 Callout::new()
6900 .severity(Severity::Error)
6901 .icon(IconName::XCircle)
6902 .title("An Error Happened")
6903 .description_slot(description)
6904 .actions_slot(
6905 h_flex()
6906 .gap_0p5()
6907 .when(can_resume, |this| {
6908 this.child(
6909 IconButton::new("retry", IconName::RotateCw)
6910 .icon_size(IconSize::Small)
6911 .tooltip(Tooltip::text("Retry Generation"))
6912 .on_click(cx.listener(|this, _, _window, cx| {
6913 this.retry_generation(cx);
6914 })),
6915 )
6916 })
6917 .child(self.create_copy_button(error.to_string())),
6918 )
6919 .dismiss_action(self.dismiss_error_button(cx))
6920 }
6921
6922 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
6923 let workspace = self.workspace.clone();
6924 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
6925 open_link(text, &workspace, window, cx);
6926 })
6927 }
6928
6929 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
6930 let message = message.into();
6931
6932 CopyButton::new("copy-error-message", message).tooltip_label("Copy Error Message")
6933 }
6934
6935 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
6936 IconButton::new("dismiss", IconName::Close)
6937 .icon_size(IconSize::Small)
6938 .tooltip(Tooltip::text("Dismiss"))
6939 .on_click(cx.listener({
6940 move |this, _, _, cx| {
6941 this.clear_thread_error(cx);
6942 cx.notify();
6943 }
6944 }))
6945 }
6946
6947 fn render_resume_notice(_cx: &Context<Self>) -> AnyElement {
6948 let description = "This agent does not support viewing previous messages. However, your session will still continue from where you last left off.";
6949
6950 div()
6951 .px_2()
6952 .pt_2()
6953 .pb_3()
6954 .w_full()
6955 .child(
6956 Callout::new()
6957 .severity(Severity::Info)
6958 .icon(IconName::Info)
6959 .title("Resumed Session")
6960 .description(description),
6961 )
6962 .into_any_element()
6963 }
6964
6965 fn update_recent_history_from_cache(
6966 &mut self,
6967 history: &Entity<ThreadHistory>,
6968 cx: &mut Context<Self>,
6969 ) {
6970 self.recent_history_entries = history.read(cx).get_recent_sessions(3);
6971 self.hovered_recent_history_item = None;
6972 cx.notify();
6973 }
6974
6975 fn render_empty_state_section_header(
6976 &self,
6977 label: impl Into<SharedString>,
6978 action_slot: Option<AnyElement>,
6979 cx: &mut Context<Self>,
6980 ) -> impl IntoElement {
6981 div().pl_1().pr_1p5().child(
6982 h_flex()
6983 .mt_2()
6984 .pl_1p5()
6985 .pb_1()
6986 .w_full()
6987 .justify_between()
6988 .border_b_1()
6989 .border_color(cx.theme().colors().border_variant)
6990 .child(
6991 Label::new(label.into())
6992 .size(LabelSize::Small)
6993 .color(Color::Muted),
6994 )
6995 .children(action_slot),
6996 )
6997 }
6998
6999 fn render_recent_history(&self, cx: &mut Context<Self>) -> AnyElement {
7000 let render_history = !self.recent_history_entries.is_empty();
7001
7002 v_flex()
7003 .size_full()
7004 .when(render_history, |this| {
7005 let recent_history = self.recent_history_entries.clone();
7006 this.justify_end().child(
7007 v_flex()
7008 .child(
7009 self.render_empty_state_section_header(
7010 "Recent",
7011 Some(
7012 Button::new("view-history", "View All")
7013 .style(ButtonStyle::Subtle)
7014 .label_size(LabelSize::Small)
7015 .key_binding(
7016 KeyBinding::for_action_in(
7017 &OpenHistory,
7018 &self.focus_handle(cx),
7019 cx,
7020 )
7021 .map(|kb| kb.size(rems_from_px(12.))),
7022 )
7023 .on_click(move |_event, window, cx| {
7024 window.dispatch_action(OpenHistory.boxed_clone(), cx);
7025 })
7026 .into_any_element(),
7027 ),
7028 cx,
7029 ),
7030 )
7031 .child(v_flex().p_1().pr_1p5().gap_1().children({
7032 let supports_delete = self.history.read(cx).supports_delete();
7033 recent_history
7034 .into_iter()
7035 .enumerate()
7036 .map(move |(index, entry)| {
7037 // TODO: Add keyboard navigation.
7038 let is_hovered =
7039 self.hovered_recent_history_item == Some(index);
7040 crate::thread_history::HistoryEntryElement::new(
7041 entry,
7042 self.server_view.clone(),
7043 )
7044 .hovered(is_hovered)
7045 .supports_delete(supports_delete)
7046 .on_hover(cx.listener(move |this, is_hovered, _window, cx| {
7047 if *is_hovered {
7048 this.hovered_recent_history_item = Some(index);
7049 } else if this.hovered_recent_history_item == Some(index) {
7050 this.hovered_recent_history_item = None;
7051 }
7052 cx.notify();
7053 }))
7054 .into_any_element()
7055 })
7056 })),
7057 )
7058 })
7059 .into_any()
7060 }
7061
7062 fn render_codex_windows_warning(&self, cx: &mut Context<Self>) -> Callout {
7063 Callout::new()
7064 .icon(IconName::Warning)
7065 .severity(Severity::Warning)
7066 .title("Codex on Windows")
7067 .description("For best performance, run Codex in Windows Subsystem for Linux (WSL2)")
7068 .actions_slot(
7069 Button::new("open-wsl-modal", "Open in WSL")
7070 .icon_size(IconSize::Small)
7071 .icon_color(Color::Muted)
7072 .on_click(cx.listener({
7073 move |_, _, _window, cx| {
7074 #[cfg(windows)]
7075 _window.dispatch_action(
7076 zed_actions::wsl_actions::OpenWsl::default().boxed_clone(),
7077 cx,
7078 );
7079 cx.notify();
7080 }
7081 })),
7082 )
7083 .dismiss_action(
7084 IconButton::new("dismiss", IconName::Close)
7085 .icon_size(IconSize::Small)
7086 .icon_color(Color::Muted)
7087 .tooltip(Tooltip::text("Dismiss Warning"))
7088 .on_click(cx.listener({
7089 move |this, _, _, cx| {
7090 this.show_codex_windows_warning = false;
7091 cx.notify();
7092 }
7093 })),
7094 )
7095 }
7096
7097 fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
7098 let server_view = self.server_view.clone();
7099 v_flex().w_full().justify_end().child(
7100 h_flex()
7101 .p_2()
7102 .pr_3()
7103 .w_full()
7104 .gap_1p5()
7105 .border_t_1()
7106 .border_color(cx.theme().colors().border)
7107 .bg(cx.theme().colors().element_background)
7108 .child(
7109 h_flex()
7110 .flex_1()
7111 .gap_1p5()
7112 .child(
7113 Icon::new(IconName::Download)
7114 .color(Color::Accent)
7115 .size(IconSize::Small),
7116 )
7117 .child(Label::new("New version available").size(LabelSize::Small)),
7118 )
7119 .child(
7120 Button::new("update-button", format!("Update to v{}", version))
7121 .label_size(LabelSize::Small)
7122 .style(ButtonStyle::Tinted(TintColor::Accent))
7123 .on_click(move |_, window, cx| {
7124 server_view
7125 .update(cx, |view, cx| view.reset(window, cx))
7126 .ok();
7127 }),
7128 ),
7129 )
7130 }
7131
7132 fn render_token_limit_callout(&self, cx: &mut Context<Self>) -> Option<Callout> {
7133 if self.token_limit_callout_dismissed {
7134 return None;
7135 }
7136
7137 let token_usage = self.thread.read(cx).token_usage()?;
7138 let ratio = token_usage.ratio();
7139
7140 let (severity, icon, title) = match ratio {
7141 acp_thread::TokenUsageRatio::Normal => return None,
7142 acp_thread::TokenUsageRatio::Warning => (
7143 Severity::Warning,
7144 IconName::Warning,
7145 "Thread reaching the token limit soon",
7146 ),
7147 acp_thread::TokenUsageRatio::Exceeded => (
7148 Severity::Error,
7149 IconName::XCircle,
7150 "Thread reached the token limit",
7151 ),
7152 };
7153
7154 let description = "To continue, start a new thread from a summary.";
7155
7156 Some(
7157 Callout::new()
7158 .severity(severity)
7159 .icon(icon)
7160 .title(title)
7161 .description(description)
7162 .actions_slot(
7163 h_flex().gap_0p5().child(
7164 Button::new("start-new-thread", "Start New Thread")
7165 .label_size(LabelSize::Small)
7166 .on_click(cx.listener(|this, _, window, cx| {
7167 let session_id = this.thread.read(cx).session_id().clone();
7168 window.dispatch_action(
7169 crate::NewNativeAgentThreadFromSummary {
7170 from_session_id: session_id,
7171 }
7172 .boxed_clone(),
7173 cx,
7174 );
7175 })),
7176 ),
7177 )
7178 .dismiss_action(self.dismiss_error_button(cx)),
7179 )
7180 }
7181
7182 fn open_permission_dropdown(
7183 &mut self,
7184 _: &crate::OpenPermissionDropdown,
7185 window: &mut Window,
7186 cx: &mut Context<Self>,
7187 ) {
7188 self.permission_dropdown_handle.clone().toggle(window, cx);
7189 }
7190
7191 fn open_add_context_menu(
7192 &mut self,
7193 _action: &OpenAddContextMenu,
7194 window: &mut Window,
7195 cx: &mut Context<Self>,
7196 ) {
7197 let menu_handle = self.add_context_menu_handle.clone();
7198 window.defer(cx, move |window, cx| {
7199 menu_handle.toggle(window, cx);
7200 });
7201 }
7202
7203 fn toggle_fast_mode(&mut self, cx: &mut Context<Self>) {
7204 if !self.fast_mode_available(cx) {
7205 return;
7206 }
7207 let Some(thread) = self.as_native_thread(cx) else {
7208 return;
7209 };
7210 thread.update(cx, |thread, cx| {
7211 thread.set_speed(
7212 thread
7213 .speed()
7214 .map(|speed| speed.toggle())
7215 .unwrap_or(Speed::Fast),
7216 cx,
7217 );
7218 });
7219 }
7220
7221 fn cycle_thinking_effort(&mut self, cx: &mut Context<Self>) {
7222 let Some(thread) = self.as_native_thread(cx) else {
7223 return;
7224 };
7225
7226 let (effort_levels, current_effort) = {
7227 let thread_ref = thread.read(cx);
7228 let Some(model) = thread_ref.model() else {
7229 return;
7230 };
7231 if !model.supports_thinking() || !thread_ref.thinking_enabled() {
7232 return;
7233 }
7234 let effort_levels = model.supported_effort_levels();
7235 if effort_levels.is_empty() {
7236 return;
7237 }
7238 let current_effort = thread_ref.thinking_effort().cloned();
7239 (effort_levels, current_effort)
7240 };
7241
7242 let current_index = current_effort.and_then(|current| {
7243 effort_levels
7244 .iter()
7245 .position(|level| level.value == current)
7246 });
7247 let next_index = match current_index {
7248 Some(index) => (index + 1) % effort_levels.len(),
7249 None => 0,
7250 };
7251 let next_effort = effort_levels[next_index].value.to_string();
7252
7253 thread.update(cx, |thread, cx| {
7254 thread.set_thinking_effort(Some(next_effort.clone()), cx);
7255
7256 let fs = thread.project().read(cx).fs().clone();
7257 update_settings_file(fs, cx, move |settings, _| {
7258 if let Some(agent) = settings.agent.as_mut()
7259 && let Some(default_model) = agent.default_model.as_mut()
7260 {
7261 default_model.effort = Some(next_effort);
7262 }
7263 });
7264 });
7265 }
7266
7267 fn toggle_thinking_effort_menu(
7268 &mut self,
7269 _action: &ToggleThinkingEffortMenu,
7270 window: &mut Window,
7271 cx: &mut Context<Self>,
7272 ) {
7273 let menu_handle = self.thinking_effort_menu_handle.clone();
7274 window.defer(cx, move |window, cx| {
7275 menu_handle.toggle(window, cx);
7276 });
7277 }
7278}
7279
7280impl Render for ThreadView {
7281 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7282 let has_messages = self.list_state.item_count() > 0;
7283
7284 let conversation = v_flex().flex_1().map(|this| {
7285 let this = this.when(self.resumed_without_history, |this| {
7286 this.child(Self::render_resume_notice(cx))
7287 });
7288 if has_messages {
7289 let list_state = self.list_state.clone();
7290 this.child(self.render_entries(cx))
7291 .vertical_scrollbar_for(&list_state, window, cx)
7292 .into_any()
7293 } else {
7294 this.child(self.render_recent_history(cx)).into_any()
7295 }
7296 });
7297
7298 v_flex()
7299 .key_context("AcpThread")
7300 .track_focus(&self.focus_handle)
7301 .on_action(cx.listener(|this, _: &menu::Cancel, _, cx| {
7302 if this.parent_id.is_none() {
7303 this.cancel_generation(cx);
7304 }
7305 }))
7306 .on_action(cx.listener(|this, _: &workspace::GoBack, window, cx| {
7307 if let Some(parent_session_id) = this.parent_id.clone() {
7308 this.server_view
7309 .update(cx, |view, cx| {
7310 view.navigate_to_session(parent_session_id, window, cx);
7311 })
7312 .ok();
7313 }
7314 }))
7315 .on_action(cx.listener(Self::keep_all))
7316 .on_action(cx.listener(Self::reject_all))
7317 .on_action(cx.listener(Self::undo_last_reject))
7318 .on_action(cx.listener(Self::allow_always))
7319 .on_action(cx.listener(Self::allow_once))
7320 .on_action(cx.listener(Self::reject_once))
7321 .on_action(cx.listener(Self::handle_authorize_tool_call))
7322 .on_action(cx.listener(Self::handle_select_permission_granularity))
7323 .on_action(cx.listener(Self::open_permission_dropdown))
7324 .on_action(cx.listener(Self::open_add_context_menu))
7325 .on_action(cx.listener(|this, _: &ToggleFastMode, _window, cx| {
7326 this.toggle_fast_mode(cx);
7327 }))
7328 .on_action(cx.listener(|this, _: &ToggleThinkingMode, _window, cx| {
7329 if let Some(thread) = this.as_native_thread(cx) {
7330 thread.update(cx, |thread, cx| {
7331 thread.set_thinking_enabled(!thread.thinking_enabled(), cx);
7332 });
7333 }
7334 }))
7335 .on_action(cx.listener(|this, _: &CycleThinkingEffort, _window, cx| {
7336 this.cycle_thinking_effort(cx);
7337 }))
7338 .on_action(cx.listener(Self::toggle_thinking_effort_menu))
7339 .on_action(cx.listener(|this, _: &SendNextQueuedMessage, window, cx| {
7340 this.send_queued_message_at_index(0, true, window, cx);
7341 }))
7342 .on_action(cx.listener(|this, _: &RemoveFirstQueuedMessage, _, cx| {
7343 this.remove_from_queue(0, cx);
7344 cx.notify();
7345 }))
7346 .on_action(cx.listener(|this, _: &EditFirstQueuedMessage, window, cx| {
7347 if let Some(editor) = this.queued_message_editors.first() {
7348 window.focus(&editor.focus_handle(cx), cx);
7349 }
7350 }))
7351 .on_action(cx.listener(|this, _: &ClearMessageQueue, _, cx| {
7352 this.local_queued_messages.clear();
7353 this.sync_queue_flag_to_native_thread(cx);
7354 this.can_fast_track_queue = false;
7355 cx.notify();
7356 }))
7357 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
7358 if let Some(config_options_view) = this.config_options_view.clone() {
7359 let handled = config_options_view.update(cx, |view, cx| {
7360 view.toggle_category_picker(
7361 acp::SessionConfigOptionCategory::Mode,
7362 window,
7363 cx,
7364 )
7365 });
7366 if handled {
7367 return;
7368 }
7369 }
7370
7371 if let Some(profile_selector) = this.profile_selector.clone() {
7372 profile_selector.read(cx).menu_handle().toggle(window, cx);
7373 } else if let Some(mode_selector) = this.mode_selector.clone() {
7374 mode_selector.read(cx).menu_handle().toggle(window, cx);
7375 }
7376 }))
7377 .on_action(cx.listener(|this, _: &CycleModeSelector, window, cx| {
7378 if let Some(config_options_view) = this.config_options_view.clone() {
7379 let handled = config_options_view.update(cx, |view, cx| {
7380 view.cycle_category_option(
7381 acp::SessionConfigOptionCategory::Mode,
7382 false,
7383 cx,
7384 )
7385 });
7386 if handled {
7387 return;
7388 }
7389 }
7390
7391 if let Some(profile_selector) = this.profile_selector.clone() {
7392 profile_selector.update(cx, |profile_selector, cx| {
7393 profile_selector.cycle_profile(cx);
7394 });
7395 } else if let Some(mode_selector) = this.mode_selector.clone() {
7396 mode_selector.update(cx, |mode_selector, cx| {
7397 mode_selector.cycle_mode(window, cx);
7398 });
7399 }
7400 }))
7401 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
7402 if let Some(config_options_view) = this.config_options_view.clone() {
7403 let handled = config_options_view.update(cx, |view, cx| {
7404 view.toggle_category_picker(
7405 acp::SessionConfigOptionCategory::Model,
7406 window,
7407 cx,
7408 )
7409 });
7410 if handled {
7411 return;
7412 }
7413 }
7414
7415 if let Some(model_selector) = this.model_selector.clone() {
7416 model_selector
7417 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
7418 }
7419 }))
7420 .on_action(cx.listener(|this, _: &CycleFavoriteModels, window, cx| {
7421 if let Some(config_options_view) = this.config_options_view.clone() {
7422 let handled = config_options_view.update(cx, |view, cx| {
7423 view.cycle_category_option(
7424 acp::SessionConfigOptionCategory::Model,
7425 true,
7426 cx,
7427 )
7428 });
7429 if handled {
7430 return;
7431 }
7432 }
7433
7434 if let Some(model_selector) = this.model_selector.clone() {
7435 model_selector.update(cx, |model_selector, cx| {
7436 model_selector.cycle_favorite_models(window, cx);
7437 });
7438 }
7439 }))
7440 .size_full()
7441 .children(self.render_subagent_titlebar(cx))
7442 .child(conversation)
7443 .children(self.render_activity_bar(window, cx))
7444 .when(self.show_codex_windows_warning, |this| {
7445 this.child(self.render_codex_windows_warning(cx))
7446 })
7447 .children(self.render_thread_retry_status_callout())
7448 .children(self.render_thread_error(window, cx))
7449 .when_some(
7450 match has_messages {
7451 true => None,
7452 false => self.new_server_version_available.clone(),
7453 },
7454 |this, version| this.child(self.render_new_version_callout(&version, cx)),
7455 )
7456 .children(self.render_token_limit_callout(cx))
7457 .child(self.render_message_editor(window, cx))
7458 }
7459}
7460
7461pub(crate) fn open_link(
7462 url: SharedString,
7463 workspace: &WeakEntity<Workspace>,
7464 window: &mut Window,
7465 cx: &mut App,
7466) {
7467 let Some(workspace) = workspace.upgrade() else {
7468 cx.open_url(&url);
7469 return;
7470 };
7471
7472 if let Some(mention) = MentionUri::parse(&url, workspace.read(cx).path_style(cx)).log_err() {
7473 workspace.update(cx, |workspace, cx| match mention {
7474 MentionUri::File { abs_path } => {
7475 let project = workspace.project();
7476 let Some(path) =
7477 project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
7478 else {
7479 return;
7480 };
7481
7482 workspace
7483 .open_path(path, None, true, window, cx)
7484 .detach_and_log_err(cx);
7485 }
7486 MentionUri::PastedImage => {}
7487 MentionUri::Directory { abs_path } => {
7488 let project = workspace.project();
7489 let Some(entry_id) = project.update(cx, |project, cx| {
7490 let path = project.find_project_path(abs_path, cx)?;
7491 project.entry_for_path(&path, cx).map(|entry| entry.id)
7492 }) else {
7493 return;
7494 };
7495
7496 project.update(cx, |_, cx| {
7497 cx.emit(project::Event::RevealInProjectPanel(entry_id));
7498 });
7499 }
7500 MentionUri::Symbol {
7501 abs_path: path,
7502 line_range,
7503 ..
7504 }
7505 | MentionUri::Selection {
7506 abs_path: Some(path),
7507 line_range,
7508 } => {
7509 let project = workspace.project();
7510 let Some(path) =
7511 project.update(cx, |project, cx| project.find_project_path(path, cx))
7512 else {
7513 return;
7514 };
7515
7516 let item = workspace.open_path(path, None, true, window, cx);
7517 window
7518 .spawn(cx, async move |cx| {
7519 let Some(editor) = item.await?.downcast::<Editor>() else {
7520 return Ok(());
7521 };
7522 let range =
7523 Point::new(*line_range.start(), 0)..Point::new(*line_range.start(), 0);
7524 editor
7525 .update_in(cx, |editor, window, cx| {
7526 editor.change_selections(
7527 SelectionEffects::scroll(Autoscroll::center()),
7528 window,
7529 cx,
7530 |s| s.select_ranges(vec![range]),
7531 );
7532 })
7533 .ok();
7534 anyhow::Ok(())
7535 })
7536 .detach_and_log_err(cx);
7537 }
7538 MentionUri::Selection { abs_path: None, .. } => {}
7539 MentionUri::Thread { id, name } => {
7540 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
7541 panel.update(cx, |panel, cx| {
7542 panel.open_thread(
7543 AgentSessionInfo {
7544 session_id: id,
7545 cwd: None,
7546 title: Some(name.into()),
7547 updated_at: None,
7548 meta: None,
7549 },
7550 window,
7551 cx,
7552 )
7553 });
7554 }
7555 }
7556 MentionUri::TextThread { path, .. } => {
7557 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
7558 panel.update(cx, |panel, cx| {
7559 panel
7560 .open_saved_text_thread(path.as_path().into(), window, cx)
7561 .detach_and_log_err(cx);
7562 });
7563 }
7564 }
7565 MentionUri::Rule { id, .. } => {
7566 let PromptId::User { uuid } = id else {
7567 return;
7568 };
7569 window.dispatch_action(
7570 Box::new(OpenRulesLibrary {
7571 prompt_to_select: Some(uuid.0),
7572 }),
7573 cx,
7574 )
7575 }
7576 MentionUri::Fetch { url } => {
7577 cx.open_url(url.as_str());
7578 }
7579 MentionUri::Diagnostics { .. } => {}
7580 MentionUri::TerminalSelection { .. } => {}
7581 MentionUri::GitDiff { .. } => {}
7582 })
7583 } else {
7584 cx.open_url(&url);
7585 }
7586}