Skip to content

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

fix(web): 模型库弹窗的「检测协议」没认出协议时,原因留在 base URL 字段下面

lmliheng3aafe825c9da
diff --git a/changelog/unreleased/2026-11-04-model-detect-refusal.md b/changelog/unreleased/2026-11-04-model-detect-refusal.md
new file mode 100644
index 00000000..390b2357
--- /dev/null
+++ b/changelog/unreleased/2026-11-04-model-detect-refusal.md
@@ -0,0 +1,62 @@
+# A model "detect" that finds no protocol says so under the base URL field, not in a six-second toast
+
+- **Date:** 2026-11-04
+- **Type:** fix
+- **Scope:** `web`
+- **Breaking:** no
+
+[中文](2026-11-04-model-detect-refusal.zh.md)
+
+The model config dialog's "detect" button probes the base URL the form currently holds (with the key
+typed into it, if any) and writes nothing: a hit fills in the protocol, a miss leaves the form
+exactly as it was. So a miss is one sentence the reader has to keep while they fix the two things it
+names — the API key and the base URL, both on that same screen — and it used to arrive as a
+notification only: it sat over the dialog, dismissed itself after six seconds, and left a form that
+looked untouched with nothing on it saying the button had been pressed at all.
+
+That sentence is now drawn in the dialog, directly under the base URL field (`role="alert"`, danger
+colour, two lines at most with the whole text on hover), and it stays until the form is edited, a
+protocol is picked by hand, or the next detection starts. A hit keeps its toast (the field's own
+suffix already shows where the protocol ended up), and so does the save-time fallback note: that one
+reports a save that went through, not a refusal.
+
+One wrong diagnosis goes with it: a request that never left the browser (a 500 from the server, an
+expired login, a dropped connection) used to read "check the API key and the base URL" as well,
+though neither field may be at fault. It now reads the localized sentence for its error code — the
+same rule the "test connection" button in this same dialog follows.
+
+## Details
+
+- `packages/web/src/features/models/detect-refusal.ts` (new, 47 lines): `detectProtocolRefusal(press)`
+ turns one press into that line, `null` for a press that found a protocol. Three shapes: the route
+ answered without a protocol, the URL never left the browser (`detectableBaseUrl`), and the request
+ itself failed. The first two share the sentence that has always named the API key and the base URL —
+ the finer per-probe differences are invisible from outside, and wording one of them as "the endpoint
+ responded" read as success. The third follows `refusalText`'s rule (7.19's, app-wide).
+- `packages/web/src/features/models/models-page.tsx`: one `detectRefusal` state — cleared when a
+ manual run starts and on every edit or manual pick (the sentence describes that run's URL, key and
+ id), set when nothing was found. The line is drawn under the base URL field, after any validation
+ error and before the read-only lock note; `failed()` takes a press instead of raising a toast, and
+ the save path's `detectFellBack` note is unchanged.
+- `packages/web/src/lib/strings{,-en}.ts`: **no new copy** — it reuses `detectFailedBody` plus the
+ sentences the error-code table already holds.
+
+## Tests
+
+- `packages/web/test/detect-refusal.test.ts` (new, 6 cases): a hit leaves nothing / an answer with no
+ protocol keeps the sentence naming the key and the URL / a URL that never left the browser says the
+ same / a failed request reads its code's localized sentence (raw English never reaches the screen,
+ and the "check your key" advice is not used) / an error the client raised itself keeps its own words
+ and nothing at all falls back to the generic text / the active language.
+- `packages/web/e2e/models-detect-refusal.spec.mjs` (new, two cases on a real server): the probe route
+ is stubbed at `page.route`. Case ①: an answer naming no protocol draws the sentence under the base
+ URL field, the notification region holds nothing to dismiss, the probe carried the form's URL,
+ nothing was written, and seven seconds later the line is still there; editing a character drops it.
+ Case ②: a request that failed on the way out — a coded 500 — reads in the app's words rather than as
+ advice to check the key, while the probe carried the unsaved `sk-probe`; once let through, the same
+ button retries, the line goes, and the "detected … protocol, applied" toast appears instead.
+
+## Compatibility
+
+- No interface, request or storage change: the same `POST …/models/detect`, which saves nothing. Only
+ where a miss is drawn has moved, and a failed request now reports its own error code.
diff --git a/changelog/unreleased/2026-11-04-model-detect-refusal.zh.md b/changelog/unreleased/2026-11-04-model-detect-refusal.zh.md
new file mode 100644
index 00000000..7f7163a1
--- /dev/null
+++ b/changelog/unreleased/2026-11-04-model-detect-refusal.zh.md
@@ -0,0 +1,52 @@
+# 模型库配置弹窗的「检测协议」没认出协议时,原因留在 base URL 字段下面,不再只活六秒
+
+- **日期:** 2026-11-04
+- **类型:** fix
+- **范围:** `web`
+- **破坏性:** 无
+
+[English](2026-11-04-model-detect-refusal.md)
+
+模型库配置弹窗里那颗「检测协议」跑的是表单当前的 base URL(以及里面填了还没保存的 key),
+什么都不写:认出来只把协议填进字段,认不出则表单一个字都不变。于是那次没认出来就是读者改同一张
+表单时要一直看着的一句话 —— 它点名的 API Key 与 base URL 就在同一屏 —— 而此前它只落进一条通知:
+盖在弹窗上方、六秒后自行消失,六秒之后屏上没有任何东西说明这颗按钮被按过。
+
+现在这句话画在弹窗里、base URL 字段的正下方(`role="alert"`、危险色、限两行、整句挂悬停),
+留到表单被编辑、手动选了协议或下一次检测开始为止。认出来的那次仍是一条通知(协议落在的字段就是
+字段右端那枚后缀,屏幕上已经有地方放着它);保存时顺带检测没认出来的那条提示也仍是通知 —— 它讲的
+是一次已经写下去的保存,不是一次拒绝。
+
+顺带修一处指错地方的诊断:请求本身就没发出去(服务端 500、登录过期、连接断了)此前也念那句
+「请检查 API Key 与 base URL」,可这两个字段可能一点问题都没有。这种情形现在念错误码自己的本地化
+句子,与这个弹窗里「测试连通性」那颗按钮同一条规则。
+
+## 细节
+
+- `packages/web/src/features/models/detect-refusal.ts`(新,47 行):`detectProtocolRefusal(press)`
+ 把一次按键的结局变成那句话,认出协议给 `null`。三种结局:路由答复但没认出协议、URL 根本没能离开
+ 浏览器(`detectableBaseUrl` 判的)、请求本身失败。前两种共用那句点名「API Key 与 base URL」的
+ 老话 —— 探测过程中更细的区别从外面看不见,把其中一种说成「端点有回应」会被读成成功;第三种走
+ `refusalText` 的既有规则(7.19 那条,全应用一致的拒绝口径)。
+- `packages/web/src/features/models/models-page.tsx`:一个 `detectRefusal` 状态 —— 手动检测开始时
+ 清掉、任何一次表单编辑或手动选协议时清掉(这句话描述的是那一次的 URL、key 与 id)、没认出来时写上。
+ 句子画在 base URL 字段下面(错误行之后、锁定说明之前);`failed()` 从「弹 toast」改成「交一份结局
+ 进来」,保存流程那条 `detectFellBack` 提示原样保留。
+- `packages/web/src/lib/strings{,-en}.ts`:**没有新文案** —— 复用 `detectFailedBody`,外加错误码
+ 表里本来就有的句子。
+
+## 测试
+
+- `packages/web/test/detect-refusal.test.ts`(新,6 条):认出协议不留话 / 答复里没有协议仍是那句
+ 老话 / URL 没能离开浏览器给同一句 / 请求失败按错误码取本地化句子(原始英文不上屏、也不退回那句
+ 检查 key 的话)/ 客户端自己抛的错保留自己的话、什么都没有时退回通用那句 / 跟着界面语言走。
+- `packages/web/e2e/models-detect-refusal.spec.mjs`(新,真服务端两条):探测路由桩在
+ `page.route` 上。用例①:答复里没有协议时 base URL 下面出现那句话、通知区 0 个可点条目、探测带走
+ 的是表单里的 URL、什么都没写,七秒后句子仍在;改一个字符即清掉。用例②:请求本身失败(500 加错误
+ 码)时按应用的本地化句子显示(不是那句检查 key 的话),探测带走的是未保存的 `sk-probe`;放行后
+ 同一颗按钮重试 —— 句子消失,换成那条「检测到 … 协议,已应用」的通知。
+
+## 兼容
+
+- 接口、请求与存储都没变:还是同一次 `POST …/models/detect`,不写任何东西。改变的只有没认出来之后
+ 画在哪里、以及请求本身失败时说的是谁的话。
diff --git a/packages/web/e2e/models-detect-refusal.spec.mjs b/packages/web/e2e/models-detect-refusal.spec.mjs
new file mode 100644
index 00000000..c1359791
--- /dev/null
+++ b/packages/web/e2e/models-detect-refusal.spec.mjs
@@ -0,0 +1,201 @@
+/**
+ * Regression: the model config dialog's "detect" button says why a probe found no protocol — in the
+ * dialog, under the base URL field it read — instead of leaving the form exactly as it was with the
+ * reason in a notification that dismissed itself after six seconds.
+ *
+ * The button asks the endpoint about the URL the form currently holds and writes nothing. A miss is
+ * therefore one sentence the reader has to keep while they fix the two things it names (the API key,
+ * the base URL), and both of those fields are in the same dialog. Six seconds after the press that
+ * sentence used to be gone, and the form carried no sign the button had been pressed at all.
+ *
+ * The probe route is stubbed rather than travelled: what this spec is about is what the page does
+ * with the answer. Both shapes are exercised — an answer that named no protocol (the same sentence
+ * the button has always used) and a request that failed on the way out (which now reads in the
+ * app's own words, because the endpoint was never asked and "check your key and URL" would send the
+ * reader to fields that may well be fine).
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const P = "password123";
+
+/** The group and model the tests work with; unique enough to appear nowhere else. */
+const GROUP = "probedetect";
+const MODEL = "probe-detect";
+const NAME = "Probe Detect";
+const BASE_URL = "http://127.0.0.1:9/v1";
+
+/** The sentence a press that found nothing leaves: the one the button has always used. */
+const MISS = "无法检测接口协议,请检查 API Key 与 base URL。";
+
+/** The row the model is, as this file seeds it: a hand-added model of a user-defined group. */
+const ROW = {
+ provider: GROUP,
+ modelId: MODEL,
+ displayName: NAME,
+ contextWindow: 32000,
+ clientType: "openai-chat",
+ baseUrl: BASE_URL,
+ maxTokens: 4096,
+};
+
+/** The table entry a `ModelInfo` came from: every field the response reports, sent back as-is. */
+function toEntry(m) {
+ const entry = { provider: m.provider, modelId: m.modelId };
+ for (const key of [
+ "displayName",
+ "contextWindow",
+ "clientType",
+ "vision",
+ "maxTokens",
+ "fastMode",
+ "pricing",
+ ]) {
+ if (m[key] !== undefined) entry[key] = m[key];
+ }
+ if (m.credential?.baseUrl !== undefined) entry.baseUrl = m.credential.baseUrl;
+ return entry;
+}
+
+/**
+ * Provision the user and seed their Project with the model, through the table PUT so nothing here
+ * depends on the built-in catalog. Idempotent: a rerun on the same data root rewrites the row the
+ * tests expect rather than trusting it.
+ */
+async function projectWithModel(page, user) {
+ await provisionAndLogin(page.request, user, P);
+ const { projects } = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects[0].projectId;
+ const read = async () =>
+ (await page.request.get(`${BASE}/api/projects/${projectId}/models`)).json();
+
+ const table = await read();
+ const current = table.models.find((m) => m.provider === GROUP && m.modelId === MODEL);
+ if (!current || (current.displayName ?? "") !== NAME) {
+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {
+ data: {
+ defaultModel: table.defaultModel,
+ models: [...table.models.filter((m) => m.provider !== GROUP).map(toEntry), ROW],
+ },
+ });
+ expect(put.ok(), "seed the model through the table PUT").toBeTruthy();
+ }
+ expect(
+ (await read()).models.find((m) => m.provider === GROUP && m.modelId === MODEL),
+ "the Project holds the model",
+ ).toBeTruthy();
+}
+
+/**
+ * Open the model's config dialog. The list is filtered rather than scrolled: a user-defined group
+ * sits far below the built-in ones, and a search force-opens every group it leaves visible.
+ */
+async function openModelDialog(page) {
+ await page.goto("/models");
+ await page.locator('input[placeholder*="搜索"]').first().fill(NAME);
+ const card = page.getByText(NAME, { exact: true }).first();
+ await expect(card).toBeVisible();
+ await card.click();
+ const dialog = page.getByRole("dialog");
+ await expect(dialog).toBeVisible();
+ await expect(page.getByRole("button", { name: "删除模型" })).toBeVisible();
+ return dialog;
+}
+
+/** The line the dialog draws under the base URL field. */
+function line(dialog) {
+ return dialog.getByRole("alert");
+}
+
+/** The notification area's dismissible entries: what a miss used to be. */
+function toasts(page) {
+ return page.getByRole("region", { name: "通知" }).getByRole("button");
+}
+
+test("a detection that found nothing leaves its reason under the base URL field", async ({
+ page,
+}) => {
+ await projectWithModel(page, "r191test");
+
+ const dialog = await openModelDialog(page);
+ const posts = [];
+ await page.route("**/api/projects/*/models/detect", async (route) => {
+ if (route.request().method() !== "POST") return route.fallback();
+ posts.push(route.request().postDataJSON());
+ // What the route sends when none of the three probes matched: no `detected`, no `baseUrl`.
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({ probes: [] }),
+ });
+ });
+
+ await dialog.getByRole("button", { name: "检测协议" }).click();
+
+ // One sentence, in the dialog, naming the two fields it sits between — not in a toast.
+ await expect(line(dialog)).toHaveText(MISS);
+ await expect(toasts(page)).toHaveCount(0);
+ expect(posts).toHaveLength(1);
+ // The probe asked about the form as it stands, and wrote nothing back into it.
+ expect(posts[0]).toMatchObject({ baseUrl: BASE_URL });
+
+ // And the reason is still on screen after the toast that used to carry it would have gone.
+ await page.waitForTimeout(7000);
+ await expect(line(dialog)).toHaveText(MISS);
+
+ // An edit retires it: the sentence described the URL the probe was sent, and that URL is no
+ // longer the one in the field.
+ await dialog.getByLabel("自定义 base URL").fill("http://127.0.0.1:9/v2");
+ await expect(line(dialog)).toHaveCount(0);
+});
+
+test("a request that failed on the way out reads in the app's words, and the retry clears it", async ({
+ page,
+}) => {
+ await projectWithModel(page, "r191retry");
+
+ const dialog = await openModelDialog(page);
+ const posts = [];
+ let refuse = true;
+ await page.route("**/api/projects/*/models/detect", async (route) => {
+ if (route.request().method() !== "POST") return route.fallback();
+ posts.push(route.request().postDataJSON());
+ if (!refuse) {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({ detected: "openai-chat", baseUrl: BASE_URL, probes: [] }),
+ });
+ return;
+ }
+ await route.fulfill({
+ status: 500,
+ contentType: "application/json",
+ body: JSON.stringify({ error: { code: "internal", message: "RAW ENGLISH MESSAGE" } }),
+ });
+ });
+
+ // A key typed but not yet saved: the probe asks about it, which is why its refusal belongs on the
+ // form rather than in a notification.
+ await dialog.getByLabel("API key").fill("sk-probe");
+
+ await dialog.getByRole("button", { name: "检测协议" }).click();
+ // The code's own sentence, not the server's English, and not the "check your key and URL" advice
+ // for a request that never reached the endpoint.
+ await expect(line(dialog)).toHaveText("服务器内部错误,请稍后重试。");
+ await expect(toasts(page)).toHaveCount(0);
+ expect(posts).toHaveLength(1);
+ // What was probed is the draft, not the stored row.
+ expect(posts[0]).toMatchObject({ baseUrl: BASE_URL, apiKey: "sk-probe" });
+
+ // The button is the retry, and a probe that lands leaves nothing behind: the line goes and the
+ // hit travels in the toast the dialog has always used for it.
+ refuse = false;
+ await dialog.getByRole("button", { name: "检测协议" }).click();
+ await expect(line(dialog)).toHaveCount(0);
+ await expect(page.getByRole("region", { name: "通知" })).toContainText(
+ "检测到 OpenAI Chat Completions 协议,已应用",
+ );
+ expect(posts).toHaveLength(2);
+});
diff --git a/packages/web/src/features/models/detect-refusal.ts b/packages/web/src/features/models/detect-refusal.ts
new file mode 100644
index 00000000..75c09194
--- /dev/null
+++ b/packages/web/src/features/models/detect-refusal.ts
@@ -0,0 +1,47 @@
+/**
+ * The model config dialog's "Detect" button: the sentence a detection that found no protocol
+ * leaves under the base URL field, and why that sentence is a line in the dialog rather than a
+ * toast.
+ *
+ * The button probes the URL the form currently holds and writes nothing — a hit only fills in the
+ * protocol, a miss changes nothing at all. So the miss is one sentence the reader has to keep
+ * while they fix the two things it names (the API key, the base URL), and those two fields are
+ * right there in the same dialog. As a notification it sat over the dialog and dismissed itself
+ * after six seconds, leaving a form that looked exactly as it did before the button was pressed.
+ *
+ * A hit keeps its toast (`detectedProtocol*`): it leaves nothing to explain, and where the
+ * protocol ended up is already visible in the field's suffix. A save-time fallback keeps its note
+ * too — it reports a save that went through, not a refusal.
+ */
+import type { ModelProtocolDetectResponse } from "@adelie/server/api";
+import { S } from "../../lib/strings";
+import { refusalText } from "../../lib/api-error";
+
+/** What one press came back with. */
+export type DetectPress =
+ /** The route answered, with or without a protocol. */
+ | { readonly kind: "answer"; readonly result: ModelProtocolDetectResponse }
+ /** The URL never left the browser (see `detectableBaseUrl`): the route was never asked. */
+ | { readonly kind: "unprobeable" }
+ /** The request itself failed on the way out (server error, login gone, connection dropped). */
+ | { readonly kind: "failed"; readonly error?: unknown };
+
+/**
+ * The line the dialog draws for one press, or `null` when the press found a protocol.
+ *
+ * Both keyless shapes — an answer naming no protocol, and a URL that was never probeable — keep
+ * the single sentence the button has always used: it names the two things the reader can act on,
+ * and the per-probe differences behind it are invisible from outside (wording one of them as "the
+ * endpoint responded" read as success).
+ *
+ * A request that never reached the route is a different fact, and telling the reader to check the
+ * key and the URL for it sends them to fields that may well be fine: it reads the error code's own
+ * localized sentence instead, the rule every other refusal slot in the app follows (7.19's).
+ */
+export function detectProtocolRefusal(press: DetectPress): string | null {
+ if (press.kind === "answer") {
+ return press.result.detected ? null : S.models.detectFailedBody;
+ }
+ if (press.kind === "unprobeable") return S.models.detectFailedBody;
+ return refusalText(press.error);
+}
diff --git a/packages/web/src/features/models/models-page.tsx b/packages/web/src/features/models/models-page.tsx
index 20dcc60a..6410d3c6 100644
--- a/packages/web/src/features/models/models-page.tsx
+++ b/packages/web/src/features/models/models-page.tsx
@@ -169,6 +169,8 @@ import { refusalOf } from "./write-outcome";
import type { WriteOutcome } from "./write-outcome";
import { modelTestRefusal } from "./model-test-refusal";
import type { ModelTestAnswer } from "./model-test-refusal";
+import { detectProtocolRefusal } from "./detect-refusal";
+import type { DetectPress } from "./detect-refusal";
/**
* The authorization flows a group's Connect dialog can run, keyed by the flow named in that
@@ -2708,10 +2710,18 @@ function ModelDialog({
/**
* Whether the last detection run came back empty, purely to tint the suffix trigger
* amber. That tint is the control's own appearance, not a message occupying the form —
- * the wording of both outcomes lives in a toast. It is deliberately the only trace left:
- * a hit needs none, because the suffix then shows the protocol it applied.
+ * the wording of a miss lives in `detectRefusal` below. A hit needs neither, because the
+ * suffix then shows the protocol it applied.
*/
const [detectFailed, setDetectFailed] = useState(false);
+ /**
+ * The sentence a detection that found nothing left under the base URL field (detect-refusal.ts).
+ * It lives on the dialog for the same reason the connectivity test's line does: the URL and the
+ * API key it names are the fields the reader is about to change, and a toast would be gone before
+ * they finished reading it against them. Cleared by every edit, by a manual pick, and at the
+ * start of the next manual run.
+ */
+ const [detectRefusal, setDetectRefusal] = useState<string | null>(null);
/**
* Monotonic run counter: each detection captures it and only the newest run may apply
* its result — a manual protocol pick or a re-run supersedes anything still in flight.
@@ -2761,8 +2771,10 @@ function ModelDialog({
const set = (patch: Partial<RowState>) => {
setForm((prev) => ({ ...prev, ...patch }));
// A refused probe described the values it was sent: any edit makes that sentence describe a
- // form that is no longer on screen, so it goes with the field it named.
+ // form that is no longer on screen, so it goes with the field it named. Same for the detection
+ // line below — a detection reads the URL, the key and the id, so every one of them retires it.
setTestRefusal(null);
+ setDetectRefusal(null);
// Clear the error marker for whichever field was changed (keys match RowState field names).
setFieldErrors((prev) => {
const next = { ...prev };
@@ -2850,34 +2862,37 @@ function ModelDialog({
* is always live and a failure explains itself afterwards instead of being pre-empted by
* a disabled control.
*
- * Outcomes are announced with a toast, like the connectivity test in this same dialog:
- * transient and non-blocking, nothing to dismiss before carrying on. The Toaster portals
- * to document.body at z-[100] against the Modal's z-50, so a toast raised from inside
- * this dialog renders above it rather than behind or clipped by it.
+ * Outcomes are announced differently by kind. A hit is a toast (`detectedProtocol*`): transient,
+ * non-blocking, and the suffix then shows the protocol it applied — nothing to read against the
+ * form. The Toaster portals to document.body at z-[100] against the Modal's z-50, so that toast
+ * renders above this dialog rather than behind or clipped by it. A miss is NOT a toast: it is a
+ * sentence under the base URL field (`detectRefusal`, built by detect-refusal.ts), where
+ * the two fields it names are, and where it stays until the form changes — a toast left a form
+ * that looked untouched with nothing on it saying the button had been pressed.
*
- * Every failure — unreachable, timeout, gateway junk, nothing matched, an invalid URL
- * that never left the browser, a server error — raises the SAME message naming the two
- * things the user can act on (API key, base URL). Per maintainer: the finer distinctions
- * are invisible from the outside, and wording one of them as "the endpoint responded"
- * read as success. The per-probe outcomes stay in the endpoint's response for debugging.
+ * Every failure names the two things the user can act on (API key, base URL) — see
+ * detectProtocolRefusal for the one shape that does not, and why.
*
* 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<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.
- const failed = () => {
+ // What a miss is reported as depends on who asked. A manual run explains itself in the form; a
+ // save run silently resolves to the compatible client and says so, because the save it was
+ // serving is still going through — that note reports a write that happened, not a refusal.
+ const failed = (press: DetectPress) => {
setDetectFailed(true);
if (mode === "save") toastInfo(S.models.detectFellBack);
- else toastError(S.models.detectFailedBody);
+ else setDetectRefusal(detectProtocolRefusal(press));
};
+ // The previous answer described a URL that may have been edited since, and this press is a new
+ // question: the line goes while that answer is in flight.
+ if (mode === "manual") setDetectRefusal(null);
const baseUrl = form.baseUrl.trim();
// An unusable URL is just another failure: the server would 400 it, and the user gets
// the same message either way rather than a distinct piece of API error text.
if (!detectableBaseUrl(baseUrl)) {
- failed();
+ failed({ kind: "unprobeable" });
return null;
}
const seq = ++detectSeq.current;
@@ -2905,10 +2920,10 @@ function ModelDialog({
set({ clientType: res.detected, ...patch });
return { clientType: res.detected, ...patch };
}
- failed();
+ failed({ kind: "answer", result: res });
return null;
- } catch {
- if (seq === detectSeq.current) failed();
+ } catch (e) {
+ if (seq === detectSeq.current) failed({ kind: "failed", error: e });
return null;
} finally {
if (seq === detectSeq.current) setDetecting(false);
@@ -2935,7 +2950,7 @@ function ModelDialog({
*/
const detectFromButton = async () => {
const detected = await runDetect("manual");
- if (detected === null) return; // detectOnce already raised the failure toast
+ if (detected === null) return; // detectOnce already put the miss in the form
const name = S.models.protocolNames[detected.clientType] ?? detected.clientType;
toastSuccess(
detected.baseUrl === undefined
@@ -3630,7 +3645,7 @@ function ModelDialog({
</FieldLabel>
{/* Always live: no API key is needed (the server falls back to the stored key
and then to the protocol's env var), and anything that does go wrong is
- explained in a popup. `detecting` only guards re-entrancy. */}
+ explained below this field. `detecting` only guards re-entrancy. */}
<Button
variant="link"
size="sm"
@@ -3697,6 +3712,19 @@ function ModelDialog({
)}
</div>
{fieldErrors.baseUrl && <FieldError>{fieldErrors.baseUrl}</FieldError>}
+ {detectRefusal !== null && (
+ // Under the field the probe read (the button that asked sits in the label row above),
+ // and the same slot the connectivity test's refusal uses: `line-clamp-2` keeps a long
+ // upstream sentence from heightening the form, and the whole text is on hover.
+ <p
+ role="alert"
+ data-tooltip={detectRefusal}
+ data-tooltip-content="text"
+ className={`mt-1 line-clamp-2 break-words text-xs ${toneInk.danger}`}
+ >
+ {detectRefusal}
+ </p>
+ )}
{/* Why the field above (and the price row below) will not take an edit — one line for
both, since the lock is one rule. It is shown rather than left to the greyed
control alone: a read-only field with no reason reads as a broken one, and the way
@@ -3707,11 +3735,12 @@ function ModelDialog({
{S.models.officialLockedHint}
</p>
)}
- {/* No detection verdict is rendered here (per maintainer): a result must not take
- up room in the form. Both outcomes are toasts, and where the protocol ENDED UP
- is already visible in the suffix above, which is the thing that actually holds
- it. Nothing conditional remains below the field, so the idle and post-detection
- layouts are identical — no reserved height, no shift. */}
+ {/* A detection VERDICT takes no room here (per maintainer): a hit needs none, because
+ where the protocol ended up is the suffix above, which is the thing that holds it.
+ A miss is not a verdict but a refusal, and it does get a line — the one drawn above
+ the lock note (detectRefusal): it names the URL and the key, both within a glance of
+ it, and it stays until the form changes. Idle and post-hit layouts stay identical:
+ that line exists only while there is something to account for. */}
</div>
{/* 3) Context window + max output tokens side by side (one row): the "Token" unit
diff --git a/packages/web/test/detect-refusal.test.ts b/packages/web/test/detect-refusal.test.ts
new file mode 100644
index 00000000..04b730a6
--- /dev/null
+++ b/packages/web/test/detect-refusal.test.ts
@@ -0,0 +1,73 @@
+/**
+ * The model config dialog's protocol-detection line (src/features/models/detect-refusal.ts):
+ * which presses leave a sentence under the base URL field, and whose words that sentence uses.
+ *
+ * A detection writes nothing on a miss — the form keeps every value it was asked with — so this
+ * line is the only thing that accounts for the press once the six-second toast is gone. The cases
+ * below are the three shapes a press comes in and the two languages; the rule that matters most is
+ * the first: a press that found a protocol leaves nothing behind.
+ */
+import { afterEach, describe, expect, it } from "vitest";
+import { ApiError } from "../src/api/client";
+import { en as EN } from "../src/lib/strings-en";
+import { S, setActiveStrings, zh as ZH } from "../src/lib/strings";
+import { detectProtocolRefusal } from "../src/features/models/detect-refusal";
+
+afterEach(() => {
+ setActiveStrings(ZH);
+});
+
+describe("detectProtocolRefusal", () => {
+ it("leaves no line when a protocol was found", () => {
+ // Where it ended up is the field's suffix, and the hit travels in a toast of its own.
+ expect(
+ detectProtocolRefusal({
+ kind: "answer",
+ result: { detected: "openai-chat", baseUrl: "http://h/v1", probes: [] },
+ }),
+ ).toBeNull();
+ });
+
+ it("keeps the one sentence that names what the reader can change", () => {
+ // Nothing matched: the route answered, but with no protocol. The per-probe detail behind that
+ // is not something the reader can act on, so the sentence names the key and the URL only.
+ expect(detectProtocolRefusal({ kind: "answer", result: { probes: [] } })).toBe(
+ S.models.detectFailedBody,
+ );
+ });
+
+ it("says the same for a URL that never left the browser", () => {
+ // detectOnce refuses to send it (detectableBaseUrl); the route was never asked, and the answer
+ // would have been the same complaint either way.
+ expect(detectProtocolRefusal({ kind: "unprobeable" })).toBe(S.models.detectFailedBody);
+ });
+
+ it("reads a failed request through its code, so the advice is not misleading", () => {
+ // The endpoint was never probed: telling the reader to check the key and the URL would send
+ // them to fields that may well be fine, so a 500 reads as a 500.
+ const line = detectProtocolRefusal({
+ kind: "failed",
+ error: new ApiError(500, "internal", "RAW ENGLISH SERVER MESSAGE"),
+ });
+ expect(line).toBe(S.errors.byCode["internal"] as string);
+ expect(line).not.toContain("RAW ENGLISH SERVER MESSAGE");
+ expect(line).not.toBe(S.models.detectFailedBody);
+ });
+
+ it("keeps the message of an error the client itself raised", () => {
+ // `refusalText`'s rule: only an ApiError goes through the code table; anything else with
+ // something to say is shown as it is, and nothing at all falls back to the generic text.
+ expect(detectProtocolRefusal({ kind: "failed", error: new Error("network down") })).toBe(
+ "network down",
+ );
+ expect(detectProtocolRefusal({ kind: "failed", error: undefined })).toBe(S.common.unknownError);
+ });
+
+ it("follows the active language", () => {
+ setActiveStrings(EN);
+ expect(detectProtocolRefusal({ kind: "answer", result: { probes: [] } })).toBe(
+ EN.models.detectFailedBody,
+ );
+ expect(detectProtocolRefusal({ kind: "unprobeable" })).toBe(EN.models.detectFailedBody);
+ });
+});