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(providers): ask a plan endpoint for its model list the way it documents (#1680)
chengzhi-cf21c550e7b45
diff --git a/apps/desktop/electron/main/ipc/provider-ipc.ts b/apps/desktop/electron/main/ipc/provider-ipc.tsindex 101b007fe..d3c741a61 100644--- a/apps/desktop/electron/main/ipc/provider-ipc.ts+++ b/apps/desktop/electron/main/ipc/provider-ipc.ts@@ -260,6 +260,17 @@ export function registerProviderIpc({baseUrl,apiKey: secret.value,apiStyle: detail.provider?.apiStyle,+ /*+ Resolved the same way the model list is resolved, so a service that+ publishes its model list in another style than it generates in (a+ subscription plan on Anthropic Messages) is tested with the+ credentials that actually answer.+ */+ discoveryStyle: inferEndpointProfile({+ baseUrl,+ apiStyle: normalizeApiStyle(detail.provider?.apiStyle),+ explicitApiStyle: true,+ })?.discoveryStyle,headers: detail.provider?.headers,signal: controller.signal,});diff --git a/apps/desktop/test/provider-stepfun-plan-discovery.test.mjs b/apps/desktop/test/provider-stepfun-plan-discovery.test.mjsnew file mode 100644index 000000000..0dc3c84aa--- /dev/null+++ b/apps/desktop/test/provider-stepfun-plan-discovery.test.mjs@@ -0,0 +1,126 @@+/**+ * A subscription endpoint whose model list authenticates differently from its+ * chat route.+ *+ * `https://api.stepfun.com/step_plan/v1` answers generation on Anthropic+ * Messages but accepts its model list only for `Authorization: Bearer`. The+ * row therefore used to derive `anthropic_models` — the style of the wire+ * format it generates in — so the probe sent `x-api-key`, took a 401, and the+ * settings dialog reported "API key rejected" for a valid key. Both surfaces+ * that ask the endpoint have to agree on the credentials that actually answer:+ * the model list and the connection test.+ *+ * This drives the real handlers and the real request builder, stubbing only+ * HTTP and host persistence.+ */+import assert from "node:assert/strict";+import { register } from "node:module";+import { fileURLToPath } from "node:url";+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 = fileURLToPath(new URL("../resources/models.dev/api.json", import.meta.url));++/** The reported row: the StepFun subscription preset, saved as its preset writes it. */+const stepfunPlanRow = {+ id: "stepfun-plan",+ name: "StepFun Plan",+ vendorKey: "stepfun-step-plan",+ enabled: true,+ hasSecret: true,+ authKind: "api_key_and_base_url",+ baseUrl: "https://api.stepfun.com/step_plan/v1",+ apiStyle: "anthropic_messages",+ headers: {},+ models: [],+};++function jsonResponse(body, status = 200) {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json" },+ });+}++async function handlersFor(t, row) {+ 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, init) => {+ calls.push({ url: String(url), method: init?.method ?? "GET", headers: init?.headers ?? {} });+ return init?.headers?.Authorization === "Bearer sk-secret"+ ? jsonResponse({ data: [{ id: "step-5-preview" }] })+ : jsonResponse({ error: { message: "Incorrect API key provided" } }, 401);+ };+ 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.get") return { provider: row };+ if (method === "providers.getSecret") return { value: "sk-secret" };+ if (method === "providers.testConnection") return { ok: true };+ return {};+ },+ }),+ modelsDevCatalog: catalog,+ vendorOAuth: {},+ logger: { app: () => {} },+ enrichProvider: (provider) => provider,+ listRuntimeProviders: async () => [row],+ bindingForModel: () => undefined,+ });++ return { calls, handlers };+}++test("the model list of an Anthropic-Messages plan is asked with a Bearer token", async (t) => {+ const { calls, handlers } = await handlersFor(t, stepfunPlanRow);++ const result = await handlers.get(IPC.invoke.providersListModels)({+ providerId: stepfunPlanRow.id,+ source: "refresh",+ });++ assert.deepEqual(calls.map((call) => call.url), [+ "https://api.stepfun.com/step_plan/v1/models",+ ]);+ assert.equal(calls[0].headers.Authorization, "Bearer sk-secret");+ assert.equal(calls[0].headers["x-api-key"], undefined, "the model list does not accept x-api-key");+ assert.deepEqual(+ result.models.map((model) => model.modelId),+ ["step-5-preview"],+ "the endpoint's own list is the answer",+ );+ assert.equal(result.source, "remote");+ assert.equal(result.discoveryStyle, "openai_models");+ assert.equal(result.effectiveBaseUrl, "https://api.stepfun.com/step_plan/v1");+});++test("the connection test of that row uses the same credentials as its model list", async (t) => {+ const { calls, handlers } = await handlersFor(t, stepfunPlanRow);++ const result = await handlers.get(IPC.invoke.providersTest)(stepfunPlanRow.id);++ assert.deepEqual(calls.map((call) => call.url), [+ "https://api.stepfun.com/step_plan/v1/models",+ ]);+ assert.equal(calls[0].headers.Authorization, "Bearer sk-secret");+ assert.equal(calls[0].headers["x-api-key"], undefined);+ assert.deepEqual(+ { ok: result.ok, network: result.network },+ { ok: true, network: "ok" },+ "a valid key must not be reported as rejected",+ );+});diff --git a/docs/guide/stepfun.md b/docs/guide/stepfun.mdindex 21a89125f..81efdebd6 100644--- a/docs/guide/stepfun.md+++ b/docs/guide/stepfun.md@@ -9,7 +9,10 @@The preset uses `https://api.stepfun.com/step_plan/v1` with **AnthropicMessages**. The runtime sends requests to `/step_plan/v1/messages`; it doesnot send subscription requests to the ordinary `/v1/messages` endpoint or-append a second `/v1` segment. The API format remains editable in Advanced.+append a second `/v1` segment. This deployment publishes its model list to+`Authorization: Bearer` rather than the Anthropic `x-api-key`, so fetching the+model list and testing the connection both authenticate with your API key as a+Bearer token. The API format remains editable in Advanced.Model availability still comes from the endpoint. If model discovery isunavailable, add the exact model ID manually. Published limits, inputdiff --git a/docs/spec/03-runtime/12-provider-config-schema.md b/docs/spec/03-runtime/12-provider-config-schema.mdindex 3666124bc..68bb7fb1c 100644--- a/docs/spec/03-runtime/12-provider-config-schema.md+++ b/docs/spec/03-runtime/12-provider-config-schema.md@@ -452,6 +452,17 @@ Step 5 Preview capabilities come from the bundled first-party models.devrecord; no supplemental catalog or hard-coded limits are needed. The ordinaryStepFun API and existing custom-provider rows retain their configuration.+Its model list is asked differently from its chat route: this deployment+publishes `GET /step_plan/v1/models` to `Authorization: Bearer`, so the preset+declares `discoveryStyle: "openai_models"` — a declared model-list style, not+one derived from `anthropic_messages`. Chat stays on Anthropic Messages while+the model-list probe and the connection test both send a Bearer token.++A declared style is a statement about the endpoint, not about one spelling of+it: it holds for the base URL and for a URL pasted with an operation suffix+(`/models`, `/messages`), which is stripped before resolution. Pasting back the+address the settings dialog itself offered therefore keeps the same model-list+authentication.Zhipu / Z.AI Completions requests still receive `thinkingFormat: "zai"` and`zaiToolStream: true`. pi-ai `zai-coding-cn` remains an alias of@@ -770,11 +781,13 @@ registry's `/api/paas/v4` sibling. The only generic extra path is `/v1` for anunknown OpenAI-compatible endpoint. Every published model-list shape is read —`data[].id`, Google's `models[].name`, and the `models[].slug` rows Zhipu'sOpenAI Responses endpoint returns — so an endpoint that answers is never treated-as empty. Connection testing reuses-the same request builder, so "the model list loaded" and "the connection test-passed" always describe the same URL, auth header and format. Anthropic-style-endpoints that return 404 because they intentionally publish no model list may-instead pass connection testing through a same-origin `OPTIONS /v1/messages`+as empty. Connection testing reuses the same request builder, so "the model list+loaded" and "the connection test passed" always describe the same URL, auth+header and format — including a deployment whose model list authenticates+differently from its chat route, where the endpoint's declared model-list style+is what both surfaces use. Anthropic-style endpoints that return 404 because+they intentionally publish no model list may instead pass connection testing+through a same-origin `OPTIONS /v1/messages`route probe; this proves reachability without sending credentials or a billablemodel request, while model IDs remain manual.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 243bb8cc7..a6bfb9f2e 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -9666,13 +9666,16 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.model discovery, explicitly select Step 5 Preview, then save.- **Expected**: The chooser and connection summary both visibly include`api.stepfun.com/step_plan/v1`. Discovery receives `https://api.stepfun.com/step_plan/v1`,- `anthropic_messages` and the entered key. Save retains that URL and format,+ `anthropic_messages`, and the entered key sent as `Authorization: Bearer` rather+ than the Anthropic `x-api-key`. Save retains that URL and format,the catalog vendor `stepfun-step-plan`, and the selected model. The ordinaryStepFun `/v1` endpoint is not substituted for the subscription endpoint.- **Automation**: `pnpm test:e2e:provider-api-style` uses real settings componentswith only the API boundary stubbed. `provider-presets.test.ts` checks thepreset contract and ordinary-endpoint separation; `service-catalog.test.mjs`- checks discoverability by localized label, name, vendor key, and URL.+ checks discoverability by localized label, name, vendor key, and URL;+ `provider-stepfun-plan-discovery.test.mjs` drives the real provider handlers+ and pins the Bearer model list for both discovery and the connection test.- **Scope**: Save/discovery payloads are covered; host persistence, live modelcalls, and visual layout are not asserted by this fixture.- **Specs linked**: `03-runtime/12-provider-config-schema.md`, `guide/stepfun.md`.diff --git a/packages/shared/src/model-catalog.ts b/packages/shared/src/model-catalog.tsindex f104a9539..6968e49c5 100644--- a/packages/shared/src/model-catalog.ts+++ b/packages/shared/src/model-catalog.ts@@ -32,6 +32,16 @@ export const API_STYLES = [export type CatalogApiStyle = (typeof API_STYLES)[number];+/**+ * How a model-list probe asks a service what it serves.+ *+ * This is deliberately narrower than {@link CatalogApiStyle}: a successful+ * `GET {base}/models` with `Authorization: Bearer` proves the endpoint answers+ * OpenAI-compatible discovery, and nothing about whether the generation call is+ * `/chat/completions`, `/responses` or something else.+ */+export type DiscoveryStyle = "openai_models" | "anthropic_models" | "google_models";+/*** Keep persisted provider rows editable when an older or newer client stored* an API style this renderer does not know yet. Runtime transport resolutiondiff --git a/packages/shared/src/provider-endpoint.test.ts b/packages/shared/src/provider-endpoint.test.tsindex ec03e8c71..7833a3f37 100644--- a/packages/shared/src/provider-endpoint.test.ts+++ b/packages/shared/src/provider-endpoint.test.ts@@ -198,6 +198,51 @@ describe("discovery candidates", () => {}});+ it("asks a named endpoint for its model list in the style that endpoint documents", () => {+ /*+ StepFun's subscription endpoint speaks Anthropic Messages for chat but+ publishes its model list the OpenAI way: it answers `Authorization:+ Bearer` and rejects the Anthropic `x-api-key` header with 401. The preset+ states that split, so the wire format stays Anthropic Messages while the+ probe authenticates the way this model list requires.+ */+ const profile = inferEndpointProfile({ baseUrl: "https://api.stepfun.com/step_plan/v1" });+ expect(profile?.apiStyle).toBe("anthropic_messages");+ expect(profile?.discoveryStyle).toBe("openai_models");+ expect(+ profile?.candidates.map((candidate) =>+ discoveryProbeUrl(candidate.baseUrl, candidate.discoveryStyle),+ ),+ ).toEqual(["https://api.stepfun.com/step_plan/v1/models"]);+ });++ it("keeps a declared model-list style when the base was pasted with its operation", () => {+ /*+ The settings form offers `.../step_plan/v1/messages` as the address, so a+ user may paste back a URL this app itself produced. That is the same+ deployment as the base endpoint, and it must keep the declared model-list+ style: the operation is stripped, so a style derived from the stripped+ path's wire format would describe an endpoint the row is not on.+ */+ for (const pasted of [+ "https://api.stepfun.com/step_plan/v1/models",+ "https://api.stepfun.com/step_plan/v1/messages",+ ]) {+ const profile = inferEndpointProfile({ baseUrl: pasted });+ expect(profile?.effectiveBaseUrl, pasted).toBe(+ "https://api.stepfun.com/step_plan/v1",+ );+ expect(profile?.apiStyle, pasted).toBe("anthropic_messages");+ expect(profile?.discoveryStyle, pasted).toBe("openai_models");+ expect(+ profile?.candidates.map((candidate) =>+ discoveryProbeUrl(candidate.baseUrl, candidate.discoveryStyle),+ ),+ pasted,+ ).toEqual(["https://api.stepfun.com/step_plan/v1/models"]);+ }+ });+it("keeps every candidate on the origin the user typed", () => {for (const baseUrl of ["https://api.foo.com",diff --git a/packages/shared/src/provider-endpoint.ts b/packages/shared/src/provider-endpoint.tsindex 18d84c119..5ec4aaef0 100644--- a/packages/shared/src/provider-endpoint.ts+++ b/packages/shared/src/provider-endpoint.ts@@ -18,19 +18,9 @@* probed.*/-import type { CatalogApiStyle } from "./model-catalog.js";+import type { CatalogApiStyle, DiscoveryStyle } from "./model-catalog.js";import { NAMED_ENDPOINT_PRESETS } from "./provider-presets.js";-/**- * How a model-list probe asks a service what it serves.- *- * This is deliberately narrower than {@link CatalogApiStyle}: a successful- * `GET {base}/models` with `Authorization: Bearer` proves the endpoint answers- * OpenAI-compatible discovery, and nothing about whether the generation call is- * `/chat/completions`, `/responses` or something else.- */-export type DiscoveryStyle = "openai_models" | "anthropic_models" | "google_models";-/** Where a resolved value came from, strongest first in the confidence table. */export type EndpointEvidenceType =| "explicit"@@ -99,6 +89,13 @@ export interface ProviderEndpointDefinition {baseUrls?: string[];apiStyle?: CatalogApiStyle;++ /**+ * Model-list style this endpoint documents, when it differs from the one+ * `apiStyle` implies. A service may publish its model list in another style+ * than it generates in, and only such a statement — never a derivation from+ * `apiStyle` — may override the resolved profile's probe style.+ */discoveryStyle?: DiscoveryStyle;/** Documented path suffixes for this provider's endpoints. */@@ -171,7 +168,7 @@ export const PROVIDER_ENDPOINT_DEFINITIONS: readonly ProviderEndpointDefinition[...(host ? { hosts: [host] } : {}),...(path ? { paths: [path] } : {}),apiStyle: preset.apiStyle,- discoveryStyle: discoveryStyleForApiStyle(preset.apiStyle),+ ...(preset.discoveryStyle ? { discoveryStyle: preset.discoveryStyle } : {}),};});@@ -344,6 +341,24 @@ export function inferEndpointProfile(input: EndpointProfileInput): EndpointProfidetail: operation.suffix,});}+ /*+ The registry is consulted twice: once for the URL as typed, and once for the+ base behind a pasted operation. `GET {base}/models` and `POST {base}/messages`+ are the same deployment, and provider documentation names the deployment by+ its operation URL, so an endpoint that states its model-list style states it+ for both spellings. The typed value is resolved before the form normalizes+ it, so a pasted `.../step_plan/v1/messages` would otherwise drop the+ declaration and probe a model list that answers only Bearer with `x-api-key`.+ */+ const declaredFromOperation =+ !registryByUrl && operation?.basePath !== undefined+ ? providerEndpointDefinitionForUrl(+ `${parsed.origin}${operation.basePath}`,+ canonicalEndpointUrl,+ )+ : undefined;+ const declaredDiscoveryStyle =+ registryByUrl?.discoveryStyle ?? declaredFromOperation?.discoveryStyle;if (registryByUrl?.apiStyle) {evidence.push({type: "known_endpoint",@@ -424,10 +439,13 @@ export function inferEndpointProfile(input: EndpointProfileInput): EndpointProfi/*The probe style follows the wire style that will actually be used, so"discovery succeeded" and "the row is configured this way" can never- disagree. A registry entry for the same host may still offer its own style- as a later candidate (see `buildDiscoveryCandidates`).+ disagree — unless the endpoint itself states how its model list is asked.+ StepFun Plan answers generation on Anthropic Messages but publishes its+ model list to a Bearer token, so a declaration outranks the derivation. A+ registry entry for the same host may still offer its own style as a later+ candidate (see `buildDiscoveryCandidates`).*/- profile.discoveryStyle = discoveryStyleForApiStyle(apiStyle);+ profile.discoveryStyle = declaredDiscoveryStyle ?? discoveryStyleForApiStyle(apiStyle);profile.candidates = buildDiscoveryCandidates(profile);return profile;}@@ -479,7 +497,8 @@ export function buildDiscoveryCandidates(profile: EndpointProfile): EndpointCandfor (const baseUrl of definition.baseUrls ?? []) {add({baseUrl,- discoveryStyle: definition.discoveryStyle ?? discoveryStyle,+ discoveryStyle:+ definition.discoveryStyle ?? discoveryStyleForApiStyle(definition.apiStyle),...(definition.apiStyle ? { apiStyleHint: definition.apiStyle } : {}),evidence: {type: "known_host",diff --git a/packages/shared/src/provider-presets.test.ts b/packages/shared/src/provider-presets.test.tsindex 152526fcf..6db92afe6 100644--- a/packages/shared/src/provider-presets.test.ts+++ b/packages/shared/src/provider-presets.test.ts@@ -182,12 +182,15 @@ describe("named endpoint presets", () => {});});- it("keeps StepFun Plan on its subscription endpoint and catalog vendor", () => {+ it("keeps StepFun Plan on its subscription endpoint, catalog vendor and model-list auth", () => {const expected = {id: "stepfun-plan",vendorKey: "stepfun-step-plan",baseUrl: "https://api.stepfun.com/step_plan/v1",apiStyle: "anthropic_messages",+ /* Chat is Anthropic Messages; this deployment publishes its models the+ OpenAI way, so the endpoint states that instead of it being derived. */+ discoveryStyle: "openai_models",};expect(NAMED_ENDPOINT_PRESETS.find((preset) => preset.id === expected.id)).toMatchObject(expected);expect(matchNamedPreset({ vendorKey: expected.vendorKey })).toMatchObject(expected);diff --git a/packages/shared/src/provider-presets.ts b/packages/shared/src/provider-presets.tsindex f93377d77..2b68a5da8 100644--- a/packages/shared/src/provider-presets.ts+++ b/packages/shared/src/provider-presets.ts@@ -1,6 +1,6 @@/** Shared identifiers and connection defaults for first-class provider presets. */-import type { CatalogApiStyle } from "./model-catalog.js";+import type { CatalogApiStyle, DiscoveryStyle } from "./model-catalog.js";export const OPENCODE_GO_API_STYLE = "opencode_go" as const;export const OPENCODE_GO_NAME = "OpenCode Go";@@ -13,6 +13,12 @@ export type NamedEndpointPreset = {name: string;baseUrl: string;apiStyle: CatalogApiStyle;+ /**+ * Model-list style this preset's deployment documents, when it differs from+ * the one `apiStyle` implies. Only a documented statement belongs here; a+ * derivation from `apiStyle` must not override the probe style.+ */+ discoveryStyle?: DiscoveryStyle;/** i18n key under `settings`. */labelKey: string;aliases?: readonly string[];@@ -209,6 +215,8 @@ export const NAMED_ENDPOINT_PRESETS: readonly NamedEndpointPreset[] = [name: "StepFun Plan",baseUrl: "https://api.stepfun.com/step_plan/v1",apiStyle: "anthropic_messages",+ // Subscription plan: generation on /messages, model list with a Bearer token.+ discoveryStyle: "openai_models",labelKey: "settings.presetStepfunPlan",},{