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