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