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(models): preserve explicit settings across catalog updates
vastsa76ae6a9e1e5f
diff --git a/apps/desktop/electron/main/runtime/provider-catalog.ts b/apps/desktop/electron/main/runtime/provider-catalog.tsindex 6cddf6703..afb46d462 100644--- a/apps/desktop/electron/main/runtime/provider-catalog.ts+++ b/apps/desktop/electron/main/runtime/provider-catalog.ts@@ -157,6 +157,9 @@ export function createProviderCatalogRuntime({...(bindingResolved.binding.contextWindowSource? { contextWindowSource: bindingResolved.binding.contextWindowSource }: {}),+ ...(bindingResolved.binding.maxTokensSource+ ? { maxTokensSource: bindingResolved.binding.maxTokensSource }+ : {}),};});return {diff --git a/apps/desktop/src/components/settings/ModelSelectionPanes.tsx b/apps/desktop/src/components/settings/ModelSelectionPanes.tsxindex ebc770525..3ce419e54 100644--- a/apps/desktop/src/components/settings/ModelSelectionPanes.tsx+++ b/apps/desktop/src/components/settings/ModelSelectionPanes.tsx@@ -776,6 +776,7 @@ export function ModelSelectionPanes({onClick={() =>updateBinding(binding.id, {maxTokens: preset.tokens,+ maxTokensSource: "user",})}>@@ -792,6 +793,7 @@ export function ModelSelectionPanes({onChange={(event) =>updateBinding(binding.id, {maxTokens: Number(event.target.value) || 0,+ maxTokensSource: "user",})}/>@@ -1017,17 +1019,15 @@ type CapabilityToggleProps = {published: boolean;/** Stored override: `true`/`false` explicit, `null`/undefined follows. */value: boolean | null | undefined;- onChange: (next: boolean | null) => void;+ onChange: (next: boolean) => void;};/*** One attachment capability as a plain checkbox showing the effective answer.*- * The three stored states stay, but they need no third control: ticking the box- * back to what models.dev publishes stores "follow the catalog" rather than an- * equal-valued override, so agreeing with the catalog is the reset. That keeps a- * later catalog correction flowing through without asking the user to- * understand the distinction.+ * An untouched checkbox follows the catalog. Once the user changes it, the+ * selected boolean is explicit and stays pinned even if it currently agrees+ * with models.dev; catalog refreshes must not undo a deliberate choice.*/function CapabilityToggle({ label, published, value, onChange }: CapabilityToggleProps) {const effective = typeof value === "boolean" ? value : published;@@ -1036,9 +1036,7 @@ function CapabilityToggle({ label, published, value, onChange }: CapabilityToggl<inputtype="checkbox"checked={effective}- onChange={(event) =>- onChange(event.target.checked === published ? null : event.target.checked)- }+ onChange={(event) => onChange(event.target.checked)}/><span>{label}</span></label>diff --git a/apps/desktop/src/components/settings/provider-copy.ts b/apps/desktop/src/components/settings/provider-copy.tsindex 653980622..ae66b704c 100644--- a/apps/desktop/src/components/settings/provider-copy.ts+++ b/apps/desktop/src/components/settings/provider-copy.ts@@ -35,6 +35,9 @@ export function copyProviderConfiguration(provider: ProviderPublic, name: string? { contextWindowSource: model.contextWindowSource }: {}),maxTokens: model.maxTokens,+ ...(model.maxTokensSource !== undefined+ ? { maxTokensSource: model.maxTokensSource }+ : {}),thinkingLevels: [...model.thinkingLevels],defaultThinkingLevel: model.defaultThinkingLevel,...(model.supportsImages !== undefined ? { supportsImages: model.supportsImages } : {}),diff --git a/apps/desktop/test/context-usage.test.mjs b/apps/desktop/test/context-usage.test.mjsindex f42e62cad..1b89d2de9 100644--- a/apps/desktop/test/context-usage.test.mjs+++ b/apps/desktop/test/context-usage.test.mjs@@ -87,6 +87,7 @@ test("context window prefers the selected model catalog over provider fallback",{id: "gpt-5.6-luna",contextWindow: 128_000,+ contextWindowSource: "catalog",maxTokens: 8_192,thinkingLevels: [],},diff --git a/apps/desktop/test/model-advanced-capabilities.test.mjs b/apps/desktop/test/model-advanced-capabilities.test.mjsindex 9de94d6ac..ac58b731e 100644--- a/apps/desktop/test/model-advanced-capabilities.test.mjs+++ b/apps/desktop/test/model-advanced-capabilities.test.mjs@@ -52,13 +52,9 @@ test("the capability checkboxes show and follow the published value", () => {assert.match(pickerSource, /settings\.documentInput/);assert.match(pickerSource, /supportsImages: next/);assert.match(pickerSource, /supportsDocuments: next/);- // Agreeing with models.dev stores "follow the catalog" instead of an- // equal-valued override, so a later catalog correction still lands and no- // separate reset control is needed.- assert.match(- pickerSource,- /onChange\(event\.target\.checked === published \? null : event\.target\.checked\)/,- );+ // A deliberate checkbox change pins the selected value even when it equals+ // today's catalog value; later catalog corrections must not undo that choice.+ assert.match(pickerSource, /onChange\(event\.target\.checked\)/);assert.match(pickerSource,/const effective = typeof value === "boolean" \? value : published/,diff --git a/apps/desktop/test/model-binding-catalog-source.test.mjs b/apps/desktop/test/model-binding-catalog-source.test.mjsindex 8e9ec412b..df609db91 100644--- a/apps/desktop/test/model-binding-catalog-source.test.mjs+++ b/apps/desktop/test/model-binding-catalog-source.test.mjs@@ -84,16 +84,39 @@ test("a catalog-sourced binding adopts a models.dev correction", async () => {assert.equal(enrichedContextWindow(runtime, binding), CORRECTED_CONTEXT_WINDOW);});-test("a hand-edited window survives a models.dev correction", async () => {+test("a user output cap stays pinned independently of its catalog window", async () => {const runtime = await fixtureRuntime();const edited = {id: "terra",- contextWindow: 256_000,- contextWindowSource: "user",- maxTokens: 64_000,+ contextWindow: 1_048_576,+ contextWindowSource: "catalog",+ maxTokens: 8_192,+ maxTokensSource: "user",thinkingLevels: ["off"],};- assert.equal(enrichedContextWindow(runtime, edited), 256_000);+ const enriched = runtime.enrichProvider(providerFor(edited)).models[0];+ assert.equal(enriched.contextWindow, CORRECTED_CONTEXT_WINDOW);+ assert.equal(enriched.maxTokens, 8_192);+ assert.equal(enriched.maxTokensSource, "user");++ // Settings receives the independent marker and must not lose it on a save.+ const savedAgain = runtime.enrichProvider(providerFor(enriched)).models[0];+ assert.equal(savedAgain.maxTokens, 8_192);+ assert.equal(savedAgain.maxTokensSource, "user");+});++test("a legacy non-generic output cap stays explicit when the window follows catalog", async () => {+ const runtime = await fixtureRuntime();+ const legacy = {+ id: "terra",+ contextWindow: 1_048_576,+ contextWindowSource: "catalog",+ maxTokens: 4_096,+ thinkingLevels: ["off"],+ };+ const enriched = runtime.enrichProvider(providerFor(legacy)).models[0];+ assert.equal(enriched.maxTokens, 4_096);+ assert.equal(enriched.maxTokensSource, "user");});test("a hand-edited window that equals the generic seed is still the user's", async () => {@@ -125,9 +148,8 @@ test("unmarked records keep the rule they were written under", async () => {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);+ // An unmarked stored number may be a user override, so an upgrade preserves it.+ assert.equal(enrichedContextWindow(runtime, legacySeed), 128_000);assert.equal(enrichedContextWindow(runtime, legacyOverride), 400_000);});@@ -136,7 +158,9 @@ test("a catalog value leaves the binding marked as catalog-sourced", async () =>const legacySeed = {id: "terra",contextWindow: 128_000,+ contextWindowSource: "catalog",maxTokens: 8_192,+ maxTokensSource: "catalog",thinkingLevels: ["off"],};const enriched = runtime.enrichProvider(providerFor(legacySeed)).models[0];diff --git a/apps/desktop/test/provider-copy.test.mjs b/apps/desktop/test/provider-copy.test.mjsindex ef810d767..5bf64def2 100644--- a/apps/desktop/test/provider-copy.test.mjs+++ b/apps/desktop/test/provider-copy.test.mjs@@ -12,6 +12,7 @@ const source = () => ({models: [{ id: 'model', alias: 'Fast', contextWindow: 32000, maxTokens: 4000,thinkingLevels: ['off', 'high'], defaultThinkingLevel: 'high',supportsImages: true, supportsDocuments: null, availableForSubagents: true,+ contextWindowSource: 'catalog', maxTokensSource: 'user',secretValue: 'never-copy' }],});test('copy drafts carry only editable non-credential fields, with independent models', () => {@@ -23,6 +24,8 @@ test('copy drafts carry only editable non-credential fields, with independent moassert.equal(copy.models[0].alias, 'Fast');assert.equal(copy.models[0].supportsImages, true);assert.equal(copy.models[0].supportsDocuments, null);+ assert.equal(copy.models[0].contextWindowSource, 'catalog');+ assert.equal(copy.models[0].maxTokensSource, 'user');assert.equal(copy.models[0].availableForSubagents, true);assert.ok(!JSON.stringify(copy).includes('never-copy'));copy.name='Changed'; copy.apiStyle='anthropic_messages';diff --git a/crates/host-core/src/plugins/providers.rs b/crates/host-core/src/plugins/providers.rsindex 99064164a..88e1e5a61 100644--- a/crates/host-core/src/plugins/providers.rs+++ b/crates/host-core/src/plugins/providers.rs@@ -169,6 +169,7 @@ pub(crate) fn declared_providers(manifest: &PluginManifest) -> Vec<DeclaredPlugi.filter(|value| !value.is_empty()).map(str::to_string),context_window_source: None,+ max_tokens_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 5845ff85b..5d6d13c57 100644--- a/crates/host-core/src/providers/catalog.rs+++ b/crates/host-core/src/providers/catalog.rs@@ -7,16 +7,16 @@ 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+/// Recognised per-limit provenance markers. Anything else is dropped so a/// row always falls back to the documented rule instead of a third state no/// reader understands.-const CONTEXT_WINDOW_SOURCES: &[&str] = &["catalog", "user"];+const MODEL_LIMIT_SOURCES: &[&str] = &["catalog", "user"];pub(crate) const DEFAULT_CONTEXT_WINDOW: u32 = 128_000;pub(crate) const DEFAULT_MAX_TOKENS: u32 = 8_192;-fn normalize_context_window_source(value: Option<&str>) -> Option<String> {+fn normalize_model_limit_source(value: Option<&str>) -> Option<String> {let trimmed = value?.trim().to_ascii_lowercase();- CONTEXT_WINDOW_SOURCES+ MODEL_LIMIT_SOURCES.contains(&trimmed.as_str()).then_some(trimmed)}@@ -52,9 +52,12 @@ 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(+ context_window_source: normalize_model_limit_source(binding.context_window_source.as_deref(),),+ max_tokens_source: normalize_model_limit_source(+ binding.max_tokens_source.as_deref(),+ ),context_window: if binding.context_window == 0 {DEFAULT_CONTEXT_WINDOW} else {@@ -84,6 +87,7 @@ fn legacy_model_binding(model_id: Option<String>) -> Vec<ModelBinding> {id: id.trim().to_string(),alias: None,context_window_source: None,+ max_tokens_source: None,context_window: DEFAULT_CONTEXT_WINDOW,max_tokens: DEFAULT_MAX_TOKENS,thinking_levels: Vec::new(),@@ -368,6 +372,7 @@ mod tests {alias: None,context_window,context_window_source: None,+ max_tokens_source: None,max_tokens: DEFAULT_MAX_TOKENS,thinking_levels: Vec::new(),default_thinking_level: None,@@ -390,22 +395,29 @@ mod tests {#[test]fn a_catalog_sourced_binding_survives_the_config_round_trip() {let raw = r#"{"models":[{"id":"terra","contextWindow":1048576,"maxTokens":64000,- "contextWindowSource":"catalog"}]}"#;+ "contextWindowSource":"catalog","maxTokensSource":"catalog"}]}"#;let saved = config_with_model_bindings("{}", &read(raw)).unwrap();let value: serde_json::Value = serde_json::from_str(&saved).unwrap();assert_eq!(value["models"][0]["contextWindowSource"], "catalog");+ assert_eq!(value["models"][0]["maxTokensSource"], "catalog");assert_eq!(read(&saved)[0].context_window_source.as_deref(),Some("catalog"));+ assert_eq!(+ read(&saved)[0].max_tokens_source.as_deref(),+ Some("catalog")+ );let mut user_binding = binding("terra", 128_000);user_binding.context_window_source = Some("user".to_string());+ user_binding.max_tokens_source = Some("user".to_string());let saved = config_with_model_bindings("{}", &[user_binding]).unwrap();assert_eq!(read(&saved)[0].context_window_source.as_deref(),Some("user"));+ assert_eq!(read(&saved)[0].max_tokens_source.as_deref(), Some("user"));}/// Records written before the marker name no source. They stay `None` so@@ -415,6 +427,7 @@ mod tests {let bindings =read(r#"{"models":[{"id":"legacy","contextWindow":128000,"maxTokens":8192}]}"#);assert_eq!(bindings[0].context_window_source, None);+ assert_eq!(bindings[0].max_tokens_source, None);let saved = config_with_model_bindings("{}", &bindings).unwrap();let value: serde_json::Value = serde_json::from_str(&saved).unwrap();assert!(value["models"][0].get("contextWindowSource").is_none());@@ -426,9 +439,10 @@ mod tests {fn an_unknown_source_is_dropped_instead_of_persisted() {let bindings = read(r#"{"models":[{"id":"odd","contextWindow":256000,"maxTokens":8192,- "contextWindowSource":"derived"}]}"#,+ "contextWindowSource":"derived","maxTokensSource":"derived"}]}"#,);assert_eq!(bindings[0].context_window_source, None);+ assert_eq!(bindings[0].max_tokens_source, None);}/// The zero-value normalisation is what keeps a freshly added model fromdiff --git a/crates/host-core/src/providers/model.rs b/crates/host-core/src/providers/model.rsindex ee7c84149..a3c4f7e09 100644--- a/crates/host-core/src/providers/model.rs+++ b/crates/host-core/src/providers/model.rs@@ -134,6 +134,10 @@ pub struct ModelBinding {/// seed is inherited).#[serde(default, skip_serializing_if = "Option::is_none")]pub context_window_source: Option<String>,+ /// Provenance of `max_tokens`, independent from the context-window marker.+ /// Absent legacy values keep the historical generic-seed fallback.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub max_tokens_source: Option<String>,/// Context window in tokens. Optional on the wire: an absent key reads as/// `0`, which `normalize_model_bindings` replaces with the generic default,/// so a stored record that omits it still loads as one binding instead ofdiff --git a/crates/host-core/src/providers/tests.rs b/crates/host-core/src/providers/tests.rsindex 8d05ea680..b2bc349b0 100644--- a/crates/host-core/src/providers/tests.rs+++ b/crates/host-core/src/providers/tests.rs@@ -163,6 +163,7 @@ fn model_bindings_roundtrip_and_legacy_model_migrates_on_read() {id: "reasoning-model".into(),alias: Some("pro".into()),context_window_source: None,+ max_tokens_source: None,context_window: 256_000,max_tokens: 16_000,thinking_levels: vec!["high".into(), "medium".into()],@@ -176,6 +177,7 @@ fn model_bindings_roundtrip_and_legacy_model_migrates_on_read() {id: "plain-model".into(),alias: None,context_window_source: None,+ max_tokens_source: None,context_window: 128_000,max_tokens: 8_192,thinking_levels: vec![],@@ -283,6 +285,7 @@ fn binding_with_alias(id: &str, alias: Option<&str>) -> ModelBinding {id: id.into(),alias: alias.map(str::to_string),context_window_source: None,+ max_tokens_source: None,context_window: DEFAULT_CONTEXT_WINDOW,max_tokens: DEFAULT_MAX_TOKENS,thinking_levels: Vec::new(),@@ -1179,6 +1182,7 @@ fn binding_with_limits(id: &str, context_window: u32, max_tokens: u32) -> ModelBid: id.into(),alias: None,context_window_source: None,+ max_tokens_source: None,context_window,max_tokens,thinking_levels: Vec::new(),diff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.mdindex 7e4c8eb95..4002f04b4 100644--- a/docs/spec/03-runtime/11-provider-model-system.md+++ b/docs/spec/03-runtime/11-provider-model-system.md@@ -246,10 +246,10 @@ PI-Desktop must not permanently restrict users to a short fixed model list.input records the capability but does not change the encoding, since pi-ai0.87.1 has no PDF content block and PDFs stay bounded file references.10. The settings checkboxes show the effective answer against the published- baseline, and setting one back to the published value stores "follow the- catalog" rather than an equal-valued override. Agreeing with models.dev is- therefore the reset, and no separate reset control or per-capability- explanatory copy is required.+ baseline. An untouched or `null` value follows the catalog; once the user+ changes a checkbox, its selected boolean is explicit and remains pinned,+ even if it equals the currently published value. Catalog refreshes therefore+ cannot undo a deliberate choice.10a. `nativeWebSearch` is a two-state opt-in (absent means off; there is nocatalog baseline because models.dev publishes no hosted-tool capability).When enabled and the model resolves to `anthropic-messages`,diff --git a/docs/spec/03-runtime/12-provider-config-schema.md b/docs/spec/03-runtime/12-provider-config-schema.mdindex 59a884463..3a8fc3324 100644--- a/docs/spec/03-runtime/12-provider-config-schema.md+++ b/docs/spec/03-runtime/12-provider-config-schema.md@@ -92,6 +92,7 @@ Tables (canonical DDL in [04-data-storage](04-data-storage.md) §4.3–4.4, §4."contextWindow": { "type": "integer", "minimum": 0 },"contextWindowSource": { "enum": ["catalog", "user"] },"maxTokens": { "type": "integer", "minimum": 0 },+ "maxTokensSource": { "enum": ["catalog", "user"] },"thinkingLevels": {"type": "array","items": { "enum": ["off", "minimal", "low", "medium", "high", "xhigh", "max"] },@@ -120,14 +121,19 @@ 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 (a lookup that falls back to the generic shape is not a correction);-`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.+`models[].contextWindowSource` and `models[].maxTokensSource` independently+record where their corresponding limit came from. `catalog` marks a models.dev+snapshot that a later correction may replace (a lookup that falls back to the+generic shape is not a correction); `user` marks a value entered in Settings+and is never replaced. In particular, changing the context window does not+change ownership of the output cap. Both properties are optional, so configs+written before either marker stay readable and older clients ignore them.+Host-core keeps only `catalog` and `user` and drops other values. Legacy rows+without a source marker preserve their stored limit, including the generic+128,000 / 8,192 values, because the old record cannot reveal whether a value was+an explicit user choice.+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 and@@ -205,6 +211,11 @@ legacy binding above is materialized with, and the same value a pluginmanifest that declares no limits already produces. The stored array and themanifest therefore agree on what a model without limits means (D610).+For `supportsImages` and `supportsDocuments`, absent or `null` follows the+published capability until the user explicitly changes the checkbox. Either+explicit boolean is then pinned, even when it equals today's published value;+a later catalog correction cannot reverse the user's choice.+Each entry of a stored `models` array is decoded on its own. An entry that nolonger matches the schema is skipped and reported on the host log with theprovider id, its index and the reason, instead of discarding the whole array.diff --git a/docs/spec/03-runtime/13-model-catalog-and-selection.md b/docs/spec/03-runtime/13-model-catalog-and-selection.mdindex a478d6e2e..b9066c2d5 100644--- a/docs/spec/03-runtime/13-model-catalog-and-selection.md+++ b/docs/spec/03-runtime/13-model-catalog-and-selection.md@@ -326,30 +326,29 @@ read.### 9.1 Effective model limitsThe runtime, the context inspector and the settings surface resolve one effective-model window and output cap. Every binding records where its `contextWindow` came-from (`contextWindowSource`), and the same marker governs `maxTokens`:--- `catalog` — the number is a models.dev snapshot, so a later correction to the- published `limit.context` or `limit.output` replaces it. A refreshed record- such as `gpt-5.6-luna` (`1,050,000` tokens) stops appearing as a 128k model, a- row added while nothing published its id stops reporting the generic 8.2k- output once the record resolves, and a limit that models.dev corrects reaches- the binding without deleting and re-adding the model. Only a resolved- models.dev record counts as published: when the lookup misses and falls back to- the generic shape (for example a custom gateway URL serving an id several- publishers list), its `128,000` and `8,192` are not a correction, and the+model window and output cap. Bindings record their provenance independently:+`contextWindowSource` belongs to `contextWindow`, and `maxTokensSource` belongs+to `maxTokens`.++- `catalog` — that limit is a models.dev snapshot, so a later correction to its+ published field replaces it. A refreshed context such as `gpt-5.6-luna`+ (`1,050,000` tokens) stops appearing as a 128k model, and a row added while+ nothing published its id stops reporting the generic 8.2k output once the+ record resolves. Only a resolved models.dev record counts as published: when+ lookup falls back to the generic shape (for example a gateway serving an id+ several publishers list), its 128k / 8.2k values are not a correction and thestored catalog snapshot stays in force.-- `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` and `8,192` values that are 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 a published `limit.output` replaces exactly the generic-`8,192`, and every other stored value stays the explicit value. Unknown models-still use the conservative 128k / 8.2k generic limits 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.+- `user` — the value was entered in that limit's Advanced control or preset+ ladder and is never replaced by the catalog, including explicit 128,000 and+ 8,192 values that equal the generic seeds. Setting a context window cannot+ change the output-cap source.++Bindings written before either marker preserve their stored window and output+cap, including 128,000 and 8,192, because old records cannot distinguish generic+seeds from user choices. Only explicit `catalog` provenance follows later+corrections. Unknown models use conservative+128k / 8.2k limits and are never promoted from an ID pattern alone. Both markers+are optional, so old configs remain readable and downgrade clients ignore them.The configured user value remains persisted and visible in Advanced settings, butprovider safety does not trust an enlarged override beyond a known publisheddiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 50b673406..42f243e7b 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -617,8 +617,8 @@ identify the platform validation still needed.#### E2E-005: Add a provider and save API key- **Preconditions**: App running; no provider configured; the models.dev snapshot ships with the build.-- **Steps**: 1) Open Settings → Model configuration and choose Add provider. 2) Confirm the dialog is ONE form with no stepper or Next/Back buttons. The first control is Service — a searchable menu (Choose a service, Custom endpoint, then a flat vendor list from models.dev including Xiaomi), not a native select, region grouping, or vendor-card grid. Open it, type to filter client-side, then choose **Custom endpoint**. Confirm Name and Base URL appear on one row with no helper paragraph under the URL (placeholder only), API Key and API format appear side by side on the next row (not behind Advanced), and that a focused field plus its 2px accent ring stays fully inside the dialog, including on a window narrower than 1040px. 3) Enter a name and a base URL for a service that publishes a `/models` route, then paste an API key. 4) Confirm the models section fills with the models THAT SERVICE returned, not with every model its vendor publishes; confirm a model the deployment does not host is absent. 5) Type in the filter box and confirm the list narrows client-side with no network request per keystroke. 6) Confirm each row shows the models.dev-derived context/output for models the catalog knows, that its compact text tracks the published value instead of a coarser rounded one (a 1,050,000 window reads `1.05M`, never `1.1M`), and that a model with no catalog match still lists with generic defaults. 7) Select two models with the checkboxes. 8) Expand Advanced on one chosen row, override its limits and toggle thinking chips; confirm each numeric field has a five-chip preset ladder for common values, clicking a chip writes the value, hand editing remains possible, and a non-preset value leaves the ladder unselected. Confirm the label and optional hint sit above one compact grouped control and do not force the options onto a second row at normal dialog width; confirm all seven canonical levels are available, that published levels start selected for a known reasoning model, and that a non-reasoning or unknown row shows the same chips unselected with the manual-override hint; enable one level on that row and confirm the other row is unaffected. 9) Open the form-level Advanced and confirm the API format is present but pre-derived. 10) Add a free-form model ID the service did not return; confirm it is added with 128,000 / 8,192 / no-thinking defaults, then enable a thinking level if the endpoint supports it; confirm re-adding the same ID in different letter case is rejected as already added. 11) Save.-- **Expected**: The service is asked first and models.dev only enriches the answer and seeds known-model defaults. Newly fetched or checked model rows stay collapsed until the user opens Advanced, so every selected model ID remains visible in the right pane after a multi-select. The settings picker always offers the seven canonical thinking levels, and the Composer later renders the explicit levels saved in the same model binding; an empty or `off`-only binding resolves to `off`. Discovery is debounced ~600 ms, does not mark loading until that window elapses, and a slow reply from an earlier keystroke never replaces a newer list; named add-path discovery waits for an API key, while an unsaved custom provider is probed with the typed base URL (and key, if any) before it exists. Preset ladders cover common context/output limits while preserving hand-edited values. Limit text renders through one shared compact formatter, so neighbouring published windows stay distinguishable (`1M` / `1.05M` / `1.1M`) and a compact limit never reads above its published value. Custom endpoint keeps API format beside the key and omits Base URL helper copy; named endpoints do not show format. Point the same custom form at an unreachable or unauthorized URL and confirm the left pane shows a classified error (not a raw JSON/HTML dump and not a second “no models” empty state); with cached rows from a later edit, the same error is a one-line banner above the list. Point a second provider at a base URL with no `/models` route and confirm the list falls back to the catalog, is labelled as coming from models.dev rather than the service, and still saves. The provider appears as a row with its host, model count and secret badge; the key is stored securely (not in plaintext config); `models` contains both bindings and `models[0]` remains the provider default.+- **Steps**: 1) Open Settings → Model configuration and choose Add provider. 2) Confirm the dialog is ONE form with no stepper or Next/Back buttons. The first control is Service — a searchable menu (Choose a service, Custom endpoint, then a flat vendor list from models.dev including Xiaomi), not a native select, region grouping, or vendor-card grid. Open it, type to filter client-side, then choose **Custom endpoint**. Confirm Name and Base URL appear on one row with no helper paragraph under the URL (placeholder only), API Key and API format appear side by side on the next row (not behind Advanced), and that a focused field plus its 2px accent ring stays fully inside the dialog, including on a window narrower than 1040px. 3) Enter a name and a base URL for a service that publishes a `/models` route, then paste an API key. 4) Confirm the models section fills with the models THAT SERVICE returned, not with every model its vendor publishes; confirm a model the deployment does not host is absent. 5) Type in the filter box and confirm the list narrows client-side with no network request per keystroke. 6) Confirm each row shows the models.dev-derived context/output for models the catalog knows, that its compact text tracks the published value instead of a coarser rounded one (a 1,050,000 window reads `1.05M`, never `1.1M`), and that a model with no catalog match still lists with generic defaults. 7) Select two models with the checkboxes. 8) Expand Advanced on one chosen row, override its limits and toggle thinking chips; confirm each numeric field has a five-chip preset ladder for common values, clicking a chip writes the value, hand editing remains possible, and a non-preset value leaves the ladder unselected. Set max output to 8,192 while its context window still follows the catalog. On a model whose published image input is enabled, toggle image input off and then back on before saving, so the explicit choice equals the current catalog value. Confirm the label and optional hint sit above one compact grouped control and do not force the options onto a second row at normal dialog width; confirm all seven canonical levels are available, that published levels start selected for a known reasoning model, and that a non-reasoning or unknown row shows the same chips unselected with the manual-override hint; enable one level on that row and confirm the other row is unaffected. 9) Open the form-level Advanced and confirm the API format is present but pre-derived. 10) Add a free-form model ID the service did not return; confirm it is added with 128,000 / 8,192 / no-thinking defaults, then enable a thinking level if the endpoint supports it; confirm re-adding the same ID in different letter case is rejected as already added. 11) Save.+- **Expected**: The service is asked first and models.dev only enriches the answer and seeds known-model defaults. Newly fetched or checked model rows stay collapsed until the user opens Advanced, so every selected model ID remains visible in the right pane after a multi-select. The settings picker always offers the seven canonical thinking levels, and the Composer later renders the explicit levels saved in the same model binding; an empty or `off`-only binding resolves to `off`. Discovery is debounced ~600 ms, does not mark loading until that window elapses, and a slow reply from an earlier keystroke never replaces a newer list; named add-path discovery waits for an API key, while an unsaved custom provider is probed with the typed base URL (and key, if any) before it exists. Preset ladders cover common context/output limits while preserving hand-edited values. The explicitly selected 8,192 output remains pinned independently of the catalog-sourced context window, and the image-input choice remains explicitly enabled after it is toggled back to the published value; neither is reinterpreted as "follow catalog" on save/reopen. Later catalog corrections change only values whose own source is `catalog`. Limit text renders through one shared compact formatter, so neighbouring published windows stay distinguishable (`1M` / `1.05M` / `1.1M`) and a compact limit never reads above its published value. Custom endpoint keeps API format beside the key and omits Base URL helper copy; named endpoints do not show format. Point the same custom form at an unreachable or unauthorized URL and confirm the left pane shows a classified error (not a raw JSON/HTML dump and not a second “no models” empty state); with cached rows from a later edit, the same error is a one-line banner above the list. Point a second provider at a base URL with no `/models` route and confirm the list falls back to the catalog, is labelled as coming from models.dev rather than the service, and still saves. The provider appears as a row with its host, model count and secret badge; the key is stored securely (not in plaintext config); `models` contains both bindings and `models[0]` remains the provider default.- **Specs linked**: `03-runtime/11-provider-model-system.md`, `03-runtime/12-provider-config-schema.md`, `03-runtime/13-model-catalog-and-selection.md`, `03-runtime/14-secrets-storage.md`, `04-ux/06-settings-ia.md`- **Acceptance**: B (multi-model provider configuration, save key)- **Milestone**: M2diff --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 482d6ade1..8d50a733c 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@@ -217,9 +217,9 @@ PI-Desktop 不得把用户永久限制在一份简短的固定模型列表上。经常接受其目录条目未列出的输入。启用图片输入会打开临时图片内容块;启用PDF 输入只记录该能力,不改变编码方式——pi-ai 0.87.1 没有 PDF 内容块,PDF 仍是有界的文件引用。-10. 设置里的复选框展示的是相对于已发布基线的有效答案;把某一项设回已发布的- 值,存下来的是"跟随目录",而不是一个取值相同的覆盖。因此与 models.dev- 保持一致本身就是重置,不需要另外的重置控件,也不需要逐项能力的解释文案。+10. 设置里的复选框展示相对于已发布基线的有效答案。未修改或为 `null` 时跟随目录;+ 用户一旦更改复选框,所选布尔值就会显式固定,即使它与当前目录值相同。目录刷新+ 不会撤销用户主动做出的选择。10a. `nativeWebSearch` 是两态主动开启(缺省即关闭;models.dev 不发布托管工具能力,因此没有目录默认值)。启用后,当模型解析到 `anthropic-messages`、`openai-responses`、`azure-openai-responses` 或 `openai-codex-responses`diff --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 e3433a90a..074171bcc 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@@ -89,6 +89,7 @@"contextWindow": { "type": "integer", "minimum": 0 },"contextWindowSource": { "enum": ["catalog", "user"] },"maxTokens": { "type": "integer", "minimum": 0 },+ "maxTokensSource": { "enum": ["catalog", "user"] },"thinkingLevels": {"type": "array","items": { "enum": ["off", "minimal", "low", "medium", "high", "xhigh", "max"] },@@ -136,12 +137,18 @@ JSON、根节点非对象、`models` 非数组,或任一条目不可读,都为防止设置页的部分视图覆盖并丢失存储数据,当存储值降级时,`providers.update` 会以`MODEL_BINDINGS_DEGRADED` 拒绝显式替换模型数组;不涉及模型数组的提供商字段仍可更新。-`models[].contextWindowSource` 记录存储的 `contextWindow` 来自哪里:`catalog` 表示-models.dev 快照,之后的目录修正可以替换它(查询未命中而回退到通用形状不算修正);`user` 表示用户在设置中手改的值,永不被-替换。该字段可选,因此早于该标记写出的配置仍可读,旧客户端会忽略它。host-core 只-保留这两个取值、丢弃其它值,避免出现第三种无人识别的状态。解析规则见+`models[].contextWindowSource` 与 `models[].maxTokensSource` 分别记录各自限额的来源。+`catalog` 表示 models.dev 快照,之后对应目录字段的修正可以替换它(查询未命中而回退到+通用形状不算修正);`user` 表示用户在设置中输入的值,永不被目录覆盖。修改上下文窗口+不会改变最大输出 token 的来源。两个字段都是可选的,旧配置仍可读,旧客户端会忽略它们。+host-core 只保留 `catalog` / `user`,丢弃其他值。没有来源标记的旧记录会保留已存限额,+包括通用的 128,000 / 8,192,因为旧值无法表明它是通用种子还是用户显式选择。解析规则见[13-model-catalog-and-selection](13-model-catalog-and-selection.md) §9.1。+`supportsImages` 与 `supportsDocuments` 缺省或为 `null` 时跟随已发布能力,直到用户+主动更改复选框。用户一旦选择,显式布尔值就会固定保存;即使当前值与目录相同,之后的+目录修正也不会撤销用户选择。+`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 72be3ca60..49e9b759e 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@@ -213,24 +213,19 @@ type ModelCatalogItem = {### 9.1 有效模型上限-运行时、上下文检查器与设置界面解析同一个有效窗口与输出上限。每个绑定记录它的-`contextWindow` 从何而来(`contextWindowSource`),该标记同样作用于 `maxTokens`:--- `catalog` —— 该数值是 models.dev 的取值,之后 `limit.context` 或 `limit.output`- 的修正会替换它。刷新后的记录(例如 `gpt-5.6-luna`,1,050,000 tokens)不再显示为- 128k 模型;在目录还没有该 ID 时加入的行,一旦记录解析出来就不再显示通用的 8.2k- 输出上限;被 models.dev 修正的数值无需删除再重新添加即可到达该绑定。只有解析出来的- models.dev 记录才算「已发布」:查询未命中而回退到通用形态时(例如自定义网关地址- 提供的是一个多家发布方都在列的 ID),它的 `128,000` 与 `8,192` 不算修正,- 已保存的目录快照继续生效。-- `user` —— 该数值来自单个模型「高级」里的输入(或其中的预设档位),目录永不替换它,- 包括本来就是通用种子值的 `128,000` 与 `8,192`。--在该标记出现之前写入的绑定没有来源标记,它们沿用历史规则且行为确定:已发布的-`limit.context` 只替换通用的 `128,000`,已发布的 `limit.output` 只替换通用的-`8,192`,其余保存值都视为用户显式值。未知模型仍使用保守的 128k / 8.2k 通用上限,-绝不会仅凭 ID 形态被提升。该标记在持久化记录中是可选的,因此旧版本写入的配置仍可读,-降级也不会因此出错。+运行时、上下文检查器与设置界面解析同一个有效窗口与输出上限。两个限额的来源分别保存:+`contextWindowSource` 只适用于 `contextWindow`,`maxTokensSource` 只适用于 `maxTokens`。++- `catalog` —— 对应限额是 models.dev 快照,之后该目录字段的修正可以替换它。刷新后的+ 长上下文模型(例如 `gpt-5.6-luna`,1,050,000 tokens)不再显示为 128k 模型;在目录+ 尚未收录该 ID 时加入的行,记录解析后也不再显示通用的 8.2k 输出上限。只有成功解析+ 的 models.dev 记录才算已发布;查询未命中、回退到通用形态时不算目录修正。+- `user` —— 该限额来自单个模型「高级」里的输入或预设档位,目录永不替换它,包括与+ 通用种子相同的 128,000 或 8,192。设置上下文窗口不会改变最大输出 token 的来源。++来源标记出现前写入的绑定会保留已有上下文窗口和输出上限,包括通用的 128,000 与+8,192,因为旧记录无法区分通用种子和用户选择。只有明确标记为 `catalog` 的值才跟随+后续目录修正。两个标记均为可选,旧版本配置仍可读,降级客户端会忽略它们。用户配置的值仍会持久化并显示在「高级」中,但提供商安全不会信任超过已知已发布窗口的放大覆盖:出站输出上限、自动压缩与溢出判定取配置值与已发布值中较小的一方;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 13730f607..561f282e4 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@@ -276,6 +276,14 @@ task-candidate E2E 从请求工作树运行,但使用主工作区已经准备- **里程碑**:M2- **状态**:自动(协议烟雾:提供商创建+秘密,无明文回显)+#### E2E-PROVIDER-keep-explicit-model-overrides:目录刷新不覆盖用户限额与能力选择++- **前提条件**:已配置一个目录发布上下文窗口、最大输出 token 和图片输入能力的模型。+- **步骤**:编辑该模型,将最大输出 token 设为通用种子值 8,192;将图片输入开关先关再开,使显式选择与当前目录值相同;保存并重开设置。再用更新后的目录记录刷新该模型。+- **预期**:最大输出 token 仍是 8,192,且来源标记为 `user`,即使上下文窗口来源为 `catalog`;图片输入仍保持用户显式选择。目录修正只更新来源标记为 `catalog` 的限额,不会把用户显式设置重新解释为跟随目录。+- **关联规格**:`03-runtime/11-provider-model-system.md`、`03-runtime/12-provider-config-schema.md`、`03-runtime/13-model-catalog-and-selection.md`+- **状态**:由 shared/runtime 与 host-core 回归测试覆盖;真实桌面 UI 验收待执行+#### E2E-PROVIDER-defaults-survive-an-added-provider:新增提供商不改写应用默认值- **前提条件**:应用运行;提供商 A 已保存并设为应用默认模型;另有提供商 B 提供不同的模型;A 上配置了一个图片模型,另一家服务上也配置了一个。diff --git a/packages/agent-runtime/src/model-capabilities.test.ts b/packages/agent-runtime/src/model-capabilities.test.tsindex 54cb30bf3..266b4e783 100644--- a/packages/agent-runtime/src/model-capabilities.test.ts+++ b/packages/agent-runtime/src/model-capabilities.test.ts@@ -78,7 +78,7 @@ describe("main-supplied model capabilities", () => {});});- it("uses the published long-context window when a legacy binding has the generic seed", () => {+ it("uses the published long-context window when a binding marks its seed as catalog-owned", () => {const model = {...knownModel(),contextWindow: 1_050_000,@@ -86,6 +86,7 @@ describe("main-supplied model capabilities", () => {};const configured = modelConfigWithBinding(model, {contextWindow: 128_000,+ contextWindowSource: "catalog",maxTokens: 8_192,thinkingLevels: [],});@@ -93,6 +94,25 @@ describe("main-supplied model capabilities", () => {expect(configured.limit?.context).toBe(1_050_000);});+ it("does not use a generic fallback to replace a catalog snapshot", () => {+ const configured = modelConfigWithBinding(genericModelConfig("gateway-model"), {+ contextWindow: 1_000_000,+ contextWindowSource: "catalog",+ maxTokens: 8_192,+ thinkingLevels: [],+ });+ expect(configured.contextWindow).toBe(1_000_000);+ });++ it("preserves a legacy stored context window without provenance", () => {+ const configured = modelConfigWithBinding(knownModel(), {+ contextWindow: 128_000,+ maxTokens: 8_192,+ thinkingLevels: [],+ });+ expect(configured.contextWindow).toBe(128_000);+ });+it("applies binding limits and preserves explicit thinking levels", () => {const configured = modelConfigWithBinding({diff --git a/packages/agent-runtime/src/model-capabilities.ts b/packages/agent-runtime/src/model-capabilities.tsindex 4593188e0..3cb939cfb 100644--- a/packages/agent-runtime/src/model-capabilities.ts+++ b/packages/agent-runtime/src/model-capabilities.ts@@ -63,9 +63,9 @@ export function capabilitiesFromModelInfo(model?: ModelInfo | null): ModelCapabi/*** Apply explicit per-provider model settings. Thinking levels and output limits- * come from the user's binding. A legacy/generated 128k context value is treated- * as the generic fallback when a published catalog window is available; every- * other context value remains an explicit Advanced override.+ * come from the user's binding. Only a context window explicitly marked as+ * catalog-sourced follows a published correction; an unmarked legacy value is+ * preserved because it may be the user's exact 128k override.*/export function modelConfigWithBinding(model: ModelConfig,@@ -73,6 +73,7 @@ export function modelConfigWithBinding(| Pick<ModelBinding,| "contextWindow"+ | "contextWindowSource"| "maxTokens"| "thinkingLevels"| "supportsImages"@@ -97,9 +98,15 @@ export function modelConfigWithBinding(thinkingLevelMap[level] = level;}}+ const publishedContextWindow = model.source === "generic"+ ? undefined+ : model.contextWindow;const contextWindow =- effectiveContextWindow(model.contextWindow, binding.contextWindow) ??- model.contextWindow;+ effectiveContextWindow(+ publishedContextWindow,+ binding.contextWindow,+ binding.contextWindowSource,+ ) ?? model.contextWindow;const catalogContextWindow =model.catalogContextWindow ??(model.source === "models.dev" && model.contextWindow > 0diff --git a/packages/shared/src/model-catalog.test.ts b/packages/shared/src/model-catalog.test.tsindex 763e45d46..0b26cb2a5 100644--- a/packages/shared/src/model-catalog.test.ts+++ b/packages/shared/src/model-catalog.test.ts@@ -38,9 +38,9 @@ function textModel(): ModelInfo {}describe("effective model context windows", () => {- it("lets a published long-context window replace the legacy generic seed", () => {- expect(effectiveContextWindow(1_050_000, 128_000)).toBe(1_050_000);- expect(effectiveContextWindow(64_000, 128_000)).toBe(64_000);+ it("lets a published long-context window replace a catalog-marked seed", () => {+ expect(effectiveContextWindow(1_050_000, 128_000, "catalog")).toBe(1_050_000);+ expect(effectiveContextWindow(64_000, 128_000, "catalog")).toBe(64_000);});it("preserves a non-default per-model override", () => {@@ -50,9 +50,11 @@ describe("effective model context windows", () => {});describe("effective model output caps", () => {- it("lets a published cap replace the legacy generic seed", () => {- expect(effectiveMaxTokens(131_072, 8_192)).toBe(131_072);- expect(effectiveMaxTokens(64_000, 8_192)).toBe(64_000);+ it("preserves every unmarked stored cap, including the generic seed", () => {+ expect(effectiveMaxTokens(131_072, 8_192)).toBe(8_192);+ expect(effectiveMaxTokens(64_000, 8_192)).toBe(8_192);+ expect(effectiveMaxTokens(131_072, 32_000)).toBe(32_000);+ expect(effectiveMaxTokens(131_072, undefined)).toBe(131_072);});it("preserves a non-default cap, a user's number and a catalog snapshot", () => {@@ -71,6 +73,7 @@ describe("binding context-window provenance", () => {});expect(binding.contextWindow).toBe(1_048_576);expect(binding.contextWindowSource).toBe("catalog");+ expect(binding.maxTokensSource).toBe("catalog");});it("follows a catalog correction for a catalog-sourced window", () => {@@ -91,10 +94,10 @@ describe("binding context-window provenance", () => {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);+ it("preserves legacy stored windows when provenance is absent", () => {+ // An old 128k value cannot reveal whether it was a generic seed or the+ // user's explicit choice, so an upgrade must not replace it speculatively.+ expect(effectiveContextWindow(1_050_000, 128_000, undefined)).toBe(128_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);@@ -139,6 +142,7 @@ describe("binding context-window provenance", () => {contextWindow: 128_000,maxTokens: 8_192,contextWindowSource: "catalog" as const,+ maxTokensSource: "catalog" as const,};const published = { source: "models.dev", contextWindow: 1_048_576, maxTokens: 131_072 };const resolved = resolveBindingLimits(published, binding);@@ -147,12 +151,51 @@ describe("binding context-window provenance", () => {expect(resolved.catalogConfig.maxTokens).toBe(131_072);});- it("keeps the output cap and window the user set", () => {- const binding = { contextWindow: 128_000, maxTokens: 4_096, contextWindowSource: "user" as const };+ it("preserves both limits on an unmarked legacy binding", () => {const published = { source: "models.dev", contextWindow: 1_048_576, maxTokens: 131_072 };- const resolved = resolveBindingLimits(published, binding);- expect(resolved.binding.contextWindow).toBe(128_000);- expect(resolved.binding.maxTokens).toBe(4_096);+ const legacy = resolveBindingLimits(published, {+ contextWindow: 128_000,+ maxTokens: 8_192,+ });+ expect(legacy.binding.contextWindow).toBe(128_000);+ expect(legacy.binding.contextWindowSource).toBe("user");+ expect(legacy.binding.maxTokens).toBe(8_192);+ expect(legacy.binding.maxTokensSource).toBe("user");+ });++ it("keeps output ownership independent when only the context window follows the catalog", () => {+ const published = { source: "models.dev", contextWindow: 1_048_576, maxTokens: 131_072 };+ const legacyOutput = resolveBindingLimits(published, {+ contextWindow: 128_000,+ contextWindowSource: "catalog" as const,+ maxTokens: 8_192,+ });+ expect(legacyOutput.binding.contextWindow).toBe(1_048_576);+ expect(legacyOutput.binding.contextWindowSource).toBe("catalog");+ expect(legacyOutput.binding.maxTokens).toBe(8_192);+ expect(legacyOutput.binding.maxTokensSource).toBe("user");+ });++ it("keeps the output cap independently when the context window follows the catalog", () => {+ const published = { source: "models.dev", contextWindow: 1_048_576, maxTokens: 131_072 };+ const explicit = resolveBindingLimits(published, {+ contextWindow: 128_000,+ contextWindowSource: "catalog" as const,+ maxTokens: 8_192,+ maxTokensSource: "user" as const,+ });+ expect(explicit.binding.contextWindow).toBe(1_048_576);+ expect(explicit.binding.maxTokens).toBe(8_192);+ expect(explicit.binding.maxTokensSource).toBe("user");++ // Legacy rows have no output-cap marker. A non-generic stored value was+ // authoritative before provenance existed and must remain so.+ const legacy = resolveBindingLimits(published, {+ contextWindow: 1_048_576,+ contextWindowSource: "catalog" as const,+ maxTokens: 4_096,+ });+ expect(legacy.binding.maxTokens).toBe(4_096);});});@@ -196,6 +239,14 @@ describe("effective binding attachment capabilities", () => {);});+ it("keeps a capability the user explicitly selected when the catalog changes", () => {+ const selected = { supportsImages: true };+ // This was the published value when the user selected it; a later catalog+ // correction must not reinterpret that explicit choice as "follow".+ expect(bindingSupportsImages(selected, visionModel())).toBe(true);+ expect(bindingSupportsImages(selected, textModel())).toBe(true);+ });+it("treats an unknown model as unsupported unless the user answered", () => {// A hand-typed model ID has no published record, so nothing can be inferred.const custom = bindingForCustomModel("my-local-model");diff --git a/packages/shared/src/model-catalog.ts b/packages/shared/src/model-catalog.tsindex cf051eea5..7fb051c57 100644--- a/packages/shared/src/model-catalog.ts+++ b/packages/shared/src/model-catalog.ts@@ -13,7 +13,7 @@import { publishedThinkingLevels } from "./thinking-levels.js";import type {- ContextWindowSource,+ ModelLimitSource,ModelBinding,ModelInfo,ThinkingLevel,@@ -147,14 +147,14 @@ export const CATALOG_DEFAULT_MAX_TOKENS = 8_192;* 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.+ * A binding without provenance keeps its stored value. Older records cannot+ * distinguish an intentional 128k override from the generic seed, so inferring+ * catalog ownership would risk overwriting a user choice.*/export function effectiveContextWindow(publishedContextWindow?: number | null,configuredContextWindow?: number | null,- source?: ContextWindowSource | null,+ source?: ModelLimitSource | null,): number | undefined {const published = positiveTokenCount(publishedContextWindow);const configured = positiveTokenCount(configuredContextWindow);@@ -162,24 +162,22 @@ export function effectiveContextWindow(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;- }return configured;}/*** Resolve a model's effective output cap.*- * The provenance rule the context window follows, applied to `limit.output`: a- * `catalog` binding reads the published record, a `user` binding is the user's- * own number and is never replaced, and a binding written before the marker- * existed treats the generic 8.2k seed as inherited.+ * Output-cap provenance is independent from context-window provenance: a+ * `catalog` follows the published record and `user` is never replaced. A+ * legacy binding with no output-cap marker preserves its stored value, including+ * 8.2k: older records cannot distinguish that seed from an intentional user+ * choice. Changing a context window never changes output-cap ownership.*/export function effectiveMaxTokens(publishedMaxTokens?: number | null,configuredMaxTokens?: number | null,- source?: ContextWindowSource | null,+ source?: ModelLimitSource | null,): number | undefined {const published = positiveTokenCount(publishedMaxTokens);const configured = positiveTokenCount(configuredMaxTokens);@@ -187,9 +185,6 @@ export function effectiveMaxTokens(if (source === "catalog") return published ?? configured;if (source === "user") return configured ?? published;if (configured === undefined) return published;- if (published !== undefined && configured === CATALOG_DEFAULT_MAX_TOKENS) {- return published;- }return configured;}@@ -203,7 +198,7 @@ function positiveTokenCount(value?: number | null): number | undefined {/** Binding fields the limits resolver reads and rewrites. */type BindingLimits = Pick<ModelBinding, "contextWindow"> &- Partial<Pick<ModelBinding, "maxTokens" | "contextWindowSource">>;+ Partial<Pick<ModelBinding, "maxTokens" | "contextWindowSource" | "maxTokensSource">>;/*** Resolve a saved binding's limits against its catalog baseline for@@ -226,14 +221,20 @@ type BindingLimits = Pick<ModelBinding, "contextWindow"> &export function resolveBindingLimits<C extends { contextWindow?: number | null; maxTokens?: number | null; source?: string },B extends BindingLimits,->(catalogConfig: C, binding: B): { catalogConfig: C; binding: B };+>(catalogConfig: C, binding: B): {+ catalogConfig: C;+ binding: B & Partial<Pick<ModelBinding, "contextWindowSource" | "maxTokensSource">>;+};export function resolveBindingLimits<C extends { contextWindow?: number | null; maxTokens?: number | null; source?: string },B extends BindingLimits,>(catalogConfig: C,binding: B | null | undefined,-): { catalogConfig: C; binding: B | null | undefined };+): {+ catalogConfig: C;+ binding: (B & Partial<Pick<ModelBinding, "contextWindowSource" | "maxTokensSource">>) | null | undefined;+};export function resolveBindingLimits(catalogConfig: { contextWindow?: number | null; maxTokens?: number | null; source?: string },binding: BindingLimits | null | undefined,@@ -249,13 +250,21 @@ export function resolveBindingLimits(const publishedMax = publishedRecord? positiveTokenCount(catalogConfig.maxTokens): undefined;- const source = binding.contextWindowSource ?? undefined;- const resolved = effectiveContextWindow(published, binding.contextWindow, source);- const resolvedMax = effectiveMaxTokens(publishedMax, binding.maxTokens, source);+ const contextWindowSource = binding.contextWindowSource ?? "user";+ const resolved = effectiveContextWindow(+ published,+ binding.contextWindow,+ contextWindowSource,+ );+ // Older rows lack independent output provenance, so preserve their stored cap+ // rather than guessing whether the generic seed was a deliberate user choice.+ const maxTokensSource = binding.maxTokensSource ?? "user";+ const resolvedMax = effectiveMaxTokens(publishedMax, binding.maxTokens, maxTokensSource);+ const resolvedMaxSource = maxTokensSource;if (resolved === undefined && resolvedMax === undefined) {return { catalogConfig, binding };}- const inherited = source !== "user" && published !== undefined;+ const inherited = contextWindowSource === "catalog" && published !== undefined;return {catalogConfig: {...catalogConfig,@@ -267,10 +276,15 @@ export function resolveBindingLimits(...(resolved !== undefined? {contextWindow: resolved,- ...(inherited ? { contextWindowSource: "catalog" as const } : {}),+ contextWindowSource: inherited ? "catalog" as const : contextWindowSource,+ }+ : {}),+ ...(resolvedMax !== undefined+ ? {+ maxTokens: resolvedMax,+ ...(resolvedMaxSource ? { maxTokensSource: resolvedMaxSource } : {}),}: {}),- ...(resolvedMax !== undefined ? { maxTokens: resolvedMax } : {}),},};}@@ -290,6 +304,7 @@ export function bindingFromModelInfo(model: ModelInfo): ModelBinding {// correction still reaches this binding.contextWindowSource: "catalog",maxTokens: model.maxTokens || model.limit?.output || CATALOG_DEFAULT_MAX_TOKENS,+ maxTokensSource: "catalog",thinkingLevels,defaultThinkingLevel: thinkingLevels.includes("medium")? "medium"@@ -326,6 +341,7 @@ export function bindingForCustomModel(id: string): ModelBinding {contextWindow: CATALOG_DEFAULT_CONTEXT_WINDOW,contextWindowSource: "catalog",maxTokens: CATALOG_DEFAULT_MAX_TOKENS,+ maxTokensSource: "catalog",thinkingLevels: [],defaultThinkingLevel: null,supportsImages: null,diff --git a/packages/shared/src/model-config-import.ts b/packages/shared/src/model-config-import.tsindex 43655a1b9..baa7b133d 100644--- a/packages/shared/src/model-config-import.ts+++ b/packages/shared/src/model-config-import.ts@@ -13,7 +13,7 @@ import {} from "./model-catalog.js";import { matchNamedPreset, normalizeEndpointUrl } from "./provider-presets.js";import type {- ContextWindowSource,+ ModelLimitSource,ModelBinding,ProviderCreateInput,ThinkingLevel,@@ -825,9 +825,12 @@ function bindingFromGenericModel(// 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) ??+ importedModelLimitSource(record?.contextWindowSource) ??(contextWindow === undefined ? base.contextWindowSource : "user"),maxTokens: maxTokens ?? base.maxTokens,+ maxTokensSource:+ importedModelLimitSource(record?.maxTokensSource) ??+ (maxTokens === undefined ? base.maxTokensSource : "user"),...(record?.nativeWebSearch === true || record?.native_web_search === true? { nativeWebSearch: true }: {}),@@ -838,7 +841,7 @@ function bindingFromGenericModel(* A config exported by PI-Desktop carries the provenance marker; an older or* foreign config does not.*/-function importedContextWindowSource(value: unknown): ContextWindowSource | undefined {+function importedModelLimitSource(value: unknown): ModelLimitSource | undefined {return value === "catalog" || value === "user" ? value : undefined;}diff --git a/packages/shared/src/types/models.ts b/packages/shared/src/types/models.tsindex 2f98f97dc..782c19949 100644--- a/packages/shared/src/types/models.ts+++ b/packages/shared/src/types/models.ts@@ -223,14 +223,10 @@ export function catalogModelIdsMatch(candidate: string, requested: string): bool);}-/**- * 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";+/** Where a saved model limit came from; user-authored values are never replaced. */+export type ModelLimitSource = "catalog" | "user";+/** @deprecated Use ModelLimitSource; kept for existing context-window callers. */+export type ContextWindowSource = ModelLimitSource;/** Provider-local model settings persisted with the provider configuration. */export type ModelBinding = {@@ -244,18 +240,21 @@ export type ModelBinding = {* `effectiveContextWindow`. */contextWindowSource?: ContextWindowSource;maxTokens: number;+ /** Provenance of `maxTokens`, independent of `contextWindowSource`. */+ maxTokensSource?: ModelLimitSource;thinkingLevels: ThinkingLevel[];/** Canonical enabled level, or `omit` when new sessions should send no override. */defaultThinkingLevel: SessionThinkingLevel | null;/*** User override for image input. `null` or absent follows the published- * models.dev capability; `true` forces image transport on for an endpoint the- * catalog describes too narrowly, `false` keeps images out of the request.+ * models.dev capability. Once explicitly selected, either boolean is pinned+ * even when it matches today's catalog value.*/supportsImages?: boolean | null;/*** User override for document (PDF) input, with the same three-state meaning.- * Documents are still transported as bounded file references, so this records+ * An explicit boolean remains pinned if the catalog later changes. Documents+ * are still transported as bounded file references, so this records* the capability the model actually has rather than switching the encoding.*/supportsDocuments?: boolean | null;