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