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