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