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