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