1use acp_thread::{
2 AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk,
3 LoadError, MentionUri, ThreadStatus, ToolCall, ToolCallContent, ToolCallStatus,
4};
5use acp_thread::{AgentConnection, Plan};
6use action_log::ActionLog;
7use agent_client_protocol as acp;
8use agent_servers::AgentServer;
9use agent_settings::{AgentSettings, NotifyWhenAgentWaiting};
10use audio::{Audio, Sound};
11use buffer_diff::BufferDiff;
12use collections::{HashMap, HashSet};
13use editor::{Editor, EditorMode, MinimapVisibility, MultiBuffer, PathKey};
14use file_icons::FileIcons;
15use gpui::{
16 Action, Animation, AnimationExt, App, BorderStyle, EdgesRefinement, Empty, Entity, EntityId,
17 FocusHandle, Focusable, Hsla, Length, ListOffset, ListState, MouseButton, PlatformDisplay,
18 SharedString, Stateful, StyleRefinement, Subscription, Task, TextStyle, TextStyleRefinement,
19 Transformation, UnderlineStyle, WeakEntity, Window, WindowHandle, div, linear_color_stop,
20 linear_gradient, list, percentage, point, prelude::*, pulsating_between,
21};
22use language::Buffer;
23use language::language_settings::SoftWrap;
24use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
25use project::Project;
26use rope::Point;
27use settings::{Settings as _, SettingsStore};
28use std::{cell::RefCell, collections::BTreeMap, process::ExitStatus, rc::Rc, time::Duration};
29use terminal_view::TerminalView;
30use text::Anchor;
31use theme::ThemeSettings;
32use ui::{
33 Disclosure, Divider, DividerColor, KeyBinding, PopoverMenuHandle, Scrollbar, ScrollbarState,
34 Tooltip, prelude::*,
35};
36use util::{ResultExt, size::format_file_size, time::duration_alt_display};
37use workspace::{CollaboratorId, Workspace};
38use zed_actions::agent::{Chat, ToggleModelSelector};
39
40use crate::acp::AcpModelSelectorPopover;
41use crate::acp::message_editor::{MessageEditor, MessageEditorEvent};
42use crate::acp::message_history::MessageHistory;
43use crate::agent_diff::AgentDiff;
44use crate::ui::{AgentNotification, AgentNotificationEvent};
45use crate::{
46 AgentDiffPane, AgentPanel, ExpandMessageEditor, Follow, KeepAll, OpenAgentDiff, RejectAll,
47};
48
49const RESPONSE_PADDING_X: Pixels = px(19.);
50
51pub struct AcpThreadView {
52 agent: Rc<dyn AgentServer>,
53 workspace: WeakEntity<Workspace>,
54 project: Entity<Project>,
55 thread_state: ThreadState,
56 diff_editors: HashMap<EntityId, Entity<Editor>>,
57 terminal_views: HashMap<EntityId, Entity<TerminalView>>,
58 message_editor: Entity<MessageEditor>,
59 model_selector: Option<Entity<AcpModelSelectorPopover>>,
60 notifications: Vec<WindowHandle<AgentNotification>>,
61 notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
62 last_error: Option<Entity<Markdown>>,
63 list_state: ListState,
64 scrollbar_state: ScrollbarState,
65 auth_task: Option<Task<()>>,
66 expanded_tool_calls: HashSet<acp::ToolCallId>,
67 expanded_thinking_blocks: HashSet<(usize, usize)>,
68 edits_expanded: bool,
69 plan_expanded: bool,
70 editor_expanded: bool,
71 terminal_expanded: bool,
72 message_history: Rc<RefCell<MessageHistory<Vec<acp::ContentBlock>>>>,
73 _cancel_task: Option<Task<()>>,
74 _subscriptions: [Subscription; 2],
75}
76
77enum ThreadState {
78 Loading {
79 _task: Task<()>,
80 },
81 Ready {
82 thread: Entity<AcpThread>,
83 _subscription: [Subscription; 2],
84 },
85 LoadError(LoadError),
86 Unauthenticated {
87 connection: Rc<dyn AgentConnection>,
88 },
89 ServerExited {
90 status: ExitStatus,
91 },
92}
93
94impl AcpThreadView {
95 pub fn new(
96 agent: Rc<dyn AgentServer>,
97 workspace: WeakEntity<Workspace>,
98 project: Entity<Project>,
99 message_history: Rc<RefCell<MessageHistory<Vec<acp::ContentBlock>>>>,
100 window: &mut Window,
101 cx: &mut Context<Self>,
102 ) -> Self {
103 let message_editor = cx.new(|cx| {
104 MessageEditor::new(
105 workspace.clone(),
106 project.clone(),
107 message_history.clone(),
108 window,
109 cx,
110 )
111 });
112
113 let list_state = ListState::new(0, gpui::ListAlignment::Bottom, px(2048.0));
114
115 let subscriptions = [
116 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
117 cx.subscribe_in(&message_editor, window, Self::on_message_editor_event),
118 ];
119
120 Self {
121 agent: agent.clone(),
122 workspace: workspace.clone(),
123 project: project.clone(),
124 thread_state: Self::initial_state(agent, workspace, project, window, cx),
125 message_editor,
126 model_selector: None,
127 notifications: Vec::new(),
128 notification_subscriptions: HashMap::default(),
129 diff_editors: Default::default(),
130 terminal_views: Default::default(),
131 list_state: list_state.clone(),
132 scrollbar_state: ScrollbarState::new(list_state).parent_entity(&cx.entity()),
133 last_error: None,
134 auth_task: None,
135 expanded_tool_calls: HashSet::default(),
136 expanded_thinking_blocks: HashSet::default(),
137 edits_expanded: false,
138 plan_expanded: false,
139 editor_expanded: false,
140 terminal_expanded: true,
141 message_history,
142 _subscriptions: subscriptions,
143 _cancel_task: None,
144 }
145 }
146
147 fn initial_state(
148 agent: Rc<dyn AgentServer>,
149 workspace: WeakEntity<Workspace>,
150 project: Entity<Project>,
151 window: &mut Window,
152 cx: &mut Context<Self>,
153 ) -> ThreadState {
154 let root_dir = project
155 .read(cx)
156 .visible_worktrees(cx)
157 .next()
158 .map(|worktree| worktree.read(cx).abs_path())
159 .unwrap_or_else(|| paths::home_dir().as_path().into());
160
161 let connect_task = agent.connect(&root_dir, &project, cx);
162 let load_task = cx.spawn_in(window, async move |this, cx| {
163 let connection = match connect_task.await {
164 Ok(connection) => connection,
165 Err(err) => {
166 this.update(cx, |this, cx| {
167 this.handle_load_error(err, cx);
168 cx.notify();
169 })
170 .log_err();
171 return;
172 }
173 };
174
175 // this.update_in(cx, |_this, _window, cx| {
176 // let status = connection.exit_status(cx);
177 // cx.spawn(async move |this, cx| {
178 // let status = status.await.ok();
179 // this.update(cx, |this, cx| {
180 // this.thread_state = ThreadState::ServerExited { status };
181 // cx.notify();
182 // })
183 // .ok();
184 // })
185 // .detach();
186 // })
187 // .ok();
188
189 let result = match connection
190 .clone()
191 .new_thread(project.clone(), &root_dir, cx)
192 .await
193 {
194 Err(e) => {
195 let mut cx = cx.clone();
196 if e.is::<acp_thread::AuthRequired>() {
197 this.update(&mut cx, |this, cx| {
198 this.thread_state = ThreadState::Unauthenticated { connection };
199 cx.notify();
200 })
201 .ok();
202 return;
203 } else {
204 Err(e)
205 }
206 }
207 Ok(thread) => Ok(thread),
208 };
209
210 this.update_in(cx, |this, window, cx| {
211 match result {
212 Ok(thread) => {
213 let thread_subscription =
214 cx.subscribe_in(&thread, window, Self::handle_thread_event);
215
216 let action_log = thread.read(cx).action_log().clone();
217 let action_log_subscription =
218 cx.observe(&action_log, |_, _, cx| cx.notify());
219
220 this.list_state
221 .splice(0..0, thread.read(cx).entries().len());
222
223 AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
224
225 this.model_selector =
226 thread
227 .read(cx)
228 .connection()
229 .model_selector()
230 .map(|selector| {
231 cx.new(|cx| {
232 AcpModelSelectorPopover::new(
233 thread.read(cx).session_id().clone(),
234 selector,
235 PopoverMenuHandle::default(),
236 this.focus_handle(cx),
237 window,
238 cx,
239 )
240 })
241 });
242
243 this.thread_state = ThreadState::Ready {
244 thread,
245 _subscription: [thread_subscription, action_log_subscription],
246 };
247
248 cx.notify();
249 }
250 Err(err) => {
251 this.handle_load_error(err, cx);
252 }
253 };
254 })
255 .log_err();
256 });
257
258 ThreadState::Loading { _task: load_task }
259 }
260
261 fn handle_load_error(&mut self, err: anyhow::Error, cx: &mut Context<Self>) {
262 if let Some(load_err) = err.downcast_ref::<LoadError>() {
263 self.thread_state = ThreadState::LoadError(load_err.clone());
264 } else {
265 self.thread_state = ThreadState::LoadError(LoadError::Other(err.to_string().into()))
266 }
267 cx.notify();
268 }
269
270 pub fn thread(&self) -> Option<&Entity<AcpThread>> {
271 match &self.thread_state {
272 ThreadState::Ready { thread, .. } => Some(thread),
273 ThreadState::Unauthenticated { .. }
274 | ThreadState::Loading { .. }
275 | ThreadState::LoadError(..)
276 | ThreadState::ServerExited { .. } => None,
277 }
278 }
279
280 pub fn title(&self, cx: &App) -> SharedString {
281 match &self.thread_state {
282 ThreadState::Ready { thread, .. } => thread.read(cx).title(),
283 ThreadState::Loading { .. } => "Loading…".into(),
284 ThreadState::LoadError(_) => "Failed to load".into(),
285 ThreadState::Unauthenticated { .. } => "Not authenticated".into(),
286 ThreadState::ServerExited { .. } => "Server exited unexpectedly".into(),
287 }
288 }
289
290 pub fn cancel(&mut self, cx: &mut Context<Self>) {
291 self.last_error.take();
292
293 if let Some(thread) = self.thread() {
294 self._cancel_task = Some(thread.update(cx, |thread, cx| thread.cancel(cx)));
295 }
296 }
297
298 pub fn expand_message_editor(
299 &mut self,
300 _: &ExpandMessageEditor,
301 _window: &mut Window,
302 cx: &mut Context<Self>,
303 ) {
304 self.set_editor_is_expanded(!self.editor_expanded, cx);
305 cx.notify();
306 }
307
308 fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
309 self.editor_expanded = is_expanded;
310 self.message_editor.update(cx, |editor, cx| {
311 editor.set_expanded(is_expanded, cx);
312 });
313 cx.notify();
314 }
315
316 pub fn on_message_editor_event(
317 &mut self,
318 _: &Entity<MessageEditor>,
319 event: &MessageEditorEvent,
320 window: &mut Window,
321 cx: &mut Context<Self>,
322 ) {
323 match event {
324 MessageEditorEvent::Chat => self.chat(window, cx),
325 }
326 }
327
328 fn chat(&mut self, window: &mut Window, cx: &mut Context<Self>) {
329 self.last_error.take();
330
331 let Some(thread) = self.thread().cloned() else {
332 return;
333 };
334
335 let contents = self
336 .message_editor
337 .update(cx, |message_editor, cx| message_editor.contents(cx));
338 let task = cx.spawn_in(window, async move |this, cx| {
339 let contents = contents.await?;
340
341 if contents.is_empty() {
342 return Ok(());
343 }
344
345 this.update_in(cx, |this, window, cx| {
346 this.set_editor_is_expanded(false, cx);
347 this.scroll_to_bottom(cx);
348 this.message_editor.update(cx, |message_editor, cx| {
349 message_editor.clear(window, cx);
350 });
351 this.message_history.borrow_mut().push(contents.clone());
352 })?;
353 let send = thread.update(cx, |thread, cx| thread.send(contents, cx))?;
354 send.await
355 });
356
357 cx.spawn(async move |this, cx| {
358 if let Err(e) = task.await {
359 this.update(cx, |this, cx| {
360 this.last_error =
361 Some(cx.new(|cx| Markdown::new(e.to_string().into(), None, None, cx)));
362 cx.notify()
363 })
364 .ok();
365 }
366 })
367 .detach();
368 }
369
370 fn open_agent_diff(&mut self, _: &OpenAgentDiff, window: &mut Window, cx: &mut Context<Self>) {
371 if let Some(thread) = self.thread() {
372 AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err();
373 }
374 }
375
376 fn open_edited_buffer(
377 &mut self,
378 buffer: &Entity<Buffer>,
379 window: &mut Window,
380 cx: &mut Context<Self>,
381 ) {
382 let Some(thread) = self.thread() else {
383 return;
384 };
385
386 let Some(diff) =
387 AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
388 else {
389 return;
390 };
391
392 diff.update(cx, |diff, cx| {
393 diff.move_to_path(PathKey::for_buffer(&buffer, cx), window, cx)
394 })
395 }
396
397 fn handle_thread_event(
398 &mut self,
399 thread: &Entity<AcpThread>,
400 event: &AcpThreadEvent,
401 window: &mut Window,
402 cx: &mut Context<Self>,
403 ) {
404 match event {
405 AcpThreadEvent::NewEntry => {
406 let index = thread.read(cx).entries().len() - 1;
407 self.sync_thread_entry_view(index, window, cx);
408 self.list_state.splice(index..index, 1);
409 }
410 AcpThreadEvent::EntryUpdated(index) => {
411 self.sync_thread_entry_view(*index, window, cx);
412 self.list_state.splice(*index..index + 1, 1);
413 }
414 AcpThreadEvent::EntriesRemoved(range) => {
415 // TODO: Clean up unused diff editors and terminal views
416 self.list_state.splice(range.clone(), 0);
417 }
418 AcpThreadEvent::ToolAuthorizationRequired => {
419 self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
420 }
421 AcpThreadEvent::Stopped => {
422 let used_tools = thread.read(cx).used_tools_since_last_user_message();
423 self.notify_with_sound(
424 if used_tools {
425 "Finished running tools"
426 } else {
427 "New message"
428 },
429 IconName::ZedAssistant,
430 window,
431 cx,
432 );
433 }
434 AcpThreadEvent::Error => {
435 self.notify_with_sound(
436 "Agent stopped due to an error",
437 IconName::Warning,
438 window,
439 cx,
440 );
441 }
442 AcpThreadEvent::ServerExited(status) => {
443 self.thread_state = ThreadState::ServerExited { status: *status };
444 }
445 }
446 cx.notify();
447 }
448
449 fn sync_thread_entry_view(
450 &mut self,
451 entry_ix: usize,
452 window: &mut Window,
453 cx: &mut Context<Self>,
454 ) {
455 self.sync_diff_multibuffers(entry_ix, window, cx);
456 self.sync_terminals(entry_ix, window, cx);
457 }
458
459 fn sync_diff_multibuffers(
460 &mut self,
461 entry_ix: usize,
462 window: &mut Window,
463 cx: &mut Context<Self>,
464 ) {
465 let Some(multibuffers) = self.entry_diff_multibuffers(entry_ix, cx) else {
466 return;
467 };
468
469 let multibuffers = multibuffers.collect::<Vec<_>>();
470
471 for multibuffer in multibuffers {
472 if self.diff_editors.contains_key(&multibuffer.entity_id()) {
473 return;
474 }
475
476 let editor = cx.new(|cx| {
477 let mut editor = Editor::new(
478 EditorMode::Full {
479 scale_ui_elements_with_buffer_font_size: false,
480 show_active_line_background: false,
481 sized_by_content: true,
482 },
483 multibuffer.clone(),
484 None,
485 window,
486 cx,
487 );
488 editor.set_show_gutter(false, cx);
489 editor.disable_inline_diagnostics();
490 editor.disable_expand_excerpt_buttons(cx);
491 editor.set_show_vertical_scrollbar(false, cx);
492 editor.set_minimap_visibility(MinimapVisibility::Disabled, window, cx);
493 editor.set_soft_wrap_mode(SoftWrap::None, cx);
494 editor.scroll_manager.set_forbid_vertical_scroll(true);
495 editor.set_show_indent_guides(false, cx);
496 editor.set_read_only(true);
497 editor.set_show_breakpoints(false, cx);
498 editor.set_show_code_actions(false, cx);
499 editor.set_show_git_diff_gutter(false, cx);
500 editor.set_expand_all_diff_hunks(cx);
501 editor.set_text_style_refinement(diff_editor_text_style_refinement(cx));
502 editor
503 });
504 let entity_id = multibuffer.entity_id();
505 cx.observe_release(&multibuffer, move |this, _, _| {
506 this.diff_editors.remove(&entity_id);
507 })
508 .detach();
509
510 self.diff_editors.insert(entity_id, editor);
511 }
512 }
513
514 fn entry_diff_multibuffers(
515 &self,
516 entry_ix: usize,
517 cx: &App,
518 ) -> Option<impl Iterator<Item = Entity<MultiBuffer>>> {
519 let entry = self.thread()?.read(cx).entries().get(entry_ix)?;
520 Some(
521 entry
522 .diffs()
523 .map(|diff| diff.read(cx).multibuffer().clone()),
524 )
525 }
526
527 fn sync_terminals(&mut self, entry_ix: usize, window: &mut Window, cx: &mut Context<Self>) {
528 let Some(terminals) = self.entry_terminals(entry_ix, cx) else {
529 return;
530 };
531
532 let terminals = terminals.collect::<Vec<_>>();
533
534 for terminal in terminals {
535 if self.terminal_views.contains_key(&terminal.entity_id()) {
536 return;
537 }
538
539 let terminal_view = cx.new(|cx| {
540 let mut view = TerminalView::new(
541 terminal.read(cx).inner().clone(),
542 self.workspace.clone(),
543 None,
544 self.project.downgrade(),
545 window,
546 cx,
547 );
548 view.set_embedded_mode(Some(1000), cx);
549 view
550 });
551
552 let entity_id = terminal.entity_id();
553 cx.observe_release(&terminal, move |this, _, _| {
554 this.terminal_views.remove(&entity_id);
555 })
556 .detach();
557
558 self.terminal_views.insert(entity_id, terminal_view);
559 }
560 }
561
562 fn entry_terminals(
563 &self,
564 entry_ix: usize,
565 cx: &App,
566 ) -> Option<impl Iterator<Item = Entity<acp_thread::Terminal>>> {
567 let entry = self.thread()?.read(cx).entries().get(entry_ix)?;
568 Some(entry.terminals().map(|terminal| terminal.clone()))
569 }
570
571 fn authenticate(
572 &mut self,
573 method: acp::AuthMethodId,
574 window: &mut Window,
575 cx: &mut Context<Self>,
576 ) {
577 let ThreadState::Unauthenticated { ref connection } = self.thread_state else {
578 return;
579 };
580
581 self.last_error.take();
582 let authenticate = connection.authenticate(method, cx);
583 self.auth_task = Some(cx.spawn_in(window, {
584 let project = self.project.clone();
585 let agent = self.agent.clone();
586 async move |this, cx| {
587 let result = authenticate.await;
588
589 this.update_in(cx, |this, window, cx| {
590 if let Err(err) = result {
591 this.last_error = Some(cx.new(|cx| {
592 Markdown::new(format!("Error: {err}").into(), None, None, cx)
593 }))
594 } else {
595 this.thread_state = Self::initial_state(
596 agent,
597 this.workspace.clone(),
598 project.clone(),
599 window,
600 cx,
601 )
602 }
603 this.auth_task.take()
604 })
605 .ok();
606 }
607 }));
608 }
609
610 fn authorize_tool_call(
611 &mut self,
612 tool_call_id: acp::ToolCallId,
613 option_id: acp::PermissionOptionId,
614 option_kind: acp::PermissionOptionKind,
615 cx: &mut Context<Self>,
616 ) {
617 let Some(thread) = self.thread() else {
618 return;
619 };
620 thread.update(cx, |thread, cx| {
621 thread.authorize_tool_call(tool_call_id, option_id, option_kind, cx);
622 });
623 cx.notify();
624 }
625
626 fn render_entry(
627 &self,
628 index: usize,
629 total_entries: usize,
630 entry: &AgentThreadEntry,
631 window: &mut Window,
632 cx: &Context<Self>,
633 ) -> AnyElement {
634 let primary = match &entry {
635 AgentThreadEntry::UserMessage(message) => div()
636 .py_4()
637 .px_2()
638 .child(
639 v_flex()
640 .p_3()
641 .gap_1p5()
642 .rounded_lg()
643 .shadow_md()
644 .bg(cx.theme().colors().editor_background)
645 .border_1()
646 .border_color(cx.theme().colors().border)
647 .text_xs()
648 .children(message.content.markdown().map(|md| {
649 self.render_markdown(
650 md.clone(),
651 user_message_markdown_style(window, cx),
652 )
653 })),
654 )
655 .into_any(),
656 AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) => {
657 let style = default_markdown_style(false, window, cx);
658 let message_body = v_flex()
659 .w_full()
660 .gap_2p5()
661 .children(chunks.iter().enumerate().filter_map(
662 |(chunk_ix, chunk)| match chunk {
663 AssistantMessageChunk::Message { block } => {
664 block.markdown().map(|md| {
665 self.render_markdown(md.clone(), style.clone())
666 .into_any_element()
667 })
668 }
669 AssistantMessageChunk::Thought { block } => {
670 block.markdown().map(|md| {
671 self.render_thinking_block(
672 index,
673 chunk_ix,
674 md.clone(),
675 window,
676 cx,
677 )
678 .into_any_element()
679 })
680 }
681 },
682 ))
683 .into_any();
684
685 v_flex()
686 .px_5()
687 .py_1()
688 .when(index + 1 == total_entries, |this| this.pb_4())
689 .w_full()
690 .text_ui(cx)
691 .child(message_body)
692 .into_any()
693 }
694 AgentThreadEntry::ToolCall(tool_call) => {
695 let has_terminals = tool_call.terminals().next().is_some();
696
697 div().w_full().py_1p5().px_5().map(|this| {
698 if has_terminals {
699 this.children(tool_call.terminals().map(|terminal| {
700 self.render_terminal_tool_call(terminal, tool_call, window, cx)
701 }))
702 } else {
703 this.child(self.render_tool_call(index, tool_call, window, cx))
704 }
705 })
706 }
707 .into_any(),
708 };
709
710 let Some(thread) = self.thread() else {
711 return primary;
712 };
713
714 let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
715 if index == total_entries - 1 && !is_generating {
716 v_flex()
717 .w_full()
718 .child(primary)
719 .child(self.render_thread_controls(cx))
720 .into_any_element()
721 } else {
722 primary
723 }
724 }
725
726 fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
727 cx.theme()
728 .colors()
729 .element_background
730 .blend(cx.theme().colors().editor_foreground.opacity(0.025))
731 }
732
733 fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
734 cx.theme().colors().border.opacity(0.6)
735 }
736
737 fn tool_name_font_size(&self) -> Rems {
738 rems_from_px(13.)
739 }
740
741 fn render_thinking_block(
742 &self,
743 entry_ix: usize,
744 chunk_ix: usize,
745 chunk: Entity<Markdown>,
746 window: &Window,
747 cx: &Context<Self>,
748 ) -> AnyElement {
749 let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
750 let card_header_id = SharedString::from("inner-card-header");
751 let key = (entry_ix, chunk_ix);
752 let is_open = self.expanded_thinking_blocks.contains(&key);
753
754 v_flex()
755 .child(
756 h_flex()
757 .id(header_id)
758 .group(&card_header_id)
759 .relative()
760 .w_full()
761 .gap_1p5()
762 .opacity(0.8)
763 .hover(|style| style.opacity(1.))
764 .child(
765 h_flex()
766 .size_4()
767 .justify_center()
768 .child(
769 div()
770 .group_hover(&card_header_id, |s| s.invisible().w_0())
771 .child(
772 Icon::new(IconName::ToolThink)
773 .size(IconSize::Small)
774 .color(Color::Muted),
775 ),
776 )
777 .child(
778 h_flex()
779 .absolute()
780 .inset_0()
781 .invisible()
782 .justify_center()
783 .group_hover(&card_header_id, |s| s.visible())
784 .child(
785 Disclosure::new(("expand", entry_ix), is_open)
786 .opened_icon(IconName::ChevronUp)
787 .closed_icon(IconName::ChevronRight)
788 .on_click(cx.listener({
789 move |this, _event, _window, cx| {
790 if is_open {
791 this.expanded_thinking_blocks.remove(&key);
792 } else {
793 this.expanded_thinking_blocks.insert(key);
794 }
795 cx.notify();
796 }
797 })),
798 ),
799 ),
800 )
801 .child(
802 div()
803 .text_size(self.tool_name_font_size())
804 .child("Thinking"),
805 )
806 .on_click(cx.listener({
807 move |this, _event, _window, cx| {
808 if is_open {
809 this.expanded_thinking_blocks.remove(&key);
810 } else {
811 this.expanded_thinking_blocks.insert(key);
812 }
813 cx.notify();
814 }
815 })),
816 )
817 .when(is_open, |this| {
818 this.child(
819 div()
820 .relative()
821 .mt_1p5()
822 .ml(px(7.))
823 .pl_4()
824 .border_l_1()
825 .border_color(self.tool_card_border_color(cx))
826 .text_ui_sm(cx)
827 .child(
828 self.render_markdown(chunk, default_markdown_style(false, window, cx)),
829 ),
830 )
831 })
832 .into_any_element()
833 }
834
835 fn render_tool_call_icon(
836 &self,
837 group_name: SharedString,
838 entry_ix: usize,
839 is_collapsible: bool,
840 is_open: bool,
841 tool_call: &ToolCall,
842 cx: &Context<Self>,
843 ) -> Div {
844 let tool_icon = Icon::new(match tool_call.kind {
845 acp::ToolKind::Read => IconName::ToolRead,
846 acp::ToolKind::Edit => IconName::ToolPencil,
847 acp::ToolKind::Delete => IconName::ToolDeleteFile,
848 acp::ToolKind::Move => IconName::ArrowRightLeft,
849 acp::ToolKind::Search => IconName::ToolSearch,
850 acp::ToolKind::Execute => IconName::ToolTerminal,
851 acp::ToolKind::Think => IconName::ToolThink,
852 acp::ToolKind::Fetch => IconName::ToolWeb,
853 acp::ToolKind::Other => IconName::ToolHammer,
854 })
855 .size(IconSize::Small)
856 .color(Color::Muted);
857
858 let base_container = h_flex().size_4().justify_center();
859
860 if is_collapsible {
861 base_container
862 .child(
863 div()
864 .group_hover(&group_name, |s| s.invisible().w_0())
865 .child(tool_icon),
866 )
867 .child(
868 h_flex()
869 .absolute()
870 .inset_0()
871 .invisible()
872 .justify_center()
873 .group_hover(&group_name, |s| s.visible())
874 .child(
875 Disclosure::new(("expand", entry_ix), is_open)
876 .opened_icon(IconName::ChevronUp)
877 .closed_icon(IconName::ChevronRight)
878 .on_click(cx.listener({
879 let id = tool_call.id.clone();
880 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
881 if is_open {
882 this.expanded_tool_calls.remove(&id);
883 } else {
884 this.expanded_tool_calls.insert(id.clone());
885 }
886 cx.notify();
887 }
888 })),
889 ),
890 )
891 } else {
892 base_container.child(tool_icon)
893 }
894 }
895
896 fn render_tool_call(
897 &self,
898 entry_ix: usize,
899 tool_call: &ToolCall,
900 window: &Window,
901 cx: &Context<Self>,
902 ) -> Div {
903 let header_id = SharedString::from(format!("outer-tool-call-header-{}", entry_ix));
904 let card_header_id = SharedString::from("inner-tool-call-header");
905
906 let status_icon = match &tool_call.status {
907 ToolCallStatus::Allowed {
908 status: acp::ToolCallStatus::Pending,
909 }
910 | ToolCallStatus::WaitingForConfirmation { .. } => None,
911 ToolCallStatus::Allowed {
912 status: acp::ToolCallStatus::InProgress,
913 ..
914 } => Some(
915 Icon::new(IconName::ArrowCircle)
916 .color(Color::Accent)
917 .size(IconSize::Small)
918 .with_animation(
919 "running",
920 Animation::new(Duration::from_secs(2)).repeat(),
921 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
922 )
923 .into_any(),
924 ),
925 ToolCallStatus::Allowed {
926 status: acp::ToolCallStatus::Completed,
927 ..
928 } => None,
929 ToolCallStatus::Rejected
930 | ToolCallStatus::Canceled
931 | ToolCallStatus::Allowed {
932 status: acp::ToolCallStatus::Failed,
933 ..
934 } => Some(
935 Icon::new(IconName::Close)
936 .color(Color::Error)
937 .size(IconSize::Small)
938 .into_any_element(),
939 ),
940 };
941
942 let needs_confirmation = matches!(
943 tool_call.status,
944 ToolCallStatus::WaitingForConfirmation { .. }
945 );
946 let is_edit = matches!(tool_call.kind, acp::ToolKind::Edit);
947 let has_diff = tool_call
948 .content
949 .iter()
950 .any(|content| matches!(content, ToolCallContent::Diff { .. }));
951 let has_nonempty_diff = tool_call.content.iter().any(|content| match content {
952 ToolCallContent::Diff(diff) => diff.read(cx).has_revealed_range(cx),
953 _ => false,
954 });
955 let use_card_layout = needs_confirmation || is_edit || has_diff;
956
957 let is_collapsible = !tool_call.content.is_empty() && !use_card_layout;
958
959 let is_open = tool_call.content.is_empty()
960 || needs_confirmation
961 || has_nonempty_diff
962 || self.expanded_tool_calls.contains(&tool_call.id);
963
964 let gradient_overlay = |color: Hsla| {
965 div()
966 .absolute()
967 .top_0()
968 .right_0()
969 .w_12()
970 .h_full()
971 .bg(linear_gradient(
972 90.,
973 linear_color_stop(color, 1.),
974 linear_color_stop(color.opacity(0.2), 0.),
975 ))
976 };
977 let gradient_color = if use_card_layout {
978 self.tool_card_header_bg(cx)
979 } else {
980 cx.theme().colors().panel_background
981 };
982
983 let tool_output_display = match &tool_call.status {
984 ToolCallStatus::WaitingForConfirmation { options, .. } => v_flex()
985 .w_full()
986 .children(tool_call.content.iter().map(|content| {
987 div()
988 .child(self.render_tool_call_content(content, tool_call, window, cx))
989 .into_any_element()
990 }))
991 .child(self.render_permission_buttons(
992 options,
993 entry_ix,
994 tool_call.id.clone(),
995 tool_call.content.is_empty(),
996 cx,
997 )),
998 ToolCallStatus::Allowed { .. } | ToolCallStatus::Canceled => v_flex()
999 .w_full()
1000 .children(tool_call.content.iter().map(|content| {
1001 div()
1002 .child(self.render_tool_call_content(content, tool_call, window, cx))
1003 .into_any_element()
1004 })),
1005 ToolCallStatus::Rejected => v_flex().size_0(),
1006 };
1007
1008 v_flex()
1009 .when(use_card_layout, |this| {
1010 this.rounded_lg()
1011 .border_1()
1012 .border_color(self.tool_card_border_color(cx))
1013 .bg(cx.theme().colors().editor_background)
1014 .overflow_hidden()
1015 })
1016 .child(
1017 h_flex()
1018 .id(header_id)
1019 .w_full()
1020 .gap_1()
1021 .justify_between()
1022 .map(|this| {
1023 if use_card_layout {
1024 this.pl_2()
1025 .pr_1()
1026 .py_1()
1027 .rounded_t_md()
1028 .bg(self.tool_card_header_bg(cx))
1029 } else {
1030 this.opacity(0.8).hover(|style| style.opacity(1.))
1031 }
1032 })
1033 .child(
1034 h_flex()
1035 .group(&card_header_id)
1036 .relative()
1037 .w_full()
1038 .text_size(self.tool_name_font_size())
1039 .child(self.render_tool_call_icon(
1040 card_header_id,
1041 entry_ix,
1042 is_collapsible,
1043 is_open,
1044 tool_call,
1045 cx,
1046 ))
1047 .child(if tool_call.locations.len() == 1 {
1048 let name = tool_call.locations[0]
1049 .path
1050 .file_name()
1051 .unwrap_or_default()
1052 .display()
1053 .to_string();
1054
1055 h_flex()
1056 .id(("open-tool-call-location", entry_ix))
1057 .w_full()
1058 .max_w_full()
1059 .px_1p5()
1060 .rounded_sm()
1061 .overflow_x_scroll()
1062 .opacity(0.8)
1063 .hover(|label| {
1064 label.opacity(1.).bg(cx
1065 .theme()
1066 .colors()
1067 .element_hover
1068 .opacity(0.5))
1069 })
1070 .child(name)
1071 .tooltip(Tooltip::text("Jump to File"))
1072 .on_click(cx.listener(move |this, _, window, cx| {
1073 this.open_tool_call_location(entry_ix, 0, window, cx);
1074 }))
1075 .into_any_element()
1076 } else {
1077 h_flex()
1078 .id("non-card-label-container")
1079 .w_full()
1080 .relative()
1081 .ml_1p5()
1082 .overflow_hidden()
1083 .child(
1084 h_flex()
1085 .id("non-card-label")
1086 .pr_8()
1087 .w_full()
1088 .overflow_x_scroll()
1089 .child(self.render_markdown(
1090 tool_call.label.clone(),
1091 default_markdown_style(
1092 needs_confirmation || is_edit || has_diff,
1093 window,
1094 cx,
1095 ),
1096 )),
1097 )
1098 .child(gradient_overlay(gradient_color))
1099 .on_click(cx.listener({
1100 let id = tool_call.id.clone();
1101 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1102 if is_open {
1103 this.expanded_tool_calls.remove(&id);
1104 } else {
1105 this.expanded_tool_calls.insert(id.clone());
1106 }
1107 cx.notify();
1108 }
1109 }))
1110 .into_any()
1111 }),
1112 )
1113 .children(status_icon),
1114 )
1115 .when(is_open, |this| this.child(tool_output_display))
1116 }
1117
1118 fn render_tool_call_content(
1119 &self,
1120 content: &ToolCallContent,
1121 tool_call: &ToolCall,
1122 window: &Window,
1123 cx: &Context<Self>,
1124 ) -> AnyElement {
1125 match content {
1126 ToolCallContent::ContentBlock(content) => {
1127 if let Some(resource_link) = content.resource_link() {
1128 self.render_resource_link(resource_link, cx)
1129 } else if let Some(markdown) = content.markdown() {
1130 self.render_markdown_output(markdown.clone(), tool_call.id.clone(), window, cx)
1131 } else {
1132 Empty.into_any_element()
1133 }
1134 }
1135 ToolCallContent::Diff(diff) => {
1136 self.render_diff_editor(&diff.read(cx).multibuffer(), cx)
1137 }
1138 ToolCallContent::Terminal(terminal) => {
1139 self.render_terminal_tool_call(terminal, tool_call, window, cx)
1140 }
1141 }
1142 }
1143
1144 fn render_markdown_output(
1145 &self,
1146 markdown: Entity<Markdown>,
1147 tool_call_id: acp::ToolCallId,
1148 window: &Window,
1149 cx: &Context<Self>,
1150 ) -> AnyElement {
1151 let button_id = SharedString::from(format!("tool_output-{:?}", tool_call_id.clone()));
1152
1153 v_flex()
1154 .mt_1p5()
1155 .ml(px(7.))
1156 .px_3p5()
1157 .gap_2()
1158 .border_l_1()
1159 .border_color(self.tool_card_border_color(cx))
1160 .text_sm()
1161 .text_color(cx.theme().colors().text_muted)
1162 .child(self.render_markdown(markdown, default_markdown_style(false, window, cx)))
1163 .child(
1164 Button::new(button_id, "Collapse Output")
1165 .full_width()
1166 .style(ButtonStyle::Outlined)
1167 .label_size(LabelSize::Small)
1168 .icon(IconName::ChevronUp)
1169 .icon_color(Color::Muted)
1170 .icon_position(IconPosition::Start)
1171 .on_click(cx.listener({
1172 let id = tool_call_id.clone();
1173 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1174 this.expanded_tool_calls.remove(&id);
1175 cx.notify();
1176 }
1177 })),
1178 )
1179 .into_any_element()
1180 }
1181
1182 fn render_resource_link(
1183 &self,
1184 resource_link: &acp::ResourceLink,
1185 cx: &Context<Self>,
1186 ) -> AnyElement {
1187 let uri: SharedString = resource_link.uri.clone().into();
1188
1189 let label: SharedString = if let Some(path) = resource_link.uri.strip_prefix("file://") {
1190 path.to_string().into()
1191 } else {
1192 uri.clone()
1193 };
1194
1195 let button_id = SharedString::from(format!("item-{}", uri.clone()));
1196
1197 div()
1198 .ml(px(7.))
1199 .pl_2p5()
1200 .border_l_1()
1201 .border_color(self.tool_card_border_color(cx))
1202 .overflow_hidden()
1203 .child(
1204 Button::new(button_id, label)
1205 .label_size(LabelSize::Small)
1206 .color(Color::Muted)
1207 .icon(IconName::ArrowUpRight)
1208 .icon_size(IconSize::XSmall)
1209 .icon_color(Color::Muted)
1210 .truncate(true)
1211 .on_click(cx.listener({
1212 let workspace = self.workspace.clone();
1213 move |_, _, window, cx: &mut Context<Self>| {
1214 Self::open_link(uri.clone(), &workspace, window, cx);
1215 }
1216 })),
1217 )
1218 .into_any_element()
1219 }
1220
1221 fn render_permission_buttons(
1222 &self,
1223 options: &[acp::PermissionOption],
1224 entry_ix: usize,
1225 tool_call_id: acp::ToolCallId,
1226 empty_content: bool,
1227 cx: &Context<Self>,
1228 ) -> Div {
1229 h_flex()
1230 .py_1()
1231 .pl_2()
1232 .pr_1()
1233 .gap_1()
1234 .justify_between()
1235 .flex_wrap()
1236 .when(!empty_content, |this| {
1237 this.border_t_1()
1238 .border_color(self.tool_card_border_color(cx))
1239 })
1240 .child(
1241 div()
1242 .min_w(rems_from_px(145.))
1243 .child(LoadingLabel::new("Waiting for Confirmation").size(LabelSize::Small)),
1244 )
1245 .child(h_flex().gap_0p5().children(options.iter().map(|option| {
1246 let option_id = SharedString::from(option.id.0.clone());
1247 Button::new((option_id, entry_ix), option.name.clone())
1248 .map(|this| match option.kind {
1249 acp::PermissionOptionKind::AllowOnce => {
1250 this.icon(IconName::Check).icon_color(Color::Success)
1251 }
1252 acp::PermissionOptionKind::AllowAlways => {
1253 this.icon(IconName::CheckDouble).icon_color(Color::Success)
1254 }
1255 acp::PermissionOptionKind::RejectOnce => {
1256 this.icon(IconName::Close).icon_color(Color::Error)
1257 }
1258 acp::PermissionOptionKind::RejectAlways => {
1259 this.icon(IconName::Close).icon_color(Color::Error)
1260 }
1261 })
1262 .icon_position(IconPosition::Start)
1263 .icon_size(IconSize::XSmall)
1264 .label_size(LabelSize::Small)
1265 .on_click(cx.listener({
1266 let tool_call_id = tool_call_id.clone();
1267 let option_id = option.id.clone();
1268 let option_kind = option.kind;
1269 move |this, _, _, cx| {
1270 this.authorize_tool_call(
1271 tool_call_id.clone(),
1272 option_id.clone(),
1273 option_kind,
1274 cx,
1275 );
1276 }
1277 }))
1278 })))
1279 }
1280
1281 fn render_diff_editor(
1282 &self,
1283 multibuffer: &Entity<MultiBuffer>,
1284 cx: &Context<Self>,
1285 ) -> AnyElement {
1286 v_flex()
1287 .h_full()
1288 .border_t_1()
1289 .border_color(self.tool_card_border_color(cx))
1290 .child(
1291 if let Some(editor) = self.diff_editors.get(&multibuffer.entity_id()) {
1292 editor.clone().into_any_element()
1293 } else {
1294 Empty.into_any()
1295 },
1296 )
1297 .into_any()
1298 }
1299
1300 fn render_terminal_tool_call(
1301 &self,
1302 terminal: &Entity<acp_thread::Terminal>,
1303 tool_call: &ToolCall,
1304 window: &Window,
1305 cx: &Context<Self>,
1306 ) -> AnyElement {
1307 let terminal_data = terminal.read(cx);
1308 let working_dir = terminal_data.working_dir();
1309 let command = terminal_data.command();
1310 let started_at = terminal_data.started_at();
1311
1312 let tool_failed = matches!(
1313 &tool_call.status,
1314 ToolCallStatus::Rejected
1315 | ToolCallStatus::Canceled
1316 | ToolCallStatus::Allowed {
1317 status: acp::ToolCallStatus::Failed,
1318 ..
1319 }
1320 );
1321
1322 let output = terminal_data.output();
1323 let command_finished = output.is_some();
1324 let truncated_output = output.is_some_and(|output| output.was_content_truncated);
1325 let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
1326
1327 let command_failed = command_finished
1328 && output.is_some_and(|o| o.exit_status.is_none_or(|status| !status.success()));
1329
1330 let time_elapsed = if let Some(output) = output {
1331 output.ended_at.duration_since(started_at)
1332 } else {
1333 started_at.elapsed()
1334 };
1335
1336 let header_bg = cx
1337 .theme()
1338 .colors()
1339 .element_background
1340 .blend(cx.theme().colors().editor_foreground.opacity(0.025));
1341 let border_color = cx.theme().colors().border.opacity(0.6);
1342
1343 let working_dir = working_dir
1344 .as_ref()
1345 .map(|path| format!("{}", path.display()))
1346 .unwrap_or_else(|| "current directory".to_string());
1347
1348 let header = h_flex()
1349 .id(SharedString::from(format!(
1350 "terminal-tool-header-{}",
1351 terminal.entity_id()
1352 )))
1353 .flex_none()
1354 .gap_1()
1355 .justify_between()
1356 .rounded_t_md()
1357 .child(
1358 div()
1359 .id(("command-target-path", terminal.entity_id()))
1360 .w_full()
1361 .max_w_full()
1362 .overflow_x_scroll()
1363 .child(
1364 Label::new(working_dir)
1365 .buffer_font(cx)
1366 .size(LabelSize::XSmall)
1367 .color(Color::Muted),
1368 ),
1369 )
1370 .when(!command_finished, |header| {
1371 header
1372 .gap_1p5()
1373 .child(
1374 Button::new(
1375 SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
1376 "Stop",
1377 )
1378 .icon(IconName::Stop)
1379 .icon_position(IconPosition::Start)
1380 .icon_size(IconSize::Small)
1381 .icon_color(Color::Error)
1382 .label_size(LabelSize::Small)
1383 .tooltip(move |window, cx| {
1384 Tooltip::with_meta(
1385 "Stop This Command",
1386 None,
1387 "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
1388 window,
1389 cx,
1390 )
1391 })
1392 .on_click({
1393 let terminal = terminal.clone();
1394 cx.listener(move |_this, _event, _window, cx| {
1395 let inner_terminal = terminal.read(cx).inner().clone();
1396 inner_terminal.update(cx, |inner_terminal, _cx| {
1397 inner_terminal.kill_active_task();
1398 });
1399 })
1400 }),
1401 )
1402 .child(Divider::vertical())
1403 .child(
1404 Icon::new(IconName::ArrowCircle)
1405 .size(IconSize::XSmall)
1406 .color(Color::Info)
1407 .with_animation(
1408 "arrow-circle",
1409 Animation::new(Duration::from_secs(2)).repeat(),
1410 |icon, delta| {
1411 icon.transform(Transformation::rotate(percentage(delta)))
1412 },
1413 ),
1414 )
1415 })
1416 .when(tool_failed || command_failed, |header| {
1417 header.child(
1418 div()
1419 .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
1420 .child(
1421 Icon::new(IconName::Close)
1422 .size(IconSize::Small)
1423 .color(Color::Error),
1424 )
1425 .when_some(output.and_then(|o| o.exit_status), |this, status| {
1426 this.tooltip(Tooltip::text(format!(
1427 "Exited with code {}",
1428 status.code().unwrap_or(-1),
1429 )))
1430 }),
1431 )
1432 })
1433 .when(truncated_output, |header| {
1434 let tooltip = if let Some(output) = output {
1435 if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
1436 "Output exceeded terminal max lines and was \
1437 truncated, the model received the first 16 KB."
1438 .to_string()
1439 } else {
1440 format!(
1441 "Output is {} long—to avoid unexpected token usage, \
1442 only 16 KB was sent back to the model.",
1443 format_file_size(output.original_content_len as u64, true),
1444 )
1445 }
1446 } else {
1447 "Output was truncated".to_string()
1448 };
1449
1450 header.child(
1451 h_flex()
1452 .id(("terminal-tool-truncated-label", terminal.entity_id()))
1453 .gap_1()
1454 .child(
1455 Icon::new(IconName::Info)
1456 .size(IconSize::XSmall)
1457 .color(Color::Ignored),
1458 )
1459 .child(
1460 Label::new("Truncated")
1461 .color(Color::Muted)
1462 .size(LabelSize::XSmall),
1463 )
1464 .tooltip(Tooltip::text(tooltip)),
1465 )
1466 })
1467 .when(time_elapsed > Duration::from_secs(10), |header| {
1468 header.child(
1469 Label::new(format!("({})", duration_alt_display(time_elapsed)))
1470 .buffer_font(cx)
1471 .color(Color::Muted)
1472 .size(LabelSize::XSmall),
1473 )
1474 })
1475 .child(
1476 Disclosure::new(
1477 SharedString::from(format!(
1478 "terminal-tool-disclosure-{}",
1479 terminal.entity_id()
1480 )),
1481 self.terminal_expanded,
1482 )
1483 .opened_icon(IconName::ChevronUp)
1484 .closed_icon(IconName::ChevronDown)
1485 .on_click(cx.listener(move |this, _event, _window, _cx| {
1486 this.terminal_expanded = !this.terminal_expanded;
1487 })),
1488 );
1489
1490 let show_output =
1491 self.terminal_expanded && self.terminal_views.contains_key(&terminal.entity_id());
1492
1493 v_flex()
1494 .mb_2()
1495 .border_1()
1496 .when(tool_failed || command_failed, |card| card.border_dashed())
1497 .border_color(border_color)
1498 .rounded_lg()
1499 .overflow_hidden()
1500 .child(
1501 v_flex()
1502 .py_1p5()
1503 .pl_2()
1504 .pr_1p5()
1505 .gap_0p5()
1506 .bg(header_bg)
1507 .text_xs()
1508 .child(header)
1509 .child(
1510 MarkdownElement::new(
1511 command.clone(),
1512 terminal_command_markdown_style(window, cx),
1513 )
1514 .code_block_renderer(
1515 markdown::CodeBlockRenderer::Default {
1516 copy_button: false,
1517 copy_button_on_hover: true,
1518 border: false,
1519 },
1520 ),
1521 ),
1522 )
1523 .when(show_output, |this| {
1524 let terminal_view = self.terminal_views.get(&terminal.entity_id()).unwrap();
1525
1526 this.child(
1527 div()
1528 .pt_2()
1529 .border_t_1()
1530 .when(tool_failed || command_failed, |card| card.border_dashed())
1531 .border_color(border_color)
1532 .bg(cx.theme().colors().editor_background)
1533 .rounded_b_md()
1534 .text_ui_sm(cx)
1535 .child(terminal_view.clone()),
1536 )
1537 })
1538 .into_any()
1539 }
1540
1541 fn render_agent_logo(&self) -> AnyElement {
1542 Icon::new(self.agent.logo())
1543 .color(Color::Muted)
1544 .size(IconSize::XLarge)
1545 .into_any_element()
1546 }
1547
1548 fn render_error_agent_logo(&self) -> AnyElement {
1549 let logo = Icon::new(self.agent.logo())
1550 .color(Color::Muted)
1551 .size(IconSize::XLarge)
1552 .into_any_element();
1553
1554 h_flex()
1555 .relative()
1556 .justify_center()
1557 .child(div().opacity(0.3).child(logo))
1558 .child(
1559 h_flex().absolute().right_1().bottom_0().child(
1560 Icon::new(IconName::XCircle)
1561 .color(Color::Error)
1562 .size(IconSize::Small),
1563 ),
1564 )
1565 .into_any_element()
1566 }
1567
1568 fn render_empty_state(&self, cx: &App) -> AnyElement {
1569 let loading = matches!(&self.thread_state, ThreadState::Loading { .. });
1570
1571 v_flex()
1572 .size_full()
1573 .items_center()
1574 .justify_center()
1575 .child(if loading {
1576 h_flex()
1577 .justify_center()
1578 .child(self.render_agent_logo())
1579 .with_animation(
1580 "pulsating_icon",
1581 Animation::new(Duration::from_secs(2))
1582 .repeat()
1583 .with_easing(pulsating_between(0.4, 1.0)),
1584 |icon, delta| icon.opacity(delta),
1585 )
1586 .into_any()
1587 } else {
1588 self.render_agent_logo().into_any_element()
1589 })
1590 .child(h_flex().mt_4().mb_1().justify_center().child(if loading {
1591 div()
1592 .child(LoadingLabel::new("").size(LabelSize::Large))
1593 .into_any_element()
1594 } else {
1595 Headline::new(self.agent.empty_state_headline())
1596 .size(HeadlineSize::Medium)
1597 .into_any_element()
1598 }))
1599 .child(
1600 div()
1601 .max_w_1_2()
1602 .text_sm()
1603 .text_center()
1604 .map(|this| {
1605 if loading {
1606 this.invisible()
1607 } else {
1608 this.text_color(cx.theme().colors().text_muted)
1609 }
1610 })
1611 .child(self.agent.empty_state_message()),
1612 )
1613 .into_any()
1614 }
1615
1616 fn render_pending_auth_state(&self) -> AnyElement {
1617 v_flex()
1618 .items_center()
1619 .justify_center()
1620 .child(self.render_error_agent_logo())
1621 .child(
1622 h_flex()
1623 .mt_4()
1624 .mb_1()
1625 .justify_center()
1626 .child(Headline::new("Not Authenticated").size(HeadlineSize::Medium)),
1627 )
1628 .into_any()
1629 }
1630
1631 fn render_server_exited(&self, status: ExitStatus, _cx: &Context<Self>) -> AnyElement {
1632 v_flex()
1633 .items_center()
1634 .justify_center()
1635 .child(self.render_error_agent_logo())
1636 .child(
1637 v_flex()
1638 .mt_4()
1639 .mb_2()
1640 .gap_0p5()
1641 .text_center()
1642 .items_center()
1643 .child(Headline::new("Server exited unexpectedly").size(HeadlineSize::Medium))
1644 .child(
1645 Label::new(format!("Exit status: {}", status.code().unwrap_or(-127)))
1646 .size(LabelSize::Small)
1647 .color(Color::Muted),
1648 ),
1649 )
1650 .into_any_element()
1651 }
1652
1653 fn render_load_error(&self, e: &LoadError, cx: &Context<Self>) -> AnyElement {
1654 let mut container = v_flex()
1655 .items_center()
1656 .justify_center()
1657 .child(self.render_error_agent_logo())
1658 .child(
1659 v_flex()
1660 .mt_4()
1661 .mb_2()
1662 .gap_0p5()
1663 .text_center()
1664 .items_center()
1665 .child(Headline::new("Failed to launch").size(HeadlineSize::Medium))
1666 .child(
1667 Label::new(e.to_string())
1668 .size(LabelSize::Small)
1669 .color(Color::Muted),
1670 ),
1671 );
1672
1673 if let LoadError::Unsupported {
1674 upgrade_message,
1675 upgrade_command,
1676 ..
1677 } = &e
1678 {
1679 let upgrade_message = upgrade_message.clone();
1680 let upgrade_command = upgrade_command.clone();
1681 container = container.child(Button::new("upgrade", upgrade_message).on_click(
1682 cx.listener(move |this, _, window, cx| {
1683 this.workspace
1684 .update(cx, |workspace, cx| {
1685 let project = workspace.project().read(cx);
1686 let cwd = project.first_project_directory(cx);
1687 let shell = project.terminal_settings(&cwd, cx).shell.clone();
1688 let spawn_in_terminal = task::SpawnInTerminal {
1689 id: task::TaskId("install".to_string()),
1690 full_label: upgrade_command.clone(),
1691 label: upgrade_command.clone(),
1692 command: Some(upgrade_command.clone()),
1693 args: Vec::new(),
1694 command_label: upgrade_command.clone(),
1695 cwd,
1696 env: Default::default(),
1697 use_new_terminal: true,
1698 allow_concurrent_runs: true,
1699 reveal: Default::default(),
1700 reveal_target: Default::default(),
1701 hide: Default::default(),
1702 shell,
1703 show_summary: true,
1704 show_command: true,
1705 show_rerun: false,
1706 };
1707 workspace
1708 .spawn_in_terminal(spawn_in_terminal, window, cx)
1709 .detach();
1710 })
1711 .ok();
1712 }),
1713 ));
1714 }
1715
1716 container.into_any()
1717 }
1718
1719 fn render_activity_bar(
1720 &self,
1721 thread_entity: &Entity<AcpThread>,
1722 window: &mut Window,
1723 cx: &Context<Self>,
1724 ) -> Option<AnyElement> {
1725 let thread = thread_entity.read(cx);
1726 let action_log = thread.action_log();
1727 let changed_buffers = action_log.read(cx).changed_buffers(cx);
1728 let plan = thread.plan();
1729
1730 if changed_buffers.is_empty() && plan.is_empty() {
1731 return None;
1732 }
1733
1734 let editor_bg_color = cx.theme().colors().editor_background;
1735 let active_color = cx.theme().colors().element_selected;
1736 let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
1737
1738 let pending_edits = thread.has_pending_edit_tool_calls();
1739
1740 v_flex()
1741 .mt_1()
1742 .mx_2()
1743 .bg(bg_edit_files_disclosure)
1744 .border_1()
1745 .border_b_0()
1746 .border_color(cx.theme().colors().border)
1747 .rounded_t_md()
1748 .shadow(vec![gpui::BoxShadow {
1749 color: gpui::black().opacity(0.15),
1750 offset: point(px(1.), px(-1.)),
1751 blur_radius: px(3.),
1752 spread_radius: px(0.),
1753 }])
1754 .when(!plan.is_empty(), |this| {
1755 this.child(self.render_plan_summary(plan, window, cx))
1756 .when(self.plan_expanded, |parent| {
1757 parent.child(self.render_plan_entries(plan, window, cx))
1758 })
1759 })
1760 .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
1761 this.child(Divider::horizontal().color(DividerColor::Border))
1762 })
1763 .when(!changed_buffers.is_empty(), |this| {
1764 this.child(self.render_edits_summary(
1765 action_log,
1766 &changed_buffers,
1767 self.edits_expanded,
1768 pending_edits,
1769 window,
1770 cx,
1771 ))
1772 .when(self.edits_expanded, |parent| {
1773 parent.child(self.render_edited_files(
1774 action_log,
1775 &changed_buffers,
1776 pending_edits,
1777 cx,
1778 ))
1779 })
1780 })
1781 .into_any()
1782 .into()
1783 }
1784
1785 fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
1786 let stats = plan.stats();
1787
1788 let title = if let Some(entry) = stats.in_progress_entry
1789 && !self.plan_expanded
1790 {
1791 h_flex()
1792 .w_full()
1793 .cursor_default()
1794 .gap_1()
1795 .text_xs()
1796 .text_color(cx.theme().colors().text_muted)
1797 .justify_between()
1798 .child(
1799 h_flex()
1800 .gap_1()
1801 .child(
1802 Label::new("Current:")
1803 .size(LabelSize::Small)
1804 .color(Color::Muted),
1805 )
1806 .child(MarkdownElement::new(
1807 entry.content.clone(),
1808 plan_label_markdown_style(&entry.status, window, cx),
1809 )),
1810 )
1811 .when(stats.pending > 0, |this| {
1812 this.child(
1813 Label::new(format!("{} left", stats.pending))
1814 .size(LabelSize::Small)
1815 .color(Color::Muted)
1816 .mr_1(),
1817 )
1818 })
1819 } else {
1820 let status_label = if stats.pending == 0 {
1821 "All Done".to_string()
1822 } else if stats.completed == 0 {
1823 format!("{} Tasks", plan.entries.len())
1824 } else {
1825 format!("{}/{}", stats.completed, plan.entries.len())
1826 };
1827
1828 h_flex()
1829 .w_full()
1830 .gap_1()
1831 .justify_between()
1832 .child(
1833 Label::new("Plan")
1834 .size(LabelSize::Small)
1835 .color(Color::Muted),
1836 )
1837 .child(
1838 Label::new(status_label)
1839 .size(LabelSize::Small)
1840 .color(Color::Muted)
1841 .mr_1(),
1842 )
1843 };
1844
1845 h_flex()
1846 .p_1()
1847 .justify_between()
1848 .when(self.plan_expanded, |this| {
1849 this.border_b_1().border_color(cx.theme().colors().border)
1850 })
1851 .child(
1852 h_flex()
1853 .id("plan_summary")
1854 .w_full()
1855 .gap_1()
1856 .child(Disclosure::new("plan_disclosure", self.plan_expanded))
1857 .child(title)
1858 .on_click(cx.listener(|this, _, _, cx| {
1859 this.plan_expanded = !this.plan_expanded;
1860 cx.notify();
1861 })),
1862 )
1863 }
1864
1865 fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
1866 v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
1867 let element = h_flex()
1868 .py_1()
1869 .px_2()
1870 .gap_2()
1871 .justify_between()
1872 .bg(cx.theme().colors().editor_background)
1873 .when(index < plan.entries.len() - 1, |parent| {
1874 parent.border_color(cx.theme().colors().border).border_b_1()
1875 })
1876 .child(
1877 h_flex()
1878 .id(("plan_entry", index))
1879 .gap_1p5()
1880 .max_w_full()
1881 .overflow_x_scroll()
1882 .text_xs()
1883 .text_color(cx.theme().colors().text_muted)
1884 .child(match entry.status {
1885 acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
1886 .size(IconSize::Small)
1887 .color(Color::Muted)
1888 .into_any_element(),
1889 acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
1890 .size(IconSize::Small)
1891 .color(Color::Accent)
1892 .with_animation(
1893 "running",
1894 Animation::new(Duration::from_secs(2)).repeat(),
1895 |icon, delta| {
1896 icon.transform(Transformation::rotate(percentage(delta)))
1897 },
1898 )
1899 .into_any_element(),
1900 acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
1901 .size(IconSize::Small)
1902 .color(Color::Success)
1903 .into_any_element(),
1904 })
1905 .child(MarkdownElement::new(
1906 entry.content.clone(),
1907 plan_label_markdown_style(&entry.status, window, cx),
1908 )),
1909 );
1910
1911 Some(element)
1912 }))
1913 }
1914
1915 fn render_edits_summary(
1916 &self,
1917 action_log: &Entity<ActionLog>,
1918 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
1919 expanded: bool,
1920 pending_edits: bool,
1921 window: &mut Window,
1922 cx: &Context<Self>,
1923 ) -> Div {
1924 const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
1925
1926 let focus_handle = self.focus_handle(cx);
1927
1928 h_flex()
1929 .p_1()
1930 .justify_between()
1931 .when(expanded, |this| {
1932 this.border_b_1().border_color(cx.theme().colors().border)
1933 })
1934 .child(
1935 h_flex()
1936 .id("edits-container")
1937 .w_full()
1938 .gap_1()
1939 .child(Disclosure::new("edits-disclosure", expanded))
1940 .map(|this| {
1941 if pending_edits {
1942 this.child(
1943 Label::new(format!(
1944 "Editing {} {}…",
1945 changed_buffers.len(),
1946 if changed_buffers.len() == 1 {
1947 "file"
1948 } else {
1949 "files"
1950 }
1951 ))
1952 .color(Color::Muted)
1953 .size(LabelSize::Small)
1954 .with_animation(
1955 "edit-label",
1956 Animation::new(Duration::from_secs(2))
1957 .repeat()
1958 .with_easing(pulsating_between(0.3, 0.7)),
1959 |label, delta| label.alpha(delta),
1960 ),
1961 )
1962 } else {
1963 this.child(
1964 Label::new("Edits")
1965 .size(LabelSize::Small)
1966 .color(Color::Muted),
1967 )
1968 .child(Label::new("•").size(LabelSize::XSmall).color(Color::Muted))
1969 .child(
1970 Label::new(format!(
1971 "{} {}",
1972 changed_buffers.len(),
1973 if changed_buffers.len() == 1 {
1974 "file"
1975 } else {
1976 "files"
1977 }
1978 ))
1979 .size(LabelSize::Small)
1980 .color(Color::Muted),
1981 )
1982 }
1983 })
1984 .on_click(cx.listener(|this, _, _, cx| {
1985 this.edits_expanded = !this.edits_expanded;
1986 cx.notify();
1987 })),
1988 )
1989 .child(
1990 h_flex()
1991 .gap_1()
1992 .child(
1993 IconButton::new("review-changes", IconName::ListTodo)
1994 .icon_size(IconSize::Small)
1995 .tooltip({
1996 let focus_handle = focus_handle.clone();
1997 move |window, cx| {
1998 Tooltip::for_action_in(
1999 "Review Changes",
2000 &OpenAgentDiff,
2001 &focus_handle,
2002 window,
2003 cx,
2004 )
2005 }
2006 })
2007 .on_click(cx.listener(|_, _, window, cx| {
2008 window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
2009 })),
2010 )
2011 .child(Divider::vertical().color(DividerColor::Border))
2012 .child(
2013 Button::new("reject-all-changes", "Reject All")
2014 .label_size(LabelSize::Small)
2015 .disabled(pending_edits)
2016 .when(pending_edits, |this| {
2017 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
2018 })
2019 .key_binding(
2020 KeyBinding::for_action_in(
2021 &RejectAll,
2022 &focus_handle.clone(),
2023 window,
2024 cx,
2025 )
2026 .map(|kb| kb.size(rems_from_px(10.))),
2027 )
2028 .on_click({
2029 let action_log = action_log.clone();
2030 cx.listener(move |_, _, _, cx| {
2031 action_log.update(cx, |action_log, cx| {
2032 action_log.reject_all_edits(cx).detach();
2033 })
2034 })
2035 }),
2036 )
2037 .child(
2038 Button::new("keep-all-changes", "Keep All")
2039 .label_size(LabelSize::Small)
2040 .disabled(pending_edits)
2041 .when(pending_edits, |this| {
2042 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
2043 })
2044 .key_binding(
2045 KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
2046 .map(|kb| kb.size(rems_from_px(10.))),
2047 )
2048 .on_click({
2049 let action_log = action_log.clone();
2050 cx.listener(move |_, _, _, cx| {
2051 action_log.update(cx, |action_log, cx| {
2052 action_log.keep_all_edits(cx);
2053 })
2054 })
2055 }),
2056 ),
2057 )
2058 }
2059
2060 fn render_edited_files(
2061 &self,
2062 action_log: &Entity<ActionLog>,
2063 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
2064 pending_edits: bool,
2065 cx: &Context<Self>,
2066 ) -> Div {
2067 let editor_bg_color = cx.theme().colors().editor_background;
2068
2069 v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
2070 |(index, (buffer, _diff))| {
2071 let file = buffer.read(cx).file()?;
2072 let path = file.path();
2073
2074 let file_path = path.parent().and_then(|parent| {
2075 let parent_str = parent.to_string_lossy();
2076
2077 if parent_str.is_empty() {
2078 None
2079 } else {
2080 Some(
2081 Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
2082 .color(Color::Muted)
2083 .size(LabelSize::XSmall)
2084 .buffer_font(cx),
2085 )
2086 }
2087 });
2088
2089 let file_name = path.file_name().map(|name| {
2090 Label::new(name.to_string_lossy().to_string())
2091 .size(LabelSize::XSmall)
2092 .buffer_font(cx)
2093 });
2094
2095 let file_icon = FileIcons::get_icon(&path, cx)
2096 .map(Icon::from_path)
2097 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
2098 .unwrap_or_else(|| {
2099 Icon::new(IconName::File)
2100 .color(Color::Muted)
2101 .size(IconSize::Small)
2102 });
2103
2104 let overlay_gradient = linear_gradient(
2105 90.,
2106 linear_color_stop(editor_bg_color, 1.),
2107 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
2108 );
2109
2110 let element = h_flex()
2111 .group("edited-code")
2112 .id(("file-container", index))
2113 .relative()
2114 .py_1()
2115 .pl_2()
2116 .pr_1()
2117 .gap_2()
2118 .justify_between()
2119 .bg(editor_bg_color)
2120 .when(index < changed_buffers.len() - 1, |parent| {
2121 parent.border_color(cx.theme().colors().border).border_b_1()
2122 })
2123 .child(
2124 h_flex()
2125 .id(("file-name", index))
2126 .pr_8()
2127 .gap_1p5()
2128 .max_w_full()
2129 .overflow_x_scroll()
2130 .child(file_icon)
2131 .child(h_flex().gap_0p5().children(file_name).children(file_path))
2132 .on_click({
2133 let buffer = buffer.clone();
2134 cx.listener(move |this, _, window, cx| {
2135 this.open_edited_buffer(&buffer, window, cx);
2136 })
2137 }),
2138 )
2139 .child(
2140 h_flex()
2141 .gap_1()
2142 .visible_on_hover("edited-code")
2143 .child(
2144 Button::new("review", "Review")
2145 .label_size(LabelSize::Small)
2146 .on_click({
2147 let buffer = buffer.clone();
2148 cx.listener(move |this, _, window, cx| {
2149 this.open_edited_buffer(&buffer, window, cx);
2150 })
2151 }),
2152 )
2153 .child(Divider::vertical().color(DividerColor::BorderVariant))
2154 .child(
2155 Button::new("reject-file", "Reject")
2156 .label_size(LabelSize::Small)
2157 .disabled(pending_edits)
2158 .on_click({
2159 let buffer = buffer.clone();
2160 let action_log = action_log.clone();
2161 move |_, _, cx| {
2162 action_log.update(cx, |action_log, cx| {
2163 action_log
2164 .reject_edits_in_ranges(
2165 buffer.clone(),
2166 vec![Anchor::MIN..Anchor::MAX],
2167 cx,
2168 )
2169 .detach_and_log_err(cx);
2170 })
2171 }
2172 }),
2173 )
2174 .child(
2175 Button::new("keep-file", "Keep")
2176 .label_size(LabelSize::Small)
2177 .disabled(pending_edits)
2178 .on_click({
2179 let buffer = buffer.clone();
2180 let action_log = action_log.clone();
2181 move |_, _, cx| {
2182 action_log.update(cx, |action_log, cx| {
2183 action_log.keep_edits_in_range(
2184 buffer.clone(),
2185 Anchor::MIN..Anchor::MAX,
2186 cx,
2187 );
2188 })
2189 }
2190 }),
2191 ),
2192 )
2193 .child(
2194 div()
2195 .id("gradient-overlay")
2196 .absolute()
2197 .h_full()
2198 .w_12()
2199 .top_0()
2200 .bottom_0()
2201 .right(px(152.))
2202 .bg(overlay_gradient),
2203 );
2204
2205 Some(element)
2206 },
2207 ))
2208 }
2209
2210 fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
2211 let focus_handle = self.message_editor.focus_handle(cx);
2212 let editor_bg_color = cx.theme().colors().editor_background;
2213 let (expand_icon, expand_tooltip) = if self.editor_expanded {
2214 (IconName::Minimize, "Minimize Message Editor")
2215 } else {
2216 (IconName::Maximize, "Expand Message Editor")
2217 };
2218
2219 v_flex()
2220 .on_action(cx.listener(Self::expand_message_editor))
2221 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
2222 if let Some(model_selector) = this.model_selector.as_ref() {
2223 model_selector
2224 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
2225 }
2226 }))
2227 .p_2()
2228 .gap_2()
2229 .border_t_1()
2230 .border_color(cx.theme().colors().border)
2231 .bg(editor_bg_color)
2232 .when(self.editor_expanded, |this| {
2233 this.h(vh(0.8, window)).size_full().justify_between()
2234 })
2235 .child(
2236 v_flex()
2237 .relative()
2238 .size_full()
2239 .pt_1()
2240 .pr_2p5()
2241 .child(self.message_editor.clone())
2242 .child(
2243 h_flex()
2244 .absolute()
2245 .top_0()
2246 .right_0()
2247 .opacity(0.5)
2248 .hover(|this| this.opacity(1.0))
2249 .child(
2250 IconButton::new("toggle-height", expand_icon)
2251 .icon_size(IconSize::Small)
2252 .icon_color(Color::Muted)
2253 .tooltip({
2254 let focus_handle = focus_handle.clone();
2255 move |window, cx| {
2256 Tooltip::for_action_in(
2257 expand_tooltip,
2258 &ExpandMessageEditor,
2259 &focus_handle,
2260 window,
2261 cx,
2262 )
2263 }
2264 })
2265 .on_click(cx.listener(|_, _, window, cx| {
2266 window.dispatch_action(Box::new(ExpandMessageEditor), cx);
2267 })),
2268 ),
2269 ),
2270 )
2271 .child(
2272 h_flex()
2273 .flex_none()
2274 .justify_between()
2275 .child(self.render_follow_toggle(cx))
2276 .child(
2277 h_flex()
2278 .gap_1()
2279 .children(self.model_selector.clone())
2280 .child(self.render_send_button(cx)),
2281 ),
2282 )
2283 .into_any()
2284 }
2285
2286 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
2287 if self.thread().map_or(true, |thread| {
2288 thread.read(cx).status() == ThreadStatus::Idle
2289 }) {
2290 let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
2291 IconButton::new("send-message", IconName::Send)
2292 .icon_color(Color::Accent)
2293 .style(ButtonStyle::Filled)
2294 .disabled(self.thread().is_none() || is_editor_empty)
2295 .when(!is_editor_empty, |button| {
2296 button.tooltip(move |window, cx| Tooltip::for_action("Send", &Chat, window, cx))
2297 })
2298 .when(is_editor_empty, |button| {
2299 button.tooltip(Tooltip::text("Type a message to submit"))
2300 })
2301 .on_click(cx.listener(|this, _, window, cx| {
2302 this.chat(window, cx);
2303 }))
2304 .into_any_element()
2305 } else {
2306 IconButton::new("stop-generation", IconName::Stop)
2307 .icon_color(Color::Error)
2308 .style(ButtonStyle::Tinted(ui::TintColor::Error))
2309 .tooltip(move |window, cx| {
2310 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
2311 })
2312 .on_click(cx.listener(|this, _event, _, cx| this.cancel(cx)))
2313 .into_any_element()
2314 }
2315 }
2316
2317 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
2318 let following = self
2319 .workspace
2320 .read_with(cx, |workspace, _| {
2321 workspace.is_being_followed(CollaboratorId::Agent)
2322 })
2323 .unwrap_or(false);
2324
2325 IconButton::new("follow-agent", IconName::Crosshair)
2326 .icon_size(IconSize::Small)
2327 .icon_color(Color::Muted)
2328 .toggle_state(following)
2329 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
2330 .tooltip(move |window, cx| {
2331 if following {
2332 Tooltip::for_action("Stop Following Agent", &Follow, window, cx)
2333 } else {
2334 Tooltip::with_meta(
2335 "Follow Agent",
2336 Some(&Follow),
2337 "Track the agent's location as it reads and edits files.",
2338 window,
2339 cx,
2340 )
2341 }
2342 })
2343 .on_click(cx.listener(move |this, _, window, cx| {
2344 this.workspace
2345 .update(cx, |workspace, cx| {
2346 if following {
2347 workspace.unfollow(CollaboratorId::Agent, window, cx);
2348 } else {
2349 workspace.follow(CollaboratorId::Agent, window, cx);
2350 }
2351 })
2352 .ok();
2353 }))
2354 }
2355
2356 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
2357 let workspace = self.workspace.clone();
2358 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
2359 Self::open_link(text, &workspace, window, cx);
2360 })
2361 }
2362
2363 fn open_link(
2364 url: SharedString,
2365 workspace: &WeakEntity<Workspace>,
2366 window: &mut Window,
2367 cx: &mut App,
2368 ) {
2369 let Some(workspace) = workspace.upgrade() else {
2370 cx.open_url(&url);
2371 return;
2372 };
2373
2374 if let Some(mention) = MentionUri::parse(&url).log_err() {
2375 workspace.update(cx, |workspace, cx| match mention {
2376 MentionUri::File(path) => {
2377 let project = workspace.project();
2378 let Some((path, entry)) = project.update(cx, |project, cx| {
2379 let path = project.find_project_path(path, cx)?;
2380 let entry = project.entry_for_path(&path, cx)?;
2381 Some((path, entry))
2382 }) else {
2383 return;
2384 };
2385
2386 if entry.is_dir() {
2387 project.update(cx, |_, cx| {
2388 cx.emit(project::Event::RevealInProjectPanel(entry.id));
2389 });
2390 } else {
2391 workspace
2392 .open_path(path, None, true, window, cx)
2393 .detach_and_log_err(cx);
2394 }
2395 }
2396 _ => {
2397 // TODO
2398 unimplemented!()
2399 }
2400 })
2401 } else {
2402 cx.open_url(&url);
2403 }
2404 }
2405
2406 fn open_tool_call_location(
2407 &self,
2408 entry_ix: usize,
2409 location_ix: usize,
2410 window: &mut Window,
2411 cx: &mut Context<Self>,
2412 ) -> Option<()> {
2413 let (tool_call_location, agent_location) = self
2414 .thread()?
2415 .read(cx)
2416 .entries()
2417 .get(entry_ix)?
2418 .location(location_ix)?;
2419
2420 let project_path = self
2421 .project
2422 .read(cx)
2423 .find_project_path(&tool_call_location.path, cx)?;
2424
2425 let open_task = self
2426 .workspace
2427 .update(cx, |workspace, cx| {
2428 workspace.open_path(project_path, None, true, window, cx)
2429 })
2430 .log_err()?;
2431 window
2432 .spawn(cx, async move |cx| {
2433 let item = open_task.await?;
2434
2435 let Some(active_editor) = item.downcast::<Editor>() else {
2436 return anyhow::Ok(());
2437 };
2438
2439 active_editor.update_in(cx, |editor, window, cx| {
2440 let multibuffer = editor.buffer().read(cx);
2441 let buffer = multibuffer.as_singleton();
2442 if agent_location.buffer.upgrade() == buffer {
2443 let excerpt_id = multibuffer.excerpt_ids().first().cloned();
2444 let anchor = editor::Anchor::in_buffer(
2445 excerpt_id.unwrap(),
2446 buffer.unwrap().read(cx).remote_id(),
2447 agent_location.position,
2448 );
2449 editor.change_selections(Default::default(), window, cx, |selections| {
2450 selections.select_anchor_ranges([anchor..anchor]);
2451 })
2452 } else {
2453 let row = tool_call_location.line.unwrap_or_default();
2454 editor.change_selections(Default::default(), window, cx, |selections| {
2455 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
2456 })
2457 }
2458 })?;
2459
2460 anyhow::Ok(())
2461 })
2462 .detach_and_log_err(cx);
2463
2464 None
2465 }
2466
2467 pub fn open_thread_as_markdown(
2468 &self,
2469 workspace: Entity<Workspace>,
2470 window: &mut Window,
2471 cx: &mut App,
2472 ) -> Task<anyhow::Result<()>> {
2473 let markdown_language_task = workspace
2474 .read(cx)
2475 .app_state()
2476 .languages
2477 .language_for_name("Markdown");
2478
2479 let (thread_summary, markdown) = if let Some(thread) = self.thread() {
2480 let thread = thread.read(cx);
2481 (thread.title().to_string(), thread.to_markdown(cx))
2482 } else {
2483 return Task::ready(Ok(()));
2484 };
2485
2486 window.spawn(cx, async move |cx| {
2487 let markdown_language = markdown_language_task.await?;
2488
2489 workspace.update_in(cx, |workspace, window, cx| {
2490 let project = workspace.project().clone();
2491
2492 if !project.read(cx).is_local() {
2493 anyhow::bail!("failed to open active thread as markdown in remote project");
2494 }
2495
2496 let buffer = project.update(cx, |project, cx| {
2497 project.create_local_buffer(&markdown, Some(markdown_language), cx)
2498 });
2499 let buffer = cx.new(|cx| {
2500 MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
2501 });
2502
2503 workspace.add_item_to_active_pane(
2504 Box::new(cx.new(|cx| {
2505 let mut editor =
2506 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
2507 editor.set_breadcrumb_header(thread_summary);
2508 editor
2509 })),
2510 None,
2511 true,
2512 window,
2513 cx,
2514 );
2515
2516 anyhow::Ok(())
2517 })??;
2518 anyhow::Ok(())
2519 })
2520 }
2521
2522 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
2523 self.list_state.scroll_to(ListOffset::default());
2524 cx.notify();
2525 }
2526
2527 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
2528 if let Some(thread) = self.thread() {
2529 let entry_count = thread.read(cx).entries().len();
2530 self.list_state.reset(entry_count);
2531 cx.notify();
2532 }
2533 }
2534
2535 fn notify_with_sound(
2536 &mut self,
2537 caption: impl Into<SharedString>,
2538 icon: IconName,
2539 window: &mut Window,
2540 cx: &mut Context<Self>,
2541 ) {
2542 self.play_notification_sound(window, cx);
2543 self.show_notification(caption, icon, window, cx);
2544 }
2545
2546 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
2547 let settings = AgentSettings::get_global(cx);
2548 if settings.play_sound_when_agent_done && !window.is_window_active() {
2549 Audio::play_sound(Sound::AgentDone, cx);
2550 }
2551 }
2552
2553 fn show_notification(
2554 &mut self,
2555 caption: impl Into<SharedString>,
2556 icon: IconName,
2557 window: &mut Window,
2558 cx: &mut Context<Self>,
2559 ) {
2560 if window.is_window_active() || !self.notifications.is_empty() {
2561 return;
2562 }
2563
2564 let title = self.title(cx);
2565
2566 match AgentSettings::get_global(cx).notify_when_agent_waiting {
2567 NotifyWhenAgentWaiting::PrimaryScreen => {
2568 if let Some(primary) = cx.primary_display() {
2569 self.pop_up(icon, caption.into(), title, window, primary, cx);
2570 }
2571 }
2572 NotifyWhenAgentWaiting::AllScreens => {
2573 let caption = caption.into();
2574 for screen in cx.displays() {
2575 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
2576 }
2577 }
2578 NotifyWhenAgentWaiting::Never => {
2579 // Don't show anything
2580 }
2581 }
2582 }
2583
2584 fn pop_up(
2585 &mut self,
2586 icon: IconName,
2587 caption: SharedString,
2588 title: SharedString,
2589 window: &mut Window,
2590 screen: Rc<dyn PlatformDisplay>,
2591 cx: &mut Context<Self>,
2592 ) {
2593 let options = AgentNotification::window_options(screen, cx);
2594
2595 let project_name = self.workspace.upgrade().and_then(|workspace| {
2596 workspace
2597 .read(cx)
2598 .project()
2599 .read(cx)
2600 .visible_worktrees(cx)
2601 .next()
2602 .map(|worktree| worktree.read(cx).root_name().to_string())
2603 });
2604
2605 if let Some(screen_window) = cx
2606 .open_window(options, |_, cx| {
2607 cx.new(|_| {
2608 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
2609 })
2610 })
2611 .log_err()
2612 {
2613 if let Some(pop_up) = screen_window.entity(cx).log_err() {
2614 self.notification_subscriptions
2615 .entry(screen_window)
2616 .or_insert_with(Vec::new)
2617 .push(cx.subscribe_in(&pop_up, window, {
2618 |this, _, event, window, cx| match event {
2619 AgentNotificationEvent::Accepted => {
2620 let handle = window.window_handle();
2621 cx.activate(true);
2622
2623 let workspace_handle = this.workspace.clone();
2624
2625 // If there are multiple Zed windows, activate the correct one.
2626 cx.defer(move |cx| {
2627 handle
2628 .update(cx, |_view, window, _cx| {
2629 window.activate_window();
2630
2631 if let Some(workspace) = workspace_handle.upgrade() {
2632 workspace.update(_cx, |workspace, cx| {
2633 workspace.focus_panel::<AgentPanel>(window, cx);
2634 });
2635 }
2636 })
2637 .log_err();
2638 });
2639
2640 this.dismiss_notifications(cx);
2641 }
2642 AgentNotificationEvent::Dismissed => {
2643 this.dismiss_notifications(cx);
2644 }
2645 }
2646 }));
2647
2648 self.notifications.push(screen_window);
2649
2650 // If the user manually refocuses the original window, dismiss the popup.
2651 self.notification_subscriptions
2652 .entry(screen_window)
2653 .or_insert_with(Vec::new)
2654 .push({
2655 let pop_up_weak = pop_up.downgrade();
2656
2657 cx.observe_window_activation(window, move |_, window, cx| {
2658 if window.is_window_active() {
2659 if let Some(pop_up) = pop_up_weak.upgrade() {
2660 pop_up.update(cx, |_, cx| {
2661 cx.emit(AgentNotificationEvent::Dismissed);
2662 });
2663 }
2664 }
2665 })
2666 });
2667 }
2668 }
2669 }
2670
2671 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
2672 for window in self.notifications.drain(..) {
2673 window
2674 .update(cx, |_, window, _| {
2675 window.remove_window();
2676 })
2677 .ok();
2678
2679 self.notification_subscriptions.remove(&window);
2680 }
2681 }
2682
2683 fn render_thread_controls(&self, cx: &Context<Self>) -> impl IntoElement {
2684 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
2685 .shape(ui::IconButtonShape::Square)
2686 .icon_size(IconSize::Small)
2687 .icon_color(Color::Ignored)
2688 .tooltip(Tooltip::text("Open Thread as Markdown"))
2689 .on_click(cx.listener(move |this, _, window, cx| {
2690 if let Some(workspace) = this.workspace.upgrade() {
2691 this.open_thread_as_markdown(workspace, window, cx)
2692 .detach_and_log_err(cx);
2693 }
2694 }));
2695
2696 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
2697 .shape(ui::IconButtonShape::Square)
2698 .icon_size(IconSize::Small)
2699 .icon_color(Color::Ignored)
2700 .tooltip(Tooltip::text("Scroll To Top"))
2701 .on_click(cx.listener(move |this, _, _, cx| {
2702 this.scroll_to_top(cx);
2703 }));
2704
2705 h_flex()
2706 .w_full()
2707 .mr_1()
2708 .pb_2()
2709 .px(RESPONSE_PADDING_X)
2710 .opacity(0.4)
2711 .hover(|style| style.opacity(1.))
2712 .flex_wrap()
2713 .justify_end()
2714 .child(open_as_markdown)
2715 .child(scroll_to_top)
2716 }
2717
2718 fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
2719 div()
2720 .id("acp-thread-scrollbar")
2721 .occlude()
2722 .on_mouse_move(cx.listener(|_, _, _, cx| {
2723 cx.notify();
2724 cx.stop_propagation()
2725 }))
2726 .on_hover(|_, _, cx| {
2727 cx.stop_propagation();
2728 })
2729 .on_any_mouse_down(|_, _, cx| {
2730 cx.stop_propagation();
2731 })
2732 .on_mouse_up(
2733 MouseButton::Left,
2734 cx.listener(|_, _, _, cx| {
2735 cx.stop_propagation();
2736 }),
2737 )
2738 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2739 cx.notify();
2740 }))
2741 .h_full()
2742 .absolute()
2743 .right_1()
2744 .top_1()
2745 .bottom_0()
2746 .w(px(12.))
2747 .cursor_default()
2748 .children(Scrollbar::vertical(self.scrollbar_state.clone()).map(|s| s.auto_hide(cx)))
2749 }
2750
2751 fn settings_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
2752 for diff_editor in self.diff_editors.values() {
2753 diff_editor.update(cx, |diff_editor, cx| {
2754 diff_editor.set_text_style_refinement(diff_editor_text_style_refinement(cx));
2755 cx.notify();
2756 })
2757 }
2758 }
2759
2760 pub(crate) fn insert_dragged_files(
2761 &self,
2762 paths: Vec<project::ProjectPath>,
2763 _added_worktrees: Vec<Entity<project::Worktree>>,
2764 window: &mut Window,
2765 cx: &mut Context<Self>,
2766 ) {
2767 self.message_editor.update(cx, |message_editor, cx| {
2768 message_editor.insert_dragged_files(paths, window, cx);
2769 })
2770 }
2771}
2772
2773impl Focusable for AcpThreadView {
2774 fn focus_handle(&self, cx: &App) -> FocusHandle {
2775 self.message_editor.focus_handle(cx)
2776 }
2777}
2778
2779impl Render for AcpThreadView {
2780 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2781 let has_messages = self.list_state.item_count() > 0;
2782
2783 v_flex()
2784 .size_full()
2785 .key_context("AcpThread")
2786 .on_action(cx.listener(Self::open_agent_diff))
2787 .bg(cx.theme().colors().panel_background)
2788 .child(match &self.thread_state {
2789 ThreadState::Unauthenticated { connection } => v_flex()
2790 .p_2()
2791 .flex_1()
2792 .items_center()
2793 .justify_center()
2794 .child(self.render_pending_auth_state())
2795 .child(h_flex().mt_1p5().justify_center().children(
2796 connection.auth_methods().into_iter().map(|method| {
2797 Button::new(
2798 SharedString::from(method.id.0.clone()),
2799 method.name.clone(),
2800 )
2801 .on_click({
2802 let method_id = method.id.clone();
2803 cx.listener(move |this, _, window, cx| {
2804 this.authenticate(method_id.clone(), window, cx)
2805 })
2806 })
2807 }),
2808 )),
2809 ThreadState::Loading { .. } => v_flex().flex_1().child(self.render_empty_state(cx)),
2810 ThreadState::LoadError(e) => v_flex()
2811 .p_2()
2812 .flex_1()
2813 .items_center()
2814 .justify_center()
2815 .child(self.render_load_error(e, cx)),
2816 ThreadState::ServerExited { status } => v_flex()
2817 .p_2()
2818 .flex_1()
2819 .items_center()
2820 .justify_center()
2821 .child(self.render_server_exited(*status, cx)),
2822 ThreadState::Ready { thread, .. } => {
2823 let thread_clone = thread.clone();
2824
2825 v_flex().flex_1().map(|this| {
2826 if has_messages {
2827 this.child(
2828 list(
2829 self.list_state.clone(),
2830 cx.processor(|this, index: usize, window, cx| {
2831 let Some((entry, len)) = this.thread().and_then(|thread| {
2832 let entries = &thread.read(cx).entries();
2833 Some((entries.get(index)?, entries.len()))
2834 }) else {
2835 return Empty.into_any();
2836 };
2837 this.render_entry(index, len, entry, window, cx)
2838 }),
2839 )
2840 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
2841 .flex_grow()
2842 .into_any(),
2843 )
2844 .child(self.render_vertical_scrollbar(cx))
2845 .children(
2846 match thread_clone.read(cx).status() {
2847 ThreadStatus::Idle
2848 | ThreadStatus::WaitingForToolConfirmation => None,
2849 ThreadStatus::Generating => div()
2850 .px_5()
2851 .py_2()
2852 .child(LoadingLabel::new("").size(LabelSize::Small))
2853 .into(),
2854 },
2855 )
2856 } else {
2857 this.child(self.render_empty_state(cx))
2858 }
2859 })
2860 }
2861 })
2862 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
2863 // above so that the scrollbar doesn't render behind it. The current setup allows
2864 // the scrollbar to stop exactly at the activity bar start.
2865 .when(has_messages, |this| match &self.thread_state {
2866 ThreadState::Ready { thread, .. } => {
2867 this.children(self.render_activity_bar(thread, window, cx))
2868 }
2869 _ => this,
2870 })
2871 .when_some(self.last_error.clone(), |el, error| {
2872 el.child(
2873 div()
2874 .p_2()
2875 .text_xs()
2876 .border_t_1()
2877 .border_color(cx.theme().colors().border)
2878 .bg(cx.theme().status().error_background)
2879 .child(
2880 self.render_markdown(error, default_markdown_style(false, window, cx)),
2881 ),
2882 )
2883 })
2884 .child(self.render_message_editor(window, cx))
2885 }
2886}
2887
2888fn user_message_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
2889 let mut style = default_markdown_style(false, window, cx);
2890 let mut text_style = window.text_style();
2891 let theme_settings = ThemeSettings::get_global(cx);
2892
2893 let buffer_font = theme_settings.buffer_font.family.clone();
2894 let buffer_font_size = TextSize::Small.rems(cx);
2895
2896 text_style.refine(&TextStyleRefinement {
2897 font_family: Some(buffer_font),
2898 font_size: Some(buffer_font_size.into()),
2899 ..Default::default()
2900 });
2901
2902 style.base_text_style = text_style;
2903 style.link_callback = Some(Rc::new(move |url, cx| {
2904 if MentionUri::parse(url).is_ok() {
2905 let colors = cx.theme().colors();
2906 Some(TextStyleRefinement {
2907 background_color: Some(colors.element_background),
2908 ..Default::default()
2909 })
2910 } else {
2911 None
2912 }
2913 }));
2914 style
2915}
2916
2917fn default_markdown_style(buffer_font: bool, window: &Window, cx: &App) -> MarkdownStyle {
2918 let theme_settings = ThemeSettings::get_global(cx);
2919 let colors = cx.theme().colors();
2920
2921 let buffer_font_size = TextSize::Small.rems(cx);
2922
2923 let mut text_style = window.text_style();
2924 let line_height = buffer_font_size * 1.75;
2925
2926 let font_family = if buffer_font {
2927 theme_settings.buffer_font.family.clone()
2928 } else {
2929 theme_settings.ui_font.family.clone()
2930 };
2931
2932 let font_size = if buffer_font {
2933 TextSize::Small.rems(cx)
2934 } else {
2935 TextSize::Default.rems(cx)
2936 };
2937
2938 text_style.refine(&TextStyleRefinement {
2939 font_family: Some(font_family),
2940 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
2941 font_features: Some(theme_settings.ui_font.features.clone()),
2942 font_size: Some(font_size.into()),
2943 line_height: Some(line_height.into()),
2944 color: Some(cx.theme().colors().text),
2945 ..Default::default()
2946 });
2947
2948 MarkdownStyle {
2949 base_text_style: text_style.clone(),
2950 syntax: cx.theme().syntax().clone(),
2951 selection_background_color: cx.theme().colors().element_selection_background,
2952 code_block_overflow_x_scroll: true,
2953 table_overflow_x_scroll: true,
2954 heading_level_styles: Some(HeadingLevelStyles {
2955 h1: Some(TextStyleRefinement {
2956 font_size: Some(rems(1.15).into()),
2957 ..Default::default()
2958 }),
2959 h2: Some(TextStyleRefinement {
2960 font_size: Some(rems(1.1).into()),
2961 ..Default::default()
2962 }),
2963 h3: Some(TextStyleRefinement {
2964 font_size: Some(rems(1.05).into()),
2965 ..Default::default()
2966 }),
2967 h4: Some(TextStyleRefinement {
2968 font_size: Some(rems(1.).into()),
2969 ..Default::default()
2970 }),
2971 h5: Some(TextStyleRefinement {
2972 font_size: Some(rems(0.95).into()),
2973 ..Default::default()
2974 }),
2975 h6: Some(TextStyleRefinement {
2976 font_size: Some(rems(0.875).into()),
2977 ..Default::default()
2978 }),
2979 }),
2980 code_block: StyleRefinement {
2981 padding: EdgesRefinement {
2982 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2983 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2984 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2985 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2986 },
2987 margin: EdgesRefinement {
2988 top: Some(Length::Definite(Pixels(8.).into())),
2989 left: Some(Length::Definite(Pixels(0.).into())),
2990 right: Some(Length::Definite(Pixels(0.).into())),
2991 bottom: Some(Length::Definite(Pixels(12.).into())),
2992 },
2993 border_style: Some(BorderStyle::Solid),
2994 border_widths: EdgesRefinement {
2995 top: Some(AbsoluteLength::Pixels(Pixels(1.))),
2996 left: Some(AbsoluteLength::Pixels(Pixels(1.))),
2997 right: Some(AbsoluteLength::Pixels(Pixels(1.))),
2998 bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
2999 },
3000 border_color: Some(colors.border_variant),
3001 background: Some(colors.editor_background.into()),
3002 text: Some(TextStyleRefinement {
3003 font_family: Some(theme_settings.buffer_font.family.clone()),
3004 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
3005 font_features: Some(theme_settings.buffer_font.features.clone()),
3006 font_size: Some(buffer_font_size.into()),
3007 ..Default::default()
3008 }),
3009 ..Default::default()
3010 },
3011 inline_code: TextStyleRefinement {
3012 font_family: Some(theme_settings.buffer_font.family.clone()),
3013 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
3014 font_features: Some(theme_settings.buffer_font.features.clone()),
3015 font_size: Some(buffer_font_size.into()),
3016 background_color: Some(colors.editor_foreground.opacity(0.08)),
3017 ..Default::default()
3018 },
3019 link: TextStyleRefinement {
3020 background_color: Some(colors.editor_foreground.opacity(0.025)),
3021 underline: Some(UnderlineStyle {
3022 color: Some(colors.text_accent.opacity(0.5)),
3023 thickness: px(1.),
3024 ..Default::default()
3025 }),
3026 ..Default::default()
3027 },
3028 ..Default::default()
3029 }
3030}
3031
3032fn plan_label_markdown_style(
3033 status: &acp::PlanEntryStatus,
3034 window: &Window,
3035 cx: &App,
3036) -> MarkdownStyle {
3037 let default_md_style = default_markdown_style(false, window, cx);
3038
3039 MarkdownStyle {
3040 base_text_style: TextStyle {
3041 color: cx.theme().colors().text_muted,
3042 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
3043 Some(gpui::StrikethroughStyle {
3044 thickness: px(1.),
3045 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
3046 })
3047 } else {
3048 None
3049 },
3050 ..default_md_style.base_text_style
3051 },
3052 ..default_md_style
3053 }
3054}
3055
3056fn diff_editor_text_style_refinement(cx: &mut App) -> TextStyleRefinement {
3057 TextStyleRefinement {
3058 font_size: Some(
3059 TextSize::Small
3060 .rems(cx)
3061 .to_pixels(ThemeSettings::get_global(cx).agent_font_size(cx))
3062 .into(),
3063 ),
3064 ..Default::default()
3065 }
3066}
3067
3068fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
3069 let default_md_style = default_markdown_style(true, window, cx);
3070
3071 MarkdownStyle {
3072 base_text_style: TextStyle {
3073 ..default_md_style.base_text_style
3074 },
3075 selection_background_color: cx.theme().colors().element_selection_background,
3076 ..Default::default()
3077 }
3078}
3079
3080#[cfg(test)]
3081pub(crate) mod tests {
3082 use std::{path::Path, sync::Arc};
3083
3084 use agent_client_protocol::SessionId;
3085 use editor::EditorSettings;
3086 use fs::FakeFs;
3087 use futures::future::try_join_all;
3088 use gpui::{SemanticVersion, TestAppContext, VisualTestContext};
3089 use parking_lot::Mutex;
3090 use rand::Rng;
3091 use settings::SettingsStore;
3092
3093 use super::*;
3094
3095 #[gpui::test]
3096 async fn test_drop(cx: &mut TestAppContext) {
3097 init_test(cx);
3098
3099 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default(), cx).await;
3100 let weak_view = thread_view.downgrade();
3101 drop(thread_view);
3102 assert!(!weak_view.is_upgradable());
3103 }
3104
3105 #[gpui::test]
3106 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
3107 init_test(cx);
3108
3109 let (thread_view, cx) = setup_thread_view(StubAgentServer::default(), cx).await;
3110
3111 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
3112 message_editor.update_in(cx, |editor, window, cx| {
3113 editor.set_text("Hello", window, cx);
3114 });
3115
3116 cx.deactivate_window();
3117
3118 thread_view.update_in(cx, |thread_view, window, cx| {
3119 thread_view.chat(window, cx);
3120 });
3121
3122 cx.run_until_parked();
3123
3124 assert!(
3125 cx.windows()
3126 .iter()
3127 .any(|window| window.downcast::<AgentNotification>().is_some())
3128 );
3129 }
3130
3131 #[gpui::test]
3132 async fn test_notification_for_error(cx: &mut TestAppContext) {
3133 init_test(cx);
3134
3135 let (thread_view, cx) =
3136 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
3137
3138 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
3139 message_editor.update_in(cx, |editor, window, cx| {
3140 editor.set_text("Hello", window, cx);
3141 });
3142
3143 cx.deactivate_window();
3144
3145 thread_view.update_in(cx, |thread_view, window, cx| {
3146 thread_view.chat(window, cx);
3147 });
3148
3149 cx.run_until_parked();
3150
3151 assert!(
3152 cx.windows()
3153 .iter()
3154 .any(|window| window.downcast::<AgentNotification>().is_some())
3155 );
3156 }
3157
3158 #[gpui::test]
3159 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
3160 init_test(cx);
3161
3162 let tool_call_id = acp::ToolCallId("1".into());
3163 let tool_call = acp::ToolCall {
3164 id: tool_call_id.clone(),
3165 title: "Label".into(),
3166 kind: acp::ToolKind::Edit,
3167 status: acp::ToolCallStatus::Pending,
3168 content: vec!["hi".into()],
3169 locations: vec![],
3170 raw_input: None,
3171 raw_output: None,
3172 };
3173 let connection = StubAgentConnection::new(vec![acp::SessionUpdate::ToolCall(tool_call)])
3174 .with_permission_requests(HashMap::from_iter([(
3175 tool_call_id,
3176 vec![acp::PermissionOption {
3177 id: acp::PermissionOptionId("1".into()),
3178 name: "Allow".into(),
3179 kind: acp::PermissionOptionKind::AllowOnce,
3180 }],
3181 )]));
3182 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
3183
3184 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
3185 message_editor.update_in(cx, |editor, window, cx| {
3186 editor.set_text("Hello", window, cx);
3187 });
3188
3189 cx.deactivate_window();
3190
3191 thread_view.update_in(cx, |thread_view, window, cx| {
3192 thread_view.chat(window, cx);
3193 });
3194
3195 cx.run_until_parked();
3196
3197 assert!(
3198 cx.windows()
3199 .iter()
3200 .any(|window| window.downcast::<AgentNotification>().is_some())
3201 );
3202 }
3203
3204 async fn setup_thread_view(
3205 agent: impl AgentServer + 'static,
3206 cx: &mut TestAppContext,
3207 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
3208 let fs = FakeFs::new(cx.executor());
3209 let project = Project::test(fs, [], cx).await;
3210 let (workspace, cx) =
3211 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
3212
3213 let thread_view = cx.update(|window, cx| {
3214 cx.new(|cx| {
3215 AcpThreadView::new(
3216 Rc::new(agent),
3217 workspace.downgrade(),
3218 project,
3219 Rc::new(RefCell::new(MessageHistory::default())),
3220 window,
3221 cx,
3222 )
3223 })
3224 });
3225 cx.run_until_parked();
3226 (thread_view, cx)
3227 }
3228
3229 struct StubAgentServer<C> {
3230 connection: C,
3231 }
3232
3233 impl<C> StubAgentServer<C> {
3234 fn new(connection: C) -> Self {
3235 Self { connection }
3236 }
3237 }
3238
3239 impl StubAgentServer<StubAgentConnection> {
3240 fn default() -> Self {
3241 Self::new(StubAgentConnection::default())
3242 }
3243 }
3244
3245 impl<C> AgentServer for StubAgentServer<C>
3246 where
3247 C: 'static + AgentConnection + Send + Clone,
3248 {
3249 fn logo(&self) -> ui::IconName {
3250 unimplemented!()
3251 }
3252
3253 fn name(&self) -> &'static str {
3254 unimplemented!()
3255 }
3256
3257 fn empty_state_headline(&self) -> &'static str {
3258 unimplemented!()
3259 }
3260
3261 fn empty_state_message(&self) -> &'static str {
3262 unimplemented!()
3263 }
3264
3265 fn connect(
3266 &self,
3267 _root_dir: &Path,
3268 _project: &Entity<Project>,
3269 _cx: &mut App,
3270 ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
3271 Task::ready(Ok(Rc::new(self.connection.clone())))
3272 }
3273 }
3274
3275 #[derive(Clone, Default)]
3276 struct StubAgentConnection {
3277 sessions: Arc<Mutex<HashMap<acp::SessionId, WeakEntity<AcpThread>>>>,
3278 permission_requests: HashMap<acp::ToolCallId, Vec<acp::PermissionOption>>,
3279 updates: Vec<acp::SessionUpdate>,
3280 }
3281
3282 impl StubAgentConnection {
3283 fn new(updates: Vec<acp::SessionUpdate>) -> Self {
3284 Self {
3285 updates,
3286 permission_requests: HashMap::default(),
3287 sessions: Arc::default(),
3288 }
3289 }
3290
3291 fn with_permission_requests(
3292 mut self,
3293 permission_requests: HashMap<acp::ToolCallId, Vec<acp::PermissionOption>>,
3294 ) -> Self {
3295 self.permission_requests = permission_requests;
3296 self
3297 }
3298 }
3299
3300 impl AgentConnection for StubAgentConnection {
3301 fn auth_methods(&self) -> &[acp::AuthMethod] {
3302 &[]
3303 }
3304
3305 fn new_thread(
3306 self: Rc<Self>,
3307 project: Entity<Project>,
3308 _cwd: &Path,
3309 cx: &mut gpui::AsyncApp,
3310 ) -> Task<gpui::Result<Entity<AcpThread>>> {
3311 let session_id = SessionId(
3312 rand::thread_rng()
3313 .sample_iter(&rand::distributions::Alphanumeric)
3314 .take(7)
3315 .map(char::from)
3316 .collect::<String>()
3317 .into(),
3318 );
3319 let thread = cx
3320 .new(|cx| AcpThread::new("Test", self.clone(), project, session_id.clone(), cx))
3321 .unwrap();
3322 self.sessions.lock().insert(session_id, thread.downgrade());
3323 Task::ready(Ok(thread))
3324 }
3325
3326 fn authenticate(
3327 &self,
3328 _method_id: acp::AuthMethodId,
3329 _cx: &mut App,
3330 ) -> Task<gpui::Result<()>> {
3331 unimplemented!()
3332 }
3333
3334 fn prompt(
3335 &self,
3336 _id: Option<acp_thread::UserMessageId>,
3337 params: acp::PromptRequest,
3338 cx: &mut App,
3339 ) -> Task<gpui::Result<acp::PromptResponse>> {
3340 let sessions = self.sessions.lock();
3341 let thread = sessions.get(¶ms.session_id).unwrap();
3342 let mut tasks = vec![];
3343 for update in &self.updates {
3344 let thread = thread.clone();
3345 let update = update.clone();
3346 let permission_request = if let acp::SessionUpdate::ToolCall(tool_call) = &update
3347 && let Some(options) = self.permission_requests.get(&tool_call.id)
3348 {
3349 Some((tool_call.clone(), options.clone()))
3350 } else {
3351 None
3352 };
3353 let task = cx.spawn(async move |cx| {
3354 if let Some((tool_call, options)) = permission_request {
3355 let permission = thread.update(cx, |thread, cx| {
3356 thread.request_tool_call_authorization(
3357 tool_call.clone(),
3358 options.clone(),
3359 cx,
3360 )
3361 })?;
3362 permission.await?;
3363 }
3364 thread.update(cx, |thread, cx| {
3365 thread.handle_session_update(update.clone(), cx).unwrap();
3366 })?;
3367 anyhow::Ok(())
3368 });
3369 tasks.push(task);
3370 }
3371 cx.spawn(async move |_| {
3372 try_join_all(tasks).await?;
3373 Ok(acp::PromptResponse {
3374 stop_reason: acp::StopReason::EndTurn,
3375 })
3376 })
3377 }
3378
3379 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
3380 unimplemented!()
3381 }
3382 }
3383
3384 #[derive(Clone)]
3385 struct SaboteurAgentConnection;
3386
3387 impl AgentConnection for SaboteurAgentConnection {
3388 fn new_thread(
3389 self: Rc<Self>,
3390 project: Entity<Project>,
3391 _cwd: &Path,
3392 cx: &mut gpui::AsyncApp,
3393 ) -> Task<gpui::Result<Entity<AcpThread>>> {
3394 Task::ready(Ok(cx
3395 .new(|cx| {
3396 AcpThread::new(
3397 "SaboteurAgentConnection",
3398 self,
3399 project,
3400 SessionId("test".into()),
3401 cx,
3402 )
3403 })
3404 .unwrap()))
3405 }
3406
3407 fn auth_methods(&self) -> &[acp::AuthMethod] {
3408 &[]
3409 }
3410
3411 fn authenticate(
3412 &self,
3413 _method_id: acp::AuthMethodId,
3414 _cx: &mut App,
3415 ) -> Task<gpui::Result<()>> {
3416 unimplemented!()
3417 }
3418
3419 fn prompt(
3420 &self,
3421 _id: Option<acp_thread::UserMessageId>,
3422 _params: acp::PromptRequest,
3423 _cx: &mut App,
3424 ) -> Task<gpui::Result<acp::PromptResponse>> {
3425 Task::ready(Err(anyhow::anyhow!("Error prompting")))
3426 }
3427
3428 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
3429 unimplemented!()
3430 }
3431 }
3432
3433 pub(crate) fn init_test(cx: &mut TestAppContext) {
3434 cx.update(|cx| {
3435 let settings_store = SettingsStore::test(cx);
3436 cx.set_global(settings_store);
3437 language::init(cx);
3438 Project::init_settings(cx);
3439 AgentSettings::register(cx);
3440 workspace::init_settings(cx);
3441 ThemeSettings::register(cx);
3442 release_channel::init(SemanticVersion::default(), cx);
3443 EditorSettings::register(cx);
3444 });
3445 }
3446}