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