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