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