1use acp_thread::{
2 AcpThread, AcpThreadEvent, AgentSessionInfo, AgentSessionList, AgentSessionListRequest,
3 AgentThreadEntry, AssistantMessage, AssistantMessageChunk, AuthRequired, LoadError, MentionUri,
4 RetryStatus, ThreadStatus, 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, DiffStat, Disclosure,
52 Divider, DividerColor, ElevationIndex, KeyBinding, PopoverMenuHandle, SpinnerLabel, TintColor,
53 Tooltip, WithScrollbar, prelude::*, right_click_menu,
54};
55use util::defer;
56use util::{ResultExt, size::format_file_size, time::duration_alt_display};
57use workspace::{CollaboratorId, NewTerminal, Toast, Workspace, notifications::NotificationId};
58use zed_actions::agent::{Chat, ToggleModelSelector};
59use zed_actions::assistant::OpenRulesLibrary;
60
61use super::config_options::ConfigOptionsView;
62use super::entry_view_state::EntryViewState;
63use crate::acp::AcpModelSelectorPopover;
64use crate::acp::ModeSelector;
65use crate::acp::entry_view_state::{EntryViewEvent, ViewEvent};
66use crate::acp::message_editor::{MessageEditor, MessageEditorEvent};
67use crate::agent_diff::AgentDiff;
68use crate::profile_selector::{ProfileProvider, ProfileSelector};
69
70use crate::ui::{AgentNotification, AgentNotificationEvent, BurnModeTooltip, UsageCallout};
71use crate::{
72 AgentDiffPane, AgentPanel, AllowAlways, AllowOnce, ClearMessageQueue, ContinueThread,
73 ContinueWithBurnMode, CycleFavoriteModels, CycleModeSelector, ExpandMessageEditor, Follow,
74 KeepAll, NewThread, OpenAgentDiff, OpenHistory, QueueMessage, RejectAll, RejectOnce,
75 SendNextQueuedMessage, ToggleBurnMode, ToggleProfileSelector,
76};
77
78const STOPWATCH_THRESHOLD: Duration = Duration::from_secs(1);
79const TOKEN_THRESHOLD: u64 = 1;
80
81#[derive(Copy, Clone, Debug, PartialEq, Eq)]
82enum ThreadFeedback {
83 Positive,
84 Negative,
85}
86
87#[derive(Debug)]
88enum ThreadError {
89 PaymentRequired,
90 ModelRequestLimitReached(cloud_llm_client::Plan),
91 ToolUseLimitReached,
92 Refusal,
93 AuthenticationRequired(SharedString),
94 Other(SharedString),
95}
96
97impl ThreadError {
98 fn from_err(error: anyhow::Error, agent: &Rc<dyn AgentServer>) -> Self {
99 if error.is::<language_model::PaymentRequiredError>() {
100 Self::PaymentRequired
101 } else if error.is::<language_model::ToolUseLimitReachedError>() {
102 Self::ToolUseLimitReached
103 } else if let Some(error) =
104 error.downcast_ref::<language_model::ModelRequestLimitReachedError>()
105 {
106 Self::ModelRequestLimitReached(error.plan)
107 } else if let Some(acp_error) = error.downcast_ref::<acp::Error>()
108 && acp_error.code == acp::ErrorCode::AuthRequired
109 {
110 Self::AuthenticationRequired(acp_error.message.clone().into())
111 } else {
112 let string = format!("{:#}", error);
113 // TODO: we should have Gemini return better errors here.
114 if agent.clone().downcast::<agent_servers::Gemini>().is_some()
115 && string.contains("Could not load the default credentials")
116 || string.contains("API key not valid")
117 || string.contains("Request had invalid authentication credentials")
118 {
119 Self::AuthenticationRequired(string.into())
120 } else {
121 Self::Other(string.into())
122 }
123 }
124 }
125}
126
127impl ProfileProvider for Entity<agent::Thread> {
128 fn profile_id(&self, cx: &App) -> AgentProfileId {
129 self.read(cx).profile().clone()
130 }
131
132 fn set_profile(&self, profile_id: AgentProfileId, cx: &mut App) {
133 self.update(cx, |thread, cx| {
134 // Apply the profile and let the thread swap to its default model.
135 thread.set_profile(profile_id, cx);
136 });
137 }
138
139 fn profiles_supported(&self, cx: &App) -> bool {
140 self.read(cx)
141 .model()
142 .is_some_and(|model| model.supports_tools())
143 }
144}
145
146#[derive(Default)]
147struct ThreadFeedbackState {
148 feedback: Option<ThreadFeedback>,
149 comments_editor: Option<Entity<Editor>>,
150}
151
152impl ThreadFeedbackState {
153 pub fn submit(
154 &mut self,
155 thread: Entity<AcpThread>,
156 feedback: ThreadFeedback,
157 window: &mut Window,
158 cx: &mut App,
159 ) {
160 let Some(telemetry) = thread.read(cx).connection().telemetry() else {
161 return;
162 };
163
164 if self.feedback == Some(feedback) {
165 return;
166 }
167
168 self.feedback = Some(feedback);
169 match feedback {
170 ThreadFeedback::Positive => {
171 self.comments_editor = None;
172 }
173 ThreadFeedback::Negative => {
174 self.comments_editor = Some(Self::build_feedback_comments_editor(window, cx));
175 }
176 }
177 let session_id = thread.read(cx).session_id().clone();
178 let agent_telemetry_id = thread.read(cx).connection().telemetry_id();
179 let task = telemetry.thread_data(&session_id, cx);
180 let rating = match feedback {
181 ThreadFeedback::Positive => "positive",
182 ThreadFeedback::Negative => "negative",
183 };
184 cx.background_spawn(async move {
185 let thread = task.await?;
186 telemetry::event!(
187 "Agent Thread Rated",
188 agent = agent_telemetry_id,
189 session_id = session_id,
190 rating = rating,
191 thread = thread
192 );
193 anyhow::Ok(())
194 })
195 .detach_and_log_err(cx);
196 }
197
198 pub fn submit_comments(&mut self, thread: Entity<AcpThread>, cx: &mut App) {
199 let Some(telemetry) = thread.read(cx).connection().telemetry() else {
200 return;
201 };
202
203 let Some(comments) = self
204 .comments_editor
205 .as_ref()
206 .map(|editor| editor.read(cx).text(cx))
207 .filter(|text| !text.trim().is_empty())
208 else {
209 return;
210 };
211
212 self.comments_editor.take();
213
214 let session_id = thread.read(cx).session_id().clone();
215 let agent_telemetry_id = thread.read(cx).connection().telemetry_id();
216 let task = telemetry.thread_data(&session_id, cx);
217 cx.background_spawn(async move {
218 let thread = task.await?;
219 telemetry::event!(
220 "Agent Thread Feedback Comments",
221 agent = agent_telemetry_id,
222 session_id = session_id,
223 comments = comments,
224 thread = thread
225 );
226 anyhow::Ok(())
227 })
228 .detach_and_log_err(cx);
229 }
230
231 pub fn clear(&mut self) {
232 *self = Self::default()
233 }
234
235 pub fn dismiss_comments(&mut self) {
236 self.comments_editor.take();
237 }
238
239 fn build_feedback_comments_editor(window: &mut Window, cx: &mut App) -> Entity<Editor> {
240 let buffer = cx.new(|cx| {
241 let empty_string = String::new();
242 MultiBuffer::singleton(cx.new(|cx| Buffer::local(empty_string, cx)), cx)
243 });
244
245 let editor = cx.new(|cx| {
246 let mut editor = Editor::new(
247 editor::EditorMode::AutoHeight {
248 min_lines: 1,
249 max_lines: Some(4),
250 },
251 buffer,
252 None,
253 window,
254 cx,
255 );
256 editor.set_placeholder_text(
257 "What went wrong? Share your feedback so we can improve.",
258 window,
259 cx,
260 );
261 editor
262 });
263
264 editor.read(cx).focus_handle(cx).focus(window, cx);
265 editor
266 }
267}
268
269#[derive(Default, Clone, Copy)]
270struct DiffStats {
271 lines_added: u32,
272 lines_removed: u32,
273}
274
275impl DiffStats {
276 fn single_file(buffer: &Buffer, diff: &BufferDiff, cx: &App) -> Self {
277 let mut stats = DiffStats::default();
278 let diff_snapshot = diff.snapshot(cx);
279 let buffer_snapshot = buffer.snapshot();
280 let base_text = diff_snapshot.base_text();
281
282 for hunk in diff_snapshot.hunks(&buffer_snapshot) {
283 let added_rows = hunk.range.end.row.saturating_sub(hunk.range.start.row);
284 stats.lines_added += added_rows;
285
286 let base_start = hunk.diff_base_byte_range.start.to_point(base_text).row;
287 let base_end = hunk.diff_base_byte_range.end.to_point(base_text).row;
288 let removed_rows = base_end.saturating_sub(base_start);
289 stats.lines_removed += removed_rows;
290 }
291
292 stats
293 }
294
295 fn all_files(changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>, cx: &App) -> Self {
296 let mut total = DiffStats::default();
297 for (buffer, diff) in changed_buffers {
298 let stats = DiffStats::single_file(buffer.read(cx), diff.read(cx), cx);
299 total.lines_added += stats.lines_added;
300 total.lines_removed += stats.lines_removed;
301 }
302 total
303 }
304}
305
306pub struct AcpThreadView {
307 agent: Rc<dyn AgentServer>,
308 agent_server_store: Entity<AgentServerStore>,
309 workspace: WeakEntity<Workspace>,
310 project: Entity<Project>,
311 thread_state: ThreadState,
312 login: Option<task::SpawnInTerminal>,
313 session_list: Option<Rc<dyn AgentSessionList>>,
314 session_list_state: Rc<RefCell<Option<Rc<dyn AgentSessionList>>>>,
315 recent_history_entries: Vec<AgentSessionInfo>,
316 _recent_history_task: Task<()>,
317 _recent_history_watch_task: Option<Task<()>>,
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 prompt_capabilities: Rc<RefCell<PromptCapabilities>>,
344 available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
345 is_loading_contents: bool,
346 new_server_version_available: Option<SharedString>,
347 resume_thread_metadata: Option<AgentSessionInfo>,
348 _cancel_task: Option<Task<()>>,
349 _subscriptions: [Subscription; 5],
350 show_codex_windows_warning: bool,
351 in_flight_prompt: Option<Vec<acp::ContentBlock>>,
352 message_queue: Vec<QueuedMessage>,
353 skip_queue_processing_count: usize,
354 user_interrupted_generation: bool,
355 turn_tokens: Option<u64>,
356 last_turn_tokens: Option<u64>,
357 turn_started_at: Option<Instant>,
358 last_turn_duration: Option<Duration>,
359 turn_generation: usize,
360 _turn_timer_task: Option<Task<()>>,
361}
362
363struct QueuedMessage {
364 content: Vec<acp::ContentBlock>,
365 tracked_buffers: Vec<Entity<Buffer>>,
366}
367
368enum ThreadState {
369 Loading(Entity<LoadingView>),
370 Ready {
371 thread: Entity<AcpThread>,
372 title_editor: Option<Entity<Editor>>,
373 mode_selector: Option<Entity<ModeSelector>>,
374 _subscriptions: Vec<Subscription>,
375 },
376 LoadError(LoadError),
377 Unauthenticated {
378 connection: Rc<dyn AgentConnection>,
379 description: Option<Entity<Markdown>>,
380 configuration_view: Option<AnyView>,
381 pending_auth_method: Option<acp::AuthMethodId>,
382 _subscription: Option<Subscription>,
383 },
384}
385
386struct LoadingView {
387 title: SharedString,
388 _load_task: Task<()>,
389 _update_title_task: Task<anyhow::Result<()>>,
390}
391
392impl AcpThreadView {
393 pub fn new(
394 agent: Rc<dyn AgentServer>,
395 resume_thread: Option<AgentSessionInfo>,
396 summarize_thread: Option<AgentSessionInfo>,
397 workspace: WeakEntity<Workspace>,
398 project: Entity<Project>,
399 thread_store: Option<Entity<ThreadStore>>,
400 prompt_store: Option<Entity<PromptStore>>,
401 track_load_event: bool,
402 window: &mut Window,
403 cx: &mut Context<Self>,
404 ) -> Self {
405 let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
406 let available_commands = Rc::new(RefCell::new(vec![]));
407 let session_list_state = Rc::new(RefCell::new(None));
408
409 let agent_server_store = project.read(cx).agent_server_store().clone();
410 let agent_display_name = agent_server_store
411 .read(cx)
412 .agent_display_name(&ExternalAgentServerName(agent.name()))
413 .unwrap_or_else(|| agent.name());
414
415 let placeholder = placeholder_text(agent_display_name.as_ref(), false);
416
417 let message_editor = cx.new(|cx| {
418 let mut editor = MessageEditor::new(
419 workspace.clone(),
420 project.downgrade(),
421 thread_store.clone(),
422 session_list_state.clone(),
423 prompt_store.clone(),
424 prompt_capabilities.clone(),
425 available_commands.clone(),
426 agent.name(),
427 &placeholder,
428 editor::EditorMode::AutoHeight {
429 min_lines: AgentSettings::get_global(cx).message_editor_min_lines,
430 max_lines: Some(AgentSettings::get_global(cx).set_message_editor_max_lines()),
431 },
432 window,
433 cx,
434 );
435 if let Some(entry) = summarize_thread {
436 editor.insert_thread_summary(entry, window, cx);
437 }
438 editor
439 });
440
441 let list_state = ListState::new(0, gpui::ListAlignment::Bottom, px(2048.0));
442
443 let entry_view_state = cx.new(|_| {
444 EntryViewState::new(
445 workspace.clone(),
446 project.downgrade(),
447 thread_store.clone(),
448 session_list_state.clone(),
449 prompt_store.clone(),
450 prompt_capabilities.clone(),
451 available_commands.clone(),
452 agent.name(),
453 )
454 });
455
456 let subscriptions = [
457 cx.observe_global_in::<SettingsStore>(window, Self::agent_ui_font_size_changed),
458 cx.observe_global_in::<AgentFontSize>(window, Self::agent_ui_font_size_changed),
459 cx.subscribe_in(&message_editor, window, Self::handle_message_editor_event),
460 cx.subscribe_in(&entry_view_state, window, Self::handle_entry_view_event),
461 cx.subscribe_in(
462 &agent_server_store,
463 window,
464 Self::handle_agent_servers_updated,
465 ),
466 ];
467
468 cx.on_release(|this, cx| {
469 for window in this.notifications.drain(..) {
470 window
471 .update(cx, |_, window, _| {
472 window.remove_window();
473 })
474 .ok();
475 }
476 })
477 .detach();
478
479 let show_codex_windows_warning = cfg!(windows)
480 && project.read(cx).is_local()
481 && agent.clone().downcast::<agent_servers::Codex>().is_some();
482
483 Self {
484 agent: agent.clone(),
485 agent_server_store,
486 workspace: workspace.clone(),
487 project: project.clone(),
488 entry_view_state,
489 thread_state: Self::initial_state(
490 agent.clone(),
491 resume_thread.clone(),
492 workspace.clone(),
493 project.clone(),
494 track_load_event,
495 window,
496 cx,
497 ),
498 login: None,
499 message_editor,
500 model_selector: None,
501 config_options_view: None,
502 profile_selector: None,
503 notifications: Vec::new(),
504 notification_subscriptions: HashMap::default(),
505 list_state: list_state,
506 thread_retry_status: None,
507 thread_error: None,
508 thread_error_markdown: None,
509 token_limit_callout_dismissed: false,
510 thread_feedback: Default::default(),
511 auth_task: None,
512 expanded_tool_calls: HashSet::default(),
513 expanded_tool_call_raw_inputs: HashSet::default(),
514 expanded_thinking_blocks: HashSet::default(),
515 editing_message: None,
516 edits_expanded: false,
517 plan_expanded: false,
518 queue_expanded: true,
519 prompt_capabilities,
520 available_commands,
521 editor_expanded: false,
522 should_be_following: false,
523 session_list: None,
524 session_list_state,
525 recent_history_entries: Vec::new(),
526 _recent_history_task: Task::ready(()),
527 _recent_history_watch_task: None,
528 hovered_recent_history_item: None,
529 is_loading_contents: false,
530 _subscriptions: subscriptions,
531 _cancel_task: None,
532 focus_handle: cx.focus_handle(),
533 new_server_version_available: None,
534 resume_thread_metadata: resume_thread,
535 show_codex_windows_warning,
536 in_flight_prompt: None,
537 message_queue: Vec::new(),
538 skip_queue_processing_count: 0,
539 user_interrupted_generation: false,
540 turn_tokens: None,
541 last_turn_tokens: None,
542 turn_started_at: None,
543 last_turn_duration: None,
544 turn_generation: 0,
545 _turn_timer_task: None,
546 }
547 }
548
549 fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
550 self.thread_state = Self::initial_state(
551 self.agent.clone(),
552 self.resume_thread_metadata.clone(),
553 self.workspace.clone(),
554 self.project.clone(),
555 true,
556 window,
557 cx,
558 );
559 self.available_commands.replace(vec![]);
560 self.new_server_version_available.take();
561 self.message_queue.clear();
562 self.session_list = None;
563 *self.session_list_state.borrow_mut() = None;
564 self.recent_history_entries.clear();
565 self._recent_history_watch_task = None;
566 self._recent_history_task = Task::ready(());
567 self.turn_tokens = None;
568 self.last_turn_tokens = None;
569 self.turn_started_at = None;
570 self.last_turn_duration = None;
571 self._turn_timer_task = None;
572 cx.notify();
573 }
574
575 fn initial_state(
576 agent: Rc<dyn AgentServer>,
577 resume_thread: Option<AgentSessionInfo>,
578 workspace: WeakEntity<Workspace>,
579 project: Entity<Project>,
580 track_load_event: bool,
581 window: &mut Window,
582 cx: &mut Context<Self>,
583 ) -> ThreadState {
584 if project.read(cx).is_via_collab()
585 && agent.clone().downcast::<NativeAgentServer>().is_none()
586 {
587 return ThreadState::LoadError(LoadError::Other(
588 "External agents are not yet supported in shared projects.".into(),
589 ));
590 }
591 let mut worktrees = project.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
592 // Pick the first non-single-file worktree for the root directory if there are any,
593 // and otherwise the parent of a single-file worktree, falling back to $HOME if there are no visible worktrees.
594 worktrees.sort_by(|l, r| {
595 l.read(cx)
596 .is_single_file()
597 .cmp(&r.read(cx).is_single_file())
598 });
599 let root_dir = worktrees
600 .into_iter()
601 .filter_map(|worktree| {
602 if worktree.read(cx).is_single_file() {
603 Some(worktree.read(cx).abs_path().parent()?.into())
604 } else {
605 Some(worktree.read(cx).abs_path())
606 }
607 })
608 .next();
609 let (status_tx, mut status_rx) = watch::channel("Loading…".into());
610 let (new_version_available_tx, mut new_version_available_rx) = watch::channel(None);
611 let delegate = AgentServerDelegate::new(
612 project.read(cx).agent_server_store().clone(),
613 project.clone(),
614 Some(status_tx),
615 Some(new_version_available_tx),
616 );
617
618 let connect_task = agent.connect(root_dir.as_deref(), delegate, cx);
619 let load_task = cx.spawn_in(window, async move |this, cx| {
620 let connection = match connect_task.await {
621 Ok((connection, login)) => {
622 this.update(cx, |this, _| this.login = login).ok();
623 connection
624 }
625 Err(err) => {
626 this.update_in(cx, |this, window, cx| {
627 if err.downcast_ref::<LoadError>().is_some() {
628 this.handle_load_error(err, window, cx);
629 } else {
630 this.handle_thread_error(err, cx);
631 }
632 cx.notify();
633 })
634 .log_err();
635 return;
636 }
637 };
638
639 if track_load_event {
640 telemetry::event!("Agent Thread Started", agent = connection.telemetry_id());
641 }
642
643 let result = if let Some(native_agent) = connection
644 .clone()
645 .downcast::<agent::NativeAgentConnection>()
646 && let Some(resume) = resume_thread.clone()
647 {
648 cx.update(|_, cx| {
649 native_agent
650 .0
651 .update(cx, |agent, cx| agent.open_thread(resume.session_id, cx))
652 })
653 .log_err()
654 } else {
655 let root_dir = root_dir.unwrap_or(paths::home_dir().as_path().into());
656 cx.update(|_, cx| {
657 connection
658 .clone()
659 .new_thread(project.clone(), &root_dir, cx)
660 })
661 .log_err()
662 };
663
664 let Some(result) = result else {
665 return;
666 };
667
668 let result = match result.await {
669 Err(e) => match e.downcast::<acp_thread::AuthRequired>() {
670 Ok(err) => {
671 cx.update(|window, cx| {
672 Self::handle_auth_required(this, err, agent, connection, window, cx)
673 })
674 .log_err();
675 return;
676 }
677 Err(err) => Err(err),
678 },
679 Ok(thread) => Ok(thread),
680 };
681
682 this.update_in(cx, |this, window, cx| {
683 match result {
684 Ok(thread) => {
685 let action_log = thread.read(cx).action_log().clone();
686
687 this.prompt_capabilities
688 .replace(thread.read(cx).prompt_capabilities());
689
690 let count = thread.read(cx).entries().len();
691 this.entry_view_state.update(cx, |view_state, cx| {
692 for ix in 0..count {
693 view_state.sync_entry(ix, &thread, window, cx);
694 }
695 this.list_state.splice_focusable(
696 0..0,
697 (0..count).map(|ix| view_state.entry(ix)?.focus_handle(cx)),
698 );
699 });
700
701 AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
702
703 let connection = thread.read(cx).connection().clone();
704 let session_id = thread.read(cx).session_id().clone();
705 let session_list = connection.session_list(cx);
706 this.set_session_list(session_list, cx);
707
708 // Check for config options first
709 // Config options take precedence over legacy mode/model selectors
710 // (feature flag gating happens at the data layer)
711 let config_options_provider =
712 connection.session_config_options(&session_id, cx);
713
714 let mode_selector;
715 if let Some(config_options) = config_options_provider {
716 // Use config options - don't create mode_selector or model_selector
717 let agent_server = this.agent.clone();
718 let fs = this.project.read(cx).fs().clone();
719 this.config_options_view = Some(cx.new(|cx| {
720 ConfigOptionsView::new(config_options, agent_server, fs, window, cx)
721 }));
722 this.model_selector = None;
723 mode_selector = None;
724 } else {
725 // Fall back to legacy mode/model selectors
726 this.config_options_view = None;
727 this.model_selector =
728 connection.model_selector(&session_id).map(|selector| {
729 let agent_server = this.agent.clone();
730 let fs = this.project.read(cx).fs().clone();
731 cx.new(|cx| {
732 AcpModelSelectorPopover::new(
733 selector,
734 agent_server,
735 fs,
736 PopoverMenuHandle::default(),
737 this.focus_handle(cx),
738 window,
739 cx,
740 )
741 })
742 });
743
744 mode_selector =
745 connection
746 .session_modes(&session_id, cx)
747 .map(|session_modes| {
748 let fs = this.project.read(cx).fs().clone();
749 let focus_handle = this.focus_handle(cx);
750 cx.new(|_cx| {
751 ModeSelector::new(
752 session_modes,
753 this.agent.clone(),
754 fs,
755 focus_handle,
756 )
757 })
758 });
759 }
760
761 let mut subscriptions = vec![
762 cx.subscribe_in(&thread, window, Self::handle_thread_event),
763 cx.observe(&action_log, |_, _, cx| cx.notify()),
764 ];
765
766 let title_editor =
767 if thread.update(cx, |thread, cx| thread.can_set_title(cx)) {
768 let editor = cx.new(|cx| {
769 let mut editor = Editor::single_line(window, cx);
770 editor.set_text(thread.read(cx).title(), window, cx);
771 editor
772 });
773 subscriptions.push(cx.subscribe_in(
774 &editor,
775 window,
776 Self::handle_title_editor_event,
777 ));
778 Some(editor)
779 } else {
780 None
781 };
782
783 this.thread_state = ThreadState::Ready {
784 thread,
785 title_editor,
786 mode_selector,
787 _subscriptions: subscriptions,
788 };
789
790 this.profile_selector = this.as_native_thread(cx).map(|thread| {
791 cx.new(|cx| {
792 ProfileSelector::new(
793 <dyn Fs>::global(cx),
794 Arc::new(thread.clone()),
795 this.focus_handle(cx),
796 cx,
797 )
798 })
799 });
800
801 this.message_editor.focus_handle(cx).focus(window, cx);
802
803 cx.notify();
804 }
805 Err(err) => {
806 this.handle_load_error(err, window, cx);
807 }
808 };
809 })
810 .log_err();
811 });
812
813 cx.spawn(async move |this, cx| {
814 while let Ok(new_version) = new_version_available_rx.recv().await {
815 if let Some(new_version) = new_version {
816 this.update(cx, |this, cx| {
817 this.new_server_version_available = Some(new_version.into());
818 cx.notify();
819 })
820 .ok();
821 }
822 }
823 })
824 .detach();
825
826 let loading_view = cx.new(|cx| {
827 let update_title_task = cx.spawn(async move |this, cx| {
828 loop {
829 let status = status_rx.recv().await?;
830 this.update(cx, |this: &mut LoadingView, cx| {
831 this.title = status;
832 cx.notify();
833 })?;
834 }
835 });
836
837 LoadingView {
838 title: "Loading…".into(),
839 _load_task: load_task,
840 _update_title_task: update_title_task,
841 }
842 });
843
844 ThreadState::Loading(loading_view)
845 }
846
847 fn handle_auth_required(
848 this: WeakEntity<Self>,
849 err: AuthRequired,
850 agent: Rc<dyn AgentServer>,
851 connection: Rc<dyn AgentConnection>,
852 window: &mut Window,
853 cx: &mut App,
854 ) {
855 let agent_name = agent.name();
856 let (configuration_view, subscription) = if let Some(provider_id) = &err.provider_id {
857 let registry = LanguageModelRegistry::global(cx);
858
859 let sub = window.subscribe(®istry, cx, {
860 let provider_id = provider_id.clone();
861 let this = this.clone();
862 move |_, ev, window, cx| {
863 if let language_model::Event::ProviderStateChanged(updated_provider_id) = &ev
864 && &provider_id == updated_provider_id
865 && LanguageModelRegistry::global(cx)
866 .read(cx)
867 .provider(&provider_id)
868 .map_or(false, |provider| provider.is_authenticated(cx))
869 {
870 this.update(cx, |this, cx| {
871 this.reset(window, cx);
872 })
873 .ok();
874 }
875 }
876 });
877
878 let view = registry.read(cx).provider(&provider_id).map(|provider| {
879 provider.configuration_view(
880 language_model::ConfigurationViewTargetAgent::Other(agent_name.clone()),
881 window,
882 cx,
883 )
884 });
885
886 (view, Some(sub))
887 } else {
888 (None, None)
889 };
890
891 this.update(cx, |this, cx| {
892 this.thread_state = ThreadState::Unauthenticated {
893 pending_auth_method: None,
894 connection,
895 configuration_view,
896 description: err
897 .description
898 .map(|desc| cx.new(|cx| Markdown::new(desc.into(), None, None, cx))),
899 _subscription: subscription,
900 };
901 if this.message_editor.focus_handle(cx).is_focused(window) {
902 this.focus_handle.focus(window, cx)
903 }
904 cx.notify();
905 })
906 .ok();
907 }
908
909 fn handle_load_error(
910 &mut self,
911 err: anyhow::Error,
912 window: &mut Window,
913 cx: &mut Context<Self>,
914 ) {
915 if let Some(load_err) = err.downcast_ref::<LoadError>() {
916 self.thread_state = ThreadState::LoadError(load_err.clone());
917 } else {
918 self.thread_state =
919 ThreadState::LoadError(LoadError::Other(format!("{:#}", err).into()))
920 }
921 if self.message_editor.focus_handle(cx).is_focused(window) {
922 self.focus_handle.focus(window, cx)
923 }
924 cx.notify();
925 }
926
927 fn handle_agent_servers_updated(
928 &mut self,
929 _agent_server_store: &Entity<project::AgentServerStore>,
930 _event: &project::AgentServersUpdated,
931 window: &mut Window,
932 cx: &mut Context<Self>,
933 ) {
934 // If we're in a LoadError state OR have a thread_error set (which can happen
935 // when agent.connect() fails during loading), retry loading the thread.
936 // This handles the case where a thread is restored before authentication completes.
937 let should_retry =
938 matches!(&self.thread_state, ThreadState::LoadError(_)) || self.thread_error.is_some();
939
940 if should_retry {
941 self.thread_error = None;
942 self.thread_error_markdown = None;
943 self.reset(window, cx);
944 }
945 }
946
947 pub fn workspace(&self) -> &WeakEntity<Workspace> {
948 &self.workspace
949 }
950
951 pub fn thread(&self) -> Option<&Entity<AcpThread>> {
952 match &self.thread_state {
953 ThreadState::Ready { thread, .. } => Some(thread),
954 ThreadState::Unauthenticated { .. }
955 | ThreadState::Loading { .. }
956 | ThreadState::LoadError { .. } => None,
957 }
958 }
959
960 pub(crate) fn session_list(&self) -> Option<Rc<dyn AgentSessionList>> {
961 self.session_list.clone()
962 }
963
964 pub fn mode_selector(&self) -> Option<&Entity<ModeSelector>> {
965 match &self.thread_state {
966 ThreadState::Ready { mode_selector, .. } => mode_selector.as_ref(),
967 ThreadState::Unauthenticated { .. }
968 | ThreadState::Loading { .. }
969 | ThreadState::LoadError { .. } => None,
970 }
971 }
972
973 pub fn title(&self, cx: &App) -> SharedString {
974 match &self.thread_state {
975 ThreadState::Ready { .. } | ThreadState::Unauthenticated { .. } => "New Thread".into(),
976 ThreadState::Loading(loading_view) => loading_view.read(cx).title.clone(),
977 ThreadState::LoadError(error) => match error {
978 LoadError::Unsupported { .. } => format!("Upgrade {}", self.agent.name()).into(),
979 LoadError::FailedToInstall(_) => {
980 format!("Failed to Install {}", self.agent.name()).into()
981 }
982 LoadError::Exited { .. } => format!("{} Exited", self.agent.name()).into(),
983 LoadError::Other(_) => format!("Error Loading {}", self.agent.name()).into(),
984 },
985 }
986 }
987
988 pub fn title_editor(&self) -> Option<Entity<Editor>> {
989 if let ThreadState::Ready { title_editor, .. } = &self.thread_state {
990 title_editor.clone()
991 } else {
992 None
993 }
994 }
995
996 pub fn cancel_generation(&mut self, cx: &mut Context<Self>) {
997 self.thread_error.take();
998 self.thread_retry_status.take();
999
1000 if let Some(thread) = self.thread() {
1001 self._cancel_task = Some(thread.update(cx, |thread, cx| thread.cancel(cx)));
1002 }
1003 }
1004
1005 fn share_thread(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1006 let Some(thread) = self.as_native_thread(cx) else {
1007 return;
1008 };
1009
1010 let client = self.project.read(cx).client();
1011 let workspace = self.workspace.clone();
1012 let session_id = thread.read(cx).id().to_string();
1013
1014 let load_task = thread.read(cx).to_db(cx);
1015
1016 cx.spawn(async move |_this, cx| {
1017 let db_thread = load_task.await;
1018
1019 let shared_thread = SharedThread::from_db_thread(&db_thread);
1020 let thread_data = shared_thread.to_bytes()?;
1021 let title = shared_thread.title.to_string();
1022
1023 client
1024 .request(proto::ShareAgentThread {
1025 session_id: session_id.clone(),
1026 title,
1027 thread_data,
1028 })
1029 .await?;
1030
1031 let share_url = client::zed_urls::shared_agent_thread_url(&session_id);
1032
1033 cx.update(|cx| {
1034 if let Some(workspace) = workspace.upgrade() {
1035 workspace.update(cx, |workspace, cx| {
1036 struct ThreadSharedToast;
1037 workspace.show_toast(
1038 Toast::new(
1039 NotificationId::unique::<ThreadSharedToast>(),
1040 "Thread shared!",
1041 )
1042 .on_click(
1043 "Copy URL",
1044 move |_window, cx| {
1045 cx.write_to_clipboard(ClipboardItem::new_string(
1046 share_url.clone(),
1047 ));
1048 },
1049 ),
1050 cx,
1051 );
1052 });
1053 }
1054 });
1055
1056 anyhow::Ok(())
1057 })
1058 .detach_and_log_err(cx);
1059 }
1060
1061 fn sync_thread(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1062 if !self.is_imported_thread(cx) {
1063 return;
1064 }
1065
1066 let Some(thread) = self.as_native_thread(cx) else {
1067 return;
1068 };
1069 let Some(session_list) = self
1070 .session_list
1071 .clone()
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).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 let is_edit =
2913 matches!(tool_call.kind, acp::ToolKind::Edit) || tool_call.diffs().next().is_some();
2914
2915 let use_card_layout = needs_confirmation || is_edit || is_terminal_tool;
2916
2917 let has_image_content = tool_call.content.iter().any(|c| c.image().is_some());
2918 let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
2919 let is_open = needs_confirmation || self.expanded_tool_calls.contains(&tool_call.id);
2920
2921 let should_show_raw_input = !is_terminal_tool && !is_edit && !has_image_content;
2922
2923 let input_output_header = |label: SharedString| {
2924 Label::new(label)
2925 .size(LabelSize::XSmall)
2926 .color(Color::Muted)
2927 .buffer_font(cx)
2928 };
2929
2930 let tool_output_display = if is_open {
2931 match &tool_call.status {
2932 ToolCallStatus::WaitingForConfirmation { options, .. } => v_flex()
2933 .w_full()
2934 .children(
2935 tool_call
2936 .content
2937 .iter()
2938 .enumerate()
2939 .map(|(content_ix, content)| {
2940 div()
2941 .child(self.render_tool_call_content(
2942 entry_ix,
2943 content,
2944 content_ix,
2945 tool_call,
2946 use_card_layout,
2947 has_image_content,
2948 window,
2949 cx,
2950 ))
2951 .into_any_element()
2952 }),
2953 )
2954 .when(should_show_raw_input, |this| {
2955 let is_raw_input_expanded =
2956 self.expanded_tool_call_raw_inputs.contains(&tool_call.id);
2957
2958 let input_header = if is_raw_input_expanded {
2959 "Raw Input:"
2960 } else {
2961 "View Raw Input"
2962 };
2963
2964 this.child(
2965 v_flex()
2966 .p_2()
2967 .gap_1()
2968 .border_t_1()
2969 .border_color(self.tool_card_border_color(cx))
2970 .child(
2971 h_flex()
2972 .id("disclosure_container")
2973 .pl_0p5()
2974 .gap_1()
2975 .justify_between()
2976 .rounded_xs()
2977 .hover(|s| s.bg(cx.theme().colors().element_hover))
2978 .child(input_output_header(input_header.into()))
2979 .child(
2980 Disclosure::new(
2981 ("raw-input-disclosure", entry_ix),
2982 is_raw_input_expanded,
2983 )
2984 .opened_icon(IconName::ChevronUp)
2985 .closed_icon(IconName::ChevronDown),
2986 )
2987 .on_click(cx.listener({
2988 let id = tool_call.id.clone();
2989
2990 move |this: &mut Self, _, _, cx| {
2991 if this.expanded_tool_call_raw_inputs.contains(&id)
2992 {
2993 this.expanded_tool_call_raw_inputs.remove(&id);
2994 } else {
2995 this.expanded_tool_call_raw_inputs
2996 .insert(id.clone());
2997 }
2998 cx.notify();
2999 }
3000 })),
3001 )
3002 .when(is_raw_input_expanded, |this| {
3003 this.children(tool_call.raw_input_markdown.clone().map(
3004 |input| {
3005 self.render_markdown(
3006 input,
3007 default_markdown_style(false, false, window, cx),
3008 )
3009 },
3010 ))
3011 }),
3012 )
3013 })
3014 .child(self.render_permission_buttons(
3015 tool_call.kind,
3016 options,
3017 entry_ix,
3018 tool_call.id.clone(),
3019 cx,
3020 ))
3021 .into_any(),
3022 ToolCallStatus::Pending | ToolCallStatus::InProgress
3023 if is_edit
3024 && tool_call.content.is_empty()
3025 && self.as_native_connection(cx).is_some() =>
3026 {
3027 self.render_diff_loading(cx).into_any()
3028 }
3029 ToolCallStatus::Pending
3030 | ToolCallStatus::InProgress
3031 | ToolCallStatus::Completed
3032 | ToolCallStatus::Failed
3033 | ToolCallStatus::Canceled => {
3034 v_flex()
3035 .when(should_show_raw_input, |this| {
3036 this.mt_1p5().w_full().child(
3037 v_flex()
3038 .ml(rems(0.4))
3039 .px_3p5()
3040 .pb_1()
3041 .gap_1()
3042 .border_l_1()
3043 .border_color(self.tool_card_border_color(cx))
3044 .child(input_output_header("Raw Input:".into()))
3045 .children(tool_call.raw_input_markdown.clone().map(|input| {
3046 div().id(("tool-call-raw-input-markdown", entry_ix)).child(
3047 self.render_markdown(
3048 input,
3049 default_markdown_style(false, false, window, cx),
3050 ),
3051 )
3052 }))
3053 .child(input_output_header("Output:".into())),
3054 )
3055 })
3056 .children(tool_call.content.iter().enumerate().map(
3057 |(content_ix, content)| {
3058 div().id(("tool-call-output", entry_ix)).child(
3059 self.render_tool_call_content(
3060 entry_ix,
3061 content,
3062 content_ix,
3063 tool_call,
3064 use_card_layout,
3065 has_image_content,
3066 window,
3067 cx,
3068 ),
3069 )
3070 },
3071 ))
3072 .into_any()
3073 }
3074 ToolCallStatus::Rejected => Empty.into_any(),
3075 }
3076 .into()
3077 } else {
3078 None
3079 };
3080
3081 v_flex()
3082 .map(|this| {
3083 if use_card_layout {
3084 this.my_1p5()
3085 .rounded_md()
3086 .border_1()
3087 .border_color(self.tool_card_border_color(cx))
3088 .bg(cx.theme().colors().editor_background)
3089 .overflow_hidden()
3090 } else {
3091 this.my_1()
3092 }
3093 })
3094 .map(|this| {
3095 if has_location && !use_card_layout {
3096 this.ml_4()
3097 } else {
3098 this.ml_5()
3099 }
3100 })
3101 .mr_5()
3102 .map(|this| {
3103 if is_terminal_tool {
3104 this.child(
3105 v_flex()
3106 .p_1p5()
3107 .gap_0p5()
3108 .text_ui_sm(cx)
3109 .bg(self.tool_card_header_bg(cx))
3110 .child(
3111 Label::new("Run Command")
3112 .buffer_font(cx)
3113 .size(LabelSize::XSmall)
3114 .color(Color::Muted),
3115 )
3116 .child(
3117 MarkdownElement::new(
3118 tool_call.label.clone(),
3119 terminal_command_markdown_style(window, cx),
3120 )
3121 .code_block_renderer(
3122 markdown::CodeBlockRenderer::Default {
3123 copy_button: false,
3124 copy_button_on_hover: false,
3125 border: false,
3126 },
3127 )
3128 ),
3129 )
3130 } else {
3131 this.child(
3132 h_flex()
3133 .group(&card_header_id)
3134 .relative()
3135 .w_full()
3136 .gap_1()
3137 .justify_between()
3138 .when(use_card_layout, |this| {
3139 this.p_0p5()
3140 .rounded_t(rems_from_px(5.))
3141 .bg(self.tool_card_header_bg(cx))
3142 })
3143 .child(self.render_tool_call_label(
3144 entry_ix,
3145 tool_call,
3146 is_edit,
3147 use_card_layout,
3148 window,
3149 cx,
3150 ))
3151 .when(is_collapsible || failed_or_canceled, |this| {
3152 let is_cancelled_edit = is_edit
3153 && matches!(tool_call.status, ToolCallStatus::Canceled);
3154 let diff_for_discard =
3155 if is_cancelled_edit && cx.has_flag::<AgentV2FeatureFlag>() {
3156 tool_call.diffs().next().cloned()
3157 } else {
3158 None
3159 };
3160 this.child(
3161 h_flex()
3162 .px_1()
3163 .gap_1()
3164 .when_some(diff_for_discard, |this, diff| {
3165 this.child(
3166 Button::new(
3167 ("discard-partial-edit", entry_ix),
3168 "Discard",
3169 )
3170 .label_size(LabelSize::Small)
3171 .tooltip(Tooltip::text(
3172 "Discard partial edits and restore the original file content",
3173 ))
3174 .on_click(cx.listener(move |_this, _, _window, cx| {
3175 let diff_data = diff.read(cx);
3176 let base_text = diff_data.base_text().clone();
3177 let buffer = diff_data.buffer().clone();
3178 buffer.update(cx, |buffer, cx| {
3179 buffer.set_text(base_text.as_ref(), cx);
3180 });
3181 })),
3182 )
3183 })
3184 .when(is_collapsible, |this| {
3185 this.child(
3186 Disclosure::new(("expand-output", entry_ix), is_open)
3187 .opened_icon(IconName::ChevronUp)
3188 .closed_icon(IconName::ChevronDown)
3189 .visible_on_hover(&card_header_id)
3190 .on_click(cx.listener({
3191 let id = tool_call.id.clone();
3192 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
3193 if is_open {
3194 this.expanded_tool_calls.remove(&id);
3195 } else {
3196 this.expanded_tool_calls.insert(id.clone());
3197 }
3198 cx.notify();
3199 }
3200 })),
3201 )
3202 })
3203 .when(failed_or_canceled, |this| {
3204 if is_cancelled_edit {
3205 this.child(
3206 div()
3207 .id(("tool-call-status-icon", entry_ix))
3208 .child(
3209 Icon::new(IconName::Warning)
3210 .color(Color::Error)
3211 .size(IconSize::Small),
3212 )
3213 .tooltip(Tooltip::text("Edit Interrupted")),
3214 )
3215 } else {
3216 this.child(
3217 Icon::new(IconName::Close)
3218 .color(Color::Error)
3219 .size(IconSize::Small),
3220 )
3221 }
3222 }),
3223 )
3224 }),
3225 )
3226 }
3227 })
3228 .children(tool_output_display)
3229 }
3230
3231 fn render_tool_call_label(
3232 &self,
3233 entry_ix: usize,
3234 tool_call: &ToolCall,
3235 is_edit: bool,
3236 use_card_layout: bool,
3237 window: &Window,
3238 cx: &Context<Self>,
3239 ) -> Div {
3240 let has_location = tool_call.locations.len() == 1;
3241
3242 let tool_icon = if tool_call.kind == acp::ToolKind::Edit && has_location {
3243 FileIcons::get_icon(&tool_call.locations[0].path, cx)
3244 .map(Icon::from_path)
3245 .unwrap_or(Icon::new(IconName::ToolPencil))
3246 } else {
3247 Icon::new(match tool_call.kind {
3248 acp::ToolKind::Read => IconName::ToolSearch,
3249 acp::ToolKind::Edit => IconName::ToolPencil,
3250 acp::ToolKind::Delete => IconName::ToolDeleteFile,
3251 acp::ToolKind::Move => IconName::ArrowRightLeft,
3252 acp::ToolKind::Search => IconName::ToolSearch,
3253 acp::ToolKind::Execute => IconName::ToolTerminal,
3254 acp::ToolKind::Think => IconName::ToolThink,
3255 acp::ToolKind::Fetch => IconName::ToolWeb,
3256 acp::ToolKind::SwitchMode => IconName::ArrowRightLeft,
3257 acp::ToolKind::Other | _ => IconName::ToolHammer,
3258 })
3259 }
3260 .size(IconSize::Small)
3261 .color(Color::Muted);
3262
3263 let gradient_overlay = {
3264 div()
3265 .absolute()
3266 .top_0()
3267 .right_0()
3268 .w_12()
3269 .h_full()
3270 .map(|this| {
3271 if use_card_layout {
3272 this.bg(linear_gradient(
3273 90.,
3274 linear_color_stop(self.tool_card_header_bg(cx), 1.),
3275 linear_color_stop(self.tool_card_header_bg(cx).opacity(0.2), 0.),
3276 ))
3277 } else {
3278 this.bg(linear_gradient(
3279 90.,
3280 linear_color_stop(cx.theme().colors().panel_background, 1.),
3281 linear_color_stop(
3282 cx.theme().colors().panel_background.opacity(0.2),
3283 0.,
3284 ),
3285 ))
3286 }
3287 })
3288 };
3289
3290 h_flex()
3291 .relative()
3292 .w_full()
3293 .h(window.line_height() - px(2.))
3294 .text_size(self.tool_name_font_size())
3295 .gap_1p5()
3296 .when(has_location || use_card_layout, |this| this.px_1())
3297 .when(has_location, |this| {
3298 this.cursor(CursorStyle::PointingHand)
3299 .rounded(rems_from_px(3.)) // Concentric border radius
3300 .hover(|s| s.bg(cx.theme().colors().element_hover.opacity(0.5)))
3301 })
3302 .overflow_hidden()
3303 .child(tool_icon)
3304 .child(if has_location {
3305 h_flex()
3306 .id(("open-tool-call-location", entry_ix))
3307 .w_full()
3308 .map(|this| {
3309 if use_card_layout {
3310 this.text_color(cx.theme().colors().text)
3311 } else {
3312 this.text_color(cx.theme().colors().text_muted)
3313 }
3314 })
3315 .child(self.render_markdown(
3316 tool_call.label.clone(),
3317 MarkdownStyle {
3318 prevent_mouse_interaction: true,
3319 ..default_markdown_style(false, true, window, cx)
3320 },
3321 ))
3322 .tooltip(Tooltip::text("Go to File"))
3323 .on_click(cx.listener(move |this, _, window, cx| {
3324 this.open_tool_call_location(entry_ix, 0, window, cx);
3325 }))
3326 .into_any_element()
3327 } else {
3328 h_flex()
3329 .w_full()
3330 .child(self.render_markdown(
3331 tool_call.label.clone(),
3332 default_markdown_style(false, true, window, cx),
3333 ))
3334 .into_any()
3335 })
3336 .when(!is_edit, |this| this.child(gradient_overlay))
3337 }
3338
3339 fn render_tool_call_content(
3340 &self,
3341 entry_ix: usize,
3342 content: &ToolCallContent,
3343 context_ix: usize,
3344 tool_call: &ToolCall,
3345 card_layout: bool,
3346 is_image_tool_call: bool,
3347 window: &Window,
3348 cx: &Context<Self>,
3349 ) -> AnyElement {
3350 match content {
3351 ToolCallContent::ContentBlock(content) => {
3352 if let Some(resource_link) = content.resource_link() {
3353 self.render_resource_link(resource_link, cx)
3354 } else if let Some(markdown) = content.markdown() {
3355 self.render_markdown_output(
3356 markdown.clone(),
3357 tool_call.id.clone(),
3358 context_ix,
3359 card_layout,
3360 window,
3361 cx,
3362 )
3363 } else if let Some(image) = content.image() {
3364 let location = tool_call.locations.first().cloned();
3365 self.render_image_output(
3366 entry_ix,
3367 image.clone(),
3368 location,
3369 card_layout,
3370 is_image_tool_call,
3371 cx,
3372 )
3373 } else {
3374 Empty.into_any_element()
3375 }
3376 }
3377 ToolCallContent::Diff(diff) => self.render_diff_editor(entry_ix, diff, tool_call, cx),
3378 ToolCallContent::Terminal(terminal) => {
3379 self.render_terminal_tool_call(entry_ix, terminal, tool_call, window, cx)
3380 }
3381 ToolCallContent::SubagentThread(_thread) => {
3382 // The subagent's AcpThread entity stores the subagent's conversation
3383 // (messages, tool calls, etc.) but we don't render it here. The entity
3384 // is used for serialization (e.g., to_markdown) and data storage, not display.
3385 Empty.into_any_element()
3386 }
3387 }
3388 }
3389
3390 fn render_markdown_output(
3391 &self,
3392 markdown: Entity<Markdown>,
3393 tool_call_id: acp::ToolCallId,
3394 context_ix: usize,
3395 card_layout: bool,
3396 window: &Window,
3397 cx: &Context<Self>,
3398 ) -> AnyElement {
3399 let button_id = SharedString::from(format!("tool_output-{:?}", tool_call_id));
3400
3401 v_flex()
3402 .gap_2()
3403 .map(|this| {
3404 if card_layout {
3405 this.when(context_ix > 0, |this| {
3406 this.pt_2()
3407 .border_t_1()
3408 .border_color(self.tool_card_border_color(cx))
3409 })
3410 } else {
3411 this.ml(rems(0.4))
3412 .px_3p5()
3413 .border_l_1()
3414 .border_color(self.tool_card_border_color(cx))
3415 }
3416 })
3417 .text_xs()
3418 .text_color(cx.theme().colors().text_muted)
3419 .child(self.render_markdown(markdown, default_markdown_style(false, false, window, cx)))
3420 .when(!card_layout, |this| {
3421 this.child(
3422 IconButton::new(button_id, IconName::ChevronUp)
3423 .full_width()
3424 .style(ButtonStyle::Outlined)
3425 .icon_color(Color::Muted)
3426 .on_click(cx.listener({
3427 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
3428 this.expanded_tool_calls.remove(&tool_call_id);
3429 cx.notify();
3430 }
3431 })),
3432 )
3433 })
3434 .into_any_element()
3435 }
3436
3437 fn render_image_output(
3438 &self,
3439 entry_ix: usize,
3440 image: Arc<gpui::Image>,
3441 location: Option<acp::ToolCallLocation>,
3442 card_layout: bool,
3443 show_dimensions: bool,
3444 cx: &Context<Self>,
3445 ) -> AnyElement {
3446 let dimensions_label = if show_dimensions {
3447 let format_name = match image.format() {
3448 gpui::ImageFormat::Png => "PNG",
3449 gpui::ImageFormat::Jpeg => "JPEG",
3450 gpui::ImageFormat::Webp => "WebP",
3451 gpui::ImageFormat::Gif => "GIF",
3452 gpui::ImageFormat::Svg => "SVG",
3453 gpui::ImageFormat::Bmp => "BMP",
3454 gpui::ImageFormat::Tiff => "TIFF",
3455 gpui::ImageFormat::Ico => "ICO",
3456 };
3457 let dimensions = image::ImageReader::new(std::io::Cursor::new(image.bytes()))
3458 .with_guessed_format()
3459 .ok()
3460 .and_then(|reader| reader.into_dimensions().ok());
3461 dimensions.map(|(w, h)| format!("{}×{} {}", w, h, format_name))
3462 } else {
3463 None
3464 };
3465
3466 v_flex()
3467 .gap_2()
3468 .map(|this| {
3469 if card_layout {
3470 this
3471 } else {
3472 this.ml(rems(0.4))
3473 .px_3p5()
3474 .border_l_1()
3475 .border_color(self.tool_card_border_color(cx))
3476 }
3477 })
3478 .when(dimensions_label.is_some() || location.is_some(), |this| {
3479 this.child(
3480 h_flex()
3481 .w_full()
3482 .justify_between()
3483 .items_center()
3484 .children(dimensions_label.map(|label| {
3485 Label::new(label)
3486 .size(LabelSize::XSmall)
3487 .color(Color::Muted)
3488 .buffer_font(cx)
3489 }))
3490 .when_some(location, |this, _loc| {
3491 this.child(
3492 Button::new(("go-to-file", entry_ix), "Go to File")
3493 .label_size(LabelSize::Small)
3494 .on_click(cx.listener(move |this, _, window, cx| {
3495 this.open_tool_call_location(entry_ix, 0, window, cx);
3496 })),
3497 )
3498 }),
3499 )
3500 })
3501 .child(
3502 img(image)
3503 .max_w_96()
3504 .max_h_96()
3505 .object_fit(ObjectFit::ScaleDown),
3506 )
3507 .into_any_element()
3508 }
3509
3510 fn render_resource_link(
3511 &self,
3512 resource_link: &acp::ResourceLink,
3513 cx: &Context<Self>,
3514 ) -> AnyElement {
3515 let uri: SharedString = resource_link.uri.clone().into();
3516 let is_file = resource_link.uri.strip_prefix("file://");
3517
3518 let label: SharedString = if let Some(abs_path) = is_file {
3519 if let Some(project_path) = self
3520 .project
3521 .read(cx)
3522 .project_path_for_absolute_path(&Path::new(abs_path), cx)
3523 && let Some(worktree) = self
3524 .project
3525 .read(cx)
3526 .worktree_for_id(project_path.worktree_id, cx)
3527 {
3528 worktree
3529 .read(cx)
3530 .full_path(&project_path.path)
3531 .to_string_lossy()
3532 .to_string()
3533 .into()
3534 } else {
3535 abs_path.to_string().into()
3536 }
3537 } else {
3538 uri.clone()
3539 };
3540
3541 let button_id = SharedString::from(format!("item-{}", uri));
3542
3543 div()
3544 .ml(rems(0.4))
3545 .pl_2p5()
3546 .border_l_1()
3547 .border_color(self.tool_card_border_color(cx))
3548 .overflow_hidden()
3549 .child(
3550 Button::new(button_id, label)
3551 .label_size(LabelSize::Small)
3552 .color(Color::Muted)
3553 .truncate(true)
3554 .when(is_file.is_none(), |this| {
3555 this.icon(IconName::ArrowUpRight)
3556 .icon_size(IconSize::XSmall)
3557 .icon_color(Color::Muted)
3558 })
3559 .on_click(cx.listener({
3560 let workspace = self.workspace.clone();
3561 move |_, _, window, cx: &mut Context<Self>| {
3562 Self::open_link(uri.clone(), &workspace, window, cx);
3563 }
3564 })),
3565 )
3566 .into_any_element()
3567 }
3568
3569 fn render_permission_buttons(
3570 &self,
3571 kind: acp::ToolKind,
3572 options: &[acp::PermissionOption],
3573 entry_ix: usize,
3574 tool_call_id: acp::ToolCallId,
3575 cx: &Context<Self>,
3576 ) -> Div {
3577 let is_first = self.thread().is_some_and(|thread| {
3578 thread
3579 .read(cx)
3580 .first_tool_awaiting_confirmation()
3581 .is_some_and(|call| call.id == tool_call_id)
3582 });
3583 let mut seen_kinds: ArrayVec<acp::PermissionOptionKind, 3> = ArrayVec::new();
3584
3585 div()
3586 .p_1()
3587 .border_t_1()
3588 .border_color(self.tool_card_border_color(cx))
3589 .w_full()
3590 .map(|this| {
3591 if kind == acp::ToolKind::SwitchMode {
3592 this.v_flex()
3593 } else {
3594 this.h_flex().justify_end().flex_wrap()
3595 }
3596 })
3597 .gap_0p5()
3598 .children(options.iter().map(move |option| {
3599 let option_id = SharedString::from(option.option_id.0.clone());
3600 Button::new((option_id, entry_ix), option.name.clone())
3601 .map(|this| {
3602 let (this, action) = match option.kind {
3603 acp::PermissionOptionKind::AllowOnce => (
3604 this.icon(IconName::Check).icon_color(Color::Success),
3605 Some(&AllowOnce as &dyn Action),
3606 ),
3607 acp::PermissionOptionKind::AllowAlways => (
3608 this.icon(IconName::CheckDouble).icon_color(Color::Success),
3609 Some(&AllowAlways as &dyn Action),
3610 ),
3611 acp::PermissionOptionKind::RejectOnce => (
3612 this.icon(IconName::Close).icon_color(Color::Error),
3613 Some(&RejectOnce as &dyn Action),
3614 ),
3615 acp::PermissionOptionKind::RejectAlways | _ => {
3616 (this.icon(IconName::Close).icon_color(Color::Error), None)
3617 }
3618 };
3619
3620 let Some(action) = action else {
3621 return this;
3622 };
3623
3624 if !is_first || seen_kinds.contains(&option.kind) {
3625 return this;
3626 }
3627
3628 seen_kinds.push(option.kind);
3629
3630 this.key_binding(
3631 KeyBinding::for_action_in(action, &self.focus_handle, cx)
3632 .map(|kb| kb.size(rems_from_px(10.))),
3633 )
3634 })
3635 .icon_position(IconPosition::Start)
3636 .icon_size(IconSize::XSmall)
3637 .label_size(LabelSize::Small)
3638 .on_click(cx.listener({
3639 let tool_call_id = tool_call_id.clone();
3640 let option_id = option.option_id.clone();
3641 let option_kind = option.kind;
3642 move |this, _, window, cx| {
3643 this.authorize_tool_call(
3644 tool_call_id.clone(),
3645 option_id.clone(),
3646 option_kind,
3647 window,
3648 cx,
3649 );
3650 }
3651 }))
3652 }))
3653 }
3654
3655 fn render_diff_loading(&self, cx: &Context<Self>) -> AnyElement {
3656 let bar = |n: u64, width_class: &str| {
3657 let bg_color = cx.theme().colors().element_active;
3658 let base = h_flex().h_1().rounded_full();
3659
3660 let modified = match width_class {
3661 "w_4_5" => base.w_3_4(),
3662 "w_1_4" => base.w_1_4(),
3663 "w_2_4" => base.w_2_4(),
3664 "w_3_5" => base.w_3_5(),
3665 "w_2_5" => base.w_2_5(),
3666 _ => base.w_1_2(),
3667 };
3668
3669 modified.with_animation(
3670 ElementId::Integer(n),
3671 Animation::new(Duration::from_secs(2)).repeat(),
3672 move |tab, delta| {
3673 let delta = (delta - 0.15 * n as f32) / 0.7;
3674 let delta = 1.0 - (0.5 - delta).abs() * 2.;
3675 let delta = ease_in_out(delta.clamp(0., 1.));
3676 let delta = 0.1 + 0.9 * delta;
3677
3678 tab.bg(bg_color.opacity(delta))
3679 },
3680 )
3681 };
3682
3683 v_flex()
3684 .p_3()
3685 .gap_1()
3686 .rounded_b_md()
3687 .bg(cx.theme().colors().editor_background)
3688 .child(bar(0, "w_4_5"))
3689 .child(bar(1, "w_1_4"))
3690 .child(bar(2, "w_2_4"))
3691 .child(bar(3, "w_3_5"))
3692 .child(bar(4, "w_2_5"))
3693 .into_any_element()
3694 }
3695
3696 fn render_diff_editor(
3697 &self,
3698 entry_ix: usize,
3699 diff: &Entity<acp_thread::Diff>,
3700 tool_call: &ToolCall,
3701 cx: &Context<Self>,
3702 ) -> AnyElement {
3703 let tool_progress = matches!(
3704 &tool_call.status,
3705 ToolCallStatus::InProgress | ToolCallStatus::Pending
3706 );
3707
3708 v_flex()
3709 .h_full()
3710 .border_t_1()
3711 .border_color(self.tool_card_border_color(cx))
3712 .child(
3713 if let Some(entry) = self.entry_view_state.read(cx).entry(entry_ix)
3714 && let Some(editor) = entry.editor_for_diff(diff)
3715 && diff.read(cx).has_revealed_range(cx)
3716 {
3717 editor.into_any_element()
3718 } else if tool_progress && self.as_native_connection(cx).is_some() {
3719 self.render_diff_loading(cx)
3720 } else {
3721 Empty.into_any()
3722 },
3723 )
3724 .into_any()
3725 }
3726
3727 fn render_terminal_tool_call(
3728 &self,
3729 entry_ix: usize,
3730 terminal: &Entity<acp_thread::Terminal>,
3731 tool_call: &ToolCall,
3732 window: &Window,
3733 cx: &Context<Self>,
3734 ) -> AnyElement {
3735 let terminal_data = terminal.read(cx);
3736 let working_dir = terminal_data.working_dir();
3737 let command = terminal_data.command();
3738 let started_at = terminal_data.started_at();
3739
3740 let tool_failed = matches!(
3741 &tool_call.status,
3742 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed
3743 );
3744
3745 let output = terminal_data.output();
3746 let command_finished = output.is_some();
3747 let truncated_output =
3748 output.is_some_and(|output| output.original_content_len > output.content.len());
3749 let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
3750
3751 let command_failed = command_finished
3752 && output.is_some_and(|o| o.exit_status.is_some_and(|status| !status.success()));
3753
3754 let time_elapsed = if let Some(output) = output {
3755 output.ended_at.duration_since(started_at)
3756 } else {
3757 started_at.elapsed()
3758 };
3759
3760 let header_id =
3761 SharedString::from(format!("terminal-tool-header-{}", terminal.entity_id()));
3762 let header_group = SharedString::from(format!(
3763 "terminal-tool-header-group-{}",
3764 terminal.entity_id()
3765 ));
3766 let header_bg = cx
3767 .theme()
3768 .colors()
3769 .element_background
3770 .blend(cx.theme().colors().editor_foreground.opacity(0.025));
3771 let border_color = cx.theme().colors().border.opacity(0.6);
3772
3773 let working_dir = working_dir
3774 .as_ref()
3775 .map(|path| path.display().to_string())
3776 .unwrap_or_else(|| "current directory".to_string());
3777
3778 let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
3779
3780 let header = h_flex()
3781 .id(header_id)
3782 .flex_none()
3783 .gap_1()
3784 .justify_between()
3785 .rounded_t_md()
3786 .child(
3787 div()
3788 .id(("command-target-path", terminal.entity_id()))
3789 .w_full()
3790 .max_w_full()
3791 .overflow_x_scroll()
3792 .child(
3793 Label::new(working_dir)
3794 .buffer_font(cx)
3795 .size(LabelSize::XSmall)
3796 .color(Color::Muted),
3797 ),
3798 )
3799 .when(!command_finished, |header| {
3800 header
3801 .gap_1p5()
3802 .child(
3803 Button::new(
3804 SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
3805 "Stop",
3806 )
3807 .icon(IconName::Stop)
3808 .icon_position(IconPosition::Start)
3809 .icon_size(IconSize::Small)
3810 .icon_color(Color::Error)
3811 .label_size(LabelSize::Small)
3812 .tooltip(move |_window, cx| {
3813 Tooltip::with_meta(
3814 "Stop This Command",
3815 None,
3816 "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
3817 cx,
3818 )
3819 })
3820 .on_click({
3821 let terminal = terminal.clone();
3822 cx.listener(move |this, _event, _window, cx| {
3823 terminal.update(cx, |terminal, cx| {
3824 terminal.stop_by_user(cx);
3825 });
3826 this.cancel_generation(cx);
3827 })
3828 }),
3829 )
3830 .child(Divider::vertical())
3831 .child(
3832 Icon::new(IconName::ArrowCircle)
3833 .size(IconSize::XSmall)
3834 .color(Color::Info)
3835 .with_rotate_animation(2)
3836 )
3837 })
3838 .when(truncated_output, |header| {
3839 let tooltip = if let Some(output) = output {
3840 if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
3841 format!("Output exceeded terminal max lines and was \
3842 truncated, the model received the first {}.", format_file_size(output.content.len() as u64, true))
3843 } else {
3844 format!(
3845 "Output is {} long, and to avoid unexpected token usage, \
3846 only {} was sent back to the agent.",
3847 format_file_size(output.original_content_len as u64, true),
3848 format_file_size(output.content.len() as u64, true)
3849 )
3850 }
3851 } else {
3852 "Output was truncated".to_string()
3853 };
3854
3855 header.child(
3856 h_flex()
3857 .id(("terminal-tool-truncated-label", terminal.entity_id()))
3858 .gap_1()
3859 .child(
3860 Icon::new(IconName::Info)
3861 .size(IconSize::XSmall)
3862 .color(Color::Ignored),
3863 )
3864 .child(
3865 Label::new("Truncated")
3866 .color(Color::Muted)
3867 .size(LabelSize::XSmall),
3868 )
3869 .tooltip(Tooltip::text(tooltip)),
3870 )
3871 })
3872 .when(time_elapsed > Duration::from_secs(10), |header| {
3873 header.child(
3874 Label::new(format!("({})", duration_alt_display(time_elapsed)))
3875 .buffer_font(cx)
3876 .color(Color::Muted)
3877 .size(LabelSize::XSmall),
3878 )
3879 })
3880 .when(tool_failed || command_failed, |header| {
3881 header.child(
3882 div()
3883 .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
3884 .child(
3885 Icon::new(IconName::Close)
3886 .size(IconSize::Small)
3887 .color(Color::Error),
3888 )
3889 .when_some(output.and_then(|o| o.exit_status), |this, status| {
3890 this.tooltip(Tooltip::text(format!(
3891 "Exited with code {}",
3892 status.code().unwrap_or(-1),
3893 )))
3894 }),
3895 )
3896 })
3897 .child(
3898 Disclosure::new(
3899 SharedString::from(format!(
3900 "terminal-tool-disclosure-{}",
3901 terminal.entity_id()
3902 )),
3903 is_expanded,
3904 )
3905 .opened_icon(IconName::ChevronUp)
3906 .closed_icon(IconName::ChevronDown)
3907 .visible_on_hover(&header_group)
3908 .on_click(cx.listener({
3909 let id = tool_call.id.clone();
3910 move |this, _event, _window, _cx| {
3911 if is_expanded {
3912 this.expanded_tool_calls.remove(&id);
3913 } else {
3914 this.expanded_tool_calls.insert(id.clone());
3915 }
3916 }
3917 })),
3918 );
3919
3920 let terminal_view = self
3921 .entry_view_state
3922 .read(cx)
3923 .entry(entry_ix)
3924 .and_then(|entry| entry.terminal(terminal));
3925 let show_output = is_expanded && terminal_view.is_some();
3926
3927 v_flex()
3928 .my_1p5()
3929 .mx_5()
3930 .border_1()
3931 .when(tool_failed || command_failed, |card| card.border_dashed())
3932 .border_color(border_color)
3933 .rounded_md()
3934 .overflow_hidden()
3935 .child(
3936 v_flex()
3937 .group(&header_group)
3938 .py_1p5()
3939 .pr_1p5()
3940 .pl_2()
3941 .gap_0p5()
3942 .bg(header_bg)
3943 .text_xs()
3944 .child(header)
3945 .child(
3946 MarkdownElement::new(
3947 command.clone(),
3948 terminal_command_markdown_style(window, cx),
3949 )
3950 .code_block_renderer(
3951 markdown::CodeBlockRenderer::Default {
3952 copy_button: false,
3953 copy_button_on_hover: true,
3954 border: false,
3955 },
3956 ),
3957 ),
3958 )
3959 .when(show_output, |this| {
3960 this.child(
3961 div()
3962 .pt_2()
3963 .border_t_1()
3964 .when(tool_failed || command_failed, |card| card.border_dashed())
3965 .border_color(border_color)
3966 .bg(cx.theme().colors().editor_background)
3967 .rounded_b_md()
3968 .text_ui_sm(cx)
3969 .h_full()
3970 .children(terminal_view.map(|terminal_view| {
3971 let element = if terminal_view
3972 .read(cx)
3973 .content_mode(window, cx)
3974 .is_scrollable()
3975 {
3976 div().h_72().child(terminal_view).into_any_element()
3977 } else {
3978 terminal_view.into_any_element()
3979 };
3980
3981 div()
3982 .on_action(cx.listener(|_this, _: &NewTerminal, window, cx| {
3983 window.dispatch_action(NewThread.boxed_clone(), cx);
3984 cx.stop_propagation();
3985 }))
3986 .child(element)
3987 .into_any_element()
3988 })),
3989 )
3990 })
3991 .into_any()
3992 }
3993
3994 fn render_rules_item(&self, cx: &Context<Self>) -> Option<AnyElement> {
3995 let project_context = self
3996 .as_native_thread(cx)?
3997 .read(cx)
3998 .project_context()
3999 .read(cx);
4000
4001 let user_rules_text = if project_context.user_rules.is_empty() {
4002 None
4003 } else if project_context.user_rules.len() == 1 {
4004 let user_rules = &project_context.user_rules[0];
4005
4006 match user_rules.title.as_ref() {
4007 Some(title) => Some(format!("Using \"{title}\" user rule")),
4008 None => Some("Using user rule".into()),
4009 }
4010 } else {
4011 Some(format!(
4012 "Using {} user rules",
4013 project_context.user_rules.len()
4014 ))
4015 };
4016
4017 let first_user_rules_id = project_context
4018 .user_rules
4019 .first()
4020 .map(|user_rules| user_rules.uuid.0);
4021
4022 let rules_files = project_context
4023 .worktrees
4024 .iter()
4025 .filter_map(|worktree| worktree.rules_file.as_ref())
4026 .collect::<Vec<_>>();
4027
4028 let rules_file_text = match rules_files.as_slice() {
4029 &[] => None,
4030 &[rules_file] => Some(format!(
4031 "Using project {:?} file",
4032 rules_file.path_in_worktree
4033 )),
4034 rules_files => Some(format!("Using {} project rules files", rules_files.len())),
4035 };
4036
4037 if user_rules_text.is_none() && rules_file_text.is_none() {
4038 return None;
4039 }
4040
4041 let has_both = user_rules_text.is_some() && rules_file_text.is_some();
4042
4043 Some(
4044 h_flex()
4045 .px_2p5()
4046 .child(
4047 Icon::new(IconName::Attach)
4048 .size(IconSize::XSmall)
4049 .color(Color::Disabled),
4050 )
4051 .when_some(user_rules_text, |parent, user_rules_text| {
4052 parent.child(
4053 h_flex()
4054 .id("user-rules")
4055 .ml_1()
4056 .mr_1p5()
4057 .child(
4058 Label::new(user_rules_text)
4059 .size(LabelSize::XSmall)
4060 .color(Color::Muted)
4061 .truncate(),
4062 )
4063 .hover(|s| s.bg(cx.theme().colors().element_hover))
4064 .tooltip(Tooltip::text("View User Rules"))
4065 .on_click(move |_event, window, cx| {
4066 window.dispatch_action(
4067 Box::new(OpenRulesLibrary {
4068 prompt_to_select: first_user_rules_id,
4069 }),
4070 cx,
4071 )
4072 }),
4073 )
4074 })
4075 .when(has_both, |this| {
4076 this.child(
4077 Label::new("•")
4078 .size(LabelSize::XSmall)
4079 .color(Color::Disabled),
4080 )
4081 })
4082 .when_some(rules_file_text, |parent, rules_file_text| {
4083 parent.child(
4084 h_flex()
4085 .id("project-rules")
4086 .ml_1p5()
4087 .child(
4088 Label::new(rules_file_text)
4089 .size(LabelSize::XSmall)
4090 .color(Color::Muted),
4091 )
4092 .hover(|s| s.bg(cx.theme().colors().element_hover))
4093 .tooltip(Tooltip::text("View Project Rules"))
4094 .on_click(cx.listener(Self::handle_open_rules)),
4095 )
4096 })
4097 .into_any(),
4098 )
4099 }
4100
4101 fn render_empty_state_section_header(
4102 &self,
4103 label: impl Into<SharedString>,
4104 action_slot: Option<AnyElement>,
4105 cx: &mut Context<Self>,
4106 ) -> impl IntoElement {
4107 div().pl_1().pr_1p5().child(
4108 h_flex()
4109 .mt_2()
4110 .pl_1p5()
4111 .pb_1()
4112 .w_full()
4113 .justify_between()
4114 .border_b_1()
4115 .border_color(cx.theme().colors().border_variant)
4116 .child(
4117 Label::new(label.into())
4118 .size(LabelSize::Small)
4119 .color(Color::Muted),
4120 )
4121 .children(action_slot),
4122 )
4123 }
4124
4125 fn set_session_list(
4126 &mut self,
4127 session_list: Option<Rc<dyn AgentSessionList>>,
4128 cx: &mut Context<Self>,
4129 ) {
4130 if let (Some(current), Some(next)) = (&self.session_list, &session_list)
4131 && Rc::ptr_eq(current, next)
4132 {
4133 return;
4134 }
4135
4136 self.session_list = session_list.clone();
4137 *self.session_list_state.borrow_mut() = session_list;
4138 self.recent_history_entries.clear();
4139 self.hovered_recent_history_item = None;
4140 self.refresh_recent_history(cx);
4141
4142 self._recent_history_watch_task = self.session_list.as_ref().and_then(|session_list| {
4143 let mut rx = session_list.watch(cx)?;
4144 Some(cx.spawn(async move |this, cx| {
4145 while let Ok(()) = rx.recv().await {
4146 this.update(cx, |this, cx| {
4147 this.refresh_recent_history(cx);
4148 })
4149 .ok();
4150 }
4151 }))
4152 });
4153 }
4154
4155 fn refresh_recent_history(&mut self, cx: &mut Context<Self>) {
4156 let Some(session_list) = self.session_list.clone() else {
4157 return;
4158 };
4159
4160 let task = session_list.list_sessions(AgentSessionListRequest::default(), cx);
4161 self._recent_history_task = cx.spawn(async move |this, cx| match task.await {
4162 Ok(response) => {
4163 this.update(cx, |this, cx| {
4164 this.recent_history_entries = response.sessions.into_iter().take(3).collect();
4165 this.hovered_recent_history_item = None;
4166 cx.notify();
4167 })
4168 .ok();
4169 }
4170 Err(error) => {
4171 log::error!("Failed to load recent session history: {error:#}");
4172 }
4173 });
4174 }
4175
4176 fn render_recent_history(&self, cx: &mut Context<Self>) -> AnyElement {
4177 let render_history = self.session_list.is_some() && !self.recent_history_entries.is_empty();
4178
4179 v_flex()
4180 .size_full()
4181 .when(render_history, |this| {
4182 let recent_history = self.recent_history_entries.clone();
4183 this.justify_end().child(
4184 v_flex()
4185 .child(
4186 self.render_empty_state_section_header(
4187 "Recent",
4188 Some(
4189 Button::new("view-history", "View All")
4190 .style(ButtonStyle::Subtle)
4191 .label_size(LabelSize::Small)
4192 .key_binding(
4193 KeyBinding::for_action_in(
4194 &OpenHistory,
4195 &self.focus_handle(cx),
4196 cx,
4197 )
4198 .map(|kb| kb.size(rems_from_px(12.))),
4199 )
4200 .on_click(move |_event, window, cx| {
4201 window.dispatch_action(OpenHistory.boxed_clone(), cx);
4202 })
4203 .into_any_element(),
4204 ),
4205 cx,
4206 ),
4207 )
4208 .child(
4209 v_flex().p_1().pr_1p5().gap_1().children(
4210 recent_history
4211 .into_iter()
4212 .enumerate()
4213 .map(|(index, entry)| {
4214 // TODO: Add keyboard navigation.
4215 let is_hovered =
4216 self.hovered_recent_history_item == Some(index);
4217 crate::acp::thread_history::AcpHistoryEntryElement::new(
4218 entry,
4219 cx.entity().downgrade(),
4220 )
4221 .hovered(is_hovered)
4222 .on_hover(cx.listener(
4223 move |this, is_hovered, _window, cx| {
4224 if *is_hovered {
4225 this.hovered_recent_history_item = Some(index);
4226 } else if this.hovered_recent_history_item
4227 == Some(index)
4228 {
4229 this.hovered_recent_history_item = None;
4230 }
4231 cx.notify();
4232 },
4233 ))
4234 .into_any_element()
4235 }),
4236 ),
4237 ),
4238 )
4239 })
4240 .into_any()
4241 }
4242
4243 fn render_auth_required_state(
4244 &self,
4245 connection: &Rc<dyn AgentConnection>,
4246 description: Option<&Entity<Markdown>>,
4247 configuration_view: Option<&AnyView>,
4248 pending_auth_method: Option<&acp::AuthMethodId>,
4249 window: &mut Window,
4250 cx: &Context<Self>,
4251 ) -> impl IntoElement {
4252 let auth_methods = connection.auth_methods();
4253
4254 let agent_display_name = self
4255 .agent_server_store
4256 .read(cx)
4257 .agent_display_name(&ExternalAgentServerName(self.agent.name()))
4258 .unwrap_or_else(|| self.agent.name());
4259
4260 let show_fallback_description = auth_methods.len() > 1
4261 && configuration_view.is_none()
4262 && description.is_none()
4263 && pending_auth_method.is_none();
4264
4265 let auth_buttons = || {
4266 h_flex().justify_end().flex_wrap().gap_1().children(
4267 connection
4268 .auth_methods()
4269 .iter()
4270 .enumerate()
4271 .rev()
4272 .map(|(ix, method)| {
4273 let (method_id, name) = if self.project.read(cx).is_via_remote_server()
4274 && method.id.0.as_ref() == "oauth-personal"
4275 && method.name == "Log in with Google"
4276 {
4277 ("spawn-gemini-cli".into(), "Log in with Gemini CLI".into())
4278 } else {
4279 (method.id.0.clone(), method.name.clone())
4280 };
4281
4282 let agent_telemetry_id = connection.telemetry_id();
4283
4284 Button::new(method_id.clone(), name)
4285 .label_size(LabelSize::Small)
4286 .map(|this| {
4287 if ix == 0 {
4288 this.style(ButtonStyle::Tinted(TintColor::Accent))
4289 } else {
4290 this.style(ButtonStyle::Outlined)
4291 }
4292 })
4293 .when_some(method.description.clone(), |this, description| {
4294 this.tooltip(Tooltip::text(description))
4295 })
4296 .on_click({
4297 cx.listener(move |this, _, window, cx| {
4298 telemetry::event!(
4299 "Authenticate Agent Started",
4300 agent = agent_telemetry_id,
4301 method = method_id
4302 );
4303
4304 this.authenticate(
4305 acp::AuthMethodId::new(method_id.clone()),
4306 window,
4307 cx,
4308 )
4309 })
4310 })
4311 }),
4312 )
4313 };
4314
4315 if pending_auth_method.is_some() {
4316 return Callout::new()
4317 .icon(IconName::Info)
4318 .title(format!("Authenticating to {}…", agent_display_name))
4319 .actions_slot(
4320 Icon::new(IconName::ArrowCircle)
4321 .size(IconSize::Small)
4322 .color(Color::Muted)
4323 .with_rotate_animation(2)
4324 .into_any_element(),
4325 )
4326 .into_any_element();
4327 }
4328
4329 Callout::new()
4330 .icon(IconName::Info)
4331 .title(format!("Authenticate to {}", agent_display_name))
4332 .when(auth_methods.len() == 1, |this| {
4333 this.actions_slot(auth_buttons())
4334 })
4335 .description_slot(
4336 v_flex()
4337 .text_ui(cx)
4338 .map(|this| {
4339 if show_fallback_description {
4340 this.child(
4341 Label::new("Choose one of the following authentication options:")
4342 .size(LabelSize::Small)
4343 .color(Color::Muted),
4344 )
4345 } else {
4346 this.children(
4347 configuration_view
4348 .cloned()
4349 .map(|view| div().w_full().child(view)),
4350 )
4351 .children(description.map(|desc| {
4352 self.render_markdown(
4353 desc.clone(),
4354 default_markdown_style(false, false, window, cx),
4355 )
4356 }))
4357 }
4358 })
4359 .when(auth_methods.len() > 1, |this| {
4360 this.gap_1().child(auth_buttons())
4361 }),
4362 )
4363 .into_any_element()
4364 }
4365
4366 fn render_load_error(
4367 &self,
4368 e: &LoadError,
4369 window: &mut Window,
4370 cx: &mut Context<Self>,
4371 ) -> AnyElement {
4372 let (title, message, action_slot): (_, SharedString, _) = match e {
4373 LoadError::Unsupported {
4374 command: path,
4375 current_version,
4376 minimum_version,
4377 } => {
4378 return self.render_unsupported(path, current_version, minimum_version, window, cx);
4379 }
4380 LoadError::FailedToInstall(msg) => (
4381 "Failed to Install",
4382 msg.into(),
4383 Some(self.create_copy_button(msg.to_string()).into_any_element()),
4384 ),
4385 LoadError::Exited { status } => (
4386 "Failed to Launch",
4387 format!("Server exited with status {status}").into(),
4388 None,
4389 ),
4390 LoadError::Other(msg) => (
4391 "Failed to Launch",
4392 msg.into(),
4393 Some(self.create_copy_button(msg.to_string()).into_any_element()),
4394 ),
4395 };
4396
4397 Callout::new()
4398 .severity(Severity::Error)
4399 .icon(IconName::XCircleFilled)
4400 .title(title)
4401 .description(message)
4402 .actions_slot(div().children(action_slot))
4403 .into_any_element()
4404 }
4405
4406 fn render_unsupported(
4407 &self,
4408 path: &SharedString,
4409 version: &SharedString,
4410 minimum_version: &SharedString,
4411 _window: &mut Window,
4412 cx: &mut Context<Self>,
4413 ) -> AnyElement {
4414 let (heading_label, description_label) = (
4415 format!("Upgrade {} to work with Zed", self.agent.name()),
4416 if version.is_empty() {
4417 format!(
4418 "Currently using {}, which does not report a valid --version",
4419 path,
4420 )
4421 } else {
4422 format!(
4423 "Currently using {}, which is only version {} (need at least {minimum_version})",
4424 path, version
4425 )
4426 },
4427 );
4428
4429 v_flex()
4430 .w_full()
4431 .p_3p5()
4432 .gap_2p5()
4433 .border_t_1()
4434 .border_color(cx.theme().colors().border)
4435 .bg(linear_gradient(
4436 180.,
4437 linear_color_stop(cx.theme().colors().editor_background.opacity(0.4), 4.),
4438 linear_color_stop(cx.theme().status().info_background.opacity(0.), 0.),
4439 ))
4440 .child(
4441 v_flex().gap_0p5().child(Label::new(heading_label)).child(
4442 Label::new(description_label)
4443 .size(LabelSize::Small)
4444 .color(Color::Muted),
4445 ),
4446 )
4447 .into_any_element()
4448 }
4449
4450 fn activity_bar_bg(&self, cx: &Context<Self>) -> Hsla {
4451 let editor_bg_color = cx.theme().colors().editor_background;
4452 let active_color = cx.theme().colors().element_selected;
4453 editor_bg_color.blend(active_color.opacity(0.3))
4454 }
4455
4456 fn render_activity_bar(
4457 &self,
4458 thread_entity: &Entity<AcpThread>,
4459 window: &mut Window,
4460 cx: &Context<Self>,
4461 ) -> Option<AnyElement> {
4462 let thread = thread_entity.read(cx);
4463 let action_log = thread.action_log();
4464 let telemetry = ActionLogTelemetry::from(thread);
4465 let changed_buffers = action_log.read(cx).changed_buffers(cx);
4466 let plan = thread.plan();
4467
4468 if changed_buffers.is_empty() && plan.is_empty() && self.message_queue.is_empty() {
4469 return None;
4470 }
4471
4472 // Temporarily always enable ACP edit controls. This is temporary, to lessen the
4473 // impact of a nasty bug that causes them to sometimes be disabled when they shouldn't
4474 // be, which blocks you from being able to accept or reject edits. This switches the
4475 // bug to be that sometimes it's enabled when it shouldn't be, which at least doesn't
4476 // block you from using the panel.
4477 let pending_edits = false;
4478
4479 let use_keep_reject_buttons = !cx.has_flag::<AgentV2FeatureFlag>();
4480
4481 v_flex()
4482 .mt_1()
4483 .mx_2()
4484 .bg(self.activity_bar_bg(cx))
4485 .border_1()
4486 .border_b_0()
4487 .border_color(cx.theme().colors().border)
4488 .rounded_t_md()
4489 .shadow(vec![gpui::BoxShadow {
4490 color: gpui::black().opacity(0.15),
4491 offset: point(px(1.), px(-1.)),
4492 blur_radius: px(3.),
4493 spread_radius: px(0.),
4494 }])
4495 .when(!plan.is_empty(), |this| {
4496 this.child(self.render_plan_summary(plan, window, cx))
4497 .when(self.plan_expanded, |parent| {
4498 parent.child(self.render_plan_entries(plan, window, cx))
4499 })
4500 })
4501 .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
4502 this.child(Divider::horizontal().color(DividerColor::Border))
4503 })
4504 .when(!changed_buffers.is_empty(), |this| {
4505 this.child(self.render_edits_summary(
4506 &changed_buffers,
4507 self.edits_expanded,
4508 pending_edits,
4509 use_keep_reject_buttons,
4510 cx,
4511 ))
4512 .when(self.edits_expanded, |parent| {
4513 parent.child(self.render_edited_files(
4514 action_log,
4515 telemetry.clone(),
4516 &changed_buffers,
4517 pending_edits,
4518 use_keep_reject_buttons,
4519 cx,
4520 ))
4521 })
4522 })
4523 .when(!self.message_queue.is_empty(), |this| {
4524 this.when(!plan.is_empty() || !changed_buffers.is_empty(), |this| {
4525 this.child(Divider::horizontal().color(DividerColor::Border))
4526 })
4527 .child(self.render_message_queue_summary(window, cx))
4528 .when(self.queue_expanded, |parent| {
4529 parent.child(self.render_message_queue_entries(window, cx))
4530 })
4531 })
4532 .into_any()
4533 .into()
4534 }
4535
4536 fn render_plan_summary(
4537 &self,
4538 plan: &Plan,
4539 window: &mut Window,
4540 cx: &Context<Self>,
4541 ) -> impl IntoElement {
4542 let stats = plan.stats();
4543
4544 let title = if let Some(entry) = stats.in_progress_entry
4545 && !self.plan_expanded
4546 {
4547 h_flex()
4548 .cursor_default()
4549 .relative()
4550 .w_full()
4551 .gap_1()
4552 .truncate()
4553 .child(
4554 Label::new("Current:")
4555 .size(LabelSize::Small)
4556 .color(Color::Muted),
4557 )
4558 .child(
4559 div()
4560 .text_xs()
4561 .text_color(cx.theme().colors().text_muted)
4562 .line_clamp(1)
4563 .child(MarkdownElement::new(
4564 entry.content.clone(),
4565 plan_label_markdown_style(&entry.status, window, cx),
4566 )),
4567 )
4568 .when(stats.pending > 0, |this| {
4569 this.child(
4570 h_flex()
4571 .absolute()
4572 .top_0()
4573 .right_0()
4574 .h_full()
4575 .child(div().min_w_8().h_full().bg(linear_gradient(
4576 90.,
4577 linear_color_stop(self.activity_bar_bg(cx), 1.),
4578 linear_color_stop(self.activity_bar_bg(cx).opacity(0.2), 0.),
4579 )))
4580 .child(
4581 div().pr_0p5().bg(self.activity_bar_bg(cx)).child(
4582 Label::new(format!("{} left", stats.pending))
4583 .size(LabelSize::Small)
4584 .color(Color::Muted),
4585 ),
4586 ),
4587 )
4588 })
4589 } else {
4590 let status_label = if stats.pending == 0 {
4591 "All Done".to_string()
4592 } else if stats.completed == 0 {
4593 format!("{} Tasks", plan.entries.len())
4594 } else {
4595 format!("{}/{}", stats.completed, plan.entries.len())
4596 };
4597
4598 h_flex()
4599 .w_full()
4600 .gap_1()
4601 .justify_between()
4602 .child(
4603 Label::new("Plan")
4604 .size(LabelSize::Small)
4605 .color(Color::Muted),
4606 )
4607 .child(
4608 Label::new(status_label)
4609 .size(LabelSize::Small)
4610 .color(Color::Muted)
4611 .mr_1(),
4612 )
4613 };
4614
4615 h_flex()
4616 .id("plan_summary")
4617 .p_1()
4618 .w_full()
4619 .gap_1()
4620 .when(self.plan_expanded, |this| {
4621 this.border_b_1().border_color(cx.theme().colors().border)
4622 })
4623 .child(Disclosure::new("plan_disclosure", self.plan_expanded))
4624 .child(title)
4625 .on_click(cx.listener(|this, _, _, cx| {
4626 this.plan_expanded = !this.plan_expanded;
4627 cx.notify();
4628 }))
4629 }
4630
4631 fn render_plan_entries(
4632 &self,
4633 plan: &Plan,
4634 window: &mut Window,
4635 cx: &Context<Self>,
4636 ) -> impl IntoElement {
4637 v_flex()
4638 .id("plan_items_list")
4639 .max_h_40()
4640 .overflow_y_scroll()
4641 .children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
4642 let element = h_flex()
4643 .py_1()
4644 .px_2()
4645 .gap_2()
4646 .justify_between()
4647 .bg(cx.theme().colors().editor_background)
4648 .when(index < plan.entries.len() - 1, |parent| {
4649 parent.border_color(cx.theme().colors().border).border_b_1()
4650 })
4651 .child(
4652 h_flex()
4653 .id(("plan_entry", index))
4654 .gap_1p5()
4655 .max_w_full()
4656 .overflow_x_scroll()
4657 .text_xs()
4658 .text_color(cx.theme().colors().text_muted)
4659 .child(match entry.status {
4660 acp::PlanEntryStatus::InProgress => {
4661 Icon::new(IconName::TodoProgress)
4662 .size(IconSize::Small)
4663 .color(Color::Accent)
4664 .with_rotate_animation(2)
4665 .into_any_element()
4666 }
4667 acp::PlanEntryStatus::Completed => {
4668 Icon::new(IconName::TodoComplete)
4669 .size(IconSize::Small)
4670 .color(Color::Success)
4671 .into_any_element()
4672 }
4673 acp::PlanEntryStatus::Pending | _ => {
4674 Icon::new(IconName::TodoPending)
4675 .size(IconSize::Small)
4676 .color(Color::Muted)
4677 .into_any_element()
4678 }
4679 })
4680 .child(MarkdownElement::new(
4681 entry.content.clone(),
4682 plan_label_markdown_style(&entry.status, window, cx),
4683 )),
4684 );
4685
4686 Some(element)
4687 }))
4688 .into_any_element()
4689 }
4690
4691 fn render_edits_summary(
4692 &self,
4693 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
4694 expanded: bool,
4695 pending_edits: bool,
4696 use_keep_reject_buttons: bool,
4697 cx: &Context<Self>,
4698 ) -> Div {
4699 const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
4700
4701 let focus_handle = self.focus_handle(cx);
4702
4703 h_flex()
4704 .p_1()
4705 .justify_between()
4706 .flex_wrap()
4707 .when(expanded, |this| {
4708 this.border_b_1().border_color(cx.theme().colors().border)
4709 })
4710 .child(
4711 h_flex()
4712 .id("edits-container")
4713 .cursor_pointer()
4714 .gap_1()
4715 .child(Disclosure::new("edits-disclosure", expanded))
4716 .map(|this| {
4717 if pending_edits {
4718 this.child(
4719 Label::new(format!(
4720 "Editing {} {}…",
4721 changed_buffers.len(),
4722 if changed_buffers.len() == 1 {
4723 "file"
4724 } else {
4725 "files"
4726 }
4727 ))
4728 .color(Color::Muted)
4729 .size(LabelSize::Small)
4730 .with_animation(
4731 "edit-label",
4732 Animation::new(Duration::from_secs(2))
4733 .repeat()
4734 .with_easing(pulsating_between(0.3, 0.7)),
4735 |label, delta| label.alpha(delta),
4736 ),
4737 )
4738 } else {
4739 let stats = DiffStats::all_files(changed_buffers, cx);
4740 let dot_divider = || {
4741 Label::new("•")
4742 .size(LabelSize::XSmall)
4743 .color(Color::Disabled)
4744 };
4745
4746 this.child(
4747 Label::new("Edits")
4748 .size(LabelSize::Small)
4749 .color(Color::Muted),
4750 )
4751 .child(dot_divider())
4752 .child(
4753 Label::new(format!(
4754 "{} {}",
4755 changed_buffers.len(),
4756 if changed_buffers.len() == 1 {
4757 "file"
4758 } else {
4759 "files"
4760 }
4761 ))
4762 .size(LabelSize::Small)
4763 .color(Color::Muted),
4764 )
4765 .child(dot_divider())
4766 .child(DiffStat::new(
4767 "total",
4768 stats.lines_added as usize,
4769 stats.lines_removed as usize,
4770 ))
4771 }
4772 })
4773 .on_click(cx.listener(|this, _, _, cx| {
4774 this.edits_expanded = !this.edits_expanded;
4775 cx.notify();
4776 })),
4777 )
4778 .when(use_keep_reject_buttons, |this| {
4779 this.child(
4780 h_flex()
4781 .gap_1()
4782 .child(
4783 IconButton::new("review-changes", IconName::ListTodo)
4784 .icon_size(IconSize::Small)
4785 .tooltip({
4786 let focus_handle = focus_handle.clone();
4787 move |_window, cx| {
4788 Tooltip::for_action_in(
4789 "Review Changes",
4790 &OpenAgentDiff,
4791 &focus_handle,
4792 cx,
4793 )
4794 }
4795 })
4796 .on_click(cx.listener(|_, _, window, cx| {
4797 window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
4798 })),
4799 )
4800 .child(Divider::vertical().color(DividerColor::Border))
4801 .child(
4802 Button::new("reject-all-changes", "Reject All")
4803 .label_size(LabelSize::Small)
4804 .disabled(pending_edits)
4805 .when(pending_edits, |this| {
4806 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
4807 })
4808 .key_binding(
4809 KeyBinding::for_action_in(
4810 &RejectAll,
4811 &focus_handle.clone(),
4812 cx,
4813 )
4814 .map(|kb| kb.size(rems_from_px(10.))),
4815 )
4816 .on_click(cx.listener(move |this, _, window, cx| {
4817 this.reject_all(&RejectAll, window, cx);
4818 })),
4819 )
4820 .child(
4821 Button::new("keep-all-changes", "Keep All")
4822 .label_size(LabelSize::Small)
4823 .disabled(pending_edits)
4824 .when(pending_edits, |this| {
4825 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
4826 })
4827 .key_binding(
4828 KeyBinding::for_action_in(&KeepAll, &focus_handle, cx)
4829 .map(|kb| kb.size(rems_from_px(10.))),
4830 )
4831 .on_click(cx.listener(move |this, _, window, cx| {
4832 this.keep_all(&KeepAll, window, cx);
4833 })),
4834 ),
4835 )
4836 })
4837 .when(!use_keep_reject_buttons, |this| {
4838 this.child(
4839 Button::new("review-changes", "Review Changes")
4840 .label_size(LabelSize::Small)
4841 .key_binding(
4842 KeyBinding::for_action_in(
4843 &git_ui::project_diff::Diff,
4844 &focus_handle,
4845 cx,
4846 )
4847 .map(|kb| kb.size(rems_from_px(10.))),
4848 )
4849 .on_click(cx.listener(move |_, _, window, cx| {
4850 window.dispatch_action(git_ui::project_diff::Diff.boxed_clone(), cx);
4851 })),
4852 )
4853 })
4854 }
4855
4856 fn render_edited_files(
4857 &self,
4858 action_log: &Entity<ActionLog>,
4859 telemetry: ActionLogTelemetry,
4860 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
4861 pending_edits: bool,
4862 use_keep_reject_buttons: bool,
4863 cx: &Context<Self>,
4864 ) -> impl IntoElement {
4865 let editor_bg_color = cx.theme().colors().editor_background;
4866
4867 v_flex()
4868 .id("edited_files_list")
4869 .max_h_40()
4870 .overflow_y_scroll()
4871 .children(
4872 changed_buffers
4873 .iter()
4874 .enumerate()
4875 .flat_map(|(index, (buffer, diff))| {
4876 let file = buffer.read(cx).file()?;
4877 let path = file.path();
4878 let path_style = file.path_style(cx);
4879 let separator = file.path_style(cx).primary_separator();
4880
4881 let file_path = path.parent().and_then(|parent| {
4882 if parent.is_empty() {
4883 None
4884 } else {
4885 Some(
4886 Label::new(format!(
4887 "{}{separator}",
4888 parent.display(path_style)
4889 ))
4890 .color(Color::Muted)
4891 .size(LabelSize::XSmall)
4892 .buffer_font(cx),
4893 )
4894 }
4895 });
4896
4897 let file_name = path.file_name().map(|name| {
4898 Label::new(name.to_string())
4899 .size(LabelSize::XSmall)
4900 .buffer_font(cx)
4901 .ml_1()
4902 });
4903
4904 let full_path = path.display(path_style).to_string();
4905
4906 let file_icon = FileIcons::get_icon(path.as_std_path(), cx)
4907 .map(Icon::from_path)
4908 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
4909 .unwrap_or_else(|| {
4910 Icon::new(IconName::File)
4911 .color(Color::Muted)
4912 .size(IconSize::Small)
4913 });
4914
4915 let overlay_gradient = linear_gradient(
4916 90.,
4917 linear_color_stop(editor_bg_color, 1.),
4918 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
4919 );
4920
4921 let file_stats = DiffStats::single_file(buffer.read(cx), diff.read(cx), cx);
4922
4923 let element = h_flex()
4924 .group("edited-code")
4925 .id(("file-container", index))
4926 .py_1()
4927 .pl_2()
4928 .pr_1()
4929 .gap_2()
4930 .justify_between()
4931 .bg(editor_bg_color)
4932 .when(index < changed_buffers.len() - 1, |parent| {
4933 parent.border_color(cx.theme().colors().border).border_b_1()
4934 })
4935 .child(
4936 h_flex()
4937 .id(("file-name-row", index))
4938 .relative()
4939 .pr_8()
4940 .w_full()
4941 .child(
4942 h_flex()
4943 .id(("file-name-path", index))
4944 .cursor_pointer()
4945 .pr_0p5()
4946 .gap_0p5()
4947 .hover(|s| s.bg(cx.theme().colors().element_hover))
4948 .rounded_xs()
4949 .child(file_icon)
4950 .children(file_name)
4951 .children(file_path)
4952 .child(
4953 DiffStat::new(
4954 "file",
4955 file_stats.lines_added as usize,
4956 file_stats.lines_removed as usize,
4957 )
4958 .label_size(LabelSize::XSmall),
4959 )
4960 .tooltip(move |_, cx| {
4961 Tooltip::with_meta(
4962 "Go to File",
4963 None,
4964 full_path.clone(),
4965 cx,
4966 )
4967 })
4968 .on_click({
4969 let buffer = buffer.clone();
4970 cx.listener(move |this, _, window, cx| {
4971 this.open_edited_buffer(&buffer, window, cx);
4972 })
4973 }),
4974 )
4975 .child(
4976 div()
4977 .absolute()
4978 .h_full()
4979 .w_12()
4980 .top_0()
4981 .bottom_0()
4982 .right_0()
4983 .bg(overlay_gradient),
4984 ),
4985 )
4986 .when(use_keep_reject_buttons, |parent| {
4987 parent.child(
4988 h_flex()
4989 .gap_1()
4990 .visible_on_hover("edited-code")
4991 .child(
4992 Button::new("review", "Review")
4993 .label_size(LabelSize::Small)
4994 .on_click({
4995 let buffer = buffer.clone();
4996 let workspace = self.workspace.clone();
4997 cx.listener(move |_, _, window, cx| {
4998 let Some(workspace) = workspace.upgrade() else {
4999 return;
5000 };
5001 let Some(file) = buffer.read(cx).file() else {
5002 return;
5003 };
5004 let project_path = project::ProjectPath {
5005 worktree_id: file.worktree_id(cx),
5006 path: file.path().clone(),
5007 };
5008 workspace.update(cx, |workspace, cx| {
5009 git_ui::project_diff::ProjectDiff::deploy_at_project_path(
5010 workspace,
5011 project_path,
5012 window,
5013 cx,
5014 );
5015 });
5016 })
5017 }),
5018 )
5019 .child(Divider::vertical().color(DividerColor::BorderVariant))
5020 .child(
5021 Button::new("reject-file", "Reject")
5022 .label_size(LabelSize::Small)
5023 .disabled(pending_edits)
5024 .on_click({
5025 let buffer = buffer.clone();
5026 let action_log = action_log.clone();
5027 let telemetry = telemetry.clone();
5028 move |_, _, cx| {
5029 action_log.update(cx, |action_log, cx| {
5030 action_log
5031 .reject_edits_in_ranges(
5032 buffer.clone(),
5033 vec![Anchor::min_max_range_for_buffer(
5034 buffer.read(cx).remote_id(),
5035 )],
5036 Some(telemetry.clone()),
5037 cx,
5038 )
5039 .detach_and_log_err(cx);
5040 })
5041 }
5042 }),
5043 )
5044 .child(
5045 Button::new("keep-file", "Keep")
5046 .label_size(LabelSize::Small)
5047 .disabled(pending_edits)
5048 .on_click({
5049 let buffer = buffer.clone();
5050 let action_log = action_log.clone();
5051 let telemetry = telemetry.clone();
5052 move |_, _, cx| {
5053 action_log.update(cx, |action_log, cx| {
5054 action_log.keep_edits_in_range(
5055 buffer.clone(),
5056 Anchor::min_max_range_for_buffer(
5057 buffer.read(cx).remote_id(),
5058 ),
5059 Some(telemetry.clone()),
5060 cx,
5061 );
5062 })
5063 }
5064 }),
5065 ),
5066 )
5067 })
5068 .when(!use_keep_reject_buttons, |parent| {
5069 parent.child(
5070 h_flex()
5071 .gap_1()
5072 .visible_on_hover("edited-code")
5073 .child(
5074 Button::new("review", "Review")
5075 .label_size(LabelSize::Small)
5076 .on_click({
5077 let buffer = buffer.clone();
5078 let workspace = self.workspace.clone();
5079 cx.listener(move |_, _, window, cx| {
5080 let Some(workspace) = workspace.upgrade() else {
5081 return;
5082 };
5083 let Some(file) = buffer.read(cx).file() else {
5084 return;
5085 };
5086 let project_path = project::ProjectPath {
5087 worktree_id: file.worktree_id(cx),
5088 path: file.path().clone(),
5089 };
5090 workspace.update(cx, |workspace, cx| {
5091 git_ui::project_diff::ProjectDiff::deploy_at_project_path(
5092 workspace,
5093 project_path,
5094 window,
5095 cx,
5096 );
5097 });
5098 })
5099 }),
5100 ),
5101 )
5102 });
5103
5104 Some(element)
5105 }),
5106 )
5107 .into_any_element()
5108 }
5109
5110 fn render_message_queue_summary(
5111 &self,
5112 _window: &mut Window,
5113 cx: &Context<Self>,
5114 ) -> impl IntoElement {
5115 let queue_count = self.message_queue.len();
5116 let title: SharedString = if queue_count == 1 {
5117 "1 Queued Message".into()
5118 } else {
5119 format!("{} Queued Messages", queue_count).into()
5120 };
5121
5122 h_flex()
5123 .p_1()
5124 .w_full()
5125 .gap_1()
5126 .justify_between()
5127 .when(self.queue_expanded, |this| {
5128 this.border_b_1().border_color(cx.theme().colors().border)
5129 })
5130 .child(
5131 h_flex()
5132 .id("queue_summary")
5133 .gap_1()
5134 .child(Disclosure::new("queue_disclosure", self.queue_expanded))
5135 .child(Label::new(title).size(LabelSize::Small).color(Color::Muted))
5136 .on_click(cx.listener(|this, _, _, cx| {
5137 this.queue_expanded = !this.queue_expanded;
5138 cx.notify();
5139 })),
5140 )
5141 .child(
5142 Button::new("clear_queue", "Clear All")
5143 .label_size(LabelSize::Small)
5144 .key_binding(KeyBinding::for_action(&ClearMessageQueue, cx))
5145 .on_click(cx.listener(|this, _, _, cx| {
5146 this.message_queue.clear();
5147 cx.notify();
5148 })),
5149 )
5150 }
5151
5152 fn render_message_queue_entries(
5153 &self,
5154 _window: &mut Window,
5155 cx: &Context<Self>,
5156 ) -> impl IntoElement {
5157 let message_editor = self.message_editor.read(cx);
5158 let focus_handle = message_editor.focus_handle(cx);
5159
5160 v_flex()
5161 .id("message_queue_list")
5162 .max_h_40()
5163 .overflow_y_scroll()
5164 .children(
5165 self.message_queue
5166 .iter()
5167 .enumerate()
5168 .map(|(index, queued)| {
5169 let is_next = index == 0;
5170 let icon_color = if is_next { Color::Accent } else { Color::Muted };
5171 let queue_len = self.message_queue.len();
5172
5173 let preview = queued
5174 .content
5175 .iter()
5176 .find_map(|block| match block {
5177 acp::ContentBlock::Text(text) => {
5178 text.text.lines().next().map(str::to_owned)
5179 }
5180 _ => None,
5181 })
5182 .unwrap_or_default();
5183
5184 h_flex()
5185 .group("queue_entry")
5186 .w_full()
5187 .p_1()
5188 .pl_2()
5189 .gap_1()
5190 .justify_between()
5191 .bg(cx.theme().colors().editor_background)
5192 .when(index < queue_len - 1, |parent| {
5193 parent.border_color(cx.theme().colors().border).border_b_1()
5194 })
5195 .child(
5196 h_flex()
5197 .id(("queued_prompt", index))
5198 .min_w_0()
5199 .w_full()
5200 .gap_1p5()
5201 .child(
5202 Icon::new(IconName::Circle)
5203 .size(IconSize::Small)
5204 .color(icon_color),
5205 )
5206 .child(
5207 Label::new(preview)
5208 .size(LabelSize::XSmall)
5209 .color(Color::Muted)
5210 .buffer_font(cx)
5211 .truncate(),
5212 )
5213 .when(is_next, |this| {
5214 this.tooltip(Tooltip::text("Next Prompt in the Queue"))
5215 }),
5216 )
5217 .child(
5218 h_flex()
5219 .flex_none()
5220 .gap_1()
5221 .visible_on_hover("queue_entry")
5222 .child(
5223 Button::new(("delete", index), "Remove")
5224 .label_size(LabelSize::Small)
5225 .on_click(cx.listener(move |this, _, _, cx| {
5226 if index < this.message_queue.len() {
5227 this.message_queue.remove(index);
5228 cx.notify();
5229 }
5230 })),
5231 )
5232 .child(
5233 Button::new(("send_now", index), "Send Now")
5234 .style(ButtonStyle::Outlined)
5235 .label_size(LabelSize::Small)
5236 .when(is_next, |this| {
5237 this.key_binding(
5238 KeyBinding::for_action_in(
5239 &SendNextQueuedMessage,
5240 &focus_handle.clone(),
5241 cx,
5242 )
5243 .map(|kb| kb.size(rems_from_px(10.))),
5244 )
5245 })
5246 .on_click(cx.listener(move |this, _, window, cx| {
5247 this.send_queued_message_at_index(
5248 index, true, window, cx,
5249 );
5250 })),
5251 ),
5252 )
5253 }),
5254 )
5255 .into_any_element()
5256 }
5257
5258 fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
5259 let focus_handle = self.message_editor.focus_handle(cx);
5260 let editor_bg_color = cx.theme().colors().editor_background;
5261 let (expand_icon, expand_tooltip) = if self.editor_expanded {
5262 (IconName::Minimize, "Minimize Message Editor")
5263 } else {
5264 (IconName::Maximize, "Expand Message Editor")
5265 };
5266
5267 let backdrop = div()
5268 .size_full()
5269 .absolute()
5270 .inset_0()
5271 .bg(cx.theme().colors().panel_background)
5272 .opacity(0.8)
5273 .block_mouse_except_scroll();
5274
5275 let enable_editor = match self.thread_state {
5276 ThreadState::Ready { .. } => true,
5277 ThreadState::Loading { .. }
5278 | ThreadState::Unauthenticated { .. }
5279 | ThreadState::LoadError(..) => false,
5280 };
5281
5282 v_flex()
5283 .on_action(cx.listener(Self::expand_message_editor))
5284 .p_2()
5285 .gap_2()
5286 .border_t_1()
5287 .border_color(cx.theme().colors().border)
5288 .bg(editor_bg_color)
5289 .when(self.editor_expanded, |this| {
5290 this.h(vh(0.8, window)).size_full().justify_between()
5291 })
5292 .child(
5293 v_flex()
5294 .relative()
5295 .size_full()
5296 .pt_1()
5297 .pr_2p5()
5298 .child(self.message_editor.clone())
5299 .child(
5300 h_flex()
5301 .absolute()
5302 .top_0()
5303 .right_0()
5304 .opacity(0.5)
5305 .hover(|this| this.opacity(1.0))
5306 .child(
5307 IconButton::new("toggle-height", expand_icon)
5308 .icon_size(IconSize::Small)
5309 .icon_color(Color::Muted)
5310 .tooltip({
5311 move |_window, cx| {
5312 Tooltip::for_action_in(
5313 expand_tooltip,
5314 &ExpandMessageEditor,
5315 &focus_handle,
5316 cx,
5317 )
5318 }
5319 })
5320 .on_click(cx.listener(|this, _, window, cx| {
5321 this.expand_message_editor(
5322 &ExpandMessageEditor,
5323 window,
5324 cx,
5325 );
5326 })),
5327 ),
5328 ),
5329 )
5330 .child(
5331 h_flex()
5332 .flex_none()
5333 .flex_wrap()
5334 .justify_between()
5335 .child(
5336 h_flex()
5337 .gap_0p5()
5338 .child(self.render_add_context_button(cx))
5339 .child(self.render_follow_toggle(cx))
5340 .children(self.render_burn_mode_toggle(cx)),
5341 )
5342 .child(
5343 h_flex()
5344 .gap_1()
5345 .children(self.render_token_usage(cx))
5346 .children(self.profile_selector.clone())
5347 // Either config_options_view OR (mode_selector + model_selector)
5348 .children(self.config_options_view.clone())
5349 .when(self.config_options_view.is_none(), |this| {
5350 this.children(self.mode_selector().cloned())
5351 .children(self.model_selector.clone())
5352 })
5353 .child(self.render_send_button(cx)),
5354 ),
5355 )
5356 .when(!enable_editor, |this| this.child(backdrop))
5357 .into_any()
5358 }
5359
5360 pub(crate) fn as_native_connection(
5361 &self,
5362 cx: &App,
5363 ) -> Option<Rc<agent::NativeAgentConnection>> {
5364 let acp_thread = self.thread()?.read(cx);
5365 acp_thread.connection().clone().downcast()
5366 }
5367
5368 pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
5369 let acp_thread = self.thread()?.read(cx);
5370 self.as_native_connection(cx)?
5371 .thread(acp_thread.session_id(), cx)
5372 }
5373
5374 fn is_imported_thread(&self, cx: &App) -> bool {
5375 let Some(thread) = self.as_native_thread(cx) else {
5376 return false;
5377 };
5378 thread.read(cx).is_imported()
5379 }
5380
5381 fn is_using_zed_ai_models(&self, cx: &App) -> bool {
5382 self.as_native_thread(cx)
5383 .and_then(|thread| thread.read(cx).model())
5384 .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
5385 }
5386
5387 fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
5388 let thread = self.thread()?.read(cx);
5389 let usage = thread.token_usage()?;
5390 let is_generating = thread.status() != ThreadStatus::Idle;
5391
5392 let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
5393 let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
5394
5395 Some(
5396 h_flex()
5397 .flex_shrink_0()
5398 .gap_0p5()
5399 .mr_1p5()
5400 .child(
5401 Label::new(used)
5402 .size(LabelSize::Small)
5403 .color(Color::Muted)
5404 .map(|label| {
5405 if is_generating {
5406 label
5407 .with_animation(
5408 "used-tokens-label",
5409 Animation::new(Duration::from_secs(2))
5410 .repeat()
5411 .with_easing(pulsating_between(0.3, 0.8)),
5412 |label, delta| label.alpha(delta),
5413 )
5414 .into_any()
5415 } else {
5416 label.into_any_element()
5417 }
5418 }),
5419 )
5420 .child(
5421 Label::new("/")
5422 .size(LabelSize::Small)
5423 .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
5424 )
5425 .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
5426 )
5427 }
5428
5429 fn toggle_burn_mode(
5430 &mut self,
5431 _: &ToggleBurnMode,
5432 _window: &mut Window,
5433 cx: &mut Context<Self>,
5434 ) {
5435 let Some(thread) = self.as_native_thread(cx) else {
5436 return;
5437 };
5438
5439 thread.update(cx, |thread, cx| {
5440 let current_mode = thread.completion_mode();
5441 thread.set_completion_mode(
5442 match current_mode {
5443 CompletionMode::Burn => CompletionMode::Normal,
5444 CompletionMode::Normal => CompletionMode::Burn,
5445 },
5446 cx,
5447 );
5448 });
5449 }
5450
5451 fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
5452 let Some(thread) = self.thread() else {
5453 return;
5454 };
5455 let telemetry = ActionLogTelemetry::from(thread.read(cx));
5456 let action_log = thread.read(cx).action_log().clone();
5457 action_log.update(cx, |action_log, cx| {
5458 action_log.keep_all_edits(Some(telemetry), cx)
5459 });
5460 }
5461
5462 fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
5463 let Some(thread) = self.thread() else {
5464 return;
5465 };
5466 let telemetry = ActionLogTelemetry::from(thread.read(cx));
5467 let action_log = thread.read(cx).action_log().clone();
5468 action_log
5469 .update(cx, |action_log, cx| {
5470 action_log.reject_all_edits(Some(telemetry), cx)
5471 })
5472 .detach();
5473 }
5474
5475 fn allow_always(&mut self, _: &AllowAlways, window: &mut Window, cx: &mut Context<Self>) {
5476 self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowAlways, window, cx);
5477 }
5478
5479 fn allow_once(&mut self, _: &AllowOnce, window: &mut Window, cx: &mut Context<Self>) {
5480 self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowOnce, window, cx);
5481 }
5482
5483 fn reject_once(&mut self, _: &RejectOnce, window: &mut Window, cx: &mut Context<Self>) {
5484 self.authorize_pending_tool_call(acp::PermissionOptionKind::RejectOnce, window, cx);
5485 }
5486
5487 fn authorize_pending_tool_call(
5488 &mut self,
5489 kind: acp::PermissionOptionKind,
5490 window: &mut Window,
5491 cx: &mut Context<Self>,
5492 ) -> Option<()> {
5493 let thread = self.thread()?.read(cx);
5494 let tool_call = thread.first_tool_awaiting_confirmation()?;
5495 let ToolCallStatus::WaitingForConfirmation { options, .. } = &tool_call.status else {
5496 return None;
5497 };
5498 let option = options.iter().find(|o| o.kind == kind)?;
5499
5500 self.authorize_tool_call(
5501 tool_call.id.clone(),
5502 option.option_id.clone(),
5503 option.kind,
5504 window,
5505 cx,
5506 );
5507
5508 Some(())
5509 }
5510
5511 fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
5512 let thread = self.as_native_thread(cx)?.read(cx);
5513
5514 if thread
5515 .model()
5516 .is_none_or(|model| !model.supports_burn_mode())
5517 {
5518 return None;
5519 }
5520
5521 let active_completion_mode = thread.completion_mode();
5522 let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
5523 let icon = if burn_mode_enabled {
5524 IconName::ZedBurnModeOn
5525 } else {
5526 IconName::ZedBurnMode
5527 };
5528
5529 Some(
5530 IconButton::new("burn-mode", icon)
5531 .icon_size(IconSize::Small)
5532 .icon_color(Color::Muted)
5533 .toggle_state(burn_mode_enabled)
5534 .selected_icon_color(Color::Error)
5535 .on_click(cx.listener(|this, _event, window, cx| {
5536 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5537 }))
5538 .tooltip(move |_window, cx| {
5539 cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
5540 .into()
5541 })
5542 .into_any_element(),
5543 )
5544 }
5545
5546 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
5547 let message_editor = self.message_editor.read(cx);
5548 let is_editor_empty = message_editor.is_empty(cx);
5549 let focus_handle = message_editor.focus_handle(cx);
5550
5551 let is_generating = self
5552 .thread()
5553 .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
5554
5555 if self.is_loading_contents {
5556 div()
5557 .id("loading-message-content")
5558 .px_1()
5559 .tooltip(Tooltip::text("Loading Added Context…"))
5560 .child(loading_contents_spinner(IconSize::default()))
5561 .into_any_element()
5562 } else if is_generating && is_editor_empty {
5563 IconButton::new("stop-generation", IconName::Stop)
5564 .icon_color(Color::Error)
5565 .style(ButtonStyle::Tinted(TintColor::Error))
5566 .tooltip(move |_window, cx| {
5567 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, cx)
5568 })
5569 .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
5570 .into_any_element()
5571 } else {
5572 IconButton::new("send-message", IconName::Send)
5573 .style(ButtonStyle::Filled)
5574 .map(|this| {
5575 if is_editor_empty && !is_generating {
5576 this.disabled(true).icon_color(Color::Muted)
5577 } else {
5578 this.icon_color(Color::Accent)
5579 }
5580 })
5581 .tooltip(move |_window, cx| {
5582 if is_editor_empty && !is_generating {
5583 Tooltip::for_action("Type to Send", &Chat, cx)
5584 } else {
5585 let title = if is_generating {
5586 "Stop and Send Message"
5587 } else {
5588 "Send"
5589 };
5590
5591 let focus_handle = focus_handle.clone();
5592
5593 Tooltip::element(move |_window, cx| {
5594 v_flex()
5595 .gap_1()
5596 .child(
5597 h_flex()
5598 .gap_2()
5599 .justify_between()
5600 .child(Label::new(title))
5601 .child(KeyBinding::for_action_in(&Chat, &focus_handle, cx)),
5602 )
5603 .child(
5604 h_flex()
5605 .pt_1()
5606 .gap_2()
5607 .justify_between()
5608 .border_t_1()
5609 .border_color(cx.theme().colors().border_variant)
5610 .child(Label::new("Queue Message"))
5611 .child(KeyBinding::for_action_in(
5612 &QueueMessage,
5613 &focus_handle,
5614 cx,
5615 )),
5616 )
5617 .into_any_element()
5618 })(_window, cx)
5619 }
5620 })
5621 .on_click(cx.listener(|this, _, window, cx| {
5622 this.send(window, cx);
5623 }))
5624 .into_any_element()
5625 }
5626 }
5627
5628 fn is_following(&self, cx: &App) -> bool {
5629 match self.thread().map(|thread| thread.read(cx).status()) {
5630 Some(ThreadStatus::Generating) => self
5631 .workspace
5632 .read_with(cx, |workspace, _| {
5633 workspace.is_being_followed(CollaboratorId::Agent)
5634 })
5635 .unwrap_or(false),
5636 _ => self.should_be_following,
5637 }
5638 }
5639
5640 fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5641 let following = self.is_following(cx);
5642
5643 self.should_be_following = !following;
5644 if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
5645 self.workspace
5646 .update(cx, |workspace, cx| {
5647 if following {
5648 workspace.unfollow(CollaboratorId::Agent, window, cx);
5649 } else {
5650 workspace.follow(CollaboratorId::Agent, window, cx);
5651 }
5652 })
5653 .ok();
5654 }
5655
5656 telemetry::event!("Follow Agent Selected", following = !following);
5657 }
5658
5659 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
5660 let following = self.is_following(cx);
5661
5662 let tooltip_label = if following {
5663 if self.agent.name() == "Zed Agent" {
5664 format!("Stop Following the {}", self.agent.name())
5665 } else {
5666 format!("Stop Following {}", self.agent.name())
5667 }
5668 } else {
5669 if self.agent.name() == "Zed Agent" {
5670 format!("Follow the {}", self.agent.name())
5671 } else {
5672 format!("Follow {}", self.agent.name())
5673 }
5674 };
5675
5676 IconButton::new("follow-agent", IconName::Crosshair)
5677 .icon_size(IconSize::Small)
5678 .icon_color(Color::Muted)
5679 .toggle_state(following)
5680 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
5681 .tooltip(move |_window, cx| {
5682 if following {
5683 Tooltip::for_action(tooltip_label.clone(), &Follow, cx)
5684 } else {
5685 Tooltip::with_meta(
5686 tooltip_label.clone(),
5687 Some(&Follow),
5688 "Track the agent's location as it reads and edits files.",
5689 cx,
5690 )
5691 }
5692 })
5693 .on_click(cx.listener(move |this, _, window, cx| {
5694 this.toggle_following(window, cx);
5695 }))
5696 }
5697
5698 fn render_add_context_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5699 let message_editor = self.message_editor.clone();
5700 let menu_visible = message_editor.read(cx).is_completions_menu_visible(cx);
5701
5702 IconButton::new("add-context", IconName::AtSign)
5703 .icon_size(IconSize::Small)
5704 .icon_color(Color::Muted)
5705 .when(!menu_visible, |this| {
5706 this.tooltip(move |_window, cx| {
5707 Tooltip::with_meta("Add Context", None, "Or type @ to include context", cx)
5708 })
5709 })
5710 .on_click(cx.listener(move |_this, _, window, cx| {
5711 let message_editor_clone = message_editor.clone();
5712
5713 window.defer(cx, move |window, cx| {
5714 message_editor_clone.update(cx, |message_editor, cx| {
5715 message_editor.trigger_completion_menu(window, cx);
5716 });
5717 });
5718 }))
5719 }
5720
5721 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
5722 let workspace = self.workspace.clone();
5723 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
5724 Self::open_link(text, &workspace, window, cx);
5725 })
5726 }
5727
5728 fn open_link(
5729 url: SharedString,
5730 workspace: &WeakEntity<Workspace>,
5731 window: &mut Window,
5732 cx: &mut App,
5733 ) {
5734 let Some(workspace) = workspace.upgrade() else {
5735 cx.open_url(&url);
5736 return;
5737 };
5738
5739 if let Some(mention) = MentionUri::parse(&url, workspace.read(cx).path_style(cx)).log_err()
5740 {
5741 workspace.update(cx, |workspace, cx| match mention {
5742 MentionUri::File { abs_path } => {
5743 let project = workspace.project();
5744 let Some(path) =
5745 project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
5746 else {
5747 return;
5748 };
5749
5750 workspace
5751 .open_path(path, None, true, window, cx)
5752 .detach_and_log_err(cx);
5753 }
5754 MentionUri::PastedImage => {}
5755 MentionUri::Directory { abs_path } => {
5756 let project = workspace.project();
5757 let Some(entry_id) = project.update(cx, |project, cx| {
5758 let path = project.find_project_path(abs_path, cx)?;
5759 project.entry_for_path(&path, cx).map(|entry| entry.id)
5760 }) else {
5761 return;
5762 };
5763
5764 project.update(cx, |_, cx| {
5765 cx.emit(project::Event::RevealInProjectPanel(entry_id));
5766 });
5767 }
5768 MentionUri::Symbol {
5769 abs_path: path,
5770 line_range,
5771 ..
5772 }
5773 | MentionUri::Selection {
5774 abs_path: Some(path),
5775 line_range,
5776 } => {
5777 let project = workspace.project();
5778 let Some(path) =
5779 project.update(cx, |project, cx| project.find_project_path(path, cx))
5780 else {
5781 return;
5782 };
5783
5784 let item = workspace.open_path(path, None, true, window, cx);
5785 window
5786 .spawn(cx, async move |cx| {
5787 let Some(editor) = item.await?.downcast::<Editor>() else {
5788 return Ok(());
5789 };
5790 let range = Point::new(*line_range.start(), 0)
5791 ..Point::new(*line_range.start(), 0);
5792 editor
5793 .update_in(cx, |editor, window, cx| {
5794 editor.change_selections(
5795 SelectionEffects::scroll(Autoscroll::center()),
5796 window,
5797 cx,
5798 |s| s.select_ranges(vec![range]),
5799 );
5800 })
5801 .ok();
5802 anyhow::Ok(())
5803 })
5804 .detach_and_log_err(cx);
5805 }
5806 MentionUri::Selection { abs_path: None, .. } => {}
5807 MentionUri::Thread { id, name } => {
5808 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
5809 panel.update(cx, |panel, cx| {
5810 panel.load_agent_thread(
5811 AgentSessionInfo {
5812 session_id: id,
5813 cwd: None,
5814 title: Some(name.into()),
5815 updated_at: None,
5816 meta: None,
5817 },
5818 window,
5819 cx,
5820 )
5821 });
5822 }
5823 }
5824 MentionUri::TextThread { path, .. } => {
5825 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
5826 panel.update(cx, |panel, cx| {
5827 panel
5828 .open_saved_text_thread(path.as_path().into(), window, cx)
5829 .detach_and_log_err(cx);
5830 });
5831 }
5832 }
5833 MentionUri::Rule { id, .. } => {
5834 let PromptId::User { uuid } = id else {
5835 return;
5836 };
5837 window.dispatch_action(
5838 Box::new(OpenRulesLibrary {
5839 prompt_to_select: Some(uuid.0),
5840 }),
5841 cx,
5842 )
5843 }
5844 MentionUri::Fetch { url } => {
5845 cx.open_url(url.as_str());
5846 }
5847 })
5848 } else {
5849 cx.open_url(&url);
5850 }
5851 }
5852
5853 fn open_tool_call_location(
5854 &self,
5855 entry_ix: usize,
5856 location_ix: usize,
5857 window: &mut Window,
5858 cx: &mut Context<Self>,
5859 ) -> Option<()> {
5860 let (tool_call_location, agent_location) = self
5861 .thread()?
5862 .read(cx)
5863 .entries()
5864 .get(entry_ix)?
5865 .location(location_ix)?;
5866
5867 let project_path = self
5868 .project
5869 .read(cx)
5870 .find_project_path(&tool_call_location.path, cx)?;
5871
5872 let open_task = self
5873 .workspace
5874 .update(cx, |workspace, cx| {
5875 workspace.open_path(project_path, None, true, window, cx)
5876 })
5877 .log_err()?;
5878 window
5879 .spawn(cx, async move |cx| {
5880 let item = open_task.await?;
5881
5882 let Some(active_editor) = item.downcast::<Editor>() else {
5883 return anyhow::Ok(());
5884 };
5885
5886 active_editor.update_in(cx, |editor, window, cx| {
5887 let multibuffer = editor.buffer().read(cx);
5888 let buffer = multibuffer.as_singleton();
5889 if agent_location.buffer.upgrade() == buffer {
5890 let excerpt_id = multibuffer.excerpt_ids().first().cloned();
5891 let anchor =
5892 editor::Anchor::in_buffer(excerpt_id.unwrap(), agent_location.position);
5893 editor.change_selections(Default::default(), window, cx, |selections| {
5894 selections.select_anchor_ranges([anchor..anchor]);
5895 })
5896 } else {
5897 let row = tool_call_location.line.unwrap_or_default();
5898 editor.change_selections(Default::default(), window, cx, |selections| {
5899 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
5900 })
5901 }
5902 })?;
5903
5904 anyhow::Ok(())
5905 })
5906 .detach_and_log_err(cx);
5907
5908 None
5909 }
5910
5911 pub fn open_thread_as_markdown(
5912 &self,
5913 workspace: Entity<Workspace>,
5914 window: &mut Window,
5915 cx: &mut App,
5916 ) -> Task<Result<()>> {
5917 let markdown_language_task = workspace
5918 .read(cx)
5919 .app_state()
5920 .languages
5921 .language_for_name("Markdown");
5922
5923 let (thread_title, markdown) = if let Some(thread) = self.thread() {
5924 let thread = thread.read(cx);
5925 (thread.title().to_string(), thread.to_markdown(cx))
5926 } else {
5927 return Task::ready(Ok(()));
5928 };
5929
5930 let project = workspace.read(cx).project().clone();
5931 window.spawn(cx, async move |cx| {
5932 let markdown_language = markdown_language_task.await?;
5933
5934 let buffer = project
5935 .update(cx, |project, cx| project.create_buffer(false, cx))
5936 .await?;
5937
5938 buffer.update(cx, |buffer, cx| {
5939 buffer.set_text(markdown, cx);
5940 buffer.set_language(Some(markdown_language), cx);
5941 buffer.set_capability(language::Capability::ReadWrite, cx);
5942 });
5943
5944 workspace.update_in(cx, |workspace, window, cx| {
5945 let buffer = cx
5946 .new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_title.clone()));
5947
5948 workspace.add_item_to_active_pane(
5949 Box::new(cx.new(|cx| {
5950 let mut editor =
5951 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
5952 editor.set_breadcrumb_header(thread_title);
5953 editor
5954 })),
5955 None,
5956 true,
5957 window,
5958 cx,
5959 );
5960 })?;
5961 anyhow::Ok(())
5962 })
5963 }
5964
5965 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
5966 self.list_state.scroll_to(ListOffset::default());
5967 cx.notify();
5968 }
5969
5970 fn scroll_to_most_recent_user_prompt(&mut self, cx: &mut Context<Self>) {
5971 let Some(thread) = self.thread() else {
5972 return;
5973 };
5974
5975 let entries = thread.read(cx).entries();
5976 if entries.is_empty() {
5977 return;
5978 }
5979
5980 // Find the most recent user message and scroll it to the top of the viewport.
5981 // (Fallback: if no user message exists, scroll to the bottom.)
5982 if let Some(ix) = entries
5983 .iter()
5984 .rposition(|entry| matches!(entry, AgentThreadEntry::UserMessage(_)))
5985 {
5986 self.list_state.scroll_to(ListOffset {
5987 item_ix: ix,
5988 offset_in_item: px(0.0),
5989 });
5990 cx.notify();
5991 } else {
5992 self.scroll_to_bottom(cx);
5993 }
5994 }
5995
5996 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
5997 if let Some(thread) = self.thread() {
5998 let entry_count = thread.read(cx).entries().len();
5999 self.list_state.reset(entry_count);
6000 cx.notify();
6001 }
6002 }
6003
6004 fn notify_with_sound(
6005 &mut self,
6006 caption: impl Into<SharedString>,
6007 icon: IconName,
6008 window: &mut Window,
6009 cx: &mut Context<Self>,
6010 ) {
6011 self.play_notification_sound(window, cx);
6012 self.show_notification(caption, icon, window, cx);
6013 }
6014
6015 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
6016 let settings = AgentSettings::get_global(cx);
6017 if settings.play_sound_when_agent_done && !window.is_window_active() {
6018 Audio::play_sound(Sound::AgentDone, cx);
6019 }
6020 }
6021
6022 fn show_notification(
6023 &mut self,
6024 caption: impl Into<SharedString>,
6025 icon: IconName,
6026 window: &mut Window,
6027 cx: &mut Context<Self>,
6028 ) {
6029 if !self.notifications.is_empty() {
6030 return;
6031 }
6032
6033 let settings = AgentSettings::get_global(cx);
6034
6035 let window_is_inactive = !window.is_window_active();
6036 let panel_is_hidden = self
6037 .workspace
6038 .upgrade()
6039 .map(|workspace| AgentPanel::is_hidden(&workspace, cx))
6040 .unwrap_or(true);
6041
6042 let should_notify = window_is_inactive || panel_is_hidden;
6043
6044 if !should_notify {
6045 return;
6046 }
6047
6048 // TODO: Change this once we have title summarization for external agents.
6049 let title = self.agent.name();
6050
6051 match settings.notify_when_agent_waiting {
6052 NotifyWhenAgentWaiting::PrimaryScreen => {
6053 if let Some(primary) = cx.primary_display() {
6054 self.pop_up(icon, caption.into(), title, window, primary, cx);
6055 }
6056 }
6057 NotifyWhenAgentWaiting::AllScreens => {
6058 let caption = caption.into();
6059 for screen in cx.displays() {
6060 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
6061 }
6062 }
6063 NotifyWhenAgentWaiting::Never => {
6064 // Don't show anything
6065 }
6066 }
6067 }
6068
6069 fn pop_up(
6070 &mut self,
6071 icon: IconName,
6072 caption: SharedString,
6073 title: SharedString,
6074 window: &mut Window,
6075 screen: Rc<dyn PlatformDisplay>,
6076 cx: &mut Context<Self>,
6077 ) {
6078 let options = AgentNotification::window_options(screen, cx);
6079
6080 let project_name = self.workspace.upgrade().and_then(|workspace| {
6081 workspace
6082 .read(cx)
6083 .project()
6084 .read(cx)
6085 .visible_worktrees(cx)
6086 .next()
6087 .map(|worktree| worktree.read(cx).root_name_str().to_string())
6088 });
6089
6090 if let Some(screen_window) = cx
6091 .open_window(options, |_window, cx| {
6092 cx.new(|_cx| {
6093 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
6094 })
6095 })
6096 .log_err()
6097 && let Some(pop_up) = screen_window.entity(cx).log_err()
6098 {
6099 self.notification_subscriptions
6100 .entry(screen_window)
6101 .or_insert_with(Vec::new)
6102 .push(cx.subscribe_in(&pop_up, window, {
6103 |this, _, event, window, cx| match event {
6104 AgentNotificationEvent::Accepted => {
6105 let handle = window.window_handle();
6106 cx.activate(true);
6107
6108 let workspace_handle = this.workspace.clone();
6109
6110 // If there are multiple Zed windows, activate the correct one.
6111 cx.defer(move |cx| {
6112 handle
6113 .update(cx, |_view, window, _cx| {
6114 window.activate_window();
6115
6116 if let Some(workspace) = workspace_handle.upgrade() {
6117 workspace.update(_cx, |workspace, cx| {
6118 workspace.focus_panel::<AgentPanel>(window, cx);
6119 });
6120 }
6121 })
6122 .log_err();
6123 });
6124
6125 this.dismiss_notifications(cx);
6126 }
6127 AgentNotificationEvent::Dismissed => {
6128 this.dismiss_notifications(cx);
6129 }
6130 }
6131 }));
6132
6133 self.notifications.push(screen_window);
6134
6135 // If the user manually refocuses the original window, dismiss the popup.
6136 self.notification_subscriptions
6137 .entry(screen_window)
6138 .or_insert_with(Vec::new)
6139 .push({
6140 let pop_up_weak = pop_up.downgrade();
6141
6142 cx.observe_window_activation(window, move |_, window, cx| {
6143 if window.is_window_active()
6144 && let Some(pop_up) = pop_up_weak.upgrade()
6145 {
6146 pop_up.update(cx, |_, cx| {
6147 cx.emit(AgentNotificationEvent::Dismissed);
6148 });
6149 }
6150 })
6151 });
6152 }
6153 }
6154
6155 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
6156 for window in self.notifications.drain(..) {
6157 window
6158 .update(cx, |_, window, _| {
6159 window.remove_window();
6160 })
6161 .ok();
6162
6163 self.notification_subscriptions.remove(&window);
6164 }
6165 }
6166
6167 fn render_generating(&self, confirmation: bool, cx: &App) -> impl IntoElement {
6168 let show_stats = AgentSettings::get_global(cx).show_turn_stats;
6169 let elapsed_label = show_stats
6170 .then(|| {
6171 self.turn_started_at.and_then(|started_at| {
6172 let elapsed = started_at.elapsed();
6173 (elapsed > STOPWATCH_THRESHOLD).then(|| duration_alt_display(elapsed))
6174 })
6175 })
6176 .flatten();
6177
6178 let is_waiting = confirmation
6179 || self
6180 .thread()
6181 .is_some_and(|thread| thread.read(cx).has_in_progress_tool_calls());
6182
6183 let turn_tokens_label = elapsed_label
6184 .is_some()
6185 .then(|| {
6186 self.turn_tokens
6187 .filter(|&tokens| tokens > TOKEN_THRESHOLD)
6188 .map(|tokens| crate::text_thread_editor::humanize_token_count(tokens))
6189 })
6190 .flatten();
6191
6192 let arrow_icon = if is_waiting {
6193 IconName::ArrowUp
6194 } else {
6195 IconName::ArrowDown
6196 };
6197
6198 h_flex()
6199 .id("generating-spinner")
6200 .py_2()
6201 .px(rems_from_px(22.))
6202 .gap_2()
6203 .map(|this| {
6204 if confirmation {
6205 this.child(
6206 h_flex()
6207 .w_2()
6208 .child(SpinnerLabel::sand().size(LabelSize::Small)),
6209 )
6210 .child(
6211 div().min_w(rems(8.)).child(
6212 LoadingLabel::new("Waiting Confirmation")
6213 .size(LabelSize::Small)
6214 .color(Color::Muted),
6215 ),
6216 )
6217 } else {
6218 this.child(SpinnerLabel::new().size(LabelSize::Small))
6219 }
6220 })
6221 .when_some(elapsed_label, |this, elapsed| {
6222 this.child(
6223 Label::new(elapsed)
6224 .size(LabelSize::Small)
6225 .color(Color::Muted),
6226 )
6227 })
6228 .when_some(turn_tokens_label, |this, tokens| {
6229 this.child(
6230 h_flex()
6231 .gap_0p5()
6232 .child(
6233 Icon::new(arrow_icon)
6234 .size(IconSize::XSmall)
6235 .color(Color::Muted),
6236 )
6237 .child(
6238 Label::new(format!("{} tokens", tokens))
6239 .size(LabelSize::Small)
6240 .color(Color::Muted),
6241 ),
6242 )
6243 })
6244 .into_any_element()
6245 }
6246
6247 fn render_thread_controls(
6248 &self,
6249 thread: &Entity<AcpThread>,
6250 cx: &Context<Self>,
6251 ) -> impl IntoElement {
6252 let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
6253 if is_generating {
6254 return self.render_generating(false, cx).into_any_element();
6255 }
6256
6257 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
6258 .shape(ui::IconButtonShape::Square)
6259 .icon_size(IconSize::Small)
6260 .icon_color(Color::Ignored)
6261 .tooltip(Tooltip::text("Open Thread as Markdown"))
6262 .on_click(cx.listener(move |this, _, window, cx| {
6263 if let Some(workspace) = this.workspace.upgrade() {
6264 this.open_thread_as_markdown(workspace, window, cx)
6265 .detach_and_log_err(cx);
6266 }
6267 }));
6268
6269 let scroll_to_recent_user_prompt =
6270 IconButton::new("scroll_to_recent_user_prompt", IconName::ForwardArrow)
6271 .shape(ui::IconButtonShape::Square)
6272 .icon_size(IconSize::Small)
6273 .icon_color(Color::Ignored)
6274 .tooltip(Tooltip::text("Scroll To Most Recent User Prompt"))
6275 .on_click(cx.listener(move |this, _, _, cx| {
6276 this.scroll_to_most_recent_user_prompt(cx);
6277 }));
6278
6279 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
6280 .shape(ui::IconButtonShape::Square)
6281 .icon_size(IconSize::Small)
6282 .icon_color(Color::Ignored)
6283 .tooltip(Tooltip::text("Scroll To Top"))
6284 .on_click(cx.listener(move |this, _, _, cx| {
6285 this.scroll_to_top(cx);
6286 }));
6287
6288 let show_stats = AgentSettings::get_global(cx).show_turn_stats;
6289 let last_turn_clock = show_stats
6290 .then(|| {
6291 self.last_turn_duration
6292 .filter(|&duration| duration > STOPWATCH_THRESHOLD)
6293 .map(|duration| {
6294 Label::new(duration_alt_display(duration))
6295 .size(LabelSize::Small)
6296 .color(Color::Muted)
6297 })
6298 })
6299 .flatten();
6300
6301 let last_turn_tokens = last_turn_clock
6302 .is_some()
6303 .then(|| {
6304 self.last_turn_tokens
6305 .filter(|&tokens| tokens > TOKEN_THRESHOLD)
6306 .map(|tokens| {
6307 Label::new(format!(
6308 "{} tokens",
6309 crate::text_thread_editor::humanize_token_count(tokens)
6310 ))
6311 .size(LabelSize::Small)
6312 .color(Color::Muted)
6313 })
6314 })
6315 .flatten();
6316
6317 let mut container = h_flex()
6318 .w_full()
6319 .py_2()
6320 .px_5()
6321 .gap_px()
6322 .opacity(0.6)
6323 .hover(|s| s.opacity(1.))
6324 .justify_end()
6325 .when(
6326 last_turn_tokens.is_some() || last_turn_clock.is_some(),
6327 |this| {
6328 this.child(
6329 h_flex()
6330 .gap_1()
6331 .px_1()
6332 .when_some(last_turn_tokens, |this, label| this.child(label))
6333 .when_some(last_turn_clock, |this, label| this.child(label)),
6334 )
6335 },
6336 );
6337
6338 if AgentSettings::get_global(cx).enable_feedback
6339 && self
6340 .thread()
6341 .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
6342 {
6343 let feedback = self.thread_feedback.feedback;
6344
6345 let tooltip_meta = || {
6346 SharedString::new(
6347 "Rating the thread sends all of your current conversation to the Zed team.",
6348 )
6349 };
6350
6351 container = container
6352 .child(
6353 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
6354 .shape(ui::IconButtonShape::Square)
6355 .icon_size(IconSize::Small)
6356 .icon_color(match feedback {
6357 Some(ThreadFeedback::Positive) => Color::Accent,
6358 _ => Color::Ignored,
6359 })
6360 .tooltip(move |window, cx| match feedback {
6361 Some(ThreadFeedback::Positive) => {
6362 Tooltip::text("Thanks for your feedback!")(window, cx)
6363 }
6364 _ => Tooltip::with_meta("Helpful Response", None, tooltip_meta(), cx),
6365 })
6366 .on_click(cx.listener(move |this, _, window, cx| {
6367 this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
6368 })),
6369 )
6370 .child(
6371 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
6372 .shape(ui::IconButtonShape::Square)
6373 .icon_size(IconSize::Small)
6374 .icon_color(match feedback {
6375 Some(ThreadFeedback::Negative) => Color::Accent,
6376 _ => Color::Ignored,
6377 })
6378 .tooltip(move |window, cx| match feedback {
6379 Some(ThreadFeedback::Negative) => {
6380 Tooltip::text(
6381 "We appreciate your feedback and will use it to improve in the future.",
6382 )(window, cx)
6383 }
6384 _ => {
6385 Tooltip::with_meta("Not Helpful Response", None, tooltip_meta(), cx)
6386 }
6387 })
6388 .on_click(cx.listener(move |this, _, window, cx| {
6389 this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
6390 })),
6391 );
6392 }
6393
6394 if cx.has_flag::<AgentSharingFeatureFlag>()
6395 && self.is_imported_thread(cx)
6396 && self
6397 .project
6398 .read(cx)
6399 .client()
6400 .status()
6401 .borrow()
6402 .is_connected()
6403 {
6404 let sync_button = IconButton::new("sync-thread", IconName::ArrowCircle)
6405 .shape(ui::IconButtonShape::Square)
6406 .icon_size(IconSize::Small)
6407 .icon_color(Color::Ignored)
6408 .tooltip(Tooltip::text("Sync with source thread"))
6409 .on_click(cx.listener(move |this, _, window, cx| {
6410 this.sync_thread(window, cx);
6411 }));
6412
6413 container = container.child(sync_button);
6414 }
6415
6416 if cx.has_flag::<AgentSharingFeatureFlag>() && !self.is_imported_thread(cx) {
6417 let share_button = IconButton::new("share-thread", IconName::ArrowUpRight)
6418 .shape(ui::IconButtonShape::Square)
6419 .icon_size(IconSize::Small)
6420 .icon_color(Color::Ignored)
6421 .tooltip(Tooltip::text("Share Thread"))
6422 .on_click(cx.listener(move |this, _, window, cx| {
6423 this.share_thread(window, cx);
6424 }));
6425
6426 container = container.child(share_button);
6427 }
6428
6429 container
6430 .child(open_as_markdown)
6431 .child(scroll_to_recent_user_prompt)
6432 .child(scroll_to_top)
6433 .into_any_element()
6434 }
6435
6436 fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
6437 h_flex()
6438 .key_context("AgentFeedbackMessageEditor")
6439 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
6440 this.thread_feedback.dismiss_comments();
6441 cx.notify();
6442 }))
6443 .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
6444 this.submit_feedback_message(cx);
6445 }))
6446 .p_2()
6447 .mb_2()
6448 .mx_5()
6449 .gap_1()
6450 .rounded_md()
6451 .border_1()
6452 .border_color(cx.theme().colors().border)
6453 .bg(cx.theme().colors().editor_background)
6454 .child(div().w_full().child(editor))
6455 .child(
6456 h_flex()
6457 .child(
6458 IconButton::new("dismiss-feedback-message", IconName::Close)
6459 .icon_color(Color::Error)
6460 .icon_size(IconSize::XSmall)
6461 .shape(ui::IconButtonShape::Square)
6462 .on_click(cx.listener(move |this, _, _window, cx| {
6463 this.thread_feedback.dismiss_comments();
6464 cx.notify();
6465 })),
6466 )
6467 .child(
6468 IconButton::new("submit-feedback-message", IconName::Return)
6469 .icon_size(IconSize::XSmall)
6470 .shape(ui::IconButtonShape::Square)
6471 .on_click(cx.listener(move |this, _, _window, cx| {
6472 this.submit_feedback_message(cx);
6473 })),
6474 ),
6475 )
6476 }
6477
6478 fn handle_feedback_click(
6479 &mut self,
6480 feedback: ThreadFeedback,
6481 window: &mut Window,
6482 cx: &mut Context<Self>,
6483 ) {
6484 let Some(thread) = self.thread().cloned() else {
6485 return;
6486 };
6487
6488 self.thread_feedback.submit(thread, feedback, window, cx);
6489 cx.notify();
6490 }
6491
6492 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
6493 let Some(thread) = self.thread().cloned() else {
6494 return;
6495 };
6496
6497 self.thread_feedback.submit_comments(thread, cx);
6498 cx.notify();
6499 }
6500
6501 fn render_token_limit_callout(&self, cx: &mut Context<Self>) -> Option<Callout> {
6502 if self.token_limit_callout_dismissed {
6503 return None;
6504 }
6505
6506 let token_usage = self.thread()?.read(cx).token_usage()?;
6507 let ratio = token_usage.ratio();
6508
6509 let (severity, icon, title) = match ratio {
6510 acp_thread::TokenUsageRatio::Normal => return None,
6511 acp_thread::TokenUsageRatio::Warning => (
6512 Severity::Warning,
6513 IconName::Warning,
6514 "Thread reaching the token limit soon",
6515 ),
6516 acp_thread::TokenUsageRatio::Exceeded => (
6517 Severity::Error,
6518 IconName::XCircle,
6519 "Thread reached the token limit",
6520 ),
6521 };
6522
6523 let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
6524 thread.read(cx).completion_mode() == CompletionMode::Normal
6525 && thread
6526 .read(cx)
6527 .model()
6528 .is_some_and(|model| model.supports_burn_mode())
6529 });
6530
6531 let description = if burn_mode_available {
6532 "To continue, start a new thread from a summary or turn Burn Mode on."
6533 } else {
6534 "To continue, start a new thread from a summary."
6535 };
6536
6537 Some(
6538 Callout::new()
6539 .severity(severity)
6540 .icon(icon)
6541 .title(title)
6542 .description(description)
6543 .actions_slot(
6544 h_flex()
6545 .gap_0p5()
6546 .child(
6547 Button::new("start-new-thread", "Start New Thread")
6548 .label_size(LabelSize::Small)
6549 .on_click(cx.listener(|this, _, window, cx| {
6550 let Some(thread) = this.thread() else {
6551 return;
6552 };
6553 let session_id = thread.read(cx).session_id().clone();
6554 window.dispatch_action(
6555 crate::NewNativeAgentThreadFromSummary {
6556 from_session_id: session_id,
6557 }
6558 .boxed_clone(),
6559 cx,
6560 );
6561 })),
6562 )
6563 .when(burn_mode_available, |this| {
6564 this.child(
6565 IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
6566 .icon_size(IconSize::XSmall)
6567 .on_click(cx.listener(|this, _event, window, cx| {
6568 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
6569 })),
6570 )
6571 }),
6572 )
6573 .dismiss_action(self.dismiss_error_button(cx)),
6574 )
6575 }
6576
6577 fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
6578 if !self.is_using_zed_ai_models(cx) {
6579 return None;
6580 }
6581
6582 let user_store = self.project.read(cx).user_store().read(cx);
6583 if user_store.is_usage_based_billing_enabled() {
6584 return None;
6585 }
6586
6587 let plan = user_store
6588 .plan()
6589 .unwrap_or(cloud_llm_client::Plan::V1(PlanV1::ZedFree));
6590
6591 let usage = user_store.model_request_usage()?;
6592
6593 Some(
6594 div()
6595 .child(UsageCallout::new(plan, usage))
6596 .line_height(line_height),
6597 )
6598 }
6599
6600 fn agent_ui_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
6601 self.entry_view_state.update(cx, |entry_view_state, cx| {
6602 entry_view_state.agent_ui_font_size_changed(cx);
6603 });
6604 }
6605
6606 pub(crate) fn insert_dragged_files(
6607 &self,
6608 paths: Vec<project::ProjectPath>,
6609 added_worktrees: Vec<Entity<project::Worktree>>,
6610 window: &mut Window,
6611 cx: &mut Context<Self>,
6612 ) {
6613 self.message_editor.update(cx, |message_editor, cx| {
6614 message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
6615 })
6616 }
6617
6618 /// Inserts the selected text into the message editor or the message being
6619 /// edited, if any.
6620 pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
6621 self.active_editor(cx).update(cx, |editor, cx| {
6622 editor.insert_selections(window, cx);
6623 });
6624 }
6625
6626 fn render_thread_retry_status_callout(
6627 &self,
6628 _window: &mut Window,
6629 _cx: &mut Context<Self>,
6630 ) -> Option<Callout> {
6631 let state = self.thread_retry_status.as_ref()?;
6632
6633 let next_attempt_in = state
6634 .duration
6635 .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
6636 if next_attempt_in.is_zero() {
6637 return None;
6638 }
6639
6640 let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
6641
6642 let retry_message = if state.max_attempts == 1 {
6643 if next_attempt_in_secs == 1 {
6644 "Retrying. Next attempt in 1 second.".to_string()
6645 } else {
6646 format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
6647 }
6648 } else if next_attempt_in_secs == 1 {
6649 format!(
6650 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
6651 state.attempt, state.max_attempts,
6652 )
6653 } else {
6654 format!(
6655 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
6656 state.attempt, state.max_attempts,
6657 )
6658 };
6659
6660 Some(
6661 Callout::new()
6662 .severity(Severity::Warning)
6663 .title(state.last_error.clone())
6664 .description(retry_message),
6665 )
6666 }
6667
6668 fn render_codex_windows_warning(&self, cx: &mut Context<Self>) -> Callout {
6669 Callout::new()
6670 .icon(IconName::Warning)
6671 .severity(Severity::Warning)
6672 .title("Codex on Windows")
6673 .description("For best performance, run Codex in Windows Subsystem for Linux (WSL2)")
6674 .actions_slot(
6675 Button::new("open-wsl-modal", "Open in WSL")
6676 .icon_size(IconSize::Small)
6677 .icon_color(Color::Muted)
6678 .on_click(cx.listener({
6679 move |_, _, _window, cx| {
6680 #[cfg(windows)]
6681 _window.dispatch_action(
6682 zed_actions::wsl_actions::OpenWsl::default().boxed_clone(),
6683 cx,
6684 );
6685 cx.notify();
6686 }
6687 })),
6688 )
6689 .dismiss_action(
6690 IconButton::new("dismiss", IconName::Close)
6691 .icon_size(IconSize::Small)
6692 .icon_color(Color::Muted)
6693 .tooltip(Tooltip::text("Dismiss Warning"))
6694 .on_click(cx.listener({
6695 move |this, _, _, cx| {
6696 this.show_codex_windows_warning = false;
6697 cx.notify();
6698 }
6699 })),
6700 )
6701 }
6702
6703 fn render_thread_error(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
6704 let content = match self.thread_error.as_ref()? {
6705 ThreadError::Other(error) => self.render_any_thread_error(error.clone(), window, cx),
6706 ThreadError::Refusal => self.render_refusal_error(cx),
6707 ThreadError::AuthenticationRequired(error) => {
6708 self.render_authentication_required_error(error.clone(), cx)
6709 }
6710 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
6711 ThreadError::ModelRequestLimitReached(plan) => {
6712 self.render_model_request_limit_reached_error(*plan, cx)
6713 }
6714 ThreadError::ToolUseLimitReached => self.render_tool_use_limit_reached_error(cx)?,
6715 };
6716
6717 Some(div().child(content))
6718 }
6719
6720 fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
6721 v_flex().w_full().justify_end().child(
6722 h_flex()
6723 .p_2()
6724 .pr_3()
6725 .w_full()
6726 .gap_1p5()
6727 .border_t_1()
6728 .border_color(cx.theme().colors().border)
6729 .bg(cx.theme().colors().element_background)
6730 .child(
6731 h_flex()
6732 .flex_1()
6733 .gap_1p5()
6734 .child(
6735 Icon::new(IconName::Download)
6736 .color(Color::Accent)
6737 .size(IconSize::Small),
6738 )
6739 .child(Label::new("New version available").size(LabelSize::Small)),
6740 )
6741 .child(
6742 Button::new("update-button", format!("Update to v{}", version))
6743 .label_size(LabelSize::Small)
6744 .style(ButtonStyle::Tinted(TintColor::Accent))
6745 .on_click(cx.listener(|this, _, window, cx| {
6746 this.reset(window, cx);
6747 })),
6748 ),
6749 )
6750 }
6751
6752 fn current_mode_id(&self, cx: &App) -> Option<Arc<str>> {
6753 if let Some(thread) = self.as_native_thread(cx) {
6754 Some(thread.read(cx).profile().0.clone())
6755 } else if let Some(mode_selector) = self.mode_selector() {
6756 Some(mode_selector.read(cx).mode().0)
6757 } else {
6758 None
6759 }
6760 }
6761
6762 fn current_model_id(&self, cx: &App) -> Option<String> {
6763 self.model_selector
6764 .as_ref()
6765 .and_then(|selector| selector.read(cx).active_model(cx).map(|m| m.id.to_string()))
6766 }
6767
6768 fn current_model_name(&self, cx: &App) -> SharedString {
6769 // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
6770 // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
6771 // This provides better clarity about what refused the request
6772 if self.as_native_connection(cx).is_some() {
6773 self.model_selector
6774 .as_ref()
6775 .and_then(|selector| selector.read(cx).active_model(cx))
6776 .map(|model| model.name.clone())
6777 .unwrap_or_else(|| SharedString::from("The model"))
6778 } else {
6779 // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
6780 self.agent.name()
6781 }
6782 }
6783
6784 fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
6785 let model_or_agent_name = self.current_model_name(cx);
6786 let refusal_message = format!(
6787 "{} 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.",
6788 model_or_agent_name
6789 );
6790
6791 Callout::new()
6792 .severity(Severity::Error)
6793 .title("Request Refused")
6794 .icon(IconName::XCircle)
6795 .description(refusal_message.clone())
6796 .actions_slot(self.create_copy_button(&refusal_message))
6797 .dismiss_action(self.dismiss_error_button(cx))
6798 }
6799
6800 fn render_any_thread_error(
6801 &mut self,
6802 error: SharedString,
6803 window: &mut Window,
6804 cx: &mut Context<'_, Self>,
6805 ) -> Callout {
6806 let can_resume = self
6807 .thread()
6808 .map_or(false, |thread| thread.read(cx).can_resume(cx));
6809
6810 let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
6811 let thread = thread.read(cx);
6812 let supports_burn_mode = thread
6813 .model()
6814 .map_or(false, |model| model.supports_burn_mode());
6815 supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
6816 });
6817
6818 let markdown = if let Some(markdown) = &self.thread_error_markdown {
6819 markdown.clone()
6820 } else {
6821 let markdown = cx.new(|cx| Markdown::new(error.clone(), None, None, cx));
6822 self.thread_error_markdown = Some(markdown.clone());
6823 markdown
6824 };
6825
6826 let markdown_style = default_markdown_style(false, true, window, cx);
6827 let description = self
6828 .render_markdown(markdown, markdown_style)
6829 .into_any_element();
6830
6831 Callout::new()
6832 .severity(Severity::Error)
6833 .icon(IconName::XCircle)
6834 .title("An Error Happened")
6835 .description_slot(description)
6836 .actions_slot(
6837 h_flex()
6838 .gap_0p5()
6839 .when(can_resume && can_enable_burn_mode, |this| {
6840 this.child(
6841 Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
6842 .icon(IconName::ZedBurnMode)
6843 .icon_position(IconPosition::Start)
6844 .icon_size(IconSize::Small)
6845 .label_size(LabelSize::Small)
6846 .on_click(cx.listener(|this, _, window, cx| {
6847 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
6848 this.resume_chat(cx);
6849 })),
6850 )
6851 })
6852 .when(can_resume, |this| {
6853 this.child(
6854 IconButton::new("retry", IconName::RotateCw)
6855 .icon_size(IconSize::Small)
6856 .tooltip(Tooltip::text("Retry Generation"))
6857 .on_click(cx.listener(|this, _, _window, cx| {
6858 this.resume_chat(cx);
6859 })),
6860 )
6861 })
6862 .child(self.create_copy_button(error.to_string())),
6863 )
6864 .dismiss_action(self.dismiss_error_button(cx))
6865 }
6866
6867 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
6868 const ERROR_MESSAGE: &str =
6869 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
6870
6871 Callout::new()
6872 .severity(Severity::Error)
6873 .icon(IconName::XCircle)
6874 .title("Free Usage Exceeded")
6875 .description(ERROR_MESSAGE)
6876 .actions_slot(
6877 h_flex()
6878 .gap_0p5()
6879 .child(self.upgrade_button(cx))
6880 .child(self.create_copy_button(ERROR_MESSAGE)),
6881 )
6882 .dismiss_action(self.dismiss_error_button(cx))
6883 }
6884
6885 fn render_authentication_required_error(
6886 &self,
6887 error: SharedString,
6888 cx: &mut Context<Self>,
6889 ) -> Callout {
6890 Callout::new()
6891 .severity(Severity::Error)
6892 .title("Authentication Required")
6893 .icon(IconName::XCircle)
6894 .description(error.clone())
6895 .actions_slot(
6896 h_flex()
6897 .gap_0p5()
6898 .child(self.authenticate_button(cx))
6899 .child(self.create_copy_button(error)),
6900 )
6901 .dismiss_action(self.dismiss_error_button(cx))
6902 }
6903
6904 fn render_model_request_limit_reached_error(
6905 &self,
6906 plan: cloud_llm_client::Plan,
6907 cx: &mut Context<Self>,
6908 ) -> Callout {
6909 let error_message = match plan {
6910 cloud_llm_client::Plan::V1(PlanV1::ZedPro) => {
6911 "Upgrade to usage-based billing for more prompts."
6912 }
6913 cloud_llm_client::Plan::V1(PlanV1::ZedProTrial)
6914 | cloud_llm_client::Plan::V1(PlanV1::ZedFree) => "Upgrade to Zed Pro for more prompts.",
6915 cloud_llm_client::Plan::V2(_) => "",
6916 };
6917
6918 Callout::new()
6919 .severity(Severity::Error)
6920 .title("Model Prompt Limit Reached")
6921 .icon(IconName::XCircle)
6922 .description(error_message)
6923 .actions_slot(
6924 h_flex()
6925 .gap_0p5()
6926 .child(self.upgrade_button(cx))
6927 .child(self.create_copy_button(error_message)),
6928 )
6929 .dismiss_action(self.dismiss_error_button(cx))
6930 }
6931
6932 fn render_tool_use_limit_reached_error(&self, cx: &mut Context<Self>) -> Option<Callout> {
6933 let thread = self.as_native_thread(cx)?;
6934 let supports_burn_mode = thread
6935 .read(cx)
6936 .model()
6937 .is_some_and(|model| model.supports_burn_mode());
6938
6939 let focus_handle = self.focus_handle(cx);
6940
6941 Some(
6942 Callout::new()
6943 .icon(IconName::Info)
6944 .title("Consecutive tool use limit reached.")
6945 .actions_slot(
6946 h_flex()
6947 .gap_0p5()
6948 .when(supports_burn_mode, |this| {
6949 this.child(
6950 Button::new("continue-burn-mode", "Continue with Burn Mode")
6951 .style(ButtonStyle::Filled)
6952 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
6953 .layer(ElevationIndex::ModalSurface)
6954 .label_size(LabelSize::Small)
6955 .key_binding(
6956 KeyBinding::for_action_in(
6957 &ContinueWithBurnMode,
6958 &focus_handle,
6959 cx,
6960 )
6961 .map(|kb| kb.size(rems_from_px(10.))),
6962 )
6963 .tooltip(Tooltip::text(
6964 "Enable Burn Mode for unlimited tool use.",
6965 ))
6966 .on_click({
6967 cx.listener(move |this, _, _window, cx| {
6968 thread.update(cx, |thread, cx| {
6969 thread
6970 .set_completion_mode(CompletionMode::Burn, cx);
6971 });
6972 this.resume_chat(cx);
6973 })
6974 }),
6975 )
6976 })
6977 .child(
6978 Button::new("continue-conversation", "Continue")
6979 .layer(ElevationIndex::ModalSurface)
6980 .label_size(LabelSize::Small)
6981 .key_binding(
6982 KeyBinding::for_action_in(&ContinueThread, &focus_handle, cx)
6983 .map(|kb| kb.size(rems_from_px(10.))),
6984 )
6985 .on_click(cx.listener(|this, _, _window, cx| {
6986 this.resume_chat(cx);
6987 })),
6988 ),
6989 ),
6990 )
6991 }
6992
6993 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
6994 let message = message.into();
6995
6996 CopyButton::new(message).tooltip_label("Copy Error Message")
6997 }
6998
6999 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
7000 IconButton::new("dismiss", IconName::Close)
7001 .icon_size(IconSize::Small)
7002 .tooltip(Tooltip::text("Dismiss"))
7003 .on_click(cx.listener({
7004 move |this, _, _, cx| {
7005 this.clear_thread_error(cx);
7006 cx.notify();
7007 }
7008 }))
7009 }
7010
7011 fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
7012 Button::new("authenticate", "Authenticate")
7013 .label_size(LabelSize::Small)
7014 .style(ButtonStyle::Filled)
7015 .on_click(cx.listener({
7016 move |this, _, window, cx| {
7017 let agent = this.agent.clone();
7018 let ThreadState::Ready { thread, .. } = &this.thread_state else {
7019 return;
7020 };
7021
7022 let connection = thread.read(cx).connection().clone();
7023 this.clear_thread_error(cx);
7024 if let Some(message) = this.in_flight_prompt.take() {
7025 this.message_editor.update(cx, |editor, cx| {
7026 editor.set_message(message, window, cx);
7027 });
7028 }
7029 let this = cx.weak_entity();
7030 window.defer(cx, |window, cx| {
7031 Self::handle_auth_required(
7032 this,
7033 AuthRequired::new(),
7034 agent,
7035 connection,
7036 window,
7037 cx,
7038 );
7039 })
7040 }
7041 }))
7042 }
7043
7044 pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7045 let agent = self.agent.clone();
7046 let ThreadState::Ready { thread, .. } = &self.thread_state else {
7047 return;
7048 };
7049
7050 let connection = thread.read(cx).connection().clone();
7051 self.clear_thread_error(cx);
7052 let this = cx.weak_entity();
7053 window.defer(cx, |window, cx| {
7054 Self::handle_auth_required(this, AuthRequired::new(), agent, connection, window, cx);
7055 })
7056 }
7057
7058 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
7059 Button::new("upgrade", "Upgrade")
7060 .label_size(LabelSize::Small)
7061 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
7062 .on_click(cx.listener({
7063 move |this, _, _, cx| {
7064 this.clear_thread_error(cx);
7065 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
7066 }
7067 }))
7068 }
7069
7070 pub fn delete_history_entry(&mut self, entry: AgentSessionInfo, cx: &mut Context<Self>) {
7071 let Some(session_list) = self.session_list.as_ref() else {
7072 return;
7073 };
7074 let task = session_list.delete_session(&entry.session_id, cx);
7075 task.detach_and_log_err(cx);
7076 }
7077
7078 /// Returns the currently active editor, either for a message that is being
7079 /// edited or the editor for a new message.
7080 fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
7081 if let Some(index) = self.editing_message
7082 && let Some(editor) = self
7083 .entry_view_state
7084 .read(cx)
7085 .entry(index)
7086 .and_then(|e| e.message_editor())
7087 .cloned()
7088 {
7089 editor
7090 } else {
7091 self.message_editor.clone()
7092 }
7093 }
7094}
7095
7096fn loading_contents_spinner(size: IconSize) -> AnyElement {
7097 Icon::new(IconName::LoadCircle)
7098 .size(size)
7099 .color(Color::Accent)
7100 .with_rotate_animation(3)
7101 .into_any_element()
7102}
7103
7104fn placeholder_text(agent_name: &str, has_commands: bool) -> String {
7105 if agent_name == "Zed Agent" {
7106 format!("Message the {} — @ to include context", agent_name)
7107 } else if has_commands {
7108 format!(
7109 "Message {} — @ to include context, / for commands",
7110 agent_name
7111 )
7112 } else {
7113 format!("Message {} — @ to include context", agent_name)
7114 }
7115}
7116
7117impl Focusable for AcpThreadView {
7118 fn focus_handle(&self, cx: &App) -> FocusHandle {
7119 match self.thread_state {
7120 ThreadState::Ready { .. } => self.active_editor(cx).focus_handle(cx),
7121 ThreadState::Loading { .. }
7122 | ThreadState::LoadError(_)
7123 | ThreadState::Unauthenticated { .. } => self.focus_handle.clone(),
7124 }
7125 }
7126}
7127
7128#[cfg(any(test, feature = "test-support"))]
7129impl AcpThreadView {
7130 /// Expands a tool call so its content is visible.
7131 /// This is primarily useful for visual testing.
7132 pub fn expand_tool_call(&mut self, tool_call_id: acp::ToolCallId, cx: &mut Context<Self>) {
7133 self.expanded_tool_calls.insert(tool_call_id);
7134 cx.notify();
7135 }
7136}
7137
7138impl Render for AcpThreadView {
7139 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7140 let has_messages = self.list_state.item_count() > 0;
7141 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
7142
7143 v_flex()
7144 .size_full()
7145 .key_context("AcpThread")
7146 .on_action(cx.listener(|this, _: &menu::Cancel, _, cx| {
7147 this.cancel_generation(cx);
7148 }))
7149 .on_action(cx.listener(Self::toggle_burn_mode))
7150 .on_action(cx.listener(Self::keep_all))
7151 .on_action(cx.listener(Self::reject_all))
7152 .on_action(cx.listener(Self::allow_always))
7153 .on_action(cx.listener(Self::allow_once))
7154 .on_action(cx.listener(Self::reject_once))
7155 .on_action(cx.listener(|this, _: &SendNextQueuedMessage, window, cx| {
7156 this.send_queued_message_at_index(0, true, window, cx);
7157 }))
7158 .on_action(cx.listener(|this, _: &ClearMessageQueue, _, cx| {
7159 this.message_queue.clear();
7160 cx.notify();
7161 }))
7162 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
7163 if let Some(config_options_view) = this.config_options_view.as_ref() {
7164 let handled = config_options_view.update(cx, |view, cx| {
7165 view.toggle_category_picker(
7166 acp::SessionConfigOptionCategory::Mode,
7167 window,
7168 cx,
7169 )
7170 });
7171 if handled {
7172 return;
7173 }
7174 }
7175
7176 if let Some(profile_selector) = this.profile_selector.as_ref() {
7177 profile_selector.read(cx).menu_handle().toggle(window, cx);
7178 } else if let Some(mode_selector) = this.mode_selector() {
7179 mode_selector.read(cx).menu_handle().toggle(window, cx);
7180 }
7181 }))
7182 .on_action(cx.listener(|this, _: &CycleModeSelector, window, cx| {
7183 if let Some(config_options_view) = this.config_options_view.as_ref() {
7184 let handled = config_options_view.update(cx, |view, cx| {
7185 view.cycle_category_option(
7186 acp::SessionConfigOptionCategory::Mode,
7187 false,
7188 cx,
7189 )
7190 });
7191 if handled {
7192 return;
7193 }
7194 }
7195
7196 if let Some(profile_selector) = this.profile_selector.as_ref() {
7197 profile_selector.update(cx, |profile_selector, cx| {
7198 profile_selector.cycle_profile(cx);
7199 });
7200 } else if let Some(mode_selector) = this.mode_selector() {
7201 mode_selector.update(cx, |mode_selector, cx| {
7202 mode_selector.cycle_mode(window, cx);
7203 });
7204 }
7205 }))
7206 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
7207 if let Some(config_options_view) = this.config_options_view.as_ref() {
7208 let handled = config_options_view.update(cx, |view, cx| {
7209 view.toggle_category_picker(
7210 acp::SessionConfigOptionCategory::Model,
7211 window,
7212 cx,
7213 )
7214 });
7215 if handled {
7216 return;
7217 }
7218 }
7219
7220 if let Some(model_selector) = this.model_selector.as_ref() {
7221 model_selector
7222 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
7223 }
7224 }))
7225 .on_action(cx.listener(|this, _: &CycleFavoriteModels, window, cx| {
7226 if let Some(config_options_view) = this.config_options_view.as_ref() {
7227 let handled = config_options_view.update(cx, |view, cx| {
7228 view.cycle_category_option(
7229 acp::SessionConfigOptionCategory::Model,
7230 true,
7231 cx,
7232 )
7233 });
7234 if handled {
7235 return;
7236 }
7237 }
7238
7239 if let Some(model_selector) = this.model_selector.as_ref() {
7240 model_selector.update(cx, |model_selector, cx| {
7241 model_selector.cycle_favorite_models(window, cx);
7242 });
7243 }
7244 }))
7245 .track_focus(&self.focus_handle)
7246 .bg(cx.theme().colors().panel_background)
7247 .child(match &self.thread_state {
7248 ThreadState::Unauthenticated {
7249 connection,
7250 description,
7251 configuration_view,
7252 pending_auth_method,
7253 ..
7254 } => v_flex()
7255 .flex_1()
7256 .size_full()
7257 .justify_end()
7258 .child(self.render_auth_required_state(
7259 connection,
7260 description.as_ref(),
7261 configuration_view.as_ref(),
7262 pending_auth_method.as_ref(),
7263 window,
7264 cx,
7265 ))
7266 .into_any_element(),
7267 ThreadState::Loading { .. } => v_flex()
7268 .flex_1()
7269 .child(self.render_recent_history(cx))
7270 .into_any(),
7271 ThreadState::LoadError(e) => v_flex()
7272 .flex_1()
7273 .size_full()
7274 .items_center()
7275 .justify_end()
7276 .child(self.render_load_error(e, window, cx))
7277 .into_any(),
7278 ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
7279 if has_messages {
7280 this.child(
7281 list(
7282 self.list_state.clone(),
7283 cx.processor(|this, index: usize, window, cx| {
7284 let Some((entry, len)) = this.thread().and_then(|thread| {
7285 let entries = &thread.read(cx).entries();
7286 Some((entries.get(index)?, entries.len()))
7287 }) else {
7288 return Empty.into_any();
7289 };
7290 this.render_entry(index, len, entry, window, cx)
7291 }),
7292 )
7293 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
7294 .flex_grow()
7295 .into_any(),
7296 )
7297 .vertical_scrollbar_for(&self.list_state, window, cx)
7298 .into_any()
7299 } else {
7300 this.child(self.render_recent_history(cx)).into_any()
7301 }
7302 }),
7303 })
7304 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
7305 // above so that the scrollbar doesn't render behind it. The current setup allows
7306 // the scrollbar to stop exactly at the activity bar start.
7307 .when(has_messages, |this| match &self.thread_state {
7308 ThreadState::Ready { thread, .. } => {
7309 this.children(self.render_activity_bar(thread, window, cx))
7310 }
7311 _ => this,
7312 })
7313 .children(self.render_thread_retry_status_callout(window, cx))
7314 .when(self.show_codex_windows_warning, |this| {
7315 this.child(self.render_codex_windows_warning(cx))
7316 })
7317 .children(self.render_thread_error(window, cx))
7318 .when_some(
7319 self.new_server_version_available.as_ref().filter(|_| {
7320 !has_messages || !matches!(self.thread_state, ThreadState::Ready { .. })
7321 }),
7322 |this, version| this.child(self.render_new_version_callout(&version, cx)),
7323 )
7324 .children(
7325 if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
7326 Some(usage_callout.into_any_element())
7327 } else {
7328 self.render_token_limit_callout(cx)
7329 .map(|token_limit_callout| token_limit_callout.into_any_element())
7330 },
7331 )
7332 .child(self.render_message_editor(window, cx))
7333 }
7334}
7335
7336fn default_markdown_style(
7337 buffer_font: bool,
7338 muted_text: bool,
7339 window: &Window,
7340 cx: &App,
7341) -> MarkdownStyle {
7342 let theme_settings = ThemeSettings::get_global(cx);
7343 let colors = cx.theme().colors();
7344
7345 let buffer_font_size = theme_settings.agent_buffer_font_size(cx);
7346
7347 let mut text_style = window.text_style();
7348 let line_height = buffer_font_size * 1.75;
7349
7350 let font_family = if buffer_font {
7351 theme_settings.buffer_font.family.clone()
7352 } else {
7353 theme_settings.ui_font.family.clone()
7354 };
7355
7356 let font_size = if buffer_font {
7357 theme_settings.agent_buffer_font_size(cx)
7358 } else {
7359 theme_settings.agent_ui_font_size(cx)
7360 };
7361
7362 let text_color = if muted_text {
7363 colors.text_muted
7364 } else {
7365 colors.text
7366 };
7367
7368 text_style.refine(&TextStyleRefinement {
7369 font_family: Some(font_family),
7370 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
7371 font_features: Some(theme_settings.ui_font.features.clone()),
7372 font_size: Some(font_size.into()),
7373 line_height: Some(line_height.into()),
7374 color: Some(text_color),
7375 ..Default::default()
7376 });
7377
7378 MarkdownStyle {
7379 base_text_style: text_style.clone(),
7380 syntax: cx.theme().syntax().clone(),
7381 selection_background_color: colors.element_selection_background,
7382 code_block_overflow_x_scroll: true,
7383 heading_level_styles: Some(HeadingLevelStyles {
7384 h1: Some(TextStyleRefinement {
7385 font_size: Some(rems(1.15).into()),
7386 ..Default::default()
7387 }),
7388 h2: Some(TextStyleRefinement {
7389 font_size: Some(rems(1.1).into()),
7390 ..Default::default()
7391 }),
7392 h3: Some(TextStyleRefinement {
7393 font_size: Some(rems(1.05).into()),
7394 ..Default::default()
7395 }),
7396 h4: Some(TextStyleRefinement {
7397 font_size: Some(rems(1.).into()),
7398 ..Default::default()
7399 }),
7400 h5: Some(TextStyleRefinement {
7401 font_size: Some(rems(0.95).into()),
7402 ..Default::default()
7403 }),
7404 h6: Some(TextStyleRefinement {
7405 font_size: Some(rems(0.875).into()),
7406 ..Default::default()
7407 }),
7408 }),
7409 code_block: StyleRefinement {
7410 padding: EdgesRefinement {
7411 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
7412 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
7413 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
7414 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
7415 },
7416 margin: EdgesRefinement {
7417 top: Some(Length::Definite(px(8.).into())),
7418 left: Some(Length::Definite(px(0.).into())),
7419 right: Some(Length::Definite(px(0.).into())),
7420 bottom: Some(Length::Definite(px(12.).into())),
7421 },
7422 border_style: Some(BorderStyle::Solid),
7423 border_widths: EdgesRefinement {
7424 top: Some(AbsoluteLength::Pixels(px(1.))),
7425 left: Some(AbsoluteLength::Pixels(px(1.))),
7426 right: Some(AbsoluteLength::Pixels(px(1.))),
7427 bottom: Some(AbsoluteLength::Pixels(px(1.))),
7428 },
7429 border_color: Some(colors.border_variant),
7430 background: Some(colors.editor_background.into()),
7431 text: TextStyleRefinement {
7432 font_family: Some(theme_settings.buffer_font.family.clone()),
7433 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
7434 font_features: Some(theme_settings.buffer_font.features.clone()),
7435 font_size: Some(buffer_font_size.into()),
7436 ..Default::default()
7437 },
7438 ..Default::default()
7439 },
7440 inline_code: TextStyleRefinement {
7441 font_family: Some(theme_settings.buffer_font.family.clone()),
7442 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
7443 font_features: Some(theme_settings.buffer_font.features.clone()),
7444 font_size: Some(buffer_font_size.into()),
7445 background_color: Some(colors.editor_foreground.opacity(0.08)),
7446 ..Default::default()
7447 },
7448 link: TextStyleRefinement {
7449 background_color: Some(colors.editor_foreground.opacity(0.025)),
7450 color: Some(colors.text_accent),
7451 underline: Some(UnderlineStyle {
7452 color: Some(colors.text_accent.opacity(0.5)),
7453 thickness: px(1.),
7454 ..Default::default()
7455 }),
7456 ..Default::default()
7457 },
7458 ..Default::default()
7459 }
7460}
7461
7462fn plan_label_markdown_style(
7463 status: &acp::PlanEntryStatus,
7464 window: &Window,
7465 cx: &App,
7466) -> MarkdownStyle {
7467 let default_md_style = default_markdown_style(false, false, window, cx);
7468
7469 MarkdownStyle {
7470 base_text_style: TextStyle {
7471 color: cx.theme().colors().text_muted,
7472 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
7473 Some(gpui::StrikethroughStyle {
7474 thickness: px(1.),
7475 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
7476 })
7477 } else {
7478 None
7479 },
7480 ..default_md_style.base_text_style
7481 },
7482 ..default_md_style
7483 }
7484}
7485
7486fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
7487 let default_md_style = default_markdown_style(true, false, window, cx);
7488
7489 MarkdownStyle {
7490 base_text_style: TextStyle {
7491 ..default_md_style.base_text_style
7492 },
7493 selection_background_color: cx.theme().colors().element_selection_background,
7494 ..Default::default()
7495 }
7496}
7497
7498#[cfg(test)]
7499pub(crate) mod tests {
7500 use acp_thread::{AgentSessionListResponse, StubAgentConnection};
7501 use action_log::ActionLog;
7502 use agent_client_protocol::SessionId;
7503 use editor::MultiBufferOffset;
7504 use fs::FakeFs;
7505 use gpui::{EventEmitter, TestAppContext, VisualTestContext};
7506 use project::Project;
7507 use serde_json::json;
7508 use settings::SettingsStore;
7509 use std::any::Any;
7510 use std::path::Path;
7511 use std::rc::Rc;
7512 use workspace::Item;
7513
7514 use super::*;
7515
7516 #[gpui::test]
7517 async fn test_drop(cx: &mut TestAppContext) {
7518 init_test(cx);
7519
7520 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7521 let weak_view = thread_view.downgrade();
7522 drop(thread_view);
7523 assert!(!weak_view.is_upgradable());
7524 }
7525
7526 #[gpui::test]
7527 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
7528 init_test(cx);
7529
7530 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7531
7532 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7533 message_editor.update_in(cx, |editor, window, cx| {
7534 editor.set_text("Hello", window, cx);
7535 });
7536
7537 cx.deactivate_window();
7538
7539 thread_view.update_in(cx, |thread_view, window, cx| {
7540 thread_view.send(window, cx);
7541 });
7542
7543 cx.run_until_parked();
7544
7545 assert!(
7546 cx.windows()
7547 .iter()
7548 .any(|window| window.downcast::<AgentNotification>().is_some())
7549 );
7550 }
7551
7552 #[gpui::test]
7553 async fn test_notification_for_error(cx: &mut TestAppContext) {
7554 init_test(cx);
7555
7556 let (thread_view, cx) =
7557 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
7558
7559 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7560 message_editor.update_in(cx, |editor, window, cx| {
7561 editor.set_text("Hello", window, cx);
7562 });
7563
7564 cx.deactivate_window();
7565
7566 thread_view.update_in(cx, |thread_view, window, cx| {
7567 thread_view.send(window, cx);
7568 });
7569
7570 cx.run_until_parked();
7571
7572 assert!(
7573 cx.windows()
7574 .iter()
7575 .any(|window| window.downcast::<AgentNotification>().is_some())
7576 );
7577 }
7578
7579 #[gpui::test]
7580 async fn test_recent_history_refreshes_when_session_list_swapped(cx: &mut TestAppContext) {
7581 init_test(cx);
7582
7583 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7584
7585 let session_a = AgentSessionInfo::new(SessionId::new("session-a"));
7586 let session_b = AgentSessionInfo::new(SessionId::new("session-b"));
7587
7588 let list_a: Rc<dyn AgentSessionList> =
7589 Rc::new(StubSessionList::new(vec![session_a.clone()]));
7590 let list_b: Rc<dyn AgentSessionList> =
7591 Rc::new(StubSessionList::new(vec![session_b.clone()]));
7592
7593 thread_view.update(cx, |view, cx| {
7594 view.set_session_list(Some(list_a.clone()), cx);
7595 });
7596 cx.run_until_parked();
7597
7598 thread_view.read_with(cx, |view, _cx| {
7599 assert_eq!(view.recent_history_entries.len(), 1);
7600 assert_eq!(
7601 view.recent_history_entries[0].session_id,
7602 session_a.session_id
7603 );
7604
7605 let session_list = view.session_list_state.borrow();
7606 let session_list = session_list.as_ref().expect("session list should be set");
7607 assert!(Rc::ptr_eq(session_list, &list_a));
7608 });
7609
7610 thread_view.update(cx, |view, cx| {
7611 view.set_session_list(Some(list_b.clone()), cx);
7612 });
7613 cx.run_until_parked();
7614
7615 thread_view.read_with(cx, |view, _cx| {
7616 assert_eq!(view.recent_history_entries.len(), 1);
7617 assert_eq!(
7618 view.recent_history_entries[0].session_id,
7619 session_b.session_id
7620 );
7621
7622 let session_list = view.session_list_state.borrow();
7623 let session_list = session_list.as_ref().expect("session list should be set");
7624 assert!(Rc::ptr_eq(session_list, &list_b));
7625 });
7626 }
7627
7628 #[gpui::test]
7629 async fn test_refusal_handling(cx: &mut TestAppContext) {
7630 init_test(cx);
7631
7632 let (thread_view, cx) =
7633 setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
7634
7635 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7636 message_editor.update_in(cx, |editor, window, cx| {
7637 editor.set_text("Do something harmful", window, cx);
7638 });
7639
7640 thread_view.update_in(cx, |thread_view, window, cx| {
7641 thread_view.send(window, cx);
7642 });
7643
7644 cx.run_until_parked();
7645
7646 // Check that the refusal error is set
7647 thread_view.read_with(cx, |thread_view, _cx| {
7648 assert!(
7649 matches!(thread_view.thread_error, Some(ThreadError::Refusal)),
7650 "Expected refusal error to be set"
7651 );
7652 });
7653 }
7654
7655 #[gpui::test]
7656 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
7657 init_test(cx);
7658
7659 let tool_call_id = acp::ToolCallId::new("1");
7660 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Label")
7661 .kind(acp::ToolKind::Edit)
7662 .content(vec!["hi".into()]);
7663 let connection =
7664 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
7665 tool_call_id,
7666 vec![acp::PermissionOption::new(
7667 "1",
7668 "Allow",
7669 acp::PermissionOptionKind::AllowOnce,
7670 )],
7671 )]));
7672
7673 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
7674
7675 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
7676
7677 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7678 message_editor.update_in(cx, |editor, window, cx| {
7679 editor.set_text("Hello", window, cx);
7680 });
7681
7682 cx.deactivate_window();
7683
7684 thread_view.update_in(cx, |thread_view, window, cx| {
7685 thread_view.send(window, cx);
7686 });
7687
7688 cx.run_until_parked();
7689
7690 assert!(
7691 cx.windows()
7692 .iter()
7693 .any(|window| window.downcast::<AgentNotification>().is_some())
7694 );
7695 }
7696
7697 #[gpui::test]
7698 async fn test_notification_when_panel_hidden(cx: &mut TestAppContext) {
7699 init_test(cx);
7700
7701 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7702
7703 add_to_workspace(thread_view.clone(), cx);
7704
7705 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7706
7707 message_editor.update_in(cx, |editor, window, cx| {
7708 editor.set_text("Hello", window, cx);
7709 });
7710
7711 // Window is active (don't deactivate), but panel will be hidden
7712 // Note: In the test environment, the panel is not actually added to the dock,
7713 // so is_agent_panel_hidden will return true
7714
7715 thread_view.update_in(cx, |thread_view, window, cx| {
7716 thread_view.send(window, cx);
7717 });
7718
7719 cx.run_until_parked();
7720
7721 // Should show notification because window is active but panel is hidden
7722 assert!(
7723 cx.windows()
7724 .iter()
7725 .any(|window| window.downcast::<AgentNotification>().is_some()),
7726 "Expected notification when panel is hidden"
7727 );
7728 }
7729
7730 #[gpui::test]
7731 async fn test_notification_still_works_when_window_inactive(cx: &mut TestAppContext) {
7732 init_test(cx);
7733
7734 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7735
7736 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7737 message_editor.update_in(cx, |editor, window, cx| {
7738 editor.set_text("Hello", window, cx);
7739 });
7740
7741 // Deactivate window - should show notification regardless of setting
7742 cx.deactivate_window();
7743
7744 thread_view.update_in(cx, |thread_view, window, cx| {
7745 thread_view.send(window, cx);
7746 });
7747
7748 cx.run_until_parked();
7749
7750 // Should still show notification when window is inactive (existing behavior)
7751 assert!(
7752 cx.windows()
7753 .iter()
7754 .any(|window| window.downcast::<AgentNotification>().is_some()),
7755 "Expected notification when window is inactive"
7756 );
7757 }
7758
7759 #[gpui::test]
7760 async fn test_notification_respects_never_setting(cx: &mut TestAppContext) {
7761 init_test(cx);
7762
7763 // Set notify_when_agent_waiting to Never
7764 cx.update(|cx| {
7765 AgentSettings::override_global(
7766 AgentSettings {
7767 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
7768 ..AgentSettings::get_global(cx).clone()
7769 },
7770 cx,
7771 );
7772 });
7773
7774 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7775
7776 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7777 message_editor.update_in(cx, |editor, window, cx| {
7778 editor.set_text("Hello", window, cx);
7779 });
7780
7781 // Window is active
7782
7783 thread_view.update_in(cx, |thread_view, window, cx| {
7784 thread_view.send(window, cx);
7785 });
7786
7787 cx.run_until_parked();
7788
7789 // Should NOT show notification because notify_when_agent_waiting is Never
7790 assert!(
7791 !cx.windows()
7792 .iter()
7793 .any(|window| window.downcast::<AgentNotification>().is_some()),
7794 "Expected no notification when notify_when_agent_waiting is Never"
7795 );
7796 }
7797
7798 #[gpui::test]
7799 async fn test_notification_closed_when_thread_view_dropped(cx: &mut TestAppContext) {
7800 init_test(cx);
7801
7802 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7803
7804 let weak_view = thread_view.downgrade();
7805
7806 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7807 message_editor.update_in(cx, |editor, window, cx| {
7808 editor.set_text("Hello", window, cx);
7809 });
7810
7811 cx.deactivate_window();
7812
7813 thread_view.update_in(cx, |thread_view, window, cx| {
7814 thread_view.send(window, cx);
7815 });
7816
7817 cx.run_until_parked();
7818
7819 // Verify notification is shown
7820 assert!(
7821 cx.windows()
7822 .iter()
7823 .any(|window| window.downcast::<AgentNotification>().is_some()),
7824 "Expected notification to be shown"
7825 );
7826
7827 // Drop the thread view (simulating navigation to a new thread)
7828 drop(thread_view);
7829 drop(message_editor);
7830 // Trigger an update to flush effects, which will call release_dropped_entities
7831 cx.update(|_window, _cx| {});
7832 cx.run_until_parked();
7833
7834 // Verify the entity was actually released
7835 assert!(
7836 !weak_view.is_upgradable(),
7837 "Thread view entity should be released after dropping"
7838 );
7839
7840 // The notification should be automatically closed via on_release
7841 assert!(
7842 !cx.windows()
7843 .iter()
7844 .any(|window| window.downcast::<AgentNotification>().is_some()),
7845 "Notification should be closed when thread view is dropped"
7846 );
7847 }
7848
7849 async fn setup_thread_view(
7850 agent: impl AgentServer + 'static,
7851 cx: &mut TestAppContext,
7852 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
7853 let fs = FakeFs::new(cx.executor());
7854 let project = Project::test(fs, [], cx).await;
7855 let (workspace, cx) =
7856 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7857
7858 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
7859
7860 let thread_view = cx.update(|window, cx| {
7861 cx.new(|cx| {
7862 AcpThreadView::new(
7863 Rc::new(agent),
7864 None,
7865 None,
7866 workspace.downgrade(),
7867 project,
7868 Some(thread_store),
7869 None,
7870 false,
7871 window,
7872 cx,
7873 )
7874 })
7875 });
7876 cx.run_until_parked();
7877 (thread_view, cx)
7878 }
7879
7880 fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
7881 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
7882
7883 workspace
7884 .update_in(cx, |workspace, window, cx| {
7885 workspace.add_item_to_active_pane(
7886 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
7887 None,
7888 true,
7889 window,
7890 cx,
7891 );
7892 })
7893 .unwrap();
7894 }
7895
7896 struct ThreadViewItem(Entity<AcpThreadView>);
7897
7898 impl Item for ThreadViewItem {
7899 type Event = ();
7900
7901 fn include_in_nav_history() -> bool {
7902 false
7903 }
7904
7905 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
7906 "Test".into()
7907 }
7908 }
7909
7910 impl EventEmitter<()> for ThreadViewItem {}
7911
7912 impl Focusable for ThreadViewItem {
7913 fn focus_handle(&self, cx: &App) -> FocusHandle {
7914 self.0.read(cx).focus_handle(cx)
7915 }
7916 }
7917
7918 impl Render for ThreadViewItem {
7919 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7920 self.0.clone().into_any_element()
7921 }
7922 }
7923
7924 struct StubAgentServer<C> {
7925 connection: C,
7926 }
7927
7928 impl<C> StubAgentServer<C> {
7929 fn new(connection: C) -> Self {
7930 Self { connection }
7931 }
7932 }
7933
7934 impl StubAgentServer<StubAgentConnection> {
7935 fn default_response() -> Self {
7936 let conn = StubAgentConnection::new();
7937 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
7938 acp::ContentChunk::new("Default response".into()),
7939 )]);
7940 Self::new(conn)
7941 }
7942 }
7943
7944 #[derive(Clone)]
7945 struct StubSessionList {
7946 sessions: Vec<AgentSessionInfo>,
7947 }
7948
7949 impl StubSessionList {
7950 fn new(sessions: Vec<AgentSessionInfo>) -> Self {
7951 Self { sessions }
7952 }
7953 }
7954
7955 impl AgentSessionList for StubSessionList {
7956 fn list_sessions(
7957 &self,
7958 _request: AgentSessionListRequest,
7959 _cx: &mut App,
7960 ) -> Task<anyhow::Result<AgentSessionListResponse>> {
7961 Task::ready(Ok(AgentSessionListResponse::new(self.sessions.clone())))
7962 }
7963 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
7964 self
7965 }
7966 }
7967
7968 impl<C> AgentServer for StubAgentServer<C>
7969 where
7970 C: 'static + AgentConnection + Send + Clone,
7971 {
7972 fn logo(&self) -> ui::IconName {
7973 ui::IconName::Ai
7974 }
7975
7976 fn name(&self) -> SharedString {
7977 "Test".into()
7978 }
7979
7980 fn connect(
7981 &self,
7982 _root_dir: Option<&Path>,
7983 _delegate: AgentServerDelegate,
7984 _cx: &mut App,
7985 ) -> Task<gpui::Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
7986 Task::ready(Ok((Rc::new(self.connection.clone()), None)))
7987 }
7988
7989 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
7990 self
7991 }
7992 }
7993
7994 #[derive(Clone)]
7995 struct SaboteurAgentConnection;
7996
7997 impl AgentConnection for SaboteurAgentConnection {
7998 fn telemetry_id(&self) -> SharedString {
7999 "saboteur".into()
8000 }
8001
8002 fn new_thread(
8003 self: Rc<Self>,
8004 project: Entity<Project>,
8005 _cwd: &Path,
8006 cx: &mut gpui::App,
8007 ) -> Task<gpui::Result<Entity<AcpThread>>> {
8008 Task::ready(Ok(cx.new(|cx| {
8009 let action_log = cx.new(|_| ActionLog::new(project.clone()));
8010 AcpThread::new(
8011 "SaboteurAgentConnection",
8012 self,
8013 project,
8014 action_log,
8015 SessionId::new("test"),
8016 watch::Receiver::constant(
8017 acp::PromptCapabilities::new()
8018 .image(true)
8019 .audio(true)
8020 .embedded_context(true),
8021 ),
8022 cx,
8023 )
8024 })))
8025 }
8026
8027 fn auth_methods(&self) -> &[acp::AuthMethod] {
8028 &[]
8029 }
8030
8031 fn authenticate(
8032 &self,
8033 _method_id: acp::AuthMethodId,
8034 _cx: &mut App,
8035 ) -> Task<gpui::Result<()>> {
8036 unimplemented!()
8037 }
8038
8039 fn prompt(
8040 &self,
8041 _id: Option<acp_thread::UserMessageId>,
8042 _params: acp::PromptRequest,
8043 _cx: &mut App,
8044 ) -> Task<gpui::Result<acp::PromptResponse>> {
8045 Task::ready(Err(anyhow::anyhow!("Error prompting")))
8046 }
8047
8048 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
8049 unimplemented!()
8050 }
8051
8052 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
8053 self
8054 }
8055 }
8056
8057 /// Simulates a model which always returns a refusal response
8058 #[derive(Clone)]
8059 struct RefusalAgentConnection;
8060
8061 impl AgentConnection for RefusalAgentConnection {
8062 fn telemetry_id(&self) -> SharedString {
8063 "refusal".into()
8064 }
8065
8066 fn new_thread(
8067 self: Rc<Self>,
8068 project: Entity<Project>,
8069 _cwd: &Path,
8070 cx: &mut gpui::App,
8071 ) -> Task<gpui::Result<Entity<AcpThread>>> {
8072 Task::ready(Ok(cx.new(|cx| {
8073 let action_log = cx.new(|_| ActionLog::new(project.clone()));
8074 AcpThread::new(
8075 "RefusalAgentConnection",
8076 self,
8077 project,
8078 action_log,
8079 SessionId::new("test"),
8080 watch::Receiver::constant(
8081 acp::PromptCapabilities::new()
8082 .image(true)
8083 .audio(true)
8084 .embedded_context(true),
8085 ),
8086 cx,
8087 )
8088 })))
8089 }
8090
8091 fn auth_methods(&self) -> &[acp::AuthMethod] {
8092 &[]
8093 }
8094
8095 fn authenticate(
8096 &self,
8097 _method_id: acp::AuthMethodId,
8098 _cx: &mut App,
8099 ) -> Task<gpui::Result<()>> {
8100 unimplemented!()
8101 }
8102
8103 fn prompt(
8104 &self,
8105 _id: Option<acp_thread::UserMessageId>,
8106 _params: acp::PromptRequest,
8107 _cx: &mut App,
8108 ) -> Task<gpui::Result<acp::PromptResponse>> {
8109 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::Refusal)))
8110 }
8111
8112 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
8113 unimplemented!()
8114 }
8115
8116 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
8117 self
8118 }
8119 }
8120
8121 pub(crate) fn init_test(cx: &mut TestAppContext) {
8122 cx.update(|cx| {
8123 let settings_store = SettingsStore::test(cx);
8124 cx.set_global(settings_store);
8125 theme::init(theme::LoadThemes::JustBase, cx);
8126 release_channel::init(semver::Version::new(0, 0, 0), cx);
8127 prompt_store::init(cx)
8128 });
8129 }
8130
8131 #[gpui::test]
8132 async fn test_rewind_views(cx: &mut TestAppContext) {
8133 init_test(cx);
8134
8135 let fs = FakeFs::new(cx.executor());
8136 fs.insert_tree(
8137 "/project",
8138 json!({
8139 "test1.txt": "old content 1",
8140 "test2.txt": "old content 2"
8141 }),
8142 )
8143 .await;
8144 let project = Project::test(fs, [Path::new("/project")], cx).await;
8145 let (workspace, cx) =
8146 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8147
8148 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
8149
8150 let connection = Rc::new(StubAgentConnection::new());
8151 let thread_view = cx.update(|window, cx| {
8152 cx.new(|cx| {
8153 AcpThreadView::new(
8154 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
8155 None,
8156 None,
8157 workspace.downgrade(),
8158 project.clone(),
8159 Some(thread_store.clone()),
8160 None,
8161 false,
8162 window,
8163 cx,
8164 )
8165 })
8166 });
8167
8168 cx.run_until_parked();
8169
8170 let thread = thread_view
8171 .read_with(cx, |view, _| view.thread().cloned())
8172 .unwrap();
8173
8174 // First user message
8175 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
8176 acp::ToolCall::new("tool1", "Edit file 1")
8177 .kind(acp::ToolKind::Edit)
8178 .status(acp::ToolCallStatus::Completed)
8179 .content(vec![acp::ToolCallContent::Diff(
8180 acp::Diff::new("/project/test1.txt", "new content 1").old_text("old content 1"),
8181 )]),
8182 )]);
8183
8184 thread
8185 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
8186 .await
8187 .unwrap();
8188 cx.run_until_parked();
8189
8190 thread.read_with(cx, |thread, _| {
8191 assert_eq!(thread.entries().len(), 2);
8192 });
8193
8194 thread_view.read_with(cx, |view, cx| {
8195 view.entry_view_state.read_with(cx, |entry_view_state, _| {
8196 assert!(
8197 entry_view_state
8198 .entry(0)
8199 .unwrap()
8200 .message_editor()
8201 .is_some()
8202 );
8203 assert!(entry_view_state.entry(1).unwrap().has_content());
8204 });
8205 });
8206
8207 // Second user message
8208 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
8209 acp::ToolCall::new("tool2", "Edit file 2")
8210 .kind(acp::ToolKind::Edit)
8211 .status(acp::ToolCallStatus::Completed)
8212 .content(vec![acp::ToolCallContent::Diff(
8213 acp::Diff::new("/project/test2.txt", "new content 2").old_text("old content 2"),
8214 )]),
8215 )]);
8216
8217 thread
8218 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
8219 .await
8220 .unwrap();
8221 cx.run_until_parked();
8222
8223 let second_user_message_id = thread.read_with(cx, |thread, _| {
8224 assert_eq!(thread.entries().len(), 4);
8225 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
8226 panic!();
8227 };
8228 user_message.id.clone().unwrap()
8229 });
8230
8231 thread_view.read_with(cx, |view, cx| {
8232 view.entry_view_state.read_with(cx, |entry_view_state, _| {
8233 assert!(
8234 entry_view_state
8235 .entry(0)
8236 .unwrap()
8237 .message_editor()
8238 .is_some()
8239 );
8240 assert!(entry_view_state.entry(1).unwrap().has_content());
8241 assert!(
8242 entry_view_state
8243 .entry(2)
8244 .unwrap()
8245 .message_editor()
8246 .is_some()
8247 );
8248 assert!(entry_view_state.entry(3).unwrap().has_content());
8249 });
8250 });
8251
8252 // Rewind to first message
8253 thread
8254 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
8255 .await
8256 .unwrap();
8257
8258 cx.run_until_parked();
8259
8260 thread.read_with(cx, |thread, _| {
8261 assert_eq!(thread.entries().len(), 2);
8262 });
8263
8264 thread_view.read_with(cx, |view, cx| {
8265 view.entry_view_state.read_with(cx, |entry_view_state, _| {
8266 assert!(
8267 entry_view_state
8268 .entry(0)
8269 .unwrap()
8270 .message_editor()
8271 .is_some()
8272 );
8273 assert!(entry_view_state.entry(1).unwrap().has_content());
8274
8275 // Old views should be dropped
8276 assert!(entry_view_state.entry(2).is_none());
8277 assert!(entry_view_state.entry(3).is_none());
8278 });
8279 });
8280 }
8281
8282 #[gpui::test]
8283 async fn test_scroll_to_most_recent_user_prompt(cx: &mut TestAppContext) {
8284 init_test(cx);
8285
8286 let connection = StubAgentConnection::new();
8287
8288 // Each user prompt will result in a user message entry plus an agent message entry.
8289 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8290 acp::ContentChunk::new("Response 1".into()),
8291 )]);
8292
8293 let (thread_view, cx) =
8294 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
8295
8296 let thread = thread_view
8297 .read_with(cx, |view, _| view.thread().cloned())
8298 .unwrap();
8299
8300 thread
8301 .update(cx, |thread, cx| thread.send_raw("Prompt 1", cx))
8302 .await
8303 .unwrap();
8304 cx.run_until_parked();
8305
8306 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8307 acp::ContentChunk::new("Response 2".into()),
8308 )]);
8309
8310 thread
8311 .update(cx, |thread, cx| thread.send_raw("Prompt 2", cx))
8312 .await
8313 .unwrap();
8314 cx.run_until_parked();
8315
8316 // Move somewhere else first so we're not trivially already on the last user prompt.
8317 thread_view.update(cx, |view, cx| {
8318 view.scroll_to_top(cx);
8319 });
8320 cx.run_until_parked();
8321
8322 thread_view.update(cx, |view, cx| {
8323 view.scroll_to_most_recent_user_prompt(cx);
8324 let scroll_top = view.list_state.logical_scroll_top();
8325 // Entries layout is: [User1, Assistant1, User2, Assistant2]
8326 assert_eq!(scroll_top.item_ix, 2);
8327 });
8328 }
8329
8330 #[gpui::test]
8331 async fn test_scroll_to_most_recent_user_prompt_falls_back_to_bottom_without_user_messages(
8332 cx: &mut TestAppContext,
8333 ) {
8334 init_test(cx);
8335
8336 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
8337
8338 // With no entries, scrolling should be a no-op and must not panic.
8339 thread_view.update(cx, |view, cx| {
8340 view.scroll_to_most_recent_user_prompt(cx);
8341 let scroll_top = view.list_state.logical_scroll_top();
8342 assert_eq!(scroll_top.item_ix, 0);
8343 });
8344 }
8345
8346 #[gpui::test]
8347 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
8348 init_test(cx);
8349
8350 let connection = StubAgentConnection::new();
8351
8352 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8353 acp::ContentChunk::new("Response".into()),
8354 )]);
8355
8356 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
8357 add_to_workspace(thread_view.clone(), cx);
8358
8359 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8360 message_editor.update_in(cx, |editor, window, cx| {
8361 editor.set_text("Original message to edit", window, cx);
8362 });
8363 thread_view.update_in(cx, |thread_view, window, cx| {
8364 thread_view.send(window, cx);
8365 });
8366
8367 cx.run_until_parked();
8368
8369 let user_message_editor = thread_view.read_with(cx, |view, cx| {
8370 assert_eq!(view.editing_message, None);
8371
8372 view.entry_view_state
8373 .read(cx)
8374 .entry(0)
8375 .unwrap()
8376 .message_editor()
8377 .unwrap()
8378 .clone()
8379 });
8380
8381 // Focus
8382 cx.focus(&user_message_editor);
8383 thread_view.read_with(cx, |view, _cx| {
8384 assert_eq!(view.editing_message, Some(0));
8385 });
8386
8387 // Edit
8388 user_message_editor.update_in(cx, |editor, window, cx| {
8389 editor.set_text("Edited message content", window, cx);
8390 });
8391
8392 // Cancel
8393 user_message_editor.update_in(cx, |_editor, window, cx| {
8394 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
8395 });
8396
8397 thread_view.read_with(cx, |view, _cx| {
8398 assert_eq!(view.editing_message, None);
8399 });
8400
8401 user_message_editor.read_with(cx, |editor, cx| {
8402 assert_eq!(editor.text(cx), "Original message to edit");
8403 });
8404 }
8405
8406 #[gpui::test]
8407 async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
8408 init_test(cx);
8409
8410 let connection = StubAgentConnection::new();
8411
8412 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
8413 add_to_workspace(thread_view.clone(), cx);
8414
8415 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8416 let mut events = cx.events(&message_editor);
8417 message_editor.update_in(cx, |editor, window, cx| {
8418 editor.set_text("", window, cx);
8419 });
8420
8421 message_editor.update_in(cx, |_editor, window, cx| {
8422 window.dispatch_action(Box::new(Chat), cx);
8423 });
8424 cx.run_until_parked();
8425 // We shouldn't have received any messages
8426 assert!(matches!(
8427 events.try_next(),
8428 Err(futures::channel::mpsc::TryRecvError { .. })
8429 ));
8430 }
8431
8432 #[gpui::test]
8433 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
8434 init_test(cx);
8435
8436 let connection = StubAgentConnection::new();
8437
8438 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8439 acp::ContentChunk::new("Response".into()),
8440 )]);
8441
8442 let (thread_view, cx) =
8443 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
8444 add_to_workspace(thread_view.clone(), cx);
8445
8446 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8447 message_editor.update_in(cx, |editor, window, cx| {
8448 editor.set_text("Original message to edit", window, cx);
8449 });
8450 thread_view.update_in(cx, |thread_view, window, cx| {
8451 thread_view.send(window, cx);
8452 });
8453
8454 cx.run_until_parked();
8455
8456 let user_message_editor = thread_view.read_with(cx, |view, cx| {
8457 assert_eq!(view.editing_message, None);
8458 assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
8459
8460 view.entry_view_state
8461 .read(cx)
8462 .entry(0)
8463 .unwrap()
8464 .message_editor()
8465 .unwrap()
8466 .clone()
8467 });
8468
8469 // Focus
8470 cx.focus(&user_message_editor);
8471
8472 // Edit
8473 user_message_editor.update_in(cx, |editor, window, cx| {
8474 editor.set_text("Edited message content", window, cx);
8475 });
8476
8477 // Send
8478 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8479 acp::ContentChunk::new("New Response".into()),
8480 )]);
8481
8482 user_message_editor.update_in(cx, |_editor, window, cx| {
8483 window.dispatch_action(Box::new(Chat), cx);
8484 });
8485
8486 cx.run_until_parked();
8487
8488 thread_view.read_with(cx, |view, cx| {
8489 assert_eq!(view.editing_message, None);
8490
8491 let entries = view.thread().unwrap().read(cx).entries();
8492 assert_eq!(entries.len(), 2);
8493 assert_eq!(
8494 entries[0].to_markdown(cx),
8495 "## User\n\nEdited message content\n\n"
8496 );
8497 assert_eq!(
8498 entries[1].to_markdown(cx),
8499 "## Assistant\n\nNew Response\n\n"
8500 );
8501
8502 let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
8503 assert!(!state.entry(1).unwrap().has_content());
8504 state.entry(0).unwrap().message_editor().unwrap().clone()
8505 });
8506
8507 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
8508 })
8509 }
8510
8511 #[gpui::test]
8512 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
8513 init_test(cx);
8514
8515 let connection = StubAgentConnection::new();
8516
8517 let (thread_view, cx) =
8518 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
8519 add_to_workspace(thread_view.clone(), cx);
8520
8521 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8522 message_editor.update_in(cx, |editor, window, cx| {
8523 editor.set_text("Original message to edit", window, cx);
8524 });
8525 thread_view.update_in(cx, |thread_view, window, cx| {
8526 thread_view.send(window, cx);
8527 });
8528
8529 cx.run_until_parked();
8530
8531 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
8532 let thread = view.thread().unwrap().read(cx);
8533 assert_eq!(thread.entries().len(), 1);
8534
8535 let editor = view
8536 .entry_view_state
8537 .read(cx)
8538 .entry(0)
8539 .unwrap()
8540 .message_editor()
8541 .unwrap()
8542 .clone();
8543
8544 (editor, thread.session_id().clone())
8545 });
8546
8547 // Focus
8548 cx.focus(&user_message_editor);
8549
8550 thread_view.read_with(cx, |view, _cx| {
8551 assert_eq!(view.editing_message, Some(0));
8552 });
8553
8554 // Edit
8555 user_message_editor.update_in(cx, |editor, window, cx| {
8556 editor.set_text("Edited message content", window, cx);
8557 });
8558
8559 thread_view.read_with(cx, |view, _cx| {
8560 assert_eq!(view.editing_message, Some(0));
8561 });
8562
8563 // Finish streaming response
8564 cx.update(|_, cx| {
8565 connection.send_update(
8566 session_id.clone(),
8567 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("Response".into())),
8568 cx,
8569 );
8570 connection.end_turn(session_id, acp::StopReason::EndTurn);
8571 });
8572
8573 thread_view.read_with(cx, |view, _cx| {
8574 assert_eq!(view.editing_message, Some(0));
8575 });
8576
8577 cx.run_until_parked();
8578
8579 // Should still be editing
8580 cx.update(|window, cx| {
8581 assert!(user_message_editor.focus_handle(cx).is_focused(window));
8582 assert_eq!(thread_view.read(cx).editing_message, Some(0));
8583 assert_eq!(
8584 user_message_editor.read(cx).text(cx),
8585 "Edited message content"
8586 );
8587 });
8588 }
8589
8590 struct GeneratingThreadSetup {
8591 thread_view: Entity<AcpThreadView>,
8592 thread: Entity<AcpThread>,
8593 message_editor: Entity<MessageEditor>,
8594 }
8595
8596 async fn setup_generating_thread(
8597 cx: &mut TestAppContext,
8598 ) -> (GeneratingThreadSetup, &mut VisualTestContext) {
8599 let connection = StubAgentConnection::new();
8600
8601 let (thread_view, cx) =
8602 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
8603 add_to_workspace(thread_view.clone(), cx);
8604
8605 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8606 message_editor.update_in(cx, |editor, window, cx| {
8607 editor.set_text("Hello", window, cx);
8608 });
8609 thread_view.update_in(cx, |thread_view, window, cx| {
8610 thread_view.send(window, cx);
8611 });
8612
8613 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
8614 let thread = view.thread().unwrap();
8615 (thread.clone(), thread.read(cx).session_id().clone())
8616 });
8617
8618 cx.run_until_parked();
8619
8620 cx.update(|_, cx| {
8621 connection.send_update(
8622 session_id.clone(),
8623 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
8624 "Response chunk".into(),
8625 )),
8626 cx,
8627 );
8628 });
8629
8630 cx.run_until_parked();
8631
8632 thread.read_with(cx, |thread, _cx| {
8633 assert_eq!(thread.status(), ThreadStatus::Generating);
8634 });
8635
8636 (
8637 GeneratingThreadSetup {
8638 thread_view,
8639 thread,
8640 message_editor,
8641 },
8642 cx,
8643 )
8644 }
8645
8646 #[gpui::test]
8647 async fn test_escape_cancels_generation_from_conversation_focus(cx: &mut TestAppContext) {
8648 init_test(cx);
8649
8650 let (setup, cx) = setup_generating_thread(cx).await;
8651
8652 let focus_handle = setup
8653 .thread_view
8654 .read_with(cx, |view, _cx| view.focus_handle.clone());
8655 cx.update(|window, cx| {
8656 window.focus(&focus_handle, cx);
8657 });
8658
8659 setup.thread_view.update_in(cx, |_, window, cx| {
8660 window.dispatch_action(menu::Cancel.boxed_clone(), cx);
8661 });
8662
8663 cx.run_until_parked();
8664
8665 setup.thread.read_with(cx, |thread, _cx| {
8666 assert_eq!(thread.status(), ThreadStatus::Idle);
8667 });
8668 }
8669
8670 #[gpui::test]
8671 async fn test_escape_cancels_generation_from_editor_focus(cx: &mut TestAppContext) {
8672 init_test(cx);
8673
8674 let (setup, cx) = setup_generating_thread(cx).await;
8675
8676 let editor_focus_handle = setup
8677 .message_editor
8678 .read_with(cx, |editor, cx| editor.focus_handle(cx));
8679 cx.update(|window, cx| {
8680 window.focus(&editor_focus_handle, cx);
8681 });
8682
8683 setup.message_editor.update_in(cx, |_, window, cx| {
8684 window.dispatch_action(editor::actions::Cancel.boxed_clone(), cx);
8685 });
8686
8687 cx.run_until_parked();
8688
8689 setup.thread.read_with(cx, |thread, _cx| {
8690 assert_eq!(thread.status(), ThreadStatus::Idle);
8691 });
8692 }
8693
8694 #[gpui::test]
8695 async fn test_escape_when_idle_is_noop(cx: &mut TestAppContext) {
8696 init_test(cx);
8697
8698 let (thread_view, cx) =
8699 setup_thread_view(StubAgentServer::new(StubAgentConnection::new()), cx).await;
8700 add_to_workspace(thread_view.clone(), cx);
8701
8702 let thread = thread_view.read_with(cx, |view, _cx| view.thread().unwrap().clone());
8703
8704 thread.read_with(cx, |thread, _cx| {
8705 assert_eq!(thread.status(), ThreadStatus::Idle);
8706 });
8707
8708 let focus_handle = thread_view.read_with(cx, |view, _cx| view.focus_handle.clone());
8709 cx.update(|window, cx| {
8710 window.focus(&focus_handle, cx);
8711 });
8712
8713 thread_view.update_in(cx, |_, window, cx| {
8714 window.dispatch_action(menu::Cancel.boxed_clone(), cx);
8715 });
8716
8717 cx.run_until_parked();
8718
8719 thread.read_with(cx, |thread, _cx| {
8720 assert_eq!(thread.status(), ThreadStatus::Idle);
8721 });
8722 }
8723
8724 #[gpui::test]
8725 async fn test_interrupt(cx: &mut TestAppContext) {
8726 init_test(cx);
8727
8728 let connection = StubAgentConnection::new();
8729
8730 let (thread_view, cx) =
8731 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
8732 add_to_workspace(thread_view.clone(), cx);
8733
8734 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8735 message_editor.update_in(cx, |editor, window, cx| {
8736 editor.set_text("Message 1", window, cx);
8737 });
8738 thread_view.update_in(cx, |thread_view, window, cx| {
8739 thread_view.send(window, cx);
8740 });
8741
8742 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
8743 let thread = view.thread().unwrap();
8744
8745 (thread.clone(), thread.read(cx).session_id().clone())
8746 });
8747
8748 cx.run_until_parked();
8749
8750 cx.update(|_, cx| {
8751 connection.send_update(
8752 session_id.clone(),
8753 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
8754 "Message 1 resp".into(),
8755 )),
8756 cx,
8757 );
8758 });
8759
8760 cx.run_until_parked();
8761
8762 thread.read_with(cx, |thread, cx| {
8763 assert_eq!(
8764 thread.to_markdown(cx),
8765 indoc::indoc! {"
8766 ## User
8767
8768 Message 1
8769
8770 ## Assistant
8771
8772 Message 1 resp
8773
8774 "}
8775 )
8776 });
8777
8778 message_editor.update_in(cx, |editor, window, cx| {
8779 editor.set_text("Message 2", window, cx);
8780 });
8781 thread_view.update_in(cx, |thread_view, window, cx| {
8782 thread_view.send(window, cx);
8783 });
8784
8785 cx.update(|_, cx| {
8786 // Simulate a response sent after beginning to cancel
8787 connection.send_update(
8788 session_id.clone(),
8789 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("onse".into())),
8790 cx,
8791 );
8792 });
8793
8794 cx.run_until_parked();
8795
8796 // Last Message 1 response should appear before Message 2
8797 thread.read_with(cx, |thread, cx| {
8798 assert_eq!(
8799 thread.to_markdown(cx),
8800 indoc::indoc! {"
8801 ## User
8802
8803 Message 1
8804
8805 ## Assistant
8806
8807 Message 1 response
8808
8809 ## User
8810
8811 Message 2
8812
8813 "}
8814 )
8815 });
8816
8817 cx.update(|_, cx| {
8818 connection.send_update(
8819 session_id.clone(),
8820 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
8821 "Message 2 response".into(),
8822 )),
8823 cx,
8824 );
8825 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
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 response
8841
8842 ## User
8843
8844 Message 2
8845
8846 ## Assistant
8847
8848 Message 2 response
8849
8850 "}
8851 )
8852 });
8853 }
8854
8855 #[gpui::test]
8856 async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
8857 init_test(cx);
8858
8859 let connection = StubAgentConnection::new();
8860 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8861 acp::ContentChunk::new("Response".into()),
8862 )]);
8863
8864 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
8865 add_to_workspace(thread_view.clone(), cx);
8866
8867 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8868 message_editor.update_in(cx, |editor, window, cx| {
8869 editor.set_text("Original message to edit", window, cx)
8870 });
8871 thread_view.update_in(cx, |thread_view, window, cx| thread_view.send(window, cx));
8872 cx.run_until_parked();
8873
8874 let user_message_editor = thread_view.read_with(cx, |thread_view, cx| {
8875 thread_view
8876 .entry_view_state
8877 .read(cx)
8878 .entry(0)
8879 .expect("Should have at least one entry")
8880 .message_editor()
8881 .expect("Should have message editor")
8882 .clone()
8883 });
8884
8885 cx.focus(&user_message_editor);
8886 thread_view.read_with(cx, |thread_view, _cx| {
8887 assert_eq!(thread_view.editing_message, Some(0));
8888 });
8889
8890 // Ensure to edit the focused message before proceeding otherwise, since
8891 // its content is not different from what was sent, focus will be lost.
8892 user_message_editor.update_in(cx, |editor, window, cx| {
8893 editor.set_text("Original message to edit with ", window, cx)
8894 });
8895
8896 // Create a simple buffer with some text so we can create a selection
8897 // that will then be added to the message being edited.
8898 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
8899 (thread_view.workspace.clone(), thread_view.project.clone())
8900 });
8901 let buffer = project.update(cx, |project, cx| {
8902 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
8903 });
8904
8905 workspace
8906 .update_in(cx, |workspace, window, cx| {
8907 let editor = cx.new(|cx| {
8908 let mut editor =
8909 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
8910
8911 editor.change_selections(Default::default(), window, cx, |selections| {
8912 selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
8913 });
8914
8915 editor
8916 });
8917 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
8918 })
8919 .unwrap();
8920
8921 thread_view.update_in(cx, |thread_view, window, cx| {
8922 assert_eq!(thread_view.editing_message, Some(0));
8923 thread_view.insert_selections(window, cx);
8924 });
8925
8926 user_message_editor.read_with(cx, |editor, cx| {
8927 let text = editor.editor().read(cx).text(cx);
8928 let expected_text = String::from("Original message to edit with selection ");
8929
8930 assert_eq!(text, expected_text);
8931 });
8932 }
8933
8934 #[gpui::test]
8935 async fn test_insert_selections(cx: &mut TestAppContext) {
8936 init_test(cx);
8937
8938 let connection = StubAgentConnection::new();
8939 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8940 acp::ContentChunk::new("Response".into()),
8941 )]);
8942
8943 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
8944 add_to_workspace(thread_view.clone(), cx);
8945
8946 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8947 message_editor.update_in(cx, |editor, window, cx| {
8948 editor.set_text("Can you review this snippet ", window, cx)
8949 });
8950
8951 // Create a simple buffer with some text so we can create a selection
8952 // that will then be added to the message being edited.
8953 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
8954 (thread_view.workspace.clone(), thread_view.project.clone())
8955 });
8956 let buffer = project.update(cx, |project, cx| {
8957 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
8958 });
8959
8960 workspace
8961 .update_in(cx, |workspace, window, cx| {
8962 let editor = cx.new(|cx| {
8963 let mut editor =
8964 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
8965
8966 editor.change_selections(Default::default(), window, cx, |selections| {
8967 selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
8968 });
8969
8970 editor
8971 });
8972 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
8973 })
8974 .unwrap();
8975
8976 thread_view.update_in(cx, |thread_view, window, cx| {
8977 assert_eq!(thread_view.editing_message, None);
8978 thread_view.insert_selections(window, cx);
8979 });
8980
8981 thread_view.read_with(cx, |thread_view, cx| {
8982 let text = thread_view.message_editor.read(cx).text(cx);
8983 let expected_txt = String::from("Can you review this snippet selection ");
8984
8985 assert_eq!(text, expected_txt);
8986 })
8987 }
8988}