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