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