Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

29.3 KB
Raw Blame
use super::*;

pub(crate) const PROVIDER_SELECT: &str =
    "SELECT id, name, vendor_key, type, protocol, enabled, base_url, auth_kind, secret_ref,
            default_model_id, api_style, config_json, created_at, updated_at, owner_plugin_id
     FROM providers";

pub(crate) const CANONICAL_THINKING_LEVELS: &[&str] =
    &["off", "minimal", "low", "medium", "high", "xhigh", "max"];
const THINKING_PROTOCOLS: &[&str] = &["legacy", "adaptive"];
/// Recognised per-limit provenance markers. Anything else is dropped so a
/// row always falls back to the documented rule instead of a third state no
/// reader understands.
const MODEL_LIMIT_SOURCES: &[&str] = &["catalog", "user"];
pub(crate) const DEFAULT_CONTEXT_WINDOW: u32 = 128_000;
pub(crate) const DEFAULT_MAX_TOKENS: u32 = 8_192;

fn normalize_model_limit_source(value: Option<&str>) -> Option<String> {
    let trimmed = value?.trim().to_ascii_lowercase();
    MODEL_LIMIT_SOURCES
        .contains(&trimmed.as_str())
        .then_some(trimmed)
}

fn default_thinking_level_allowed(level: &str, thinking_levels: &[String]) -> bool {
    if level == "omit" {
        return thinking_levels.iter().any(|item| item != "off");
    }
    thinking_levels.iter().any(|item| item == level)
}

pub(crate) fn normalize_model_bindings(bindings: &[ModelBinding]) -> Vec<ModelBinding> {
    bindings
        .iter()
        .filter_map(|binding| {
            let id = binding.id.trim();
            if id.is_empty() {
                return None;
            }
            let thinking_levels = normalize_thinking_levels(&binding.thinking_levels);
            let thinking_protocol = binding
                .thinking_protocol
                .as_deref()
                .filter(|protocol| THINKING_PROTOCOLS.contains(protocol))
                .map(str::to_string);
            let default_thinking_level = binding
                .default_thinking_level
                .as_deref()
                .map(str::trim)
                .filter(|level| default_thinking_level_allowed(level, &thinking_levels))
                .map(str::to_string)
                .or_else(|| thinking_levels.first().cloned());
            Some(ModelBinding {
                id: id.to_string(),
                alias: binding
                    .alias
                    .as_deref()
                    .map(str::trim)
                    .filter(|value| !value.is_empty())
                    .map(str::to_string),
                context_window_source: normalize_model_limit_source(
                    binding.context_window_source.as_deref(),
                ),
                max_tokens_source: normalize_model_limit_source(
                    binding.max_tokens_source.as_deref(),
                ),
                context_window: if binding.context_window == 0 {
                    DEFAULT_CONTEXT_WINDOW
                } else {
                    binding.context_window
                },
                max_tokens: if binding.max_tokens == 0 {
                    DEFAULT_MAX_TOKENS
                } else {
                    binding.max_tokens
                },
                thinking_levels,
                default_thinking_level,
                thinking_protocol,
                supports_reasoning_effort: binding.supports_reasoning_effort,
                supports_images: binding.supports_images,
                supports_documents: binding.supports_documents,
                available_for_subagents: binding.available_for_subagents,
                native_web_search: binding.native_web_search,
                fast_mode_allowed: binding.fast_mode_allowed,
                allow_empty_thinking_signature: binding.allow_empty_thinking_signature,
            })
        })
        .collect()
}

fn legacy_model_binding(model_id: Option<String>) -> Vec<ModelBinding> {
    model_id
        .filter(|id| !id.trim().is_empty())
        .map(|id| {
            vec![ModelBinding {
                id: id.trim().to_string(),
                alias: None,
                context_window_source: None,
                max_tokens_source: None,
                context_window: DEFAULT_CONTEXT_WINDOW,
                max_tokens: DEFAULT_MAX_TOKENS,
                thinking_levels: Vec::new(),
                default_thinking_level: None,
                thinking_protocol: None,
                supports_reasoning_effort: None,
                supports_images: None,
                supports_documents: None,
                available_for_subagents: None,
                native_web_search: None,
                fast_mode_allowed: None,
                allow_empty_thinking_signature: None,
            }]
        })
        .unwrap_or_default()
}

