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