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