Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(model-catalog): let a catalog correction reach a saved model binding
vastsa6b591ecd9566
diff --git a/apps/desktop/electron/main/ipc/provider-ipc.ts b/apps/desktop/electron/main/ipc/provider-ipc.tsindex d5828ef06..1b2c464a6 100644--- a/apps/desktop/electron/main/ipc/provider-ipc.ts+++ b/apps/desktop/electron/main/ipc/provider-ipc.ts@@ -1,4 +1,11 @@-import { IPC, ErrorCodes, type ModelBinding, type OAuthRespondInput, type ThinkingLevel } from "@pi-desktop/shared";+import {+ IPC,+ ErrorCodes,+ resolveBindingContextWindow,+ type ModelBinding,+ type OAuthRespondInput,+ type ThinkingLevel,+} from "@pi-desktop/shared";import { OAUTH_AUTH_KIND, type VendorOAuth } from "../oauth";import { discoverProviderModels } from "../model-discovery";import { genericModelConfig, modelConfigWithBinding, mergeProviderHeaders } from "@pi-desktop/agent-runtime";@@ -260,7 +267,11 @@ export function registerProviderIpc({? modelConfigFromModelsDev(modelsDevModel, baseUrl): genericModelConfig(model.modelId, baseUrl);const storedModel = provider ? bindingForModel(provider, model.modelId) : undefined;- const modelConfig = modelConfigWithBinding(catalogModelConfig, storedModel);+ const resolvedModel = resolveBindingContextWindow(catalogModelConfig, storedModel);+ const modelConfig = modelConfigWithBinding(+ resolvedModel.catalogConfig,+ resolvedModel.binding,+ );const info = modelsDevModel? modelInfoFromModelsDev(modelsDevModel, provider?.id ?? ""): {diff --git a/apps/desktop/electron/main/runtime/provider-catalog.ts b/apps/desktop/electron/main/runtime/provider-catalog.tsindex dbbe4922a..3d9818cfa 100644--- a/apps/desktop/electron/main/runtime/provider-catalog.ts+++ b/apps/desktop/electron/main/runtime/provider-catalog.ts@@ -4,6 +4,7 @@ import {defaultCommandShellForPlatform,isCommandShellId,modelIdsMatch,+ resolveBindingContextWindow,validateNetworkProxy,type CommandShellId,type ModelBinding,@@ -91,10 +92,14 @@ export function createProviderCatalogRuntime({modelId: string,catalogModelConfig: Parameters<typeof modelConfigWithBinding>[0],) => {- const modelConfig = modelConfigWithBinding(+ const resolved = resolveBindingContextWindow(catalogModelConfig,bindingForModel(provider, modelId),);+ const modelConfig = modelConfigWithBinding(+ resolved.catalogConfig,+ resolved.binding,+ );return {modelConfig,capabilities: capabilitiesFromModelConfig(modelConfig),@@ -113,23 +118,37 @@ export function createProviderCatalogRuntime({"";const storedModel = bindingForModel(provider, modelId);const modelsDevModel = modelsDevModelFor(provider, modelId);- const modelConfig = modelConfigWithBinding(+ const resolved = resolveBindingContextWindow(modelsDevModel? modelConfigFromModelsDev(modelsDevModel, provider.baseUrl): genericModelConfig(modelId, provider.baseUrl ?? ""),storedModel,);+ const modelConfig = modelConfigWithBinding(+ resolved.catalogConfig,+ resolved.binding,+ );const models = provider.models?.map((binding) => {const catalogModel = modelsDevModelFor(provider, binding.id);if (!catalogModel) return binding;- const effective = modelConfigWithBinding(+ const bindingResolved = resolveBindingContextWindow(modelConfigFromModelsDev(catalogModel, provider.baseUrl),binding,);+ const effective = modelConfigWithBinding(+ bindingResolved.catalogConfig,+ bindingResolved.binding,+ );return {...binding,contextWindow: effective.contextWindow,maxTokens: effective.maxTokens,+ // An inherited window keeps its catalog provenance on the exposed row,+ // so saving this form cannot freeze a models.dev value into a snapshot+ // of its own.+ ...(bindingResolved.binding.contextWindowSource+ ? { contextWindowSource: bindingResolved.binding.contextWindowSource }+ : {}),};});return {@@ -283,12 +302,16 @@ export function createProviderCatalogRuntime({}const { provider, modelId } = target;const catalogModel = modelsDevModelFor(provider, modelId);- const modelConfig = modelConfigWithBinding(+ const resolved = resolveBindingContextWindow(catalogModel? modelConfigFromModelsDev(catalogModel, provider.baseUrl): genericModelConfig(modelId, provider.baseUrl ?? ""),bindingForModel(provider, modelId),);+ const modelConfig = modelConfigWithBinding(+ resolved.catalogConfig,+ resolved.binding,+ );return {...session,...capabilitiesFromModelConfig(modelConfig),diff --git a/apps/desktop/electron/main/runtime/session-launch.ts b/apps/desktop/electron/main/runtime/session-launch.tsindex d4c43986c..f7d7bd5e6 100644--- a/apps/desktop/electron/main/runtime/session-launch.ts+++ b/apps/desktop/electron/main/runtime/session-launch.ts@@ -4,6 +4,7 @@ import {isActiveInProject,isCommandShellCatalog,normalizeMode,+ resolveBindingContextWindow,trustedExtensionAgentKeyFromProviderId,type CommandShellCatalog,type McpServerRecord,@@ -346,7 +347,11 @@ export function createSessionLaunchRuntime({(modelsDevModel? modelConfigFromModelsDev(modelsDevModel, baseUrl): genericModelConfig(modelId, baseUrl ?? ""));- const modelConfig = modelConfigWithBinding(catalogModelConfig, storedModel);+ const resolvedLimits = resolveBindingContextWindow(catalogModelConfig, storedModel);+ const modelConfig = modelConfigWithBinding(+ resolvedLimits.catalogConfig,+ resolvedLimits.binding,+ );const thinkingCapabilities = capabilitiesFromModelConfig(modelConfig);const thinkingLevel = clampThinkingLevel(thinkingCapabilities,diff --git a/apps/desktop/src/components/settings/ModelSelectionPanes.tsx b/apps/desktop/src/components/settings/ModelSelectionPanes.tsxindex 35914c92a..5a9effaee 100644--- a/apps/desktop/src/components/settings/ModelSelectionPanes.tsx+++ b/apps/desktop/src/components/settings/ModelSelectionPanes.tsx@@ -499,6 +499,14 @@ export function ModelSelectionPanes({const enabledLevels = sortThinkingLevels(binding.thinkingLevels);const info = infoById.get(binding.id.toLowerCase());const publishedImages = info ? modelMatchesFilter(info, "vision") : false;+ // The row's published window, so the hint below the field can say+ // the number still follows it.+ const publishedContextWindow = info+ ? (info.contextWindow ?? info.limit?.context)+ : undefined;+ const followsCatalog =+ binding.contextWindowSource !== "user" &&+ publishedContextWindow !== undefined;const publishedDocuments = info ? modelMatchesFilter(info, "pdf") : false;const expanded = expandedModelId === binding.id;const advancedId = `model-advanced-${binding.id}`;@@ -601,6 +609,7 @@ export function ModelSelectionPanes({onClick={() =>updateBinding(binding.id, {contextWindow: preset.tokens,+ contextWindowSource: "user",})}>@@ -617,9 +626,17 @@ export function ModelSelectionPanes({onChange={(event) =>updateBinding(binding.id, {contextWindow: Number(event.target.value) || 0,+ contextWindowSource: "user",})}/>+ {/* A catalog window keeps following models.dev; the hint+ says so until the user pins a number. */}+ {followsCatalog ? (+ <span className="provider-chosen-limit-hint">+ {t("settings.contextWindowCatalogHint")}+ </span>+ ) : null}</label><label className="provider-chosen-field"><span className="provider-chosen-field-label">diff --git a/apps/desktop/src/components/settings/provider-copy.ts b/apps/desktop/src/components/settings/provider-copy.tsindex 9d56fa1a2..81874d83d 100644--- a/apps/desktop/src/components/settings/provider-copy.ts+++ b/apps/desktop/src/components/settings/provider-copy.ts@@ -29,6 +29,11 @@ export function copyProviderConfiguration(provider: ProviderPublic, name: stringid: model.id,...(model.alias !== undefined ? { alias: model.alias } : {}),contextWindow: model.contextWindow,+ // Provenance travels with the value, so a copied catalog window keeps+ // following models.dev and a copied override stays the user's.+ ...(model.contextWindowSource !== undefined+ ? { contextWindowSource: model.contextWindowSource }+ : {}),maxTokens: model.maxTokens,thinkingLevels: [...model.thinkingLevels],defaultThinkingLevel: model.defaultThinkingLevel,diff --git a/apps/desktop/src/lib/context-usage.ts b/apps/desktop/src/lib/context-usage.tsindex 7dd6607fd..d078d9c6d 100644--- a/apps/desktop/src/lib/context-usage.ts+++ b/apps/desktop/src/lib/context-usage.ts@@ -3,6 +3,7 @@ import {modelIdsMatch,type ContextUsageDisplay,type MessageUsage,+ type ModelBinding,type ModelInfo,type ProviderPublic,type ToolTokenUsage,@@ -55,16 +56,27 @@ function providerContextWindow(provider: ProviderPublic | undefined): number | ureturn value > 0 ? value : undefined;}+/**+ * The saved binding for a model, reduced to the fields the window resolver+ * needs. The provenance travels with the value, so a catalog snapshot follows+ * models.dev while a hand-edited number stays the user's.+ */function bindingContextWindow(provider: ProviderPublic | undefined,modelId: string | undefined,-): number | undefined {+): Pick<ModelBinding, "contextWindow" | "contextWindowSource"> | undefined {if (!provider || !modelId) return undefined;const binding = provider.models?.find((candidate) =>modelIdsMatch(candidate.id, modelId),);- const value = positiveTokenCount(binding?.contextWindow);- return value > 0 ? value : undefined;+ if (!binding) return undefined;+ const value = positiveTokenCount(binding.contextWindow);+ return value > 0+ ? {+ contextWindow: value,+ contextWindowSource: binding.contextWindowSource,+ }+ : undefined;}export function resolveContextWindow(@@ -82,9 +94,11 @@ export function resolveContextWindow(.find((model) => modelIdsMatch(model.modelId, modelId)): undefined;const catalogWindow = modelContextWindow(catalogModel);+ const configured = bindingContextWindow(provider, modelId);const configuredWindow = effectiveContextWindow(catalogWindow,- bindingContextWindow(provider, modelId),+ configured?.contextWindow,+ configured?.contextWindowSource,);if (configuredWindow) return configuredWindow;diff --git a/apps/desktop/src/styles/model-config.css b/apps/desktop/src/styles/model-config.cssindex c7c9557c6..fd23958b7 100644--- a/apps/desktop/src/styles/model-config.css+++ b/apps/desktop/src/styles/model-config.css@@ -1030,6 +1030,13 @@line-height: var(--leading-normal);}+/* The context-window field says when its number still follows models.dev. */+.provider-chosen-limit-hint {+ color: var(--ds-text-faint);+ font-size: var(--text-3xs);+ line-height: var(--leading-normal);+}+.provider-chosen-thinking-default {display: flex;align-items: center;diff --git a/apps/desktop/test/model-binding-catalog-source.test.mjs b/apps/desktop/test/model-binding-catalog-source.test.mjsnew file mode 100644index 000000000..8e9ec412b--- /dev/null+++ b/apps/desktop/test/model-binding-catalog-source.test.mjs@@ -0,0 +1,167 @@+import assert from "node:assert/strict";+import { registerHooks } from "node:module";+import test from "node:test";++import { ModelsDevCatalog } from "../electron/main/models-dev-catalog.ts";++const runtimeModule = new URL("../electron/main/runtime/provider-catalog.ts", import.meta.url);+// The production bundler resolves this extensionless TypeScript import.+const resolution = registerHooks({+ resolve(specifier, context, nextResolve) {+ if (context.parentURL === runtimeModule.href && specifier === "../models-dev-catalog") {+ return nextResolve("../models-dev-catalog.ts", context);+ }+ return nextResolve(specifier, context);+ },+});+const { createProviderCatalogRuntime } = await import(runtimeModule.href)+ .finally(() => resolution.deregister());++/**+ * A catalog read *after* models.dev corrected the model: the published window+ * (1,050,000) differs from the value a binding saved earlier snapshotted.+ */+const CORRECTED_CONTEXT_WINDOW = 1_050_000;++const fixture = {+ requesty: {+ name: "Requesty",+ api: "https://router.requesty.ai/v1",+ models: {+ "terra": {+ id: "terra",+ reasoning: true,+ modalities: { input: ["text"], output: ["text"] },+ limit: { context: CORRECTED_CONTEXT_WINDOW, output: 64_000 },+ },+ "unpublished": {+ id: "unpublished",+ reasoning: false,+ modalities: { input: ["text"], output: ["text"] },+ // No published limit: values.dev has nothing to correct here.+ },+ },+ },+};++async function fixtureRuntime() {+ const catalog = new ModelsDevCatalog({+ catalogPath: "unused-model-catalog.json",+ fetchImpl: async () => new Response(JSON.stringify(fixture), { status: 200 }),+ });+ assert.equal(await catalog.refresh(), true);+ return createProviderCatalogRuntime({+ getHost: () => null,+ modelsDevCatalog: catalog,+ });+}++function providerFor(binding) {+ return {+ id: "provider-row",+ name: "Requesty",+ vendorKey: "requesty",+ baseUrl: "https://router.requesty.ai/v1",+ models: [binding],+ };+}++function enrichedContextWindow(runtime, binding) {+ const provider = runtime.enrichProvider(providerFor(binding));+ return provider.models[0].contextWindow;+}++test("a catalog-sourced binding adopts a models.dev correction", async () => {+ const runtime = await fixtureRuntime();+ // The value the binding snapshotted when the model was added.+ const binding = {+ id: "terra",+ contextWindow: 1_048_576,+ contextWindowSource: "catalog",+ maxTokens: 64_000,+ thinkingLevels: ["off"],+ };+ assert.equal(enrichedContextWindow(runtime, binding), CORRECTED_CONTEXT_WINDOW);+});++test("a hand-edited window survives a models.dev correction", async () => {+ const runtime = await fixtureRuntime();+ const edited = {+ id: "terra",+ contextWindow: 256_000,+ contextWindowSource: "user",+ maxTokens: 64_000,+ thinkingLevels: ["off"],+ };+ assert.equal(enrichedContextWindow(runtime, edited), 256_000);+});++test("a hand-edited window that equals the generic seed is still the user's", async () => {+ const runtime = await fixtureRuntime();+ // 128k is the generic fallback this codebase inherits from the catalog, so a+ // user who picks exactly that number for a smaller endpoint must not be read+ // as "follow models.dev".+ const explicit = {+ id: "terra",+ contextWindow: 128_000,+ contextWindowSource: "user",+ maxTokens: 8_192,+ thinkingLevels: ["off"],+ };+ assert.equal(enrichedContextWindow(runtime, explicit), 128_000);+});++test("unmarked records keep the rule they were written under", async () => {+ const runtime = await fixtureRuntime();+ const legacySeed = {+ id: "terra",+ contextWindow: 128_000,+ maxTokens: 8_192,+ thinkingLevels: ["off"],+ };+ const legacyOverride = {+ id: "terra",+ contextWindow: 400_000,+ maxTokens: 8_192,+ thinkingLevels: ["off"],+ };+ // Documented fallback for records written before the provenance marker: the+ // generic seed follows the catalog, every other value is treated as explicit.+ assert.equal(enrichedContextWindow(runtime, legacySeed), CORRECTED_CONTEXT_WINDOW);+ assert.equal(enrichedContextWindow(runtime, legacyOverride), 400_000);+});++test("a catalog value leaves the binding marked as catalog-sourced", async () => {+ const runtime = await fixtureRuntime();+ const legacySeed = {+ id: "terra",+ contextWindow: 128_000,+ maxTokens: 8_192,+ thinkingLevels: ["off"],+ };+ const enriched = runtime.enrichProvider(providerFor(legacySeed)).models[0];+ // Settings round-trip safety: a later save of this row must not turn the+ // inherited value into a frozen snapshot of its own.+ assert.equal(enriched.contextWindowSource, "catalog");+ assert.equal(+ enrichedContextWindow(runtime, { ...enriched, contextWindow: 1_100_000 }),+ CORRECTED_CONTEXT_WINDOW,+ );++ const userEdited = runtime.enrichProvider(+ providerFor({ ...legacySeed, contextWindow: 256_000, contextWindowSource: "user" }),+ ).models[0];+ assert.equal(userEdited.contextWindowSource, "user");+});++test("a model the catalog does not publish keeps its stored window", async () => {+ const runtime = await fixtureRuntime();+ const binding = {+ id: "unpublished",+ contextWindow: 96_000,+ contextWindowSource: "user",+ maxTokens: 8_192,+ thinkingLevels: ["off"],+ };+ assert.equal(enrichedContextWindow(runtime, binding), 96_000);+});diff --git a/crates/host-core/src/plugins/providers.rs b/crates/host-core/src/plugins/providers.rsindex 791de0806..5c053fd76 100644--- a/crates/host-core/src/plugins/providers.rs+++ b/crates/host-core/src/plugins/providers.rs@@ -127,6 +127,7 @@ pub(crate) fn declared_providers(manifest: &PluginManifest) -> Vec<DeclaredPlugi.map(str::trim).filter(|value| !value.is_empty()).map(str::to_string),+ context_window_source: None,context_window: model.get("contextWindow").and_then(Value::as_u64)diff --git a/crates/host-core/src/providers/catalog.rs b/crates/host-core/src/providers/catalog.rsindex e578d1502..019ebc55e 100644--- a/crates/host-core/src/providers/catalog.rs+++ b/crates/host-core/src/providers/catalog.rs@@ -7,9 +7,20 @@ pub(crate) const PROVIDER_SELECT: &str =pub(crate) const CANONICAL_THINKING_LEVELS: &[&str] =&["off", "minimal", "low", "medium", "high", "xhigh", "max"];+/// Recognised context-window provenance markers. Anything else is dropped so a+/// row always falls back to the documented rule instead of a third state no+/// reader understands.+const CONTEXT_WINDOW_SOURCES: &[&str] = &["catalog", "user"];const DEFAULT_CONTEXT_WINDOW: u32 = 128_000;const DEFAULT_MAX_TOKENS: u32 = 8_192;+fn normalize_context_window_source(value: Option<&str>) -> Option<String> {+ let trimmed = value?.trim().to_ascii_lowercase();+ CONTEXT_WINDOW_SOURCES+ .contains(&trimmed.as_str())+ .then_some(trimmed)+}+pub(crate) fn normalize_model_bindings(bindings: &[ModelBinding]) -> Vec<ModelBinding> {bindings.iter()@@ -33,6 +44,9 @@ pub(crate) fn normalize_model_bindings(bindings: &[ModelBinding]) -> Vec<ModelBi.map(str::trim).filter(|value| !value.is_empty()).map(str::to_string),+ context_window_source: normalize_context_window_source(+ binding.context_window_source.as_deref(),+ ),context_window: if binding.context_window == 0 {DEFAULT_CONTEXT_WINDOW} else {@@ -60,6 +74,7 @@ fn legacy_model_binding(model_id: Option<String>) -> Vec<ModelBinding> {vec![ModelBinding {id: id.trim().to_string(),alias: None,+ context_window_source: None,context_window: DEFAULT_CONTEXT_WINDOW,max_tokens: DEFAULT_MAX_TOKENS,thinking_levels: Vec::new(),@@ -203,3 +218,86 @@ pub fn cache_discovered_models(tx.commit()?;Ok(changed)}++#[cfg(test)]+mod tests {+ use super::*;++ fn binding(id: &str, context_window: u32) -> ModelBinding {+ ModelBinding {+ id: id.to_string(),+ alias: None,+ context_window,+ context_window_source: None,+ max_tokens: DEFAULT_MAX_TOKENS,+ thinking_levels: Vec::new(),+ default_thinking_level: None,+ supports_images: None,+ supports_documents: None,+ available_for_subagents: None,+ }+ }++ /// The settings surface round-trips a provider through `config_json`, so a+ /// marker the store drops would silently turn an inherited catalog value+ /// into a frozen snapshot of its own.+ #[test]+ fn a_catalog_sourced_binding_survives_the_config_round_trip() {+ let raw = r#"{"models":[{"id":"terra","contextWindow":1048576,"maxTokens":64000,+ "contextWindowSource":"catalog"}]}"#;+ let saved = config_with_model_bindings("{}", &config_model_bindings(raw, None)).unwrap();+ let value: serde_json::Value = serde_json::from_str(&saved).unwrap();+ assert_eq!(value["models"][0]["contextWindowSource"], "catalog");+ assert_eq!(+ config_model_bindings(&saved, None)[0]+ .context_window_source+ .as_deref(),+ Some("catalog")+ );++ let mut user_binding = binding("terra", 128_000);+ user_binding.context_window_source = Some("user".to_string());+ let saved = config_with_model_bindings("{}", &[user_binding]).unwrap();+ assert_eq!(+ config_model_bindings(&saved, None)[0]+ .context_window_source+ .as_deref(),+ Some("user")+ );+ }++ /// Records written before the marker name no source. They stay `None` so+ /// every reader applies one documented rule instead of guessing.+ #[test]+ fn a_binding_without_a_source_stays_unmarked() {+ let bindings = config_model_bindings(+ r#"{"models":[{"id":"legacy","contextWindow":128000,"maxTokens":8192}]}"#,+ None,+ );+ assert_eq!(bindings[0].context_window_source, None);+ let saved = config_with_model_bindings("{}", &bindings).unwrap();+ let value: serde_json::Value = serde_json::from_str(&saved).unwrap();+ assert!(value["models"][0].get("contextWindowSource").is_none());+ }++ /// An unrecognised marker is not a third state: it is dropped so the+ /// historical rule keeps applying to that row.+ #[test]+ fn an_unknown_source_is_dropped_instead_of_persisted() {+ let bindings = config_model_bindings(+ r#"{"models":[{"id":"odd","contextWindow":256000,"maxTokens":8192,+ "contextWindowSource":"derived"}]}"#,+ None,+ );+ assert_eq!(bindings[0].context_window_source, None);+ }++ /// The zero-value normalisation is what keeps a freshly added model from+ /// persisting a window of `0`; the source marker must not disturb it.+ #[test]+ fn zero_limits_still_fall_back_to_the_generic_defaults() {+ let normalized = normalize_model_bindings(&[binding("terra", 0)]);+ assert_eq!(normalized[0].context_window, DEFAULT_CONTEXT_WINDOW);+ assert_eq!(normalized[0].max_tokens, DEFAULT_MAX_TOKENS);+ }+}diff --git a/crates/host-core/src/providers/model.rs b/crates/host-core/src/providers/model.rsindex 627f8e1c5..b218c47ad 100644--- a/crates/host-core/src/providers/model.rs+++ b/crates/host-core/src/providers/model.rs@@ -127,6 +127,13 @@ pub struct ModelBinding {/// published name; `id` remains the wire identity.#[serde(default, skip_serializing_if = "Option::is_none")]pub alias: Option<String>,+ /// Provenance of `context_window`. `catalog` values follow the published+ /// models.dev record, so a catalog correction still reaches a saved binding;+ /// `user` values are the user's own number. Absent means the record predates+ /// the marker and readers apply the historical rule (only the generic 128k+ /// seed is inherited).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub context_window_source: Option<String>,pub context_window: u32,pub max_tokens: u32,#[serde(default)]diff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.mdindex bad4daf7c..9d3865e29 100644--- a/docs/spec/03-runtime/11-provider-model-system.md+++ b/docs/spec/03-runtime/11-provider-model-system.md@@ -305,6 +305,10 @@ type UserModelConfig = {type ModelBinding = {id: stringcontextWindow: number+ /** Where `contextWindow` came from; absent on records older than the marker,+ * which then resolve through the historical rule (see+ * `13-model-catalog-and-selection.md` §9.1). */+ contextWindowSource?: "catalog" | "user"maxTokens: numberthinkingLevels: ThinkingLevel[]defaultThinkingLevel: ThinkingLevel | nulldiff --git a/docs/spec/03-runtime/12-provider-config-schema.md b/docs/spec/03-runtime/12-provider-config-schema.mdindex 386164bac..068fb7101 100644--- a/docs/spec/03-runtime/12-provider-config-schema.md+++ b/docs/spec/03-runtime/12-provider-config-schema.md@@ -90,6 +90,7 @@ Tables (canonical DDL in [04-data-storage](04-data-storage.md) §4.3–4.4, §4."id": { "type": "string", "minLength": 1 },"alias": { "type": "string", "maxLength": 60 },"contextWindow": { "type": "integer", "minimum": 1 },+ "contextWindowSource": { "enum": ["catalog", "user"] },"maxTokens": { "type": "integer", "minimum": 1 },"thinkingLevels": {"type": "array",@@ -119,6 +120,14 @@ provider or model resolution; UI naming and clearing rules are specified inalias, drops a blank one, and enforces the 60-character limit by rejecting anover-long alias with `MODEL_ALIAS_TOO_LONG`.+`models[].contextWindowSource` records where the stored `contextWindow` came+from. `catalog` marks a models.dev snapshot that a later catalog correction may+replace; `user` marks a number entered in Settings and is never replaced. The+property is optional, so a config written before the marker stays readable and+older clients ignore it. Host-core keeps only those two values and drops anything+else, so an unreadable marker cannot turn into a third state. The resolution rule+is specified in [13-model-catalog-and-selection](13-model-catalog-and-selection.md) §9.1.+`compatibility.supportsReasoning` and`compatibility.supportedThinkingLevels` remain readable for stored-record andolder-client compatibility, but Electron main ignores them during runtimediff --git a/docs/spec/03-runtime/13-model-catalog-and-selection.md b/docs/spec/03-runtime/13-model-catalog-and-selection.mdindex 4997ac232..6474581f0 100644--- a/docs/spec/03-runtime/13-model-catalog-and-selection.md+++ b/docs/spec/03-runtime/13-model-catalog-and-selection.md@@ -282,13 +282,25 @@ read.### 9.1 Effective context window-The runtime and context inspector use the same effective model window. A positive-published `limit.context` from models.dev replaces the legacy `128,000` generic-seed that older bindings may contain; this allows a refreshed catalog record such-as `gpt-5.6-luna` (`1,050,000` tokens) to stop appearing as a 128k model. A-non-default value entered through the per-model Advanced control remains the-explicit user override. Unknown models still use the conservative 128k generic-window and are never promoted from an ID pattern alone.+The runtime, the context inspector and the settings surface resolve one effective+model window. Every binding records where its `contextWindow` came from+(`contextWindowSource`):++- `catalog` — the number is a models.dev snapshot, so a later correction to the+ published `limit.context` replaces it. A refreshed record such as+ `gpt-5.6-luna` (`1,050,000` tokens) stops appearing as a 128k model, and a limit+ that models.dev corrects reaches the binding without deleting and re-adding the+ model.+- `user` — the number was entered through the per-model Advanced control (or the+ preset ladder in it) and is never replaced by the catalog, including the+ `128,000` value that is otherwise the generic seed.++Bindings written before the marker name no source. They keep the historical rule,+deterministically: a published `limit.context` replaces exactly the generic+`128,000` seed, and every other stored value stays the explicit value. Unknown+models still use the conservative 128k generic window and are never promoted from+an ID pattern alone. The marker is optional in the persisted record, so a config+written by an older version stays readable and a downgrade ignores it.### 9.2 Conversation Composer scope@@ -464,6 +476,15 @@ same model to the check mark, the toggle and the duplicate guard.it uses the generic shape while pi-ai supplies only transport/OAuth- [ ] provider settings and cached discovery cannot replace known catalogcapabilities; explicit binding edits remain persisted configuration+- [ ] a models.dev limit correction reaches an already saved `catalog` binding+ without deleting and re-adding the model, while a number the user entered in+ Advanced (`user`) survives every correction, a hand-entered `128,000`+ included+- [ ] a binding saved before the provenance marker resolves deterministically:+ the generic 128k seed follows the catalog and every other value stays as+ stored+- [ ] the provenance marker survives a provider save/read round trip and an+ unmarked record keeps working- [ ] unknown free-form models remain runnable without invented capabilities- [ ] a models.dev record and an unknown generic record resolve through the sameselected transport without sending provider credentials to the remote catalogdiff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.mdindex 93b9196b7..f073d0e0d 100644--- a/docs/spec/04-ux/06-settings-ia.md+++ b/docs/spec/04-ux/06-settings-ia.md@@ -251,6 +251,12 @@ a usage tab.outside settings container dismisses it before the trigger can becomedetached. Search results keep a dedicated no-match state instead ofreusing the search placeholder.+ - the context-window field states its provenance: while the number still+ follows the published models.dev limit, a faint hint under the input says so+ (`settings.contextWindowCatalogHint`), and the first edit — the preset+ ladder or the numeric input — pins the value to the user, which removes the+ hint. A value the user pinned is never replaced by a catalog refresh; an+ unpublished model shows no hint because there is nothing to follow.- each model option and configuration row shows a compact text/visioncapability state. Settings compares the checkbox with the published modelrecord, while the Composer badge and runtime use the effective binding:diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 5fadaf9a5..40d52957e 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -7499,6 +7499,10 @@ identify the platform validation still needed.| C — Conversation & stream (opaque floating surfaces) | E2E-CHAT-opaque-floating-decision-and-retry-surfaces || Quality (opaque floating surfaces) | E2E-CHAT-opaque-floating-decision-and-retry-surfaces || M6 (opaque floating surfaces) | E2E-CHAT-opaque-floating-decision-and-retry-surfaces |+| B — Model config (catalog window provenance) | E2E-MODEL-catalog-window-correction-reaches-saved-bindings |+| F — Persistence (catalog window provenance) | E2E-MODEL-catalog-window-correction-reaches-saved-bindings |+| Quality (catalog window provenance) | E2E-MODEL-catalog-window-correction-reaches-saved-bindings |+| M6+ (catalog window provenance) | E2E-MODEL-catalog-window-correction-reaches-saved-bindings |The `US-UI-*` visual scenarios (§UI shell visual scenarios) trace to theCodex parity decisions in [decisions-log §D](../08-meta/decisions-log.md)@@ -12513,3 +12517,43 @@ plugin-form fixtures in an isolated temporary directory at runtime.picked directory, and a session root stands in when the window shows noproject. The two-live-sessions desktop journey and the panel step are Draft(run only in a capable environment when this surface changes)++#### E2E-MODEL-catalog-window-correction-reaches-saved-bindings++- **Goal**: a models.dev limit correction reaches an already saved binding without+ deleting and re-adding the model, while a number the user entered in Settings is+ never overwritten.+- **Steps**:+ 1. Configure a provider, select a model models.dev publishes a `limit.context`+ for, and save. Open the row's Advanced body and read the context-window field+ and its hint.+ 2. Serve a corrected catalog record for that model (a different published+ window), reopen Settings, and read the row, the context inspector, and the+ window a new session launches with.+ 3. Type a window in the Advanced field — the preset ladder once and a+ hand-typed `128000` once — save, then serve another catalog correction and+ reopen Settings and the inspector.+ 4. Save and reopen a provider row whose binding carries no+ `contextWindowSource`: once with the generic `128000` seed, once with any+ other stored value.+- **Expected**: Step 1 shows the published number with the "follows models.dev"+ hint. Step 2 shows the corrected number everywhere the effective window is used+ (settings row, context inspector, session launch) with no delete and re-add.+ Step 3 keeps the entered number in the settings row, in the inspector, and in+ the launched request, including a hand-typed `128000` for a model whose+ published window is larger, and the hint is gone. Step 4 resolves+ deterministically: the `128000` seed follows the catalog, every other value+ stays as stored. Every step keeps the marker across the save/read round trip of+ the provider row, and a config written before the marker stays readable.+- **Specs linked**: `03-runtime/13-model-catalog-and-selection.md` §9.1,+ `03-runtime/12-provider-config-schema.md` §2,+ `03-runtime/11-provider-model-system.md` §2, `04-ux/06-settings-ia.md` §2+- **Acceptance**: B (model config), F (persistence), Quality+- **Milestone**: M6++- **Status**: Partially automated:+ `apps/desktop/test/model-binding-catalog-source.test.mjs` drives the main-process+ resolver (catalog-sourced correction reaches the exposed row, a user value+ survives it, the generic seed still follows the catalog, an inherited value stays+ marked); `packages/shared/src/model-catalog.test.ts` covers the four source rules;+ `crates/host-core/src/providers/catalog.rs` covers the config round trip, the+ unmarked record, and the dropped unknown marker. The end-to-end settings journeydiff --git a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md b/docs/zh-CN/spec/03-runtime/11-provider-model-system.mdindex a74301798..cda3c60ee 100644--- a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md+++ b/docs/zh-CN/spec/03-runtime/11-provider-model-system.md@@ -278,6 +278,9 @@ type UserModelConfig = {type ModelBinding = {id: stringcontextWindow: number+ /** `contextWindow` 的来源;早于该标记的记录没有此字段,按历史规则解析+ * (见 `13-model-catalog-and-selection.md` §9.1)。 */+ contextWindowSource?: "catalog" | "user"maxTokens: numberthinkingLevels: ThinkingLevel[]defaultThinkingLevel: ThinkingLevel | nulldiff --git a/docs/zh-CN/spec/03-runtime/12-provider-config-schema.md b/docs/zh-CN/spec/03-runtime/12-provider-config-schema.mdindex 8066ca4e6..7c6ac8df7 100644--- a/docs/zh-CN/spec/03-runtime/12-provider-config-schema.md+++ b/docs/zh-CN/spec/03-runtime/12-provider-config-schema.md@@ -87,6 +87,7 @@"id": { "type": "string", "minLength": 1 },"alias": { "type": "string", "maxLength": 60 },"contextWindow": { "type": "integer", "minimum": 1 },+ "contextWindowSource": { "enum": ["catalog", "user"] },"maxTokens": { "type": "integer", "minimum": 1 },"thinkingLevels": {"type": "array",@@ -123,6 +124,12 @@身份,别名从不用于提供商或模型解析。host-core 会修剪别名、丢弃空白值,并在超过 60 个 Unicode 字符时以 `MODEL_ALIAS_TOO_LONG` 拒绝。+`models[].contextWindowSource` 记录存储的 `contextWindow` 来自哪里:`catalog` 表示+models.dev 快照,之后的目录修正可以替换它;`user` 表示用户在设置中手改的值,永不被+替换。该字段可选,因此早于该标记写出的配置仍可读,旧客户端会忽略它。host-core 只+保留这两个取值、丢弃其它值,避免出现第三种无人识别的状态。解析规则见+[13-model-catalog-and-selection](13-model-catalog-and-selection.md) §9.1。+`compatibility.supportsReasoning` 和`compatibility.supportedThinkingLevels` 对于存储的记录保持可读状态旧客户端兼容性,但 Electron main 在运行时忽略它们diff --git a/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md b/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.mdindex d2a9636a4..f67221841 100644--- a/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md+++ b/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md@@ -258,10 +258,19 @@ Electron 使用本地 `models.dev` 记录装饰缓存和新发现的模型行。`contextWindow` 与 agent sidecar 共享同一套 effective 解析;提供商发现只为目录缺失的模型提供 ID,未知模型仍使用通用后备。-上下文窗口解析必须与 agent runtime 使用同一个 effective window:已发布的-`models.dev limit.context` 会替换旧 binding 中遗留的 128k 通用种子,因此-`gpt-5.6-luna` 这类 1m 级模型不会再显示为 128k。用户在 Advanced 中输入的-非默认值仍是明确的按模型覆盖;未知模型仍保守使用 128k,不能仅凭 ID 猜测。+上下文窗口解析必须与 agent runtime 使用同一个 effective window。每个 binding 记录+自己的 `contextWindow` 从哪来(`contextWindowSource`):++- `catalog`——该值是 models.dev 快照,之后目录修正 `limit.context` 时会跟着更新,+ 所以 `gpt-5.6-luna`(`1,050,000`)这类记录不会再显示为 128k,被修正上限的模型+ 也不用删掉重建;+- `user`——该值来自 Advanced 里的手改(含预设档位),任何目录修正都不会覆盖它,+ 包括手改的 `128,000`。++在标记出现之前保存的 binding 没有来源标记,它们按确定的历史规则解析:已发布的+`limit.context` 只替换恰好等于 128,000 的通用种子,其余值一律按显式值保留;未知模型+仍保守使用 128k,不能仅凭 ID 猜测。标记在持久化记录中是可选的,旧版本写出的配置+仍可读,降级版本会忽略它。## 13. 搜索行为@@ -287,5 +296,9 @@ Electron 使用本地 `models.dev` 记录装饰缓存和新发现的模型行。- [ ] 提供程序设置和缓存发现无法覆盖已知的 pi 模型- [ ] 未知的自由形式模型在没有发明功能的情况下仍然可以运行- [ ] 固定 pi-ai ^0.82.1+ 将 `claude-opus-5`(和网关兼容的别名)解析为已发布的 1M 上下文自适应思维记录,无需桌面覆盖+- [ ] 目录修正的模型上限会回流到已保存的 `catalog` 绑定,无需删除重建;用户在+ Advanced 手改的值(`user`)在任何修正下都不被覆盖,包括手改的 `128,000`+- [ ] 没有来源标记的旧 binding 按确定规则解析:128k 通用种子跟随目录,其余值保持原样+- [ ] 来源标记能在提供商保存/读取往返后保留,未标记记录仍可正常使用- [ ] 紧凑上限文本不会高于已发布值,1M 附近的相邻窗口保持可区分(`1M` / `1.05M` / `1.1M`),且永远不会渲染出大于等于 1000 的 `K` 尾数diff --git a/docs/zh-CN/spec/04-ux/06-settings-ia.md b/docs/zh-CN/spec/04-ux/06-settings-ia.mdindex 688b7ddbb..fba54ff08 100644--- a/docs/zh-CN/spec/04-ux/06-settings-ia.md+++ b/docs/zh-CN/spec/04-ux/06-settings-ia.md@@ -144,6 +144,10 @@ Token 用量**不是设置目的地**(D335 / ADR 0173)。已完成回合历行内以统一的紧凑格式显示模型 ID、来源、能力与上限(如 `1.05M · 128K`),相邻窗口不会被舍入成同一个字符串;展开区是紧凑表单:别名说明放在输入框 title 上,数字框去掉原生步进按钮,思考档铺满一行且默认档与标签同行,附件与委派勾选同一行。+ 上下文窗口字段会说明自己的来源:数值仍跟随 models.dev 发布上限时,输入框下方显示+ 一行淡色提示(`settings.contextWindowCatalogHint`);用户第一次改动(预设档位或+ 数字输入)即把该值固定为用户自己的值并移除提示。被用户固定的值不会被目录刷新+ 覆盖;目录没有该模型的记录时不显示提示。因此两种凭据的模型选择完全一致。账户没有 API 密钥输入框,模型发现改由已保存的 OAuth 登录解析。保存会更新该 OAuth 提供商行,并在该账户被选为默认时同步全局默认模型diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 8d4e22d7f..fc3097c2c 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -5004,6 +5004,10 @@ IPC 请求无法关闭。| C — 对话与流式(不透明浮动表面) | E2E-CHAT-opaque-floating-decision-and-retry-surfaces || 品质(不透明浮动表面) | E2E-CHAT-opaque-floating-decision-and-retry-surfaces || M6(不透明浮动表面) | E2E-CHAT-opaque-floating-decision-and-retry-surfaces |+| B — 模型配置(目录窗口来源) | E2E-MODEL-catalog-window-correction-reaches-saved-bindings |+| F — 持久化(目录窗口来源) | E2E-MODEL-catalog-window-correction-reaches-saved-bindings |+| 品质(目录窗口来源) | E2E-MODEL-catalog-window-correction-reaches-saved-bindings |+| M6+(目录窗口来源) | E2E-MODEL-catalog-window-correction-reaches-saved-bindings |`US-UI-*` 视觉场景(§UI shell 视觉场景)追踪到[决策日志 §D](/zh-CN/spec/08-meta/decisions-log) 中的法典平价决策@@ -7485,3 +7489,32 @@ runner 会在运行时的隔离临时目录中生成六个插件形态 fixture- **验收**:G(插件)、安全性、品质- **里程碑**:M6+- **状态**:部分自动化(`apps/desktop/test/plugin-fs-session-root.test.mjs`):工具调用在发起会话的项目下写入与读取,面板调用与宿主未跟踪的会话回退到可见工作区,`userSelected` 模式保留选定的目录,窗口不显示任何项目时会话根依然生效。双活会话的桌面旅程与面板步骤为草稿(仅在此表面变化时于具备条件的环境中运行)++#### E2E-MODEL-catalog-window-correction-reaches-saved-bindings:目录修正回流已保存绑定,且不覆盖用户手改值++- **目标**:models.dev 修正某模型上限后回流到已保存的绑定(不必删除重建),+ 而用户在设置里手改的数值永不被覆盖。+- **步骤**:+ 1. 配置一个提供商,勾选 models.dev 已发布 `limit.context` 的模型并保存。展开该行的+ 高级区,读取上下文窗口字段与其提示。+ 2. 用修正后的目录记录(不同的发布上限)替换该模型记录,重新打开设置,读取该行、+ 上下文检查器,以及新会话启动时使用的窗口。+ 3. 在高级区输入窗口——先用预设档位,再手输 `128000`——保存,然后再喂一次目录修正,+ 重新打开设置与检查器。+ 4. 保存并重新打开一个绑定不带 `contextWindowSource` 的提供商行:一次使用通用+ `128000` 种子,一次使用任意其它已存值。+- **预期**:步骤 1 显示发布值并带「跟随 models.dev」提示。步骤 2 在所有使用 effective+ window 的地方(设置行、上下文检查器、会话启动)都显示修正后的值,无需删除重建。+ 步骤 3 在设置行、检查器和实际请求中都保留用户输入的值,包括在目录窗口更大时手输的+ `128000`,且提示消失。步骤 4 表现确定:`128000` 种子跟随目录,其它值保持原样。+ 每一步中标记都能在提供商行的保存/读取往返后保留,早于该标记写出的配置仍可读。+- **关联规范**:`03-runtime/13-model-catalog-and-selection.md` §9.1、+ `03-runtime/12-provider-config-schema.md` §2、+ `03-runtime/11-provider-model-system.md` §2、`04-ux/06-settings-ia.md` §2+- **验收**:B(模型配置)、F(持久化)、Quality+- **里程碑**:M6++- **状态**:部分自动化:`apps/desktop/test/model-binding-catalog-source.test.mjs` 驱动+ 主进程解析(目录来源的修正会到达对外暴露的行、用户值不受修正影响、通用种子仍跟随+ 目录、继承值保持 `catalog` 标记);`packages/shared/src/model-catalog.test.ts` 覆盖+ 四条来源规则;`crates/host-core/src/providers/catalog.rs` 覆盖配置往返、无标记记录与+ 被丢弃的未知标记。端到端的设置旅程与实际启动窗口断言为草稿。diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 2834cf9b3..abe0e5357 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -999,6 +999,7 @@ sklm: {"imageInput": "Bilder","documentInput": "PDF","thinkingManualOverrideHint": "Nicht im Katalog; aktivieren, wenn unterstützt.",+ "contextWindowCatalogHint": "Folgt models.dev; eine Änderung fixiert deinen Wert.","availableForSubagents": "Verfügbar für AI-Delegation","availableForSubagentsHint": "Ermöglichen Sie AI, dieses Modell zu verwenden, wenn Aufgaben an Subagenten delegiert werden.","searchModelId": "Modell-ID suchen…",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 885592f9b..9ecfce98f 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -1015,6 +1015,7 @@ sklm: {imageInput: "Images",documentInput: "PDF",thinkingManualOverrideHint: "Not in catalog; enable if supported.",+ contextWindowCatalogHint: "Follows models.dev; editing pins your value.",availableForSubagents: "Available for AI delegation",availableForSubagentsHint: "Allow AI to use this model when delegating tasks to subagents",searchModelId: "Search model ID…",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex d8a9fc543..cfccb4d81 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -999,6 +999,7 @@ sklm: {"imageInput": "Imágenes","documentInput": "PDF","thinkingManualOverrideHint": "No en el catálogo; habilitar si es compatible.",+ "contextWindowCatalogHint": "Sigue a models.dev; al editarlo se fija tu valor.","availableForSubagents": "Disponible para delegación de AI","availableForSubagentsHint": "Permitir que AI use este modelo al delegar tareas a subagentes","searchModelId": "ID de modelo de búsqueda…",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 2c743a09b..85cedac5d 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -999,6 +999,7 @@ sklm: {"imageInput": "Images","documentInput": "PDF","thinkingManualOverrideHint": "Pas dans le catalogue ; activer si pris en charge.",+ "contextWindowCatalogHint": "Suit models.dev ; une modification fixe votre valeur.","availableForSubagents": "Disponible pour la délégation de l'IA","availableForSubagentsHint": "Autoriser l'IA à utiliser ce modèle lors de la délégation de tâches à des sous-agents","searchModelId": "ID de modèle de recherche…",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 295895a41..d334df6c8 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -1016,6 +1016,7 @@ sklm: {imageInput: "이미지",documentInput: "PDF",thinkingManualOverrideHint: "카탈로그에 없음. 지원되는 경우 활성화하세요.",+ contextWindowCatalogHint: "models.dev를 따릅니다. 수정하면 내 값으로 고정됩니다.",availableForSubagents: "AI 위임에 사용 가능",availableForSubagentsHint: "서브에이전트에 작업을 위임할 때 AI가 이 모델을 사용하도록 허용",searchModelId: "모델 ID 검색…",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 6194ba453..c3ec41dbb 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -1016,6 +1016,7 @@ sklm: {imageInput: "Görüntüler",documentInput: "PDF",thinkingManualOverrideHint: "Katalogda yok; destekleniyorsa açın.",+ contextWindowCatalogHint: "models.dev'i takip eder; düzenlerseniz değeriniz sabitlenir.",availableForSubagents: "AI devri için kullanılabilir",availableForSubagentsHint: "Görevler alt ajanlara devredilirken AI’nin bu modeli kullanmasına izin ver",searchModelId: "Model kimliği ara…",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 8cb6faac8..9ecf66072 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -1002,6 +1002,7 @@ sklm: {imageInput: "图片",documentInput: "PDF",thinkingManualOverrideHint: "目录未标注,可手动开启",+ contextWindowCatalogHint: "跟随 models.dev;手动修改后会固定为你的值",availableForSubagents: "可供 AI 自动调度",availableForSubagentsHint: "允许 AI 在委派子任务时自动选用此模型",searchModelId: "搜索模型 ID…",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex c454520ab..8c4fecea1 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -1002,6 +1002,7 @@ sklm: {imageInput: "圖片",documentInput: "PDF",thinkingManualOverrideHint: "目錄未標註,可手動開啟",+ contextWindowCatalogHint: "跟隨 models.dev;手動修改後會固定為你的值",availableForSubagents: "可供 AI 自動排程",availableForSubagentsHint: "允許 AI 在委派子任務時自動選用此模型",searchModelId: "搜尋模型 ID…",diff --git a/packages/shared/src/model-catalog.test.ts b/packages/shared/src/model-catalog.test.tsindex dd9044a50..f31a10acb 100644--- a/packages/shared/src/model-catalog.test.ts+++ b/packages/shared/src/model-catalog.test.ts@@ -46,6 +46,54 @@ describe("effective model context windows", () => {});});+describe("binding context-window provenance", () => {+ it("marks the catalog snapshot a fresh binding is seeded with", () => {+ const binding = bindingFromModelInfo({+ ...textModel(),+ limit: { context: 1_048_576, output: 64_000 },+ });+ expect(binding.contextWindow).toBe(1_048_576);+ expect(binding.contextWindowSource).toBe("catalog");+ });++ it("follows a catalog correction for a catalog-sourced window", () => {+ // The bug this guards: a binding saved before models.dev corrected the+ // model kept the old snapshot forever, so the only fix was deleting and+ // re-adding the model.+ expect(effectiveContextWindow(1_050_000, 1_048_576, "catalog")).toBe(1_050_000);+ expect(effectiveContextWindow(1_050_000, 64_000, "catalog")).toBe(1_050_000);+ });++ it("keeps a hand-edited window even when it equals the generic seed", () => {+ // 128k is a real user answer, not the "inherit the catalog" sentinel, once+ // the binding records where the value came from.+ expect(effectiveContextWindow(1_050_000, 128_000, "user")).toBe(128_000);+ expect(effectiveContextWindow(1_050_000, 256_000, "user")).toBe(256_000);+ // An unpublished model leaves the stored value as the only answer.+ expect(effectiveContextWindow(undefined, 256_000, "user")).toBe(256_000);+ expect(effectiveContextWindow(undefined, 128_000, "catalog")).toBe(128_000);+ });++ it("keeps the historical rule for records written before the marker", () => {+ // Older bindings name no source. The documented fallback is the rule this+ // helper always applied: only the generic 128k seed is inherited.+ expect(effectiveContextWindow(1_050_000, 128_000, undefined)).toBe(1_050_000);+ expect(effectiveContextWindow(1_050_000, 1_048_576, undefined)).toBe(1_048_576);+ expect(effectiveContextWindow(1_050_000, 256_000, null)).toBe(256_000);+ expect(effectiveContextWindow(undefined, 128_000, undefined)).toBe(128_000);+ });++ it("keeps the provenance marker across a JSON round trip", () => {+ const stored = JSON.parse(JSON.stringify(bindingFromModelInfo(textModel())));+ expect(stored.contextWindowSource).toBe("catalog");+ // An edit path stamps the user as the author.+ const edited = { ...stored, contextWindow: 256_000, contextWindowSource: "user" };+ expect(effectiveContextWindow(1_050_000, edited.contextWindow, edited.contextWindowSource)).toBe(+ 256_000,+ );+ });+});+describe("provider API style compatibility", () => {it("falls back to Chat Completions for missing or unknown persisted styles", () => {expect(normalizeApiStyle(undefined)).toBe("chat_completions");diff --git a/packages/shared/src/model-catalog.ts b/packages/shared/src/model-catalog.tsindex 4d5fc8946..5c212ecb6 100644--- a/packages/shared/src/model-catalog.ts+++ b/packages/shared/src/model-catalog.ts@@ -12,7 +12,12 @@*/import { publishedThinkingLevels } from "./thinking-levels.js";-import type { ModelBinding, ModelInfo, ThinkingLevel } from "./types.js";+import type {+ ContextWindowSource,+ ModelBinding,+ ModelInfo,+ ThinkingLevel,+} from "./types.js";/** Wire protocol a provider row speaks. Mirrors the runtime adapter list. */export const API_STYLES = [@@ -137,28 +142,25 @@ export const CATALOG_DEFAULT_MAX_TOKENS = 8_192;/*** Resolve a model's effective context window.*- * Older provider bindings were seeded with the generic 128k fallback before a- * catalog record was available. Treat that value as inherited when a published- * model limit is now known, while preserving every non-default value as an- * explicit Advanced override.+ * `source` is the stored provenance of the configured value. A `catalog`+ * binding follows the published record, so a models.dev correction reaches a+ * binding that was saved before the fix; a `user` binding is the user's own+ * number and is never replaced, even when it equals the generic fallback.+ *+ * Older provider bindings name no source. They keep the rule this helper has+ * always applied: the generic 128k seed is treated as inherited when a+ * published limit is known, while every other value stays authoritative.*/export function effectiveContextWindow(publishedContextWindow?: number | null,configuredContextWindow?: number | null,+ source?: ContextWindowSource | null,): number | undefined {- const published =- typeof publishedContextWindow === "number" &&- Number.isFinite(publishedContextWindow) &&- publishedContextWindow > 0- ? Math.round(publishedContextWindow)- : undefined;- const configured =- typeof configuredContextWindow === "number" &&- Number.isFinite(configuredContextWindow) &&- configuredContextWindow > 0- ? Math.round(configuredContextWindow)- : undefined;+ const published = positiveTokenCount(publishedContextWindow);+ const configured = positiveTokenCount(configuredContextWindow);+ if (source === "catalog") return published ?? configured;+ if (source === "user") return configured ?? published;if (configured === undefined) return published;if (published !== undefined && configured === CATALOG_DEFAULT_CONTEXT_WINDOW) {return published;@@ -166,19 +168,78 @@ export function effectiveContextWindow(return configured;}+/** Token counts are whole positive numbers; anything else means "unset". */+function positiveTokenCount(value?: number | null): number | undefined {+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {+ return undefined;+ }+ return Math.round(value);+}++/** Context-window fields the resolver reads and rewrites on a binding. */+type BindingContextWindow = Pick<ModelBinding, "contextWindow"> &+ Partial<Pick<ModelBinding, "contextWindowSource">>;++/**+ * Resolve a saved binding against its catalog baseline for+ * `modelConfigWithBinding`.+ *+ * That runtime helper applies the historical two-argument rule, which cannot+ * tell a hand-edited 128k from the generic seed. Callers that know where a+ * stored value came from resolve it first: the returned baseline and binding+ * both carry the source-aware window, so the two-argument rule lands on the+ * same answer. An exported binding keeps the catalog as its provenance whenever+ * the catalog supplied the value, so a later settings save cannot freeze an+ * inherited value into a snapshot of its own.+ */+export function resolveBindingContextWindow<+ C extends { contextWindow?: number | null },+ B extends BindingContextWindow,+>(catalogConfig: C, binding: B): { catalogConfig: C; binding: B };+export function resolveBindingContextWindow<+ C extends { contextWindow?: number | null },+ B extends BindingContextWindow,+>(+ catalogConfig: C,+ binding: B | null | undefined,+): { catalogConfig: C; binding: B | null | undefined };+export function resolveBindingContextWindow(+ catalogConfig: { contextWindow?: number | null },+ binding: BindingContextWindow | null | undefined,+): {+ catalogConfig: { contextWindow?: number | null };+ binding: BindingContextWindow | null | undefined;+} {+ if (!binding) return { catalogConfig, binding };+ const published = positiveTokenCount(catalogConfig.contextWindow);+ const source = binding.contextWindowSource ?? undefined;+ const resolved = effectiveContextWindow(published, binding.contextWindow, source);+ if (resolved === undefined) return { catalogConfig, binding };+ const inherited = source !== "user" && published !== undefined;+ return {+ catalogConfig: { ...catalogConfig, contextWindow: resolved },+ binding: {+ ...binding,+ contextWindow: resolved,+ ...(inherited ? { contextWindowSource: "catalog" as const } : {}),+ },+ };+}+/*** Build the persisted binding for a published record. Published limits and* thinking levels seed a fresh binding, so a newly picked model needs no* manual token entry; the user can still configure the endpoint explicitly.*/export function bindingFromModelInfo(model: ModelInfo): ModelBinding {- // Published levels seed a fresh binding. The user may add other canonical- // levels later when the endpoint supports more than the catalog reports.const thinkingLevels = sortThinkingLevels(publishedThinkingLevels(model));return {id: model.modelId,contextWindow:model.contextWindow || model.limit?.context || CATALOG_DEFAULT_CONTEXT_WINDOW,+ // The snapshot is a catalog value, not a user answer: a later models.dev+ // correction still reaches this binding.+ contextWindowSource: "catalog",maxTokens: model.maxTokens || model.limit?.output || CATALOG_DEFAULT_MAX_TOKENS,thinkingLevels,defaultThinkingLevel: thinkingLevels.includes("medium")@@ -195,7 +256,11 @@ export function bindingFromModelInfo(model: ModelInfo): ModelBinding {export function bindingForCustomModel(id: string): ModelBinding {return {id: id.trim(),+ // An unpublished model has no catalog value to inherit yet, so the seed+ // stays catalog-sourced: if models.dev describes the id later, the window+ // it publishes takes over.contextWindow: CATALOG_DEFAULT_CONTEXT_WINDOW,+ contextWindowSource: "catalog",maxTokens: CATALOG_DEFAULT_MAX_TOKENS,thinkingLevels: [],defaultThinkingLevel: null,diff --git a/packages/shared/src/model-config-import.ts b/packages/shared/src/model-config-import.tsindex da082c221..7ee845f51 100644--- a/packages/shared/src/model-config-import.ts+++ b/packages/shared/src/model-config-import.ts@@ -12,7 +12,12 @@ import {type CatalogApiStyle,} from "./model-catalog.js";import { matchNamedPreset, normalizeEndpointUrl } from "./provider-presets.js";-import type { ModelBinding, ProviderCreateInput, ThinkingLevel } from "./types.js";+import type {+ ContextWindowSource,+ ModelBinding,+ ProviderCreateInput,+ ThinkingLevel,+} from "./types.js";export const MODEL_CONFIG_IMPORT_SOURCES = ["claude-code",@@ -814,10 +819,23 @@ function bindingFromGenericModel(return {...base,contextWindow: contextWindow ?? base.contextWindow,+ // A window the file states is an explicit answer from its author; the+ // generic seed it falls back to keeps following the catalog.+ contextWindowSource:+ importedContextWindowSource(record?.contextWindowSource) ??+ (contextWindow === undefined ? base.contextWindowSource : "user"),maxTokens: maxTokens ?? base.maxTokens,};}+/**+ * A config exported by PI-Desktop carries the provenance marker; an older or+ * foreign config does not.+ */+function importedContextWindowSource(value: unknown): ContextWindowSource | undefined {+ return value === "catalog" || value === "user" ? value : undefined;+}+function bindingFromPiModel(value: unknown): ModelBinding | null {if (typeof value === "string") return bindingForCustomModel(value);const record = asRecord(value);diff --git a/packages/shared/src/types/models.ts b/packages/shared/src/types/models.tsindex 0b00f23f7..ff8710ce8 100644--- a/packages/shared/src/types/models.ts+++ b/packages/shared/src/types/models.ts@@ -68,6 +68,15 @@ export function modelIdsMatch(candidate: string, requested: string): boolean {return false;}+/**+ * Where a saved context window came from.+ *+ * `catalog` is a metadata snapshot: the value follows the published models.dev+ * record, so a later catalog correction still reaches an already saved binding.+ * `user` is the user's own number and is never overwritten by the catalog.+ */+export type ContextWindowSource = "catalog" | "user";+/** Provider-local model settings persisted with the provider configuration. */export type ModelBinding = {id: string;@@ -75,6 +84,10 @@ export type ModelBinding = {* shows a model label; the id remains the wire identity. */alias?: string;contextWindow: number;+ /** Provenance of `contextWindow`. Absent on records written before the+ * marker existed; readers then apply the historical rule documented on+ * `effectiveContextWindow`. */+ contextWindowSource?: ContextWindowSource;maxTokens: number;/** Explicit endpoint levels; an empty or off-only set disables thinking. */thinkingLevels: ThinkingLevel[];@@ -99,7 +112,6 @@ export type ModelBinding = {availableForSubagents?: boolean;};-export const MODEL_MODALITIES = ["text", "image", "audio", "video", "pdf"] as const;export type ModelModality = (typeof MODEL_MODALITIES)[number];