thread_view.rs

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