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