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