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