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