thread_view.rs

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