Skip to content

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

fix(runtime): honor endpoint-reported context windows

zhanglinrun5145ff846fba
diff --git a/apps/desktop/electron/main/ipc/provider-ipc.ts b/apps/desktop/electron/main/ipc/provider-ipc.ts
index cb2de157a..61d8f2460 100644
--- a/apps/desktop/electron/main/ipc/provider-ipc.ts
+++ b/apps/desktop/electron/main/ipc/provider-ipc.ts
@@ -520,7 +520,7 @@ export function registerProviderIpc({
};
const cacheForCurrentProvider = async (models: unknown[], complete: boolean) => {
- if (!provider || req.source === "cache") return;
+ if (!host || !provider || req.source === "cache") return;
const savedBaseUrl = (provider.baseUrl ?? "").trim().replace(/\/+$/, "");
const requestBaseUrl = baseUrl.replace(/\/+$/, "");
const usesSavedEndpoint =
@@ -528,23 +528,15 @@ export function registerProviderIpc({
apiStyle === (provider.apiStyle ?? "chat_completions");
if (!usesSavedEndpoint) return;
try {
- const latestProvider = (await listRuntimeProviders()).find(
- (candidate) => candidate.id === provider.id,
- );
- const endpointStillCurrent =
- (latestProvider?.baseUrl ?? "").trim().replace(/\/+$/, "") ===
- requestBaseUrl &&
- (latestProvider?.apiStyle ?? "chat_completions") === apiStyle;
- if (endpointStillCurrent) {
- 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,
- ]));
- }
+ const cached = await host.call<{ models: CachedModel[] }>("providers.cacheModels", {
+ providerId: provider.id,
+ endpoint: { baseUrl: provider.baseUrl ?? "", apiStyle: provider.apiStyle ?? "" },
+ 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", {
data: {
@@ -671,7 +663,10 @@ export function registerProviderIpc({
}));
// Only what the endpoint actually served is cached; a configured id
// it never offered must not be recorded as discovered.
- await cacheForCurrentProvider(models, outcome.complete);
+ await cacheForCurrentProvider(models.map((model, index) => ({
+ ...model,
+ reportedContextWindow: outcome.models[index].contextWindow,
+ })), outcome.complete);
return {
models: withConfiguredBindings(models),
source: "remote" as const,
diff --git a/apps/desktop/electron/main/runtime/session-launch.ts b/apps/desktop/electron/main/runtime/session-launch.ts
index e62b1cec9..e20344515 100644
--- a/apps/desktop/electron/main/runtime/session-launch.ts
+++ b/apps/desktop/electron/main/runtime/session-launch.ts
@@ -22,6 +22,8 @@ import {
type McpServerRecord,
type Mode,
type ModelBinding,
+ type ModelInfo,
+ modelWireIdsEqual,
normalizeMode,
type Risk,
type SessionThinkingLevel,
@@ -322,6 +324,28 @@ export function createSessionLaunchRuntime({
return root;
}
+ async function discoveredContextWindow(provider: RuntimeProvider, modelId: string): Promise<number | undefined> {
+ try {
+ const { models } = await runtimeState.host!.call<{
+ models: (Pick<ModelInfo, "modelId" | "discoveryState"> & { reportedContextWindow?: number })[];
+ }>("providers.listModels", {
+ providerId: provider.id,
+ endpoint: { baseUrl: provider.baseUrl ?? "", apiStyle: provider.apiStyle ?? "" },
+ });
+ const window = models.find((model) =>
+ model.discoveryState === "published" && modelWireIdsEqual(model.modelId, modelId),
+ )?.reportedContextWindow;
+ return typeof window === "number" && Number.isSafeInteger(window) && window > 0
+ ? window
+ : undefined;
+ } catch (error) {
+ if (!isHostUnavailable(error)) {
+ logger.app("provider", "warn", "model discovery cache read failed", { data: String(error) });
+ }
+ return undefined;
+ }
+ }
+
async function resolveAgentRuntimeLaunch(
sessionId: string,
session: any,
@@ -434,9 +458,20 @@ export function createSessionLaunchRuntime({
// row that would undo it (#2120). The subagent path and enrichProvider
// already apply the binding; the main session was the one path that
// dropped it. Without a stored binding the catalog answer stands.
- const modelConfig = storedModel
+ const boundModelConfig = storedModel
? modelConfigWithBinding(catalogModelConfig, storedModel)
: catalogModelConfig;
+ // The saved endpoint can serve a different window from the published model.
+ // Follow its discovered value for catalog-owned bindings, like the inspector.
+ const discoveredWindow = !isVendorAccount && storedModel?.contextWindowSource === "catalog"
+ ? await discoveredContextWindow(provider, modelId)
+ : undefined;
+ const modelConfig = discoveredWindow === undefined ? boundModelConfig : {
+ ...boundModelConfig,
+ contextWindow: discoveredWindow,
+ catalogContextWindow: discoveredWindow,
+ limit: { ...boundModelConfig.limit, context: discoveredWindow },
+ };
// Only a pure image-generation endpoint is rejected: a model the user
// marked for image generation that also supports conversation keeps its
// chat eligibility (#2253). The catalog row (or a catalog miss on a custom
diff --git a/apps/desktop/test/discovered-context-session-launch.test.mjs b/apps/desktop/test/discovered-context-session-launch.test.mjs
new file mode 100644
index 000000000..e13339e08
--- /dev/null
+++ b/apps/desktop/test/discovered-context-session-launch.test.mjs
@@ -0,0 +1,142 @@
+import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { join } from "node:path";
+import test from "node:test";
+import { pathToFileURL } from "node:url";
+import { repositoryRoot } from "../../../scripts/e2e/boot.mjs";
+
+const root = repositoryRoot();
+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");
+
+test("session launch resolves the saved endpoint's context window", async (t) => {
+ const temp = await mkdtemp(join(root, "apps/desktop/.discovered-context-launch-test-"));
+ t.after(() => rm(temp, { recursive: true, force: true }));
+ const bundle = join(temp, "session-launch.mjs");
+ await build({
+ entryPoints: [join(root, "apps/desktop/electron/main/runtime/session-launch.ts")],
+ outfile: bundle,
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ packages: "external",
+ });
+ const { createSessionLaunchRuntime } = await import(pathToFileURL(bundle).href);
+
+ const modelId = "relay/large-model";
+ const binding = {
+ id: modelId,
+ contextWindow: 1_050_000,
+ contextWindowSource: "catalog",
+ maxTokens: 128_000,
+ thinkingLevels: [],
+ defaultThinkingLevel: null,
+ };
+ const provider = {
+ id: "relay",
+ name: "Relay",
+ authKind: "none",
+ baseUrl: "http://127.0.0.1:9/v1",
+ apiStyle: "responses",
+ models: [binding],
+ };
+ const discoveredModel = {
+ providerId: provider.id,
+ modelId,
+ source: "discovered",
+ discoveryState: "published",
+ contextWindow: 500_000,
+ reportedContextWindow: 500_000,
+ };
+ let cachedModels = [discoveredModel];
+ let cacheError;
+ const warnings = [];
+ const shell = {
+ id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true,
+ };
+ const host = {
+ isAvailable: () => true,
+ async call(method, params) {
+ switch (method) {
+ case "commandShells.list":
+ return { configuredId: "bash", effective: shell, fallback: false, choices: [shell] };
+ case "providers.list": return { providers: [provider] };
+ case "providers.getSecret": return {};
+ case "providers.listModels":
+ assert.equal(params.providerId, provider.id);
+ assert.deepEqual(params.endpoint, { baseUrl: provider.baseUrl, apiStyle: provider.apiStyle });
+ if (cacheError) throw cacheError;
+ return { models: cachedModels };
+ case "skills.disabledBuiltins": return { disabled: [] };
+ case "skills.active": return { skills: [] };
+ case "mcp.active": return { servers: [] };
+ case "agents.active": return { subagents: [] };
+ case "agents.disabledBuiltins": return { disabled: [] };
+ default: throw new Error(`Unexpected fixture Host method: ${method}`);
+ }
+ },
+ };
+ const launchRuntime = createSessionLaunchRuntime({
+ runtimeState: { host, sidecar: { setVendorAuthBindings() {} }, agentHostBridge: null },
+ logger: { app(...args) { warnings.push(args); } },
+ userMcp: { setRecords() {}, async toolsForProject() { return []; } },
+ plugins: { getTools: () => [], getSkills: () => [], listLoaded: () => [], getAgentExtensions: () => [] },
+ sessionProjects: new Map(),
+ dataDir: temp,
+ vendorOAuth: { async bindingFor() { return undefined; } },
+ modelsDevCatalog: {
+ async ensureLoaded() {},
+ configureAccount() {},
+ modelConfigFor: () => ({
+ source: "models.dev", name: "Large model", input: ["text"], reasoning: false,
+ contextWindow: 1_050_000, catalogContextWindow: 1_050_000, maxTokens: 128_000,
+ }),
+ },
+ getWorkspacePath: () => null,
+ pluginActiveInProject: () => true,
+ bindingForModel: (row, selectedId) => row.models?.find((entry) => entry.id === selectedId),
+ effectiveSubagentModelConfig: () => ({ modelConfig: undefined, capabilities: {} }),
+ normalizeThinkingLevel: () => "off",
+ });
+ async function launchModel() {
+ const { sidecarParams } = await launchRuntime.resolveAgentRuntimeLaunch(
+ "session-fixture", { providerId: provider.id, modelId }, { defaultMode: "agent" },
+ );
+ return sidecarParams.provider.modelConfig;
+ }
+
+ const discovered = await launchModel();
+ assert.equal(discovered.contextWindow, 500_000);
+ assert.equal(discovered.maxTokens, 128_000);
+
+ await t.test("a user window takes precedence", async () => {
+ provider.models = [{ ...binding, contextWindow: 300_000, contextWindowSource: "user" }];
+ assert.equal((await launchModel()).contextWindow, 300_000);
+ provider.models = [binding];
+ });
+
+ await t.test("a legacy binding keeps its saved window", async () => {
+ provider.models = [{ ...binding, contextWindow: 350_000, contextWindowSource: undefined }];
+ assert.equal((await launchModel()).contextWindow, 350_000);
+ provider.models = [binding];
+ });
+
+ await t.test("an enriched cache row without a report leaves the catalog window in place", async () => {
+ cachedModels = [{ ...discoveredModel, reportedContextWindow: undefined }];
+ assert.equal((await launchModel()).contextWindow, 1_050_000);
+ });
+
+ await t.test("another route and an unlisted record leave the catalog window in place", async () => {
+ cachedModels = [
+ { ...discoveredModel, modelId: "another-relay/large-model" },
+ { ...discoveredModel, discoveryState: "unlisted" },
+ ];
+ assert.equal((await launchModel()).contextWindow, 1_050_000);
+ });
+
+ await t.test("a cache read failure leaves the catalog window in place", async () => {
+ cacheError = new Error("fixture cache read failure");
+ assert.equal((await launchModel()).contextWindow, 1_050_000);
+ assert.ok(warnings.some(([, level, message]) => level === "warn" && message.includes("cache")));
+ });
+});
diff --git a/apps/desktop/test/model-cache.test.mjs b/apps/desktop/test/model-cache.test.mjs
index 5e76834f1..53b106093 100644
--- a/apps/desktop/test/model-cache.test.mjs
+++ b/apps/desktop/test/model-cache.test.mjs
@@ -26,7 +26,6 @@ test("saved provider discovery persists models in the host catalog", () => {
assert.match(mainSource, /providersRefreshModelCatalog/);
assert.doesNotMatch(mainSource, /modelsDevCatalog\.persist/);
assert.match(mainSource, /usesSavedEndpoint/);
- assert.match(mainSource, /endpointStillCurrent/);
assert.match(mainSource, /for \(const binding of provider\.models \?\? \[\]\)/);
assert.match(mainSource, /models\.dev or generic[\s\S]*per-model state/);
});
diff --git a/apps/desktop/test/provider-endpoint-metadata.test.mjs b/apps/desktop/test/provider-endpoint-metadata.test.mjs
index bee343765..df380cd7b 100644
--- a/apps/desktop/test/provider-endpoint-metadata.test.mjs
+++ b/apps/desktop/test/provider-endpoint-metadata.test.mjs
@@ -40,6 +40,7 @@ async function handlersFor(t, row, body) {
const original = globalThis.fetch;
const calls = [];
+ const cacheWrites = [];
globalThis.fetch = async (url) => {
calls.push(String(url));
return String(url).endsWith("/models") ? jsonResponse(body) : new Response("", { status: 404 });
@@ -52,10 +53,14 @@ async function handlersFor(t, row, body) {
registerProviderIpc({
registrar: { handle: (channel, handler) => handlers.set(channel, handler) },
getHost: () => ({
- call: async (method) => {
+ call: async (method, params) => {
if (method === "providers.list") return { providers: [row] };
if (method === "providers.getSecret") return { value: "sk-secret" };
if (method === "providers.get") return { provider: row };
+ if (method === "providers.cacheModels") {
+ cacheWrites.push(params);
+ return { models: params.models };
+ }
return {};
},
}),
@@ -75,6 +80,7 @@ async function handlersFor(t, row, body) {
return {
calls,
+ cacheWrites,
row,
result: await listModels({ providerId: row.id, source: "refresh" }),
/** The hand-typed id channel a picker uses when a user types an id in. */
@@ -149,14 +155,21 @@ test("a model-list capacity report takes precedence over catalog limits", async
name: "Relay",
baseUrl: "https://relay.example/v1",
});
- const { result } = await handlersFor(t, row, {
- data: [{ id: "claude-sonnet-4-5", context_length: 321_000, max_tokens: 12_345 }],
+ const { result, cacheWrites } = await handlersFor(t, row, {
+ data: [
+ { id: "claude-sonnet-4-5", context_length: 321_000, max_tokens: 12_345 },
+ { id: "some-private-model" },
+ ],
});
const [model] = result.models;
assert.equal(model.contextWindow, 321_000, "the endpoint reports its actual context window");
assert.equal(model.maxTokens, 12_345, "the endpoint reports its actual output limit");
assert.equal(model.catalogSource, "models.dev", "catalog metadata still identifies the model");
+ assert.deepEqual(cacheWrites[0].endpoint, { baseUrl: row.baseUrl, apiStyle: row.apiStyle });
+ assert.equal(cacheWrites[0].models[0].reportedContextWindow, 321_000);
+ assert.equal(cacheWrites[0].models[1].contextWindow, 128_000);
+ assert.equal(cacheWrites[0].models[1].reportedContextWindow, undefined);
});
test("a hand-typed id on the same relay answers with the same record", async (t) => {
diff --git a/crates/host-core/src/db.rs b/crates/host-core/src/db.rs
index 74e394237..944f7a1f1 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 = 33;
+pub const SCHEMA_VERSION: i64 = 34;
/// Absolute approval deadline for a newly submitted Plan or Goal proposal.
pub const PLAN_APPROVAL_TIMEOUT_MS: i64 = 30 * 60 * 1000;
diff --git a/crates/host-core/src/db/completion_report_migration_tests.rs b/crates/host-core/src/db/completion_report_migration_tests.rs
index 1c79e4800..b273a0b10 100644
--- a/crates/host-core/src/db/completion_report_migration_tests.rs
+++ b/crates/host-core/src/db/completion_report_migration_tests.rs
@@ -74,7 +74,6 @@ fn completion_report_migration_populated_30_preserves_all_data_and_pre_migration
drop(before);
let db = Database::open(&path).unwrap();
assert_eq!(version(db.conn()), SCHEMA_VERSION);
- assert_eq!(SCHEMA_VERSION, 33);
assert!(has_report(db.conn()));
assert_eq!(rows(db.conn(), LEGACY_RUN), old_run);
assert_eq!(rows(db.conn(), "SELECT * FROM mode_gate_results"), gates);
diff --git a/crates/host-core/src/db/mode_runs_migration.rs b/crates/host-core/src/db/mode_runs_migration.rs
index 06fd375fe..b5bba9d3d 100644
--- a/crates/host-core/src/db/mode_runs_migration.rs
+++ b/crates/host-core/src/db/mode_runs_migration.rs
@@ -157,7 +157,6 @@ mod tests {
let db = Database::open(&path).unwrap();
assert_eq!(version(db.conn()), SCHEMA_VERSION);
- assert_eq!(SCHEMA_VERSION, 33);
assert!(has_column(db.conn(), "sessions", "mode_snapshot_hash"));
for table in ["mode_snapshots", "mode_runs", "mode_gate_results"] {
assert!(has_table(db.conn(), table), "{table}");
diff --git a/crates/host-core/src/db/model_discovery_migration.rs b/crates/host-core/src/db/model_discovery_migration.rs
index a3fdb4f9e..55667fd30 100644
--- a/crates/host-core/src/db/model_discovery_migration.rs
+++ b/crates/host-core/src/db/model_discovery_migration.rs
@@ -26,3 +26,58 @@ pub(crate) fn migrate(conn: &Connection, path: &Path) -> Result<()> {
})?;
Ok(())
}
+
+pub(crate) fn migrate_reported_context_window(conn: &Connection, path: &Path) -> Result<()> {
+ let backup = create_migration_backup(conn, path, 33)?;
+ let tx = conn.unchecked_transaction()?;
+ let has_column: bool = tx.query_row(
+ "SELECT EXISTS(SELECT 1 FROM pragma_table_info('models') WHERE name = 'reported_context_window')",
+ [],
+ |row| row.get(0),
+ )?;
+ if !has_column {
+ // The previous cache could contain enriched defaults, so leave provenance unknown.
+ tx.execute_batch("ALTER TABLE models ADD COLUMN reported_context_window INTEGER;")?;
+ }
+ tx.pragma_update(None, "user_version", 34i64)?;
+ tx.commit().with_context(|| {
+ format!(
+ "commit schema v33 to v34 migration; backup {} remains",
+ backup.display()
+ )
+ })?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::db::{Database, SCHEMA_VERSION};
+
+ #[test]
+ fn upgrade_keeps_cached_capacity_without_inventing_its_provenance() {
+ 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 reported_context_window;
+ INSERT INTO providers(id, name, vendor_key, type, protocol, auth_kind, created_at, updated_at)
+ VALUES ('relay', 'Relay', 'custom', 'openai_compatible', 'openai_compatible', 'none', 0, 0);
+ INSERT INTO models(provider_id, model_id, display_name, source, context_window, discovery_state, updated_at)
+ VALUES ('relay', 'model', 'Model', 'discovered', 500000, 'published', 0);
+ PRAGMA user_version = 33;",
+ ).unwrap();
+ drop(db);
+
+ let upgraded = Database::open(&path).unwrap();
+ let version: i64 = upgraded
+ .conn()
+ .query_row("PRAGMA user_version", [], |row| row.get(0))
+ .unwrap();
+ assert_eq!(version, SCHEMA_VERSION);
+ let rows = crate::providers::list_models(&upgraded, Some("relay")).unwrap();
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0].context_window, Some(500_000));
+ assert_eq!(rows[0].reported_context_window, None);
+ assert!(super::super::migration_backup_path(&path, 33).is_file());
+ }
+}
diff --git a/crates/host-core/src/db/repositories.rs b/crates/host-core/src/db/repositories.rs
index 48515cf44..904b00405 100644
--- a/crates/host-core/src/db/repositories.rs
+++ b/crates/host-core/src/db/repositories.rs
@@ -225,6 +225,7 @@ impl Database {
30 => {}
31 => {}
32 => {}
+ 33 => {}
legacy @ 1..=6 => {
let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");
drop(conn);
@@ -312,6 +313,10 @@ impl Database {
if version == 32 {
super::legacy_goal_migration::migrate(&conn, path)?;
}
+ let version: i64 = conn.query_row("PRAGMA user_version", [], |r| r.get(0))?;
+ if version == 33 {
+ super::model_discovery_migration::migrate_reported_context_window(&conn, path)?;
+ }
let db = Self { conn, data_dir };
db.boot_maintenance()?;
crate::session_collaboration::recover(&db)?;
diff --git a/crates/host-core/src/db/schema.rs b/crates/host-core/src/db/schema.rs
index f9dcc4d20..d94e6f564 100644
--- a/crates/host-core/src/db/schema.rs
+++ b/crates/host-core/src/db/schema.rs
@@ -78,6 +78,7 @@ CREATE TABLE models (
source TEXT NOT NULL DEFAULT 'user',
capabilities_json TEXT NOT NULL DEFAULT '[]',
context_window INTEGER,
+ reported_context_window INTEGER,
max_output_tokens INTEGER,
deprecated INTEGER NOT NULL DEFAULT 0,
discovery_state TEXT CHECK (discovery_state IN ('published', 'unlisted')),
diff --git a/crates/host-core/src/plugins/providers/tests.rs b/crates/host-core/src/plugins/providers/tests.rs
index 993e58975..77e691659 100644
--- a/crates/host-core/src/plugins/providers/tests.rs
+++ b/crates/host-core/src/plugins/providers/tests.rs
@@ -191,6 +191,7 @@ fn empty_api_key_model_list_uses_the_cached_endpoint_discovery() {
display_name: "Demo Chat".to_string(),
capabilities: vec!["text".to_string()],
context_window: Some(128_000),
+ reported_context_window: None,
}],
true,
)
@@ -263,18 +264,21 @@ fn dropping_a_declared_model_forgets_its_cached_row() {
display_name: "Demo Large".into(),
capabilities: vec!["text".into()],
context_window: Some(200_000),
+ reported_context_window: None,
},
providers::DiscoveredModelInput {
model_id: "demo-small".into(),
display_name: "Demo Small".into(),
capabilities: vec!["text".into()],
context_window: Some(32_000),
+ reported_context_window: None,
},
providers::DiscoveredModelInput {
model_id: "demo-extra".into(),
display_name: "Demo Extra".into(),
capabilities: vec!["text".into()],
context_window: None,
+ reported_context_window: None,
},
],
true,
@@ -326,12 +330,14 @@ fn moving_a_declared_endpoint_forgets_the_discovered_answer() {
display_name: "Demo Large".into(),
capabilities: vec!["text".into()],
context_window: Some(200_000),
+ reported_context_window: None,
},
providers::DiscoveredModelInput {
model_id: "demo-remote-only".into(),
display_name: "Demo Remote Only".into(),
capabilities: vec!["text".into()],
context_window: Some(8_000),
+ reported_context_window: None,
},
],
true,
diff --git a/crates/host-core/src/providers/catalog.rs b/crates/host-core/src/providers/catalog.rs
index 42d9c836d..911fa339f 100644
--- a/crates/host-core/src/providers/catalog.rs
+++ b/crates/host-core/src/providers/catalog.rs
@@ -289,7 +289,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, discovery_state
+ capabilities_json, context_window, discovery_state, reported_context_window
FROM models
WHERE provider_id = ?1
ORDER BY display_name COLLATE NOCASE, model_id",
@@ -297,7 +297,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, discovery_state
+ capabilities_json, context_window, discovery_state, reported_context_window
FROM models
ORDER BY provider_id, display_name COLLATE NOCASE, model_id",
None,
@@ -317,6 +317,9 @@ pub fn list_models(db: &Database, provider_id: Option<&str>) -> Result<Vec<Model
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 {
@@ -355,12 +358,13 @@ pub fn cache_discovered_models(
let mut stmt = tx.prepare_cached(
"INSERT INTO models (
provider_id, model_id, display_name, source,
- capabilities_json, context_window, updated_at, discovery_state
- ) VALUES (?1, ?2, ?3, 'discovered', ?4, ?5, ?6, 'published')
+ 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'",
@@ -379,10 +383,10 @@ pub fn cache_discovered_models(
// 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'
+ "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],
+ params![provider_id, model_id, model.reported_context_window],
)?;
changed += stmt.execute(params![
provider_id,
@@ -391,6 +395,7 @@ pub fn cache_discovered_models(
serde_json::to_string(&model.capabilities)?,
model.context_window,
now,
+ model.reported_context_window,
])?;
}
}
diff --git a/crates/host-core/src/providers/model.rs b/crates/host-core/src/providers/model.rs
index 7e923fd3b..900c12ea4 100644
--- a/crates/host-core/src/providers/model.rs
+++ b/crates/host-core/src/providers/model.rs
@@ -193,6 +193,8 @@ pub struct ModelCatalogItem {
pub capabilities: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub context_window: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub reported_context_window: Option<u32>,
}
#[derive(Debug, Clone, Deserialize)]
@@ -204,4 +206,6 @@ pub struct DiscoveredModelInput {
pub capabilities: Vec<String>,
#[serde(default)]
pub context_window: Option<u32>,
+ #[serde(default)]
+ pub reported_context_window: Option<u32>,
}
diff --git a/crates/host-core/src/providers/repository.rs b/crates/host-core/src/providers/repository.rs
index 8cd0c12be..c51f650a6 100644
--- a/crates/host-core/src/providers/repository.rs
+++ b/crates/host-core/src/providers/repository.rs
@@ -474,7 +474,8 @@ pub fn update_provider(
};
forget_missing_discovered_models(db, &input.id, &configured)?;
db.conn().execute(
- "UPDATE models SET discovery_state = NULL WHERE provider_id = ?1",
+ "UPDATE models SET discovery_state = NULL, reported_context_window = NULL
+ WHERE provider_id = ?1",
params![input.id],
)?;
}
diff --git a/crates/host-core/src/providers/tests.rs b/crates/host-core/src/providers/tests.rs
index ae844df4d..69bb14d74 100644
--- a/crates/host-core/src/providers/tests.rs
+++ b/crates/host-core/src/providers/tests.rs
@@ -947,12 +947,14 @@ fn discovered_models_are_cached_without_overwriting_user_rows() {
display_name: "Beta".into(),
capabilities: vec!["text".into()],
context_window: None,
+ reported_context_window: None,
},
DiscoveredModelInput {
model_id: "model-a".into(),
display_name: "Alpha".into(),
capabilities: vec!["text".into()],
context_window: Some(128_000),
+ reported_context_window: None,
},
],
true,
@@ -969,12 +971,14 @@ fn discovered_models_are_cached_without_overwriting_user_rows() {
display_name: "Alpha updated".into(),
capabilities: vec!["text".into(), "reasoning".into()],
context_window: Some(256_000),
+ reported_context_window: None,
},
DiscoveredModelInput {
model_id: "user-model".into(),
display_name: "Remote label".into(),
capabilities: vec!["text".into()],
context_window: None,
+ reported_context_window: None,
},
],
true,
@@ -1045,6 +1049,7 @@ fn deleting_a_binding_and_saving_forgets_its_cached_parameters() {
display_name: "Alpha".into(),
capabilities: vec!["text".into()],
context_window: Some(128_000),
+ reported_context_window: None,
},
// The service spells it differently from the binding that drops it.
DiscoveredModelInput {
@@ -1052,12 +1057,14 @@ fn deleting_a_binding_and_saving_forgets_its_cached_parameters() {
display_name: "Beta".into(),
capabilities: vec!["text".into()],
context_window: Some(32_000),
+ reported_context_window: None,
},
DiscoveredModelInput {
model_id: "model-c".into(),
display_name: "Gamma".into(),
capabilities: vec!["text".into()],
context_window: Some(64_000),
+ reported_context_window: None,
},
],
true,
@@ -1152,6 +1159,7 @@ fn a_probe_answer_forgets_models_it_no_longer_publishes() {
display_name: (*id).to_string(),
capabilities: vec!["text".into()],
context_window: Some(64_000),
+ reported_context_window: None,
})
.collect()
};
@@ -1292,12 +1300,14 @@ fn changing_the_endpoint_forgets_the_discovered_answer() {
display_name: "Alpha".into(),
capabilities: vec!["text".into()],
context_window: Some(128_000),
+ reported_context_window: Some(128_000),
},
DiscoveredModelInput {
model_id: "model-b".into(),
display_name: "Beta".into(),
capabilities: vec!["text".into()],
context_window: Some(32_000),
+ reported_context_window: Some(32_000),
},
],
true,
@@ -1343,6 +1353,9 @@ fn changing_the_endpoint_forgets_the_discovered_answer() {
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()));
+ assert!(reset
+ .iter()
+ .all(|model| model.reported_context_window.is_none()));
cache_discovered_models(
&db,
&provider.id,
@@ -1351,6 +1364,7 @@ fn changing_the_endpoint_forgets_the_discovered_answer() {
display_name: "New".into(),
capabilities: vec![],
context_window: None,
+ reported_context_window: None,
}],
true,
)
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index cd452d678..0dfe327dd 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -104,6 +104,25 @@ struct CacheModelsParams {
complete: bool,
provider_id: String,
models: Vec<DiscoveredModelInput>,
+ endpoint: Option<ModelDiscoveryEndpoint>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct ModelDiscoveryEndpoint {
+ base_url: String,
+ api_style: String,
+}
+
+impl ModelDiscoveryEndpoint {
+ fn matches(&self, db: &crate::db::Database, provider_id: &str) -> rusqlite::Result<bool> {
+ db.conn().query_row(
+ "SELECT EXISTS(SELECT 1 FROM providers WHERE id = ?1
+ AND COALESCE(base_url, '') = ?2 AND COALESCE(api_style, '') = ?3)",
+ rusqlite::params![provider_id, self.base_url, self.api_style],
+ |row| row.get(0),
+ )
+ }
}
#[derive(Debug)]
@@ -2715,7 +2734,18 @@ async fn handle_request(
}
"providers.listModels" => {
let provider_id = params.get("providerId").and_then(|v| v.as_str());
+ let endpoint: Option<ModelDiscoveryEndpoint> =
+ serde_json::from_value(params.get("endpoint").cloned().unwrap_or(Value::Null))
+ .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
let st = state.lock().await;
+ if let Some(endpoint) = endpoint {
+ if !endpoint
+ .matches(&st.db, provider_id.unwrap_or_default())
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
+ {
+ return Ok(json!({ "models": [] }));
+ }
+ }
let models = providers::list_models(&st.db, provider_id)
.map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
Ok(json!({ "models": models }))
@@ -2724,6 +2754,14 @@ 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;
+ if let Some(endpoint) = input.endpoint {
+ if !endpoint
+ .matches(&st.db, &input.provider_id)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
+ {
+ return Ok(json!({ "cached": 0, "models": [] }));
+ }
+ }
let cached = providers::cache_discovered_models(
&st.db,
&input.provider_id,
@@ -11027,22 +11065,27 @@ mod tests {
.await
.unwrap();
let provider_id = created["provider"]["id"].as_str().unwrap();
+ let endpoint = json!({ "baseUrl": "http://localhost:11434/v1", "apiStyle": "" });
let cached = handle_request(
state.clone(),
"providers.cacheModels",
json!({
"providerId": provider_id,
+ "endpoint": endpoint,
"models": [
{
"modelId": "model-a",
"displayName": "Model A",
- "capabilities": ["text"]
+ "capabilities": ["text"],
+ "contextWindow": 500000,
+ "reportedContextWindow": 500000
},
{
"modelId": "model-b",
"displayName": "Model B",
- "capabilities": ["text", "reasoning"]
+ "capabilities": ["text", "reasoning"],
+ "contextWindow": 128000
}
]
}),
@@ -11053,16 +11096,48 @@ mod tests {
assert_eq!(cached["cached"], 2);
let listed = handle_request(
- state,
+ state.clone(),
"providers.listModels",
- json!({ "providerId": provider_id }),
- tx,
+ json!({ "providerId": provider_id, "endpoint": endpoint }),
+ tx.clone(),
)
.await
.unwrap();
assert_eq!(listed["models"].as_array().unwrap().len(), 2);
assert_eq!(listed["models"][1]["modelId"], "model-b");
assert_eq!(listed["models"][1]["capabilities"][1], "reasoning");
+ assert_eq!(listed["models"][0]["reportedContextWindow"], 500000);
+ assert_eq!(listed["models"][1]["contextWindow"], 128000);
+ assert!(listed["models"][1].get("reportedContextWindow").is_none());
+
+ handle_request(
+ state.clone(),
+ "providers.update",
+ json!({ "id": provider_id, "baseUrl": "http://localhost:11435/v1" }),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ let rejected = handle_request(
+ state.clone(),
+ "providers.cacheModels",
+ json!({ "providerId": provider_id, "endpoint": endpoint, "models": [
+ { "modelId": "stale", "displayName": "Stale", "reportedContextWindow": 500000 }
+ ] }),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(rejected["cached"], 0);
+ let stale_read = handle_request(
+ state,
+ "providers.listModels",
+ json!({ "providerId": provider_id, "endpoint": endpoint }),
+ tx,
+ )
+ .await
+ .unwrap();
+ assert_eq!(stale_read["models"], json!([]));
}
#[tokio::test]
diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.md
index d30704340..b6660b763 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 v33)
+# 04. Data Storage (Schema v34)
### Project path aliases (#2148)
@@ -682,6 +682,7 @@ CREATE TABLE models (
source TEXT NOT NULL DEFAULT 'user', -- bundled | discovered | user
capabilities_json TEXT NOT NULL DEFAULT '[]',
context_window INTEGER,
+ reported_context_window INTEGER,
max_output_tokens INTEGER,
deprecated INTEGER NOT NULL DEFAULT 0,
discovery_state TEXT CHECK (discovery_state IN ('published', 'unlisted')),
@@ -694,6 +695,10 @@ 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 v34 adds nullable `models.reported_context_window` for a limit explicitly
+reported by the endpoint. The backed-up migration preserves the display cache
+and leaves the new field unknown until the next successful discovery refresh.
+
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
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index 1dd79426f..8ff58f013 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -849,6 +849,10 @@ against a live host, and replaying one after the final row would be wrong.
`complete` (default false). Model rows expose optional `discoveryState`
(`published` / `unlisted`); omission is unknown. Only complete, nonempty
snapshots reconcile missing discovered rows, without changing configuration.
+ An optional `endpoint` (`baseUrl`, `apiStyle`) guards the read or write
+ against the current saved provider under the Host lock. A mismatch returns
+ no cached models and performs no write. The optional `reportedContextWindow`
+ records capacity from the endpoint response independently of display metadata.
See provider-config schema for the conservative refresh and consumer rules.
- `providers.testConnection`
diff --git a/docs/spec/03-runtime/12-provider-config-schema.md b/docs/spec/03-runtime/12-provider-config-schema.md
index 39ae46c1c..ca1cd7b9e 100644
--- a/docs/spec/03-runtime/12-provider-config-schema.md
+++ b/docs/spec/03-runtime/12-provider-config-schema.md
@@ -673,13 +673,16 @@ 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[], complete?: boolean }`
+- in: `{ providerId, models: DiscoveredModelInput[], complete?: boolean, endpoint?: { baseUrl, apiStyle } }`
- 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.
+ A supplied endpoint must still match the saved provider at write time. For
+ runtime budgeting, `reportedContextWindow` is populated only from a limit
+ explicitly present in the discovery response.
- 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.
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 9b33788e3..6ba15df79 100644
--- a/docs/spec/03-runtime/13-model-catalog-and-selection.md
+++ b/docs/spec/03-runtime/13-model-catalog-and-selection.md
@@ -412,6 +412,13 @@ configured that value; the Advanced inputs retain the conservative runtime
limits until the user edits them. Both markers are optional, so old configs
remain readable and downgrade clients ignore them.
+For a saved non-OAuth endpoint, a catalog-owned context window follows the
+cached capacity reported for the exact provider and wire model ID when the
+endpoint still lists the model. Session launch passes this window to the
+runtime for compaction and provider requests. Missing capacity, unlisted
+models, and an unavailable cache fall back to the catalog/binding resolution
+above. Discovery does not change the saved binding or its output cap.
+
The configured user value remains persisted and visible in Advanced settings, but
provider safety does not trust an enlarged override beyond a known published
window. Outbound output caps, automatic compaction, and overflow classification
diff --git a/docs/spec/06-delivery/e2e/providers-and-models.md b/docs/spec/06-delivery/e2e/providers-and-models.md
index b28a52255..78e738fad 100644
--- a/docs/spec/06-delivery/e2e/providers-and-models.md
+++ b/docs/spec/06-delivery/e2e/providers-and-models.md
@@ -1067,6 +1067,9 @@ with only Host API controlled. Running-turn configuration remains queued.
`prompt is too long: N tokens > M maximum` once.
8. Run a turn where the model calls `new_context` well below the hard budget.
9. Invoke `/compact` manually while idle.
+ 10. Use a saved non-OAuth Responses endpoint whose catalog-owned window is
+ 1,050,000, whose discovery record reports 500,000, and whose output cap
+ is 128,000. Report 400,000 occupied tokens and submit a follow-up.
- **Expected**:
- The summary request of every checkpoint carries the session's own
conversation identity: on the Responses-shaped providers
@@ -1083,6 +1086,10 @@ with only Host API controlled. Running-turn configuration remains queued.
assistant turns compact through `prepareNextTurn` (pi 0.84.4+ skips that
hook on a terminating turn); a new user prompt still compacts before its
first provider request.
+ - In step 10, the main session launches with a 500,000-token window and
+ installs a checkpoint before the follow-up request. A smaller manual
+ window still applies, and missing or unlisted discovery falls back to
+ the existing catalog or binding.
- Every successful compaction adds exactly one divider row to the transcript,
positioned immediately after the last message that checkpoint covers, and
raises exactly one warning toast. Two checkpoints produce two rows, in
diff --git a/scripts/e2e-context-usage-compaction.mjs b/scripts/e2e-context-usage-compaction.mjs
index 3e3c890d1..2bd627065 100644
--- a/scripts/e2e-context-usage-compaction.mjs
+++ b/scripts/e2e-context-usage-compaction.mjs
@@ -1,4 +1,4 @@
-/** Production sidecar + localhost Responses gateway with inconsistent usage totals. */
+/** Production sidecar + localhost Responses gateway with controlled usage and context limits. */
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { createServer } from "node:http";
@@ -28,6 +28,17 @@ class CompactionSidecar extends OfflineSidecar {
async function scenario(mode) {
const dir = join(temporary, mode);
await mkdir(dir, { recursive: true });
+ const contextWindow = mode === "discovered-window" ? 500_000
+ : mode === "catalog-window" ? 1_050_000 : 100_000;
+ const maxTokens = contextWindow === 100_000 ? 8_192 : 128_000;
+ const firstUsage = {
+ "cached-input": { input_tokens: 80_000, output_tokens: 100, total_tokens: 20_100,
+ input_tokens_details: { cached_tokens: 60_000 } },
+ "partial-buckets": { input_tokens: 0, output_tokens: 10, total_tokens: 80_000 },
+ "normal-usage": { input_tokens: 4_000, output_tokens: 10, total_tokens: 4_010,
+ input_tokens_details: { cached_tokens: 2_000 } },
+ }[mode] ?? { input_tokens: 399_900, output_tokens: 100, total_tokens: 400_000,
+ input_tokens_details: { cached_tokens: 390_000 } };
const requests = [], timeline = [], checkpoints = [];
const server = createServer(async (request, response) => {
let raw = "";
@@ -42,13 +53,6 @@ async function scenario(mode) {
id: `message-${serial}`, type: "message", role: "assistant", status: "completed",
content: [{ type: "output_text", text, annotations: [] }],
};
- const firstUsage = mode === "cached-input"
- ? { input_tokens: 80_000, output_tokens: 100, total_tokens: 20_100,
- input_tokens_details: { cached_tokens: 60_000 } }
- : mode === "partial-buckets"
- ? { input_tokens: 0, output_tokens: 10, total_tokens: 80_000 }
- : { input_tokens: 4_000, output_tokens: 10, total_tokens: 4_010,
- input_tokens_details: { cached_tokens: 2_000 } };
const usage = serial === 1 ? firstUsage : { input_tokens: 100, output_tokens: 10, total_tokens: 110 };
const events = [
{ type: "response.created", response: { id: `response-${serial}` } },
@@ -87,17 +91,16 @@ async function scenario(mode) {
modelConfig: {
source: "generic", name: "Fixture model", baseUrl, reasoning: false, input: ["text"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
- contextWindow: 100_000, maxTokens: 8_192,
+ contextWindow, maxTokens,
},
},
};
await sidecar.prompt(params, "Start the task.");
const first = [...sidecar.messages.values()].find((message) => message.role === "assistant");
- const expectedTotal = mode === "cached-input" ? 20_100 : mode === "partial-buckets" ? 80_000 : 4_010;
- assert.equal(first?.usage?.totalTokens, expectedTotal);
+ assert.equal(first?.usage?.totalTokens, firstUsage.total_tokens);
if (mode === "cached-input") assert.equal(first?.usage?.cacheReadTokens, 60_000);
await sidecar.prompt(params, "Continue the task.");
- if (mode !== "normal-usage") {
+ if (mode !== "normal-usage" && mode !== "catalog-window") {
assert.deepEqual(timeline, ["turn", "summary", "checkpoint", "turn"]);
assert.equal(checkpoints.length, 1);
assert.equal(checkpoints[0].summary, "Fixture checkpoint summary.");
@@ -118,7 +121,9 @@ async function scenario(mode) {
}
try {
- for (const mode of ["cached-input", "partial-buckets", "normal-usage"]) await scenario(mode);
+ for (const mode of ["cached-input", "partial-buckets", "normal-usage", "discovered-window", "catalog-window"]) {
+ await scenario(mode);
+ }
} finally {
await rm(temporary, { recursive: true, force: true });
}