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