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::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, 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::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, OpenHistory, QueueMessage, RejectAll, RejectOnce, SendNextQueuedMessage,
75 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 changed_buffers = action_log.read(cx).changed_buffers(cx);
4423 let plan = thread.plan();
4424
4425 if changed_buffers.is_empty() && plan.is_empty() && self.message_queue.is_empty() {
4426 return None;
4427 }
4428
4429 // Temporarily always enable ACP edit controls. This is temporary, to lessen the
4430 // impact of a nasty bug that causes them to sometimes be disabled when they shouldn't
4431 // be, which blocks you from being able to accept or reject edits. This switches the
4432 // bug to be that sometimes it's enabled when it shouldn't be, which at least doesn't
4433 // block you from using the panel.
4434 let pending_edits = false;
4435
4436 v_flex()
4437 .mt_1()
4438 .mx_2()
4439 .bg(self.activity_bar_bg(cx))
4440 .border_1()
4441 .border_b_0()
4442 .border_color(cx.theme().colors().border)
4443 .rounded_t_md()
4444 .shadow(vec![gpui::BoxShadow {
4445 color: gpui::black().opacity(0.15),
4446 offset: point(px(1.), px(-1.)),
4447 blur_radius: px(3.),
4448 spread_radius: px(0.),
4449 }])
4450 .when(!plan.is_empty(), |this| {
4451 this.child(self.render_plan_summary(plan, window, cx))
4452 .when(self.plan_expanded, |parent| {
4453 parent.child(self.render_plan_entries(plan, window, cx))
4454 })
4455 })
4456 .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
4457 this.child(Divider::horizontal().color(DividerColor::Border))
4458 })
4459 .when(!changed_buffers.is_empty(), |this| {
4460 this.child(self.render_edits_summary(
4461 &changed_buffers,
4462 self.edits_expanded,
4463 pending_edits,
4464 cx,
4465 ))
4466 .when(self.edits_expanded, |parent| {
4467 parent.child(self.render_edited_files(&changed_buffers, cx))
4468 })
4469 })
4470 .when(!self.message_queue.is_empty(), |this| {
4471 this.when(!plan.is_empty() || !changed_buffers.is_empty(), |this| {
4472 this.child(Divider::horizontal().color(DividerColor::Border))
4473 })
4474 .child(self.render_message_queue_summary(window, cx))
4475 .when(self.queue_expanded, |parent| {
4476 parent.child(self.render_message_queue_entries(window, cx))
4477 })
4478 })
4479 .into_any()
4480 .into()
4481 }
4482
4483 fn render_plan_summary(
4484 &self,
4485 plan: &Plan,
4486 window: &mut Window,
4487 cx: &Context<Self>,
4488 ) -> impl IntoElement {
4489 let stats = plan.stats();
4490
4491 let title = if let Some(entry) = stats.in_progress_entry
4492 && !self.plan_expanded
4493 {
4494 h_flex()
4495 .cursor_default()
4496 .relative()
4497 .w_full()
4498 .gap_1()
4499 .truncate()
4500 .child(
4501 Label::new("Current:")
4502 .size(LabelSize::Small)
4503 .color(Color::Muted),
4504 )
4505 .child(
4506 div()
4507 .text_xs()
4508 .text_color(cx.theme().colors().text_muted)
4509 .line_clamp(1)
4510 .child(MarkdownElement::new(
4511 entry.content.clone(),
4512 plan_label_markdown_style(&entry.status, window, cx),
4513 )),
4514 )
4515 .when(stats.pending > 0, |this| {
4516 this.child(
4517 h_flex()
4518 .absolute()
4519 .top_0()
4520 .right_0()
4521 .h_full()
4522 .child(div().min_w_8().h_full().bg(linear_gradient(
4523 90.,
4524 linear_color_stop(self.activity_bar_bg(cx), 1.),
4525 linear_color_stop(self.activity_bar_bg(cx).opacity(0.2), 0.),
4526 )))
4527 .child(
4528 div().pr_0p5().bg(self.activity_bar_bg(cx)).child(
4529 Label::new(format!("{} left", stats.pending))
4530 .size(LabelSize::Small)
4531 .color(Color::Muted),
4532 ),
4533 ),
4534 )
4535 })
4536 } else {
4537 let status_label = if stats.pending == 0 {
4538 "All Done".to_string()
4539 } else if stats.completed == 0 {
4540 format!("{} Tasks", plan.entries.len())
4541 } else {
4542 format!("{}/{}", stats.completed, plan.entries.len())
4543 };
4544
4545 h_flex()
4546 .w_full()
4547 .gap_1()
4548 .justify_between()
4549 .child(
4550 Label::new("Plan")
4551 .size(LabelSize::Small)
4552 .color(Color::Muted),
4553 )
4554 .child(
4555 Label::new(status_label)
4556 .size(LabelSize::Small)
4557 .color(Color::Muted)
4558 .mr_1(),
4559 )
4560 };
4561
4562 h_flex()
4563 .id("plan_summary")
4564 .p_1()
4565 .w_full()
4566 .gap_1()
4567 .when(self.plan_expanded, |this| {
4568 this.border_b_1().border_color(cx.theme().colors().border)
4569 })
4570 .child(Disclosure::new("plan_disclosure", self.plan_expanded))
4571 .child(title)
4572 .on_click(cx.listener(|this, _, _, cx| {
4573 this.plan_expanded = !this.plan_expanded;
4574 cx.notify();
4575 }))
4576 }
4577
4578 fn render_plan_entries(
4579 &self,
4580 plan: &Plan,
4581 window: &mut Window,
4582 cx: &Context<Self>,
4583 ) -> impl IntoElement {
4584 v_flex()
4585 .id("plan_items_list")
4586 .max_h_40()
4587 .overflow_y_scroll()
4588 .children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
4589 let element = h_flex()
4590 .py_1()
4591 .px_2()
4592 .gap_2()
4593 .justify_between()
4594 .bg(cx.theme().colors().editor_background)
4595 .when(index < plan.entries.len() - 1, |parent| {
4596 parent.border_color(cx.theme().colors().border).border_b_1()
4597 })
4598 .child(
4599 h_flex()
4600 .id(("plan_entry", index))
4601 .gap_1p5()
4602 .max_w_full()
4603 .overflow_x_scroll()
4604 .text_xs()
4605 .text_color(cx.theme().colors().text_muted)
4606 .child(match entry.status {
4607 acp::PlanEntryStatus::InProgress => {
4608 Icon::new(IconName::TodoProgress)
4609 .size(IconSize::Small)
4610 .color(Color::Accent)
4611 .with_rotate_animation(2)
4612 .into_any_element()
4613 }
4614 acp::PlanEntryStatus::Completed => {
4615 Icon::new(IconName::TodoComplete)
4616 .size(IconSize::Small)
4617 .color(Color::Success)
4618 .into_any_element()
4619 }
4620 acp::PlanEntryStatus::Pending | _ => {
4621 Icon::new(IconName::TodoPending)
4622 .size(IconSize::Small)
4623 .color(Color::Muted)
4624 .into_any_element()
4625 }
4626 })
4627 .child(MarkdownElement::new(
4628 entry.content.clone(),
4629 plan_label_markdown_style(&entry.status, window, cx),
4630 )),
4631 );
4632
4633 Some(element)
4634 }))
4635 .into_any_element()
4636 }
4637
4638 fn render_edits_summary(
4639 &self,
4640 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
4641 expanded: bool,
4642 pending_edits: bool,
4643 cx: &Context<Self>,
4644 ) -> Div {
4645 let focus_handle = self.focus_handle(cx);
4646
4647 h_flex()
4648 .p_1()
4649 .justify_between()
4650 .flex_wrap()
4651 .when(expanded, |this| {
4652 this.border_b_1().border_color(cx.theme().colors().border)
4653 })
4654 .child(
4655 h_flex()
4656 .id("edits-container")
4657 .cursor_pointer()
4658 .gap_1()
4659 .child(Disclosure::new("edits-disclosure", expanded))
4660 .map(|this| {
4661 if pending_edits {
4662 this.child(
4663 Label::new(format!(
4664 "Editing {} {}…",
4665 changed_buffers.len(),
4666 if changed_buffers.len() == 1 {
4667 "file"
4668 } else {
4669 "files"
4670 }
4671 ))
4672 .color(Color::Muted)
4673 .size(LabelSize::Small)
4674 .with_animation(
4675 "edit-label",
4676 Animation::new(Duration::from_secs(2))
4677 .repeat()
4678 .with_easing(pulsating_between(0.3, 0.7)),
4679 |label, delta| label.alpha(delta),
4680 ),
4681 )
4682 } else {
4683 let stats = DiffStats::all_files(changed_buffers, cx);
4684 let dot_divider = || {
4685 Label::new("•")
4686 .size(LabelSize::XSmall)
4687 .color(Color::Disabled)
4688 };
4689
4690 this.child(
4691 Label::new("Edits")
4692 .size(LabelSize::Small)
4693 .color(Color::Muted),
4694 )
4695 .child(dot_divider())
4696 .child(
4697 Label::new(format!(
4698 "{} {}",
4699 changed_buffers.len(),
4700 if changed_buffers.len() == 1 {
4701 "file"
4702 } else {
4703 "files"
4704 }
4705 ))
4706 .size(LabelSize::Small)
4707 .color(Color::Muted),
4708 )
4709 .child(dot_divider())
4710 .child(DiffStat::new(
4711 "total",
4712 stats.lines_added as usize,
4713 stats.lines_removed as usize,
4714 ))
4715 }
4716 })
4717 .on_click(cx.listener(|this, _, _, cx| {
4718 this.edits_expanded = !this.edits_expanded;
4719 cx.notify();
4720 })),
4721 )
4722 .child(
4723 Button::new("review-changes", "Review Changes")
4724 .label_size(LabelSize::Small)
4725 .key_binding(
4726 KeyBinding::for_action_in(&git_ui::project_diff::Diff, &focus_handle, cx)
4727 .map(|kb| kb.size(rems_from_px(10.))),
4728 )
4729 .on_click(cx.listener(move |_, _, window, cx| {
4730 window.dispatch_action(git_ui::project_diff::Diff.boxed_clone(), cx);
4731 })),
4732 )
4733 }
4734
4735 fn render_edited_files(
4736 &self,
4737 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
4738 cx: &Context<Self>,
4739 ) -> impl IntoElement {
4740 let editor_bg_color = cx.theme().colors().editor_background;
4741
4742 v_flex()
4743 .id("edited_files_list")
4744 .max_h_40()
4745 .overflow_y_scroll()
4746 .children(
4747 changed_buffers
4748 .iter()
4749 .enumerate()
4750 .flat_map(|(index, (buffer, diff))| {
4751 let file = buffer.read(cx).file()?;
4752 let path = file.path();
4753 let path_style = file.path_style(cx);
4754 let separator = file.path_style(cx).primary_separator();
4755
4756 let file_path = path.parent().and_then(|parent| {
4757 if parent.is_empty() {
4758 None
4759 } else {
4760 Some(
4761 Label::new(format!(
4762 "{}{separator}",
4763 parent.display(path_style)
4764 ))
4765 .color(Color::Muted)
4766 .size(LabelSize::XSmall)
4767 .buffer_font(cx),
4768 )
4769 }
4770 });
4771
4772 let file_name = path.file_name().map(|name| {
4773 Label::new(name.to_string())
4774 .size(LabelSize::XSmall)
4775 .buffer_font(cx)
4776 .ml_1()
4777 });
4778
4779 let full_path = path.display(path_style).to_string();
4780
4781 let file_icon = FileIcons::get_icon(path.as_std_path(), cx)
4782 .map(Icon::from_path)
4783 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
4784 .unwrap_or_else(|| {
4785 Icon::new(IconName::File)
4786 .color(Color::Muted)
4787 .size(IconSize::Small)
4788 });
4789
4790 let overlay_gradient = linear_gradient(
4791 90.,
4792 linear_color_stop(editor_bg_color, 1.),
4793 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
4794 );
4795
4796 let file_stats = DiffStats::single_file(buffer.read(cx), diff.read(cx), cx);
4797
4798 let element = h_flex()
4799 .group("edited-code")
4800 .id(("file-container", index))
4801 .py_1()
4802 .pl_2()
4803 .pr_1()
4804 .gap_2()
4805 .justify_between()
4806 .bg(editor_bg_color)
4807 .when(index < changed_buffers.len() - 1, |parent| {
4808 parent.border_color(cx.theme().colors().border).border_b_1()
4809 })
4810 .child(
4811 h_flex()
4812 .id(("file-name-row", index))
4813 .relative()
4814 .pr_8()
4815 .w_full()
4816 .child(
4817 h_flex()
4818 .id(("file-name-path", index))
4819 .cursor_pointer()
4820 .pr_0p5()
4821 .gap_0p5()
4822 .hover(|s| s.bg(cx.theme().colors().element_hover))
4823 .rounded_xs()
4824 .child(file_icon)
4825 .children(file_name)
4826 .children(file_path)
4827 .child(
4828 DiffStat::new(
4829 "file",
4830 file_stats.lines_added as usize,
4831 file_stats.lines_removed as usize,
4832 )
4833 .label_size(LabelSize::XSmall),
4834 )
4835 .tooltip(move |_, cx| {
4836 Tooltip::with_meta(
4837 "Go to File",
4838 None,
4839 full_path.clone(),
4840 cx,
4841 )
4842 })
4843 .on_click({
4844 let buffer = buffer.clone();
4845 cx.listener(move |this, _, window, cx| {
4846 this.open_edited_buffer(&buffer, window, cx);
4847 })
4848 }),
4849 )
4850 .child(
4851 div()
4852 .absolute()
4853 .h_full()
4854 .w_12()
4855 .top_0()
4856 .bottom_0()
4857 .right_0()
4858 .bg(overlay_gradient),
4859 ),
4860 )
4861 .child(
4862 h_flex()
4863 .gap_1()
4864 .visible_on_hover("edited-code")
4865 .child(
4866 Button::new("review", "Review")
4867 .label_size(LabelSize::Small)
4868 .on_click({
4869 let buffer = buffer.clone();
4870 let workspace = self.workspace.clone();
4871 cx.listener(move |_, _, window, cx| {
4872 let Some(workspace) = workspace.upgrade() else {
4873 return;
4874 };
4875 let Some(file) = buffer.read(cx).file() else {
4876 return;
4877 };
4878 let project_path = project::ProjectPath {
4879 worktree_id: file.worktree_id(cx),
4880 path: file.path().clone(),
4881 };
4882 workspace.update(cx, |workspace, cx| {
4883 git_ui::project_diff::ProjectDiff::deploy_at_project_path(
4884 workspace,
4885 project_path,
4886 window,
4887 cx,
4888 );
4889 });
4890 })
4891 }),
4892 ),
4893 );
4894
4895 Some(element)
4896 }),
4897 )
4898 .into_any_element()
4899 }
4900
4901 fn render_message_queue_summary(
4902 &self,
4903 _window: &mut Window,
4904 cx: &Context<Self>,
4905 ) -> impl IntoElement {
4906 let queue_count = self.message_queue.len();
4907 let title: SharedString = if queue_count == 1 {
4908 "1 Queued Message".into()
4909 } else {
4910 format!("{} Queued Messages", queue_count).into()
4911 };
4912
4913 h_flex()
4914 .p_1()
4915 .w_full()
4916 .gap_1()
4917 .justify_between()
4918 .when(self.queue_expanded, |this| {
4919 this.border_b_1().border_color(cx.theme().colors().border)
4920 })
4921 .child(
4922 h_flex()
4923 .id("queue_summary")
4924 .gap_1()
4925 .child(Disclosure::new("queue_disclosure", self.queue_expanded))
4926 .child(Label::new(title).size(LabelSize::Small).color(Color::Muted))
4927 .on_click(cx.listener(|this, _, _, cx| {
4928 this.queue_expanded = !this.queue_expanded;
4929 cx.notify();
4930 })),
4931 )
4932 .child(
4933 Button::new("clear_queue", "Clear All")
4934 .label_size(LabelSize::Small)
4935 .key_binding(KeyBinding::for_action(&ClearMessageQueue, cx))
4936 .on_click(cx.listener(|this, _, _, cx| {
4937 this.message_queue.clear();
4938 cx.notify();
4939 })),
4940 )
4941 }
4942
4943 fn render_message_queue_entries(
4944 &self,
4945 _window: &mut Window,
4946 cx: &Context<Self>,
4947 ) -> impl IntoElement {
4948 let message_editor = self.message_editor.read(cx);
4949 let focus_handle = message_editor.focus_handle(cx);
4950
4951 v_flex()
4952 .id("message_queue_list")
4953 .max_h_40()
4954 .overflow_y_scroll()
4955 .children(
4956 self.message_queue
4957 .iter()
4958 .enumerate()
4959 .map(|(index, queued)| {
4960 let is_next = index == 0;
4961 let icon_color = if is_next { Color::Accent } else { Color::Muted };
4962 let queue_len = self.message_queue.len();
4963
4964 let preview = queued
4965 .content
4966 .iter()
4967 .find_map(|block| match block {
4968 acp::ContentBlock::Text(text) => {
4969 text.text.lines().next().map(str::to_owned)
4970 }
4971 _ => None,
4972 })
4973 .unwrap_or_default();
4974
4975 h_flex()
4976 .group("queue_entry")
4977 .w_full()
4978 .p_1()
4979 .pl_2()
4980 .gap_1()
4981 .justify_between()
4982 .bg(cx.theme().colors().editor_background)
4983 .when(index < queue_len - 1, |parent| {
4984 parent.border_color(cx.theme().colors().border).border_b_1()
4985 })
4986 .child(
4987 h_flex()
4988 .id(("queued_prompt", index))
4989 .min_w_0()
4990 .w_full()
4991 .gap_1p5()
4992 .child(
4993 Icon::new(IconName::Circle)
4994 .size(IconSize::Small)
4995 .color(icon_color),
4996 )
4997 .child(
4998 Label::new(preview)
4999 .size(LabelSize::XSmall)
5000 .color(Color::Muted)
5001 .buffer_font(cx)
5002 .truncate(),
5003 )
5004 .when(is_next, |this| {
5005 this.tooltip(Tooltip::text("Next Prompt in the Queue"))
5006 }),
5007 )
5008 .child(
5009 h_flex()
5010 .flex_none()
5011 .gap_1()
5012 .visible_on_hover("queue_entry")
5013 .child(
5014 Button::new(("delete", index), "Remove")
5015 .label_size(LabelSize::Small)
5016 .on_click(cx.listener(move |this, _, _, cx| {
5017 if index < this.message_queue.len() {
5018 this.message_queue.remove(index);
5019 cx.notify();
5020 }
5021 })),
5022 )
5023 .child(
5024 Button::new(("send_now", index), "Send Now")
5025 .style(ButtonStyle::Outlined)
5026 .label_size(LabelSize::Small)
5027 .when(is_next, |this| {
5028 this.key_binding(
5029 KeyBinding::for_action_in(
5030 &SendNextQueuedMessage,
5031 &focus_handle.clone(),
5032 cx,
5033 )
5034 .map(|kb| kb.size(rems_from_px(10.))),
5035 )
5036 })
5037 .on_click(cx.listener(move |this, _, window, cx| {
5038 this.send_queued_message_at_index(
5039 index, true, window, cx,
5040 );
5041 })),
5042 ),
5043 )
5044 }),
5045 )
5046 .into_any_element()
5047 }
5048
5049 fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
5050 let focus_handle = self.message_editor.focus_handle(cx);
5051 let editor_bg_color = cx.theme().colors().editor_background;
5052 let (expand_icon, expand_tooltip) = if self.editor_expanded {
5053 (IconName::Minimize, "Minimize Message Editor")
5054 } else {
5055 (IconName::Maximize, "Expand Message Editor")
5056 };
5057
5058 let backdrop = div()
5059 .size_full()
5060 .absolute()
5061 .inset_0()
5062 .bg(cx.theme().colors().panel_background)
5063 .opacity(0.8)
5064 .block_mouse_except_scroll();
5065
5066 let enable_editor = match self.thread_state {
5067 ThreadState::Ready { .. } => true,
5068 ThreadState::Loading { .. }
5069 | ThreadState::Unauthenticated { .. }
5070 | ThreadState::LoadError(..) => false,
5071 };
5072
5073 v_flex()
5074 .on_action(cx.listener(Self::expand_message_editor))
5075 .p_2()
5076 .gap_2()
5077 .border_t_1()
5078 .border_color(cx.theme().colors().border)
5079 .bg(editor_bg_color)
5080 .when(self.editor_expanded, |this| {
5081 this.h(vh(0.8, window)).size_full().justify_between()
5082 })
5083 .child(
5084 v_flex()
5085 .relative()
5086 .size_full()
5087 .pt_1()
5088 .pr_2p5()
5089 .child(self.message_editor.clone())
5090 .child(
5091 h_flex()
5092 .absolute()
5093 .top_0()
5094 .right_0()
5095 .opacity(0.5)
5096 .hover(|this| this.opacity(1.0))
5097 .child(
5098 IconButton::new("toggle-height", expand_icon)
5099 .icon_size(IconSize::Small)
5100 .icon_color(Color::Muted)
5101 .tooltip({
5102 move |_window, cx| {
5103 Tooltip::for_action_in(
5104 expand_tooltip,
5105 &ExpandMessageEditor,
5106 &focus_handle,
5107 cx,
5108 )
5109 }
5110 })
5111 .on_click(cx.listener(|this, _, window, cx| {
5112 this.expand_message_editor(
5113 &ExpandMessageEditor,
5114 window,
5115 cx,
5116 );
5117 })),
5118 ),
5119 ),
5120 )
5121 .child(
5122 h_flex()
5123 .flex_none()
5124 .flex_wrap()
5125 .justify_between()
5126 .child(
5127 h_flex()
5128 .gap_0p5()
5129 .child(self.render_add_context_button(cx))
5130 .child(self.render_follow_toggle(cx))
5131 .children(self.render_burn_mode_toggle(cx)),
5132 )
5133 .child(
5134 h_flex()
5135 .gap_1()
5136 .children(self.render_token_usage(cx))
5137 .children(self.profile_selector.clone())
5138 // Either config_options_view OR (mode_selector + model_selector)
5139 .children(self.config_options_view.clone())
5140 .when(self.config_options_view.is_none(), |this| {
5141 this.children(self.mode_selector().cloned())
5142 .children(self.model_selector.clone())
5143 })
5144 .child(self.render_send_button(cx)),
5145 ),
5146 )
5147 .when(!enable_editor, |this| this.child(backdrop))
5148 .into_any()
5149 }
5150
5151 pub(crate) fn as_native_connection(
5152 &self,
5153 cx: &App,
5154 ) -> Option<Rc<agent::NativeAgentConnection>> {
5155 let acp_thread = self.thread()?.read(cx);
5156 acp_thread.connection().clone().downcast()
5157 }
5158
5159 pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
5160 let acp_thread = self.thread()?.read(cx);
5161 self.as_native_connection(cx)?
5162 .thread(acp_thread.session_id(), cx)
5163 }
5164
5165 fn is_imported_thread(&self, cx: &App) -> bool {
5166 let Some(thread) = self.as_native_thread(cx) else {
5167 return false;
5168 };
5169 thread.read(cx).is_imported()
5170 }
5171
5172 fn is_using_zed_ai_models(&self, cx: &App) -> bool {
5173 self.as_native_thread(cx)
5174 .and_then(|thread| thread.read(cx).model())
5175 .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
5176 }
5177
5178 fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
5179 let thread = self.thread()?.read(cx);
5180 let usage = thread.token_usage()?;
5181 let is_generating = thread.status() != ThreadStatus::Idle;
5182
5183 let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
5184 let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
5185
5186 Some(
5187 h_flex()
5188 .flex_shrink_0()
5189 .gap_0p5()
5190 .mr_1p5()
5191 .child(
5192 Label::new(used)
5193 .size(LabelSize::Small)
5194 .color(Color::Muted)
5195 .map(|label| {
5196 if is_generating {
5197 label
5198 .with_animation(
5199 "used-tokens-label",
5200 Animation::new(Duration::from_secs(2))
5201 .repeat()
5202 .with_easing(pulsating_between(0.3, 0.8)),
5203 |label, delta| label.alpha(delta),
5204 )
5205 .into_any()
5206 } else {
5207 label.into_any_element()
5208 }
5209 }),
5210 )
5211 .child(
5212 Label::new("/")
5213 .size(LabelSize::Small)
5214 .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
5215 )
5216 .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
5217 )
5218 }
5219
5220 fn toggle_burn_mode(
5221 &mut self,
5222 _: &ToggleBurnMode,
5223 _window: &mut Window,
5224 cx: &mut Context<Self>,
5225 ) {
5226 let Some(thread) = self.as_native_thread(cx) else {
5227 return;
5228 };
5229
5230 thread.update(cx, |thread, cx| {
5231 let current_mode = thread.completion_mode();
5232 thread.set_completion_mode(
5233 match current_mode {
5234 CompletionMode::Burn => CompletionMode::Normal,
5235 CompletionMode::Normal => CompletionMode::Burn,
5236 },
5237 cx,
5238 );
5239 });
5240 }
5241
5242 fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
5243 let Some(thread) = self.thread() else {
5244 return;
5245 };
5246 let telemetry = ActionLogTelemetry::from(thread.read(cx));
5247 let action_log = thread.read(cx).action_log().clone();
5248 action_log.update(cx, |action_log, cx| {
5249 action_log.keep_all_edits(Some(telemetry), cx)
5250 });
5251 }
5252
5253 fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
5254 let Some(thread) = self.thread() else {
5255 return;
5256 };
5257 let telemetry = ActionLogTelemetry::from(thread.read(cx));
5258 let action_log = thread.read(cx).action_log().clone();
5259 action_log
5260 .update(cx, |action_log, cx| {
5261 action_log.reject_all_edits(Some(telemetry), cx)
5262 })
5263 .detach();
5264 }
5265
5266 fn allow_always(&mut self, _: &AllowAlways, window: &mut Window, cx: &mut Context<Self>) {
5267 self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowAlways, window, cx);
5268 }
5269
5270 fn allow_once(&mut self, _: &AllowOnce, window: &mut Window, cx: &mut Context<Self>) {
5271 self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowOnce, window, cx);
5272 }
5273
5274 fn reject_once(&mut self, _: &RejectOnce, window: &mut Window, cx: &mut Context<Self>) {
5275 self.authorize_pending_tool_call(acp::PermissionOptionKind::RejectOnce, window, cx);
5276 }
5277
5278 fn authorize_pending_tool_call(
5279 &mut self,
5280 kind: acp::PermissionOptionKind,
5281 window: &mut Window,
5282 cx: &mut Context<Self>,
5283 ) -> Option<()> {
5284 let thread = self.thread()?.read(cx);
5285 let tool_call = thread.first_tool_awaiting_confirmation()?;
5286 let ToolCallStatus::WaitingForConfirmation { options, .. } = &tool_call.status else {
5287 return None;
5288 };
5289 let option = options.iter().find(|o| o.kind == kind)?;
5290
5291 self.authorize_tool_call(
5292 tool_call.id.clone(),
5293 option.option_id.clone(),
5294 option.kind,
5295 window,
5296 cx,
5297 );
5298
5299 Some(())
5300 }
5301
5302 fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
5303 let thread = self.as_native_thread(cx)?.read(cx);
5304
5305 if thread
5306 .model()
5307 .is_none_or(|model| !model.supports_burn_mode())
5308 {
5309 return None;
5310 }
5311
5312 let active_completion_mode = thread.completion_mode();
5313 let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
5314 let icon = if burn_mode_enabled {
5315 IconName::ZedBurnModeOn
5316 } else {
5317 IconName::ZedBurnMode
5318 };
5319
5320 Some(
5321 IconButton::new("burn-mode", icon)
5322 .icon_size(IconSize::Small)
5323 .icon_color(Color::Muted)
5324 .toggle_state(burn_mode_enabled)
5325 .selected_icon_color(Color::Error)
5326 .on_click(cx.listener(|this, _event, window, cx| {
5327 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5328 }))
5329 .tooltip(move |_window, cx| {
5330 cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
5331 .into()
5332 })
5333 .into_any_element(),
5334 )
5335 }
5336
5337 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
5338 let message_editor = self.message_editor.read(cx);
5339 let is_editor_empty = message_editor.is_empty(cx);
5340 let focus_handle = message_editor.focus_handle(cx);
5341
5342 let is_generating = self
5343 .thread()
5344 .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
5345
5346 if self.is_loading_contents {
5347 div()
5348 .id("loading-message-content")
5349 .px_1()
5350 .tooltip(Tooltip::text("Loading Added Context…"))
5351 .child(loading_contents_spinner(IconSize::default()))
5352 .into_any_element()
5353 } else if is_generating && is_editor_empty {
5354 IconButton::new("stop-generation", IconName::Stop)
5355 .icon_color(Color::Error)
5356 .style(ButtonStyle::Tinted(TintColor::Error))
5357 .tooltip(move |_window, cx| {
5358 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, cx)
5359 })
5360 .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
5361 .into_any_element()
5362 } else {
5363 IconButton::new("send-message", IconName::Send)
5364 .style(ButtonStyle::Filled)
5365 .map(|this| {
5366 if is_editor_empty && !is_generating {
5367 this.disabled(true).icon_color(Color::Muted)
5368 } else {
5369 this.icon_color(Color::Accent)
5370 }
5371 })
5372 .tooltip(move |_window, cx| {
5373 if is_editor_empty && !is_generating {
5374 Tooltip::for_action("Type to Send", &Chat, cx)
5375 } else {
5376 let title = if is_generating {
5377 "Stop and Send Message"
5378 } else {
5379 "Send"
5380 };
5381
5382 let focus_handle = focus_handle.clone();
5383
5384 Tooltip::element(move |_window, cx| {
5385 v_flex()
5386 .gap_1()
5387 .child(
5388 h_flex()
5389 .gap_2()
5390 .justify_between()
5391 .child(Label::new(title))
5392 .child(KeyBinding::for_action_in(&Chat, &focus_handle, cx)),
5393 )
5394 .child(
5395 h_flex()
5396 .pt_1()
5397 .gap_2()
5398 .justify_between()
5399 .border_t_1()
5400 .border_color(cx.theme().colors().border_variant)
5401 .child(Label::new("Queue Message"))
5402 .child(KeyBinding::for_action_in(
5403 &QueueMessage,
5404 &focus_handle,
5405 cx,
5406 )),
5407 )
5408 .into_any_element()
5409 })(_window, cx)
5410 }
5411 })
5412 .on_click(cx.listener(|this, _, window, cx| {
5413 this.send(window, cx);
5414 }))
5415 .into_any_element()
5416 }
5417 }
5418
5419 fn is_following(&self, cx: &App) -> bool {
5420 match self.thread().map(|thread| thread.read(cx).status()) {
5421 Some(ThreadStatus::Generating) => self
5422 .workspace
5423 .read_with(cx, |workspace, _| {
5424 workspace.is_being_followed(CollaboratorId::Agent)
5425 })
5426 .unwrap_or(false),
5427 _ => self.should_be_following,
5428 }
5429 }
5430
5431 fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5432 let following = self.is_following(cx);
5433
5434 self.should_be_following = !following;
5435 if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
5436 self.workspace
5437 .update(cx, |workspace, cx| {
5438 if following {
5439 workspace.unfollow(CollaboratorId::Agent, window, cx);
5440 } else {
5441 workspace.follow(CollaboratorId::Agent, window, cx);
5442 }
5443 })
5444 .ok();
5445 }
5446
5447 telemetry::event!("Follow Agent Selected", following = !following);
5448 }
5449
5450 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
5451 let following = self.is_following(cx);
5452
5453 let tooltip_label = if following {
5454 if self.agent.name() == "Zed Agent" {
5455 format!("Stop Following the {}", self.agent.name())
5456 } else {
5457 format!("Stop Following {}", self.agent.name())
5458 }
5459 } else {
5460 if self.agent.name() == "Zed Agent" {
5461 format!("Follow the {}", self.agent.name())
5462 } else {
5463 format!("Follow {}", self.agent.name())
5464 }
5465 };
5466
5467 IconButton::new("follow-agent", IconName::Crosshair)
5468 .icon_size(IconSize::Small)
5469 .icon_color(Color::Muted)
5470 .toggle_state(following)
5471 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
5472 .tooltip(move |_window, cx| {
5473 if following {
5474 Tooltip::for_action(tooltip_label.clone(), &Follow, cx)
5475 } else {
5476 Tooltip::with_meta(
5477 tooltip_label.clone(),
5478 Some(&Follow),
5479 "Track the agent's location as it reads and edits files.",
5480 cx,
5481 )
5482 }
5483 })
5484 .on_click(cx.listener(move |this, _, window, cx| {
5485 this.toggle_following(window, cx);
5486 }))
5487 }
5488
5489 fn render_add_context_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5490 let message_editor = self.message_editor.clone();
5491 let menu_visible = message_editor.read(cx).is_completions_menu_visible(cx);
5492
5493 IconButton::new("add-context", IconName::AtSign)
5494 .icon_size(IconSize::Small)
5495 .icon_color(Color::Muted)
5496 .when(!menu_visible, |this| {
5497 this.tooltip(move |_window, cx| {
5498 Tooltip::with_meta("Add Context", None, "Or type @ to include context", cx)
5499 })
5500 })
5501 .on_click(cx.listener(move |_this, _, window, cx| {
5502 let message_editor_clone = message_editor.clone();
5503
5504 window.defer(cx, move |window, cx| {
5505 message_editor_clone.update(cx, |message_editor, cx| {
5506 message_editor.trigger_completion_menu(window, cx);
5507 });
5508 });
5509 }))
5510 }
5511
5512 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
5513 let workspace = self.workspace.clone();
5514 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
5515 Self::open_link(text, &workspace, window, cx);
5516 })
5517 }
5518
5519 fn open_link(
5520 url: SharedString,
5521 workspace: &WeakEntity<Workspace>,
5522 window: &mut Window,
5523 cx: &mut App,
5524 ) {
5525 let Some(workspace) = workspace.upgrade() else {
5526 cx.open_url(&url);
5527 return;
5528 };
5529
5530 if let Some(mention) = MentionUri::parse(&url, workspace.read(cx).path_style(cx)).log_err()
5531 {
5532 workspace.update(cx, |workspace, cx| match mention {
5533 MentionUri::File { abs_path } => {
5534 let project = workspace.project();
5535 let Some(path) =
5536 project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
5537 else {
5538 return;
5539 };
5540
5541 workspace
5542 .open_path(path, None, true, window, cx)
5543 .detach_and_log_err(cx);
5544 }
5545 MentionUri::PastedImage => {}
5546 MentionUri::Directory { abs_path } => {
5547 let project = workspace.project();
5548 let Some(entry_id) = project.update(cx, |project, cx| {
5549 let path = project.find_project_path(abs_path, cx)?;
5550 project.entry_for_path(&path, cx).map(|entry| entry.id)
5551 }) else {
5552 return;
5553 };
5554
5555 project.update(cx, |_, cx| {
5556 cx.emit(project::Event::RevealInProjectPanel(entry_id));
5557 });
5558 }
5559 MentionUri::Symbol {
5560 abs_path: path,
5561 line_range,
5562 ..
5563 }
5564 | MentionUri::Selection {
5565 abs_path: Some(path),
5566 line_range,
5567 } => {
5568 let project = workspace.project();
5569 let Some(path) =
5570 project.update(cx, |project, cx| project.find_project_path(path, cx))
5571 else {
5572 return;
5573 };
5574
5575 let item = workspace.open_path(path, None, true, window, cx);
5576 window
5577 .spawn(cx, async move |cx| {
5578 let Some(editor) = item.await?.downcast::<Editor>() else {
5579 return Ok(());
5580 };
5581 let range = Point::new(*line_range.start(), 0)
5582 ..Point::new(*line_range.start(), 0);
5583 editor
5584 .update_in(cx, |editor, window, cx| {
5585 editor.change_selections(
5586 SelectionEffects::scroll(Autoscroll::center()),
5587 window,
5588 cx,
5589 |s| s.select_ranges(vec![range]),
5590 );
5591 })
5592 .ok();
5593 anyhow::Ok(())
5594 })
5595 .detach_and_log_err(cx);
5596 }
5597 MentionUri::Selection { abs_path: None, .. } => {}
5598 MentionUri::Thread { id, name } => {
5599 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
5600 panel.update(cx, |panel, cx| {
5601 panel.load_agent_thread(
5602 AgentSessionInfo {
5603 session_id: id,
5604 cwd: None,
5605 title: Some(name.into()),
5606 updated_at: None,
5607 meta: None,
5608 },
5609 window,
5610 cx,
5611 )
5612 });
5613 }
5614 }
5615 MentionUri::TextThread { path, .. } => {
5616 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
5617 panel.update(cx, |panel, cx| {
5618 panel
5619 .open_saved_text_thread(path.as_path().into(), window, cx)
5620 .detach_and_log_err(cx);
5621 });
5622 }
5623 }
5624 MentionUri::Rule { id, .. } => {
5625 let PromptId::User { uuid } = id else {
5626 return;
5627 };
5628 window.dispatch_action(
5629 Box::new(OpenRulesLibrary {
5630 prompt_to_select: Some(uuid.0),
5631 }),
5632 cx,
5633 )
5634 }
5635 MentionUri::Fetch { url } => {
5636 cx.open_url(url.as_str());
5637 }
5638 })
5639 } else {
5640 cx.open_url(&url);
5641 }
5642 }
5643
5644 fn open_tool_call_location(
5645 &self,
5646 entry_ix: usize,
5647 location_ix: usize,
5648 window: &mut Window,
5649 cx: &mut Context<Self>,
5650 ) -> Option<()> {
5651 let (tool_call_location, agent_location) = self
5652 .thread()?
5653 .read(cx)
5654 .entries()
5655 .get(entry_ix)?
5656 .location(location_ix)?;
5657
5658 let project_path = self
5659 .project
5660 .read(cx)
5661 .find_project_path(&tool_call_location.path, cx)?;
5662
5663 let open_task = self
5664 .workspace
5665 .update(cx, |workspace, cx| {
5666 workspace.open_path(project_path, None, true, window, cx)
5667 })
5668 .log_err()?;
5669 window
5670 .spawn(cx, async move |cx| {
5671 let item = open_task.await?;
5672
5673 let Some(active_editor) = item.downcast::<Editor>() else {
5674 return anyhow::Ok(());
5675 };
5676
5677 active_editor.update_in(cx, |editor, window, cx| {
5678 let multibuffer = editor.buffer().read(cx);
5679 let buffer = multibuffer.as_singleton();
5680 if agent_location.buffer.upgrade() == buffer {
5681 let excerpt_id = multibuffer.excerpt_ids().first().cloned();
5682 let anchor =
5683 editor::Anchor::in_buffer(excerpt_id.unwrap(), agent_location.position);
5684 editor.change_selections(Default::default(), window, cx, |selections| {
5685 selections.select_anchor_ranges([anchor..anchor]);
5686 })
5687 } else {
5688 let row = tool_call_location.line.unwrap_or_default();
5689 editor.change_selections(Default::default(), window, cx, |selections| {
5690 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
5691 })
5692 }
5693 })?;
5694
5695 anyhow::Ok(())
5696 })
5697 .detach_and_log_err(cx);
5698
5699 None
5700 }
5701
5702 pub fn open_thread_as_markdown(
5703 &self,
5704 workspace: Entity<Workspace>,
5705 window: &mut Window,
5706 cx: &mut App,
5707 ) -> Task<Result<()>> {
5708 let markdown_language_task = workspace
5709 .read(cx)
5710 .app_state()
5711 .languages
5712 .language_for_name("Markdown");
5713
5714 let (thread_title, markdown) = if let Some(thread) = self.thread() {
5715 let thread = thread.read(cx);
5716 (thread.title().to_string(), thread.to_markdown(cx))
5717 } else {
5718 return Task::ready(Ok(()));
5719 };
5720
5721 let project = workspace.read(cx).project().clone();
5722 window.spawn(cx, async move |cx| {
5723 let markdown_language = markdown_language_task.await?;
5724
5725 let buffer = project
5726 .update(cx, |project, cx| project.create_buffer(false, cx))
5727 .await?;
5728
5729 buffer.update(cx, |buffer, cx| {
5730 buffer.set_text(markdown, cx);
5731 buffer.set_language(Some(markdown_language), cx);
5732 buffer.set_capability(language::Capability::ReadWrite, cx);
5733 });
5734
5735 workspace.update_in(cx, |workspace, window, cx| {
5736 let buffer = cx
5737 .new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_title.clone()));
5738
5739 workspace.add_item_to_active_pane(
5740 Box::new(cx.new(|cx| {
5741 let mut editor =
5742 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
5743 editor.set_breadcrumb_header(thread_title);
5744 editor
5745 })),
5746 None,
5747 true,
5748 window,
5749 cx,
5750 );
5751 })?;
5752 anyhow::Ok(())
5753 })
5754 }
5755
5756 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
5757 self.list_state.scroll_to(ListOffset::default());
5758 cx.notify();
5759 }
5760
5761 fn scroll_to_most_recent_user_prompt(&mut self, cx: &mut Context<Self>) {
5762 let Some(thread) = self.thread() else {
5763 return;
5764 };
5765
5766 let entries = thread.read(cx).entries();
5767 if entries.is_empty() {
5768 return;
5769 }
5770
5771 // Find the most recent user message and scroll it to the top of the viewport.
5772 // (Fallback: if no user message exists, scroll to the bottom.)
5773 if let Some(ix) = entries
5774 .iter()
5775 .rposition(|entry| matches!(entry, AgentThreadEntry::UserMessage(_)))
5776 {
5777 self.list_state.scroll_to(ListOffset {
5778 item_ix: ix,
5779 offset_in_item: px(0.0),
5780 });
5781 cx.notify();
5782 } else {
5783 self.scroll_to_bottom(cx);
5784 }
5785 }
5786
5787 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
5788 if let Some(thread) = self.thread() {
5789 let entry_count = thread.read(cx).entries().len();
5790 self.list_state.reset(entry_count);
5791 cx.notify();
5792 }
5793 }
5794
5795 fn notify_with_sound(
5796 &mut self,
5797 caption: impl Into<SharedString>,
5798 icon: IconName,
5799 window: &mut Window,
5800 cx: &mut Context<Self>,
5801 ) {
5802 self.play_notification_sound(window, cx);
5803 self.show_notification(caption, icon, window, cx);
5804 }
5805
5806 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
5807 let settings = AgentSettings::get_global(cx);
5808 if settings.play_sound_when_agent_done && !window.is_window_active() {
5809 Audio::play_sound(Sound::AgentDone, cx);
5810 }
5811 }
5812
5813 fn show_notification(
5814 &mut self,
5815 caption: impl Into<SharedString>,
5816 icon: IconName,
5817 window: &mut Window,
5818 cx: &mut Context<Self>,
5819 ) {
5820 if !self.notifications.is_empty() {
5821 return;
5822 }
5823
5824 let settings = AgentSettings::get_global(cx);
5825
5826 let window_is_inactive = !window.is_window_active();
5827 let panel_is_hidden = self
5828 .workspace
5829 .upgrade()
5830 .map(|workspace| AgentPanel::is_hidden(&workspace, cx))
5831 .unwrap_or(true);
5832
5833 let should_notify = window_is_inactive || panel_is_hidden;
5834
5835 if !should_notify {
5836 return;
5837 }
5838
5839 // TODO: Change this once we have title summarization for external agents.
5840 let title = self.agent.name();
5841
5842 match settings.notify_when_agent_waiting {
5843 NotifyWhenAgentWaiting::PrimaryScreen => {
5844 if let Some(primary) = cx.primary_display() {
5845 self.pop_up(icon, caption.into(), title, window, primary, cx);
5846 }
5847 }
5848 NotifyWhenAgentWaiting::AllScreens => {
5849 let caption = caption.into();
5850 for screen in cx.displays() {
5851 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
5852 }
5853 }
5854 NotifyWhenAgentWaiting::Never => {
5855 // Don't show anything
5856 }
5857 }
5858 }
5859
5860 fn pop_up(
5861 &mut self,
5862 icon: IconName,
5863 caption: SharedString,
5864 title: SharedString,
5865 window: &mut Window,
5866 screen: Rc<dyn PlatformDisplay>,
5867 cx: &mut Context<Self>,
5868 ) {
5869 let options = AgentNotification::window_options(screen, cx);
5870
5871 let project_name = self.workspace.upgrade().and_then(|workspace| {
5872 workspace
5873 .read(cx)
5874 .project()
5875 .read(cx)
5876 .visible_worktrees(cx)
5877 .next()
5878 .map(|worktree| worktree.read(cx).root_name_str().to_string())
5879 });
5880
5881 if let Some(screen_window) = cx
5882 .open_window(options, |_window, cx| {
5883 cx.new(|_cx| {
5884 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
5885 })
5886 })
5887 .log_err()
5888 && let Some(pop_up) = screen_window.entity(cx).log_err()
5889 {
5890 self.notification_subscriptions
5891 .entry(screen_window)
5892 .or_insert_with(Vec::new)
5893 .push(cx.subscribe_in(&pop_up, window, {
5894 |this, _, event, window, cx| match event {
5895 AgentNotificationEvent::Accepted => {
5896 let handle = window.window_handle();
5897 cx.activate(true);
5898
5899 let workspace_handle = this.workspace.clone();
5900
5901 // If there are multiple Zed windows, activate the correct one.
5902 cx.defer(move |cx| {
5903 handle
5904 .update(cx, |_view, window, _cx| {
5905 window.activate_window();
5906
5907 if let Some(workspace) = workspace_handle.upgrade() {
5908 workspace.update(_cx, |workspace, cx| {
5909 workspace.focus_panel::<AgentPanel>(window, cx);
5910 });
5911 }
5912 })
5913 .log_err();
5914 });
5915
5916 this.dismiss_notifications(cx);
5917 }
5918 AgentNotificationEvent::Dismissed => {
5919 this.dismiss_notifications(cx);
5920 }
5921 }
5922 }));
5923
5924 self.notifications.push(screen_window);
5925
5926 // If the user manually refocuses the original window, dismiss the popup.
5927 self.notification_subscriptions
5928 .entry(screen_window)
5929 .or_insert_with(Vec::new)
5930 .push({
5931 let pop_up_weak = pop_up.downgrade();
5932
5933 cx.observe_window_activation(window, move |_, window, cx| {
5934 if window.is_window_active()
5935 && let Some(pop_up) = pop_up_weak.upgrade()
5936 {
5937 pop_up.update(cx, |_, cx| {
5938 cx.emit(AgentNotificationEvent::Dismissed);
5939 });
5940 }
5941 })
5942 });
5943 }
5944 }
5945
5946 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
5947 for window in self.notifications.drain(..) {
5948 window
5949 .update(cx, |_, window, _| {
5950 window.remove_window();
5951 })
5952 .ok();
5953
5954 self.notification_subscriptions.remove(&window);
5955 }
5956 }
5957
5958 fn render_generating(&self, confirmation: bool, cx: &App) -> impl IntoElement {
5959 let show_stats = AgentSettings::get_global(cx).show_turn_stats;
5960 let elapsed_label = show_stats
5961 .then(|| {
5962 self.turn_started_at.and_then(|started_at| {
5963 let elapsed = started_at.elapsed();
5964 (elapsed > STOPWATCH_THRESHOLD).then(|| duration_alt_display(elapsed))
5965 })
5966 })
5967 .flatten();
5968
5969 let is_waiting = confirmation
5970 || self
5971 .thread()
5972 .is_some_and(|thread| thread.read(cx).has_in_progress_tool_calls());
5973
5974 let turn_tokens_label = elapsed_label
5975 .is_some()
5976 .then(|| {
5977 self.turn_tokens
5978 .filter(|&tokens| tokens > TOKEN_THRESHOLD)
5979 .map(|tokens| crate::text_thread_editor::humanize_token_count(tokens))
5980 })
5981 .flatten();
5982
5983 let arrow_icon = if is_waiting {
5984 IconName::ArrowUp
5985 } else {
5986 IconName::ArrowDown
5987 };
5988
5989 h_flex()
5990 .id("generating-spinner")
5991 .py_2()
5992 .px(rems_from_px(22.))
5993 .gap_2()
5994 .map(|this| {
5995 if confirmation {
5996 this.child(
5997 h_flex()
5998 .w_2()
5999 .child(SpinnerLabel::sand().size(LabelSize::Small)),
6000 )
6001 .child(
6002 div().min_w(rems(8.)).child(
6003 LoadingLabel::new("Waiting Confirmation")
6004 .size(LabelSize::Small)
6005 .color(Color::Muted),
6006 ),
6007 )
6008 } else {
6009 this.child(SpinnerLabel::new().size(LabelSize::Small))
6010 }
6011 })
6012 .when_some(elapsed_label, |this, elapsed| {
6013 this.child(
6014 Label::new(elapsed)
6015 .size(LabelSize::Small)
6016 .color(Color::Muted),
6017 )
6018 })
6019 .when_some(turn_tokens_label, |this, tokens| {
6020 this.child(
6021 h_flex()
6022 .gap_0p5()
6023 .child(
6024 Icon::new(arrow_icon)
6025 .size(IconSize::XSmall)
6026 .color(Color::Muted),
6027 )
6028 .child(
6029 Label::new(format!("{} tokens", tokens))
6030 .size(LabelSize::Small)
6031 .color(Color::Muted),
6032 ),
6033 )
6034 })
6035 .into_any_element()
6036 }
6037
6038 fn render_thread_controls(
6039 &self,
6040 thread: &Entity<AcpThread>,
6041 cx: &Context<Self>,
6042 ) -> impl IntoElement {
6043 let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
6044 if is_generating {
6045 return self.render_generating(false, cx).into_any_element();
6046 }
6047
6048 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
6049 .shape(ui::IconButtonShape::Square)
6050 .icon_size(IconSize::Small)
6051 .icon_color(Color::Ignored)
6052 .tooltip(Tooltip::text("Open Thread as Markdown"))
6053 .on_click(cx.listener(move |this, _, window, cx| {
6054 if let Some(workspace) = this.workspace.upgrade() {
6055 this.open_thread_as_markdown(workspace, window, cx)
6056 .detach_and_log_err(cx);
6057 }
6058 }));
6059
6060 let scroll_to_recent_user_prompt =
6061 IconButton::new("scroll_to_recent_user_prompt", IconName::ForwardArrow)
6062 .shape(ui::IconButtonShape::Square)
6063 .icon_size(IconSize::Small)
6064 .icon_color(Color::Ignored)
6065 .tooltip(Tooltip::text("Scroll To Most Recent User Prompt"))
6066 .on_click(cx.listener(move |this, _, _, cx| {
6067 this.scroll_to_most_recent_user_prompt(cx);
6068 }));
6069
6070 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
6071 .shape(ui::IconButtonShape::Square)
6072 .icon_size(IconSize::Small)
6073 .icon_color(Color::Ignored)
6074 .tooltip(Tooltip::text("Scroll To Top"))
6075 .on_click(cx.listener(move |this, _, _, cx| {
6076 this.scroll_to_top(cx);
6077 }));
6078
6079 let show_stats = AgentSettings::get_global(cx).show_turn_stats;
6080 let last_turn_clock = show_stats
6081 .then(|| {
6082 self.last_turn_duration
6083 .filter(|&duration| duration > STOPWATCH_THRESHOLD)
6084 .map(|duration| {
6085 Label::new(duration_alt_display(duration))
6086 .size(LabelSize::Small)
6087 .color(Color::Muted)
6088 })
6089 })
6090 .flatten();
6091
6092 let last_turn_tokens = last_turn_clock
6093 .is_some()
6094 .then(|| {
6095 self.last_turn_tokens
6096 .filter(|&tokens| tokens > TOKEN_THRESHOLD)
6097 .map(|tokens| {
6098 Label::new(format!(
6099 "{} tokens",
6100 crate::text_thread_editor::humanize_token_count(tokens)
6101 ))
6102 .size(LabelSize::Small)
6103 .color(Color::Muted)
6104 })
6105 })
6106 .flatten();
6107
6108 let mut container = h_flex()
6109 .w_full()
6110 .py_2()
6111 .px_5()
6112 .gap_px()
6113 .opacity(0.6)
6114 .hover(|s| s.opacity(1.))
6115 .justify_end()
6116 .when(
6117 last_turn_tokens.is_some() || last_turn_clock.is_some(),
6118 |this| {
6119 this.child(
6120 h_flex()
6121 .gap_1()
6122 .px_1()
6123 .when_some(last_turn_tokens, |this, label| this.child(label))
6124 .when_some(last_turn_clock, |this, label| this.child(label)),
6125 )
6126 },
6127 );
6128
6129 if AgentSettings::get_global(cx).enable_feedback
6130 && self
6131 .thread()
6132 .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
6133 {
6134 let feedback = self.thread_feedback.feedback;
6135
6136 let tooltip_meta = || {
6137 SharedString::new(
6138 "Rating the thread sends all of your current conversation to the Zed team.",
6139 )
6140 };
6141
6142 container = container
6143 .child(
6144 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
6145 .shape(ui::IconButtonShape::Square)
6146 .icon_size(IconSize::Small)
6147 .icon_color(match feedback {
6148 Some(ThreadFeedback::Positive) => Color::Accent,
6149 _ => Color::Ignored,
6150 })
6151 .tooltip(move |window, cx| match feedback {
6152 Some(ThreadFeedback::Positive) => {
6153 Tooltip::text("Thanks for your feedback!")(window, cx)
6154 }
6155 _ => Tooltip::with_meta("Helpful Response", None, tooltip_meta(), cx),
6156 })
6157 .on_click(cx.listener(move |this, _, window, cx| {
6158 this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
6159 })),
6160 )
6161 .child(
6162 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
6163 .shape(ui::IconButtonShape::Square)
6164 .icon_size(IconSize::Small)
6165 .icon_color(match feedback {
6166 Some(ThreadFeedback::Negative) => Color::Accent,
6167 _ => Color::Ignored,
6168 })
6169 .tooltip(move |window, cx| match feedback {
6170 Some(ThreadFeedback::Negative) => {
6171 Tooltip::text(
6172 "We appreciate your feedback and will use it to improve in the future.",
6173 )(window, cx)
6174 }
6175 _ => {
6176 Tooltip::with_meta("Not Helpful Response", None, tooltip_meta(), cx)
6177 }
6178 })
6179 .on_click(cx.listener(move |this, _, window, cx| {
6180 this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
6181 })),
6182 );
6183 }
6184
6185 if cx.has_flag::<AgentSharingFeatureFlag>()
6186 && self.is_imported_thread(cx)
6187 && self
6188 .project
6189 .read(cx)
6190 .client()
6191 .status()
6192 .borrow()
6193 .is_connected()
6194 {
6195 let sync_button = IconButton::new("sync-thread", IconName::ArrowCircle)
6196 .shape(ui::IconButtonShape::Square)
6197 .icon_size(IconSize::Small)
6198 .icon_color(Color::Ignored)
6199 .tooltip(Tooltip::text("Sync with source thread"))
6200 .on_click(cx.listener(move |this, _, window, cx| {
6201 this.sync_thread(window, cx);
6202 }));
6203
6204 container = container.child(sync_button);
6205 }
6206
6207 if cx.has_flag::<AgentSharingFeatureFlag>() && !self.is_imported_thread(cx) {
6208 let share_button = IconButton::new("share-thread", IconName::ArrowUpRight)
6209 .shape(ui::IconButtonShape::Square)
6210 .icon_size(IconSize::Small)
6211 .icon_color(Color::Ignored)
6212 .tooltip(Tooltip::text("Share Thread"))
6213 .on_click(cx.listener(move |this, _, window, cx| {
6214 this.share_thread(window, cx);
6215 }));
6216
6217 container = container.child(share_button);
6218 }
6219
6220 container
6221 .child(open_as_markdown)
6222 .child(scroll_to_recent_user_prompt)
6223 .child(scroll_to_top)
6224 .into_any_element()
6225 }
6226
6227 fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
6228 h_flex()
6229 .key_context("AgentFeedbackMessageEditor")
6230 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
6231 this.thread_feedback.dismiss_comments();
6232 cx.notify();
6233 }))
6234 .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
6235 this.submit_feedback_message(cx);
6236 }))
6237 .p_2()
6238 .mb_2()
6239 .mx_5()
6240 .gap_1()
6241 .rounded_md()
6242 .border_1()
6243 .border_color(cx.theme().colors().border)
6244 .bg(cx.theme().colors().editor_background)
6245 .child(div().w_full().child(editor))
6246 .child(
6247 h_flex()
6248 .child(
6249 IconButton::new("dismiss-feedback-message", IconName::Close)
6250 .icon_color(Color::Error)
6251 .icon_size(IconSize::XSmall)
6252 .shape(ui::IconButtonShape::Square)
6253 .on_click(cx.listener(move |this, _, _window, cx| {
6254 this.thread_feedback.dismiss_comments();
6255 cx.notify();
6256 })),
6257 )
6258 .child(
6259 IconButton::new("submit-feedback-message", IconName::Return)
6260 .icon_size(IconSize::XSmall)
6261 .shape(ui::IconButtonShape::Square)
6262 .on_click(cx.listener(move |this, _, _window, cx| {
6263 this.submit_feedback_message(cx);
6264 })),
6265 ),
6266 )
6267 }
6268
6269 fn handle_feedback_click(
6270 &mut self,
6271 feedback: ThreadFeedback,
6272 window: &mut Window,
6273 cx: &mut Context<Self>,
6274 ) {
6275 let Some(thread) = self.thread().cloned() else {
6276 return;
6277 };
6278
6279 self.thread_feedback.submit(thread, feedback, window, cx);
6280 cx.notify();
6281 }
6282
6283 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
6284 let Some(thread) = self.thread().cloned() else {
6285 return;
6286 };
6287
6288 self.thread_feedback.submit_comments(thread, cx);
6289 cx.notify();
6290 }
6291
6292 fn render_token_limit_callout(&self, cx: &mut Context<Self>) -> Option<Callout> {
6293 if self.token_limit_callout_dismissed {
6294 return None;
6295 }
6296
6297 let token_usage = self.thread()?.read(cx).token_usage()?;
6298 let ratio = token_usage.ratio();
6299
6300 let (severity, icon, title) = match ratio {
6301 acp_thread::TokenUsageRatio::Normal => return None,
6302 acp_thread::TokenUsageRatio::Warning => (
6303 Severity::Warning,
6304 IconName::Warning,
6305 "Thread reaching the token limit soon",
6306 ),
6307 acp_thread::TokenUsageRatio::Exceeded => (
6308 Severity::Error,
6309 IconName::XCircle,
6310 "Thread reached the token limit",
6311 ),
6312 };
6313
6314 let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
6315 thread.read(cx).completion_mode() == CompletionMode::Normal
6316 && thread
6317 .read(cx)
6318 .model()
6319 .is_some_and(|model| model.supports_burn_mode())
6320 });
6321
6322 let description = if burn_mode_available {
6323 "To continue, start a new thread from a summary or turn Burn Mode on."
6324 } else {
6325 "To continue, start a new thread from a summary."
6326 };
6327
6328 Some(
6329 Callout::new()
6330 .severity(severity)
6331 .icon(icon)
6332 .title(title)
6333 .description(description)
6334 .actions_slot(
6335 h_flex()
6336 .gap_0p5()
6337 .child(
6338 Button::new("start-new-thread", "Start New Thread")
6339 .label_size(LabelSize::Small)
6340 .on_click(cx.listener(|this, _, window, cx| {
6341 let Some(thread) = this.thread() else {
6342 return;
6343 };
6344 let session_id = thread.read(cx).session_id().clone();
6345 window.dispatch_action(
6346 crate::NewNativeAgentThreadFromSummary {
6347 from_session_id: session_id,
6348 }
6349 .boxed_clone(),
6350 cx,
6351 );
6352 })),
6353 )
6354 .when(burn_mode_available, |this| {
6355 this.child(
6356 IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
6357 .icon_size(IconSize::XSmall)
6358 .on_click(cx.listener(|this, _event, window, cx| {
6359 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
6360 })),
6361 )
6362 }),
6363 )
6364 .dismiss_action(self.dismiss_error_button(cx)),
6365 )
6366 }
6367
6368 fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
6369 if !self.is_using_zed_ai_models(cx) {
6370 return None;
6371 }
6372
6373 let user_store = self.project.read(cx).user_store().read(cx);
6374 if user_store.is_usage_based_billing_enabled() {
6375 return None;
6376 }
6377
6378 let plan = user_store
6379 .plan()
6380 .unwrap_or(cloud_llm_client::Plan::V1(PlanV1::ZedFree));
6381
6382 let usage = user_store.model_request_usage()?;
6383
6384 Some(
6385 div()
6386 .child(UsageCallout::new(plan, usage))
6387 .line_height(line_height),
6388 )
6389 }
6390
6391 fn agent_ui_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
6392 self.entry_view_state.update(cx, |entry_view_state, cx| {
6393 entry_view_state.agent_ui_font_size_changed(cx);
6394 });
6395 }
6396
6397 pub(crate) fn insert_dragged_files(
6398 &self,
6399 paths: Vec<project::ProjectPath>,
6400 added_worktrees: Vec<Entity<project::Worktree>>,
6401 window: &mut Window,
6402 cx: &mut Context<Self>,
6403 ) {
6404 self.message_editor.update(cx, |message_editor, cx| {
6405 message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
6406 })
6407 }
6408
6409 /// Inserts the selected text into the message editor or the message being
6410 /// edited, if any.
6411 pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
6412 self.active_editor(cx).update(cx, |editor, cx| {
6413 editor.insert_selections(window, cx);
6414 });
6415 }
6416
6417 fn render_thread_retry_status_callout(
6418 &self,
6419 _window: &mut Window,
6420 _cx: &mut Context<Self>,
6421 ) -> Option<Callout> {
6422 let state = self.thread_retry_status.as_ref()?;
6423
6424 let next_attempt_in = state
6425 .duration
6426 .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
6427 if next_attempt_in.is_zero() {
6428 return None;
6429 }
6430
6431 let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
6432
6433 let retry_message = if state.max_attempts == 1 {
6434 if next_attempt_in_secs == 1 {
6435 "Retrying. Next attempt in 1 second.".to_string()
6436 } else {
6437 format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
6438 }
6439 } else if next_attempt_in_secs == 1 {
6440 format!(
6441 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
6442 state.attempt, state.max_attempts,
6443 )
6444 } else {
6445 format!(
6446 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
6447 state.attempt, state.max_attempts,
6448 )
6449 };
6450
6451 Some(
6452 Callout::new()
6453 .severity(Severity::Warning)
6454 .title(state.last_error.clone())
6455 .description(retry_message),
6456 )
6457 }
6458
6459 fn render_codex_windows_warning(&self, cx: &mut Context<Self>) -> Callout {
6460 Callout::new()
6461 .icon(IconName::Warning)
6462 .severity(Severity::Warning)
6463 .title("Codex on Windows")
6464 .description("For best performance, run Codex in Windows Subsystem for Linux (WSL2)")
6465 .actions_slot(
6466 Button::new("open-wsl-modal", "Open in WSL")
6467 .icon_size(IconSize::Small)
6468 .icon_color(Color::Muted)
6469 .on_click(cx.listener({
6470 move |_, _, _window, cx| {
6471 #[cfg(windows)]
6472 _window.dispatch_action(
6473 zed_actions::wsl_actions::OpenWsl::default().boxed_clone(),
6474 cx,
6475 );
6476 cx.notify();
6477 }
6478 })),
6479 )
6480 .dismiss_action(
6481 IconButton::new("dismiss", IconName::Close)
6482 .icon_size(IconSize::Small)
6483 .icon_color(Color::Muted)
6484 .tooltip(Tooltip::text("Dismiss Warning"))
6485 .on_click(cx.listener({
6486 move |this, _, _, cx| {
6487 this.show_codex_windows_warning = false;
6488 cx.notify();
6489 }
6490 })),
6491 )
6492 }
6493
6494 fn render_thread_error(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
6495 let content = match self.thread_error.as_ref()? {
6496 ThreadError::Other(error) => self.render_any_thread_error(error.clone(), window, cx),
6497 ThreadError::Refusal => self.render_refusal_error(cx),
6498 ThreadError::AuthenticationRequired(error) => {
6499 self.render_authentication_required_error(error.clone(), cx)
6500 }
6501 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
6502 ThreadError::ModelRequestLimitReached(plan) => {
6503 self.render_model_request_limit_reached_error(*plan, cx)
6504 }
6505 ThreadError::ToolUseLimitReached => self.render_tool_use_limit_reached_error(cx)?,
6506 };
6507
6508 Some(div().child(content))
6509 }
6510
6511 fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
6512 v_flex().w_full().justify_end().child(
6513 h_flex()
6514 .p_2()
6515 .pr_3()
6516 .w_full()
6517 .gap_1p5()
6518 .border_t_1()
6519 .border_color(cx.theme().colors().border)
6520 .bg(cx.theme().colors().element_background)
6521 .child(
6522 h_flex()
6523 .flex_1()
6524 .gap_1p5()
6525 .child(
6526 Icon::new(IconName::Download)
6527 .color(Color::Accent)
6528 .size(IconSize::Small),
6529 )
6530 .child(Label::new("New version available").size(LabelSize::Small)),
6531 )
6532 .child(
6533 Button::new("update-button", format!("Update to v{}", version))
6534 .label_size(LabelSize::Small)
6535 .style(ButtonStyle::Tinted(TintColor::Accent))
6536 .on_click(cx.listener(|this, _, window, cx| {
6537 this.reset(window, cx);
6538 })),
6539 ),
6540 )
6541 }
6542
6543 fn current_mode_id(&self, cx: &App) -> Option<Arc<str>> {
6544 if let Some(thread) = self.as_native_thread(cx) {
6545 Some(thread.read(cx).profile().0.clone())
6546 } else if let Some(mode_selector) = self.mode_selector() {
6547 Some(mode_selector.read(cx).mode().0)
6548 } else {
6549 None
6550 }
6551 }
6552
6553 fn current_model_id(&self, cx: &App) -> Option<String> {
6554 self.model_selector
6555 .as_ref()
6556 .and_then(|selector| selector.read(cx).active_model(cx).map(|m| m.id.to_string()))
6557 }
6558
6559 fn current_model_name(&self, cx: &App) -> SharedString {
6560 // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
6561 // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
6562 // This provides better clarity about what refused the request
6563 if self.as_native_connection(cx).is_some() {
6564 self.model_selector
6565 .as_ref()
6566 .and_then(|selector| selector.read(cx).active_model(cx))
6567 .map(|model| model.name.clone())
6568 .unwrap_or_else(|| SharedString::from("The model"))
6569 } else {
6570 // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
6571 self.agent.name()
6572 }
6573 }
6574
6575 fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
6576 let model_or_agent_name = self.current_model_name(cx);
6577 let refusal_message = format!(
6578 "{} 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.",
6579 model_or_agent_name
6580 );
6581
6582 Callout::new()
6583 .severity(Severity::Error)
6584 .title("Request Refused")
6585 .icon(IconName::XCircle)
6586 .description(refusal_message.clone())
6587 .actions_slot(self.create_copy_button(&refusal_message))
6588 .dismiss_action(self.dismiss_error_button(cx))
6589 }
6590
6591 fn render_any_thread_error(
6592 &mut self,
6593 error: SharedString,
6594 window: &mut Window,
6595 cx: &mut Context<'_, Self>,
6596 ) -> Callout {
6597 let can_resume = self
6598 .thread()
6599 .map_or(false, |thread| thread.read(cx).can_resume(cx));
6600
6601 let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
6602 let thread = thread.read(cx);
6603 let supports_burn_mode = thread
6604 .model()
6605 .map_or(false, |model| model.supports_burn_mode());
6606 supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
6607 });
6608
6609 let markdown = if let Some(markdown) = &self.thread_error_markdown {
6610 markdown.clone()
6611 } else {
6612 let markdown = cx.new(|cx| Markdown::new(error.clone(), None, None, cx));
6613 self.thread_error_markdown = Some(markdown.clone());
6614 markdown
6615 };
6616
6617 let markdown_style = default_markdown_style(false, true, window, cx);
6618 let description = self
6619 .render_markdown(markdown, markdown_style)
6620 .into_any_element();
6621
6622 Callout::new()
6623 .severity(Severity::Error)
6624 .icon(IconName::XCircle)
6625 .title("An Error Happened")
6626 .description_slot(description)
6627 .actions_slot(
6628 h_flex()
6629 .gap_0p5()
6630 .when(can_resume && can_enable_burn_mode, |this| {
6631 this.child(
6632 Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
6633 .icon(IconName::ZedBurnMode)
6634 .icon_position(IconPosition::Start)
6635 .icon_size(IconSize::Small)
6636 .label_size(LabelSize::Small)
6637 .on_click(cx.listener(|this, _, window, cx| {
6638 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
6639 this.resume_chat(cx);
6640 })),
6641 )
6642 })
6643 .when(can_resume, |this| {
6644 this.child(
6645 IconButton::new("retry", IconName::RotateCw)
6646 .icon_size(IconSize::Small)
6647 .tooltip(Tooltip::text("Retry Generation"))
6648 .on_click(cx.listener(|this, _, _window, cx| {
6649 this.resume_chat(cx);
6650 })),
6651 )
6652 })
6653 .child(self.create_copy_button(error.to_string())),
6654 )
6655 .dismiss_action(self.dismiss_error_button(cx))
6656 }
6657
6658 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
6659 const ERROR_MESSAGE: &str =
6660 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
6661
6662 Callout::new()
6663 .severity(Severity::Error)
6664 .icon(IconName::XCircle)
6665 .title("Free Usage Exceeded")
6666 .description(ERROR_MESSAGE)
6667 .actions_slot(
6668 h_flex()
6669 .gap_0p5()
6670 .child(self.upgrade_button(cx))
6671 .child(self.create_copy_button(ERROR_MESSAGE)),
6672 )
6673 .dismiss_action(self.dismiss_error_button(cx))
6674 }
6675
6676 fn render_authentication_required_error(
6677 &self,
6678 error: SharedString,
6679 cx: &mut Context<Self>,
6680 ) -> Callout {
6681 Callout::new()
6682 .severity(Severity::Error)
6683 .title("Authentication Required")
6684 .icon(IconName::XCircle)
6685 .description(error.clone())
6686 .actions_slot(
6687 h_flex()
6688 .gap_0p5()
6689 .child(self.authenticate_button(cx))
6690 .child(self.create_copy_button(error)),
6691 )
6692 .dismiss_action(self.dismiss_error_button(cx))
6693 }
6694
6695 fn render_model_request_limit_reached_error(
6696 &self,
6697 plan: cloud_llm_client::Plan,
6698 cx: &mut Context<Self>,
6699 ) -> Callout {
6700 let error_message = match plan {
6701 cloud_llm_client::Plan::V1(PlanV1::ZedPro) => {
6702 "Upgrade to usage-based billing for more prompts."
6703 }
6704 cloud_llm_client::Plan::V1(PlanV1::ZedProTrial)
6705 | cloud_llm_client::Plan::V1(PlanV1::ZedFree) => "Upgrade to Zed Pro for more prompts.",
6706 cloud_llm_client::Plan::V2(_) => "",
6707 };
6708
6709 Callout::new()
6710 .severity(Severity::Error)
6711 .title("Model Prompt Limit Reached")
6712 .icon(IconName::XCircle)
6713 .description(error_message)
6714 .actions_slot(
6715 h_flex()
6716 .gap_0p5()
6717 .child(self.upgrade_button(cx))
6718 .child(self.create_copy_button(error_message)),
6719 )
6720 .dismiss_action(self.dismiss_error_button(cx))
6721 }
6722
6723 fn render_tool_use_limit_reached_error(&self, cx: &mut Context<Self>) -> Option<Callout> {
6724 let thread = self.as_native_thread(cx)?;
6725 let supports_burn_mode = thread
6726 .read(cx)
6727 .model()
6728 .is_some_and(|model| model.supports_burn_mode());
6729
6730 let focus_handle = self.focus_handle(cx);
6731
6732 Some(
6733 Callout::new()
6734 .icon(IconName::Info)
6735 .title("Consecutive tool use limit reached.")
6736 .actions_slot(
6737 h_flex()
6738 .gap_0p5()
6739 .when(supports_burn_mode, |this| {
6740 this.child(
6741 Button::new("continue-burn-mode", "Continue with Burn Mode")
6742 .style(ButtonStyle::Filled)
6743 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
6744 .layer(ElevationIndex::ModalSurface)
6745 .label_size(LabelSize::Small)
6746 .key_binding(
6747 KeyBinding::for_action_in(
6748 &ContinueWithBurnMode,
6749 &focus_handle,
6750 cx,
6751 )
6752 .map(|kb| kb.size(rems_from_px(10.))),
6753 )
6754 .tooltip(Tooltip::text(
6755 "Enable Burn Mode for unlimited tool use.",
6756 ))
6757 .on_click({
6758 cx.listener(move |this, _, _window, cx| {
6759 thread.update(cx, |thread, cx| {
6760 thread
6761 .set_completion_mode(CompletionMode::Burn, cx);
6762 });
6763 this.resume_chat(cx);
6764 })
6765 }),
6766 )
6767 })
6768 .child(
6769 Button::new("continue-conversation", "Continue")
6770 .layer(ElevationIndex::ModalSurface)
6771 .label_size(LabelSize::Small)
6772 .key_binding(
6773 KeyBinding::for_action_in(&ContinueThread, &focus_handle, cx)
6774 .map(|kb| kb.size(rems_from_px(10.))),
6775 )
6776 .on_click(cx.listener(|this, _, _window, cx| {
6777 this.resume_chat(cx);
6778 })),
6779 ),
6780 ),
6781 )
6782 }
6783
6784 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
6785 let message = message.into();
6786
6787 CopyButton::new(message).tooltip_label("Copy Error Message")
6788 }
6789
6790 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
6791 IconButton::new("dismiss", IconName::Close)
6792 .icon_size(IconSize::Small)
6793 .tooltip(Tooltip::text("Dismiss"))
6794 .on_click(cx.listener({
6795 move |this, _, _, cx| {
6796 this.clear_thread_error(cx);
6797 cx.notify();
6798 }
6799 }))
6800 }
6801
6802 fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
6803 Button::new("authenticate", "Authenticate")
6804 .label_size(LabelSize::Small)
6805 .style(ButtonStyle::Filled)
6806 .on_click(cx.listener({
6807 move |this, _, window, cx| {
6808 let agent = this.agent.clone();
6809 let ThreadState::Ready { thread, .. } = &this.thread_state else {
6810 return;
6811 };
6812
6813 let connection = thread.read(cx).connection().clone();
6814 this.clear_thread_error(cx);
6815 if let Some(message) = this.in_flight_prompt.take() {
6816 this.message_editor.update(cx, |editor, cx| {
6817 editor.set_message(message, window, cx);
6818 });
6819 }
6820 let this = cx.weak_entity();
6821 window.defer(cx, |window, cx| {
6822 Self::handle_auth_required(
6823 this,
6824 AuthRequired::new(),
6825 agent,
6826 connection,
6827 window,
6828 cx,
6829 );
6830 })
6831 }
6832 }))
6833 }
6834
6835 pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6836 let agent = self.agent.clone();
6837 let ThreadState::Ready { thread, .. } = &self.thread_state else {
6838 return;
6839 };
6840
6841 let connection = thread.read(cx).connection().clone();
6842 self.clear_thread_error(cx);
6843 let this = cx.weak_entity();
6844 window.defer(cx, |window, cx| {
6845 Self::handle_auth_required(this, AuthRequired::new(), agent, connection, window, cx);
6846 })
6847 }
6848
6849 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
6850 Button::new("upgrade", "Upgrade")
6851 .label_size(LabelSize::Small)
6852 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
6853 .on_click(cx.listener({
6854 move |this, _, _, cx| {
6855 this.clear_thread_error(cx);
6856 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
6857 }
6858 }))
6859 }
6860
6861 pub fn delete_history_entry(&mut self, entry: AgentSessionInfo, cx: &mut Context<Self>) {
6862 let Some(session_list) = self.session_list.as_ref() else {
6863 return;
6864 };
6865 let task = session_list.delete_session(&entry.session_id, cx);
6866 task.detach_and_log_err(cx);
6867 }
6868
6869 /// Returns the currently active editor, either for a message that is being
6870 /// edited or the editor for a new message.
6871 fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
6872 if let Some(index) = self.editing_message
6873 && let Some(editor) = self
6874 .entry_view_state
6875 .read(cx)
6876 .entry(index)
6877 .and_then(|e| e.message_editor())
6878 .cloned()
6879 {
6880 editor
6881 } else {
6882 self.message_editor.clone()
6883 }
6884 }
6885}
6886
6887fn loading_contents_spinner(size: IconSize) -> AnyElement {
6888 Icon::new(IconName::LoadCircle)
6889 .size(size)
6890 .color(Color::Accent)
6891 .with_rotate_animation(3)
6892 .into_any_element()
6893}
6894
6895fn placeholder_text(agent_name: &str, has_commands: bool) -> String {
6896 if agent_name == "Zed Agent" {
6897 format!("Message the {} — @ to include context", agent_name)
6898 } else if has_commands {
6899 format!(
6900 "Message {} — @ to include context, / for commands",
6901 agent_name
6902 )
6903 } else {
6904 format!("Message {} — @ to include context", agent_name)
6905 }
6906}
6907
6908impl Focusable for AcpThreadView {
6909 fn focus_handle(&self, cx: &App) -> FocusHandle {
6910 match self.thread_state {
6911 ThreadState::Ready { .. } => self.active_editor(cx).focus_handle(cx),
6912 ThreadState::Loading { .. }
6913 | ThreadState::LoadError(_)
6914 | ThreadState::Unauthenticated { .. } => self.focus_handle.clone(),
6915 }
6916 }
6917}
6918
6919#[cfg(any(test, feature = "test-support"))]
6920impl AcpThreadView {
6921 /// Expands a tool call so its content is visible.
6922 /// This is primarily useful for visual testing.
6923 pub fn expand_tool_call(&mut self, tool_call_id: acp::ToolCallId, cx: &mut Context<Self>) {
6924 self.expanded_tool_calls.insert(tool_call_id);
6925 cx.notify();
6926 }
6927}
6928
6929impl Render for AcpThreadView {
6930 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
6931 let has_messages = self.list_state.item_count() > 0;
6932 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
6933
6934 v_flex()
6935 .size_full()
6936 .key_context("AcpThread")
6937 .on_action(cx.listener(|this, _: &menu::Cancel, _, cx| {
6938 this.cancel_generation(cx);
6939 }))
6940 .on_action(cx.listener(Self::toggle_burn_mode))
6941 .on_action(cx.listener(Self::keep_all))
6942 .on_action(cx.listener(Self::reject_all))
6943 .on_action(cx.listener(Self::allow_always))
6944 .on_action(cx.listener(Self::allow_once))
6945 .on_action(cx.listener(Self::reject_once))
6946 .on_action(cx.listener(|this, _: &SendNextQueuedMessage, window, cx| {
6947 this.send_queued_message_at_index(0, true, window, cx);
6948 }))
6949 .on_action(cx.listener(|this, _: &ClearMessageQueue, _, cx| {
6950 this.message_queue.clear();
6951 cx.notify();
6952 }))
6953 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
6954 if let Some(config_options_view) = this.config_options_view.as_ref() {
6955 let handled = config_options_view.update(cx, |view, cx| {
6956 view.toggle_category_picker(
6957 acp::SessionConfigOptionCategory::Mode,
6958 window,
6959 cx,
6960 )
6961 });
6962 if handled {
6963 return;
6964 }
6965 }
6966
6967 if let Some(profile_selector) = this.profile_selector.as_ref() {
6968 profile_selector.read(cx).menu_handle().toggle(window, cx);
6969 } else if let Some(mode_selector) = this.mode_selector() {
6970 mode_selector.read(cx).menu_handle().toggle(window, cx);
6971 }
6972 }))
6973 .on_action(cx.listener(|this, _: &CycleModeSelector, window, cx| {
6974 if let Some(config_options_view) = this.config_options_view.as_ref() {
6975 let handled = config_options_view.update(cx, |view, cx| {
6976 view.cycle_category_option(
6977 acp::SessionConfigOptionCategory::Mode,
6978 false,
6979 cx,
6980 )
6981 });
6982 if handled {
6983 return;
6984 }
6985 }
6986
6987 if let Some(profile_selector) = this.profile_selector.as_ref() {
6988 profile_selector.update(cx, |profile_selector, cx| {
6989 profile_selector.cycle_profile(cx);
6990 });
6991 } else if let Some(mode_selector) = this.mode_selector() {
6992 mode_selector.update(cx, |mode_selector, cx| {
6993 mode_selector.cycle_mode(window, cx);
6994 });
6995 }
6996 }))
6997 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
6998 if let Some(config_options_view) = this.config_options_view.as_ref() {
6999 let handled = config_options_view.update(cx, |view, cx| {
7000 view.toggle_category_picker(
7001 acp::SessionConfigOptionCategory::Model,
7002 window,
7003 cx,
7004 )
7005 });
7006 if handled {
7007 return;
7008 }
7009 }
7010
7011 if let Some(model_selector) = this.model_selector.as_ref() {
7012 model_selector
7013 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
7014 }
7015 }))
7016 .on_action(cx.listener(|this, _: &CycleFavoriteModels, window, cx| {
7017 if let Some(config_options_view) = this.config_options_view.as_ref() {
7018 let handled = config_options_view.update(cx, |view, cx| {
7019 view.cycle_category_option(
7020 acp::SessionConfigOptionCategory::Model,
7021 true,
7022 cx,
7023 )
7024 });
7025 if handled {
7026 return;
7027 }
7028 }
7029
7030 if let Some(model_selector) = this.model_selector.as_ref() {
7031 model_selector.update(cx, |model_selector, cx| {
7032 model_selector.cycle_favorite_models(window, cx);
7033 });
7034 }
7035 }))
7036 .track_focus(&self.focus_handle)
7037 .bg(cx.theme().colors().panel_background)
7038 .child(match &self.thread_state {
7039 ThreadState::Unauthenticated {
7040 connection,
7041 description,
7042 configuration_view,
7043 pending_auth_method,
7044 ..
7045 } => v_flex()
7046 .flex_1()
7047 .size_full()
7048 .justify_end()
7049 .child(self.render_auth_required_state(
7050 connection,
7051 description.as_ref(),
7052 configuration_view.as_ref(),
7053 pending_auth_method.as_ref(),
7054 window,
7055 cx,
7056 ))
7057 .into_any_element(),
7058 ThreadState::Loading { .. } => v_flex()
7059 .flex_1()
7060 .child(self.render_recent_history(cx))
7061 .into_any(),
7062 ThreadState::LoadError(e) => v_flex()
7063 .flex_1()
7064 .size_full()
7065 .items_center()
7066 .justify_end()
7067 .child(self.render_load_error(e, window, cx))
7068 .into_any(),
7069 ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
7070 if has_messages {
7071 this.child(
7072 list(
7073 self.list_state.clone(),
7074 cx.processor(|this, index: usize, window, cx| {
7075 let Some((entry, len)) = this.thread().and_then(|thread| {
7076 let entries = &thread.read(cx).entries();
7077 Some((entries.get(index)?, entries.len()))
7078 }) else {
7079 return Empty.into_any();
7080 };
7081 this.render_entry(index, len, entry, window, cx)
7082 }),
7083 )
7084 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
7085 .flex_grow()
7086 .into_any(),
7087 )
7088 .vertical_scrollbar_for(&self.list_state, window, cx)
7089 .into_any()
7090 } else {
7091 this.child(self.render_recent_history(cx)).into_any()
7092 }
7093 }),
7094 })
7095 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
7096 // above so that the scrollbar doesn't render behind it. The current setup allows
7097 // the scrollbar to stop exactly at the activity bar start.
7098 .when(has_messages, |this| match &self.thread_state {
7099 ThreadState::Ready { thread, .. } => {
7100 this.children(self.render_activity_bar(thread, window, cx))
7101 }
7102 _ => this,
7103 })
7104 .children(self.render_thread_retry_status_callout(window, cx))
7105 .when(self.show_codex_windows_warning, |this| {
7106 this.child(self.render_codex_windows_warning(cx))
7107 })
7108 .children(self.render_thread_error(window, cx))
7109 .when_some(
7110 self.new_server_version_available.as_ref().filter(|_| {
7111 !has_messages || !matches!(self.thread_state, ThreadState::Ready { .. })
7112 }),
7113 |this, version| this.child(self.render_new_version_callout(&version, cx)),
7114 )
7115 .children(
7116 if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
7117 Some(usage_callout.into_any_element())
7118 } else {
7119 self.render_token_limit_callout(cx)
7120 .map(|token_limit_callout| token_limit_callout.into_any_element())
7121 },
7122 )
7123 .child(self.render_message_editor(window, cx))
7124 }
7125}
7126
7127fn default_markdown_style(
7128 buffer_font: bool,
7129 muted_text: bool,
7130 window: &Window,
7131 cx: &App,
7132) -> MarkdownStyle {
7133 let theme_settings = ThemeSettings::get_global(cx);
7134 let colors = cx.theme().colors();
7135
7136 let buffer_font_size = theme_settings.agent_buffer_font_size(cx);
7137
7138 let mut text_style = window.text_style();
7139 let line_height = buffer_font_size * 1.75;
7140
7141 let font_family = if buffer_font {
7142 theme_settings.buffer_font.family.clone()
7143 } else {
7144 theme_settings.ui_font.family.clone()
7145 };
7146
7147 let font_size = if buffer_font {
7148 theme_settings.agent_buffer_font_size(cx)
7149 } else {
7150 theme_settings.agent_ui_font_size(cx)
7151 };
7152
7153 let text_color = if muted_text {
7154 colors.text_muted
7155 } else {
7156 colors.text
7157 };
7158
7159 text_style.refine(&TextStyleRefinement {
7160 font_family: Some(font_family),
7161 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
7162 font_features: Some(theme_settings.ui_font.features.clone()),
7163 font_size: Some(font_size.into()),
7164 line_height: Some(line_height.into()),
7165 color: Some(text_color),
7166 ..Default::default()
7167 });
7168
7169 MarkdownStyle {
7170 base_text_style: text_style.clone(),
7171 syntax: cx.theme().syntax().clone(),
7172 selection_background_color: colors.element_selection_background,
7173 code_block_overflow_x_scroll: true,
7174 heading_level_styles: Some(HeadingLevelStyles {
7175 h1: Some(TextStyleRefinement {
7176 font_size: Some(rems(1.15).into()),
7177 ..Default::default()
7178 }),
7179 h2: Some(TextStyleRefinement {
7180 font_size: Some(rems(1.1).into()),
7181 ..Default::default()
7182 }),
7183 h3: Some(TextStyleRefinement {
7184 font_size: Some(rems(1.05).into()),
7185 ..Default::default()
7186 }),
7187 h4: Some(TextStyleRefinement {
7188 font_size: Some(rems(1.).into()),
7189 ..Default::default()
7190 }),
7191 h5: Some(TextStyleRefinement {
7192 font_size: Some(rems(0.95).into()),
7193 ..Default::default()
7194 }),
7195 h6: Some(TextStyleRefinement {
7196 font_size: Some(rems(0.875).into()),
7197 ..Default::default()
7198 }),
7199 }),
7200 code_block: StyleRefinement {
7201 padding: EdgesRefinement {
7202 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
7203 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
7204 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
7205 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
7206 },
7207 margin: EdgesRefinement {
7208 top: Some(Length::Definite(px(8.).into())),
7209 left: Some(Length::Definite(px(0.).into())),
7210 right: Some(Length::Definite(px(0.).into())),
7211 bottom: Some(Length::Definite(px(12.).into())),
7212 },
7213 border_style: Some(BorderStyle::Solid),
7214 border_widths: EdgesRefinement {
7215 top: Some(AbsoluteLength::Pixels(px(1.))),
7216 left: Some(AbsoluteLength::Pixels(px(1.))),
7217 right: Some(AbsoluteLength::Pixels(px(1.))),
7218 bottom: Some(AbsoluteLength::Pixels(px(1.))),
7219 },
7220 border_color: Some(colors.border_variant),
7221 background: Some(colors.editor_background.into()),
7222 text: TextStyleRefinement {
7223 font_family: Some(theme_settings.buffer_font.family.clone()),
7224 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
7225 font_features: Some(theme_settings.buffer_font.features.clone()),
7226 font_size: Some(buffer_font_size.into()),
7227 ..Default::default()
7228 },
7229 ..Default::default()
7230 },
7231 inline_code: TextStyleRefinement {
7232 font_family: Some(theme_settings.buffer_font.family.clone()),
7233 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
7234 font_features: Some(theme_settings.buffer_font.features.clone()),
7235 font_size: Some(buffer_font_size.into()),
7236 background_color: Some(colors.editor_foreground.opacity(0.08)),
7237 ..Default::default()
7238 },
7239 link: TextStyleRefinement {
7240 background_color: Some(colors.editor_foreground.opacity(0.025)),
7241 color: Some(colors.text_accent),
7242 underline: Some(UnderlineStyle {
7243 color: Some(colors.text_accent.opacity(0.5)),
7244 thickness: px(1.),
7245 ..Default::default()
7246 }),
7247 ..Default::default()
7248 },
7249 ..Default::default()
7250 }
7251}
7252
7253fn plan_label_markdown_style(
7254 status: &acp::PlanEntryStatus,
7255 window: &Window,
7256 cx: &App,
7257) -> MarkdownStyle {
7258 let default_md_style = default_markdown_style(false, false, window, cx);
7259
7260 MarkdownStyle {
7261 base_text_style: TextStyle {
7262 color: cx.theme().colors().text_muted,
7263 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
7264 Some(gpui::StrikethroughStyle {
7265 thickness: px(1.),
7266 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
7267 })
7268 } else {
7269 None
7270 },
7271 ..default_md_style.base_text_style
7272 },
7273 ..default_md_style
7274 }
7275}
7276
7277fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
7278 let default_md_style = default_markdown_style(true, false, window, cx);
7279
7280 MarkdownStyle {
7281 base_text_style: TextStyle {
7282 ..default_md_style.base_text_style
7283 },
7284 selection_background_color: cx.theme().colors().element_selection_background,
7285 ..Default::default()
7286 }
7287}
7288
7289#[cfg(test)]
7290pub(crate) mod tests {
7291 use acp_thread::{AgentSessionListResponse, StubAgentConnection};
7292 use action_log::ActionLog;
7293 use agent_client_protocol::SessionId;
7294 use editor::MultiBufferOffset;
7295 use fs::FakeFs;
7296 use gpui::{EventEmitter, TestAppContext, VisualTestContext};
7297 use project::Project;
7298 use serde_json::json;
7299 use settings::SettingsStore;
7300 use std::any::Any;
7301 use std::path::Path;
7302 use std::rc::Rc;
7303 use workspace::Item;
7304
7305 use super::*;
7306
7307 #[gpui::test]
7308 async fn test_drop(cx: &mut TestAppContext) {
7309 init_test(cx);
7310
7311 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7312 let weak_view = thread_view.downgrade();
7313 drop(thread_view);
7314 assert!(!weak_view.is_upgradable());
7315 }
7316
7317 #[gpui::test]
7318 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
7319 init_test(cx);
7320
7321 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7322
7323 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7324 message_editor.update_in(cx, |editor, window, cx| {
7325 editor.set_text("Hello", window, cx);
7326 });
7327
7328 cx.deactivate_window();
7329
7330 thread_view.update_in(cx, |thread_view, window, cx| {
7331 thread_view.send(window, cx);
7332 });
7333
7334 cx.run_until_parked();
7335
7336 assert!(
7337 cx.windows()
7338 .iter()
7339 .any(|window| window.downcast::<AgentNotification>().is_some())
7340 );
7341 }
7342
7343 #[gpui::test]
7344 async fn test_notification_for_error(cx: &mut TestAppContext) {
7345 init_test(cx);
7346
7347 let (thread_view, cx) =
7348 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
7349
7350 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7351 message_editor.update_in(cx, |editor, window, cx| {
7352 editor.set_text("Hello", window, cx);
7353 });
7354
7355 cx.deactivate_window();
7356
7357 thread_view.update_in(cx, |thread_view, window, cx| {
7358 thread_view.send(window, cx);
7359 });
7360
7361 cx.run_until_parked();
7362
7363 assert!(
7364 cx.windows()
7365 .iter()
7366 .any(|window| window.downcast::<AgentNotification>().is_some())
7367 );
7368 }
7369
7370 #[gpui::test]
7371 async fn test_recent_history_refreshes_when_session_list_swapped(cx: &mut TestAppContext) {
7372 init_test(cx);
7373
7374 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7375
7376 let session_a = AgentSessionInfo::new(SessionId::new("session-a"));
7377 let session_b = AgentSessionInfo::new(SessionId::new("session-b"));
7378
7379 let list_a: Rc<dyn AgentSessionList> =
7380 Rc::new(StubSessionList::new(vec![session_a.clone()]));
7381 let list_b: Rc<dyn AgentSessionList> =
7382 Rc::new(StubSessionList::new(vec![session_b.clone()]));
7383
7384 thread_view.update(cx, |view, cx| {
7385 view.set_session_list(Some(list_a.clone()), cx);
7386 });
7387 cx.run_until_parked();
7388
7389 thread_view.read_with(cx, |view, _cx| {
7390 assert_eq!(view.recent_history_entries.len(), 1);
7391 assert_eq!(
7392 view.recent_history_entries[0].session_id,
7393 session_a.session_id
7394 );
7395
7396 let session_list = view.session_list_state.borrow();
7397 let session_list = session_list.as_ref().expect("session list should be set");
7398 assert!(Rc::ptr_eq(session_list, &list_a));
7399 });
7400
7401 thread_view.update(cx, |view, cx| {
7402 view.set_session_list(Some(list_b.clone()), cx);
7403 });
7404 cx.run_until_parked();
7405
7406 thread_view.read_with(cx, |view, _cx| {
7407 assert_eq!(view.recent_history_entries.len(), 1);
7408 assert_eq!(
7409 view.recent_history_entries[0].session_id,
7410 session_b.session_id
7411 );
7412
7413 let session_list = view.session_list_state.borrow();
7414 let session_list = session_list.as_ref().expect("session list should be set");
7415 assert!(Rc::ptr_eq(session_list, &list_b));
7416 });
7417 }
7418
7419 #[gpui::test]
7420 async fn test_refusal_handling(cx: &mut TestAppContext) {
7421 init_test(cx);
7422
7423 let (thread_view, cx) =
7424 setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
7425
7426 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7427 message_editor.update_in(cx, |editor, window, cx| {
7428 editor.set_text("Do something harmful", window, cx);
7429 });
7430
7431 thread_view.update_in(cx, |thread_view, window, cx| {
7432 thread_view.send(window, cx);
7433 });
7434
7435 cx.run_until_parked();
7436
7437 // Check that the refusal error is set
7438 thread_view.read_with(cx, |thread_view, _cx| {
7439 assert!(
7440 matches!(thread_view.thread_error, Some(ThreadError::Refusal)),
7441 "Expected refusal error to be set"
7442 );
7443 });
7444 }
7445
7446 #[gpui::test]
7447 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
7448 init_test(cx);
7449
7450 let tool_call_id = acp::ToolCallId::new("1");
7451 let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Label")
7452 .kind(acp::ToolKind::Edit)
7453 .content(vec!["hi".into()]);
7454 let connection =
7455 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
7456 tool_call_id,
7457 vec![acp::PermissionOption::new(
7458 "1",
7459 "Allow",
7460 acp::PermissionOptionKind::AllowOnce,
7461 )],
7462 )]));
7463
7464 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
7465
7466 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
7467
7468 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7469 message_editor.update_in(cx, |editor, window, cx| {
7470 editor.set_text("Hello", window, cx);
7471 });
7472
7473 cx.deactivate_window();
7474
7475 thread_view.update_in(cx, |thread_view, window, cx| {
7476 thread_view.send(window, cx);
7477 });
7478
7479 cx.run_until_parked();
7480
7481 assert!(
7482 cx.windows()
7483 .iter()
7484 .any(|window| window.downcast::<AgentNotification>().is_some())
7485 );
7486 }
7487
7488 #[gpui::test]
7489 async fn test_notification_when_panel_hidden(cx: &mut TestAppContext) {
7490 init_test(cx);
7491
7492 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7493
7494 add_to_workspace(thread_view.clone(), cx);
7495
7496 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7497
7498 message_editor.update_in(cx, |editor, window, cx| {
7499 editor.set_text("Hello", window, cx);
7500 });
7501
7502 // Window is active (don't deactivate), but panel will be hidden
7503 // Note: In the test environment, the panel is not actually added to the dock,
7504 // so is_agent_panel_hidden will return true
7505
7506 thread_view.update_in(cx, |thread_view, window, cx| {
7507 thread_view.send(window, cx);
7508 });
7509
7510 cx.run_until_parked();
7511
7512 // Should show notification because window is active but panel is hidden
7513 assert!(
7514 cx.windows()
7515 .iter()
7516 .any(|window| window.downcast::<AgentNotification>().is_some()),
7517 "Expected notification when panel is hidden"
7518 );
7519 }
7520
7521 #[gpui::test]
7522 async fn test_notification_still_works_when_window_inactive(cx: &mut TestAppContext) {
7523 init_test(cx);
7524
7525 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7526
7527 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7528 message_editor.update_in(cx, |editor, window, cx| {
7529 editor.set_text("Hello", window, cx);
7530 });
7531
7532 // Deactivate window - should show notification regardless of setting
7533 cx.deactivate_window();
7534
7535 thread_view.update_in(cx, |thread_view, window, cx| {
7536 thread_view.send(window, cx);
7537 });
7538
7539 cx.run_until_parked();
7540
7541 // Should still show notification when window is inactive (existing behavior)
7542 assert!(
7543 cx.windows()
7544 .iter()
7545 .any(|window| window.downcast::<AgentNotification>().is_some()),
7546 "Expected notification when window is inactive"
7547 );
7548 }
7549
7550 #[gpui::test]
7551 async fn test_notification_respects_never_setting(cx: &mut TestAppContext) {
7552 init_test(cx);
7553
7554 // Set notify_when_agent_waiting to Never
7555 cx.update(|cx| {
7556 AgentSettings::override_global(
7557 AgentSettings {
7558 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
7559 ..AgentSettings::get_global(cx).clone()
7560 },
7561 cx,
7562 );
7563 });
7564
7565 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7566
7567 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7568 message_editor.update_in(cx, |editor, window, cx| {
7569 editor.set_text("Hello", window, cx);
7570 });
7571
7572 // Window is active
7573
7574 thread_view.update_in(cx, |thread_view, window, cx| {
7575 thread_view.send(window, cx);
7576 });
7577
7578 cx.run_until_parked();
7579
7580 // Should NOT show notification because notify_when_agent_waiting is Never
7581 assert!(
7582 !cx.windows()
7583 .iter()
7584 .any(|window| window.downcast::<AgentNotification>().is_some()),
7585 "Expected no notification when notify_when_agent_waiting is Never"
7586 );
7587 }
7588
7589 #[gpui::test]
7590 async fn test_notification_closed_when_thread_view_dropped(cx: &mut TestAppContext) {
7591 init_test(cx);
7592
7593 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
7594
7595 let weak_view = thread_view.downgrade();
7596
7597 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7598 message_editor.update_in(cx, |editor, window, cx| {
7599 editor.set_text("Hello", window, cx);
7600 });
7601
7602 cx.deactivate_window();
7603
7604 thread_view.update_in(cx, |thread_view, window, cx| {
7605 thread_view.send(window, cx);
7606 });
7607
7608 cx.run_until_parked();
7609
7610 // Verify notification is shown
7611 assert!(
7612 cx.windows()
7613 .iter()
7614 .any(|window| window.downcast::<AgentNotification>().is_some()),
7615 "Expected notification to be shown"
7616 );
7617
7618 // Drop the thread view (simulating navigation to a new thread)
7619 drop(thread_view);
7620 drop(message_editor);
7621 // Trigger an update to flush effects, which will call release_dropped_entities
7622 cx.update(|_window, _cx| {});
7623 cx.run_until_parked();
7624
7625 // Verify the entity was actually released
7626 assert!(
7627 !weak_view.is_upgradable(),
7628 "Thread view entity should be released after dropping"
7629 );
7630
7631 // The notification should be automatically closed via on_release
7632 assert!(
7633 !cx.windows()
7634 .iter()
7635 .any(|window| window.downcast::<AgentNotification>().is_some()),
7636 "Notification should be closed when thread view is dropped"
7637 );
7638 }
7639
7640 async fn setup_thread_view(
7641 agent: impl AgentServer + 'static,
7642 cx: &mut TestAppContext,
7643 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
7644 let fs = FakeFs::new(cx.executor());
7645 let project = Project::test(fs, [], cx).await;
7646 let (workspace, cx) =
7647 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7648
7649 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
7650
7651 let thread_view = cx.update(|window, cx| {
7652 cx.new(|cx| {
7653 AcpThreadView::new(
7654 Rc::new(agent),
7655 None,
7656 None,
7657 workspace.downgrade(),
7658 project,
7659 Some(thread_store),
7660 None,
7661 false,
7662 window,
7663 cx,
7664 )
7665 })
7666 });
7667 cx.run_until_parked();
7668 (thread_view, cx)
7669 }
7670
7671 fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
7672 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
7673
7674 workspace
7675 .update_in(cx, |workspace, window, cx| {
7676 workspace.add_item_to_active_pane(
7677 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
7678 None,
7679 true,
7680 window,
7681 cx,
7682 );
7683 })
7684 .unwrap();
7685 }
7686
7687 struct ThreadViewItem(Entity<AcpThreadView>);
7688
7689 impl Item for ThreadViewItem {
7690 type Event = ();
7691
7692 fn include_in_nav_history() -> bool {
7693 false
7694 }
7695
7696 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
7697 "Test".into()
7698 }
7699 }
7700
7701 impl EventEmitter<()> for ThreadViewItem {}
7702
7703 impl Focusable for ThreadViewItem {
7704 fn focus_handle(&self, cx: &App) -> FocusHandle {
7705 self.0.read(cx).focus_handle(cx)
7706 }
7707 }
7708
7709 impl Render for ThreadViewItem {
7710 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7711 self.0.clone().into_any_element()
7712 }
7713 }
7714
7715 struct StubAgentServer<C> {
7716 connection: C,
7717 }
7718
7719 impl<C> StubAgentServer<C> {
7720 fn new(connection: C) -> Self {
7721 Self { connection }
7722 }
7723 }
7724
7725 impl StubAgentServer<StubAgentConnection> {
7726 fn default_response() -> Self {
7727 let conn = StubAgentConnection::new();
7728 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
7729 acp::ContentChunk::new("Default response".into()),
7730 )]);
7731 Self::new(conn)
7732 }
7733 }
7734
7735 #[derive(Clone)]
7736 struct StubSessionList {
7737 sessions: Vec<AgentSessionInfo>,
7738 }
7739
7740 impl StubSessionList {
7741 fn new(sessions: Vec<AgentSessionInfo>) -> Self {
7742 Self { sessions }
7743 }
7744 }
7745
7746 impl AgentSessionList for StubSessionList {
7747 fn list_sessions(
7748 &self,
7749 _request: AgentSessionListRequest,
7750 _cx: &mut App,
7751 ) -> Task<anyhow::Result<AgentSessionListResponse>> {
7752 Task::ready(Ok(AgentSessionListResponse::new(self.sessions.clone())))
7753 }
7754 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
7755 self
7756 }
7757 }
7758
7759 impl<C> AgentServer for StubAgentServer<C>
7760 where
7761 C: 'static + AgentConnection + Send + Clone,
7762 {
7763 fn logo(&self) -> ui::IconName {
7764 ui::IconName::Ai
7765 }
7766
7767 fn name(&self) -> SharedString {
7768 "Test".into()
7769 }
7770
7771 fn connect(
7772 &self,
7773 _root_dir: Option<&Path>,
7774 _delegate: AgentServerDelegate,
7775 _cx: &mut App,
7776 ) -> Task<gpui::Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
7777 Task::ready(Ok((Rc::new(self.connection.clone()), None)))
7778 }
7779
7780 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
7781 self
7782 }
7783 }
7784
7785 #[derive(Clone)]
7786 struct SaboteurAgentConnection;
7787
7788 impl AgentConnection for SaboteurAgentConnection {
7789 fn telemetry_id(&self) -> SharedString {
7790 "saboteur".into()
7791 }
7792
7793 fn new_thread(
7794 self: Rc<Self>,
7795 project: Entity<Project>,
7796 _cwd: &Path,
7797 cx: &mut gpui::App,
7798 ) -> Task<gpui::Result<Entity<AcpThread>>> {
7799 Task::ready(Ok(cx.new(|cx| {
7800 let action_log = cx.new(|_| ActionLog::new(project.clone()));
7801 AcpThread::new(
7802 "SaboteurAgentConnection",
7803 self,
7804 project,
7805 action_log,
7806 SessionId::new("test"),
7807 watch::Receiver::constant(
7808 acp::PromptCapabilities::new()
7809 .image(true)
7810 .audio(true)
7811 .embedded_context(true),
7812 ),
7813 cx,
7814 )
7815 })))
7816 }
7817
7818 fn auth_methods(&self) -> &[acp::AuthMethod] {
7819 &[]
7820 }
7821
7822 fn authenticate(
7823 &self,
7824 _method_id: acp::AuthMethodId,
7825 _cx: &mut App,
7826 ) -> Task<gpui::Result<()>> {
7827 unimplemented!()
7828 }
7829
7830 fn prompt(
7831 &self,
7832 _id: Option<acp_thread::UserMessageId>,
7833 _params: acp::PromptRequest,
7834 _cx: &mut App,
7835 ) -> Task<gpui::Result<acp::PromptResponse>> {
7836 Task::ready(Err(anyhow::anyhow!("Error prompting")))
7837 }
7838
7839 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
7840 unimplemented!()
7841 }
7842
7843 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
7844 self
7845 }
7846 }
7847
7848 /// Simulates a model which always returns a refusal response
7849 #[derive(Clone)]
7850 struct RefusalAgentConnection;
7851
7852 impl AgentConnection for RefusalAgentConnection {
7853 fn telemetry_id(&self) -> SharedString {
7854 "refusal".into()
7855 }
7856
7857 fn new_thread(
7858 self: Rc<Self>,
7859 project: Entity<Project>,
7860 _cwd: &Path,
7861 cx: &mut gpui::App,
7862 ) -> Task<gpui::Result<Entity<AcpThread>>> {
7863 Task::ready(Ok(cx.new(|cx| {
7864 let action_log = cx.new(|_| ActionLog::new(project.clone()));
7865 AcpThread::new(
7866 "RefusalAgentConnection",
7867 self,
7868 project,
7869 action_log,
7870 SessionId::new("test"),
7871 watch::Receiver::constant(
7872 acp::PromptCapabilities::new()
7873 .image(true)
7874 .audio(true)
7875 .embedded_context(true),
7876 ),
7877 cx,
7878 )
7879 })))
7880 }
7881
7882 fn auth_methods(&self) -> &[acp::AuthMethod] {
7883 &[]
7884 }
7885
7886 fn authenticate(
7887 &self,
7888 _method_id: acp::AuthMethodId,
7889 _cx: &mut App,
7890 ) -> Task<gpui::Result<()>> {
7891 unimplemented!()
7892 }
7893
7894 fn prompt(
7895 &self,
7896 _id: Option<acp_thread::UserMessageId>,
7897 _params: acp::PromptRequest,
7898 _cx: &mut App,
7899 ) -> Task<gpui::Result<acp::PromptResponse>> {
7900 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::Refusal)))
7901 }
7902
7903 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
7904 unimplemented!()
7905 }
7906
7907 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
7908 self
7909 }
7910 }
7911
7912 pub(crate) fn init_test(cx: &mut TestAppContext) {
7913 cx.update(|cx| {
7914 let settings_store = SettingsStore::test(cx);
7915 cx.set_global(settings_store);
7916 theme::init(theme::LoadThemes::JustBase, cx);
7917 release_channel::init(semver::Version::new(0, 0, 0), cx);
7918 prompt_store::init(cx)
7919 });
7920 }
7921
7922 #[gpui::test]
7923 async fn test_rewind_views(cx: &mut TestAppContext) {
7924 init_test(cx);
7925
7926 let fs = FakeFs::new(cx.executor());
7927 fs.insert_tree(
7928 "/project",
7929 json!({
7930 "test1.txt": "old content 1",
7931 "test2.txt": "old content 2"
7932 }),
7933 )
7934 .await;
7935 let project = Project::test(fs, [Path::new("/project")], cx).await;
7936 let (workspace, cx) =
7937 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7938
7939 let thread_store = cx.update(|_window, cx| cx.new(|cx| ThreadStore::new(cx)));
7940
7941 let connection = Rc::new(StubAgentConnection::new());
7942 let thread_view = cx.update(|window, cx| {
7943 cx.new(|cx| {
7944 AcpThreadView::new(
7945 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
7946 None,
7947 None,
7948 workspace.downgrade(),
7949 project.clone(),
7950 Some(thread_store.clone()),
7951 None,
7952 false,
7953 window,
7954 cx,
7955 )
7956 })
7957 });
7958
7959 cx.run_until_parked();
7960
7961 let thread = thread_view
7962 .read_with(cx, |view, _| view.thread().cloned())
7963 .unwrap();
7964
7965 // First user message
7966 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
7967 acp::ToolCall::new("tool1", "Edit file 1")
7968 .kind(acp::ToolKind::Edit)
7969 .status(acp::ToolCallStatus::Completed)
7970 .content(vec![acp::ToolCallContent::Diff(
7971 acp::Diff::new("/project/test1.txt", "new content 1").old_text("old content 1"),
7972 )]),
7973 )]);
7974
7975 thread
7976 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
7977 .await
7978 .unwrap();
7979 cx.run_until_parked();
7980
7981 thread.read_with(cx, |thread, _| {
7982 assert_eq!(thread.entries().len(), 2);
7983 });
7984
7985 thread_view.read_with(cx, |view, cx| {
7986 view.entry_view_state.read_with(cx, |entry_view_state, _| {
7987 assert!(
7988 entry_view_state
7989 .entry(0)
7990 .unwrap()
7991 .message_editor()
7992 .is_some()
7993 );
7994 assert!(entry_view_state.entry(1).unwrap().has_content());
7995 });
7996 });
7997
7998 // Second user message
7999 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
8000 acp::ToolCall::new("tool2", "Edit file 2")
8001 .kind(acp::ToolKind::Edit)
8002 .status(acp::ToolCallStatus::Completed)
8003 .content(vec![acp::ToolCallContent::Diff(
8004 acp::Diff::new("/project/test2.txt", "new content 2").old_text("old content 2"),
8005 )]),
8006 )]);
8007
8008 thread
8009 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
8010 .await
8011 .unwrap();
8012 cx.run_until_parked();
8013
8014 let second_user_message_id = thread.read_with(cx, |thread, _| {
8015 assert_eq!(thread.entries().len(), 4);
8016 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
8017 panic!();
8018 };
8019 user_message.id.clone().unwrap()
8020 });
8021
8022 thread_view.read_with(cx, |view, cx| {
8023 view.entry_view_state.read_with(cx, |entry_view_state, _| {
8024 assert!(
8025 entry_view_state
8026 .entry(0)
8027 .unwrap()
8028 .message_editor()
8029 .is_some()
8030 );
8031 assert!(entry_view_state.entry(1).unwrap().has_content());
8032 assert!(
8033 entry_view_state
8034 .entry(2)
8035 .unwrap()
8036 .message_editor()
8037 .is_some()
8038 );
8039 assert!(entry_view_state.entry(3).unwrap().has_content());
8040 });
8041 });
8042
8043 // Rewind to first message
8044 thread
8045 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
8046 .await
8047 .unwrap();
8048
8049 cx.run_until_parked();
8050
8051 thread.read_with(cx, |thread, _| {
8052 assert_eq!(thread.entries().len(), 2);
8053 });
8054
8055 thread_view.read_with(cx, |view, cx| {
8056 view.entry_view_state.read_with(cx, |entry_view_state, _| {
8057 assert!(
8058 entry_view_state
8059 .entry(0)
8060 .unwrap()
8061 .message_editor()
8062 .is_some()
8063 );
8064 assert!(entry_view_state.entry(1).unwrap().has_content());
8065
8066 // Old views should be dropped
8067 assert!(entry_view_state.entry(2).is_none());
8068 assert!(entry_view_state.entry(3).is_none());
8069 });
8070 });
8071 }
8072
8073 #[gpui::test]
8074 async fn test_scroll_to_most_recent_user_prompt(cx: &mut TestAppContext) {
8075 init_test(cx);
8076
8077 let connection = StubAgentConnection::new();
8078
8079 // Each user prompt will result in a user message entry plus an agent message entry.
8080 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8081 acp::ContentChunk::new("Response 1".into()),
8082 )]);
8083
8084 let (thread_view, cx) =
8085 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
8086
8087 let thread = thread_view
8088 .read_with(cx, |view, _| view.thread().cloned())
8089 .unwrap();
8090
8091 thread
8092 .update(cx, |thread, cx| thread.send_raw("Prompt 1", cx))
8093 .await
8094 .unwrap();
8095 cx.run_until_parked();
8096
8097 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8098 acp::ContentChunk::new("Response 2".into()),
8099 )]);
8100
8101 thread
8102 .update(cx, |thread, cx| thread.send_raw("Prompt 2", cx))
8103 .await
8104 .unwrap();
8105 cx.run_until_parked();
8106
8107 // Move somewhere else first so we're not trivially already on the last user prompt.
8108 thread_view.update(cx, |view, cx| {
8109 view.scroll_to_top(cx);
8110 });
8111 cx.run_until_parked();
8112
8113 thread_view.update(cx, |view, cx| {
8114 view.scroll_to_most_recent_user_prompt(cx);
8115 let scroll_top = view.list_state.logical_scroll_top();
8116 // Entries layout is: [User1, Assistant1, User2, Assistant2]
8117 assert_eq!(scroll_top.item_ix, 2);
8118 });
8119 }
8120
8121 #[gpui::test]
8122 async fn test_scroll_to_most_recent_user_prompt_falls_back_to_bottom_without_user_messages(
8123 cx: &mut TestAppContext,
8124 ) {
8125 init_test(cx);
8126
8127 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
8128
8129 // With no entries, scrolling should be a no-op and must not panic.
8130 thread_view.update(cx, |view, cx| {
8131 view.scroll_to_most_recent_user_prompt(cx);
8132 let scroll_top = view.list_state.logical_scroll_top();
8133 assert_eq!(scroll_top.item_ix, 0);
8134 });
8135 }
8136
8137 #[gpui::test]
8138 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
8139 init_test(cx);
8140
8141 let connection = StubAgentConnection::new();
8142
8143 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8144 acp::ContentChunk::new("Response".into()),
8145 )]);
8146
8147 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
8148 add_to_workspace(thread_view.clone(), cx);
8149
8150 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8151 message_editor.update_in(cx, |editor, window, cx| {
8152 editor.set_text("Original message to edit", window, cx);
8153 });
8154 thread_view.update_in(cx, |thread_view, window, cx| {
8155 thread_view.send(window, cx);
8156 });
8157
8158 cx.run_until_parked();
8159
8160 let user_message_editor = thread_view.read_with(cx, |view, cx| {
8161 assert_eq!(view.editing_message, None);
8162
8163 view.entry_view_state
8164 .read(cx)
8165 .entry(0)
8166 .unwrap()
8167 .message_editor()
8168 .unwrap()
8169 .clone()
8170 });
8171
8172 // Focus
8173 cx.focus(&user_message_editor);
8174 thread_view.read_with(cx, |view, _cx| {
8175 assert_eq!(view.editing_message, Some(0));
8176 });
8177
8178 // Edit
8179 user_message_editor.update_in(cx, |editor, window, cx| {
8180 editor.set_text("Edited message content", window, cx);
8181 });
8182
8183 // Cancel
8184 user_message_editor.update_in(cx, |_editor, window, cx| {
8185 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
8186 });
8187
8188 thread_view.read_with(cx, |view, _cx| {
8189 assert_eq!(view.editing_message, None);
8190 });
8191
8192 user_message_editor.read_with(cx, |editor, cx| {
8193 assert_eq!(editor.text(cx), "Original message to edit");
8194 });
8195 }
8196
8197 #[gpui::test]
8198 async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
8199 init_test(cx);
8200
8201 let connection = StubAgentConnection::new();
8202
8203 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
8204 add_to_workspace(thread_view.clone(), cx);
8205
8206 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8207 let mut events = cx.events(&message_editor);
8208 message_editor.update_in(cx, |editor, window, cx| {
8209 editor.set_text("", window, cx);
8210 });
8211
8212 message_editor.update_in(cx, |_editor, window, cx| {
8213 window.dispatch_action(Box::new(Chat), cx);
8214 });
8215 cx.run_until_parked();
8216 // We shouldn't have received any messages
8217 assert!(matches!(
8218 events.try_next(),
8219 Err(futures::channel::mpsc::TryRecvError { .. })
8220 ));
8221 }
8222
8223 #[gpui::test]
8224 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
8225 init_test(cx);
8226
8227 let connection = StubAgentConnection::new();
8228
8229 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8230 acp::ContentChunk::new("Response".into()),
8231 )]);
8232
8233 let (thread_view, cx) =
8234 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
8235 add_to_workspace(thread_view.clone(), cx);
8236
8237 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8238 message_editor.update_in(cx, |editor, window, cx| {
8239 editor.set_text("Original message to edit", window, cx);
8240 });
8241 thread_view.update_in(cx, |thread_view, window, cx| {
8242 thread_view.send(window, cx);
8243 });
8244
8245 cx.run_until_parked();
8246
8247 let user_message_editor = thread_view.read_with(cx, |view, cx| {
8248 assert_eq!(view.editing_message, None);
8249 assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
8250
8251 view.entry_view_state
8252 .read(cx)
8253 .entry(0)
8254 .unwrap()
8255 .message_editor()
8256 .unwrap()
8257 .clone()
8258 });
8259
8260 // Focus
8261 cx.focus(&user_message_editor);
8262
8263 // Edit
8264 user_message_editor.update_in(cx, |editor, window, cx| {
8265 editor.set_text("Edited message content", window, cx);
8266 });
8267
8268 // Send
8269 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8270 acp::ContentChunk::new("New Response".into()),
8271 )]);
8272
8273 user_message_editor.update_in(cx, |_editor, window, cx| {
8274 window.dispatch_action(Box::new(Chat), cx);
8275 });
8276
8277 cx.run_until_parked();
8278
8279 thread_view.read_with(cx, |view, cx| {
8280 assert_eq!(view.editing_message, None);
8281
8282 let entries = view.thread().unwrap().read(cx).entries();
8283 assert_eq!(entries.len(), 2);
8284 assert_eq!(
8285 entries[0].to_markdown(cx),
8286 "## User\n\nEdited message content\n\n"
8287 );
8288 assert_eq!(
8289 entries[1].to_markdown(cx),
8290 "## Assistant\n\nNew Response\n\n"
8291 );
8292
8293 let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
8294 assert!(!state.entry(1).unwrap().has_content());
8295 state.entry(0).unwrap().message_editor().unwrap().clone()
8296 });
8297
8298 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
8299 })
8300 }
8301
8302 #[gpui::test]
8303 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
8304 init_test(cx);
8305
8306 let connection = StubAgentConnection::new();
8307
8308 let (thread_view, cx) =
8309 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
8310 add_to_workspace(thread_view.clone(), cx);
8311
8312 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8313 message_editor.update_in(cx, |editor, window, cx| {
8314 editor.set_text("Original message to edit", window, cx);
8315 });
8316 thread_view.update_in(cx, |thread_view, window, cx| {
8317 thread_view.send(window, cx);
8318 });
8319
8320 cx.run_until_parked();
8321
8322 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
8323 let thread = view.thread().unwrap().read(cx);
8324 assert_eq!(thread.entries().len(), 1);
8325
8326 let editor = view
8327 .entry_view_state
8328 .read(cx)
8329 .entry(0)
8330 .unwrap()
8331 .message_editor()
8332 .unwrap()
8333 .clone();
8334
8335 (editor, thread.session_id().clone())
8336 });
8337
8338 // Focus
8339 cx.focus(&user_message_editor);
8340
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 thread_view.read_with(cx, |view, _cx| {
8351 assert_eq!(view.editing_message, Some(0));
8352 });
8353
8354 // Finish streaming response
8355 cx.update(|_, cx| {
8356 connection.send_update(
8357 session_id.clone(),
8358 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("Response".into())),
8359 cx,
8360 );
8361 connection.end_turn(session_id, acp::StopReason::EndTurn);
8362 });
8363
8364 thread_view.read_with(cx, |view, _cx| {
8365 assert_eq!(view.editing_message, Some(0));
8366 });
8367
8368 cx.run_until_parked();
8369
8370 // Should still be editing
8371 cx.update(|window, cx| {
8372 assert!(user_message_editor.focus_handle(cx).is_focused(window));
8373 assert_eq!(thread_view.read(cx).editing_message, Some(0));
8374 assert_eq!(
8375 user_message_editor.read(cx).text(cx),
8376 "Edited message content"
8377 );
8378 });
8379 }
8380
8381 struct GeneratingThreadSetup {
8382 thread_view: Entity<AcpThreadView>,
8383 thread: Entity<AcpThread>,
8384 message_editor: Entity<MessageEditor>,
8385 }
8386
8387 async fn setup_generating_thread(
8388 cx: &mut TestAppContext,
8389 ) -> (GeneratingThreadSetup, &mut VisualTestContext) {
8390 let connection = StubAgentConnection::new();
8391
8392 let (thread_view, cx) =
8393 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
8394 add_to_workspace(thread_view.clone(), cx);
8395
8396 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8397 message_editor.update_in(cx, |editor, window, cx| {
8398 editor.set_text("Hello", window, cx);
8399 });
8400 thread_view.update_in(cx, |thread_view, window, cx| {
8401 thread_view.send(window, cx);
8402 });
8403
8404 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
8405 let thread = view.thread().unwrap();
8406 (thread.clone(), thread.read(cx).session_id().clone())
8407 });
8408
8409 cx.run_until_parked();
8410
8411 cx.update(|_, cx| {
8412 connection.send_update(
8413 session_id.clone(),
8414 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
8415 "Response chunk".into(),
8416 )),
8417 cx,
8418 );
8419 });
8420
8421 cx.run_until_parked();
8422
8423 thread.read_with(cx, |thread, _cx| {
8424 assert_eq!(thread.status(), ThreadStatus::Generating);
8425 });
8426
8427 (
8428 GeneratingThreadSetup {
8429 thread_view,
8430 thread,
8431 message_editor,
8432 },
8433 cx,
8434 )
8435 }
8436
8437 #[gpui::test]
8438 async fn test_escape_cancels_generation_from_conversation_focus(cx: &mut TestAppContext) {
8439 init_test(cx);
8440
8441 let (setup, cx) = setup_generating_thread(cx).await;
8442
8443 let focus_handle = setup
8444 .thread_view
8445 .read_with(cx, |view, _cx| view.focus_handle.clone());
8446 cx.update(|window, cx| {
8447 window.focus(&focus_handle, cx);
8448 });
8449
8450 setup.thread_view.update_in(cx, |_, window, cx| {
8451 window.dispatch_action(menu::Cancel.boxed_clone(), cx);
8452 });
8453
8454 cx.run_until_parked();
8455
8456 setup.thread.read_with(cx, |thread, _cx| {
8457 assert_eq!(thread.status(), ThreadStatus::Idle);
8458 });
8459 }
8460
8461 #[gpui::test]
8462 async fn test_escape_cancels_generation_from_editor_focus(cx: &mut TestAppContext) {
8463 init_test(cx);
8464
8465 let (setup, cx) = setup_generating_thread(cx).await;
8466
8467 let editor_focus_handle = setup
8468 .message_editor
8469 .read_with(cx, |editor, cx| editor.focus_handle(cx));
8470 cx.update(|window, cx| {
8471 window.focus(&editor_focus_handle, cx);
8472 });
8473
8474 setup.message_editor.update_in(cx, |_, window, cx| {
8475 window.dispatch_action(editor::actions::Cancel.boxed_clone(), cx);
8476 });
8477
8478 cx.run_until_parked();
8479
8480 setup.thread.read_with(cx, |thread, _cx| {
8481 assert_eq!(thread.status(), ThreadStatus::Idle);
8482 });
8483 }
8484
8485 #[gpui::test]
8486 async fn test_escape_when_idle_is_noop(cx: &mut TestAppContext) {
8487 init_test(cx);
8488
8489 let (thread_view, cx) =
8490 setup_thread_view(StubAgentServer::new(StubAgentConnection::new()), cx).await;
8491 add_to_workspace(thread_view.clone(), cx);
8492
8493 let thread = thread_view.read_with(cx, |view, _cx| view.thread().unwrap().clone());
8494
8495 thread.read_with(cx, |thread, _cx| {
8496 assert_eq!(thread.status(), ThreadStatus::Idle);
8497 });
8498
8499 let focus_handle = thread_view.read_with(cx, |view, _cx| view.focus_handle.clone());
8500 cx.update(|window, cx| {
8501 window.focus(&focus_handle, cx);
8502 });
8503
8504 thread_view.update_in(cx, |_, window, cx| {
8505 window.dispatch_action(menu::Cancel.boxed_clone(), cx);
8506 });
8507
8508 cx.run_until_parked();
8509
8510 thread.read_with(cx, |thread, _cx| {
8511 assert_eq!(thread.status(), ThreadStatus::Idle);
8512 });
8513 }
8514
8515 #[gpui::test]
8516 async fn test_interrupt(cx: &mut TestAppContext) {
8517 init_test(cx);
8518
8519 let connection = StubAgentConnection::new();
8520
8521 let (thread_view, cx) =
8522 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
8523 add_to_workspace(thread_view.clone(), cx);
8524
8525 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8526 message_editor.update_in(cx, |editor, window, cx| {
8527 editor.set_text("Message 1", window, cx);
8528 });
8529 thread_view.update_in(cx, |thread_view, window, cx| {
8530 thread_view.send(window, cx);
8531 });
8532
8533 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
8534 let thread = view.thread().unwrap();
8535
8536 (thread.clone(), thread.read(cx).session_id().clone())
8537 });
8538
8539 cx.run_until_parked();
8540
8541 cx.update(|_, cx| {
8542 connection.send_update(
8543 session_id.clone(),
8544 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
8545 "Message 1 resp".into(),
8546 )),
8547 cx,
8548 );
8549 });
8550
8551 cx.run_until_parked();
8552
8553 thread.read_with(cx, |thread, cx| {
8554 assert_eq!(
8555 thread.to_markdown(cx),
8556 indoc::indoc! {"
8557 ## User
8558
8559 Message 1
8560
8561 ## Assistant
8562
8563 Message 1 resp
8564
8565 "}
8566 )
8567 });
8568
8569 message_editor.update_in(cx, |editor, window, cx| {
8570 editor.set_text("Message 2", window, cx);
8571 });
8572 thread_view.update_in(cx, |thread_view, window, cx| {
8573 thread_view.send(window, cx);
8574 });
8575
8576 cx.update(|_, cx| {
8577 // Simulate a response sent after beginning to cancel
8578 connection.send_update(
8579 session_id.clone(),
8580 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("onse".into())),
8581 cx,
8582 );
8583 });
8584
8585 cx.run_until_parked();
8586
8587 // Last Message 1 response should appear before Message 2
8588 thread.read_with(cx, |thread, cx| {
8589 assert_eq!(
8590 thread.to_markdown(cx),
8591 indoc::indoc! {"
8592 ## User
8593
8594 Message 1
8595
8596 ## Assistant
8597
8598 Message 1 response
8599
8600 ## User
8601
8602 Message 2
8603
8604 "}
8605 )
8606 });
8607
8608 cx.update(|_, cx| {
8609 connection.send_update(
8610 session_id.clone(),
8611 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
8612 "Message 2 response".into(),
8613 )),
8614 cx,
8615 );
8616 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
8617 });
8618
8619 cx.run_until_parked();
8620
8621 thread.read_with(cx, |thread, cx| {
8622 assert_eq!(
8623 thread.to_markdown(cx),
8624 indoc::indoc! {"
8625 ## User
8626
8627 Message 1
8628
8629 ## Assistant
8630
8631 Message 1 response
8632
8633 ## User
8634
8635 Message 2
8636
8637 ## Assistant
8638
8639 Message 2 response
8640
8641 "}
8642 )
8643 });
8644 }
8645
8646 #[gpui::test]
8647 async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
8648 init_test(cx);
8649
8650 let connection = StubAgentConnection::new();
8651 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8652 acp::ContentChunk::new("Response".into()),
8653 )]);
8654
8655 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
8656 add_to_workspace(thread_view.clone(), cx);
8657
8658 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8659 message_editor.update_in(cx, |editor, window, cx| {
8660 editor.set_text("Original message to edit", window, cx)
8661 });
8662 thread_view.update_in(cx, |thread_view, window, cx| thread_view.send(window, cx));
8663 cx.run_until_parked();
8664
8665 let user_message_editor = thread_view.read_with(cx, |thread_view, cx| {
8666 thread_view
8667 .entry_view_state
8668 .read(cx)
8669 .entry(0)
8670 .expect("Should have at least one entry")
8671 .message_editor()
8672 .expect("Should have message editor")
8673 .clone()
8674 });
8675
8676 cx.focus(&user_message_editor);
8677 thread_view.read_with(cx, |thread_view, _cx| {
8678 assert_eq!(thread_view.editing_message, Some(0));
8679 });
8680
8681 // Ensure to edit the focused message before proceeding otherwise, since
8682 // its content is not different from what was sent, focus will be lost.
8683 user_message_editor.update_in(cx, |editor, window, cx| {
8684 editor.set_text("Original message to edit with ", window, cx)
8685 });
8686
8687 // Create a simple buffer with some text so we can create a selection
8688 // that will then be added to the message being edited.
8689 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
8690 (thread_view.workspace.clone(), thread_view.project.clone())
8691 });
8692 let buffer = project.update(cx, |project, cx| {
8693 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
8694 });
8695
8696 workspace
8697 .update_in(cx, |workspace, window, cx| {
8698 let editor = cx.new(|cx| {
8699 let mut editor =
8700 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
8701
8702 editor.change_selections(Default::default(), window, cx, |selections| {
8703 selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
8704 });
8705
8706 editor
8707 });
8708 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
8709 })
8710 .unwrap();
8711
8712 thread_view.update_in(cx, |thread_view, window, cx| {
8713 assert_eq!(thread_view.editing_message, Some(0));
8714 thread_view.insert_selections(window, cx);
8715 });
8716
8717 user_message_editor.read_with(cx, |editor, cx| {
8718 let text = editor.editor().read(cx).text(cx);
8719 let expected_text = String::from("Original message to edit with selection ");
8720
8721 assert_eq!(text, expected_text);
8722 });
8723 }
8724
8725 #[gpui::test]
8726 async fn test_insert_selections(cx: &mut TestAppContext) {
8727 init_test(cx);
8728
8729 let connection = StubAgentConnection::new();
8730 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
8731 acp::ContentChunk::new("Response".into()),
8732 )]);
8733
8734 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
8735 add_to_workspace(thread_view.clone(), cx);
8736
8737 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
8738 message_editor.update_in(cx, |editor, window, cx| {
8739 editor.set_text("Can you review this snippet ", window, cx)
8740 });
8741
8742 // Create a simple buffer with some text so we can create a selection
8743 // that will then be added to the message being edited.
8744 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
8745 (thread_view.workspace.clone(), thread_view.project.clone())
8746 });
8747 let buffer = project.update(cx, |project, cx| {
8748 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
8749 });
8750
8751 workspace
8752 .update_in(cx, |workspace, window, cx| {
8753 let editor = cx.new(|cx| {
8754 let mut editor =
8755 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
8756
8757 editor.change_selections(Default::default(), window, cx, |selections| {
8758 selections.select_ranges([MultiBufferOffset(8)..MultiBufferOffset(15)]);
8759 });
8760
8761 editor
8762 });
8763 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
8764 })
8765 .unwrap();
8766
8767 thread_view.update_in(cx, |thread_view, window, cx| {
8768 assert_eq!(thread_view.editing_message, None);
8769 thread_view.insert_selections(window, cx);
8770 });
8771
8772 thread_view.read_with(cx, |thread_view, cx| {
8773 let text = thread_view.message_editor.read(cx).text(cx);
8774 let expected_txt = String::from("Can you review this snippet selection ");
8775
8776 assert_eq!(text, expected_txt);
8777 })
8778 }
8779}