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 fn as_native_connection(&self, cx: &App) -> Option<Rc<agent2::NativeAgentConnection>> {
2448 let acp_thread = self.thread()?.read(cx);
2449 acp_thread.connection().clone().downcast()
2450 }
2451
2452 fn as_native_thread(&self, cx: &App) -> Option<Entity<agent2::Thread>> {
2453 let acp_thread = self.thread()?.read(cx);
2454 self.as_native_connection(cx)?
2455 .thread(acp_thread.session_id(), cx)
2456 }
2457
2458 fn toggle_burn_mode(
2459 &mut self,
2460 _: &ToggleBurnMode,
2461 _window: &mut Window,
2462 cx: &mut Context<Self>,
2463 ) {
2464 let Some(thread) = self.as_native_thread(cx) else {
2465 return;
2466 };
2467
2468 thread.update(cx, |thread, _cx| {
2469 let current_mode = thread.completion_mode();
2470 thread.set_completion_mode(match current_mode {
2471 CompletionMode::Burn => CompletionMode::Normal,
2472 CompletionMode::Normal => CompletionMode::Burn,
2473 });
2474 });
2475 }
2476
2477 fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2478 let thread = self.as_native_thread(cx)?.read(cx);
2479
2480 if thread
2481 .model()
2482 .map_or(true, |model| !model.supports_burn_mode())
2483 {
2484 return None;
2485 }
2486
2487 let active_completion_mode = thread.completion_mode();
2488 let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
2489 let icon = if burn_mode_enabled {
2490 IconName::ZedBurnModeOn
2491 } else {
2492 IconName::ZedBurnMode
2493 };
2494
2495 Some(
2496 IconButton::new("burn-mode", icon)
2497 .icon_size(IconSize::Small)
2498 .icon_color(Color::Muted)
2499 .toggle_state(burn_mode_enabled)
2500 .selected_icon_color(Color::Error)
2501 .on_click(cx.listener(|this, _event, window, cx| {
2502 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
2503 }))
2504 .tooltip(move |_window, cx| {
2505 cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
2506 .into()
2507 })
2508 .into_any_element(),
2509 )
2510 }
2511
2512 fn render_sent_message_editor(
2513 &self,
2514 entry_ix: usize,
2515 editor: &Entity<MessageEditor>,
2516 cx: &Context<Self>,
2517 ) -> Div {
2518 v_flex().w_full().gap_2().child(editor.clone()).when(
2519 self.editing_message == Some(entry_ix),
2520 |el| {
2521 el.child(
2522 h_flex()
2523 .gap_1()
2524 .child(
2525 Icon::new(IconName::Warning)
2526 .color(Color::Warning)
2527 .size(IconSize::XSmall),
2528 )
2529 .child(
2530 Label::new("Editing will restart the thread from this point.")
2531 .color(Color::Muted)
2532 .size(LabelSize::XSmall),
2533 )
2534 .child(self.render_sent_message_editor_buttons(entry_ix, editor, cx)),
2535 )
2536 },
2537 )
2538 }
2539
2540 fn render_sent_message_editor_buttons(
2541 &self,
2542 entry_ix: usize,
2543 editor: &Entity<MessageEditor>,
2544 cx: &Context<Self>,
2545 ) -> Div {
2546 h_flex()
2547 .gap_0p5()
2548 .flex_1()
2549 .justify_end()
2550 .child(
2551 IconButton::new("cancel-edit-message", IconName::Close)
2552 .shape(ui::IconButtonShape::Square)
2553 .icon_color(Color::Error)
2554 .icon_size(IconSize::Small)
2555 .tooltip({
2556 let focus_handle = editor.focus_handle(cx);
2557 move |window, cx| {
2558 Tooltip::for_action_in(
2559 "Cancel Edit",
2560 &menu::Cancel,
2561 &focus_handle,
2562 window,
2563 cx,
2564 )
2565 }
2566 })
2567 .on_click(cx.listener(Self::cancel_editing)),
2568 )
2569 .child(
2570 IconButton::new("confirm-edit-message", IconName::Return)
2571 .disabled(editor.read(cx).is_empty(cx))
2572 .shape(ui::IconButtonShape::Square)
2573 .icon_color(Color::Muted)
2574 .icon_size(IconSize::Small)
2575 .tooltip({
2576 let focus_handle = editor.focus_handle(cx);
2577 move |window, cx| {
2578 Tooltip::for_action_in(
2579 "Regenerate",
2580 &menu::Confirm,
2581 &focus_handle,
2582 window,
2583 cx,
2584 )
2585 }
2586 })
2587 .on_click(cx.listener({
2588 let editor = editor.clone();
2589 move |this, _, window, cx| {
2590 this.regenerate(entry_ix, &editor, window, cx);
2591 }
2592 })),
2593 )
2594 }
2595
2596 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
2597 if self.thread().map_or(true, |thread| {
2598 thread.read(cx).status() == ThreadStatus::Idle
2599 }) {
2600 let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
2601 IconButton::new("send-message", IconName::Send)
2602 .icon_color(Color::Accent)
2603 .style(ButtonStyle::Filled)
2604 .disabled(self.thread().is_none() || is_editor_empty)
2605 .when(!is_editor_empty, |button| {
2606 button.tooltip(move |window, cx| Tooltip::for_action("Send", &Chat, window, cx))
2607 })
2608 .when(is_editor_empty, |button| {
2609 button.tooltip(Tooltip::text("Type a message to submit"))
2610 })
2611 .on_click(cx.listener(|this, _, window, cx| {
2612 this.send(window, cx);
2613 }))
2614 .into_any_element()
2615 } else {
2616 IconButton::new("stop-generation", IconName::Stop)
2617 .icon_color(Color::Error)
2618 .style(ButtonStyle::Tinted(ui::TintColor::Error))
2619 .tooltip(move |window, cx| {
2620 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
2621 })
2622 .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
2623 .into_any_element()
2624 }
2625 }
2626
2627 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
2628 let following = self
2629 .workspace
2630 .read_with(cx, |workspace, _| {
2631 workspace.is_being_followed(CollaboratorId::Agent)
2632 })
2633 .unwrap_or(false);
2634
2635 IconButton::new("follow-agent", IconName::Crosshair)
2636 .icon_size(IconSize::Small)
2637 .icon_color(Color::Muted)
2638 .toggle_state(following)
2639 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
2640 .tooltip(move |window, cx| {
2641 if following {
2642 Tooltip::for_action("Stop Following Agent", &Follow, window, cx)
2643 } else {
2644 Tooltip::with_meta(
2645 "Follow Agent",
2646 Some(&Follow),
2647 "Track the agent's location as it reads and edits files.",
2648 window,
2649 cx,
2650 )
2651 }
2652 })
2653 .on_click(cx.listener(move |this, _, window, cx| {
2654 this.workspace
2655 .update(cx, |workspace, cx| {
2656 if following {
2657 workspace.unfollow(CollaboratorId::Agent, window, cx);
2658 } else {
2659 workspace.follow(CollaboratorId::Agent, window, cx);
2660 }
2661 })
2662 .ok();
2663 }))
2664 }
2665
2666 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
2667 let workspace = self.workspace.clone();
2668 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
2669 Self::open_link(text, &workspace, window, cx);
2670 })
2671 }
2672
2673 fn open_link(
2674 url: SharedString,
2675 workspace: &WeakEntity<Workspace>,
2676 window: &mut Window,
2677 cx: &mut App,
2678 ) {
2679 let Some(workspace) = workspace.upgrade() else {
2680 cx.open_url(&url);
2681 return;
2682 };
2683
2684 if let Some(mention) = MentionUri::parse(&url).log_err() {
2685 workspace.update(cx, |workspace, cx| match mention {
2686 MentionUri::File { abs_path, .. } => {
2687 let project = workspace.project();
2688 let Some((path, entry)) = project.update(cx, |project, cx| {
2689 let path = project.find_project_path(abs_path, cx)?;
2690 let entry = project.entry_for_path(&path, cx)?;
2691 Some((path, entry))
2692 }) else {
2693 return;
2694 };
2695
2696 if entry.is_dir() {
2697 project.update(cx, |_, cx| {
2698 cx.emit(project::Event::RevealInProjectPanel(entry.id));
2699 });
2700 } else {
2701 workspace
2702 .open_path(path, None, true, window, cx)
2703 .detach_and_log_err(cx);
2704 }
2705 }
2706 MentionUri::Symbol {
2707 path, line_range, ..
2708 }
2709 | MentionUri::Selection { path, line_range } => {
2710 let project = workspace.project();
2711 let Some((path, _)) = project.update(cx, |project, cx| {
2712 let path = project.find_project_path(path, cx)?;
2713 let entry = project.entry_for_path(&path, cx)?;
2714 Some((path, entry))
2715 }) else {
2716 return;
2717 };
2718
2719 let item = workspace.open_path(path, None, true, window, cx);
2720 window
2721 .spawn(cx, async move |cx| {
2722 let Some(editor) = item.await?.downcast::<Editor>() else {
2723 return Ok(());
2724 };
2725 let range =
2726 Point::new(line_range.start, 0)..Point::new(line_range.start, 0);
2727 editor
2728 .update_in(cx, |editor, window, cx| {
2729 editor.change_selections(
2730 SelectionEffects::scroll(Autoscroll::center()),
2731 window,
2732 cx,
2733 |s| s.select_ranges(vec![range]),
2734 );
2735 })
2736 .ok();
2737 anyhow::Ok(())
2738 })
2739 .detach_and_log_err(cx);
2740 }
2741 MentionUri::Thread { id, .. } => {
2742 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
2743 panel.update(cx, |panel, cx| {
2744 panel
2745 .open_thread_by_id(&id, window, cx)
2746 .detach_and_log_err(cx)
2747 });
2748 }
2749 }
2750 MentionUri::TextThread { path, .. } => {
2751 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
2752 panel.update(cx, |panel, cx| {
2753 panel
2754 .open_saved_prompt_editor(path.as_path().into(), window, cx)
2755 .detach_and_log_err(cx);
2756 });
2757 }
2758 }
2759 MentionUri::Rule { id, .. } => {
2760 let PromptId::User { uuid } = id else {
2761 return;
2762 };
2763 window.dispatch_action(
2764 Box::new(OpenRulesLibrary {
2765 prompt_to_select: Some(uuid.0),
2766 }),
2767 cx,
2768 )
2769 }
2770 MentionUri::Fetch { url } => {
2771 cx.open_url(url.as_str());
2772 }
2773 })
2774 } else {
2775 cx.open_url(&url);
2776 }
2777 }
2778
2779 fn open_tool_call_location(
2780 &self,
2781 entry_ix: usize,
2782 location_ix: usize,
2783 window: &mut Window,
2784 cx: &mut Context<Self>,
2785 ) -> Option<()> {
2786 let (tool_call_location, agent_location) = self
2787 .thread()?
2788 .read(cx)
2789 .entries()
2790 .get(entry_ix)?
2791 .location(location_ix)?;
2792
2793 let project_path = self
2794 .project
2795 .read(cx)
2796 .find_project_path(&tool_call_location.path, cx)?;
2797
2798 let open_task = self
2799 .workspace
2800 .update(cx, |workspace, cx| {
2801 workspace.open_path(project_path, None, true, window, cx)
2802 })
2803 .log_err()?;
2804 window
2805 .spawn(cx, async move |cx| {
2806 let item = open_task.await?;
2807
2808 let Some(active_editor) = item.downcast::<Editor>() else {
2809 return anyhow::Ok(());
2810 };
2811
2812 active_editor.update_in(cx, |editor, window, cx| {
2813 let multibuffer = editor.buffer().read(cx);
2814 let buffer = multibuffer.as_singleton();
2815 if agent_location.buffer.upgrade() == buffer {
2816 let excerpt_id = multibuffer.excerpt_ids().first().cloned();
2817 let anchor = editor::Anchor::in_buffer(
2818 excerpt_id.unwrap(),
2819 buffer.unwrap().read(cx).remote_id(),
2820 agent_location.position,
2821 );
2822 editor.change_selections(Default::default(), window, cx, |selections| {
2823 selections.select_anchor_ranges([anchor..anchor]);
2824 })
2825 } else {
2826 let row = tool_call_location.line.unwrap_or_default();
2827 editor.change_selections(Default::default(), window, cx, |selections| {
2828 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
2829 })
2830 }
2831 })?;
2832
2833 anyhow::Ok(())
2834 })
2835 .detach_and_log_err(cx);
2836
2837 None
2838 }
2839
2840 pub fn open_thread_as_markdown(
2841 &self,
2842 workspace: Entity<Workspace>,
2843 window: &mut Window,
2844 cx: &mut App,
2845 ) -> Task<anyhow::Result<()>> {
2846 let markdown_language_task = workspace
2847 .read(cx)
2848 .app_state()
2849 .languages
2850 .language_for_name("Markdown");
2851
2852 let (thread_summary, markdown) = if let Some(thread) = self.thread() {
2853 let thread = thread.read(cx);
2854 (thread.title().to_string(), thread.to_markdown(cx))
2855 } else {
2856 return Task::ready(Ok(()));
2857 };
2858
2859 window.spawn(cx, async move |cx| {
2860 let markdown_language = markdown_language_task.await?;
2861
2862 workspace.update_in(cx, |workspace, window, cx| {
2863 let project = workspace.project().clone();
2864
2865 if !project.read(cx).is_local() {
2866 bail!("failed to open active thread as markdown in remote project");
2867 }
2868
2869 let buffer = project.update(cx, |project, cx| {
2870 project.create_local_buffer(&markdown, Some(markdown_language), cx)
2871 });
2872 let buffer = cx.new(|cx| {
2873 MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
2874 });
2875
2876 workspace.add_item_to_active_pane(
2877 Box::new(cx.new(|cx| {
2878 let mut editor =
2879 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
2880 editor.set_breadcrumb_header(thread_summary);
2881 editor
2882 })),
2883 None,
2884 true,
2885 window,
2886 cx,
2887 );
2888
2889 anyhow::Ok(())
2890 })??;
2891 anyhow::Ok(())
2892 })
2893 }
2894
2895 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
2896 self.list_state.scroll_to(ListOffset::default());
2897 cx.notify();
2898 }
2899
2900 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
2901 if let Some(thread) = self.thread() {
2902 let entry_count = thread.read(cx).entries().len();
2903 self.list_state.reset(entry_count);
2904 cx.notify();
2905 }
2906 }
2907
2908 fn notify_with_sound(
2909 &mut self,
2910 caption: impl Into<SharedString>,
2911 icon: IconName,
2912 window: &mut Window,
2913 cx: &mut Context<Self>,
2914 ) {
2915 self.play_notification_sound(window, cx);
2916 self.show_notification(caption, icon, window, cx);
2917 }
2918
2919 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
2920 let settings = AgentSettings::get_global(cx);
2921 if settings.play_sound_when_agent_done && !window.is_window_active() {
2922 Audio::play_sound(Sound::AgentDone, cx);
2923 }
2924 }
2925
2926 fn show_notification(
2927 &mut self,
2928 caption: impl Into<SharedString>,
2929 icon: IconName,
2930 window: &mut Window,
2931 cx: &mut Context<Self>,
2932 ) {
2933 if window.is_window_active() || !self.notifications.is_empty() {
2934 return;
2935 }
2936
2937 let title = self.title(cx);
2938
2939 match AgentSettings::get_global(cx).notify_when_agent_waiting {
2940 NotifyWhenAgentWaiting::PrimaryScreen => {
2941 if let Some(primary) = cx.primary_display() {
2942 self.pop_up(icon, caption.into(), title, window, primary, cx);
2943 }
2944 }
2945 NotifyWhenAgentWaiting::AllScreens => {
2946 let caption = caption.into();
2947 for screen in cx.displays() {
2948 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
2949 }
2950 }
2951 NotifyWhenAgentWaiting::Never => {
2952 // Don't show anything
2953 }
2954 }
2955 }
2956
2957 fn pop_up(
2958 &mut self,
2959 icon: IconName,
2960 caption: SharedString,
2961 title: SharedString,
2962 window: &mut Window,
2963 screen: Rc<dyn PlatformDisplay>,
2964 cx: &mut Context<Self>,
2965 ) {
2966 let options = AgentNotification::window_options(screen, cx);
2967
2968 let project_name = self.workspace.upgrade().and_then(|workspace| {
2969 workspace
2970 .read(cx)
2971 .project()
2972 .read(cx)
2973 .visible_worktrees(cx)
2974 .next()
2975 .map(|worktree| worktree.read(cx).root_name().to_string())
2976 });
2977
2978 if let Some(screen_window) = cx
2979 .open_window(options, |_, cx| {
2980 cx.new(|_| {
2981 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
2982 })
2983 })
2984 .log_err()
2985 {
2986 if let Some(pop_up) = screen_window.entity(cx).log_err() {
2987 self.notification_subscriptions
2988 .entry(screen_window)
2989 .or_insert_with(Vec::new)
2990 .push(cx.subscribe_in(&pop_up, window, {
2991 |this, _, event, window, cx| match event {
2992 AgentNotificationEvent::Accepted => {
2993 let handle = window.window_handle();
2994 cx.activate(true);
2995
2996 let workspace_handle = this.workspace.clone();
2997
2998 // If there are multiple Zed windows, activate the correct one.
2999 cx.defer(move |cx| {
3000 handle
3001 .update(cx, |_view, window, _cx| {
3002 window.activate_window();
3003
3004 if let Some(workspace) = workspace_handle.upgrade() {
3005 workspace.update(_cx, |workspace, cx| {
3006 workspace.focus_panel::<AgentPanel>(window, cx);
3007 });
3008 }
3009 })
3010 .log_err();
3011 });
3012
3013 this.dismiss_notifications(cx);
3014 }
3015 AgentNotificationEvent::Dismissed => {
3016 this.dismiss_notifications(cx);
3017 }
3018 }
3019 }));
3020
3021 self.notifications.push(screen_window);
3022
3023 // If the user manually refocuses the original window, dismiss the popup.
3024 self.notification_subscriptions
3025 .entry(screen_window)
3026 .or_insert_with(Vec::new)
3027 .push({
3028 let pop_up_weak = pop_up.downgrade();
3029
3030 cx.observe_window_activation(window, move |_, window, cx| {
3031 if window.is_window_active() {
3032 if let Some(pop_up) = pop_up_weak.upgrade() {
3033 pop_up.update(cx, |_, cx| {
3034 cx.emit(AgentNotificationEvent::Dismissed);
3035 });
3036 }
3037 }
3038 })
3039 });
3040 }
3041 }
3042 }
3043
3044 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
3045 for window in self.notifications.drain(..) {
3046 window
3047 .update(cx, |_, window, _| {
3048 window.remove_window();
3049 })
3050 .ok();
3051
3052 self.notification_subscriptions.remove(&window);
3053 }
3054 }
3055
3056 fn render_thread_controls(&self, cx: &Context<Self>) -> impl IntoElement {
3057 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
3058 .shape(ui::IconButtonShape::Square)
3059 .icon_size(IconSize::Small)
3060 .icon_color(Color::Ignored)
3061 .tooltip(Tooltip::text("Open Thread as Markdown"))
3062 .on_click(cx.listener(move |this, _, window, cx| {
3063 if let Some(workspace) = this.workspace.upgrade() {
3064 this.open_thread_as_markdown(workspace, window, cx)
3065 .detach_and_log_err(cx);
3066 }
3067 }));
3068
3069 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
3070 .shape(ui::IconButtonShape::Square)
3071 .icon_size(IconSize::Small)
3072 .icon_color(Color::Ignored)
3073 .tooltip(Tooltip::text("Scroll To Top"))
3074 .on_click(cx.listener(move |this, _, _, cx| {
3075 this.scroll_to_top(cx);
3076 }));
3077
3078 h_flex()
3079 .w_full()
3080 .mr_1()
3081 .pb_2()
3082 .px(RESPONSE_PADDING_X)
3083 .opacity(0.4)
3084 .hover(|style| style.opacity(1.))
3085 .flex_wrap()
3086 .justify_end()
3087 .child(open_as_markdown)
3088 .child(scroll_to_top)
3089 }
3090
3091 fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
3092 div()
3093 .id("acp-thread-scrollbar")
3094 .occlude()
3095 .on_mouse_move(cx.listener(|_, _, _, cx| {
3096 cx.notify();
3097 cx.stop_propagation()
3098 }))
3099 .on_hover(|_, _, cx| {
3100 cx.stop_propagation();
3101 })
3102 .on_any_mouse_down(|_, _, cx| {
3103 cx.stop_propagation();
3104 })
3105 .on_mouse_up(
3106 MouseButton::Left,
3107 cx.listener(|_, _, _, cx| {
3108 cx.stop_propagation();
3109 }),
3110 )
3111 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3112 cx.notify();
3113 }))
3114 .h_full()
3115 .absolute()
3116 .right_1()
3117 .top_1()
3118 .bottom_0()
3119 .w(px(12.))
3120 .cursor_default()
3121 .children(Scrollbar::vertical(self.scrollbar_state.clone()).map(|s| s.auto_hide(cx)))
3122 }
3123
3124 fn settings_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
3125 self.entry_view_state.update(cx, |entry_view_state, cx| {
3126 entry_view_state.settings_changed(cx);
3127 });
3128 }
3129
3130 pub(crate) fn insert_dragged_files(
3131 &self,
3132 paths: Vec<project::ProjectPath>,
3133 added_worktrees: Vec<Entity<project::Worktree>>,
3134 window: &mut Window,
3135 cx: &mut Context<Self>,
3136 ) {
3137 self.message_editor.update(cx, |message_editor, cx| {
3138 message_editor.insert_dragged_files(paths, window, cx);
3139 drop(added_worktrees);
3140 })
3141 }
3142
3143 fn render_thread_error(&self, window: &mut Window, cx: &mut Context<'_, Self>) -> Option<Div> {
3144 let content = match self.thread_error.as_ref()? {
3145 ThreadError::Other(error) => self.render_any_thread_error(error.clone(), cx),
3146 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
3147 ThreadError::ModelRequestLimitReached(plan) => {
3148 self.render_model_request_limit_reached_error(*plan, cx)
3149 }
3150 ThreadError::ToolUseLimitReached => {
3151 self.render_tool_use_limit_reached_error(window, cx)?
3152 }
3153 };
3154
3155 Some(
3156 div()
3157 .border_t_1()
3158 .border_color(cx.theme().colors().border)
3159 .child(content),
3160 )
3161 }
3162
3163 fn render_any_thread_error(&self, error: SharedString, cx: &mut Context<'_, Self>) -> Callout {
3164 let icon = Icon::new(IconName::XCircle)
3165 .size(IconSize::Small)
3166 .color(Color::Error);
3167
3168 Callout::new()
3169 .icon(icon)
3170 .title("Error")
3171 .description(error.clone())
3172 .secondary_action(self.create_copy_button(error.to_string()))
3173 .primary_action(self.dismiss_error_button(cx))
3174 .bg_color(self.error_callout_bg(cx))
3175 }
3176
3177 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
3178 const ERROR_MESSAGE: &str =
3179 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
3180
3181 let icon = Icon::new(IconName::XCircle)
3182 .size(IconSize::Small)
3183 .color(Color::Error);
3184
3185 Callout::new()
3186 .icon(icon)
3187 .title("Free Usage Exceeded")
3188 .description(ERROR_MESSAGE)
3189 .tertiary_action(self.upgrade_button(cx))
3190 .secondary_action(self.create_copy_button(ERROR_MESSAGE))
3191 .primary_action(self.dismiss_error_button(cx))
3192 .bg_color(self.error_callout_bg(cx))
3193 }
3194
3195 fn render_model_request_limit_reached_error(
3196 &self,
3197 plan: cloud_llm_client::Plan,
3198 cx: &mut Context<Self>,
3199 ) -> Callout {
3200 let error_message = match plan {
3201 cloud_llm_client::Plan::ZedPro => "Upgrade to usage-based billing for more prompts.",
3202 cloud_llm_client::Plan::ZedProTrial | cloud_llm_client::Plan::ZedFree => {
3203 "Upgrade to Zed Pro for more prompts."
3204 }
3205 };
3206
3207 let icon = Icon::new(IconName::XCircle)
3208 .size(IconSize::Small)
3209 .color(Color::Error);
3210
3211 Callout::new()
3212 .icon(icon)
3213 .title("Model Prompt Limit Reached")
3214 .description(error_message)
3215 .tertiary_action(self.upgrade_button(cx))
3216 .secondary_action(self.create_copy_button(error_message))
3217 .primary_action(self.dismiss_error_button(cx))
3218 .bg_color(self.error_callout_bg(cx))
3219 }
3220
3221 fn render_tool_use_limit_reached_error(
3222 &self,
3223 window: &mut Window,
3224 cx: &mut Context<Self>,
3225 ) -> Option<Callout> {
3226 let thread = self.as_native_thread(cx)?;
3227 let supports_burn_mode = thread
3228 .read(cx)
3229 .model()
3230 .map_or(false, |model| model.supports_burn_mode());
3231
3232 let focus_handle = self.focus_handle(cx);
3233
3234 let icon = Icon::new(IconName::Info)
3235 .size(IconSize::Small)
3236 .color(Color::Info);
3237
3238 Some(
3239 Callout::new()
3240 .icon(icon)
3241 .title("Consecutive tool use limit reached.")
3242 .when(supports_burn_mode, |this| {
3243 this.secondary_action(
3244 Button::new("continue-burn-mode", "Continue with Burn Mode")
3245 .style(ButtonStyle::Filled)
3246 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
3247 .layer(ElevationIndex::ModalSurface)
3248 .label_size(LabelSize::Small)
3249 .key_binding(
3250 KeyBinding::for_action_in(
3251 &ContinueWithBurnMode,
3252 &focus_handle,
3253 window,
3254 cx,
3255 )
3256 .map(|kb| kb.size(rems_from_px(10.))),
3257 )
3258 .tooltip(Tooltip::text("Enable Burn Mode for unlimited tool use."))
3259 .on_click({
3260 cx.listener(move |this, _, _window, cx| {
3261 thread.update(cx, |thread, _cx| {
3262 thread.set_completion_mode(CompletionMode::Burn);
3263 });
3264 this.resume_chat(cx);
3265 })
3266 }),
3267 )
3268 })
3269 .primary_action(
3270 Button::new("continue-conversation", "Continue")
3271 .layer(ElevationIndex::ModalSurface)
3272 .label_size(LabelSize::Small)
3273 .key_binding(
3274 KeyBinding::for_action_in(&ContinueThread, &focus_handle, window, cx)
3275 .map(|kb| kb.size(rems_from_px(10.))),
3276 )
3277 .on_click(cx.listener(|this, _, _window, cx| {
3278 this.resume_chat(cx);
3279 })),
3280 ),
3281 )
3282 }
3283
3284 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
3285 let message = message.into();
3286
3287 IconButton::new("copy", IconName::Copy)
3288 .icon_size(IconSize::Small)
3289 .icon_color(Color::Muted)
3290 .tooltip(Tooltip::text("Copy Error Message"))
3291 .on_click(move |_, _, cx| {
3292 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
3293 })
3294 }
3295
3296 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3297 IconButton::new("dismiss", IconName::Close)
3298 .icon_size(IconSize::Small)
3299 .icon_color(Color::Muted)
3300 .tooltip(Tooltip::text("Dismiss Error"))
3301 .on_click(cx.listener({
3302 move |this, _, _, cx| {
3303 this.clear_thread_error(cx);
3304 cx.notify();
3305 }
3306 }))
3307 }
3308
3309 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3310 Button::new("upgrade", "Upgrade")
3311 .label_size(LabelSize::Small)
3312 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
3313 .on_click(cx.listener({
3314 move |this, _, _, cx| {
3315 this.clear_thread_error(cx);
3316 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
3317 }
3318 }))
3319 }
3320
3321 fn error_callout_bg(&self, cx: &Context<Self>) -> Hsla {
3322 cx.theme().status().error.opacity(0.08)
3323 }
3324}
3325
3326impl Focusable for AcpThreadView {
3327 fn focus_handle(&self, cx: &App) -> FocusHandle {
3328 self.message_editor.focus_handle(cx)
3329 }
3330}
3331
3332impl Render for AcpThreadView {
3333 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3334 let has_messages = self.list_state.item_count() > 0;
3335
3336 v_flex()
3337 .size_full()
3338 .key_context("AcpThread")
3339 .on_action(cx.listener(Self::open_agent_diff))
3340 .on_action(cx.listener(Self::toggle_burn_mode))
3341 .bg(cx.theme().colors().panel_background)
3342 .child(match &self.thread_state {
3343 ThreadState::Unauthenticated { connection } => v_flex()
3344 .p_2()
3345 .flex_1()
3346 .items_center()
3347 .justify_center()
3348 .child(self.render_pending_auth_state())
3349 .child(h_flex().mt_1p5().justify_center().children(
3350 connection.auth_methods().into_iter().map(|method| {
3351 Button::new(
3352 SharedString::from(method.id.0.clone()),
3353 method.name.clone(),
3354 )
3355 .on_click({
3356 let method_id = method.id.clone();
3357 cx.listener(move |this, _, window, cx| {
3358 this.authenticate(method_id.clone(), window, cx)
3359 })
3360 })
3361 }),
3362 )),
3363 ThreadState::Loading { .. } => v_flex().flex_1().child(self.render_empty_state(cx)),
3364 ThreadState::LoadError(e) => v_flex()
3365 .p_2()
3366 .flex_1()
3367 .items_center()
3368 .justify_center()
3369 .child(self.render_load_error(e, cx)),
3370 ThreadState::ServerExited { status } => v_flex()
3371 .p_2()
3372 .flex_1()
3373 .items_center()
3374 .justify_center()
3375 .child(self.render_server_exited(*status, cx)),
3376 ThreadState::Ready { thread, .. } => {
3377 let thread_clone = thread.clone();
3378
3379 v_flex().flex_1().map(|this| {
3380 if has_messages {
3381 this.child(
3382 list(
3383 self.list_state.clone(),
3384 cx.processor(|this, index: usize, window, cx| {
3385 let Some((entry, len)) = this.thread().and_then(|thread| {
3386 let entries = &thread.read(cx).entries();
3387 Some((entries.get(index)?, entries.len()))
3388 }) else {
3389 return Empty.into_any();
3390 };
3391 this.render_entry(index, len, entry, window, cx)
3392 }),
3393 )
3394 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
3395 .flex_grow()
3396 .into_any(),
3397 )
3398 .child(self.render_vertical_scrollbar(cx))
3399 .children(
3400 match thread_clone.read(cx).status() {
3401 ThreadStatus::Idle
3402 | ThreadStatus::WaitingForToolConfirmation => None,
3403 ThreadStatus::Generating => div()
3404 .px_5()
3405 .py_2()
3406 .child(LoadingLabel::new("").size(LabelSize::Small))
3407 .into(),
3408 },
3409 )
3410 } else {
3411 this.child(self.render_empty_state(cx))
3412 }
3413 })
3414 }
3415 })
3416 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
3417 // above so that the scrollbar doesn't render behind it. The current setup allows
3418 // the scrollbar to stop exactly at the activity bar start.
3419 .when(has_messages, |this| match &self.thread_state {
3420 ThreadState::Ready { thread, .. } => {
3421 this.children(self.render_activity_bar(thread, window, cx))
3422 }
3423 _ => this,
3424 })
3425 .children(self.render_thread_error(window, cx))
3426 .child(self.render_message_editor(window, cx))
3427 }
3428}
3429
3430fn default_markdown_style(buffer_font: bool, window: &Window, cx: &App) -> MarkdownStyle {
3431 let theme_settings = ThemeSettings::get_global(cx);
3432 let colors = cx.theme().colors();
3433
3434 let buffer_font_size = TextSize::Small.rems(cx);
3435
3436 let mut text_style = window.text_style();
3437 let line_height = buffer_font_size * 1.75;
3438
3439 let font_family = if buffer_font {
3440 theme_settings.buffer_font.family.clone()
3441 } else {
3442 theme_settings.ui_font.family.clone()
3443 };
3444
3445 let font_size = if buffer_font {
3446 TextSize::Small.rems(cx)
3447 } else {
3448 TextSize::Default.rems(cx)
3449 };
3450
3451 text_style.refine(&TextStyleRefinement {
3452 font_family: Some(font_family),
3453 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
3454 font_features: Some(theme_settings.ui_font.features.clone()),
3455 font_size: Some(font_size.into()),
3456 line_height: Some(line_height.into()),
3457 color: Some(cx.theme().colors().text),
3458 ..Default::default()
3459 });
3460
3461 MarkdownStyle {
3462 base_text_style: text_style.clone(),
3463 syntax: cx.theme().syntax().clone(),
3464 selection_background_color: cx.theme().colors().element_selection_background,
3465 code_block_overflow_x_scroll: true,
3466 table_overflow_x_scroll: true,
3467 heading_level_styles: Some(HeadingLevelStyles {
3468 h1: Some(TextStyleRefinement {
3469 font_size: Some(rems(1.15).into()),
3470 ..Default::default()
3471 }),
3472 h2: Some(TextStyleRefinement {
3473 font_size: Some(rems(1.1).into()),
3474 ..Default::default()
3475 }),
3476 h3: Some(TextStyleRefinement {
3477 font_size: Some(rems(1.05).into()),
3478 ..Default::default()
3479 }),
3480 h4: Some(TextStyleRefinement {
3481 font_size: Some(rems(1.).into()),
3482 ..Default::default()
3483 }),
3484 h5: Some(TextStyleRefinement {
3485 font_size: Some(rems(0.95).into()),
3486 ..Default::default()
3487 }),
3488 h6: Some(TextStyleRefinement {
3489 font_size: Some(rems(0.875).into()),
3490 ..Default::default()
3491 }),
3492 }),
3493 code_block: StyleRefinement {
3494 padding: EdgesRefinement {
3495 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3496 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3497 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3498 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3499 },
3500 margin: EdgesRefinement {
3501 top: Some(Length::Definite(Pixels(8.).into())),
3502 left: Some(Length::Definite(Pixels(0.).into())),
3503 right: Some(Length::Definite(Pixels(0.).into())),
3504 bottom: Some(Length::Definite(Pixels(12.).into())),
3505 },
3506 border_style: Some(BorderStyle::Solid),
3507 border_widths: EdgesRefinement {
3508 top: Some(AbsoluteLength::Pixels(Pixels(1.))),
3509 left: Some(AbsoluteLength::Pixels(Pixels(1.))),
3510 right: Some(AbsoluteLength::Pixels(Pixels(1.))),
3511 bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
3512 },
3513 border_color: Some(colors.border_variant),
3514 background: Some(colors.editor_background.into()),
3515 text: Some(TextStyleRefinement {
3516 font_family: Some(theme_settings.buffer_font.family.clone()),
3517 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
3518 font_features: Some(theme_settings.buffer_font.features.clone()),
3519 font_size: Some(buffer_font_size.into()),
3520 ..Default::default()
3521 }),
3522 ..Default::default()
3523 },
3524 inline_code: TextStyleRefinement {
3525 font_family: Some(theme_settings.buffer_font.family.clone()),
3526 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
3527 font_features: Some(theme_settings.buffer_font.features.clone()),
3528 font_size: Some(buffer_font_size.into()),
3529 background_color: Some(colors.editor_foreground.opacity(0.08)),
3530 ..Default::default()
3531 },
3532 link: TextStyleRefinement {
3533 background_color: Some(colors.editor_foreground.opacity(0.025)),
3534 underline: Some(UnderlineStyle {
3535 color: Some(colors.text_accent.opacity(0.5)),
3536 thickness: px(1.),
3537 ..Default::default()
3538 }),
3539 ..Default::default()
3540 },
3541 ..Default::default()
3542 }
3543}
3544
3545fn plan_label_markdown_style(
3546 status: &acp::PlanEntryStatus,
3547 window: &Window,
3548 cx: &App,
3549) -> MarkdownStyle {
3550 let default_md_style = default_markdown_style(false, window, cx);
3551
3552 MarkdownStyle {
3553 base_text_style: TextStyle {
3554 color: cx.theme().colors().text_muted,
3555 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
3556 Some(gpui::StrikethroughStyle {
3557 thickness: px(1.),
3558 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
3559 })
3560 } else {
3561 None
3562 },
3563 ..default_md_style.base_text_style
3564 },
3565 ..default_md_style
3566 }
3567}
3568
3569fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
3570 let default_md_style = default_markdown_style(true, window, cx);
3571
3572 MarkdownStyle {
3573 base_text_style: TextStyle {
3574 ..default_md_style.base_text_style
3575 },
3576 selection_background_color: cx.theme().colors().element_selection_background,
3577 ..Default::default()
3578 }
3579}
3580
3581#[cfg(test)]
3582pub(crate) mod tests {
3583 use acp_thread::StubAgentConnection;
3584 use agent::{TextThreadStore, ThreadStore};
3585 use agent_client_protocol::SessionId;
3586 use editor::EditorSettings;
3587 use fs::FakeFs;
3588 use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
3589 use project::Project;
3590 use serde_json::json;
3591 use settings::SettingsStore;
3592 use std::any::Any;
3593 use std::path::Path;
3594 use workspace::Item;
3595
3596 use super::*;
3597
3598 #[gpui::test]
3599 async fn test_drop(cx: &mut TestAppContext) {
3600 init_test(cx);
3601
3602 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default(), cx).await;
3603 let weak_view = thread_view.downgrade();
3604 drop(thread_view);
3605 assert!(!weak_view.is_upgradable());
3606 }
3607
3608 #[gpui::test]
3609 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
3610 init_test(cx);
3611
3612 let (thread_view, cx) = setup_thread_view(StubAgentServer::default(), cx).await;
3613
3614 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
3615 message_editor.update_in(cx, |editor, window, cx| {
3616 editor.set_text("Hello", window, cx);
3617 });
3618
3619 cx.deactivate_window();
3620
3621 thread_view.update_in(cx, |thread_view, window, cx| {
3622 thread_view.send(window, cx);
3623 });
3624
3625 cx.run_until_parked();
3626
3627 assert!(
3628 cx.windows()
3629 .iter()
3630 .any(|window| window.downcast::<AgentNotification>().is_some())
3631 );
3632 }
3633
3634 #[gpui::test]
3635 async fn test_notification_for_error(cx: &mut TestAppContext) {
3636 init_test(cx);
3637
3638 let (thread_view, cx) =
3639 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
3640
3641 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
3642 message_editor.update_in(cx, |editor, window, cx| {
3643 editor.set_text("Hello", window, cx);
3644 });
3645
3646 cx.deactivate_window();
3647
3648 thread_view.update_in(cx, |thread_view, window, cx| {
3649 thread_view.send(window, cx);
3650 });
3651
3652 cx.run_until_parked();
3653
3654 assert!(
3655 cx.windows()
3656 .iter()
3657 .any(|window| window.downcast::<AgentNotification>().is_some())
3658 );
3659 }
3660
3661 #[gpui::test]
3662 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
3663 init_test(cx);
3664
3665 let tool_call_id = acp::ToolCallId("1".into());
3666 let tool_call = acp::ToolCall {
3667 id: tool_call_id.clone(),
3668 title: "Label".into(),
3669 kind: acp::ToolKind::Edit,
3670 status: acp::ToolCallStatus::Pending,
3671 content: vec!["hi".into()],
3672 locations: vec![],
3673 raw_input: None,
3674 raw_output: None,
3675 };
3676 let connection =
3677 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
3678 tool_call_id,
3679 vec![acp::PermissionOption {
3680 id: acp::PermissionOptionId("1".into()),
3681 name: "Allow".into(),
3682 kind: acp::PermissionOptionKind::AllowOnce,
3683 }],
3684 )]));
3685
3686 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
3687
3688 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
3689
3690 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
3691 message_editor.update_in(cx, |editor, window, cx| {
3692 editor.set_text("Hello", window, cx);
3693 });
3694
3695 cx.deactivate_window();
3696
3697 thread_view.update_in(cx, |thread_view, window, cx| {
3698 thread_view.send(window, cx);
3699 });
3700
3701 cx.run_until_parked();
3702
3703 assert!(
3704 cx.windows()
3705 .iter()
3706 .any(|window| window.downcast::<AgentNotification>().is_some())
3707 );
3708 }
3709
3710 async fn setup_thread_view(
3711 agent: impl AgentServer + 'static,
3712 cx: &mut TestAppContext,
3713 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
3714 let fs = FakeFs::new(cx.executor());
3715 let project = Project::test(fs, [], cx).await;
3716 let (workspace, cx) =
3717 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
3718
3719 let thread_store =
3720 cx.update(|_window, cx| cx.new(|cx| ThreadStore::fake(project.clone(), cx)));
3721 let text_thread_store =
3722 cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
3723
3724 let thread_view = cx.update(|window, cx| {
3725 cx.new(|cx| {
3726 AcpThreadView::new(
3727 Rc::new(agent),
3728 workspace.downgrade(),
3729 project,
3730 thread_store.clone(),
3731 text_thread_store.clone(),
3732 window,
3733 cx,
3734 )
3735 })
3736 });
3737 cx.run_until_parked();
3738 (thread_view, cx)
3739 }
3740
3741 fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
3742 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
3743
3744 workspace
3745 .update_in(cx, |workspace, window, cx| {
3746 workspace.add_item_to_active_pane(
3747 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
3748 None,
3749 true,
3750 window,
3751 cx,
3752 );
3753 })
3754 .unwrap();
3755 }
3756
3757 struct ThreadViewItem(Entity<AcpThreadView>);
3758
3759 impl Item for ThreadViewItem {
3760 type Event = ();
3761
3762 fn include_in_nav_history() -> bool {
3763 false
3764 }
3765
3766 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
3767 "Test".into()
3768 }
3769 }
3770
3771 impl EventEmitter<()> for ThreadViewItem {}
3772
3773 impl Focusable for ThreadViewItem {
3774 fn focus_handle(&self, cx: &App) -> FocusHandle {
3775 self.0.read(cx).focus_handle(cx).clone()
3776 }
3777 }
3778
3779 impl Render for ThreadViewItem {
3780 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3781 self.0.clone().into_any_element()
3782 }
3783 }
3784
3785 struct StubAgentServer<C> {
3786 connection: C,
3787 }
3788
3789 impl<C> StubAgentServer<C> {
3790 fn new(connection: C) -> Self {
3791 Self { connection }
3792 }
3793 }
3794
3795 impl StubAgentServer<StubAgentConnection> {
3796 fn default() -> Self {
3797 Self::new(StubAgentConnection::default())
3798 }
3799 }
3800
3801 impl<C> AgentServer for StubAgentServer<C>
3802 where
3803 C: 'static + AgentConnection + Send + Clone,
3804 {
3805 fn logo(&self) -> ui::IconName {
3806 ui::IconName::Ai
3807 }
3808
3809 fn name(&self) -> &'static str {
3810 "Test"
3811 }
3812
3813 fn empty_state_headline(&self) -> &'static str {
3814 "Test"
3815 }
3816
3817 fn empty_state_message(&self) -> &'static str {
3818 "Test"
3819 }
3820
3821 fn connect(
3822 &self,
3823 _root_dir: &Path,
3824 _project: &Entity<Project>,
3825 _cx: &mut App,
3826 ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
3827 Task::ready(Ok(Rc::new(self.connection.clone())))
3828 }
3829 }
3830
3831 #[derive(Clone)]
3832 struct SaboteurAgentConnection;
3833
3834 impl AgentConnection for SaboteurAgentConnection {
3835 fn new_thread(
3836 self: Rc<Self>,
3837 project: Entity<Project>,
3838 _cwd: &Path,
3839 cx: &mut gpui::App,
3840 ) -> Task<gpui::Result<Entity<AcpThread>>> {
3841 Task::ready(Ok(cx.new(|cx| {
3842 AcpThread::new(
3843 "SaboteurAgentConnection",
3844 self,
3845 project,
3846 SessionId("test".into()),
3847 cx,
3848 )
3849 })))
3850 }
3851
3852 fn auth_methods(&self) -> &[acp::AuthMethod] {
3853 &[]
3854 }
3855
3856 fn authenticate(
3857 &self,
3858 _method_id: acp::AuthMethodId,
3859 _cx: &mut App,
3860 ) -> Task<gpui::Result<()>> {
3861 unimplemented!()
3862 }
3863
3864 fn prompt(
3865 &self,
3866 _id: Option<acp_thread::UserMessageId>,
3867 _params: acp::PromptRequest,
3868 _cx: &mut App,
3869 ) -> Task<gpui::Result<acp::PromptResponse>> {
3870 Task::ready(Err(anyhow::anyhow!("Error prompting")))
3871 }
3872
3873 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
3874 unimplemented!()
3875 }
3876
3877 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
3878 self
3879 }
3880 }
3881
3882 pub(crate) fn init_test(cx: &mut TestAppContext) {
3883 cx.update(|cx| {
3884 let settings_store = SettingsStore::test(cx);
3885 cx.set_global(settings_store);
3886 language::init(cx);
3887 Project::init_settings(cx);
3888 AgentSettings::register(cx);
3889 workspace::init_settings(cx);
3890 ThemeSettings::register(cx);
3891 release_channel::init(SemanticVersion::default(), cx);
3892 EditorSettings::register(cx);
3893 });
3894 }
3895
3896 #[gpui::test]
3897 async fn test_rewind_views(cx: &mut TestAppContext) {
3898 init_test(cx);
3899
3900 let fs = FakeFs::new(cx.executor());
3901 fs.insert_tree(
3902 "/project",
3903 json!({
3904 "test1.txt": "old content 1",
3905 "test2.txt": "old content 2"
3906 }),
3907 )
3908 .await;
3909 let project = Project::test(fs, [Path::new("/project")], cx).await;
3910 let (workspace, cx) =
3911 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
3912
3913 let thread_store =
3914 cx.update(|_window, cx| cx.new(|cx| ThreadStore::fake(project.clone(), cx)));
3915 let text_thread_store =
3916 cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
3917
3918 let connection = Rc::new(StubAgentConnection::new());
3919 let thread_view = cx.update(|window, cx| {
3920 cx.new(|cx| {
3921 AcpThreadView::new(
3922 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
3923 workspace.downgrade(),
3924 project.clone(),
3925 thread_store.clone(),
3926 text_thread_store.clone(),
3927 window,
3928 cx,
3929 )
3930 })
3931 });
3932
3933 cx.run_until_parked();
3934
3935 let thread = thread_view
3936 .read_with(cx, |view, _| view.thread().cloned())
3937 .unwrap();
3938
3939 // First user message
3940 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
3941 id: acp::ToolCallId("tool1".into()),
3942 title: "Edit file 1".into(),
3943 kind: acp::ToolKind::Edit,
3944 status: acp::ToolCallStatus::Completed,
3945 content: vec![acp::ToolCallContent::Diff {
3946 diff: acp::Diff {
3947 path: "/project/test1.txt".into(),
3948 old_text: Some("old content 1".into()),
3949 new_text: "new content 1".into(),
3950 },
3951 }],
3952 locations: vec![],
3953 raw_input: None,
3954 raw_output: None,
3955 })]);
3956
3957 thread
3958 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
3959 .await
3960 .unwrap();
3961 cx.run_until_parked();
3962
3963 thread.read_with(cx, |thread, _| {
3964 assert_eq!(thread.entries().len(), 2);
3965 });
3966
3967 thread_view.read_with(cx, |view, cx| {
3968 view.entry_view_state.read_with(cx, |entry_view_state, _| {
3969 assert!(
3970 entry_view_state
3971 .entry(0)
3972 .unwrap()
3973 .message_editor()
3974 .is_some()
3975 );
3976 assert!(entry_view_state.entry(1).unwrap().has_content());
3977 });
3978 });
3979
3980 // Second user message
3981 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
3982 id: acp::ToolCallId("tool2".into()),
3983 title: "Edit file 2".into(),
3984 kind: acp::ToolKind::Edit,
3985 status: acp::ToolCallStatus::Completed,
3986 content: vec![acp::ToolCallContent::Diff {
3987 diff: acp::Diff {
3988 path: "/project/test2.txt".into(),
3989 old_text: Some("old content 2".into()),
3990 new_text: "new content 2".into(),
3991 },
3992 }],
3993 locations: vec![],
3994 raw_input: None,
3995 raw_output: None,
3996 })]);
3997
3998 thread
3999 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
4000 .await
4001 .unwrap();
4002 cx.run_until_parked();
4003
4004 let second_user_message_id = thread.read_with(cx, |thread, _| {
4005 assert_eq!(thread.entries().len(), 4);
4006 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
4007 panic!();
4008 };
4009 user_message.id.clone().unwrap()
4010 });
4011
4012 thread_view.read_with(cx, |view, cx| {
4013 view.entry_view_state.read_with(cx, |entry_view_state, _| {
4014 assert!(
4015 entry_view_state
4016 .entry(0)
4017 .unwrap()
4018 .message_editor()
4019 .is_some()
4020 );
4021 assert!(entry_view_state.entry(1).unwrap().has_content());
4022 assert!(
4023 entry_view_state
4024 .entry(2)
4025 .unwrap()
4026 .message_editor()
4027 .is_some()
4028 );
4029 assert!(entry_view_state.entry(3).unwrap().has_content());
4030 });
4031 });
4032
4033 // Rewind to first message
4034 thread
4035 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
4036 .await
4037 .unwrap();
4038
4039 cx.run_until_parked();
4040
4041 thread.read_with(cx, |thread, _| {
4042 assert_eq!(thread.entries().len(), 2);
4043 });
4044
4045 thread_view.read_with(cx, |view, cx| {
4046 view.entry_view_state.read_with(cx, |entry_view_state, _| {
4047 assert!(
4048 entry_view_state
4049 .entry(0)
4050 .unwrap()
4051 .message_editor()
4052 .is_some()
4053 );
4054 assert!(entry_view_state.entry(1).unwrap().has_content());
4055
4056 // Old views should be dropped
4057 assert!(entry_view_state.entry(2).is_none());
4058 assert!(entry_view_state.entry(3).is_none());
4059 });
4060 });
4061 }
4062
4063 #[gpui::test]
4064 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
4065 init_test(cx);
4066
4067 let connection = StubAgentConnection::new();
4068
4069 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4070 content: acp::ContentBlock::Text(acp::TextContent {
4071 text: "Response".into(),
4072 annotations: None,
4073 }),
4074 }]);
4075
4076 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4077 add_to_workspace(thread_view.clone(), cx);
4078
4079 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4080 message_editor.update_in(cx, |editor, window, cx| {
4081 editor.set_text("Original message to edit", window, cx);
4082 });
4083 thread_view.update_in(cx, |thread_view, window, cx| {
4084 thread_view.send(window, cx);
4085 });
4086
4087 cx.run_until_parked();
4088
4089 let user_message_editor = thread_view.read_with(cx, |view, cx| {
4090 assert_eq!(view.editing_message, None);
4091
4092 view.entry_view_state
4093 .read(cx)
4094 .entry(0)
4095 .unwrap()
4096 .message_editor()
4097 .unwrap()
4098 .clone()
4099 });
4100
4101 // Focus
4102 cx.focus(&user_message_editor);
4103 thread_view.read_with(cx, |view, _cx| {
4104 assert_eq!(view.editing_message, Some(0));
4105 });
4106
4107 // Edit
4108 user_message_editor.update_in(cx, |editor, window, cx| {
4109 editor.set_text("Edited message content", window, cx);
4110 });
4111
4112 // Cancel
4113 user_message_editor.update_in(cx, |_editor, window, cx| {
4114 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
4115 });
4116
4117 thread_view.read_with(cx, |view, _cx| {
4118 assert_eq!(view.editing_message, None);
4119 });
4120
4121 user_message_editor.read_with(cx, |editor, cx| {
4122 assert_eq!(editor.text(cx), "Original message to edit");
4123 });
4124 }
4125
4126 #[gpui::test]
4127 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
4128 init_test(cx);
4129
4130 let connection = StubAgentConnection::new();
4131
4132 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4133 content: acp::ContentBlock::Text(acp::TextContent {
4134 text: "Response".into(),
4135 annotations: None,
4136 }),
4137 }]);
4138
4139 let (thread_view, cx) =
4140 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4141 add_to_workspace(thread_view.clone(), cx);
4142
4143 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4144 message_editor.update_in(cx, |editor, window, cx| {
4145 editor.set_text("Original message to edit", window, cx);
4146 });
4147 thread_view.update_in(cx, |thread_view, window, cx| {
4148 thread_view.send(window, cx);
4149 });
4150
4151 cx.run_until_parked();
4152
4153 let user_message_editor = thread_view.read_with(cx, |view, cx| {
4154 assert_eq!(view.editing_message, None);
4155 assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
4156
4157 view.entry_view_state
4158 .read(cx)
4159 .entry(0)
4160 .unwrap()
4161 .message_editor()
4162 .unwrap()
4163 .clone()
4164 });
4165
4166 // Focus
4167 cx.focus(&user_message_editor);
4168
4169 // Edit
4170 user_message_editor.update_in(cx, |editor, window, cx| {
4171 editor.set_text("Edited message content", window, cx);
4172 });
4173
4174 // Send
4175 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4176 content: acp::ContentBlock::Text(acp::TextContent {
4177 text: "New Response".into(),
4178 annotations: None,
4179 }),
4180 }]);
4181
4182 user_message_editor.update_in(cx, |_editor, window, cx| {
4183 window.dispatch_action(Box::new(Chat), cx);
4184 });
4185
4186 cx.run_until_parked();
4187
4188 thread_view.read_with(cx, |view, cx| {
4189 assert_eq!(view.editing_message, None);
4190
4191 let entries = view.thread().unwrap().read(cx).entries();
4192 assert_eq!(entries.len(), 2);
4193 assert_eq!(
4194 entries[0].to_markdown(cx),
4195 "## User\n\nEdited message content\n\n"
4196 );
4197 assert_eq!(
4198 entries[1].to_markdown(cx),
4199 "## Assistant\n\nNew Response\n\n"
4200 );
4201
4202 let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
4203 assert!(!state.entry(1).unwrap().has_content());
4204 state.entry(0).unwrap().message_editor().unwrap().clone()
4205 });
4206
4207 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
4208 })
4209 }
4210}