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): read a relay's own capacity report and version notation
pengwei2694466689a3b6dc5d9c2
diff --git a/apps/desktop/electron/main/ipc/provider-ipc.ts b/apps/desktop/electron/main/ipc/provider-ipc.tsindex 9926a5831..101b007fe 100644--- a/apps/desktop/electron/main/ipc/provider-ipc.ts+++ b/apps/desktop/electron/main/ipc/provider-ipc.ts@@ -451,8 +451,12 @@ export function registerProviderIpc({modelId: model.modelId,displayName: info.displayName || modelConfig.name,providerId: provider?.id ?? "",- contextWindow: operationMetadata?.contextWindow ?? modelConfig.contextWindow,- maxTokens: operationMetadata?.maxTokens ?? modelConfig.maxTokens,+ // The service's own model-list row states what it actually gives;+ // an endpoint that reports capacity outranks both the catalog and+ // any stored value it carries (PiDeck parity: reported > catalog >+ // nothing — an omission is never a guess).+ contextWindow: model.contextWindow ?? operationMetadata?.contextWindow ?? modelConfig.contextWindow,+ maxTokens: model.maxTokens ?? operationMetadata?.maxTokens ?? modelConfig.maxTokens,// Published modalities, taken before the binding is applied. This// record is what the settings panel compares its checkboxes against,// so letting a stored override shape it would make the override itsdiff --git a/apps/desktop/electron/main/model-discovery.ts b/apps/desktop/electron/main/model-discovery.tsindex edc54c381..2f0d89f3b 100644--- a/apps/desktop/electron/main/model-discovery.ts+++ b/apps/desktop/electron/main/model-discovery.ts@@ -24,6 +24,14 @@ import {export type DiscoveredModel = {modelId: string;displayName: string;+ /**+ * Capacity the service itself reported on its model-list row+ * (`context_window` / `context_length` / `inputTokenLimit` / …). Endpoint-+ * reported values outrank catalog enrichment; absent means the service+ * stated nothing, so nothing is guessed.+ */+ contextWindow?: number;+ maxTokens?: number;};export const DISCOVERY_TIMEOUT_MS = 10_000;@@ -84,6 +92,42 @@ function dedupeSort(models: DiscoveredModel[]): DiscoveredModel[] {.slice(0, MAX_MODELS);}+/**+ * The first positive 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+ * small, so nothing is guessed in its place.+ */+function firstPositiveInteger(row: Record<string, unknown> | null | undefined, keys: readonly string[]): number | undefined {+ if (!row) return undefined;+ for (const key of keys) {+ const value = row[key];+ if (typeof value === "number" && Number.isInteger(value) && value > 0) return value;+ }+ return undefined;+}++/** Context capacity the service itself stated on the row, or nothing. */+function reportedContextWindow(row: Record<string, unknown> | null): number | undefined {+ return firstPositiveInteger(row, [+ "context_window",+ "context_length",+ "inputTokenLimit",+ "contextWindow",+ ]);+}++/** Output capacity the service itself stated on the row, or nothing. */+function reportedMaxTokens(row: Record<string, unknown> | null): number | undefined {+ return firstPositiveInteger(row, [+ "max_output_tokens",+ "max_tokens",+ "outputTokenLimit",+ "maxTokens",+ ]);+}+/*** Normalize a model-list response body. Pure.*@@ -110,7 +154,16 @@ export function normalizeModelList(typeof item?.displayName === "string" && item.displayName? item.displayName: modelId;- return [{ modelId, displayName }];+ const contextWindow = reportedContextWindow(item);+ const maxTokens = reportedMaxTokens(item);+ return [+ {+ modelId,+ displayName,+ ...(contextWindow !== undefined ? { contextWindow } : {}),+ ...(maxTokens !== undefined ? { maxTokens } : {}),+ },+ ];}),);}@@ -132,7 +185,16 @@ export function normalizeModelList(typeof item?.display_name === "string" && item.display_name? item.display_name: modelId;- return [{ modelId, displayName }];+ const contextWindow = reportedContextWindow(item);+ const maxTokens = reportedMaxTokens(item);+ return [+ {+ modelId,+ displayName,+ ...(contextWindow !== undefined ? { contextWindow } : {}),+ ...(maxTokens !== undefined ? { maxTokens } : {}),+ },+ ];}),);}diff --git a/apps/desktop/electron/main/models-dev-catalog.ts b/apps/desktop/electron/main/models-dev-catalog.tsindex 4a775851e..58aa35c97 100644--- a/apps/desktop/electron/main/models-dev-catalog.ts+++ b/apps/desktop/electron/main/models-dev-catalog.ts@@ -108,6 +108,13 @@ export type ModelsDevModel = {cost?: ModelCost;interleaved?: ModelInterleaved;status?: string;+ /**+ * The catalog's internal name for this model's current generation+ * (models.dev `canonical_model_id`, e.g. `deepseek/deepseek-v4.1-flash`).+ * A relay may serve this canonical name directly; only the owner's own+ * records answer it.+ */+ canonicalModelId?: string;experimental?: ModelExperimentalMetadata;provider?: ModelProviderMetadata;};@@ -501,6 +508,9 @@ function modelFromRaw(? { interleaved: parseInterleaved(raw.interleaved) }: {}),...(nonEmptyString(raw.status) ? { status: nonEmptyString(raw.status) } : {}),+ ...(nonEmptyString(raw.canonical_model_id)+ ? { canonicalModelId: nonEmptyString(raw.canonical_model_id) }+ : {}),...(experimental !== undefined ? { experimental } : {}),...(providerMetadata !== undefined ? { provider: providerMetadata } : {}),...(modelApi !== undefined ? { modelApi } : {}),@@ -1207,6 +1217,46 @@ function relayDeploymentSuffixStrip(value: string): string | undefined {return match[1];}+/**+ * Notation aliases of a versioned leaf: `4.5` reads as `4-5` and back. A relay+ * may name a generation in either spelling; each alias is checked as a whole+ * published id, so an alias that the catalog does not publish simply stays+ * unmatched.+ */+function dotsToDashes(value: string): string {+ return value.includes(".") ? value.replace(/\./g, "-") : value;+}++function dashesToDots(value: string): string {+ // Only the dashes between two digits form a version (`3-1` reads as `3.1`);+ // the dashes that join semantic parts stay in place.+ return value.replace(/(?<=\d)-(?=\d)/g, ".");+}++/**+ * The relay id's leaves to check against the owner's published records: the+ * leaf itself, its dotted/dashed notation aliases, and — after one whitelisted+ * deployment label is stripped — those aliases again. No alias chain is+ * followed and the wire id is never rewritten.+ */+function relayNotationCandidates(requested: string): string[] {+ const out: string[] = [];+ const push = (value?: string) => {+ if (value && !out.includes(value)) out.push(value);+ };+ const leaf = leafOf(requested);+ push(leaf);+ push(dotsToDashes(leaf));+ push(dashesToDots(leaf));+ const base = relayDeploymentSuffixStrip(leaf);+ if (base) {+ push(base);+ push(dotsToDashes(base));+ push(dashesToDots(base));+ }+ return out;+}+/*** Published ids to read when nothing the catalog publishes matches the id the* service serves: the id behind a route prefix, and that id without one@@ -1571,9 +1621,8 @@ export class ModelsDevCatalog {(an unidentified relay) still answers when the model's own family namesa publisher the catalog ships: the weight owner's record is whatdescribes the model the relay serves, not a reseller's flags about its- own deployment. Deployment-marker / variant-suffix fallbacks areintentionally not applied to the borrowed result (approved #1047- matching rules). */+ matching rules); when the owner states nothing, the row stays plain. */const borrowed = result ?? deploymentFallback ??(preferredProvider ? this.borrowedAcrossProviders(input) : this.unanchoredOwnerRecord(requested));// Cache the result (a miss included) so a repeated miss is also O(1) and@@ -1694,15 +1743,19 @@ export class ModelsDevCatalog {* record and keeps its window and output visible instead of dropping to* the generic 128k text-only seed.*- * Two rules keep the result honest:+ * The rules that keep the result honest:** - Only the owner's own records answer. Reseller copies and route* prefixes never participate, and a split owner answer still states* nothing.* - The wire ID is never rewritten: at most one whitelisted deployment- * label (`-1m`, `-test`, …) is stripped to reach the owner's published- * base ID; model variants such as `-thinking` or dated releases are- * distinct models and stay unmatched.+ * label (`-1m`, `-test`, …) is stripped, and a dotted/dashed notation+ * alias (`4.5` reads as `4-5`) is tried, to reach the owner's+ * published ID; model variants such as `-thinking` or dated releases+ * are distinct models and stay unmatched.+ * - When the relay names the owner's canonical generation id (the+ * 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 {const ownerKey = RELAY_FAMILY_PUBLISHERS[leafOf(requested).split(/[-.]/)[0] ?? ""];@@ -1715,22 +1768,58 @@ export class ModelsDevCatalog {ownerKeys.has(normalizedProviderKey(provider.providerKey)),).map((entry) => entry.model);- let lookupId = leafOf(requested);- let hits = ownerHits(lookupId);- // Remove one whitelisted trailing label at a time, stopping at the- // nearest published base ID; never rewrite the id used on the wire.- while (hits.length === 0) {- const base = relayDeploymentSuffixStrip(lookupId);- if (!base) break;- lookupId = base;- hits = ownerHits(lookupId);+ const pick = (hits: ModelsDevModel[]): ModelsDevModel | 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];+ }+ return undefined;+ };+ // 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 (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];+ // The relay named the owner's canonical generation id; the owner's own+ // live record for it answers.+ return this.canonicalOwnerRecord(ownerKeys, candidates);+ }++ /**+ * The owner's record whose canonical id (models.dev `canonical_model_id`,+ * owner-prefixed) is one of the requested leaves. A non-deprecated record+ * wins; when the owner's aliases for one canonical model disagree on shape+ * 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 {+ if (targets.length === 0) return undefined;+ const wanted = new Set(targets.map((id) => normalizedModelId(leafOf(id))));+ const records = new Map<string, ModelsDevModel>();+ for (const provider of this.providers.values()) {+ if (!ownerKeys.has(normalizedProviderKey(provider.providerKey))) continue;+ for (const model of provider.models) {+ const canonical = model.canonicalModelId;+ if (!canonical) continue;+ if (!wanted.has(normalizedModelId(leafOf(canonical)))) continue;+ records.set(`${provider.providerKey}\u0000${model.modelId}`, model);+ }}- return undefined;+ const candidates = [...records.values()];+ if (candidates.length === 0) return undefined;+ const active = candidates.filter((model) => model.status?.toLowerCase() !== "deprecated");+ const pool = active.length > 0 ? active : candidates;+ if (pool.length === 1) return pool[0];+ const first = pool[0];+ const agreed = pool.every(+ (model) =>+ capabilitySignature(model) === capabilitySignature(first) &&+ JSON.stringify(model.limit) === JSON.stringify(first.limit),+ );+ return agreed ? pool[0] : undefined;}/**diff --git a/apps/desktop/test/model-discovery.test.mjs b/apps/desktop/test/model-discovery.test.mjsindex 5917782c9..834280c41 100644--- a/apps/desktop/test/model-discovery.test.mjs+++ b/apps/desktop/test/model-discovery.test.mjs@@ -37,7 +37,7 @@ test("a models[] response with slug rows is read as a list too", () => {{ slug: "glm-5.3" },],}),- [{ modelId: "glm-5.3", displayName: "glm-5.3" }],+ [{ modelId: "glm-5.3", displayName: "glm-5.3", contextWindow: 1_048_576 }],);// The two id keys are mutually exclusive; `id` wins if a gateway publishes both.assert.deepEqual(normalizeModelList("chat_completions", { models: [{ id: "m", slug: "s" }] }), [@@ -74,6 +74,31 @@ test("google lists strip the models/ prefix", () => {]);});+test("a model list's own capacity report is kept, nothing is guessed when absent", () => {+ const models = normalizeModelList("chat_completions", {+ data: [+ { id: "with-capacity", context_window: 1_000_000, max_output_tokens: 64_000 },+ { id: "openrouter-style", context_length: 200_000, max_tokens: 8_192 },+ { id: "gemini-style", inputTokenLimit: 1_048_576, outputTokenLimit: 65_536 },+ { id: "camel-style", contextWindow: 32_000, maxTokens: 4_096 },+ { id: "silent" },+ { id: "zero", context_window: 0 },+ ],+ });+ const byId = new Map(models.map((model) => [model.modelId, model]));+ assert.equal(byId.get("with-capacity").contextWindow, 1_000_000);+ assert.equal(byId.get("with-capacity").maxTokens, 64_000);+ assert.equal(byId.get("openrouter-style").contextWindow, 200_000);+ assert.equal(byId.get("openrouter-style").maxTokens, 8_192);+ assert.equal(byId.get("gemini-style").contextWindow, 1_048_576);+ assert.equal(byId.get("gemini-style").maxTokens, 65_536);+ assert.equal(byId.get("camel-style").contextWindow, 32_000);+ // An omitted or non-positive capacity states nothing: no guessed default.+ assert.equal(byId.get("silent").contextWindow, undefined);+ assert.equal(byId.get("silent").maxTokens, undefined);+ assert.equal(byId.get("zero").contextWindow, undefined);+});+test("requests use per-style endpoints and auth headers", () => {const openai = modelListRequest({baseUrl: "https://api.example.com/v1/",diff --git a/apps/desktop/test/models-dev-catalog.test.mjs b/apps/desktop/test/models-dev-catalog.test.mjsindex 2bc87cdb6..24f0dc7b8 100644--- a/apps/desktop/test/models-dev-catalog.test.mjs+++ b/apps/desktop/test/models-dev-catalog.test.mjs@@ -1850,3 +1850,65 @@ test("a host two publishers share leaves conflicting leaves unmatched", async (tassert.equal(alpha?.providerKey, "alpha");assert.equal(alpha?.limit.context, 1_000_000);});++test("a relay's dotted version name reads the owner's dashed published record", async (t) => {+ // `claude-sonnet-4.5` is Claude's `claude-sonnet-4-5`: a notation difference,+ // not a distinct model, so the owner's own published record answers.+ const catalog = await loadFixtureCatalog(t, {+ gateway: { api: "https://gateway.example/v1", models: {} },+ anthropic: { models: { "claude-sonnet-4-5": {+ id: "claude-sonnet-4-5", tool_call: true, limit: { context: 200_000, output: 64_000 },+ } } },+ });+ const match = catalog.findModel({+ vendorKey: "custom", baseUrl: "https://relay.example/v1", modelId: "claude-sonnet-4.5",+ });+ assert.ok(match, "a dotted version alias must reach the owner's published record");+ assert.equal(match.providerKey, "anthropic");+ assert.equal(match.modelId, "claude-sonnet-4-5", "the wire id is never rewritten");+ assert.equal(match.limit.context, 200_000);+ assert.equal(match.limit.output, 64_000);+});++test("a relay's canonical generation name reads the owner's live record", async (t) => {+ // The relay serves `deepseek-v4.1-flash` — models.dev's canonical id for+ // DeepSeek's current flash model, which DeepSeek publishes only under version+ // aliases. The live (non-deprecated) alias is what answers.+ const catalog = await loadFixtureCatalog(t, {+ gateway: { api: "https://gateway.example/v1", models: {} },+ deepseek: { models: {+ "deepseek-flash": {+ id: "deepseek-flash", tool_call: true,+ canonical_model_id: "deepseek/deepseek-v4.1-flash",+ limit: { context: 1_000_000, output: 393_216 },+ },+ "deepseek-v4-flash": {+ id: "deepseek-v4-flash", tool_call: true, status: "deprecated",+ canonical_model_id: "deepseek/deepseek-v4.1-flash",+ limit: { context: 1_000_000, output: 393_216 },+ },+ } },+ });+ const match = catalog.findModel({+ vendorKey: "custom", baseUrl: "https://relay.example/v1", modelId: "deepseek-v4.1-flash",+ });+ assert.ok(match, "the owner's canonical id must not drop to the generic seed");+ assert.equal(match.providerKey, "deepseek");+ assert.equal(match.modelId, "deepseek-flash", "the live alias answers, not the deprecated one");+ assert.equal(match.limit.context, 1_000_000);+});++test("a generation name the catalog never publishes stays unmatched", async (t) => {+ // `gemini-3-flash` is a distinct (non-preview) model the catalog does not+ // publish; a preview record must not answer for it.+ const catalog = await loadFixtureCatalog(t, {+ gateway: { api: "https://gateway.example/v1", models: {} },+ google: { models: { "gemini-3-flash-preview": {+ id: "gemini-3-flash-preview", tool_call: true, limit: { context: 1_000_000 },+ } } },+ });+ assert.equal(catalog.findModel({+ vendorKey: "custom", baseUrl: "https://relay.example/v1", modelId: "gemini-3-flash",+ }), undefined);+});+