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