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