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