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