Skip to content

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

fix(models): persist discovery membership without deleting bindings

sinolinefaa782f63cf
diff --git a/apps/desktop/electron/main/ipc/provider-ipc.ts b/apps/desktop/electron/main/ipc/provider-ipc.ts
index 1bfd6a88a..cb2de157a 100644
--- a/apps/desktop/electron/main/ipc/provider-ipc.ts
+++ b/apps/desktop/electron/main/ipc/provider-ipc.ts
@@ -4,6 +4,7 @@ import {
inferEndpointProfile,
normalizeApiStyle,
type ModelBinding,
+ type ModelInfo,
type ProviderReorderInput,
type OAuthRespondInput,
} from "@pi-desktop/shared";
@@ -401,6 +402,18 @@ export function registerProviderIpc({
} else {
await modelsDevCatalog.ensureLoaded();
}
+ type CachedModel = Pick<ModelInfo, "modelId" | "displayName"> & Partial<ModelInfo>;
+ const usesSavedDiscoveryEndpoint = provider
+ && baseUrl.replace(/\/+$/, "") === (provider.baseUrl ?? "").trim().replace(/\/+$/, "")
+ && apiStyle === (provider.apiStyle ?? "chat_completions");
+ const cachedModels = provider && (req.source === "cache" || usesSavedDiscoveryEndpoint)
+ ? (await host.call<{ models: CachedModel[] }>("providers.listModels", {
+ providerId: provider.id,
+ })).models ?? []
+ : [];
+ let discoveryStates = new Map(cachedModels.map((model) => [
+ model.modelId.trim().toLowerCase(), model.discoveryState,
+ ]));
const decorate = (
model: {
modelId: string;
@@ -410,6 +423,7 @@ export function registerProviderIpc({
contextWindow?: number;
maxTokens?: number;
source?: "bundled" | "discovered" | "user";
+ discoveryState?: ModelInfo["discoveryState"];
},
// Vendor accounts can span wire APIs, so a model may need a style of
// its own rather than the row's. The endpoint is per call too: the live
@@ -458,6 +472,7 @@ export function registerProviderIpc({
// Catalog enrichment must not turn a configured-only row into
// evidence that the endpoint still serves it.
source: model.source ?? info.source,
+ discoveryState: model.discoveryState ?? discoveryStates.get(model.modelId.trim().toLowerCase()),
modelId: model.modelId,
displayName: info.displayName || modelConfig.name,
providerId: provider?.id ?? "",
@@ -504,7 +519,7 @@ export function registerProviderIpc({
return [...discovered, ...extra];
};
- const cacheForCurrentProvider = async (models: unknown[]) => {
+ const cacheForCurrentProvider = async (models: unknown[], complete: boolean) => {
if (!provider || req.source === "cache") return;
const savedBaseUrl = (provider.baseUrl ?? "").trim().replace(/\/+$/, "");
const requestBaseUrl = baseUrl.replace(/\/+$/, "");
@@ -521,10 +536,14 @@ export function registerProviderIpc({
requestBaseUrl &&
(latestProvider?.apiStyle ?? "chat_completions") === apiStyle;
if (endpointStillCurrent) {
- await host!.call("providers.cacheModels", {
+ const cached = await host!.call<{ models: CachedModel[] }>("providers.cacheModels", {
providerId: provider.id,
models,
+ complete,
});
+ discoveryStates = new Map((cached.models ?? []).map((model) => [
+ model.modelId.trim().toLowerCase(), model.discoveryState,
+ ]));
}
} catch (e) {
logger.app("provider", "warn", "model cache update failed", {
@@ -549,6 +568,7 @@ export function registerProviderIpc({
{
modelId: option.modelId,
displayName: option.modelId,
+ discoveryState: "published",
},
option.apiStyle,
),
@@ -568,22 +588,13 @@ export function registerProviderIpc({
}
if (req.source === "cache" && provider) {
- const cached = await host.call<{
- models: Array<{
- modelId: string;
- displayName: string;
- capabilities?: string[];
- contextWindow?: number;
- source?: "bundled" | "discovered" | "user";
- }>;
- }>("providers.listModels", { providerId: provider.id });
// Keep every configured binding visible when the endpoint cache is
// partial or empty. Decorating these ids through models.dev or generic
// defaults preserves the per-model state for offline editing too.
- const cachedById = new Map(cached.models.map((model) => [model.modelId, model]));
+ const cachedById = new Map(cachedModels.map((model) => [model.modelId.trim().toLowerCase(), model]));
for (const binding of provider.models ?? []) {
- if (!cachedById.has(binding.id)) {
- cachedById.set(binding.id, {
+ if (!cachedById.has(binding.id.trim().toLowerCase())) {
+ cachedById.set(binding.id.trim().toLowerCase(), {
modelId: binding.id,
displayName: binding.id,
source: "user" as const,
@@ -655,10 +666,12 @@ export function registerProviderIpc({
...(outcome.apiStyleHint ? { apiStyleHint: outcome.apiStyleHint } : {}),
evidence: outcome.evidence.type,
};
- const models = outcome.models.map((model) => decorate(model));
+ const models = outcome.models.map((model) => decorate({
+ ...model, discoveryState: "published",
+ }));
// Only what the endpoint actually served is cached; a configured id
// it never offered must not be recorded as discovered.
- await cacheForCurrentProvider(models);
+ await cacheForCurrentProvider(models, outcome.complete);
return {
models: withConfiguredBindings(models),
source: "remote" as const,
@@ -707,7 +720,7 @@ export function registerProviderIpc({
const fallback = fallbackModelId
? [decorate({ modelId: fallbackModelId, displayName: fallbackModelId })]
: [];
- return { models: fallback, source: "fallback", ...resolution, error: discoveryError };
+ return { models: withConfiguredBindings(fallback), source: "fallback", ...resolution, error: discoveryError };
},
);
diff --git a/apps/desktop/electron/main/model-discovery.ts b/apps/desktop/electron/main/model-discovery.ts
index 9c1e1a3b9..efd3023fd 100644
--- a/apps/desktop/electron/main/model-discovery.ts
+++ b/apps/desktop/electron/main/model-discovery.ts
@@ -256,7 +256,28 @@ export function modelListRequest(opts: {
};
}
+/** A single page is authoritative only when it contains valid rows and no
+ * continuation marker. Unknown pagination is never guessed from row count. */
+export function modelListIsComplete(style: string | undefined, body: unknown): boolean {
+ const record = asRecord(body);
+ if (record && (record.has_more === true || record.hasMore === true
+ || record.nextPageToken || record.next_page_token || record.next_page
+ || record.next || record.partial === true || record.truncated === true
+ || asRecord(record.links)?.next || asRecord(record.pagination)?.next
+ || asRecord(record.pagination)?.has_more)) return false;
+ const rows = Array.isArray(body) ? body
+ : Array.isArray(record?.data) ? record.data
+ : Array.isArray(record?.models) ? record.models : [];
+ if (rows.length === 0) return false;
+ const total = record?.total ?? record?.total_count ?? asRecord(record?.pagination)?.total;
+ if (typeof total === "number" && total > rows.length) return false;
+ return rows.every((row) => normalizeModelList(style,
+ style === "google_models" || style === "google_generative_ai"
+ ? { models: [row] } : { data: [row] }).length === 1);
+}
+
export type ModelListProbe = {
+ complete?: boolean;
/** The URL that answered, after any same-origin redirect. */
url: string;
status: number;
@@ -386,13 +407,15 @@ export async function probeModelList(opts: {
status: res.status,
});
}
+ const body: unknown = await res.json();
+ const style = opts.discoveryStyle ?? opts.apiStyle;
return {
url,
status: res.status,
- models: normalizeModelList(
- opts.discoveryStyle ?? opts.apiStyle,
- await res.json(),
- ),
+ models: normalizeModelList(style, body),
+ complete: res.status !== 206
+ && !/rel="?next/i.test(res.headers.get("link") ?? "")
+ && modelListIsComplete(style, body),
};
}
throw new Error("model list request followed too many redirects");
diff --git a/apps/desktop/electron/main/provider-endpoint-probe.ts b/apps/desktop/electron/main/provider-endpoint-probe.ts
index ade9b9c27..d5ac76da3 100644
--- a/apps/desktop/electron/main/provider-endpoint-probe.ts
+++ b/apps/desktop/electron/main/provider-endpoint-probe.ts
@@ -36,6 +36,7 @@ export type DiscoveryAttempt = {
};
export type DiscoveryProbeOutcome = {
+ complete: boolean;
models: DiscoveredModel[];
/** The base URL that answered: what the row should store and display. */
effectiveBaseUrl: string;
@@ -136,6 +137,7 @@ export async function probeDiscoveryCandidates(
return {
outcome: {
models: result.models,
+ complete: result.complete === true,
effectiveBaseUrl: candidate.baseUrl,
discoveryStyle: candidate.discoveryStyle,
...(candidate.apiStyleHint ? { apiStyleHint: candidate.apiStyleHint } : {}),
diff --git a/apps/desktop/src/components/settings/ModelSelectionPanes.tsx b/apps/desktop/src/components/settings/ModelSelectionPanes.tsx
index 8068d5106..349eeb8c5 100644
--- a/apps/desktop/src/components/settings/ModelSelectionPanes.tsx
+++ b/apps/desktop/src/components/settings/ModelSelectionPanes.tsx
@@ -266,9 +266,10 @@ export function ModelSelectionPanes({
const visibleRows = useMemo(() => {
// The service pane follows a live answer. Configured-only rows remain in
// the chosen pane, including hand-typed IDs absent from discovery.
+ const listedRows = rows.filter((row) => row.info?.discoveryState !== "unlisted");
const availableRows = discovery.source === "remote"
- ? rows.filter((row) => row.info && row.info.source !== "user")
- : rows;
+ ? listedRows.filter((row) => row.info && row.info.source !== "user")
+ : listedRows;
const needle = modelQuery.trim().toLowerCase();
if (!needle) return availableRows;
return availableRows.filter(
diff --git a/apps/desktop/src/lib/composer-models.ts b/apps/desktop/src/lib/composer-models.ts
index f64785c1d..6e3aa504e 100644
--- a/apps/desktop/src/lib/composer-models.ts
+++ b/apps/desktop/src/lib/composer-models.ts
@@ -39,7 +39,9 @@ export function composerModelsForProvider(
imageGeneration?: ImageGenerationBindings | null,
): ModelInfo[] {
return configuredModelIds(provider).filter((modelId) =>
- !isImageGenerationModel(imageGeneration, provider.id, modelId),
+ !isImageGenerationModel(imageGeneration, provider.id, modelId)
+ && !(discovered ?? []).some((model) =>
+ sameComposerModelId(model.modelId, modelId) && model.discoveryState === "unlisted"),
).map((modelId) => {
const metadata = (discovered ?? []).find((model) =>
sameComposerModelId(model.modelId, modelId),
diff --git a/apps/desktop/test/composer-models.test.mjs b/apps/desktop/test/composer-models.test.mjs
index 4e2148795..2c91e2427 100644
--- a/apps/desktop/test/composer-models.test.mjs
+++ b/apps/desktop/test/composer-models.test.mjs
@@ -408,3 +408,20 @@ test("trusted matches retain published capabilities and explicit empty bindings"
assert.deepEqual(thinkingProviderForModel(provider, "route/model", [reasoning]).supportedThinkingLevels, ["low", "high"]);
assert.equal(thinkingProviderForModel({ ...provider, models: [binding("route/model")] }, "route/model", [reasoning]).supportsReasoning, false);
});
+
+test("unlisted configured models leave the menu without deleting bindings or changing the current default", () => {
+ const provider = { id: "relay", defaultModelId: "beta", models: [binding("alpha"), binding("beta"), binding("manual")] };
+ const original = structuredClone(provider);
+ const snapshot = [
+ { ...model("alpha"), discoveryState: "published" },
+ { ...model("BETA"), discoveryState: "unlisted" },
+ ];
+ assert.deepEqual(composerModelsForProvider(provider, snapshot).map(row => row.modelId), ["alpha", "manual"]);
+ assert.deepEqual(composerModelsForProvider(provider, JSON.parse(JSON.stringify(snapshot))).map(row => row.modelId), ["alpha", "manual"]);
+ assert.deepEqual(provider, original);
+ snapshot[1].discoveryState = "published";
+ assert.deepEqual(composerModelsForProvider(provider, snapshot).map(row => row.modelId), ["alpha", "beta", "manual"]);
+ assert.deepEqual(composerModelsForProvider({ id: "relay", defaultModelId: "beta" }, [
+ { ...model("beta"), discoveryState: "unlisted" },
+ ]), []);
+});
diff --git a/apps/desktop/test/model-advanced-capabilities.test.mjs b/apps/desktop/test/model-advanced-capabilities.test.mjs
index 8e1010564..87e9e9c19 100644
--- a/apps/desktop/test/model-advanced-capabilities.test.mjs
+++ b/apps/desktop/test/model-advanced-capabilities.test.mjs
@@ -174,7 +174,7 @@ test("a configured model keeps its published record when discovery omits it", ()
// Discovery stays the authority on what the service offers: only the rows it
// returned are cached as discovered.
const liveReturn = mainSource.slice(
- mainSource.indexOf("await cacheForCurrentProvider(models);"),
+ mainSource.indexOf("await cacheForCurrentProvider(models, outcome.complete);"),
);
assert.match(liveReturn.slice(0, 260), /models: withConfiguredBindings\(models\)/);
});
diff --git a/apps/desktop/test/model-discovery-precedence.test.mjs b/apps/desktop/test/model-discovery-precedence.test.mjs
index 7e3b42b79..5b1bf86a9 100644
--- a/apps/desktop/test/model-discovery-precedence.test.mjs
+++ b/apps/desktop/test/model-discovery-precedence.test.mjs
@@ -56,7 +56,7 @@ test("a catalog-derived list is reported as such, not as the service's answer",
// The live branch keeps its own distinct source value. What it returns may be
// widened with the user's configured bindings, but only the rows the endpoint
// actually served are cached, which the next test pins.
- const liveReturn = handler.slice(handler.indexOf("await cacheForCurrentProvider(models);"));
+ const liveReturn = handler.slice(handler.indexOf("await cacheForCurrentProvider(models, outcome.complete);"));
assert.match(liveReturn.slice(0, 240), /source: "remote" as const/);
});
@@ -76,7 +76,7 @@ test("every returned model is enriched through the published models.dev catalog
// `decorate` is what attaches published limits, modalities and thinking
// levels, so all three branches must route through it.
assert.match(handler, /const modelsDevModel = .*modelsDevCatalog\.publishedModelFor/);
- assert.match(handler, /outcome\.models\.map\(\(model\) => decorate\(model\)\)/);
+ assert.match(handler, /outcome\.models\.map\(\(model\) => decorate\(\{\s*\.\.\.model, discoveryState: "published",\s*\}\)\)/);
assert.match(handler, /catalogModels\.map\(\(model\) => decorate\(model\)\)/);
});
diff --git a/apps/desktop/test/model-discovery.test.mjs b/apps/desktop/test/model-discovery.test.mjs
index 103346520..2793b177c 100644
--- a/apps/desktop/test/model-discovery.test.mjs
+++ b/apps/desktop/test/model-discovery.test.mjs
@@ -177,3 +177,15 @@ test("optional custom headers are attached to discovery requests", () => {
});
assert.equal(google.headers["User-Agent"], undefined);
});
+
+test("only valid nonempty complete model responses can reconcile missing ids", async () => {
+ const { modelListIsComplete } = await import("../electron/main/model-discovery.ts");
+ const data = [{ id: "alpha" }];
+ assert.equal(modelListIsComplete("openai_models", { data }), true);
+ assert.equal(modelListIsComplete("google_models", { models: [{ name: "models/alpha" }] }), true);
+ for (const body of [ { data: [] }, { data: [...data, {}] }, { data, has_more: true },
+ { data, nextPageToken: "page-2" }, { data, links: { next: "/models?page=2" } },
+ { models: [{ name: "models/alpha" }], nextPageToken: "page-2" } ]) {
+ assert.equal(modelListIsComplete("openai_models", body), false);
+ }
+});
diff --git a/apps/desktop/test/provider-model-list-refresh.test.mjs b/apps/desktop/test/provider-model-list-refresh.test.mjs
index 9bf1cae74..dd387c563 100644
--- a/apps/desktop/test/provider-model-list-refresh.test.mjs
+++ b/apps/desktop/test/provider-model-list-refresh.test.mjs
@@ -15,7 +15,7 @@ const { createProviderCatalogRuntime } = await import("../electron/main/runtime/
const { bindingForCustomModel, formatTokenCount, IPC } = await import("@pi-desktop/shared");
// Run the real IPC discovery and settings picker; mock only HTTP and host persistence.
-test("refresh removes revoked service rows and preserves configured chat bindings", async (t) => {
+test("refresh hides unlisted chat choices and preserves editable configured bindings", async (t) => {
const row = {
id: "relay", name: "Relay", vendorKey: "custom", enabled: true,
authKind: "none", hasSecret: false, apiStyle: "chat_completions",
@@ -46,9 +46,14 @@ test("refresh removes revoked service rows and preserves configured chat binding
getHost: () => ({ call: async (method, input) => {
if (method === "providers.list") return { providers: [row] };
if (method === "providers.get") return { provider: row };
+ if (method === "providers.listModels") return { models: cachedModels };
if (method === "providers.cacheModels") {
- cachedModels = input?.models ?? [];
- return {};
+ const byId = new Map(cachedModels.map(model => [model.modelId, {
+ ...model, discoveryState: input.complete ? "unlisted" : model.discoveryState,
+ }]));
+ for (const model of input.models) byId.set(model.modelId, { ...model, discoveryState: "published" });
+ cachedModels = [...byId.values()];
+ return { models: cachedModels };
}
return {};
} }),
@@ -128,8 +133,11 @@ test("refresh removes revoked service rows and preserves configured chat binding
]);
assert.deepEqual(
composerModelsForProvider(row, discovery.models).map((model) => model.modelId),
- ["gpt-6-sol", "claude-sonnet-4-5", "gpt-6-astra", "new-model"],
+ ["gpt-6-sol", "new-model"],
);
+ const hydrated = await handlers.get(IPC.invoke.providersListModels)({ providerId: row.id, source: "cache" });
+ assert.deepEqual(composerModelsForProvider(row, hydrated.models).map(model => model.modelId), ["gpt-6-sol", "new-model"]);
+ assert.equal(hydrated.models.find(model => model.modelId === "claude-sonnet-4-5").discoveryState, "unlisted");
assert.equal(
limitsFor(html, "provider-models-row-id", "provider-models-row-limits", "new-model"),
"— · —",
diff --git a/crates/host-core/src/db.rs b/crates/host-core/src/db.rs
index 518e0005a..0ec286825 100644
--- a/crates/host-core/src/db.rs
+++ b/crates/host-core/src/db.rs
@@ -7,7 +7,7 @@ pub(crate) use serde_json::Value;
pub(crate) use std::path::{Path, PathBuf};
/// Current SQLite schema version.
-pub const SCHEMA_VERSION: i64 = 24;
+pub const SCHEMA_VERSION: i64 = 25;
/// Absolute approval deadline for a newly submitted Plan or Goal proposal.
pub const PLAN_APPROVAL_TIMEOUT_MS: i64 = 30 * 60 * 1000;
@@ -17,6 +17,7 @@ pub const NOTIFICATION_KEEP: i64 = 200;
mod migrations;
mod model;
+mod model_discovery_migration;
mod plugin_providers_migration;
mod project_groups;
mod repositories;
diff --git a/crates/host-core/src/db/model_discovery_migration.rs b/crates/host-core/src/db/model_discovery_migration.rs
new file mode 100644
index 000000000..a3fdb4f9e
--- /dev/null
+++ b/crates/host-core/src/db/model_discovery_migration.rs
@@ -0,0 +1,28 @@
+use super::{create_migration_backup, Connection, Context, Path, Result};
+
+/// Existing discovered rows establish past publication, not binding provenance.
+/// User-owned rows remain unknown. No saved configuration is changed.
+pub(crate) fn migrate(conn: &Connection, path: &Path) -> Result<()> {
+ let backup = create_migration_backup(conn, path, 24)?;
+ let tx = conn.unchecked_transaction()?;
+ let has_column: bool = tx.query_row(
+ "SELECT EXISTS(SELECT 1 FROM pragma_table_info('models') WHERE name = 'discovery_state')",
+ [],
+ |row| row.get(0),
+ )?;
+ if !has_column {
+ tx.execute_batch(
+ "ALTER TABLE models ADD COLUMN discovery_state TEXT
+ CHECK (discovery_state IN ('published', 'unlisted'));
+ UPDATE models SET discovery_state = 'published' WHERE source = 'discovered';",
+ )?;
+ }
+ tx.pragma_update(None, "user_version", 25i64)?;
+ tx.commit().with_context(|| {
+ format!(
+ "commit schema v24 to v25 migration; backup {} remains",
+ backup.display()
+ )
+ })?;
+ Ok(())
+}
diff --git a/crates/host-core/src/db/repositories.rs b/crates/host-core/src/db/repositories.rs
index 30bc39d30..178e1cb55 100644
--- a/crates/host-core/src/db/repositories.rs
+++ b/crates/host-core/src/db/repositories.rs
@@ -207,6 +207,9 @@ impl Database {
23 => {
migrate_v23_to_v24(&conn, path)?;
}
+ 24 => {
+ super::model_discovery_migration::migrate(&conn, path)?;
+ }
legacy @ 1..=6 => {
let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");
drop(conn);
@@ -257,6 +260,10 @@ impl Database {
}
if migrated_version == 23 {
migrate_v23_to_v24(&conn, path)?;
+ migrated_version = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?;
+ }
+ if migrated_version == 24 {
+ super::model_discovery_migration::migrate(&conn, path)?;
}
let db = Self { conn, data_dir };
db.boot_maintenance()?;
diff --git a/crates/host-core/src/db/schema.rs b/crates/host-core/src/db/schema.rs
index 2237f0519..29ad6a4f1 100644
--- a/crates/host-core/src/db/schema.rs
+++ b/crates/host-core/src/db/schema.rs
@@ -80,6 +80,7 @@ CREATE TABLE models (
context_window INTEGER,
max_output_tokens INTEGER,
deprecated INTEGER NOT NULL DEFAULT 0,
+ discovery_state TEXT CHECK (discovery_state IN ('published', 'unlisted')),
updated_at INTEGER NOT NULL,
PRIMARY KEY (provider_id, model_id)
) WITHOUT ROWID;
diff --git a/crates/host-core/src/db/tests.rs b/crates/host-core/src/db/tests.rs
index f710de61e..205fd8597 100644
--- a/crates/host-core/src/db/tests.rs
+++ b/crates/host-core/src/db/tests.rs
@@ -2192,3 +2192,31 @@ fn migrates_v21_to_v22_replaces_session_index() {
"idx_sessions_updated_id should be created"
);
}
+
+#[test]
+fn v24_model_discovery_upgrade_preserves_rows_and_reopens() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("pi.sqlite");
+ {
+ let db = Database::open(&path).unwrap();
+ db.conn().execute_batch("ALTER TABLE models DROP COLUMN discovery_state;
+ INSERT INTO providers(id, name, type, protocol, auth_kind, config_json, created_at, updated_at)
+ VALUES ('fixture', 'Fixture', 'openai_compatible', 'openai_compatible', 'none', '{}', 1, 1);
+ INSERT INTO models(provider_id, model_id, display_name, source, updated_at)
+ VALUES ('fixture', 'known', 'Known', 'discovered', 1), ('fixture', 'manual', 'Manual', 'user', 1);
+ PRAGMA user_version = 24;").unwrap();
+ }
+ let db = Database::open(&path).unwrap();
+ assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);
+ assert!(migration_backup_path(&path, 24).exists());
+ let models = crate::providers::list_models(&db, Some("fixture")).unwrap();
+ assert_eq!(models.len(), 2);
+ assert_eq!(models[0].discovery_state.as_deref(), Some("published"));
+ assert!(models[1].discovery_state.is_none());
+ drop(db);
+ let db = Database::open(&path).unwrap();
+ assert_eq!(
+ crate::providers::list_models(&db, Some("fixture")).unwrap(),
+ models
+ );
+}
diff --git a/crates/host-core/src/plugins/providers/tests.rs b/crates/host-core/src/plugins/providers/tests.rs
index bab05ca21..6278a8e98 100644
--- a/crates/host-core/src/plugins/providers/tests.rs
+++ b/crates/host-core/src/plugins/providers/tests.rs
@@ -100,9 +100,9 @@ fn a_new_database_carries_the_owner_column_at_the_current_schema_version() {
// v17 added the owner column, v18 the turn-queue priority column,
// v19 session omit, v21 the session Todo checklist, and v22 the
// session-list index, v23 the session title source, and v24 the worktree
- // registry. A fresh database is stamped with the newest version, so the
+ // registry; v25 adds model discovery state. A fresh database is stamped with the newest version, so the
// column set is the current one.
- assert_eq!(SCHEMA_VERSION, 24);
+ assert_eq!(SCHEMA_VERSION, 25);
let version: i64 = db
.conn()
.query_row("PRAGMA user_version", [], |row| row.get(0))
@@ -190,6 +190,7 @@ fn empty_api_key_model_list_uses_the_cached_endpoint_discovery() {
capabilities: vec!["text".to_string()],
context_window: Some(128_000),
}],
+ true,
)
.unwrap();
@@ -274,6 +275,7 @@ fn dropping_a_declared_model_forgets_its_cached_row() {
context_window: None,
},
],
+ true,
)
.unwrap();
assert_eq!(providers::list_models(&db, Some(row_id)).unwrap().len(), 3);
@@ -330,6 +332,7 @@ fn moving_a_declared_endpoint_forgets_the_discovered_answer() {
context_window: Some(8_000),
},
],
+ true,
)
.unwrap();
assert_eq!(providers::list_models(&db, Some(row_id)).unwrap().len(), 2);
diff --git a/crates/host-core/src/providers/catalog.rs b/crates/host-core/src/providers/catalog.rs
index 0f2de9869..4c5150559 100644
--- a/crates/host-core/src/providers/catalog.rs
+++ b/crates/host-core/src/providers/catalog.rs
@@ -287,7 +287,7 @@ pub fn list_models(db: &Database, provider_id: Option<&str>) -> Result<Vec<Model
let (sql, bind_provider) = match provider_id {
Some(id) => (
"SELECT provider_id, model_id, display_name, source,
- capabilities_json, context_window
+ capabilities_json, context_window, discovery_state
FROM models
WHERE provider_id = ?1
ORDER BY display_name COLLATE NOCASE, model_id",
@@ -295,7 +295,7 @@ pub fn list_models(db: &Database, provider_id: Option<&str>) -> Result<Vec<Model
),
None => (
"SELECT provider_id, model_id, display_name, source,
- capabilities_json, context_window
+ capabilities_json, context_window, discovery_state
FROM models
ORDER BY provider_id, display_name COLLATE NOCASE, model_id",
None,
@@ -306,6 +306,7 @@ pub fn list_models(db: &Database, provider_id: Option<&str>) -> Result<Vec<Model
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)?,
@@ -324,33 +325,42 @@ 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.
-///
-/// 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.
+/// 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
- ) VALUES (?1, ?2, ?3, 'discovered', ?4, ?5, ?6)
+ capabilities_json, context_window, updated_at, discovery_state
+ ) VALUES (?1, ?2, ?3, 'discovered', ?4, ?5, ?6, 'published')
ON CONFLICT(provider_id, model_id) DO UPDATE SET
display_name = excluded.display_name,
capabilities_json = excluded.capabilities_json,
context_window = excluded.context_window,
- updated_at = excluded.updated_at
+ updated_at = excluded.updated_at,
+ discovery_state = 'published'
WHERE models.source != 'user'",
)?;
for model in models {
@@ -364,6 +374,14 @@ pub fn cache_discovered_models(
} 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'
+ WHERE provider_id = ?1 AND lower(model_id) = lower(?2)
+ AND source = 'discovered'",
+ params![provider_id, model_id],
+ )?;
changed += stmt.execute(params![
provider_id,
model_id,
@@ -374,16 +392,32 @@ pub fn cache_discovered_models(
])?;
}
}
+ 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()?;
- // 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)
}
@@ -428,18 +462,18 @@ pub(crate) fn forget_cached_models(
/// 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
+ let saved: Option<(String, Option<String>)> = db
.conn()
.query_row(
- "SELECT config_json FROM providers WHERE id = ?1",
+ "SELECT config_json, default_model_id FROM providers WHERE id = ?1",
params![provider_id],
- |row| row.get(0),
+ |row| Ok((row.get(0)?, row.get(1)?)),
)
.optional()?;
- let Some(raw) = raw else {
+ let Some((raw, default_model_id)) = saved else {
return Ok(Vec::new());
};
- Ok(config_model_bindings(&raw, None, provider_id)
+ Ok(config_model_bindings(&raw, default_model_id, provider_id)
.into_iter()
.map(|binding| binding.id)
.collect())
diff --git a/crates/host-core/src/providers/model.rs b/crates/host-core/src/providers/model.rs
index 1af5a54c6..92da8e05d 100644
--- a/crates/host-core/src/providers/model.rs
+++ b/crates/host-core/src/providers/model.rs
@@ -178,6 +178,9 @@ pub struct ModelBinding {
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ModelCatalogItem {
+ /// Endpoint-list membership, not proof of whether inference will succeed.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub discovery_state: Option<String>,
pub provider_id: String,
pub model_id: String,
pub display_name: String,
diff --git a/crates/host-core/src/providers/repository.rs b/crates/host-core/src/providers/repository.rs
index 027648787..bf21a1964 100644
--- a/crates/host-core/src/providers/repository.rs
+++ b/crates/host-core/src/providers/repository.rs
@@ -472,6 +472,10 @@ pub fn update_provider(
.collect(),
};
forget_missing_discovered_models(db, &input.id, &configured)?;
+ db.conn().execute(
+ "UPDATE models SET discovery_state = NULL WHERE provider_id = ?1",
+ params![input.id],
+ )?;
}
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 497be4896..70c4f8355 100644
--- a/crates/host-core/src/providers/tests.rs
+++ b/crates/host-core/src/providers/tests.rs
@@ -948,6 +948,7 @@ fn discovered_models_are_cached_without_overwriting_user_rows() {
context_window: Some(128_000),
},
],
+ true,
)
.unwrap();
assert_eq!(changed, 2);
@@ -969,6 +970,7 @@ fn discovered_models_are_cached_without_overwriting_user_rows() {
context_window: None,
},
],
+ true,
)
.unwrap();
@@ -1051,6 +1053,7 @@ fn deleting_a_binding_and_saving_forgets_its_cached_parameters() {
context_window: Some(64_000),
},
],
+ true,
)
.unwrap();
assert_eq!(list_models(&db, Some(&provider.id)).unwrap().len(), 3);
@@ -1151,12 +1154,56 @@ fn a_probe_answer_forgets_models_it_no_longer_publishes() {
&db,
&provider.id,
&answer(&["model-a", "model-b", "custom-model"]),
+ true,
)
.unwrap();
assert_eq!(list_models(&db, Some(&provider.id)).unwrap().len(), 4);
+ let original_bindings = get_provider(&db, &secrets, &provider.id)
+ .unwrap()
+ .unwrap()
+ .models;
// The endpoint stopped publishing model-b.
- cache_discovered_models(&db, &provider.id, &answer(&["model-a"])).unwrap();
+ cache_discovered_models(&db, &provider.id, &answer(&["model-a"]), true).unwrap();
+
+ let states = serde_json::to_value(list_models(&db, Some(&provider.id)).unwrap()).unwrap();
+ let state = |id: &str| {
+ states
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|row| row["modelId"] == id)
+ .unwrap()["discoveryState"]
+ .clone()
+ };
+ assert_eq!(
+ state("custom-model"),
+ "unlisted",
+ "saved bindings need durable discovery state"
+ );
+ assert_eq!(state("model-a"), "published");
+ assert!(
+ state("pinned-model").is_null(),
+ "user-owned rows are not reconciled"
+ );
+ assert_eq!(
+ get_provider(&db, &secrets, &provider.id)
+ .unwrap()
+ .unwrap()
+ .models,
+ original_bindings
+ );
+ let reopened = Database::open(&db.data_dir().join("pi.sqlite")).unwrap();
+ assert_eq!(
+ serde_json::to_value(list_models(&reopened, Some(&provider.id)).unwrap()).unwrap(),
+ states
+ );
+ cache_discovered_models(&db, &provider.id, &[], true).unwrap();
+ assert_eq!(
+ serde_json::to_value(list_models(&db, Some(&provider.id)).unwrap()).unwrap(),
+ states,
+ "an empty answer must not invalidate the last successful snapshot"
+ );
let mut cached: Vec<String> = list_models(&db, Some(&provider.id))
.unwrap()
@@ -1169,6 +1216,34 @@ fn a_probe_answer_forgets_models_it_no_longer_publishes() {
vec!["custom-model", "model-a", "pinned-model"],
"the unpublished model goes with the answer; the user's rows stay"
);
+ cache_discovered_models(&db, &provider.id, &answer(&["new-page"]), false).unwrap();
+ let rows = list_models(&db, Some(&provider.id)).unwrap();
+ assert_eq!(
+ rows.iter()
+ .find(|row| row.model_id == "model-a")
+ .unwrap()
+ .discovery_state
+ .as_deref(),
+ Some("published")
+ );
+ assert_eq!(
+ rows.iter()
+ .find(|row| row.model_id == "custom-model")
+ .unwrap()
+ .discovery_state
+ .as_deref(),
+ Some("unlisted")
+ );
+ cache_discovered_models(&db, &provider.id, &answer(&["custom-model"]), true).unwrap();
+ let rows = list_models(&db, Some(&provider.id)).unwrap();
+ assert_eq!(
+ rows.iter()
+ .find(|row| row.model_id == "custom-model")
+ .unwrap()
+ .discovery_state
+ .as_deref(),
+ Some("published")
+ );
}
/// The discovered answer belongs to the endpoint that produced it: saving a new
@@ -1218,6 +1293,7 @@ fn changing_the_endpoint_forgets_the_discovered_answer() {
context_window: Some(32_000),
},
],
+ true,
)
.unwrap();
assert_eq!(list_models(&db, Some(&provider.id)).unwrap().len(), 2);
@@ -1258,6 +1334,29 @@ fn changing_the_endpoint_forgets_the_discovered_answer() {
.map(|model| model.model_id)
.collect();
assert_eq!(cached, vec!["model-a"]);
+ let reset = list_models(&db, Some(&provider.id)).unwrap();
+ assert!(reset.iter().all(|model| model.discovery_state.is_none()));
+ cache_discovered_models(
+ &db,
+ &provider.id,
+ &[DiscoveredModelInput {
+ model_id: "new-endpoint-model".into(),
+ display_name: "New".into(),
+ capabilities: vec![],
+ context_window: None,
+ }],
+ true,
+ )
+ .unwrap();
+ let rows = list_models(&db, Some(&provider.id)).unwrap();
+ assert!(
+ rows.iter()
+ .find(|model| model.model_id == "model-a")
+ .unwrap()
+ .discovery_state
+ .is_none(),
+ "the new endpoint never published the old configured id"
+ );
}
#[test]
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 6cc895b64..0e2e7870f 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -79,6 +79,8 @@ struct JsonRpcNotification {
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CacheModelsParams {
+ #[serde(default)]
+ complete: bool,
provider_id: String,
models: Vec<DiscoveredModelInput>,
}
@@ -2601,9 +2603,13 @@ async fn handle_request(
let input: CacheModelsParams = serde_json::from_value(params)
.map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
let st = state.lock().await;
- let cached =
- providers::cache_discovered_models(&st.db, &input.provider_id, &input.models)
- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
+ let cached = providers::cache_discovered_models(
+ &st.db,
+ &input.provider_id,
+ &input.models,
+ input.complete,
+ )
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
let models = providers::list_models(&st.db, Some(&input.provider_id))
.map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
Ok(json!({ "cached": cached, "models": models }))
diff --git a/crates/host-core/src/turn_queue.rs b/crates/host-core/src/turn_queue.rs
index 92e9b3733..6ca93814e 100644
--- a/crates/host-core/src/turn_queue.rs
+++ b/crates/host-core/src/turn_queue.rs
@@ -532,7 +532,7 @@ mod tests {
assert_eq!(entries[0].content, "existing");
assert!(entries[0].user_message_id.is_none());
assert!(entries[0].voice_origin.is_none());
- assert_eq!(crate::db::SCHEMA_VERSION, 24);
+ assert_eq!(crate::db::SCHEMA_VERSION, 25);
}
#[test]
diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.md
index 004f687a8..8bc6deda6 100644
--- a/docs/spec/03-runtime/04-data-storage.md
+++ b/docs/spec/03-runtime/04-data-storage.md
@@ -1,4 +1,4 @@
-# 04. Data Storage (Schema v23)
+# 04. Data Storage (Schema v25)
## 0. Ownership decision
@@ -571,6 +571,7 @@ CREATE TABLE models (
context_window INTEGER,
max_output_tokens INTEGER,
deprecated INTEGER NOT NULL DEFAULT 0,
+ discovery_state TEXT CHECK (discovery_state IN ('published', 'unlisted')),
updated_at INTEGER NOT NULL,
PRIMARY KEY (provider_id, model_id)
) WITHOUT ROWID;
@@ -580,6 +581,14 @@ Refresh (spec 13 §6/§9) upserts `discovered` rows and **never overwrites
`source='user'`** rows. Recent-model MRU stays in `kv(cache)` — it is a
bounded display list, not relational data.
+Schema v25 adds nullable `discovery_state`, distinct from metadata deprecation.
+The v24 upgrade backs up first, adds the field transactionally, and marks
+existing discovered rows as past publication evidence. User-owned rows remain
+unknown. No provider configuration, credentials, sessions, or turns are changed.
+Configured missing rows retain an `unlisted` marker across restart; an endpoint
+change clears it. Older apps refuse the newer schema rather than interpreting
+it incorrectly; rollback requires the pre-migration backup.
+
### 4.5 sessions
```sql
@@ -1582,7 +1591,7 @@ truncating at a guessed position.
Sessions, providers, and settings from the old file are not carried over;
the archive remains for manual recovery. All pre-v7 migration code
(v1 `settings.sqlite` import, v2→v6 chain) is deleted.
-- Fresh installs run the full v23 DDL directly.
+- Fresh installs run the full v25 DDL directly.
- **Schema v7 first reaches v8, then uses the guarded path.** The v7→v8
migration is followed by the same guarded v8→v15 migration; schema-v9 and
schema-v10 databases take the same guarded path and receive an exact readable
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index 1966ae230..7e5a92e13 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -791,7 +791,11 @@ against a live host, and replaying one after the final row would be wrong.
deletes the stored key. Returns `{ provider }`, or `null` for an unknown id
- `providers.getSecret` — main/host only, never reachable from the renderer
- `providers.listModels` / `providers.cacheModels` — discovered model rows
- and their host-side cache (ADR 0027 / ADR 0134)
+ and their host-side cache (ADR 0027 / ADR 0134). `cacheModels` accepts optional
+ `complete` (default false). Model rows expose optional `discoveryState`
+ (`published` / `unlisted`); omission is unknown. Only complete, nonempty
+ snapshots reconcile missing discovered rows, without changing configuration.
+ See provider-config schema for the conservative refresh and consumer rules.
- `providers.testConnection`
### Agent capabilities (skills, subagents, MCP servers)
diff --git a/docs/spec/03-runtime/12-provider-config-schema.md b/docs/spec/03-runtime/12-provider-config-schema.md
index 7cbd481c0..4482dca4b 100644
--- a/docs/spec/03-runtime/12-provider-config-schema.md
+++ b/docs/spec/03-runtime/12-provider-config-schema.md
@@ -672,10 +672,21 @@ The canonical DDL lives in [04-data-storage](04-data-storage.md) (D086). Summary
never overwrites an edit or delete made while it was in flight.
### `providers.cacheModels` (internal host RPC)
-- in: `{ providerId, models: DiscoveredModelInput[] }`
-- behavior: transactionally upsert successful live discovery into `models` as
- `source='discovered'`; never overwrite `source='user'` rows and never delete
- prior cache rows on a failed or partial refresh
+- in: `{ providerId, models: DiscoveredModelInput[], complete?: boolean }`
+- behavior: atomically upsert discovered rows with `discoveryState: "published"`.
+ Only an explicitly complete, nonempty, valid answer marks previously published
+ missing rows `"unlisted"`; missing configured rows are retained with that state,
+ while unconfigured discovered rows may be pruned. An omitted `complete` means
+ additive-only for backward compatibility. User-owned rows, bindings, defaults,
+ and conversation history are never rewritten by discovery.
+- failure/partial behavior: failed or empty responses cannot narrow the cache;
+ paginated, truncated, malformed-row, and larger-reported-total responses are
+ additive-only. The client does not claim to detect undisclosed truncation.
+- consumers: settings keep saved bindings editable; Composer excludes explicitly
+ unlisted rows from ordinary and recent choices. Manual ids never discovered
+ remain selectable. Reappearance restores publication; endpoint edits clear
+ previous publication evidence. Existing selections/defaults are not switched.
+ Unlisted means absent from the last complete list, not proven uncallable.
- out: `{ cached: number, models: ModelCatalogItem[] }`
- raw secrets and authorization headers are never part of this call
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 bf61c3f75..13000b67a 100644
--- a/docs/spec/03-runtime/13-model-catalog-and-selection.md
+++ b/docs/spec/03-runtime/13-model-catalog-and-selection.md
@@ -148,20 +148,22 @@ Only the ids a save dropped are touched — the rest of the discovered list is t
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 in the chosen-model pane even when the service stops
-listing it. After a live refresh, the service-model pane displays only rows
-actually served, excluding configured-only rows marked `source: "user"`.
-Catalog enrichment preserves that origin independently of published metadata;
-cache, catalog and manual fallbacks still expose configured rows for editing.
-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.
+A complete, nonempty discovery answer updates endpoint-list membership
+atomically. Previously published configured models missing from that answer
+remain saved and editable, but carry `discoveryState: "unlisted"` through live
+results, offline fallback, and restart hydration. Composer excludes these rows
+from ordinary and recent model choices; it never changes a session's current
+model or the saved default automatically. A missing id is not proof of failed
+inference. Manually configured ids never discovered are unknown, not unlisted,
+and remain selectable. Republishing a model restores its normal choices.
+
+Unconfigured missing discovered rows are pruned, and user-owned rows remain
+untouched. The settings service-model pane excludes unlisted and configured-only
+rows; the chosen pane retains bindings for editing. Changing the endpoint or
+wire format clears old discovery state. Failed, empty, explicitly paginated,
+truncated, or malformed-row answers do not invalidate missing rows. Partial
+answers may add/update the rows they actually contain. Unknown server-side
+truncation cannot be inferred from a successful response alone.
The picker never dumps the raw host error into the model list. A failed probe
that leaves no rows shows a one-line "the list is missing" label in the empty
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 1e8b666fd..6ca6d2593 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -8,6 +8,23 @@
## 1. Goals
+### E2E model discovery membership
+
+- **Entry:** `node scripts/e2e-model-discovery-state.mjs` after building Host,
+ shared, agent-runtime and host-runtime in the task worktree.
+- **Environment:** Real isolated Host process and SQLite; production provider
+ IPC and Composer selection; simulated HTTP only, no credentials/live app.
+- **Sequence:** Discover two configured models and retain a never-discovered
+ manual id; remove one; refresh offline; restart Host; read cache; republish;
+ change id casing; send partial, malformed, and empty lists; change endpoint.
+- **Expected:** Missing previously published models leave normal/recent choices
+ without deleting bindings or changing defaults. Offline/restart cannot
+ resurrect them. Reappearance restores them. Manual ids and partial refreshes
+ remain safe; old endpoint state does not contaminate the new endpoint.
+- **Component coverage:** `provider-model-list-refresh.test.mjs` also renders
+ the actual settings panes and verifies saved bindings remain editable.
+
+
### E2E-PI-130-kernel-upgrade
- **Preconditions:** Exact Pi 1.3.0 pins and migrated patches in a dedicated
diff --git a/package.json b/package.json
index 7001f9a89..b91451644 100644
--- a/package.json
+++ b/package.json
@@ -38,6 +38,7 @@
"test:e2e:composer-occlusion": "node scripts/e2e-theme-surfaces.mjs --dock-mask-only",
"test:e2e:composer-autocomplete": "node scripts/e2e-composer-autocomplete.mjs",
"test:e2e:composer-ime-slash": "node scripts/e2e-composer-ime-stack.mjs",
+ "test:e2e:model-discovery-state": "node scripts/e2e-model-discovery-state.mjs",
"test:e2e:composer-model-selection": "node scripts/e2e-composer-model-selection.mjs",
"test:e2e:composer-paste": "node scripts/e2e-composer-paste.mjs",
"test:e2e:transcript": "node scripts/e2e-transcript-render.mjs",
diff --git a/packages/shared/src/types/models.ts b/packages/shared/src/types/models.ts
index c5d8dcbca..64138cb17 100644
--- a/packages/shared/src/types/models.ts
+++ b/packages/shared/src/types/models.ts
@@ -329,6 +329,8 @@ export type ModelInfo = {
cost?: ModelCost;
interleaved?: ModelInterleaved;
status?: string;
+ /** Last endpoint-list membership; absence is unknown, not an inference failure. */
+ discoveryState?: "published" | "unlisted";
/** Provider-local upstream metadata, including models.dev adapter details. */
provider?: ModelProviderMetadata;
/** Model metadata extension published by models.dev. */
diff --git a/scripts/e2e-model-discovery-state.mjs b/scripts/e2e-model-discovery-state.mjs
new file mode 100644
index 000000000..d75e05d81
--- /dev/null
+++ b/scripts/e2e-model-discovery-state.mjs
@@ -0,0 +1,90 @@
+#!/usr/bin/env node
+// Real Host persistence, production IPC and Composer; only HTTP is simulated.
+import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { register } from "node:module";
+register(new URL("../apps/desktop/test/helpers/ts-import-hooks.mjs", import.meta.url));
+const { HostProcess } = await import("../packages/host-runtime/dist/index.js");
+const { registerProviderIpc } = await import("../apps/desktop/electron/main/ipc/provider-ipc.ts");
+const { ModelsDevCatalog } = await import("../apps/desktop/electron/main/models-dev-catalog.ts");
+const { createProviderCatalogRuntime } = await import("../apps/desktop/electron/main/runtime/provider-catalog.ts");
+const { composerModelsForProvider } = await import("../apps/desktop/src/lib/composer-models.ts");
+const { bindingForCustomModel, IPC } = await import("../packages/shared/dist/index.js");
+const root = fileURLToPath(new URL("..", import.meta.url));
+const dataDir = await mkdtemp(join(process.env.PI_SCRATCH_DIR ?? tmpdir(), "model-discovery-e2e-"));
+const originalFetch = globalThis.fetch;
+let host;
+let body = { data: [{ id: "alpha" }, { id: "beta" }] };
+let offline = false;
+try {
+ const boot = async () => {
+ host = new HostProcess({ binaryPath: join(root, "target/debug/pi-desktop-host-core"), dataDir, onStderr() {} });
+ await host.handshake();
+ };
+ await boot();
+ const { provider } = await host.call("providers.create", {
+ name: "Discovery fixture", baseUrl: "https://fixture.example/v1", authKind: "none",
+ apiStyle: "chat_completions", defaultModelId: "beta",
+ models: ["alpha", "beta", "manual"].map(bindingForCustomModel),
+ });
+ const catalog = new ModelsDevCatalog({ catalogPath: join(root, "apps/desktop/resources/models.dev/api.json") });
+ assert.equal(await catalog.loadLocal(), true);
+ globalThis.fetch = async () => {
+ if (offline) throw new Error("fixture offline");
+ return new Response(JSON.stringify(body), { headers: { "content-type": "application/json" } });
+ };
+ const wire = () => {
+ const runtime = createProviderCatalogRuntime({ getHost: () => host, modelsDevCatalog: catalog });
+ const handlers = new Map();
+ registerProviderIpc({ registrar: { handle: (key, handler) => handlers.set(key, handler) },
+ getHost: () => host, modelsDevCatalog: catalog, vendorOAuth: {}, logger: { app() {} }, ...runtime });
+ return (source = "refresh") => handlers.get(IPC.invoke.providersListModels)({ providerId: provider.id, source });
+ };
+ let list = wire();
+ const choices = result => composerModelsForProvider(provider, result.models).map(row => row.modelId);
+ assert.deepEqual(choices(await list()), ["alpha", "beta", "manual"]);
+ body = { data: [{ id: "alpha" }] };
+ assert.deepEqual(choices(await list()), ["alpha", "manual"]);
+ assert.equal((await host.call("providers.get", { id: provider.id })).provider.defaultModelId, provider.defaultModelId);
+ assert.deepEqual((await host.call("providers.get", { id: provider.id })).provider.models, provider.models);
+ offline = true;
+ assert.deepEqual(choices(await list()), ["alpha", "manual"]);
+ await host.dispose();
+ await boot();
+ list = wire();
+ assert.deepEqual(choices(await list("cache")), ["alpha", "manual"]);
+ offline = false;
+ body = { data: [{ id: "alpha" }, { id: "beta" }] };
+ assert.deepEqual(choices(await list()), ["alpha", "beta", "manual"]);
+ body = { data: [{ id: "ALPHA" }, { id: "BETA" }] };
+ assert.deepEqual(choices(await list()), ["alpha", "beta", "manual"]);
+ assert.deepEqual(choices(await list("cache")), ["alpha", "beta", "manual"]);
+ body = { data: [{ id: "alpha" }], has_more: true };
+ assert.deepEqual(choices(await list()), ["alpha", "beta", "manual"]);
+ body = { data: [{ id: "alpha" }, {}] };
+ assert.deepEqual(choices(await list()), ["alpha", "beta", "manual"]);
+ body = { data: [] };
+ assert.deepEqual(choices(await list()), ["alpha", "beta", "manual"]);
+ body = { data: [{ id: "alpha" }] };
+ assert.deepEqual(choices(await list()), ["alpha", "manual"]);
+ await host.call("providers.update", { id: provider.id, baseUrl: "https://other.example/v1" });
+ assert.deepEqual(choices(await list("cache")), ["alpha", "beta", "manual"]);
+ assert.deepEqual(choices(await list()), ["alpha", "beta", "manual"]);
+ const legacy = await host.call("providers.create", {
+ name: "Legacy fixture", baseUrl: "https://legacy.example/v1", authKind: "none",
+ defaultModelId: "legacy", apiStyle: "chat_completions",
+ });
+ await host.call("providers.cacheModels", { providerId: legacy.provider.id, complete: true,
+ models: [{ modelId: "legacy", displayName: "Legacy" }] });
+ const legacyCache = await host.call("providers.cacheModels", { providerId: legacy.provider.id, complete: true,
+ models: [{ modelId: "new", displayName: "New" }] });
+ assert.equal(legacyCache.models.find(row => row.modelId === "legacy").discoveryState, "unlisted");
+ console.log("PASS real Host -> IPC -> Composer: removal, offline fallback, restart, recovery, partial/empty answers, manual bindings and endpoint isolation");
+} finally {
+ globalThis.fetch = originalFetch;
+ if (host) await host.dispose();
+ await rm(dataDir, { recursive: true, force: true });
+}