1use acp_thread::{
2 AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk,
3 AuthRequired, LoadError, MentionUri, RetryStatus, ThreadStatus, ToolCall, ToolCallContent,
4 ToolCallStatus, UserMessageId,
5};
6use acp_thread::{AgentConnection, Plan};
7use action_log::ActionLog;
8use agent_client_protocol::{self as acp, PromptCapabilities};
9use agent_servers::{AgentServer, AgentServerDelegate, ClaudeCode};
10use agent_settings::{AgentProfileId, AgentSettings, CompletionMode, NotifyWhenAgentWaiting};
11use agent2::{DbThreadMetadata, HistoryEntry, HistoryEntryId, HistoryStore};
12use anyhow::bail;
13use audio::{Audio, Sound};
14use buffer_diff::BufferDiff;
15use client::zed_urls;
16use collections::{HashMap, HashSet};
17use editor::scroll::Autoscroll;
18use editor::{Editor, EditorEvent, EditorMode, MultiBuffer, PathKey, SelectionEffects};
19use file_icons::FileIcons;
20use fs::Fs;
21use gpui::{
22 Action, Animation, AnimationExt, AnyView, App, BorderStyle, ClickEvent, ClipboardItem,
23 CursorStyle, EdgesRefinement, ElementId, Empty, Entity, FocusHandle, Focusable, Hsla, Length,
24 ListOffset, ListState, MouseButton, PlatformDisplay, SharedString, Stateful, StyleRefinement,
25 Subscription, Task, TextStyle, TextStyleRefinement, Transformation, UnderlineStyle, WeakEntity,
26 Window, WindowHandle, div, ease_in_out, linear_color_stop, linear_gradient, list, percentage,
27 point, prelude::*, pulsating_between,
28};
29use language::Buffer;
30
31use language_model::LanguageModelRegistry;
32use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
33use project::{Project, ProjectEntryId};
34use prompt_store::{PromptId, PromptStore};
35use rope::Point;
36use settings::{Settings as _, SettingsStore};
37use std::cell::Cell;
38use std::path::Path;
39use std::sync::Arc;
40use std::time::Instant;
41use std::{collections::BTreeMap, rc::Rc, time::Duration};
42use text::Anchor;
43use theme::ThemeSettings;
44use ui::{
45 Callout, Disclosure, Divider, DividerColor, ElevationIndex, KeyBinding, PopoverMenuHandle,
46 Scrollbar, ScrollbarState, SpinnerLabel, Tooltip, prelude::*,
47};
48use util::{ResultExt, size::format_file_size, time::duration_alt_display};
49use workspace::{CollaboratorId, Workspace};
50use zed_actions::agent::{Chat, ToggleModelSelector};
51use zed_actions::assistant::OpenRulesLibrary;
52
53use super::entry_view_state::EntryViewState;
54use crate::acp::AcpModelSelectorPopover;
55use crate::acp::entry_view_state::{EntryViewEvent, ViewEvent};
56use crate::acp::message_editor::{MessageEditor, MessageEditorEvent};
57use crate::agent_diff::AgentDiff;
58use crate::profile_selector::{ProfileProvider, ProfileSelector};
59
60use crate::ui::preview::UsageCallout;
61use crate::ui::{
62 AgentNotification, AgentNotificationEvent, BurnModeTooltip, UnavailableEditingTooltip,
63};
64use crate::{
65 AgentDiffPane, AgentPanel, ContinueThread, ContinueWithBurnMode, ExpandMessageEditor, Follow,
66 KeepAll, OpenAgentDiff, OpenHistory, RejectAll, ToggleBurnMode, ToggleProfileSelector,
67};
68
69pub const MIN_EDITOR_LINES: usize = 4;
70pub const MAX_EDITOR_LINES: usize = 8;
71
72#[derive(Copy, Clone, Debug, PartialEq, Eq)]
73enum ThreadFeedback {
74 Positive,
75 Negative,
76}
77
78enum ThreadError {
79 PaymentRequired,
80 ModelRequestLimitReached(cloud_llm_client::Plan),
81 ToolUseLimitReached,
82 AuthenticationRequired(SharedString),
83 Other(SharedString),
84}
85
86impl ThreadError {
87 fn from_err(error: anyhow::Error, agent: &Rc<dyn AgentServer>) -> Self {
88 if error.is::<language_model::PaymentRequiredError>() {
89 Self::PaymentRequired
90 } else if error.is::<language_model::ToolUseLimitReachedError>() {
91 Self::ToolUseLimitReached
92 } else if let Some(error) =
93 error.downcast_ref::<language_model::ModelRequestLimitReachedError>()
94 {
95 Self::ModelRequestLimitReached(error.plan)
96 } else {
97 let string = error.to_string();
98 // TODO: we should have Gemini return better errors here.
99 if agent.clone().downcast::<agent_servers::Gemini>().is_some()
100 && string.contains("Could not load the default credentials")
101 || string.contains("API key not valid")
102 || string.contains("Request had invalid authentication credentials")
103 {
104 Self::AuthenticationRequired(string.into())
105 } else {
106 Self::Other(error.to_string().into())
107 }
108 }
109 }
110}
111
112impl ProfileProvider for Entity<agent2::Thread> {
113 fn profile_id(&self, cx: &App) -> AgentProfileId {
114 self.read(cx).profile().clone()
115 }
116
117 fn set_profile(&self, profile_id: AgentProfileId, cx: &mut App) {
118 self.update(cx, |thread, _cx| {
119 thread.set_profile(profile_id);
120 });
121 }
122
123 fn profiles_supported(&self, cx: &App) -> bool {
124 self.read(cx)
125 .model()
126 .is_some_and(|model| model.supports_tools())
127 }
128}
129
130#[derive(Default)]
131struct ThreadFeedbackState {
132 feedback: Option<ThreadFeedback>,
133 comments_editor: Option<Entity<Editor>>,
134}
135
136impl ThreadFeedbackState {
137 pub fn submit(
138 &mut self,
139 thread: Entity<AcpThread>,
140 feedback: ThreadFeedback,
141 window: &mut Window,
142 cx: &mut App,
143 ) {
144 let Some(telemetry) = thread.read(cx).connection().telemetry() else {
145 return;
146 };
147
148 if self.feedback == Some(feedback) {
149 return;
150 }
151
152 self.feedback = Some(feedback);
153 match feedback {
154 ThreadFeedback::Positive => {
155 self.comments_editor = None;
156 }
157 ThreadFeedback::Negative => {
158 self.comments_editor = Some(Self::build_feedback_comments_editor(window, cx));
159 }
160 }
161 let session_id = thread.read(cx).session_id().clone();
162 let agent_name = telemetry.agent_name();
163 let task = telemetry.thread_data(&session_id, cx);
164 let rating = match feedback {
165 ThreadFeedback::Positive => "positive",
166 ThreadFeedback::Negative => "negative",
167 };
168 cx.background_spawn(async move {
169 let thread = task.await?;
170 telemetry::event!(
171 "Agent Thread Rated",
172 session_id = session_id,
173 rating = rating,
174 agent = agent_name,
175 thread = thread
176 );
177 anyhow::Ok(())
178 })
179 .detach_and_log_err(cx);
180 }
181
182 pub fn submit_comments(&mut self, thread: Entity<AcpThread>, cx: &mut App) {
183 let Some(telemetry) = thread.read(cx).connection().telemetry() else {
184 return;
185 };
186
187 let Some(comments) = self
188 .comments_editor
189 .as_ref()
190 .map(|editor| editor.read(cx).text(cx))
191 .filter(|text| !text.trim().is_empty())
192 else {
193 return;
194 };
195
196 self.comments_editor.take();
197
198 let session_id = thread.read(cx).session_id().clone();
199 let agent_name = telemetry.agent_name();
200 let task = telemetry.thread_data(&session_id, cx);
201 cx.background_spawn(async move {
202 let thread = task.await?;
203 telemetry::event!(
204 "Agent Thread Feedback Comments",
205 session_id = session_id,
206 comments = comments,
207 agent = agent_name,
208 thread = thread
209 );
210 anyhow::Ok(())
211 })
212 .detach_and_log_err(cx);
213 }
214
215 pub fn clear(&mut self) {
216 *self = Self::default()
217 }
218
219 pub fn dismiss_comments(&mut self) {
220 self.comments_editor.take();
221 }
222
223 fn build_feedback_comments_editor(window: &mut Window, cx: &mut App) -> Entity<Editor> {
224 let buffer = cx.new(|cx| {
225 let empty_string = String::new();
226 MultiBuffer::singleton(cx.new(|cx| Buffer::local(empty_string, cx)), cx)
227 });
228
229 let editor = cx.new(|cx| {
230 let mut editor = Editor::new(
231 editor::EditorMode::AutoHeight {
232 min_lines: 1,
233 max_lines: Some(4),
234 },
235 buffer,
236 None,
237 window,
238 cx,
239 );
240 editor.set_placeholder_text(
241 "What went wrong? Share your feedback so we can improve.",
242 cx,
243 );
244 editor
245 });
246
247 editor.read(cx).focus_handle(cx).focus(window);
248 editor
249 }
250}
251
252pub struct AcpThreadView {
253 agent: Rc<dyn AgentServer>,
254 workspace: WeakEntity<Workspace>,
255 project: Entity<Project>,
256 thread_state: ThreadState,
257 history_store: Entity<HistoryStore>,
258 hovered_recent_history_item: Option<usize>,
259 entry_view_state: Entity<EntryViewState>,
260 message_editor: Entity<MessageEditor>,
261 focus_handle: FocusHandle,
262 model_selector: Option<Entity<AcpModelSelectorPopover>>,
263 profile_selector: Option<Entity<ProfileSelector>>,
264 notifications: Vec<WindowHandle<AgentNotification>>,
265 notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
266 thread_retry_status: Option<RetryStatus>,
267 thread_error: Option<ThreadError>,
268 thread_feedback: ThreadFeedbackState,
269 list_state: ListState,
270 scrollbar_state: ScrollbarState,
271 auth_task: Option<Task<()>>,
272 expanded_tool_calls: HashSet<acp::ToolCallId>,
273 expanded_thinking_blocks: HashSet<(usize, usize)>,
274 edits_expanded: bool,
275 plan_expanded: bool,
276 editor_expanded: bool,
277 should_be_following: bool,
278 editing_message: Option<usize>,
279 prompt_capabilities: Rc<Cell<PromptCapabilities>>,
280 is_loading_contents: bool,
281 _cancel_task: Option<Task<()>>,
282 _subscriptions: [Subscription; 3],
283}
284
285enum ThreadState {
286 Loading(Entity<LoadingView>),
287 Ready {
288 thread: Entity<AcpThread>,
289 title_editor: Option<Entity<Editor>>,
290 _subscriptions: Vec<Subscription>,
291 },
292 LoadError(LoadError),
293 Unauthenticated {
294 connection: Rc<dyn AgentConnection>,
295 description: Option<Entity<Markdown>>,
296 configuration_view: Option<AnyView>,
297 pending_auth_method: Option<acp::AuthMethodId>,
298 _subscription: Option<Subscription>,
299 },
300}
301
302struct LoadingView {
303 title: SharedString,
304 _load_task: Task<()>,
305 _update_title_task: Task<anyhow::Result<()>>,
306}
307
308impl AcpThreadView {
309 pub fn new(
310 agent: Rc<dyn AgentServer>,
311 resume_thread: Option<DbThreadMetadata>,
312 summarize_thread: Option<DbThreadMetadata>,
313 workspace: WeakEntity<Workspace>,
314 project: Entity<Project>,
315 history_store: Entity<HistoryStore>,
316 prompt_store: Option<Entity<PromptStore>>,
317 window: &mut Window,
318 cx: &mut Context<Self>,
319 ) -> Self {
320 let prompt_capabilities = Rc::new(Cell::new(acp::PromptCapabilities::default()));
321 let prevent_slash_commands = agent.clone().downcast::<ClaudeCode>().is_some();
322
323 let placeholder = if agent.name() == "Zed Agent" {
324 format!("Message the {} — @ to include context", agent.name())
325 } else {
326 format!("Message {} — @ to include context", agent.name())
327 };
328
329 let message_editor = cx.new(|cx| {
330 let mut editor = MessageEditor::new(
331 workspace.clone(),
332 project.clone(),
333 history_store.clone(),
334 prompt_store.clone(),
335 prompt_capabilities.clone(),
336 placeholder,
337 prevent_slash_commands,
338 editor::EditorMode::AutoHeight {
339 min_lines: MIN_EDITOR_LINES,
340 max_lines: Some(MAX_EDITOR_LINES),
341 },
342 window,
343 cx,
344 );
345 if let Some(entry) = summarize_thread {
346 editor.insert_thread_summary(entry, window, cx);
347 }
348 editor
349 });
350
351 let list_state = ListState::new(0, gpui::ListAlignment::Bottom, px(2048.0));
352
353 let entry_view_state = cx.new(|_| {
354 EntryViewState::new(
355 workspace.clone(),
356 project.clone(),
357 history_store.clone(),
358 prompt_store.clone(),
359 prompt_capabilities.clone(),
360 prevent_slash_commands,
361 )
362 });
363
364 let subscriptions = [
365 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
366 cx.subscribe_in(&message_editor, window, Self::handle_message_editor_event),
367 cx.subscribe_in(&entry_view_state, window, Self::handle_entry_view_event),
368 ];
369
370 Self {
371 agent: agent.clone(),
372 workspace: workspace.clone(),
373 project: project.clone(),
374 entry_view_state,
375 thread_state: Self::initial_state(agent, resume_thread, workspace, project, window, cx),
376 message_editor,
377 model_selector: None,
378 profile_selector: None,
379 notifications: Vec::new(),
380 notification_subscriptions: HashMap::default(),
381 list_state: list_state.clone(),
382 scrollbar_state: ScrollbarState::new(list_state).parent_entity(&cx.entity()),
383 thread_retry_status: None,
384 thread_error: None,
385 thread_feedback: Default::default(),
386 auth_task: None,
387 expanded_tool_calls: HashSet::default(),
388 expanded_thinking_blocks: HashSet::default(),
389 editing_message: None,
390 edits_expanded: false,
391 plan_expanded: false,
392 editor_expanded: false,
393 should_be_following: false,
394 history_store,
395 hovered_recent_history_item: None,
396 prompt_capabilities,
397 is_loading_contents: false,
398 _subscriptions: subscriptions,
399 _cancel_task: None,
400 focus_handle: cx.focus_handle(),
401 }
402 }
403
404 fn initial_state(
405 agent: Rc<dyn AgentServer>,
406 resume_thread: Option<DbThreadMetadata>,
407 workspace: WeakEntity<Workspace>,
408 project: Entity<Project>,
409 window: &mut Window,
410 cx: &mut Context<Self>,
411 ) -> ThreadState {
412 let root_dir = project
413 .read(cx)
414 .visible_worktrees(cx)
415 .next()
416 .map(|worktree| worktree.read(cx).abs_path())
417 .unwrap_or_else(|| paths::home_dir().as_path().into());
418 let (tx, mut rx) = watch::channel("Loading…".into());
419 let delegate = AgentServerDelegate::new(project.clone(), tx);
420
421 let connect_task = agent.connect(&root_dir, delegate, cx);
422 let load_task = cx.spawn_in(window, async move |this, cx| {
423 let connection = match connect_task.await {
424 Ok(connection) => connection,
425 Err(err) => {
426 this.update_in(cx, |this, window, cx| {
427 if err.downcast_ref::<LoadError>().is_some() {
428 this.handle_load_error(err, window, cx);
429 } else {
430 this.handle_thread_error(err, cx);
431 }
432 cx.notify();
433 })
434 .log_err();
435 return;
436 }
437 };
438
439 let result = if let Some(native_agent) = connection
440 .clone()
441 .downcast::<agent2::NativeAgentConnection>()
442 && let Some(resume) = resume_thread.clone()
443 {
444 cx.update(|_, cx| {
445 native_agent
446 .0
447 .update(cx, |agent, cx| agent.open_thread(resume.id, cx))
448 })
449 .log_err()
450 } else {
451 cx.update(|_, cx| {
452 connection
453 .clone()
454 .new_thread(project.clone(), &root_dir, cx)
455 })
456 .log_err()
457 };
458
459 let Some(result) = result else {
460 return;
461 };
462
463 let result = match result.await {
464 Err(e) => match e.downcast::<acp_thread::AuthRequired>() {
465 Ok(err) => {
466 cx.update(|window, cx| {
467 Self::handle_auth_required(this, err, agent, connection, window, cx)
468 })
469 .log_err();
470 return;
471 }
472 Err(err) => Err(err),
473 },
474 Ok(thread) => Ok(thread),
475 };
476
477 this.update_in(cx, |this, window, cx| {
478 match result {
479 Ok(thread) => {
480 let action_log = thread.read(cx).action_log().clone();
481
482 this.prompt_capabilities
483 .set(thread.read(cx).prompt_capabilities());
484
485 let count = thread.read(cx).entries().len();
486 this.entry_view_state.update(cx, |view_state, cx| {
487 for ix in 0..count {
488 view_state.sync_entry(ix, &thread, window, cx);
489 }
490 this.list_state.splice_focusable(
491 0..0,
492 (0..count).map(|ix| view_state.entry(ix)?.focus_handle(cx)),
493 );
494 });
495
496 if let Some(resume) = resume_thread {
497 this.history_store.update(cx, |history, cx| {
498 history.push_recently_opened_entry(
499 HistoryEntryId::AcpThread(resume.id),
500 cx,
501 );
502 });
503 }
504
505 AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
506
507 this.model_selector =
508 thread
509 .read(cx)
510 .connection()
511 .model_selector()
512 .map(|selector| {
513 cx.new(|cx| {
514 AcpModelSelectorPopover::new(
515 thread.read(cx).session_id().clone(),
516 selector,
517 PopoverMenuHandle::default(),
518 this.focus_handle(cx),
519 window,
520 cx,
521 )
522 })
523 });
524
525 let mut subscriptions = vec![
526 cx.subscribe_in(&thread, window, Self::handle_thread_event),
527 cx.observe(&action_log, |_, _, cx| cx.notify()),
528 ];
529
530 let title_editor =
531 if thread.update(cx, |thread, cx| thread.can_set_title(cx)) {
532 let editor = cx.new(|cx| {
533 let mut editor = Editor::single_line(window, cx);
534 editor.set_text(thread.read(cx).title(), window, cx);
535 editor
536 });
537 subscriptions.push(cx.subscribe_in(
538 &editor,
539 window,
540 Self::handle_title_editor_event,
541 ));
542 Some(editor)
543 } else {
544 None
545 };
546 this.thread_state = ThreadState::Ready {
547 thread,
548 title_editor,
549 _subscriptions: subscriptions,
550 };
551 this.message_editor.focus_handle(cx).focus(window);
552
553 this.profile_selector = this.as_native_thread(cx).map(|thread| {
554 cx.new(|cx| {
555 ProfileSelector::new(
556 <dyn Fs>::global(cx),
557 Arc::new(thread.clone()),
558 this.focus_handle(cx),
559 cx,
560 )
561 })
562 });
563
564 cx.notify();
565 }
566 Err(err) => {
567 this.handle_load_error(err, window, cx);
568 }
569 };
570 })
571 .log_err();
572 });
573
574 let loading_view = cx.new(|cx| {
575 let update_title_task = cx.spawn(async move |this, cx| {
576 loop {
577 let status = rx.recv().await?;
578 this.update(cx, |this: &mut LoadingView, cx| {
579 this.title = status;
580 cx.notify();
581 })?;
582 }
583 });
584
585 LoadingView {
586 title: "Loading…".into(),
587 _load_task: load_task,
588 _update_title_task: update_title_task,
589 }
590 });
591
592 ThreadState::Loading(loading_view)
593 }
594
595 fn handle_auth_required(
596 this: WeakEntity<Self>,
597 err: AuthRequired,
598 agent: Rc<dyn AgentServer>,
599 connection: Rc<dyn AgentConnection>,
600 window: &mut Window,
601 cx: &mut App,
602 ) {
603 let agent_name = agent.name();
604 let (configuration_view, subscription) = if let Some(provider_id) = err.provider_id {
605 let registry = LanguageModelRegistry::global(cx);
606
607 let sub = window.subscribe(®istry, cx, {
608 let provider_id = provider_id.clone();
609 let this = this.clone();
610 move |_, ev, window, cx| {
611 if let language_model::Event::ProviderStateChanged(updated_provider_id) = &ev
612 && &provider_id == updated_provider_id
613 {
614 this.update(cx, |this, cx| {
615 this.thread_state = Self::initial_state(
616 agent.clone(),
617 None,
618 this.workspace.clone(),
619 this.project.clone(),
620 window,
621 cx,
622 );
623 cx.notify();
624 })
625 .ok();
626 }
627 }
628 });
629
630 let view = registry.read(cx).provider(&provider_id).map(|provider| {
631 provider.configuration_view(
632 language_model::ConfigurationViewTargetAgent::Other(agent_name.clone()),
633 window,
634 cx,
635 )
636 });
637
638 (view, Some(sub))
639 } else {
640 (None, None)
641 };
642
643 this.update(cx, |this, cx| {
644 this.thread_state = ThreadState::Unauthenticated {
645 pending_auth_method: None,
646 connection,
647 configuration_view,
648 description: err
649 .description
650 .clone()
651 .map(|desc| cx.new(|cx| Markdown::new(desc.into(), None, None, cx))),
652 _subscription: subscription,
653 };
654 if this.message_editor.focus_handle(cx).is_focused(window) {
655 this.focus_handle.focus(window)
656 }
657 cx.notify();
658 })
659 .ok();
660 }
661
662 fn handle_load_error(
663 &mut self,
664 err: anyhow::Error,
665 window: &mut Window,
666 cx: &mut Context<Self>,
667 ) {
668 if let Some(load_err) = err.downcast_ref::<LoadError>() {
669 self.thread_state = ThreadState::LoadError(load_err.clone());
670 } else {
671 self.thread_state = ThreadState::LoadError(LoadError::Other(err.to_string().into()))
672 }
673 if self.message_editor.focus_handle(cx).is_focused(window) {
674 self.focus_handle.focus(window)
675 }
676 cx.notify();
677 }
678
679 pub fn workspace(&self) -> &WeakEntity<Workspace> {
680 &self.workspace
681 }
682
683 pub fn thread(&self) -> Option<&Entity<AcpThread>> {
684 match &self.thread_state {
685 ThreadState::Ready { thread, .. } => Some(thread),
686 ThreadState::Unauthenticated { .. }
687 | ThreadState::Loading { .. }
688 | ThreadState::LoadError { .. } => None,
689 }
690 }
691
692 pub fn title(&self, cx: &App) -> SharedString {
693 match &self.thread_state {
694 ThreadState::Ready { .. } | ThreadState::Unauthenticated { .. } => "New Thread".into(),
695 ThreadState::Loading(loading_view) => loading_view.read(cx).title.clone(),
696 ThreadState::LoadError(error) => match error {
697 LoadError::Unsupported { .. } => format!("Upgrade {}", self.agent.name()).into(),
698 LoadError::FailedToInstall(_) => {
699 format!("Failed to Install {}", self.agent.name()).into()
700 }
701 LoadError::Exited { .. } => format!("{} Exited", self.agent.name()).into(),
702 LoadError::Other(_) => format!("Error Loading {}", self.agent.name()).into(),
703 },
704 }
705 }
706
707 pub fn title_editor(&self) -> Option<Entity<Editor>> {
708 if let ThreadState::Ready { title_editor, .. } = &self.thread_state {
709 title_editor.clone()
710 } else {
711 None
712 }
713 }
714
715 pub fn cancel_generation(&mut self, cx: &mut Context<Self>) {
716 self.thread_error.take();
717 self.thread_retry_status.take();
718
719 if let Some(thread) = self.thread() {
720 self._cancel_task = Some(thread.update(cx, |thread, cx| thread.cancel(cx)));
721 }
722 }
723
724 pub fn expand_message_editor(
725 &mut self,
726 _: &ExpandMessageEditor,
727 _window: &mut Window,
728 cx: &mut Context<Self>,
729 ) {
730 self.set_editor_is_expanded(!self.editor_expanded, cx);
731 cx.notify();
732 }
733
734 fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
735 self.editor_expanded = is_expanded;
736 self.message_editor.update(cx, |editor, cx| {
737 if is_expanded {
738 editor.set_mode(
739 EditorMode::Full {
740 scale_ui_elements_with_buffer_font_size: false,
741 show_active_line_background: false,
742 sized_by_content: false,
743 },
744 cx,
745 )
746 } else {
747 editor.set_mode(
748 EditorMode::AutoHeight {
749 min_lines: MIN_EDITOR_LINES,
750 max_lines: Some(MAX_EDITOR_LINES),
751 },
752 cx,
753 )
754 }
755 });
756 cx.notify();
757 }
758
759 pub fn handle_title_editor_event(
760 &mut self,
761 title_editor: &Entity<Editor>,
762 event: &EditorEvent,
763 window: &mut Window,
764 cx: &mut Context<Self>,
765 ) {
766 let Some(thread) = self.thread() else { return };
767
768 match event {
769 EditorEvent::BufferEdited => {
770 let new_title = title_editor.read(cx).text(cx);
771 thread.update(cx, |thread, cx| {
772 thread
773 .set_title(new_title.into(), cx)
774 .detach_and_log_err(cx);
775 })
776 }
777 EditorEvent::Blurred => {
778 if title_editor.read(cx).text(cx).is_empty() {
779 title_editor.update(cx, |editor, cx| {
780 editor.set_text("New Thread", window, cx);
781 });
782 }
783 }
784 _ => {}
785 }
786 }
787
788 pub fn handle_message_editor_event(
789 &mut self,
790 _: &Entity<MessageEditor>,
791 event: &MessageEditorEvent,
792 window: &mut Window,
793 cx: &mut Context<Self>,
794 ) {
795 match event {
796 MessageEditorEvent::Send => self.send(window, cx),
797 MessageEditorEvent::Cancel => self.cancel_generation(cx),
798 MessageEditorEvent::Focus => {
799 self.cancel_editing(&Default::default(), window, cx);
800 }
801 MessageEditorEvent::LostFocus => {}
802 }
803 }
804
805 pub fn handle_entry_view_event(
806 &mut self,
807 _: &Entity<EntryViewState>,
808 event: &EntryViewEvent,
809 window: &mut Window,
810 cx: &mut Context<Self>,
811 ) {
812 match &event.view_event {
813 ViewEvent::NewDiff(tool_call_id) => {
814 if AgentSettings::get_global(cx).expand_edit_card {
815 self.expanded_tool_calls.insert(tool_call_id.clone());
816 }
817 }
818 ViewEvent::NewTerminal(tool_call_id) => {
819 if AgentSettings::get_global(cx).expand_terminal_card {
820 self.expanded_tool_calls.insert(tool_call_id.clone());
821 }
822 }
823 ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Focus) => {
824 if let Some(thread) = self.thread()
825 && let Some(AgentThreadEntry::UserMessage(user_message)) =
826 thread.read(cx).entries().get(event.entry_index)
827 && user_message.id.is_some()
828 {
829 self.editing_message = Some(event.entry_index);
830 cx.notify();
831 }
832 }
833 ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::LostFocus) => {
834 if let Some(thread) = self.thread()
835 && let Some(AgentThreadEntry::UserMessage(user_message)) =
836 thread.read(cx).entries().get(event.entry_index)
837 && user_message.id.is_some()
838 {
839 if editor.read(cx).text(cx).as_str() == user_message.content.to_markdown(cx) {
840 self.editing_message = None;
841 cx.notify();
842 }
843 }
844 }
845 ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::Send) => {
846 self.regenerate(event.entry_index, editor, window, cx);
847 }
848 ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Cancel) => {
849 self.cancel_editing(&Default::default(), window, cx);
850 }
851 }
852 }
853
854 fn resume_chat(&mut self, cx: &mut Context<Self>) {
855 self.thread_error.take();
856 let Some(thread) = self.thread() else {
857 return;
858 };
859 if !thread.read(cx).can_resume(cx) {
860 return;
861 }
862
863 let task = thread.update(cx, |thread, cx| thread.resume(cx));
864 cx.spawn(async move |this, cx| {
865 let result = task.await;
866
867 this.update(cx, |this, cx| {
868 if let Err(err) = result {
869 this.handle_thread_error(err, cx);
870 }
871 })
872 })
873 .detach();
874 }
875
876 fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
877 let Some(thread) = self.thread() else { return };
878
879 if self.is_loading_contents {
880 return;
881 }
882
883 self.history_store.update(cx, |history, cx| {
884 history.push_recently_opened_entry(
885 HistoryEntryId::AcpThread(thread.read(cx).session_id().clone()),
886 cx,
887 );
888 });
889
890 if thread.read(cx).status() != ThreadStatus::Idle {
891 self.stop_current_and_send_new_message(window, cx);
892 return;
893 }
894
895 let contents = self
896 .message_editor
897 .update(cx, |message_editor, cx| message_editor.contents(cx));
898 self.send_impl(contents, window, cx)
899 }
900
901 fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
902 let Some(thread) = self.thread().cloned() else {
903 return;
904 };
905
906 let cancelled = thread.update(cx, |thread, cx| thread.cancel(cx));
907
908 let contents = self
909 .message_editor
910 .update(cx, |message_editor, cx| message_editor.contents(cx));
911
912 cx.spawn_in(window, async move |this, cx| {
913 cancelled.await;
914
915 this.update_in(cx, |this, window, cx| {
916 this.send_impl(contents, window, cx);
917 })
918 .ok();
919 })
920 .detach();
921 }
922
923 fn send_impl(
924 &mut self,
925 contents: Task<anyhow::Result<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>>,
926 window: &mut Window,
927 cx: &mut Context<Self>,
928 ) {
929 let agent_telemetry_id = self.agent.telemetry_id();
930
931 self.thread_error.take();
932 self.editing_message.take();
933 self.thread_feedback.clear();
934
935 let Some(thread) = self.thread() else {
936 return;
937 };
938 let thread = thread.downgrade();
939 if self.should_be_following {
940 self.workspace
941 .update(cx, |workspace, cx| {
942 workspace.follow(CollaboratorId::Agent, window, cx);
943 })
944 .ok();
945 }
946
947 self.is_loading_contents = true;
948 let guard = cx.new(|_| ());
949 cx.observe_release(&guard, |this, _guard, cx| {
950 this.is_loading_contents = false;
951 cx.notify();
952 })
953 .detach();
954
955 let task = cx.spawn_in(window, async move |this, cx| {
956 let (contents, tracked_buffers) = contents.await?;
957
958 if contents.is_empty() {
959 return Ok(());
960 }
961
962 this.update_in(cx, |this, window, cx| {
963 this.set_editor_is_expanded(false, cx);
964 this.scroll_to_bottom(cx);
965 this.message_editor.update(cx, |message_editor, cx| {
966 message_editor.clear(window, cx);
967 });
968 })?;
969 let send = thread.update(cx, |thread, cx| {
970 thread.action_log().update(cx, |action_log, cx| {
971 for buffer in tracked_buffers {
972 action_log.buffer_read(buffer, cx)
973 }
974 });
975 drop(guard);
976
977 telemetry::event!("Agent Message Sent", agent = agent_telemetry_id);
978
979 thread.send(contents, cx)
980 })?;
981 send.await
982 });
983
984 cx.spawn(async move |this, cx| {
985 if let Err(err) = task.await {
986 this.update(cx, |this, cx| {
987 this.handle_thread_error(err, cx);
988 })
989 .ok();
990 } else {
991 this.update(cx, |this, cx| {
992 this.should_be_following = this
993 .workspace
994 .update(cx, |workspace, _| {
995 workspace.is_being_followed(CollaboratorId::Agent)
996 })
997 .unwrap_or_default();
998 })
999 .ok();
1000 }
1001 })
1002 .detach();
1003 }
1004
1005 fn cancel_editing(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1006 let Some(thread) = self.thread().cloned() else {
1007 return;
1008 };
1009
1010 if let Some(index) = self.editing_message.take()
1011 && let Some(editor) = self
1012 .entry_view_state
1013 .read(cx)
1014 .entry(index)
1015 .and_then(|e| e.message_editor())
1016 .cloned()
1017 {
1018 editor.update(cx, |editor, cx| {
1019 if let Some(user_message) = thread
1020 .read(cx)
1021 .entries()
1022 .get(index)
1023 .and_then(|e| e.user_message())
1024 {
1025 editor.set_message(user_message.chunks.clone(), window, cx);
1026 }
1027 })
1028 };
1029 self.focus_handle(cx).focus(window);
1030 cx.notify();
1031 }
1032
1033 fn regenerate(
1034 &mut self,
1035 entry_ix: usize,
1036 message_editor: &Entity<MessageEditor>,
1037 window: &mut Window,
1038 cx: &mut Context<Self>,
1039 ) {
1040 let Some(thread) = self.thread().cloned() else {
1041 return;
1042 };
1043 if self.is_loading_contents {
1044 return;
1045 }
1046
1047 let Some(user_message_id) = thread.update(cx, |thread, _| {
1048 thread.entries().get(entry_ix)?.user_message()?.id.clone()
1049 }) else {
1050 return;
1051 };
1052
1053 let contents = message_editor.update(cx, |message_editor, cx| message_editor.contents(cx));
1054
1055 let task = cx.spawn(async move |_, cx| {
1056 let contents = contents.await?;
1057 thread
1058 .update(cx, |thread, cx| thread.rewind(user_message_id, cx))?
1059 .await?;
1060 Ok(contents)
1061 });
1062 self.send_impl(task, window, cx);
1063 }
1064
1065 fn open_agent_diff(&mut self, _: &OpenAgentDiff, window: &mut Window, cx: &mut Context<Self>) {
1066 if let Some(thread) = self.thread() {
1067 AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err();
1068 }
1069 }
1070
1071 fn open_edited_buffer(
1072 &mut self,
1073 buffer: &Entity<Buffer>,
1074 window: &mut Window,
1075 cx: &mut Context<Self>,
1076 ) {
1077 let Some(thread) = self.thread() else {
1078 return;
1079 };
1080
1081 let Some(diff) =
1082 AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
1083 else {
1084 return;
1085 };
1086
1087 diff.update(cx, |diff, cx| {
1088 diff.move_to_path(PathKey::for_buffer(buffer, cx), window, cx)
1089 })
1090 }
1091
1092 fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1093 let Some(thread) = self.as_native_thread(cx) else {
1094 return;
1095 };
1096 let project_context = thread.read(cx).project_context().read(cx);
1097
1098 let project_entry_ids = project_context
1099 .worktrees
1100 .iter()
1101 .flat_map(|worktree| worktree.rules_file.as_ref())
1102 .map(|rules_file| ProjectEntryId::from_usize(rules_file.project_entry_id))
1103 .collect::<Vec<_>>();
1104
1105 self.workspace
1106 .update(cx, move |workspace, cx| {
1107 // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
1108 // files clear. For example, if rules file 1 is already open but rules file 2 is not,
1109 // this would open and focus rules file 2 in a tab that is not next to rules file 1.
1110 let project = workspace.project().read(cx);
1111 let project_paths = project_entry_ids
1112 .into_iter()
1113 .flat_map(|entry_id| project.path_for_entry(entry_id, cx))
1114 .collect::<Vec<_>>();
1115 for project_path in project_paths {
1116 workspace
1117 .open_path(project_path, None, true, window, cx)
1118 .detach_and_log_err(cx);
1119 }
1120 })
1121 .ok();
1122 }
1123
1124 fn handle_thread_error(&mut self, error: anyhow::Error, cx: &mut Context<Self>) {
1125 self.thread_error = Some(ThreadError::from_err(error, &self.agent));
1126 cx.notify();
1127 }
1128
1129 fn clear_thread_error(&mut self, cx: &mut Context<Self>) {
1130 self.thread_error = None;
1131 cx.notify();
1132 }
1133
1134 fn handle_thread_event(
1135 &mut self,
1136 thread: &Entity<AcpThread>,
1137 event: &AcpThreadEvent,
1138 window: &mut Window,
1139 cx: &mut Context<Self>,
1140 ) {
1141 match event {
1142 AcpThreadEvent::NewEntry => {
1143 let len = thread.read(cx).entries().len();
1144 let index = len - 1;
1145 self.entry_view_state.update(cx, |view_state, cx| {
1146 view_state.sync_entry(index, thread, window, cx);
1147 self.list_state.splice_focusable(
1148 index..index,
1149 [view_state
1150 .entry(index)
1151 .and_then(|entry| entry.focus_handle(cx))],
1152 );
1153 });
1154 }
1155 AcpThreadEvent::EntryUpdated(index) => {
1156 self.entry_view_state.update(cx, |view_state, cx| {
1157 view_state.sync_entry(*index, thread, window, cx)
1158 });
1159 }
1160 AcpThreadEvent::EntriesRemoved(range) => {
1161 self.entry_view_state
1162 .update(cx, |view_state, _cx| view_state.remove(range.clone()));
1163 self.list_state.splice(range.clone(), 0);
1164 }
1165 AcpThreadEvent::ToolAuthorizationRequired => {
1166 self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
1167 }
1168 AcpThreadEvent::Retry(retry) => {
1169 self.thread_retry_status = Some(retry.clone());
1170 }
1171 AcpThreadEvent::Stopped => {
1172 self.thread_retry_status.take();
1173 let used_tools = thread.read(cx).used_tools_since_last_user_message();
1174 self.notify_with_sound(
1175 if used_tools {
1176 "Finished running tools"
1177 } else {
1178 "New message"
1179 },
1180 IconName::ZedAssistant,
1181 window,
1182 cx,
1183 );
1184 }
1185 AcpThreadEvent::Error => {
1186 self.thread_retry_status.take();
1187 self.notify_with_sound(
1188 "Agent stopped due to an error",
1189 IconName::Warning,
1190 window,
1191 cx,
1192 );
1193 }
1194 AcpThreadEvent::LoadError(error) => {
1195 self.thread_retry_status.take();
1196 self.thread_state = ThreadState::LoadError(error.clone());
1197 if self.message_editor.focus_handle(cx).is_focused(window) {
1198 self.focus_handle.focus(window)
1199 }
1200 }
1201 AcpThreadEvent::TitleUpdated => {
1202 let title = thread.read(cx).title();
1203 if let Some(title_editor) = self.title_editor() {
1204 title_editor.update(cx, |editor, cx| {
1205 if editor.text(cx) != title {
1206 editor.set_text(title, window, cx);
1207 }
1208 });
1209 }
1210 }
1211 AcpThreadEvent::PromptCapabilitiesUpdated => {
1212 self.prompt_capabilities
1213 .set(thread.read(cx).prompt_capabilities());
1214 }
1215 AcpThreadEvent::TokenUsageUpdated => {}
1216 }
1217 cx.notify();
1218 }
1219
1220 fn authenticate(
1221 &mut self,
1222 method: acp::AuthMethodId,
1223 window: &mut Window,
1224 cx: &mut Context<Self>,
1225 ) {
1226 let ThreadState::Unauthenticated {
1227 connection,
1228 pending_auth_method,
1229 configuration_view,
1230 ..
1231 } = &mut self.thread_state
1232 else {
1233 return;
1234 };
1235
1236 if method.0.as_ref() == "gemini-api-key" {
1237 let registry = LanguageModelRegistry::global(cx);
1238 let provider = registry
1239 .read(cx)
1240 .provider(&language_model::GOOGLE_PROVIDER_ID)
1241 .unwrap();
1242 if !provider.is_authenticated(cx) {
1243 let this = cx.weak_entity();
1244 let agent = self.agent.clone();
1245 let connection = connection.clone();
1246 window.defer(cx, |window, cx| {
1247 Self::handle_auth_required(
1248 this,
1249 AuthRequired {
1250 description: Some("GEMINI_API_KEY must be set".to_owned()),
1251 provider_id: Some(language_model::GOOGLE_PROVIDER_ID),
1252 },
1253 agent,
1254 connection,
1255 window,
1256 cx,
1257 );
1258 });
1259 return;
1260 }
1261 } else if method.0.as_ref() == "vertex-ai"
1262 && std::env::var("GOOGLE_API_KEY").is_err()
1263 && (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()
1264 || (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()))
1265 {
1266 let this = cx.weak_entity();
1267 let agent = self.agent.clone();
1268 let connection = connection.clone();
1269
1270 window.defer(cx, |window, cx| {
1271 Self::handle_auth_required(
1272 this,
1273 AuthRequired {
1274 description: Some(
1275 "GOOGLE_API_KEY must be set in the environment to use Vertex AI authentication for Gemini CLI. Please export it and restart Zed."
1276 .to_owned(),
1277 ),
1278 provider_id: None,
1279 },
1280 agent,
1281 connection,
1282 window,
1283 cx,
1284 )
1285 });
1286 return;
1287 }
1288
1289 self.thread_error.take();
1290 configuration_view.take();
1291 pending_auth_method.replace(method.clone());
1292 let authenticate = connection.authenticate(method, cx);
1293 cx.notify();
1294 self.auth_task =
1295 Some(cx.spawn_in(window, {
1296 let project = self.project.clone();
1297 let agent = self.agent.clone();
1298 async move |this, cx| {
1299 let result = authenticate.await;
1300
1301 match &result {
1302 Ok(_) => telemetry::event!(
1303 "Authenticate Agent Succeeded",
1304 agent = agent.telemetry_id()
1305 ),
1306 Err(_) => {
1307 telemetry::event!(
1308 "Authenticate Agent Failed",
1309 agent = agent.telemetry_id(),
1310 )
1311 }
1312 }
1313
1314 this.update_in(cx, |this, window, cx| {
1315 if let Err(err) = result {
1316 this.handle_thread_error(err, cx);
1317 } else {
1318 this.thread_state = Self::initial_state(
1319 agent,
1320 None,
1321 this.workspace.clone(),
1322 project.clone(),
1323 window,
1324 cx,
1325 )
1326 }
1327 this.auth_task.take()
1328 })
1329 .ok();
1330 }
1331 }));
1332 }
1333
1334 fn authorize_tool_call(
1335 &mut self,
1336 tool_call_id: acp::ToolCallId,
1337 option_id: acp::PermissionOptionId,
1338 option_kind: acp::PermissionOptionKind,
1339 window: &mut Window,
1340 cx: &mut Context<Self>,
1341 ) {
1342 let Some(thread) = self.thread() else {
1343 return;
1344 };
1345 thread.update(cx, |thread, cx| {
1346 thread.authorize_tool_call(tool_call_id, option_id, option_kind, cx);
1347 });
1348 if self.should_be_following {
1349 self.workspace
1350 .update(cx, |workspace, cx| {
1351 workspace.follow(CollaboratorId::Agent, window, cx);
1352 })
1353 .ok();
1354 }
1355 cx.notify();
1356 }
1357
1358 fn rewind(&mut self, message_id: &UserMessageId, cx: &mut Context<Self>) {
1359 let Some(thread) = self.thread() else {
1360 return;
1361 };
1362 thread
1363 .update(cx, |thread, cx| thread.rewind(message_id.clone(), cx))
1364 .detach_and_log_err(cx);
1365 cx.notify();
1366 }
1367
1368 fn render_entry(
1369 &self,
1370 entry_ix: usize,
1371 total_entries: usize,
1372 entry: &AgentThreadEntry,
1373 window: &mut Window,
1374 cx: &Context<Self>,
1375 ) -> AnyElement {
1376 let primary = match &entry {
1377 AgentThreadEntry::UserMessage(message) => {
1378 let Some(editor) = self
1379 .entry_view_state
1380 .read(cx)
1381 .entry(entry_ix)
1382 .and_then(|entry| entry.message_editor())
1383 .cloned()
1384 else {
1385 return Empty.into_any_element();
1386 };
1387
1388 let editing = self.editing_message == Some(entry_ix);
1389 let editor_focus = editor.focus_handle(cx).is_focused(window);
1390 let focus_border = cx.theme().colors().border_focused;
1391
1392 let rules_item = if entry_ix == 0 {
1393 self.render_rules_item(cx)
1394 } else {
1395 None
1396 };
1397
1398 let has_checkpoint_button = message
1399 .checkpoint
1400 .as_ref()
1401 .is_some_and(|checkpoint| checkpoint.show);
1402
1403 let agent_name = self.agent.name();
1404
1405 v_flex()
1406 .id(("user_message", entry_ix))
1407 .map(|this| {
1408 if entry_ix == 0 && !has_checkpoint_button && rules_item.is_none() {
1409 this.pt(rems_from_px(18.))
1410 } else if rules_item.is_some() {
1411 this.pt_3()
1412 } else {
1413 this.pt_2()
1414 }
1415 })
1416 .pb_3()
1417 .px_2()
1418 .gap_1p5()
1419 .w_full()
1420 .children(rules_item)
1421 .children(message.id.clone().and_then(|message_id| {
1422 message.checkpoint.as_ref()?.show.then(|| {
1423 h_flex()
1424 .px_3()
1425 .gap_2()
1426 .child(Divider::horizontal())
1427 .child(
1428 Button::new("restore-checkpoint", "Restore Checkpoint")
1429 .icon(IconName::Undo)
1430 .icon_size(IconSize::XSmall)
1431 .icon_position(IconPosition::Start)
1432 .label_size(LabelSize::XSmall)
1433 .icon_color(Color::Muted)
1434 .color(Color::Muted)
1435 .on_click(cx.listener(move |this, _, _window, cx| {
1436 this.rewind(&message_id, cx);
1437 }))
1438 )
1439 .child(Divider::horizontal())
1440 })
1441 }))
1442 .child(
1443 div()
1444 .relative()
1445 .child(
1446 div()
1447 .py_3()
1448 .px_2()
1449 .rounded_md()
1450 .shadow_md()
1451 .bg(cx.theme().colors().editor_background)
1452 .border_1()
1453 .when(editing && !editor_focus, |this| this.border_dashed())
1454 .border_color(cx.theme().colors().border)
1455 .map(|this|{
1456 if editing && editor_focus {
1457 this.border_color(focus_border)
1458 } else if message.id.is_some() {
1459 this.hover(|s| s.border_color(focus_border.opacity(0.8)))
1460 } else {
1461 this
1462 }
1463 })
1464 .text_xs()
1465 .child(editor.clone().into_any_element()),
1466 )
1467 .when(editor_focus, |this| {
1468 let base_container = h_flex()
1469 .absolute()
1470 .top_neg_3p5()
1471 .right_3()
1472 .gap_1()
1473 .rounded_sm()
1474 .border_1()
1475 .border_color(cx.theme().colors().border)
1476 .bg(cx.theme().colors().editor_background)
1477 .overflow_hidden();
1478
1479 if message.id.is_some() {
1480 this.child(
1481 base_container
1482 .child(
1483 IconButton::new("cancel", IconName::Close)
1484 .disabled(self.is_loading_contents)
1485 .icon_color(Color::Error)
1486 .icon_size(IconSize::XSmall)
1487 .on_click(cx.listener(Self::cancel_editing))
1488 )
1489 .child(
1490 if self.is_loading_contents {
1491 div()
1492 .id("loading-edited-message-content")
1493 .tooltip(Tooltip::text("Loading Added Context…"))
1494 .child(loading_contents_spinner(IconSize::XSmall))
1495 .into_any_element()
1496 } else {
1497 IconButton::new("regenerate", IconName::Return)
1498 .icon_color(Color::Muted)
1499 .icon_size(IconSize::XSmall)
1500 .tooltip(Tooltip::text(
1501 "Editing will restart the thread from this point."
1502 ))
1503 .on_click(cx.listener({
1504 let editor = editor.clone();
1505 move |this, _, window, cx| {
1506 this.regenerate(
1507 entry_ix, &editor, window, cx,
1508 );
1509 }
1510 })).into_any_element()
1511 }
1512 )
1513 )
1514 } else {
1515 this.child(
1516 base_container
1517 .border_dashed()
1518 .child(
1519 IconButton::new("editing_unavailable", IconName::PencilUnavailable)
1520 .icon_size(IconSize::Small)
1521 .icon_color(Color::Muted)
1522 .style(ButtonStyle::Transparent)
1523 .tooltip(move |_window, cx| {
1524 cx.new(|_| UnavailableEditingTooltip::new(agent_name.clone()))
1525 .into()
1526 })
1527 )
1528 )
1529 }
1530 }),
1531 )
1532 .into_any()
1533 }
1534 AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) => {
1535 let is_last = entry_ix + 1 == total_entries;
1536
1537 let style = default_markdown_style(false, false, window, cx);
1538 let message_body = v_flex()
1539 .w_full()
1540 .gap_3()
1541 .children(chunks.iter().enumerate().filter_map(
1542 |(chunk_ix, chunk)| match chunk {
1543 AssistantMessageChunk::Message { block } => {
1544 block.markdown().map(|md| {
1545 self.render_markdown(md.clone(), style.clone())
1546 .into_any_element()
1547 })
1548 }
1549 AssistantMessageChunk::Thought { block } => {
1550 block.markdown().map(|md| {
1551 self.render_thinking_block(
1552 entry_ix,
1553 chunk_ix,
1554 md.clone(),
1555 window,
1556 cx,
1557 )
1558 .into_any_element()
1559 })
1560 }
1561 },
1562 ))
1563 .into_any();
1564
1565 v_flex()
1566 .px_5()
1567 .py_1p5()
1568 .when(is_last, |this| this.pb_4())
1569 .w_full()
1570 .text_ui(cx)
1571 .child(message_body)
1572 .into_any()
1573 }
1574 AgentThreadEntry::ToolCall(tool_call) => {
1575 let has_terminals = tool_call.terminals().next().is_some();
1576
1577 div().w_full().map(|this| {
1578 if has_terminals {
1579 this.children(tool_call.terminals().map(|terminal| {
1580 self.render_terminal_tool_call(
1581 entry_ix, terminal, tool_call, window, cx,
1582 )
1583 }))
1584 } else {
1585 this.child(self.render_tool_call(entry_ix, tool_call, window, cx))
1586 }
1587 })
1588 }
1589 .into_any(),
1590 };
1591
1592 let Some(thread) = self.thread() else {
1593 return primary;
1594 };
1595
1596 let primary = if entry_ix == total_entries - 1 {
1597 v_flex()
1598 .w_full()
1599 .child(primary)
1600 .child(self.render_thread_controls(&thread, cx))
1601 .when_some(
1602 self.thread_feedback.comments_editor.clone(),
1603 |this, editor| this.child(Self::render_feedback_feedback_editor(editor, cx)),
1604 )
1605 .into_any_element()
1606 } else {
1607 primary
1608 };
1609
1610 if let Some(editing_index) = self.editing_message.as_ref()
1611 && *editing_index < entry_ix
1612 {
1613 let backdrop = div()
1614 .id(("backdrop", entry_ix))
1615 .size_full()
1616 .absolute()
1617 .inset_0()
1618 .bg(cx.theme().colors().panel_background)
1619 .opacity(0.8)
1620 .block_mouse_except_scroll()
1621 .on_click(cx.listener(Self::cancel_editing));
1622
1623 div()
1624 .relative()
1625 .child(primary)
1626 .child(backdrop)
1627 .into_any_element()
1628 } else {
1629 primary
1630 }
1631 }
1632
1633 fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
1634 cx.theme()
1635 .colors()
1636 .element_background
1637 .blend(cx.theme().colors().editor_foreground.opacity(0.025))
1638 }
1639
1640 fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
1641 cx.theme().colors().border.opacity(0.8)
1642 }
1643
1644 fn tool_name_font_size(&self) -> Rems {
1645 rems_from_px(13.)
1646 }
1647
1648 fn render_thinking_block(
1649 &self,
1650 entry_ix: usize,
1651 chunk_ix: usize,
1652 chunk: Entity<Markdown>,
1653 window: &Window,
1654 cx: &Context<Self>,
1655 ) -> AnyElement {
1656 let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
1657 let card_header_id = SharedString::from("inner-card-header");
1658
1659 let key = (entry_ix, chunk_ix);
1660
1661 let is_open = self.expanded_thinking_blocks.contains(&key);
1662
1663 let scroll_handle = self
1664 .entry_view_state
1665 .read(cx)
1666 .entry(entry_ix)
1667 .and_then(|entry| entry.scroll_handle_for_assistant_message_chunk(chunk_ix));
1668
1669 let thinking_content = {
1670 div()
1671 .id(("thinking-content", chunk_ix))
1672 .when_some(scroll_handle, |this, scroll_handle| {
1673 this.track_scroll(&scroll_handle)
1674 })
1675 .text_ui_sm(cx)
1676 .overflow_hidden()
1677 .child(
1678 self.render_markdown(chunk, default_markdown_style(false, false, window, cx)),
1679 )
1680 };
1681
1682 v_flex()
1683 .gap_1()
1684 .child(
1685 h_flex()
1686 .id(header_id)
1687 .group(&card_header_id)
1688 .relative()
1689 .w_full()
1690 .pr_1()
1691 .justify_between()
1692 .child(
1693 h_flex()
1694 .h(window.line_height() - px(2.))
1695 .gap_1p5()
1696 .overflow_hidden()
1697 .child(
1698 Icon::new(IconName::ToolThink)
1699 .size(IconSize::Small)
1700 .color(Color::Muted),
1701 )
1702 .child(
1703 div()
1704 .text_size(self.tool_name_font_size())
1705 .text_color(cx.theme().colors().text_muted)
1706 .child("Thinking"),
1707 ),
1708 )
1709 .child(
1710 Disclosure::new(("expand", entry_ix), is_open)
1711 .opened_icon(IconName::ChevronUp)
1712 .closed_icon(IconName::ChevronDown)
1713 .visible_on_hover(&card_header_id)
1714 .on_click(cx.listener({
1715 move |this, _event, _window, cx| {
1716 if is_open {
1717 this.expanded_thinking_blocks.remove(&key);
1718 } else {
1719 this.expanded_thinking_blocks.insert(key);
1720 }
1721 cx.notify();
1722 }
1723 })),
1724 )
1725 .on_click(cx.listener({
1726 move |this, _event, _window, cx| {
1727 if is_open {
1728 this.expanded_thinking_blocks.remove(&key);
1729 } else {
1730 this.expanded_thinking_blocks.insert(key);
1731 }
1732 cx.notify();
1733 }
1734 })),
1735 )
1736 .when(is_open, |this| {
1737 this.child(
1738 div()
1739 .ml_1p5()
1740 .pl_3p5()
1741 .border_l_1()
1742 .border_color(self.tool_card_border_color(cx))
1743 .child(thinking_content),
1744 )
1745 })
1746 .into_any_element()
1747 }
1748
1749 fn render_tool_call(
1750 &self,
1751 entry_ix: usize,
1752 tool_call: &ToolCall,
1753 window: &Window,
1754 cx: &Context<Self>,
1755 ) -> Div {
1756 let card_header_id = SharedString::from("inner-tool-call-header");
1757
1758 let tool_icon =
1759 if tool_call.kind == acp::ToolKind::Edit && tool_call.locations.len() == 1 {
1760 FileIcons::get_icon(&tool_call.locations[0].path, cx)
1761 .map(Icon::from_path)
1762 .unwrap_or(Icon::new(IconName::ToolPencil))
1763 } else {
1764 Icon::new(match tool_call.kind {
1765 acp::ToolKind::Read => IconName::ToolSearch,
1766 acp::ToolKind::Edit => IconName::ToolPencil,
1767 acp::ToolKind::Delete => IconName::ToolDeleteFile,
1768 acp::ToolKind::Move => IconName::ArrowRightLeft,
1769 acp::ToolKind::Search => IconName::ToolSearch,
1770 acp::ToolKind::Execute => IconName::ToolTerminal,
1771 acp::ToolKind::Think => IconName::ToolThink,
1772 acp::ToolKind::Fetch => IconName::ToolWeb,
1773 acp::ToolKind::Other => IconName::ToolHammer,
1774 })
1775 }
1776 .size(IconSize::Small)
1777 .color(Color::Muted);
1778
1779 let failed_or_canceled = match &tool_call.status {
1780 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed => true,
1781 _ => false,
1782 };
1783
1784 let has_location = tool_call.locations.len() == 1;
1785 let needs_confirmation = matches!(
1786 tool_call.status,
1787 ToolCallStatus::WaitingForConfirmation { .. }
1788 );
1789 let is_edit =
1790 matches!(tool_call.kind, acp::ToolKind::Edit) || tool_call.diffs().next().is_some();
1791 let use_card_layout = needs_confirmation || is_edit;
1792
1793 let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
1794
1795 let is_open = needs_confirmation || self.expanded_tool_calls.contains(&tool_call.id);
1796
1797 let gradient_overlay = {
1798 div()
1799 .absolute()
1800 .top_0()
1801 .right_0()
1802 .w_12()
1803 .h_full()
1804 .map(|this| {
1805 if use_card_layout {
1806 this.bg(linear_gradient(
1807 90.,
1808 linear_color_stop(self.tool_card_header_bg(cx), 1.),
1809 linear_color_stop(self.tool_card_header_bg(cx).opacity(0.2), 0.),
1810 ))
1811 } else {
1812 this.bg(linear_gradient(
1813 90.,
1814 linear_color_stop(cx.theme().colors().panel_background, 1.),
1815 linear_color_stop(
1816 cx.theme().colors().panel_background.opacity(0.2),
1817 0.,
1818 ),
1819 ))
1820 }
1821 })
1822 };
1823
1824 let tool_output_display = if is_open {
1825 match &tool_call.status {
1826 ToolCallStatus::WaitingForConfirmation { options, .. } => v_flex()
1827 .w_full()
1828 .children(tool_call.content.iter().map(|content| {
1829 div()
1830 .child(self.render_tool_call_content(
1831 entry_ix,
1832 content,
1833 tool_call,
1834 use_card_layout,
1835 window,
1836 cx,
1837 ))
1838 .into_any_element()
1839 }))
1840 .child(self.render_permission_buttons(
1841 options,
1842 entry_ix,
1843 tool_call.id.clone(),
1844 cx,
1845 ))
1846 .into_any(),
1847 ToolCallStatus::Pending | ToolCallStatus::InProgress
1848 if is_edit
1849 && tool_call.content.is_empty()
1850 && self.as_native_connection(cx).is_some() =>
1851 {
1852 self.render_diff_loading(cx).into_any()
1853 }
1854 ToolCallStatus::Pending
1855 | ToolCallStatus::InProgress
1856 | ToolCallStatus::Completed
1857 | ToolCallStatus::Failed
1858 | ToolCallStatus::Canceled => v_flex()
1859 .w_full()
1860 .children(tool_call.content.iter().map(|content| {
1861 div().child(self.render_tool_call_content(
1862 entry_ix,
1863 content,
1864 tool_call,
1865 use_card_layout,
1866 window,
1867 cx,
1868 ))
1869 }))
1870 .into_any(),
1871 ToolCallStatus::Rejected => Empty.into_any(),
1872 }
1873 .into()
1874 } else {
1875 None
1876 };
1877
1878 v_flex()
1879 .map(|this| {
1880 if use_card_layout {
1881 this.my_1p5()
1882 .rounded_md()
1883 .border_1()
1884 .border_color(self.tool_card_border_color(cx))
1885 .bg(cx.theme().colors().editor_background)
1886 .overflow_hidden()
1887 } else {
1888 this.my_1()
1889 }
1890 })
1891 .map(|this| {
1892 if has_location && !use_card_layout {
1893 this.ml_4()
1894 } else {
1895 this.ml_5()
1896 }
1897 })
1898 .mr_5()
1899 .child(
1900 h_flex()
1901 .group(&card_header_id)
1902 .relative()
1903 .w_full()
1904 .gap_1()
1905 .justify_between()
1906 .when(use_card_layout, |this| {
1907 this.p_0p5()
1908 .rounded_t(rems_from_px(5.))
1909 .bg(self.tool_card_header_bg(cx))
1910 })
1911 .child(
1912 h_flex()
1913 .relative()
1914 .w_full()
1915 .h(window.line_height() - px(2.))
1916 .text_size(self.tool_name_font_size())
1917 .gap_1p5()
1918 .when(has_location || use_card_layout, |this| this.px_1())
1919 .when(has_location, |this| {
1920 this.cursor(CursorStyle::PointingHand)
1921 .rounded(rems_from_px(3.)) // Concentric border radius
1922 .hover(|s| s.bg(cx.theme().colors().element_hover.opacity(0.5)))
1923 })
1924 .overflow_hidden()
1925 .child(tool_icon)
1926 .child(if has_location {
1927 let name = tool_call.locations[0]
1928 .path
1929 .file_name()
1930 .unwrap_or_default()
1931 .display()
1932 .to_string();
1933
1934 h_flex()
1935 .id(("open-tool-call-location", entry_ix))
1936 .w_full()
1937 .map(|this| {
1938 if use_card_layout {
1939 this.text_color(cx.theme().colors().text)
1940 } else {
1941 this.text_color(cx.theme().colors().text_muted)
1942 }
1943 })
1944 .child(name)
1945 .tooltip(Tooltip::text("Jump to File"))
1946 .on_click(cx.listener(move |this, _, window, cx| {
1947 this.open_tool_call_location(entry_ix, 0, window, cx);
1948 }))
1949 .into_any_element()
1950 } else {
1951 h_flex()
1952 .w_full()
1953 .child(self.render_markdown(
1954 tool_call.label.clone(),
1955 default_markdown_style(false, true, window, cx),
1956 ))
1957 .into_any()
1958 })
1959 .when(!has_location, |this| this.child(gradient_overlay)),
1960 )
1961 .when(is_collapsible || failed_or_canceled, |this| {
1962 this.child(
1963 h_flex()
1964 .px_1()
1965 .gap_px()
1966 .when(is_collapsible, |this| {
1967 this.child(
1968 Disclosure::new(("expand", entry_ix), is_open)
1969 .opened_icon(IconName::ChevronUp)
1970 .closed_icon(IconName::ChevronDown)
1971 .visible_on_hover(&card_header_id)
1972 .on_click(cx.listener({
1973 let id = tool_call.id.clone();
1974 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1975 if is_open {
1976 this.expanded_tool_calls.remove(&id);
1977 } else {
1978 this.expanded_tool_calls.insert(id.clone());
1979 }
1980 cx.notify();
1981 }
1982 })),
1983 )
1984 })
1985 .when(failed_or_canceled, |this| {
1986 this.child(
1987 Icon::new(IconName::Close)
1988 .color(Color::Error)
1989 .size(IconSize::Small),
1990 )
1991 }),
1992 )
1993 }),
1994 )
1995 .children(tool_output_display)
1996 }
1997
1998 fn render_tool_call_content(
1999 &self,
2000 entry_ix: usize,
2001 content: &ToolCallContent,
2002 tool_call: &ToolCall,
2003 card_layout: bool,
2004 window: &Window,
2005 cx: &Context<Self>,
2006 ) -> AnyElement {
2007 match content {
2008 ToolCallContent::ContentBlock(content) => {
2009 if let Some(resource_link) = content.resource_link() {
2010 self.render_resource_link(resource_link, cx)
2011 } else if let Some(markdown) = content.markdown() {
2012 self.render_markdown_output(
2013 markdown.clone(),
2014 tool_call.id.clone(),
2015 card_layout,
2016 window,
2017 cx,
2018 )
2019 } else {
2020 Empty.into_any_element()
2021 }
2022 }
2023 ToolCallContent::Diff(diff) => self.render_diff_editor(entry_ix, diff, tool_call, cx),
2024 ToolCallContent::Terminal(terminal) => {
2025 self.render_terminal_tool_call(entry_ix, terminal, tool_call, window, cx)
2026 }
2027 }
2028 }
2029
2030 fn render_markdown_output(
2031 &self,
2032 markdown: Entity<Markdown>,
2033 tool_call_id: acp::ToolCallId,
2034 card_layout: bool,
2035 window: &Window,
2036 cx: &Context<Self>,
2037 ) -> AnyElement {
2038 let button_id = SharedString::from(format!("tool_output-{:?}", tool_call_id));
2039
2040 v_flex()
2041 .mt_1p5()
2042 .gap_2()
2043 .when(!card_layout, |this| {
2044 this.ml(rems(0.4))
2045 .px_3p5()
2046 .border_l_1()
2047 .border_color(self.tool_card_border_color(cx))
2048 })
2049 .when(card_layout, |this| {
2050 this.p_2()
2051 .border_t_1()
2052 .border_color(self.tool_card_border_color(cx))
2053 })
2054 .text_sm()
2055 .text_color(cx.theme().colors().text_muted)
2056 .child(self.render_markdown(markdown, default_markdown_style(false, false, window, cx)))
2057 .when(!card_layout, |this| {
2058 this.child(
2059 IconButton::new(button_id, IconName::ChevronUp)
2060 .full_width()
2061 .style(ButtonStyle::Outlined)
2062 .icon_color(Color::Muted)
2063 .on_click(cx.listener({
2064 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
2065 this.expanded_tool_calls.remove(&tool_call_id);
2066 cx.notify();
2067 }
2068 })),
2069 )
2070 })
2071 .into_any_element()
2072 }
2073
2074 fn render_resource_link(
2075 &self,
2076 resource_link: &acp::ResourceLink,
2077 cx: &Context<Self>,
2078 ) -> AnyElement {
2079 let uri: SharedString = resource_link.uri.clone().into();
2080 let is_file = resource_link.uri.strip_prefix("file://");
2081
2082 let label: SharedString = if let Some(abs_path) = is_file {
2083 if let Some(project_path) = self
2084 .project
2085 .read(cx)
2086 .project_path_for_absolute_path(&Path::new(abs_path), cx)
2087 && let Some(worktree) = self
2088 .project
2089 .read(cx)
2090 .worktree_for_id(project_path.worktree_id, cx)
2091 {
2092 worktree
2093 .read(cx)
2094 .full_path(&project_path.path)
2095 .to_string_lossy()
2096 .to_string()
2097 .into()
2098 } else {
2099 abs_path.to_string().into()
2100 }
2101 } else {
2102 uri.clone()
2103 };
2104
2105 let button_id = SharedString::from(format!("item-{}", uri));
2106
2107 div()
2108 .ml(rems(0.4))
2109 .pl_2p5()
2110 .border_l_1()
2111 .border_color(self.tool_card_border_color(cx))
2112 .overflow_hidden()
2113 .child(
2114 Button::new(button_id, label)
2115 .label_size(LabelSize::Small)
2116 .color(Color::Muted)
2117 .truncate(true)
2118 .when(is_file.is_none(), |this| {
2119 this.icon(IconName::ArrowUpRight)
2120 .icon_size(IconSize::XSmall)
2121 .icon_color(Color::Muted)
2122 })
2123 .on_click(cx.listener({
2124 let workspace = self.workspace.clone();
2125 move |_, _, window, cx: &mut Context<Self>| {
2126 Self::open_link(uri.clone(), &workspace, window, cx);
2127 }
2128 })),
2129 )
2130 .into_any_element()
2131 }
2132
2133 fn render_permission_buttons(
2134 &self,
2135 options: &[acp::PermissionOption],
2136 entry_ix: usize,
2137 tool_call_id: acp::ToolCallId,
2138 cx: &Context<Self>,
2139 ) -> Div {
2140 h_flex()
2141 .py_1()
2142 .pl_2()
2143 .pr_1()
2144 .gap_1()
2145 .justify_between()
2146 .flex_wrap()
2147 .border_t_1()
2148 .border_color(self.tool_card_border_color(cx))
2149 .child(
2150 div()
2151 .min_w(rems_from_px(145.))
2152 .child(LoadingLabel::new("Waiting for Confirmation").size(LabelSize::Small)),
2153 )
2154 .child(h_flex().gap_0p5().children(options.iter().map(|option| {
2155 let option_id = SharedString::from(option.id.0.clone());
2156 Button::new((option_id, entry_ix), option.name.clone())
2157 .map(|this| match option.kind {
2158 acp::PermissionOptionKind::AllowOnce => {
2159 this.icon(IconName::Check).icon_color(Color::Success)
2160 }
2161 acp::PermissionOptionKind::AllowAlways => {
2162 this.icon(IconName::CheckDouble).icon_color(Color::Success)
2163 }
2164 acp::PermissionOptionKind::RejectOnce => {
2165 this.icon(IconName::Close).icon_color(Color::Error)
2166 }
2167 acp::PermissionOptionKind::RejectAlways => {
2168 this.icon(IconName::Close).icon_color(Color::Error)
2169 }
2170 })
2171 .icon_position(IconPosition::Start)
2172 .icon_size(IconSize::XSmall)
2173 .label_size(LabelSize::Small)
2174 .on_click(cx.listener({
2175 let tool_call_id = tool_call_id.clone();
2176 let option_id = option.id.clone();
2177 let option_kind = option.kind;
2178 move |this, _, window, cx| {
2179 this.authorize_tool_call(
2180 tool_call_id.clone(),
2181 option_id.clone(),
2182 option_kind,
2183 window,
2184 cx,
2185 );
2186 }
2187 }))
2188 })))
2189 }
2190
2191 fn render_diff_loading(&self, cx: &Context<Self>) -> AnyElement {
2192 let bar = |n: u64, width_class: &str| {
2193 let bg_color = cx.theme().colors().element_active;
2194 let base = h_flex().h_1().rounded_full();
2195
2196 let modified = match width_class {
2197 "w_4_5" => base.w_3_4(),
2198 "w_1_4" => base.w_1_4(),
2199 "w_2_4" => base.w_2_4(),
2200 "w_3_5" => base.w_3_5(),
2201 "w_2_5" => base.w_2_5(),
2202 _ => base.w_1_2(),
2203 };
2204
2205 modified.with_animation(
2206 ElementId::Integer(n),
2207 Animation::new(Duration::from_secs(2)).repeat(),
2208 move |tab, delta| {
2209 let delta = (delta - 0.15 * n as f32) / 0.7;
2210 let delta = 1.0 - (0.5 - delta).abs() * 2.;
2211 let delta = ease_in_out(delta.clamp(0., 1.));
2212 let delta = 0.1 + 0.9 * delta;
2213
2214 tab.bg(bg_color.opacity(delta))
2215 },
2216 )
2217 };
2218
2219 v_flex()
2220 .p_3()
2221 .gap_1()
2222 .rounded_b_md()
2223 .bg(cx.theme().colors().editor_background)
2224 .child(bar(0, "w_4_5"))
2225 .child(bar(1, "w_1_4"))
2226 .child(bar(2, "w_2_4"))
2227 .child(bar(3, "w_3_5"))
2228 .child(bar(4, "w_2_5"))
2229 .into_any_element()
2230 }
2231
2232 fn render_diff_editor(
2233 &self,
2234 entry_ix: usize,
2235 diff: &Entity<acp_thread::Diff>,
2236 tool_call: &ToolCall,
2237 cx: &Context<Self>,
2238 ) -> AnyElement {
2239 let tool_progress = matches!(
2240 &tool_call.status,
2241 ToolCallStatus::InProgress | ToolCallStatus::Pending
2242 );
2243
2244 v_flex()
2245 .h_full()
2246 .border_t_1()
2247 .border_color(self.tool_card_border_color(cx))
2248 .child(
2249 if let Some(entry) = self.entry_view_state.read(cx).entry(entry_ix)
2250 && let Some(editor) = entry.editor_for_diff(diff)
2251 && diff.read(cx).has_revealed_range(cx)
2252 {
2253 editor.into_any_element()
2254 } else if tool_progress && self.as_native_connection(cx).is_some() {
2255 self.render_diff_loading(cx)
2256 } else {
2257 Empty.into_any()
2258 },
2259 )
2260 .into_any()
2261 }
2262
2263 fn render_terminal_tool_call(
2264 &self,
2265 entry_ix: usize,
2266 terminal: &Entity<acp_thread::Terminal>,
2267 tool_call: &ToolCall,
2268 window: &Window,
2269 cx: &Context<Self>,
2270 ) -> AnyElement {
2271 let terminal_data = terminal.read(cx);
2272 let working_dir = terminal_data.working_dir();
2273 let command = terminal_data.command();
2274 let started_at = terminal_data.started_at();
2275
2276 let tool_failed = matches!(
2277 &tool_call.status,
2278 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed
2279 );
2280
2281 let output = terminal_data.output();
2282 let command_finished = output.is_some();
2283 let truncated_output = output.is_some_and(|output| output.was_content_truncated);
2284 let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
2285
2286 let command_failed = command_finished
2287 && output.is_some_and(|o| o.exit_status.is_none_or(|status| !status.success()));
2288
2289 let time_elapsed = if let Some(output) = output {
2290 output.ended_at.duration_since(started_at)
2291 } else {
2292 started_at.elapsed()
2293 };
2294
2295 let header_id =
2296 SharedString::from(format!("terminal-tool-header-{}", terminal.entity_id()));
2297 let header_group = SharedString::from(format!(
2298 "terminal-tool-header-group-{}",
2299 terminal.entity_id()
2300 ));
2301 let header_bg = cx
2302 .theme()
2303 .colors()
2304 .element_background
2305 .blend(cx.theme().colors().editor_foreground.opacity(0.025));
2306 let border_color = cx.theme().colors().border.opacity(0.6);
2307
2308 let working_dir = working_dir
2309 .as_ref()
2310 .map(|path| format!("{}", path.display()))
2311 .unwrap_or_else(|| "current directory".to_string());
2312
2313 let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
2314
2315 let header = h_flex()
2316 .id(header_id)
2317 .flex_none()
2318 .gap_1()
2319 .justify_between()
2320 .rounded_t_md()
2321 .child(
2322 div()
2323 .id(("command-target-path", terminal.entity_id()))
2324 .w_full()
2325 .max_w_full()
2326 .overflow_x_scroll()
2327 .child(
2328 Label::new(working_dir)
2329 .buffer_font(cx)
2330 .size(LabelSize::XSmall)
2331 .color(Color::Muted),
2332 ),
2333 )
2334 .when(!command_finished, |header| {
2335 header
2336 .gap_1p5()
2337 .child(
2338 Button::new(
2339 SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
2340 "Stop",
2341 )
2342 .icon(IconName::Stop)
2343 .icon_position(IconPosition::Start)
2344 .icon_size(IconSize::Small)
2345 .icon_color(Color::Error)
2346 .label_size(LabelSize::Small)
2347 .tooltip(move |window, cx| {
2348 Tooltip::with_meta(
2349 "Stop This Command",
2350 None,
2351 "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
2352 window,
2353 cx,
2354 )
2355 })
2356 .on_click({
2357 let terminal = terminal.clone();
2358 cx.listener(move |_this, _event, _window, cx| {
2359 let inner_terminal = terminal.read(cx).inner().clone();
2360 inner_terminal.update(cx, |inner_terminal, _cx| {
2361 inner_terminal.kill_active_task();
2362 });
2363 })
2364 }),
2365 )
2366 .child(Divider::vertical())
2367 .child(
2368 Icon::new(IconName::ArrowCircle)
2369 .size(IconSize::XSmall)
2370 .color(Color::Info)
2371 .with_animation(
2372 "arrow-circle",
2373 Animation::new(Duration::from_secs(2)).repeat(),
2374 |icon, delta| {
2375 icon.transform(Transformation::rotate(percentage(delta)))
2376 },
2377 ),
2378 )
2379 })
2380 .child(
2381 Disclosure::new(
2382 SharedString::from(format!(
2383 "terminal-tool-disclosure-{}",
2384 terminal.entity_id()
2385 )),
2386 is_expanded,
2387 )
2388 .opened_icon(IconName::ChevronUp)
2389 .closed_icon(IconName::ChevronDown)
2390 .visible_on_hover(&header_group)
2391 .on_click(cx.listener({
2392 let id = tool_call.id.clone();
2393 move |this, _event, _window, _cx| {
2394 if is_expanded {
2395 this.expanded_tool_calls.remove(&id);
2396 } else {
2397 this.expanded_tool_calls.insert(id.clone());
2398 }
2399 }
2400 })),
2401 )
2402 .when(truncated_output, |header| {
2403 let tooltip = if let Some(output) = output {
2404 if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
2405 "Output exceeded terminal max lines and was \
2406 truncated, the model received the first 16 KB."
2407 .to_string()
2408 } else {
2409 format!(
2410 "Output is {} long, and to avoid unexpected token usage, \
2411 only 16 KB was sent back to the model.",
2412 format_file_size(output.original_content_len as u64, true),
2413 )
2414 }
2415 } else {
2416 "Output was truncated".to_string()
2417 };
2418
2419 header.child(
2420 h_flex()
2421 .id(("terminal-tool-truncated-label", terminal.entity_id()))
2422 .gap_1()
2423 .child(
2424 Icon::new(IconName::Info)
2425 .size(IconSize::XSmall)
2426 .color(Color::Ignored),
2427 )
2428 .child(
2429 Label::new("Truncated")
2430 .color(Color::Muted)
2431 .size(LabelSize::XSmall),
2432 )
2433 .tooltip(Tooltip::text(tooltip)),
2434 )
2435 })
2436 .when(time_elapsed > Duration::from_secs(10), |header| {
2437 header.child(
2438 Label::new(format!("({})", duration_alt_display(time_elapsed)))
2439 .buffer_font(cx)
2440 .color(Color::Muted)
2441 .size(LabelSize::XSmall),
2442 )
2443 })
2444 .when(tool_failed || command_failed, |header| {
2445 header.child(
2446 div()
2447 .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
2448 .child(
2449 Icon::new(IconName::Close)
2450 .size(IconSize::Small)
2451 .color(Color::Error),
2452 )
2453 .when_some(output.and_then(|o| o.exit_status), |this, status| {
2454 this.tooltip(Tooltip::text(format!(
2455 "Exited with code {}",
2456 status.code().unwrap_or(-1),
2457 )))
2458 }),
2459 )
2460 });
2461
2462 let terminal_view = self
2463 .entry_view_state
2464 .read(cx)
2465 .entry(entry_ix)
2466 .and_then(|entry| entry.terminal(terminal));
2467 let show_output = is_expanded && terminal_view.is_some();
2468
2469 v_flex()
2470 .my_1p5()
2471 .mx_5()
2472 .border_1()
2473 .when(tool_failed || command_failed, |card| card.border_dashed())
2474 .border_color(border_color)
2475 .rounded_md()
2476 .overflow_hidden()
2477 .child(
2478 v_flex()
2479 .group(&header_group)
2480 .py_1p5()
2481 .pr_1p5()
2482 .pl_2()
2483 .gap_0p5()
2484 .bg(header_bg)
2485 .text_xs()
2486 .child(header)
2487 .child(
2488 MarkdownElement::new(
2489 command.clone(),
2490 terminal_command_markdown_style(window, cx),
2491 )
2492 .code_block_renderer(
2493 markdown::CodeBlockRenderer::Default {
2494 copy_button: false,
2495 copy_button_on_hover: true,
2496 border: false,
2497 },
2498 ),
2499 ),
2500 )
2501 .when(show_output, |this| {
2502 this.child(
2503 div()
2504 .pt_2()
2505 .border_t_1()
2506 .when(tool_failed || command_failed, |card| card.border_dashed())
2507 .border_color(border_color)
2508 .bg(cx.theme().colors().editor_background)
2509 .rounded_b_md()
2510 .text_ui_sm(cx)
2511 .children(terminal_view.clone()),
2512 )
2513 })
2514 .into_any()
2515 }
2516
2517 fn render_rules_item(&self, cx: &Context<Self>) -> Option<AnyElement> {
2518 let project_context = self
2519 .as_native_thread(cx)?
2520 .read(cx)
2521 .project_context()
2522 .read(cx);
2523
2524 let user_rules_text = if project_context.user_rules.is_empty() {
2525 None
2526 } else if project_context.user_rules.len() == 1 {
2527 let user_rules = &project_context.user_rules[0];
2528
2529 match user_rules.title.as_ref() {
2530 Some(title) => Some(format!("Using \"{title}\" user rule")),
2531 None => Some("Using user rule".into()),
2532 }
2533 } else {
2534 Some(format!(
2535 "Using {} user rules",
2536 project_context.user_rules.len()
2537 ))
2538 };
2539
2540 let first_user_rules_id = project_context
2541 .user_rules
2542 .first()
2543 .map(|user_rules| user_rules.uuid.0);
2544
2545 let rules_files = project_context
2546 .worktrees
2547 .iter()
2548 .filter_map(|worktree| worktree.rules_file.as_ref())
2549 .collect::<Vec<_>>();
2550
2551 let rules_file_text = match rules_files.as_slice() {
2552 &[] => None,
2553 &[rules_file] => Some(format!(
2554 "Using project {:?} file",
2555 rules_file.path_in_worktree
2556 )),
2557 rules_files => Some(format!("Using {} project rules files", rules_files.len())),
2558 };
2559
2560 if user_rules_text.is_none() && rules_file_text.is_none() {
2561 return None;
2562 }
2563
2564 let has_both = user_rules_text.is_some() && rules_file_text.is_some();
2565
2566 Some(
2567 h_flex()
2568 .px_2p5()
2569 .child(
2570 Icon::new(IconName::Attach)
2571 .size(IconSize::XSmall)
2572 .color(Color::Disabled),
2573 )
2574 .when_some(user_rules_text, |parent, user_rules_text| {
2575 parent.child(
2576 h_flex()
2577 .id("user-rules")
2578 .ml_1()
2579 .mr_1p5()
2580 .child(
2581 Label::new(user_rules_text)
2582 .size(LabelSize::XSmall)
2583 .color(Color::Muted)
2584 .truncate(),
2585 )
2586 .hover(|s| s.bg(cx.theme().colors().element_hover))
2587 .tooltip(Tooltip::text("View User Rules"))
2588 .on_click(move |_event, window, cx| {
2589 window.dispatch_action(
2590 Box::new(OpenRulesLibrary {
2591 prompt_to_select: first_user_rules_id,
2592 }),
2593 cx,
2594 )
2595 }),
2596 )
2597 })
2598 .when(has_both, |this| {
2599 this.child(
2600 Label::new("•")
2601 .size(LabelSize::XSmall)
2602 .color(Color::Disabled),
2603 )
2604 })
2605 .when_some(rules_file_text, |parent, rules_file_text| {
2606 parent.child(
2607 h_flex()
2608 .id("project-rules")
2609 .ml_1p5()
2610 .child(
2611 Label::new(rules_file_text)
2612 .size(LabelSize::XSmall)
2613 .color(Color::Muted),
2614 )
2615 .hover(|s| s.bg(cx.theme().colors().element_hover))
2616 .tooltip(Tooltip::text("View Project Rules"))
2617 .on_click(cx.listener(Self::handle_open_rules)),
2618 )
2619 })
2620 .into_any(),
2621 )
2622 }
2623
2624 fn render_empty_state_section_header(
2625 &self,
2626 label: impl Into<SharedString>,
2627 action_slot: Option<AnyElement>,
2628 cx: &mut Context<Self>,
2629 ) -> impl IntoElement {
2630 div().pl_1().pr_1p5().child(
2631 h_flex()
2632 .mt_2()
2633 .pl_1p5()
2634 .pb_1()
2635 .w_full()
2636 .justify_between()
2637 .border_b_1()
2638 .border_color(cx.theme().colors().border_variant)
2639 .child(
2640 Label::new(label.into())
2641 .size(LabelSize::Small)
2642 .color(Color::Muted),
2643 )
2644 .children(action_slot),
2645 )
2646 }
2647
2648 fn render_recent_history(&self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
2649 let render_history = self
2650 .agent
2651 .clone()
2652 .downcast::<agent2::NativeAgentServer>()
2653 .is_some()
2654 && self
2655 .history_store
2656 .update(cx, |history_store, cx| !history_store.is_empty(cx));
2657
2658 v_flex()
2659 .size_full()
2660 .when(render_history, |this| {
2661 let recent_history: Vec<_> = self.history_store.update(cx, |history_store, _| {
2662 history_store.entries().take(3).collect()
2663 });
2664 this.justify_end().child(
2665 v_flex()
2666 .child(
2667 self.render_empty_state_section_header(
2668 "Recent",
2669 Some(
2670 Button::new("view-history", "View All")
2671 .style(ButtonStyle::Subtle)
2672 .label_size(LabelSize::Small)
2673 .key_binding(
2674 KeyBinding::for_action_in(
2675 &OpenHistory,
2676 &self.focus_handle(cx),
2677 window,
2678 cx,
2679 )
2680 .map(|kb| kb.size(rems_from_px(12.))),
2681 )
2682 .on_click(move |_event, window, cx| {
2683 window.dispatch_action(OpenHistory.boxed_clone(), cx);
2684 })
2685 .into_any_element(),
2686 ),
2687 cx,
2688 ),
2689 )
2690 .child(
2691 v_flex().p_1().pr_1p5().gap_1().children(
2692 recent_history
2693 .into_iter()
2694 .enumerate()
2695 .map(|(index, entry)| {
2696 // TODO: Add keyboard navigation.
2697 let is_hovered =
2698 self.hovered_recent_history_item == Some(index);
2699 crate::acp::thread_history::AcpHistoryEntryElement::new(
2700 entry,
2701 cx.entity().downgrade(),
2702 )
2703 .hovered(is_hovered)
2704 .on_hover(cx.listener(
2705 move |this, is_hovered, _window, cx| {
2706 if *is_hovered {
2707 this.hovered_recent_history_item = Some(index);
2708 } else if this.hovered_recent_history_item
2709 == Some(index)
2710 {
2711 this.hovered_recent_history_item = None;
2712 }
2713 cx.notify();
2714 },
2715 ))
2716 .into_any_element()
2717 }),
2718 ),
2719 ),
2720 )
2721 })
2722 .into_any()
2723 }
2724
2725 fn render_auth_required_state(
2726 &self,
2727 connection: &Rc<dyn AgentConnection>,
2728 description: Option<&Entity<Markdown>>,
2729 configuration_view: Option<&AnyView>,
2730 pending_auth_method: Option<&acp::AuthMethodId>,
2731 window: &mut Window,
2732 cx: &Context<Self>,
2733 ) -> Div {
2734 let show_description =
2735 configuration_view.is_none() && description.is_none() && pending_auth_method.is_none();
2736
2737 v_flex().flex_1().size_full().justify_end().child(
2738 v_flex()
2739 .p_2()
2740 .pr_3()
2741 .w_full()
2742 .gap_1()
2743 .border_t_1()
2744 .border_color(cx.theme().colors().border)
2745 .bg(cx.theme().status().warning.opacity(0.04))
2746 .child(
2747 h_flex()
2748 .gap_1p5()
2749 .child(
2750 Icon::new(IconName::Warning)
2751 .color(Color::Warning)
2752 .size(IconSize::Small),
2753 )
2754 .child(Label::new("Authentication Required").size(LabelSize::Small)),
2755 )
2756 .children(description.map(|desc| {
2757 div().text_ui(cx).child(self.render_markdown(
2758 desc.clone(),
2759 default_markdown_style(false, false, window, cx),
2760 ))
2761 }))
2762 .children(
2763 configuration_view
2764 .cloned()
2765 .map(|view| div().w_full().child(view)),
2766 )
2767 .when(
2768 show_description,
2769 |el| {
2770 el.child(
2771 Label::new(format!(
2772 "You are not currently authenticated with {}. Please choose one of the following options:",
2773 self.agent.name()
2774 ))
2775 .size(LabelSize::Small)
2776 .color(Color::Muted)
2777 .mb_1()
2778 .ml_5(),
2779 )
2780 },
2781 )
2782 .when_some(pending_auth_method, |el, _| {
2783 el.child(
2784 h_flex()
2785 .py_4()
2786 .w_full()
2787 .justify_center()
2788 .gap_1()
2789 .child(
2790 Icon::new(IconName::ArrowCircle)
2791 .size(IconSize::Small)
2792 .color(Color::Muted)
2793 .with_animation(
2794 "arrow-circle",
2795 Animation::new(Duration::from_secs(2)).repeat(),
2796 |icon, delta| {
2797 icon.transform(Transformation::rotate(percentage(
2798 delta,
2799 )))
2800 },
2801 )
2802 .into_any_element(),
2803 )
2804 .child(Label::new("Authenticating…").size(LabelSize::Small)),
2805 )
2806 })
2807 .when(!connection.auth_methods().is_empty(), |this| {
2808 this.child(
2809 h_flex()
2810 .justify_end()
2811 .flex_wrap()
2812 .gap_1()
2813 .when(!show_description, |this| {
2814 this.border_t_1()
2815 .mt_1()
2816 .pt_2()
2817 .border_color(cx.theme().colors().border.opacity(0.8))
2818 })
2819 .children(
2820 connection
2821 .auth_methods()
2822 .iter()
2823 .enumerate()
2824 .rev()
2825 .map(|(ix, method)| {
2826 Button::new(
2827 SharedString::from(method.id.0.clone()),
2828 method.name.clone(),
2829 )
2830 .when(ix == 0, |el| {
2831 el.style(ButtonStyle::Tinted(ui::TintColor::Warning))
2832 })
2833 .label_size(LabelSize::Small)
2834 .on_click({
2835 let method_id = method.id.clone();
2836 cx.listener(move |this, _, window, cx| {
2837 telemetry::event!(
2838 "Authenticate Agent Started",
2839 agent = this.agent.telemetry_id(),
2840 method = method_id
2841 );
2842
2843 this.authenticate(method_id.clone(), window, cx)
2844 })
2845 })
2846 }),
2847 ),
2848 )
2849 })
2850
2851 )
2852 }
2853
2854 fn render_load_error(
2855 &self,
2856 e: &LoadError,
2857 window: &mut Window,
2858 cx: &mut Context<Self>,
2859 ) -> AnyElement {
2860 let (title, message, action_slot): (_, SharedString, _) = match e {
2861 LoadError::Unsupported {
2862 command: path,
2863 current_version,
2864 minimum_version,
2865 } => {
2866 return self.render_unsupported(path, current_version, minimum_version, window, cx);
2867 }
2868 LoadError::FailedToInstall(msg) => (
2869 "Failed to Install",
2870 msg.into(),
2871 Some(self.create_copy_button(msg.to_string()).into_any_element()),
2872 ),
2873 LoadError::Exited { status } => (
2874 "Failed to Launch",
2875 format!("Server exited with status {status}").into(),
2876 None,
2877 ),
2878 LoadError::Other(msg) => (
2879 "Failed to Launch",
2880 msg.into(),
2881 Some(self.create_copy_button(msg.to_string()).into_any_element()),
2882 ),
2883 };
2884
2885 Callout::new()
2886 .severity(Severity::Error)
2887 .icon(IconName::XCircleFilled)
2888 .title(title)
2889 .description(message)
2890 .actions_slot(div().children(action_slot))
2891 .into_any_element()
2892 }
2893
2894 fn render_unsupported(
2895 &self,
2896 path: &SharedString,
2897 version: &SharedString,
2898 minimum_version: &SharedString,
2899 _window: &mut Window,
2900 cx: &mut Context<Self>,
2901 ) -> AnyElement {
2902 let (heading_label, description_label) = (
2903 format!("Upgrade {} to work with Zed", self.agent.name()),
2904 if version.is_empty() {
2905 format!(
2906 "Currently using {}, which does not report a valid --version",
2907 path,
2908 )
2909 } else {
2910 format!(
2911 "Currently using {}, which is only version {} (need at least {minimum_version})",
2912 path, version
2913 )
2914 },
2915 );
2916
2917 v_flex()
2918 .w_full()
2919 .p_3p5()
2920 .gap_2p5()
2921 .border_t_1()
2922 .border_color(cx.theme().colors().border)
2923 .bg(linear_gradient(
2924 180.,
2925 linear_color_stop(cx.theme().colors().editor_background.opacity(0.4), 4.),
2926 linear_color_stop(cx.theme().status().info_background.opacity(0.), 0.),
2927 ))
2928 .child(
2929 v_flex().gap_0p5().child(Label::new(heading_label)).child(
2930 Label::new(description_label)
2931 .size(LabelSize::Small)
2932 .color(Color::Muted),
2933 ),
2934 )
2935 .into_any_element()
2936 }
2937
2938 fn render_activity_bar(
2939 &self,
2940 thread_entity: &Entity<AcpThread>,
2941 window: &mut Window,
2942 cx: &Context<Self>,
2943 ) -> Option<AnyElement> {
2944 let thread = thread_entity.read(cx);
2945 let action_log = thread.action_log();
2946 let changed_buffers = action_log.read(cx).changed_buffers(cx);
2947 let plan = thread.plan();
2948
2949 if changed_buffers.is_empty() && plan.is_empty() {
2950 return None;
2951 }
2952
2953 let editor_bg_color = cx.theme().colors().editor_background;
2954 let active_color = cx.theme().colors().element_selected;
2955 let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
2956
2957 let pending_edits = thread.has_pending_edit_tool_calls();
2958
2959 v_flex()
2960 .mt_1()
2961 .mx_2()
2962 .bg(bg_edit_files_disclosure)
2963 .border_1()
2964 .border_b_0()
2965 .border_color(cx.theme().colors().border)
2966 .rounded_t_md()
2967 .shadow(vec![gpui::BoxShadow {
2968 color: gpui::black().opacity(0.15),
2969 offset: point(px(1.), px(-1.)),
2970 blur_radius: px(3.),
2971 spread_radius: px(0.),
2972 }])
2973 .when(!plan.is_empty(), |this| {
2974 this.child(self.render_plan_summary(plan, window, cx))
2975 .when(self.plan_expanded, |parent| {
2976 parent.child(self.render_plan_entries(plan, window, cx))
2977 })
2978 })
2979 .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
2980 this.child(Divider::horizontal().color(DividerColor::Border))
2981 })
2982 .when(!changed_buffers.is_empty(), |this| {
2983 this.child(self.render_edits_summary(
2984 &changed_buffers,
2985 self.edits_expanded,
2986 pending_edits,
2987 window,
2988 cx,
2989 ))
2990 .when(self.edits_expanded, |parent| {
2991 parent.child(self.render_edited_files(
2992 action_log,
2993 &changed_buffers,
2994 pending_edits,
2995 cx,
2996 ))
2997 })
2998 })
2999 .into_any()
3000 .into()
3001 }
3002
3003 fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
3004 let stats = plan.stats();
3005
3006 let title = if let Some(entry) = stats.in_progress_entry
3007 && !self.plan_expanded
3008 {
3009 h_flex()
3010 .w_full()
3011 .cursor_default()
3012 .gap_1()
3013 .text_xs()
3014 .text_color(cx.theme().colors().text_muted)
3015 .justify_between()
3016 .child(
3017 h_flex()
3018 .gap_1()
3019 .child(
3020 Label::new("Current:")
3021 .size(LabelSize::Small)
3022 .color(Color::Muted),
3023 )
3024 .child(MarkdownElement::new(
3025 entry.content.clone(),
3026 plan_label_markdown_style(&entry.status, window, cx),
3027 )),
3028 )
3029 .when(stats.pending > 0, |this| {
3030 this.child(
3031 Label::new(format!("{} left", stats.pending))
3032 .size(LabelSize::Small)
3033 .color(Color::Muted)
3034 .mr_1(),
3035 )
3036 })
3037 } else {
3038 let status_label = if stats.pending == 0 {
3039 "All Done".to_string()
3040 } else if stats.completed == 0 {
3041 format!("{} Tasks", plan.entries.len())
3042 } else {
3043 format!("{}/{}", stats.completed, plan.entries.len())
3044 };
3045
3046 h_flex()
3047 .w_full()
3048 .gap_1()
3049 .justify_between()
3050 .child(
3051 Label::new("Plan")
3052 .size(LabelSize::Small)
3053 .color(Color::Muted),
3054 )
3055 .child(
3056 Label::new(status_label)
3057 .size(LabelSize::Small)
3058 .color(Color::Muted)
3059 .mr_1(),
3060 )
3061 };
3062
3063 h_flex()
3064 .p_1()
3065 .justify_between()
3066 .when(self.plan_expanded, |this| {
3067 this.border_b_1().border_color(cx.theme().colors().border)
3068 })
3069 .child(
3070 h_flex()
3071 .id("plan_summary")
3072 .w_full()
3073 .gap_1()
3074 .child(Disclosure::new("plan_disclosure", self.plan_expanded))
3075 .child(title)
3076 .on_click(cx.listener(|this, _, _, cx| {
3077 this.plan_expanded = !this.plan_expanded;
3078 cx.notify();
3079 })),
3080 )
3081 }
3082
3083 fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
3084 v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
3085 let element = h_flex()
3086 .py_1()
3087 .px_2()
3088 .gap_2()
3089 .justify_between()
3090 .bg(cx.theme().colors().editor_background)
3091 .when(index < plan.entries.len() - 1, |parent| {
3092 parent.border_color(cx.theme().colors().border).border_b_1()
3093 })
3094 .child(
3095 h_flex()
3096 .id(("plan_entry", index))
3097 .gap_1p5()
3098 .max_w_full()
3099 .overflow_x_scroll()
3100 .text_xs()
3101 .text_color(cx.theme().colors().text_muted)
3102 .child(match entry.status {
3103 acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
3104 .size(IconSize::Small)
3105 .color(Color::Muted)
3106 .into_any_element(),
3107 acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
3108 .size(IconSize::Small)
3109 .color(Color::Accent)
3110 .with_animation(
3111 "running",
3112 Animation::new(Duration::from_secs(2)).repeat(),
3113 |icon, delta| {
3114 icon.transform(Transformation::rotate(percentage(delta)))
3115 },
3116 )
3117 .into_any_element(),
3118 acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
3119 .size(IconSize::Small)
3120 .color(Color::Success)
3121 .into_any_element(),
3122 })
3123 .child(MarkdownElement::new(
3124 entry.content.clone(),
3125 plan_label_markdown_style(&entry.status, window, cx),
3126 )),
3127 );
3128
3129 Some(element)
3130 }))
3131 }
3132
3133 fn render_edits_summary(
3134 &self,
3135 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3136 expanded: bool,
3137 pending_edits: bool,
3138 window: &mut Window,
3139 cx: &Context<Self>,
3140 ) -> Div {
3141 const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
3142
3143 let focus_handle = self.focus_handle(cx);
3144
3145 h_flex()
3146 .p_1()
3147 .justify_between()
3148 .flex_wrap()
3149 .when(expanded, |this| {
3150 this.border_b_1().border_color(cx.theme().colors().border)
3151 })
3152 .child(
3153 h_flex()
3154 .id("edits-container")
3155 .gap_1()
3156 .child(Disclosure::new("edits-disclosure", expanded))
3157 .map(|this| {
3158 if pending_edits {
3159 this.child(
3160 Label::new(format!(
3161 "Editing {} {}…",
3162 changed_buffers.len(),
3163 if changed_buffers.len() == 1 {
3164 "file"
3165 } else {
3166 "files"
3167 }
3168 ))
3169 .color(Color::Muted)
3170 .size(LabelSize::Small)
3171 .with_animation(
3172 "edit-label",
3173 Animation::new(Duration::from_secs(2))
3174 .repeat()
3175 .with_easing(pulsating_between(0.3, 0.7)),
3176 |label, delta| label.alpha(delta),
3177 ),
3178 )
3179 } else {
3180 this.child(
3181 Label::new("Edits")
3182 .size(LabelSize::Small)
3183 .color(Color::Muted),
3184 )
3185 .child(Label::new("•").size(LabelSize::XSmall).color(Color::Muted))
3186 .child(
3187 Label::new(format!(
3188 "{} {}",
3189 changed_buffers.len(),
3190 if changed_buffers.len() == 1 {
3191 "file"
3192 } else {
3193 "files"
3194 }
3195 ))
3196 .size(LabelSize::Small)
3197 .color(Color::Muted),
3198 )
3199 }
3200 })
3201 .on_click(cx.listener(|this, _, _, cx| {
3202 this.edits_expanded = !this.edits_expanded;
3203 cx.notify();
3204 })),
3205 )
3206 .child(
3207 h_flex()
3208 .gap_1()
3209 .child(
3210 IconButton::new("review-changes", IconName::ListTodo)
3211 .icon_size(IconSize::Small)
3212 .tooltip({
3213 let focus_handle = focus_handle.clone();
3214 move |window, cx| {
3215 Tooltip::for_action_in(
3216 "Review Changes",
3217 &OpenAgentDiff,
3218 &focus_handle,
3219 window,
3220 cx,
3221 )
3222 }
3223 })
3224 .on_click(cx.listener(|_, _, window, cx| {
3225 window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
3226 })),
3227 )
3228 .child(Divider::vertical().color(DividerColor::Border))
3229 .child(
3230 Button::new("reject-all-changes", "Reject All")
3231 .label_size(LabelSize::Small)
3232 .disabled(pending_edits)
3233 .when(pending_edits, |this| {
3234 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3235 })
3236 .key_binding(
3237 KeyBinding::for_action_in(
3238 &RejectAll,
3239 &focus_handle.clone(),
3240 window,
3241 cx,
3242 )
3243 .map(|kb| kb.size(rems_from_px(10.))),
3244 )
3245 .on_click(cx.listener(move |this, _, window, cx| {
3246 this.reject_all(&RejectAll, window, cx);
3247 })),
3248 )
3249 .child(
3250 Button::new("keep-all-changes", "Keep All")
3251 .label_size(LabelSize::Small)
3252 .disabled(pending_edits)
3253 .when(pending_edits, |this| {
3254 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3255 })
3256 .key_binding(
3257 KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
3258 .map(|kb| kb.size(rems_from_px(10.))),
3259 )
3260 .on_click(cx.listener(move |this, _, window, cx| {
3261 this.keep_all(&KeepAll, window, cx);
3262 })),
3263 ),
3264 )
3265 }
3266
3267 fn render_edited_files(
3268 &self,
3269 action_log: &Entity<ActionLog>,
3270 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3271 pending_edits: bool,
3272 cx: &Context<Self>,
3273 ) -> Div {
3274 let editor_bg_color = cx.theme().colors().editor_background;
3275
3276 v_flex().children(changed_buffers.iter().enumerate().flat_map(
3277 |(index, (buffer, _diff))| {
3278 let file = buffer.read(cx).file()?;
3279 let path = file.path();
3280
3281 let file_path = path.parent().and_then(|parent| {
3282 let parent_str = parent.to_string_lossy();
3283
3284 if parent_str.is_empty() {
3285 None
3286 } else {
3287 Some(
3288 Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
3289 .color(Color::Muted)
3290 .size(LabelSize::XSmall)
3291 .buffer_font(cx),
3292 )
3293 }
3294 });
3295
3296 let file_name = path.file_name().map(|name| {
3297 Label::new(name.to_string_lossy().to_string())
3298 .size(LabelSize::XSmall)
3299 .buffer_font(cx)
3300 });
3301
3302 let file_icon = FileIcons::get_icon(path, cx)
3303 .map(Icon::from_path)
3304 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
3305 .unwrap_or_else(|| {
3306 Icon::new(IconName::File)
3307 .color(Color::Muted)
3308 .size(IconSize::Small)
3309 });
3310
3311 let overlay_gradient = linear_gradient(
3312 90.,
3313 linear_color_stop(editor_bg_color, 1.),
3314 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
3315 );
3316
3317 let element = h_flex()
3318 .group("edited-code")
3319 .id(("file-container", index))
3320 .py_1()
3321 .pl_2()
3322 .pr_1()
3323 .gap_2()
3324 .justify_between()
3325 .bg(editor_bg_color)
3326 .when(index < changed_buffers.len() - 1, |parent| {
3327 parent.border_color(cx.theme().colors().border).border_b_1()
3328 })
3329 .child(
3330 h_flex()
3331 .relative()
3332 .id(("file-name", index))
3333 .pr_8()
3334 .gap_1p5()
3335 .max_w_full()
3336 .overflow_x_scroll()
3337 .child(file_icon)
3338 .child(h_flex().gap_0p5().children(file_name).children(file_path))
3339 .child(
3340 div()
3341 .absolute()
3342 .h_full()
3343 .w_12()
3344 .top_0()
3345 .bottom_0()
3346 .right_0()
3347 .bg(overlay_gradient),
3348 )
3349 .on_click({
3350 let buffer = buffer.clone();
3351 cx.listener(move |this, _, window, cx| {
3352 this.open_edited_buffer(&buffer, window, cx);
3353 })
3354 }),
3355 )
3356 .child(
3357 h_flex()
3358 .gap_1()
3359 .visible_on_hover("edited-code")
3360 .child(
3361 Button::new("review", "Review")
3362 .label_size(LabelSize::Small)
3363 .on_click({
3364 let buffer = buffer.clone();
3365 cx.listener(move |this, _, window, cx| {
3366 this.open_edited_buffer(&buffer, window, cx);
3367 })
3368 }),
3369 )
3370 .child(Divider::vertical().color(DividerColor::BorderVariant))
3371 .child(
3372 Button::new("reject-file", "Reject")
3373 .label_size(LabelSize::Small)
3374 .disabled(pending_edits)
3375 .on_click({
3376 let buffer = buffer.clone();
3377 let action_log = action_log.clone();
3378 move |_, _, cx| {
3379 action_log.update(cx, |action_log, cx| {
3380 action_log
3381 .reject_edits_in_ranges(
3382 buffer.clone(),
3383 vec![Anchor::MIN..Anchor::MAX],
3384 cx,
3385 )
3386 .detach_and_log_err(cx);
3387 })
3388 }
3389 }),
3390 )
3391 .child(
3392 Button::new("keep-file", "Keep")
3393 .label_size(LabelSize::Small)
3394 .disabled(pending_edits)
3395 .on_click({
3396 let buffer = buffer.clone();
3397 let action_log = action_log.clone();
3398 move |_, _, cx| {
3399 action_log.update(cx, |action_log, cx| {
3400 action_log.keep_edits_in_range(
3401 buffer.clone(),
3402 Anchor::MIN..Anchor::MAX,
3403 cx,
3404 );
3405 })
3406 }
3407 }),
3408 ),
3409 );
3410
3411 Some(element)
3412 },
3413 ))
3414 }
3415
3416 fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
3417 let focus_handle = self.message_editor.focus_handle(cx);
3418 let editor_bg_color = cx.theme().colors().editor_background;
3419 let (expand_icon, expand_tooltip) = if self.editor_expanded {
3420 (IconName::Minimize, "Minimize Message Editor")
3421 } else {
3422 (IconName::Maximize, "Expand Message Editor")
3423 };
3424
3425 let backdrop = div()
3426 .size_full()
3427 .absolute()
3428 .inset_0()
3429 .bg(cx.theme().colors().panel_background)
3430 .opacity(0.8)
3431 .block_mouse_except_scroll();
3432
3433 let enable_editor = match self.thread_state {
3434 ThreadState::Loading { .. } | ThreadState::Ready { .. } => true,
3435 ThreadState::Unauthenticated { .. } | ThreadState::LoadError(..) => false,
3436 };
3437
3438 v_flex()
3439 .on_action(cx.listener(Self::expand_message_editor))
3440 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
3441 if let Some(profile_selector) = this.profile_selector.as_ref() {
3442 profile_selector.read(cx).menu_handle().toggle(window, cx);
3443 }
3444 }))
3445 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
3446 if let Some(model_selector) = this.model_selector.as_ref() {
3447 model_selector
3448 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
3449 }
3450 }))
3451 .p_2()
3452 .gap_2()
3453 .border_t_1()
3454 .border_color(cx.theme().colors().border)
3455 .bg(editor_bg_color)
3456 .when(self.editor_expanded, |this| {
3457 this.h(vh(0.8, window)).size_full().justify_between()
3458 })
3459 .child(
3460 v_flex()
3461 .relative()
3462 .size_full()
3463 .pt_1()
3464 .pr_2p5()
3465 .child(self.message_editor.clone())
3466 .child(
3467 h_flex()
3468 .absolute()
3469 .top_0()
3470 .right_0()
3471 .opacity(0.5)
3472 .hover(|this| this.opacity(1.0))
3473 .child(
3474 IconButton::new("toggle-height", expand_icon)
3475 .icon_size(IconSize::Small)
3476 .icon_color(Color::Muted)
3477 .tooltip({
3478 move |window, cx| {
3479 Tooltip::for_action_in(
3480 expand_tooltip,
3481 &ExpandMessageEditor,
3482 &focus_handle,
3483 window,
3484 cx,
3485 )
3486 }
3487 })
3488 .on_click(cx.listener(|_, _, window, cx| {
3489 window.dispatch_action(Box::new(ExpandMessageEditor), cx);
3490 })),
3491 ),
3492 ),
3493 )
3494 .child(
3495 h_flex()
3496 .flex_none()
3497 .flex_wrap()
3498 .justify_between()
3499 .child(
3500 h_flex()
3501 .child(self.render_follow_toggle(cx))
3502 .children(self.render_burn_mode_toggle(cx)),
3503 )
3504 .child(
3505 h_flex()
3506 .gap_1()
3507 .children(self.render_token_usage(cx))
3508 .children(self.profile_selector.clone())
3509 .children(self.model_selector.clone())
3510 .child(self.render_send_button(cx)),
3511 ),
3512 )
3513 .when(!enable_editor, |this| this.child(backdrop))
3514 .into_any()
3515 }
3516
3517 pub(crate) fn as_native_connection(
3518 &self,
3519 cx: &App,
3520 ) -> Option<Rc<agent2::NativeAgentConnection>> {
3521 let acp_thread = self.thread()?.read(cx);
3522 acp_thread.connection().clone().downcast()
3523 }
3524
3525 pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent2::Thread>> {
3526 let acp_thread = self.thread()?.read(cx);
3527 self.as_native_connection(cx)?
3528 .thread(acp_thread.session_id(), cx)
3529 }
3530
3531 fn is_using_zed_ai_models(&self, cx: &App) -> bool {
3532 self.as_native_thread(cx)
3533 .and_then(|thread| thread.read(cx).model())
3534 .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
3535 }
3536
3537 fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
3538 let thread = self.thread()?.read(cx);
3539 let usage = thread.token_usage()?;
3540 let is_generating = thread.status() != ThreadStatus::Idle;
3541
3542 let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
3543 let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
3544
3545 Some(
3546 h_flex()
3547 .flex_shrink_0()
3548 .gap_0p5()
3549 .mr_1p5()
3550 .child(
3551 Label::new(used)
3552 .size(LabelSize::Small)
3553 .color(Color::Muted)
3554 .map(|label| {
3555 if is_generating {
3556 label
3557 .with_animation(
3558 "used-tokens-label",
3559 Animation::new(Duration::from_secs(2))
3560 .repeat()
3561 .with_easing(pulsating_between(0.3, 0.8)),
3562 |label, delta| label.alpha(delta),
3563 )
3564 .into_any()
3565 } else {
3566 label.into_any_element()
3567 }
3568 }),
3569 )
3570 .child(
3571 Label::new("/")
3572 .size(LabelSize::Small)
3573 .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
3574 )
3575 .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
3576 )
3577 }
3578
3579 fn toggle_burn_mode(
3580 &mut self,
3581 _: &ToggleBurnMode,
3582 _window: &mut Window,
3583 cx: &mut Context<Self>,
3584 ) {
3585 let Some(thread) = self.as_native_thread(cx) else {
3586 return;
3587 };
3588
3589 thread.update(cx, |thread, cx| {
3590 let current_mode = thread.completion_mode();
3591 thread.set_completion_mode(
3592 match current_mode {
3593 CompletionMode::Burn => CompletionMode::Normal,
3594 CompletionMode::Normal => CompletionMode::Burn,
3595 },
3596 cx,
3597 );
3598 });
3599 }
3600
3601 fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
3602 let Some(thread) = self.thread() else {
3603 return;
3604 };
3605 let action_log = thread.read(cx).action_log().clone();
3606 action_log.update(cx, |action_log, cx| action_log.keep_all_edits(cx));
3607 }
3608
3609 fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
3610 let Some(thread) = self.thread() else {
3611 return;
3612 };
3613 let action_log = thread.read(cx).action_log().clone();
3614 action_log
3615 .update(cx, |action_log, cx| action_log.reject_all_edits(cx))
3616 .detach();
3617 }
3618
3619 fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3620 let thread = self.as_native_thread(cx)?.read(cx);
3621
3622 if thread
3623 .model()
3624 .is_none_or(|model| !model.supports_burn_mode())
3625 {
3626 return None;
3627 }
3628
3629 let active_completion_mode = thread.completion_mode();
3630 let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
3631 let icon = if burn_mode_enabled {
3632 IconName::ZedBurnModeOn
3633 } else {
3634 IconName::ZedBurnMode
3635 };
3636
3637 Some(
3638 IconButton::new("burn-mode", icon)
3639 .icon_size(IconSize::Small)
3640 .icon_color(Color::Muted)
3641 .toggle_state(burn_mode_enabled)
3642 .selected_icon_color(Color::Error)
3643 .on_click(cx.listener(|this, _event, window, cx| {
3644 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
3645 }))
3646 .tooltip(move |_window, cx| {
3647 cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
3648 .into()
3649 })
3650 .into_any_element(),
3651 )
3652 }
3653
3654 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
3655 let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
3656 let is_generating = self
3657 .thread()
3658 .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
3659
3660 if self.is_loading_contents {
3661 div()
3662 .id("loading-message-content")
3663 .px_1()
3664 .tooltip(Tooltip::text("Loading Added Context…"))
3665 .child(loading_contents_spinner(IconSize::default()))
3666 .into_any_element()
3667 } else if is_generating && is_editor_empty {
3668 IconButton::new("stop-generation", IconName::Stop)
3669 .icon_color(Color::Error)
3670 .style(ButtonStyle::Tinted(ui::TintColor::Error))
3671 .tooltip(move |window, cx| {
3672 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
3673 })
3674 .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
3675 .into_any_element()
3676 } else {
3677 let send_btn_tooltip = if is_editor_empty && !is_generating {
3678 "Type to Send"
3679 } else if is_generating {
3680 "Stop and Send Message"
3681 } else {
3682 "Send"
3683 };
3684
3685 IconButton::new("send-message", IconName::Send)
3686 .style(ButtonStyle::Filled)
3687 .map(|this| {
3688 if is_editor_empty && !is_generating {
3689 this.disabled(true).icon_color(Color::Muted)
3690 } else {
3691 this.icon_color(Color::Accent)
3692 }
3693 })
3694 .tooltip(move |window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, window, cx))
3695 .on_click(cx.listener(|this, _, window, cx| {
3696 this.send(window, cx);
3697 }))
3698 .into_any_element()
3699 }
3700 }
3701
3702 fn is_following(&self, cx: &App) -> bool {
3703 match self.thread().map(|thread| thread.read(cx).status()) {
3704 Some(ThreadStatus::Generating) => self
3705 .workspace
3706 .read_with(cx, |workspace, _| {
3707 workspace.is_being_followed(CollaboratorId::Agent)
3708 })
3709 .unwrap_or(false),
3710 _ => self.should_be_following,
3711 }
3712 }
3713
3714 fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3715 let following = self.is_following(cx);
3716
3717 self.should_be_following = !following;
3718 if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
3719 self.workspace
3720 .update(cx, |workspace, cx| {
3721 if following {
3722 workspace.unfollow(CollaboratorId::Agent, window, cx);
3723 } else {
3724 workspace.follow(CollaboratorId::Agent, window, cx);
3725 }
3726 })
3727 .ok();
3728 }
3729
3730 telemetry::event!("Follow Agent Selected", following = !following);
3731 }
3732
3733 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
3734 let following = self.is_following(cx);
3735
3736 let tooltip_label = if following {
3737 if self.agent.name() == "Zed Agent" {
3738 format!("Stop Following the {}", self.agent.name())
3739 } else {
3740 format!("Stop Following {}", self.agent.name())
3741 }
3742 } else {
3743 if self.agent.name() == "Zed Agent" {
3744 format!("Follow the {}", self.agent.name())
3745 } else {
3746 format!("Follow {}", self.agent.name())
3747 }
3748 };
3749
3750 IconButton::new("follow-agent", IconName::Crosshair)
3751 .icon_size(IconSize::Small)
3752 .icon_color(Color::Muted)
3753 .toggle_state(following)
3754 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
3755 .tooltip(move |window, cx| {
3756 if following {
3757 Tooltip::for_action(tooltip_label.clone(), &Follow, window, cx)
3758 } else {
3759 Tooltip::with_meta(
3760 tooltip_label.clone(),
3761 Some(&Follow),
3762 "Track the agent's location as it reads and edits files.",
3763 window,
3764 cx,
3765 )
3766 }
3767 })
3768 .on_click(cx.listener(move |this, _, window, cx| {
3769 this.toggle_following(window, cx);
3770 }))
3771 }
3772
3773 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
3774 let workspace = self.workspace.clone();
3775 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
3776 Self::open_link(text, &workspace, window, cx);
3777 })
3778 }
3779
3780 fn open_link(
3781 url: SharedString,
3782 workspace: &WeakEntity<Workspace>,
3783 window: &mut Window,
3784 cx: &mut App,
3785 ) {
3786 let Some(workspace) = workspace.upgrade() else {
3787 cx.open_url(&url);
3788 return;
3789 };
3790
3791 if let Some(mention) = MentionUri::parse(&url).log_err() {
3792 workspace.update(cx, |workspace, cx| match mention {
3793 MentionUri::File { abs_path } => {
3794 let project = workspace.project();
3795 let Some(path) =
3796 project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
3797 else {
3798 return;
3799 };
3800
3801 workspace
3802 .open_path(path, None, true, window, cx)
3803 .detach_and_log_err(cx);
3804 }
3805 MentionUri::PastedImage => {}
3806 MentionUri::Directory { abs_path } => {
3807 let project = workspace.project();
3808 let Some(entry) = project.update(cx, |project, cx| {
3809 let path = project.find_project_path(abs_path, cx)?;
3810 project.entry_for_path(&path, cx)
3811 }) else {
3812 return;
3813 };
3814
3815 project.update(cx, |_, cx| {
3816 cx.emit(project::Event::RevealInProjectPanel(entry.id));
3817 });
3818 }
3819 MentionUri::Symbol {
3820 abs_path: path,
3821 line_range,
3822 ..
3823 }
3824 | MentionUri::Selection {
3825 abs_path: Some(path),
3826 line_range,
3827 } => {
3828 let project = workspace.project();
3829 let Some((path, _)) = project.update(cx, |project, cx| {
3830 let path = project.find_project_path(path, cx)?;
3831 let entry = project.entry_for_path(&path, cx)?;
3832 Some((path, entry))
3833 }) else {
3834 return;
3835 };
3836
3837 let item = workspace.open_path(path, None, true, window, cx);
3838 window
3839 .spawn(cx, async move |cx| {
3840 let Some(editor) = item.await?.downcast::<Editor>() else {
3841 return Ok(());
3842 };
3843 let range = Point::new(*line_range.start(), 0)
3844 ..Point::new(*line_range.start(), 0);
3845 editor
3846 .update_in(cx, |editor, window, cx| {
3847 editor.change_selections(
3848 SelectionEffects::scroll(Autoscroll::center()),
3849 window,
3850 cx,
3851 |s| s.select_ranges(vec![range]),
3852 );
3853 })
3854 .ok();
3855 anyhow::Ok(())
3856 })
3857 .detach_and_log_err(cx);
3858 }
3859 MentionUri::Selection { abs_path: None, .. } => {}
3860 MentionUri::Thread { id, name } => {
3861 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3862 panel.update(cx, |panel, cx| {
3863 panel.load_agent_thread(
3864 DbThreadMetadata {
3865 id,
3866 title: name.into(),
3867 updated_at: Default::default(),
3868 },
3869 window,
3870 cx,
3871 )
3872 });
3873 }
3874 }
3875 MentionUri::TextThread { path, .. } => {
3876 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3877 panel.update(cx, |panel, cx| {
3878 panel
3879 .open_saved_prompt_editor(path.as_path().into(), window, cx)
3880 .detach_and_log_err(cx);
3881 });
3882 }
3883 }
3884 MentionUri::Rule { id, .. } => {
3885 let PromptId::User { uuid } = id else {
3886 return;
3887 };
3888 window.dispatch_action(
3889 Box::new(OpenRulesLibrary {
3890 prompt_to_select: Some(uuid.0),
3891 }),
3892 cx,
3893 )
3894 }
3895 MentionUri::Fetch { url } => {
3896 cx.open_url(url.as_str());
3897 }
3898 })
3899 } else {
3900 cx.open_url(&url);
3901 }
3902 }
3903
3904 fn open_tool_call_location(
3905 &self,
3906 entry_ix: usize,
3907 location_ix: usize,
3908 window: &mut Window,
3909 cx: &mut Context<Self>,
3910 ) -> Option<()> {
3911 let (tool_call_location, agent_location) = self
3912 .thread()?
3913 .read(cx)
3914 .entries()
3915 .get(entry_ix)?
3916 .location(location_ix)?;
3917
3918 let project_path = self
3919 .project
3920 .read(cx)
3921 .find_project_path(&tool_call_location.path, cx)?;
3922
3923 let open_task = self
3924 .workspace
3925 .update(cx, |workspace, cx| {
3926 workspace.open_path(project_path, None, true, window, cx)
3927 })
3928 .log_err()?;
3929 window
3930 .spawn(cx, async move |cx| {
3931 let item = open_task.await?;
3932
3933 let Some(active_editor) = item.downcast::<Editor>() else {
3934 return anyhow::Ok(());
3935 };
3936
3937 active_editor.update_in(cx, |editor, window, cx| {
3938 let multibuffer = editor.buffer().read(cx);
3939 let buffer = multibuffer.as_singleton();
3940 if agent_location.buffer.upgrade() == buffer {
3941 let excerpt_id = multibuffer.excerpt_ids().first().cloned();
3942 let anchor = editor::Anchor::in_buffer(
3943 excerpt_id.unwrap(),
3944 buffer.unwrap().read(cx).remote_id(),
3945 agent_location.position,
3946 );
3947 editor.change_selections(Default::default(), window, cx, |selections| {
3948 selections.select_anchor_ranges([anchor..anchor]);
3949 })
3950 } else {
3951 let row = tool_call_location.line.unwrap_or_default();
3952 editor.change_selections(Default::default(), window, cx, |selections| {
3953 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
3954 })
3955 }
3956 })?;
3957
3958 anyhow::Ok(())
3959 })
3960 .detach_and_log_err(cx);
3961
3962 None
3963 }
3964
3965 pub fn open_thread_as_markdown(
3966 &self,
3967 workspace: Entity<Workspace>,
3968 window: &mut Window,
3969 cx: &mut App,
3970 ) -> Task<anyhow::Result<()>> {
3971 let markdown_language_task = workspace
3972 .read(cx)
3973 .app_state()
3974 .languages
3975 .language_for_name("Markdown");
3976
3977 let (thread_summary, markdown) = if let Some(thread) = self.thread() {
3978 let thread = thread.read(cx);
3979 (thread.title().to_string(), thread.to_markdown(cx))
3980 } else {
3981 return Task::ready(Ok(()));
3982 };
3983
3984 window.spawn(cx, async move |cx| {
3985 let markdown_language = markdown_language_task.await?;
3986
3987 workspace.update_in(cx, |workspace, window, cx| {
3988 let project = workspace.project().clone();
3989
3990 if !project.read(cx).is_local() {
3991 bail!("failed to open active thread as markdown in remote project");
3992 }
3993
3994 let buffer = project.update(cx, |project, cx| {
3995 project.create_local_buffer(&markdown, Some(markdown_language), cx)
3996 });
3997 let buffer = cx.new(|cx| {
3998 MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
3999 });
4000
4001 workspace.add_item_to_active_pane(
4002 Box::new(cx.new(|cx| {
4003 let mut editor =
4004 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4005 editor.set_breadcrumb_header(thread_summary);
4006 editor
4007 })),
4008 None,
4009 true,
4010 window,
4011 cx,
4012 );
4013
4014 anyhow::Ok(())
4015 })??;
4016 anyhow::Ok(())
4017 })
4018 }
4019
4020 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
4021 self.list_state.scroll_to(ListOffset::default());
4022 cx.notify();
4023 }
4024
4025 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
4026 if let Some(thread) = self.thread() {
4027 let entry_count = thread.read(cx).entries().len();
4028 self.list_state.reset(entry_count);
4029 cx.notify();
4030 }
4031 }
4032
4033 fn notify_with_sound(
4034 &mut self,
4035 caption: impl Into<SharedString>,
4036 icon: IconName,
4037 window: &mut Window,
4038 cx: &mut Context<Self>,
4039 ) {
4040 self.play_notification_sound(window, cx);
4041 self.show_notification(caption, icon, window, cx);
4042 }
4043
4044 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
4045 let settings = AgentSettings::get_global(cx);
4046 if settings.play_sound_when_agent_done && !window.is_window_active() {
4047 Audio::play_sound(Sound::AgentDone, cx);
4048 }
4049 }
4050
4051 fn show_notification(
4052 &mut self,
4053 caption: impl Into<SharedString>,
4054 icon: IconName,
4055 window: &mut Window,
4056 cx: &mut Context<Self>,
4057 ) {
4058 if window.is_window_active() || !self.notifications.is_empty() {
4059 return;
4060 }
4061
4062 // TODO: Change this once we have title summarization for external agents.
4063 let title = self.agent.name();
4064
4065 match AgentSettings::get_global(cx).notify_when_agent_waiting {
4066 NotifyWhenAgentWaiting::PrimaryScreen => {
4067 if let Some(primary) = cx.primary_display() {
4068 self.pop_up(icon, caption.into(), title, window, primary, cx);
4069 }
4070 }
4071 NotifyWhenAgentWaiting::AllScreens => {
4072 let caption = caption.into();
4073 for screen in cx.displays() {
4074 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
4075 }
4076 }
4077 NotifyWhenAgentWaiting::Never => {
4078 // Don't show anything
4079 }
4080 }
4081 }
4082
4083 fn pop_up(
4084 &mut self,
4085 icon: IconName,
4086 caption: SharedString,
4087 title: SharedString,
4088 window: &mut Window,
4089 screen: Rc<dyn PlatformDisplay>,
4090 cx: &mut Context<Self>,
4091 ) {
4092 let options = AgentNotification::window_options(screen, cx);
4093
4094 let project_name = self.workspace.upgrade().and_then(|workspace| {
4095 workspace
4096 .read(cx)
4097 .project()
4098 .read(cx)
4099 .visible_worktrees(cx)
4100 .next()
4101 .map(|worktree| worktree.read(cx).root_name().to_string())
4102 });
4103
4104 if let Some(screen_window) = cx
4105 .open_window(options, |_, cx| {
4106 cx.new(|_| {
4107 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
4108 })
4109 })
4110 .log_err()
4111 && let Some(pop_up) = screen_window.entity(cx).log_err()
4112 {
4113 self.notification_subscriptions
4114 .entry(screen_window)
4115 .or_insert_with(Vec::new)
4116 .push(cx.subscribe_in(&pop_up, window, {
4117 |this, _, event, window, cx| match event {
4118 AgentNotificationEvent::Accepted => {
4119 let handle = window.window_handle();
4120 cx.activate(true);
4121
4122 let workspace_handle = this.workspace.clone();
4123
4124 // If there are multiple Zed windows, activate the correct one.
4125 cx.defer(move |cx| {
4126 handle
4127 .update(cx, |_view, window, _cx| {
4128 window.activate_window();
4129
4130 if let Some(workspace) = workspace_handle.upgrade() {
4131 workspace.update(_cx, |workspace, cx| {
4132 workspace.focus_panel::<AgentPanel>(window, cx);
4133 });
4134 }
4135 })
4136 .log_err();
4137 });
4138
4139 this.dismiss_notifications(cx);
4140 }
4141 AgentNotificationEvent::Dismissed => {
4142 this.dismiss_notifications(cx);
4143 }
4144 }
4145 }));
4146
4147 self.notifications.push(screen_window);
4148
4149 // If the user manually refocuses the original window, dismiss the popup.
4150 self.notification_subscriptions
4151 .entry(screen_window)
4152 .or_insert_with(Vec::new)
4153 .push({
4154 let pop_up_weak = pop_up.downgrade();
4155
4156 cx.observe_window_activation(window, move |_, window, cx| {
4157 if window.is_window_active()
4158 && let Some(pop_up) = pop_up_weak.upgrade()
4159 {
4160 pop_up.update(cx, |_, cx| {
4161 cx.emit(AgentNotificationEvent::Dismissed);
4162 });
4163 }
4164 })
4165 });
4166 }
4167 }
4168
4169 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
4170 for window in self.notifications.drain(..) {
4171 window
4172 .update(cx, |_, window, _| {
4173 window.remove_window();
4174 })
4175 .ok();
4176
4177 self.notification_subscriptions.remove(&window);
4178 }
4179 }
4180
4181 fn render_thread_controls(
4182 &self,
4183 thread: &Entity<AcpThread>,
4184 cx: &Context<Self>,
4185 ) -> impl IntoElement {
4186 let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
4187 if is_generating {
4188 return h_flex().id("thread-controls-container").child(
4189 div()
4190 .py_2()
4191 .px(rems_from_px(22.))
4192 .child(SpinnerLabel::new().size(LabelSize::Small)),
4193 );
4194 }
4195
4196 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
4197 .shape(ui::IconButtonShape::Square)
4198 .icon_size(IconSize::Small)
4199 .icon_color(Color::Ignored)
4200 .tooltip(Tooltip::text("Open Thread as Markdown"))
4201 .on_click(cx.listener(move |this, _, window, cx| {
4202 if let Some(workspace) = this.workspace.upgrade() {
4203 this.open_thread_as_markdown(workspace, window, cx)
4204 .detach_and_log_err(cx);
4205 }
4206 }));
4207
4208 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
4209 .shape(ui::IconButtonShape::Square)
4210 .icon_size(IconSize::Small)
4211 .icon_color(Color::Ignored)
4212 .tooltip(Tooltip::text("Scroll To Top"))
4213 .on_click(cx.listener(move |this, _, _, cx| {
4214 this.scroll_to_top(cx);
4215 }));
4216
4217 let mut container = h_flex()
4218 .id("thread-controls-container")
4219 .group("thread-controls-container")
4220 .w_full()
4221 .py_2()
4222 .px_5()
4223 .gap_px()
4224 .opacity(0.6)
4225 .hover(|style| style.opacity(1.))
4226 .flex_wrap()
4227 .justify_end();
4228
4229 if AgentSettings::get_global(cx).enable_feedback
4230 && self
4231 .thread()
4232 .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
4233 {
4234 let feedback = self.thread_feedback.feedback;
4235
4236 container = container
4237 .child(
4238 div().visible_on_hover("thread-controls-container").child(
4239 Label::new(match feedback {
4240 Some(ThreadFeedback::Positive) => "Thanks for your feedback!",
4241 Some(ThreadFeedback::Negative) => {
4242 "We appreciate your feedback and will use it to improve."
4243 }
4244 None => {
4245 "Rating the thread sends all of your current conversation to the Zed team."
4246 }
4247 })
4248 .color(Color::Muted)
4249 .size(LabelSize::XSmall)
4250 .truncate(),
4251 ),
4252 )
4253 .child(
4254 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
4255 .shape(ui::IconButtonShape::Square)
4256 .icon_size(IconSize::Small)
4257 .icon_color(match feedback {
4258 Some(ThreadFeedback::Positive) => Color::Accent,
4259 _ => Color::Ignored,
4260 })
4261 .tooltip(Tooltip::text("Helpful Response"))
4262 .on_click(cx.listener(move |this, _, window, cx| {
4263 this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
4264 })),
4265 )
4266 .child(
4267 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
4268 .shape(ui::IconButtonShape::Square)
4269 .icon_size(IconSize::Small)
4270 .icon_color(match feedback {
4271 Some(ThreadFeedback::Negative) => Color::Accent,
4272 _ => Color::Ignored,
4273 })
4274 .tooltip(Tooltip::text("Not Helpful"))
4275 .on_click(cx.listener(move |this, _, window, cx| {
4276 this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
4277 })),
4278 );
4279 }
4280
4281 container.child(open_as_markdown).child(scroll_to_top)
4282 }
4283
4284 fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
4285 h_flex()
4286 .key_context("AgentFeedbackMessageEditor")
4287 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
4288 this.thread_feedback.dismiss_comments();
4289 cx.notify();
4290 }))
4291 .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
4292 this.submit_feedback_message(cx);
4293 }))
4294 .p_2()
4295 .mb_2()
4296 .mx_5()
4297 .gap_1()
4298 .rounded_md()
4299 .border_1()
4300 .border_color(cx.theme().colors().border)
4301 .bg(cx.theme().colors().editor_background)
4302 .child(div().w_full().child(editor))
4303 .child(
4304 h_flex()
4305 .child(
4306 IconButton::new("dismiss-feedback-message", IconName::Close)
4307 .icon_color(Color::Error)
4308 .icon_size(IconSize::XSmall)
4309 .shape(ui::IconButtonShape::Square)
4310 .on_click(cx.listener(move |this, _, _window, cx| {
4311 this.thread_feedback.dismiss_comments();
4312 cx.notify();
4313 })),
4314 )
4315 .child(
4316 IconButton::new("submit-feedback-message", IconName::Return)
4317 .icon_size(IconSize::XSmall)
4318 .shape(ui::IconButtonShape::Square)
4319 .on_click(cx.listener(move |this, _, _window, cx| {
4320 this.submit_feedback_message(cx);
4321 })),
4322 ),
4323 )
4324 }
4325
4326 fn handle_feedback_click(
4327 &mut self,
4328 feedback: ThreadFeedback,
4329 window: &mut Window,
4330 cx: &mut Context<Self>,
4331 ) {
4332 let Some(thread) = self.thread().cloned() else {
4333 return;
4334 };
4335
4336 self.thread_feedback.submit(thread, feedback, window, cx);
4337 cx.notify();
4338 }
4339
4340 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
4341 let Some(thread) = self.thread().cloned() else {
4342 return;
4343 };
4344
4345 self.thread_feedback.submit_comments(thread, cx);
4346 cx.notify();
4347 }
4348
4349 fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
4350 div()
4351 .id("acp-thread-scrollbar")
4352 .occlude()
4353 .on_mouse_move(cx.listener(|_, _, _, cx| {
4354 cx.notify();
4355 cx.stop_propagation()
4356 }))
4357 .on_hover(|_, _, cx| {
4358 cx.stop_propagation();
4359 })
4360 .on_any_mouse_down(|_, _, cx| {
4361 cx.stop_propagation();
4362 })
4363 .on_mouse_up(
4364 MouseButton::Left,
4365 cx.listener(|_, _, _, cx| {
4366 cx.stop_propagation();
4367 }),
4368 )
4369 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
4370 cx.notify();
4371 }))
4372 .h_full()
4373 .absolute()
4374 .right_1()
4375 .top_1()
4376 .bottom_0()
4377 .w(px(12.))
4378 .cursor_default()
4379 .children(Scrollbar::vertical(self.scrollbar_state.clone()).map(|s| s.auto_hide(cx)))
4380 }
4381
4382 fn render_token_limit_callout(
4383 &self,
4384 line_height: Pixels,
4385 cx: &mut Context<Self>,
4386 ) -> Option<Callout> {
4387 let token_usage = self.thread()?.read(cx).token_usage()?;
4388 let ratio = token_usage.ratio();
4389
4390 let (severity, title) = match ratio {
4391 acp_thread::TokenUsageRatio::Normal => return None,
4392 acp_thread::TokenUsageRatio::Warning => {
4393 (Severity::Warning, "Thread reaching the token limit soon")
4394 }
4395 acp_thread::TokenUsageRatio::Exceeded => {
4396 (Severity::Error, "Thread reached the token limit")
4397 }
4398 };
4399
4400 let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
4401 thread.read(cx).completion_mode() == CompletionMode::Normal
4402 && thread
4403 .read(cx)
4404 .model()
4405 .is_some_and(|model| model.supports_burn_mode())
4406 });
4407
4408 let description = if burn_mode_available {
4409 "To continue, start a new thread from a summary or turn Burn Mode on."
4410 } else {
4411 "To continue, start a new thread from a summary."
4412 };
4413
4414 Some(
4415 Callout::new()
4416 .severity(severity)
4417 .line_height(line_height)
4418 .title(title)
4419 .description(description)
4420 .actions_slot(
4421 h_flex()
4422 .gap_0p5()
4423 .child(
4424 Button::new("start-new-thread", "Start New Thread")
4425 .label_size(LabelSize::Small)
4426 .on_click(cx.listener(|this, _, window, cx| {
4427 let Some(thread) = this.thread() else {
4428 return;
4429 };
4430 let session_id = thread.read(cx).session_id().clone();
4431 window.dispatch_action(
4432 crate::NewNativeAgentThreadFromSummary {
4433 from_session_id: session_id,
4434 }
4435 .boxed_clone(),
4436 cx,
4437 );
4438 })),
4439 )
4440 .when(burn_mode_available, |this| {
4441 this.child(
4442 IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
4443 .icon_size(IconSize::XSmall)
4444 .on_click(cx.listener(|this, _event, window, cx| {
4445 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4446 })),
4447 )
4448 }),
4449 ),
4450 )
4451 }
4452
4453 fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
4454 if !self.is_using_zed_ai_models(cx) {
4455 return None;
4456 }
4457
4458 let user_store = self.project.read(cx).user_store().read(cx);
4459 if user_store.is_usage_based_billing_enabled() {
4460 return None;
4461 }
4462
4463 let plan = user_store.plan().unwrap_or(cloud_llm_client::Plan::ZedFree);
4464
4465 let usage = user_store.model_request_usage()?;
4466
4467 Some(
4468 div()
4469 .child(UsageCallout::new(plan, usage))
4470 .line_height(line_height),
4471 )
4472 }
4473
4474 fn settings_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
4475 self.entry_view_state.update(cx, |entry_view_state, cx| {
4476 entry_view_state.settings_changed(cx);
4477 });
4478 }
4479
4480 pub(crate) fn insert_dragged_files(
4481 &self,
4482 paths: Vec<project::ProjectPath>,
4483 added_worktrees: Vec<Entity<project::Worktree>>,
4484 window: &mut Window,
4485 cx: &mut Context<Self>,
4486 ) {
4487 self.message_editor.update(cx, |message_editor, cx| {
4488 message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
4489 })
4490 }
4491
4492 pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
4493 self.message_editor.update(cx, |message_editor, cx| {
4494 message_editor.insert_selections(window, cx);
4495 })
4496 }
4497
4498 fn render_thread_retry_status_callout(
4499 &self,
4500 _window: &mut Window,
4501 _cx: &mut Context<Self>,
4502 ) -> Option<Callout> {
4503 let state = self.thread_retry_status.as_ref()?;
4504
4505 let next_attempt_in = state
4506 .duration
4507 .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
4508 if next_attempt_in.is_zero() {
4509 return None;
4510 }
4511
4512 let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
4513
4514 let retry_message = if state.max_attempts == 1 {
4515 if next_attempt_in_secs == 1 {
4516 "Retrying. Next attempt in 1 second.".to_string()
4517 } else {
4518 format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
4519 }
4520 } else if next_attempt_in_secs == 1 {
4521 format!(
4522 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
4523 state.attempt, state.max_attempts,
4524 )
4525 } else {
4526 format!(
4527 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
4528 state.attempt, state.max_attempts,
4529 )
4530 };
4531
4532 Some(
4533 Callout::new()
4534 .severity(Severity::Warning)
4535 .title(state.last_error.clone())
4536 .description(retry_message),
4537 )
4538 }
4539
4540 fn render_thread_error(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
4541 let content = match self.thread_error.as_ref()? {
4542 ThreadError::Other(error) => self.render_any_thread_error(error.clone(), cx),
4543 ThreadError::AuthenticationRequired(error) => {
4544 self.render_authentication_required_error(error.clone(), cx)
4545 }
4546 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
4547 ThreadError::ModelRequestLimitReached(plan) => {
4548 self.render_model_request_limit_reached_error(*plan, cx)
4549 }
4550 ThreadError::ToolUseLimitReached => {
4551 self.render_tool_use_limit_reached_error(window, cx)?
4552 }
4553 };
4554
4555 Some(div().child(content))
4556 }
4557
4558 fn render_any_thread_error(&self, error: SharedString, cx: &mut Context<'_, Self>) -> Callout {
4559 let can_resume = self
4560 .thread()
4561 .map_or(false, |thread| thread.read(cx).can_resume(cx));
4562
4563 let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
4564 let thread = thread.read(cx);
4565 let supports_burn_mode = thread
4566 .model()
4567 .map_or(false, |model| model.supports_burn_mode());
4568 supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
4569 });
4570
4571 Callout::new()
4572 .severity(Severity::Error)
4573 .title("Error")
4574 .icon(IconName::XCircle)
4575 .description(error.clone())
4576 .actions_slot(
4577 h_flex()
4578 .gap_0p5()
4579 .when(can_resume && can_enable_burn_mode, |this| {
4580 this.child(
4581 Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
4582 .icon(IconName::ZedBurnMode)
4583 .icon_position(IconPosition::Start)
4584 .icon_size(IconSize::Small)
4585 .label_size(LabelSize::Small)
4586 .on_click(cx.listener(|this, _, window, cx| {
4587 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4588 this.resume_chat(cx);
4589 })),
4590 )
4591 })
4592 .when(can_resume, |this| {
4593 this.child(
4594 Button::new("retry", "Retry")
4595 .icon(IconName::RotateCw)
4596 .icon_position(IconPosition::Start)
4597 .icon_size(IconSize::Small)
4598 .label_size(LabelSize::Small)
4599 .on_click(cx.listener(|this, _, _window, cx| {
4600 this.resume_chat(cx);
4601 })),
4602 )
4603 })
4604 .child(self.create_copy_button(error.to_string())),
4605 )
4606 .dismiss_action(self.dismiss_error_button(cx))
4607 }
4608
4609 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
4610 const ERROR_MESSAGE: &str =
4611 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
4612
4613 Callout::new()
4614 .severity(Severity::Error)
4615 .icon(IconName::XCircle)
4616 .title("Free Usage Exceeded")
4617 .description(ERROR_MESSAGE)
4618 .actions_slot(
4619 h_flex()
4620 .gap_0p5()
4621 .child(self.upgrade_button(cx))
4622 .child(self.create_copy_button(ERROR_MESSAGE)),
4623 )
4624 .dismiss_action(self.dismiss_error_button(cx))
4625 }
4626
4627 fn render_authentication_required_error(
4628 &self,
4629 error: SharedString,
4630 cx: &mut Context<Self>,
4631 ) -> Callout {
4632 Callout::new()
4633 .severity(Severity::Error)
4634 .title("Authentication Required")
4635 .icon(IconName::XCircle)
4636 .description(error.clone())
4637 .actions_slot(
4638 h_flex()
4639 .gap_0p5()
4640 .child(self.authenticate_button(cx))
4641 .child(self.create_copy_button(error)),
4642 )
4643 .dismiss_action(self.dismiss_error_button(cx))
4644 }
4645
4646 fn render_model_request_limit_reached_error(
4647 &self,
4648 plan: cloud_llm_client::Plan,
4649 cx: &mut Context<Self>,
4650 ) -> Callout {
4651 let error_message = match plan {
4652 cloud_llm_client::Plan::ZedPro => "Upgrade to usage-based billing for more prompts.",
4653 cloud_llm_client::Plan::ZedProTrial | cloud_llm_client::Plan::ZedFree => {
4654 "Upgrade to Zed Pro for more prompts."
4655 }
4656 };
4657
4658 Callout::new()
4659 .severity(Severity::Error)
4660 .title("Model Prompt Limit Reached")
4661 .icon(IconName::XCircle)
4662 .description(error_message)
4663 .actions_slot(
4664 h_flex()
4665 .gap_0p5()
4666 .child(self.upgrade_button(cx))
4667 .child(self.create_copy_button(error_message)),
4668 )
4669 .dismiss_action(self.dismiss_error_button(cx))
4670 }
4671
4672 fn render_tool_use_limit_reached_error(
4673 &self,
4674 window: &mut Window,
4675 cx: &mut Context<Self>,
4676 ) -> Option<Callout> {
4677 let thread = self.as_native_thread(cx)?;
4678 let supports_burn_mode = thread
4679 .read(cx)
4680 .model()
4681 .is_some_and(|model| model.supports_burn_mode());
4682
4683 let focus_handle = self.focus_handle(cx);
4684
4685 Some(
4686 Callout::new()
4687 .icon(IconName::Info)
4688 .title("Consecutive tool use limit reached.")
4689 .actions_slot(
4690 h_flex()
4691 .gap_0p5()
4692 .when(supports_burn_mode, |this| {
4693 this.child(
4694 Button::new("continue-burn-mode", "Continue with Burn Mode")
4695 .style(ButtonStyle::Filled)
4696 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
4697 .layer(ElevationIndex::ModalSurface)
4698 .label_size(LabelSize::Small)
4699 .key_binding(
4700 KeyBinding::for_action_in(
4701 &ContinueWithBurnMode,
4702 &focus_handle,
4703 window,
4704 cx,
4705 )
4706 .map(|kb| kb.size(rems_from_px(10.))),
4707 )
4708 .tooltip(Tooltip::text(
4709 "Enable Burn Mode for unlimited tool use.",
4710 ))
4711 .on_click({
4712 cx.listener(move |this, _, _window, cx| {
4713 thread.update(cx, |thread, cx| {
4714 thread
4715 .set_completion_mode(CompletionMode::Burn, cx);
4716 });
4717 this.resume_chat(cx);
4718 })
4719 }),
4720 )
4721 })
4722 .child(
4723 Button::new("continue-conversation", "Continue")
4724 .layer(ElevationIndex::ModalSurface)
4725 .label_size(LabelSize::Small)
4726 .key_binding(
4727 KeyBinding::for_action_in(
4728 &ContinueThread,
4729 &focus_handle,
4730 window,
4731 cx,
4732 )
4733 .map(|kb| kb.size(rems_from_px(10.))),
4734 )
4735 .on_click(cx.listener(|this, _, _window, cx| {
4736 this.resume_chat(cx);
4737 })),
4738 ),
4739 ),
4740 )
4741 }
4742
4743 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
4744 let message = message.into();
4745
4746 IconButton::new("copy", IconName::Copy)
4747 .icon_size(IconSize::Small)
4748 .icon_color(Color::Muted)
4749 .tooltip(Tooltip::text("Copy Error Message"))
4750 .on_click(move |_, _, cx| {
4751 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
4752 })
4753 }
4754
4755 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4756 IconButton::new("dismiss", IconName::Close)
4757 .icon_size(IconSize::Small)
4758 .icon_color(Color::Muted)
4759 .tooltip(Tooltip::text("Dismiss Error"))
4760 .on_click(cx.listener({
4761 move |this, _, _, cx| {
4762 this.clear_thread_error(cx);
4763 cx.notify();
4764 }
4765 }))
4766 }
4767
4768 fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4769 Button::new("authenticate", "Authenticate")
4770 .label_size(LabelSize::Small)
4771 .style(ButtonStyle::Filled)
4772 .on_click(cx.listener({
4773 move |this, _, window, cx| {
4774 let agent = this.agent.clone();
4775 let ThreadState::Ready { thread, .. } = &this.thread_state else {
4776 return;
4777 };
4778
4779 let connection = thread.read(cx).connection().clone();
4780 let err = AuthRequired {
4781 description: None,
4782 provider_id: None,
4783 };
4784 this.clear_thread_error(cx);
4785 let this = cx.weak_entity();
4786 window.defer(cx, |window, cx| {
4787 Self::handle_auth_required(this, err, agent, connection, window, cx);
4788 })
4789 }
4790 }))
4791 }
4792
4793 pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4794 let agent = self.agent.clone();
4795 let ThreadState::Ready { thread, .. } = &self.thread_state else {
4796 return;
4797 };
4798
4799 let connection = thread.read(cx).connection().clone();
4800 let err = AuthRequired {
4801 description: None,
4802 provider_id: None,
4803 };
4804 self.clear_thread_error(cx);
4805 let this = cx.weak_entity();
4806 window.defer(cx, |window, cx| {
4807 Self::handle_auth_required(this, err, agent, connection, window, cx);
4808 })
4809 }
4810
4811 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4812 Button::new("upgrade", "Upgrade")
4813 .label_size(LabelSize::Small)
4814 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
4815 .on_click(cx.listener({
4816 move |this, _, _, cx| {
4817 this.clear_thread_error(cx);
4818 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
4819 }
4820 }))
4821 }
4822
4823 pub fn delete_history_entry(&mut self, entry: HistoryEntry, cx: &mut Context<Self>) {
4824 let task = match entry {
4825 HistoryEntry::AcpThread(thread) => self.history_store.update(cx, |history, cx| {
4826 history.delete_thread(thread.id.clone(), cx)
4827 }),
4828 HistoryEntry::TextThread(context) => self.history_store.update(cx, |history, cx| {
4829 history.delete_text_thread(context.path.clone(), cx)
4830 }),
4831 };
4832 task.detach_and_log_err(cx);
4833 }
4834}
4835
4836fn loading_contents_spinner(size: IconSize) -> AnyElement {
4837 Icon::new(IconName::LoadCircle)
4838 .size(size)
4839 .color(Color::Accent)
4840 .with_animation(
4841 "load_context_circle",
4842 Animation::new(Duration::from_secs(3)).repeat(),
4843 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
4844 )
4845 .into_any_element()
4846}
4847
4848impl Focusable for AcpThreadView {
4849 fn focus_handle(&self, cx: &App) -> FocusHandle {
4850 match self.thread_state {
4851 ThreadState::Loading { .. } | ThreadState::Ready { .. } => {
4852 self.message_editor.focus_handle(cx)
4853 }
4854 ThreadState::LoadError(_) | ThreadState::Unauthenticated { .. } => {
4855 self.focus_handle.clone()
4856 }
4857 }
4858 }
4859}
4860
4861impl Render for AcpThreadView {
4862 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4863 let has_messages = self.list_state.item_count() > 0;
4864 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
4865
4866 v_flex()
4867 .size_full()
4868 .key_context("AcpThread")
4869 .on_action(cx.listener(Self::open_agent_diff))
4870 .on_action(cx.listener(Self::toggle_burn_mode))
4871 .on_action(cx.listener(Self::keep_all))
4872 .on_action(cx.listener(Self::reject_all))
4873 .track_focus(&self.focus_handle)
4874 .bg(cx.theme().colors().panel_background)
4875 .child(match &self.thread_state {
4876 ThreadState::Unauthenticated {
4877 connection,
4878 description,
4879 configuration_view,
4880 pending_auth_method,
4881 ..
4882 } => self.render_auth_required_state(
4883 connection,
4884 description.as_ref(),
4885 configuration_view.as_ref(),
4886 pending_auth_method.as_ref(),
4887 window,
4888 cx,
4889 ),
4890 ThreadState::Loading { .. } => v_flex()
4891 .flex_1()
4892 .child(self.render_recent_history(window, cx)),
4893 ThreadState::LoadError(e) => v_flex()
4894 .flex_1()
4895 .size_full()
4896 .items_center()
4897 .justify_end()
4898 .child(self.render_load_error(e, window, cx)),
4899 ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
4900 if has_messages {
4901 this.child(
4902 list(
4903 self.list_state.clone(),
4904 cx.processor(|this, index: usize, window, cx| {
4905 let Some((entry, len)) = this.thread().and_then(|thread| {
4906 let entries = &thread.read(cx).entries();
4907 Some((entries.get(index)?, entries.len()))
4908 }) else {
4909 return Empty.into_any();
4910 };
4911 this.render_entry(index, len, entry, window, cx)
4912 }),
4913 )
4914 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
4915 .flex_grow()
4916 .into_any(),
4917 )
4918 .child(self.render_vertical_scrollbar(cx))
4919 } else {
4920 this.child(self.render_recent_history(window, cx))
4921 }
4922 }),
4923 })
4924 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
4925 // above so that the scrollbar doesn't render behind it. The current setup allows
4926 // the scrollbar to stop exactly at the activity bar start.
4927 .when(has_messages, |this| match &self.thread_state {
4928 ThreadState::Ready { thread, .. } => {
4929 this.children(self.render_activity_bar(thread, window, cx))
4930 }
4931 _ => this,
4932 })
4933 .children(self.render_thread_retry_status_callout(window, cx))
4934 .children(self.render_thread_error(window, cx))
4935 .children(
4936 if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
4937 Some(usage_callout.into_any_element())
4938 } else {
4939 self.render_token_limit_callout(line_height, cx)
4940 .map(|token_limit_callout| token_limit_callout.into_any_element())
4941 },
4942 )
4943 .child(self.render_message_editor(window, cx))
4944 }
4945}
4946
4947fn default_markdown_style(
4948 buffer_font: bool,
4949 muted_text: bool,
4950 window: &Window,
4951 cx: &App,
4952) -> MarkdownStyle {
4953 let theme_settings = ThemeSettings::get_global(cx);
4954 let colors = cx.theme().colors();
4955
4956 let buffer_font_size = TextSize::Small.rems(cx);
4957
4958 let mut text_style = window.text_style();
4959 let line_height = buffer_font_size * 1.75;
4960
4961 let font_family = if buffer_font {
4962 theme_settings.buffer_font.family.clone()
4963 } else {
4964 theme_settings.ui_font.family.clone()
4965 };
4966
4967 let font_size = if buffer_font {
4968 TextSize::Small.rems(cx)
4969 } else {
4970 TextSize::Default.rems(cx)
4971 };
4972
4973 let text_color = if muted_text {
4974 colors.text_muted
4975 } else {
4976 colors.text
4977 };
4978
4979 text_style.refine(&TextStyleRefinement {
4980 font_family: Some(font_family),
4981 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
4982 font_features: Some(theme_settings.ui_font.features.clone()),
4983 font_size: Some(font_size.into()),
4984 line_height: Some(line_height.into()),
4985 color: Some(text_color),
4986 ..Default::default()
4987 });
4988
4989 MarkdownStyle {
4990 base_text_style: text_style.clone(),
4991 syntax: cx.theme().syntax().clone(),
4992 selection_background_color: colors.element_selection_background,
4993 code_block_overflow_x_scroll: true,
4994 table_overflow_x_scroll: true,
4995 heading_level_styles: Some(HeadingLevelStyles {
4996 h1: Some(TextStyleRefinement {
4997 font_size: Some(rems(1.15).into()),
4998 ..Default::default()
4999 }),
5000 h2: Some(TextStyleRefinement {
5001 font_size: Some(rems(1.1).into()),
5002 ..Default::default()
5003 }),
5004 h3: Some(TextStyleRefinement {
5005 font_size: Some(rems(1.05).into()),
5006 ..Default::default()
5007 }),
5008 h4: Some(TextStyleRefinement {
5009 font_size: Some(rems(1.).into()),
5010 ..Default::default()
5011 }),
5012 h5: Some(TextStyleRefinement {
5013 font_size: Some(rems(0.95).into()),
5014 ..Default::default()
5015 }),
5016 h6: Some(TextStyleRefinement {
5017 font_size: Some(rems(0.875).into()),
5018 ..Default::default()
5019 }),
5020 }),
5021 code_block: StyleRefinement {
5022 padding: EdgesRefinement {
5023 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5024 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5025 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5026 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5027 },
5028 margin: EdgesRefinement {
5029 top: Some(Length::Definite(Pixels(8.).into())),
5030 left: Some(Length::Definite(Pixels(0.).into())),
5031 right: Some(Length::Definite(Pixels(0.).into())),
5032 bottom: Some(Length::Definite(Pixels(12.).into())),
5033 },
5034 border_style: Some(BorderStyle::Solid),
5035 border_widths: EdgesRefinement {
5036 top: Some(AbsoluteLength::Pixels(Pixels(1.))),
5037 left: Some(AbsoluteLength::Pixels(Pixels(1.))),
5038 right: Some(AbsoluteLength::Pixels(Pixels(1.))),
5039 bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
5040 },
5041 border_color: Some(colors.border_variant),
5042 background: Some(colors.editor_background.into()),
5043 text: Some(TextStyleRefinement {
5044 font_family: Some(theme_settings.buffer_font.family.clone()),
5045 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5046 font_features: Some(theme_settings.buffer_font.features.clone()),
5047 font_size: Some(buffer_font_size.into()),
5048 ..Default::default()
5049 }),
5050 ..Default::default()
5051 },
5052 inline_code: TextStyleRefinement {
5053 font_family: Some(theme_settings.buffer_font.family.clone()),
5054 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5055 font_features: Some(theme_settings.buffer_font.features.clone()),
5056 font_size: Some(buffer_font_size.into()),
5057 background_color: Some(colors.editor_foreground.opacity(0.08)),
5058 ..Default::default()
5059 },
5060 link: TextStyleRefinement {
5061 background_color: Some(colors.editor_foreground.opacity(0.025)),
5062 underline: Some(UnderlineStyle {
5063 color: Some(colors.text_accent.opacity(0.5)),
5064 thickness: px(1.),
5065 ..Default::default()
5066 }),
5067 ..Default::default()
5068 },
5069 ..Default::default()
5070 }
5071}
5072
5073fn plan_label_markdown_style(
5074 status: &acp::PlanEntryStatus,
5075 window: &Window,
5076 cx: &App,
5077) -> MarkdownStyle {
5078 let default_md_style = default_markdown_style(false, false, window, cx);
5079
5080 MarkdownStyle {
5081 base_text_style: TextStyle {
5082 color: cx.theme().colors().text_muted,
5083 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
5084 Some(gpui::StrikethroughStyle {
5085 thickness: px(1.),
5086 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
5087 })
5088 } else {
5089 None
5090 },
5091 ..default_md_style.base_text_style
5092 },
5093 ..default_md_style
5094 }
5095}
5096
5097fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
5098 let default_md_style = default_markdown_style(true, false, window, cx);
5099
5100 MarkdownStyle {
5101 base_text_style: TextStyle {
5102 ..default_md_style.base_text_style
5103 },
5104 selection_background_color: cx.theme().colors().element_selection_background,
5105 ..Default::default()
5106 }
5107}
5108
5109#[cfg(test)]
5110pub(crate) mod tests {
5111 use acp_thread::StubAgentConnection;
5112 use agent_client_protocol::SessionId;
5113 use assistant_context::ContextStore;
5114 use editor::EditorSettings;
5115 use fs::FakeFs;
5116 use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
5117 use project::Project;
5118 use serde_json::json;
5119 use settings::SettingsStore;
5120 use std::any::Any;
5121 use std::path::Path;
5122 use workspace::Item;
5123
5124 use super::*;
5125
5126 #[gpui::test]
5127 async fn test_drop(cx: &mut TestAppContext) {
5128 init_test(cx);
5129
5130 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5131 let weak_view = thread_view.downgrade();
5132 drop(thread_view);
5133 assert!(!weak_view.is_upgradable());
5134 }
5135
5136 #[gpui::test]
5137 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
5138 init_test(cx);
5139
5140 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5141
5142 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5143 message_editor.update_in(cx, |editor, window, cx| {
5144 editor.set_text("Hello", window, cx);
5145 });
5146
5147 cx.deactivate_window();
5148
5149 thread_view.update_in(cx, |thread_view, window, cx| {
5150 thread_view.send(window, cx);
5151 });
5152
5153 cx.run_until_parked();
5154
5155 assert!(
5156 cx.windows()
5157 .iter()
5158 .any(|window| window.downcast::<AgentNotification>().is_some())
5159 );
5160 }
5161
5162 #[gpui::test]
5163 async fn test_notification_for_error(cx: &mut TestAppContext) {
5164 init_test(cx);
5165
5166 let (thread_view, cx) =
5167 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
5168
5169 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5170 message_editor.update_in(cx, |editor, window, cx| {
5171 editor.set_text("Hello", window, cx);
5172 });
5173
5174 cx.deactivate_window();
5175
5176 thread_view.update_in(cx, |thread_view, window, cx| {
5177 thread_view.send(window, cx);
5178 });
5179
5180 cx.run_until_parked();
5181
5182 assert!(
5183 cx.windows()
5184 .iter()
5185 .any(|window| window.downcast::<AgentNotification>().is_some())
5186 );
5187 }
5188
5189 #[gpui::test]
5190 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
5191 init_test(cx);
5192
5193 let tool_call_id = acp::ToolCallId("1".into());
5194 let tool_call = acp::ToolCall {
5195 id: tool_call_id.clone(),
5196 title: "Label".into(),
5197 kind: acp::ToolKind::Edit,
5198 status: acp::ToolCallStatus::Pending,
5199 content: vec!["hi".into()],
5200 locations: vec![],
5201 raw_input: None,
5202 raw_output: None,
5203 };
5204 let connection =
5205 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5206 tool_call_id,
5207 vec![acp::PermissionOption {
5208 id: acp::PermissionOptionId("1".into()),
5209 name: "Allow".into(),
5210 kind: acp::PermissionOptionKind::AllowOnce,
5211 }],
5212 )]));
5213
5214 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5215
5216 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5217
5218 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5219 message_editor.update_in(cx, |editor, window, cx| {
5220 editor.set_text("Hello", window, cx);
5221 });
5222
5223 cx.deactivate_window();
5224
5225 thread_view.update_in(cx, |thread_view, window, cx| {
5226 thread_view.send(window, cx);
5227 });
5228
5229 cx.run_until_parked();
5230
5231 assert!(
5232 cx.windows()
5233 .iter()
5234 .any(|window| window.downcast::<AgentNotification>().is_some())
5235 );
5236 }
5237
5238 async fn setup_thread_view(
5239 agent: impl AgentServer + 'static,
5240 cx: &mut TestAppContext,
5241 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
5242 let fs = FakeFs::new(cx.executor());
5243 let project = Project::test(fs, [], cx).await;
5244 let (workspace, cx) =
5245 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5246
5247 let context_store =
5248 cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5249 let history_store =
5250 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5251
5252 let thread_view = cx.update(|window, cx| {
5253 cx.new(|cx| {
5254 AcpThreadView::new(
5255 Rc::new(agent),
5256 None,
5257 None,
5258 workspace.downgrade(),
5259 project,
5260 history_store,
5261 None,
5262 window,
5263 cx,
5264 )
5265 })
5266 });
5267 cx.run_until_parked();
5268 (thread_view, cx)
5269 }
5270
5271 fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
5272 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
5273
5274 workspace
5275 .update_in(cx, |workspace, window, cx| {
5276 workspace.add_item_to_active_pane(
5277 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
5278 None,
5279 true,
5280 window,
5281 cx,
5282 );
5283 })
5284 .unwrap();
5285 }
5286
5287 struct ThreadViewItem(Entity<AcpThreadView>);
5288
5289 impl Item for ThreadViewItem {
5290 type Event = ();
5291
5292 fn include_in_nav_history() -> bool {
5293 false
5294 }
5295
5296 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
5297 "Test".into()
5298 }
5299 }
5300
5301 impl EventEmitter<()> for ThreadViewItem {}
5302
5303 impl Focusable for ThreadViewItem {
5304 fn focus_handle(&self, cx: &App) -> FocusHandle {
5305 self.0.read(cx).focus_handle(cx)
5306 }
5307 }
5308
5309 impl Render for ThreadViewItem {
5310 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5311 self.0.clone().into_any_element()
5312 }
5313 }
5314
5315 struct StubAgentServer<C> {
5316 connection: C,
5317 }
5318
5319 impl<C> StubAgentServer<C> {
5320 fn new(connection: C) -> Self {
5321 Self { connection }
5322 }
5323 }
5324
5325 impl StubAgentServer<StubAgentConnection> {
5326 fn default_response() -> Self {
5327 let conn = StubAgentConnection::new();
5328 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5329 content: "Default response".into(),
5330 }]);
5331 Self::new(conn)
5332 }
5333 }
5334
5335 impl<C> AgentServer for StubAgentServer<C>
5336 where
5337 C: 'static + AgentConnection + Send + Clone,
5338 {
5339 fn telemetry_id(&self) -> &'static str {
5340 "test"
5341 }
5342
5343 fn logo(&self) -> ui::IconName {
5344 ui::IconName::Ai
5345 }
5346
5347 fn name(&self) -> SharedString {
5348 "Test".into()
5349 }
5350
5351 fn connect(
5352 &self,
5353 _root_dir: &Path,
5354 _delegate: AgentServerDelegate,
5355 _cx: &mut App,
5356 ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
5357 Task::ready(Ok(Rc::new(self.connection.clone())))
5358 }
5359
5360 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5361 self
5362 }
5363 }
5364
5365 #[derive(Clone)]
5366 struct SaboteurAgentConnection;
5367
5368 impl AgentConnection for SaboteurAgentConnection {
5369 fn new_thread(
5370 self: Rc<Self>,
5371 project: Entity<Project>,
5372 _cwd: &Path,
5373 cx: &mut gpui::App,
5374 ) -> Task<gpui::Result<Entity<AcpThread>>> {
5375 Task::ready(Ok(cx.new(|cx| {
5376 let action_log = cx.new(|_| ActionLog::new(project.clone()));
5377 AcpThread::new(
5378 "SaboteurAgentConnection",
5379 self,
5380 project,
5381 action_log,
5382 SessionId("test".into()),
5383 watch::Receiver::constant(acp::PromptCapabilities {
5384 image: true,
5385 audio: true,
5386 embedded_context: true,
5387 }),
5388 cx,
5389 )
5390 })))
5391 }
5392
5393 fn auth_methods(&self) -> &[acp::AuthMethod] {
5394 &[]
5395 }
5396
5397 fn authenticate(
5398 &self,
5399 _method_id: acp::AuthMethodId,
5400 _cx: &mut App,
5401 ) -> Task<gpui::Result<()>> {
5402 unimplemented!()
5403 }
5404
5405 fn prompt(
5406 &self,
5407 _id: Option<acp_thread::UserMessageId>,
5408 _params: acp::PromptRequest,
5409 _cx: &mut App,
5410 ) -> Task<gpui::Result<acp::PromptResponse>> {
5411 Task::ready(Err(anyhow::anyhow!("Error prompting")))
5412 }
5413
5414 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
5415 unimplemented!()
5416 }
5417
5418 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5419 self
5420 }
5421 }
5422
5423 pub(crate) fn init_test(cx: &mut TestAppContext) {
5424 cx.update(|cx| {
5425 let settings_store = SettingsStore::test(cx);
5426 cx.set_global(settings_store);
5427 language::init(cx);
5428 Project::init_settings(cx);
5429 AgentSettings::register(cx);
5430 workspace::init_settings(cx);
5431 ThemeSettings::register(cx);
5432 release_channel::init(SemanticVersion::default(), cx);
5433 EditorSettings::register(cx);
5434 prompt_store::init(cx)
5435 });
5436 }
5437
5438 #[gpui::test]
5439 async fn test_rewind_views(cx: &mut TestAppContext) {
5440 init_test(cx);
5441
5442 let fs = FakeFs::new(cx.executor());
5443 fs.insert_tree(
5444 "/project",
5445 json!({
5446 "test1.txt": "old content 1",
5447 "test2.txt": "old content 2"
5448 }),
5449 )
5450 .await;
5451 let project = Project::test(fs, [Path::new("/project")], cx).await;
5452 let (workspace, cx) =
5453 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5454
5455 let context_store =
5456 cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5457 let history_store =
5458 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5459
5460 let connection = Rc::new(StubAgentConnection::new());
5461 let thread_view = cx.update(|window, cx| {
5462 cx.new(|cx| {
5463 AcpThreadView::new(
5464 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
5465 None,
5466 None,
5467 workspace.downgrade(),
5468 project.clone(),
5469 history_store.clone(),
5470 None,
5471 window,
5472 cx,
5473 )
5474 })
5475 });
5476
5477 cx.run_until_parked();
5478
5479 let thread = thread_view
5480 .read_with(cx, |view, _| view.thread().cloned())
5481 .unwrap();
5482
5483 // First user message
5484 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5485 id: acp::ToolCallId("tool1".into()),
5486 title: "Edit file 1".into(),
5487 kind: acp::ToolKind::Edit,
5488 status: acp::ToolCallStatus::Completed,
5489 content: vec![acp::ToolCallContent::Diff {
5490 diff: acp::Diff {
5491 path: "/project/test1.txt".into(),
5492 old_text: Some("old content 1".into()),
5493 new_text: "new content 1".into(),
5494 },
5495 }],
5496 locations: vec![],
5497 raw_input: None,
5498 raw_output: None,
5499 })]);
5500
5501 thread
5502 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
5503 .await
5504 .unwrap();
5505 cx.run_until_parked();
5506
5507 thread.read_with(cx, |thread, _| {
5508 assert_eq!(thread.entries().len(), 2);
5509 });
5510
5511 thread_view.read_with(cx, |view, cx| {
5512 view.entry_view_state.read_with(cx, |entry_view_state, _| {
5513 assert!(
5514 entry_view_state
5515 .entry(0)
5516 .unwrap()
5517 .message_editor()
5518 .is_some()
5519 );
5520 assert!(entry_view_state.entry(1).unwrap().has_content());
5521 });
5522 });
5523
5524 // Second user message
5525 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5526 id: acp::ToolCallId("tool2".into()),
5527 title: "Edit file 2".into(),
5528 kind: acp::ToolKind::Edit,
5529 status: acp::ToolCallStatus::Completed,
5530 content: vec![acp::ToolCallContent::Diff {
5531 diff: acp::Diff {
5532 path: "/project/test2.txt".into(),
5533 old_text: Some("old content 2".into()),
5534 new_text: "new content 2".into(),
5535 },
5536 }],
5537 locations: vec![],
5538 raw_input: None,
5539 raw_output: None,
5540 })]);
5541
5542 thread
5543 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
5544 .await
5545 .unwrap();
5546 cx.run_until_parked();
5547
5548 let second_user_message_id = thread.read_with(cx, |thread, _| {
5549 assert_eq!(thread.entries().len(), 4);
5550 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
5551 panic!();
5552 };
5553 user_message.id.clone().unwrap()
5554 });
5555
5556 thread_view.read_with(cx, |view, cx| {
5557 view.entry_view_state.read_with(cx, |entry_view_state, _| {
5558 assert!(
5559 entry_view_state
5560 .entry(0)
5561 .unwrap()
5562 .message_editor()
5563 .is_some()
5564 );
5565 assert!(entry_view_state.entry(1).unwrap().has_content());
5566 assert!(
5567 entry_view_state
5568 .entry(2)
5569 .unwrap()
5570 .message_editor()
5571 .is_some()
5572 );
5573 assert!(entry_view_state.entry(3).unwrap().has_content());
5574 });
5575 });
5576
5577 // Rewind to first message
5578 thread
5579 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
5580 .await
5581 .unwrap();
5582
5583 cx.run_until_parked();
5584
5585 thread.read_with(cx, |thread, _| {
5586 assert_eq!(thread.entries().len(), 2);
5587 });
5588
5589 thread_view.read_with(cx, |view, cx| {
5590 view.entry_view_state.read_with(cx, |entry_view_state, _| {
5591 assert!(
5592 entry_view_state
5593 .entry(0)
5594 .unwrap()
5595 .message_editor()
5596 .is_some()
5597 );
5598 assert!(entry_view_state.entry(1).unwrap().has_content());
5599
5600 // Old views should be dropped
5601 assert!(entry_view_state.entry(2).is_none());
5602 assert!(entry_view_state.entry(3).is_none());
5603 });
5604 });
5605 }
5606
5607 #[gpui::test]
5608 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
5609 init_test(cx);
5610
5611 let connection = StubAgentConnection::new();
5612
5613 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5614 content: acp::ContentBlock::Text(acp::TextContent {
5615 text: "Response".into(),
5616 annotations: None,
5617 }),
5618 }]);
5619
5620 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5621 add_to_workspace(thread_view.clone(), cx);
5622
5623 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5624 message_editor.update_in(cx, |editor, window, cx| {
5625 editor.set_text("Original message to edit", window, cx);
5626 });
5627 thread_view.update_in(cx, |thread_view, window, cx| {
5628 thread_view.send(window, cx);
5629 });
5630
5631 cx.run_until_parked();
5632
5633 let user_message_editor = thread_view.read_with(cx, |view, cx| {
5634 assert_eq!(view.editing_message, None);
5635
5636 view.entry_view_state
5637 .read(cx)
5638 .entry(0)
5639 .unwrap()
5640 .message_editor()
5641 .unwrap()
5642 .clone()
5643 });
5644
5645 // Focus
5646 cx.focus(&user_message_editor);
5647 thread_view.read_with(cx, |view, _cx| {
5648 assert_eq!(view.editing_message, Some(0));
5649 });
5650
5651 // Edit
5652 user_message_editor.update_in(cx, |editor, window, cx| {
5653 editor.set_text("Edited message content", window, cx);
5654 });
5655
5656 // Cancel
5657 user_message_editor.update_in(cx, |_editor, window, cx| {
5658 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
5659 });
5660
5661 thread_view.read_with(cx, |view, _cx| {
5662 assert_eq!(view.editing_message, None);
5663 });
5664
5665 user_message_editor.read_with(cx, |editor, cx| {
5666 assert_eq!(editor.text(cx), "Original message to edit");
5667 });
5668 }
5669
5670 #[gpui::test]
5671 async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
5672 init_test(cx);
5673
5674 let connection = StubAgentConnection::new();
5675
5676 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5677 add_to_workspace(thread_view.clone(), cx);
5678
5679 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5680 let mut events = cx.events(&message_editor);
5681 message_editor.update_in(cx, |editor, window, cx| {
5682 editor.set_text("", window, cx);
5683 });
5684
5685 message_editor.update_in(cx, |_editor, window, cx| {
5686 window.dispatch_action(Box::new(Chat), cx);
5687 });
5688 cx.run_until_parked();
5689 // We shouldn't have received any messages
5690 assert!(matches!(
5691 events.try_next(),
5692 Err(futures::channel::mpsc::TryRecvError { .. })
5693 ));
5694 }
5695
5696 #[gpui::test]
5697 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
5698 init_test(cx);
5699
5700 let connection = StubAgentConnection::new();
5701
5702 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5703 content: acp::ContentBlock::Text(acp::TextContent {
5704 text: "Response".into(),
5705 annotations: None,
5706 }),
5707 }]);
5708
5709 let (thread_view, cx) =
5710 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5711 add_to_workspace(thread_view.clone(), cx);
5712
5713 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5714 message_editor.update_in(cx, |editor, window, cx| {
5715 editor.set_text("Original message to edit", window, cx);
5716 });
5717 thread_view.update_in(cx, |thread_view, window, cx| {
5718 thread_view.send(window, cx);
5719 });
5720
5721 cx.run_until_parked();
5722
5723 let user_message_editor = thread_view.read_with(cx, |view, cx| {
5724 assert_eq!(view.editing_message, None);
5725 assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
5726
5727 view.entry_view_state
5728 .read(cx)
5729 .entry(0)
5730 .unwrap()
5731 .message_editor()
5732 .unwrap()
5733 .clone()
5734 });
5735
5736 // Focus
5737 cx.focus(&user_message_editor);
5738
5739 // Edit
5740 user_message_editor.update_in(cx, |editor, window, cx| {
5741 editor.set_text("Edited message content", window, cx);
5742 });
5743
5744 // Send
5745 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5746 content: acp::ContentBlock::Text(acp::TextContent {
5747 text: "New Response".into(),
5748 annotations: None,
5749 }),
5750 }]);
5751
5752 user_message_editor.update_in(cx, |_editor, window, cx| {
5753 window.dispatch_action(Box::new(Chat), cx);
5754 });
5755
5756 cx.run_until_parked();
5757
5758 thread_view.read_with(cx, |view, cx| {
5759 assert_eq!(view.editing_message, None);
5760
5761 let entries = view.thread().unwrap().read(cx).entries();
5762 assert_eq!(entries.len(), 2);
5763 assert_eq!(
5764 entries[0].to_markdown(cx),
5765 "## User\n\nEdited message content\n\n"
5766 );
5767 assert_eq!(
5768 entries[1].to_markdown(cx),
5769 "## Assistant\n\nNew Response\n\n"
5770 );
5771
5772 let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
5773 assert!(!state.entry(1).unwrap().has_content());
5774 state.entry(0).unwrap().message_editor().unwrap().clone()
5775 });
5776
5777 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
5778 })
5779 }
5780
5781 #[gpui::test]
5782 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
5783 init_test(cx);
5784
5785 let connection = StubAgentConnection::new();
5786
5787 let (thread_view, cx) =
5788 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5789 add_to_workspace(thread_view.clone(), cx);
5790
5791 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5792 message_editor.update_in(cx, |editor, window, cx| {
5793 editor.set_text("Original message to edit", window, cx);
5794 });
5795 thread_view.update_in(cx, |thread_view, window, cx| {
5796 thread_view.send(window, cx);
5797 });
5798
5799 cx.run_until_parked();
5800
5801 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
5802 let thread = view.thread().unwrap().read(cx);
5803 assert_eq!(thread.entries().len(), 1);
5804
5805 let editor = view
5806 .entry_view_state
5807 .read(cx)
5808 .entry(0)
5809 .unwrap()
5810 .message_editor()
5811 .unwrap()
5812 .clone();
5813
5814 (editor, thread.session_id().clone())
5815 });
5816
5817 // Focus
5818 cx.focus(&user_message_editor);
5819
5820 thread_view.read_with(cx, |view, _cx| {
5821 assert_eq!(view.editing_message, Some(0));
5822 });
5823
5824 // Edit
5825 user_message_editor.update_in(cx, |editor, window, cx| {
5826 editor.set_text("Edited message content", window, cx);
5827 });
5828
5829 thread_view.read_with(cx, |view, _cx| {
5830 assert_eq!(view.editing_message, Some(0));
5831 });
5832
5833 // Finish streaming response
5834 cx.update(|_, cx| {
5835 connection.send_update(
5836 session_id.clone(),
5837 acp::SessionUpdate::AgentMessageChunk {
5838 content: acp::ContentBlock::Text(acp::TextContent {
5839 text: "Response".into(),
5840 annotations: None,
5841 }),
5842 },
5843 cx,
5844 );
5845 connection.end_turn(session_id, acp::StopReason::EndTurn);
5846 });
5847
5848 thread_view.read_with(cx, |view, _cx| {
5849 assert_eq!(view.editing_message, Some(0));
5850 });
5851
5852 cx.run_until_parked();
5853
5854 // Should still be editing
5855 cx.update(|window, cx| {
5856 assert!(user_message_editor.focus_handle(cx).is_focused(window));
5857 assert_eq!(thread_view.read(cx).editing_message, Some(0));
5858 assert_eq!(
5859 user_message_editor.read(cx).text(cx),
5860 "Edited message content"
5861 );
5862 });
5863 }
5864
5865 #[gpui::test]
5866 async fn test_interrupt(cx: &mut TestAppContext) {
5867 init_test(cx);
5868
5869 let connection = StubAgentConnection::new();
5870
5871 let (thread_view, cx) =
5872 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5873 add_to_workspace(thread_view.clone(), cx);
5874
5875 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5876 message_editor.update_in(cx, |editor, window, cx| {
5877 editor.set_text("Message 1", window, cx);
5878 });
5879 thread_view.update_in(cx, |thread_view, window, cx| {
5880 thread_view.send(window, cx);
5881 });
5882
5883 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
5884 let thread = view.thread().unwrap();
5885
5886 (thread.clone(), thread.read(cx).session_id().clone())
5887 });
5888
5889 cx.run_until_parked();
5890
5891 cx.update(|_, cx| {
5892 connection.send_update(
5893 session_id.clone(),
5894 acp::SessionUpdate::AgentMessageChunk {
5895 content: "Message 1 resp".into(),
5896 },
5897 cx,
5898 );
5899 });
5900
5901 cx.run_until_parked();
5902
5903 thread.read_with(cx, |thread, cx| {
5904 assert_eq!(
5905 thread.to_markdown(cx),
5906 indoc::indoc! {"
5907 ## User
5908
5909 Message 1
5910
5911 ## Assistant
5912
5913 Message 1 resp
5914
5915 "}
5916 )
5917 });
5918
5919 message_editor.update_in(cx, |editor, window, cx| {
5920 editor.set_text("Message 2", window, cx);
5921 });
5922 thread_view.update_in(cx, |thread_view, window, cx| {
5923 thread_view.send(window, cx);
5924 });
5925
5926 cx.update(|_, cx| {
5927 // Simulate a response sent after beginning to cancel
5928 connection.send_update(
5929 session_id.clone(),
5930 acp::SessionUpdate::AgentMessageChunk {
5931 content: "onse".into(),
5932 },
5933 cx,
5934 );
5935 });
5936
5937 cx.run_until_parked();
5938
5939 // Last Message 1 response should appear before Message 2
5940 thread.read_with(cx, |thread, cx| {
5941 assert_eq!(
5942 thread.to_markdown(cx),
5943 indoc::indoc! {"
5944 ## User
5945
5946 Message 1
5947
5948 ## Assistant
5949
5950 Message 1 response
5951
5952 ## User
5953
5954 Message 2
5955
5956 "}
5957 )
5958 });
5959
5960 cx.update(|_, cx| {
5961 connection.send_update(
5962 session_id.clone(),
5963 acp::SessionUpdate::AgentMessageChunk {
5964 content: "Message 2 response".into(),
5965 },
5966 cx,
5967 );
5968 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
5969 });
5970
5971 cx.run_until_parked();
5972
5973 thread.read_with(cx, |thread, cx| {
5974 assert_eq!(
5975 thread.to_markdown(cx),
5976 indoc::indoc! {"
5977 ## User
5978
5979 Message 1
5980
5981 ## Assistant
5982
5983 Message 1 response
5984
5985 ## User
5986
5987 Message 2
5988
5989 ## Assistant
5990
5991 Message 2 response
5992
5993 "}
5994 )
5995 });
5996 }
5997}