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 custom endpoint's metadata through its publishing host
vastsa5446e0967794
diff --git a/apps/desktop/electron/main/ipc/provider-ipc.ts b/apps/desktop/electron/main/ipc/provider-ipc.tsindex 0a2a49251..a6abd10b8 100644--- a/apps/desktop/electron/main/ipc/provider-ipc.ts+++ b/apps/desktop/electron/main/ipc/provider-ipc.ts@@ -136,8 +136,22 @@ export function registerProviderIpc({const modelId = (input?.modelId ?? "").trim();if (!modelId) return { info: null };await modelsDevCatalog.ensureLoaded();+ /*+ A hand-typed id on a custom endpoint names no publisher itself, so the+ host decides whose records to read — the same anchor the discovered list+ uses. A host the registry does not know keeps the caller's key (usually+ `custom`), where the snapshot only answers an unambiguous id. Pure: this+ stays a snapshot read with no network request or host call.+ */+ const declaredKey = input?.vendorKey;+ const lookupVendorKey =+ declaredKey && declaredKey !== "custom"+ ? declaredKey+ : typeof input?.baseUrl === "string" && input.baseUrl+ ? (inferEndpointProfile({ baseUrl: input.baseUrl })?.providerKey ?? declaredKey)+ : declaredKey;const model = modelsDevCatalog.findModel({- vendorKey: input?.vendorKey,+ vendorKey: lookupVendorKey,baseUrl: input?.baseUrl,modelId,});@@ -339,6 +353,20 @@ export function registerProviderIpc({// stays the key for cache writes: the cache belongs to the saved endpoint,// not to a suggestion.let endpointBaseUrl = profile?.effectiveBaseUrl ?? baseUrl;+ /*+ Which publisher's metadata this row is read against.++ A custom endpoint on a published host still serves that vendor's models,+ so when the row names no publisher itself the registry's identity for+ the host anchors the models.dev lookup. That is a host fact, not a guess+ from a model name. An unknown host keeps `custom`, where the catalog+ only answers an unambiguous id — metadata missing beats metadata wrong.+ */+ const catalogVendorKey =+ provider?.vendorKey && provider.vendorKey !== "custom"+ ? provider.vendorKey+ : (profile?.providerKey ?? "custom");+// Cache hydration must stay fast; the renderer already requests a live// refresh after it has painted the cached list. Live requests load the@@ -365,12 +393,12 @@ export function registerProviderIpc({catalogBaseUrl: string = endpointBaseUrl,) => {const modelsDevModel = modelsDevCatalog.findModel({- vendorKey: provider?.vendorKey || "custom",+ vendorKey: catalogVendorKey,baseUrl: catalogBaseUrl,modelId: model.modelId,});const catalogModelConfig = catalogModelConfigFor(modelsDevCatalog, {- vendorKey: provider?.vendorKey || "custom",+ vendorKey: catalogVendorKey,baseUrl: catalogBaseUrl,apiStyle: modelApiStyle,modelId: model.modelId,@@ -624,7 +652,7 @@ export function registerProviderIpc({// The endpoint published nothing usable (no /models route, an auth error,// or an empty list). The catalog is the fallback, not the primary source.const catalogModels = modelsDevCatalog.modelsForProvider({- vendorKey: provider?.vendorKey,+ vendorKey: catalogVendorKey,baseUrl: endpointBaseUrl,providerId: provider?.id ?? "",});diff --git a/apps/desktop/electron/main/models-dev-catalog.ts b/apps/desktop/electron/main/models-dev-catalog.tsindex c38742810..1abfce4b0 100644--- a/apps/desktop/electron/main/models-dev-catalog.ts+++ b/apps/desktop/electron/main/models-dev-catalog.ts@@ -629,6 +629,22 @@ export function apiMatches(left: string | undefined, right: string | undefined):return Boolean(normalizedLeft && normalizedRight && normalizedLeft === normalizedRight);}++/**+ * Hostname of a base URL, lowercased, or undefined when it has none.+ *+ * Only the host is read: two paths on one host can be the same publisher's+ * different API surfaces, which is exactly what `apiMatches` cannot see.+ */+function hostOfUrl(value: string | undefined): string | undefined {+ const raw = nonEmptyString(value);+ if (!raw) return undefined;+ try {+ return new URL(raw).host.toLowerCase() || undefined;+ } catch {+ return undefined;+ }+}function isTextAgentModel(model: ModelsDevModel): boolean {return model.modalities.input.includes("text") && model.modalities.output.includes("text");}@@ -989,6 +1005,8 @@ function borrowedModel(entries: readonly ModelsDevModel[]): ModelsDevModel | undexport class ModelsDevCatalog {private providers = new Map<string, ModelsDevProvider>();private lookupIndex: ModelsDevLookupIndex | undefined;+ /** Host → publishers, derived from the current provider map. */+ private hostIndex: Map<string, ModelsDevProvider[]> | undefined;private readonly lookupMemo = new Map<string, ModelsDevModel | undefined>();private loadPromise: Promise<boolean> | undefined;private loaded = false;@@ -1022,6 +1040,7 @@ export class ModelsDevCatalog {this.providers = new Map(parsed.map((provider) => [provider.providerKey, provider]));// Replacing the provider map invalidates the derived lookup index.this.lookupIndex = undefined;+ this.hostIndex = undefined;this.lookupMemo.clear();this.loaded = true;this.source = "bundled";@@ -1063,6 +1082,7 @@ export class ModelsDevCatalog {this.providers = new Map(parsed.map((provider) => [provider.providerKey, provider]));// Replacing the provider map invalidates the derived lookup index.this.lookupIndex = undefined;+ this.hostIndex = undefined;this.lookupMemo.clear();this.loaded = true;this.source = "remote";@@ -1117,9 +1137,41 @@ export class ModelsDevCatalog {);if (knownProvider) return knownProvider;}- return [...this.providers.values()].find((provider) =>+ const byKey = [...this.providers.values()].find((provider) =>candidates.has(normalizedProviderKey(provider.providerKey)),);+ return byKey ?? this.providerForUniqueHost(input.baseUrl);+ }++ /**+ * Publisher that uniquely owns this host, when nothing else identified the row.+ *+ * A custom endpoint on a published host is still that publisher's deployment:+ * a user who types `https://open.bigmodel.cn/api/v1` for the Responses API is+ * on Zhipu, not on an anonymous gateway. The catalog's own `api` host is the+ * evidence, and it is only used when exactly one provider publishes from it,+ * so a shared or unknown host still resolves to nothing — missing metadata+ * stays ahead of wrong metadata.+ *+ * Built lazily from the current provider map and cleared with the lookup+ * index, so it can never describe a previous catalog generation.+ */+ private providerForUniqueHost(baseUrl: string | undefined): ModelsDevProvider | undefined {+ const host = hostOfUrl(baseUrl);+ if (!host) return undefined;+ if (!this.hostIndex) {+ const index = new Map<string, ModelsDevProvider[]>();+ for (const provider of this.providers.values()) {+ const providerHost = hostOfUrl(provider.api);+ if (!providerHost) continue;+ const bucket = index.get(providerHost);+ if (bucket) bucket.push(provider);+ else index.set(providerHost, [provider]);+ }+ this.hostIndex = index;+ }+ const bucket = this.hostIndex.get(host);+ return bucket?.length === 1 ? bucket[0] : undefined;}findModel(input: { vendorKey?: string; baseUrl?: string; modelId: string }): ModelsDevModel | undefined {diff --git a/apps/desktop/test/models-dev-catalog.test.mjs b/apps/desktop/test/models-dev-catalog.test.mjsindex cd55d5a7e..71844bb5a 100644--- a/apps/desktop/test/models-dev-catalog.test.mjs+++ b/apps/desktop/test/models-dev-catalog.test.mjs@@ -1494,3 +1494,64 @@ test("an exact record answers an id its shorter siblings would only alias", asynassert.equal(published?.providerKey, "alpha");assert.equal(published?.limit.context, 128_000);});++/*+ A custom endpoint is often the same publisher on another path.++ The reported failure: a custom row at `https://open.bigmodel.cn/api/v1` listed+ its models but every one of them showed generic defaults, because provider+ matching only accepted models.dev's own path for that host.+*/+test("a custom endpoint on a uniquely published host inherits that publisher", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ alpha: {+ api: "https://alpha.example/api/paas/v4",+ models: {+ "glm-5.3": {+ id: "glm-5.3",+ reasoning: true,+ tool_call: true,+ limit: { context: 1_000_000, output: 131_072 },+ },+ },+ },+ });+ const model = catalog.findModel({+ vendorKey: "custom",+ baseUrl: "https://alpha.example/api/v1",+ modelId: "glm-5.3",+ });+ assert.equal(model?.providerKey, "alpha");+ assert.equal(model?.limit.context, 1_000_000);+ assert.equal(model?.toolCall, true);++ // The whole row's records are reachable, not just the one id.+ assert.equal(+ catalog.modelsForProvider({ vendorKey: "custom", baseUrl: "https://alpha.example/api/v1", providerId: "row" }).length,+ 1,+ );+});++test("a host two publishers share stays unresolved rather than guessed", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ alpha: {+ api: "https://shared.example/api/paas/v4",+ models: { "glm-5.3": { id: "glm-5.3", reasoning: true, limit: { context: 1_000_000 } } },+ },+ beta: {+ api: "https://shared.example/api/coding/v4",+ models: { "glm-5.3": { id: "glm-5.3", reasoning: false, limit: { context: 32_000 } } },+ },+ });+ // The path is not published, so the host is the only evidence — and it names+ // two publishers. Missing metadata beats metadata from the wrong one.+ assert.equal(+ catalog.findModel({ vendorKey: "custom", baseUrl: "https://shared.example/v1", modelId: "glm-5.3" }),+ undefined,+ );+ // Naming the publisher still resolves it.+ assert.equal(+ catalog.findModel({ vendorKey: "alpha", baseUrl: "https://shared.example/v1", modelId: "glm-5.3" })?.providerKey,+ "alpha",+ );+});diff --git a/apps/desktop/test/provider-endpoint-metadata.test.mjs b/apps/desktop/test/provider-endpoint-metadata.test.mjsnew file mode 100644index 000000000..fbb88c3dd--- /dev/null+++ b/apps/desktop/test/provider-endpoint-metadata.test.mjs@@ -0,0 +1,118 @@+/**+ * A custom endpoint on a published host still gets that publisher's metadata.+ *+ * The reported failure: a custom row pointed at `https://open.bigmodel.cn/api/v1`+ * (the Zhipu OpenAI Responses endpoint) listed its models but showed a generic+ * 128k / 8k text-only row for every one of them, while the same models are fully+ * described in models.dev — the catalog only accepted that host's own published+ * path, and the row declared no publisher of its own.+ *+ * This drives the real `providersListModels` handler with the bundled snapshot,+ * so it pins the whole chain: discovery, endpoint resolution, catalog anchoring.+ */+import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";++register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));++const { registerProviderIpc } = await import("../electron/main/ipc/provider-ipc.ts");+const { ModelsDevCatalog } = await import("../electron/main/models-dev-catalog.ts");+const { IPC } = await import("@pi-desktop/shared");++const catalogPath = new URL("../resources/models.dev/api.json", import.meta.url).pathname;++function jsonResponse(body, status = 200) {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json" },+ });+}++/** Register the real list-models handler against one row and one served list. */+async function listModelsFor(t, row, body) {+ const catalog = new ModelsDevCatalog({ catalogPath });+ assert.equal(await catalog.ensureLoaded(), true, "the bundled snapshot must load");++ const original = globalThis.fetch;+ const calls = [];+ globalThis.fetch = async (url) => {+ calls.push(String(url));+ return String(url).endsWith("/models") ? jsonResponse(body) : new Response("", { status: 404 });+ };+ t.after(() => {+ globalThis.fetch = original;+ });++ const handlers = new Map();+ registerProviderIpc({+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },+ getHost: () => ({+ call: async (method) => {+ if (method === "providers.list") return { providers: [row] };+ if (method === "providers.getSecret") return { value: "sk-secret" };+ if (method === "providers.get") return { provider: row };+ return {};+ },+ }),+ modelsDevCatalog: catalog,+ vendorOAuth: {},+ logger: { app: () => {} },+ enrichProvider: (provider) => provider,+ listRuntimeProviders: async () => [row],+ enrichProviderList: (result) => result,+ bindingForModel: () => undefined,+ });++ const handler = handlers.get(IPC.invoke.providersListModels);+ assert.equal(typeof handler, "function", "list-models handler is not registered");+ return { result: await handler({ providerId: row.id, source: "refresh" }), calls };+}++test("a custom row on a published host gets that publisher's model metadata", async (t) => {+ const row = {+ id: "row-1",+ name: "Zhipu",+ vendorKey: "custom",+ baseUrl: "https://open.bigmodel.cn/api/v1",+ apiStyle: "responses",+ models: [],+ authKind: "api_key_and_base_url",+ headers: {},+ };+ const { result, calls } = await listModelsFor(t, row, {+ models: [{ slug: "glm-5.3", display_name: "glm-5.3" }],+ });++ assert.deepEqual(calls, ["https://open.bigmodel.cn/api/v1/models"]);+ // The address the user typed answered, so it stays the row's address.+ assert.equal(result.effectiveBaseUrl, "https://open.bigmodel.cn/api/v1");++ const [model] = result.models;+ assert.equal(model.modelId, "glm-5.3", "the wire id is the one the service served");+ assert.equal(model.catalogSource, "models.dev", "the host identified the publisher");+ assert.equal(model.contextWindow, 1_000_000);+ assert.equal(model.maxTokens, 131_072);+ for (const capability of ["tools", "reasoning"]) {+ assert.ok(model.capabilities.includes(capability), `expected ${capability} capability`);+ }+});++test("a custom row on a host the catalog does not know keeps generic defaults", async (t) => {+ const row = {+ id: "row-2",+ name: "Relay",+ vendorKey: "custom",+ baseUrl: "https://relay.example/v1",+ apiStyle: "chat_completions",+ models: [],+ authKind: "api_key_and_base_url",+ headers: {},+ };+ const { result } = await listModelsFor(t, row, { data: [{ id: "some-private-model" }] });++ const [model] = result.models;+ assert.equal(model.catalogSource, undefined);+ assert.equal(model.contextWindow, 128_000);+ assert.deepEqual(model.capabilities, ["text"]);+});diff --git a/docs/spec/03-runtime/12-provider-config-schema.md b/docs/spec/03-runtime/12-provider-config-schema.mdindex ce4026aff..f5762e49b 100644--- a/docs/spec/03-runtime/12-provider-config-schema.md+++ b/docs/spec/03-runtime/12-provider-config-schema.md@@ -724,6 +724,18 @@ as empty. Connection testing reusesthe same request builder, so "the model list loaded" and "the connection testpassed" always describe the same URL, auth header and format.+### Which publisher a row is read against++A row that names no publisher of its own is read against the publisher its+endpoint identifies, in this order: the catalog entry whose published base URL+matches, the endpoint registry for a known host, then the catalog's own host+when exactly one provider publishes from it. That is what keeps a custom row on+a vendor's alternative API path — `https://open.bigmodel.cn/api/v1` for Zhipu's+OpenAI Responses endpoint — from showing generic 128k / 8k / text-only defaults+for models the catalog describes in full. A host two publishers share, or a host+the catalog does not know, resolves to nothing: a missing record stays ahead of+a wrong one. A model ID never decides which publisher is read.+Metadata matching may follow a release stamp: `mify/mimo-v2.5-pro-0731` borrowsthe published record of `mimo-v2.5-pro`, and a record the catalog publishesunder exactly the requested ID still wins over such an alias. The alias isdiff --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 f47157008..8e86aa5b9 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@@ -505,6 +505,14 @@ Chat Completions 配置使用同源 Responses。关闭搜索后恢复原配置当成空列表。连接测试复用同一套请求构造,因此「模型列表加载成功」与「连接测试通过」描述的始终是同一个地址、认证头与格式。+### 按哪个发布方读取元数据++行自身没有指明发布方时,按端点能识别的发布方来读,顺序是:已发布基础地址完全匹配的目录记录、+端点注册表中的已知主机、以及该主机在目录里恰好只有一个发布方时的这条记录。这样自定义行指向厂商+的另一个接口路径时(例如智谱 OpenAI Responses 端点 `https://open.bigmodel.cn/api/v1`),不会对+目录里已有完整描述的模型显示成通用的 128k / 8k / 纯文本默认值。多个发布方共用的主机、或目录不认识+的主机,一律不做匹配:宁可缺元数据,也不给错元数据。模型 ID 不参与判断该读哪个发布方。+元数据匹配可以跟随发布日期后缀:`mify/mimo-v2.5-pro-0731` 会借用 `mimo-v2.5-pro` 的发布记录,但目录中与该 ID 完全一致的记录仍然优先于这类别名。别名只影响元数据:已保存绑定的线上 ID 保持服务实际返回的原值。