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