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