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