/// What `config_json.models` holds.
enum StoredModels {
    /// The key is absent — a record written before bindings existed.
    Absent,
    /// The stored config is not valid JSON or is not an object.
    InvalidConfig {
        /// A safe, non-secret description suitable for the RPC error/log.
        reason: String,
    },
    /// The key is present but is not an array, so there is nothing to decode.
    NotAnArray,
    /// The array, decoded one entry at a time.
    Entries {
        /// Entries that decoded, in stored order.
        bindings: Vec<ModelBinding>,
        /// `(index, reason)` for every entry that did not, so a reader can
        /// name the exact entry instead of only counting the loss.
        unreadable: Vec<(usize, String)>,
    },
}

/// Decode `config_json.models` one entry at a time.
///
/// The array is the only place a provider's model list lives and it is written
/// by more than one hand — a settings save, a plugin declaration, and an
/// external edit of the stored row. Decoding it as a single `Vec<ModelBinding>`
/// let one entry that no longer matched the schema discard every sibling, after
/// which the provider read back as one legacy default model with nothing said
/// about why (issue #784). Each entry is therefore decoded on its own and the
/// ones that fail are collected for the caller to report.
fn decode_stored_models(raw: &str) -> StoredModels {
    let value = match serde_json::from_str::<serde_json::Value>(raw) {
        Ok(value) if value.is_object() => value,
        Ok(_) => {
            return StoredModels::InvalidConfig {
                reason: "config_json root must be an object".to_string(),
            };
        }
        Err(error) => {
            return StoredModels::InvalidConfig {
                reason: format!("config_json is not valid JSON: {error}"),
            };
        }
    };
    let Some(models) = value.get("models").cloned() else {
        return StoredModels::Absent;
    };
    let Some(entries) = models.as_array() else {
        return StoredModels::NotAnArray;
    };
    let mut bindings = Vec::with_capacity(entries.len());
    let mut unreadable = Vec::new();
    for (index, entry) in entries.iter().enumerate() {
        match serde_json::from_value::<ModelBinding>(entry.clone()) {
            Ok(binding) if binding.id.trim().is_empty() => unreadable.push((
                index,
                "model binding id must be a non-empty string".to_string(),
            )),
            Ok(binding) => bindings.push(binding),
            Err(error) => unreadable.push((index, error.to_string())),
        }
    }
    StoredModels::Entries {
        bindings,
        unreadable,
    }
}

/// Read the provider's model bindings out of `config_json`.
///
/// An absent array and an empty one leave the single legacy binding without a
/// warning. Invalid config shapes and unreadable entries are reported. An array
/// whose every entry is unreadable still falls back to the legacy binding, so a
/// provider stays selectable while the loss remains diagnosable.
pub(crate) fn config_model_bindings(
    raw: &str,
    legacy_model_id: Option<String>,
    provider_id: &str,
) -> Vec<ModelBinding> {
    let legacy_model_id = legacy_model_id.or_else(|| {
        config_value(raw).and_then(|value| value.get("modelId")?.as_str().map(str::to_string))
    });
    match decode_stored_models(raw) {
        StoredModels::Entries {
            bindings,
            unreadable,
        } => {
            for (index, reason) in &unreadable {
                tracing::warn!(
                    %provider_id,
                    index,
                    %reason,
                    "skipping an unreadable model binding"
                );
            }
            let bindings = normalize_model_bindings(&bindings);
            if bindings.is_empty() {
                legacy_model_binding(legacy_model_id)
            } else {
                bindings
            }
        }
        StoredModels::InvalidConfig { reason } => {
            tracing::warn!(
                %provider_id,
                %reason,
                "invalid provider config_json; reading the legacy binding"
            );
            legacy_model_binding(legacy_model_id)
        }
        StoredModels::NotAnArray => {
            tracing::warn!(
                %provider_id,
                "config_json.models is not an array; reading the legacy binding"
            );
            legacy_model_binding(legacy_model_id)
        }
        StoredModels::Absent => legacy_model_binding(legacy_model_id),
    }
}

