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