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