thread_view.rs

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