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