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