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