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