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
1629 && tool_call.content.is_empty()
1630 && self.as_native_connection(cx).is_some() =>
1631 {
1632 self.render_diff_loading(cx).into_any()
1633 }
1634 ToolCallStatus::Pending
1635 | ToolCallStatus::InProgress
1636 | ToolCallStatus::Completed
1637 | ToolCallStatus::Failed
1638 | ToolCallStatus::Canceled => v_flex()
1639 .w_full()
1640 .children(tool_call.content.iter().map(|content| {
1641 div().child(
1642 self.render_tool_call_content(entry_ix, content, tool_call, window, cx),
1643 )
1644 }))
1645 .into_any(),
1646 ToolCallStatus::Rejected => Empty.into_any(),
1647 }
1648 .into()
1649 } else {
1650 None
1651 };
1652
1653 v_flex()
1654 .when(use_card_layout, |this| {
1655 this.rounded_lg()
1656 .border_1()
1657 .border_color(self.tool_card_border_color(cx))
1658 .bg(cx.theme().colors().editor_background)
1659 .overflow_hidden()
1660 })
1661 .child(
1662 h_flex()
1663 .id(header_id)
1664 .w_full()
1665 .gap_1()
1666 .justify_between()
1667 .map(|this| {
1668 if use_card_layout {
1669 this.pl_2()
1670 .pr_1p5()
1671 .py_1()
1672 .rounded_t_md()
1673 .when(is_open, |this| {
1674 this.border_b_1()
1675 .border_color(self.tool_card_border_color(cx))
1676 })
1677 .bg(self.tool_card_header_bg(cx))
1678 } else {
1679 this.opacity(0.8).hover(|style| style.opacity(1.))
1680 }
1681 })
1682 .child(
1683 h_flex()
1684 .group(&card_header_id)
1685 .relative()
1686 .w_full()
1687 .min_h_6()
1688 .text_size(self.tool_name_font_size())
1689 .child(self.render_tool_call_icon(
1690 card_header_id,
1691 entry_ix,
1692 is_collapsible,
1693 is_open,
1694 tool_call,
1695 cx,
1696 ))
1697 .child(if tool_call.locations.len() == 1 {
1698 let name = tool_call.locations[0]
1699 .path
1700 .file_name()
1701 .unwrap_or_default()
1702 .display()
1703 .to_string();
1704
1705 h_flex()
1706 .id(("open-tool-call-location", entry_ix))
1707 .w_full()
1708 .max_w_full()
1709 .px_1p5()
1710 .rounded_sm()
1711 .overflow_x_scroll()
1712 .opacity(0.8)
1713 .hover(|label| {
1714 label.opacity(1.).bg(cx
1715 .theme()
1716 .colors()
1717 .element_hover
1718 .opacity(0.5))
1719 })
1720 .child(name)
1721 .tooltip(Tooltip::text("Jump to File"))
1722 .on_click(cx.listener(move |this, _, window, cx| {
1723 this.open_tool_call_location(entry_ix, 0, window, cx);
1724 }))
1725 .into_any_element()
1726 } else {
1727 h_flex()
1728 .id("non-card-label-container")
1729 .w_full()
1730 .relative()
1731 .ml_1p5()
1732 .overflow_hidden()
1733 .child(
1734 h_flex()
1735 .id("non-card-label")
1736 .pr_8()
1737 .w_full()
1738 .overflow_x_scroll()
1739 .child(self.render_markdown(
1740 tool_call.label.clone(),
1741 default_markdown_style(false, window, cx),
1742 )),
1743 )
1744 .child(gradient_overlay(gradient_color))
1745 .on_click(cx.listener({
1746 let id = tool_call.id.clone();
1747 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1748 if is_open {
1749 this.expanded_tool_calls.remove(&id);
1750 } else {
1751 this.expanded_tool_calls.insert(id.clone());
1752 }
1753 cx.notify();
1754 }
1755 }))
1756 .into_any()
1757 }),
1758 )
1759 .children(status_icon),
1760 )
1761 .children(tool_output_display)
1762 }
1763
1764 fn render_tool_call_content(
1765 &self,
1766 entry_ix: usize,
1767 content: &ToolCallContent,
1768 tool_call: &ToolCall,
1769 window: &Window,
1770 cx: &Context<Self>,
1771 ) -> AnyElement {
1772 match content {
1773 ToolCallContent::ContentBlock(content) => {
1774 if let Some(resource_link) = content.resource_link() {
1775 self.render_resource_link(resource_link, cx)
1776 } else if let Some(markdown) = content.markdown() {
1777 self.render_markdown_output(markdown.clone(), tool_call.id.clone(), window, cx)
1778 } else {
1779 Empty.into_any_element()
1780 }
1781 }
1782 ToolCallContent::Diff(diff) => self.render_diff_editor(entry_ix, diff, tool_call, cx),
1783 ToolCallContent::Terminal(terminal) => {
1784 self.render_terminal_tool_call(entry_ix, terminal, tool_call, window, cx)
1785 }
1786 }
1787 }
1788
1789 fn render_markdown_output(
1790 &self,
1791 markdown: Entity<Markdown>,
1792 tool_call_id: acp::ToolCallId,
1793 window: &Window,
1794 cx: &Context<Self>,
1795 ) -> AnyElement {
1796 let button_id = SharedString::from(format!("tool_output-{:?}", tool_call_id));
1797
1798 v_flex()
1799 .mt_1p5()
1800 .ml(px(7.))
1801 .px_3p5()
1802 .gap_2()
1803 .border_l_1()
1804 .border_color(self.tool_card_border_color(cx))
1805 .text_sm()
1806 .text_color(cx.theme().colors().text_muted)
1807 .child(self.render_markdown(markdown, default_markdown_style(false, window, cx)))
1808 .child(
1809 Button::new(button_id, "Collapse Output")
1810 .full_width()
1811 .style(ButtonStyle::Outlined)
1812 .label_size(LabelSize::Small)
1813 .icon(IconName::ChevronUp)
1814 .icon_color(Color::Muted)
1815 .icon_position(IconPosition::Start)
1816 .on_click(cx.listener({
1817 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1818 this.expanded_tool_calls.remove(&tool_call_id);
1819 cx.notify();
1820 }
1821 })),
1822 )
1823 .into_any_element()
1824 }
1825
1826 fn render_resource_link(
1827 &self,
1828 resource_link: &acp::ResourceLink,
1829 cx: &Context<Self>,
1830 ) -> AnyElement {
1831 let uri: SharedString = resource_link.uri.clone().into();
1832
1833 let label: SharedString = if let Some(path) = resource_link.uri.strip_prefix("file://") {
1834 path.to_string().into()
1835 } else {
1836 uri.clone()
1837 };
1838
1839 let button_id = SharedString::from(format!("item-{}", uri));
1840
1841 div()
1842 .ml(px(7.))
1843 .pl_2p5()
1844 .border_l_1()
1845 .border_color(self.tool_card_border_color(cx))
1846 .overflow_hidden()
1847 .child(
1848 Button::new(button_id, label)
1849 .label_size(LabelSize::Small)
1850 .color(Color::Muted)
1851 .icon(IconName::ArrowUpRight)
1852 .icon_size(IconSize::XSmall)
1853 .icon_color(Color::Muted)
1854 .truncate(true)
1855 .on_click(cx.listener({
1856 let workspace = self.workspace.clone();
1857 move |_, _, window, cx: &mut Context<Self>| {
1858 Self::open_link(uri.clone(), &workspace, window, cx);
1859 }
1860 })),
1861 )
1862 .into_any_element()
1863 }
1864
1865 fn render_permission_buttons(
1866 &self,
1867 options: &[acp::PermissionOption],
1868 entry_ix: usize,
1869 tool_call_id: acp::ToolCallId,
1870 empty_content: bool,
1871 cx: &Context<Self>,
1872 ) -> Div {
1873 h_flex()
1874 .py_1()
1875 .pl_2()
1876 .pr_1()
1877 .gap_1()
1878 .justify_between()
1879 .flex_wrap()
1880 .when(!empty_content, |this| {
1881 this.border_t_1()
1882 .border_color(self.tool_card_border_color(cx))
1883 })
1884 .child(
1885 div()
1886 .min_w(rems_from_px(145.))
1887 .child(LoadingLabel::new("Waiting for Confirmation").size(LabelSize::Small)),
1888 )
1889 .child(h_flex().gap_0p5().children(options.iter().map(|option| {
1890 let option_id = SharedString::from(option.id.0.clone());
1891 Button::new((option_id, entry_ix), option.name.clone())
1892 .map(|this| match option.kind {
1893 acp::PermissionOptionKind::AllowOnce => {
1894 this.icon(IconName::Check).icon_color(Color::Success)
1895 }
1896 acp::PermissionOptionKind::AllowAlways => {
1897 this.icon(IconName::CheckDouble).icon_color(Color::Success)
1898 }
1899 acp::PermissionOptionKind::RejectOnce => {
1900 this.icon(IconName::Close).icon_color(Color::Error)
1901 }
1902 acp::PermissionOptionKind::RejectAlways => {
1903 this.icon(IconName::Close).icon_color(Color::Error)
1904 }
1905 })
1906 .icon_position(IconPosition::Start)
1907 .icon_size(IconSize::XSmall)
1908 .label_size(LabelSize::Small)
1909 .on_click(cx.listener({
1910 let tool_call_id = tool_call_id.clone();
1911 let option_id = option.id.clone();
1912 let option_kind = option.kind;
1913 move |this, _, _, cx| {
1914 this.authorize_tool_call(
1915 tool_call_id.clone(),
1916 option_id.clone(),
1917 option_kind,
1918 cx,
1919 );
1920 }
1921 }))
1922 })))
1923 }
1924
1925 fn render_diff_loading(&self, cx: &Context<Self>) -> AnyElement {
1926 let bar = |n: u64, width_class: &str| {
1927 let bg_color = cx.theme().colors().element_active;
1928 let base = h_flex().h_1().rounded_full();
1929
1930 let modified = match width_class {
1931 "w_4_5" => base.w_3_4(),
1932 "w_1_4" => base.w_1_4(),
1933 "w_2_4" => base.w_2_4(),
1934 "w_3_5" => base.w_3_5(),
1935 "w_2_5" => base.w_2_5(),
1936 _ => base.w_1_2(),
1937 };
1938
1939 modified.with_animation(
1940 ElementId::Integer(n),
1941 Animation::new(Duration::from_secs(2)).repeat(),
1942 move |tab, delta| {
1943 let delta = (delta - 0.15 * n as f32) / 0.7;
1944 let delta = 1.0 - (0.5 - delta).abs() * 2.;
1945 let delta = ease_in_out(delta.clamp(0., 1.));
1946 let delta = 0.1 + 0.9 * delta;
1947
1948 tab.bg(bg_color.opacity(delta))
1949 },
1950 )
1951 };
1952
1953 v_flex()
1954 .p_3()
1955 .gap_1()
1956 .rounded_b_md()
1957 .bg(cx.theme().colors().editor_background)
1958 .child(bar(0, "w_4_5"))
1959 .child(bar(1, "w_1_4"))
1960 .child(bar(2, "w_2_4"))
1961 .child(bar(3, "w_3_5"))
1962 .child(bar(4, "w_2_5"))
1963 .into_any_element()
1964 }
1965
1966 fn render_diff_editor(
1967 &self,
1968 entry_ix: usize,
1969 diff: &Entity<acp_thread::Diff>,
1970 tool_call: &ToolCall,
1971 cx: &Context<Self>,
1972 ) -> AnyElement {
1973 let tool_progress = matches!(
1974 &tool_call.status,
1975 ToolCallStatus::InProgress | ToolCallStatus::Pending
1976 );
1977
1978 v_flex()
1979 .h_full()
1980 .child(
1981 if let Some(entry) = self.entry_view_state.read(cx).entry(entry_ix)
1982 && let Some(editor) = entry.editor_for_diff(diff)
1983 && diff.read(cx).has_revealed_range(cx)
1984 {
1985 editor.into_any_element()
1986 } else if tool_progress && self.as_native_connection(cx).is_some() {
1987 self.render_diff_loading(cx)
1988 } else {
1989 Empty.into_any()
1990 },
1991 )
1992 .into_any()
1993 }
1994
1995 fn render_terminal_tool_call(
1996 &self,
1997 entry_ix: usize,
1998 terminal: &Entity<acp_thread::Terminal>,
1999 tool_call: &ToolCall,
2000 window: &Window,
2001 cx: &Context<Self>,
2002 ) -> AnyElement {
2003 let terminal_data = terminal.read(cx);
2004 let working_dir = terminal_data.working_dir();
2005 let command = terminal_data.command();
2006 let started_at = terminal_data.started_at();
2007
2008 let tool_failed = matches!(
2009 &tool_call.status,
2010 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed
2011 );
2012
2013 let output = terminal_data.output();
2014 let command_finished = output.is_some();
2015 let truncated_output = output.is_some_and(|output| output.was_content_truncated);
2016 let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
2017
2018 let command_failed = command_finished
2019 && output.is_some_and(|o| o.exit_status.is_none_or(|status| !status.success()));
2020
2021 let time_elapsed = if let Some(output) = output {
2022 output.ended_at.duration_since(started_at)
2023 } else {
2024 started_at.elapsed()
2025 };
2026
2027 let header_bg = cx
2028 .theme()
2029 .colors()
2030 .element_background
2031 .blend(cx.theme().colors().editor_foreground.opacity(0.025));
2032 let border_color = cx.theme().colors().border.opacity(0.6);
2033
2034 let working_dir = working_dir
2035 .as_ref()
2036 .map(|path| format!("{}", path.display()))
2037 .unwrap_or_else(|| "current directory".to_string());
2038
2039 let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
2040
2041 let header = h_flex()
2042 .id(SharedString::from(format!(
2043 "terminal-tool-header-{}",
2044 terminal.entity_id()
2045 )))
2046 .flex_none()
2047 .gap_1()
2048 .justify_between()
2049 .rounded_t_md()
2050 .child(
2051 div()
2052 .id(("command-target-path", terminal.entity_id()))
2053 .w_full()
2054 .max_w_full()
2055 .overflow_x_scroll()
2056 .child(
2057 Label::new(working_dir)
2058 .buffer_font(cx)
2059 .size(LabelSize::XSmall)
2060 .color(Color::Muted),
2061 ),
2062 )
2063 .when(!command_finished, |header| {
2064 header
2065 .gap_1p5()
2066 .child(
2067 Button::new(
2068 SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
2069 "Stop",
2070 )
2071 .icon(IconName::Stop)
2072 .icon_position(IconPosition::Start)
2073 .icon_size(IconSize::Small)
2074 .icon_color(Color::Error)
2075 .label_size(LabelSize::Small)
2076 .tooltip(move |window, cx| {
2077 Tooltip::with_meta(
2078 "Stop This Command",
2079 None,
2080 "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
2081 window,
2082 cx,
2083 )
2084 })
2085 .on_click({
2086 let terminal = terminal.clone();
2087 cx.listener(move |_this, _event, _window, cx| {
2088 let inner_terminal = terminal.read(cx).inner().clone();
2089 inner_terminal.update(cx, |inner_terminal, _cx| {
2090 inner_terminal.kill_active_task();
2091 });
2092 })
2093 }),
2094 )
2095 .child(Divider::vertical())
2096 .child(
2097 Icon::new(IconName::ArrowCircle)
2098 .size(IconSize::XSmall)
2099 .color(Color::Info)
2100 .with_animation(
2101 "arrow-circle",
2102 Animation::new(Duration::from_secs(2)).repeat(),
2103 |icon, delta| {
2104 icon.transform(Transformation::rotate(percentage(delta)))
2105 },
2106 ),
2107 )
2108 })
2109 .when(tool_failed || command_failed, |header| {
2110 header.child(
2111 div()
2112 .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
2113 .child(
2114 Icon::new(IconName::Close)
2115 .size(IconSize::Small)
2116 .color(Color::Error),
2117 )
2118 .when_some(output.and_then(|o| o.exit_status), |this, status| {
2119 this.tooltip(Tooltip::text(format!(
2120 "Exited with code {}",
2121 status.code().unwrap_or(-1),
2122 )))
2123 }),
2124 )
2125 })
2126 .when(truncated_output, |header| {
2127 let tooltip = if let Some(output) = output {
2128 if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
2129 "Output exceeded terminal max lines and was \
2130 truncated, the model received the first 16 KB."
2131 .to_string()
2132 } else {
2133 format!(
2134 "Output is {} long—to avoid unexpected token usage, \
2135 only 16 KB was sent back to the model.",
2136 format_file_size(output.original_content_len as u64, true),
2137 )
2138 }
2139 } else {
2140 "Output was truncated".to_string()
2141 };
2142
2143 header.child(
2144 h_flex()
2145 .id(("terminal-tool-truncated-label", terminal.entity_id()))
2146 .gap_1()
2147 .child(
2148 Icon::new(IconName::Info)
2149 .size(IconSize::XSmall)
2150 .color(Color::Ignored),
2151 )
2152 .child(
2153 Label::new("Truncated")
2154 .color(Color::Muted)
2155 .size(LabelSize::XSmall),
2156 )
2157 .tooltip(Tooltip::text(tooltip)),
2158 )
2159 })
2160 .when(time_elapsed > Duration::from_secs(10), |header| {
2161 header.child(
2162 Label::new(format!("({})", duration_alt_display(time_elapsed)))
2163 .buffer_font(cx)
2164 .color(Color::Muted)
2165 .size(LabelSize::XSmall),
2166 )
2167 })
2168 .child(
2169 Disclosure::new(
2170 SharedString::from(format!(
2171 "terminal-tool-disclosure-{}",
2172 terminal.entity_id()
2173 )),
2174 is_expanded,
2175 )
2176 .opened_icon(IconName::ChevronUp)
2177 .closed_icon(IconName::ChevronDown)
2178 .on_click(cx.listener({
2179 let id = tool_call.id.clone();
2180 move |this, _event, _window, _cx| {
2181 if is_expanded {
2182 this.expanded_tool_calls.remove(&id);
2183 } else {
2184 this.expanded_tool_calls.insert(id.clone());
2185 }
2186 }
2187 })),
2188 );
2189
2190 let terminal_view = self
2191 .entry_view_state
2192 .read(cx)
2193 .entry(entry_ix)
2194 .and_then(|entry| entry.terminal(terminal));
2195 let show_output = is_expanded && terminal_view.is_some();
2196
2197 v_flex()
2198 .mb_2()
2199 .border_1()
2200 .when(tool_failed || command_failed, |card| card.border_dashed())
2201 .border_color(border_color)
2202 .rounded_lg()
2203 .overflow_hidden()
2204 .child(
2205 v_flex()
2206 .py_1p5()
2207 .pl_2()
2208 .pr_1p5()
2209 .gap_0p5()
2210 .bg(header_bg)
2211 .text_xs()
2212 .child(header)
2213 .child(
2214 MarkdownElement::new(
2215 command.clone(),
2216 terminal_command_markdown_style(window, cx),
2217 )
2218 .code_block_renderer(
2219 markdown::CodeBlockRenderer::Default {
2220 copy_button: false,
2221 copy_button_on_hover: true,
2222 border: false,
2223 },
2224 ),
2225 ),
2226 )
2227 .when(show_output, |this| {
2228 this.child(
2229 div()
2230 .pt_2()
2231 .border_t_1()
2232 .when(tool_failed || command_failed, |card| card.border_dashed())
2233 .border_color(border_color)
2234 .bg(cx.theme().colors().editor_background)
2235 .rounded_b_md()
2236 .text_ui_sm(cx)
2237 .children(terminal_view.clone()),
2238 )
2239 })
2240 .into_any()
2241 }
2242
2243 fn render_agent_logo(&self) -> AnyElement {
2244 Icon::new(self.agent.logo())
2245 .color(Color::Muted)
2246 .size(IconSize::XLarge)
2247 .into_any_element()
2248 }
2249
2250 fn render_error_agent_logo(&self) -> AnyElement {
2251 let logo = Icon::new(self.agent.logo())
2252 .color(Color::Muted)
2253 .size(IconSize::XLarge)
2254 .into_any_element();
2255
2256 h_flex()
2257 .relative()
2258 .justify_center()
2259 .child(div().opacity(0.3).child(logo))
2260 .child(
2261 h_flex()
2262 .absolute()
2263 .right_1()
2264 .bottom_0()
2265 .child(Icon::new(IconName::XCircleFilled).color(Color::Error)),
2266 )
2267 .into_any_element()
2268 }
2269
2270 fn render_rules_item(&self, cx: &Context<Self>) -> Option<AnyElement> {
2271 let project_context = self
2272 .as_native_thread(cx)?
2273 .read(cx)
2274 .project_context()
2275 .read(cx);
2276
2277 let user_rules_text = if project_context.user_rules.is_empty() {
2278 None
2279 } else if project_context.user_rules.len() == 1 {
2280 let user_rules = &project_context.user_rules[0];
2281
2282 match user_rules.title.as_ref() {
2283 Some(title) => Some(format!("Using \"{title}\" user rule")),
2284 None => Some("Using user rule".into()),
2285 }
2286 } else {
2287 Some(format!(
2288 "Using {} user rules",
2289 project_context.user_rules.len()
2290 ))
2291 };
2292
2293 let first_user_rules_id = project_context
2294 .user_rules
2295 .first()
2296 .map(|user_rules| user_rules.uuid.0);
2297
2298 let rules_files = project_context
2299 .worktrees
2300 .iter()
2301 .filter_map(|worktree| worktree.rules_file.as_ref())
2302 .collect::<Vec<_>>();
2303
2304 let rules_file_text = match rules_files.as_slice() {
2305 &[] => None,
2306 &[rules_file] => Some(format!(
2307 "Using project {:?} file",
2308 rules_file.path_in_worktree
2309 )),
2310 rules_files => Some(format!("Using {} project rules files", rules_files.len())),
2311 };
2312
2313 if user_rules_text.is_none() && rules_file_text.is_none() {
2314 return None;
2315 }
2316
2317 Some(
2318 v_flex()
2319 .px_2p5()
2320 .gap_1()
2321 .when_some(user_rules_text, |parent, user_rules_text| {
2322 parent.child(
2323 h_flex()
2324 .group("user-rules")
2325 .id("user-rules")
2326 .w_full()
2327 .child(
2328 Icon::new(IconName::Reader)
2329 .size(IconSize::XSmall)
2330 .color(Color::Disabled),
2331 )
2332 .child(
2333 Label::new(user_rules_text)
2334 .size(LabelSize::XSmall)
2335 .color(Color::Muted)
2336 .truncate()
2337 .buffer_font(cx)
2338 .ml_1p5()
2339 .mr_0p5(),
2340 )
2341 .child(
2342 IconButton::new("open-prompt-library", IconName::ArrowUpRight)
2343 .shape(ui::IconButtonShape::Square)
2344 .icon_size(IconSize::XSmall)
2345 .icon_color(Color::Ignored)
2346 .visible_on_hover("user-rules")
2347 // TODO: Figure out a way to pass focus handle here so we can display the `OpenRulesLibrary` keybinding
2348 .tooltip(Tooltip::text("View User Rules")),
2349 )
2350 .on_click(move |_event, window, cx| {
2351 window.dispatch_action(
2352 Box::new(OpenRulesLibrary {
2353 prompt_to_select: first_user_rules_id,
2354 }),
2355 cx,
2356 )
2357 }),
2358 )
2359 })
2360 .when_some(rules_file_text, |parent, rules_file_text| {
2361 parent.child(
2362 h_flex()
2363 .group("project-rules")
2364 .id("project-rules")
2365 .w_full()
2366 .child(
2367 Icon::new(IconName::Reader)
2368 .size(IconSize::XSmall)
2369 .color(Color::Disabled),
2370 )
2371 .child(
2372 Label::new(rules_file_text)
2373 .size(LabelSize::XSmall)
2374 .color(Color::Muted)
2375 .buffer_font(cx)
2376 .ml_1p5()
2377 .mr_0p5(),
2378 )
2379 .child(
2380 IconButton::new("open-rule", IconName::ArrowUpRight)
2381 .shape(ui::IconButtonShape::Square)
2382 .icon_size(IconSize::XSmall)
2383 .icon_color(Color::Ignored)
2384 .visible_on_hover("project-rules")
2385 .tooltip(Tooltip::text("View Project Rules")),
2386 )
2387 .on_click(cx.listener(Self::handle_open_rules)),
2388 )
2389 })
2390 .into_any(),
2391 )
2392 }
2393
2394 fn render_empty_state_section_header(
2395 &self,
2396 label: impl Into<SharedString>,
2397 action_slot: Option<AnyElement>,
2398 cx: &mut Context<Self>,
2399 ) -> impl IntoElement {
2400 div().pl_1().pr_1p5().child(
2401 h_flex()
2402 .mt_2()
2403 .pl_1p5()
2404 .pb_1()
2405 .w_full()
2406 .justify_between()
2407 .border_b_1()
2408 .border_color(cx.theme().colors().border_variant)
2409 .child(
2410 Label::new(label.into())
2411 .size(LabelSize::Small)
2412 .color(Color::Muted),
2413 )
2414 .children(action_slot),
2415 )
2416 }
2417
2418 fn render_empty_state(&self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
2419 let loading = matches!(&self.thread_state, ThreadState::Loading { .. });
2420 let render_history = self
2421 .agent
2422 .clone()
2423 .downcast::<agent2::NativeAgentServer>()
2424 .is_some()
2425 && self
2426 .history_store
2427 .update(cx, |history_store, cx| !history_store.is_empty(cx));
2428
2429 v_flex()
2430 .size_full()
2431 .when(!render_history, |this| {
2432 this.child(
2433 v_flex()
2434 .size_full()
2435 .items_center()
2436 .justify_center()
2437 .child(if loading {
2438 h_flex()
2439 .justify_center()
2440 .child(self.render_agent_logo())
2441 .with_animation(
2442 "pulsating_icon",
2443 Animation::new(Duration::from_secs(2))
2444 .repeat()
2445 .with_easing(pulsating_between(0.4, 1.0)),
2446 |icon, delta| icon.opacity(delta),
2447 )
2448 .into_any()
2449 } else {
2450 self.render_agent_logo().into_any_element()
2451 })
2452 .child(h_flex().mt_4().mb_2().justify_center().child(if loading {
2453 div()
2454 .child(LoadingLabel::new("").size(LabelSize::Large))
2455 .into_any_element()
2456 } else {
2457 Headline::new(self.agent.empty_state_headline())
2458 .size(HeadlineSize::Medium)
2459 .into_any_element()
2460 })),
2461 )
2462 })
2463 .when(render_history, |this| {
2464 let recent_history = self
2465 .history_store
2466 .update(cx, |history_store, cx| history_store.recent_entries(3, cx));
2467 this.justify_end().child(
2468 v_flex()
2469 .child(
2470 self.render_empty_state_section_header(
2471 "Recent",
2472 Some(
2473 Button::new("view-history", "View All")
2474 .style(ButtonStyle::Subtle)
2475 .label_size(LabelSize::Small)
2476 .key_binding(
2477 KeyBinding::for_action_in(
2478 &OpenHistory,
2479 &self.focus_handle(cx),
2480 window,
2481 cx,
2482 )
2483 .map(|kb| kb.size(rems_from_px(12.))),
2484 )
2485 .on_click(move |_event, window, cx| {
2486 window.dispatch_action(OpenHistory.boxed_clone(), cx);
2487 })
2488 .into_any_element(),
2489 ),
2490 cx,
2491 ),
2492 )
2493 .child(
2494 v_flex().p_1().pr_1p5().gap_1().children(
2495 recent_history
2496 .into_iter()
2497 .enumerate()
2498 .map(|(index, entry)| {
2499 // TODO: Add keyboard navigation.
2500 let is_hovered =
2501 self.hovered_recent_history_item == Some(index);
2502 crate::acp::thread_history::AcpHistoryEntryElement::new(
2503 entry,
2504 cx.entity().downgrade(),
2505 )
2506 .hovered(is_hovered)
2507 .on_hover(cx.listener(
2508 move |this, is_hovered, _window, cx| {
2509 if *is_hovered {
2510 this.hovered_recent_history_item = Some(index);
2511 } else if this.hovered_recent_history_item
2512 == Some(index)
2513 {
2514 this.hovered_recent_history_item = None;
2515 }
2516 cx.notify();
2517 },
2518 ))
2519 .into_any_element()
2520 }),
2521 ),
2522 ),
2523 )
2524 })
2525 .into_any()
2526 }
2527
2528 fn render_auth_required_state(
2529 &self,
2530 connection: &Rc<dyn AgentConnection>,
2531 description: Option<&Entity<Markdown>>,
2532 configuration_view: Option<&AnyView>,
2533 pending_auth_method: Option<&acp::AuthMethodId>,
2534 window: &mut Window,
2535 cx: &Context<Self>,
2536 ) -> Div {
2537 v_flex()
2538 .p_2()
2539 .gap_2()
2540 .flex_1()
2541 .items_center()
2542 .justify_center()
2543 .child(
2544 v_flex()
2545 .items_center()
2546 .justify_center()
2547 .child(self.render_error_agent_logo())
2548 .child(
2549 h_flex().mt_4().mb_1().justify_center().child(
2550 Headline::new("Authentication Required").size(HeadlineSize::Medium),
2551 ),
2552 )
2553 .into_any(),
2554 )
2555 .children(description.map(|desc| {
2556 div().text_ui(cx).text_center().child(
2557 self.render_markdown(desc.clone(), default_markdown_style(false, window, cx)),
2558 )
2559 }))
2560 .children(
2561 configuration_view
2562 .cloned()
2563 .map(|view| div().px_4().w_full().max_w_128().child(view)),
2564 )
2565 .when(
2566 configuration_view.is_none()
2567 && description.is_none()
2568 && pending_auth_method.is_none(),
2569 |el| {
2570 el.child(
2571 div()
2572 .text_ui(cx)
2573 .text_center()
2574 .px_4()
2575 .w_full()
2576 .max_w_128()
2577 .child(Label::new("Authentication required")),
2578 )
2579 },
2580 )
2581 .when_some(pending_auth_method, |el, _| {
2582 let spinner_icon = div()
2583 .px_0p5()
2584 .id("generating")
2585 .tooltip(Tooltip::text("Generating Changes…"))
2586 .child(
2587 Icon::new(IconName::ArrowCircle)
2588 .size(IconSize::Small)
2589 .with_animation(
2590 "arrow-circle",
2591 Animation::new(Duration::from_secs(2)).repeat(),
2592 |icon, delta| {
2593 icon.transform(Transformation::rotate(percentage(delta)))
2594 },
2595 )
2596 .into_any_element(),
2597 )
2598 .into_any();
2599 el.child(
2600 h_flex()
2601 .text_ui(cx)
2602 .text_center()
2603 .justify_center()
2604 .gap_2()
2605 .px_4()
2606 .w_full()
2607 .max_w_128()
2608 .child(Label::new("Authenticating..."))
2609 .child(spinner_icon),
2610 )
2611 })
2612 .child(
2613 h_flex()
2614 .mt_1p5()
2615 .gap_1()
2616 .flex_wrap()
2617 .justify_center()
2618 .children(connection.auth_methods().iter().enumerate().rev().map(
2619 |(ix, method)| {
2620 Button::new(
2621 SharedString::from(method.id.0.clone()),
2622 method.name.clone(),
2623 )
2624 .style(ButtonStyle::Outlined)
2625 .when(ix == 0, |el| {
2626 el.style(ButtonStyle::Tinted(ui::TintColor::Accent))
2627 })
2628 .size(ButtonSize::Medium)
2629 .label_size(LabelSize::Small)
2630 .on_click({
2631 let method_id = method.id.clone();
2632 cx.listener(move |this, _, window, cx| {
2633 this.authenticate(method_id.clone(), window, cx)
2634 })
2635 })
2636 },
2637 )),
2638 )
2639 }
2640
2641 fn render_load_error(&self, e: &LoadError, cx: &Context<Self>) -> AnyElement {
2642 let mut container = v_flex()
2643 .items_center()
2644 .justify_center()
2645 .child(self.render_error_agent_logo())
2646 .child(
2647 v_flex()
2648 .mt_4()
2649 .mb_2()
2650 .gap_0p5()
2651 .text_center()
2652 .items_center()
2653 .child(Headline::new("Failed to launch").size(HeadlineSize::Medium))
2654 .child(
2655 Label::new(e.to_string())
2656 .size(LabelSize::Small)
2657 .color(Color::Muted),
2658 ),
2659 );
2660
2661 if let LoadError::Unsupported {
2662 upgrade_message,
2663 upgrade_command,
2664 ..
2665 } = &e
2666 {
2667 let upgrade_message = upgrade_message.clone();
2668 let upgrade_command = upgrade_command.clone();
2669 container = container.child(
2670 Button::new("upgrade", upgrade_message)
2671 .tooltip(Tooltip::text(upgrade_command.clone()))
2672 .on_click(cx.listener(move |this, _, window, cx| {
2673 let task = this
2674 .workspace
2675 .update(cx, |workspace, cx| {
2676 let project = workspace.project().read(cx);
2677 let cwd = project.first_project_directory(cx);
2678 let shell = project.terminal_settings(&cwd, cx).shell.clone();
2679 let spawn_in_terminal = task::SpawnInTerminal {
2680 id: task::TaskId("upgrade".to_string()),
2681 full_label: upgrade_command.clone(),
2682 label: upgrade_command.clone(),
2683 command: Some(upgrade_command.clone()),
2684 args: Vec::new(),
2685 command_label: upgrade_command.clone(),
2686 cwd,
2687 env: Default::default(),
2688 use_new_terminal: true,
2689 allow_concurrent_runs: true,
2690 reveal: Default::default(),
2691 reveal_target: Default::default(),
2692 hide: Default::default(),
2693 shell,
2694 show_summary: true,
2695 show_command: true,
2696 show_rerun: false,
2697 };
2698 workspace.spawn_in_terminal(spawn_in_terminal, window, cx)
2699 })
2700 .ok();
2701 let Some(task) = task else { return };
2702 cx.spawn_in(window, async move |this, cx| {
2703 if let Some(Ok(_)) = task.await {
2704 this.update_in(cx, |this, window, cx| {
2705 this.reset(window, cx);
2706 })
2707 .ok();
2708 }
2709 })
2710 .detach()
2711 })),
2712 );
2713 } else if let LoadError::NotInstalled {
2714 install_message,
2715 install_command,
2716 ..
2717 } = e
2718 {
2719 let install_message = install_message.clone();
2720 let install_command = install_command.clone();
2721 container = container.child(
2722 Button::new("install", install_message)
2723 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
2724 .size(ButtonSize::Medium)
2725 .tooltip(Tooltip::text(install_command.clone()))
2726 .on_click(cx.listener(move |this, _, window, cx| {
2727 let task = this
2728 .workspace
2729 .update(cx, |workspace, cx| {
2730 let project = workspace.project().read(cx);
2731 let cwd = project.first_project_directory(cx);
2732 let shell = project.terminal_settings(&cwd, cx).shell.clone();
2733 let spawn_in_terminal = task::SpawnInTerminal {
2734 id: task::TaskId("install".to_string()),
2735 full_label: install_command.clone(),
2736 label: install_command.clone(),
2737 command: Some(install_command.clone()),
2738 args: Vec::new(),
2739 command_label: install_command.clone(),
2740 cwd,
2741 env: Default::default(),
2742 use_new_terminal: true,
2743 allow_concurrent_runs: true,
2744 reveal: Default::default(),
2745 reveal_target: Default::default(),
2746 hide: Default::default(),
2747 shell,
2748 show_summary: true,
2749 show_command: true,
2750 show_rerun: false,
2751 };
2752 workspace.spawn_in_terminal(spawn_in_terminal, window, cx)
2753 })
2754 .ok();
2755 let Some(task) = task else { return };
2756 cx.spawn_in(window, async move |this, cx| {
2757 if let Some(Ok(_)) = task.await {
2758 this.update_in(cx, |this, window, cx| {
2759 this.reset(window, cx);
2760 })
2761 .ok();
2762 }
2763 })
2764 .detach()
2765 })),
2766 );
2767 }
2768
2769 container.into_any()
2770 }
2771
2772 fn render_activity_bar(
2773 &self,
2774 thread_entity: &Entity<AcpThread>,
2775 window: &mut Window,
2776 cx: &Context<Self>,
2777 ) -> Option<AnyElement> {
2778 let thread = thread_entity.read(cx);
2779 let action_log = thread.action_log();
2780 let changed_buffers = action_log.read(cx).changed_buffers(cx);
2781 let plan = thread.plan();
2782
2783 if changed_buffers.is_empty() && plan.is_empty() {
2784 return None;
2785 }
2786
2787 let editor_bg_color = cx.theme().colors().editor_background;
2788 let active_color = cx.theme().colors().element_selected;
2789 let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
2790
2791 let pending_edits = thread.has_pending_edit_tool_calls();
2792
2793 v_flex()
2794 .mt_1()
2795 .mx_2()
2796 .bg(bg_edit_files_disclosure)
2797 .border_1()
2798 .border_b_0()
2799 .border_color(cx.theme().colors().border)
2800 .rounded_t_md()
2801 .shadow(vec![gpui::BoxShadow {
2802 color: gpui::black().opacity(0.15),
2803 offset: point(px(1.), px(-1.)),
2804 blur_radius: px(3.),
2805 spread_radius: px(0.),
2806 }])
2807 .when(!plan.is_empty(), |this| {
2808 this.child(self.render_plan_summary(plan, window, cx))
2809 .when(self.plan_expanded, |parent| {
2810 parent.child(self.render_plan_entries(plan, window, cx))
2811 })
2812 })
2813 .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
2814 this.child(Divider::horizontal().color(DividerColor::Border))
2815 })
2816 .when(!changed_buffers.is_empty(), |this| {
2817 this.child(self.render_edits_summary(
2818 &changed_buffers,
2819 self.edits_expanded,
2820 pending_edits,
2821 window,
2822 cx,
2823 ))
2824 .when(self.edits_expanded, |parent| {
2825 parent.child(self.render_edited_files(
2826 action_log,
2827 &changed_buffers,
2828 pending_edits,
2829 cx,
2830 ))
2831 })
2832 })
2833 .into_any()
2834 .into()
2835 }
2836
2837 fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
2838 let stats = plan.stats();
2839
2840 let title = if let Some(entry) = stats.in_progress_entry
2841 && !self.plan_expanded
2842 {
2843 h_flex()
2844 .w_full()
2845 .cursor_default()
2846 .gap_1()
2847 .text_xs()
2848 .text_color(cx.theme().colors().text_muted)
2849 .justify_between()
2850 .child(
2851 h_flex()
2852 .gap_1()
2853 .child(
2854 Label::new("Current:")
2855 .size(LabelSize::Small)
2856 .color(Color::Muted),
2857 )
2858 .child(MarkdownElement::new(
2859 entry.content.clone(),
2860 plan_label_markdown_style(&entry.status, window, cx),
2861 )),
2862 )
2863 .when(stats.pending > 0, |this| {
2864 this.child(
2865 Label::new(format!("{} left", stats.pending))
2866 .size(LabelSize::Small)
2867 .color(Color::Muted)
2868 .mr_1(),
2869 )
2870 })
2871 } else {
2872 let status_label = if stats.pending == 0 {
2873 "All Done".to_string()
2874 } else if stats.completed == 0 {
2875 format!("{} Tasks", plan.entries.len())
2876 } else {
2877 format!("{}/{}", stats.completed, plan.entries.len())
2878 };
2879
2880 h_flex()
2881 .w_full()
2882 .gap_1()
2883 .justify_between()
2884 .child(
2885 Label::new("Plan")
2886 .size(LabelSize::Small)
2887 .color(Color::Muted),
2888 )
2889 .child(
2890 Label::new(status_label)
2891 .size(LabelSize::Small)
2892 .color(Color::Muted)
2893 .mr_1(),
2894 )
2895 };
2896
2897 h_flex()
2898 .p_1()
2899 .justify_between()
2900 .when(self.plan_expanded, |this| {
2901 this.border_b_1().border_color(cx.theme().colors().border)
2902 })
2903 .child(
2904 h_flex()
2905 .id("plan_summary")
2906 .w_full()
2907 .gap_1()
2908 .child(Disclosure::new("plan_disclosure", self.plan_expanded))
2909 .child(title)
2910 .on_click(cx.listener(|this, _, _, cx| {
2911 this.plan_expanded = !this.plan_expanded;
2912 cx.notify();
2913 })),
2914 )
2915 }
2916
2917 fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
2918 v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
2919 let element = h_flex()
2920 .py_1()
2921 .px_2()
2922 .gap_2()
2923 .justify_between()
2924 .bg(cx.theme().colors().editor_background)
2925 .when(index < plan.entries.len() - 1, |parent| {
2926 parent.border_color(cx.theme().colors().border).border_b_1()
2927 })
2928 .child(
2929 h_flex()
2930 .id(("plan_entry", index))
2931 .gap_1p5()
2932 .max_w_full()
2933 .overflow_x_scroll()
2934 .text_xs()
2935 .text_color(cx.theme().colors().text_muted)
2936 .child(match entry.status {
2937 acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
2938 .size(IconSize::Small)
2939 .color(Color::Muted)
2940 .into_any_element(),
2941 acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
2942 .size(IconSize::Small)
2943 .color(Color::Accent)
2944 .with_animation(
2945 "running",
2946 Animation::new(Duration::from_secs(2)).repeat(),
2947 |icon, delta| {
2948 icon.transform(Transformation::rotate(percentage(delta)))
2949 },
2950 )
2951 .into_any_element(),
2952 acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
2953 .size(IconSize::Small)
2954 .color(Color::Success)
2955 .into_any_element(),
2956 })
2957 .child(MarkdownElement::new(
2958 entry.content.clone(),
2959 plan_label_markdown_style(&entry.status, window, cx),
2960 )),
2961 );
2962
2963 Some(element)
2964 }))
2965 }
2966
2967 fn render_edits_summary(
2968 &self,
2969 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
2970 expanded: bool,
2971 pending_edits: bool,
2972 window: &mut Window,
2973 cx: &Context<Self>,
2974 ) -> Div {
2975 const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
2976
2977 let focus_handle = self.focus_handle(cx);
2978
2979 h_flex()
2980 .p_1()
2981 .justify_between()
2982 .when(expanded, |this| {
2983 this.border_b_1().border_color(cx.theme().colors().border)
2984 })
2985 .child(
2986 h_flex()
2987 .id("edits-container")
2988 .w_full()
2989 .gap_1()
2990 .child(Disclosure::new("edits-disclosure", expanded))
2991 .map(|this| {
2992 if pending_edits {
2993 this.child(
2994 Label::new(format!(
2995 "Editing {} {}…",
2996 changed_buffers.len(),
2997 if changed_buffers.len() == 1 {
2998 "file"
2999 } else {
3000 "files"
3001 }
3002 ))
3003 .color(Color::Muted)
3004 .size(LabelSize::Small)
3005 .with_animation(
3006 "edit-label",
3007 Animation::new(Duration::from_secs(2))
3008 .repeat()
3009 .with_easing(pulsating_between(0.3, 0.7)),
3010 |label, delta| label.alpha(delta),
3011 ),
3012 )
3013 } else {
3014 this.child(
3015 Label::new("Edits")
3016 .size(LabelSize::Small)
3017 .color(Color::Muted),
3018 )
3019 .child(Label::new("•").size(LabelSize::XSmall).color(Color::Muted))
3020 .child(
3021 Label::new(format!(
3022 "{} {}",
3023 changed_buffers.len(),
3024 if changed_buffers.len() == 1 {
3025 "file"
3026 } else {
3027 "files"
3028 }
3029 ))
3030 .size(LabelSize::Small)
3031 .color(Color::Muted),
3032 )
3033 }
3034 })
3035 .on_click(cx.listener(|this, _, _, cx| {
3036 this.edits_expanded = !this.edits_expanded;
3037 cx.notify();
3038 })),
3039 )
3040 .child(
3041 h_flex()
3042 .gap_1()
3043 .child(
3044 IconButton::new("review-changes", IconName::ListTodo)
3045 .icon_size(IconSize::Small)
3046 .tooltip({
3047 let focus_handle = focus_handle.clone();
3048 move |window, cx| {
3049 Tooltip::for_action_in(
3050 "Review Changes",
3051 &OpenAgentDiff,
3052 &focus_handle,
3053 window,
3054 cx,
3055 )
3056 }
3057 })
3058 .on_click(cx.listener(|_, _, window, cx| {
3059 window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
3060 })),
3061 )
3062 .child(Divider::vertical().color(DividerColor::Border))
3063 .child(
3064 Button::new("reject-all-changes", "Reject All")
3065 .label_size(LabelSize::Small)
3066 .disabled(pending_edits)
3067 .when(pending_edits, |this| {
3068 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3069 })
3070 .key_binding(
3071 KeyBinding::for_action_in(
3072 &RejectAll,
3073 &focus_handle.clone(),
3074 window,
3075 cx,
3076 )
3077 .map(|kb| kb.size(rems_from_px(10.))),
3078 )
3079 .on_click(cx.listener(move |this, _, window, cx| {
3080 this.reject_all(&RejectAll, window, cx);
3081 })),
3082 )
3083 .child(
3084 Button::new("keep-all-changes", "Keep All")
3085 .label_size(LabelSize::Small)
3086 .disabled(pending_edits)
3087 .when(pending_edits, |this| {
3088 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3089 })
3090 .key_binding(
3091 KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
3092 .map(|kb| kb.size(rems_from_px(10.))),
3093 )
3094 .on_click(cx.listener(move |this, _, window, cx| {
3095 this.keep_all(&KeepAll, window, cx);
3096 })),
3097 ),
3098 )
3099 }
3100
3101 fn render_edited_files(
3102 &self,
3103 action_log: &Entity<ActionLog>,
3104 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3105 pending_edits: bool,
3106 cx: &Context<Self>,
3107 ) -> Div {
3108 let editor_bg_color = cx.theme().colors().editor_background;
3109
3110 v_flex().children(changed_buffers.iter().enumerate().flat_map(
3111 |(index, (buffer, _diff))| {
3112 let file = buffer.read(cx).file()?;
3113 let path = file.path();
3114
3115 let file_path = path.parent().and_then(|parent| {
3116 let parent_str = parent.to_string_lossy();
3117
3118 if parent_str.is_empty() {
3119 None
3120 } else {
3121 Some(
3122 Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
3123 .color(Color::Muted)
3124 .size(LabelSize::XSmall)
3125 .buffer_font(cx),
3126 )
3127 }
3128 });
3129
3130 let file_name = path.file_name().map(|name| {
3131 Label::new(name.to_string_lossy().to_string())
3132 .size(LabelSize::XSmall)
3133 .buffer_font(cx)
3134 });
3135
3136 let file_icon = FileIcons::get_icon(path, cx)
3137 .map(Icon::from_path)
3138 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
3139 .unwrap_or_else(|| {
3140 Icon::new(IconName::File)
3141 .color(Color::Muted)
3142 .size(IconSize::Small)
3143 });
3144
3145 let overlay_gradient = linear_gradient(
3146 90.,
3147 linear_color_stop(editor_bg_color, 1.),
3148 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
3149 );
3150
3151 let element = h_flex()
3152 .group("edited-code")
3153 .id(("file-container", index))
3154 .relative()
3155 .py_1()
3156 .pl_2()
3157 .pr_1()
3158 .gap_2()
3159 .justify_between()
3160 .bg(editor_bg_color)
3161 .when(index < changed_buffers.len() - 1, |parent| {
3162 parent.border_color(cx.theme().colors().border).border_b_1()
3163 })
3164 .child(
3165 h_flex()
3166 .id(("file-name", index))
3167 .pr_8()
3168 .gap_1p5()
3169 .max_w_full()
3170 .overflow_x_scroll()
3171 .child(file_icon)
3172 .child(h_flex().gap_0p5().children(file_name).children(file_path))
3173 .on_click({
3174 let buffer = buffer.clone();
3175 cx.listener(move |this, _, window, cx| {
3176 this.open_edited_buffer(&buffer, window, cx);
3177 })
3178 }),
3179 )
3180 .child(
3181 h_flex()
3182 .gap_1()
3183 .visible_on_hover("edited-code")
3184 .child(
3185 Button::new("review", "Review")
3186 .label_size(LabelSize::Small)
3187 .on_click({
3188 let buffer = buffer.clone();
3189 cx.listener(move |this, _, window, cx| {
3190 this.open_edited_buffer(&buffer, window, cx);
3191 })
3192 }),
3193 )
3194 .child(Divider::vertical().color(DividerColor::BorderVariant))
3195 .child(
3196 Button::new("reject-file", "Reject")
3197 .label_size(LabelSize::Small)
3198 .disabled(pending_edits)
3199 .on_click({
3200 let buffer = buffer.clone();
3201 let action_log = action_log.clone();
3202 move |_, _, cx| {
3203 action_log.update(cx, |action_log, cx| {
3204 action_log
3205 .reject_edits_in_ranges(
3206 buffer.clone(),
3207 vec![Anchor::MIN..Anchor::MAX],
3208 cx,
3209 )
3210 .detach_and_log_err(cx);
3211 })
3212 }
3213 }),
3214 )
3215 .child(
3216 Button::new("keep-file", "Keep")
3217 .label_size(LabelSize::Small)
3218 .disabled(pending_edits)
3219 .on_click({
3220 let buffer = buffer.clone();
3221 let action_log = action_log.clone();
3222 move |_, _, cx| {
3223 action_log.update(cx, |action_log, cx| {
3224 action_log.keep_edits_in_range(
3225 buffer.clone(),
3226 Anchor::MIN..Anchor::MAX,
3227 cx,
3228 );
3229 })
3230 }
3231 }),
3232 ),
3233 )
3234 .child(
3235 div()
3236 .id("gradient-overlay")
3237 .absolute()
3238 .h_full()
3239 .w_12()
3240 .top_0()
3241 .bottom_0()
3242 .right(px(152.))
3243 .bg(overlay_gradient),
3244 );
3245
3246 Some(element)
3247 },
3248 ))
3249 }
3250
3251 fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
3252 let focus_handle = self.message_editor.focus_handle(cx);
3253 let editor_bg_color = cx.theme().colors().editor_background;
3254 let (expand_icon, expand_tooltip) = if self.editor_expanded {
3255 (IconName::Minimize, "Minimize Message Editor")
3256 } else {
3257 (IconName::Maximize, "Expand Message Editor")
3258 };
3259
3260 v_flex()
3261 .on_action(cx.listener(Self::expand_message_editor))
3262 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
3263 if let Some(profile_selector) = this.profile_selector.as_ref() {
3264 profile_selector.read(cx).menu_handle().toggle(window, cx);
3265 }
3266 }))
3267 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
3268 if let Some(model_selector) = this.model_selector.as_ref() {
3269 model_selector
3270 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
3271 }
3272 }))
3273 .p_2()
3274 .gap_2()
3275 .border_t_1()
3276 .border_color(cx.theme().colors().border)
3277 .bg(editor_bg_color)
3278 .when(self.editor_expanded, |this| {
3279 this.h(vh(0.8, window)).size_full().justify_between()
3280 })
3281 .child(
3282 v_flex()
3283 .relative()
3284 .size_full()
3285 .pt_1()
3286 .pr_2p5()
3287 .child(self.message_editor.clone())
3288 .child(
3289 h_flex()
3290 .absolute()
3291 .top_0()
3292 .right_0()
3293 .opacity(0.5)
3294 .hover(|this| this.opacity(1.0))
3295 .child(
3296 IconButton::new("toggle-height", expand_icon)
3297 .icon_size(IconSize::Small)
3298 .icon_color(Color::Muted)
3299 .tooltip({
3300 move |window, cx| {
3301 Tooltip::for_action_in(
3302 expand_tooltip,
3303 &ExpandMessageEditor,
3304 &focus_handle,
3305 window,
3306 cx,
3307 )
3308 }
3309 })
3310 .on_click(cx.listener(|_, _, window, cx| {
3311 window.dispatch_action(Box::new(ExpandMessageEditor), cx);
3312 })),
3313 ),
3314 ),
3315 )
3316 .child(
3317 h_flex()
3318 .flex_none()
3319 .flex_wrap()
3320 .justify_between()
3321 .child(
3322 h_flex()
3323 .child(self.render_follow_toggle(cx))
3324 .children(self.render_burn_mode_toggle(cx)),
3325 )
3326 .child(
3327 h_flex()
3328 .gap_1()
3329 .children(self.render_token_usage(cx))
3330 .children(self.profile_selector.clone())
3331 .children(self.model_selector.clone())
3332 .child(self.render_send_button(cx)),
3333 ),
3334 )
3335 .into_any()
3336 }
3337
3338 pub(crate) fn as_native_connection(
3339 &self,
3340 cx: &App,
3341 ) -> Option<Rc<agent2::NativeAgentConnection>> {
3342 let acp_thread = self.thread()?.read(cx);
3343 acp_thread.connection().clone().downcast()
3344 }
3345
3346 pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent2::Thread>> {
3347 let acp_thread = self.thread()?.read(cx);
3348 self.as_native_connection(cx)?
3349 .thread(acp_thread.session_id(), cx)
3350 }
3351
3352 fn is_using_zed_ai_models(&self, cx: &App) -> bool {
3353 self.as_native_thread(cx)
3354 .and_then(|thread| thread.read(cx).model())
3355 .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
3356 }
3357
3358 fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
3359 let thread = self.thread()?.read(cx);
3360 let usage = thread.token_usage()?;
3361 let is_generating = thread.status() != ThreadStatus::Idle;
3362
3363 let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
3364 let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
3365
3366 Some(
3367 h_flex()
3368 .flex_shrink_0()
3369 .gap_0p5()
3370 .mr_1p5()
3371 .child(
3372 Label::new(used)
3373 .size(LabelSize::Small)
3374 .color(Color::Muted)
3375 .map(|label| {
3376 if is_generating {
3377 label
3378 .with_animation(
3379 "used-tokens-label",
3380 Animation::new(Duration::from_secs(2))
3381 .repeat()
3382 .with_easing(pulsating_between(0.6, 1.)),
3383 |label, delta| label.alpha(delta),
3384 )
3385 .into_any()
3386 } else {
3387 label.into_any_element()
3388 }
3389 }),
3390 )
3391 .child(
3392 Label::new("/")
3393 .size(LabelSize::Small)
3394 .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
3395 )
3396 .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
3397 )
3398 }
3399
3400 fn toggle_burn_mode(
3401 &mut self,
3402 _: &ToggleBurnMode,
3403 _window: &mut Window,
3404 cx: &mut Context<Self>,
3405 ) {
3406 let Some(thread) = self.as_native_thread(cx) else {
3407 return;
3408 };
3409
3410 thread.update(cx, |thread, cx| {
3411 let current_mode = thread.completion_mode();
3412 thread.set_completion_mode(
3413 match current_mode {
3414 CompletionMode::Burn => CompletionMode::Normal,
3415 CompletionMode::Normal => CompletionMode::Burn,
3416 },
3417 cx,
3418 );
3419 });
3420 }
3421
3422 fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
3423 let Some(thread) = self.thread() else {
3424 return;
3425 };
3426 let action_log = thread.read(cx).action_log().clone();
3427 action_log.update(cx, |action_log, cx| action_log.keep_all_edits(cx));
3428 }
3429
3430 fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
3431 let Some(thread) = self.thread() else {
3432 return;
3433 };
3434 let action_log = thread.read(cx).action_log().clone();
3435 action_log
3436 .update(cx, |action_log, cx| action_log.reject_all_edits(cx))
3437 .detach();
3438 }
3439
3440 fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3441 let thread = self.as_native_thread(cx)?.read(cx);
3442
3443 if thread
3444 .model()
3445 .is_none_or(|model| !model.supports_burn_mode())
3446 {
3447 return None;
3448 }
3449
3450 let active_completion_mode = thread.completion_mode();
3451 let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
3452 let icon = if burn_mode_enabled {
3453 IconName::ZedBurnModeOn
3454 } else {
3455 IconName::ZedBurnMode
3456 };
3457
3458 Some(
3459 IconButton::new("burn-mode", icon)
3460 .icon_size(IconSize::Small)
3461 .icon_color(Color::Muted)
3462 .toggle_state(burn_mode_enabled)
3463 .selected_icon_color(Color::Error)
3464 .on_click(cx.listener(|this, _event, window, cx| {
3465 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
3466 }))
3467 .tooltip(move |_window, cx| {
3468 cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
3469 .into()
3470 })
3471 .into_any_element(),
3472 )
3473 }
3474
3475 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
3476 let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
3477 let is_generating = self
3478 .thread()
3479 .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
3480
3481 if is_generating && is_editor_empty {
3482 IconButton::new("stop-generation", IconName::Stop)
3483 .icon_color(Color::Error)
3484 .style(ButtonStyle::Tinted(ui::TintColor::Error))
3485 .tooltip(move |window, cx| {
3486 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
3487 })
3488 .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
3489 .into_any_element()
3490 } else {
3491 let send_btn_tooltip = if is_editor_empty && !is_generating {
3492 "Type to Send"
3493 } else if is_generating {
3494 "Stop and Send Message"
3495 } else {
3496 "Send"
3497 };
3498
3499 IconButton::new("send-message", IconName::Send)
3500 .style(ButtonStyle::Filled)
3501 .map(|this| {
3502 if is_editor_empty && !is_generating {
3503 this.disabled(true).icon_color(Color::Muted)
3504 } else {
3505 this.icon_color(Color::Accent)
3506 }
3507 })
3508 .tooltip(move |window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, window, cx))
3509 .on_click(cx.listener(|this, _, window, cx| {
3510 this.send(window, cx);
3511 }))
3512 .into_any_element()
3513 }
3514 }
3515
3516 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
3517 let following = self
3518 .workspace
3519 .read_with(cx, |workspace, _| {
3520 workspace.is_being_followed(CollaboratorId::Agent)
3521 })
3522 .unwrap_or(false);
3523
3524 IconButton::new("follow-agent", IconName::Crosshair)
3525 .icon_size(IconSize::Small)
3526 .icon_color(Color::Muted)
3527 .toggle_state(following)
3528 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
3529 .tooltip(move |window, cx| {
3530 if following {
3531 Tooltip::for_action("Stop Following Agent", &Follow, window, cx)
3532 } else {
3533 Tooltip::with_meta(
3534 "Follow Agent",
3535 Some(&Follow),
3536 "Track the agent's location as it reads and edits files.",
3537 window,
3538 cx,
3539 )
3540 }
3541 })
3542 .on_click(cx.listener(move |this, _, window, cx| {
3543 this.workspace
3544 .update(cx, |workspace, cx| {
3545 if following {
3546 workspace.unfollow(CollaboratorId::Agent, window, cx);
3547 } else {
3548 workspace.follow(CollaboratorId::Agent, window, cx);
3549 }
3550 })
3551 .ok();
3552 }))
3553 }
3554
3555 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
3556 let workspace = self.workspace.clone();
3557 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
3558 Self::open_link(text, &workspace, window, cx);
3559 })
3560 }
3561
3562 fn open_link(
3563 url: SharedString,
3564 workspace: &WeakEntity<Workspace>,
3565 window: &mut Window,
3566 cx: &mut App,
3567 ) {
3568 let Some(workspace) = workspace.upgrade() else {
3569 cx.open_url(&url);
3570 return;
3571 };
3572
3573 if let Some(mention) = MentionUri::parse(&url).log_err() {
3574 workspace.update(cx, |workspace, cx| match mention {
3575 MentionUri::File { abs_path } => {
3576 let project = workspace.project();
3577 let Some(path) =
3578 project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
3579 else {
3580 return;
3581 };
3582
3583 workspace
3584 .open_path(path, None, true, window, cx)
3585 .detach_and_log_err(cx);
3586 }
3587 MentionUri::Directory { abs_path } => {
3588 let project = workspace.project();
3589 let Some(entry) = project.update(cx, |project, cx| {
3590 let path = project.find_project_path(abs_path, cx)?;
3591 project.entry_for_path(&path, cx)
3592 }) else {
3593 return;
3594 };
3595
3596 project.update(cx, |_, cx| {
3597 cx.emit(project::Event::RevealInProjectPanel(entry.id));
3598 });
3599 }
3600 MentionUri::Symbol {
3601 path, line_range, ..
3602 }
3603 | MentionUri::Selection { path, line_range } => {
3604 let project = workspace.project();
3605 let Some((path, _)) = project.update(cx, |project, cx| {
3606 let path = project.find_project_path(path, cx)?;
3607 let entry = project.entry_for_path(&path, cx)?;
3608 Some((path, entry))
3609 }) else {
3610 return;
3611 };
3612
3613 let item = workspace.open_path(path, None, true, window, cx);
3614 window
3615 .spawn(cx, async move |cx| {
3616 let Some(editor) = item.await?.downcast::<Editor>() else {
3617 return Ok(());
3618 };
3619 let range =
3620 Point::new(line_range.start, 0)..Point::new(line_range.start, 0);
3621 editor
3622 .update_in(cx, |editor, window, cx| {
3623 editor.change_selections(
3624 SelectionEffects::scroll(Autoscroll::center()),
3625 window,
3626 cx,
3627 |s| s.select_ranges(vec![range]),
3628 );
3629 })
3630 .ok();
3631 anyhow::Ok(())
3632 })
3633 .detach_and_log_err(cx);
3634 }
3635 MentionUri::Thread { id, name } => {
3636 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3637 panel.update(cx, |panel, cx| {
3638 panel.load_agent_thread(
3639 DbThreadMetadata {
3640 id,
3641 title: name.into(),
3642 updated_at: Default::default(),
3643 },
3644 window,
3645 cx,
3646 )
3647 });
3648 }
3649 }
3650 MentionUri::TextThread { path, .. } => {
3651 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3652 panel.update(cx, |panel, cx| {
3653 panel
3654 .open_saved_prompt_editor(path.as_path().into(), window, cx)
3655 .detach_and_log_err(cx);
3656 });
3657 }
3658 }
3659 MentionUri::Rule { id, .. } => {
3660 let PromptId::User { uuid } = id else {
3661 return;
3662 };
3663 window.dispatch_action(
3664 Box::new(OpenRulesLibrary {
3665 prompt_to_select: Some(uuid.0),
3666 }),
3667 cx,
3668 )
3669 }
3670 MentionUri::Fetch { url } => {
3671 cx.open_url(url.as_str());
3672 }
3673 })
3674 } else {
3675 cx.open_url(&url);
3676 }
3677 }
3678
3679 fn open_tool_call_location(
3680 &self,
3681 entry_ix: usize,
3682 location_ix: usize,
3683 window: &mut Window,
3684 cx: &mut Context<Self>,
3685 ) -> Option<()> {
3686 let (tool_call_location, agent_location) = self
3687 .thread()?
3688 .read(cx)
3689 .entries()
3690 .get(entry_ix)?
3691 .location(location_ix)?;
3692
3693 let project_path = self
3694 .project
3695 .read(cx)
3696 .find_project_path(&tool_call_location.path, cx)?;
3697
3698 let open_task = self
3699 .workspace
3700 .update(cx, |workspace, cx| {
3701 workspace.open_path(project_path, None, true, window, cx)
3702 })
3703 .log_err()?;
3704 window
3705 .spawn(cx, async move |cx| {
3706 let item = open_task.await?;
3707
3708 let Some(active_editor) = item.downcast::<Editor>() else {
3709 return anyhow::Ok(());
3710 };
3711
3712 active_editor.update_in(cx, |editor, window, cx| {
3713 let multibuffer = editor.buffer().read(cx);
3714 let buffer = multibuffer.as_singleton();
3715 if agent_location.buffer.upgrade() == buffer {
3716 let excerpt_id = multibuffer.excerpt_ids().first().cloned();
3717 let anchor = editor::Anchor::in_buffer(
3718 excerpt_id.unwrap(),
3719 buffer.unwrap().read(cx).remote_id(),
3720 agent_location.position,
3721 );
3722 editor.change_selections(Default::default(), window, cx, |selections| {
3723 selections.select_anchor_ranges([anchor..anchor]);
3724 })
3725 } else {
3726 let row = tool_call_location.line.unwrap_or_default();
3727 editor.change_selections(Default::default(), window, cx, |selections| {
3728 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
3729 })
3730 }
3731 })?;
3732
3733 anyhow::Ok(())
3734 })
3735 .detach_and_log_err(cx);
3736
3737 None
3738 }
3739
3740 pub fn open_thread_as_markdown(
3741 &self,
3742 workspace: Entity<Workspace>,
3743 window: &mut Window,
3744 cx: &mut App,
3745 ) -> Task<anyhow::Result<()>> {
3746 let markdown_language_task = workspace
3747 .read(cx)
3748 .app_state()
3749 .languages
3750 .language_for_name("Markdown");
3751
3752 let (thread_summary, markdown) = if let Some(thread) = self.thread() {
3753 let thread = thread.read(cx);
3754 (thread.title().to_string(), thread.to_markdown(cx))
3755 } else {
3756 return Task::ready(Ok(()));
3757 };
3758
3759 window.spawn(cx, async move |cx| {
3760 let markdown_language = markdown_language_task.await?;
3761
3762 workspace.update_in(cx, |workspace, window, cx| {
3763 let project = workspace.project().clone();
3764
3765 if !project.read(cx).is_local() {
3766 bail!("failed to open active thread as markdown in remote project");
3767 }
3768
3769 let buffer = project.update(cx, |project, cx| {
3770 project.create_local_buffer(&markdown, Some(markdown_language), cx)
3771 });
3772 let buffer = cx.new(|cx| {
3773 MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
3774 });
3775
3776 workspace.add_item_to_active_pane(
3777 Box::new(cx.new(|cx| {
3778 let mut editor =
3779 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
3780 editor.set_breadcrumb_header(thread_summary);
3781 editor
3782 })),
3783 None,
3784 true,
3785 window,
3786 cx,
3787 );
3788
3789 anyhow::Ok(())
3790 })??;
3791 anyhow::Ok(())
3792 })
3793 }
3794
3795 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
3796 self.list_state.scroll_to(ListOffset::default());
3797 cx.notify();
3798 }
3799
3800 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
3801 if let Some(thread) = self.thread() {
3802 let entry_count = thread.read(cx).entries().len();
3803 self.list_state.reset(entry_count);
3804 cx.notify();
3805 }
3806 }
3807
3808 fn notify_with_sound(
3809 &mut self,
3810 caption: impl Into<SharedString>,
3811 icon: IconName,
3812 window: &mut Window,
3813 cx: &mut Context<Self>,
3814 ) {
3815 self.play_notification_sound(window, cx);
3816 self.show_notification(caption, icon, window, cx);
3817 }
3818
3819 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
3820 let settings = AgentSettings::get_global(cx);
3821 if settings.play_sound_when_agent_done && !window.is_window_active() {
3822 Audio::play_sound(Sound::AgentDone, cx);
3823 }
3824 }
3825
3826 fn show_notification(
3827 &mut self,
3828 caption: impl Into<SharedString>,
3829 icon: IconName,
3830 window: &mut Window,
3831 cx: &mut Context<Self>,
3832 ) {
3833 if window.is_window_active() || !self.notifications.is_empty() {
3834 return;
3835 }
3836
3837 let title = self.title(cx);
3838
3839 match AgentSettings::get_global(cx).notify_when_agent_waiting {
3840 NotifyWhenAgentWaiting::PrimaryScreen => {
3841 if let Some(primary) = cx.primary_display() {
3842 self.pop_up(icon, caption.into(), title, window, primary, cx);
3843 }
3844 }
3845 NotifyWhenAgentWaiting::AllScreens => {
3846 let caption = caption.into();
3847 for screen in cx.displays() {
3848 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
3849 }
3850 }
3851 NotifyWhenAgentWaiting::Never => {
3852 // Don't show anything
3853 }
3854 }
3855 }
3856
3857 fn pop_up(
3858 &mut self,
3859 icon: IconName,
3860 caption: SharedString,
3861 title: SharedString,
3862 window: &mut Window,
3863 screen: Rc<dyn PlatformDisplay>,
3864 cx: &mut Context<Self>,
3865 ) {
3866 let options = AgentNotification::window_options(screen, cx);
3867
3868 let project_name = self.workspace.upgrade().and_then(|workspace| {
3869 workspace
3870 .read(cx)
3871 .project()
3872 .read(cx)
3873 .visible_worktrees(cx)
3874 .next()
3875 .map(|worktree| worktree.read(cx).root_name().to_string())
3876 });
3877
3878 if let Some(screen_window) = cx
3879 .open_window(options, |_, cx| {
3880 cx.new(|_| {
3881 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
3882 })
3883 })
3884 .log_err()
3885 && let Some(pop_up) = screen_window.entity(cx).log_err()
3886 {
3887 self.notification_subscriptions
3888 .entry(screen_window)
3889 .or_insert_with(Vec::new)
3890 .push(cx.subscribe_in(&pop_up, window, {
3891 |this, _, event, window, cx| match event {
3892 AgentNotificationEvent::Accepted => {
3893 let handle = window.window_handle();
3894 cx.activate(true);
3895
3896 let workspace_handle = this.workspace.clone();
3897
3898 // If there are multiple Zed windows, activate the correct one.
3899 cx.defer(move |cx| {
3900 handle
3901 .update(cx, |_view, window, _cx| {
3902 window.activate_window();
3903
3904 if let Some(workspace) = workspace_handle.upgrade() {
3905 workspace.update(_cx, |workspace, cx| {
3906 workspace.focus_panel::<AgentPanel>(window, cx);
3907 });
3908 }
3909 })
3910 .log_err();
3911 });
3912
3913 this.dismiss_notifications(cx);
3914 }
3915 AgentNotificationEvent::Dismissed => {
3916 this.dismiss_notifications(cx);
3917 }
3918 }
3919 }));
3920
3921 self.notifications.push(screen_window);
3922
3923 // If the user manually refocuses the original window, dismiss the popup.
3924 self.notification_subscriptions
3925 .entry(screen_window)
3926 .or_insert_with(Vec::new)
3927 .push({
3928 let pop_up_weak = pop_up.downgrade();
3929
3930 cx.observe_window_activation(window, move |_, window, cx| {
3931 if window.is_window_active()
3932 && let Some(pop_up) = pop_up_weak.upgrade()
3933 {
3934 pop_up.update(cx, |_, cx| {
3935 cx.emit(AgentNotificationEvent::Dismissed);
3936 });
3937 }
3938 })
3939 });
3940 }
3941 }
3942
3943 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
3944 for window in self.notifications.drain(..) {
3945 window
3946 .update(cx, |_, window, _| {
3947 window.remove_window();
3948 })
3949 .ok();
3950
3951 self.notification_subscriptions.remove(&window);
3952 }
3953 }
3954
3955 fn render_thread_controls(&self, cx: &Context<Self>) -> impl IntoElement {
3956 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
3957 .shape(ui::IconButtonShape::Square)
3958 .icon_size(IconSize::Small)
3959 .icon_color(Color::Ignored)
3960 .tooltip(Tooltip::text("Open Thread as Markdown"))
3961 .on_click(cx.listener(move |this, _, window, cx| {
3962 if let Some(workspace) = this.workspace.upgrade() {
3963 this.open_thread_as_markdown(workspace, window, cx)
3964 .detach_and_log_err(cx);
3965 }
3966 }));
3967
3968 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
3969 .shape(ui::IconButtonShape::Square)
3970 .icon_size(IconSize::Small)
3971 .icon_color(Color::Ignored)
3972 .tooltip(Tooltip::text("Scroll To Top"))
3973 .on_click(cx.listener(move |this, _, _, cx| {
3974 this.scroll_to_top(cx);
3975 }));
3976
3977 let mut container = h_flex()
3978 .id("thread-controls-container")
3979 .group("thread-controls-container")
3980 .w_full()
3981 .mr_1()
3982 .pb_2()
3983 .px(RESPONSE_PADDING_X)
3984 .opacity(0.4)
3985 .hover(|style| style.opacity(1.))
3986 .flex_wrap()
3987 .justify_end();
3988
3989 if AgentSettings::get_global(cx).enable_feedback
3990 && self
3991 .thread()
3992 .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
3993 {
3994 let feedback = self.thread_feedback.feedback;
3995 container = container.child(
3996 div().visible_on_hover("thread-controls-container").child(
3997 Label::new(
3998 match feedback {
3999 Some(ThreadFeedback::Positive) => "Thanks for your feedback!",
4000 Some(ThreadFeedback::Negative) => "We appreciate your feedback and will use it to improve.",
4001 None => "Rating the thread sends all of your current conversation to the Zed team.",
4002 }
4003 )
4004 .color(Color::Muted)
4005 .size(LabelSize::XSmall)
4006 .truncate(),
4007 ),
4008 ).child(
4009 h_flex()
4010 .child(
4011 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
4012 .shape(ui::IconButtonShape::Square)
4013 .icon_size(IconSize::Small)
4014 .icon_color(match feedback {
4015 Some(ThreadFeedback::Positive) => Color::Accent,
4016 _ => Color::Ignored,
4017 })
4018 .tooltip(Tooltip::text("Helpful Response"))
4019 .on_click(cx.listener(move |this, _, window, cx| {
4020 this.handle_feedback_click(
4021 ThreadFeedback::Positive,
4022 window,
4023 cx,
4024 );
4025 })),
4026 )
4027 .child(
4028 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
4029 .shape(ui::IconButtonShape::Square)
4030 .icon_size(IconSize::Small)
4031 .icon_color(match feedback {
4032 Some(ThreadFeedback::Negative) => Color::Accent,
4033 _ => Color::Ignored,
4034 })
4035 .tooltip(Tooltip::text("Not Helpful"))
4036 .on_click(cx.listener(move |this, _, window, cx| {
4037 this.handle_feedback_click(
4038 ThreadFeedback::Negative,
4039 window,
4040 cx,
4041 );
4042 })),
4043 )
4044 )
4045 }
4046
4047 container.child(open_as_markdown).child(scroll_to_top)
4048 }
4049
4050 fn render_feedback_feedback_editor(
4051 editor: Entity<Editor>,
4052 window: &mut Window,
4053 cx: &Context<Self>,
4054 ) -> Div {
4055 let focus_handle = editor.focus_handle(cx);
4056 v_flex()
4057 .key_context("AgentFeedbackMessageEditor")
4058 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
4059 this.thread_feedback.dismiss_comments();
4060 cx.notify();
4061 }))
4062 .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
4063 this.submit_feedback_message(cx);
4064 }))
4065 .mb_2()
4066 .mx_4()
4067 .p_2()
4068 .rounded_md()
4069 .border_1()
4070 .border_color(cx.theme().colors().border)
4071 .bg(cx.theme().colors().editor_background)
4072 .child(editor)
4073 .child(
4074 h_flex()
4075 .gap_1()
4076 .justify_end()
4077 .child(
4078 Button::new("dismiss-feedback-message", "Cancel")
4079 .label_size(LabelSize::Small)
4080 .key_binding(
4081 KeyBinding::for_action_in(&menu::Cancel, &focus_handle, window, cx)
4082 .map(|kb| kb.size(rems_from_px(10.))),
4083 )
4084 .on_click(cx.listener(move |this, _, _window, cx| {
4085 this.thread_feedback.dismiss_comments();
4086 cx.notify();
4087 })),
4088 )
4089 .child(
4090 Button::new("submit-feedback-message", "Share Feedback")
4091 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
4092 .label_size(LabelSize::Small)
4093 .key_binding(
4094 KeyBinding::for_action_in(
4095 &menu::Confirm,
4096 &focus_handle,
4097 window,
4098 cx,
4099 )
4100 .map(|kb| kb.size(rems_from_px(10.))),
4101 )
4102 .on_click(cx.listener(move |this, _, _window, cx| {
4103 this.submit_feedback_message(cx);
4104 })),
4105 ),
4106 )
4107 }
4108
4109 fn handle_feedback_click(
4110 &mut self,
4111 feedback: ThreadFeedback,
4112 window: &mut Window,
4113 cx: &mut Context<Self>,
4114 ) {
4115 let Some(thread) = self.thread().cloned() else {
4116 return;
4117 };
4118
4119 self.thread_feedback.submit(thread, feedback, window, cx);
4120 cx.notify();
4121 }
4122
4123 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
4124 let Some(thread) = self.thread().cloned() else {
4125 return;
4126 };
4127
4128 self.thread_feedback.submit_comments(thread, cx);
4129 cx.notify();
4130 }
4131
4132 fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
4133 div()
4134 .id("acp-thread-scrollbar")
4135 .occlude()
4136 .on_mouse_move(cx.listener(|_, _, _, cx| {
4137 cx.notify();
4138 cx.stop_propagation()
4139 }))
4140 .on_hover(|_, _, cx| {
4141 cx.stop_propagation();
4142 })
4143 .on_any_mouse_down(|_, _, cx| {
4144 cx.stop_propagation();
4145 })
4146 .on_mouse_up(
4147 MouseButton::Left,
4148 cx.listener(|_, _, _, cx| {
4149 cx.stop_propagation();
4150 }),
4151 )
4152 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
4153 cx.notify();
4154 }))
4155 .h_full()
4156 .absolute()
4157 .right_1()
4158 .top_1()
4159 .bottom_0()
4160 .w(px(12.))
4161 .cursor_default()
4162 .children(Scrollbar::vertical(self.scrollbar_state.clone()).map(|s| s.auto_hide(cx)))
4163 }
4164
4165 fn render_token_limit_callout(
4166 &self,
4167 line_height: Pixels,
4168 cx: &mut Context<Self>,
4169 ) -> Option<Callout> {
4170 let token_usage = self.thread()?.read(cx).token_usage()?;
4171 let ratio = token_usage.ratio();
4172
4173 let (severity, title) = match ratio {
4174 acp_thread::TokenUsageRatio::Normal => return None,
4175 acp_thread::TokenUsageRatio::Warning => {
4176 (Severity::Warning, "Thread reaching the token limit soon")
4177 }
4178 acp_thread::TokenUsageRatio::Exceeded => {
4179 (Severity::Error, "Thread reached the token limit")
4180 }
4181 };
4182
4183 let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
4184 thread.read(cx).completion_mode() == CompletionMode::Normal
4185 && thread
4186 .read(cx)
4187 .model()
4188 .is_some_and(|model| model.supports_burn_mode())
4189 });
4190
4191 let description = if burn_mode_available {
4192 "To continue, start a new thread from a summary or turn Burn Mode on."
4193 } else {
4194 "To continue, start a new thread from a summary."
4195 };
4196
4197 Some(
4198 Callout::new()
4199 .severity(severity)
4200 .line_height(line_height)
4201 .title(title)
4202 .description(description)
4203 .actions_slot(
4204 h_flex()
4205 .gap_0p5()
4206 .child(
4207 Button::new("start-new-thread", "Start New Thread")
4208 .label_size(LabelSize::Small)
4209 .on_click(cx.listener(|this, _, window, cx| {
4210 let Some(thread) = this.thread() else {
4211 return;
4212 };
4213 let session_id = thread.read(cx).session_id().clone();
4214 window.dispatch_action(
4215 crate::NewNativeAgentThreadFromSummary {
4216 from_session_id: session_id,
4217 }
4218 .boxed_clone(),
4219 cx,
4220 );
4221 })),
4222 )
4223 .when(burn_mode_available, |this| {
4224 this.child(
4225 IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
4226 .icon_size(IconSize::XSmall)
4227 .on_click(cx.listener(|this, _event, window, cx| {
4228 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4229 })),
4230 )
4231 }),
4232 ),
4233 )
4234 }
4235
4236 fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
4237 if !self.is_using_zed_ai_models(cx) {
4238 return None;
4239 }
4240
4241 let user_store = self.project.read(cx).user_store().read(cx);
4242 if user_store.is_usage_based_billing_enabled() {
4243 return None;
4244 }
4245
4246 let plan = user_store.plan().unwrap_or(cloud_llm_client::Plan::ZedFree);
4247
4248 let usage = user_store.model_request_usage()?;
4249
4250 Some(
4251 div()
4252 .child(UsageCallout::new(plan, usage))
4253 .line_height(line_height),
4254 )
4255 }
4256
4257 fn settings_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
4258 self.entry_view_state.update(cx, |entry_view_state, cx| {
4259 entry_view_state.settings_changed(cx);
4260 });
4261 }
4262
4263 pub(crate) fn insert_dragged_files(
4264 &self,
4265 paths: Vec<project::ProjectPath>,
4266 added_worktrees: Vec<Entity<project::Worktree>>,
4267 window: &mut Window,
4268 cx: &mut Context<Self>,
4269 ) {
4270 self.message_editor.update(cx, |message_editor, cx| {
4271 message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
4272 })
4273 }
4274
4275 pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
4276 self.message_editor.update(cx, |message_editor, cx| {
4277 message_editor.insert_selections(window, cx);
4278 })
4279 }
4280
4281 fn render_thread_retry_status_callout(
4282 &self,
4283 _window: &mut Window,
4284 _cx: &mut Context<Self>,
4285 ) -> Option<Callout> {
4286 let state = self.thread_retry_status.as_ref()?;
4287
4288 let next_attempt_in = state
4289 .duration
4290 .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
4291 if next_attempt_in.is_zero() {
4292 return None;
4293 }
4294
4295 let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
4296
4297 let retry_message = if state.max_attempts == 1 {
4298 if next_attempt_in_secs == 1 {
4299 "Retrying. Next attempt in 1 second.".to_string()
4300 } else {
4301 format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
4302 }
4303 } else if next_attempt_in_secs == 1 {
4304 format!(
4305 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
4306 state.attempt, state.max_attempts,
4307 )
4308 } else {
4309 format!(
4310 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
4311 state.attempt, state.max_attempts,
4312 )
4313 };
4314
4315 Some(
4316 Callout::new()
4317 .severity(Severity::Warning)
4318 .title(state.last_error.clone())
4319 .description(retry_message),
4320 )
4321 }
4322
4323 fn render_thread_error(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
4324 let content = match self.thread_error.as_ref()? {
4325 ThreadError::Other(error) => self.render_any_thread_error(error.clone(), cx),
4326 ThreadError::AuthenticationRequired(error) => {
4327 self.render_authentication_required_error(error.clone(), cx)
4328 }
4329 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
4330 ThreadError::ModelRequestLimitReached(plan) => {
4331 self.render_model_request_limit_reached_error(*plan, cx)
4332 }
4333 ThreadError::ToolUseLimitReached => {
4334 self.render_tool_use_limit_reached_error(window, cx)?
4335 }
4336 };
4337
4338 Some(div().child(content))
4339 }
4340
4341 fn render_any_thread_error(&self, error: SharedString, cx: &mut Context<'_, Self>) -> Callout {
4342 Callout::new()
4343 .severity(Severity::Error)
4344 .title("Error")
4345 .description(error.clone())
4346 .actions_slot(self.create_copy_button(error.to_string()))
4347 .dismiss_action(self.dismiss_error_button(cx))
4348 }
4349
4350 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
4351 const ERROR_MESSAGE: &str =
4352 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
4353
4354 Callout::new()
4355 .severity(Severity::Error)
4356 .title("Free Usage Exceeded")
4357 .description(ERROR_MESSAGE)
4358 .actions_slot(
4359 h_flex()
4360 .gap_0p5()
4361 .child(self.upgrade_button(cx))
4362 .child(self.create_copy_button(ERROR_MESSAGE)),
4363 )
4364 .dismiss_action(self.dismiss_error_button(cx))
4365 }
4366
4367 fn render_authentication_required_error(
4368 &self,
4369 error: SharedString,
4370 cx: &mut Context<Self>,
4371 ) -> Callout {
4372 Callout::new()
4373 .severity(Severity::Error)
4374 .title("Authentication Required")
4375 .description(error.clone())
4376 .actions_slot(
4377 h_flex()
4378 .gap_0p5()
4379 .child(self.authenticate_button(cx))
4380 .child(self.create_copy_button(error)),
4381 )
4382 .dismiss_action(self.dismiss_error_button(cx))
4383 }
4384
4385 fn render_model_request_limit_reached_error(
4386 &self,
4387 plan: cloud_llm_client::Plan,
4388 cx: &mut Context<Self>,
4389 ) -> Callout {
4390 let error_message = match plan {
4391 cloud_llm_client::Plan::ZedPro => "Upgrade to usage-based billing for more prompts.",
4392 cloud_llm_client::Plan::ZedProTrial | cloud_llm_client::Plan::ZedFree => {
4393 "Upgrade to Zed Pro for more prompts."
4394 }
4395 };
4396
4397 Callout::new()
4398 .severity(Severity::Error)
4399 .title("Model Prompt Limit Reached")
4400 .description(error_message)
4401 .actions_slot(
4402 h_flex()
4403 .gap_0p5()
4404 .child(self.upgrade_button(cx))
4405 .child(self.create_copy_button(error_message)),
4406 )
4407 .dismiss_action(self.dismiss_error_button(cx))
4408 }
4409
4410 fn render_tool_use_limit_reached_error(
4411 &self,
4412 window: &mut Window,
4413 cx: &mut Context<Self>,
4414 ) -> Option<Callout> {
4415 let thread = self.as_native_thread(cx)?;
4416 let supports_burn_mode = thread
4417 .read(cx)
4418 .model()
4419 .is_some_and(|model| model.supports_burn_mode());
4420
4421 let focus_handle = self.focus_handle(cx);
4422
4423 Some(
4424 Callout::new()
4425 .icon(IconName::Info)
4426 .title("Consecutive tool use limit reached.")
4427 .actions_slot(
4428 h_flex()
4429 .gap_0p5()
4430 .when(supports_burn_mode, |this| {
4431 this.child(
4432 Button::new("continue-burn-mode", "Continue with Burn Mode")
4433 .style(ButtonStyle::Filled)
4434 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
4435 .layer(ElevationIndex::ModalSurface)
4436 .label_size(LabelSize::Small)
4437 .key_binding(
4438 KeyBinding::for_action_in(
4439 &ContinueWithBurnMode,
4440 &focus_handle,
4441 window,
4442 cx,
4443 )
4444 .map(|kb| kb.size(rems_from_px(10.))),
4445 )
4446 .tooltip(Tooltip::text(
4447 "Enable Burn Mode for unlimited tool use.",
4448 ))
4449 .on_click({
4450 cx.listener(move |this, _, _window, cx| {
4451 thread.update(cx, |thread, cx| {
4452 thread
4453 .set_completion_mode(CompletionMode::Burn, cx);
4454 });
4455 this.resume_chat(cx);
4456 })
4457 }),
4458 )
4459 })
4460 .child(
4461 Button::new("continue-conversation", "Continue")
4462 .layer(ElevationIndex::ModalSurface)
4463 .label_size(LabelSize::Small)
4464 .key_binding(
4465 KeyBinding::for_action_in(
4466 &ContinueThread,
4467 &focus_handle,
4468 window,
4469 cx,
4470 )
4471 .map(|kb| kb.size(rems_from_px(10.))),
4472 )
4473 .on_click(cx.listener(|this, _, _window, cx| {
4474 this.resume_chat(cx);
4475 })),
4476 ),
4477 ),
4478 )
4479 }
4480
4481 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
4482 let message = message.into();
4483
4484 IconButton::new("copy", IconName::Copy)
4485 .icon_size(IconSize::Small)
4486 .icon_color(Color::Muted)
4487 .tooltip(Tooltip::text("Copy Error Message"))
4488 .on_click(move |_, _, cx| {
4489 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
4490 })
4491 }
4492
4493 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4494 IconButton::new("dismiss", IconName::Close)
4495 .icon_size(IconSize::Small)
4496 .icon_color(Color::Muted)
4497 .tooltip(Tooltip::text("Dismiss Error"))
4498 .on_click(cx.listener({
4499 move |this, _, _, cx| {
4500 this.clear_thread_error(cx);
4501 cx.notify();
4502 }
4503 }))
4504 }
4505
4506 fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4507 Button::new("authenticate", "Authenticate")
4508 .label_size(LabelSize::Small)
4509 .style(ButtonStyle::Filled)
4510 .on_click(cx.listener({
4511 move |this, _, window, cx| {
4512 let agent = this.agent.clone();
4513 let ThreadState::Ready { thread, .. } = &this.thread_state else {
4514 return;
4515 };
4516
4517 let connection = thread.read(cx).connection().clone();
4518 let err = AuthRequired {
4519 description: None,
4520 provider_id: None,
4521 };
4522 this.clear_thread_error(cx);
4523 let this = cx.weak_entity();
4524 window.defer(cx, |window, cx| {
4525 Self::handle_auth_required(this, err, agent, connection, window, cx);
4526 })
4527 }
4528 }))
4529 }
4530
4531 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4532 Button::new("upgrade", "Upgrade")
4533 .label_size(LabelSize::Small)
4534 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
4535 .on_click(cx.listener({
4536 move |this, _, _, cx| {
4537 this.clear_thread_error(cx);
4538 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
4539 }
4540 }))
4541 }
4542
4543 fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4544 self.thread_state = Self::initial_state(
4545 self.agent.clone(),
4546 None,
4547 self.workspace.clone(),
4548 self.project.clone(),
4549 window,
4550 cx,
4551 );
4552 cx.notify();
4553 }
4554
4555 pub fn delete_history_entry(&mut self, entry: HistoryEntry, cx: &mut Context<Self>) {
4556 let task = match entry {
4557 HistoryEntry::AcpThread(thread) => self.history_store.update(cx, |history, cx| {
4558 history.delete_thread(thread.id.clone(), cx)
4559 }),
4560 HistoryEntry::TextThread(context) => self.history_store.update(cx, |history, cx| {
4561 history.delete_text_thread(context.path.clone(), cx)
4562 }),
4563 };
4564 task.detach_and_log_err(cx);
4565 }
4566}
4567
4568impl Focusable for AcpThreadView {
4569 fn focus_handle(&self, cx: &App) -> FocusHandle {
4570 self.message_editor.focus_handle(cx)
4571 }
4572}
4573
4574impl Render for AcpThreadView {
4575 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4576 let has_messages = self.list_state.item_count() > 0;
4577 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
4578
4579 v_flex()
4580 .size_full()
4581 .key_context("AcpThread")
4582 .on_action(cx.listener(Self::open_agent_diff))
4583 .on_action(cx.listener(Self::toggle_burn_mode))
4584 .on_action(cx.listener(Self::keep_all))
4585 .on_action(cx.listener(Self::reject_all))
4586 .bg(cx.theme().colors().panel_background)
4587 .child(match &self.thread_state {
4588 ThreadState::Unauthenticated {
4589 connection,
4590 description,
4591 configuration_view,
4592 pending_auth_method,
4593 ..
4594 } => self.render_auth_required_state(
4595 connection,
4596 description.as_ref(),
4597 configuration_view.as_ref(),
4598 pending_auth_method.as_ref(),
4599 window,
4600 cx,
4601 ),
4602 ThreadState::Loading { .. } => {
4603 v_flex().flex_1().child(self.render_empty_state(window, cx))
4604 }
4605 ThreadState::LoadError(e) => v_flex()
4606 .p_2()
4607 .flex_1()
4608 .items_center()
4609 .justify_center()
4610 .child(self.render_load_error(e, cx)),
4611 ThreadState::Ready { thread, .. } => {
4612 let thread_clone = thread.clone();
4613
4614 v_flex().flex_1().map(|this| {
4615 if has_messages {
4616 this.child(
4617 list(
4618 self.list_state.clone(),
4619 cx.processor(|this, index: usize, window, cx| {
4620 let Some((entry, len)) = this.thread().and_then(|thread| {
4621 let entries = &thread.read(cx).entries();
4622 Some((entries.get(index)?, entries.len()))
4623 }) else {
4624 return Empty.into_any();
4625 };
4626 this.render_entry(index, len, entry, window, cx)
4627 }),
4628 )
4629 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
4630 .flex_grow()
4631 .into_any(),
4632 )
4633 .child(self.render_vertical_scrollbar(cx))
4634 .children(
4635 match thread_clone.read(cx).status() {
4636 ThreadStatus::Idle
4637 | ThreadStatus::WaitingForToolConfirmation => None,
4638 ThreadStatus::Generating => div()
4639 .px_5()
4640 .py_2()
4641 .child(LoadingLabel::new("").size(LabelSize::Small))
4642 .into(),
4643 },
4644 )
4645 } else {
4646 this.child(self.render_empty_state(window, cx))
4647 }
4648 })
4649 }
4650 })
4651 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
4652 // above so that the scrollbar doesn't render behind it. The current setup allows
4653 // the scrollbar to stop exactly at the activity bar start.
4654 .when(has_messages, |this| match &self.thread_state {
4655 ThreadState::Ready { thread, .. } => {
4656 this.children(self.render_activity_bar(thread, window, cx))
4657 }
4658 _ => this,
4659 })
4660 .children(self.render_thread_retry_status_callout(window, cx))
4661 .children(self.render_thread_error(window, cx))
4662 .children(
4663 if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
4664 Some(usage_callout.into_any_element())
4665 } else {
4666 self.render_token_limit_callout(line_height, cx)
4667 .map(|token_limit_callout| token_limit_callout.into_any_element())
4668 },
4669 )
4670 .child(self.render_message_editor(window, cx))
4671 }
4672}
4673
4674fn default_markdown_style(buffer_font: bool, window: &Window, cx: &App) -> MarkdownStyle {
4675 let theme_settings = ThemeSettings::get_global(cx);
4676 let colors = cx.theme().colors();
4677
4678 let buffer_font_size = TextSize::Small.rems(cx);
4679
4680 let mut text_style = window.text_style();
4681 let line_height = buffer_font_size * 1.75;
4682
4683 let font_family = if buffer_font {
4684 theme_settings.buffer_font.family.clone()
4685 } else {
4686 theme_settings.ui_font.family.clone()
4687 };
4688
4689 let font_size = if buffer_font {
4690 TextSize::Small.rems(cx)
4691 } else {
4692 TextSize::Default.rems(cx)
4693 };
4694
4695 text_style.refine(&TextStyleRefinement {
4696 font_family: Some(font_family),
4697 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
4698 font_features: Some(theme_settings.ui_font.features.clone()),
4699 font_size: Some(font_size.into()),
4700 line_height: Some(line_height.into()),
4701 color: Some(cx.theme().colors().text),
4702 ..Default::default()
4703 });
4704
4705 MarkdownStyle {
4706 base_text_style: text_style.clone(),
4707 syntax: cx.theme().syntax().clone(),
4708 selection_background_color: cx.theme().colors().element_selection_background,
4709 code_block_overflow_x_scroll: true,
4710 table_overflow_x_scroll: true,
4711 heading_level_styles: Some(HeadingLevelStyles {
4712 h1: Some(TextStyleRefinement {
4713 font_size: Some(rems(1.15).into()),
4714 ..Default::default()
4715 }),
4716 h2: Some(TextStyleRefinement {
4717 font_size: Some(rems(1.1).into()),
4718 ..Default::default()
4719 }),
4720 h3: Some(TextStyleRefinement {
4721 font_size: Some(rems(1.05).into()),
4722 ..Default::default()
4723 }),
4724 h4: Some(TextStyleRefinement {
4725 font_size: Some(rems(1.).into()),
4726 ..Default::default()
4727 }),
4728 h5: Some(TextStyleRefinement {
4729 font_size: Some(rems(0.95).into()),
4730 ..Default::default()
4731 }),
4732 h6: Some(TextStyleRefinement {
4733 font_size: Some(rems(0.875).into()),
4734 ..Default::default()
4735 }),
4736 }),
4737 code_block: StyleRefinement {
4738 padding: EdgesRefinement {
4739 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
4740 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
4741 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
4742 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
4743 },
4744 margin: EdgesRefinement {
4745 top: Some(Length::Definite(Pixels(8.).into())),
4746 left: Some(Length::Definite(Pixels(0.).into())),
4747 right: Some(Length::Definite(Pixels(0.).into())),
4748 bottom: Some(Length::Definite(Pixels(12.).into())),
4749 },
4750 border_style: Some(BorderStyle::Solid),
4751 border_widths: EdgesRefinement {
4752 top: Some(AbsoluteLength::Pixels(Pixels(1.))),
4753 left: Some(AbsoluteLength::Pixels(Pixels(1.))),
4754 right: Some(AbsoluteLength::Pixels(Pixels(1.))),
4755 bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
4756 },
4757 border_color: Some(colors.border_variant),
4758 background: Some(colors.editor_background.into()),
4759 text: Some(TextStyleRefinement {
4760 font_family: Some(theme_settings.buffer_font.family.clone()),
4761 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
4762 font_features: Some(theme_settings.buffer_font.features.clone()),
4763 font_size: Some(buffer_font_size.into()),
4764 ..Default::default()
4765 }),
4766 ..Default::default()
4767 },
4768 inline_code: TextStyleRefinement {
4769 font_family: Some(theme_settings.buffer_font.family.clone()),
4770 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
4771 font_features: Some(theme_settings.buffer_font.features.clone()),
4772 font_size: Some(buffer_font_size.into()),
4773 background_color: Some(colors.editor_foreground.opacity(0.08)),
4774 ..Default::default()
4775 },
4776 link: TextStyleRefinement {
4777 background_color: Some(colors.editor_foreground.opacity(0.025)),
4778 underline: Some(UnderlineStyle {
4779 color: Some(colors.text_accent.opacity(0.5)),
4780 thickness: px(1.),
4781 ..Default::default()
4782 }),
4783 ..Default::default()
4784 },
4785 ..Default::default()
4786 }
4787}
4788
4789fn plan_label_markdown_style(
4790 status: &acp::PlanEntryStatus,
4791 window: &Window,
4792 cx: &App,
4793) -> MarkdownStyle {
4794 let default_md_style = default_markdown_style(false, window, cx);
4795
4796 MarkdownStyle {
4797 base_text_style: TextStyle {
4798 color: cx.theme().colors().text_muted,
4799 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
4800 Some(gpui::StrikethroughStyle {
4801 thickness: px(1.),
4802 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
4803 })
4804 } else {
4805 None
4806 },
4807 ..default_md_style.base_text_style
4808 },
4809 ..default_md_style
4810 }
4811}
4812
4813fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
4814 let default_md_style = default_markdown_style(true, window, cx);
4815
4816 MarkdownStyle {
4817 base_text_style: TextStyle {
4818 ..default_md_style.base_text_style
4819 },
4820 selection_background_color: cx.theme().colors().element_selection_background,
4821 ..Default::default()
4822 }
4823}
4824
4825#[cfg(test)]
4826pub(crate) mod tests {
4827 use acp_thread::StubAgentConnection;
4828 use agent_client_protocol::SessionId;
4829 use assistant_context::ContextStore;
4830 use editor::EditorSettings;
4831 use fs::FakeFs;
4832 use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
4833 use project::Project;
4834 use serde_json::json;
4835 use settings::SettingsStore;
4836 use std::any::Any;
4837 use std::path::Path;
4838 use workspace::Item;
4839
4840 use super::*;
4841
4842 #[gpui::test]
4843 async fn test_drop(cx: &mut TestAppContext) {
4844 init_test(cx);
4845
4846 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
4847 let weak_view = thread_view.downgrade();
4848 drop(thread_view);
4849 assert!(!weak_view.is_upgradable());
4850 }
4851
4852 #[gpui::test]
4853 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
4854 init_test(cx);
4855
4856 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
4857
4858 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4859 message_editor.update_in(cx, |editor, window, cx| {
4860 editor.set_text("Hello", window, cx);
4861 });
4862
4863 cx.deactivate_window();
4864
4865 thread_view.update_in(cx, |thread_view, window, cx| {
4866 thread_view.send(window, cx);
4867 });
4868
4869 cx.run_until_parked();
4870
4871 assert!(
4872 cx.windows()
4873 .iter()
4874 .any(|window| window.downcast::<AgentNotification>().is_some())
4875 );
4876 }
4877
4878 #[gpui::test]
4879 async fn test_notification_for_error(cx: &mut TestAppContext) {
4880 init_test(cx);
4881
4882 let (thread_view, cx) =
4883 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
4884
4885 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4886 message_editor.update_in(cx, |editor, window, cx| {
4887 editor.set_text("Hello", window, cx);
4888 });
4889
4890 cx.deactivate_window();
4891
4892 thread_view.update_in(cx, |thread_view, window, cx| {
4893 thread_view.send(window, cx);
4894 });
4895
4896 cx.run_until_parked();
4897
4898 assert!(
4899 cx.windows()
4900 .iter()
4901 .any(|window| window.downcast::<AgentNotification>().is_some())
4902 );
4903 }
4904
4905 #[gpui::test]
4906 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
4907 init_test(cx);
4908
4909 let tool_call_id = acp::ToolCallId("1".into());
4910 let tool_call = acp::ToolCall {
4911 id: tool_call_id.clone(),
4912 title: "Label".into(),
4913 kind: acp::ToolKind::Edit,
4914 status: acp::ToolCallStatus::Pending,
4915 content: vec!["hi".into()],
4916 locations: vec![],
4917 raw_input: None,
4918 raw_output: None,
4919 };
4920 let connection =
4921 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
4922 tool_call_id,
4923 vec![acp::PermissionOption {
4924 id: acp::PermissionOptionId("1".into()),
4925 name: "Allow".into(),
4926 kind: acp::PermissionOptionKind::AllowOnce,
4927 }],
4928 )]));
4929
4930 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
4931
4932 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4933
4934 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4935 message_editor.update_in(cx, |editor, window, cx| {
4936 editor.set_text("Hello", window, cx);
4937 });
4938
4939 cx.deactivate_window();
4940
4941 thread_view.update_in(cx, |thread_view, window, cx| {
4942 thread_view.send(window, cx);
4943 });
4944
4945 cx.run_until_parked();
4946
4947 assert!(
4948 cx.windows()
4949 .iter()
4950 .any(|window| window.downcast::<AgentNotification>().is_some())
4951 );
4952 }
4953
4954 async fn setup_thread_view(
4955 agent: impl AgentServer + 'static,
4956 cx: &mut TestAppContext,
4957 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
4958 let fs = FakeFs::new(cx.executor());
4959 let project = Project::test(fs, [], cx).await;
4960 let (workspace, cx) =
4961 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4962
4963 let context_store =
4964 cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
4965 let history_store =
4966 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
4967
4968 let thread_view = cx.update(|window, cx| {
4969 cx.new(|cx| {
4970 AcpThreadView::new(
4971 Rc::new(agent),
4972 None,
4973 None,
4974 workspace.downgrade(),
4975 project,
4976 history_store,
4977 None,
4978 window,
4979 cx,
4980 )
4981 })
4982 });
4983 cx.run_until_parked();
4984 (thread_view, cx)
4985 }
4986
4987 fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
4988 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
4989
4990 workspace
4991 .update_in(cx, |workspace, window, cx| {
4992 workspace.add_item_to_active_pane(
4993 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
4994 None,
4995 true,
4996 window,
4997 cx,
4998 );
4999 })
5000 .unwrap();
5001 }
5002
5003 struct ThreadViewItem(Entity<AcpThreadView>);
5004
5005 impl Item for ThreadViewItem {
5006 type Event = ();
5007
5008 fn include_in_nav_history() -> bool {
5009 false
5010 }
5011
5012 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
5013 "Test".into()
5014 }
5015 }
5016
5017 impl EventEmitter<()> for ThreadViewItem {}
5018
5019 impl Focusable for ThreadViewItem {
5020 fn focus_handle(&self, cx: &App) -> FocusHandle {
5021 self.0.read(cx).focus_handle(cx)
5022 }
5023 }
5024
5025 impl Render for ThreadViewItem {
5026 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5027 self.0.clone().into_any_element()
5028 }
5029 }
5030
5031 struct StubAgentServer<C> {
5032 connection: C,
5033 }
5034
5035 impl<C> StubAgentServer<C> {
5036 fn new(connection: C) -> Self {
5037 Self { connection }
5038 }
5039 }
5040
5041 impl StubAgentServer<StubAgentConnection> {
5042 fn default_response() -> Self {
5043 let conn = StubAgentConnection::new();
5044 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5045 content: "Default response".into(),
5046 }]);
5047 Self::new(conn)
5048 }
5049 }
5050
5051 impl<C> AgentServer for StubAgentServer<C>
5052 where
5053 C: 'static + AgentConnection + Send + Clone,
5054 {
5055 fn logo(&self) -> ui::IconName {
5056 ui::IconName::Ai
5057 }
5058
5059 fn name(&self) -> &'static str {
5060 "Test"
5061 }
5062
5063 fn empty_state_headline(&self) -> &'static str {
5064 "Test"
5065 }
5066
5067 fn empty_state_message(&self) -> &'static str {
5068 "Test"
5069 }
5070
5071 fn connect(
5072 &self,
5073 _root_dir: &Path,
5074 _project: &Entity<Project>,
5075 _cx: &mut App,
5076 ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
5077 Task::ready(Ok(Rc::new(self.connection.clone())))
5078 }
5079
5080 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5081 self
5082 }
5083 }
5084
5085 #[derive(Clone)]
5086 struct SaboteurAgentConnection;
5087
5088 impl AgentConnection for SaboteurAgentConnection {
5089 fn new_thread(
5090 self: Rc<Self>,
5091 project: Entity<Project>,
5092 _cwd: &Path,
5093 cx: &mut gpui::App,
5094 ) -> Task<gpui::Result<Entity<AcpThread>>> {
5095 Task::ready(Ok(cx.new(|cx| {
5096 let action_log = cx.new(|_| ActionLog::new(project.clone()));
5097 AcpThread::new(
5098 "SaboteurAgentConnection",
5099 self,
5100 project,
5101 action_log,
5102 SessionId("test".into()),
5103 )
5104 })))
5105 }
5106
5107 fn auth_methods(&self) -> &[acp::AuthMethod] {
5108 &[]
5109 }
5110
5111 fn prompt_capabilities(&self) -> acp::PromptCapabilities {
5112 acp::PromptCapabilities {
5113 image: true,
5114 audio: true,
5115 embedded_context: true,
5116 }
5117 }
5118
5119 fn authenticate(
5120 &self,
5121 _method_id: acp::AuthMethodId,
5122 _cx: &mut App,
5123 ) -> Task<gpui::Result<()>> {
5124 unimplemented!()
5125 }
5126
5127 fn prompt(
5128 &self,
5129 _id: Option<acp_thread::UserMessageId>,
5130 _params: acp::PromptRequest,
5131 _cx: &mut App,
5132 ) -> Task<gpui::Result<acp::PromptResponse>> {
5133 Task::ready(Err(anyhow::anyhow!("Error prompting")))
5134 }
5135
5136 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
5137 unimplemented!()
5138 }
5139
5140 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5141 self
5142 }
5143 }
5144
5145 pub(crate) fn init_test(cx: &mut TestAppContext) {
5146 cx.update(|cx| {
5147 let settings_store = SettingsStore::test(cx);
5148 cx.set_global(settings_store);
5149 language::init(cx);
5150 Project::init_settings(cx);
5151 AgentSettings::register(cx);
5152 workspace::init_settings(cx);
5153 ThemeSettings::register(cx);
5154 release_channel::init(SemanticVersion::default(), cx);
5155 EditorSettings::register(cx);
5156 prompt_store::init(cx)
5157 });
5158 }
5159
5160 #[gpui::test]
5161 async fn test_rewind_views(cx: &mut TestAppContext) {
5162 init_test(cx);
5163
5164 let fs = FakeFs::new(cx.executor());
5165 fs.insert_tree(
5166 "/project",
5167 json!({
5168 "test1.txt": "old content 1",
5169 "test2.txt": "old content 2"
5170 }),
5171 )
5172 .await;
5173 let project = Project::test(fs, [Path::new("/project")], cx).await;
5174 let (workspace, cx) =
5175 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5176
5177 let context_store =
5178 cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5179 let history_store =
5180 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5181
5182 let connection = Rc::new(StubAgentConnection::new());
5183 let thread_view = cx.update(|window, cx| {
5184 cx.new(|cx| {
5185 AcpThreadView::new(
5186 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
5187 None,
5188 None,
5189 workspace.downgrade(),
5190 project.clone(),
5191 history_store.clone(),
5192 None,
5193 window,
5194 cx,
5195 )
5196 })
5197 });
5198
5199 cx.run_until_parked();
5200
5201 let thread = thread_view
5202 .read_with(cx, |view, _| view.thread().cloned())
5203 .unwrap();
5204
5205 // First user message
5206 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5207 id: acp::ToolCallId("tool1".into()),
5208 title: "Edit file 1".into(),
5209 kind: acp::ToolKind::Edit,
5210 status: acp::ToolCallStatus::Completed,
5211 content: vec![acp::ToolCallContent::Diff {
5212 diff: acp::Diff {
5213 path: "/project/test1.txt".into(),
5214 old_text: Some("old content 1".into()),
5215 new_text: "new content 1".into(),
5216 },
5217 }],
5218 locations: vec![],
5219 raw_input: None,
5220 raw_output: None,
5221 })]);
5222
5223 thread
5224 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
5225 .await
5226 .unwrap();
5227 cx.run_until_parked();
5228
5229 thread.read_with(cx, |thread, _| {
5230 assert_eq!(thread.entries().len(), 2);
5231 });
5232
5233 thread_view.read_with(cx, |view, cx| {
5234 view.entry_view_state.read_with(cx, |entry_view_state, _| {
5235 assert!(
5236 entry_view_state
5237 .entry(0)
5238 .unwrap()
5239 .message_editor()
5240 .is_some()
5241 );
5242 assert!(entry_view_state.entry(1).unwrap().has_content());
5243 });
5244 });
5245
5246 // Second user message
5247 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5248 id: acp::ToolCallId("tool2".into()),
5249 title: "Edit file 2".into(),
5250 kind: acp::ToolKind::Edit,
5251 status: acp::ToolCallStatus::Completed,
5252 content: vec![acp::ToolCallContent::Diff {
5253 diff: acp::Diff {
5254 path: "/project/test2.txt".into(),
5255 old_text: Some("old content 2".into()),
5256 new_text: "new content 2".into(),
5257 },
5258 }],
5259 locations: vec![],
5260 raw_input: None,
5261 raw_output: None,
5262 })]);
5263
5264 thread
5265 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
5266 .await
5267 .unwrap();
5268 cx.run_until_parked();
5269
5270 let second_user_message_id = thread.read_with(cx, |thread, _| {
5271 assert_eq!(thread.entries().len(), 4);
5272 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
5273 panic!();
5274 };
5275 user_message.id.clone().unwrap()
5276 });
5277
5278 thread_view.read_with(cx, |view, cx| {
5279 view.entry_view_state.read_with(cx, |entry_view_state, _| {
5280 assert!(
5281 entry_view_state
5282 .entry(0)
5283 .unwrap()
5284 .message_editor()
5285 .is_some()
5286 );
5287 assert!(entry_view_state.entry(1).unwrap().has_content());
5288 assert!(
5289 entry_view_state
5290 .entry(2)
5291 .unwrap()
5292 .message_editor()
5293 .is_some()
5294 );
5295 assert!(entry_view_state.entry(3).unwrap().has_content());
5296 });
5297 });
5298
5299 // Rewind to first message
5300 thread
5301 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
5302 .await
5303 .unwrap();
5304
5305 cx.run_until_parked();
5306
5307 thread.read_with(cx, |thread, _| {
5308 assert_eq!(thread.entries().len(), 2);
5309 });
5310
5311 thread_view.read_with(cx, |view, cx| {
5312 view.entry_view_state.read_with(cx, |entry_view_state, _| {
5313 assert!(
5314 entry_view_state
5315 .entry(0)
5316 .unwrap()
5317 .message_editor()
5318 .is_some()
5319 );
5320 assert!(entry_view_state.entry(1).unwrap().has_content());
5321
5322 // Old views should be dropped
5323 assert!(entry_view_state.entry(2).is_none());
5324 assert!(entry_view_state.entry(3).is_none());
5325 });
5326 });
5327 }
5328
5329 #[gpui::test]
5330 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
5331 init_test(cx);
5332
5333 let connection = StubAgentConnection::new();
5334
5335 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5336 content: acp::ContentBlock::Text(acp::TextContent {
5337 text: "Response".into(),
5338 annotations: None,
5339 }),
5340 }]);
5341
5342 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5343 add_to_workspace(thread_view.clone(), cx);
5344
5345 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5346 message_editor.update_in(cx, |editor, window, cx| {
5347 editor.set_text("Original message to edit", window, cx);
5348 });
5349 thread_view.update_in(cx, |thread_view, window, cx| {
5350 thread_view.send(window, cx);
5351 });
5352
5353 cx.run_until_parked();
5354
5355 let user_message_editor = thread_view.read_with(cx, |view, cx| {
5356 assert_eq!(view.editing_message, None);
5357
5358 view.entry_view_state
5359 .read(cx)
5360 .entry(0)
5361 .unwrap()
5362 .message_editor()
5363 .unwrap()
5364 .clone()
5365 });
5366
5367 // Focus
5368 cx.focus(&user_message_editor);
5369 thread_view.read_with(cx, |view, _cx| {
5370 assert_eq!(view.editing_message, Some(0));
5371 });
5372
5373 // Edit
5374 user_message_editor.update_in(cx, |editor, window, cx| {
5375 editor.set_text("Edited message content", window, cx);
5376 });
5377
5378 // Cancel
5379 user_message_editor.update_in(cx, |_editor, window, cx| {
5380 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
5381 });
5382
5383 thread_view.read_with(cx, |view, _cx| {
5384 assert_eq!(view.editing_message, None);
5385 });
5386
5387 user_message_editor.read_with(cx, |editor, cx| {
5388 assert_eq!(editor.text(cx), "Original message to edit");
5389 });
5390 }
5391
5392 #[gpui::test]
5393 async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
5394 init_test(cx);
5395
5396 let connection = StubAgentConnection::new();
5397
5398 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5399 add_to_workspace(thread_view.clone(), cx);
5400
5401 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5402 let mut events = cx.events(&message_editor);
5403 message_editor.update_in(cx, |editor, window, cx| {
5404 editor.set_text("", window, cx);
5405 });
5406
5407 message_editor.update_in(cx, |_editor, window, cx| {
5408 window.dispatch_action(Box::new(Chat), cx);
5409 });
5410 cx.run_until_parked();
5411 // We shouldn't have received any messages
5412 assert!(matches!(
5413 events.try_next(),
5414 Err(futures::channel::mpsc::TryRecvError { .. })
5415 ));
5416 }
5417
5418 #[gpui::test]
5419 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
5420 init_test(cx);
5421
5422 let connection = StubAgentConnection::new();
5423
5424 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5425 content: acp::ContentBlock::Text(acp::TextContent {
5426 text: "Response".into(),
5427 annotations: None,
5428 }),
5429 }]);
5430
5431 let (thread_view, cx) =
5432 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5433 add_to_workspace(thread_view.clone(), cx);
5434
5435 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5436 message_editor.update_in(cx, |editor, window, cx| {
5437 editor.set_text("Original message to edit", window, cx);
5438 });
5439 thread_view.update_in(cx, |thread_view, window, cx| {
5440 thread_view.send(window, cx);
5441 });
5442
5443 cx.run_until_parked();
5444
5445 let user_message_editor = thread_view.read_with(cx, |view, cx| {
5446 assert_eq!(view.editing_message, None);
5447 assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
5448
5449 view.entry_view_state
5450 .read(cx)
5451 .entry(0)
5452 .unwrap()
5453 .message_editor()
5454 .unwrap()
5455 .clone()
5456 });
5457
5458 // Focus
5459 cx.focus(&user_message_editor);
5460
5461 // Edit
5462 user_message_editor.update_in(cx, |editor, window, cx| {
5463 editor.set_text("Edited message content", window, cx);
5464 });
5465
5466 // Send
5467 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5468 content: acp::ContentBlock::Text(acp::TextContent {
5469 text: "New Response".into(),
5470 annotations: None,
5471 }),
5472 }]);
5473
5474 user_message_editor.update_in(cx, |_editor, window, cx| {
5475 window.dispatch_action(Box::new(Chat), cx);
5476 });
5477
5478 cx.run_until_parked();
5479
5480 thread_view.read_with(cx, |view, cx| {
5481 assert_eq!(view.editing_message, None);
5482
5483 let entries = view.thread().unwrap().read(cx).entries();
5484 assert_eq!(entries.len(), 2);
5485 assert_eq!(
5486 entries[0].to_markdown(cx),
5487 "## User\n\nEdited message content\n\n"
5488 );
5489 assert_eq!(
5490 entries[1].to_markdown(cx),
5491 "## Assistant\n\nNew Response\n\n"
5492 );
5493
5494 let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
5495 assert!(!state.entry(1).unwrap().has_content());
5496 state.entry(0).unwrap().message_editor().unwrap().clone()
5497 });
5498
5499 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
5500 })
5501 }
5502
5503 #[gpui::test]
5504 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
5505 init_test(cx);
5506
5507 let connection = StubAgentConnection::new();
5508
5509 let (thread_view, cx) =
5510 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5511 add_to_workspace(thread_view.clone(), cx);
5512
5513 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5514 message_editor.update_in(cx, |editor, window, cx| {
5515 editor.set_text("Original message to edit", window, cx);
5516 });
5517 thread_view.update_in(cx, |thread_view, window, cx| {
5518 thread_view.send(window, cx);
5519 });
5520
5521 cx.run_until_parked();
5522
5523 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
5524 let thread = view.thread().unwrap().read(cx);
5525 assert_eq!(thread.entries().len(), 1);
5526
5527 let editor = view
5528 .entry_view_state
5529 .read(cx)
5530 .entry(0)
5531 .unwrap()
5532 .message_editor()
5533 .unwrap()
5534 .clone();
5535
5536 (editor, thread.session_id().clone())
5537 });
5538
5539 // Focus
5540 cx.focus(&user_message_editor);
5541
5542 thread_view.read_with(cx, |view, _cx| {
5543 assert_eq!(view.editing_message, Some(0));
5544 });
5545
5546 // Edit
5547 user_message_editor.update_in(cx, |editor, window, cx| {
5548 editor.set_text("Edited message content", window, cx);
5549 });
5550
5551 thread_view.read_with(cx, |view, _cx| {
5552 assert_eq!(view.editing_message, Some(0));
5553 });
5554
5555 // Finish streaming response
5556 cx.update(|_, cx| {
5557 connection.send_update(
5558 session_id.clone(),
5559 acp::SessionUpdate::AgentMessageChunk {
5560 content: acp::ContentBlock::Text(acp::TextContent {
5561 text: "Response".into(),
5562 annotations: None,
5563 }),
5564 },
5565 cx,
5566 );
5567 connection.end_turn(session_id, acp::StopReason::EndTurn);
5568 });
5569
5570 thread_view.read_with(cx, |view, _cx| {
5571 assert_eq!(view.editing_message, Some(0));
5572 });
5573
5574 cx.run_until_parked();
5575
5576 // Should still be editing
5577 cx.update(|window, cx| {
5578 assert!(user_message_editor.focus_handle(cx).is_focused(window));
5579 assert_eq!(thread_view.read(cx).editing_message, Some(0));
5580 assert_eq!(
5581 user_message_editor.read(cx).text(cx),
5582 "Edited message content"
5583 );
5584 });
5585 }
5586
5587 #[gpui::test]
5588 async fn test_interrupt(cx: &mut TestAppContext) {
5589 init_test(cx);
5590
5591 let connection = StubAgentConnection::new();
5592
5593 let (thread_view, cx) =
5594 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
5595 add_to_workspace(thread_view.clone(), cx);
5596
5597 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5598 message_editor.update_in(cx, |editor, window, cx| {
5599 editor.set_text("Message 1", window, cx);
5600 });
5601 thread_view.update_in(cx, |thread_view, window, cx| {
5602 thread_view.send(window, cx);
5603 });
5604
5605 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
5606 let thread = view.thread().unwrap();
5607
5608 (thread.clone(), thread.read(cx).session_id().clone())
5609 });
5610
5611 cx.run_until_parked();
5612
5613 cx.update(|_, cx| {
5614 connection.send_update(
5615 session_id.clone(),
5616 acp::SessionUpdate::AgentMessageChunk {
5617 content: "Message 1 resp".into(),
5618 },
5619 cx,
5620 );
5621 });
5622
5623 cx.run_until_parked();
5624
5625 thread.read_with(cx, |thread, cx| {
5626 assert_eq!(
5627 thread.to_markdown(cx),
5628 indoc::indoc! {"
5629 ## User
5630
5631 Message 1
5632
5633 ## Assistant
5634
5635 Message 1 resp
5636
5637 "}
5638 )
5639 });
5640
5641 message_editor.update_in(cx, |editor, window, cx| {
5642 editor.set_text("Message 2", window, cx);
5643 });
5644 thread_view.update_in(cx, |thread_view, window, cx| {
5645 thread_view.send(window, cx);
5646 });
5647
5648 cx.update(|_, cx| {
5649 // Simulate a response sent after beginning to cancel
5650 connection.send_update(
5651 session_id.clone(),
5652 acp::SessionUpdate::AgentMessageChunk {
5653 content: "onse".into(),
5654 },
5655 cx,
5656 );
5657 });
5658
5659 cx.run_until_parked();
5660
5661 // Last Message 1 response should appear before Message 2
5662 thread.read_with(cx, |thread, cx| {
5663 assert_eq!(
5664 thread.to_markdown(cx),
5665 indoc::indoc! {"
5666 ## User
5667
5668 Message 1
5669
5670 ## Assistant
5671
5672 Message 1 response
5673
5674 ## User
5675
5676 Message 2
5677
5678 "}
5679 )
5680 });
5681
5682 cx.update(|_, cx| {
5683 connection.send_update(
5684 session_id.clone(),
5685 acp::SessionUpdate::AgentMessageChunk {
5686 content: "Message 2 response".into(),
5687 },
5688 cx,
5689 );
5690 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
5691 });
5692
5693 cx.run_until_parked();
5694
5695 thread.read_with(cx, |thread, cx| {
5696 assert_eq!(
5697 thread.to_markdown(cx),
5698 indoc::indoc! {"
5699 ## User
5700
5701 Message 1
5702
5703 ## Assistant
5704
5705 Message 1 response
5706
5707 ## User
5708
5709 Message 2
5710
5711 ## Assistant
5712
5713 Message 2 response
5714
5715 "}
5716 )
5717 });
5718 }
5719}