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