thread_view.rs

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