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