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 .id("thread-controls-container")
5028 .group("thread-controls-container")
5029 .w_full()
5030 .py_2()
5031 .px_5()
5032 .gap_px()
5033 .opacity(0.6)
5034 .hover(|style| style.opacity(1.))
5035 .flex_wrap()
5036 .justify_end();
5037
5038 if AgentSettings::get_global(cx).enable_feedback
5039 && self
5040 .thread()
5041 .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
5042 {
5043 let feedback = self.thread_feedback.feedback;
5044
5045 container = container
5046 .child(
5047 div().visible_on_hover("thread-controls-container").child(
5048 Label::new(match feedback {
5049 Some(ThreadFeedback::Positive) => "Thanks for your feedback!",
5050 Some(ThreadFeedback::Negative) => {
5051 "We appreciate your feedback and will use it to improve."
5052 }
5053 None => {
5054 "Rating the thread sends all of your current conversation to the Zed team."
5055 }
5056 })
5057 .color(Color::Muted)
5058 .size(LabelSize::XSmall)
5059 .truncate(),
5060 ),
5061 )
5062 .child(
5063 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
5064 .shape(ui::IconButtonShape::Square)
5065 .icon_size(IconSize::Small)
5066 .icon_color(match feedback {
5067 Some(ThreadFeedback::Positive) => Color::Accent,
5068 _ => Color::Ignored,
5069 })
5070 .tooltip(Tooltip::text("Helpful Response"))
5071 .on_click(cx.listener(move |this, _, window, cx| {
5072 this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
5073 })),
5074 )
5075 .child(
5076 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
5077 .shape(ui::IconButtonShape::Square)
5078 .icon_size(IconSize::Small)
5079 .icon_color(match feedback {
5080 Some(ThreadFeedback::Negative) => Color::Accent,
5081 _ => Color::Ignored,
5082 })
5083 .tooltip(Tooltip::text("Not Helpful"))
5084 .on_click(cx.listener(move |this, _, window, cx| {
5085 this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
5086 })),
5087 );
5088 }
5089
5090 container
5091 .child(open_as_markdown)
5092 .child(scroll_to_top)
5093 .into_any_element()
5094 }
5095
5096 fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
5097 h_flex()
5098 .key_context("AgentFeedbackMessageEditor")
5099 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
5100 this.thread_feedback.dismiss_comments();
5101 cx.notify();
5102 }))
5103 .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
5104 this.submit_feedback_message(cx);
5105 }))
5106 .p_2()
5107 .mb_2()
5108 .mx_5()
5109 .gap_1()
5110 .rounded_md()
5111 .border_1()
5112 .border_color(cx.theme().colors().border)
5113 .bg(cx.theme().colors().editor_background)
5114 .child(div().w_full().child(editor))
5115 .child(
5116 h_flex()
5117 .child(
5118 IconButton::new("dismiss-feedback-message", IconName::Close)
5119 .icon_color(Color::Error)
5120 .icon_size(IconSize::XSmall)
5121 .shape(ui::IconButtonShape::Square)
5122 .on_click(cx.listener(move |this, _, _window, cx| {
5123 this.thread_feedback.dismiss_comments();
5124 cx.notify();
5125 })),
5126 )
5127 .child(
5128 IconButton::new("submit-feedback-message", IconName::Return)
5129 .icon_size(IconSize::XSmall)
5130 .shape(ui::IconButtonShape::Square)
5131 .on_click(cx.listener(move |this, _, _window, cx| {
5132 this.submit_feedback_message(cx);
5133 })),
5134 ),
5135 )
5136 }
5137
5138 fn handle_feedback_click(
5139 &mut self,
5140 feedback: ThreadFeedback,
5141 window: &mut Window,
5142 cx: &mut Context<Self>,
5143 ) {
5144 let Some(thread) = self.thread().cloned() else {
5145 return;
5146 };
5147
5148 self.thread_feedback.submit(thread, feedback, window, cx);
5149 cx.notify();
5150 }
5151
5152 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
5153 let Some(thread) = self.thread().cloned() else {
5154 return;
5155 };
5156
5157 self.thread_feedback.submit_comments(thread, cx);
5158 cx.notify();
5159 }
5160
5161 fn render_token_limit_callout(
5162 &self,
5163 line_height: Pixels,
5164 cx: &mut Context<Self>,
5165 ) -> Option<Callout> {
5166 let token_usage = self.thread()?.read(cx).token_usage()?;
5167 let ratio = token_usage.ratio();
5168
5169 let (severity, title) = match ratio {
5170 acp_thread::TokenUsageRatio::Normal => return None,
5171 acp_thread::TokenUsageRatio::Warning => {
5172 (Severity::Warning, "Thread reaching the token limit soon")
5173 }
5174 acp_thread::TokenUsageRatio::Exceeded => {
5175 (Severity::Error, "Thread reached the token limit")
5176 }
5177 };
5178
5179 let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
5180 thread.read(cx).completion_mode() == CompletionMode::Normal
5181 && thread
5182 .read(cx)
5183 .model()
5184 .is_some_and(|model| model.supports_burn_mode())
5185 });
5186
5187 let description = if burn_mode_available {
5188 "To continue, start a new thread from a summary or turn Burn Mode on."
5189 } else {
5190 "To continue, start a new thread from a summary."
5191 };
5192
5193 Some(
5194 Callout::new()
5195 .severity(severity)
5196 .line_height(line_height)
5197 .title(title)
5198 .description(description)
5199 .actions_slot(
5200 h_flex()
5201 .gap_0p5()
5202 .child(
5203 Button::new("start-new-thread", "Start New Thread")
5204 .label_size(LabelSize::Small)
5205 .on_click(cx.listener(|this, _, window, cx| {
5206 let Some(thread) = this.thread() else {
5207 return;
5208 };
5209 let session_id = thread.read(cx).session_id().clone();
5210 window.dispatch_action(
5211 crate::NewNativeAgentThreadFromSummary {
5212 from_session_id: session_id,
5213 }
5214 .boxed_clone(),
5215 cx,
5216 );
5217 })),
5218 )
5219 .when(burn_mode_available, |this| {
5220 this.child(
5221 IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
5222 .icon_size(IconSize::XSmall)
5223 .on_click(cx.listener(|this, _event, window, cx| {
5224 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5225 })),
5226 )
5227 }),
5228 ),
5229 )
5230 }
5231
5232 fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
5233 if !self.is_using_zed_ai_models(cx) {
5234 return None;
5235 }
5236
5237 let user_store = self.project.read(cx).user_store().read(cx);
5238 if user_store.is_usage_based_billing_enabled() {
5239 return None;
5240 }
5241
5242 let plan = user_store
5243 .plan()
5244 .unwrap_or(cloud_llm_client::Plan::V1(PlanV1::ZedFree));
5245
5246 let usage = user_store.model_request_usage()?;
5247
5248 Some(
5249 div()
5250 .child(UsageCallout::new(plan, usage))
5251 .line_height(line_height),
5252 )
5253 }
5254
5255 fn agent_ui_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
5256 self.entry_view_state.update(cx, |entry_view_state, cx| {
5257 entry_view_state.agent_ui_font_size_changed(cx);
5258 });
5259 }
5260
5261 pub(crate) fn insert_dragged_files(
5262 &self,
5263 paths: Vec<project::ProjectPath>,
5264 added_worktrees: Vec<Entity<project::Worktree>>,
5265 window: &mut Window,
5266 cx: &mut Context<Self>,
5267 ) {
5268 self.message_editor.update(cx, |message_editor, cx| {
5269 message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
5270 })
5271 }
5272
5273 /// Inserts the selected text into the message editor or the message being
5274 /// edited, if any.
5275 pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
5276 self.active_editor(cx).update(cx, |editor, cx| {
5277 editor.insert_selections(window, cx);
5278 });
5279 }
5280
5281 fn render_thread_retry_status_callout(
5282 &self,
5283 _window: &mut Window,
5284 _cx: &mut Context<Self>,
5285 ) -> Option<Callout> {
5286 let state = self.thread_retry_status.as_ref()?;
5287
5288 let next_attempt_in = state
5289 .duration
5290 .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
5291 if next_attempt_in.is_zero() {
5292 return None;
5293 }
5294
5295 let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
5296
5297 let retry_message = if state.max_attempts == 1 {
5298 if next_attempt_in_secs == 1 {
5299 "Retrying. Next attempt in 1 second.".to_string()
5300 } else {
5301 format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
5302 }
5303 } else if next_attempt_in_secs == 1 {
5304 format!(
5305 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
5306 state.attempt, state.max_attempts,
5307 )
5308 } else {
5309 format!(
5310 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
5311 state.attempt, state.max_attempts,
5312 )
5313 };
5314
5315 Some(
5316 Callout::new()
5317 .severity(Severity::Warning)
5318 .title(state.last_error.clone())
5319 .description(retry_message),
5320 )
5321 }
5322
5323 fn render_codex_windows_warning(&self, cx: &mut Context<Self>) -> Option<Callout> {
5324 if self.show_codex_windows_warning {
5325 Some(
5326 Callout::new()
5327 .icon(IconName::Warning)
5328 .severity(Severity::Warning)
5329 .title("Codex on Windows")
5330 .description(
5331 "For best performance, run Codex in Windows Subsystem for Linux (WSL2)",
5332 )
5333 .actions_slot(
5334 Button::new("open-wsl-modal", "Open in WSL")
5335 .icon_size(IconSize::Small)
5336 .icon_color(Color::Muted)
5337 .on_click(cx.listener({
5338 move |_, _, _window, cx| {
5339 #[cfg(windows)]
5340 _window.dispatch_action(
5341 zed_actions::wsl_actions::OpenWsl::default().boxed_clone(),
5342 cx,
5343 );
5344 cx.notify();
5345 }
5346 })),
5347 )
5348 .dismiss_action(
5349 IconButton::new("dismiss", IconName::Close)
5350 .icon_size(IconSize::Small)
5351 .icon_color(Color::Muted)
5352 .tooltip(Tooltip::text("Dismiss Warning"))
5353 .on_click(cx.listener({
5354 move |this, _, _, cx| {
5355 this.show_codex_windows_warning = false;
5356 cx.notify();
5357 }
5358 })),
5359 ),
5360 )
5361 } else {
5362 None
5363 }
5364 }
5365
5366 fn render_thread_error(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
5367 let content = match self.thread_error.as_ref()? {
5368 ThreadError::Other(error) => self.render_any_thread_error(error.clone(), window, cx),
5369 ThreadError::Refusal => self.render_refusal_error(cx),
5370 ThreadError::AuthenticationRequired(error) => {
5371 self.render_authentication_required_error(error.clone(), cx)
5372 }
5373 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
5374 ThreadError::ModelRequestLimitReached(plan) => {
5375 self.render_model_request_limit_reached_error(*plan, cx)
5376 }
5377 ThreadError::ToolUseLimitReached => self.render_tool_use_limit_reached_error(cx)?,
5378 };
5379
5380 Some(div().child(content))
5381 }
5382
5383 fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
5384 v_flex().w_full().justify_end().child(
5385 h_flex()
5386 .p_2()
5387 .pr_3()
5388 .w_full()
5389 .gap_1p5()
5390 .border_t_1()
5391 .border_color(cx.theme().colors().border)
5392 .bg(cx.theme().colors().element_background)
5393 .child(
5394 h_flex()
5395 .flex_1()
5396 .gap_1p5()
5397 .child(
5398 Icon::new(IconName::Download)
5399 .color(Color::Accent)
5400 .size(IconSize::Small),
5401 )
5402 .child(Label::new("New version available").size(LabelSize::Small)),
5403 )
5404 .child(
5405 Button::new("update-button", format!("Update to v{}", version))
5406 .label_size(LabelSize::Small)
5407 .style(ButtonStyle::Tinted(TintColor::Accent))
5408 .on_click(cx.listener(|this, _, window, cx| {
5409 this.reset(window, cx);
5410 })),
5411 ),
5412 )
5413 }
5414
5415 fn current_mode_id(&self, cx: &App) -> Option<Arc<str>> {
5416 if let Some(thread) = self.as_native_thread(cx) {
5417 Some(thread.read(cx).profile().0.clone())
5418 } else if let Some(mode_selector) = self.mode_selector() {
5419 Some(mode_selector.read(cx).mode().0)
5420 } else {
5421 None
5422 }
5423 }
5424
5425 fn current_model_id(&self, cx: &App) -> Option<String> {
5426 self.model_selector
5427 .as_ref()
5428 .and_then(|selector| selector.read(cx).active_model(cx).map(|m| m.id.to_string()))
5429 }
5430
5431 fn current_model_name(&self, cx: &App) -> SharedString {
5432 // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
5433 // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
5434 // This provides better clarity about what refused the request
5435 if self.as_native_connection(cx).is_some() {
5436 self.model_selector
5437 .as_ref()
5438 .and_then(|selector| selector.read(cx).active_model(cx))
5439 .map(|model| model.name.clone())
5440 .unwrap_or_else(|| SharedString::from("The model"))
5441 } else {
5442 // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
5443 self.agent.name()
5444 }
5445 }
5446
5447 fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
5448 let model_or_agent_name = self.current_model_name(cx);
5449 let refusal_message = format!(
5450 "{} 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.",
5451 model_or_agent_name
5452 );
5453
5454 Callout::new()
5455 .severity(Severity::Error)
5456 .title("Request Refused")
5457 .icon(IconName::XCircle)
5458 .description(refusal_message.clone())
5459 .actions_slot(self.create_copy_button(&refusal_message))
5460 .dismiss_action(self.dismiss_error_button(cx))
5461 }
5462
5463 fn render_any_thread_error(
5464 &mut self,
5465 error: SharedString,
5466 window: &mut Window,
5467 cx: &mut Context<'_, Self>,
5468 ) -> Callout {
5469 let can_resume = self
5470 .thread()
5471 .map_or(false, |thread| thread.read(cx).can_resume(cx));
5472
5473 let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
5474 let thread = thread.read(cx);
5475 let supports_burn_mode = thread
5476 .model()
5477 .map_or(false, |model| model.supports_burn_mode());
5478 supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
5479 });
5480
5481 let markdown = if let Some(markdown) = &self.thread_error_markdown {
5482 markdown.clone()
5483 } else {
5484 let markdown = cx.new(|cx| Markdown::new(error.clone(), None, None, cx));
5485 self.thread_error_markdown = Some(markdown.clone());
5486 markdown
5487 };
5488
5489 let markdown_style = default_markdown_style(false, true, window, cx);
5490 let description = self
5491 .render_markdown(markdown, markdown_style)
5492 .into_any_element();
5493
5494 Callout::new()
5495 .severity(Severity::Error)
5496 .icon(IconName::XCircle)
5497 .title("An Error Happened")
5498 .description_slot(description)
5499 .actions_slot(
5500 h_flex()
5501 .gap_0p5()
5502 .when(can_resume && can_enable_burn_mode, |this| {
5503 this.child(
5504 Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
5505 .icon(IconName::ZedBurnMode)
5506 .icon_position(IconPosition::Start)
5507 .icon_size(IconSize::Small)
5508 .label_size(LabelSize::Small)
5509 .on_click(cx.listener(|this, _, window, cx| {
5510 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5511 this.resume_chat(cx);
5512 })),
5513 )
5514 })
5515 .when(can_resume, |this| {
5516 this.child(
5517 IconButton::new("retry", IconName::RotateCw)
5518 .icon_size(IconSize::Small)
5519 .tooltip(Tooltip::text("Retry Generation"))
5520 .on_click(cx.listener(|this, _, _window, cx| {
5521 this.resume_chat(cx);
5522 })),
5523 )
5524 })
5525 .child(self.create_copy_button(error.to_string())),
5526 )
5527 .dismiss_action(self.dismiss_error_button(cx))
5528 }
5529
5530 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
5531 const ERROR_MESSAGE: &str =
5532 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
5533
5534 Callout::new()
5535 .severity(Severity::Error)
5536 .icon(IconName::XCircle)
5537 .title("Free Usage Exceeded")
5538 .description(ERROR_MESSAGE)
5539 .actions_slot(
5540 h_flex()
5541 .gap_0p5()
5542 .child(self.upgrade_button(cx))
5543 .child(self.create_copy_button(ERROR_MESSAGE)),
5544 )
5545 .dismiss_action(self.dismiss_error_button(cx))
5546 }
5547
5548 fn render_authentication_required_error(
5549 &self,
5550 error: SharedString,
5551 cx: &mut Context<Self>,
5552 ) -> Callout {
5553 Callout::new()
5554 .severity(Severity::Error)
5555 .title("Authentication Required")
5556 .icon(IconName::XCircle)
5557 .description(error.clone())
5558 .actions_slot(
5559 h_flex()
5560 .gap_0p5()
5561 .child(self.authenticate_button(cx))
5562 .child(self.create_copy_button(error)),
5563 )
5564 .dismiss_action(self.dismiss_error_button(cx))
5565 }
5566
5567 fn render_model_request_limit_reached_error(
5568 &self,
5569 plan: cloud_llm_client::Plan,
5570 cx: &mut Context<Self>,
5571 ) -> Callout {
5572 let error_message = match plan {
5573 cloud_llm_client::Plan::V1(PlanV1::ZedPro) => {
5574 "Upgrade to usage-based billing for more prompts."
5575 }
5576 cloud_llm_client::Plan::V1(PlanV1::ZedProTrial)
5577 | cloud_llm_client::Plan::V1(PlanV1::ZedFree) => "Upgrade to Zed Pro for more prompts.",
5578 cloud_llm_client::Plan::V2(_) => "",
5579 };
5580
5581 Callout::new()
5582 .severity(Severity::Error)
5583 .title("Model Prompt Limit Reached")
5584 .icon(IconName::XCircle)
5585 .description(error_message)
5586 .actions_slot(
5587 h_flex()
5588 .gap_0p5()
5589 .child(self.upgrade_button(cx))
5590 .child(self.create_copy_button(error_message)),
5591 )
5592 .dismiss_action(self.dismiss_error_button(cx))
5593 }
5594
5595 fn render_tool_use_limit_reached_error(&self, cx: &mut Context<Self>) -> Option<Callout> {
5596 let thread = self.as_native_thread(cx)?;
5597 let supports_burn_mode = thread
5598 .read(cx)
5599 .model()
5600 .is_some_and(|model| model.supports_burn_mode());
5601
5602 let focus_handle = self.focus_handle(cx);
5603
5604 Some(
5605 Callout::new()
5606 .icon(IconName::Info)
5607 .title("Consecutive tool use limit reached.")
5608 .actions_slot(
5609 h_flex()
5610 .gap_0p5()
5611 .when(supports_burn_mode, |this| {
5612 this.child(
5613 Button::new("continue-burn-mode", "Continue with Burn Mode")
5614 .style(ButtonStyle::Filled)
5615 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5616 .layer(ElevationIndex::ModalSurface)
5617 .label_size(LabelSize::Small)
5618 .key_binding(
5619 KeyBinding::for_action_in(
5620 &ContinueWithBurnMode,
5621 &focus_handle,
5622 cx,
5623 )
5624 .map(|kb| kb.size(rems_from_px(10.))),
5625 )
5626 .tooltip(Tooltip::text(
5627 "Enable Burn Mode for unlimited tool use.",
5628 ))
5629 .on_click({
5630 cx.listener(move |this, _, _window, cx| {
5631 thread.update(cx, |thread, cx| {
5632 thread
5633 .set_completion_mode(CompletionMode::Burn, cx);
5634 });
5635 this.resume_chat(cx);
5636 })
5637 }),
5638 )
5639 })
5640 .child(
5641 Button::new("continue-conversation", "Continue")
5642 .layer(ElevationIndex::ModalSurface)
5643 .label_size(LabelSize::Small)
5644 .key_binding(
5645 KeyBinding::for_action_in(&ContinueThread, &focus_handle, cx)
5646 .map(|kb| kb.size(rems_from_px(10.))),
5647 )
5648 .on_click(cx.listener(|this, _, _window, cx| {
5649 this.resume_chat(cx);
5650 })),
5651 ),
5652 ),
5653 )
5654 }
5655
5656 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
5657 let message = message.into();
5658
5659 IconButton::new("copy", IconName::Copy)
5660 .icon_size(IconSize::Small)
5661 .tooltip(Tooltip::text("Copy Error Message"))
5662 .on_click(move |_, _, cx| {
5663 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
5664 })
5665 }
5666
5667 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5668 IconButton::new("dismiss", IconName::Close)
5669 .icon_size(IconSize::Small)
5670 .tooltip(Tooltip::text("Dismiss Error"))
5671 .on_click(cx.listener({
5672 move |this, _, _, cx| {
5673 this.clear_thread_error(cx);
5674 cx.notify();
5675 }
5676 }))
5677 }
5678
5679 fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5680 Button::new("authenticate", "Authenticate")
5681 .label_size(LabelSize::Small)
5682 .style(ButtonStyle::Filled)
5683 .on_click(cx.listener({
5684 move |this, _, window, cx| {
5685 let agent = this.agent.clone();
5686 let ThreadState::Ready { thread, .. } = &this.thread_state else {
5687 return;
5688 };
5689
5690 let connection = thread.read(cx).connection().clone();
5691 let err = AuthRequired {
5692 description: None,
5693 provider_id: None,
5694 };
5695 this.clear_thread_error(cx);
5696 let this = cx.weak_entity();
5697 window.defer(cx, |window, cx| {
5698 Self::handle_auth_required(this, err, agent, connection, window, cx);
5699 })
5700 }
5701 }))
5702 }
5703
5704 pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5705 let agent = self.agent.clone();
5706 let ThreadState::Ready { thread, .. } = &self.thread_state else {
5707 return;
5708 };
5709
5710 let connection = thread.read(cx).connection().clone();
5711 let err = AuthRequired {
5712 description: None,
5713 provider_id: None,
5714 };
5715 self.clear_thread_error(cx);
5716 let this = cx.weak_entity();
5717 window.defer(cx, |window, cx| {
5718 Self::handle_auth_required(this, err, agent, connection, window, cx);
5719 })
5720 }
5721
5722 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5723 Button::new("upgrade", "Upgrade")
5724 .label_size(LabelSize::Small)
5725 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5726 .on_click(cx.listener({
5727 move |this, _, _, cx| {
5728 this.clear_thread_error(cx);
5729 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
5730 }
5731 }))
5732 }
5733
5734 pub fn delete_history_entry(&mut self, entry: HistoryEntry, cx: &mut Context<Self>) {
5735 let task = match entry {
5736 HistoryEntry::AcpThread(thread) => self.history_store.update(cx, |history, cx| {
5737 history.delete_thread(thread.id.clone(), cx)
5738 }),
5739 HistoryEntry::TextThread(text_thread) => {
5740 self.history_store.update(cx, |history, cx| {
5741 history.delete_text_thread(text_thread.path.clone(), cx)
5742 })
5743 }
5744 };
5745 task.detach_and_log_err(cx);
5746 }
5747
5748 /// Returns the currently active editor, either for a message that is being
5749 /// edited or the editor for a new message.
5750 fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
5751 if let Some(index) = self.editing_message
5752 && let Some(editor) = self
5753 .entry_view_state
5754 .read(cx)
5755 .entry(index)
5756 .and_then(|e| e.message_editor())
5757 .cloned()
5758 {
5759 editor
5760 } else {
5761 self.message_editor.clone()
5762 }
5763 }
5764}
5765
5766fn loading_contents_spinner(size: IconSize) -> AnyElement {
5767 Icon::new(IconName::LoadCircle)
5768 .size(size)
5769 .color(Color::Accent)
5770 .with_rotate_animation(3)
5771 .into_any_element()
5772}
5773
5774fn placeholder_text(agent_name: &str, has_commands: bool) -> String {
5775 if agent_name == "Zed Agent" {
5776 format!("Message the {} — @ to include context", agent_name)
5777 } else if has_commands {
5778 format!(
5779 "Message {} — @ to include context, / for commands",
5780 agent_name
5781 )
5782 } else {
5783 format!("Message {} — @ to include context", agent_name)
5784 }
5785}
5786
5787impl Focusable for AcpThreadView {
5788 fn focus_handle(&self, cx: &App) -> FocusHandle {
5789 match self.thread_state {
5790 ThreadState::Loading { .. } | ThreadState::Ready { .. } => {
5791 self.active_editor(cx).focus_handle(cx)
5792 }
5793 ThreadState::LoadError(_) | ThreadState::Unauthenticated { .. } => {
5794 self.focus_handle.clone()
5795 }
5796 }
5797 }
5798}
5799
5800impl Render for AcpThreadView {
5801 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5802 let has_messages = self.list_state.item_count() > 0;
5803 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
5804
5805 v_flex()
5806 .size_full()
5807 .key_context("AcpThread")
5808 .on_action(cx.listener(Self::toggle_burn_mode))
5809 .on_action(cx.listener(Self::keep_all))
5810 .on_action(cx.listener(Self::reject_all))
5811 .on_action(cx.listener(Self::allow_always))
5812 .on_action(cx.listener(Self::allow_once))
5813 .on_action(cx.listener(Self::reject_once))
5814 .track_focus(&self.focus_handle)
5815 .bg(cx.theme().colors().panel_background)
5816 .child(match &self.thread_state {
5817 ThreadState::Unauthenticated {
5818 connection,
5819 description,
5820 configuration_view,
5821 pending_auth_method,
5822 ..
5823 } => self
5824 .render_auth_required_state(
5825 connection,
5826 description.as_ref(),
5827 configuration_view.as_ref(),
5828 pending_auth_method.as_ref(),
5829 window,
5830 cx,
5831 )
5832 .into_any(),
5833 ThreadState::Loading { .. } => v_flex()
5834 .flex_1()
5835 .child(self.render_recent_history(cx))
5836 .into_any(),
5837 ThreadState::LoadError(e) => v_flex()
5838 .flex_1()
5839 .size_full()
5840 .items_center()
5841 .justify_end()
5842 .child(self.render_load_error(e, window, cx))
5843 .into_any(),
5844 ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
5845 if has_messages {
5846 this.child(
5847 list(
5848 self.list_state.clone(),
5849 cx.processor(|this, index: usize, window, cx| {
5850 let Some((entry, len)) = this.thread().and_then(|thread| {
5851 let entries = &thread.read(cx).entries();
5852 Some((entries.get(index)?, entries.len()))
5853 }) else {
5854 return Empty.into_any();
5855 };
5856 this.render_entry(index, len, entry, window, cx)
5857 }),
5858 )
5859 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
5860 .flex_grow()
5861 .into_any(),
5862 )
5863 .vertical_scrollbar_for(self.list_state.clone(), window, cx)
5864 .into_any()
5865 } else {
5866 this.child(self.render_recent_history(cx)).into_any()
5867 }
5868 }),
5869 })
5870 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
5871 // above so that the scrollbar doesn't render behind it. The current setup allows
5872 // the scrollbar to stop exactly at the activity bar start.
5873 .when(has_messages, |this| match &self.thread_state {
5874 ThreadState::Ready { thread, .. } => {
5875 this.children(self.render_activity_bar(thread, window, cx))
5876 }
5877 _ => this,
5878 })
5879 .children(self.render_thread_retry_status_callout(window, cx))
5880 .children({
5881 if cfg!(windows) && self.project.read(cx).is_local() {
5882 self.render_codex_windows_warning(cx)
5883 } else {
5884 None
5885 }
5886 })
5887 .children(self.render_thread_error(window, cx))
5888 .when_some(
5889 self.new_server_version_available.as_ref().filter(|_| {
5890 !has_messages || !matches!(self.thread_state, ThreadState::Ready { .. })
5891 }),
5892 |this, version| this.child(self.render_new_version_callout(&version, cx)),
5893 )
5894 .children(
5895 if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
5896 Some(usage_callout.into_any_element())
5897 } else {
5898 self.render_token_limit_callout(line_height, cx)
5899 .map(|token_limit_callout| token_limit_callout.into_any_element())
5900 },
5901 )
5902 .child(self.render_message_editor(window, cx))
5903 }
5904}
5905
5906fn default_markdown_style(
5907 buffer_font: bool,
5908 muted_text: bool,
5909 window: &Window,
5910 cx: &App,
5911) -> MarkdownStyle {
5912 let theme_settings = ThemeSettings::get_global(cx);
5913 let colors = cx.theme().colors();
5914
5915 let buffer_font_size = theme_settings.agent_buffer_font_size(cx);
5916
5917 let mut text_style = window.text_style();
5918 let line_height = buffer_font_size * 1.75;
5919
5920 let font_family = if buffer_font {
5921 theme_settings.buffer_font.family.clone()
5922 } else {
5923 theme_settings.ui_font.family.clone()
5924 };
5925
5926 let font_size = if buffer_font {
5927 theme_settings.agent_buffer_font_size(cx)
5928 } else {
5929 theme_settings.agent_ui_font_size(cx)
5930 };
5931
5932 let text_color = if muted_text {
5933 colors.text_muted
5934 } else {
5935 colors.text
5936 };
5937
5938 text_style.refine(&TextStyleRefinement {
5939 font_family: Some(font_family),
5940 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
5941 font_features: Some(theme_settings.ui_font.features.clone()),
5942 font_size: Some(font_size.into()),
5943 line_height: Some(line_height.into()),
5944 color: Some(text_color),
5945 ..Default::default()
5946 });
5947
5948 MarkdownStyle {
5949 base_text_style: text_style.clone(),
5950 syntax: cx.theme().syntax().clone(),
5951 selection_background_color: colors.element_selection_background,
5952 code_block_overflow_x_scroll: true,
5953 heading_level_styles: Some(HeadingLevelStyles {
5954 h1: Some(TextStyleRefinement {
5955 font_size: Some(rems(1.15).into()),
5956 ..Default::default()
5957 }),
5958 h2: Some(TextStyleRefinement {
5959 font_size: Some(rems(1.1).into()),
5960 ..Default::default()
5961 }),
5962 h3: Some(TextStyleRefinement {
5963 font_size: Some(rems(1.05).into()),
5964 ..Default::default()
5965 }),
5966 h4: Some(TextStyleRefinement {
5967 font_size: Some(rems(1.).into()),
5968 ..Default::default()
5969 }),
5970 h5: Some(TextStyleRefinement {
5971 font_size: Some(rems(0.95).into()),
5972 ..Default::default()
5973 }),
5974 h6: Some(TextStyleRefinement {
5975 font_size: Some(rems(0.875).into()),
5976 ..Default::default()
5977 }),
5978 }),
5979 code_block: StyleRefinement {
5980 padding: EdgesRefinement {
5981 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5982 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5983 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5984 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5985 },
5986 margin: EdgesRefinement {
5987 top: Some(Length::Definite(px(8.).into())),
5988 left: Some(Length::Definite(px(0.).into())),
5989 right: Some(Length::Definite(px(0.).into())),
5990 bottom: Some(Length::Definite(px(12.).into())),
5991 },
5992 border_style: Some(BorderStyle::Solid),
5993 border_widths: EdgesRefinement {
5994 top: Some(AbsoluteLength::Pixels(px(1.))),
5995 left: Some(AbsoluteLength::Pixels(px(1.))),
5996 right: Some(AbsoluteLength::Pixels(px(1.))),
5997 bottom: Some(AbsoluteLength::Pixels(px(1.))),
5998 },
5999 border_color: Some(colors.border_variant),
6000 background: Some(colors.editor_background.into()),
6001 text: Some(TextStyleRefinement {
6002 font_family: Some(theme_settings.buffer_font.family.clone()),
6003 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
6004 font_features: Some(theme_settings.buffer_font.features.clone()),
6005 font_size: Some(buffer_font_size.into()),
6006 ..Default::default()
6007 }),
6008 ..Default::default()
6009 },
6010 inline_code: TextStyleRefinement {
6011 font_family: Some(theme_settings.buffer_font.family.clone()),
6012 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
6013 font_features: Some(theme_settings.buffer_font.features.clone()),
6014 font_size: Some(buffer_font_size.into()),
6015 background_color: Some(colors.editor_foreground.opacity(0.08)),
6016 ..Default::default()
6017 },
6018 link: TextStyleRefinement {
6019 background_color: Some(colors.editor_foreground.opacity(0.025)),
6020 color: Some(colors.text_accent),
6021 underline: Some(UnderlineStyle {
6022 color: Some(colors.text_accent.opacity(0.5)),
6023 thickness: px(1.),
6024 ..Default::default()
6025 }),
6026 ..Default::default()
6027 },
6028 ..Default::default()
6029 }
6030}
6031
6032fn plan_label_markdown_style(
6033 status: &acp::PlanEntryStatus,
6034 window: &Window,
6035 cx: &App,
6036) -> MarkdownStyle {
6037 let default_md_style = default_markdown_style(false, false, window, cx);
6038
6039 MarkdownStyle {
6040 base_text_style: TextStyle {
6041 color: cx.theme().colors().text_muted,
6042 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
6043 Some(gpui::StrikethroughStyle {
6044 thickness: px(1.),
6045 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
6046 })
6047 } else {
6048 None
6049 },
6050 ..default_md_style.base_text_style
6051 },
6052 ..default_md_style
6053 }
6054}
6055
6056fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
6057 let default_md_style = default_markdown_style(true, false, window, cx);
6058
6059 MarkdownStyle {
6060 base_text_style: TextStyle {
6061 ..default_md_style.base_text_style
6062 },
6063 selection_background_color: cx.theme().colors().element_selection_background,
6064 ..Default::default()
6065 }
6066}
6067
6068#[cfg(test)]
6069pub(crate) mod tests {
6070 use acp_thread::StubAgentConnection;
6071 use agent_client_protocol::SessionId;
6072 use assistant_text_thread::TextThreadStore;
6073 use editor::MultiBufferOffset;
6074 use fs::FakeFs;
6075 use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
6076 use project::Project;
6077 use serde_json::json;
6078 use settings::SettingsStore;
6079 use std::any::Any;
6080 use std::path::Path;
6081 use workspace::Item;
6082
6083 use super::*;
6084
6085 #[gpui::test]
6086 async fn test_drop(cx: &mut TestAppContext) {
6087 init_test(cx);
6088
6089 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6090 let weak_view = thread_view.downgrade();
6091 drop(thread_view);
6092 assert!(!weak_view.is_upgradable());
6093 }
6094
6095 #[gpui::test]
6096 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
6097 init_test(cx);
6098
6099 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6100
6101 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6102 message_editor.update_in(cx, |editor, window, cx| {
6103 editor.set_text("Hello", window, cx);
6104 });
6105
6106 cx.deactivate_window();
6107
6108 thread_view.update_in(cx, |thread_view, window, cx| {
6109 thread_view.send(window, cx);
6110 });
6111
6112 cx.run_until_parked();
6113
6114 assert!(
6115 cx.windows()
6116 .iter()
6117 .any(|window| window.downcast::<AgentNotification>().is_some())
6118 );
6119 }
6120
6121 #[gpui::test]
6122 async fn test_notification_for_error(cx: &mut TestAppContext) {
6123 init_test(cx);
6124
6125 let (thread_view, cx) =
6126 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
6127
6128 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6129 message_editor.update_in(cx, |editor, window, cx| {
6130 editor.set_text("Hello", window, cx);
6131 });
6132
6133 cx.deactivate_window();
6134
6135 thread_view.update_in(cx, |thread_view, window, cx| {
6136 thread_view.send(window, cx);
6137 });
6138
6139 cx.run_until_parked();
6140
6141 assert!(
6142 cx.windows()
6143 .iter()
6144 .any(|window| window.downcast::<AgentNotification>().is_some())
6145 );
6146 }
6147
6148 #[gpui::test]
6149 async fn test_refusal_handling(cx: &mut TestAppContext) {
6150 init_test(cx);
6151
6152 let (thread_view, cx) =
6153 setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
6154
6155 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6156 message_editor.update_in(cx, |editor, window, cx| {
6157 editor.set_text("Do something harmful", window, cx);
6158 });
6159
6160 thread_view.update_in(cx, |thread_view, window, cx| {
6161 thread_view.send(window, cx);
6162 });
6163
6164 cx.run_until_parked();
6165
6166 // Check that the refusal error is set
6167 thread_view.read_with(cx, |thread_view, _cx| {
6168 assert!(
6169 matches!(thread_view.thread_error, Some(ThreadError::Refusal)),
6170 "Expected refusal error to be set"
6171 );
6172 });
6173 }
6174
6175 #[gpui::test]
6176 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
6177 init_test(cx);
6178
6179 let tool_call_id = acp::ToolCallId("1".into());
6180 let tool_call = acp::ToolCall {
6181 id: tool_call_id.clone(),
6182 title: "Label".into(),
6183 kind: acp::ToolKind::Edit,
6184 status: acp::ToolCallStatus::Pending,
6185 content: vec!["hi".into()],
6186 locations: vec![],
6187 raw_input: None,
6188 raw_output: None,
6189 meta: None,
6190 };
6191 let connection =
6192 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
6193 tool_call_id,
6194 vec![acp::PermissionOption {
6195 id: acp::PermissionOptionId("1".into()),
6196 name: "Allow".into(),
6197 kind: acp::PermissionOptionKind::AllowOnce,
6198 meta: None,
6199 }],
6200 )]));
6201
6202 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
6203
6204 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6205
6206 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6207 message_editor.update_in(cx, |editor, window, cx| {
6208 editor.set_text("Hello", window, cx);
6209 });
6210
6211 cx.deactivate_window();
6212
6213 thread_view.update_in(cx, |thread_view, window, cx| {
6214 thread_view.send(window, cx);
6215 });
6216
6217 cx.run_until_parked();
6218
6219 assert!(
6220 cx.windows()
6221 .iter()
6222 .any(|window| window.downcast::<AgentNotification>().is_some())
6223 );
6224 }
6225
6226 #[gpui::test]
6227 async fn test_notification_when_panel_hidden(cx: &mut TestAppContext) {
6228 init_test(cx);
6229
6230 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6231
6232 add_to_workspace(thread_view.clone(), cx);
6233
6234 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6235
6236 message_editor.update_in(cx, |editor, window, cx| {
6237 editor.set_text("Hello", window, cx);
6238 });
6239
6240 // Window is active (don't deactivate), but panel will be hidden
6241 // Note: In the test environment, the panel is not actually added to the dock,
6242 // so is_agent_panel_hidden will return true
6243
6244 thread_view.update_in(cx, |thread_view, window, cx| {
6245 thread_view.send(window, cx);
6246 });
6247
6248 cx.run_until_parked();
6249
6250 // Should show notification because window is active but panel is hidden
6251 assert!(
6252 cx.windows()
6253 .iter()
6254 .any(|window| window.downcast::<AgentNotification>().is_some()),
6255 "Expected notification when panel is hidden"
6256 );
6257 }
6258
6259 #[gpui::test]
6260 async fn test_notification_still_works_when_window_inactive(cx: &mut TestAppContext) {
6261 init_test(cx);
6262
6263 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6264
6265 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6266 message_editor.update_in(cx, |editor, window, cx| {
6267 editor.set_text("Hello", window, cx);
6268 });
6269
6270 // Deactivate window - should show notification regardless of setting
6271 cx.deactivate_window();
6272
6273 thread_view.update_in(cx, |thread_view, window, cx| {
6274 thread_view.send(window, cx);
6275 });
6276
6277 cx.run_until_parked();
6278
6279 // Should still show notification when window is inactive (existing behavior)
6280 assert!(
6281 cx.windows()
6282 .iter()
6283 .any(|window| window.downcast::<AgentNotification>().is_some()),
6284 "Expected notification when window is inactive"
6285 );
6286 }
6287
6288 #[gpui::test]
6289 async fn test_notification_respects_never_setting(cx: &mut TestAppContext) {
6290 init_test(cx);
6291
6292 // Set notify_when_agent_waiting to Never
6293 cx.update(|cx| {
6294 AgentSettings::override_global(
6295 AgentSettings {
6296 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
6297 ..AgentSettings::get_global(cx).clone()
6298 },
6299 cx,
6300 );
6301 });
6302
6303 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6304
6305 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6306 message_editor.update_in(cx, |editor, window, cx| {
6307 editor.set_text("Hello", window, cx);
6308 });
6309
6310 // Window is active
6311
6312 thread_view.update_in(cx, |thread_view, window, cx| {
6313 thread_view.send(window, cx);
6314 });
6315
6316 cx.run_until_parked();
6317
6318 // Should NOT show notification because notify_when_agent_waiting is Never
6319 assert!(
6320 !cx.windows()
6321 .iter()
6322 .any(|window| window.downcast::<AgentNotification>().is_some()),
6323 "Expected no notification when notify_when_agent_waiting is Never"
6324 );
6325 }
6326
6327 async fn setup_thread_view(
6328 agent: impl AgentServer + 'static,
6329 cx: &mut TestAppContext,
6330 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
6331 let fs = FakeFs::new(cx.executor());
6332 let project = Project::test(fs, [], cx).await;
6333 let (workspace, cx) =
6334 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6335
6336 let text_thread_store =
6337 cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
6338 let history_store =
6339 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(text_thread_store, cx)));
6340
6341 let thread_view = cx.update(|window, cx| {
6342 cx.new(|cx| {
6343 AcpThreadView::new(
6344 Rc::new(agent),
6345 None,
6346 None,
6347 workspace.downgrade(),
6348 project,
6349 history_store,
6350 None,
6351 window,
6352 cx,
6353 )
6354 })
6355 });
6356 cx.run_until_parked();
6357 (thread_view, cx)
6358 }
6359
6360 fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
6361 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
6362
6363 workspace
6364 .update_in(cx, |workspace, window, cx| {
6365 workspace.add_item_to_active_pane(
6366 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
6367 None,
6368 true,
6369 window,
6370 cx,
6371 );
6372 })
6373 .unwrap();
6374 }
6375
6376 struct ThreadViewItem(Entity<AcpThreadView>);
6377
6378 impl Item for ThreadViewItem {
6379 type Event = ();
6380
6381 fn include_in_nav_history() -> bool {
6382 false
6383 }
6384
6385 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
6386 "Test".into()
6387 }
6388 }
6389
6390 impl EventEmitter<()> for ThreadViewItem {}
6391
6392 impl Focusable for ThreadViewItem {
6393 fn focus_handle(&self, cx: &App) -> FocusHandle {
6394 self.0.read(cx).focus_handle(cx)
6395 }
6396 }
6397
6398 impl Render for ThreadViewItem {
6399 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
6400 self.0.clone().into_any_element()
6401 }
6402 }
6403
6404 struct StubAgentServer<C> {
6405 connection: C,
6406 }
6407
6408 impl<C> StubAgentServer<C> {
6409 fn new(connection: C) -> Self {
6410 Self { connection }
6411 }
6412 }
6413
6414 impl StubAgentServer<StubAgentConnection> {
6415 fn default_response() -> Self {
6416 let conn = StubAgentConnection::new();
6417 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6418 acp::ContentChunk {
6419 content: "Default response".into(),
6420 meta: None,
6421 },
6422 )]);
6423 Self::new(conn)
6424 }
6425 }
6426
6427 impl<C> AgentServer for StubAgentServer<C>
6428 where
6429 C: 'static + AgentConnection + Send + Clone,
6430 {
6431 fn telemetry_id(&self) -> &'static str {
6432 "test"
6433 }
6434
6435 fn logo(&self) -> ui::IconName {
6436 ui::IconName::Ai
6437 }
6438
6439 fn name(&self) -> SharedString {
6440 "Test".into()
6441 }
6442
6443 fn connect(
6444 &self,
6445 _root_dir: Option<&Path>,
6446 _delegate: AgentServerDelegate,
6447 _cx: &mut App,
6448 ) -> Task<gpui::Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
6449 Task::ready(Ok((Rc::new(self.connection.clone()), None)))
6450 }
6451
6452 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6453 self
6454 }
6455 }
6456
6457 #[derive(Clone)]
6458 struct SaboteurAgentConnection;
6459
6460 impl AgentConnection for SaboteurAgentConnection {
6461 fn telemetry_id(&self) -> &'static str {
6462 "saboteur"
6463 }
6464
6465 fn new_thread(
6466 self: Rc<Self>,
6467 project: Entity<Project>,
6468 _cwd: &Path,
6469 cx: &mut gpui::App,
6470 ) -> Task<gpui::Result<Entity<AcpThread>>> {
6471 Task::ready(Ok(cx.new(|cx| {
6472 let action_log = cx.new(|_| ActionLog::new(project.clone()));
6473 AcpThread::new(
6474 "SaboteurAgentConnection",
6475 self,
6476 project,
6477 action_log,
6478 SessionId("test".into()),
6479 watch::Receiver::constant(acp::PromptCapabilities {
6480 image: true,
6481 audio: true,
6482 embedded_context: true,
6483 meta: None,
6484 }),
6485 cx,
6486 )
6487 })))
6488 }
6489
6490 fn auth_methods(&self) -> &[acp::AuthMethod] {
6491 &[]
6492 }
6493
6494 fn authenticate(
6495 &self,
6496 _method_id: acp::AuthMethodId,
6497 _cx: &mut App,
6498 ) -> Task<gpui::Result<()>> {
6499 unimplemented!()
6500 }
6501
6502 fn prompt(
6503 &self,
6504 _id: Option<acp_thread::UserMessageId>,
6505 _params: acp::PromptRequest,
6506 _cx: &mut App,
6507 ) -> Task<gpui::Result<acp::PromptResponse>> {
6508 Task::ready(Err(anyhow::anyhow!("Error prompting")))
6509 }
6510
6511 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
6512 unimplemented!()
6513 }
6514
6515 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6516 self
6517 }
6518 }
6519
6520 /// Simulates a model which always returns a refusal response
6521 #[derive(Clone)]
6522 struct RefusalAgentConnection;
6523
6524 impl AgentConnection for RefusalAgentConnection {
6525 fn telemetry_id(&self) -> &'static str {
6526 "refusal"
6527 }
6528
6529 fn new_thread(
6530 self: Rc<Self>,
6531 project: Entity<Project>,
6532 _cwd: &Path,
6533 cx: &mut gpui::App,
6534 ) -> Task<gpui::Result<Entity<AcpThread>>> {
6535 Task::ready(Ok(cx.new(|cx| {
6536 let action_log = cx.new(|_| ActionLog::new(project.clone()));
6537 AcpThread::new(
6538 "RefusalAgentConnection",
6539 self,
6540 project,
6541 action_log,
6542 SessionId("test".into()),
6543 watch::Receiver::constant(acp::PromptCapabilities {
6544 image: true,
6545 audio: true,
6546 embedded_context: true,
6547 meta: None,
6548 }),
6549 cx,
6550 )
6551 })))
6552 }
6553
6554 fn auth_methods(&self) -> &[acp::AuthMethod] {
6555 &[]
6556 }
6557
6558 fn authenticate(
6559 &self,
6560 _method_id: acp::AuthMethodId,
6561 _cx: &mut App,
6562 ) -> Task<gpui::Result<()>> {
6563 unimplemented!()
6564 }
6565
6566 fn prompt(
6567 &self,
6568 _id: Option<acp_thread::UserMessageId>,
6569 _params: acp::PromptRequest,
6570 _cx: &mut App,
6571 ) -> Task<gpui::Result<acp::PromptResponse>> {
6572 Task::ready(Ok(acp::PromptResponse {
6573 stop_reason: acp::StopReason::Refusal,
6574 meta: None,
6575 }))
6576 }
6577
6578 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
6579 unimplemented!()
6580 }
6581
6582 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6583 self
6584 }
6585 }
6586
6587 pub(crate) fn init_test(cx: &mut TestAppContext) {
6588 cx.update(|cx| {
6589 let settings_store = SettingsStore::test(cx);
6590 cx.set_global(settings_store);
6591 theme::init(theme::LoadThemes::JustBase, cx);
6592 release_channel::init(SemanticVersion::default(), cx);
6593 prompt_store::init(cx)
6594 });
6595 }
6596
6597 #[gpui::test]
6598 async fn test_rewind_views(cx: &mut TestAppContext) {
6599 init_test(cx);
6600
6601 let fs = FakeFs::new(cx.executor());
6602 fs.insert_tree(
6603 "/project",
6604 json!({
6605 "test1.txt": "old content 1",
6606 "test2.txt": "old content 2"
6607 }),
6608 )
6609 .await;
6610 let project = Project::test(fs, [Path::new("/project")], cx).await;
6611 let (workspace, cx) =
6612 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6613
6614 let text_thread_store =
6615 cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
6616 let history_store =
6617 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(text_thread_store, cx)));
6618
6619 let connection = Rc::new(StubAgentConnection::new());
6620 let thread_view = cx.update(|window, cx| {
6621 cx.new(|cx| {
6622 AcpThreadView::new(
6623 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
6624 None,
6625 None,
6626 workspace.downgrade(),
6627 project.clone(),
6628 history_store.clone(),
6629 None,
6630 window,
6631 cx,
6632 )
6633 })
6634 });
6635
6636 cx.run_until_parked();
6637
6638 let thread = thread_view
6639 .read_with(cx, |view, _| view.thread().cloned())
6640 .unwrap();
6641
6642 // First user message
6643 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
6644 id: acp::ToolCallId("tool1".into()),
6645 title: "Edit file 1".into(),
6646 kind: acp::ToolKind::Edit,
6647 status: acp::ToolCallStatus::Completed,
6648 content: vec![acp::ToolCallContent::Diff {
6649 diff: acp::Diff {
6650 path: "/project/test1.txt".into(),
6651 old_text: Some("old content 1".into()),
6652 new_text: "new content 1".into(),
6653 meta: None,
6654 },
6655 }],
6656 locations: vec![],
6657 raw_input: None,
6658 raw_output: None,
6659 meta: None,
6660 })]);
6661
6662 thread
6663 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
6664 .await
6665 .unwrap();
6666 cx.run_until_parked();
6667
6668 thread.read_with(cx, |thread, _| {
6669 assert_eq!(thread.entries().len(), 2);
6670 });
6671
6672 thread_view.read_with(cx, |view, cx| {
6673 view.entry_view_state.read_with(cx, |entry_view_state, _| {
6674 assert!(
6675 entry_view_state
6676 .entry(0)
6677 .unwrap()
6678 .message_editor()
6679 .is_some()
6680 );
6681 assert!(entry_view_state.entry(1).unwrap().has_content());
6682 });
6683 });
6684
6685 // Second user message
6686 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
6687 id: acp::ToolCallId("tool2".into()),
6688 title: "Edit file 2".into(),
6689 kind: acp::ToolKind::Edit,
6690 status: acp::ToolCallStatus::Completed,
6691 content: vec![acp::ToolCallContent::Diff {
6692 diff: acp::Diff {
6693 path: "/project/test2.txt".into(),
6694 old_text: Some("old content 2".into()),
6695 new_text: "new content 2".into(),
6696 meta: None,
6697 },
6698 }],
6699 locations: vec![],
6700 raw_input: None,
6701 raw_output: None,
6702 meta: None,
6703 })]);
6704
6705 thread
6706 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
6707 .await
6708 .unwrap();
6709 cx.run_until_parked();
6710
6711 let second_user_message_id = thread.read_with(cx, |thread, _| {
6712 assert_eq!(thread.entries().len(), 4);
6713 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
6714 panic!();
6715 };
6716 user_message.id.clone().unwrap()
6717 });
6718
6719 thread_view.read_with(cx, |view, cx| {
6720 view.entry_view_state.read_with(cx, |entry_view_state, _| {
6721 assert!(
6722 entry_view_state
6723 .entry(0)
6724 .unwrap()
6725 .message_editor()
6726 .is_some()
6727 );
6728 assert!(entry_view_state.entry(1).unwrap().has_content());
6729 assert!(
6730 entry_view_state
6731 .entry(2)
6732 .unwrap()
6733 .message_editor()
6734 .is_some()
6735 );
6736 assert!(entry_view_state.entry(3).unwrap().has_content());
6737 });
6738 });
6739
6740 // Rewind to first message
6741 thread
6742 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
6743 .await
6744 .unwrap();
6745
6746 cx.run_until_parked();
6747
6748 thread.read_with(cx, |thread, _| {
6749 assert_eq!(thread.entries().len(), 2);
6750 });
6751
6752 thread_view.read_with(cx, |view, cx| {
6753 view.entry_view_state.read_with(cx, |entry_view_state, _| {
6754 assert!(
6755 entry_view_state
6756 .entry(0)
6757 .unwrap()
6758 .message_editor()
6759 .is_some()
6760 );
6761 assert!(entry_view_state.entry(1).unwrap().has_content());
6762
6763 // Old views should be dropped
6764 assert!(entry_view_state.entry(2).is_none());
6765 assert!(entry_view_state.entry(3).is_none());
6766 });
6767 });
6768 }
6769
6770 #[gpui::test]
6771 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
6772 init_test(cx);
6773
6774 let connection = StubAgentConnection::new();
6775
6776 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6777 acp::ContentChunk {
6778 content: acp::ContentBlock::Text(acp::TextContent {
6779 text: "Response".into(),
6780 annotations: None,
6781 meta: None,
6782 }),
6783 meta: None,
6784 },
6785 )]);
6786
6787 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6788 add_to_workspace(thread_view.clone(), cx);
6789
6790 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6791 message_editor.update_in(cx, |editor, window, cx| {
6792 editor.set_text("Original message to edit", window, cx);
6793 });
6794 thread_view.update_in(cx, |thread_view, window, cx| {
6795 thread_view.send(window, cx);
6796 });
6797
6798 cx.run_until_parked();
6799
6800 let user_message_editor = thread_view.read_with(cx, |view, cx| {
6801 assert_eq!(view.editing_message, None);
6802
6803 view.entry_view_state
6804 .read(cx)
6805 .entry(0)
6806 .unwrap()
6807 .message_editor()
6808 .unwrap()
6809 .clone()
6810 });
6811
6812 // Focus
6813 cx.focus(&user_message_editor);
6814 thread_view.read_with(cx, |view, _cx| {
6815 assert_eq!(view.editing_message, Some(0));
6816 });
6817
6818 // Edit
6819 user_message_editor.update_in(cx, |editor, window, cx| {
6820 editor.set_text("Edited message content", window, cx);
6821 });
6822
6823 // Cancel
6824 user_message_editor.update_in(cx, |_editor, window, cx| {
6825 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
6826 });
6827
6828 thread_view.read_with(cx, |view, _cx| {
6829 assert_eq!(view.editing_message, None);
6830 });
6831
6832 user_message_editor.read_with(cx, |editor, cx| {
6833 assert_eq!(editor.text(cx), "Original message to edit");
6834 });
6835 }
6836
6837 #[gpui::test]
6838 async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
6839 init_test(cx);
6840
6841 let connection = StubAgentConnection::new();
6842
6843 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6844 add_to_workspace(thread_view.clone(), cx);
6845
6846 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6847 let mut events = cx.events(&message_editor);
6848 message_editor.update_in(cx, |editor, window, cx| {
6849 editor.set_text("", window, cx);
6850 });
6851
6852 message_editor.update_in(cx, |_editor, window, cx| {
6853 window.dispatch_action(Box::new(Chat), cx);
6854 });
6855 cx.run_until_parked();
6856 // We shouldn't have received any messages
6857 assert!(matches!(
6858 events.try_next(),
6859 Err(futures::channel::mpsc::TryRecvError { .. })
6860 ));
6861 }
6862
6863 #[gpui::test]
6864 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
6865 init_test(cx);
6866
6867 let connection = StubAgentConnection::new();
6868
6869 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6870 acp::ContentChunk {
6871 content: acp::ContentBlock::Text(acp::TextContent {
6872 text: "Response".into(),
6873 annotations: None,
6874 meta: None,
6875 }),
6876 meta: None,
6877 },
6878 )]);
6879
6880 let (thread_view, cx) =
6881 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6882 add_to_workspace(thread_view.clone(), cx);
6883
6884 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6885 message_editor.update_in(cx, |editor, window, cx| {
6886 editor.set_text("Original message to edit", window, cx);
6887 });
6888 thread_view.update_in(cx, |thread_view, window, cx| {
6889 thread_view.send(window, cx);
6890 });
6891
6892 cx.run_until_parked();
6893
6894 let user_message_editor = thread_view.read_with(cx, |view, cx| {
6895 assert_eq!(view.editing_message, None);
6896 assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
6897
6898 view.entry_view_state
6899 .read(cx)
6900 .entry(0)
6901 .unwrap()
6902 .message_editor()
6903 .unwrap()
6904 .clone()
6905 });
6906
6907 // Focus
6908 cx.focus(&user_message_editor);
6909
6910 // Edit
6911 user_message_editor.update_in(cx, |editor, window, cx| {
6912 editor.set_text("Edited message content", window, cx);
6913 });
6914
6915 // Send
6916 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6917 acp::ContentChunk {
6918 content: acp::ContentBlock::Text(acp::TextContent {
6919 text: "New Response".into(),
6920 annotations: None,
6921 meta: None,
6922 }),
6923 meta: None,
6924 },
6925 )]);
6926
6927 user_message_editor.update_in(cx, |_editor, window, cx| {
6928 window.dispatch_action(Box::new(Chat), cx);
6929 });
6930
6931 cx.run_until_parked();
6932
6933 thread_view.read_with(cx, |view, cx| {
6934 assert_eq!(view.editing_message, None);
6935
6936 let entries = view.thread().unwrap().read(cx).entries();
6937 assert_eq!(entries.len(), 2);
6938 assert_eq!(
6939 entries[0].to_markdown(cx),
6940 "## User\n\nEdited message content\n\n"
6941 );
6942 assert_eq!(
6943 entries[1].to_markdown(cx),
6944 "## Assistant\n\nNew Response\n\n"
6945 );
6946
6947 let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
6948 assert!(!state.entry(1).unwrap().has_content());
6949 state.entry(0).unwrap().message_editor().unwrap().clone()
6950 });
6951
6952 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
6953 })
6954 }
6955
6956 #[gpui::test]
6957 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
6958 init_test(cx);
6959
6960 let connection = StubAgentConnection::new();
6961
6962 let (thread_view, cx) =
6963 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6964 add_to_workspace(thread_view.clone(), cx);
6965
6966 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6967 message_editor.update_in(cx, |editor, window, cx| {
6968 editor.set_text("Original message to edit", window, cx);
6969 });
6970 thread_view.update_in(cx, |thread_view, window, cx| {
6971 thread_view.send(window, cx);
6972 });
6973
6974 cx.run_until_parked();
6975
6976 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
6977 let thread = view.thread().unwrap().read(cx);
6978 assert_eq!(thread.entries().len(), 1);
6979
6980 let editor = view
6981 .entry_view_state
6982 .read(cx)
6983 .entry(0)
6984 .unwrap()
6985 .message_editor()
6986 .unwrap()
6987 .clone();
6988
6989 (editor, thread.session_id().clone())
6990 });
6991
6992 // Focus
6993 cx.focus(&user_message_editor);
6994
6995 thread_view.read_with(cx, |view, _cx| {
6996 assert_eq!(view.editing_message, Some(0));
6997 });
6998
6999 // Edit
7000 user_message_editor.update_in(cx, |editor, window, cx| {
7001 editor.set_text("Edited message content", window, cx);
7002 });
7003
7004 thread_view.read_with(cx, |view, _cx| {
7005 assert_eq!(view.editing_message, Some(0));
7006 });
7007
7008 // Finish streaming response
7009 cx.update(|_, cx| {
7010 connection.send_update(
7011 session_id.clone(),
7012 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
7013 content: acp::ContentBlock::Text(acp::TextContent {
7014 text: "Response".into(),
7015 annotations: None,
7016 meta: None,
7017 }),
7018 meta: None,
7019 }),
7020 cx,
7021 );
7022 connection.end_turn(session_id, acp::StopReason::EndTurn);
7023 });
7024
7025 thread_view.read_with(cx, |view, _cx| {
7026 assert_eq!(view.editing_message, Some(0));
7027 });
7028
7029 cx.run_until_parked();
7030
7031 // Should still be editing
7032 cx.update(|window, cx| {
7033 assert!(user_message_editor.focus_handle(cx).is_focused(window));
7034 assert_eq!(thread_view.read(cx).editing_message, Some(0));
7035 assert_eq!(
7036 user_message_editor.read(cx).text(cx),
7037 "Edited message content"
7038 );
7039 });
7040 }
7041
7042 #[gpui::test]
7043 async fn test_interrupt(cx: &mut TestAppContext) {
7044 init_test(cx);
7045
7046 let connection = StubAgentConnection::new();
7047
7048 let (thread_view, cx) =
7049 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
7050 add_to_workspace(thread_view.clone(), cx);
7051
7052 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7053 message_editor.update_in(cx, |editor, window, cx| {
7054 editor.set_text("Message 1", window, cx);
7055 });
7056 thread_view.update_in(cx, |thread_view, window, cx| {
7057 thread_view.send(window, cx);
7058 });
7059
7060 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
7061 let thread = view.thread().unwrap();
7062
7063 (thread.clone(), thread.read(cx).session_id().clone())
7064 });
7065
7066 cx.run_until_parked();
7067
7068 cx.update(|_, cx| {
7069 connection.send_update(
7070 session_id.clone(),
7071 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
7072 content: "Message 1 resp".into(),
7073 meta: None,
7074 }),
7075 cx,
7076 );
7077 });
7078
7079 cx.run_until_parked();
7080
7081 thread.read_with(cx, |thread, cx| {
7082 assert_eq!(
7083 thread.to_markdown(cx),
7084 indoc::indoc! {"
7085 ## User
7086
7087 Message 1
7088
7089 ## Assistant
7090
7091 Message 1 resp
7092
7093 "}
7094 )
7095 });
7096
7097 message_editor.update_in(cx, |editor, window, cx| {
7098 editor.set_text("Message 2", window, cx);
7099 });
7100 thread_view.update_in(cx, |thread_view, window, cx| {
7101 thread_view.send(window, cx);
7102 });
7103
7104 cx.update(|_, cx| {
7105 // Simulate a response sent after beginning to cancel
7106 connection.send_update(
7107 session_id.clone(),
7108 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
7109 content: "onse".into(),
7110 meta: None,
7111 }),
7112 cx,
7113 );
7114 });
7115
7116 cx.run_until_parked();
7117
7118 // Last Message 1 response should appear before Message 2
7119 thread.read_with(cx, |thread, cx| {
7120 assert_eq!(
7121 thread.to_markdown(cx),
7122 indoc::indoc! {"
7123 ## User
7124
7125 Message 1
7126
7127 ## Assistant
7128
7129 Message 1 response
7130
7131 ## User
7132
7133 Message 2
7134
7135 "}
7136 )
7137 });
7138
7139 cx.update(|_, cx| {
7140 connection.send_update(
7141 session_id.clone(),
7142 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
7143 content: "Message 2 response".into(),
7144 meta: None,
7145 }),
7146 cx,
7147 );
7148 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
7149 });
7150
7151 cx.run_until_parked();
7152
7153 thread.read_with(cx, |thread, cx| {
7154 assert_eq!(
7155 thread.to_markdown(cx),
7156 indoc::indoc! {"
7157 ## User
7158
7159 Message 1
7160
7161 ## Assistant
7162
7163 Message 1 response
7164
7165 ## User
7166
7167 Message 2
7168
7169 ## Assistant
7170
7171 Message 2 response
7172
7173 "}
7174 )
7175 });
7176 }
7177
7178 #[gpui::test]
7179 async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
7180 init_test(cx);
7181
7182 let connection = StubAgentConnection::new();
7183 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
7184 acp::ContentChunk {
7185 content: acp::ContentBlock::Text(acp::TextContent {
7186 text: "Response".into(),
7187 annotations: None,
7188 meta: None,
7189 }),
7190 meta: None,
7191 },
7192 )]);
7193
7194 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
7195 add_to_workspace(thread_view.clone(), cx);
7196
7197 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7198 message_editor.update_in(cx, |editor, window, cx| {
7199 editor.set_text("Original message to edit", window, cx)
7200 });
7201 thread_view.update_in(cx, |thread_view, window, cx| thread_view.send(window, cx));
7202 cx.run_until_parked();
7203
7204 let user_message_editor = thread_view.read_with(cx, |thread_view, cx| {
7205 thread_view
7206 .entry_view_state
7207 .read(cx)
7208 .entry(0)
7209 .expect("Should have at least one entry")
7210 .message_editor()
7211 .expect("Should have message editor")
7212 .clone()
7213 });
7214
7215 cx.focus(&user_message_editor);
7216 thread_view.read_with(cx, |thread_view, _cx| {
7217 assert_eq!(thread_view.editing_message, Some(0));
7218 });
7219
7220 // Ensure to edit the focused message before proceeding otherwise, since
7221 // its content is not different from what was sent, focus will be lost.
7222 user_message_editor.update_in(cx, |editor, window, cx| {
7223 editor.set_text("Original message to edit with ", window, cx)
7224 });
7225
7226 // Create a simple buffer with some text so we can create a selection
7227 // that will then be added to the message being edited.
7228 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
7229 (thread_view.workspace.clone(), thread_view.project.clone())
7230 });
7231 let buffer = project.update(cx, |project, cx| {
7232 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
7233 });
7234
7235 workspace
7236 .update_in(cx, |workspace, window, cx| {
7237 let editor = cx.new(|cx| {
7238 let mut editor =
7239 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
7240
7241 editor.change_selections(Default::default(), window, cx, |selections| {
7242 selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
7243 });
7244
7245 editor
7246 });
7247 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
7248 })
7249 .unwrap();
7250
7251 thread_view.update_in(cx, |thread_view, window, cx| {
7252 assert_eq!(thread_view.editing_message, Some(0));
7253 thread_view.insert_selections(window, cx);
7254 });
7255
7256 user_message_editor.read_with(cx, |editor, cx| {
7257 let text = editor.editor().read(cx).text(cx);
7258 let expected_text = String::from("Original message to edit with selection ");
7259
7260 assert_eq!(text, expected_text);
7261 });
7262 }
7263
7264 #[gpui::test]
7265 async fn test_insert_selections(cx: &mut TestAppContext) {
7266 init_test(cx);
7267
7268 let connection = StubAgentConnection::new();
7269 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
7270 acp::ContentChunk {
7271 content: acp::ContentBlock::Text(acp::TextContent {
7272 text: "Response".into(),
7273 annotations: None,
7274 meta: None,
7275 }),
7276 meta: None,
7277 },
7278 )]);
7279
7280 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
7281 add_to_workspace(thread_view.clone(), cx);
7282
7283 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7284 message_editor.update_in(cx, |editor, window, cx| {
7285 editor.set_text("Can you review this snippet ", window, cx)
7286 });
7287
7288 // Create a simple buffer with some text so we can create a selection
7289 // that will then be added to the message being edited.
7290 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
7291 (thread_view.workspace.clone(), thread_view.project.clone())
7292 });
7293 let buffer = project.update(cx, |project, cx| {
7294 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
7295 });
7296
7297 workspace
7298 .update_in(cx, |workspace, window, cx| {
7299 let editor = cx.new(|cx| {
7300 let mut editor =
7301 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
7302
7303 editor.change_selections(Default::default(), window, cx, |selections| {
7304 selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
7305 });
7306
7307 editor
7308 });
7309 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
7310 })
7311 .unwrap();
7312
7313 thread_view.update_in(cx, |thread_view, window, cx| {
7314 assert_eq!(thread_view.editing_message, None);
7315 thread_view.insert_selections(window, cx);
7316 });
7317
7318 thread_view.read_with(cx, |thread_view, cx| {
7319 let text = thread_view.message_editor.read(cx).text(cx);
7320 let expected_txt = String::from("Can you review this snippet selection ");
7321
7322 assert_eq!(text, expected_txt);
7323 })
7324 }
7325}