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