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