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