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