thread_view.rs

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