thread_view.rs

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