/// Reject a full model-array replacement while the stored array is degraded.
///
/// Returning the readable subset from a degraded read keeps providers usable,
/// but accepting that subset back through `providers.update` would permanently
/// erase unreadable entries. Callers may still update unrelated provider fields;
/// only an explicit `models` replacement is blocked.
pub(crate) fn ensure_model_bindings_update_safe(raw: &str) -> Result<()> {
    match decode_stored_models(raw) {
        StoredModels::Absent => Ok(()),
        StoredModels::Entries { unreadable, .. } if unreadable.is_empty() => Ok(()),
        StoredModels::Entries { unreadable, .. } => {
            let details = unreadable
                .into_iter()
                .map(|(index, reason)| format!("index {index}: {reason}"))
                .collect::<Vec<_>>()
                .join("; ");
            bail!("MODEL_BINDINGS_DEGRADED: {details}");
        }
        StoredModels::InvalidConfig { reason } => {
            bail!("MODEL_BINDINGS_DEGRADED: {reason}");
        }
        StoredModels::NotAnArray => {
            bail!("MODEL_BINDINGS_DEGRADED: config_json.models is not an array");
        }
    }
}

pub(crate) fn config_with_model_bindings(raw: &str, bindings: &[ModelBinding]) -> Result<String> {
    let mut config = ensure_config_object(raw)?;
    config["models"] = serde_json::to_value(normalize_model_bindings(bindings))?;
    Ok(config.to_string())
}

pub(crate) fn config_thinking_levels_override(raw: &str) -> Option<Vec<String>> {
    let levels = config_value(raw)?
        .get("compatibility")?
        .get("supportedThinkingLevels")?
        .as_array()
        .cloned()?;
    let parsed: Vec<String> = levels
        .into_iter()
        .filter_map(|value| value.as_str().map(str::to_string))
        .collect();
    let normalized = normalize_thinking_levels(&parsed);
    if normalized.is_empty() {
        None
    } else {
        Some(normalized)
    }
}

pub fn list_models(db: &Database, provider_id: Option<&str>) -> Result<Vec<ModelCatalogItem>> {
    let (sql, bind_provider) = match provider_id {
        Some(id) => (
            "SELECT provider_id, model_id, display_name, source,
                capabilities_json, context_window, discovery_state, reported_context_window
         FROM models
         WHERE provider_id = ?1
         ORDER BY display_name COLLATE NOCASE, model_id",
            Some(id),
        ),
        None => (
            "SELECT provider_id, model_id, display_name, source,
                capabilities_json, context_window, discovery_state, reported_context_window
         FROM models
         ORDER BY provider_id, display_name COLLATE NOCASE, model_id",
            None,
        ),
    };
    let mut stmt = db.conn().prepare_cached(sql)?;
    let parse = |row: &rusqlite::Row<'_>| -> rusqlite::Result<ModelCatalogItem> {
        let raw_capabilities: String = row.get(4)?;
        let capabilities = serde_json::from_str(&raw_capabilities).unwrap_or_default();
        Ok(ModelCatalogItem {
            discovery_state: row.get(6)?,
            provider_id: row.get(0)?,
            model_id: row.get(1)?,
            display_name: row.get(2)?,
            source: row.get(3)?,
            capabilities,
            context_window: row
                .get::<_, Option<i64>>(5)?
                .and_then(|value| u32::try_from(value).ok()),
            reported_context_window: row
                .get::<_, Option<i64>>(7)?
                .and_then(|value| u32::try_from(value).ok()),
        })
    };
    let rows = if let Some(id) = bind_provider {
        stmt.query_map(params![id], parse)?
    } else {
        stmt.query_map([], parse)?
    };
    Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}

