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::WaitingForConfirmation { .. } => None,
876 ToolCallStatus::Allowed {
877 status: acp::ToolCallStatus::InProgress,
878 ..
879 } => Some(
880 Icon::new(IconName::ArrowCircle)
881 .color(Color::Accent)
882 .size(IconSize::Small)
883 .with_animation(
884 "running",
885 Animation::new(Duration::from_secs(2)).repeat(),
886 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
887 )
888 .into_any(),
889 ),
890 ToolCallStatus::Allowed {
891 status: acp::ToolCallStatus::Completed,
892 ..
893 } => None,
894 ToolCallStatus::Rejected
895 | ToolCallStatus::Canceled
896 | ToolCallStatus::Allowed {
897 status: acp::ToolCallStatus::Failed,
898 ..
899 } => Some(
900 Icon::new(IconName::X)
901 .color(Color::Error)
902 .size(IconSize::Small)
903 .into_any_element(),
904 ),
905 };
906
907 let needs_confirmation = match &tool_call.status {
908 ToolCallStatus::WaitingForConfirmation { .. } => true,
909 _ => tool_call
910 .content
911 .iter()
912 .any(|content| matches!(content, ToolCallContent::Diff { .. })),
913 };
914
915 let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
916 let is_open = !is_collapsible || self.expanded_tool_calls.contains(&tool_call.id);
917
918 v_flex()
919 .when(needs_confirmation, |this| {
920 this.rounded_lg()
921 .border_1()
922 .border_color(self.tool_card_border_color(cx))
923 .bg(cx.theme().colors().editor_background)
924 .overflow_hidden()
925 })
926 .child(
927 h_flex()
928 .id(header_id)
929 .w_full()
930 .gap_1()
931 .justify_between()
932 .map(|this| {
933 if needs_confirmation {
934 this.px_2()
935 .py_1()
936 .rounded_t_md()
937 .bg(self.tool_card_header_bg(cx))
938 .border_b_1()
939 .border_color(self.tool_card_border_color(cx))
940 } else {
941 this.opacity(0.8).hover(|style| style.opacity(1.))
942 }
943 })
944 .child(
945 h_flex()
946 .id("tool-call-header")
947 .overflow_x_scroll()
948 .map(|this| {
949 if needs_confirmation {
950 this.text_xs()
951 } else {
952 this.text_size(self.tool_name_font_size())
953 }
954 })
955 .gap_1p5()
956 .child(
957 Icon::new(match tool_call.kind {
958 acp::ToolKind::Read => IconName::ToolRead,
959 acp::ToolKind::Edit => IconName::ToolPencil,
960 acp::ToolKind::Search => IconName::ToolSearch,
961 acp::ToolKind::Execute => IconName::ToolTerminal,
962 acp::ToolKind::Think => IconName::ToolBulb,
963 acp::ToolKind::Fetch => IconName::ToolWeb,
964 acp::ToolKind::Other => IconName::ToolHammer,
965 })
966 .size(IconSize::Small)
967 .color(Color::Muted),
968 )
969 .child(if tool_call.locations.len() == 1 {
970 let name = tool_call.locations[0]
971 .path
972 .file_name()
973 .unwrap_or_default()
974 .display()
975 .to_string();
976
977 h_flex()
978 .id(("open-tool-call-location", entry_ix))
979 .child(name)
980 .w_full()
981 .max_w_full()
982 .pr_1()
983 .gap_0p5()
984 .cursor_pointer()
985 .rounded_sm()
986 .opacity(0.8)
987 .hover(|label| {
988 label.opacity(1.).bg(cx
989 .theme()
990 .colors()
991 .element_hover
992 .opacity(0.5))
993 })
994 .tooltip(Tooltip::text("Jump to File"))
995 .on_click(cx.listener(move |this, _, window, cx| {
996 this.open_tool_call_location(entry_ix, 0, window, cx);
997 }))
998 .into_any_element()
999 } else {
1000 self.render_markdown(
1001 tool_call.label.clone(),
1002 default_markdown_style(needs_confirmation, window, cx),
1003 )
1004 .into_any()
1005 }),
1006 )
1007 .child(
1008 h_flex()
1009 .gap_0p5()
1010 .when(is_collapsible, |this| {
1011 this.child(
1012 Disclosure::new(("expand", entry_ix), is_open)
1013 .opened_icon(IconName::ChevronUp)
1014 .closed_icon(IconName::ChevronDown)
1015 .on_click(cx.listener({
1016 let id = tool_call.id.clone();
1017 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1018 if is_open {
1019 this.expanded_tool_calls.remove(&id);
1020 } else {
1021 this.expanded_tool_calls.insert(id.clone());
1022 }
1023 cx.notify();
1024 }
1025 })),
1026 )
1027 })
1028 .children(status_icon),
1029 )
1030 .on_click(cx.listener({
1031 let id = tool_call.id.clone();
1032 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1033 if is_open {
1034 this.expanded_tool_calls.remove(&id);
1035 } else {
1036 this.expanded_tool_calls.insert(id.clone());
1037 }
1038 cx.notify();
1039 }
1040 })),
1041 )
1042 .when(is_open, |this| {
1043 this.child(
1044 v_flex()
1045 .text_xs()
1046 .when(is_collapsible, |this| {
1047 this.mt_1()
1048 .border_1()
1049 .border_color(self.tool_card_border_color(cx))
1050 .bg(cx.theme().colors().editor_background)
1051 .rounded_lg()
1052 })
1053 .map(|this| {
1054 if is_open {
1055 match &tool_call.status {
1056 ToolCallStatus::WaitingForConfirmation { options, .. } => this
1057 .children(tool_call.content.iter().map(|content| {
1058 div()
1059 .py_1p5()
1060 .child(
1061 self.render_tool_call_content(
1062 content, window, cx,
1063 ),
1064 )
1065 .into_any_element()
1066 }))
1067 // todo! confirm this looks ok
1068 .child(self.render_permission_buttons(
1069 options,
1070 entry_ix,
1071 tool_call.id.clone(),
1072 cx,
1073 )),
1074 ToolCallStatus::Allowed { .. } | ToolCallStatus::Canceled => {
1075 this.children(tool_call.content.iter().map(|content| {
1076 div()
1077 .py_1p5()
1078 .child(
1079 self.render_tool_call_content(
1080 content, window, cx,
1081 ),
1082 )
1083 .into_any_element()
1084 }))
1085 }
1086 ToolCallStatus::Rejected => this,
1087 }
1088 } else {
1089 this
1090 }
1091 }),
1092 )
1093 })
1094 }
1095
1096 fn render_tool_call_content(
1097 &self,
1098 content: &ToolCallContent,
1099 window: &Window,
1100 cx: &Context<Self>,
1101 ) -> AnyElement {
1102 match content {
1103 ToolCallContent::ContentBlock { content } => {
1104 if let Some(md) = content.markdown() {
1105 div()
1106 .p_2()
1107 .child(
1108 self.render_markdown(
1109 md.clone(),
1110 default_markdown_style(false, window, cx),
1111 ),
1112 )
1113 .into_any_element()
1114 } else {
1115 Empty.into_any_element()
1116 }
1117 }
1118 ToolCallContent::Diff {
1119 diff: Diff { multibuffer, .. },
1120 ..
1121 } => self.render_diff_editor(multibuffer),
1122 }
1123 }
1124
1125 fn render_permission_buttons(
1126 &self,
1127 options: &[acp::PermissionOption],
1128 entry_ix: usize,
1129 tool_call_id: acp::ToolCallId,
1130 cx: &Context<Self>,
1131 ) -> Div {
1132 h_flex()
1133 .py_1p5()
1134 .px_1p5()
1135 .gap_1()
1136 .justify_end()
1137 .border_t_1()
1138 .border_color(self.tool_card_border_color(cx))
1139 .children(options.iter().map(|option| {
1140 let option_id = SharedString::from(option.id.0.clone());
1141 Button::new((option_id, entry_ix), option.label.clone())
1142 .map(|this| match option.kind {
1143 acp::PermissionOptionKind::AllowOnce => {
1144 this.icon(IconName::Check).icon_color(Color::Success)
1145 }
1146 acp::PermissionOptionKind::AllowAlways => {
1147 this.icon(IconName::CheckDouble).icon_color(Color::Success)
1148 }
1149 acp::PermissionOptionKind::RejectOnce => {
1150 this.icon(IconName::X).icon_color(Color::Error)
1151 }
1152 acp::PermissionOptionKind::RejectAlways => {
1153 this.icon(IconName::X).icon_color(Color::Error)
1154 }
1155 })
1156 .icon_position(IconPosition::Start)
1157 .icon_size(IconSize::XSmall)
1158 .on_click(cx.listener({
1159 let tool_call_id = tool_call_id.clone();
1160 let option_id = option.id.clone();
1161 let option_kind = option.kind;
1162 move |this, _, _, cx| {
1163 this.authorize_tool_call(
1164 tool_call_id.clone(),
1165 option_id.clone(),
1166 option_kind,
1167 cx,
1168 );
1169 }
1170 }))
1171 }))
1172 }
1173
1174 fn render_diff_editor(&self, multibuffer: &Entity<MultiBuffer>) -> AnyElement {
1175 v_flex()
1176 .h_full()
1177 .child(
1178 if let Some(editor) = self.diff_editors.get(&multibuffer.entity_id()) {
1179 editor.clone().into_any_element()
1180 } else {
1181 Empty.into_any()
1182 },
1183 )
1184 .into_any()
1185 }
1186
1187 fn render_agent_logo(&self) -> AnyElement {
1188 Icon::new(self.agent.logo())
1189 .color(Color::Muted)
1190 .size(IconSize::XLarge)
1191 .into_any_element()
1192 }
1193
1194 fn render_error_agent_logo(&self) -> AnyElement {
1195 let logo = Icon::new(self.agent.logo())
1196 .color(Color::Muted)
1197 .size(IconSize::XLarge)
1198 .into_any_element();
1199
1200 h_flex()
1201 .relative()
1202 .justify_center()
1203 .child(div().opacity(0.3).child(logo))
1204 .child(
1205 h_flex().absolute().right_1().bottom_0().child(
1206 Icon::new(IconName::XCircle)
1207 .color(Color::Error)
1208 .size(IconSize::Small),
1209 ),
1210 )
1211 .into_any_element()
1212 }
1213
1214 fn render_empty_state(&self, cx: &App) -> AnyElement {
1215 let loading = matches!(&self.thread_state, ThreadState::Loading { .. });
1216
1217 v_flex()
1218 .size_full()
1219 .items_center()
1220 .justify_center()
1221 .child(if loading {
1222 h_flex()
1223 .justify_center()
1224 .child(self.render_agent_logo())
1225 .with_animation(
1226 "pulsating_icon",
1227 Animation::new(Duration::from_secs(2))
1228 .repeat()
1229 .with_easing(pulsating_between(0.4, 1.0)),
1230 |icon, delta| icon.opacity(delta),
1231 )
1232 .into_any()
1233 } else {
1234 self.render_agent_logo().into_any_element()
1235 })
1236 .child(h_flex().mt_4().mb_1().justify_center().child(if loading {
1237 div()
1238 .child(LoadingLabel::new("").size(LabelSize::Large))
1239 .into_any_element()
1240 } else {
1241 Headline::new(self.agent.empty_state_headline())
1242 .size(HeadlineSize::Medium)
1243 .into_any_element()
1244 }))
1245 .child(
1246 div()
1247 .max_w_1_2()
1248 .text_sm()
1249 .text_center()
1250 .map(|this| {
1251 if loading {
1252 this.invisible()
1253 } else {
1254 this.text_color(cx.theme().colors().text_muted)
1255 }
1256 })
1257 .child(self.agent.empty_state_message()),
1258 )
1259 .into_any()
1260 }
1261
1262 fn render_pending_auth_state(&self) -> AnyElement {
1263 v_flex()
1264 .items_center()
1265 .justify_center()
1266 .child(self.render_error_agent_logo())
1267 .child(
1268 h_flex()
1269 .mt_4()
1270 .mb_1()
1271 .justify_center()
1272 .child(Headline::new("Not Authenticated").size(HeadlineSize::Medium)),
1273 )
1274 .into_any()
1275 }
1276
1277 fn render_error_state(&self, e: &LoadError, cx: &Context<Self>) -> AnyElement {
1278 let mut container = v_flex()
1279 .items_center()
1280 .justify_center()
1281 .child(self.render_error_agent_logo())
1282 .child(
1283 v_flex()
1284 .mt_4()
1285 .mb_2()
1286 .gap_0p5()
1287 .text_center()
1288 .items_center()
1289 .child(Headline::new("Failed to launch").size(HeadlineSize::Medium))
1290 .child(
1291 Label::new(e.to_string())
1292 .size(LabelSize::Small)
1293 .color(Color::Muted),
1294 ),
1295 );
1296
1297 if let LoadError::Unsupported {
1298 upgrade_message,
1299 upgrade_command,
1300 ..
1301 } = &e
1302 {
1303 let upgrade_message = upgrade_message.clone();
1304 let upgrade_command = upgrade_command.clone();
1305 container = container.child(Button::new("upgrade", upgrade_message).on_click(
1306 cx.listener(move |this, _, window, cx| {
1307 this.workspace
1308 .update(cx, |workspace, cx| {
1309 let project = workspace.project().read(cx);
1310 let cwd = project.first_project_directory(cx);
1311 let shell = project.terminal_settings(&cwd, cx).shell.clone();
1312 let spawn_in_terminal = task::SpawnInTerminal {
1313 id: task::TaskId("install".to_string()),
1314 full_label: upgrade_command.clone(),
1315 label: upgrade_command.clone(),
1316 command: Some(upgrade_command.clone()),
1317 args: Vec::new(),
1318 command_label: upgrade_command.clone(),
1319 cwd,
1320 env: Default::default(),
1321 use_new_terminal: true,
1322 allow_concurrent_runs: true,
1323 reveal: Default::default(),
1324 reveal_target: Default::default(),
1325 hide: Default::default(),
1326 shell,
1327 show_summary: true,
1328 show_command: true,
1329 show_rerun: false,
1330 };
1331 workspace
1332 .spawn_in_terminal(spawn_in_terminal, window, cx)
1333 .detach();
1334 })
1335 .ok();
1336 }),
1337 ));
1338 }
1339
1340 container.into_any()
1341 }
1342
1343 fn render_activity_bar(
1344 &self,
1345 thread_entity: &Entity<AcpThread>,
1346 window: &mut Window,
1347 cx: &Context<Self>,
1348 ) -> Option<AnyElement> {
1349 let thread = thread_entity.read(cx);
1350 let action_log = thread.action_log();
1351 let changed_buffers = action_log.read(cx).changed_buffers(cx);
1352 let plan = thread.plan();
1353
1354 if changed_buffers.is_empty() && plan.is_empty() {
1355 return None;
1356 }
1357
1358 let editor_bg_color = cx.theme().colors().editor_background;
1359 let active_color = cx.theme().colors().element_selected;
1360 let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
1361
1362 let pending_edits = thread.has_pending_edit_tool_calls();
1363
1364 v_flex()
1365 .mt_1()
1366 .mx_2()
1367 .bg(bg_edit_files_disclosure)
1368 .border_1()
1369 .border_b_0()
1370 .border_color(cx.theme().colors().border)
1371 .rounded_t_md()
1372 .shadow(vec![gpui::BoxShadow {
1373 color: gpui::black().opacity(0.15),
1374 offset: point(px(1.), px(-1.)),
1375 blur_radius: px(3.),
1376 spread_radius: px(0.),
1377 }])
1378 .when(!plan.is_empty(), |this| {
1379 this.child(self.render_plan_summary(plan, window, cx))
1380 .when(self.plan_expanded, |parent| {
1381 parent.child(self.render_plan_entries(plan, window, cx))
1382 })
1383 })
1384 .when(!changed_buffers.is_empty(), |this| {
1385 this.child(Divider::horizontal())
1386 .child(self.render_edits_summary(
1387 action_log,
1388 &changed_buffers,
1389 self.edits_expanded,
1390 pending_edits,
1391 window,
1392 cx,
1393 ))
1394 .when(self.edits_expanded, |parent| {
1395 parent.child(self.render_edited_files(
1396 action_log,
1397 &changed_buffers,
1398 pending_edits,
1399 cx,
1400 ))
1401 })
1402 })
1403 .into_any()
1404 .into()
1405 }
1406
1407 fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
1408 let stats = plan.stats();
1409
1410 let title = if let Some(entry) = stats.in_progress_entry
1411 && !self.plan_expanded
1412 {
1413 h_flex()
1414 .w_full()
1415 .gap_1()
1416 .text_xs()
1417 .text_color(cx.theme().colors().text_muted)
1418 .justify_between()
1419 .child(
1420 h_flex()
1421 .gap_1()
1422 .child(
1423 Label::new("Current:")
1424 .size(LabelSize::Small)
1425 .color(Color::Muted),
1426 )
1427 .child(MarkdownElement::new(
1428 entry.content.clone(),
1429 plan_label_markdown_style(&entry.status, window, cx),
1430 )),
1431 )
1432 .when(stats.pending > 0, |this| {
1433 this.child(
1434 Label::new(format!("{} left", stats.pending))
1435 .size(LabelSize::Small)
1436 .color(Color::Muted)
1437 .mr_1(),
1438 )
1439 })
1440 } else {
1441 let status_label = if stats.pending == 0 {
1442 "All Done".to_string()
1443 } else if stats.completed == 0 {
1444 format!("{}", plan.entries.len())
1445 } else {
1446 format!("{}/{}", stats.completed, plan.entries.len())
1447 };
1448
1449 h_flex()
1450 .w_full()
1451 .gap_1()
1452 .justify_between()
1453 .child(
1454 Label::new("Plan")
1455 .size(LabelSize::Small)
1456 .color(Color::Muted),
1457 )
1458 .child(
1459 Label::new(status_label)
1460 .size(LabelSize::Small)
1461 .color(Color::Muted)
1462 .mr_1(),
1463 )
1464 };
1465
1466 h_flex()
1467 .p_1()
1468 .justify_between()
1469 .when(self.plan_expanded, |this| {
1470 this.border_b_1().border_color(cx.theme().colors().border)
1471 })
1472 .child(
1473 h_flex()
1474 .id("plan_summary")
1475 .w_full()
1476 .gap_1()
1477 .child(Disclosure::new("plan_disclosure", self.plan_expanded))
1478 .child(title)
1479 .on_click(cx.listener(|this, _, _, cx| {
1480 this.plan_expanded = !this.plan_expanded;
1481 cx.notify();
1482 })),
1483 )
1484 }
1485
1486 fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
1487 v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
1488 let element = h_flex()
1489 .py_1()
1490 .px_2()
1491 .gap_2()
1492 .justify_between()
1493 .bg(cx.theme().colors().editor_background)
1494 .when(index < plan.entries.len() - 1, |parent| {
1495 parent.border_color(cx.theme().colors().border).border_b_1()
1496 })
1497 .child(
1498 h_flex()
1499 .id(("plan_entry", index))
1500 .gap_1p5()
1501 .max_w_full()
1502 .overflow_x_scroll()
1503 .text_xs()
1504 .text_color(cx.theme().colors().text_muted)
1505 .child(match entry.status {
1506 acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
1507 .size(IconSize::Small)
1508 .color(Color::Muted)
1509 .into_any_element(),
1510 acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
1511 .size(IconSize::Small)
1512 .color(Color::Accent)
1513 .with_animation(
1514 "running",
1515 Animation::new(Duration::from_secs(2)).repeat(),
1516 |icon, delta| {
1517 icon.transform(Transformation::rotate(percentage(delta)))
1518 },
1519 )
1520 .into_any_element(),
1521 acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
1522 .size(IconSize::Small)
1523 .color(Color::Success)
1524 .into_any_element(),
1525 })
1526 .child(MarkdownElement::new(
1527 entry.content.clone(),
1528 plan_label_markdown_style(&entry.status, window, cx),
1529 )),
1530 );
1531
1532 Some(element)
1533 }))
1534 }
1535
1536 fn render_edits_summary(
1537 &self,
1538 action_log: &Entity<ActionLog>,
1539 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
1540 expanded: bool,
1541 pending_edits: bool,
1542 window: &mut Window,
1543 cx: &Context<Self>,
1544 ) -> Div {
1545 const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
1546
1547 let focus_handle = self.focus_handle(cx);
1548
1549 h_flex()
1550 .p_1()
1551 .justify_between()
1552 .when(expanded, |this| {
1553 this.border_b_1().border_color(cx.theme().colors().border)
1554 })
1555 .child(
1556 h_flex()
1557 .id("edits-container")
1558 .cursor_pointer()
1559 .w_full()
1560 .gap_1()
1561 .child(Disclosure::new("edits-disclosure", expanded))
1562 .map(|this| {
1563 if pending_edits {
1564 this.child(
1565 Label::new(format!(
1566 "Editing {} {}…",
1567 changed_buffers.len(),
1568 if changed_buffers.len() == 1 {
1569 "file"
1570 } else {
1571 "files"
1572 }
1573 ))
1574 .color(Color::Muted)
1575 .size(LabelSize::Small)
1576 .with_animation(
1577 "edit-label",
1578 Animation::new(Duration::from_secs(2))
1579 .repeat()
1580 .with_easing(pulsating_between(0.3, 0.7)),
1581 |label, delta| label.alpha(delta),
1582 ),
1583 )
1584 } else {
1585 this.child(
1586 Label::new("Edits")
1587 .size(LabelSize::Small)
1588 .color(Color::Muted),
1589 )
1590 .child(Label::new("•").size(LabelSize::XSmall).color(Color::Muted))
1591 .child(
1592 Label::new(format!(
1593 "{} {}",
1594 changed_buffers.len(),
1595 if changed_buffers.len() == 1 {
1596 "file"
1597 } else {
1598 "files"
1599 }
1600 ))
1601 .size(LabelSize::Small)
1602 .color(Color::Muted),
1603 )
1604 }
1605 })
1606 .on_click(cx.listener(|this, _, _, cx| {
1607 this.edits_expanded = !this.edits_expanded;
1608 cx.notify();
1609 })),
1610 )
1611 .child(
1612 h_flex()
1613 .gap_1()
1614 .child(
1615 IconButton::new("review-changes", IconName::ListTodo)
1616 .icon_size(IconSize::Small)
1617 .tooltip({
1618 let focus_handle = focus_handle.clone();
1619 move |window, cx| {
1620 Tooltip::for_action_in(
1621 "Review Changes",
1622 &OpenAgentDiff,
1623 &focus_handle,
1624 window,
1625 cx,
1626 )
1627 }
1628 })
1629 .on_click(cx.listener(|_, _, window, cx| {
1630 window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
1631 })),
1632 )
1633 .child(Divider::vertical().color(DividerColor::Border))
1634 .child(
1635 Button::new("reject-all-changes", "Reject All")
1636 .label_size(LabelSize::Small)
1637 .disabled(pending_edits)
1638 .when(pending_edits, |this| {
1639 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
1640 })
1641 .key_binding(
1642 KeyBinding::for_action_in(
1643 &RejectAll,
1644 &focus_handle.clone(),
1645 window,
1646 cx,
1647 )
1648 .map(|kb| kb.size(rems_from_px(10.))),
1649 )
1650 .on_click({
1651 let action_log = action_log.clone();
1652 cx.listener(move |_, _, _, cx| {
1653 action_log.update(cx, |action_log, cx| {
1654 action_log.reject_all_edits(cx).detach();
1655 })
1656 })
1657 }),
1658 )
1659 .child(
1660 Button::new("keep-all-changes", "Keep All")
1661 .label_size(LabelSize::Small)
1662 .disabled(pending_edits)
1663 .when(pending_edits, |this| {
1664 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
1665 })
1666 .key_binding(
1667 KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
1668 .map(|kb| kb.size(rems_from_px(10.))),
1669 )
1670 .on_click({
1671 let action_log = action_log.clone();
1672 cx.listener(move |_, _, _, cx| {
1673 action_log.update(cx, |action_log, cx| {
1674 action_log.keep_all_edits(cx);
1675 })
1676 })
1677 }),
1678 ),
1679 )
1680 }
1681
1682 fn render_edited_files(
1683 &self,
1684 action_log: &Entity<ActionLog>,
1685 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
1686 pending_edits: bool,
1687 cx: &Context<Self>,
1688 ) -> Div {
1689 let editor_bg_color = cx.theme().colors().editor_background;
1690
1691 v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
1692 |(index, (buffer, _diff))| {
1693 let file = buffer.read(cx).file()?;
1694 let path = file.path();
1695
1696 let file_path = path.parent().and_then(|parent| {
1697 let parent_str = parent.to_string_lossy();
1698
1699 if parent_str.is_empty() {
1700 None
1701 } else {
1702 Some(
1703 Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
1704 .color(Color::Muted)
1705 .size(LabelSize::XSmall)
1706 .buffer_font(cx),
1707 )
1708 }
1709 });
1710
1711 let file_name = path.file_name().map(|name| {
1712 Label::new(name.to_string_lossy().to_string())
1713 .size(LabelSize::XSmall)
1714 .buffer_font(cx)
1715 });
1716
1717 let file_icon = FileIcons::get_icon(&path, cx)
1718 .map(Icon::from_path)
1719 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
1720 .unwrap_or_else(|| {
1721 Icon::new(IconName::File)
1722 .color(Color::Muted)
1723 .size(IconSize::Small)
1724 });
1725
1726 let overlay_gradient = linear_gradient(
1727 90.,
1728 linear_color_stop(editor_bg_color, 1.),
1729 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
1730 );
1731
1732 let element = h_flex()
1733 .group("edited-code")
1734 .id(("file-container", index))
1735 .relative()
1736 .py_1()
1737 .pl_2()
1738 .pr_1()
1739 .gap_2()
1740 .justify_between()
1741 .bg(editor_bg_color)
1742 .when(index < changed_buffers.len() - 1, |parent| {
1743 parent.border_color(cx.theme().colors().border).border_b_1()
1744 })
1745 .child(
1746 h_flex()
1747 .id(("file-name", index))
1748 .pr_8()
1749 .gap_1p5()
1750 .max_w_full()
1751 .overflow_x_scroll()
1752 .child(file_icon)
1753 .child(h_flex().gap_0p5().children(file_name).children(file_path))
1754 .on_click({
1755 let buffer = buffer.clone();
1756 cx.listener(move |this, _, window, cx| {
1757 this.open_edited_buffer(&buffer, window, cx);
1758 })
1759 }),
1760 )
1761 .child(
1762 h_flex()
1763 .gap_1()
1764 .visible_on_hover("edited-code")
1765 .child(
1766 Button::new("review", "Review")
1767 .label_size(LabelSize::Small)
1768 .on_click({
1769 let buffer = buffer.clone();
1770 cx.listener(move |this, _, window, cx| {
1771 this.open_edited_buffer(&buffer, window, cx);
1772 })
1773 }),
1774 )
1775 .child(Divider::vertical().color(DividerColor::BorderVariant))
1776 .child(
1777 Button::new("reject-file", "Reject")
1778 .label_size(LabelSize::Small)
1779 .disabled(pending_edits)
1780 .on_click({
1781 let buffer = buffer.clone();
1782 let action_log = action_log.clone();
1783 move |_, _, cx| {
1784 action_log.update(cx, |action_log, cx| {
1785 action_log
1786 .reject_edits_in_ranges(
1787 buffer.clone(),
1788 vec![Anchor::MIN..Anchor::MAX],
1789 cx,
1790 )
1791 .detach_and_log_err(cx);
1792 })
1793 }
1794 }),
1795 )
1796 .child(
1797 Button::new("keep-file", "Keep")
1798 .label_size(LabelSize::Small)
1799 .disabled(pending_edits)
1800 .on_click({
1801 let buffer = buffer.clone();
1802 let action_log = action_log.clone();
1803 move |_, _, cx| {
1804 action_log.update(cx, |action_log, cx| {
1805 action_log.keep_edits_in_range(
1806 buffer.clone(),
1807 Anchor::MIN..Anchor::MAX,
1808 cx,
1809 );
1810 })
1811 }
1812 }),
1813 ),
1814 )
1815 .child(
1816 div()
1817 .id("gradient-overlay")
1818 .absolute()
1819 .h_full()
1820 .w_12()
1821 .top_0()
1822 .bottom_0()
1823 .right(px(152.))
1824 .bg(overlay_gradient),
1825 );
1826
1827 Some(element)
1828 },
1829 ))
1830 }
1831
1832 fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
1833 let focus_handle = self.message_editor.focus_handle(cx);
1834 let editor_bg_color = cx.theme().colors().editor_background;
1835 let (expand_icon, expand_tooltip) = if self.editor_expanded {
1836 (IconName::Minimize, "Minimize Message Editor")
1837 } else {
1838 (IconName::Maximize, "Expand Message Editor")
1839 };
1840
1841 v_flex()
1842 .on_action(cx.listener(Self::expand_message_editor))
1843 .p_2()
1844 .gap_2()
1845 .border_t_1()
1846 .border_color(cx.theme().colors().border)
1847 .bg(editor_bg_color)
1848 .when(self.editor_expanded, |this| {
1849 this.h(vh(0.8, window)).size_full().justify_between()
1850 })
1851 .child(
1852 v_flex()
1853 .relative()
1854 .size_full()
1855 .pt_1()
1856 .pr_2p5()
1857 .child(div().flex_1().child({
1858 let settings = ThemeSettings::get_global(cx);
1859 let font_size = TextSize::Small
1860 .rems(cx)
1861 .to_pixels(settings.agent_font_size(cx));
1862 let line_height = settings.buffer_line_height.value() * font_size;
1863
1864 let text_style = TextStyle {
1865 color: cx.theme().colors().text,
1866 font_family: settings.buffer_font.family.clone(),
1867 font_fallbacks: settings.buffer_font.fallbacks.clone(),
1868 font_features: settings.buffer_font.features.clone(),
1869 font_size: font_size.into(),
1870 line_height: line_height.into(),
1871 ..Default::default()
1872 };
1873
1874 EditorElement::new(
1875 &self.message_editor,
1876 EditorStyle {
1877 background: editor_bg_color,
1878 local_player: cx.theme().players().local(),
1879 text: text_style,
1880 syntax: cx.theme().syntax().clone(),
1881 ..Default::default()
1882 },
1883 )
1884 }))
1885 .child(
1886 h_flex()
1887 .absolute()
1888 .top_0()
1889 .right_0()
1890 .opacity(0.5)
1891 .hover(|this| this.opacity(1.0))
1892 .child(
1893 IconButton::new("toggle-height", expand_icon)
1894 .icon_size(IconSize::XSmall)
1895 .icon_color(Color::Muted)
1896 .tooltip({
1897 let focus_handle = focus_handle.clone();
1898 move |window, cx| {
1899 Tooltip::for_action_in(
1900 expand_tooltip,
1901 &ExpandMessageEditor,
1902 &focus_handle,
1903 window,
1904 cx,
1905 )
1906 }
1907 })
1908 .on_click(cx.listener(|_, _, window, cx| {
1909 window.dispatch_action(Box::new(ExpandMessageEditor), cx);
1910 })),
1911 ),
1912 ),
1913 )
1914 .child(
1915 h_flex()
1916 .flex_none()
1917 .justify_between()
1918 .child(self.render_follow_toggle(cx))
1919 .child(self.render_send_button(cx)),
1920 )
1921 .into_any()
1922 }
1923
1924 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
1925 if self.thread().map_or(true, |thread| {
1926 thread.read(cx).status() == ThreadStatus::Idle
1927 }) {
1928 let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
1929 IconButton::new("send-message", IconName::Send)
1930 .icon_color(Color::Accent)
1931 .style(ButtonStyle::Filled)
1932 .disabled(self.thread().is_none() || is_editor_empty)
1933 .on_click(cx.listener(|this, _, window, cx| {
1934 this.chat(&Chat, window, cx);
1935 }))
1936 .when(!is_editor_empty, |button| {
1937 button.tooltip(move |window, cx| Tooltip::for_action("Send", &Chat, window, cx))
1938 })
1939 .when(is_editor_empty, |button| {
1940 button.tooltip(Tooltip::text("Type a message to submit"))
1941 })
1942 .into_any_element()
1943 } else {
1944 IconButton::new("stop-generation", IconName::StopFilled)
1945 .icon_color(Color::Error)
1946 .style(ButtonStyle::Tinted(ui::TintColor::Error))
1947 .tooltip(move |window, cx| {
1948 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
1949 })
1950 .on_click(cx.listener(|this, _event, _, cx| this.cancel(cx)))
1951 .into_any_element()
1952 }
1953 }
1954
1955 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
1956 let following = self
1957 .workspace
1958 .read_with(cx, |workspace, _| {
1959 workspace.is_being_followed(CollaboratorId::Agent)
1960 })
1961 .unwrap_or(false);
1962
1963 IconButton::new("follow-agent", IconName::Crosshair)
1964 .icon_size(IconSize::Small)
1965 .icon_color(Color::Muted)
1966 .toggle_state(following)
1967 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
1968 .tooltip(move |window, cx| {
1969 if following {
1970 Tooltip::for_action("Stop Following Agent", &Follow, window, cx)
1971 } else {
1972 Tooltip::with_meta(
1973 "Follow Agent",
1974 Some(&Follow),
1975 "Track the agent's location as it reads and edits files.",
1976 window,
1977 cx,
1978 )
1979 }
1980 })
1981 .on_click(cx.listener(move |this, _, window, cx| {
1982 this.workspace
1983 .update(cx, |workspace, cx| {
1984 if following {
1985 workspace.unfollow(CollaboratorId::Agent, window, cx);
1986 } else {
1987 workspace.follow(CollaboratorId::Agent, window, cx);
1988 }
1989 })
1990 .ok();
1991 }))
1992 }
1993
1994 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
1995 let workspace = self.workspace.clone();
1996 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
1997 Self::open_link(text, &workspace, window, cx);
1998 })
1999 }
2000
2001 fn open_link(
2002 url: SharedString,
2003 workspace: &WeakEntity<Workspace>,
2004 window: &mut Window,
2005 cx: &mut App,
2006 ) {
2007 let Some(workspace) = workspace.upgrade() else {
2008 cx.open_url(&url);
2009 return;
2010 };
2011
2012 if let Some(mention_path) = MentionPath::try_parse(&url) {
2013 workspace.update(cx, |workspace, cx| {
2014 let project = workspace.project();
2015 let Some((path, entry)) = project.update(cx, |project, cx| {
2016 let path = project.find_project_path(mention_path.path(), cx)?;
2017 let entry = project.entry_for_path(&path, cx)?;
2018 Some((path, entry))
2019 }) else {
2020 return;
2021 };
2022
2023 if entry.is_dir() {
2024 project.update(cx, |_, cx| {
2025 cx.emit(project::Event::RevealInProjectPanel(entry.id));
2026 });
2027 } else {
2028 workspace
2029 .open_path(path, None, true, window, cx)
2030 .detach_and_log_err(cx);
2031 }
2032 })
2033 } else {
2034 cx.open_url(&url);
2035 }
2036 }
2037
2038 fn open_tool_call_location(
2039 &self,
2040 entry_ix: usize,
2041 location_ix: usize,
2042 window: &mut Window,
2043 cx: &mut Context<Self>,
2044 ) -> Option<()> {
2045 let location = self
2046 .thread()?
2047 .read(cx)
2048 .entries()
2049 .get(entry_ix)?
2050 .locations()?
2051 .get(location_ix)?;
2052
2053 let project_path = self
2054 .project
2055 .read(cx)
2056 .find_project_path(&location.path, cx)?;
2057
2058 let open_task = self
2059 .workspace
2060 .update(cx, |worskpace, cx| {
2061 worskpace.open_path(project_path, None, true, window, cx)
2062 })
2063 .log_err()?;
2064
2065 window
2066 .spawn(cx, async move |cx| {
2067 let item = open_task.await?;
2068
2069 let Some(active_editor) = item.downcast::<Editor>() else {
2070 return anyhow::Ok(());
2071 };
2072
2073 active_editor.update_in(cx, |editor, window, cx| {
2074 let snapshot = editor.buffer().read(cx).snapshot(cx);
2075 let first_hunk = editor
2076 .diff_hunks_in_ranges(
2077 &[editor::Anchor::min()..editor::Anchor::max()],
2078 &snapshot,
2079 )
2080 .next();
2081 if let Some(first_hunk) = first_hunk {
2082 let first_hunk_start = first_hunk.multi_buffer_range().start;
2083 editor.change_selections(Default::default(), window, cx, |selections| {
2084 selections.select_anchor_ranges([first_hunk_start..first_hunk_start]);
2085 })
2086 }
2087 })?;
2088
2089 anyhow::Ok(())
2090 })
2091 .detach_and_log_err(cx);
2092
2093 None
2094 }
2095
2096 pub fn open_thread_as_markdown(
2097 &self,
2098 workspace: Entity<Workspace>,
2099 window: &mut Window,
2100 cx: &mut App,
2101 ) -> Task<anyhow::Result<()>> {
2102 let markdown_language_task = workspace
2103 .read(cx)
2104 .app_state()
2105 .languages
2106 .language_for_name("Markdown");
2107
2108 let (thread_summary, markdown) = if let Some(thread) = self.thread() {
2109 let thread = thread.read(cx);
2110 (thread.title().to_string(), thread.to_markdown(cx))
2111 } else {
2112 return Task::ready(Ok(()));
2113 };
2114
2115 window.spawn(cx, async move |cx| {
2116 let markdown_language = markdown_language_task.await?;
2117
2118 workspace.update_in(cx, |workspace, window, cx| {
2119 let project = workspace.project().clone();
2120
2121 if !project.read(cx).is_local() {
2122 anyhow::bail!("failed to open active thread as markdown in remote project");
2123 }
2124
2125 let buffer = project.update(cx, |project, cx| {
2126 project.create_local_buffer(&markdown, Some(markdown_language), cx)
2127 });
2128 let buffer = cx.new(|cx| {
2129 MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
2130 });
2131
2132 workspace.add_item_to_active_pane(
2133 Box::new(cx.new(|cx| {
2134 let mut editor =
2135 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
2136 editor.set_breadcrumb_header(thread_summary);
2137 editor
2138 })),
2139 None,
2140 true,
2141 window,
2142 cx,
2143 );
2144
2145 anyhow::Ok(())
2146 })??;
2147 anyhow::Ok(())
2148 })
2149 }
2150
2151 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
2152 self.list_state.scroll_to(ListOffset::default());
2153 cx.notify();
2154 }
2155}
2156
2157impl Focusable for AcpThreadView {
2158 fn focus_handle(&self, cx: &App) -> FocusHandle {
2159 self.message_editor.focus_handle(cx)
2160 }
2161}
2162
2163impl Render for AcpThreadView {
2164 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2165 let open_as_markdown = IconButton::new("open-as-markdown", IconName::DocumentText)
2166 .icon_size(IconSize::XSmall)
2167 .icon_color(Color::Ignored)
2168 .tooltip(Tooltip::text("Open Thread as Markdown"))
2169 .on_click(cx.listener(move |this, _, window, cx| {
2170 if let Some(workspace) = this.workspace.upgrade() {
2171 this.open_thread_as_markdown(workspace, window, cx)
2172 .detach_and_log_err(cx);
2173 }
2174 }));
2175
2176 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUpAlt)
2177 .icon_size(IconSize::XSmall)
2178 .icon_color(Color::Ignored)
2179 .tooltip(Tooltip::text("Scroll To Top"))
2180 .on_click(cx.listener(move |this, _, _, cx| {
2181 this.scroll_to_top(cx);
2182 }));
2183
2184 v_flex()
2185 .size_full()
2186 .key_context("AcpThread")
2187 .on_action(cx.listener(Self::chat))
2188 .on_action(cx.listener(Self::previous_history_message))
2189 .on_action(cx.listener(Self::next_history_message))
2190 .on_action(cx.listener(Self::open_agent_diff))
2191 .child(match &self.thread_state {
2192 ThreadState::Unauthenticated { .. } => {
2193 v_flex()
2194 .p_2()
2195 .flex_1()
2196 .items_center()
2197 .justify_center()
2198 .child(self.render_pending_auth_state())
2199 .child(
2200 h_flex().mt_1p5().justify_center().child(
2201 Button::new("sign-in", format!("Sign in to {}", self.agent.name()))
2202 .on_click(cx.listener(|this, _, window, cx| {
2203 this.authenticate(window, cx)
2204 })),
2205 ),
2206 )
2207 }
2208 ThreadState::Loading { .. } => v_flex().flex_1().child(self.render_empty_state(cx)),
2209 ThreadState::LoadError(e) => v_flex()
2210 .p_2()
2211 .flex_1()
2212 .items_center()
2213 .justify_center()
2214 .child(self.render_error_state(e, cx)),
2215 ThreadState::Ready { thread, .. } => v_flex().flex_1().map(|this| {
2216 if self.list_state.item_count() > 0 {
2217 this.child(
2218 list(self.list_state.clone())
2219 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
2220 .flex_grow()
2221 .into_any(),
2222 )
2223 .child(
2224 h_flex()
2225 .group("controls")
2226 .mt_1()
2227 .mr_1()
2228 .py_2()
2229 .px(RESPONSE_PADDING_X)
2230 .opacity(0.4)
2231 .hover(|style| style.opacity(1.))
2232 .flex_wrap()
2233 .justify_end()
2234 .child(open_as_markdown)
2235 .child(scroll_to_top)
2236 .into_any_element(),
2237 )
2238 .children(match thread.read(cx).status() {
2239 ThreadStatus::Idle | ThreadStatus::WaitingForToolConfirmation => None,
2240 ThreadStatus::Generating => div()
2241 .px_5()
2242 .py_2()
2243 .child(LoadingLabel::new("").size(LabelSize::Small))
2244 .into(),
2245 })
2246 .children(self.render_activity_bar(&thread, window, cx))
2247 } else {
2248 this.child(self.render_empty_state(cx))
2249 }
2250 }),
2251 })
2252 .when_some(self.last_error.clone(), |el, error| {
2253 el.child(
2254 div()
2255 .p_2()
2256 .text_xs()
2257 .border_t_1()
2258 .border_color(cx.theme().colors().border)
2259 .bg(cx.theme().status().error_background)
2260 .child(
2261 self.render_markdown(error, default_markdown_style(false, window, cx)),
2262 ),
2263 )
2264 })
2265 .child(self.render_message_editor(window, cx))
2266 }
2267}
2268
2269fn user_message_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
2270 let mut style = default_markdown_style(false, window, cx);
2271 let mut text_style = window.text_style();
2272 let theme_settings = ThemeSettings::get_global(cx);
2273
2274 let buffer_font = theme_settings.buffer_font.family.clone();
2275 let buffer_font_size = TextSize::Small.rems(cx);
2276
2277 text_style.refine(&TextStyleRefinement {
2278 font_family: Some(buffer_font),
2279 font_size: Some(buffer_font_size.into()),
2280 ..Default::default()
2281 });
2282
2283 style.base_text_style = text_style;
2284 style.link_callback = Some(Rc::new(move |url, cx| {
2285 if MentionPath::try_parse(url).is_some() {
2286 let colors = cx.theme().colors();
2287 Some(TextStyleRefinement {
2288 background_color: Some(colors.element_background),
2289 ..Default::default()
2290 })
2291 } else {
2292 None
2293 }
2294 }));
2295 style
2296}
2297
2298fn default_markdown_style(buffer_font: bool, window: &Window, cx: &App) -> MarkdownStyle {
2299 let theme_settings = ThemeSettings::get_global(cx);
2300 let colors = cx.theme().colors();
2301
2302 let buffer_font_size = TextSize::Small.rems(cx);
2303
2304 let mut text_style = window.text_style();
2305 let line_height = buffer_font_size * 1.75;
2306
2307 let font_family = if buffer_font {
2308 theme_settings.buffer_font.family.clone()
2309 } else {
2310 theme_settings.ui_font.family.clone()
2311 };
2312
2313 let font_size = if buffer_font {
2314 TextSize::Small.rems(cx)
2315 } else {
2316 TextSize::Default.rems(cx)
2317 };
2318
2319 text_style.refine(&TextStyleRefinement {
2320 font_family: Some(font_family),
2321 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
2322 font_features: Some(theme_settings.ui_font.features.clone()),
2323 font_size: Some(font_size.into()),
2324 line_height: Some(line_height.into()),
2325 color: Some(cx.theme().colors().text),
2326 ..Default::default()
2327 });
2328
2329 MarkdownStyle {
2330 base_text_style: text_style.clone(),
2331 syntax: cx.theme().syntax().clone(),
2332 selection_background_color: cx.theme().colors().element_selection_background,
2333 code_block_overflow_x_scroll: true,
2334 table_overflow_x_scroll: true,
2335 heading_level_styles: Some(HeadingLevelStyles {
2336 h1: Some(TextStyleRefinement {
2337 font_size: Some(rems(1.15).into()),
2338 ..Default::default()
2339 }),
2340 h2: Some(TextStyleRefinement {
2341 font_size: Some(rems(1.1).into()),
2342 ..Default::default()
2343 }),
2344 h3: Some(TextStyleRefinement {
2345 font_size: Some(rems(1.05).into()),
2346 ..Default::default()
2347 }),
2348 h4: Some(TextStyleRefinement {
2349 font_size: Some(rems(1.).into()),
2350 ..Default::default()
2351 }),
2352 h5: Some(TextStyleRefinement {
2353 font_size: Some(rems(0.95).into()),
2354 ..Default::default()
2355 }),
2356 h6: Some(TextStyleRefinement {
2357 font_size: Some(rems(0.875).into()),
2358 ..Default::default()
2359 }),
2360 }),
2361 code_block: StyleRefinement {
2362 padding: EdgesRefinement {
2363 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2364 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2365 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2366 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2367 },
2368 margin: EdgesRefinement {
2369 top: Some(Length::Definite(Pixels(8.).into())),
2370 left: Some(Length::Definite(Pixels(0.).into())),
2371 right: Some(Length::Definite(Pixels(0.).into())),
2372 bottom: Some(Length::Definite(Pixels(12.).into())),
2373 },
2374 border_style: Some(BorderStyle::Solid),
2375 border_widths: EdgesRefinement {
2376 top: Some(AbsoluteLength::Pixels(Pixels(1.))),
2377 left: Some(AbsoluteLength::Pixels(Pixels(1.))),
2378 right: Some(AbsoluteLength::Pixels(Pixels(1.))),
2379 bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
2380 },
2381 border_color: Some(colors.border_variant),
2382 background: Some(colors.editor_background.into()),
2383 text: Some(TextStyleRefinement {
2384 font_family: Some(theme_settings.buffer_font.family.clone()),
2385 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
2386 font_features: Some(theme_settings.buffer_font.features.clone()),
2387 font_size: Some(buffer_font_size.into()),
2388 ..Default::default()
2389 }),
2390 ..Default::default()
2391 },
2392 inline_code: TextStyleRefinement {
2393 font_family: Some(theme_settings.buffer_font.family.clone()),
2394 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
2395 font_features: Some(theme_settings.buffer_font.features.clone()),
2396 font_size: Some(buffer_font_size.into()),
2397 background_color: Some(colors.editor_foreground.opacity(0.08)),
2398 ..Default::default()
2399 },
2400 link: TextStyleRefinement {
2401 background_color: Some(colors.editor_foreground.opacity(0.025)),
2402 underline: Some(UnderlineStyle {
2403 color: Some(colors.text_accent.opacity(0.5)),
2404 thickness: px(1.),
2405 ..Default::default()
2406 }),
2407 ..Default::default()
2408 },
2409 ..Default::default()
2410 }
2411}
2412
2413fn plan_label_markdown_style(
2414 status: &acp::PlanEntryStatus,
2415 window: &Window,
2416 cx: &App,
2417) -> MarkdownStyle {
2418 let default_md_style = default_markdown_style(false, window, cx);
2419
2420 MarkdownStyle {
2421 base_text_style: TextStyle {
2422 color: cx.theme().colors().text_muted,
2423 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
2424 Some(gpui::StrikethroughStyle {
2425 thickness: px(1.),
2426 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
2427 })
2428 } else {
2429 None
2430 },
2431 ..default_md_style.base_text_style
2432 },
2433 ..default_md_style
2434 }
2435}