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 error_message: _,
2830 install_message: _,
2831 install_command,
2832 } => {
2833 return self.render_not_installed(install_command.clone(), false, window, cx);
2834 }
2835 LoadError::Unsupported {
2836 error_message: _,
2837 upgrade_message: _,
2838 upgrade_command,
2839 } => {
2840 return self.render_not_installed(upgrade_command.clone(), true, window, cx);
2841 }
2842 LoadError::Exited { .. } => ("Server exited with status {status}".into(), None),
2843 LoadError::Other(msg) => (
2844 msg.into(),
2845 Some(self.create_copy_button(msg.to_string()).into_any_element()),
2846 ),
2847 };
2848
2849 Callout::new()
2850 .severity(Severity::Error)
2851 .icon(IconName::XCircleFilled)
2852 .title("Failed to Launch")
2853 .description(message)
2854 .actions_slot(div().children(action_slot))
2855 .into_any_element()
2856 }
2857
2858 fn install_agent(&self, install_command: String, window: &mut Window, cx: &mut Context<Self>) {
2859 telemetry::event!("Agent Install CLI", agent = self.agent.telemetry_id());
2860 let task = self
2861 .workspace
2862 .update(cx, |workspace, cx| {
2863 let project = workspace.project().read(cx);
2864 let cwd = project.first_project_directory(cx);
2865 let shell = project.terminal_settings(&cwd, cx).shell.clone();
2866 let spawn_in_terminal = task::SpawnInTerminal {
2867 id: task::TaskId(install_command.clone()),
2868 full_label: install_command.clone(),
2869 label: install_command.clone(),
2870 command: Some(install_command.clone()),
2871 args: Vec::new(),
2872 command_label: install_command.clone(),
2873 cwd,
2874 env: Default::default(),
2875 use_new_terminal: true,
2876 allow_concurrent_runs: true,
2877 reveal: Default::default(),
2878 reveal_target: Default::default(),
2879 hide: Default::default(),
2880 shell,
2881 show_summary: true,
2882 show_command: true,
2883 show_rerun: false,
2884 };
2885 workspace.spawn_in_terminal(spawn_in_terminal, window, cx)
2886 })
2887 .ok();
2888 let Some(task) = task else { return };
2889 cx.spawn_in(window, async move |this, cx| {
2890 if let Some(Ok(_)) = task.await {
2891 this.update_in(cx, |this, window, cx| {
2892 this.reset(window, cx);
2893 })
2894 .ok();
2895 }
2896 })
2897 .detach()
2898 }
2899
2900 fn render_not_installed(
2901 &self,
2902 install_command: String,
2903 is_upgrade: bool,
2904 window: &mut Window,
2905 cx: &mut Context<Self>,
2906 ) -> AnyElement {
2907 self.install_command_markdown.update(cx, |markdown, cx| {
2908 if !markdown.source().contains(&install_command) {
2909 markdown.replace(format!("```\n{}\n```", install_command), cx);
2910 }
2911 });
2912
2913 let (heading_label, description_label, button_label, or_label) = if is_upgrade {
2914 (
2915 "Upgrade Gemini CLI in Zed",
2916 "Get access to the latest version with support for Zed.",
2917 "Upgrade Gemini CLI",
2918 "Or, to upgrade it manually:",
2919 )
2920 } else {
2921 (
2922 "Get Started with Gemini CLI in Zed",
2923 "Use Google's new coding agent directly in Zed.",
2924 "Install Gemini CLI",
2925 "Or, to install it manually:",
2926 )
2927 };
2928
2929 v_flex()
2930 .w_full()
2931 .p_3p5()
2932 .gap_2p5()
2933 .border_t_1()
2934 .border_color(cx.theme().colors().border)
2935 .bg(linear_gradient(
2936 180.,
2937 linear_color_stop(cx.theme().colors().editor_background.opacity(0.4), 4.),
2938 linear_color_stop(cx.theme().status().info_background.opacity(0.), 0.),
2939 ))
2940 .child(
2941 v_flex().gap_0p5().child(Label::new(heading_label)).child(
2942 Label::new(description_label)
2943 .size(LabelSize::Small)
2944 .color(Color::Muted),
2945 ),
2946 )
2947 .child(
2948 Button::new("install_gemini", button_label)
2949 .full_width()
2950 .size(ButtonSize::Medium)
2951 .style(ButtonStyle::Tinted(TintColor::Accent))
2952 .label_size(LabelSize::Small)
2953 .icon(IconName::TerminalGhost)
2954 .icon_color(Color::Muted)
2955 .icon_size(IconSize::Small)
2956 .icon_position(IconPosition::Start)
2957 .on_click(cx.listener(move |this, _, window, cx| {
2958 this.install_agent(install_command.clone(), window, cx)
2959 })),
2960 )
2961 .child(
2962 Label::new(or_label)
2963 .size(LabelSize::Small)
2964 .color(Color::Muted),
2965 )
2966 .child(MarkdownElement::new(
2967 self.install_command_markdown.clone(),
2968 default_markdown_style(false, false, window, cx),
2969 ))
2970 .into_any_element()
2971 }
2972
2973 fn render_activity_bar(
2974 &self,
2975 thread_entity: &Entity<AcpThread>,
2976 window: &mut Window,
2977 cx: &Context<Self>,
2978 ) -> Option<AnyElement> {
2979 let thread = thread_entity.read(cx);
2980 let action_log = thread.action_log();
2981 let changed_buffers = action_log.read(cx).changed_buffers(cx);
2982 let plan = thread.plan();
2983
2984 if changed_buffers.is_empty() && plan.is_empty() {
2985 return None;
2986 }
2987
2988 let editor_bg_color = cx.theme().colors().editor_background;
2989 let active_color = cx.theme().colors().element_selected;
2990 let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
2991
2992 let pending_edits = thread.has_pending_edit_tool_calls();
2993
2994 v_flex()
2995 .mt_1()
2996 .mx_2()
2997 .bg(bg_edit_files_disclosure)
2998 .border_1()
2999 .border_b_0()
3000 .border_color(cx.theme().colors().border)
3001 .rounded_t_md()
3002 .shadow(vec![gpui::BoxShadow {
3003 color: gpui::black().opacity(0.15),
3004 offset: point(px(1.), px(-1.)),
3005 blur_radius: px(3.),
3006 spread_radius: px(0.),
3007 }])
3008 .when(!plan.is_empty(), |this| {
3009 this.child(self.render_plan_summary(plan, window, cx))
3010 .when(self.plan_expanded, |parent| {
3011 parent.child(self.render_plan_entries(plan, window, cx))
3012 })
3013 })
3014 .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
3015 this.child(Divider::horizontal().color(DividerColor::Border))
3016 })
3017 .when(!changed_buffers.is_empty(), |this| {
3018 this.child(self.render_edits_summary(
3019 &changed_buffers,
3020 self.edits_expanded,
3021 pending_edits,
3022 window,
3023 cx,
3024 ))
3025 .when(self.edits_expanded, |parent| {
3026 parent.child(self.render_edited_files(
3027 action_log,
3028 &changed_buffers,
3029 pending_edits,
3030 cx,
3031 ))
3032 })
3033 })
3034 .into_any()
3035 .into()
3036 }
3037
3038 fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
3039 let stats = plan.stats();
3040
3041 let title = if let Some(entry) = stats.in_progress_entry
3042 && !self.plan_expanded
3043 {
3044 h_flex()
3045 .w_full()
3046 .cursor_default()
3047 .gap_1()
3048 .text_xs()
3049 .text_color(cx.theme().colors().text_muted)
3050 .justify_between()
3051 .child(
3052 h_flex()
3053 .gap_1()
3054 .child(
3055 Label::new("Current:")
3056 .size(LabelSize::Small)
3057 .color(Color::Muted),
3058 )
3059 .child(MarkdownElement::new(
3060 entry.content.clone(),
3061 plan_label_markdown_style(&entry.status, window, cx),
3062 )),
3063 )
3064 .when(stats.pending > 0, |this| {
3065 this.child(
3066 Label::new(format!("{} left", stats.pending))
3067 .size(LabelSize::Small)
3068 .color(Color::Muted)
3069 .mr_1(),
3070 )
3071 })
3072 } else {
3073 let status_label = if stats.pending == 0 {
3074 "All Done".to_string()
3075 } else if stats.completed == 0 {
3076 format!("{} Tasks", plan.entries.len())
3077 } else {
3078 format!("{}/{}", stats.completed, plan.entries.len())
3079 };
3080
3081 h_flex()
3082 .w_full()
3083 .gap_1()
3084 .justify_between()
3085 .child(
3086 Label::new("Plan")
3087 .size(LabelSize::Small)
3088 .color(Color::Muted),
3089 )
3090 .child(
3091 Label::new(status_label)
3092 .size(LabelSize::Small)
3093 .color(Color::Muted)
3094 .mr_1(),
3095 )
3096 };
3097
3098 h_flex()
3099 .p_1()
3100 .justify_between()
3101 .when(self.plan_expanded, |this| {
3102 this.border_b_1().border_color(cx.theme().colors().border)
3103 })
3104 .child(
3105 h_flex()
3106 .id("plan_summary")
3107 .w_full()
3108 .gap_1()
3109 .child(Disclosure::new("plan_disclosure", self.plan_expanded))
3110 .child(title)
3111 .on_click(cx.listener(|this, _, _, cx| {
3112 this.plan_expanded = !this.plan_expanded;
3113 cx.notify();
3114 })),
3115 )
3116 }
3117
3118 fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
3119 v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
3120 let element = h_flex()
3121 .py_1()
3122 .px_2()
3123 .gap_2()
3124 .justify_between()
3125 .bg(cx.theme().colors().editor_background)
3126 .when(index < plan.entries.len() - 1, |parent| {
3127 parent.border_color(cx.theme().colors().border).border_b_1()
3128 })
3129 .child(
3130 h_flex()
3131 .id(("plan_entry", index))
3132 .gap_1p5()
3133 .max_w_full()
3134 .overflow_x_scroll()
3135 .text_xs()
3136 .text_color(cx.theme().colors().text_muted)
3137 .child(match entry.status {
3138 acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
3139 .size(IconSize::Small)
3140 .color(Color::Muted)
3141 .into_any_element(),
3142 acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
3143 .size(IconSize::Small)
3144 .color(Color::Accent)
3145 .with_animation(
3146 "running",
3147 Animation::new(Duration::from_secs(2)).repeat(),
3148 |icon, delta| {
3149 icon.transform(Transformation::rotate(percentage(delta)))
3150 },
3151 )
3152 .into_any_element(),
3153 acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
3154 .size(IconSize::Small)
3155 .color(Color::Success)
3156 .into_any_element(),
3157 })
3158 .child(MarkdownElement::new(
3159 entry.content.clone(),
3160 plan_label_markdown_style(&entry.status, window, cx),
3161 )),
3162 );
3163
3164 Some(element)
3165 }))
3166 }
3167
3168 fn render_edits_summary(
3169 &self,
3170 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3171 expanded: bool,
3172 pending_edits: bool,
3173 window: &mut Window,
3174 cx: &Context<Self>,
3175 ) -> Div {
3176 const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
3177
3178 let focus_handle = self.focus_handle(cx);
3179
3180 h_flex()
3181 .p_1()
3182 .justify_between()
3183 .flex_wrap()
3184 .when(expanded, |this| {
3185 this.border_b_1().border_color(cx.theme().colors().border)
3186 })
3187 .child(
3188 h_flex()
3189 .id("edits-container")
3190 .gap_1()
3191 .child(Disclosure::new("edits-disclosure", expanded))
3192 .map(|this| {
3193 if pending_edits {
3194 this.child(
3195 Label::new(format!(
3196 "Editing {} {}…",
3197 changed_buffers.len(),
3198 if changed_buffers.len() == 1 {
3199 "file"
3200 } else {
3201 "files"
3202 }
3203 ))
3204 .color(Color::Muted)
3205 .size(LabelSize::Small)
3206 .with_animation(
3207 "edit-label",
3208 Animation::new(Duration::from_secs(2))
3209 .repeat()
3210 .with_easing(pulsating_between(0.3, 0.7)),
3211 |label, delta| label.alpha(delta),
3212 ),
3213 )
3214 } else {
3215 this.child(
3216 Label::new("Edits")
3217 .size(LabelSize::Small)
3218 .color(Color::Muted),
3219 )
3220 .child(Label::new("•").size(LabelSize::XSmall).color(Color::Muted))
3221 .child(
3222 Label::new(format!(
3223 "{} {}",
3224 changed_buffers.len(),
3225 if changed_buffers.len() == 1 {
3226 "file"
3227 } else {
3228 "files"
3229 }
3230 ))
3231 .size(LabelSize::Small)
3232 .color(Color::Muted),
3233 )
3234 }
3235 })
3236 .on_click(cx.listener(|this, _, _, cx| {
3237 this.edits_expanded = !this.edits_expanded;
3238 cx.notify();
3239 })),
3240 )
3241 .child(
3242 h_flex()
3243 .gap_1()
3244 .child(
3245 IconButton::new("review-changes", IconName::ListTodo)
3246 .icon_size(IconSize::Small)
3247 .tooltip({
3248 let focus_handle = focus_handle.clone();
3249 move |window, cx| {
3250 Tooltip::for_action_in(
3251 "Review Changes",
3252 &OpenAgentDiff,
3253 &focus_handle,
3254 window,
3255 cx,
3256 )
3257 }
3258 })
3259 .on_click(cx.listener(|_, _, window, cx| {
3260 window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
3261 })),
3262 )
3263 .child(Divider::vertical().color(DividerColor::Border))
3264 .child(
3265 Button::new("reject-all-changes", "Reject All")
3266 .label_size(LabelSize::Small)
3267 .disabled(pending_edits)
3268 .when(pending_edits, |this| {
3269 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3270 })
3271 .key_binding(
3272 KeyBinding::for_action_in(
3273 &RejectAll,
3274 &focus_handle.clone(),
3275 window,
3276 cx,
3277 )
3278 .map(|kb| kb.size(rems_from_px(10.))),
3279 )
3280 .on_click(cx.listener(move |this, _, window, cx| {
3281 this.reject_all(&RejectAll, window, cx);
3282 })),
3283 )
3284 .child(
3285 Button::new("keep-all-changes", "Keep All")
3286 .label_size(LabelSize::Small)
3287 .disabled(pending_edits)
3288 .when(pending_edits, |this| {
3289 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3290 })
3291 .key_binding(
3292 KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
3293 .map(|kb| kb.size(rems_from_px(10.))),
3294 )
3295 .on_click(cx.listener(move |this, _, window, cx| {
3296 this.keep_all(&KeepAll, window, cx);
3297 })),
3298 ),
3299 )
3300 }
3301
3302 fn render_edited_files(
3303 &self,
3304 action_log: &Entity<ActionLog>,
3305 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3306 pending_edits: bool,
3307 cx: &Context<Self>,
3308 ) -> Div {
3309 let editor_bg_color = cx.theme().colors().editor_background;
3310
3311 v_flex().children(changed_buffers.iter().enumerate().flat_map(
3312 |(index, (buffer, _diff))| {
3313 let file = buffer.read(cx).file()?;
3314 let path = file.path();
3315
3316 let file_path = path.parent().and_then(|parent| {
3317 let parent_str = parent.to_string_lossy();
3318
3319 if parent_str.is_empty() {
3320 None
3321 } else {
3322 Some(
3323 Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
3324 .color(Color::Muted)
3325 .size(LabelSize::XSmall)
3326 .buffer_font(cx),
3327 )
3328 }
3329 });
3330
3331 let file_name = path.file_name().map(|name| {
3332 Label::new(name.to_string_lossy().to_string())
3333 .size(LabelSize::XSmall)
3334 .buffer_font(cx)
3335 });
3336
3337 let file_icon = FileIcons::get_icon(path, cx)
3338 .map(Icon::from_path)
3339 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
3340 .unwrap_or_else(|| {
3341 Icon::new(IconName::File)
3342 .color(Color::Muted)
3343 .size(IconSize::Small)
3344 });
3345
3346 let overlay_gradient = linear_gradient(
3347 90.,
3348 linear_color_stop(editor_bg_color, 1.),
3349 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
3350 );
3351
3352 let element = h_flex()
3353 .group("edited-code")
3354 .id(("file-container", index))
3355 .py_1()
3356 .pl_2()
3357 .pr_1()
3358 .gap_2()
3359 .justify_between()
3360 .bg(editor_bg_color)
3361 .when(index < changed_buffers.len() - 1, |parent| {
3362 parent.border_color(cx.theme().colors().border).border_b_1()
3363 })
3364 .child(
3365 h_flex()
3366 .relative()
3367 .id(("file-name", index))
3368 .pr_8()
3369 .gap_1p5()
3370 .max_w_full()
3371 .overflow_x_scroll()
3372 .child(file_icon)
3373 .child(h_flex().gap_0p5().children(file_name).children(file_path))
3374 .child(
3375 div()
3376 .absolute()
3377 .h_full()
3378 .w_12()
3379 .top_0()
3380 .bottom_0()
3381 .right_0()
3382 .bg(overlay_gradient),
3383 )
3384 .on_click({
3385 let buffer = buffer.clone();
3386 cx.listener(move |this, _, window, cx| {
3387 this.open_edited_buffer(&buffer, window, cx);
3388 })
3389 }),
3390 )
3391 .child(
3392 h_flex()
3393 .gap_1()
3394 .visible_on_hover("edited-code")
3395 .child(
3396 Button::new("review", "Review")
3397 .label_size(LabelSize::Small)
3398 .on_click({
3399 let buffer = buffer.clone();
3400 cx.listener(move |this, _, window, cx| {
3401 this.open_edited_buffer(&buffer, window, cx);
3402 })
3403 }),
3404 )
3405 .child(Divider::vertical().color(DividerColor::BorderVariant))
3406 .child(
3407 Button::new("reject-file", "Reject")
3408 .label_size(LabelSize::Small)
3409 .disabled(pending_edits)
3410 .on_click({
3411 let buffer = buffer.clone();
3412 let action_log = action_log.clone();
3413 move |_, _, cx| {
3414 action_log.update(cx, |action_log, cx| {
3415 action_log
3416 .reject_edits_in_ranges(
3417 buffer.clone(),
3418 vec![Anchor::MIN..Anchor::MAX],
3419 cx,
3420 )
3421 .detach_and_log_err(cx);
3422 })
3423 }
3424 }),
3425 )
3426 .child(
3427 Button::new("keep-file", "Keep")
3428 .label_size(LabelSize::Small)
3429 .disabled(pending_edits)
3430 .on_click({
3431 let buffer = buffer.clone();
3432 let action_log = action_log.clone();
3433 move |_, _, cx| {
3434 action_log.update(cx, |action_log, cx| {
3435 action_log.keep_edits_in_range(
3436 buffer.clone(),
3437 Anchor::MIN..Anchor::MAX,
3438 cx,
3439 );
3440 })
3441 }
3442 }),
3443 ),
3444 );
3445
3446 Some(element)
3447 },
3448 ))
3449 }
3450
3451 fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
3452 let focus_handle = self.message_editor.focus_handle(cx);
3453 let editor_bg_color = cx.theme().colors().editor_background;
3454 let (expand_icon, expand_tooltip) = if self.editor_expanded {
3455 (IconName::Minimize, "Minimize Message Editor")
3456 } else {
3457 (IconName::Maximize, "Expand Message Editor")
3458 };
3459
3460 let backdrop = div()
3461 .size_full()
3462 .absolute()
3463 .inset_0()
3464 .bg(cx.theme().colors().panel_background)
3465 .opacity(0.8)
3466 .block_mouse_except_scroll();
3467
3468 let enable_editor = match self.thread_state {
3469 ThreadState::Loading { .. } | ThreadState::Ready { .. } => true,
3470 ThreadState::Unauthenticated { .. } | ThreadState::LoadError(..) => false,
3471 };
3472
3473 v_flex()
3474 .on_action(cx.listener(Self::expand_message_editor))
3475 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
3476 if let Some(profile_selector) = this.profile_selector.as_ref() {
3477 profile_selector.read(cx).menu_handle().toggle(window, cx);
3478 }
3479 }))
3480 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
3481 if let Some(model_selector) = this.model_selector.as_ref() {
3482 model_selector
3483 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
3484 }
3485 }))
3486 .p_2()
3487 .gap_2()
3488 .border_t_1()
3489 .border_color(cx.theme().colors().border)
3490 .bg(editor_bg_color)
3491 .when(self.editor_expanded, |this| {
3492 this.h(vh(0.8, window)).size_full().justify_between()
3493 })
3494 .child(
3495 v_flex()
3496 .relative()
3497 .size_full()
3498 .pt_1()
3499 .pr_2p5()
3500 .child(self.message_editor.clone())
3501 .child(
3502 h_flex()
3503 .absolute()
3504 .top_0()
3505 .right_0()
3506 .opacity(0.5)
3507 .hover(|this| this.opacity(1.0))
3508 .child(
3509 IconButton::new("toggle-height", expand_icon)
3510 .icon_size(IconSize::Small)
3511 .icon_color(Color::Muted)
3512 .tooltip({
3513 move |window, cx| {
3514 Tooltip::for_action_in(
3515 expand_tooltip,
3516 &ExpandMessageEditor,
3517 &focus_handle,
3518 window,
3519 cx,
3520 )
3521 }
3522 })
3523 .on_click(cx.listener(|_, _, window, cx| {
3524 window.dispatch_action(Box::new(ExpandMessageEditor), cx);
3525 })),
3526 ),
3527 ),
3528 )
3529 .child(
3530 h_flex()
3531 .flex_none()
3532 .flex_wrap()
3533 .justify_between()
3534 .child(
3535 h_flex()
3536 .child(self.render_follow_toggle(cx))
3537 .children(self.render_burn_mode_toggle(cx)),
3538 )
3539 .child(
3540 h_flex()
3541 .gap_1()
3542 .children(self.render_token_usage(cx))
3543 .children(self.profile_selector.clone())
3544 .children(self.model_selector.clone())
3545 .child(self.render_send_button(cx)),
3546 ),
3547 )
3548 .when(!enable_editor, |this| this.child(backdrop))
3549 .into_any()
3550 }
3551
3552 pub(crate) fn as_native_connection(
3553 &self,
3554 cx: &App,
3555 ) -> Option<Rc<agent2::NativeAgentConnection>> {
3556 let acp_thread = self.thread()?.read(cx);
3557 acp_thread.connection().clone().downcast()
3558 }
3559
3560 pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent2::Thread>> {
3561 let acp_thread = self.thread()?.read(cx);
3562 self.as_native_connection(cx)?
3563 .thread(acp_thread.session_id(), cx)
3564 }
3565
3566 fn is_using_zed_ai_models(&self, cx: &App) -> bool {
3567 self.as_native_thread(cx)
3568 .and_then(|thread| thread.read(cx).model())
3569 .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
3570 }
3571
3572 fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
3573 let thread = self.thread()?.read(cx);
3574 let usage = thread.token_usage()?;
3575 let is_generating = thread.status() != ThreadStatus::Idle;
3576
3577 let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
3578 let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
3579
3580 Some(
3581 h_flex()
3582 .flex_shrink_0()
3583 .gap_0p5()
3584 .mr_1p5()
3585 .child(
3586 Label::new(used)
3587 .size(LabelSize::Small)
3588 .color(Color::Muted)
3589 .map(|label| {
3590 if is_generating {
3591 label
3592 .with_animation(
3593 "used-tokens-label",
3594 Animation::new(Duration::from_secs(2))
3595 .repeat()
3596 .with_easing(pulsating_between(0.3, 0.8)),
3597 |label, delta| label.alpha(delta),
3598 )
3599 .into_any()
3600 } else {
3601 label.into_any_element()
3602 }
3603 }),
3604 )
3605 .child(
3606 Label::new("/")
3607 .size(LabelSize::Small)
3608 .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
3609 )
3610 .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
3611 )
3612 }
3613
3614 fn toggle_burn_mode(
3615 &mut self,
3616 _: &ToggleBurnMode,
3617 _window: &mut Window,
3618 cx: &mut Context<Self>,
3619 ) {
3620 let Some(thread) = self.as_native_thread(cx) else {
3621 return;
3622 };
3623
3624 thread.update(cx, |thread, cx| {
3625 let current_mode = thread.completion_mode();
3626 thread.set_completion_mode(
3627 match current_mode {
3628 CompletionMode::Burn => CompletionMode::Normal,
3629 CompletionMode::Normal => CompletionMode::Burn,
3630 },
3631 cx,
3632 );
3633 });
3634 }
3635
3636 fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
3637 let Some(thread) = self.thread() else {
3638 return;
3639 };
3640 let action_log = thread.read(cx).action_log().clone();
3641 action_log.update(cx, |action_log, cx| action_log.keep_all_edits(cx));
3642 }
3643
3644 fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
3645 let Some(thread) = self.thread() else {
3646 return;
3647 };
3648 let action_log = thread.read(cx).action_log().clone();
3649 action_log
3650 .update(cx, |action_log, cx| action_log.reject_all_edits(cx))
3651 .detach();
3652 }
3653
3654 fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3655 let thread = self.as_native_thread(cx)?.read(cx);
3656
3657 if thread
3658 .model()
3659 .is_none_or(|model| !model.supports_burn_mode())
3660 {
3661 return None;
3662 }
3663
3664 let active_completion_mode = thread.completion_mode();
3665 let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
3666 let icon = if burn_mode_enabled {
3667 IconName::ZedBurnModeOn
3668 } else {
3669 IconName::ZedBurnMode
3670 };
3671
3672 Some(
3673 IconButton::new("burn-mode", icon)
3674 .icon_size(IconSize::Small)
3675 .icon_color(Color::Muted)
3676 .toggle_state(burn_mode_enabled)
3677 .selected_icon_color(Color::Error)
3678 .on_click(cx.listener(|this, _event, window, cx| {
3679 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
3680 }))
3681 .tooltip(move |_window, cx| {
3682 cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
3683 .into()
3684 })
3685 .into_any_element(),
3686 )
3687 }
3688
3689 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
3690 let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
3691 let is_generating = self
3692 .thread()
3693 .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
3694
3695 if self.is_loading_contents {
3696 div()
3697 .id("loading-message-content")
3698 .px_1()
3699 .tooltip(Tooltip::text("Loading Added Context…"))
3700 .child(loading_contents_spinner(IconSize::default()))
3701 .into_any_element()
3702 } else if is_generating && is_editor_empty {
3703 IconButton::new("stop-generation", IconName::Stop)
3704 .icon_color(Color::Error)
3705 .style(ButtonStyle::Tinted(ui::TintColor::Error))
3706 .tooltip(move |window, cx| {
3707 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
3708 })
3709 .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
3710 .into_any_element()
3711 } else {
3712 let send_btn_tooltip = if is_editor_empty && !is_generating {
3713 "Type to Send"
3714 } else if is_generating {
3715 "Stop and Send Message"
3716 } else {
3717 "Send"
3718 };
3719
3720 IconButton::new("send-message", IconName::Send)
3721 .style(ButtonStyle::Filled)
3722 .map(|this| {
3723 if is_editor_empty && !is_generating {
3724 this.disabled(true).icon_color(Color::Muted)
3725 } else {
3726 this.icon_color(Color::Accent)
3727 }
3728 })
3729 .tooltip(move |window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, window, cx))
3730 .on_click(cx.listener(|this, _, window, cx| {
3731 this.send(window, cx);
3732 }))
3733 .into_any_element()
3734 }
3735 }
3736
3737 fn is_following(&self, cx: &App) -> bool {
3738 match self.thread().map(|thread| thread.read(cx).status()) {
3739 Some(ThreadStatus::Generating) => self
3740 .workspace
3741 .read_with(cx, |workspace, _| {
3742 workspace.is_being_followed(CollaboratorId::Agent)
3743 })
3744 .unwrap_or(false),
3745 _ => self.should_be_following,
3746 }
3747 }
3748
3749 fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3750 let following = self.is_following(cx);
3751
3752 self.should_be_following = !following;
3753 if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
3754 self.workspace
3755 .update(cx, |workspace, cx| {
3756 if following {
3757 workspace.unfollow(CollaboratorId::Agent, window, cx);
3758 } else {
3759 workspace.follow(CollaboratorId::Agent, window, cx);
3760 }
3761 })
3762 .ok();
3763 }
3764
3765 telemetry::event!("Follow Agent Selected", following = !following);
3766 }
3767
3768 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
3769 let following = self.is_following(cx);
3770
3771 let tooltip_label = if following {
3772 if self.agent.name() == "Zed Agent" {
3773 format!("Stop Following the {}", self.agent.name())
3774 } else {
3775 format!("Stop Following {}", self.agent.name())
3776 }
3777 } else {
3778 if self.agent.name() == "Zed Agent" {
3779 format!("Follow the {}", self.agent.name())
3780 } else {
3781 format!("Follow {}", self.agent.name())
3782 }
3783 };
3784
3785 IconButton::new("follow-agent", IconName::Crosshair)
3786 .icon_size(IconSize::Small)
3787 .icon_color(Color::Muted)
3788 .toggle_state(following)
3789 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
3790 .tooltip(move |window, cx| {
3791 if following {
3792 Tooltip::for_action(tooltip_label.clone(), &Follow, window, cx)
3793 } else {
3794 Tooltip::with_meta(
3795 tooltip_label.clone(),
3796 Some(&Follow),
3797 "Track the agent's location as it reads and edits files.",
3798 window,
3799 cx,
3800 )
3801 }
3802 })
3803 .on_click(cx.listener(move |this, _, window, cx| {
3804 this.toggle_following(window, cx);
3805 }))
3806 }
3807
3808 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
3809 let workspace = self.workspace.clone();
3810 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
3811 Self::open_link(text, &workspace, window, cx);
3812 })
3813 }
3814
3815 fn open_link(
3816 url: SharedString,
3817 workspace: &WeakEntity<Workspace>,
3818 window: &mut Window,
3819 cx: &mut App,
3820 ) {
3821 let Some(workspace) = workspace.upgrade() else {
3822 cx.open_url(&url);
3823 return;
3824 };
3825
3826 if let Some(mention) = MentionUri::parse(&url).log_err() {
3827 workspace.update(cx, |workspace, cx| match mention {
3828 MentionUri::File { abs_path } => {
3829 let project = workspace.project();
3830 let Some(path) =
3831 project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
3832 else {
3833 return;
3834 };
3835
3836 workspace
3837 .open_path(path, None, true, window, cx)
3838 .detach_and_log_err(cx);
3839 }
3840 MentionUri::PastedImage => {}
3841 MentionUri::Directory { abs_path } => {
3842 let project = workspace.project();
3843 let Some(entry) = project.update(cx, |project, cx| {
3844 let path = project.find_project_path(abs_path, cx)?;
3845 project.entry_for_path(&path, cx)
3846 }) else {
3847 return;
3848 };
3849
3850 project.update(cx, |_, cx| {
3851 cx.emit(project::Event::RevealInProjectPanel(entry.id));
3852 });
3853 }
3854 MentionUri::Symbol {
3855 abs_path: path,
3856 line_range,
3857 ..
3858 }
3859 | MentionUri::Selection {
3860 abs_path: Some(path),
3861 line_range,
3862 } => {
3863 let project = workspace.project();
3864 let Some((path, _)) = project.update(cx, |project, cx| {
3865 let path = project.find_project_path(path, cx)?;
3866 let entry = project.entry_for_path(&path, cx)?;
3867 Some((path, entry))
3868 }) else {
3869 return;
3870 };
3871
3872 let item = workspace.open_path(path, None, true, window, cx);
3873 window
3874 .spawn(cx, async move |cx| {
3875 let Some(editor) = item.await?.downcast::<Editor>() else {
3876 return Ok(());
3877 };
3878 let range = Point::new(*line_range.start(), 0)
3879 ..Point::new(*line_range.start(), 0);
3880 editor
3881 .update_in(cx, |editor, window, cx| {
3882 editor.change_selections(
3883 SelectionEffects::scroll(Autoscroll::center()),
3884 window,
3885 cx,
3886 |s| s.select_ranges(vec![range]),
3887 );
3888 })
3889 .ok();
3890 anyhow::Ok(())
3891 })
3892 .detach_and_log_err(cx);
3893 }
3894 MentionUri::Selection { abs_path: None, .. } => {}
3895 MentionUri::Thread { id, name } => {
3896 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3897 panel.update(cx, |panel, cx| {
3898 panel.load_agent_thread(
3899 DbThreadMetadata {
3900 id,
3901 title: name.into(),
3902 updated_at: Default::default(),
3903 },
3904 window,
3905 cx,
3906 )
3907 });
3908 }
3909 }
3910 MentionUri::TextThread { path, .. } => {
3911 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3912 panel.update(cx, |panel, cx| {
3913 panel
3914 .open_saved_prompt_editor(path.as_path().into(), window, cx)
3915 .detach_and_log_err(cx);
3916 });
3917 }
3918 }
3919 MentionUri::Rule { id, .. } => {
3920 let PromptId::User { uuid } = id else {
3921 return;
3922 };
3923 window.dispatch_action(
3924 Box::new(OpenRulesLibrary {
3925 prompt_to_select: Some(uuid.0),
3926 }),
3927 cx,
3928 )
3929 }
3930 MentionUri::Fetch { url } => {
3931 cx.open_url(url.as_str());
3932 }
3933 })
3934 } else {
3935 cx.open_url(&url);
3936 }
3937 }
3938
3939 fn open_tool_call_location(
3940 &self,
3941 entry_ix: usize,
3942 location_ix: usize,
3943 window: &mut Window,
3944 cx: &mut Context<Self>,
3945 ) -> Option<()> {
3946 let (tool_call_location, agent_location) = self
3947 .thread()?
3948 .read(cx)
3949 .entries()
3950 .get(entry_ix)?
3951 .location(location_ix)?;
3952
3953 let project_path = self
3954 .project
3955 .read(cx)
3956 .find_project_path(&tool_call_location.path, cx)?;
3957
3958 let open_task = self
3959 .workspace
3960 .update(cx, |workspace, cx| {
3961 workspace.open_path(project_path, None, true, window, cx)
3962 })
3963 .log_err()?;
3964 window
3965 .spawn(cx, async move |cx| {
3966 let item = open_task.await?;
3967
3968 let Some(active_editor) = item.downcast::<Editor>() else {
3969 return anyhow::Ok(());
3970 };
3971
3972 active_editor.update_in(cx, |editor, window, cx| {
3973 let multibuffer = editor.buffer().read(cx);
3974 let buffer = multibuffer.as_singleton();
3975 if agent_location.buffer.upgrade() == buffer {
3976 let excerpt_id = multibuffer.excerpt_ids().first().cloned();
3977 let anchor = editor::Anchor::in_buffer(
3978 excerpt_id.unwrap(),
3979 buffer.unwrap().read(cx).remote_id(),
3980 agent_location.position,
3981 );
3982 editor.change_selections(Default::default(), window, cx, |selections| {
3983 selections.select_anchor_ranges([anchor..anchor]);
3984 })
3985 } else {
3986 let row = tool_call_location.line.unwrap_or_default();
3987 editor.change_selections(Default::default(), window, cx, |selections| {
3988 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
3989 })
3990 }
3991 })?;
3992
3993 anyhow::Ok(())
3994 })
3995 .detach_and_log_err(cx);
3996
3997 None
3998 }
3999
4000 pub fn open_thread_as_markdown(
4001 &self,
4002 workspace: Entity<Workspace>,
4003 window: &mut Window,
4004 cx: &mut App,
4005 ) -> Task<anyhow::Result<()>> {
4006 let markdown_language_task = workspace
4007 .read(cx)
4008 .app_state()
4009 .languages
4010 .language_for_name("Markdown");
4011
4012 let (thread_summary, markdown) = if let Some(thread) = self.thread() {
4013 let thread = thread.read(cx);
4014 (thread.title().to_string(), thread.to_markdown(cx))
4015 } else {
4016 return Task::ready(Ok(()));
4017 };
4018
4019 window.spawn(cx, async move |cx| {
4020 let markdown_language = markdown_language_task.await?;
4021
4022 workspace.update_in(cx, |workspace, window, cx| {
4023 let project = workspace.project().clone();
4024
4025 if !project.read(cx).is_local() {
4026 bail!("failed to open active thread as markdown in remote project");
4027 }
4028
4029 let buffer = project.update(cx, |project, cx| {
4030 project.create_local_buffer(&markdown, Some(markdown_language), cx)
4031 });
4032 let buffer = cx.new(|cx| {
4033 MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
4034 });
4035
4036 workspace.add_item_to_active_pane(
4037 Box::new(cx.new(|cx| {
4038 let mut editor =
4039 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4040 editor.set_breadcrumb_header(thread_summary);
4041 editor
4042 })),
4043 None,
4044 true,
4045 window,
4046 cx,
4047 );
4048
4049 anyhow::Ok(())
4050 })??;
4051 anyhow::Ok(())
4052 })
4053 }
4054
4055 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
4056 self.list_state.scroll_to(ListOffset::default());
4057 cx.notify();
4058 }
4059
4060 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
4061 if let Some(thread) = self.thread() {
4062 let entry_count = thread.read(cx).entries().len();
4063 self.list_state.reset(entry_count);
4064 cx.notify();
4065 }
4066 }
4067
4068 fn notify_with_sound(
4069 &mut self,
4070 caption: impl Into<SharedString>,
4071 icon: IconName,
4072 window: &mut Window,
4073 cx: &mut Context<Self>,
4074 ) {
4075 self.play_notification_sound(window, cx);
4076 self.show_notification(caption, icon, window, cx);
4077 }
4078
4079 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
4080 let settings = AgentSettings::get_global(cx);
4081 if settings.play_sound_when_agent_done && !window.is_window_active() {
4082 Audio::play_sound(Sound::AgentDone, cx);
4083 }
4084 }
4085
4086 fn show_notification(
4087 &mut self,
4088 caption: impl Into<SharedString>,
4089 icon: IconName,
4090 window: &mut Window,
4091 cx: &mut Context<Self>,
4092 ) {
4093 if window.is_window_active() || !self.notifications.is_empty() {
4094 return;
4095 }
4096
4097 // TODO: Change this once we have title summarization for external agents.
4098 let title = self.agent.name();
4099
4100 match AgentSettings::get_global(cx).notify_when_agent_waiting {
4101 NotifyWhenAgentWaiting::PrimaryScreen => {
4102 if let Some(primary) = cx.primary_display() {
4103 self.pop_up(icon, caption.into(), title, window, primary, cx);
4104 }
4105 }
4106 NotifyWhenAgentWaiting::AllScreens => {
4107 let caption = caption.into();
4108 for screen in cx.displays() {
4109 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
4110 }
4111 }
4112 NotifyWhenAgentWaiting::Never => {
4113 // Don't show anything
4114 }
4115 }
4116 }
4117
4118 fn pop_up(
4119 &mut self,
4120 icon: IconName,
4121 caption: SharedString,
4122 title: SharedString,
4123 window: &mut Window,
4124 screen: Rc<dyn PlatformDisplay>,
4125 cx: &mut Context<Self>,
4126 ) {
4127 let options = AgentNotification::window_options(screen, cx);
4128
4129 let project_name = self.workspace.upgrade().and_then(|workspace| {
4130 workspace
4131 .read(cx)
4132 .project()
4133 .read(cx)
4134 .visible_worktrees(cx)
4135 .next()
4136 .map(|worktree| worktree.read(cx).root_name().to_string())
4137 });
4138
4139 if let Some(screen_window) = cx
4140 .open_window(options, |_, cx| {
4141 cx.new(|_| {
4142 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
4143 })
4144 })
4145 .log_err()
4146 && let Some(pop_up) = screen_window.entity(cx).log_err()
4147 {
4148 self.notification_subscriptions
4149 .entry(screen_window)
4150 .or_insert_with(Vec::new)
4151 .push(cx.subscribe_in(&pop_up, window, {
4152 |this, _, event, window, cx| match event {
4153 AgentNotificationEvent::Accepted => {
4154 let handle = window.window_handle();
4155 cx.activate(true);
4156
4157 let workspace_handle = this.workspace.clone();
4158
4159 // If there are multiple Zed windows, activate the correct one.
4160 cx.defer(move |cx| {
4161 handle
4162 .update(cx, |_view, window, _cx| {
4163 window.activate_window();
4164
4165 if let Some(workspace) = workspace_handle.upgrade() {
4166 workspace.update(_cx, |workspace, cx| {
4167 workspace.focus_panel::<AgentPanel>(window, cx);
4168 });
4169 }
4170 })
4171 .log_err();
4172 });
4173
4174 this.dismiss_notifications(cx);
4175 }
4176 AgentNotificationEvent::Dismissed => {
4177 this.dismiss_notifications(cx);
4178 }
4179 }
4180 }));
4181
4182 self.notifications.push(screen_window);
4183
4184 // If the user manually refocuses the original window, dismiss the popup.
4185 self.notification_subscriptions
4186 .entry(screen_window)
4187 .or_insert_with(Vec::new)
4188 .push({
4189 let pop_up_weak = pop_up.downgrade();
4190
4191 cx.observe_window_activation(window, move |_, window, cx| {
4192 if window.is_window_active()
4193 && let Some(pop_up) = pop_up_weak.upgrade()
4194 {
4195 pop_up.update(cx, |_, cx| {
4196 cx.emit(AgentNotificationEvent::Dismissed);
4197 });
4198 }
4199 })
4200 });
4201 }
4202 }
4203
4204 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
4205 for window in self.notifications.drain(..) {
4206 window
4207 .update(cx, |_, window, _| {
4208 window.remove_window();
4209 })
4210 .ok();
4211
4212 self.notification_subscriptions.remove(&window);
4213 }
4214 }
4215
4216 fn render_thread_controls(
4217 &self,
4218 thread: &Entity<AcpThread>,
4219 cx: &Context<Self>,
4220 ) -> impl IntoElement {
4221 let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
4222 if is_generating {
4223 return h_flex().id("thread-controls-container").child(
4224 div()
4225 .py_2()
4226 .px(rems_from_px(22.))
4227 .child(SpinnerLabel::new().size(LabelSize::Small)),
4228 );
4229 }
4230
4231 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
4232 .shape(ui::IconButtonShape::Square)
4233 .icon_size(IconSize::Small)
4234 .icon_color(Color::Ignored)
4235 .tooltip(Tooltip::text("Open Thread as Markdown"))
4236 .on_click(cx.listener(move |this, _, window, cx| {
4237 if let Some(workspace) = this.workspace.upgrade() {
4238 this.open_thread_as_markdown(workspace, window, cx)
4239 .detach_and_log_err(cx);
4240 }
4241 }));
4242
4243 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
4244 .shape(ui::IconButtonShape::Square)
4245 .icon_size(IconSize::Small)
4246 .icon_color(Color::Ignored)
4247 .tooltip(Tooltip::text("Scroll To Top"))
4248 .on_click(cx.listener(move |this, _, _, cx| {
4249 this.scroll_to_top(cx);
4250 }));
4251
4252 let mut container = h_flex()
4253 .id("thread-controls-container")
4254 .group("thread-controls-container")
4255 .w_full()
4256 .py_2()
4257 .px_5()
4258 .gap_px()
4259 .opacity(0.6)
4260 .hover(|style| style.opacity(1.))
4261 .flex_wrap()
4262 .justify_end();
4263
4264 if AgentSettings::get_global(cx).enable_feedback
4265 && self
4266 .thread()
4267 .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
4268 {
4269 let feedback = self.thread_feedback.feedback;
4270
4271 container = container
4272 .child(
4273 div().visible_on_hover("thread-controls-container").child(
4274 Label::new(match feedback {
4275 Some(ThreadFeedback::Positive) => "Thanks for your feedback!",
4276 Some(ThreadFeedback::Negative) => {
4277 "We appreciate your feedback and will use it to improve."
4278 }
4279 None => {
4280 "Rating the thread sends all of your current conversation to the Zed team."
4281 }
4282 })
4283 .color(Color::Muted)
4284 .size(LabelSize::XSmall)
4285 .truncate(),
4286 ),
4287 )
4288 .child(
4289 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
4290 .shape(ui::IconButtonShape::Square)
4291 .icon_size(IconSize::Small)
4292 .icon_color(match feedback {
4293 Some(ThreadFeedback::Positive) => Color::Accent,
4294 _ => Color::Ignored,
4295 })
4296 .tooltip(Tooltip::text("Helpful Response"))
4297 .on_click(cx.listener(move |this, _, window, cx| {
4298 this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
4299 })),
4300 )
4301 .child(
4302 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
4303 .shape(ui::IconButtonShape::Square)
4304 .icon_size(IconSize::Small)
4305 .icon_color(match feedback {
4306 Some(ThreadFeedback::Negative) => Color::Accent,
4307 _ => Color::Ignored,
4308 })
4309 .tooltip(Tooltip::text("Not Helpful"))
4310 .on_click(cx.listener(move |this, _, window, cx| {
4311 this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
4312 })),
4313 );
4314 }
4315
4316 container.child(open_as_markdown).child(scroll_to_top)
4317 }
4318
4319 fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
4320 h_flex()
4321 .key_context("AgentFeedbackMessageEditor")
4322 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
4323 this.thread_feedback.dismiss_comments();
4324 cx.notify();
4325 }))
4326 .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
4327 this.submit_feedback_message(cx);
4328 }))
4329 .p_2()
4330 .mb_2()
4331 .mx_5()
4332 .gap_1()
4333 .rounded_md()
4334 .border_1()
4335 .border_color(cx.theme().colors().border)
4336 .bg(cx.theme().colors().editor_background)
4337 .child(div().w_full().child(editor))
4338 .child(
4339 h_flex()
4340 .child(
4341 IconButton::new("dismiss-feedback-message", IconName::Close)
4342 .icon_color(Color::Error)
4343 .icon_size(IconSize::XSmall)
4344 .shape(ui::IconButtonShape::Square)
4345 .on_click(cx.listener(move |this, _, _window, cx| {
4346 this.thread_feedback.dismiss_comments();
4347 cx.notify();
4348 })),
4349 )
4350 .child(
4351 IconButton::new("submit-feedback-message", IconName::Return)
4352 .icon_size(IconSize::XSmall)
4353 .shape(ui::IconButtonShape::Square)
4354 .on_click(cx.listener(move |this, _, _window, cx| {
4355 this.submit_feedback_message(cx);
4356 })),
4357 ),
4358 )
4359 }
4360
4361 fn handle_feedback_click(
4362 &mut self,
4363 feedback: ThreadFeedback,
4364 window: &mut Window,
4365 cx: &mut Context<Self>,
4366 ) {
4367 let Some(thread) = self.thread().cloned() else {
4368 return;
4369 };
4370
4371 self.thread_feedback.submit(thread, feedback, window, cx);
4372 cx.notify();
4373 }
4374
4375 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
4376 let Some(thread) = self.thread().cloned() else {
4377 return;
4378 };
4379
4380 self.thread_feedback.submit_comments(thread, cx);
4381 cx.notify();
4382 }
4383
4384 fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
4385 div()
4386 .id("acp-thread-scrollbar")
4387 .occlude()
4388 .on_mouse_move(cx.listener(|_, _, _, cx| {
4389 cx.notify();
4390 cx.stop_propagation()
4391 }))
4392 .on_hover(|_, _, cx| {
4393 cx.stop_propagation();
4394 })
4395 .on_any_mouse_down(|_, _, cx| {
4396 cx.stop_propagation();
4397 })
4398 .on_mouse_up(
4399 MouseButton::Left,
4400 cx.listener(|_, _, _, cx| {
4401 cx.stop_propagation();
4402 }),
4403 )
4404 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
4405 cx.notify();
4406 }))
4407 .h_full()
4408 .absolute()
4409 .right_1()
4410 .top_1()
4411 .bottom_0()
4412 .w(px(12.))
4413 .cursor_default()
4414 .children(Scrollbar::vertical(self.scrollbar_state.clone()).map(|s| s.auto_hide(cx)))
4415 }
4416
4417 fn render_token_limit_callout(
4418 &self,
4419 line_height: Pixels,
4420 cx: &mut Context<Self>,
4421 ) -> Option<Callout> {
4422 let token_usage = self.thread()?.read(cx).token_usage()?;
4423 let ratio = token_usage.ratio();
4424
4425 let (severity, title) = match ratio {
4426 acp_thread::TokenUsageRatio::Normal => return None,
4427 acp_thread::TokenUsageRatio::Warning => {
4428 (Severity::Warning, "Thread reaching the token limit soon")
4429 }
4430 acp_thread::TokenUsageRatio::Exceeded => {
4431 (Severity::Error, "Thread reached the token limit")
4432 }
4433 };
4434
4435 let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
4436 thread.read(cx).completion_mode() == CompletionMode::Normal
4437 && thread
4438 .read(cx)
4439 .model()
4440 .is_some_and(|model| model.supports_burn_mode())
4441 });
4442
4443 let description = if burn_mode_available {
4444 "To continue, start a new thread from a summary or turn Burn Mode on."
4445 } else {
4446 "To continue, start a new thread from a summary."
4447 };
4448
4449 Some(
4450 Callout::new()
4451 .severity(severity)
4452 .line_height(line_height)
4453 .title(title)
4454 .description(description)
4455 .actions_slot(
4456 h_flex()
4457 .gap_0p5()
4458 .child(
4459 Button::new("start-new-thread", "Start New Thread")
4460 .label_size(LabelSize::Small)
4461 .on_click(cx.listener(|this, _, window, cx| {
4462 let Some(thread) = this.thread() else {
4463 return;
4464 };
4465 let session_id = thread.read(cx).session_id().clone();
4466 window.dispatch_action(
4467 crate::NewNativeAgentThreadFromSummary {
4468 from_session_id: session_id,
4469 }
4470 .boxed_clone(),
4471 cx,
4472 );
4473 })),
4474 )
4475 .when(burn_mode_available, |this| {
4476 this.child(
4477 IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
4478 .icon_size(IconSize::XSmall)
4479 .on_click(cx.listener(|this, _event, window, cx| {
4480 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4481 })),
4482 )
4483 }),
4484 ),
4485 )
4486 }
4487
4488 fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
4489 if !self.is_using_zed_ai_models(cx) {
4490 return None;
4491 }
4492
4493 let user_store = self.project.read(cx).user_store().read(cx);
4494 if user_store.is_usage_based_billing_enabled() {
4495 return None;
4496 }
4497
4498 let plan = user_store.plan().unwrap_or(cloud_llm_client::Plan::ZedFree);
4499
4500 let usage = user_store.model_request_usage()?;
4501
4502 Some(
4503 div()
4504 .child(UsageCallout::new(plan, usage))
4505 .line_height(line_height),
4506 )
4507 }
4508
4509 fn settings_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
4510 self.entry_view_state.update(cx, |entry_view_state, cx| {
4511 entry_view_state.settings_changed(cx);
4512 });
4513 }
4514
4515 pub(crate) fn insert_dragged_files(
4516 &self,
4517 paths: Vec<project::ProjectPath>,
4518 added_worktrees: Vec<Entity<project::Worktree>>,
4519 window: &mut Window,
4520 cx: &mut Context<Self>,
4521 ) {
4522 self.message_editor.update(cx, |message_editor, cx| {
4523 message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
4524 })
4525 }
4526
4527 pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
4528 self.message_editor.update(cx, |message_editor, cx| {
4529 message_editor.insert_selections(window, cx);
4530 })
4531 }
4532
4533 fn render_thread_retry_status_callout(
4534 &self,
4535 _window: &mut Window,
4536 _cx: &mut Context<Self>,
4537 ) -> Option<Callout> {
4538 let state = self.thread_retry_status.as_ref()?;
4539
4540 let next_attempt_in = state
4541 .duration
4542 .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
4543 if next_attempt_in.is_zero() {
4544 return None;
4545 }
4546
4547 let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
4548
4549 let retry_message = if state.max_attempts == 1 {
4550 if next_attempt_in_secs == 1 {
4551 "Retrying. Next attempt in 1 second.".to_string()
4552 } else {
4553 format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
4554 }
4555 } else if next_attempt_in_secs == 1 {
4556 format!(
4557 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
4558 state.attempt, state.max_attempts,
4559 )
4560 } else {
4561 format!(
4562 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
4563 state.attempt, state.max_attempts,
4564 )
4565 };
4566
4567 Some(
4568 Callout::new()
4569 .severity(Severity::Warning)
4570 .title(state.last_error.clone())
4571 .description(retry_message),
4572 )
4573 }
4574
4575 fn render_thread_error(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
4576 let content = match self.thread_error.as_ref()? {
4577 ThreadError::Other(error) => self.render_any_thread_error(error.clone(), cx),
4578 ThreadError::AuthenticationRequired(error) => {
4579 self.render_authentication_required_error(error.clone(), cx)
4580 }
4581 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
4582 ThreadError::ModelRequestLimitReached(plan) => {
4583 self.render_model_request_limit_reached_error(*plan, cx)
4584 }
4585 ThreadError::ToolUseLimitReached => {
4586 self.render_tool_use_limit_reached_error(window, cx)?
4587 }
4588 };
4589
4590 Some(div().child(content))
4591 }
4592
4593 fn render_any_thread_error(&self, error: SharedString, cx: &mut Context<'_, Self>) -> Callout {
4594 let can_resume = self
4595 .thread()
4596 .map_or(false, |thread| thread.read(cx).can_resume(cx));
4597
4598 let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
4599 let thread = thread.read(cx);
4600 let supports_burn_mode = thread
4601 .model()
4602 .map_or(false, |model| model.supports_burn_mode());
4603 supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
4604 });
4605
4606 Callout::new()
4607 .severity(Severity::Error)
4608 .title("Error")
4609 .icon(IconName::XCircle)
4610 .description(error.clone())
4611 .actions_slot(
4612 h_flex()
4613 .gap_0p5()
4614 .when(can_resume && can_enable_burn_mode, |this| {
4615 this.child(
4616 Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
4617 .icon(IconName::ZedBurnMode)
4618 .icon_position(IconPosition::Start)
4619 .icon_size(IconSize::Small)
4620 .label_size(LabelSize::Small)
4621 .on_click(cx.listener(|this, _, window, cx| {
4622 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4623 this.resume_chat(cx);
4624 })),
4625 )
4626 })
4627 .when(can_resume, |this| {
4628 this.child(
4629 Button::new("retry", "Retry")
4630 .icon(IconName::RotateCw)
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.resume_chat(cx);
4636 })),
4637 )
4638 })
4639 .child(self.create_copy_button(error.to_string())),
4640 )
4641 .dismiss_action(self.dismiss_error_button(cx))
4642 }
4643
4644 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
4645 const ERROR_MESSAGE: &str =
4646 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
4647
4648 Callout::new()
4649 .severity(Severity::Error)
4650 .icon(IconName::XCircle)
4651 .title("Free Usage Exceeded")
4652 .description(ERROR_MESSAGE)
4653 .actions_slot(
4654 h_flex()
4655 .gap_0p5()
4656 .child(self.upgrade_button(cx))
4657 .child(self.create_copy_button(ERROR_MESSAGE)),
4658 )
4659 .dismiss_action(self.dismiss_error_button(cx))
4660 }
4661
4662 fn render_authentication_required_error(
4663 &self,
4664 error: SharedString,
4665 cx: &mut Context<Self>,
4666 ) -> Callout {
4667 Callout::new()
4668 .severity(Severity::Error)
4669 .title("Authentication Required")
4670 .icon(IconName::XCircle)
4671 .description(error.clone())
4672 .actions_slot(
4673 h_flex()
4674 .gap_0p5()
4675 .child(self.authenticate_button(cx))
4676 .child(self.create_copy_button(error)),
4677 )
4678 .dismiss_action(self.dismiss_error_button(cx))
4679 }
4680
4681 fn render_model_request_limit_reached_error(
4682 &self,
4683 plan: cloud_llm_client::Plan,
4684 cx: &mut Context<Self>,
4685 ) -> Callout {
4686 let error_message = match plan {
4687 cloud_llm_client::Plan::ZedPro => "Upgrade to usage-based billing for more prompts.",
4688 cloud_llm_client::Plan::ZedProTrial | cloud_llm_client::Plan::ZedFree => {
4689 "Upgrade to Zed Pro for more prompts."
4690 }
4691 };
4692
4693 Callout::new()
4694 .severity(Severity::Error)
4695 .title("Model Prompt Limit Reached")
4696 .icon(IconName::XCircle)
4697 .description(error_message)
4698 .actions_slot(
4699 h_flex()
4700 .gap_0p5()
4701 .child(self.upgrade_button(cx))
4702 .child(self.create_copy_button(error_message)),
4703 )
4704 .dismiss_action(self.dismiss_error_button(cx))
4705 }
4706
4707 fn render_tool_use_limit_reached_error(
4708 &self,
4709 window: &mut Window,
4710 cx: &mut Context<Self>,
4711 ) -> Option<Callout> {
4712 let thread = self.as_native_thread(cx)?;
4713 let supports_burn_mode = thread
4714 .read(cx)
4715 .model()
4716 .is_some_and(|model| model.supports_burn_mode());
4717
4718 let focus_handle = self.focus_handle(cx);
4719
4720 Some(
4721 Callout::new()
4722 .icon(IconName::Info)
4723 .title("Consecutive tool use limit reached.")
4724 .actions_slot(
4725 h_flex()
4726 .gap_0p5()
4727 .when(supports_burn_mode, |this| {
4728 this.child(
4729 Button::new("continue-burn-mode", "Continue with Burn Mode")
4730 .style(ButtonStyle::Filled)
4731 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
4732 .layer(ElevationIndex::ModalSurface)
4733 .label_size(LabelSize::Small)
4734 .key_binding(
4735 KeyBinding::for_action_in(
4736 &ContinueWithBurnMode,
4737 &focus_handle,
4738 window,
4739 cx,
4740 )
4741 .map(|kb| kb.size(rems_from_px(10.))),
4742 )
4743 .tooltip(Tooltip::text(
4744 "Enable Burn Mode for unlimited tool use.",
4745 ))
4746 .on_click({
4747 cx.listener(move |this, _, _window, cx| {
4748 thread.update(cx, |thread, cx| {
4749 thread
4750 .set_completion_mode(CompletionMode::Burn, cx);
4751 });
4752 this.resume_chat(cx);
4753 })
4754 }),
4755 )
4756 })
4757 .child(
4758 Button::new("continue-conversation", "Continue")
4759 .layer(ElevationIndex::ModalSurface)
4760 .label_size(LabelSize::Small)
4761 .key_binding(
4762 KeyBinding::for_action_in(
4763 &ContinueThread,
4764 &focus_handle,
4765 window,
4766 cx,
4767 )
4768 .map(|kb| kb.size(rems_from_px(10.))),
4769 )
4770 .on_click(cx.listener(|this, _, _window, cx| {
4771 this.resume_chat(cx);
4772 })),
4773 ),
4774 ),
4775 )
4776 }
4777
4778 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
4779 let message = message.into();
4780
4781 IconButton::new("copy", IconName::Copy)
4782 .icon_size(IconSize::Small)
4783 .icon_color(Color::Muted)
4784 .tooltip(Tooltip::text("Copy Error Message"))
4785 .on_click(move |_, _, cx| {
4786 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
4787 })
4788 }
4789
4790 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4791 IconButton::new("dismiss", IconName::Close)
4792 .icon_size(IconSize::Small)
4793 .icon_color(Color::Muted)
4794 .tooltip(Tooltip::text("Dismiss Error"))
4795 .on_click(cx.listener({
4796 move |this, _, _, cx| {
4797 this.clear_thread_error(cx);
4798 cx.notify();
4799 }
4800 }))
4801 }
4802
4803 fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4804 Button::new("authenticate", "Authenticate")
4805 .label_size(LabelSize::Small)
4806 .style(ButtonStyle::Filled)
4807 .on_click(cx.listener({
4808 move |this, _, window, cx| {
4809 let agent = this.agent.clone();
4810 let ThreadState::Ready { thread, .. } = &this.thread_state else {
4811 return;
4812 };
4813
4814 let connection = thread.read(cx).connection().clone();
4815 let err = AuthRequired {
4816 description: None,
4817 provider_id: None,
4818 };
4819 this.clear_thread_error(cx);
4820 let this = cx.weak_entity();
4821 window.defer(cx, |window, cx| {
4822 Self::handle_auth_required(this, err, agent, connection, window, cx);
4823 })
4824 }
4825 }))
4826 }
4827
4828 pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4829 let agent = self.agent.clone();
4830 let ThreadState::Ready { thread, .. } = &self.thread_state else {
4831 return;
4832 };
4833
4834 let connection = thread.read(cx).connection().clone();
4835 let err = AuthRequired {
4836 description: None,
4837 provider_id: None,
4838 };
4839 self.clear_thread_error(cx);
4840 let this = cx.weak_entity();
4841 window.defer(cx, |window, cx| {
4842 Self::handle_auth_required(this, err, agent, connection, window, cx);
4843 })
4844 }
4845
4846 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4847 Button::new("upgrade", "Upgrade")
4848 .label_size(LabelSize::Small)
4849 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
4850 .on_click(cx.listener({
4851 move |this, _, _, cx| {
4852 this.clear_thread_error(cx);
4853 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
4854 }
4855 }))
4856 }
4857
4858 fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4859 self.thread_state = Self::initial_state(
4860 self.agent.clone(),
4861 None,
4862 self.workspace.clone(),
4863 self.project.clone(),
4864 window,
4865 cx,
4866 );
4867 cx.notify();
4868 }
4869
4870 pub fn delete_history_entry(&mut self, entry: HistoryEntry, cx: &mut Context<Self>) {
4871 let task = match entry {
4872 HistoryEntry::AcpThread(thread) => self.history_store.update(cx, |history, cx| {
4873 history.delete_thread(thread.id.clone(), cx)
4874 }),
4875 HistoryEntry::TextThread(context) => self.history_store.update(cx, |history, cx| {
4876 history.delete_text_thread(context.path.clone(), cx)
4877 }),
4878 };
4879 task.detach_and_log_err(cx);
4880 }
4881}
4882
4883fn loading_contents_spinner(size: IconSize) -> AnyElement {
4884 Icon::new(IconName::LoadCircle)
4885 .size(size)
4886 .color(Color::Accent)
4887 .with_animation(
4888 "load_context_circle",
4889 Animation::new(Duration::from_secs(3)).repeat(),
4890 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
4891 )
4892 .into_any_element()
4893}
4894
4895impl Focusable for AcpThreadView {
4896 fn focus_handle(&self, cx: &App) -> FocusHandle {
4897 match self.thread_state {
4898 ThreadState::Loading { .. } | ThreadState::Ready { .. } => {
4899 self.message_editor.focus_handle(cx)
4900 }
4901 ThreadState::LoadError(_) | ThreadState::Unauthenticated { .. } => {
4902 self.focus_handle.clone()
4903 }
4904 }
4905 }
4906}
4907
4908impl Render for AcpThreadView {
4909 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4910 let has_messages = self.list_state.item_count() > 0;
4911 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
4912
4913 v_flex()
4914 .size_full()
4915 .key_context("AcpThread")
4916 .on_action(cx.listener(Self::open_agent_diff))
4917 .on_action(cx.listener(Self::toggle_burn_mode))
4918 .on_action(cx.listener(Self::keep_all))
4919 .on_action(cx.listener(Self::reject_all))
4920 .track_focus(&self.focus_handle)
4921 .bg(cx.theme().colors().panel_background)
4922 .child(match &self.thread_state {
4923 ThreadState::Unauthenticated {
4924 connection,
4925 description,
4926 configuration_view,
4927 pending_auth_method,
4928 ..
4929 } => self.render_auth_required_state(
4930 connection,
4931 description.as_ref(),
4932 configuration_view.as_ref(),
4933 pending_auth_method.as_ref(),
4934 window,
4935 cx,
4936 ),
4937 ThreadState::Loading { .. } => v_flex()
4938 .flex_1()
4939 .child(self.render_recent_history(window, cx)),
4940 ThreadState::LoadError(e) => v_flex()
4941 .flex_1()
4942 .size_full()
4943 .items_center()
4944 .justify_end()
4945 .child(self.render_load_error(e, window, cx)),
4946 ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
4947 if has_messages {
4948 this.child(
4949 list(
4950 self.list_state.clone(),
4951 cx.processor(|this, index: usize, window, cx| {
4952 let Some((entry, len)) = this.thread().and_then(|thread| {
4953 let entries = &thread.read(cx).entries();
4954 Some((entries.get(index)?, entries.len()))
4955 }) else {
4956 return Empty.into_any();
4957 };
4958 this.render_entry(index, len, entry, window, cx)
4959 }),
4960 )
4961 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
4962 .flex_grow()
4963 .into_any(),
4964 )
4965 .child(self.render_vertical_scrollbar(cx))
4966 } else {
4967 this.child(self.render_recent_history(window, cx))
4968 }
4969 }),
4970 })
4971 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
4972 // above so that the scrollbar doesn't render behind it. The current setup allows
4973 // the scrollbar to stop exactly at the activity bar start.
4974 .when(has_messages, |this| match &self.thread_state {
4975 ThreadState::Ready { thread, .. } => {
4976 this.children(self.render_activity_bar(thread, window, cx))
4977 }
4978 _ => this,
4979 })
4980 .children(self.render_thread_retry_status_callout(window, cx))
4981 .children(self.render_thread_error(window, cx))
4982 .children(
4983 if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
4984 Some(usage_callout.into_any_element())
4985 } else {
4986 self.render_token_limit_callout(line_height, cx)
4987 .map(|token_limit_callout| token_limit_callout.into_any_element())
4988 },
4989 )
4990 .child(self.render_message_editor(window, cx))
4991 }
4992}
4993
4994fn default_markdown_style(
4995 buffer_font: bool,
4996 muted_text: bool,
4997 window: &Window,
4998 cx: &App,
4999) -> MarkdownStyle {
5000 let theme_settings = ThemeSettings::get_global(cx);
5001 let colors = cx.theme().colors();
5002
5003 let buffer_font_size = TextSize::Small.rems(cx);
5004
5005 let mut text_style = window.text_style();
5006 let line_height = buffer_font_size * 1.75;
5007
5008 let font_family = if buffer_font {
5009 theme_settings.buffer_font.family.clone()
5010 } else {
5011 theme_settings.ui_font.family.clone()
5012 };
5013
5014 let font_size = if buffer_font {
5015 TextSize::Small.rems(cx)
5016 } else {
5017 TextSize::Default.rems(cx)
5018 };
5019
5020 let text_color = if muted_text {
5021 colors.text_muted
5022 } else {
5023 colors.text
5024 };
5025
5026 text_style.refine(&TextStyleRefinement {
5027 font_family: Some(font_family),
5028 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
5029 font_features: Some(theme_settings.ui_font.features.clone()),
5030 font_size: Some(font_size.into()),
5031 line_height: Some(line_height.into()),
5032 color: Some(text_color),
5033 ..Default::default()
5034 });
5035
5036 MarkdownStyle {
5037 base_text_style: text_style.clone(),
5038 syntax: cx.theme().syntax().clone(),
5039 selection_background_color: colors.element_selection_background,
5040 code_block_overflow_x_scroll: true,
5041 table_overflow_x_scroll: true,
5042 heading_level_styles: Some(HeadingLevelStyles {
5043 h1: Some(TextStyleRefinement {
5044 font_size: Some(rems(1.15).into()),
5045 ..Default::default()
5046 }),
5047 h2: Some(TextStyleRefinement {
5048 font_size: Some(rems(1.1).into()),
5049 ..Default::default()
5050 }),
5051 h3: Some(TextStyleRefinement {
5052 font_size: Some(rems(1.05).into()),
5053 ..Default::default()
5054 }),
5055 h4: Some(TextStyleRefinement {
5056 font_size: Some(rems(1.).into()),
5057 ..Default::default()
5058 }),
5059 h5: Some(TextStyleRefinement {
5060 font_size: Some(rems(0.95).into()),
5061 ..Default::default()
5062 }),
5063 h6: Some(TextStyleRefinement {
5064 font_size: Some(rems(0.875).into()),
5065 ..Default::default()
5066 }),
5067 }),
5068 code_block: StyleRefinement {
5069 padding: EdgesRefinement {
5070 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5071 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5072 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5073 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5074 },
5075 margin: EdgesRefinement {
5076 top: Some(Length::Definite(Pixels(8.).into())),
5077 left: Some(Length::Definite(Pixels(0.).into())),
5078 right: Some(Length::Definite(Pixels(0.).into())),
5079 bottom: Some(Length::Definite(Pixels(12.).into())),
5080 },
5081 border_style: Some(BorderStyle::Solid),
5082 border_widths: EdgesRefinement {
5083 top: Some(AbsoluteLength::Pixels(Pixels(1.))),
5084 left: Some(AbsoluteLength::Pixels(Pixels(1.))),
5085 right: Some(AbsoluteLength::Pixels(Pixels(1.))),
5086 bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
5087 },
5088 border_color: Some(colors.border_variant),
5089 background: Some(colors.editor_background.into()),
5090 text: Some(TextStyleRefinement {
5091 font_family: Some(theme_settings.buffer_font.family.clone()),
5092 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5093 font_features: Some(theme_settings.buffer_font.features.clone()),
5094 font_size: Some(buffer_font_size.into()),
5095 ..Default::default()
5096 }),
5097 ..Default::default()
5098 },
5099 inline_code: TextStyleRefinement {
5100 font_family: Some(theme_settings.buffer_font.family.clone()),
5101 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5102 font_features: Some(theme_settings.buffer_font.features.clone()),
5103 font_size: Some(buffer_font_size.into()),
5104 background_color: Some(colors.editor_foreground.opacity(0.08)),
5105 ..Default::default()
5106 },
5107 link: TextStyleRefinement {
5108 background_color: Some(colors.editor_foreground.opacity(0.025)),
5109 underline: Some(UnderlineStyle {
5110 color: Some(colors.text_accent.opacity(0.5)),
5111 thickness: px(1.),
5112 ..Default::default()
5113 }),
5114 ..Default::default()
5115 },
5116 ..Default::default()
5117 }
5118}
5119
5120fn plan_label_markdown_style(
5121 status: &acp::PlanEntryStatus,
5122 window: &Window,
5123 cx: &App,
5124) -> MarkdownStyle {
5125 let default_md_style = default_markdown_style(false, false, window, cx);
5126
5127 MarkdownStyle {
5128 base_text_style: TextStyle {
5129 color: cx.theme().colors().text_muted,
5130 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
5131 Some(gpui::StrikethroughStyle {
5132 thickness: px(1.),
5133 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
5134 })
5135 } else {
5136 None
5137 },
5138 ..default_md_style.base_text_style
5139 },
5140 ..default_md_style
5141 }
5142}
5143
5144fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
5145 let default_md_style = default_markdown_style(true, false, window, cx);
5146
5147 MarkdownStyle {
5148 base_text_style: TextStyle {
5149 ..default_md_style.base_text_style
5150 },
5151 selection_background_color: cx.theme().colors().element_selection_background,
5152 ..Default::default()
5153 }
5154}
5155
5156#[cfg(test)]
5157pub(crate) mod tests {
5158 use acp_thread::StubAgentConnection;
5159 use agent_client_protocol::SessionId;
5160 use assistant_context::ContextStore;
5161 use editor::EditorSettings;
5162 use fs::FakeFs;
5163 use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
5164 use project::Project;
5165 use serde_json::json;
5166 use settings::SettingsStore;
5167 use std::any::Any;
5168 use std::path::Path;
5169 use workspace::Item;
5170
5171 use super::*;
5172
5173 #[gpui::test]
5174 async fn test_drop(cx: &mut TestAppContext) {
5175 init_test(cx);
5176
5177 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5178 let weak_view = thread_view.downgrade();
5179 drop(thread_view);
5180 assert!(!weak_view.is_upgradable());
5181 }
5182
5183 #[gpui::test]
5184 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
5185 init_test(cx);
5186
5187 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5188
5189 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5190 message_editor.update_in(cx, |editor, window, cx| {
5191 editor.set_text("Hello", window, cx);
5192 });
5193
5194 cx.deactivate_window();
5195
5196 thread_view.update_in(cx, |thread_view, window, cx| {
5197 thread_view.send(window, cx);
5198 });
5199
5200 cx.run_until_parked();
5201
5202 assert!(
5203 cx.windows()
5204 .iter()
5205 .any(|window| window.downcast::<AgentNotification>().is_some())
5206 );
5207 }
5208
5209 #[gpui::test]
5210 async fn test_notification_for_error(cx: &mut TestAppContext) {
5211 init_test(cx);
5212
5213 let (thread_view, cx) =
5214 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
5215
5216 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5217 message_editor.update_in(cx, |editor, window, cx| {
5218 editor.set_text("Hello", window, cx);
5219 });
5220
5221 cx.deactivate_window();
5222
5223 thread_view.update_in(cx, |thread_view, window, cx| {
5224 thread_view.send(window, cx);
5225 });
5226
5227 cx.run_until_parked();
5228
5229 assert!(
5230 cx.windows()
5231 .iter()
5232 .any(|window| window.downcast::<AgentNotification>().is_some())
5233 );
5234 }
5235
5236 #[gpui::test]
5237 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
5238 init_test(cx);
5239
5240 let tool_call_id = acp::ToolCallId("1".into());
5241 let tool_call = acp::ToolCall {
5242 id: tool_call_id.clone(),
5243 title: "Label".into(),
5244 kind: acp::ToolKind::Edit,
5245 status: acp::ToolCallStatus::Pending,
5246 content: vec!["hi".into()],
5247 locations: vec![],
5248 raw_input: None,
5249 raw_output: None,
5250 };
5251 let connection =
5252 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5253 tool_call_id,
5254 vec![acp::PermissionOption {
5255 id: acp::PermissionOptionId("1".into()),
5256 name: "Allow".into(),
5257 kind: acp::PermissionOptionKind::AllowOnce,
5258 }],
5259 )]));
5260
5261 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5262
5263 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5264
5265 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5266 message_editor.update_in(cx, |editor, window, cx| {
5267 editor.set_text("Hello", window, cx);
5268 });
5269
5270 cx.deactivate_window();
5271
5272 thread_view.update_in(cx, |thread_view, window, cx| {
5273 thread_view.send(window, cx);
5274 });
5275
5276 cx.run_until_parked();
5277
5278 assert!(
5279 cx.windows()
5280 .iter()
5281 .any(|window| window.downcast::<AgentNotification>().is_some())
5282 );
5283 }
5284
5285 async fn setup_thread_view(
5286 agent: impl AgentServer + 'static,
5287 cx: &mut TestAppContext,
5288 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
5289 let fs = FakeFs::new(cx.executor());
5290 let project = Project::test(fs, [], cx).await;
5291 let (workspace, cx) =
5292 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5293
5294 let context_store =
5295 cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5296 let history_store =
5297 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5298
5299 let thread_view = cx.update(|window, cx| {
5300 cx.new(|cx| {
5301 AcpThreadView::new(
5302 Rc::new(agent),
5303 None,
5304 None,
5305 workspace.downgrade(),
5306 project,
5307 history_store,
5308 None,
5309 window,
5310 cx,
5311 )
5312 })
5313 });
5314 cx.run_until_parked();
5315 (thread_view, cx)
5316 }
5317
5318 fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
5319 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
5320
5321 workspace
5322 .update_in(cx, |workspace, window, cx| {
5323 workspace.add_item_to_active_pane(
5324 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
5325 None,
5326 true,
5327 window,
5328 cx,
5329 );
5330 })
5331 .unwrap();
5332 }
5333
5334 struct ThreadViewItem(Entity<AcpThreadView>);
5335
5336 impl Item for ThreadViewItem {
5337 type Event = ();
5338
5339 fn include_in_nav_history() -> bool {
5340 false
5341 }
5342
5343 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
5344 "Test".into()
5345 }
5346 }
5347
5348 impl EventEmitter<()> for ThreadViewItem {}
5349
5350 impl Focusable for ThreadViewItem {
5351 fn focus_handle(&self, cx: &App) -> FocusHandle {
5352 self.0.read(cx).focus_handle(cx)
5353 }
5354 }
5355
5356 impl Render for ThreadViewItem {
5357 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5358 self.0.clone().into_any_element()
5359 }
5360 }
5361
5362 struct StubAgentServer<C> {
5363 connection: C,
5364 }
5365
5366 impl<C> StubAgentServer<C> {
5367 fn new(connection: C) -> Self {
5368 Self { connection }
5369 }
5370 }
5371
5372 impl StubAgentServer<StubAgentConnection> {
5373 fn default_response() -> Self {
5374 let conn = StubAgentConnection::new();
5375 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5376 content: "Default response".into(),
5377 }]);
5378 Self::new(conn)
5379 }
5380 }
5381
5382 impl<C> AgentServer for StubAgentServer<C>
5383 where
5384 C: 'static + AgentConnection + Send + Clone,
5385 {
5386 fn telemetry_id(&self) -> &'static str {
5387 "test"
5388 }
5389
5390 fn logo(&self) -> ui::IconName {
5391 ui::IconName::Ai
5392 }
5393
5394 fn name(&self) -> SharedString {
5395 "Test".into()
5396 }
5397
5398 fn empty_state_headline(&self) -> SharedString {
5399 "Test".into()
5400 }
5401
5402 fn empty_state_message(&self) -> SharedString {
5403 "Test".into()
5404 }
5405
5406 fn connect(
5407 &self,
5408 _root_dir: &Path,
5409 _project: &Entity<Project>,
5410 _cx: &mut App,
5411 ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
5412 Task::ready(Ok(Rc::new(self.connection.clone())))
5413 }
5414
5415 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5416 self
5417 }
5418 }
5419
5420 #[derive(Clone)]
5421 struct SaboteurAgentConnection;
5422
5423 impl AgentConnection for SaboteurAgentConnection {
5424 fn new_thread(
5425 self: Rc<Self>,
5426 project: Entity<Project>,
5427 _cwd: &Path,
5428 cx: &mut gpui::App,
5429 ) -> Task<gpui::Result<Entity<AcpThread>>> {
5430 Task::ready(Ok(cx.new(|cx| {
5431 let action_log = cx.new(|_| ActionLog::new(project.clone()));
5432 AcpThread::new(
5433 "SaboteurAgentConnection",
5434 self,
5435 project,
5436 action_log,
5437 SessionId("test".into()),
5438 watch::Receiver::constant(acp::PromptCapabilities {
5439 image: true,
5440 audio: true,
5441 embedded_context: true,
5442 }),
5443 cx,
5444 )
5445 })))
5446 }
5447
5448 fn auth_methods(&self) -> &[acp::AuthMethod] {
5449 &[]
5450 }
5451
5452 fn authenticate(
5453 &self,
5454 _method_id: acp::AuthMethodId,
5455 _cx: &mut App,
5456 ) -> Task<gpui::Result<()>> {
5457 unimplemented!()
5458 }
5459
5460 fn prompt(
5461 &self,
5462 _id: Option<acp_thread::UserMessageId>,
5463 _params: acp::PromptRequest,
5464 _cx: &mut App,
5465 ) -> Task<gpui::Result<acp::PromptResponse>> {
5466 Task::ready(Err(anyhow::anyhow!("Error prompting")))
5467 }
5468
5469 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
5470 unimplemented!()
5471 }
5472
5473 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5474 self
5475 }
5476 }
5477
5478 pub(crate) fn init_test(cx: &mut TestAppContext) {
5479 cx.update(|cx| {
5480 let settings_store = SettingsStore::test(cx);
5481 cx.set_global(settings_store);
5482 language::init(cx);
5483 Project::init_settings(cx);
5484 AgentSettings::register(cx);
5485 workspace::init_settings(cx);
5486 ThemeSettings::register(cx);
5487 release_channel::init(SemanticVersion::default(), cx);
5488 EditorSettings::register(cx);
5489 prompt_store::init(cx)
5490 });
5491 }
5492
5493 #[gpui::test]
5494 async fn test_rewind_views(cx: &mut TestAppContext) {
5495 init_test(cx);
5496
5497 let fs = FakeFs::new(cx.executor());
5498 fs.insert_tree(
5499 "/project",
5500 json!({
5501 "test1.txt": "old content 1",
5502 "test2.txt": "old content 2"
5503 }),
5504 )
5505 .await;
5506 let project = Project::test(fs, [Path::new("/project")], cx).await;
5507 let (workspace, cx) =
5508 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5509
5510 let context_store =
5511 cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5512 let history_store =
5513 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5514
5515 let connection = Rc::new(StubAgentConnection::new());
5516 let thread_view = cx.update(|window, cx| {
5517 cx.new(|cx| {
5518 AcpThreadView::new(
5519 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
5520 None,
5521 None,
5522 workspace.downgrade(),
5523 project.clone(),
5524 history_store.clone(),
5525 None,
5526 window,
5527 cx,
5528 )
5529 })
5530 });
5531
5532 cx.run_until_parked();
5533
5534 let thread = thread_view
5535 .read_with(cx, |view, _| view.thread().cloned())
5536 .unwrap();
5537
5538 // First user message
5539 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5540 id: acp::ToolCallId("tool1".into()),
5541 title: "Edit file 1".into(),
5542 kind: acp::ToolKind::Edit,
5543 status: acp::ToolCallStatus::Completed,
5544 content: vec![acp::ToolCallContent::Diff {
5545 diff: acp::Diff {
5546 path: "/project/test1.txt".into(),
5547 old_text: Some("old content 1".into()),
5548 new_text: "new content 1".into(),
5549 },
5550 }],
5551 locations: vec![],
5552 raw_input: None,
5553 raw_output: None,
5554 })]);
5555
5556 thread
5557 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
5558 .await
5559 .unwrap();
5560 cx.run_until_parked();
5561
5562 thread.read_with(cx, |thread, _| {
5563 assert_eq!(thread.entries().len(), 2);
5564 });
5565
5566 thread_view.read_with(cx, |view, cx| {
5567 view.entry_view_state.read_with(cx, |entry_view_state, _| {
5568 assert!(
5569 entry_view_state
5570 .entry(0)
5571 .unwrap()
5572 .message_editor()
5573 .is_some()
5574 );
5575 assert!(entry_view_state.entry(1).unwrap().has_content());
5576 });
5577 });
5578
5579 // Second user message
5580 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5581 id: acp::ToolCallId("tool2".into()),
5582 title: "Edit file 2".into(),
5583 kind: acp::ToolKind::Edit,
5584 status: acp::ToolCallStatus::Completed,
5585 content: vec![acp::ToolCallContent::Diff {
5586 diff: acp::Diff {
5587 path: "/project/test2.txt".into(),
5588 old_text: Some("old content 2".into()),
5589 new_text: "new content 2".into(),
5590 },
5591 }],
5592 locations: vec![],
5593 raw_input: None,
5594 raw_output: None,
5595 })]);
5596
5597 thread
5598 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
5599 .await
5600 .unwrap();
5601 cx.run_until_parked();
5602
5603 let second_user_message_id = thread.read_with(cx, |thread, _| {
5604 assert_eq!(thread.entries().len(), 4);
5605 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
5606 panic!();
5607 };
5608 user_message.id.clone().unwrap()
5609 });
5610
5611 thread_view.read_with(cx, |view, cx| {
5612 view.entry_view_state.read_with(cx, |entry_view_state, _| {
5613 assert!(
5614 entry_view_state
5615 .entry(0)
5616 .unwrap()
5617 .message_editor()
5618 .is_some()
5619 );
5620 assert!(entry_view_state.entry(1).unwrap().has_content());
5621 assert!(
5622 entry_view_state
5623 .entry(2)
5624 .unwrap()
5625 .message_editor()
5626 .is_some()
5627 );
5628 assert!(entry_view_state.entry(3).unwrap().has_content());
5629 });
5630 });
5631
5632 // Rewind to first message
5633 thread
5634 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
5635 .await
5636 .unwrap();
5637
5638 cx.run_until_parked();
5639
5640 thread.read_with(cx, |thread, _| {
5641 assert_eq!(thread.entries().len(), 2);
5642 });
5643
5644 thread_view.read_with(cx, |view, cx| {
5645 view.entry_view_state.read_with(cx, |entry_view_state, _| {
5646 assert!(
5647 entry_view_state
5648 .entry(0)
5649 .unwrap()
5650 .message_editor()
5651 .is_some()
5652 );
5653 assert!(entry_view_state.entry(1).unwrap().has_content());
5654
5655 // Old views should be dropped
5656 assert!(entry_view_state.entry(2).is_none());
5657 assert!(entry_view_state.entry(3).is_none());
5658 });
5659 });
5660 }
5661
5662 #[gpui::test]
5663 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
5664 init_test(cx);
5665
5666 let connection = StubAgentConnection::new();
5667
5668 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5669 content: acp::ContentBlock::Text(acp::TextContent {
5670 text: "Response".into(),
5671 annotations: None,
5672 }),
5673 }]);
5674
5675 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5676 add_to_workspace(thread_view.clone(), cx);
5677
5678 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5679 message_editor.update_in(cx, |editor, window, cx| {
5680 editor.set_text("Original message to edit", window, cx);
5681 });
5682 thread_view.update_in(cx, |thread_view, window, cx| {
5683 thread_view.send(window, cx);
5684 });
5685
5686 cx.run_until_parked();
5687
5688 let user_message_editor = thread_view.read_with(cx, |view, cx| {
5689 assert_eq!(view.editing_message, None);
5690
5691 view.entry_view_state
5692 .read(cx)
5693 .entry(0)
5694 .unwrap()
5695 .message_editor()
5696 .unwrap()
5697 .clone()
5698 });
5699
5700 // Focus
5701 cx.focus(&user_message_editor);
5702 thread_view.read_with(cx, |view, _cx| {
5703 assert_eq!(view.editing_message, Some(0));
5704 });
5705
5706 // Edit
5707 user_message_editor.update_in(cx, |editor, window, cx| {
5708 editor.set_text("Edited message content", window, cx);
5709 });
5710
5711 // Cancel
5712 user_message_editor.update_in(cx, |_editor, window, cx| {
5713 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
5714 });
5715
5716 thread_view.read_with(cx, |view, _cx| {
5717 assert_eq!(view.editing_message, None);
5718 });
5719
5720 user_message_editor.read_with(cx, |editor, cx| {
5721 assert_eq!(editor.text(cx), "Original message to edit");
5722 });
5723 }
5724
5725 #[gpui::test]
5726 async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
5727 init_test(cx);
5728
5729 let connection = StubAgentConnection::new();
5730
5731 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5732 add_to_workspace(thread_view.clone(), cx);
5733
5734 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5735 let mut events = cx.events(&message_editor);
5736 message_editor.update_in(cx, |editor, window, cx| {
5737 editor.set_text("", window, cx);
5738 });
5739
5740 message_editor.update_in(cx, |_editor, window, cx| {
5741 window.dispatch_action(Box::new(Chat), cx);
5742 });
5743 cx.run_until_parked();
5744 // We shouldn't have received any messages
5745 assert!(matches!(
5746 events.try_next(),
5747 Err(futures::channel::mpsc::TryRecvError { .. })
5748 ));
5749 }
5750
5751 #[gpui::test]
5752 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
5753 init_test(cx);
5754
5755 let connection = StubAgentConnection::new();
5756
5757 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5758 content: acp::ContentBlock::Text(acp::TextContent {
5759 text: "Response".into(),
5760 annotations: None,
5761 }),
5762 }]);
5763
5764 let (thread_view, cx) =
5765 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5766 add_to_workspace(thread_view.clone(), cx);
5767
5768 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5769 message_editor.update_in(cx, |editor, window, cx| {
5770 editor.set_text("Original message to edit", window, cx);
5771 });
5772 thread_view.update_in(cx, |thread_view, window, cx| {
5773 thread_view.send(window, cx);
5774 });
5775
5776 cx.run_until_parked();
5777
5778 let user_message_editor = thread_view.read_with(cx, |view, cx| {
5779 assert_eq!(view.editing_message, None);
5780 assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
5781
5782 view.entry_view_state
5783 .read(cx)
5784 .entry(0)
5785 .unwrap()
5786 .message_editor()
5787 .unwrap()
5788 .clone()
5789 });
5790
5791 // Focus
5792 cx.focus(&user_message_editor);
5793
5794 // Edit
5795 user_message_editor.update_in(cx, |editor, window, cx| {
5796 editor.set_text("Edited message content", window, cx);
5797 });
5798
5799 // Send
5800 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5801 content: acp::ContentBlock::Text(acp::TextContent {
5802 text: "New Response".into(),
5803 annotations: None,
5804 }),
5805 }]);
5806
5807 user_message_editor.update_in(cx, |_editor, window, cx| {
5808 window.dispatch_action(Box::new(Chat), cx);
5809 });
5810
5811 cx.run_until_parked();
5812
5813 thread_view.read_with(cx, |view, cx| {
5814 assert_eq!(view.editing_message, None);
5815
5816 let entries = view.thread().unwrap().read(cx).entries();
5817 assert_eq!(entries.len(), 2);
5818 assert_eq!(
5819 entries[0].to_markdown(cx),
5820 "## User\n\nEdited message content\n\n"
5821 );
5822 assert_eq!(
5823 entries[1].to_markdown(cx),
5824 "## Assistant\n\nNew Response\n\n"
5825 );
5826
5827 let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
5828 assert!(!state.entry(1).unwrap().has_content());
5829 state.entry(0).unwrap().message_editor().unwrap().clone()
5830 });
5831
5832 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
5833 })
5834 }
5835
5836 #[gpui::test]
5837 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
5838 init_test(cx);
5839
5840 let connection = StubAgentConnection::new();
5841
5842 let (thread_view, cx) =
5843 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5844 add_to_workspace(thread_view.clone(), cx);
5845
5846 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5847 message_editor.update_in(cx, |editor, window, cx| {
5848 editor.set_text("Original message to edit", window, cx);
5849 });
5850 thread_view.update_in(cx, |thread_view, window, cx| {
5851 thread_view.send(window, cx);
5852 });
5853
5854 cx.run_until_parked();
5855
5856 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
5857 let thread = view.thread().unwrap().read(cx);
5858 assert_eq!(thread.entries().len(), 1);
5859
5860 let editor = view
5861 .entry_view_state
5862 .read(cx)
5863 .entry(0)
5864 .unwrap()
5865 .message_editor()
5866 .unwrap()
5867 .clone();
5868
5869 (editor, thread.session_id().clone())
5870 });
5871
5872 // Focus
5873 cx.focus(&user_message_editor);
5874
5875 thread_view.read_with(cx, |view, _cx| {
5876 assert_eq!(view.editing_message, Some(0));
5877 });
5878
5879 // Edit
5880 user_message_editor.update_in(cx, |editor, window, cx| {
5881 editor.set_text("Edited message content", window, cx);
5882 });
5883
5884 thread_view.read_with(cx, |view, _cx| {
5885 assert_eq!(view.editing_message, Some(0));
5886 });
5887
5888 // Finish streaming response
5889 cx.update(|_, cx| {
5890 connection.send_update(
5891 session_id.clone(),
5892 acp::SessionUpdate::AgentMessageChunk {
5893 content: acp::ContentBlock::Text(acp::TextContent {
5894 text: "Response".into(),
5895 annotations: None,
5896 }),
5897 },
5898 cx,
5899 );
5900 connection.end_turn(session_id, acp::StopReason::EndTurn);
5901 });
5902
5903 thread_view.read_with(cx, |view, _cx| {
5904 assert_eq!(view.editing_message, Some(0));
5905 });
5906
5907 cx.run_until_parked();
5908
5909 // Should still be editing
5910 cx.update(|window, cx| {
5911 assert!(user_message_editor.focus_handle(cx).is_focused(window));
5912 assert_eq!(thread_view.read(cx).editing_message, Some(0));
5913 assert_eq!(
5914 user_message_editor.read(cx).text(cx),
5915 "Edited message content"
5916 );
5917 });
5918 }
5919
5920 #[gpui::test]
5921 async fn test_interrupt(cx: &mut TestAppContext) {
5922 init_test(cx);
5923
5924 let connection = StubAgentConnection::new();
5925
5926 let (thread_view, cx) =
5927 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5928 add_to_workspace(thread_view.clone(), cx);
5929
5930 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5931 message_editor.update_in(cx, |editor, window, cx| {
5932 editor.set_text("Message 1", window, cx);
5933 });
5934 thread_view.update_in(cx, |thread_view, window, cx| {
5935 thread_view.send(window, cx);
5936 });
5937
5938 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
5939 let thread = view.thread().unwrap();
5940
5941 (thread.clone(), thread.read(cx).session_id().clone())
5942 });
5943
5944 cx.run_until_parked();
5945
5946 cx.update(|_, cx| {
5947 connection.send_update(
5948 session_id.clone(),
5949 acp::SessionUpdate::AgentMessageChunk {
5950 content: "Message 1 resp".into(),
5951 },
5952 cx,
5953 );
5954 });
5955
5956 cx.run_until_parked();
5957
5958 thread.read_with(cx, |thread, cx| {
5959 assert_eq!(
5960 thread.to_markdown(cx),
5961 indoc::indoc! {"
5962 ## User
5963
5964 Message 1
5965
5966 ## Assistant
5967
5968 Message 1 resp
5969
5970 "}
5971 )
5972 });
5973
5974 message_editor.update_in(cx, |editor, window, cx| {
5975 editor.set_text("Message 2", window, cx);
5976 });
5977 thread_view.update_in(cx, |thread_view, window, cx| {
5978 thread_view.send(window, cx);
5979 });
5980
5981 cx.update(|_, cx| {
5982 // Simulate a response sent after beginning to cancel
5983 connection.send_update(
5984 session_id.clone(),
5985 acp::SessionUpdate::AgentMessageChunk {
5986 content: "onse".into(),
5987 },
5988 cx,
5989 );
5990 });
5991
5992 cx.run_until_parked();
5993
5994 // Last Message 1 response should appear before Message 2
5995 thread.read_with(cx, |thread, cx| {
5996 assert_eq!(
5997 thread.to_markdown(cx),
5998 indoc::indoc! {"
5999 ## User
6000
6001 Message 1
6002
6003 ## Assistant
6004
6005 Message 1 response
6006
6007 ## User
6008
6009 Message 2
6010
6011 "}
6012 )
6013 });
6014
6015 cx.update(|_, cx| {
6016 connection.send_update(
6017 session_id.clone(),
6018 acp::SessionUpdate::AgentMessageChunk {
6019 content: "Message 2 response".into(),
6020 },
6021 cx,
6022 );
6023 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
6024 });
6025
6026 cx.run_until_parked();
6027
6028 thread.read_with(cx, |thread, cx| {
6029 assert_eq!(
6030 thread.to_markdown(cx),
6031 indoc::indoc! {"
6032 ## User
6033
6034 Message 1
6035
6036 ## Assistant
6037
6038 Message 1 response
6039
6040 ## User
6041
6042 Message 2
6043
6044 ## Assistant
6045
6046 Message 2 response
6047
6048 "}
6049 )
6050 });
6051 }
6052}