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