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