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