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