thread_view.rs

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