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