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