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