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