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