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): prefer unambiguous relay owner limits
vastsab8634ea000d4
diff --git a/apps/desktop/electron/main/model-discovery.ts b/apps/desktop/electron/main/model-discovery.tsindex 2f0d89f3b..1ba9f5c9b 100644--- a/apps/desktop/electron/main/model-discovery.ts+++ b/apps/desktop/electron/main/model-discovery.ts@@ -93,7 +93,7 @@ function dedupeSort(models: DiscoveredModel[]): DiscoveredModel[] {}/**- * The first positive integer a row of a model list states for a capacity,+ * The first positive safe integer a row of a model list states for a capacity,* reading the OpenAI/Anthropic and Google/Gemini spellings side by side the* way the service's own console does. Zero, fractional and missing values* state nothing: an endpoint that omits a capacity is not evidence it is@@ -103,7 +103,7 @@ function firstPositiveInteger(row: Record<string, unknown> | null | undefined, kif (!row) return undefined;for (const key of keys) {const value = row[key];- if (typeof value === "number" && Number.isInteger(value) && value > 0) return value;+ if (typeof value === "number" && Number.isSafeInteger(value) && value > 0) return value;}return undefined;}diff --git a/apps/desktop/electron/main/models-dev-catalog.ts b/apps/desktop/electron/main/models-dev-catalog.tsindex 58aa35c97..8130761e3 100644--- a/apps/desktop/electron/main/models-dev-catalog.ts+++ b/apps/desktop/electron/main/models-dev-catalog.ts@@ -1610,21 +1610,19 @@ export class ModelsDevCatalog {const deploymentFallback = result? undefined: this.modelForDeploymentMarker(input.modelId, preferredProvider);- /* The row's own catalog provider did not publish this id. Borrowing needs a- known provider identity to anchor on: the row resolved to a catalog- provider whose own records are authoritative, so anything missing from it- can be checked against the other publishers of the exact id instead of- dropping the model to the generic shape.-- This only fills a miss the lookup already had — a record the preferred- provider does publish stays authoritative. A row the catalog cannot place- (an unidentified relay) still answers when the model's own family names- a publisher the catalog ships: the weight owner's record is what- describes the model the relay serves, not a reseller's flags about its- intentionally not applied to the borrowed result (approved #1047- matching rules); when the owner states nothing, the row stays plain. */- const borrowed = result ?? deploymentFallback ??- (preferredProvider ? this.borrowedAcrossProviders(input) : this.unanchoredOwnerRecord(requested));+ /* The row's own catalog provider stays authoritative. When an unanchored+ relay serves a known model family and the weight owner publishes a+ matching record, prefer that record over reseller consensus. An+ ambiguous owner answer stays generic; without an owner match, existing+ shared-record matching continues to apply. */+ const relayOwnerKey = preferredProvider+ ? undefined+ : RELAY_FAMILY_PUBLISHERS[leafOf(requested).split(/[-.]/)[0] ?? ""];+ const ownerRecord = relayOwnerKey ? this.unanchoredOwnerRecord(requested) : undefined;+ const borrowed = ownerRecord === null+ ? undefined+ : ownerRecord ?? result ?? deploymentFallback ??+ (preferredProvider ? this.borrowedAcrossProviders(input) : undefined);// Cache the result (a miss included) so a repeated miss is also O(1) and// cannot grow the candidate index with query-dependent keys.this.lookupMemo.set(memoKey, borrowed);@@ -1757,7 +1755,7 @@ export class ModelsDevCatalog {* catalog's internal name, e.g. `deepseek-v4.1-flash`), the owner's* own live record for that canonical id answers.*/- private unanchoredOwnerRecord(requested: string): ModelsDevModel | undefined {+ private unanchoredOwnerRecord(requested: string): ModelsDevModel | null | undefined {const ownerKey = RELAY_FAMILY_PUBLISHERS[leafOf(requested).split(/[-.]/)[0] ?? ""];if (!ownerKey) return undefined;const ownerKeys = new Set(providerKeyCandidates(ownerKey));@@ -1768,20 +1766,30 @@ export class ModelsDevCatalog {ownerKeys.has(normalizedProviderKey(provider.providerKey)),).map((entry) => entry.model);- const pick = (hits: ModelsDevModel[]): ModelsDevModel | undefined => {+ const pick = (hits: ModelsDevModel[]): ModelsDevModel | null | undefined => {+ if (hits.length === 0) return undefined;if (hits.length === 1) return hits[0];if (hits.length > 1) {const signature = capabilitySignature(hits[0]);- if (hits.every((model) => capabilitySignature(model) === signature)) return hits[0];+ const limit = JSON.stringify(hits[0].limit);+ if (+ hits.every(+ (model) =>+ capabilitySignature(model) === signature &&+ JSON.stringify(model.limit) === limit,+ )+ ) {+ return hits[0];+ }}- return undefined;+ return null;};// Notation aliases and one whitelisted deployment label, each checked as// a whole published id; the wire id is never rewritten.const candidates = relayNotationCandidates(requested);for (const candidate of candidates) {const hit = pick(ownerHits(candidate));- if (hit) return hit;+ if (hit !== undefined) return hit;}// The relay named the owner's canonical generation id; the owner's own// live record for it answers.@@ -1795,7 +1803,7 @@ export class ModelsDevCatalog {* nothing is claimed. Reseller copies never enter this set: only the* weight owner's records may answer a canonical name.*/- private canonicalOwnerRecord(ownerKeys: Set<string>, targets: string[]): ModelsDevModel | undefined {+ private canonicalOwnerRecord(ownerKeys: Set<string>, targets: string[]): ModelsDevModel | null | undefined {if (targets.length === 0) return undefined;const wanted = new Set(targets.map((id) => normalizedModelId(leafOf(id))));const records = new Map<string, ModelsDevModel>();@@ -1819,7 +1827,7 @@ export class ModelsDevCatalog {capabilitySignature(model) === capabilitySignature(first) &&JSON.stringify(model.limit) === JSON.stringify(first.limit),);- return agreed ? pool[0] : undefined;+ return agreed ? pool[0] : null;}/**diff --git a/apps/desktop/test/model-discovery.test.mjs b/apps/desktop/test/model-discovery.test.mjsindex 834280c41..103346520 100644--- a/apps/desktop/test/model-discovery.test.mjs+++ b/apps/desktop/test/model-discovery.test.mjs@@ -64,13 +64,23 @@ test("anthropic lists keep display names", () => {test("google lists strip the models/ prefix", () => {const models = normalizeModelList("google_generative_ai", {models: [- { name: "models/gemini-2.5-pro", displayName: "Gemini 2.5 Pro" },+ {+ name: "models/gemini-2.5-pro",+ displayName: "Gemini 2.5 Pro",+ inputTokenLimit: 1_048_576,+ outputTokenLimit: 65_536,+ },{ name: "models/gemini-2.5-flash" },],});assert.deepEqual(models, [{ modelId: "gemini-2.5-flash", displayName: "gemini-2.5-flash" },- { modelId: "gemini-2.5-pro", displayName: "Gemini 2.5 Pro" },+ {+ modelId: "gemini-2.5-pro",+ displayName: "Gemini 2.5 Pro",+ contextWindow: 1_048_576,+ maxTokens: 65_536,+ },]);});@@ -83,6 +93,7 @@ test("a model list's own capacity report is kept, nothing is guessed when absent{ id: "camel-style", contextWindow: 32_000, maxTokens: 4_096 },{ id: "silent" },{ id: "zero", context_window: 0 },+ { id: "unsafe", context_window: Number.MAX_SAFE_INTEGER + 1 },],});const byId = new Map(models.map((model) => [model.modelId, model]));@@ -97,6 +108,7 @@ test("a model list's own capacity report is kept, nothing is guessed when absentassert.equal(byId.get("silent").contextWindow, undefined);assert.equal(byId.get("silent").maxTokens, undefined);assert.equal(byId.get("zero").contextWindow, undefined);+ assert.equal(byId.get("unsafe").contextWindow, undefined);});test("requests use per-style endpoints and auth headers", () => {diff --git a/apps/desktop/test/models-dev-catalog.test.mjs b/apps/desktop/test/models-dev-catalog.test.mjsindex 24f0dc7b8..505d21997 100644--- a/apps/desktop/test/models-dev-catalog.test.mjs+++ b/apps/desktop/test/models-dev-catalog.test.mjs@@ -836,6 +836,51 @@ test("an unanchored relay reads its family owner's record over a conflicting resassert.equal(match?.limit.context, 1_048_576);});+test("an unanchored relay prefers its owner's limits over matching reseller copies", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ gateway: { api: "https://gateway.example/v1", models: {} },+ xiaomi: { models: { "mimo-v2.5": {+ id: "mimo-v2.5", tool_call: true,+ modalities: { input: ["text", "image"], output: ["text"] },+ limit: { context: 1_048_576, output: 131_072 },+ } } },+ reseller: { models: { "mimo-v2.5": {+ id: "mimo-v2.5", tool_call: true,+ modalities: { input: ["text", "image"], output: ["text"] },+ limit: { context: 262_144, output: 16_384 },+ } } },+ });++ const match = catalog.findModel({+ vendorKey: "custom",+ baseUrl: "https://relay.example/v1",+ modelId: "mimo-v2.5",+ });+ assert.equal(match?.providerKey, "xiaomi");+ assert.equal(match?.limit.context, 1_048_576);+ assert.equal(match?.limit.output, 131_072);+});++test("an unanchored relay stays generic when owner aliases disagree on capacity", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ gateway: { api: "https://gateway.example/v1", models: {} },+ minimax: { models: { "MiniMax-M2.7": {+ id: "MiniMax-M2.7", tool_call: true,+ limit: { context: 204_800, output: 131_072 },+ } } },+ "minimax-cn": { models: { "MiniMax-M2.7": {+ id: "MiniMax-M2.7", tool_call: true,+ limit: { context: 128_000, output: 65_536 },+ } } },+ });++ assert.equal(catalog.findModel({+ vendorKey: "custom",+ baseUrl: "https://relay.example/v1",+ modelId: "MiniMax-M2.7",+ }), undefined, "conflicting owner limits must not be chosen by catalog order");+});+test("unique leaf enrichment coexists with exact-id borrowing and unknown misses", async (t) => {const catalog = await loadFixtureCatalog(t, {gateway: { api: "https://gateway.example/v1", models: {} },@@ -1911,4 +1956,3 @@ test("a generation name the catalog never publishes stays unmatched", async (t)vendorKey: "custom", baseUrl: "https://relay.example/v1", modelId: "gemini-3-flash",}), undefined);});-diff --git a/apps/desktop/test/provider-endpoint-metadata.test.mjs b/apps/desktop/test/provider-endpoint-metadata.test.mjsindex 5a09cf54e..ac4014177 100644--- a/apps/desktop/test/provider-endpoint-metadata.test.mjs+++ b/apps/desktop/test/provider-endpoint-metadata.test.mjs@@ -142,6 +142,22 @@ test("a relay's list reads the shipped publisher's record for a known id", asyncassert.deepEqual(unknown.capabilities, ["text"]);});+test("a model-list capacity report takes precedence over catalog limits", async (t) => {+ const row = rowOf({+ id: "row-reported-capacity",+ name: "Relay",+ baseUrl: "https://relay.example/v1",+ });+ const { result } = await handlersFor(t, row, {+ data: [{ id: "claude-sonnet-4-5", context_length: 321_000, max_tokens: 12_345 }],+ });++ const [model] = result.models;+ assert.equal(model.contextWindow, 321_000, "the endpoint reports its actual context window");+ assert.equal(model.maxTokens, 12_345, "the endpoint reports its actual output limit");+ assert.equal(model.catalogSource, "models.dev", "catalog metadata still identifies the model");+});+test("a hand-typed id on the same relay answers with the same record", async (t) => {const row = rowOf({id: "row-3",diff --git a/docs/spec/03-runtime/13-model-catalog-and-selection.md b/docs/spec/03-runtime/13-model-catalog-and-selection.mdindex 1be12ad23..e6df84ac2 100644--- a/docs/spec/03-runtime/13-model-catalog-and-selection.md+++ b/docs/spec/03-runtime/13-model-catalog-and-selection.md@@ -276,11 +276,23 @@ remote catalog and uses no ambient credentials. `providers.refreshModelCatalog`refreshes models.dev explicitly; settings metadata lookups themselves are local.For keyed endpoints, live discovery supplies IDs and models.dev enriches their-metadata. For OAuth, the live account endpoint supplies entitled IDs, which are-then enriched from models.dev. Successful account lists are authoritative; a-failed list preserves the last usable IDs. A live-only ID with no models.dev-match stays generic; pi-ai sibling metadata never supplies its chat limits,-reasoning or price.+metadata. A positive safe integer context/input or output limit reported on a live+model-list row takes precedence over the catalog for that field; each field+falls back independently to catalog metadata when the endpoint omits it. An+omitted or non-positive value is not guessed. For OAuth, the live account+endpoint supplies entitled IDs, which are then enriched from models.dev.+Successful account lists are authoritative; a failed list preserves the last+usable IDs. A live-only ID with no service or catalog capacity stays generic;+pi-ai sibling metadata never supplies its chat limits, reasoning or price.++For an unanchored OpenAI-compatible relay, a known model family may use the+weight owner's published record when that owner names the model. This record+outranks shared reseller matches without changing the configured wire ID.+Lookup accepts dotted/dashed version notation, one whitelisted deployment+label, and the owner's published canonical generation ID; semantic variants+and unpublished generations remain distinct. If owner aliases disagree on+capabilities or limits, no owner record is borrowed. When the owner publishes+no matching record, the existing shared catalog matching rules still apply.`source: "cache"` reads Host caches and configured bindings without network.`source: "refresh"` probes the selected endpoint/account and decorates returneddiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 68d9bdf88..8511f4a0f 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -1065,11 +1065,17 @@ identify the platform validation still needed.- **Expected**: `providers.lookupModel` answers a hand-typed id from the local snapshot only — no provider network request and no host call — and a hit seeds the binding the way a picked model is seeded (published context window, max output tokens, thinking levels, `contextWindowSource: "catalog"`) while the stored id stays exactly what the user typed. A miss, a failed call, or an id the current discovery already described leaves the previous behavior intact: one usable row, the generic seed, and no stalled or duplicated list.A record published under another spelling of that id — a route prefix, a datedstamp, a marker the deployment appends — is a hit too: the row is upgraded in- place as soon as the answer arrives, without waiting for a save.+ place as soon as the answer arrives, without waiting for a save. In a live+ discovered row, a positive safe integer context/input or output limit reported by+ the endpoint takes precedence over the catalog for that field; omitted fields+ independently use catalog metadata. For an unanchored relay, a published+ owner record outranks reseller matches; dotted/dashed version aliases and one+ whitelisted deployment label keep the served ID intact, and conflicting+ owner records do not supply guessed limits.- **Specs linked**: `03-runtime/12-provider-config-schema.md`, `03-runtime/13-model-catalog-and-selection.md`- **Acceptance**: B (multi-model provider configuration)- **Milestone**: M2-- **Status**: Documented; covered by `apps/desktop/test/model-custom-lookup.test.mjs` and `apps/desktop/test/provider-lookup-model-handler.test.mjs`+- **Status**: Documented; covered by `apps/desktop/test/model-custom-lookup.test.mjs`, `apps/desktop/test/provider-lookup-model-handler.test.mjs`, and `apps/desktop/test/provider-endpoint-metadata.test.mjs`#### E2E-PROVIDER-configured-models-search: The chosen pane's search narrows the configured listdiff --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 012733b60..84f3e50ae 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@@ -55,6 +55,7 @@ AI 服务和 OAuth 厂商账户编辑器共用已选模型面板。每个已选- 提供商名称- 能力徽章- 可选的上下文窗口+- 服务模型列表为某字段报告正安全整数上下文/输入或输出上限时,该值优先于目录;未报告的字段独立回退到目录值。缺失或非正数不作猜测。- 上限值与用量计数经同一个紧凑格式化函数(`formatCompactTokenCount`)渲染:`M` 量级最多两位小数、`K` 量级一位小数,去掉末尾零;`K` 尾数若进位到 1000则提升到 `M` 量级。1M 附近的已发布窗口因此保持可区分(1000000 显示 `1M`,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 b15e2e44c..646bd2848 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@@ -391,10 +391,11 @@ task-candidate E2E 从请求工作树运行,但使用主工作区已经准备- **预期**:`providers.lookupModel` 只从本地快照回答手输 id —— 不访问提供商网络、不调用主机 —— 命中时按「被勾选的模型」同样的口径播种绑定(已发布的上下文长度、最大输出、思考等级,`contextWindowSource: "catalog"`),而存储的 id 保持用户输入的原样。未命中、调用失败,或该 id 已被本次发现结果描述过时,行为与之前一致:一行可用,通用种子,列表既不卡住也不重复。该 id 以另一种拼写发布(路由前缀、日期戳、部署自己追加的标记)同样算命中:答复到达即就地升级该行,不必等到保存。+- 实时发现的模型行若由服务报告正安全整数上下文/输入或输出上限,则该字段优先使用服务值;未报告字段独立回退到目录元数据。对于未锚定的中继,若模型所有者发布了匹配记录,则优先使用所有者记录;带点/连字符版本别名和一个白名单部署标签不会改写服务端 ID,所有者记录冲突时不会猜测限额。- **链接规格**:`03-runtime/12-provider-config-schema.md`、`03-runtime/13-model-catalog-and-selection.md`- **接受**:B(多模型提供商配置)- **里程碑**:M2-- **状态**:已文档化;由 `apps/desktop/test/model-custom-lookup.test.mjs` 与 `apps/desktop/test/provider-lookup-model-handler.test.mjs` 覆盖+- **状态**:已文档化;由 `apps/desktop/test/model-custom-lookup.test.mjs`、`apps/desktop/test/provider-lookup-model-handler.test.mjs` 与 `apps/desktop/test/provider-endpoint-metadata.test.mjs` 覆盖#### E2E-005H:从较长的服务模型列表一次全选当前可见模型