/// Merge discovery atomically. Only a complete, nonempty answer marks missing
/// previously discovered bindings as unlisted. Partial answers only enrich rows;
/// user-owned rows, saved configuration, defaults and history are never changed.
pub fn cache_discovered_models(
    db: &Database,
    provider_id: &str,
    models: &[DiscoveredModelInput],
    complete: bool,
) -> Result<usize> {
    // Empty or malformed answers cannot revoke a previously published model.
    let complete = complete
        && !models.is_empty()
        && models.iter().all(|model| !model.model_id.trim().is_empty());
    let configured = configured_model_ids(db, provider_id)?;
    let tx = db.conn().unchecked_transaction()?;
    if complete {
        tx.execute(
            "UPDATE models SET discovery_state = 'unlisted'
            WHERE provider_id = ?1 AND source = 'discovered' AND discovery_state IS NOT NULL",
            params![provider_id],
        )?;
    }
    let now = now_ms();
    let mut changed = 0;
    {
        let mut stmt = tx.prepare_cached(
            "INSERT INTO models (
            provider_id, model_id, display_name, source,
            capabilities_json, context_window, updated_at, discovery_state, reported_context_window
         ) VALUES (?1, ?2, ?3, 'discovered', ?4, ?5, ?6, 'published', ?7)
         ON CONFLICT(provider_id, model_id) DO UPDATE SET
            display_name = excluded.display_name,
            capabilities_json = excluded.capabilities_json,
            context_window = excluded.context_window,
            reported_context_window = excluded.reported_context_window,
            updated_at = excluded.updated_at,
            discovery_state = 'published'
         WHERE models.source != 'user'",
        )?;
        for model in models {
            let model_id = model.model_id.trim();
            if model_id.is_empty() {
                continue;
            }
            let display_name = model.display_name.trim();
            let display_name = if display_name.is_empty() {
                model_id
            } else {
                display_name
            };
            // Bindings compare complete wire ids case-insensitively. A casing
            // change must not leave an older spelling marked as unlisted.
            tx.execute(
                "UPDATE models SET discovery_state = 'published', reported_context_window = ?3
                WHERE provider_id = ?1 AND lower(model_id) = lower(?2)
                AND source = 'discovered'",
                params![provider_id, model_id, model.reported_context_window],
            )?;
            changed += stmt.execute(params![
                provider_id,
                model_id,
                display_name,
                serde_json::to_string(&model.capabilities)?,
                model.context_window,
                now,
                model.reported_context_window,
            ])?;
        }
    }
    if complete {
        // Keep configured rows as durable unlisted records. Unconfigured rows
        // can still be pruned; neither bindings nor history are rewritten.
        let keep: std::collections::BTreeSet<String> = configured
            .iter()
            .map(|id| id.trim().to_lowercase())
            .collect();
        let stale: Vec<String> = {
            let mut stmt = tx.prepare_cached(
                "SELECT model_id FROM models
                WHERE provider_id = ?1 AND source = 'discovered'
                AND discovery_state = 'unlisted'",
            )?;
            let rows = stmt.query_map(params![provider_id], |row| row.get::<_, String>(0))?;
            rows.collect::<rusqlite::Result<Vec<_>>>()?
        };
        for id in stale {
            if !keep.contains(&id.trim().to_lowercase()) {
                tx.execute(
                    "DELETE FROM models WHERE provider_id = ?1 AND model_id = ?2",
                    params![provider_id, id],
                )?;
            }
        }
    }
    tx.commit()?;
    Ok(changed)
}

