Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

63.2 KB
Raw Blame
use crate::{AcpThread, ElicitationStore, ReceiptSubmission};
use agent_client_protocol::{schema::MaybeUndefined, v1::schema as acp_v1, v2::schema as acp_v2};
use anyhow::Result;
use chrono::{DateTime, Utc};
use collections::{HashMap, HashSet, IndexMap};
use gpui::{Context, Entity, SharedString, Task};
use language_model::DisabledReason;
use project::{AgentId, Project};
use serde::{Deserialize, Serialize};
use std::{any::Any, error::Error, fmt, path::PathBuf, rc::Rc};
use task::{HideStrategy, SpawnInTerminal, TaskId};
use ui::{App, IconName};
use util::path_list::PathList;
use uuid::Uuid;

/// A user-message ID generated by Zed and passed to agents that support client IDs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub struct ClientUserMessageId(SharedString);

impl ClientUserMessageId {
    pub fn new() -> Self {
        Self(Uuid::new_v4().to_string().into())
    }

    pub fn message_id(&self) -> acp_v2::MessageId {
        acp_v2::MessageId::new(self.0.as_ref())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub struct AgentModelId(SharedString);

impl AgentModelId {
    pub fn new(id: impl Into<Self>) -> Self {
        id.into()
    }

    pub fn as_str(&self) -> &str {
        self.0.as_ref()
    }
}

impl AsRef<str> for AgentModelId {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl fmt::Display for AgentModelId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl From<SharedString> for AgentModelId {
    fn from(id: SharedString) -> Self {
        Self(id)
    }
}

impl From<String> for AgentModelId {
    fn from(id: String) -> Self {
        Self(SharedString::from(id))
    }
}

impl From<&str> for AgentModelId {
    fn from(id: &str) -> Self {
        Self(SharedString::from(id.to_owned()))
    }
}

pub fn build_terminal_auth_task(
    id: String,
    label: String,
    command: String,
    args: Vec<String>,
    env: HashMap<String, String>,
) -> SpawnInTerminal {
    SpawnInTerminal {
        id: TaskId(id),
        full_label: label.clone(),
        label: label.clone(),
        command: Some(command),
        args,
        command_label: label,
        env,
        use_new_terminal: true,
        allow_concurrent_runs: true,
        hide: HideStrategy::Always,
        ..Default::default()
    }
}

pub trait AgentConnection {
    fn agent_id(&self) -> AgentId;

    fn telemetry_id(&self) -> SharedString;

    fn agent_version(&self) -> Option<SharedString> {
        None
    }

    /// Initiate shutdown of connection-owned resources when their shared UI owner ends.
    /// This is independent of session close and may leave retained models alive.
    /// It does not wait for process exit or a complete protocol drain.
    fn shutdown(&self) {}

    fn new_session(
        self: Rc<Self>,
        project: Entity<Project>,
        _work_dirs: PathList,
        cx: &mut App,
    ) -> Task<Result<Entity<AcpThread>>>;

    /// Whether this agent supports loading existing sessions.
    fn supports_load_session(&self) -> bool {
        false
    }

    /// Load an existing session by ID.
    fn load_session(
        self: Rc<Self>,
        _session_id: acp_v2::SessionId,
        _project: Entity<Project>,
        _work_dirs: PathList,
        _title: Option<SharedString>,
        _cx: &mut App,
    ) -> Task<Result<Entity<AcpThread>>> {
        Task::ready(Err(anyhow::Error::msg("Loading sessions is not supported")))
    }

    /// Whether this agent supports explicitly closing existing sessions.
    fn supports_close_session(&self) -> bool {
        false
    }

    /// Whether subagents follow the ACP subagents RFD on this connection: they are discovered
    /// only through their parent's announcements, and must never be loaded or resumed.
    fn announces_subagents(&self) -> bool {
        false
    }

    /// Whether cancelling a session's work answers its pending permission requests with
    /// `cancelled` locally instead of waiting for the agent to cancel them.
    fn answers_permission_requests_on_cancel(&self) -> bool {
        true
    }

    /// Whether conversation teardown should invoke `close_session`.
    /// The default preserves existing UI cleanup; backend-owned release hooks are separate.
    /// Autonomous backends can opt out without disabling explicit close support.
    fn should_close_sessions_on_release(&self) -> bool {
        self.supports_close_session()
    }

    /// Close an existing session and free its resources. This may cancel remote work;
    /// automatic cleanup must also respect `should_close_sessions_on_release`.
    fn close_session(
        self: Rc<Self>,
        _session_id: &acp_v2::SessionId,
        _cx: &mut App,
    ) -> Task<Result<()>> {
        Task::ready(Err(anyhow::Error::msg("Closing sessions is not supported")))
    }

    /// Whether this agent supports resuming existing sessions without loading history.
    fn supports_resume_session(&self) -> bool {
        false
    }

    /// Resume an existing session by ID without replaying previous messages.
    fn resume_session(
        self: Rc<Self>,
        _session_id: acp_v2::SessionId,
        _project: Entity<Project>,
        _work_dirs: PathList,
        _title: Option<SharedString>,
        _cx: &mut App,
    ) -> Task<Result<Entity<AcpThread>>> {
        Task::ready(Err(anyhow::Error::msg(
            "Resuming sessions is not supported",
        )))
    }

    /// Whether this agent supports showing session history.
    fn supports_session_history(&self) -> bool {
        self.supports_load_session() || self.supports_resume_session()
    }

    /// Whether this agent supports additional session directories.
    fn supports_session_additional_directories(&self) -> bool {
        false
    }

    fn auth_methods(&self) -> &[acp_v2::AuthMethod];

    fn terminal_auth_task(
        &self,
        _method: &acp_v2::AuthMethodId,
        _cx: &App,
    ) -> Option<Task<Result<SpawnInTerminal>>> {
        None
    }

    fn authenticate(&self, method: acp_v2::AuthMethodId, cx: &mut App) -> Task<Result<()>>;

    fn supports_logout(&self) -> bool {
        false
    }

    fn logout(&self, _cx: &mut App) -> Task<Result<()>> {
        Task::ready(Err(anyhow::Error::msg("Logout is not supported")))
    }

    /// Returns a capability for agents that accept client-generated user message IDs.
    fn client_user_message_ids(
        &self,
        _cx: &App,
    ) -> Option<Rc<dyn AgentSessionClientUserMessageIds>> {
        None
    }

    /// Selected during thread construction, before backend registration may be complete.
    /// Validate the submitting owner when publishing, not when selecting this capability.
    fn receipt_submissions(
        &self,
        _session_id: &acp_v2::SessionId,
        _cx: &App,
    ) -> Option<Rc<dyn ReceiptSessionSubmissions>> {
        None
    }

    /// Preflight without starting transport work so rejection cannot interrupt an
    /// existing turn. Adapters must also validate when called directly.
    fn validate_prompt_content(&self, _content: &[acp_v2::ContentBlock]) -> Result<()> {
        Ok(())
    }

    /// Receipt transports acknowledge acceptance through `receipt_submissions`
    /// instead of implementing this completion-based path.
    fn prompt(
        &self,
        _params: acp_v2::PromptRequest,
        _cx: &mut App,
    ) -> Task<Result<acp_v1::PromptResponse>> {
        Task::ready(Err(anyhow::anyhow!(
            "This agent does not support completion-based prompts"
        )))
    }

    fn retry(
        &self,
        _session_id: &acp_v2::SessionId,
        _cx: &App,
    ) -> Option<Rc<dyn AgentSessionRetry>> {
        None
    }

    /// Requests cancellation; success does not establish that execution stopped.
    fn cancel(&self, session_id: &acp_v2::SessionId, cx: &mut App) -> Result<()>;

    /// Asks the agent to stop one tool call. Success means the agent accepted the request;
    /// the tool call's own updates report when it stops.
    fn cancel_tool_call(
        &self,
        _session_id: &acp_v2::SessionId,
        _tool_call_id: &acp_v2::ToolCallId,
        _cx: &mut App,
    ) -> Task<Result<()>> {
        Task::ready(Err(anyhow::anyhow!(
            "Cancelling tool calls is not supported"
        )))
    }

    /// Asks the agent to stop one terminal's process. Success means the agent accepted the
    /// request; the terminal's exit status reports when it stops.
    fn cancel_terminal(
        &self,
        _session_id: &acp_v2::SessionId,
        _terminal_id: &acp_v2::TerminalId,
        _cx: &mut App,
    ) -> Task<Result<()>> {
        Task::ready(Err(anyhow::anyhow!(
            "Cancelling terminals is not supported"
        )))
    }

    /// Request-scoped elicitations are connection-level because they can arrive before a session
    /// thread exists. Session-scoped elicitations stay in the thread timeline, but use
    /// `ElicitationStore` for shared processing.
    fn request_elicitations(&self) -> Option<Entity<ElicitationStore>> {
        None
    }

    fn truncate(
        &self,
        _session_id: &acp_v2::SessionId,
        _cx: &App,
    ) -> Option<Rc<dyn AgentSessionTruncate>> {
        None
    }

    fn set_title(
        &self,
        _session_id: &acp_v2::SessionId,
        _cx: &App,
    ) -> Option<Rc<dyn AgentSessionSetTitle>> {
        None
    }

    /// Returns this agent as an [Rc<dyn ModelSelector>] if the model selection capability is supported.
    ///
    /// If the agent does not support model selection, returns [None].
    /// This allows sharing the selector in UI components.
    fn model_selector(
        &self,
        _session_id: &acp_v2::SessionId,
    ) -> Option<Rc<dyn AgentModelSelector>> {
        None
    }

    fn telemetry(&self) -> Option<Rc<dyn AgentTelemetry>> {
        None
    }

    fn session_modes(
        &self,
        _session_id: &acp_v2::SessionId,
        _cx: &App,
    ) -> Option<Rc<dyn AgentSessionModes>> {
        None
    }

    fn session_config_options(
        &self,
        _session_id: &acp_v2::SessionId,
        _cx: &App,
    ) -> Option<Rc<dyn AgentSessionConfigOptions>> {
        None
    }

    fn session_list(&self, _cx: &mut App) -> Option<Rc<dyn AgentSessionList>> {
        None
    }

    fn into_any(self: Rc<Self>) -> Rc<dyn Any>;
}

impl dyn AgentConnection {
    pub fn downcast<T: 'static + AgentConnection + Sized>(self: Rc<Self>) -> Option<Rc<T>> {
        self.into_any().downcast().ok()
    }
}

pub trait AgentSessionTruncate {
    fn run(&self, client_user_message_id: ClientUserMessageId, cx: &mut App) -> Task<Result<()>>;
}

pub trait AgentSessionClientUserMessageIds {
    fn new_id(&self) -> ClientUserMessageId {
        ClientUserMessageId::new()
    }

    fn prompt(
        &self,
        client_user_message_id: ClientUserMessageId,
        params: acp_v2::PromptRequest,
        cx: &mut App,
    ) -> Task<Result<acp_v1::PromptResponse>>;
}

/// A session-bound prompt transport whose response acknowledges acceptance, not completion.
/// Implementations must report foreground state separately through `AcpThread::update_session_state`.
pub trait ReceiptSessionSubmissions {
    /// Transport loss must carry [`crate::SubmissionDisconnected`] (which may be
    /// added as error context) rather than claiming that the agent rejected insertion.
    /// The owner context binds publication even when capability selection preceded registration.
    fn submit(
        &self,
        content: Vec<acp_v2::ContentBlock>,
        cx: &mut Context<AcpThread>,
    ) -> ReceiptSubmission;

    fn supports_retry(&self) -> bool {
        false
    }

    fn retry(&self, _cx: &mut Context<AcpThread>) -> ReceiptSubmission {
        Task::ready(Err(anyhow::anyhow!(
            "Receipt-driven retry is not supported"
        )))
        .into()
    }
}

pub trait AgentSessionRetry {
    fn run(&self, cx: &mut App) -> Task<Result<acp_v1::PromptResponse>>;
}

pub trait AgentSessionSetTitle {
    fn run(&self, title: SharedString, cx: &mut App) -> Task<Result<()>>;
}

pub trait AgentTelemetry {
    /// A representation of the current thread state that can be serialized for
    /// storage with telemetry events.
    fn thread_data(
        &self,
        session_id: &acp_v2::SessionId,
        cx: &mut App,
    ) -> Task<Result<serde_json::Value>>;
}

pub trait AgentSessionModes {
    fn current_mode(&self) -> acp_v2::SessionConfigValueId;

    fn all_modes(&self) -> Vec<acp_v2::SessionConfigSelectOption>;

    fn set_mode(&self, mode: acp_v2::SessionConfigValueId, cx: &mut App) -> Task<Result<()>>;
}

pub trait AgentSessionConfigOptions {
    /// Get all current config options with their state
    fn config_options(&self) -> Vec<acp_v2::SessionConfigOption>;

    /// Agent-owned sessions may report configuration without allowing the client to change it.
    fn is_read_only(&self) -> bool {
        false
    }

    /// Set a config option value
    /// Returns the full updated list of config options
    fn set_config_option(
        &self,
        config_id: acp_v2::SessionConfigId,
        value: acp_v2::SessionConfigOptionValue,
        cx: &mut App,
    ) -> Task<Result<Vec<acp_v2::SessionConfigOption>>>;

    /// Whenever the config options are updated the receiver will be notified.
    /// Optional for agents that don't update their config options dynamically.
    fn watch(&self, _cx: &mut App) -> Option<watch::Receiver<()>> {
        None
    }
}

#[derive(Debug, Clone, Default)]
pub struct AgentSessionListRequest {
    pub cwd: Option<PathBuf>,
    pub cursor: Option<String>,
    pub meta: Option<acp_v2::Meta>,
}

#[derive(Debug, Clone)]
pub struct AgentSessionListResponse {
    pub sessions: Vec<AgentSessionInfo>,
    pub next_cursor: Option<String>,
    pub meta: Option<acp_v2::Meta>,
}

impl AgentSessionListResponse {
    pub fn new(sessions: Vec<AgentSessionInfo>) -> Self {
        Self {
            sessions,
            next_cursor: None,
            meta: None,
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct AgentSessionInfo {
    pub session_id: acp_v2::SessionId,
    pub work_dirs: Option<PathList>,
    pub title: Option<SharedString>,
    pub updated_at: Option<DateTime<Utc>>,
    pub created_at: Option<DateTime<Utc>>,
    pub meta: Option<acp_v2::Meta>,
}

impl AgentSessionInfo {
    pub fn new(session_id: impl Into<acp_v2::SessionId>) -> Self {
        Self {
            session_id: session_id.into(),
            work_dirs: None,
            title: None,
            updated_at: None,
            created_at: None,
            meta: None,
        }
    }

    pub fn apply_update(&mut self, update: impl Into<AgentSessionInfoUpdate>) -> bool {
        let (title, updated_at, metadata) = match update.into() {
            AgentSessionInfoUpdate::V1(update) => (
                update.title,
                update.updated_at,
                crate::MetadataUpdate::V1(
                    update.meta.map(MaybeUndefined::Value).unwrap_or_default(),
                ),
            ),
            AgentSessionInfoUpdate::V2(update) => (
                update.title,
                update.updated_at,
                crate::MetadataUpdate::V2(update.meta),
            ),
        };
        let mut changed = false;
        if !title.is_undefined() {
            let title = title.take().map(SharedString::from);
            changed |= self.title != title;
            self.title = title;
        }

        let updated_at = match updated_at {
            MaybeUndefined::Undefined => None,
            MaybeUndefined::Null => Some(None),
            MaybeUndefined::Value(updated_at) => match DateTime::parse_from_rfc3339(&updated_at) {
                Ok(updated_at) => Some(Some(updated_at.with_timezone(&Utc))),
                Err(_) => {
                    log::warn!("Ignoring invalid session information timestamp");
                    None
                }
            },
        };
        if let Some(updated_at) = updated_at {
            changed |= self.updated_at != updated_at;
            self.updated_at = updated_at;
        }

        changed |= metadata.apply(&mut self.meta);
        changed
    }
}

/// Retains wire provenance because v1 metadata replaces while v2 metadata patches.
#[derive(Debug, Clone, PartialEq)]
pub enum AgentSessionInfoUpdate {
    V1(acp_v1::SessionInfoUpdate),
    V2(acp_v2::SessionInfoUpdate),
}

impl AgentSessionInfoUpdate {
    pub(crate) fn has_title(&self) -> bool {
        match self {
            Self::V1(update) => !update.title.is_undefined(),
            Self::V2(update) => !update.title.is_undefined(),
        }
    }
}

impl From<acp_v1::SessionInfoUpdate> for AgentSessionInfoUpdate {
    fn from(update: acp_v1::SessionInfoUpdate) -> Self {
        Self::V1(update)
    }
}

impl From<acp_v2::SessionInfoUpdate> for AgentSessionInfoUpdate {
    fn from(update: acp_v2::SessionInfoUpdate) -> Self {
        Self::V2(update)
    }
}

#[derive(Debug, Clone)]
pub enum SessionListUpdate {
    Refresh,
    SessionInfo {
        session_id: acp_v2::SessionId,
        update: AgentSessionInfoUpdate,
    },
}

pub trait AgentSessionList {
    fn list_sessions(
        &self,
        request: AgentSessionListRequest,
        cx: &mut App,
    ) -> Task<Result<AgentSessionListResponse>>;

    fn supports_delete(&self) -> bool {
        false
    }

    fn delete_session(&self, _session_id: &acp_v2::SessionId, _cx: &mut App) -> Task<Result<()>> {
        Task::ready(Err(anyhow::anyhow!("delete_session not supported")))
    }

    fn delete_sessions(&self, _cx: &mut App) -> Task<Result<()>> {
        Task::ready(Err(anyhow::anyhow!("delete_sessions not supported")))
    }

    fn watch(&self, _cx: &mut App) -> Option<async_channel::Receiver<SessionListUpdate>> {
        None
    }

    fn notify_refresh(&self) {}

    fn into_any(self: Rc<Self>) -> Rc<dyn Any>;
}

impl dyn AgentSessionList {
    pub fn downcast<T: 'static + AgentSessionList + Sized>(self: Rc<Self>) -> Option<Rc<T>> {
        self.into_any().downcast().ok()
    }
}

/// Read protocol fields without replacing the concrete SDK error or its context chain.
#[derive(Clone, Copy)]
pub struct ProtocolErrorInfo<'a> {
    pub code: i32,
    pub message: &'a str,
    pub data: Option<&'a serde_json::Value>,
}

impl<'a> ProtocolErrorInfo<'a> {
    pub fn from_error(error: &'a anyhow::Error) -> Option<Self> {
        if let Some(error) = error.downcast_ref::<agent_client_protocol::Error>() {
            return Some(Self {
                code: error.code.into(),
                message: &error.message,
                data: error.data.as_ref(),
            });
        }
        if let Some(error) = error.downcast_ref::<acp_v1::Error>() {
            return Some(Self {
                code: error.code.into(),
                message: &error.message,
                data: error.data.as_ref(),
            });
        }
        error.downcast_ref::<acp_v2::Error>().map(|error| Self {
            code: error.code.into(),
            message: &error.message,
            data: error.data.as_ref(),
        })
    }

    pub fn is_auth_required(&self) -> bool {
        self.code == i32::from(acp_v2::ErrorCode::AuthRequired)
    }
}

#[derive(Debug)]
pub struct AuthRequired {
    pub description: Option<String>,
}

impl AuthRequired {
    pub fn new() -> Self {
        Self { description: None }
    }

    pub fn with_description(mut self, description: String) -> Self {
        self.description = Some(description);
        self
    }

    pub fn from_error(error: &anyhow::Error) -> Option<Self> {
        if let Some(error) = error.downcast_ref::<Self>() {
            return Some(Self {
                description: error.description.clone(),
            });
        }
        let error = ProtocolErrorInfo::from_error(error)?;
        error.is_auth_required().then(|| Self {
            description: (error.message != acp_v2::ErrorCode::AuthRequired.to_string())
                .then(|| error.message.to_owned()),
        })
    }
}

impl Error for AuthRequired {}
impl fmt::Display for AuthRequired {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Authentication required")
    }
}

/// Trait for agents that support listing, selecting, and querying language models.
///
/// This is an optional capability; agents indicate support via [AgentConnection::model_selector].
pub trait AgentModelSelector: 'static {
    /// Lists all available language models for this agent.
    ///
    /// # Parameters
    /// - `cx`: The GPUI app context for async operations and global access.
    ///
    /// # Returns
    /// A task resolving to the list of models or an error (e.g., if no models are configured).
    fn list_models(&self, cx: &mut App) -> Task<Result<AgentModelList>>;

    /// Selects a model for a specific session (thread).
    ///
    /// # Parameters
    /// - `model_id`: The model to select (should be one from [list_models]).
    /// - `cx`: The GPUI app context.
    ///
    /// # Returns
    /// A task resolving to `Ok(())` on success or an error.
    fn select_model(&self, model_id: AgentModelId, cx: &mut App) -> Task<Result<()>>;

    /// Retrieves the currently selected model for a specific session (thread).
    ///
    /// # Parameters
    /// - `cx`: The GPUI app context.
    ///
    /// # Returns
    /// A task resolving to the selected model (always set) or an error (e.g., session not found).
    fn selected_model(&self, cx: &mut App) -> Task<Result<AgentModelInfo>>;

    fn favorite_model_ids(&self, _cx: &mut App) -> HashSet<AgentModelId> {
        HashSet::default()
    }

    fn toggle_favorite_model(&self, _model_id: AgentModelId, _should_be_favorite: bool, _cx: &App) {
    }

    /// Whenever the model list is updated the receiver will be notified.
    /// Optional for agents that don't update their model list.
    fn watch(&self, _cx: &mut App) -> Option<watch::Receiver<()>> {
        None
    }

    /// Returns whether the model picker should render a footer.
    fn should_render_footer(&self) -> bool {
        false
    }
}

/// Icon for a model in the model selector.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AgentModelIcon {
    /// A built-in icon from Zed's icon set.
    Named(IconName),
    /// Path to a custom SVG icon file.
    Path(SharedString),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentModelInfo {
    pub id: AgentModelId,
    pub name: SharedString,
    pub description: Option<SharedString>,
    pub icon: Option<AgentModelIcon>,
    pub is_latest: bool,
    pub cost: Option<SharedString>,
    pub disabled: Option<DisabledReason>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AgentModelGroupName(pub SharedString);

#[derive(Debug, Clone)]
pub enum AgentModelList {
    Flat(Vec<AgentModelInfo>),
    Grouped(IndexMap<AgentModelGroupName, Vec<AgentModelInfo>>),
}

impl AgentModelList {
    pub fn is_empty(&self) -> bool {
        match self {
            AgentModelList::Flat(models) => models.is_empty(),
            AgentModelList::Grouped(groups) => groups.is_empty(),
        }
    }

    pub fn is_flat(&self) -> bool {
        matches!(self, AgentModelList::Flat(_))
    }
}

#[derive(Debug, Clone)]
pub struct PermissionOptionChoice {
    pub allow: acp_v2::PermissionOption,
    pub deny: acp_v2::PermissionOption,
    pub sub_patterns: Vec<String>,
}

impl PermissionOptionChoice {
    pub fn label(&self) -> SharedString {
        self.allow.name.clone().into()
    }

    /// Build a `SelectedPermissionOutcome` for this choice.
    ///
    /// If the choice carries `sub_patterns`, they are attached as
    /// `SelectedPermissionParams::Terminal`.
    pub fn build_outcome(&self, is_allow: bool) -> crate::SelectedPermissionOutcome {
        let option = if is_allow { &self.allow } else { &self.deny };

        let params = if !self.sub_patterns.is_empty() {
            Some(crate::SelectedPermissionParams::Terminal {
                patterns: self.sub_patterns.clone(),
            })
        } else {
            None
        };

        crate::SelectedPermissionOutcome::new(option.option_id.clone(), option.kind.clone())
            .params(params)
    }
}

/// Pairs a tool's permission pattern with its display name
///
/// For example, a pattern of `^cargo\\s+build(\\s|$)` would display as `cargo
/// build`. It's handy to keep these together rather than trying to derive
/// one from the other.
#[derive(Debug, Clone, PartialEq)]
pub struct PermissionPattern {
    pub pattern: String,
    pub display_name: String,
}

#[derive(Debug, Clone)]
pub enum PermissionOptions {
    Flat(Vec<acp_v2::PermissionOption>),
    Dropdown(Vec<PermissionOptionChoice>),
    DropdownWithPatterns {
        choices: Vec<PermissionOptionChoice>,
        patterns: Vec<PermissionPattern>,
        tool_name: String,
    },
}

impl PermissionOptions {
    pub fn is_empty(&self) -> bool {
        match self {
            PermissionOptions::Flat(options) => options.is_empty(),
            PermissionOptions::Dropdown(options) => options.is_empty(),
            PermissionOptions::DropdownWithPatterns { choices, .. } => choices.is_empty(),
        }
    }

    pub fn option_for_id(
        &self,
        id: &acp_v2::PermissionOptionId,
    ) -> Option<&acp_v2::PermissionOption> {
        match self {
            Self::Flat(options) => options.iter().find(|option| &option.option_id == id),
            Self::Dropdown(choices) | Self::DropdownWithPatterns { choices, .. } => {
                choices.iter().find_map(|choice| {
                    if &choice.allow.option_id == id {
                        Some(&choice.allow)
                    } else if &choice.deny.option_id == id {
                        Some(&choice.deny)
                    } else {
                        None
                    }
                })
            }
        }
    }

    pub fn first_option_of_kind(
        &self,
        kind: acp_v2::PermissionOptionKind,
    ) -> Option<&acp_v2::PermissionOption> {
        match self {
            PermissionOptions::Flat(options) => options.iter().find(|option| option.kind == kind),
            PermissionOptions::Dropdown(options) => options.iter().find_map(|choice| {
                if choice.allow.kind == kind {
                    Some(&choice.allow)
                } else if choice.deny.kind == kind {
                    Some(&choice.deny)
                } else {
                    None
                }
            }),
            PermissionOptions::DropdownWithPatterns { choices, .. } => {
                choices.iter().find_map(|choice| {
                    if choice.allow.kind == kind {
                        Some(&choice.allow)
                    } else if choice.deny.kind == kind {
                        Some(&choice.deny)
                    } else {
                        None
                    }
                })
            }
        }
    }

    pub fn allow_once_option_id(&self) -> Option<acp_v2::PermissionOptionId> {
        self.first_option_of_kind(acp_v2::PermissionOptionKind::AllowOnce)
            .map(|option| option.option_id.clone())
    }

    pub fn deny_once_option_id(&self) -> Option<acp_v2::PermissionOptionId> {
        self.first_option_of_kind(acp_v2::PermissionOptionKind::RejectOnce)
            .map(|option| option.option_id.clone())
    }

    /// Build a `SelectedPermissionOutcome` for the `DropdownWithPatterns`
    /// variant when the user has checked specific pattern indices.
    ///
    /// Returns `Some` with the always-allow/deny outcome when at least one
    /// pattern is checked. Returns `None` when zero patterns are checked,
    /// signaling that the caller should degrade to allow-once / deny-once.
    ///
    /// Panics (debug) or returns `None` (release) if called on a non-
    /// `DropdownWithPatterns` variant.
    pub fn build_outcome_for_checked_patterns(
        &self,
        checked_indices: &[usize],
        is_allow: bool,
    ) -> Option<crate::SelectedPermissionOutcome> {
        let PermissionOptions::DropdownWithPatterns {
            choices, patterns, ..
        } = self
        else {
            debug_assert!(
                false,
                "build_outcome_for_checked_patterns called on non-DropdownWithPatterns"
            );
            return None;
        };

        let checked_patterns: Vec<String> = patterns
            .iter()
            .enumerate()
            .filter(|(index, _)| checked_indices.contains(index))
            .map(|(_, cp)| cp.pattern.clone())
            .collect();

        if checked_patterns.is_empty() {
            return None;
        }

        // Use the first choice (the "Always" choice) as the base for the outcome.
        let always_choice = choices.first()?;
        let option = if is_allow {
            &always_choice.allow
        } else {
            &always_choice.deny
        };

        let outcome =
            crate::SelectedPermissionOutcome::new(option.option_id.clone(), option.kind.clone())
                .params(Some(crate::SelectedPermissionParams::Terminal {
                    patterns: checked_patterns,
                }));
        Some(outcome)
    }
}

#[cfg(any(test, feature = "test-support"))]
mod test_support {
    //! Test-only stubs and helpers for acp_thread.
    //!
    //! This module is available to unit tests and the `test-support` feature,
    //! but not production builds. It provides:
    //! - `StubAgentConnection` for mocking agent connections in tests
    //! - `create_test_png_base64` for generating test images

    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use action_log::ActionLog;
    use collections::{HashMap, VecDeque};
    use futures::{channel::oneshot, future::try_join_all};
    use gpui::{AppContext as _, Entity, WeakEntity};
    use parking_lot::Mutex;

    use crate::AuthorizationKind;

    use super::*;

    /// Creates a PNG image encoded as base64 for testing.
    ///
    /// Generates a solid-color PNG of the specified dimensions and returns
    /// it as a base64-encoded string suitable for use in `ImageContent`.
    pub fn create_test_png_base64(width: u32, height: u32, color: [u8; 4]) -> String {
        use image::ImageEncoder as _;

        let mut png_data = Vec::new();
        {
            let encoder = image::codecs::png::PngEncoder::new(&mut png_data);
            let mut pixels = Vec::with_capacity((width * height * 4) as usize);
            for _ in 0..(width * height) {
                pixels.extend_from_slice(&color);
            }
            encoder
                .write_image(&pixels, width, height, image::ExtendedColorType::Rgba8)
                .expect("Failed to encode PNG");
        }

        use image::EncodableLayout as _;
        base64::Engine::encode(
            &base64::engine::general_purpose::STANDARD,
            png_data.as_bytes(),
        )
    }

    /// Test-scoped counter for generating unique session IDs across all
    /// `StubAgentConnection` instances within a test case. Set as a GPUI
    /// global in test init so each case starts fresh.
    pub struct StubSessionCounter(pub AtomicUsize);
    impl gpui::Global for StubSessionCounter {}

    impl StubSessionCounter {
        pub fn next(cx: &App) -> usize {
            cx.try_global::<Self>()
                .map(|g| g.0.fetch_add(1, Ordering::SeqCst))
                .unwrap_or_else(|| {
                    static FALLBACK: AtomicUsize = AtomicUsize::new(0);
                    FALLBACK.fetch_add(1, Ordering::SeqCst)
                })
        }
    }

    #[derive(Clone)]
    pub struct StubAgentConnection {
        sessions: Arc<Mutex<HashMap<acp_v2::SessionId, Session>>>,
        permission_requests: HashMap<acp_v2::ToolCallId, PermissionOptions>,
        next_prompt_updates: Arc<Mutex<Vec<StubPromptUpdate>>>,
        next_prompt_response: Arc<Mutex<Option<oneshot::Receiver<Result<acp_v1::PromptResponse>>>>>,
        auth_methods: Vec<acp_v2::AuthMethod>,
        next_authenticate_response: Arc<Mutex<Option<oneshot::Receiver<Result<()>>>>>,
        next_load_error: Arc<Mutex<Option<anyhow::Error>>>,
        next_receipt_response:
            Arc<Mutex<Option<oneshot::Receiver<Result<acp_v2::PromptResponse>>>>>,
        receipt_prompt: Arc<Mutex<Option<Vec<acp_v2::ContentBlock>>>>,
        next_truncate: Arc<Mutex<Option<oneshot::Receiver<()>>>>,
        close_session_calls: Arc<Mutex<Vec<acp_v2::SessionId>>>,
        next_close_responses: Arc<Mutex<VecDeque<oneshot::Receiver<Result<()>>>>>,
        set_title_calls: Arc<Mutex<Vec<(acp_v2::SessionId, SharedString)>>>,
        cancel_calls: Arc<Mutex<Vec<acp_v2::SessionId>>>,
        shutdown_calls: Arc<AtomicUsize>,
        next_cancel_error: Arc<Mutex<Option<anyhow::Error>>>,
        supports_receipt_submissions: bool,
        supports_retry: bool,
        supports_load_session: bool,
        supports_close_session: bool,
        announces_subagents: bool,
        close_sessions_on_release: bool,
        supports_session_additional_directories: bool,
        supports_set_title: bool,
        supports_truncate: bool,
        agent_id: AgentId,
        telemetry_id: SharedString,
        prompt_capabilities_rx: watch::Receiver<acp_v2::PromptCapabilities>,
    }

    enum StubPromptUpdate {
        Legacy(Box<acp_v1::SessionUpdate>),
        Application(
            Box<dyn FnOnce(&mut AcpThread, &mut gpui::Context<AcpThread>) -> Result<()> + Send>,
        ),
    }

    struct Session {
        thread: WeakEntity<AcpThread>,
        response_tx: Option<oneshot::Sender<acp_v1::StopReason>>,
    }

    impl Default for StubAgentConnection {
        fn default() -> Self {
            Self::new()
        }
    }

    impl StubAgentConnection {
        pub fn new() -> Self {
            Self {
                next_prompt_updates: Default::default(),
                next_prompt_response: Default::default(),
                auth_methods: Vec::new(),
                next_authenticate_response: Default::default(),
                next_load_error: Default::default(),
                next_receipt_response: Default::default(),
                receipt_prompt: Default::default(),
                next_truncate: Default::default(),
                close_session_calls: Default::default(),
                next_close_responses: Default::default(),
                set_title_calls: Default::default(),
                cancel_calls: Default::default(),
                shutdown_calls: Default::default(),
                next_cancel_error: Default::default(),
                permission_requests: HashMap::default(),
                sessions: Arc::default(),
                supports_receipt_submissions: false,
                supports_retry: false,
                supports_load_session: false,
                supports_close_session: false,
                announces_subagents: false,
                close_sessions_on_release: true,
                supports_session_additional_directories: false,
                supports_set_title: true,
                supports_truncate: true,
                agent_id: AgentId::new("stub"),
                telemetry_id: "stub".into(),
                prompt_capabilities_rx: watch::Receiver::constant(
                    acp_v2::PromptCapabilities::new()
                        .image(acp_v2::PromptImageCapabilities::new())
                        .audio(acp_v2::PromptAudioCapabilities::new())
                        .embedded_context(acp_v2::PromptEmbeddedContextCapabilities::new()),
                ),
            }
        }

        pub fn set_next_load_error(&self, error: anyhow::Error) {
            *self.next_load_error.lock() = Some(error);
        }

        pub fn shutdown_calls(&self) -> usize {
            self.shutdown_calls.load(Ordering::SeqCst)
        }

        pub fn set_next_prompt_updates(&self, updates: Vec<acp_v1::SessionUpdate>) {
            *self.next_prompt_updates.lock() = updates
                .into_iter()
                .map(|update| StubPromptUpdate::Legacy(Box::new(update)))
                .collect();
        }

        pub fn set_next_prompt_action(
            &self,
            update: impl FnOnce(&mut AcpThread, &mut gpui::Context<AcpThread>) -> Result<()>
            + Send
            + 'static,
        ) {
            *self.next_prompt_updates.lock() =
                vec![StubPromptUpdate::Application(Box::new(update))];
        }

        pub fn defer_next_prompt_response(
            &self,
        ) -> oneshot::Sender<Result<acp_v1::PromptResponse>> {
            let (sender, receiver) = oneshot::channel();
            assert!(self.next_prompt_response.lock().replace(receiver).is_none());
            sender
        }

        pub fn with_auth_methods(mut self, methods: Vec<acp_v2::AuthMethod>) -> Self {
            self.auth_methods = methods;
            self
        }

        pub fn defer_next_authenticate_response(&self) -> oneshot::Sender<Result<()>> {
            let (sender, receiver) = oneshot::channel();
            assert!(
                self.next_authenticate_response
                    .lock()
                    .replace(receiver)
                    .is_none()
            );
            sender
        }

        pub fn defer_next_receipt_response(
            &self,
        ) -> oneshot::Sender<Result<acp_v2::PromptResponse>> {
            let (sender, receiver) = oneshot::channel();
            assert!(
                self.next_receipt_response
                    .lock()
                    .replace(receiver)
                    .is_none()
            );
            sender
        }

        pub fn take_receipt_prompt(&self) -> Option<Vec<acp_v2::ContentBlock>> {
            self.receipt_prompt.lock().take()
        }

        pub fn take_set_title_calls(&self) -> Vec<(acp_v2::SessionId, SharedString)> {
            std::mem::take(&mut *self.set_title_calls.lock())
        }

        pub fn take_close_session_calls(&self) -> Vec<acp_v2::SessionId> {
            std::mem::take(&mut *self.close_session_calls.lock())
        }

        pub fn defer_next_close_response(&self) -> oneshot::Sender<Result<()>> {
            let (sender, receiver) = oneshot::channel();
            self.next_close_responses.lock().push_back(receiver);
            sender
        }

        /// Makes a session this connection did not create, such as an ACP subagent, known to
        /// it, as a real connection knows the subagents it announced.
        pub fn track_session(&self, thread: &Entity<AcpThread>, cx: &App) {
            self.sessions.lock().insert(
                thread.read(cx).session_id().clone(),
                Session {
                    thread: thread.downgrade(),
                    response_tx: None,
                },
            );
        }

        pub fn take_cancel_calls(&self) -> Vec<acp_v2::SessionId> {
            std::mem::take(&mut *self.cancel_calls.lock())
        }

        pub fn set_next_cancel_error(&self, error: anyhow::Error) {
            assert!(self.next_cancel_error.lock().replace(error).is_none());
        }

        pub fn defer_next_truncate(&self) -> oneshot::Sender<()> {
            let (sender, receiver) = oneshot::channel();
            assert!(self.next_truncate.lock().replace(receiver).is_none());
            sender
        }

        pub fn with_permission_requests(
            mut self,
            permission_requests: HashMap<acp_v2::ToolCallId, PermissionOptions>,
        ) -> Self {
            self.permission_requests = permission_requests;
            self
        }

        pub fn with_supports_load_session(mut self, supports_load_session: bool) -> Self {
            self.supports_load_session = supports_load_session;
            self
        }

        pub fn with_supports_close_session(mut self, supports_close_session: bool) -> Self {
            self.supports_close_session = supports_close_session;
            self
        }

        pub fn with_announced_subagents(mut self, announces_subagents: bool) -> Self {
            self.announces_subagents = announces_subagents;
            self
        }

        pub fn with_close_sessions_on_release(mut self, close_sessions_on_release: bool) -> Self {
            self.close_sessions_on_release = close_sessions_on_release;
            self
        }

        pub fn with_receipt_submissions(mut self, enabled: bool) -> Self {
            self.supports_receipt_submissions = enabled;
            self
        }

        pub fn with_retry(mut self) -> Self {
            self.supports_retry = true;
            self
        }

        pub fn with_prompt_capabilities(
            mut self,
            prompt_capabilities_rx: watch::Receiver<acp_v2::PromptCapabilities>,
        ) -> Self {
            self.prompt_capabilities_rx = prompt_capabilities_rx;
            self
        }

        pub fn with_supports_session_additional_directories(
            mut self,
            supports_session_additional_directories: bool,
        ) -> Self {
            self.supports_session_additional_directories = supports_session_additional_directories;
            self
        }

        pub fn with_supports_set_title(mut self, supports_set_title: bool) -> Self {
            self.supports_set_title = supports_set_title;
            self
        }

        pub fn with_supports_truncate(mut self, supports_truncate: bool) -> Self {
            self.supports_truncate = supports_truncate;
            self
        }

        pub fn with_agent_id(mut self, agent_id: AgentId) -> Self {
            self.agent_id = agent_id;
            self
        }

        pub fn with_telemetry_id(mut self, telemetry_id: SharedString) -> Self {
            self.telemetry_id = telemetry_id;
            self
        }

        fn create_session(
            self: Rc<Self>,
            session_id: acp_v2::SessionId,
            project: Entity<Project>,
            work_dirs: PathList,
            title: Option<SharedString>,
            cx: &mut gpui::App,
        ) -> Entity<AcpThread> {
            let action_log = cx.new(|_| ActionLog::new(project.clone()));
            let thread = cx.new(|cx| {
                AcpThread::new(
                    None,
                    title,
                    Some(work_dirs),
                    self.clone(),
                    project,
                    action_log,
                    session_id.clone(),
                    self.prompt_capabilities_rx.clone(),
                    cx,
                )
            });
            self.sessions.lock().insert(
                session_id,
                Session {
                    thread: thread.downgrade(),
                    response_tx: None,
                },
            );
            thread
        }

        pub fn send_update(
            &self,
            session_id: acp_v2::SessionId,
            update: acp_v1::SessionUpdate,
            cx: &mut App,
        ) {
            assert!(
                self.next_prompt_updates.lock().is_empty(),
                "Use either send_update or set_next_prompt_updates"
            );

            self.sessions
                .lock()
                .get(&session_id)
                .unwrap()
                .thread
                .update(cx, |thread, cx| {
                    thread.handle_session_update(update, cx).unwrap();
                })
                .unwrap();
        }

        pub fn end_turn(&self, session_id: acp_v2::SessionId, stop_reason: acp_v1::StopReason) {
            self.sessions
                .lock()
                .get_mut(&session_id)
                .unwrap()
                .response_tx
                .take()
                .expect("No pending turn")
                .send(stop_reason)
                .unwrap();
        }
    }

    impl AgentConnection for StubAgentConnection {
        fn shutdown(&self) {
            self.shutdown_calls.fetch_add(1, Ordering::SeqCst);
        }

        fn agent_id(&self) -> AgentId {
            self.agent_id.clone()
        }

        fn telemetry_id(&self) -> SharedString {
            self.telemetry_id.clone()
        }

        fn auth_methods(&self) -> &[acp_v2::AuthMethod] {
            &self.auth_methods
        }

        fn model_selector(
            &self,
            _session_id: &acp_v2::SessionId,
        ) -> Option<Rc<dyn AgentModelSelector>> {
            Some(self.model_selector_impl())
        }

        fn new_session(
            self: Rc<Self>,
            project: Entity<Project>,
            work_dirs: PathList,
            cx: &mut gpui::App,
        ) -> Task<gpui::Result<Entity<AcpThread>>> {
            let session_id = acp_v2::SessionId::new(StubSessionCounter::next(cx).to_string());
            let thread = self.create_session(session_id, project, work_dirs, None, cx);
            Task::ready(Ok(thread))
        }

        fn supports_load_session(&self) -> bool {
            self.supports_load_session
        }

        fn supports_close_session(&self) -> bool {
            self.supports_close_session
        }

        fn announces_subagents(&self) -> bool {
            self.announces_subagents
        }

        fn should_close_sessions_on_release(&self) -> bool {
            self.supports_close_session && self.close_sessions_on_release
        }

        fn close_session(
            self: Rc<Self>,
            session_id: &acp_v2::SessionId,
            cx: &mut App,
        ) -> Task<Result<()>> {
            if !self.supports_close_session {
                return Task::ready(Err(anyhow::Error::msg("Closing sessions is not supported")));
            }
            self.close_session_calls.lock().push(session_id.clone());
            match self.next_close_responses.lock().pop_front() {
                Some(response) => cx.spawn(async move |_| response.await?),
                None => Task::ready(Ok(())),
            }
        }

        fn supports_session_additional_directories(&self) -> bool {
            self.supports_session_additional_directories
        }

        fn load_session(
            self: Rc<Self>,
            session_id: acp_v2::SessionId,
            project: Entity<Project>,
            work_dirs: PathList,
            title: Option<SharedString>,
            cx: &mut App,
        ) -> Task<Result<Entity<AcpThread>>> {
            if !self.supports_load_session {
                return Task::ready(Err(anyhow::Error::msg("Loading sessions is not supported")));
            }

            if let Some(error) = self.next_load_error.lock().take() {
                return Task::ready(Err(error));
            }
            let thread = self.create_session(session_id, project, work_dirs, title, cx);
            Task::ready(Ok(thread))
        }

        fn authenticate(
            &self,
            _method_id: acp_v2::AuthMethodId,
            cx: &mut App,
        ) -> Task<gpui::Result<()>> {
            match self.next_authenticate_response.lock().take() {
                Some(response) => cx.spawn(async move |_| response.await?),
                None => Task::ready(Err(anyhow::Error::msg(
                    "No deferred authentication response",
                ))),
            }
        }

        fn validate_prompt_content(&self, content: &[acp_v2::ContentBlock]) -> Result<()> {
            crate::content::validate_prompt_content_for_v1(content)
        }

        fn prompt(
            &self,
            params: acp_v2::PromptRequest,
            cx: &mut App,
        ) -> Task<gpui::Result<acp_v1::PromptResponse>> {
            let session_id = params.session_id.clone();
            if let Err(error) = crate::content::prompt_to_v1(params) {
                return Task::ready(Err(error));
            }
            let mut sessions = self.sessions.lock();
            let Session {
                thread,
                response_tx,
            } = sessions.get_mut(&session_id).unwrap();
            let mut tasks = vec![];
            if let Some(receiver) = self.next_prompt_response.lock().take() {
                cx.spawn(async move |_| receiver.await?)
            } else if self.next_prompt_updates.lock().is_empty() {
                let (tx, rx) = oneshot::channel();
                response_tx.replace(tx);
                cx.spawn(async move |_| {
                    let stop_reason = rx.await?;
                    Ok(acp_v1::PromptResponse::new(stop_reason))
                })
            } else {
                for update in self.next_prompt_updates.lock().drain(..) {
                    let thread = thread.clone();
                    let permission_request = if let StubPromptUpdate::Legacy(update) = &update
                        && let acp_v1::SessionUpdate::ToolCall(tool_call) = update.as_ref()
                        && let Some(options) = self
                            .permission_requests
                            .get(&acp_v2::ToolCallId::new(tool_call.tool_call_id.0.clone()))
                    {
                        Some((tool_call.clone(), options.clone()))
                    } else {
                        None
                    };
                    let task = cx.spawn(async move |cx| {
                        if let Some((tool_call, options)) = permission_request {
                            thread
                                .update(cx, |thread, cx| {
                                    thread.request_tool_call_authorization(
                                        tool_call.clone().into(),
                                        options.clone(),
                                        AuthorizationKind::PermissionGrant,
                                        cx,
                                    )
                                })??
                                .await;
                        }
                        thread.update(cx, |thread, cx| match update {
                            StubPromptUpdate::Legacy(update) => thread
                                .handle_session_update(*update, cx)
                                .map_err(anyhow::Error::from),
                            StubPromptUpdate::Application(update) => update(thread, cx),
                        })??;
                        anyhow::Ok(())
                    });
                    tasks.push(task);
                }

                cx.spawn(async move |_| {
                    try_join_all(tasks).await?;
                    Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))
                })
            }
        }

        fn client_user_message_ids(
            &self,
            _cx: &App,
        ) -> Option<Rc<dyn AgentSessionClientUserMessageIds>> {
            Some(Rc::new(StubAgentSessionClientUserMessageIds {
                connection: self.clone(),
            }))
        }

        fn receipt_submissions(
            &self,
            session_id: &acp_v2::SessionId,
            _cx: &App,
        ) -> Option<Rc<dyn ReceiptSessionSubmissions>> {
            self.supports_receipt_submissions.then(|| {
                Rc::new(StubReceiptSessionSubmissions {
                    session_id: session_id.clone(),
                    sessions: self.sessions.clone(),
                    next_receipt_response: self.next_receipt_response.clone(),
                    receipt_prompt: self.receipt_prompt.clone(),
                }) as Rc<dyn ReceiptSessionSubmissions>
            })
        }

        fn retry(
            &self,
            _session_id: &acp_v2::SessionId,
            _cx: &App,
        ) -> Option<Rc<dyn AgentSessionRetry>> {
            self.supports_retry
                .then(|| Rc::new(StubAgentSessionRetry) as Rc<dyn AgentSessionRetry>)
        }

        fn cancel(&self, session_id: &acp_v2::SessionId, _cx: &mut App) -> Result<()> {
            self.cancel_calls.lock().push(session_id.clone());
            if let Some(error) = self.next_cancel_error.lock().take() {
                return Err(error);
            }
            if let Some(end_turn_tx) = self
                .sessions
                .lock()
                .get_mut(session_id)
                .ok_or_else(|| anyhow::anyhow!("Session not found"))?
                .response_tx
                .take()
            {
                end_turn_tx
                    .send(acp_v1::StopReason::Cancelled)
                    .map_err(|_| anyhow::anyhow!("Prompt observer was released"))?;
            }
            Ok(())
        }

        fn set_title(
            &self,
            session_id: &acp_v2::SessionId,
            _cx: &App,
        ) -> Option<Rc<dyn AgentSessionSetTitle>> {
            self.supports_set_title.then(|| {
                Rc::new(StubAgentSessionSetTitle {
                    session_id: session_id.clone(),
                    calls: self.set_title_calls.clone(),
                }) as _
            })
        }

        fn truncate(
            &self,
            _session_id: &acp_v2::SessionId,
            _cx: &App,
        ) -> Option<Rc<dyn AgentSessionTruncate>> {
            // Capability checks also call this; only run may consume the gate.
            self.supports_truncate.then(|| {
                Rc::new(StubAgentSessionEditor {
                    next_truncate: self.next_truncate.clone(),
                }) as Rc<dyn AgentSessionTruncate>
            })
        }

        fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
            self
        }
    }

    struct StubAgentSessionSetTitle {
        session_id: acp_v2::SessionId,
        calls: Arc<Mutex<Vec<(acp_v2::SessionId, SharedString)>>>,
    }

    impl AgentSessionSetTitle for StubAgentSessionSetTitle {
        fn run(&self, title: SharedString, _cx: &mut App) -> Task<Result<()>> {
            self.calls.lock().push((self.session_id.clone(), title));
            Task::ready(Ok(()))
        }
    }

    struct StubAgentSessionClientUserMessageIds {
        connection: StubAgentConnection,
    }

    impl AgentSessionClientUserMessageIds for StubAgentSessionClientUserMessageIds {
        fn prompt(
            &self,
            _client_user_message_id: ClientUserMessageId,
            params: acp_v2::PromptRequest,
            cx: &mut App,
        ) -> Task<Result<acp_v1::PromptResponse>> {
            self.connection.prompt(params, cx)
        }
    }

    struct StubReceiptSessionSubmissions {
        session_id: acp_v2::SessionId,
        sessions: Arc<Mutex<HashMap<acp_v2::SessionId, Session>>>,
        next_receipt_response:
            Arc<Mutex<Option<oneshot::Receiver<Result<acp_v2::PromptResponse>>>>>,
        receipt_prompt: Arc<Mutex<Option<Vec<acp_v2::ContentBlock>>>>,
    }

    impl ReceiptSessionSubmissions for StubReceiptSessionSubmissions {
        fn submit(
            &self,
            content: Vec<acp_v2::ContentBlock>,
            cx: &mut gpui::Context<AcpThread>,
        ) -> ReceiptSubmission {
            if !self.sessions.lock().contains_key(&self.session_id) {
                return Task::ready(Err(anyhow::Error::msg("Unknown receipt session"))).into();
            }
            *self.receipt_prompt.lock() = Some(content);
            match self.next_receipt_response.lock().take() {
                Some(receiver) => cx.spawn(async move |_, _| Ok(receiver.await??)),
                None => Task::ready(Err(anyhow::Error::msg("No deferred receipt response"))),
            }
            .into()
        }
    }

    struct StubAgentSessionRetry;

    impl AgentSessionRetry for StubAgentSessionRetry {
        fn run(&self, _cx: &mut App) -> Task<Result<acp_v1::PromptResponse>> {
            Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
        }
    }

    struct StubAgentSessionEditor {
        next_truncate: Arc<Mutex<Option<oneshot::Receiver<()>>>>,
    }

    impl AgentSessionTruncate for StubAgentSessionEditor {
        fn run(&self, _: ClientUserMessageId, cx: &mut App) -> Task<Result<()>> {
            if let Some(receiver) = self.next_truncate.lock().take() {
                cx.foreground_executor().spawn(async move {
                    receiver.await?;
                    Ok(())
                })
            } else {
                Task::ready(Ok(()))
            }
        }
    }

    #[derive(Clone)]
    struct StubModelSelector {
        selected_model: Arc<Mutex<AgentModelInfo>>,
    }

    impl StubModelSelector {
        fn new() -> Self {
            Self {
                selected_model: Arc::new(Mutex::new(AgentModelInfo {
                    id: AgentModelId::new("visual-test-model"),
                    name: "Visual Test Model".into(),
                    description: Some("A stub model for visual testing".into()),
                    icon: Some(AgentModelIcon::Named(ui::IconName::ZedAssistant)),
                    is_latest: false,
                    cost: None,
                    disabled: None,
                })),
            }
        }
    }

    impl AgentModelSelector for StubModelSelector {
        fn list_models(&self, _cx: &mut App) -> Task<Result<AgentModelList>> {
            let model = self.selected_model.lock().clone();
            Task::ready(Ok(AgentModelList::Flat(vec![model])))
        }

        fn select_model(&self, model_id: AgentModelId, _cx: &mut App) -> Task<Result<()>> {
            self.selected_model.lock().id = model_id;
            Task::ready(Ok(()))
        }

        fn selected_model(&self, _cx: &mut App) -> Task<Result<AgentModelInfo>> {
            Task::ready(Ok(self.selected_model.lock().clone()))
        }
    }

    impl StubAgentConnection {
        /// Returns a model selector for this stub connection.
        pub fn model_selector_impl(&self) -> Rc<dyn AgentModelSelector> {
            Rc::new(StubModelSelector::new())
        }
    }
}

