Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat: Atria Dawn Preview preset and URL-tolerant protocol detection (#729)

Yaowei Zhengb16ed405877f
diff --git a/changelog/unreleased/2026-09-15-atria-dawn-preview.md b/changelog/unreleased/2026-09-15-atria-dawn-preview.md
new file mode 100644
index 00000000..51895521
--- /dev/null
+++ b/changelog/unreleased/2026-09-15-atria-dawn-preview.md
@@ -0,0 +1,11 @@
+# The custom group ships Atria Dawn Preview
+
+- **Date:** 2026-09-15
+- **Type:** feat
+- **Scope:** `core`
+
+[中文版](2026-09-15-atria-dawn-preview.zh.md)
+
+## What changed
+
+- The built-in catalog's custom group gains its first preset, `Atria-Dawn-Preview`: the Anthropic Messages API at `https://api.atria-asi.ai` (the client appends `/v1/messages`; with no key on the entry it reads `ANTHROPIC_API_KEY`), a 256K context window, text only, and a $0 price until the vendor publishes one. The endpoint also serves Responses, but that side rejects the replayed assistant turn of a multi-turn conversation, so the preset speaks Messages. A preset in the custom group carries its own base URL and a pinned generic protocol, since the group implies neither; existing Projects pick it up through the models page's "sync presets".
diff --git a/changelog/unreleased/2026-09-15-atria-dawn-preview.zh.md b/changelog/unreleased/2026-09-15-atria-dawn-preview.zh.md
new file mode 100644
index 00000000..940070b0
--- /dev/null
+++ b/changelog/unreleased/2026-09-15-atria-dawn-preview.zh.md
@@ -0,0 +1,11 @@
+# 自定义分组自带 Atria Dawn Preview
+
+- **Date:** 2026-09-15
+- **Type:** feat
+- **Scope:** `core`
+
+[English](2026-09-15-atria-dawn-preview.md)
+
+## 变更内容
+
+- 内置目录的自定义分组有了第一条预置:`Atria-Dawn-Preview`——`https://api.atria-asi.ai` 的 Anthropic Messages API(客户端自行拼上 `/v1/messages`;条目未填 key 时读 `ANTHROPIC_API_KEY`),256K 上下文,只收文本,厂商公布价格前暂记 0。该端点也提供 Responses 接口,但那一侧会拒绝多轮对话里回放的 assistant 轮,所以预置走 Messages。自定义分组里的预置行自带 base URL 与钉住的通用协议,因为这个分组本身两者都不暗示;已有 Project 经模型库的「同步预置」取得它。
diff --git a/changelog/unreleased/2026-09-15-url-tolerant-protocol-detection.md b/changelog/unreleased/2026-09-15-url-tolerant-protocol-detection.md
new file mode 100644
index 00000000..afae0e2f
--- /dev/null
+++ b/changelog/unreleased/2026-09-15-url-tolerant-protocol-detection.md
@@ -0,0 +1,12 @@
+# Protocol detection copes with a base URL that is one `/v1` off
+
+- **Date:** 2026-09-15
+- **Type:** fix
+- **Scope:** `server`, `web`
+
+[中文版](2026-09-15-url-tolerant-protocol-detection.zh.md)
+
+## What changed
+
+- Custom-model protocol detection no longer takes the typed base URL literally. The URL is normalized first — trailing slashes, query and fragment dropped, a pasted endpoint path (`/chat/completions`, `/completions`, `/responses`, `/messages`, `/v1/messages`) stripped, a run of repeated `/v1` collapsed to one — and then probed, followed by the same URL with a trailing `/v1` removed or added. Each candidate runs the three protocols in the existing order (`openai-responses` → `ant-messages` → `openai-chat`) and the first one served wins, so an extra `/v1`, a missing `/v1`, or a whole endpoint URL copied out of a provider's documentation all detect the same protocol they would have with the URL typed exactly right. `POST /api/projects/:p/models/detect` reports the base URL that answered as `baseUrl` alongside `detected`.
+- Both detect actions in the Web App's Models page — the model dialog's and the add-group dialog's — write that base URL back into the field when it differs from what was typed, and say so in the success toast ("Detected OpenAI Chat Completions; base URL normalized to https://host/v1"). Saving a model whose protocol is still unset detects first, as before, and now persists the corrected URL with it, so the entry is saved against the URL the protocol is really served at.
diff --git a/changelog/unreleased/2026-09-15-url-tolerant-protocol-detection.zh.md b/changelog/unreleased/2026-09-15-url-tolerant-protocol-detection.zh.md
new file mode 100644
index 00000000..3716075b
--- /dev/null
+++ b/changelog/unreleased/2026-09-15-url-tolerant-protocol-detection.zh.md
@@ -0,0 +1,12 @@
+# 协议检测能认出多写或少写一个 `/v1` 的 base URL
+
+- **Date:** 2026-09-15
+- **Type:** fix
+- **Scope:** `server`, `web`
+
+[English](2026-09-15-url-tolerant-protocol-detection.md)
+
+## 变更内容
+
+- 自定义模型的协议检测不再逐字使用填入的 base URL。先整理:去掉末尾斜杠、query 与 fragment,剥掉粘进来的端点路径(`/chat/completions`、`/completions`、`/responses`、`/messages`、`/v1/messages`),把连续重复的 `/v1` 合并为一个;按整理后的地址探测,再用它去掉或补上末尾 `/v1` 的形式探测一次。每个候选都按原有顺序试三种协议(`openai-responses` → `ant-messages` → `openai-chat`),第一个被提供的即为结果——因此多写一个 `/v1`、少写一个 `/v1`、或整段从厂商文档里复制的端点 URL,都能检测出与填写完全正确时相同的协议。`POST /api/projects/:p/models/detect` 在 `detected` 之外返回实际应答的 `baseUrl`。
+- Web App 模型库页的两处「检测协议」——模型对话框与新增分组对话框——在该地址与填入的不同时改写输入框,并在成功 toast 中说明(「已检测为 OpenAI Chat Completions,base URL 已整理为 https://host/v1」)。协议为空时保存仍先检测,现在会连同整理后的地址一起写入,条目因此保存在协议真正被提供的那个地址上。
diff --git a/packages/core/src/state/model-catalog.ts b/packages/core/src/state/model-catalog.ts
index fbeaa0b6..ba701cb1 100644
--- a/packages/core/src/state/model-catalog.ts
+++ b/packages/core/src/state/model-catalog.ts
@@ -2046,6 +2046,26 @@ export const MODEL_CATALOG: ModelCatalogEntry[] = [
supportsVision: true,
clientType: VLLM_CLIENT_TYPE,
},
+ // -- Custom (the group that otherwise holds only user-defined models). A preset may live
+ // here only as a complete row — its own base URL and a pinned generic protocol — because the
+ // group implies neither; it is where a vendor with a single preview model and no console
+ // of its own goes rather than opening a group for it. Atria Dawn Preview: the Anthropic
+ // Messages API at api.atria-asi.ai (the client appends /v1/messages, so the base URL carries
+ // no /v1; the endpoint also serves Chat Completions and Responses, but its Responses side
+ // rejects the replayed assistant turn of a multi-turn conversation), a 256K window (262144 —
+ // the API caps max_output_tokens at that minus the input), text only (the endpoint rejects
+ // image input), and no published price yet, so the row records $0 until the vendor prices
+ // it. Read 2026-09-15 from api.atria-asi.ai/docs.
+ {
+ modelId: "Atria-Dawn-Preview",
+ displayName: "Atria Dawn Preview",
+ provider: "custom",
+ contextWindow: 262144,
+ pricing: usd(0, 0, 0),
+ supportsVision: false,
+ clientType: "ant-messages",
+ baseUrl: "https://api.atria-asi.ai",
+ },
];
/**
diff --git a/packages/core/test/model-catalog.test.ts b/packages/core/test/model-catalog.test.ts
index 143336a6..0576bf77 100644
--- a/packages/core/test/model-catalog.test.ts
+++ b/packages/core/test/model-catalog.test.ts
@@ -70,11 +70,16 @@ describe("model-catalog", () => {
expect(ids).not.toContain("inclusionai/ling-3.0-flash:free");
});
- it("every provider is in MODEL_PROVIDERS (custom only groups user-defined models; the catalog never uses it)", () => {
+ it("every provider is in MODEL_PROVIDERS (a custom preset carries its own base URL and a pinned generic protocol)", () => {
const providerIds = new Set(MODEL_PROVIDERS.map((p) => p.id));
for (const m of MODEL_CATALOG) {
expect(providerIds.has(m.provider)).toBe(true);
- expect(m.provider).not.toBe("custom");
+ // custom groups user-defined models, so the group implies no endpoint and no protocol:
+ // a preset filed there has to say both itself.
+ if (m.provider === "custom") {
+ expect(["openai-responses", "ant-messages", "openai-chat"]).toContain(m.clientType);
+ expect(m.baseUrl).toMatch(/^https:\/\//);
+ }
}
// Every provider gives a console link to "get an API key" (shown in the frontend's group
// header) and a model list / docs link to "get a model id" (shown in the add-model
@@ -123,13 +128,15 @@ describe("model-catalog", () => {
m.provider === "vllm" ||
m.modelId.endsWith(":free") ||
m.modelId === "openrouter/free" ||
+ m.modelId === "Atria-Dawn-Preview" ||
m.modelId === "dots-3-note-preview"
) {
// Self-hosted vLLM and the free-tier gateway rows share one treatment: a genuine $0
// price (not "unknown"), so costs compute to 0 and the free badge shows. Nobody bills
// per token for either — a vLLM deployment costs its operator hardware, which no
- // catalog rate expresses. TokenDance's dots-3-note-preview is the one free row of
- // its group.
+ // catalog rate expresses. Atria Dawn Preview has no published price yet and is
+ // recorded at $0 until the vendor prices it; TokenDance's dots-3-note-preview is the
+ // one free row of its group.
expect(m.pricing, m.modelId).toBeDefined();
expect([m.pricing!.cache_read, m.pricing!.cache_write, m.pricing!.output]).toEqual([
0, 0, 0,
@@ -146,6 +153,35 @@ describe("model-catalog", () => {
}
});
+ it("custom: the group pins nothing, and its one preset carries its own endpoint and protocol", () => {
+ // The custom group holds user-defined models, so the group itself implies no endpoint and
+ // no protocol (see the MODEL_PROVIDERS test above). A preset filed there is complete on its
+ // own row: Atria Dawn Preview at api.atria-asi.ai, Anthropic Messages API (the client
+ // appends /v1/messages, so the base carries no /v1), 256K window, text only.
+ expect(providerClientType("custom")).toBeUndefined();
+ expect(providerInfo("custom")!.gatewayBaseUrl).toBeUndefined();
+ const custom = MODEL_CATALOG.filter((m) => m.provider === "custom");
+ expect(
+ custom.map((m) => [m.modelId, m.clientType, m.baseUrl, m.contextWindow, m.supportsVision]),
+ ).toEqual([["Atria-Dawn-Preview", "ant-messages", "https://api.atria-asi.ai", 262144, false]]);
+ // The custom group is last, and so is its row: the catalog is laid out group by group.
+ expect(MODEL_CATALOG.at(-1)!.modelId).toBe("Atria-Dawn-Preview");
+ expect(catalogEntryFor("custom", "Atria-Dawn-Preview")?.displayName).toBe("Atria Dawn Preview");
+ // Ids are case-sensitive at the vendor, so the lookup is too.
+ expect(catalogEntryFor("custom", "atria-dawn-preview")).toBeUndefined();
+ const preset = presetModelEntries().find((e) => e.provider === "custom");
+ expect(preset).toEqual({
+ provider: "custom",
+ model_id: "Atria-Dawn-Preview",
+ context_window: 262144,
+ client_type: "ant-messages",
+ pricing: { unit: "usd_per_mtok", cache_read: 0, cache_write: 0, output: 0 },
+ vision: false,
+ base_url: "https://api.atria-asi.ai",
+ });
+ expect(modelHomepageUrl("custom", "Atria-Dawn-Preview")).toBeUndefined();
+ });
+
it("vLLM (self-hosted): the group pins openai-chat-vllm-adapter, prices at zero and carries no endpoint", () => {
const vllm = MODEL_CATALOG.filter((m) => m.provider === "vllm");
// Dictionary order by upstream id, case-insensitive (as in siliconflow): deepseek-ai/
@@ -671,12 +707,16 @@ describe("model-catalog", () => {
expect(catalogEntryFor("google", "gemini-3.5-flash")!.contextWindow).toBe(1048576);
// In preset entries, every gateway model inlines base_url, and so do the two direct rows
- // whose own id does not route — MiniMax M3 and DeepSeek deepseek-flash (no credentials).
+ // whose own id does not route — MiniMax M3 and DeepSeek deepseek-flash (no credentials) —
+ // and the custom group's preset, whose group implies no endpoint at all.
const pinnedDirect = MODEL_CATALOG.filter((m) => m.provider === "deepseek" && m.baseUrl);
expect(pinnedDirect.map((m) => m.modelId)).toEqual(["deepseek-flash"]);
+ const customPresets = MODEL_CATALOG.filter((m) => m.provider === "custom");
const withBaseUrl = presetModelEntries().filter((e) => e.base_url !== undefined);
expect(withBaseUrl.map((e) => [e.provider, e.model_id]).sort()).toEqual(
- [...gateway, ...minimax, ...pinnedDirect].map((m) => [m.provider, m.modelId]).sort(),
+ [...gateway, ...minimax, ...pinnedDirect, ...customPresets]
+ .map((m) => [m.provider, m.modelId])
+ .sort(),
);
});
@@ -1143,6 +1183,14 @@ describe("resolveModelEnv (PRN-021: env fallback resolved by AgentHub routing ru
const env = resolveModelEnv(m.modelId, m.clientType);
const provider = providerInfo(m.provider)!;
expect(env, `${m.provider}/${m.modelId}`).toBeDefined();
+ if (m.provider === "custom") {
+ // The custom group's pair is the fallback for its OpenAI-protocol default; an entry
+ // pinned to another generic protocol reads that protocol's pair instead, exactly as a
+ // user-added custom model on ant-messages does. The one preset here is on Messages.
+ expect(env!.envKey, m.modelId).toBe("ANTHROPIC_API_KEY");
+ expect(env!.envBaseUrlKey, m.modelId).toBe("ANTHROPIC_BASE_URL");
+ continue;
+ }
expect(env!.envKey, m.modelId).toBe(provider.envKey);
expect(env!.envBaseUrlKey, m.modelId).toBe(provider.envBaseUrlKey);
}
diff --git a/packages/docs/content/models.en.md b/packages/docs/content/models.en.md
index dcf556d4..8f854a31 100644
--- a/packages/docs/content/models.en.md
+++ b/packages/docs/content/models.en.md
@@ -74,7 +74,7 @@ Built-in groups and their env-var fallbacks (catalog source: `packages/core/src/
| minimax | `MINIMAX_API_KEY` | Direct MiniMax M3 Responses client (`client_type = "minimax-m3"`): `MiniMax-M3` with a 1,000,000-token context window and vision; preset base URL `https://api.minimax.io/v1`; accepts a Token Plan Subscription Key or pay-as-you-go API key |
| qwen-pay-as-you-go | `OPENAI_API_KEY` | Qwen pay-as-you-go (DashScope's OpenAI-compatible endpoint), preset base URL `https://dashscope.aliyuncs.com/compatible-mode/v1`; resold third-party models keep vendor-prefixed ids (e.g. `kimi/kimi-k3`) |
| qwen-token-plan | `OPENAI_API_KEY` | Qwen Token Plan subscription gateway, preset base URL `https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1`; pricing from each model page's official list price (the preview model has only a quota-multiplier promo, no list price) |
-| custom | `OPENAI_API_KEY` | Any OpenAI-protocol endpoint |
+| custom | `OPENAI_API_KEY` | Any OpenAI-protocol endpoint; ships one preset, Atria Dawn Preview (Anthropic Messages API at `api.atria-asi.ai`, credential from `ANTHROPIC_API_KEY` when the entry has none, 256K window, priced at $0 until the vendor publishes prices) |
The gateway groups (openrouter / fireworks / siliconflow / tokendance / qwen-pay-as-you-go / qwen-token-plan) go through AgentHub's generic OpenAI-protocol clients, so with blank credentials they read `OPENAI_API_KEY` — not a gateway-specific variable. The OpenRouter group uses the Responses client (`client_type = "openai-responses"`) throughout — its presets and any model you add to the group alike — because OpenRouter serves the Responses API at that same base URL for every model it resells; the other gateway presets pin the Chat Completions client (`client_type = "openai-chat"`). Both clients read the same `OPENAI_*` variables, so the credential rules are identical either way. The direct MiniMax M3 client reads `MINIMAX_API_KEY`. The built-in MiniMax preset pins `https://api.minimax.io/v1`; `MINIMAX_BASE_URL` is consulted only for entries without an inline `base_url`. M3 pricing records MiniMax's standard pay-as-you-go tier at 512K input tokens or below; every rate doubles above that and the priority tier is 1.5x, so long-context and priority usage is underestimated — the same base-tier convention already used for OpenAI (>272K) and Gemini 3.1 Pro (>200K).
@@ -120,6 +120,8 @@ A local inference server is just a `custom` entry: `client_type = "openai-chat"`
Custom and user-defined groups speak AgentHub's generic protocol clients, and the Web dialog detects which one a base URL serves. A new custom model starts with **no protocol selected**: the suffix at the right edge of the base URL field reads "Select protocol" rather than a path, and no row in its menu is checked. **Detect** sits at the top-right of that field, next to its label, and is always available — no API key is needed to press it. Pressing it has the server probe the URL with three cheap requests in fixed order — `openai-responses` (`POST {base}/responses`, OpenAI Responses API) first, then `ant-messages` (`POST {base}/v1/messages`, Anthropic Messages API), then `openai-chat` (`POST {base}/chat/completions`) — and the first protocol the endpoint actually serves is applied to the entry's `client_type`, confirmed by a toast naming what was found. Nothing about a result is written into the form itself — where the protocol ended up is visible in the suffix, which is what actually holds it.
+Detection tolerates the ways a base URL is usually mistyped: one `/v1` too many (`https://host/v1/v1`), one too few (`https://host` for an API served under `https://host/v1`), or a whole endpoint URL pasted from a provider's documentation (`/chat/completions`, `/responses`, `/messages`). It probes the normalized base first, then its neighbouring form — the trailing `/v1` removed when it has one, added when it has not — taking the three protocols in the usual order for each (six short probes at most), and the base URL field is rewritten to the form that actually answered, so what you save is the URL the protocol is really served at.
+
Saving is the backstop: confirm the dialog while the protocol is still unset and detection runs first, then the save continues with what it found (the button reads "Detecting…" for the round-trip). A hit there is not announced — the save you asked for simply proceeds. If the probe finds nothing the model is **not** saved: the failure pops up and the dialog stays open, so you can pick a protocol by hand or correct the URL. This matters because AgentHub resolves an unmatched client type by raising, not by defaulting: an entry persisted with no protocol would be a model that cannot start.
Probes are minimal invalid requests (`{}` bodies): they cost no tokens and need no valid model id — an error in the protocol's own shape already proves the route exists, while a `404`/`405` means the path isn't served and HTML or gateway junk counts for nothing. The probed URLs and auth headers are exactly what the AgentHub client would use after saving (`Authorization: Bearer` for the OpenAI protocols; `x-api-key` plus `Authorization: Bearer` and `anthropic-version` for `ant-messages`), so a detected protocol is one that will really work.
diff --git a/packages/docs/content/models.zh.md b/packages/docs/content/models.zh.md
index 8a15fc01..27babdc5 100644
--- a/packages/docs/content/models.zh.md
+++ b/packages/docs/content/models.zh.md
@@ -74,7 +74,7 @@ api_key = "sk-..."
| minimax | `MINIMAX_API_KEY` | 直连 MiniMax M3 Responses 客户端(`client_type = "minimax-m3"`):`MiniMax-M3` 支持 1,000,000 Token 上下文和视觉输入;预置 base URL `https://api.minimax.io/v1`;接受 Token Plan Subscription Key 或按量付费 API Key |
| qwen-pay-as-you-go | `OPENAI_API_KEY` | Qwen 按量付费(DashScope OpenAI 兼容端),预置 base URL `https://dashscope.aliyuncs.com/compatible-mode/v1`;转售第三方模型保留厂商前缀 id(如 `kimi/kimi-k3`) |
| qwen-token-plan | `OPENAI_API_KEY` | Qwen Token Plan 订阅网关,预置 base URL `https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1`;定价取各模型页官方牌价(预览模型仅配额倍率促销、无牌价) |
-| custom | `OPENAI_API_KEY` | 任意 OpenAI 协议端点 |
+| custom | `OPENAI_API_KEY` | 任意 OpenAI 协议端点;自带一条预置:Atria Dawn Preview(`api.atria-asi.ai` 的 Anthropic Messages API,条目未填 key 时读 `ANTHROPIC_API_KEY`,256K 窗口,厂商未公布价格前暂记 0) |
网关分组(openrouter / fireworks / siliconflow / tokendance / qwen-pay-as-you-go / qwen-token-plan)经 AgentHub 的通用 OpenAI 协议客户端请求,因此凭证留空时读取的是 `OPENAI_API_KEY`,而非网关自己的变量名。OpenRouter 分组整体使用 Responses 客户端(`client_type = "openai-responses"`)——预置条目与你自行添加进该分组的模型都是——因为 OpenRouter 为其转售的每一个模型都在同一 base URL 上提供 Responses API;其余网关预置则固定 Chat Completions 客户端(`client_type = "openai-chat"`)。两种客户端读取相同的 `OPENAI_*` 变量,凭证规则完全一致。直连 MiniMax M3 客户端读取 `MINIMAX_API_KEY`。内置 MiniMax 预设固定使用 `https://api.minimax.io/v1`;仅当模型条目未内联 `base_url` 时才读取 `MINIMAX_BASE_URL`。M3 价格取 MiniMax 按量付费的标准档、输入不超过 512K Token 的牌价;超过 512K 后各档价格翻倍,priority 档另为 1.5 倍,因此长上下文与 priority 用量会被低估——与 OpenAI(>272K)、Gemini 3.1 Pro(>200K)沿用的基准档口径一致。
@@ -120,6 +120,8 @@ TokenDance 分组的条目记录该网关的牌价,并在有促销时记录折
Custom 与自建分组走 AgentHub 的通用协议客户端,Web 对话框会检测 base URL 实际提供的是哪一种。新建自定义模型时**默认不选择任何协议**:base URL 输入框右端的后缀显示「选择协议」而不是某条路径,其菜单中也没有任何一项被勾选。「检测协议」按钮位于该输入框右上角、与标签同一行,始终可点击——不需要先填 API Key。点击它,服务端按固定顺序向该 URL 发三个轻量探测请求——先 `openai-responses`(`POST {base}/responses`,OpenAI Responses API),再 `ant-messages`(`POST {base}/v1/messages`,Anthropic Messages API),最后 `openai-chat`(`POST {base}/chat/completions`)——第一个真正被端点提供的协议写入条目的 `client_type`,并以 toast 提示检测到的是哪一种。表单里不会留下任何结果文字——协议最终落在哪,看后缀即可,那才是真正承载它的地方。
+检测容忍多写一个 `/v1`、少写一个 `/v1`、或整段端点 URL(`/chat/completions`、`/responses`、`/messages`)粘进来的情况:先按整理后的 base 探测,再试它的相邻形式(带 `/v1` 的去掉、不带的补上),每种都按原有协议顺序试(最多六次短探测),命中后把 base URL 字段改写成实际应答的那个形式。
+
保存是兜底环节:若确认对话框时协议仍为空,会先自动检测,再带着检测结果继续保存(这段往返期间按钮显示「检测中…」)。此处检测成功不额外提示——你要的保存直接继续。若这次探测什么都没找到,模型**不会**被保存:toast 说明原因,对话框保持打开,你可以手动选协议或修正 URL。这一步是必要的:AgentHub 遇到无法匹配的 client type 会直接抛错而不是回退默认值,协议为空的条目就是一个根本起不来的模型。
探测请求是刻意构造的最小非法请求(`{}` 请求体):不消耗 Token、不需要有效的模型 id——按协议自身形态返回的错误即证明路由存在;`404`/`405` 则说明该路径未提供,HTML 或网关杂讯一概不算数。探测的 URL 与鉴权头和保存后 AgentHub 客户端实际使用的完全一致(OpenAI 系协议用 `Authorization: Bearer`;`ant-messages` 同时带 `x-api-key`、`Authorization: Bearer` 与 `anthropic-version`),因此检测出的协议就是真正能跑通的协议。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 0ac2ca2e..f7746f6f 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -174,7 +174,7 @@ Member writes are owner-only. The member routes also answer `403 desktop_single_
| GET | /api/projects/:projectId/models | List models (api_key masked) |
| PUT | /api/projects/:projectId/models | Full-table replace, keyed by `(provider, modelId)` |
| POST | /api/projects/:projectId/models/test | Connectivity test: `{provider, modelId, …}` → `{ok, latencyMs?, message?}` |
-| POST | /api/projects/:projectId/models/detect | Protocol auto-detection for a custom base URL: probes `openai-responses` → `ant-messages` → `openai-chat` in order and reports the first served protocol: `{baseUrl, apiKey?, …}` → `{detected?, probes}` |
+| POST | /api/projects/:projectId/models/detect | Protocol auto-detection for a custom base URL: probes `openai-responses` → `ant-messages` → `openai-chat` in order, first on the URL as typed (normalized, a pasted endpoint path stripped) and then on its neighbouring `/v1` form, reporting the first served protocol and the base URL that served it: `{baseUrl, apiKey?, …}` → `{detected?, baseUrl?, probes}` |
| POST | /api/projects/:projectId/models/list | Endpoint model listing for the add-group import: the ids the endpoint serves on a detected protocol: `{baseUrl, clientType, apiKey?}` → `{ok, models?, unsupported?, message?}` |
| POST | /api/projects/:projectId/models/detect-vision | Vision capability probe: sends one 1x1 image on this model's credential (a real, billed completion): `{provider, modelId, apiKey?, baseUrl?, clientType?}` → `{outcome: supported\|unsupported\|failed, message?}` |
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index edf8a516..0f34c702 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -174,7 +174,7 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
| GET | /api/projects/:projectId/models | 模型列表(api_key 掩码显示) |
| PUT | /api/projects/:projectId/models | 全表替换,条目以 `(provider, modelId)` 为键 |
| POST | /api/projects/:projectId/models/test | 连通性测试:`{provider, modelId, …}` → `{ok, latencyMs?, message?}` |
-| POST | /api/projects/:projectId/models/detect | 自定义 base URL 的协议自动检测:按 `openai-responses` → `ant-messages` → `openai-chat` 顺序探测并返回第一个被提供的协议:`{baseUrl, apiKey?, …}` → `{detected?, probes}` |
+| POST | /api/projects/:projectId/models/detect | 自定义 base URL 的协议自动检测:按 `openai-responses` → `ant-messages` → `openai-chat` 顺序探测,先用整理后的 URL(整段端点路径会先被剥掉),再用它增删 `/v1` 后的形式,返回第一个被提供的协议与实际应答的 base URL:`{baseUrl, apiKey?, …}` → `{detected?, baseUrl?, probes}` |
| POST | /api/projects/:projectId/models/list | 新增分组导入所用的端点模型列表:按检测出的协议列出端点服务的全部模型 id:`{baseUrl, clientType, apiKey?}` → `{ok, models?, unsupported?, message?}` |
| POST | /api/projects/:projectId/models/detect-vision | 视觉能力探测:用该模型的凭据发送一张 1x1 图片(一次真实计费的补全):`{provider, modelId, apiKey?, baseUrl?, clientType?}` → `{outcome: supported\|unsupported\|failed, message?}` |
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index f25eb46c..8929a05e 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -701,10 +701,22 @@ export interface ModelProtocolProbeDto {
status?: number;
}
-/** Detection result: probes run sequentially and stop at the first served protocol, so `probes` lists only the ones actually run, in order. */
+/**
+ * Detection result: probes run sequentially over the candidate base URLs derived from the
+ * one that was typed and stop at the first served protocol, so `probes` lists only the
+ * ones actually run, in order.
+ */
export interface ModelProtocolDetectResponse {
- /** The first protocol the endpoint serves (an AgentHub client type); absent when none of the three matched. */
+ /** The first protocol an endpoint serves (an AgentHub client type); absent when none of the three matched. */
detected?: string;
+ /**
+ * The base URL the detected protocol answered at — the typed URL normalized (endpoint
+ * path stripped, repeated `/v1` collapsed) and possibly with a trailing `/v1` added or
+ * removed, so `https://host/v1/chat/completions` comes back as `https://host/v1`.
+ * Present only alongside `detected`; callers write it back into their base URL field,
+ * since that is where the protocol is served.
+ */
+ baseUrl?: string;
probes: ModelProtocolProbeDto[];
}
diff --git a/packages/server/src/services/protocol-detect.ts b/packages/server/src/services/protocol-detect.ts
index f7006e32..55bd7bcd 100644
--- a/packages/server/src/services/protocol-detect.ts
+++ b/packages/server/src/services/protocol-detect.ts
@@ -38,6 +38,11 @@
* Probes run sequentially in the order above and stop at the first `served` hit. The API
* key is only ever placed in request headers — never in URLs, results, or logs.
*
+ * The typed URL is not taken literally: it is normalized and paired with its neighbouring
+ * `/v1` form (see candidateBaseUrls), and every candidate gets the full protocol sequence
+ * before the next one is tried. The candidate that answered is reported back as `baseUrl`
+ * so the caller can correct the field. Worst case a detection is six short probes.
+ *
* Credential resolution is layered: the caller passes the key typed in the dialog or the
* entry's stored one, and when there is neither, each probe falls back to the environment
* variable for the protocol IT speaks (`ANTHROPIC_API_KEY` for `ant-messages`,
@@ -137,6 +142,50 @@ export function probeUrl(baseUrl: string, path: string): string {
return baseUrl.trim().replace(/\/+$/, "") + path;
}
+/**
+ * Endpoint paths a pasted URL may already carry, longest match first — `/chat/completions`
+ * before `/completions`, `/v1/messages` before `/messages` — so the whole endpoint path is
+ * stripped rather than its tail.
+ */
+const ENDPOINT_PATH_SUFFIXES = [
+ "/chat/completions",
+ "/v1/messages",
+ "/completions",
+ "/responses",
+ "/messages",
+] as const;
+
+/**
+ * The base URLs one detection tries, in order, for a URL as the user typed it.
+ *
+ * What gets pasted is usually a variant of the right thing: one `/v1` too many
+ * (`https://host/v1/v1`), one too few (`https://host` for an API that lives under
+ * `https://host/v1`), or a whole endpoint URL copied out of a provider's documentation
+ * (`https://host/v1/chat/completions`). So the typed value is first normalized — trimmed,
+ * query and fragment dropped, trailing slashes removed, a trailing endpoint path stripped,
+ * runs of repeated `/v1` collapsed to one — and then its neighbouring form is tried as
+ * well: the trailing `/v1` removed when it has one, `/v1` appended when it has not. Those
+ * two forms are the whole list, so a detection costs at most six short probes.
+ *
+ * Pure string work, deliberately: `new URL()` would lowercase the host and re-encode the
+ * path, and a base URL must be probed as it was written apart from the edits above.
+ */
+export function candidateBaseUrls(typed: string): string[] {
+ // Query and fragment are never part of an endpoint base URL, but a URL copied from a
+ // browser carries them.
+ let base = typed.trim().replace(/[?#][\s\S]*$/, "");
+ base = base.replace(/\/+$/, "");
+ for (const suffix of ENDPOINT_PATH_SUFFIXES) {
+ if (base.endsWith(suffix)) {
+ base = base.slice(0, -suffix.length);
+ break;
+ }
+ }
+ base = base.replace(/\/+$/, "").replace(/(?:\/v1){2,}/g, "/v1");
+ // The two forms differ by exactly one `/v1` segment, so they can never coincide.
+ return [base, base.endsWith("/v1") ? base.slice(0, -"/v1".length) : `${base}/v1`];
+}
+
/** A JSON body that looks like a structured API error (vs an HTML page / junk): see the header doc for why this check is tolerant. */
function isApiErrorShape(body: Record<string, unknown>): boolean {
const err = body.error;
@@ -279,10 +328,14 @@ async function runProbe(
}
/**
- * Runs the three probes sequentially in the required order and stops at the first
- * protocol the endpoint serves. Never throws: every failure mode is a probe outcome.
- * The result lists only the probes actually run (their order is the probe order), so
- * callers can render per-protocol outcomes for debugging; no secret ever appears in it.
+ * Runs the protocol probes in the required order against each candidate base URL (see
+ * candidateBaseUrls) and stops at the first protocol an endpoint serves: candidate by
+ * candidate, and within a candidate Responses, then Messages, then Chat Completions.
+ * The candidate that answered comes back as `baseUrl`, so a URL that was typed one `/v1`
+ * off — or pasted as a full endpoint URL — is reported in the form that actually works.
+ * Never throws: every failure mode is a probe outcome. The result lists only the probes
+ * actually run, in the order they ran (each carries the URL it hit, so a reader can tell
+ * the candidates apart); no secret ever appears in it.
*/
export async function detectModelProtocol(options: {
baseUrl: string;
@@ -303,11 +356,13 @@ export async function detectModelProtocol(options: {
const fetchImpl = options.fetchImpl ?? fetch;
const timeoutMs = options.timeoutMs ?? PROBE_TIMEOUT_MS;
const probes: ModelProtocolProbeDto[] = [];
- for (const spec of PROTOCOL_PROBES) {
- const apiKey = options.apiKey ?? envApiKeyForProtocol(spec.clientType, options.env);
- const probe = await runProbe(spec, options.baseUrl, apiKey, fetchImpl, timeoutMs);
- probes.push(probe);
- if (probe.outcome === "served") return { detected: spec.clientType, probes };
+ for (const baseUrl of candidateBaseUrls(options.baseUrl)) {
+ for (const spec of PROTOCOL_PROBES) {
+ const apiKey = options.apiKey ?? envApiKeyForProtocol(spec.clientType, options.env);
+ const probe = await runProbe(spec, baseUrl, apiKey, fetchImpl, timeoutMs);
+ probes.push(probe);
+ if (probe.outcome === "served") return { detected: spec.clientType, baseUrl, probes };
+ }
}
return { probes };
}
diff --git a/packages/server/test/protocol-detect.test.ts b/packages/server/test/protocol-detect.test.ts
index b74dc169..866fb2d2 100644
--- a/packages/server/test/protocol-detect.test.ts
+++ b/packages/server/test/protocol-detect.test.ts
@@ -1,7 +1,9 @@
/**
* Protocol auto-detection tests: classification of probe answers (route-exists vs
- * route-missing 404/405 vs HTML/gateway junk vs 5xx), the required probe order
- * (openai-responses → ant-messages → openai-chat, stop at the first served protocol),
+ * route-missing 404/405 vs HTML/gateway junk vs 5xx), the candidate base URLs a typed URL
+ * expands to (an extra `/v1`, a missing `/v1`, a whole endpoint URL pasted in), the
+ * required probe order (openai-responses → ant-messages → openai-chat, candidate by
+ * candidate, stop at the first served protocol) and the base URL reported back,
* auth header shapes per protocol (Bearer for the OpenAI protocols; x-api-key +
* Bearer + anthropic-version for ant-messages, mirroring AgentHub's clients), the
* per-protocol environment-variable fallback used when no key was typed or stored
@@ -16,6 +18,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { ModelProtocolDetectResponse, ModelsResponse } from "../src/api/types.js";
import {
MAX_PROBE_BODY_BYTES,
+ candidateBaseUrls,
classifyProbeResponse,
detectModelProtocol,
envApiKeyForProtocol,
@@ -139,6 +142,79 @@ describe("isHttpUrl / probeUrl", () => {
});
});
+describe("candidateBaseUrls", () => {
+ it("covers the three ways a base URL is mistyped: one /v1 too many, one too few, a whole endpoint URL", () => {
+ expect(candidateBaseUrls("https://host/v1/v1")).toEqual(["https://host/v1", "https://host"]);
+ expect(candidateBaseUrls("https://host")).toEqual(["https://host", "https://host/v1"]);
+ expect(candidateBaseUrls("https://host/v1/chat/completions")).toEqual([
+ "https://host/v1",
+ "https://host",
+ ]);
+ expect(candidateBaseUrls("https://host/v1/responses")).toEqual([
+ "https://host/v1",
+ "https://host",
+ ]);
+ expect(candidateBaseUrls("https://host/v1/messages")).toEqual([
+ "https://host",
+ "https://host/v1",
+ ]);
+ });
+
+ it("strips the longest endpoint path, not its tail (/chat/completions before /completions, /v1/messages before /messages)", () => {
+ expect(candidateBaseUrls("https://host/v1/completions")).toEqual([
+ "https://host/v1",
+ "https://host",
+ ]);
+ expect(candidateBaseUrls("https://host/messages")).toEqual(["https://host", "https://host/v1"]);
+ expect(candidateBaseUrls("https://host/api/chat/completions")).toEqual([
+ "https://host/api",
+ "https://host/api/v1",
+ ]);
+ });
+
+ it("a URL that is already right still gets its neighbour, and a plain host gets /v1", () => {
+ expect(candidateBaseUrls("https://api.example.com/v1")).toEqual([
+ "https://api.example.com/v1",
+ "https://api.example.com",
+ ]);
+ expect(candidateBaseUrls("http://127.0.0.1:8000")).toEqual([
+ "http://127.0.0.1:8000",
+ "http://127.0.0.1:8000/v1",
+ ]);
+ });
+
+ it("trims whitespace, drops trailing slashes, query and fragment", () => {
+ expect(candidateBaseUrls(" https://host/v1/ ")).toEqual(["https://host/v1", "https://host"]);
+ expect(candidateBaseUrls("https://host/v1/chat/completions?key=abc")).toEqual([
+ "https://host/v1",
+ "https://host",
+ ]);
+ expect(candidateBaseUrls("https://host/v1#section")).toEqual([
+ "https://host/v1",
+ "https://host",
+ ]);
+ });
+
+ it("collapses a run of repeated /v1 segments, endpoint path included", () => {
+ expect(candidateBaseUrls("https://host/v1/v1/v1")).toEqual(["https://host/v1", "https://host"]);
+ expect(candidateBaseUrls("https://host/v1/v1/responses")).toEqual([
+ "https://host/v1",
+ "https://host",
+ ]);
+ });
+
+ it("leaves the host's case and every other path segment exactly as typed", () => {
+ expect(candidateBaseUrls("https://API.Example.COM/v1")).toEqual([
+ "https://API.Example.COM/v1",
+ "https://API.Example.COM",
+ ]);
+ expect(candidateBaseUrls("https://host/OpenAI/Compat")).toEqual([
+ "https://host/OpenAI/Compat",
+ "https://host/OpenAI/Compat/v1",
+ ]);
+ });
+});
+
// ---------------------------------------------------------------------------
// Probe ordering and header shapes (mocked fetch)
// ---------------------------------------------------------------------------
@@ -193,6 +269,8 @@ describe("detectModelProtocol (order and stop-at-first)", () => {
),
});
expect(res.detected).toBe("openai-responses");
+ // A base URL that needed no fixing is still reported, so callers compare rather than guess.
+ expect(res.baseUrl).toBe(BASE);
expect(res.probes.map((p) => p.outcome)).toEqual(["served"]);
expect(seen.map((c) => c.url)).toEqual(["https://gw.example.com/v1/responses"]);
});
@@ -224,11 +302,52 @@ describe("detectModelProtocol (order and stop-at-first)", () => {
expect(res.probes.map((p) => p.outcome)).toEqual(["route_missing", "route_missing", "served"]);
});
- it("nothing matches: no detected protocol, all three probes reported", async () => {
+ it("nothing matches: no detected protocol, no base URL, and every candidate's probes reported", async () => {
const res = await detectModelProtocol({ baseUrl: BASE, fetchImpl: fakeFetch({}) });
expect(res.detected).toBeUndefined();
- expect(res.probes).toHaveLength(3);
+ expect(res.baseUrl).toBeUndefined();
+ expect(res.probes).toHaveLength(candidateBaseUrls(BASE).length * 3);
expect(res.probes.every((p) => p.outcome === "route_missing")).toBe(true);
+ // The whole first candidate is exhausted before the second one is tried.
+ expect(res.probes.map((p) => p.url)).toEqual([
+ "https://gw.example.com/v1/responses",
+ "https://gw.example.com/v1/v1/messages",
+ "https://gw.example.com/v1/chat/completions",
+ "https://gw.example.com/responses",
+ "https://gw.example.com/v1/messages",
+ "https://gw.example.com/chat/completions",
+ ]);
+ });
+
+ it("a pasted endpoint URL detects on the base it strips down to, and reports that base back", async () => {
+ const res = await detectModelProtocol({
+ baseUrl: "https://gw.example.com/v1/chat/completions",
+ fetchImpl: fakeFetch({ "/v1/chat/completions": { status: 401, body: OPENAI_ERROR } }),
+ });
+ expect(res.detected).toBe("openai-chat");
+ expect(res.baseUrl).toBe("https://gw.example.com/v1");
+ // The two misses before it are the same candidate's earlier protocols, not another base.
+ expect(res.probes.map((p) => [p.clientType, p.outcome, p.url])).toEqual([
+ ["openai-responses", "route_missing", "https://gw.example.com/v1/responses"],
+ ["ant-messages", "route_missing", "https://gw.example.com/v1/v1/messages"],
+ ["openai-chat", "served", "https://gw.example.com/v1/chat/completions"],
+ ]);
+ });
+
+ it("a base URL typed without /v1 falls through to the /v1 candidate and reports it", async () => {
+ const res = await detectModelProtocol({
+ baseUrl: "https://gw.example.com",
+ fetchImpl: fakeFetch({ "/v1/responses": { status: 400, body: OPENAI_ERROR } }),
+ });
+ expect(res.detected).toBe("openai-responses");
+ expect(res.baseUrl).toBe("https://gw.example.com/v1");
+ expect(res.probes.map((p) => p.outcome)).toEqual([
+ "route_missing",
+ "route_missing",
+ "route_missing",
+ "served",
+ ]);
+ expect(res.probes[3]!.url).toBe("https://gw.example.com/v1/responses");
});
it("probe failures do not stop the sequence: a timeout on /responses still finds chat completions", async () => {
@@ -300,7 +419,9 @@ describe("detectModelProtocol (order and stop-at-first)", () => {
apiKey: "sk-secret-key",
fetchImpl: fakeFetch({}, seen),
});
- expect(seen).toHaveLength(3);
+ // Nothing serves, so both candidates are probed; the header shapes are asserted on the
+ // first candidate's three calls.
+ expect(seen).toHaveLength(6);
const [responses, messages, chat] = seen as [SeenCall, SeenCall, SeenCall];
expect(responses.url).toBe("https://gw.example.com/v1/responses");
expect(messages.url).toBe("https://gw.example.com/v1/v1/messages");
@@ -359,9 +480,9 @@ describe("detectModelProtocol env fallback", () => {
await detectModelProtocol({
baseUrl: BASE,
env: { OPENAI_API_KEY: "sk-openai", ANTHROPIC_API_KEY: "sk-anthropic" },
- fetchImpl: fakeFetch({}, seen), // every path 404s, so all three probes run
+ fetchImpl: fakeFetch({}, seen), // every path 404s, so both candidates run all three probes
});
- expect(seen).toHaveLength(3);
+ expect(seen).toHaveLength(6);
const [responses, messages, chat] = seen as [SeenCall, SeenCall, SeenCall];
expect(responses.headers.authorization).toBe("Bearer sk-openai");
expect(chat.headers.authorization).toBe("Bearer sk-openai");
diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsx
index dafb33bb..e1ce09a4 100644
--- a/packages/web/src/features/models/models-page.tsx
+++ b/packages/web/src/features/models/models-page.tsx
@@ -251,6 +251,17 @@ export function clientTypeAfterProviderChange(provider: string, current: string)
*/
type DetectMode = "manual" | "save";
+/**
+ * What a detection run yields. The server probes neighbouring forms of the URL that was
+ * typed, so it reports back which one actually served the protocol; `baseUrl` carries that
+ * form only when it differs from what the field held, i.e. only when the field needs
+ * correcting.
+ */
+interface DetectOutcome {
+ clientType: string;
+ baseUrl?: string;
+}
+
/** Local edit state for one model row (string-typed for form use; parsed uniformly on save). */
export interface RowState {
/**
@@ -1696,7 +1707,16 @@ function AddGroupDialog({
const detected = res.detected !== undefined ? protocolSelectorValue(res.detected) : null;
if (detected !== null) {
setClientType(detected);
- toastSuccess(S.models.detectedProtocol(S.models.protocolNames[detected] ?? detected));
+ const name = S.models.protocolNames[detected] ?? detected;
+ // The protocol may have answered on a tidied-up form of the URL (a `/v1` added or
+ // dropped, a pasted endpoint path removed); the import must speak to that one, so
+ // the field takes it and the toast says so.
+ if (res.baseUrl !== undefined && res.baseUrl !== url) {
+ setBaseUrl(res.baseUrl);
+ toastSuccess(S.models.detectedProtocolAndUrl(name, res.baseUrl));
+ } else {
+ toastSuccess(S.models.detectedProtocol(name));
+ }
} else {
setDetectFailed(true);
// Same condition the model dialog reports, so it gets the same sentence.
@@ -2331,7 +2351,7 @@ function ModelDialog({
* probe: clicking Detect while the save path is already probing (or vice versa) must not
* double-fire, and the save path needs the SAME run's verdict to decide whether to go on.
*/
- const detectInFlight = useRef<Promise<string | null> | null>(null);
+ const detectInFlight = useRef<Promise<DetectOutcome | null> | null>(null);
/** Vision probe in progress (its own control, so its own busy state). */
const [visionDetecting, setVisionDetecting] = useState(false);
/** Single-flight guard for the vision probe: it bills the user, so never twice at once. */
@@ -2435,7 +2455,7 @@ function ModelDialog({
* A stale run (superseded by a manual pick or a newer run) discards its result instead
* of clobbering the form, and stays silent.
*/
- const detectOnce = async (mode: DetectMode): Promise<string | null> => {
+ const detectOnce = async (mode: DetectMode): Promise<DetectOutcome | null> => {
// What an empty result means depends on who asked. A manual run simply failed; a save
// run silently resolves to the compatible client and says so, because the save it was
// serving is still going through.
@@ -2467,8 +2487,14 @@ function ModelDialog({
const res = await api.detectProtocol(projectId, body);
if (seq !== detectSeq.current) return null;
if (res.detected) {
- set({ clientType: res.detected });
- return res.detected;
+ // The protocol may have answered on a tidied-up form of the URL (a `/v1` added or
+ // dropped, a pasted endpoint path removed). Saving the typed form would persist a
+ // base URL the detected protocol is not served at, so the field takes the one that
+ // answered and the outcome carries it on to the save path.
+ const served = res.baseUrl;
+ const patch = served !== undefined && served !== baseUrl ? { baseUrl: served } : {};
+ set({ clientType: res.detected, ...patch });
+ return { clientType: res.detected, ...patch };
}
failed();
return null;
@@ -2484,7 +2510,7 @@ function ModelDialog({
* Single-flight wrapper: a second trigger joins the run already in progress rather than
* starting a rival probe (the button while the save path is probing, or vice versa).
*/
- const runDetect = (mode: DetectMode): Promise<string | null> => {
+ const runDetect = (mode: DetectMode): Promise<DetectOutcome | null> => {
if (detectInFlight.current) return detectInFlight.current;
const run = detectOnce(mode).finally(() => {
detectInFlight.current = null;
@@ -2501,7 +2527,12 @@ function ModelDialog({
const detectFromButton = async () => {
const detected = await runDetect("manual");
if (detected === null) return; // detectOnce already raised the failure toast
- toastSuccess(S.models.detectedProtocol(S.models.protocolNames[detected] ?? detected));
+ const name = S.models.protocolNames[detected.clientType] ?? detected.clientType;
+ toastSuccess(
+ detected.baseUrl === undefined
+ ? S.models.detectedProtocol(name)
+ : S.models.detectedProtocolAndUrl(name, detected.baseUrl),
+ );
};
/**
@@ -2682,7 +2713,17 @@ function ModelDialog({
if (needsProtocolDetectOnSave(action, next.provider, next.clientType)) {
// Joins a run already started from the Detect button rather than probing twice.
const detected = await runDetect("save");
- onSubmit({ ...next, clientType: detected ?? DEFAULT_CUSTOM_CLIENT_TYPE }, action);
+ onSubmit(
+ {
+ ...next,
+ clientType: detected?.clientType ?? DEFAULT_CUSTOM_CLIENT_TYPE,
+ // The draft was snapshotted before the probe, so a base URL the probe corrected
+ // has to be carried over by hand — otherwise the entry saves a URL the detected
+ // protocol is not served at.
+ ...(detected?.baseUrl !== undefined ? { baseUrl: detected.baseUrl } : {}),
+ },
+ action,
+ );
return;
}
onSubmit(next, action);
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index b79a10db..6b87dbb8 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -1034,6 +1034,9 @@ export const en: Strings = {
detecting: "Detecting…",
/** Success toast; the protocol itself then shows in the base URL field's suffix. */
detectedProtocol: (name: string): string => `Detected ${name}; applied`,
+ /** Success toast when the probe answered on a tidied-up base URL, which the field now holds. */
+ detectedProtocolAndUrl: (protocol: string, url: string): string =>
+ `Detected ${protocol}; base URL normalized to ${url}`,
/** The ONE failure toast: every mode collapses to it, naming only what the user can act on. */
detectFailedBody: "Could not detect the protocol. Please check the API key and the base URL.",
/** Save-time detection came back empty: the save proceeds on the compatible client. */
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index af96b146..c3b5d25b 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -1027,6 +1027,9 @@ export const zh = {
detecting: "检测中…",
/** Success toast;协议本身随后显示在 base URL 输入框的后缀处。 */
detectedProtocol: (name: string): string => `检测到 ${name} 协议,已应用`,
+ /** Success toast when the probe answered on a tidied-up base URL, which the field now holds. */
+ detectedProtocolAndUrl: (protocol: string, url: string): string =>
+ `已检测为 ${protocol},base URL 已整理为 ${url}`,
/** The ONE failure toast: 所有失败情形共用,只讲用户能动手改的两件事。 */
detectFailedBody: "无法检测接口协议,请检查 API Key 与 base URL。",
/** 保存时检测无结果:按兼容协议继续保存。 */