Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(provider): 支持无模型列表的 Anthropic 端点

zszz3d2ab099d1b3f
diff --git a/apps/desktop/electron/main/ipc/provider-ipc.ts b/apps/desktop/electron/main/ipc/provider-ipc.ts
index 6a7db8480..6ff132c31 100644
--- a/apps/desktop/electron/main/ipc/provider-ipc.ts
+++ b/apps/desktop/electron/main/ipc/provider-ipc.ts
@@ -9,7 +9,7 @@ import {
type OAuthRespondInput,
} from "@pi-desktop/shared";
import { OAUTH_AUTH_KIND, type VendorOAuth } from "../oauth";
-import { probeModelList } from "../model-discovery";
+import { probeProviderEndpoint } from "../model-discovery";
import {
probeDiscoveryCandidates,
type DiscoveryAttempt,
@@ -242,7 +242,7 @@ export function registerProviderIpc({
connection test passed" can never describe two different endpoints: one
URL rule, one auth rule, one wire style, for a real at-least-once check.
*/
- const probe = await probeModelList({
+ const probe = await probeProviderEndpoint({
baseUrl,
apiKey: secret.value,
apiStyle: detail.provider?.apiStyle,
diff --git a/apps/desktop/electron/main/model-discovery.ts b/apps/desktop/electron/main/model-discovery.ts
index 5ba478346..edc54c381 100644
--- a/apps/desktop/electron/main/model-discovery.ts
+++ b/apps/desktop/electron/main/model-discovery.ts
@@ -6,7 +6,9 @@
*
* - `normalizeModelList` turns a response body into rows and is pure;
* - `modelListRequest` builds the request one endpoint needs;
- * - `probeModelList` performs exactly one request, with redirect safety.
+ * - `probeModelList` performs exactly one model-list request, with redirect safety;
+ * - `probeProviderEndpoint` also recognizes Anthropic-compatible services that
+ * intentionally do not publish a model list, such as token-plan gateways.
*
* The candidate sweep that resolves an unknown Base URL lives in
* `provider-endpoint-probe.ts` and drives `probeModelList`, so discovery and
@@ -197,6 +199,61 @@ export type ModelListProbe = {
models: DiscoveredModel[];
};
+/**
+ * Probe an Anthropic-compatible message route when model discovery is absent.
+ *
+ * Some token-plan gateways expose only POST /v1/messages and deliberately do
+ * not implement GET /v1/models. OPTIONS proves that the configured route is
+ * registered without sending credentials or a billable model request.
+ */
+async function probeAnthropicMessagesEndpoint(opts: {
+ baseUrl: string;
+ allowOrigin?: string;
+ signal: AbortSignal;
+}): Promise<{ url: string; status: number }> {
+ const base = opts.baseUrl.trim().replace(/\/+$/, "");
+ const root = base.endsWith("/v1") ? base : `${base}/v1`;
+ const requestUrl = `${root}/messages`;
+ const allowOrigin = opts.allowOrigin ?? originOf(opts.baseUrl);
+ if (allowOrigin && originOf(requestUrl) !== allowOrigin) {
+ throw new Error("message endpoint request refused: it left the configured origin");
+ }
+ const response = await fetch(requestUrl, {
+ method: "OPTIONS",
+ signal: opts.signal,
+ redirect: "manual",
+ });
+ if (!response.ok) {
+ throw Object.assign(new Error(`message endpoint probe failed (${response.status})`), {
+ status: response.status,
+ });
+ }
+ return { url: requestUrl, status: response.status };
+}
+
+/**
+ * Check the configured provider endpoint for connection tests.
+ *
+ * A successful model list includes models. A successful Anthropic OPTIONS
+ * fallback proves only route reachability, so it deliberately returns an
+ * empty model list and leaves manual model entry to the settings UI.
+ */
+export async function probeProviderEndpoint(opts: Parameters<typeof probeModelList>[0]): Promise<ModelListProbe> {
+ try {
+ return await probeModelList(opts);
+ } catch (error) {
+ const status = (error as { status?: unknown }).status;
+ const discoveryStyle = opts.discoveryStyle ?? discoveryStyleForApiStyle(opts.apiStyle);
+ if (status !== 404 || discoveryStyle !== "anthropic_models") throw error;
+ const fallback = await probeAnthropicMessagesEndpoint({
+ baseUrl: opts.baseUrl,
+ allowOrigin: opts.allowOrigin,
+ signal: opts.signal ?? defaultTimeoutSignal(),
+ });
+ return { ...fallback, models: [] };
+ }
+}
+
function originOf(value: string): string | undefined {
try {
return new URL(value.trim()).origin;
diff --git a/apps/desktop/test/provider-endpoint-probe.test.mjs b/apps/desktop/test/provider-endpoint-probe.test.mjs
index 876d2da9e..353c7bc7e 100644
--- a/apps/desktop/test/provider-endpoint-probe.test.mjs
+++ b/apps/desktop/test/provider-endpoint-probe.test.mjs
@@ -16,7 +16,7 @@ const {
DISCOVERY_SWEEP_BUDGET_MS,
probeDiscoveryCandidates,
} = await import("../electron/main/provider-endpoint-probe.ts");
-const { probeModelList } = await import("../electron/main/model-discovery.ts");
+const { probeModelList, probeProviderEndpoint } = await import("../electron/main/model-discovery.ts");
function jsonResponse(body, status = 200, headers = {}) {
return new Response(JSON.stringify(body), {
@@ -30,7 +30,12 @@ async function withFetch(handler, fn) {
const original = globalThis.fetch;
const calls = [];
globalThis.fetch = async (url, init) => {
- calls.push({ url: String(url), headers: init?.headers ?? {}, redirect: init?.redirect });
+ calls.push({
+ url: String(url),
+ method: init?.method ?? "GET",
+ headers: init?.headers ?? {},
+ redirect: init?.redirect,
+ });
return handler(String(url), init);
};
try {
@@ -184,6 +189,28 @@ test("a cross-origin redirect is refused before the credential travels", async (
assert.equal(calls[0].redirect, "manual");
});
+test("Anthropic token-plan endpoints can pass connection testing without a model list", async () => {
+ const { calls, result } = await withFetch((url, init) => {
+ if (init?.method === "OPTIONS" && url.endsWith("/anthropic/v1/messages")) {
+ return new Response("", { status: 200 });
+ }
+ return new Response("not found", { status: 404 });
+ }, () => probeProviderEndpoint({
+ baseUrl: "https://token-plan-cn.xiaomimimo.com/anthropic",
+ apiStyle: "anthropic_messages",
+ apiKey: "sk-secret",
+ }));
+
+ assert.equal(result.status, 200);
+ assert.deepEqual(result.models, []);
+ assert.deepEqual(calls.map((call) => call.url), [
+ "https://token-plan-cn.xiaomimimo.com/anthropic/v1/models?limit=1000",
+ "https://token-plan-cn.xiaomimimo.com/anthropic/v1/messages",
+ ]);
+ assert.equal(calls[1].method, "OPTIONS");
+ assert.equal(calls[1].headers["x-api-key"], undefined);
+});
+
test("a same-origin redirect is followed with the same credential", async () => {
const { calls } = await withFetch(
(url) => url.endsWith("/moved")
@@ -254,4 +281,3 @@ test("a typed path that answers keeps the row, even when a sibling path also ans
assert.equal(result.outcome.effectiveBaseUrl, "https://open.bigmodel.cn/api/v1");
assert.deepEqual(result.outcome.models, [{ modelId: "glm-5.3", displayName: "glm-5.3" }]);
});
-
diff --git a/apps/desktop/test/provider-lookup-model-handler.test.mjs b/apps/desktop/test/provider-lookup-model-handler.test.mjs
index 42ef76d77..0e14ed11a 100644
--- a/apps/desktop/test/provider-lookup-model-handler.test.mjs
+++ b/apps/desktop/test/provider-lookup-model-handler.test.mjs
@@ -92,7 +92,7 @@ function harness(realCatalog) {
},
"../oauth": { OAUTH_AUTH_KIND: "oauth" },
"../model-discovery": {
- probeModelList: async () => {
+ probeProviderEndpoint: async () => {
throw new Error("the lookup must not probe the network");
},
},
diff --git a/docs/spec/03-runtime/12-provider-config-schema.md b/docs/spec/03-runtime/12-provider-config-schema.md
index 7479e95e4..5bc07493d 100644
--- a/docs/spec/03-runtime/12-provider-config-schema.md
+++ b/docs/spec/03-runtime/12-provider-config-schema.md
@@ -722,7 +722,11 @@ unknown OpenAI-compatible endpoint. Every published model-list shape is read —
OpenAI 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.
+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`
+route probe; this proves reachability without sending credentials or a billable
+model request, while model IDs remain manual.
### Which publisher a row is read against
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.md
index 681ad73fd..7f91a79b9 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
@@ -504,6 +504,9 @@ Chat Completions 配置使用同源 Responses。关闭搜索后恢复原配置
`models[].name`,以及智谱 OpenAI Responses 端点返回的 `models[].slug`——因此有应答的端点不会被
当成空列表。连接测试复用同一
套请求构造,因此「模型列表加载成功」与「连接测试通过」描述的始终是同一个地址、认证头与格式。
+Anthropic 风格端点如果因为服务本来就不提供模型列表而返回 404,连接测试可以改用同源的
+`OPTIONS /v1/messages` 路由探测;这个探测不会发送凭据或产生计费模型请求,只证明端点可达,模型 ID
+仍需手动添加。
### 按哪个发布方读取元数据