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