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