1use acp_thread::{AgentConnection, Plan};
2use agent_servers::AgentServer;
3use std::cell::RefCell;
4use std::collections::BTreeMap;
5use std::path::Path;
6use std::rc::Rc;
7use std::sync::Arc;
8use std::time::Duration;
9
10use agent_client_protocol as acp;
11use assistant_tool::ActionLog;
12use buffer_diff::BufferDiff;
13use collections::{HashMap, HashSet};
14use editor::{
15 AnchorRangeExt, ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement, EditorMode,
16 EditorStyle, MinimapVisibility, MultiBuffer, PathKey,
17};
18use file_icons::FileIcons;
19use gpui::{
20 Action, Animation, AnimationExt, App, BorderStyle, EdgesRefinement, Empty, Entity, EntityId,
21 FocusHandle, Focusable, Hsla, Length, ListOffset, ListState, SharedString, StyleRefinement,
22 Subscription, Task, TextStyle, TextStyleRefinement, Transformation, UnderlineStyle, WeakEntity,
23 Window, div, linear_color_stop, linear_gradient, list, percentage, point, prelude::*,
24 pulsating_between,
25};
26use language::language_settings::SoftWrap;
27use language::{Buffer, Language};
28use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
29use parking_lot::Mutex;
30use project::Project;
31use settings::Settings as _;
32use text::Anchor;
33use theme::ThemeSettings;
34use ui::{Disclosure, Divider, DividerColor, KeyBinding, Tooltip, prelude::*};
35use util::ResultExt;
36use workspace::{CollaboratorId, Workspace};
37use zed_actions::agent::{Chat, NextHistoryMessage, PreviousHistoryMessage};
38
39use ::acp_thread::{
40 AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk, Diff,
41 LoadError, MentionPath, ThreadStatus, ToolCall, ToolCallContent, ToolCallStatus,
42};
43
44use crate::acp::completion_provider::{ContextPickerCompletionProvider, MentionSet};
45use crate::acp::message_history::MessageHistory;
46use crate::agent_diff::AgentDiff;
47use crate::message_editor::{MAX_EDITOR_LINES, MIN_EDITOR_LINES};
48use crate::{AgentDiffPane, ExpandMessageEditor, Follow, KeepAll, OpenAgentDiff, RejectAll};
49
50const RESPONSE_PADDING_X: Pixels = px(19.);
51
52pub struct AcpThreadView {
53 agent: Rc<dyn AgentServer>,
54 workspace: WeakEntity<Workspace>,
55 project: Entity<Project>,
56 thread_state: ThreadState,
57 diff_editors: HashMap<EntityId, Entity<Editor>>,
58 message_editor: Entity<Editor>,
59 message_set_from_history: bool,
60 _message_editor_subscription: Subscription,
61 mention_set: Arc<Mutex<MentionSet>>,
62 last_error: Option<Entity<Markdown>>,
63 list_state: ListState,
64 auth_task: Option<Task<()>>,
65 expanded_tool_calls: HashSet<acp::ToolCallId>,
66 expanded_thinking_blocks: HashSet<(usize, usize)>,
67 edits_expanded: bool,
68 plan_expanded: bool,
69 editor_expanded: bool,
70 message_history: Rc<RefCell<MessageHistory<Vec<acp::ContentBlock>>>>,
71 _cancel_task: Option<Task<()>>,
72}
73
74enum ThreadState {
75 Loading {
76 _task: Task<()>,
77 },
78 Ready {
79 thread: Entity<AcpThread>,
80 _subscription: [Subscription; 2],
81 },
82 LoadError(LoadError),
83 Unauthenticated {
84 connection: Rc<dyn AgentConnection>,
85 },
86}
87
88impl AcpThreadView {
89 pub fn new(
90 agent: Rc<dyn AgentServer>,
91 workspace: WeakEntity<Workspace>,
92 project: Entity<Project>,
93 message_history: Rc<RefCell<MessageHistory<Vec<acp::ContentBlock>>>>,
94 min_lines: usize,
95 max_lines: Option<usize>,
96 window: &mut Window,
97 cx: &mut Context<Self>,
98 ) -> Self {
99 let language = Language::new(
100 language::LanguageConfig {
101 completion_query_characters: HashSet::from_iter(['.', '-', '_', '@']),
102 ..Default::default()
103 },
104 None,
105 );
106
107 let mention_set = Arc::new(Mutex::new(MentionSet::default()));
108
109 let message_editor = cx.new(|cx| {
110 let buffer = cx.new(|cx| Buffer::local("", cx).with_language(Arc::new(language), cx));
111 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
112
113 let mut editor = Editor::new(
114 editor::EditorMode::AutoHeight {
115 min_lines,
116 max_lines: max_lines,
117 },
118 buffer,
119 None,
120 window,
121 cx,
122 );
123 editor.set_placeholder_text("Message the agent - @ to include files", cx);
124 editor.set_show_indent_guides(false, cx);
125 editor.set_soft_wrap();
126 editor.set_use_modal_editing(true);
127 editor.set_completion_provider(Some(Rc::new(ContextPickerCompletionProvider::new(
128 mention_set.clone(),
129 workspace.clone(),
130 cx.weak_entity(),
131 ))));
132 editor.set_context_menu_options(ContextMenuOptions {
133 min_entries_visible: 12,
134 max_entries_visible: 12,
135 placement: Some(ContextMenuPlacement::Above),
136 });
137 editor
138 });
139
140 let message_editor_subscription = cx.subscribe(&message_editor, |this, _, event, _| {
141 if let editor::EditorEvent::BufferEdited = &event {
142 if !this.message_set_from_history {
143 this.message_history.borrow_mut().reset_position();
144 }
145 this.message_set_from_history = false;
146 }
147 });
148
149 let mention_set = mention_set.clone();
150
151 let list_state = ListState::new(
152 0,
153 gpui::ListAlignment::Bottom,
154 px(2048.0),
155 cx.processor({
156 move |this: &mut Self, index: usize, window, cx| {
157 let Some((entry, len)) = this.thread().and_then(|thread| {
158 let entries = &thread.read(cx).entries();
159 Some((entries.get(index)?, entries.len()))
160 }) else {
161 return Empty.into_any();
162 };
163 this.render_entry(index, len, entry, window, cx)
164 }
165 }),
166 );
167
168 Self {
169 agent: agent.clone(),
170 workspace: workspace.clone(),
171 project: project.clone(),
172 thread_state: Self::initial_state(agent, workspace, project, window, cx),
173 message_editor,
174 message_set_from_history: false,
175 _message_editor_subscription: message_editor_subscription,
176 mention_set,
177 diff_editors: Default::default(),
178 list_state: list_state,
179 last_error: None,
180 auth_task: None,
181 expanded_tool_calls: HashSet::default(),
182 expanded_thinking_blocks: HashSet::default(),
183 edits_expanded: false,
184 plan_expanded: false,
185 editor_expanded: false,
186 message_history,
187 _cancel_task: None,
188 }
189 }
190
191 fn initial_state(
192 agent: Rc<dyn AgentServer>,
193 workspace: WeakEntity<Workspace>,
194 project: Entity<Project>,
195 window: &mut Window,
196 cx: &mut Context<Self>,
197 ) -> ThreadState {
198 let root_dir = project
199 .read(cx)
200 .visible_worktrees(cx)
201 .next()
202 .map(|worktree| worktree.read(cx).abs_path())
203 .unwrap_or_else(|| paths::home_dir().as_path().into());
204
205 let connect_task = agent.connect(&root_dir, &project, cx);
206 let load_task = cx.spawn_in(window, async move |this, cx| {
207 let connection = match connect_task.await {
208 Ok(thread) => thread,
209 Err(err) => {
210 this.update(cx, |this, cx| {
211 this.handle_load_error(err, cx);
212 cx.notify();
213 })
214 .log_err();
215 return;
216 }
217 };
218
219 let result = match connection
220 .clone()
221 .new_thread(project.clone(), &root_dir, cx)
222 .await
223 {
224 Err(e) => {
225 let mut cx = cx.clone();
226 if e.downcast_ref::<acp_thread::Unauthenticated>().is_some() {
227 this.update(&mut cx, |this, cx| {
228 this.thread_state = ThreadState::Unauthenticated { connection };
229 cx.notify();
230 })
231 .ok();
232 return;
233 } else {
234 Err(e)
235 }
236 }
237 Ok(session_id) => Ok(session_id),
238 };
239
240 this.update_in(cx, |this, window, cx| {
241 match result {
242 Ok(thread) => {
243 let thread_subscription =
244 cx.subscribe_in(&thread, window, Self::handle_thread_event);
245
246 let action_log = thread.read(cx).action_log().clone();
247 let action_log_subscription =
248 cx.observe(&action_log, |_, _, cx| cx.notify());
249
250 this.list_state
251 .splice(0..0, thread.read(cx).entries().len());
252
253 AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
254
255 this.thread_state = ThreadState::Ready {
256 thread,
257 _subscription: [thread_subscription, action_log_subscription],
258 };
259
260 cx.notify();
261 }
262 Err(err) => {
263 this.handle_load_error(err, cx);
264 }
265 };
266 })
267 .log_err();
268 });
269
270 ThreadState::Loading { _task: load_task }
271 }
272
273 fn handle_load_error(&mut self, err: anyhow::Error, cx: &mut Context<Self>) {
274 if let Some(load_err) = err.downcast_ref::<LoadError>() {
275 self.thread_state = ThreadState::LoadError(load_err.clone());
276 } else {
277 self.thread_state = ThreadState::LoadError(LoadError::Other(err.to_string().into()))
278 }
279 cx.notify();
280 }
281
282 pub fn thread(&self) -> Option<&Entity<AcpThread>> {
283 match &self.thread_state {
284 ThreadState::Ready { thread, .. } => Some(thread),
285 ThreadState::Unauthenticated { .. }
286 | ThreadState::Loading { .. }
287 | ThreadState::LoadError(..) => None,
288 }
289 }
290
291 pub fn title(&self, cx: &App) -> SharedString {
292 match &self.thread_state {
293 ThreadState::Ready { thread, .. } => thread.read(cx).title(),
294 ThreadState::Loading { .. } => "Loading…".into(),
295 ThreadState::LoadError(_) => "Failed to load".into(),
296 ThreadState::Unauthenticated { .. } => "Not authenticated".into(),
297 }
298 }
299
300 pub fn cancel(&mut self, cx: &mut Context<Self>) {
301 self.last_error.take();
302
303 if let Some(thread) = self.thread() {
304 self._cancel_task = Some(thread.update(cx, |thread, cx| thread.cancel(cx)));
305 }
306 }
307
308 pub fn expand_message_editor(
309 &mut self,
310 _: &ExpandMessageEditor,
311 _window: &mut Window,
312 cx: &mut Context<Self>,
313 ) {
314 self.set_editor_is_expanded(!self.editor_expanded, cx);
315 cx.notify();
316 }
317
318 fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
319 self.editor_expanded = is_expanded;
320 self.message_editor.update(cx, |editor, _| {
321 if self.editor_expanded {
322 editor.set_mode(EditorMode::Full {
323 scale_ui_elements_with_buffer_font_size: false,
324 show_active_line_background: false,
325 sized_by_content: false,
326 })
327 } else {
328 editor.set_mode(EditorMode::AutoHeight {
329 min_lines: MIN_EDITOR_LINES,
330 max_lines: Some(MAX_EDITOR_LINES),
331 })
332 }
333 });
334 cx.notify();
335 }
336
337 fn chat(&mut self, _: &Chat, window: &mut Window, cx: &mut Context<Self>) {
338 self.last_error.take();
339
340 let mut ix = 0;
341 let mut chunks: Vec<acp::ContentBlock> = Vec::new();
342 let project = self.project.clone();
343 self.message_editor.update(cx, |editor, cx| {
344 let text = editor.text(cx);
345 editor.display_map.update(cx, |map, cx| {
346 let snapshot = map.snapshot(cx);
347 for (crease_id, crease) in snapshot.crease_snapshot.creases() {
348 if let Some(project_path) =
349 self.mention_set.lock().path_for_crease_id(crease_id)
350 {
351 let crease_range = crease.range().to_offset(&snapshot.buffer_snapshot);
352 if crease_range.start > ix {
353 chunks.push(text[ix..crease_range.start].into());
354 }
355 if let Some(abs_path) = project.read(cx).absolute_path(&project_path, cx) {
356 let path_str = abs_path.display().to_string();
357 chunks.push(acp::ContentBlock::ResourceLink(acp::ResourceLink {
358 uri: path_str.clone(),
359 name: path_str,
360 annotations: None,
361 description: None,
362 mime_type: None,
363 size: None,
364 title: None,
365 }));
366 }
367 ix = crease_range.end;
368 }
369 }
370
371 if ix < text.len() {
372 let last_chunk = text[ix..].trim();
373 if !last_chunk.is_empty() {
374 chunks.push(last_chunk.into());
375 }
376 }
377 })
378 });
379
380 if chunks.is_empty() {
381 return;
382 }
383
384 let Some(thread) = self.thread() else { return };
385 let task = thread.update(cx, |thread, cx| thread.send(chunks.clone(), cx));
386
387 cx.spawn(async move |this, cx| {
388 let result = task.await;
389
390 this.update(cx, |this, cx| {
391 if let Err(err) = result {
392 this.last_error =
393 Some(cx.new(|cx| Markdown::new(err.to_string().into(), None, None, cx)))
394 }
395 })
396 })
397 .detach();
398
399 let mention_set = self.mention_set.clone();
400
401 self.set_editor_is_expanded(false, cx);
402 self.message_editor.update(cx, |editor, cx| {
403 editor.clear(window, cx);
404 editor.remove_creases(mention_set.lock().drain(), cx)
405 });
406
407 self.message_history.borrow_mut().push(chunks);
408 }
409
410 fn previous_history_message(
411 &mut self,
412 _: &PreviousHistoryMessage,
413 window: &mut Window,
414 cx: &mut Context<Self>,
415 ) {
416 self.message_set_from_history = Self::set_draft_message(
417 self.message_editor.clone(),
418 self.mention_set.clone(),
419 self.project.clone(),
420 self.message_history.borrow_mut().prev(),
421 window,
422 cx,
423 );
424 }
425
426 fn next_history_message(
427 &mut self,
428 _: &NextHistoryMessage,
429 window: &mut Window,
430 cx: &mut Context<Self>,
431 ) {
432 self.message_set_from_history = Self::set_draft_message(
433 self.message_editor.clone(),
434 self.mention_set.clone(),
435 self.project.clone(),
436 self.message_history.borrow_mut().next(),
437 window,
438 cx,
439 );
440 }
441
442 fn open_agent_diff(&mut self, _: &OpenAgentDiff, window: &mut Window, cx: &mut Context<Self>) {
443 if let Some(thread) = self.thread() {
444 AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err();
445 }
446 }
447
448 fn open_edited_buffer(
449 &mut self,
450 buffer: &Entity<Buffer>,
451 window: &mut Window,
452 cx: &mut Context<Self>,
453 ) {
454 let Some(thread) = self.thread() else {
455 return;
456 };
457
458 let Some(diff) =
459 AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
460 else {
461 return;
462 };
463
464 diff.update(cx, |diff, cx| {
465 diff.move_to_path(PathKey::for_buffer(&buffer, cx), window, cx)
466 })
467 }
468
469 fn set_draft_message(
470 message_editor: Entity<Editor>,
471 mention_set: Arc<Mutex<MentionSet>>,
472 project: Entity<Project>,
473 message: Option<&Vec<acp::ContentBlock>>,
474 window: &mut Window,
475 cx: &mut Context<Self>,
476 ) -> bool {
477 cx.notify();
478
479 let Some(message) = message else {
480 return false;
481 };
482
483 let mut text = String::new();
484 let mut mentions = Vec::new();
485
486 for chunk in message {
487 match chunk {
488 acp::ContentBlock::Text(text_content) => {
489 text.push_str(&text_content.text);
490 }
491 acp::ContentBlock::ResourceLink(resource_link) => {
492 let path = Path::new(&resource_link.uri);
493 let start = text.len();
494 let content = MentionPath::new(&path).to_string();
495 text.push_str(&content);
496 let end = text.len();
497 if let Some(project_path) =
498 project.read(cx).project_path_for_absolute_path(&path, cx)
499 {
500 let filename: SharedString = path
501 .file_name()
502 .unwrap_or_default()
503 .to_string_lossy()
504 .to_string()
505 .into();
506 mentions.push((start..end, project_path, filename));
507 }
508 }
509 acp::ContentBlock::Image(_)
510 | acp::ContentBlock::Audio(_)
511 | acp::ContentBlock::Resource(_) => {}
512 }
513 }
514
515 let snapshot = message_editor.update(cx, |editor, cx| {
516 editor.set_text(text, window, cx);
517 editor.buffer().read(cx).snapshot(cx)
518 });
519
520 for (range, project_path, filename) in mentions {
521 let crease_icon_path = if project_path.path.is_dir() {
522 FileIcons::get_folder_icon(false, cx)
523 .unwrap_or_else(|| IconName::Folder.path().into())
524 } else {
525 FileIcons::get_icon(Path::new(project_path.path.as_ref()), cx)
526 .unwrap_or_else(|| IconName::File.path().into())
527 };
528
529 let anchor = snapshot.anchor_before(range.start);
530 let crease_id = crate::context_picker::insert_crease_for_mention(
531 anchor.excerpt_id,
532 anchor.text_anchor,
533 range.end - range.start,
534 filename,
535 crease_icon_path,
536 message_editor.clone(),
537 window,
538 cx,
539 );
540 if let Some(crease_id) = crease_id {
541 mention_set.lock().insert(crease_id, project_path);
542 }
543 }
544
545 true
546 }
547
548 fn handle_thread_event(
549 &mut self,
550 thread: &Entity<AcpThread>,
551 event: &AcpThreadEvent,
552 window: &mut Window,
553 cx: &mut Context<Self>,
554 ) {
555 let count = self.list_state.item_count();
556 match event {
557 AcpThreadEvent::NewEntry => {
558 let index = thread.read(cx).entries().len() - 1;
559 self.sync_thread_entry_view(index, window, cx);
560 self.list_state.splice(count..count, 1);
561 }
562 AcpThreadEvent::EntryUpdated(index) => {
563 let index = *index;
564 self.sync_thread_entry_view(index, window, cx);
565 self.list_state.splice(index..index + 1, 1);
566 }
567 }
568 cx.notify();
569 }
570
571 fn sync_thread_entry_view(
572 &mut self,
573 entry_ix: usize,
574 window: &mut Window,
575 cx: &mut Context<Self>,
576 ) {
577 let Some(multibuffers) = self.entry_diff_multibuffers(entry_ix, cx) else {
578 return;
579 };
580
581 let multibuffers = multibuffers.collect::<Vec<_>>();
582
583 for multibuffer in multibuffers {
584 if self.diff_editors.contains_key(&multibuffer.entity_id()) {
585 return;
586 }
587
588 let editor = cx.new(|cx| {
589 let mut editor = Editor::new(
590 EditorMode::Full {
591 scale_ui_elements_with_buffer_font_size: false,
592 show_active_line_background: false,
593 sized_by_content: true,
594 },
595 multibuffer.clone(),
596 None,
597 window,
598 cx,
599 );
600 editor.set_show_gutter(false, cx);
601 editor.disable_inline_diagnostics();
602 editor.disable_expand_excerpt_buttons(cx);
603 editor.set_show_vertical_scrollbar(false, cx);
604 editor.set_minimap_visibility(MinimapVisibility::Disabled, window, cx);
605 editor.set_soft_wrap_mode(SoftWrap::None, cx);
606 editor.scroll_manager.set_forbid_vertical_scroll(true);
607 editor.set_show_indent_guides(false, cx);
608 editor.set_read_only(true);
609 editor.set_show_breakpoints(false, cx);
610 editor.set_show_code_actions(false, cx);
611 editor.set_show_git_diff_gutter(false, cx);
612 editor.set_expand_all_diff_hunks(cx);
613 editor.set_text_style_refinement(TextStyleRefinement {
614 font_size: Some(
615 TextSize::Small
616 .rems(cx)
617 .to_pixels(ThemeSettings::get_global(cx).agent_font_size(cx))
618 .into(),
619 ),
620 ..Default::default()
621 });
622 editor
623 });
624 let entity_id = multibuffer.entity_id();
625 cx.observe_release(&multibuffer, move |this, _, _| {
626 this.diff_editors.remove(&entity_id);
627 })
628 .detach();
629
630 self.diff_editors.insert(entity_id, editor);
631 }
632 }
633
634 fn entry_diff_multibuffers(
635 &self,
636 entry_ix: usize,
637 cx: &App,
638 ) -> Option<impl Iterator<Item = Entity<MultiBuffer>>> {
639 let entry = self.thread()?.read(cx).entries().get(entry_ix)?;
640 Some(entry.diffs().map(|diff| diff.multibuffer.clone()))
641 }
642
643 fn authenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
644 let ThreadState::Unauthenticated { ref connection } = self.thread_state else {
645 return;
646 };
647
648 self.last_error.take();
649 let authenticate = connection.authenticate(cx);
650 self.auth_task = Some(cx.spawn_in(window, {
651 let project = self.project.clone();
652 let agent = self.agent.clone();
653 async move |this, cx| {
654 let result = authenticate.await;
655
656 this.update_in(cx, |this, window, cx| {
657 if let Err(err) = result {
658 this.last_error = Some(cx.new(|cx| {
659 Markdown::new(format!("Error: {err}").into(), None, None, cx)
660 }))
661 } else {
662 this.thread_state = Self::initial_state(
663 agent,
664 this.workspace.clone(),
665 project.clone(),
666 window,
667 cx,
668 )
669 }
670 this.auth_task.take()
671 })
672 .ok();
673 }
674 }));
675 }
676
677 fn authorize_tool_call(
678 &mut self,
679 tool_call_id: acp::ToolCallId,
680 option_id: acp::PermissionOptionId,
681 option_kind: acp::PermissionOptionKind,
682 cx: &mut Context<Self>,
683 ) {
684 let Some(thread) = self.thread() else {
685 return;
686 };
687 thread.update(cx, |thread, cx| {
688 thread.authorize_tool_call(tool_call_id, option_id, option_kind, cx);
689 });
690 cx.notify();
691 }
692
693 fn render_entry(
694 &self,
695 index: usize,
696 total_entries: usize,
697 entry: &AgentThreadEntry,
698 window: &mut Window,
699 cx: &Context<Self>,
700 ) -> AnyElement {
701 match &entry {
702 AgentThreadEntry::UserMessage(message) => div()
703 .py_4()
704 .px_2()
705 .child(
706 v_flex()
707 .p_3()
708 .gap_1p5()
709 .rounded_lg()
710 .shadow_md()
711 .bg(cx.theme().colors().editor_background)
712 .border_1()
713 .border_color(cx.theme().colors().border)
714 .text_xs()
715 .children(message.content.markdown().map(|md| {
716 self.render_markdown(
717 md.clone(),
718 user_message_markdown_style(window, cx),
719 )
720 })),
721 )
722 .into_any(),
723 AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) => {
724 let style = default_markdown_style(false, window, cx);
725 let message_body = v_flex()
726 .w_full()
727 .gap_2p5()
728 .children(chunks.iter().enumerate().filter_map(
729 |(chunk_ix, chunk)| match chunk {
730 AssistantMessageChunk::Message { block } => {
731 block.markdown().map(|md| {
732 self.render_markdown(md.clone(), style.clone())
733 .into_any_element()
734 })
735 }
736 AssistantMessageChunk::Thought { block } => {
737 block.markdown().map(|md| {
738 self.render_thinking_block(
739 index,
740 chunk_ix,
741 md.clone(),
742 window,
743 cx,
744 )
745 .into_any_element()
746 })
747 }
748 },
749 ))
750 .into_any();
751
752 v_flex()
753 .px_5()
754 .py_1()
755 .when(index + 1 == total_entries, |this| this.pb_4())
756 .w_full()
757 .text_ui(cx)
758 .child(message_body)
759 .into_any()
760 }
761 AgentThreadEntry::ToolCall(tool_call) => div()
762 .py_1p5()
763 .px_5()
764 .child(self.render_tool_call(index, tool_call, window, cx))
765 .into_any(),
766 }
767 }
768
769 fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
770 cx.theme()
771 .colors()
772 .element_background
773 .blend(cx.theme().colors().editor_foreground.opacity(0.025))
774 }
775
776 fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
777 cx.theme().colors().border.opacity(0.6)
778 }
779
780 fn tool_name_font_size(&self) -> Rems {
781 rems_from_px(13.)
782 }
783
784 fn render_thinking_block(
785 &self,
786 entry_ix: usize,
787 chunk_ix: usize,
788 chunk: Entity<Markdown>,
789 window: &Window,
790 cx: &Context<Self>,
791 ) -> AnyElement {
792 let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
793 let key = (entry_ix, chunk_ix);
794 let is_open = self.expanded_thinking_blocks.contains(&key);
795
796 v_flex()
797 .child(
798 h_flex()
799 .id(header_id)
800 .group("disclosure-header")
801 .w_full()
802 .justify_between()
803 .opacity(0.8)
804 .hover(|style| style.opacity(1.))
805 .child(
806 h_flex()
807 .gap_1p5()
808 .child(
809 Icon::new(IconName::ToolBulb)
810 .size(IconSize::Small)
811 .color(Color::Muted),
812 )
813 .child(
814 div()
815 .text_size(self.tool_name_font_size())
816 .child("Thinking"),
817 ),
818 )
819 .child(
820 div().visible_on_hover("disclosure-header").child(
821 Disclosure::new("thinking-disclosure", is_open)
822 .opened_icon(IconName::ChevronUp)
823 .closed_icon(IconName::ChevronDown)
824 .on_click(cx.listener({
825 move |this, _event, _window, cx| {
826 if is_open {
827 this.expanded_thinking_blocks.remove(&key);
828 } else {
829 this.expanded_thinking_blocks.insert(key);
830 }
831 cx.notify();
832 }
833 })),
834 ),
835 )
836 .on_click(cx.listener({
837 move |this, _event, _window, cx| {
838 if is_open {
839 this.expanded_thinking_blocks.remove(&key);
840 } else {
841 this.expanded_thinking_blocks.insert(key);
842 }
843 cx.notify();
844 }
845 })),
846 )
847 .when(is_open, |this| {
848 this.child(
849 div()
850 .relative()
851 .mt_1p5()
852 .ml(px(7.))
853 .pl_4()
854 .border_l_1()
855 .border_color(self.tool_card_border_color(cx))
856 .text_ui_sm(cx)
857 .child(
858 self.render_markdown(chunk, default_markdown_style(false, window, cx)),
859 ),
860 )
861 })
862 .into_any_element()
863 }
864
865 fn render_tool_call(
866 &self,
867 entry_ix: usize,
868 tool_call: &ToolCall,
869 window: &Window,
870 cx: &Context<Self>,
871 ) -> Div {
872 let header_id = SharedString::from(format!("tool-call-header-{}", entry_ix));
873
874 let status_icon = match &tool_call.status {
875 ToolCallStatus::Allowed {
876 status: acp::ToolCallStatus::Pending,
877 }
878 | ToolCallStatus::WaitingForConfirmation { .. } => None,
879 ToolCallStatus::Allowed {
880 status: acp::ToolCallStatus::InProgress,
881 ..
882 } => Some(
883 Icon::new(IconName::ArrowCircle)
884 .color(Color::Accent)
885 .size(IconSize::Small)
886 .with_animation(
887 "running",
888 Animation::new(Duration::from_secs(2)).repeat(),
889 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
890 )
891 .into_any(),
892 ),
893 ToolCallStatus::Allowed {
894 status: acp::ToolCallStatus::Completed,
895 ..
896 } => None,
897 ToolCallStatus::Rejected
898 | ToolCallStatus::Canceled
899 | ToolCallStatus::Allowed {
900 status: acp::ToolCallStatus::Failed,
901 ..
902 } => Some(
903 Icon::new(IconName::X)
904 .color(Color::Error)
905 .size(IconSize::Small)
906 .into_any_element(),
907 ),
908 };
909
910 let needs_confirmation = match &tool_call.status {
911 ToolCallStatus::WaitingForConfirmation { .. } => true,
912 _ => tool_call
913 .content
914 .iter()
915 .any(|content| matches!(content, ToolCallContent::Diff { .. })),
916 };
917
918 let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
919 let is_open = !is_collapsible || self.expanded_tool_calls.contains(&tool_call.id);
920
921 v_flex()
922 .when(needs_confirmation, |this| {
923 this.rounded_lg()
924 .border_1()
925 .border_color(self.tool_card_border_color(cx))
926 .bg(cx.theme().colors().editor_background)
927 .overflow_hidden()
928 })
929 .child(
930 h_flex()
931 .id(header_id)
932 .w_full()
933 .gap_1()
934 .justify_between()
935 .map(|this| {
936 if needs_confirmation {
937 this.px_2()
938 .py_1()
939 .rounded_t_md()
940 .bg(self.tool_card_header_bg(cx))
941 .border_b_1()
942 .border_color(self.tool_card_border_color(cx))
943 } else {
944 this.opacity(0.8).hover(|style| style.opacity(1.))
945 }
946 })
947 .child(
948 h_flex()
949 .id("tool-call-header")
950 .overflow_x_scroll()
951 .map(|this| {
952 if needs_confirmation {
953 this.text_xs()
954 } else {
955 this.text_size(self.tool_name_font_size())
956 }
957 })
958 .gap_1p5()
959 .child(
960 Icon::new(match tool_call.kind {
961 acp::ToolKind::Read => IconName::ToolRead,
962 acp::ToolKind::Edit => IconName::ToolPencil,
963 acp::ToolKind::Delete => IconName::ToolDeleteFile,
964 acp::ToolKind::Move => IconName::ArrowRightLeft,
965 acp::ToolKind::Search => IconName::ToolSearch,
966 acp::ToolKind::Execute => IconName::ToolTerminal,
967 acp::ToolKind::Think => IconName::ToolBulb,
968 acp::ToolKind::Fetch => IconName::ToolWeb,
969 acp::ToolKind::Other => IconName::ToolHammer,
970 })
971 .size(IconSize::Small)
972 .color(Color::Muted),
973 )
974 .child(if tool_call.locations.len() == 1 {
975 let name = tool_call.locations[0]
976 .path
977 .file_name()
978 .unwrap_or_default()
979 .display()
980 .to_string();
981
982 h_flex()
983 .id(("open-tool-call-location", entry_ix))
984 .child(name)
985 .w_full()
986 .max_w_full()
987 .pr_1()
988 .gap_0p5()
989 .cursor_pointer()
990 .rounded_sm()
991 .opacity(0.8)
992 .hover(|label| {
993 label.opacity(1.).bg(cx
994 .theme()
995 .colors()
996 .element_hover
997 .opacity(0.5))
998 })
999 .tooltip(Tooltip::text("Jump to File"))
1000 .on_click(cx.listener(move |this, _, window, cx| {
1001 this.open_tool_call_location(entry_ix, 0, window, cx);
1002 }))
1003 .into_any_element()
1004 } else {
1005 self.render_markdown(
1006 tool_call.label.clone(),
1007 default_markdown_style(needs_confirmation, window, cx),
1008 )
1009 .into_any()
1010 }),
1011 )
1012 .child(
1013 h_flex()
1014 .gap_0p5()
1015 .when(is_collapsible, |this| {
1016 this.child(
1017 Disclosure::new(("expand", entry_ix), is_open)
1018 .opened_icon(IconName::ChevronUp)
1019 .closed_icon(IconName::ChevronDown)
1020 .on_click(cx.listener({
1021 let id = tool_call.id.clone();
1022 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1023 if is_open {
1024 this.expanded_tool_calls.remove(&id);
1025 } else {
1026 this.expanded_tool_calls.insert(id.clone());
1027 }
1028 cx.notify();
1029 }
1030 })),
1031 )
1032 })
1033 .children(status_icon),
1034 )
1035 .on_click(cx.listener({
1036 let id = tool_call.id.clone();
1037 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1038 if is_open {
1039 this.expanded_tool_calls.remove(&id);
1040 } else {
1041 this.expanded_tool_calls.insert(id.clone());
1042 }
1043 cx.notify();
1044 }
1045 })),
1046 )
1047 .when(is_open, |this| {
1048 this.child(
1049 v_flex()
1050 .text_xs()
1051 .when(is_collapsible, |this| {
1052 this.mt_1()
1053 .border_1()
1054 .border_color(self.tool_card_border_color(cx))
1055 .bg(cx.theme().colors().editor_background)
1056 .rounded_lg()
1057 })
1058 .map(|this| {
1059 if is_open {
1060 match &tool_call.status {
1061 ToolCallStatus::WaitingForConfirmation { options, .. } => this
1062 .children(tool_call.content.iter().map(|content| {
1063 div()
1064 .py_1p5()
1065 .child(
1066 self.render_tool_call_content(
1067 content, window, cx,
1068 ),
1069 )
1070 .into_any_element()
1071 }))
1072 .child(self.render_permission_buttons(
1073 options,
1074 entry_ix,
1075 tool_call.id.clone(),
1076 tool_call.content.is_empty(),
1077 cx,
1078 )),
1079 ToolCallStatus::Allowed { .. } | ToolCallStatus::Canceled => {
1080 this.children(tool_call.content.iter().map(|content| {
1081 div()
1082 .py_1p5()
1083 .child(
1084 self.render_tool_call_content(
1085 content, window, cx,
1086 ),
1087 )
1088 .into_any_element()
1089 }))
1090 }
1091 ToolCallStatus::Rejected => this,
1092 }
1093 } else {
1094 this
1095 }
1096 }),
1097 )
1098 })
1099 }
1100
1101 fn render_tool_call_content(
1102 &self,
1103 content: &ToolCallContent,
1104 window: &Window,
1105 cx: &Context<Self>,
1106 ) -> AnyElement {
1107 match content {
1108 ToolCallContent::ContentBlock { content } => {
1109 if let Some(md) = content.markdown() {
1110 div()
1111 .p_2()
1112 .child(
1113 self.render_markdown(
1114 md.clone(),
1115 default_markdown_style(false, window, cx),
1116 ),
1117 )
1118 .into_any_element()
1119 } else {
1120 Empty.into_any_element()
1121 }
1122 }
1123 ToolCallContent::Diff {
1124 diff: Diff { multibuffer, .. },
1125 ..
1126 } => self.render_diff_editor(multibuffer),
1127 }
1128 }
1129
1130 fn render_permission_buttons(
1131 &self,
1132 options: &[acp::PermissionOption],
1133 entry_ix: usize,
1134 tool_call_id: acp::ToolCallId,
1135 empty_content: bool,
1136 cx: &Context<Self>,
1137 ) -> Div {
1138 h_flex()
1139 .py_1p5()
1140 .px_1p5()
1141 .gap_1()
1142 .justify_end()
1143 .when(!empty_content, |this| {
1144 this.border_t_1()
1145 .border_color(self.tool_card_border_color(cx))
1146 })
1147 .children(options.iter().map(|option| {
1148 let option_id = SharedString::from(option.id.0.clone());
1149 Button::new((option_id, entry_ix), option.label.clone())
1150 .map(|this| match option.kind {
1151 acp::PermissionOptionKind::AllowOnce => {
1152 this.icon(IconName::Check).icon_color(Color::Success)
1153 }
1154 acp::PermissionOptionKind::AllowAlways => {
1155 this.icon(IconName::CheckDouble).icon_color(Color::Success)
1156 }
1157 acp::PermissionOptionKind::RejectOnce => {
1158 this.icon(IconName::X).icon_color(Color::Error)
1159 }
1160 acp::PermissionOptionKind::RejectAlways => {
1161 this.icon(IconName::X).icon_color(Color::Error)
1162 }
1163 })
1164 .icon_position(IconPosition::Start)
1165 .icon_size(IconSize::XSmall)
1166 .on_click(cx.listener({
1167 let tool_call_id = tool_call_id.clone();
1168 let option_id = option.id.clone();
1169 let option_kind = option.kind;
1170 move |this, _, _, cx| {
1171 this.authorize_tool_call(
1172 tool_call_id.clone(),
1173 option_id.clone(),
1174 option_kind,
1175 cx,
1176 );
1177 }
1178 }))
1179 }))
1180 }
1181
1182 fn render_diff_editor(&self, multibuffer: &Entity<MultiBuffer>) -> AnyElement {
1183 v_flex()
1184 .h_full()
1185 .child(
1186 if let Some(editor) = self.diff_editors.get(&multibuffer.entity_id()) {
1187 editor.clone().into_any_element()
1188 } else {
1189 Empty.into_any()
1190 },
1191 )
1192 .into_any()
1193 }
1194
1195 fn render_agent_logo(&self) -> AnyElement {
1196 Icon::new(self.agent.logo())
1197 .color(Color::Muted)
1198 .size(IconSize::XLarge)
1199 .into_any_element()
1200 }
1201
1202 fn render_error_agent_logo(&self) -> AnyElement {
1203 let logo = Icon::new(self.agent.logo())
1204 .color(Color::Muted)
1205 .size(IconSize::XLarge)
1206 .into_any_element();
1207
1208 h_flex()
1209 .relative()
1210 .justify_center()
1211 .child(div().opacity(0.3).child(logo))
1212 .child(
1213 h_flex().absolute().right_1().bottom_0().child(
1214 Icon::new(IconName::XCircle)
1215 .color(Color::Error)
1216 .size(IconSize::Small),
1217 ),
1218 )
1219 .into_any_element()
1220 }
1221
1222 fn render_empty_state(&self, cx: &App) -> AnyElement {
1223 let loading = matches!(&self.thread_state, ThreadState::Loading { .. });
1224
1225 v_flex()
1226 .size_full()
1227 .items_center()
1228 .justify_center()
1229 .child(if loading {
1230 h_flex()
1231 .justify_center()
1232 .child(self.render_agent_logo())
1233 .with_animation(
1234 "pulsating_icon",
1235 Animation::new(Duration::from_secs(2))
1236 .repeat()
1237 .with_easing(pulsating_between(0.4, 1.0)),
1238 |icon, delta| icon.opacity(delta),
1239 )
1240 .into_any()
1241 } else {
1242 self.render_agent_logo().into_any_element()
1243 })
1244 .child(h_flex().mt_4().mb_1().justify_center().child(if loading {
1245 div()
1246 .child(LoadingLabel::new("").size(LabelSize::Large))
1247 .into_any_element()
1248 } else {
1249 Headline::new(self.agent.empty_state_headline())
1250 .size(HeadlineSize::Medium)
1251 .into_any_element()
1252 }))
1253 .child(
1254 div()
1255 .max_w_1_2()
1256 .text_sm()
1257 .text_center()
1258 .map(|this| {
1259 if loading {
1260 this.invisible()
1261 } else {
1262 this.text_color(cx.theme().colors().text_muted)
1263 }
1264 })
1265 .child(self.agent.empty_state_message()),
1266 )
1267 .into_any()
1268 }
1269
1270 fn render_pending_auth_state(&self) -> AnyElement {
1271 v_flex()
1272 .items_center()
1273 .justify_center()
1274 .child(self.render_error_agent_logo())
1275 .child(
1276 h_flex()
1277 .mt_4()
1278 .mb_1()
1279 .justify_center()
1280 .child(Headline::new("Not Authenticated").size(HeadlineSize::Medium)),
1281 )
1282 .into_any()
1283 }
1284
1285 fn render_error_state(&self, e: &LoadError, cx: &Context<Self>) -> AnyElement {
1286 let mut container = v_flex()
1287 .items_center()
1288 .justify_center()
1289 .child(self.render_error_agent_logo())
1290 .child(
1291 v_flex()
1292 .mt_4()
1293 .mb_2()
1294 .gap_0p5()
1295 .text_center()
1296 .items_center()
1297 .child(Headline::new("Failed to launch").size(HeadlineSize::Medium))
1298 .child(
1299 Label::new(e.to_string())
1300 .size(LabelSize::Small)
1301 .color(Color::Muted),
1302 ),
1303 );
1304
1305 if let LoadError::Unsupported {
1306 upgrade_message,
1307 upgrade_command,
1308 ..
1309 } = &e
1310 {
1311 let upgrade_message = upgrade_message.clone();
1312 let upgrade_command = upgrade_command.clone();
1313 container = container.child(Button::new("upgrade", upgrade_message).on_click(
1314 cx.listener(move |this, _, window, cx| {
1315 this.workspace
1316 .update(cx, |workspace, cx| {
1317 let project = workspace.project().read(cx);
1318 let cwd = project.first_project_directory(cx);
1319 let shell = project.terminal_settings(&cwd, cx).shell.clone();
1320 let spawn_in_terminal = task::SpawnInTerminal {
1321 id: task::TaskId("install".to_string()),
1322 full_label: upgrade_command.clone(),
1323 label: upgrade_command.clone(),
1324 command: Some(upgrade_command.clone()),
1325 args: Vec::new(),
1326 command_label: upgrade_command.clone(),
1327 cwd,
1328 env: Default::default(),
1329 use_new_terminal: true,
1330 allow_concurrent_runs: true,
1331 reveal: Default::default(),
1332 reveal_target: Default::default(),
1333 hide: Default::default(),
1334 shell,
1335 show_summary: true,
1336 show_command: true,
1337 show_rerun: false,
1338 };
1339 workspace
1340 .spawn_in_terminal(spawn_in_terminal, window, cx)
1341 .detach();
1342 })
1343 .ok();
1344 }),
1345 ));
1346 }
1347
1348 container.into_any()
1349 }
1350
1351 fn render_activity_bar(
1352 &self,
1353 thread_entity: &Entity<AcpThread>,
1354 window: &mut Window,
1355 cx: &Context<Self>,
1356 ) -> Option<AnyElement> {
1357 let thread = thread_entity.read(cx);
1358 let action_log = thread.action_log();
1359 let changed_buffers = action_log.read(cx).changed_buffers(cx);
1360 let plan = thread.plan();
1361
1362 if changed_buffers.is_empty() && plan.is_empty() {
1363 return None;
1364 }
1365
1366 let editor_bg_color = cx.theme().colors().editor_background;
1367 let active_color = cx.theme().colors().element_selected;
1368 let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
1369
1370 let pending_edits = thread.has_pending_edit_tool_calls();
1371
1372 v_flex()
1373 .mt_1()
1374 .mx_2()
1375 .bg(bg_edit_files_disclosure)
1376 .border_1()
1377 .border_b_0()
1378 .border_color(cx.theme().colors().border)
1379 .rounded_t_md()
1380 .shadow(vec![gpui::BoxShadow {
1381 color: gpui::black().opacity(0.15),
1382 offset: point(px(1.), px(-1.)),
1383 blur_radius: px(3.),
1384 spread_radius: px(0.),
1385 }])
1386 .when(!plan.is_empty(), |this| {
1387 this.child(self.render_plan_summary(plan, window, cx))
1388 .when(self.plan_expanded, |parent| {
1389 parent.child(self.render_plan_entries(plan, window, cx))
1390 })
1391 })
1392 .when(!changed_buffers.is_empty(), |this| {
1393 this.child(Divider::horizontal())
1394 .child(self.render_edits_summary(
1395 action_log,
1396 &changed_buffers,
1397 self.edits_expanded,
1398 pending_edits,
1399 window,
1400 cx,
1401 ))
1402 .when(self.edits_expanded, |parent| {
1403 parent.child(self.render_edited_files(
1404 action_log,
1405 &changed_buffers,
1406 pending_edits,
1407 cx,
1408 ))
1409 })
1410 })
1411 .into_any()
1412 .into()
1413 }
1414
1415 fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
1416 let stats = plan.stats();
1417
1418 let title = if let Some(entry) = stats.in_progress_entry
1419 && !self.plan_expanded
1420 {
1421 h_flex()
1422 .w_full()
1423 .gap_1()
1424 .text_xs()
1425 .text_color(cx.theme().colors().text_muted)
1426 .justify_between()
1427 .child(
1428 h_flex()
1429 .gap_1()
1430 .child(
1431 Label::new("Current:")
1432 .size(LabelSize::Small)
1433 .color(Color::Muted),
1434 )
1435 .child(MarkdownElement::new(
1436 entry.content.clone(),
1437 plan_label_markdown_style(&entry.status, window, cx),
1438 )),
1439 )
1440 .when(stats.pending > 0, |this| {
1441 this.child(
1442 Label::new(format!("{} left", stats.pending))
1443 .size(LabelSize::Small)
1444 .color(Color::Muted)
1445 .mr_1(),
1446 )
1447 })
1448 } else {
1449 let status_label = if stats.pending == 0 {
1450 "All Done".to_string()
1451 } else if stats.completed == 0 {
1452 format!("{}", plan.entries.len())
1453 } else {
1454 format!("{}/{}", stats.completed, plan.entries.len())
1455 };
1456
1457 h_flex()
1458 .w_full()
1459 .gap_1()
1460 .justify_between()
1461 .child(
1462 Label::new("Plan")
1463 .size(LabelSize::Small)
1464 .color(Color::Muted),
1465 )
1466 .child(
1467 Label::new(status_label)
1468 .size(LabelSize::Small)
1469 .color(Color::Muted)
1470 .mr_1(),
1471 )
1472 };
1473
1474 h_flex()
1475 .p_1()
1476 .justify_between()
1477 .when(self.plan_expanded, |this| {
1478 this.border_b_1().border_color(cx.theme().colors().border)
1479 })
1480 .child(
1481 h_flex()
1482 .id("plan_summary")
1483 .w_full()
1484 .gap_1()
1485 .child(Disclosure::new("plan_disclosure", self.plan_expanded))
1486 .child(title)
1487 .on_click(cx.listener(|this, _, _, cx| {
1488 this.plan_expanded = !this.plan_expanded;
1489 cx.notify();
1490 })),
1491 )
1492 }
1493
1494 fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
1495 v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
1496 let element = h_flex()
1497 .py_1()
1498 .px_2()
1499 .gap_2()
1500 .justify_between()
1501 .bg(cx.theme().colors().editor_background)
1502 .when(index < plan.entries.len() - 1, |parent| {
1503 parent.border_color(cx.theme().colors().border).border_b_1()
1504 })
1505 .child(
1506 h_flex()
1507 .id(("plan_entry", index))
1508 .gap_1p5()
1509 .max_w_full()
1510 .overflow_x_scroll()
1511 .text_xs()
1512 .text_color(cx.theme().colors().text_muted)
1513 .child(match entry.status {
1514 acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
1515 .size(IconSize::Small)
1516 .color(Color::Muted)
1517 .into_any_element(),
1518 acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
1519 .size(IconSize::Small)
1520 .color(Color::Accent)
1521 .with_animation(
1522 "running",
1523 Animation::new(Duration::from_secs(2)).repeat(),
1524 |icon, delta| {
1525 icon.transform(Transformation::rotate(percentage(delta)))
1526 },
1527 )
1528 .into_any_element(),
1529 acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
1530 .size(IconSize::Small)
1531 .color(Color::Success)
1532 .into_any_element(),
1533 })
1534 .child(MarkdownElement::new(
1535 entry.content.clone(),
1536 plan_label_markdown_style(&entry.status, window, cx),
1537 )),
1538 );
1539
1540 Some(element)
1541 }))
1542 }
1543
1544 fn render_edits_summary(
1545 &self,
1546 action_log: &Entity<ActionLog>,
1547 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
1548 expanded: bool,
1549 pending_edits: bool,
1550 window: &mut Window,
1551 cx: &Context<Self>,
1552 ) -> Div {
1553 const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
1554
1555 let focus_handle = self.focus_handle(cx);
1556
1557 h_flex()
1558 .p_1()
1559 .justify_between()
1560 .when(expanded, |this| {
1561 this.border_b_1().border_color(cx.theme().colors().border)
1562 })
1563 .child(
1564 h_flex()
1565 .id("edits-container")
1566 .cursor_pointer()
1567 .w_full()
1568 .gap_1()
1569 .child(Disclosure::new("edits-disclosure", expanded))
1570 .map(|this| {
1571 if pending_edits {
1572 this.child(
1573 Label::new(format!(
1574 "Editing {} {}…",
1575 changed_buffers.len(),
1576 if changed_buffers.len() == 1 {
1577 "file"
1578 } else {
1579 "files"
1580 }
1581 ))
1582 .color(Color::Muted)
1583 .size(LabelSize::Small)
1584 .with_animation(
1585 "edit-label",
1586 Animation::new(Duration::from_secs(2))
1587 .repeat()
1588 .with_easing(pulsating_between(0.3, 0.7)),
1589 |label, delta| label.alpha(delta),
1590 ),
1591 )
1592 } else {
1593 this.child(
1594 Label::new("Edits")
1595 .size(LabelSize::Small)
1596 .color(Color::Muted),
1597 )
1598 .child(Label::new("•").size(LabelSize::XSmall).color(Color::Muted))
1599 .child(
1600 Label::new(format!(
1601 "{} {}",
1602 changed_buffers.len(),
1603 if changed_buffers.len() == 1 {
1604 "file"
1605 } else {
1606 "files"
1607 }
1608 ))
1609 .size(LabelSize::Small)
1610 .color(Color::Muted),
1611 )
1612 }
1613 })
1614 .on_click(cx.listener(|this, _, _, cx| {
1615 this.edits_expanded = !this.edits_expanded;
1616 cx.notify();
1617 })),
1618 )
1619 .child(
1620 h_flex()
1621 .gap_1()
1622 .child(
1623 IconButton::new("review-changes", IconName::ListTodo)
1624 .icon_size(IconSize::Small)
1625 .tooltip({
1626 let focus_handle = focus_handle.clone();
1627 move |window, cx| {
1628 Tooltip::for_action_in(
1629 "Review Changes",
1630 &OpenAgentDiff,
1631 &focus_handle,
1632 window,
1633 cx,
1634 )
1635 }
1636 })
1637 .on_click(cx.listener(|_, _, window, cx| {
1638 window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
1639 })),
1640 )
1641 .child(Divider::vertical().color(DividerColor::Border))
1642 .child(
1643 Button::new("reject-all-changes", "Reject All")
1644 .label_size(LabelSize::Small)
1645 .disabled(pending_edits)
1646 .when(pending_edits, |this| {
1647 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
1648 })
1649 .key_binding(
1650 KeyBinding::for_action_in(
1651 &RejectAll,
1652 &focus_handle.clone(),
1653 window,
1654 cx,
1655 )
1656 .map(|kb| kb.size(rems_from_px(10.))),
1657 )
1658 .on_click({
1659 let action_log = action_log.clone();
1660 cx.listener(move |_, _, _, cx| {
1661 action_log.update(cx, |action_log, cx| {
1662 action_log.reject_all_edits(cx).detach();
1663 })
1664 })
1665 }),
1666 )
1667 .child(
1668 Button::new("keep-all-changes", "Keep All")
1669 .label_size(LabelSize::Small)
1670 .disabled(pending_edits)
1671 .when(pending_edits, |this| {
1672 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
1673 })
1674 .key_binding(
1675 KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
1676 .map(|kb| kb.size(rems_from_px(10.))),
1677 )
1678 .on_click({
1679 let action_log = action_log.clone();
1680 cx.listener(move |_, _, _, cx| {
1681 action_log.update(cx, |action_log, cx| {
1682 action_log.keep_all_edits(cx);
1683 })
1684 })
1685 }),
1686 ),
1687 )
1688 }
1689
1690 fn render_edited_files(
1691 &self,
1692 action_log: &Entity<ActionLog>,
1693 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
1694 pending_edits: bool,
1695 cx: &Context<Self>,
1696 ) -> Div {
1697 let editor_bg_color = cx.theme().colors().editor_background;
1698
1699 v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
1700 |(index, (buffer, _diff))| {
1701 let file = buffer.read(cx).file()?;
1702 let path = file.path();
1703
1704 let file_path = path.parent().and_then(|parent| {
1705 let parent_str = parent.to_string_lossy();
1706
1707 if parent_str.is_empty() {
1708 None
1709 } else {
1710 Some(
1711 Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
1712 .color(Color::Muted)
1713 .size(LabelSize::XSmall)
1714 .buffer_font(cx),
1715 )
1716 }
1717 });
1718
1719 let file_name = path.file_name().map(|name| {
1720 Label::new(name.to_string_lossy().to_string())
1721 .size(LabelSize::XSmall)
1722 .buffer_font(cx)
1723 });
1724
1725 let file_icon = FileIcons::get_icon(&path, cx)
1726 .map(Icon::from_path)
1727 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
1728 .unwrap_or_else(|| {
1729 Icon::new(IconName::File)
1730 .color(Color::Muted)
1731 .size(IconSize::Small)
1732 });
1733
1734 let overlay_gradient = linear_gradient(
1735 90.,
1736 linear_color_stop(editor_bg_color, 1.),
1737 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
1738 );
1739
1740 let element = h_flex()
1741 .group("edited-code")
1742 .id(("file-container", index))
1743 .relative()
1744 .py_1()
1745 .pl_2()
1746 .pr_1()
1747 .gap_2()
1748 .justify_between()
1749 .bg(editor_bg_color)
1750 .when(index < changed_buffers.len() - 1, |parent| {
1751 parent.border_color(cx.theme().colors().border).border_b_1()
1752 })
1753 .child(
1754 h_flex()
1755 .id(("file-name", index))
1756 .pr_8()
1757 .gap_1p5()
1758 .max_w_full()
1759 .overflow_x_scroll()
1760 .child(file_icon)
1761 .child(h_flex().gap_0p5().children(file_name).children(file_path))
1762 .on_click({
1763 let buffer = buffer.clone();
1764 cx.listener(move |this, _, window, cx| {
1765 this.open_edited_buffer(&buffer, window, cx);
1766 })
1767 }),
1768 )
1769 .child(
1770 h_flex()
1771 .gap_1()
1772 .visible_on_hover("edited-code")
1773 .child(
1774 Button::new("review", "Review")
1775 .label_size(LabelSize::Small)
1776 .on_click({
1777 let buffer = buffer.clone();
1778 cx.listener(move |this, _, window, cx| {
1779 this.open_edited_buffer(&buffer, window, cx);
1780 })
1781 }),
1782 )
1783 .child(Divider::vertical().color(DividerColor::BorderVariant))
1784 .child(
1785 Button::new("reject-file", "Reject")
1786 .label_size(LabelSize::Small)
1787 .disabled(pending_edits)
1788 .on_click({
1789 let buffer = buffer.clone();
1790 let action_log = action_log.clone();
1791 move |_, _, cx| {
1792 action_log.update(cx, |action_log, cx| {
1793 action_log
1794 .reject_edits_in_ranges(
1795 buffer.clone(),
1796 vec![Anchor::MIN..Anchor::MAX],
1797 cx,
1798 )
1799 .detach_and_log_err(cx);
1800 })
1801 }
1802 }),
1803 )
1804 .child(
1805 Button::new("keep-file", "Keep")
1806 .label_size(LabelSize::Small)
1807 .disabled(pending_edits)
1808 .on_click({
1809 let buffer = buffer.clone();
1810 let action_log = action_log.clone();
1811 move |_, _, cx| {
1812 action_log.update(cx, |action_log, cx| {
1813 action_log.keep_edits_in_range(
1814 buffer.clone(),
1815 Anchor::MIN..Anchor::MAX,
1816 cx,
1817 );
1818 })
1819 }
1820 }),
1821 ),
1822 )
1823 .child(
1824 div()
1825 .id("gradient-overlay")
1826 .absolute()
1827 .h_full()
1828 .w_12()
1829 .top_0()
1830 .bottom_0()
1831 .right(px(152.))
1832 .bg(overlay_gradient),
1833 );
1834
1835 Some(element)
1836 },
1837 ))
1838 }
1839
1840 fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
1841 let focus_handle = self.message_editor.focus_handle(cx);
1842 let editor_bg_color = cx.theme().colors().editor_background;
1843 let (expand_icon, expand_tooltip) = if self.editor_expanded {
1844 (IconName::Minimize, "Minimize Message Editor")
1845 } else {
1846 (IconName::Maximize, "Expand Message Editor")
1847 };
1848
1849 v_flex()
1850 .on_action(cx.listener(Self::expand_message_editor))
1851 .p_2()
1852 .gap_2()
1853 .border_t_1()
1854 .border_color(cx.theme().colors().border)
1855 .bg(editor_bg_color)
1856 .when(self.editor_expanded, |this| {
1857 this.h(vh(0.8, window)).size_full().justify_between()
1858 })
1859 .child(
1860 v_flex()
1861 .relative()
1862 .size_full()
1863 .pt_1()
1864 .pr_2p5()
1865 .child(div().flex_1().child({
1866 let settings = ThemeSettings::get_global(cx);
1867 let font_size = TextSize::Small
1868 .rems(cx)
1869 .to_pixels(settings.agent_font_size(cx));
1870 let line_height = settings.buffer_line_height.value() * font_size;
1871
1872 let text_style = TextStyle {
1873 color: cx.theme().colors().text,
1874 font_family: settings.buffer_font.family.clone(),
1875 font_fallbacks: settings.buffer_font.fallbacks.clone(),
1876 font_features: settings.buffer_font.features.clone(),
1877 font_size: font_size.into(),
1878 line_height: line_height.into(),
1879 ..Default::default()
1880 };
1881
1882 EditorElement::new(
1883 &self.message_editor,
1884 EditorStyle {
1885 background: editor_bg_color,
1886 local_player: cx.theme().players().local(),
1887 text: text_style,
1888 syntax: cx.theme().syntax().clone(),
1889 ..Default::default()
1890 },
1891 )
1892 }))
1893 .child(
1894 h_flex()
1895 .absolute()
1896 .top_0()
1897 .right_0()
1898 .opacity(0.5)
1899 .hover(|this| this.opacity(1.0))
1900 .child(
1901 IconButton::new("toggle-height", expand_icon)
1902 .icon_size(IconSize::XSmall)
1903 .icon_color(Color::Muted)
1904 .tooltip({
1905 let focus_handle = focus_handle.clone();
1906 move |window, cx| {
1907 Tooltip::for_action_in(
1908 expand_tooltip,
1909 &ExpandMessageEditor,
1910 &focus_handle,
1911 window,
1912 cx,
1913 )
1914 }
1915 })
1916 .on_click(cx.listener(|_, _, window, cx| {
1917 window.dispatch_action(Box::new(ExpandMessageEditor), cx);
1918 })),
1919 ),
1920 ),
1921 )
1922 .child(
1923 h_flex()
1924 .flex_none()
1925 .justify_between()
1926 .child(self.render_follow_toggle(cx))
1927 .child(self.render_send_button(cx)),
1928 )
1929 .into_any()
1930 }
1931
1932 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
1933 if self.thread().map_or(true, |thread| {
1934 thread.read(cx).status() == ThreadStatus::Idle
1935 }) {
1936 let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
1937 IconButton::new("send-message", IconName::Send)
1938 .icon_color(Color::Accent)
1939 .style(ButtonStyle::Filled)
1940 .disabled(self.thread().is_none() || is_editor_empty)
1941 .on_click(cx.listener(|this, _, window, cx| {
1942 this.chat(&Chat, window, cx);
1943 }))
1944 .when(!is_editor_empty, |button| {
1945 button.tooltip(move |window, cx| Tooltip::for_action("Send", &Chat, window, cx))
1946 })
1947 .when(is_editor_empty, |button| {
1948 button.tooltip(Tooltip::text("Type a message to submit"))
1949 })
1950 .into_any_element()
1951 } else {
1952 IconButton::new("stop-generation", IconName::StopFilled)
1953 .icon_color(Color::Error)
1954 .style(ButtonStyle::Tinted(ui::TintColor::Error))
1955 .tooltip(move |window, cx| {
1956 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
1957 })
1958 .on_click(cx.listener(|this, _event, _, cx| this.cancel(cx)))
1959 .into_any_element()
1960 }
1961 }
1962
1963 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
1964 let following = self
1965 .workspace
1966 .read_with(cx, |workspace, _| {
1967 workspace.is_being_followed(CollaboratorId::Agent)
1968 })
1969 .unwrap_or(false);
1970
1971 IconButton::new("follow-agent", IconName::Crosshair)
1972 .icon_size(IconSize::Small)
1973 .icon_color(Color::Muted)
1974 .toggle_state(following)
1975 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
1976 .tooltip(move |window, cx| {
1977 if following {
1978 Tooltip::for_action("Stop Following Agent", &Follow, window, cx)
1979 } else {
1980 Tooltip::with_meta(
1981 "Follow Agent",
1982 Some(&Follow),
1983 "Track the agent's location as it reads and edits files.",
1984 window,
1985 cx,
1986 )
1987 }
1988 })
1989 .on_click(cx.listener(move |this, _, window, cx| {
1990 this.workspace
1991 .update(cx, |workspace, cx| {
1992 if following {
1993 workspace.unfollow(CollaboratorId::Agent, window, cx);
1994 } else {
1995 workspace.follow(CollaboratorId::Agent, window, cx);
1996 }
1997 })
1998 .ok();
1999 }))
2000 }
2001
2002 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
2003 let workspace = self.workspace.clone();
2004 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
2005 Self::open_link(text, &workspace, window, cx);
2006 })
2007 }
2008
2009 fn open_link(
2010 url: SharedString,
2011 workspace: &WeakEntity<Workspace>,
2012 window: &mut Window,
2013 cx: &mut App,
2014 ) {
2015 let Some(workspace) = workspace.upgrade() else {
2016 cx.open_url(&url);
2017 return;
2018 };
2019
2020 if let Some(mention_path) = MentionPath::try_parse(&url) {
2021 workspace.update(cx, |workspace, cx| {
2022 let project = workspace.project();
2023 let Some((path, entry)) = project.update(cx, |project, cx| {
2024 let path = project.find_project_path(mention_path.path(), cx)?;
2025 let entry = project.entry_for_path(&path, cx)?;
2026 Some((path, entry))
2027 }) else {
2028 return;
2029 };
2030
2031 if entry.is_dir() {
2032 project.update(cx, |_, cx| {
2033 cx.emit(project::Event::RevealInProjectPanel(entry.id));
2034 });
2035 } else {
2036 workspace
2037 .open_path(path, None, true, window, cx)
2038 .detach_and_log_err(cx);
2039 }
2040 })
2041 } else {
2042 cx.open_url(&url);
2043 }
2044 }
2045
2046 fn open_tool_call_location(
2047 &self,
2048 entry_ix: usize,
2049 location_ix: usize,
2050 window: &mut Window,
2051 cx: &mut Context<Self>,
2052 ) -> Option<()> {
2053 let location = self
2054 .thread()?
2055 .read(cx)
2056 .entries()
2057 .get(entry_ix)?
2058 .locations()?
2059 .get(location_ix)?;
2060
2061 let project_path = self
2062 .project
2063 .read(cx)
2064 .find_project_path(&location.path, cx)?;
2065
2066 let open_task = self
2067 .workspace
2068 .update(cx, |worskpace, cx| {
2069 worskpace.open_path(project_path, None, true, window, cx)
2070 })
2071 .log_err()?;
2072
2073 window
2074 .spawn(cx, async move |cx| {
2075 let item = open_task.await?;
2076
2077 let Some(active_editor) = item.downcast::<Editor>() else {
2078 return anyhow::Ok(());
2079 };
2080
2081 active_editor.update_in(cx, |editor, window, cx| {
2082 let snapshot = editor.buffer().read(cx).snapshot(cx);
2083 let first_hunk = editor
2084 .diff_hunks_in_ranges(
2085 &[editor::Anchor::min()..editor::Anchor::max()],
2086 &snapshot,
2087 )
2088 .next();
2089 if let Some(first_hunk) = first_hunk {
2090 let first_hunk_start = first_hunk.multi_buffer_range().start;
2091 editor.change_selections(Default::default(), window, cx, |selections| {
2092 selections.select_anchor_ranges([first_hunk_start..first_hunk_start]);
2093 })
2094 }
2095 })?;
2096
2097 anyhow::Ok(())
2098 })
2099 .detach_and_log_err(cx);
2100
2101 None
2102 }
2103
2104 pub fn open_thread_as_markdown(
2105 &self,
2106 workspace: Entity<Workspace>,
2107 window: &mut Window,
2108 cx: &mut App,
2109 ) -> Task<anyhow::Result<()>> {
2110 let markdown_language_task = workspace
2111 .read(cx)
2112 .app_state()
2113 .languages
2114 .language_for_name("Markdown");
2115
2116 let (thread_summary, markdown) = if let Some(thread) = self.thread() {
2117 let thread = thread.read(cx);
2118 (thread.title().to_string(), thread.to_markdown(cx))
2119 } else {
2120 return Task::ready(Ok(()));
2121 };
2122
2123 window.spawn(cx, async move |cx| {
2124 let markdown_language = markdown_language_task.await?;
2125
2126 workspace.update_in(cx, |workspace, window, cx| {
2127 let project = workspace.project().clone();
2128
2129 if !project.read(cx).is_local() {
2130 anyhow::bail!("failed to open active thread as markdown in remote project");
2131 }
2132
2133 let buffer = project.update(cx, |project, cx| {
2134 project.create_local_buffer(&markdown, Some(markdown_language), cx)
2135 });
2136 let buffer = cx.new(|cx| {
2137 MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
2138 });
2139
2140 workspace.add_item_to_active_pane(
2141 Box::new(cx.new(|cx| {
2142 let mut editor =
2143 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
2144 editor.set_breadcrumb_header(thread_summary);
2145 editor
2146 })),
2147 None,
2148 true,
2149 window,
2150 cx,
2151 );
2152
2153 anyhow::Ok(())
2154 })??;
2155 anyhow::Ok(())
2156 })
2157 }
2158
2159 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
2160 self.list_state.scroll_to(ListOffset::default());
2161 cx.notify();
2162 }
2163}
2164
2165impl Focusable for AcpThreadView {
2166 fn focus_handle(&self, cx: &App) -> FocusHandle {
2167 self.message_editor.focus_handle(cx)
2168 }
2169}
2170
2171impl Render for AcpThreadView {
2172 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2173 let open_as_markdown = IconButton::new("open-as-markdown", IconName::DocumentText)
2174 .icon_size(IconSize::XSmall)
2175 .icon_color(Color::Ignored)
2176 .tooltip(Tooltip::text("Open Thread as Markdown"))
2177 .on_click(cx.listener(move |this, _, window, cx| {
2178 if let Some(workspace) = this.workspace.upgrade() {
2179 this.open_thread_as_markdown(workspace, window, cx)
2180 .detach_and_log_err(cx);
2181 }
2182 }));
2183
2184 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUpAlt)
2185 .icon_size(IconSize::XSmall)
2186 .icon_color(Color::Ignored)
2187 .tooltip(Tooltip::text("Scroll To Top"))
2188 .on_click(cx.listener(move |this, _, _, cx| {
2189 this.scroll_to_top(cx);
2190 }));
2191
2192 v_flex()
2193 .size_full()
2194 .key_context("AcpThread")
2195 .on_action(cx.listener(Self::chat))
2196 .on_action(cx.listener(Self::previous_history_message))
2197 .on_action(cx.listener(Self::next_history_message))
2198 .on_action(cx.listener(Self::open_agent_diff))
2199 .child(match &self.thread_state {
2200 ThreadState::Unauthenticated { .. } => {
2201 v_flex()
2202 .p_2()
2203 .flex_1()
2204 .items_center()
2205 .justify_center()
2206 .child(self.render_pending_auth_state())
2207 .child(
2208 h_flex().mt_1p5().justify_center().child(
2209 Button::new("sign-in", format!("Sign in to {}", self.agent.name()))
2210 .on_click(cx.listener(|this, _, window, cx| {
2211 this.authenticate(window, cx)
2212 })),
2213 ),
2214 )
2215 }
2216 ThreadState::Loading { .. } => v_flex().flex_1().child(self.render_empty_state(cx)),
2217 ThreadState::LoadError(e) => v_flex()
2218 .p_2()
2219 .flex_1()
2220 .items_center()
2221 .justify_center()
2222 .child(self.render_error_state(e, cx)),
2223 ThreadState::Ready { thread, .. } => v_flex().flex_1().map(|this| {
2224 if self.list_state.item_count() > 0 {
2225 this.child(
2226 list(self.list_state.clone())
2227 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
2228 .flex_grow()
2229 .into_any(),
2230 )
2231 .child(
2232 h_flex()
2233 .group("controls")
2234 .mt_1()
2235 .mr_1()
2236 .py_2()
2237 .px(RESPONSE_PADDING_X)
2238 .opacity(0.4)
2239 .hover(|style| style.opacity(1.))
2240 .flex_wrap()
2241 .justify_end()
2242 .child(open_as_markdown)
2243 .child(scroll_to_top)
2244 .into_any_element(),
2245 )
2246 .children(match thread.read(cx).status() {
2247 ThreadStatus::Idle | ThreadStatus::WaitingForToolConfirmation => None,
2248 ThreadStatus::Generating => div()
2249 .px_5()
2250 .py_2()
2251 .child(LoadingLabel::new("").size(LabelSize::Small))
2252 .into(),
2253 })
2254 .children(self.render_activity_bar(&thread, window, cx))
2255 } else {
2256 this.child(self.render_empty_state(cx))
2257 }
2258 }),
2259 })
2260 .when_some(self.last_error.clone(), |el, error| {
2261 el.child(
2262 div()
2263 .p_2()
2264 .text_xs()
2265 .border_t_1()
2266 .border_color(cx.theme().colors().border)
2267 .bg(cx.theme().status().error_background)
2268 .child(
2269 self.render_markdown(error, default_markdown_style(false, window, cx)),
2270 ),
2271 )
2272 })
2273 .child(self.render_message_editor(window, cx))
2274 }
2275}
2276
2277fn user_message_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
2278 let mut style = default_markdown_style(false, window, cx);
2279 let mut text_style = window.text_style();
2280 let theme_settings = ThemeSettings::get_global(cx);
2281
2282 let buffer_font = theme_settings.buffer_font.family.clone();
2283 let buffer_font_size = TextSize::Small.rems(cx);
2284
2285 text_style.refine(&TextStyleRefinement {
2286 font_family: Some(buffer_font),
2287 font_size: Some(buffer_font_size.into()),
2288 ..Default::default()
2289 });
2290
2291 style.base_text_style = text_style;
2292 style.link_callback = Some(Rc::new(move |url, cx| {
2293 if MentionPath::try_parse(url).is_some() {
2294 let colors = cx.theme().colors();
2295 Some(TextStyleRefinement {
2296 background_color: Some(colors.element_background),
2297 ..Default::default()
2298 })
2299 } else {
2300 None
2301 }
2302 }));
2303 style
2304}
2305
2306fn default_markdown_style(buffer_font: bool, window: &Window, cx: &App) -> MarkdownStyle {
2307 let theme_settings = ThemeSettings::get_global(cx);
2308 let colors = cx.theme().colors();
2309
2310 let buffer_font_size = TextSize::Small.rems(cx);
2311
2312 let mut text_style = window.text_style();
2313 let line_height = buffer_font_size * 1.75;
2314
2315 let font_family = if buffer_font {
2316 theme_settings.buffer_font.family.clone()
2317 } else {
2318 theme_settings.ui_font.family.clone()
2319 };
2320
2321 let font_size = if buffer_font {
2322 TextSize::Small.rems(cx)
2323 } else {
2324 TextSize::Default.rems(cx)
2325 };
2326
2327 text_style.refine(&TextStyleRefinement {
2328 font_family: Some(font_family),
2329 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
2330 font_features: Some(theme_settings.ui_font.features.clone()),
2331 font_size: Some(font_size.into()),
2332 line_height: Some(line_height.into()),
2333 color: Some(cx.theme().colors().text),
2334 ..Default::default()
2335 });
2336
2337 MarkdownStyle {
2338 base_text_style: text_style.clone(),
2339 syntax: cx.theme().syntax().clone(),
2340 selection_background_color: cx.theme().colors().element_selection_background,
2341 code_block_overflow_x_scroll: true,
2342 table_overflow_x_scroll: true,
2343 heading_level_styles: Some(HeadingLevelStyles {
2344 h1: Some(TextStyleRefinement {
2345 font_size: Some(rems(1.15).into()),
2346 ..Default::default()
2347 }),
2348 h2: Some(TextStyleRefinement {
2349 font_size: Some(rems(1.1).into()),
2350 ..Default::default()
2351 }),
2352 h3: Some(TextStyleRefinement {
2353 font_size: Some(rems(1.05).into()),
2354 ..Default::default()
2355 }),
2356 h4: Some(TextStyleRefinement {
2357 font_size: Some(rems(1.).into()),
2358 ..Default::default()
2359 }),
2360 h5: Some(TextStyleRefinement {
2361 font_size: Some(rems(0.95).into()),
2362 ..Default::default()
2363 }),
2364 h6: Some(TextStyleRefinement {
2365 font_size: Some(rems(0.875).into()),
2366 ..Default::default()
2367 }),
2368 }),
2369 code_block: StyleRefinement {
2370 padding: EdgesRefinement {
2371 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2372 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2373 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2374 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2375 },
2376 margin: EdgesRefinement {
2377 top: Some(Length::Definite(Pixels(8.).into())),
2378 left: Some(Length::Definite(Pixels(0.).into())),
2379 right: Some(Length::Definite(Pixels(0.).into())),
2380 bottom: Some(Length::Definite(Pixels(12.).into())),
2381 },
2382 border_style: Some(BorderStyle::Solid),
2383 border_widths: EdgesRefinement {
2384 top: Some(AbsoluteLength::Pixels(Pixels(1.))),
2385 left: Some(AbsoluteLength::Pixels(Pixels(1.))),
2386 right: Some(AbsoluteLength::Pixels(Pixels(1.))),
2387 bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
2388 },
2389 border_color: Some(colors.border_variant),
2390 background: Some(colors.editor_background.into()),
2391 text: Some(TextStyleRefinement {
2392 font_family: Some(theme_settings.buffer_font.family.clone()),
2393 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
2394 font_features: Some(theme_settings.buffer_font.features.clone()),
2395 font_size: Some(buffer_font_size.into()),
2396 ..Default::default()
2397 }),
2398 ..Default::default()
2399 },
2400 inline_code: TextStyleRefinement {
2401 font_family: Some(theme_settings.buffer_font.family.clone()),
2402 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
2403 font_features: Some(theme_settings.buffer_font.features.clone()),
2404 font_size: Some(buffer_font_size.into()),
2405 background_color: Some(colors.editor_foreground.opacity(0.08)),
2406 ..Default::default()
2407 },
2408 link: TextStyleRefinement {
2409 background_color: Some(colors.editor_foreground.opacity(0.025)),
2410 underline: Some(UnderlineStyle {
2411 color: Some(colors.text_accent.opacity(0.5)),
2412 thickness: px(1.),
2413 ..Default::default()
2414 }),
2415 ..Default::default()
2416 },
2417 ..Default::default()
2418 }
2419}
2420
2421fn plan_label_markdown_style(
2422 status: &acp::PlanEntryStatus,
2423 window: &Window,
2424 cx: &App,
2425) -> MarkdownStyle {
2426 let default_md_style = default_markdown_style(false, window, cx);
2427
2428 MarkdownStyle {
2429 base_text_style: TextStyle {
2430 color: cx.theme().colors().text_muted,
2431 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
2432 Some(gpui::StrikethroughStyle {
2433 thickness: px(1.),
2434 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
2435 })
2436 } else {
2437 None
2438 },
2439 ..default_md_style.base_text_style
2440 },
2441 ..default_md_style
2442 }
2443}