/// Forget the cached rows of models a save removed from the provider.
///
/// The `models` table is a cache of what the service published, and deleting a
/// binding is the user saying that model is no longer part of this service's
/// configuration. Keeping the row would hand the deleted model's recorded
/// parameters — context window, capabilities, display name — to the next add of
/// the same id, and would keep the id in the picker's cache-first paint. Only
/// rows of ids the save actually dropped are touched: the rest of the discovered
/// list is the service's answer, not the user's configuration. A model the
/// service still publishes comes back on the next probe, described by the
/// service rather than by a stale answer.
pub(crate) fn forget_cached_models(
    db: &Database,
    provider_id: &str,
    model_ids: &[String],
) -> Result<usize> {
    if model_ids.is_empty() {
        return Ok(0);
    }
    let tx = db.conn().unchecked_transaction()?;
    let mut removed = 0;
    {
        // Ids are matched case-insensitively: a binding may spell a model
        // differently from the answer it was added from.
        let mut stmt = tx.prepare_cached(
            "DELETE FROM models WHERE provider_id = ?1 AND lower(model_id) = lower(?2)",
        )?;
        for model_id in model_ids {
            let model_id = model_id.trim();
            if model_id.is_empty() {
                continue;
            }
            removed += stmt.execute(params![provider_id, model_id])?;
        }
    }
    tx.commit()?;
    Ok(removed)
}

/// Model ids the provider's own bindings configure, in any spelling.
fn configured_model_ids(db: &Database, provider_id: &str) -> Result<Vec<String>> {
    let saved: Option<(String, Option<String>)> = db
        .conn()
        .query_row(
            "SELECT config_json, default_model_id FROM providers WHERE id = ?1",
            params![provider_id],
            |row| Ok((row.get(0)?, row.get(1)?)),
        )
        .optional()?;
    let Some((raw, default_model_id)) = saved else {
        return Ok(Vec::new());
    };
    Ok(config_model_bindings(&raw, default_model_id, provider_id)
        .into_iter()
        .map(|binding| binding.id)
        .collect())
}

