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