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