#[cfg(any(test, feature = "test-support"))]
pub use test_support::*;

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::sync::Arc;

    #[test]
    fn session_info_id_preserves_backing_arc_and_legacy_serialization() {
        for value in ["", "session/ \0 雪 😀"] {
            let backing: Arc<str> = value.into();
            let info = AgentSessionInfo::new(acp_v2::SessionId::new(backing.clone()));
            assert!(Arc::ptr_eq(&info.session_id.0, &backing));
            let wire_id = acp_v1::SessionId::new(backing);
            let serialized = serde_json::to_value(&info.session_id).expect("application ID");
            assert_eq!(serialized, json!(value));
            assert_eq!(
                serialized,
                serde_json::to_value(&wire_id).expect("legacy ID"),
            );
            let restored = AgentSessionInfo::new(
                serde_json::from_value::<acp_v2::SessionId>(serialized).expect("restored ID"),
            );
            assert_eq!(restored, info);
        }
    }

    #[test]
    fn session_info_patches_preserve_legacy_fields_and_apply_tristate_updates() {
        let timestamp = "2026-03-04T05:06:07+02:30";
        let updated_at = DateTime::parse_from_rfc3339(timestamp)
            .expect("valid timestamp")
            .with_timezone(&Utc);
        let original_meta = acp_v2::Meta::from_iter([(
            "original".into(),
            json!({"nested": [1, {"value": "retained"}]}),
        )]);
        let original = AgentSessionInfo {
            session_id: acp_v2::SessionId::new("opaque/session"),
            work_dirs: Some(PathList::new(&[std::path::Path::new("/workspace")])),
            title: Some("Original title".into()),
            updated_at: Some(updated_at),
            created_at: Some(updated_at),
            meta: Some(original_meta),
        };

        for (wire, title, expected_updated_at, meta, changed) in [
            (
                json!({}),
                original.title.clone(),
                original.updated_at,
                original.meta.clone(),
                false,
            ),
            (
                json!({"title": null, "updatedAt": null}),
                None,
                None,
                original.meta.clone(),
                true,
            ),
            (
                json!({"title": "", "updatedAt": timestamp, "_meta": {}}),
                Some("".into()),
                Some(updated_at),
                Some(acp_v2::Meta::new()),
                true,
            ),
            (
                json!({"_meta": {"replacement": {"value": []}}}),
                original.title.clone(),
                original.updated_at,
                Some(acp_v2::Meta::from_iter([(
                    "replacement".into(),
                    json!({"value": []}),
                )])),
                true,
            ),
            (
                json!({"_meta": {"literal": null}}),
                original.title.clone(),
                original.updated_at,
                Some(acp_v2::Meta::from_iter([("literal".into(), json!(null))])),
                true,
            ),
            (
                json!({"_meta": null}),
                original.title.clone(),
                original.updated_at,
                original.meta.clone(),
                false,
            ),
        ] {
            let legacy: acp_v1::SessionInfoUpdate =
                serde_json::from_value(wire).expect("legacy patch");
            let mut info = original.clone();
            assert_eq!(info.apply_update(legacy.clone()), changed);
            assert_eq!(
                info,
                AgentSessionInfo {
                    title,
                    updated_at: expected_updated_at,
                    meta,
                    ..original.clone()
                }
            );
            assert!(!info.apply_update(legacy), "identical patch is a no-op");
        }

        let mut info = original.clone();
        assert!(info.apply_update(acp_v2::SessionInfoUpdate::new().meta(None::<acp_v2::Meta>)));
        assert_eq!(
            info,
            AgentSessionInfo {
                meta: None,
                ..original.clone()
            }
        );
        assert!(!info.apply_update(acp_v2::SessionInfoUpdate::new().meta(acp_v2::Meta::new())));
        assert_eq!(info.meta, Some(acp_v2::Meta::new()));

        let mut info = original.clone();
        assert!(
            info.apply_update(
                acp_v2::SessionInfoUpdate::new()
                    .title("New title")
                    .updated_at("invalid private timestamp")
            )
        );
        assert_eq!(
            info,
            AgentSessionInfo {
                title: Some("New title".into()),
                ..original
            }
        );
        assert!(!info.apply_update(
            acp_v2::SessionInfoUpdate::new().updated_at("invalid private timestamp")
        ));
    }

    #[test]
    fn session_info_v2_metadata_patches_report_only_effective_changes() {
        let mut info = AgentSessionInfo::new("metadata");
        for (patch, expected, changed) in [
            (json!({"_meta": {"missing": null}}), json!({}), false),
            (json!({"_meta": {}}), json!({}), false),
            (
                json!({"_meta": {"keep": 1, "nested": {"old": true, "literal": null}}}),
                json!({"keep": 1, "nested": {"old": true, "literal": null}}),
                true,
            ),
            (
                json!({"_meta": {"nested": {"new": true, "literal": null}}}),
                json!({"keep": 1, "nested": {"new": true, "literal": null}}),
                true,
            ),
            (
                json!({"_meta": {"unknown": null}}),
                json!({"keep": 1, "nested": {"new": true, "literal": null}}),
                false,
            ),
            (
                json!({"_meta": {"keep": null}}),
                json!({"nested": {"new": true, "literal": null}}),
                true,
            ),
            (json!({"_meta": null}), json!(null), true),
            (json!({"_meta": null}), json!(null), false),
        ] {
            let update: acp_v2::SessionInfoUpdate =
                serde_json::from_value(patch).expect("v2 session information");
            assert_eq!(info.apply_update(update.clone()), changed);
            assert_eq!(
                serde_json::to_value(&info.meta).expect("metadata JSON"),
                expected
            );
            assert!(!info.apply_update(update), "repeated patch is a no-op");
        }
    }
}