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