Skip to content

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

fix(host-core): keep the model cache aligned with its configuration

vastsab759d5276d17
diff --git a/crates/host-core/src/plugins/providers.rs b/crates/host-core/src/plugins/providers.rs
index 9b6f9a207..6e562f727 100644
--- a/crates/host-core/src/plugins/providers.rs
+++ b/crates/host-core/src/plugins/providers.rs
@@ -266,16 +266,46 @@ pub(crate) fn sync_plugin_providers(
),
None => {}
}
- let (existing_config, existing_secret_ref): (Option<String>, Option<String>) = db
+ let (existing_config, existing_secret_ref, existing_base_url, existing_api_style): (
+ Option<String>,
+ Option<String>,
+ Option<String>,
+ Option<String>,
+ ) = db
.conn()
.query_row(
- "SELECT config_json, secret_ref FROM providers WHERE id = ?1",
+ "SELECT config_json, secret_ref, base_url, api_style FROM providers WHERE id = ?1",
params![row_id],
- |row| Ok((row.get(0)?, row.get(1)?)),
+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
)
.optional()?
- .unwrap_or((None, None));
+ .unwrap_or((None, None, None, None));
let models = providers::normalize_model_bindings(&provider.models);
+ // A declaration that moves the endpoint abandons the answer the previous
+ // one produced: the cached rows carry no endpoint of their own, so the
+ // discovery cache is dropped and the next probe records the new answer.
+ let endpoint_changed = existing_config.is_some()
+ && (existing_base_url.as_deref().unwrap_or("").trim()
+ != provider.base_url.as_deref().unwrap_or("").trim()
+ || existing_api_style.as_deref().unwrap_or("") != provider.api_style);
+ // A declaration that no longer names a model forgets that model's
+ // cached row, exactly as a user save does: the row would otherwise keep
+ // describing a model this provider stopped declaring. The row above is
+ // already known to be absent or owned by this plugin.
+ let removed_models = providers::config_model_bindings(
+ existing_config.as_deref().unwrap_or("{}"),
+ None,
+ &row_id,
+ )
+ .into_iter()
+ .filter(|binding| {
+ !models
+ .iter()
+ .any(|model| model.id.eq_ignore_ascii_case(&binding.id))
+ })
+ .map(|binding| binding.id)
+ .collect::<Vec<_>>();
+ providers::forget_cached_models(db, &row_id, &removed_models)?;
// The merge replaces only the model bindings: headers and the OAuth
// account label a login flow wrote are not this function's to drop.
let config = providers::config_with_model_bindings(
@@ -338,6 +368,11 @@ pub(crate) fn sync_plugin_providers(
secret_ref,
now
])?;
+ if endpoint_changed {
+ let declared_model_ids: Vec<String> =
+ models.iter().map(|model| model.id.clone()).collect();
+ providers::forget_missing_discovered_models(db, &row_id, &declared_model_ids)?;
+ }
written += 1;
}
let declared_rows: Vec<String> = declared
diff --git a/crates/host-core/src/plugins/providers/tests.rs b/crates/host-core/src/plugins/providers/tests.rs
index 9b6191f88..f7563a88f 100644
--- a/crates/host-core/src/plugins/providers/tests.rs
+++ b/crates/host-core/src/plugins/providers/tests.rs
@@ -178,6 +178,118 @@ fn sync_is_declarative_and_drops_a_removed_declaration() {
assert!(!secrets.has(&key_ref));
}
+/// A declaration that stops naming a model forgets the row cached for it, the
+/// same way a user save does: the cache must not keep describing a model this
+/// provider no longer declares.
+#[test]
+fn dropping_a_declared_model_forgets_its_cached_row() {
+ let (_dir, db, secrets) = test_context();
+ let declared = declared_providers(&manifest());
+ sync_plugin_providers(&db, &secrets, "demo.provider", &declared, true).unwrap();
+ let row_id = "plugin:demo.provider:demo";
+ providers::cache_discovered_models(
+ &db,
+ row_id,
+ &[
+ providers::DiscoveredModelInput {
+ model_id: "demo-large".into(),
+ display_name: "Demo Large".into(),
+ capabilities: vec!["text".into()],
+ context_window: Some(200_000),
+ },
+ providers::DiscoveredModelInput {
+ model_id: "demo-small".into(),
+ display_name: "Demo Small".into(),
+ capabilities: vec!["text".into()],
+ context_window: Some(32_000),
+ },
+ providers::DiscoveredModelInput {
+ model_id: "demo-extra".into(),
+ display_name: "Demo Extra".into(),
+ capabilities: vec!["text".into()],
+ context_window: None,
+ },
+ ],
+ )
+ .unwrap();
+ assert_eq!(providers::list_models(&db, Some(row_id)).unwrap().len(), 3);
+
+ let mut value = serde_json::to_value(manifest()).unwrap();
+ value["contributes"]["providers"][0]["models"] = json!([{
+ "id": "demo-large",
+ "name": "Demo Large",
+ "contextWindow": 200000,
+ "maxTokens": 8192
+ }]);
+ let shrunk: PluginManifest = serde_json::from_value(value).unwrap();
+ sync_plugin_providers(
+ &db,
+ &secrets,
+ "demo.provider",
+ &declared_providers(&shrunk),
+ true,
+ )
+ .unwrap();
+
+ let mut cached: Vec<String> = providers::list_models(&db, Some(row_id))
+ .unwrap()
+ .into_iter()
+ .map(|model| model.model_id)
+ .collect();
+ cached.sort();
+ assert_eq!(cached, vec!["demo-extra", "demo-large"]);
+}
+
+/// A declaration that moves its endpoint abandons the discovery answer the
+/// previous one produced: those rows describe a service this provider no longer
+/// points at.
+#[test]
+fn moving_a_declared_endpoint_forgets_the_discovered_answer() {
+ let (_dir, db, secrets) = test_context();
+ let declared = declared_providers(&manifest());
+ sync_plugin_providers(&db, &secrets, "demo.provider", &declared, true).unwrap();
+ let row_id = "plugin:demo.provider:demo";
+ providers::cache_discovered_models(
+ &db,
+ row_id,
+ &[
+ providers::DiscoveredModelInput {
+ model_id: "demo-large".into(),
+ display_name: "Demo Large".into(),
+ capabilities: vec!["text".into()],
+ context_window: Some(200_000),
+ },
+ providers::DiscoveredModelInput {
+ model_id: "demo-remote-only".into(),
+ display_name: "Demo Remote Only".into(),
+ capabilities: vec!["text".into()],
+ context_window: Some(8_000),
+ },
+ ],
+ )
+ .unwrap();
+ assert_eq!(providers::list_models(&db, Some(row_id)).unwrap().len(), 2);
+
+ let mut value = serde_json::to_value(manifest()).unwrap();
+ value["contributes"]["providers"][0]["baseUrl"] = json!("https://mirror.example.com/v1");
+ let moved: PluginManifest = serde_json::from_value(value).unwrap();
+ sync_plugin_providers(
+ &db,
+ &secrets,
+ "demo.provider",
+ &declared_providers(&moved),
+ true,
+ )
+ .unwrap();
+
+ let cached: Vec<String> = providers::list_models(&db, Some(row_id))
+ .unwrap()
+ .into_iter()
+ .map(|model| model.model_id)
+ .collect();
+ assert_eq!(cached, vec!["demo-large"]);
+}
+
#[test]
fn sync_keeps_provider_config_it_does_not_own() {
let (_dir, db, secrets) = test_context();
diff --git a/crates/host-core/src/providers.rs b/crates/host-core/src/providers.rs
index d4f7b2f5e..6041d94e6 100644
--- a/crates/host-core/src/providers.rs
+++ b/crates/host-core/src/providers.rs
@@ -34,8 +34,9 @@ pub(crate) use repository::{delete_provider_row, provider_exists, provider_owner
pub(crate) use catalog::{
config_model_bindings, config_thinking_levels_override, config_with_model_bindings,
- ensure_model_bindings_update_safe, normalize_model_bindings, CANONICAL_THINKING_LEVELS,
- DEFAULT_CONTEXT_WINDOW, DEFAULT_MAX_TOKENS, PROVIDER_SELECT,
+ ensure_model_bindings_update_safe, forget_cached_models, forget_missing_discovered_models,
+ normalize_model_bindings, CANONICAL_THINKING_LEVELS, DEFAULT_CONTEXT_WINDOW,
+ DEFAULT_MAX_TOKENS, PROVIDER_SELECT,
};
pub(crate) use credentials::{
build_provider_config_json, config_headers, config_oauth_account_label,
diff --git a/crates/host-core/src/providers/catalog.rs b/crates/host-core/src/providers/catalog.rs
index ab1567189..76472dfd6 100644
--- a/crates/host-core/src/providers/catalog.rs
+++ b/crates/host-core/src/providers/catalog.rs
@@ -322,8 +322,14 @@ pub fn list_models(db: &Database, provider_id: Option<&str>) -> Result<Vec<Model
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}
-/// Merge live discovery results into the durable catalog cache. User-created
-/// rows are authoritative and stale cache remains available if discovery fails.
+/// Merge live discovery results into the durable catalog cache.
+///
+/// The answer is the service's current list, so it replaces the previous one:
+/// rows this answer no longer contains are dropped with it, while the rows the
+/// user owns survive — a configured binding, including a hand-typed id, is the
+/// user's configuration rather than the service's answer. A failed or empty
+/// probe never reaches this call, so a cache is only ever narrowed by an answer
+/// that actually arrived.
pub fn cache_discovered_models(
db: &Database,
provider_id: &str,
@@ -367,9 +373,104 @@ pub fn cache_discovered_models(
}
}
tx.commit()?;
+ // The rows above are the answer; anything discovered before that the answer
+ // no longer names belongs to a model the endpoint stopped publishing.
+ let mut keep: Vec<String> = models
+ .iter()
+ .map(|model| model.model_id.trim().to_string())
+ .filter(|model_id| !model_id.is_empty())
+ .collect();
+ keep.extend(configured_model_ids(db, provider_id)?);
+ forget_missing_discovered_models(db, provider_id, &keep)?;
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 raw: Option<String> = db
+ .conn()
+ .query_row(
+ "SELECT config_json FROM providers WHERE id = ?1",
+ params![provider_id],
+ |row| row.get(0),
+ )
+ .optional()?;
+ let Some(raw) = raw else {
+ return Ok(Vec::new());
+ };
+ Ok(config_model_bindings(&raw, None, 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::*;
diff --git a/crates/host-core/src/providers/repository.rs b/crates/host-core/src/providers/repository.rs
index 36f8b9f0a..60eac0509 100644
--- a/crates/host-core/src/providers/repository.rs
+++ b/crates/host-core/src/providers/repository.rs
@@ -283,6 +283,19 @@ pub fn update_provider(
if input.models.is_some() {
ensure_model_bindings_update_safe(&raw_config)?;
}
+ // The discovered answer belongs to the endpoint that produced it, and the
+ // cached rows carry no endpoint of their own: an edit that moves the address
+ // or the wire format has to drop that answer, or the picker would paint the
+ // previous service's models as this one's. Read before the update moves the
+ // fields into the row.
+ let endpoint_changed = input
+ .base_url
+ .as_deref()
+ .is_some_and(|value| value.trim() != current.base_url.as_deref().unwrap_or("").trim())
+ || input
+ .api_style
+ .as_deref()
+ .is_some_and(|value| value != current.api_style.as_deref().unwrap_or(""));
// Derive from the API key ref directly: `has_secret` now also covers an
// OAuth credential, so reusing it here would stamp an api_key ref onto a
// provider that only ever signed in with a vendor account.
@@ -366,6 +379,38 @@ pub fn update_provider(
now_ms(),
input.id
])?;
+ // A save that drops bindings also forgets their cached rows. The cache is
+ // the service's answer, and a model the user removed is no longer part of
+ // the configuration that answer belongs to; keeping the row would feed the
+ // deleted model's recorded limits back to the next add of the same id.
+ if let Some(models) = input.models.as_deref() {
+ let removed: Vec<String> = current
+ .models
+ .iter()
+ .filter(|binding| {
+ let id = binding.id.trim().to_lowercase();
+ !models
+ .iter()
+ .any(|model| model.id.trim().to_lowercase() == id)
+ })
+ .map(|binding| binding.id.clone())
+ .collect();
+ forget_cached_models(db, &input.id, &removed)?;
+ }
+ // A save that moves the endpoint drops the answer the previous one
+ // produced. The models the user configured stay: they are the configuration
+ // the save just wrote, not a cached answer.
+ if endpoint_changed {
+ let configured: Vec<String> = match input.models.as_ref() {
+ Some(models) => models.iter().map(|model| model.id.clone()).collect(),
+ None => current
+ .models
+ .iter()
+ .map(|binding| binding.id.clone())
+ .collect(),
+ };
+ forget_missing_discovered_models(db, &input.id, &configured)?;
+ }
get_provider(db, secrets, &input.id)
}
diff --git a/crates/host-core/src/providers/tests.rs b/crates/host-core/src/providers/tests.rs
index 3a6e9ec0f..6ddf7d8d5 100644
--- a/crates/host-core/src/providers/tests.rs
+++ b/crates/host-core/src/providers/tests.rs
@@ -890,7 +890,9 @@ fn discovered_models_are_cached_without_overwriting_user_rows() {
.unwrap();
let models = list_models(&db, Some(&provider.id)).unwrap();
- assert_eq!(models.len(), 3);
+ // The second answer names model-a and the user's row only, so the model it
+ // stopped publishing goes with the answer it belonged to.
+ assert_eq!(models.len(), 2);
let alpha = models
.iter()
.find(|model| model.model_id == "model-a")
@@ -898,7 +900,7 @@ fn discovered_models_are_cached_without_overwriting_user_rows() {
assert_eq!(alpha.display_name, "Alpha updated");
assert_eq!(alpha.capabilities, vec!["text", "reasoning"]);
assert_eq!(alpha.context_window, Some(256_000));
- assert!(models.iter().any(|model| model.model_id == "model-b"));
+ assert!(!models.iter().any(|model| model.model_id == "model-b"));
let custom = models
.iter()
.find(|model| model.model_id == "user-model")
@@ -908,6 +910,273 @@ fn discovered_models_are_cached_without_overwriting_user_rows() {
assert_eq!(custom.capabilities, vec!["tools"]);
}
+/// A model the user deleted and saved is no longer part of the configuration,
+/// so the parameters recorded for it go with it: keeping the row handed the
+/// deleted model's context window back to the next add of the same id, and kept
+/// it in the picker's cache-first paint.
+#[test]
+fn deleting_a_binding_and_saving_forgets_its_cached_parameters() {
+ let (_dir, db, secrets) = test_context();
+ let provider = create_provider(
+ &db,
+ &secrets,
+ ProviderCreateInput {
+ name: "Catalog".into(),
+ vendor_key: None,
+ provider_type: None,
+ protocol: None,
+ base_url: Some("http://localhost:11434/v1".into()),
+ auth_kind: Some("none".into()),
+ models: Some(vec![
+ binding_with_limits("model-a", 128_000, 8_192),
+ binding_with_limits("model-b", 32_000, 4_096),
+ ]),
+ default_model_id: Some("model-a".into()),
+ secret_value: None,
+ api_style: Some("chat_completions".into()),
+ oauth_account_label: None,
+ headers: None,
+ context_window: None,
+ max_output_tokens: None,
+ temperature: None,
+ supports_reasoning: None,
+ supported_thinking_levels: None,
+ },
+ )
+ .unwrap();
+ cache_discovered_models(
+ &db,
+ &provider.id,
+ &[
+ DiscoveredModelInput {
+ model_id: "model-a".into(),
+ display_name: "Alpha".into(),
+ capabilities: vec!["text".into()],
+ context_window: Some(128_000),
+ },
+ // The service spells it differently from the binding that drops it.
+ DiscoveredModelInput {
+ model_id: "MODEL-B".into(),
+ display_name: "Beta".into(),
+ capabilities: vec!["text".into()],
+ context_window: Some(32_000),
+ },
+ DiscoveredModelInput {
+ model_id: "model-c".into(),
+ display_name: "Gamma".into(),
+ capabilities: vec!["text".into()],
+ context_window: Some(64_000),
+ },
+ ],
+ )
+ .unwrap();
+ assert_eq!(list_models(&db, Some(&provider.id)).unwrap().len(), 3);
+
+ update_provider(
+ &db,
+ &secrets,
+ ProviderUpdateInput {
+ id: provider.id.clone(),
+ name: None,
+ vendor_key: None,
+ provider_type: None,
+ protocol: None,
+ base_url: None,
+ auth_kind: None,
+ models: Some(vec![binding_with_limits("model-a", 128_000, 8_192)]),
+ default_model_id: None,
+ secret_value: None,
+ api_style: None,
+ oauth_account_label: None,
+ headers: None,
+ context_window: None,
+ max_output_tokens: None,
+ temperature: None,
+ supports_reasoning: None,
+ supported_thinking_levels: None,
+ enabled: None,
+ },
+ )
+ .unwrap()
+ .unwrap();
+
+ let cached = list_models(&db, Some(&provider.id)).unwrap();
+ assert_eq!(
+ cached
+ .iter()
+ .map(|model| model.model_id.as_str())
+ .collect::<Vec<_>>(),
+ vec!["model-a", "model-c"]
+ );
+}
+
+/// The cache is the service's answer, so an answer that no longer publishes a
+/// model drops that model's row — while a row the user owns survives it: a
+/// hand-typed id and a configured binding are the user's configuration, not the
+/// service's answer.
+#[test]
+fn a_probe_answer_forgets_models_it_no_longer_publishes() {
+ let (_dir, db, secrets) = test_context();
+ let provider = create_provider(
+ &db,
+ &secrets,
+ ProviderCreateInput {
+ name: "Catalog".into(),
+ vendor_key: None,
+ provider_type: None,
+ protocol: None,
+ base_url: Some("http://localhost:11434/v1".into()),
+ auth_kind: Some("none".into()),
+ models: Some(vec![binding_with_limits("custom-model", 8_000, 1_024)]),
+ default_model_id: Some("custom-model".into()),
+ secret_value: None,
+ api_style: Some("chat_completions".into()),
+ oauth_account_label: None,
+ headers: None,
+ context_window: None,
+ max_output_tokens: None,
+ temperature: None,
+ supports_reasoning: None,
+ supported_thinking_levels: None,
+ },
+ )
+ .unwrap();
+ // A hand-typed id the service never published, recorded as the user's own.
+ db.conn()
+ .execute(
+ "INSERT INTO models (
+ provider_id, model_id, display_name, source,
+ capabilities_json, updated_at
+ ) VALUES (?1, 'pinned-model', 'Pinned', 'user', '[]', ?2)",
+ params![provider.id, now_ms()],
+ )
+ .unwrap();
+ let answer = |discovered: &[&str]| -> Vec<DiscoveredModelInput> {
+ discovered
+ .iter()
+ .map(|id| DiscoveredModelInput {
+ model_id: (*id).to_string(),
+ display_name: (*id).to_string(),
+ capabilities: vec!["text".into()],
+ context_window: Some(64_000),
+ })
+ .collect()
+ };
+
+ // This answer publishes the hand-typed id too, so its row is discovered.
+ cache_discovered_models(
+ &db,
+ &provider.id,
+ &answer(&["model-a", "model-b", "custom-model"]),
+ )
+ .unwrap();
+ assert_eq!(list_models(&db, Some(&provider.id)).unwrap().len(), 4);
+
+ // The endpoint stopped publishing model-b.
+ cache_discovered_models(&db, &provider.id, &answer(&["model-a"])).unwrap();
+
+ let mut cached: Vec<String> = list_models(&db, Some(&provider.id))
+ .unwrap()
+ .into_iter()
+ .map(|model| model.model_id)
+ .collect();
+ cached.sort();
+ assert_eq!(
+ cached,
+ vec!["custom-model", "model-a", "pinned-model"],
+ "the unpublished model goes with the answer; the user's rows stay"
+ );
+}
+
+/// The discovered answer belongs to the endpoint that produced it: saving a new
+/// address drops the previous one's answer, while the models the user configured
+/// stay exactly as saved.
+#[test]
+fn changing_the_endpoint_forgets_the_discovered_answer() {
+ let (_dir, db, secrets) = test_context();
+ let provider = create_provider(
+ &db,
+ &secrets,
+ ProviderCreateInput {
+ name: "Relay".into(),
+ vendor_key: None,
+ provider_type: None,
+ protocol: None,
+ base_url: Some("http://localhost:11434/v1".into()),
+ auth_kind: Some("none".into()),
+ models: Some(vec![binding_with_limits("model-a", 128_000, 8_192)]),
+ default_model_id: Some("model-a".into()),
+ secret_value: None,
+ api_style: Some("chat_completions".into()),
+ oauth_account_label: None,
+ headers: None,
+ context_window: None,
+ max_output_tokens: None,
+ temperature: None,
+ supports_reasoning: None,
+ supported_thinking_levels: None,
+ },
+ )
+ .unwrap();
+ cache_discovered_models(
+ &db,
+ &provider.id,
+ &[
+ DiscoveredModelInput {
+ model_id: "model-a".into(),
+ display_name: "Alpha".into(),
+ capabilities: vec!["text".into()],
+ context_window: Some(128_000),
+ },
+ DiscoveredModelInput {
+ model_id: "model-b".into(),
+ display_name: "Beta".into(),
+ capabilities: vec!["text".into()],
+ context_window: Some(32_000),
+ },
+ ],
+ )
+ .unwrap();
+ assert_eq!(list_models(&db, Some(&provider.id)).unwrap().len(), 2);
+
+ // A URL-only edit: the model list is untouched, so only the endpoint rule can
+ // be what drops the old answer.
+ update_provider(
+ &db,
+ &secrets,
+ ProviderUpdateInput {
+ id: provider.id.clone(),
+ name: None,
+ vendor_key: None,
+ provider_type: None,
+ protocol: None,
+ base_url: Some("http://localhost:9000/v1".into()),
+ auth_kind: None,
+ models: None,
+ default_model_id: None,
+ secret_value: None,
+ api_style: None,
+ oauth_account_label: None,
+ headers: None,
+ context_window: None,
+ max_output_tokens: None,
+ temperature: None,
+ supports_reasoning: None,
+ supported_thinking_levels: None,
+ enabled: None,
+ },
+ )
+ .unwrap()
+ .unwrap();
+
+ let cached: Vec<String> = list_models(&db, Some(&provider.id))
+ .unwrap()
+ .into_iter()
+ .map(|model| model.model_id)
+ .collect();
+ assert_eq!(cached, vec!["model-a"]);
+}
+
#[test]
fn an_oauth_credential_alone_makes_the_provider_ready() {
let (_dir, db, secrets) = test_context();
diff --git a/docs/spec/03-runtime/13-model-catalog-and-selection.md b/docs/spec/03-runtime/13-model-catalog-and-selection.md
index f67f02f24..8610a7595 100644
--- a/docs/spec/03-runtime/13-model-catalog-and-selection.md
+++ b/docs/spec/03-runtime/13-model-catalog-and-selection.md
@@ -112,8 +112,8 @@ contract changes are required.
1. The stored secret is resolved, so an edit needs no retyped key.
2. `discoverProviderModels` asks the service (`/models` or the per-style
equivalent). A non-empty answer wins, is enriched per model through
- `modelsDevCatalog.findModel`, is written back to the model cache, and is
- reported as `source: "remote"`.
+ `modelsDevCatalog.findModel`, replaces what the model cache held for that
+ provider, and is reported as `source: "remote"`.
3. Only if the endpoint published nothing usable —no route, an auth error, or an
empty list— does `modelsForProvider` supply the vendor's published models,
reported as `source: "catalog"` together with any discovery error so the UI
@@ -124,11 +124,30 @@ contract changes are required.
An OAuth vendor account skips step 2 — it has no key to probe with, and pi-ai
already knows which models the subscription allows.
+The cache belongs to the configuration it was recorded for: saving a provider
+without a binding it used to have deletes that model's cached row, so a deleted
+model's recorded limits, capabilities and display name are not handed back to
+the next add of the same id, and the id leaves the picker's cache-first paint.
+Only the ids a save dropped are touched — the rest of the discovered list is the
+service's answer, and a model the service still publishes is recorded again by
+the next probe, described by the service rather than by a stale answer.
+
+The answer also replaces the previous one. A probe that no longer publishes a
+model drops that model's row, so the pane stops painting a model the endpoint
+retired and a hand-typed id stops inheriting its old limits; a row whose source
+is not discovery — the user's own — is never dropped this way, and a configured
+binding stays visible even when the service stops listing it. Cached rows carry
+no endpoint of their own, so a save that moves the base URL or the wire format
+drops the answer the previous endpoint produced, and the next probe records the
+new one. A failed or empty probe is not an answer: it never reaches the cache,
+so it can neither replace nor narrow what is stored.
+
The picker never dumps the raw host error into the model list. A failed probe
-with no rows shows a classified one-line summary (auth, missing list, rate
-limit, timeout, network, invalid response, or HTTP status) plus a short hint
-to add an ID manually. A failed probe that still has cached rows keeps those
-rows and shows the same summary as a compact banner.
+that leaves no rows shows a one-line "the list is missing" label in the empty
+pane, while the classified reason (auth, missing list, rate limit, timeout,
+network, invalid response, or HTTP status) is reported once through the app
+toast stack. A refused probe that still has cached rows keeps those rows and
+reports the same reason as a toast.
### Subagent editor
diff --git a/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md b/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md
index 1387c71f8..7c2b2c84a 100644
--- a/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md
+++ b/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md
@@ -162,6 +162,18 @@ still-existing account. Refresh does not rewrite configured models or history.
- 允许自定义模型ID
- 仍然允许具有已知模型 ID 的提供商
+缓存只属于记录它时的那份配置:保存时移除了某个模型绑定,该模型的缓存行一并
+遗忘,因此被删模型的上下文、能力与显示名不会在下次添加同一 ID 时被交还,该 ID
+也不再出现在选择器的“先画缓存”里。只清理这次保存真正移除的 ID——其余发现结果
+是服务的回答;服务仍在提供该模型时,下一次探测会按服务的描述重新记录。
+
+新的回答同样会替换旧回答:一次探测不再提供的模型,其缓存行随之删除,选择器
+不会再按旧参数画出已被端点下线的模型,手输 ID 也不会继承它过去的参数;来源不是
+发现的(用户自己的)行永不因此删除,已配置的绑定即使服务不再列出也仍然可见。
+缓存行本身不记录端点,因此保存时改动接口地址或接口格式会丢弃上一个端点给出的
+回答,由下一次探测记录新的回答。失败或空回答不算回答:它进不了缓存,因此既不能
+替换也不能收窄已存内容。
+
## 8. 目录项架构
```ts