/// Drop discovered rows the current answer no longer names.
///
/// The cache is the service's answer, so it has to move when the answer moves: a
/// model the endpoint stopped publishing must stop being painted from cache with
/// the parameters it used to have, and it must stop being offered as "already
/// known" to a hand-typed id. `keep_ids` carries what the answer does name,
/// together with the provider's configured bindings; only rows whose source is
/// discovery are eligible, so a row the user owns is never dropped here.
pub(crate) fn forget_missing_discovered_models(
    db: &Database,
    provider_id: &str,
    keep_ids: &[String],
) -> Result<usize> {
    let keep: std::collections::BTreeSet<String> =
        keep_ids.iter().map(|id| id.trim().to_lowercase()).collect();
    let stale: Vec<String> = {
        let mut stmt = db.conn().prepare_cached(
            "SELECT model_id FROM models WHERE provider_id = ?1 AND source = 'discovered'",
        )?;
        let rows = stmt.query_map(params![provider_id], |row| row.get::<_, String>(0))?;
        rows.collect::<rusqlite::Result<Vec<String>>>()?
            .into_iter()
            .filter(|model_id| !keep.contains(&model_id.trim().to_lowercase()))
            .collect()
    };
    forget_cached_models(db, provider_id, &stale)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn binding(id: &str, context_window: u32) -> ModelBinding {
        ModelBinding {
            id: id.to_string(),
            alias: None,
            context_window,
            context_window_source: None,
            max_tokens_source: None,
            max_tokens: DEFAULT_MAX_TOKENS,
            thinking_levels: Vec::new(),
            default_thinking_level: None,
            thinking_protocol: None,
            supports_reasoning_effort: None,
            supports_images: None,
            supports_documents: None,
            available_for_subagents: None,
            native_web_search: None,
            fast_mode_allowed: None,
            allow_empty_thinking_signature: None,
        }
    }

    /// Every read names the provider it came from: a warning that does not is
    /// not locatable, which is half of what issue #784 reports.
    fn read(raw: &str) -> Vec<ModelBinding> {
        config_model_bindings(raw, None, "provider-under-test")
    }

    /// The settings surface round-trips a provider through `config_json`, so a
    /// marker the store drops would silently turn an inherited catalog value
    /// into a frozen snapshot of its own.
    #[test]
    fn a_catalog_sourced_binding_survives_the_config_round_trip() {
        let raw = r#"{"models":[{"id":"terra","contextWindow":1048576,"maxTokens":64000,
            "contextWindowSource":"catalog","maxTokensSource":"catalog"}]}"#;
        let saved = config_with_model_bindings("{}", &read(raw)).unwrap();
        let value: serde_json::Value = serde_json::from_str(&saved).unwrap();
        assert_eq!(value["models"][0]["contextWindowSource"], "catalog");
        assert_eq!(value["models"][0]["maxTokensSource"], "catalog");
        assert_eq!(
            read(&saved)[0].context_window_source.as_deref(),
            Some("catalog")
        );
        assert_eq!(
            read(&saved)[0].max_tokens_source.as_deref(),
            Some("catalog")
        );

        let mut user_binding = binding("terra", 128_000);
        user_binding.context_window_source = Some("user".to_string());
        user_binding.max_tokens_source = Some("user".to_string());
        let saved = config_with_model_bindings("{}", &[user_binding]).unwrap();
        assert_eq!(
            read(&saved)[0].context_window_source.as_deref(),
            Some("user")
        );
        assert_eq!(read(&saved)[0].max_tokens_source.as_deref(), Some("user"));
    }

    /// Records written before the marker name no source. They stay `None` so
    /// every reader applies one documented rule instead of guessing.
    #[test]
    fn a_binding_without_a_source_stays_unmarked() {
        let bindings =
            read(r#"{"models":[{"id":"legacy","contextWindow":128000,"maxTokens":8192}]}"#);
        assert_eq!(bindings[0].context_window_source, None);
        assert_eq!(bindings[0].max_tokens_source, None);
        let saved = config_with_model_bindings("{}", &bindings).unwrap();
        let value: serde_json::Value = serde_json::from_str(&saved).unwrap();
        assert!(value["models"][0].get("contextWindowSource").is_none());
    }

    /// An unrecognised marker is not a third state: it is dropped so the
    /// historical rule keeps applying to that row.
    #[test]
    fn an_unknown_source_is_dropped_instead_of_persisted() {
        let bindings = read(
            r#"{"models":[{"id":"odd","contextWindow":256000,"maxTokens":8192,
                "contextWindowSource":"derived","maxTokensSource":"derived"}]}"#,
        );
        assert_eq!(bindings[0].context_window_source, None);
        assert_eq!(bindings[0].max_tokens_source, None);
    }

    /// The zero-value normalisation is what keeps a freshly added model from
    /// persisting a window of `0`; the source marker must not disturb it.
    #[test]
    fn zero_limits_still_fall_back_to_the_generic_defaults() {
        let normalized = normalize_model_bindings(&[binding("terra", 0)]);
        assert_eq!(normalized[0].context_window, DEFAULT_CONTEXT_WINDOW);
        assert_eq!(normalized[0].max_tokens, DEFAULT_MAX_TOKENS);
    }

    #[test]
    fn omit_default_survives_on_reasoning_bindings_only() {
        let mut reasoning = binding("r", DEFAULT_CONTEXT_WINDOW);
        reasoning.thinking_levels = vec!["high".into(), "medium".into()];
        reasoning.default_thinking_level = Some("omit".into());
        let mut off_only = binding("plain", DEFAULT_CONTEXT_WINDOW);
        off_only.thinking_levels = vec!["off".into()];
        off_only.default_thinking_level = Some("omit".into());
        let normalized = normalize_model_bindings(&[reasoning, off_only]);
        assert_eq!(
            normalized[0].default_thinking_level.as_deref(),
            Some("omit")
        );
        assert_eq!(normalized[1].default_thinking_level.as_deref(), Some("off"));
    }

    /// A binding that omits its limits is one binding, not a broken array: the
    /// absent key reads as zero and the zero normalisation already in place
    /// seeds the generic default. This is the reported failure — a stored array
    /// whose second entry lost `maxTokens` used to read back as one legacy
    /// default model (issue #784).
    #[test]
    fn a_binding_without_limits_keeps_its_siblings() {
        let bindings = read(
            r#"{"models":[
                {"id":"no-limits"},
                {"id":"explicit","contextWindow":200000,"maxTokens":4096}
            ]}"#,
        );
        assert_eq!(bindings.len(), 2);
        assert_eq!(bindings[0].id, "no-limits");
        assert_eq!(bindings[0].context_window, DEFAULT_CONTEXT_WINDOW);
        assert_eq!(bindings[0].max_tokens, DEFAULT_MAX_TOKENS);
        assert_eq!(bindings[1].id, "explicit");
        assert_eq!(bindings[1].context_window, 200_000);
        assert_eq!(bindings[1].max_tokens, 4_096);
    }

    /// An entry that no longer matches the schema costs itself, not the array:
    /// the readable entries survive in their stored order.
    #[test]
    fn an_unreadable_binding_costs_only_itself() {
        let bindings = read(
            r#"{"models":[
                {"id":"first","contextWindow":1000,"maxTokens":100},
                {"id":"second","maxTokens":"not-a-number"},
                {"id":"third","contextWindow":3000,"maxTokens":300}
            ]}"#,
        );
        assert_eq!(
            bindings
                .iter()
                .map(|binding| binding.id.as_str())
                .collect::<Vec<_>>(),
            ["first", "third"]
        );
    }

    /// Every entry unreadable still leaves the legacy binding, so the provider
    /// stays selectable; the loss is reported per entry rather than being
    /// silent.
    #[test]
    fn an_all_unreadable_array_still_reads_the_legacy_binding() {
        let bindings = config_model_bindings(
            r#"{"models":[{"id":"a","maxTokens":"x"},{"id":"b","contextWindow":"y"}]}"#,
            Some("fallback".into()),
            "provider-under-test",
        );
        assert_eq!(bindings.len(), 1);
        assert_eq!(bindings[0].id, "fallback");
    }

    /// An empty array is a legal state, not a damaged one, so it reads the
    /// legacy binding without being reported as corruption.
    #[test]
    fn an_empty_models_array_reads_the_legacy_binding() {
        let bindings = config_model_bindings(
            r#"{"models":[],"modelId":"config-legacy"}"#,
            None,
            "provider-under-test",
        );
        assert_eq!(bindings.len(), 1);
        assert_eq!(bindings[0].id, "config-legacy");
    }

    /// A `models` value that is not an array is reported rather than silently
    /// read as the legacy binding.
    #[test]
    fn a_non_array_models_value_reads_the_legacy_binding() {
        let bindings = config_model_bindings(
            r#"{"models":{"id":"wrapped"},"modelId":"config-legacy"}"#,
            None,
            "provider-under-test",
        );
        assert_eq!(bindings.len(), 1);
        assert_eq!(bindings[0].id, "config-legacy");
    }
    #[test]
    fn malformed_model_storage_is_explicitly_degraded() {
        let invalid_json = ensure_model_bindings_update_safe("not-json").unwrap_err();
        assert!(invalid_json
            .to_string()
            .starts_with("MODEL_BINDINGS_DEGRADED: config_json is not valid JSON"));

        let non_object = ensure_model_bindings_update_safe("[]").unwrap_err();
        assert!(non_object
            .to_string()
            .contains("config_json root must be an object"));

        let non_array =
            ensure_model_bindings_update_safe(r#"{"models":{"id":"wrapped"}}"#).unwrap_err();
        assert!(non_array
            .to_string()
            .contains("config_json.models is not an array"));

        let empty_id = read(r#"{"models":[{"id":"  "},{"id":"readable"}]}"#);
        assert_eq!(
            empty_id
                .iter()
                .map(|binding| binding.id.as_str())
                .collect::<Vec<_>>(),
            ["readable"]
        );
        let empty_id_error =
            ensure_model_bindings_update_safe(r#"{"models":[{"id":"  "},{"id":"readable"}]}"#)
                .unwrap_err();
        assert!(empty_id_error.to_string().contains("index 0"));

        assert!(ensure_model_bindings_update_safe(r#"{"models":[]}"#).is_ok());
    }
}