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