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