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