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