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