Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(model-hub): detect-then-confirm add-key flow (#1831)
Max359df0abaafd
diff --git a/docs/plans/model-hub-ui-spec.md b/docs/plans/model-hub-ui-spec.mdindex fbdb4118e..a6b1f7ede 100644--- a/docs/plans/model-hub-ui-spec.md+++ b/docs/plans/model-hub-ui-spec.md@@ -755,13 +755,14 @@ success row; a classified pre-commit answer takes the matching observation row;Source-create transport/no-answer result or a response with no terminal observationclassifier enters ⑦.-| O1 evidence | Explicit observe, Add origin | Explicit observe, Pull origin | Source-create repeated observation |-| --- | --- | --- | --- |-| `authentication_failed`, `unreachable`, `timeout` or `adapter_error` | ③ | ③′ | ③; no Source committed |-| `ambiguous` | ④ | ④′ | ④; no Source committed |-| `observed`, protocol non-null, `discovery: failed` | ⑤ | ⑤′ | ⑤ when `SourceCreate.accept_unavailable_inventory` is false / omitted; only ⑤ resends it as true `[contract]` |-| accepted producer result: explicit `observed` + `discovery: succeeded`, or a Source-create committed success envelope | Send the complete `SourceCreate` with `accept_unavailable_inventory` false / omitted `[contract]` | ①′ | Close into 06 with the returned Source and placement evidence |-| no terminal observation classifier | The explicit observe failure remains F1 and sends no create | The explicit observe failure remains F1 and sends no create | ⑦; commit status is genuinely unconfirmed |+| O1 evidence | Explicit observe (`检测`) | Source-create repeated observation |+| --- | --- | --- |+| `authentication_failed`, `unreachable`, `timeout` or `adapter_error` | ③ | ③; no Source committed |+| `ambiguous` | ④ | ④; no Source committed |+| `observed`, protocol non-null, `discovery: failed` | ⑤ | ⑤ when `SourceCreate.accept_unavailable_inventory` is false / omitted; only ⑤ resends it as true `[contract]` |+| accepted producer result: explicit `observed` + `discovery: succeeded` | ①″ Identified — persist nothing | — |+| accepted producer result: a Source-create committed success envelope | — | Close into 06 with the returned Source and placement evidence |+| no terminal observation classifier | The explicit observe failure remains F1 and sends no create | ⑦; commit status is genuinely unconfirmed |**Held-install status-read owner** `[derived]`. The existing `BackendOAuthPanel`establishes the product's 2s polling cadence; installation borrows that cadence, not its@@ -862,19 +863,16 @@ state exit; held intent never bypasses the evidence column.| §1.4 | Engine unavailable | The gateway is not running and gateway-upstream was chosen | F1 | `addSub.error.engineDown`, `addSub.retry` | 重试 re-sends, and that press **is** the recovery observation — nothing here watches for one — so its answer decides: whichever of *Awaiting sign-in* / *Already bound* / *Start failed* the start call then names, or still down → back here; 取消 → dismiss, nothing bound `[derived]` || §1.4 | Already bound | 去登录 was refused by the start call because that backend already holds its one `native_cli` Source — 「the API rejects duplicate creation with the existing Source id」 `[spec §4.1]`. **This is the race the dialog cannot see**: it disables the native row from the sources it read on open, and the singleton can appear after that | F1, in place — nothing was sent to the provider, so there is no flow to cancel | `addSub.error.alreadyBound`, `addSub.retry` | 重试 → Second pass: the dialog re-reads the sources, the native row is now the inert one, and the hub row is what 去登录 sends; 取消 → dismiss, nothing bound `[derived]` || §1.4 | Start failed | `POST /api/models/oauth/start` did not put a flow in this dialog's hands, for any reason that is not the singleton refusal above — a refusal, or no answer at all. The exact generated `(client_nonce, vendor, channel)` tuple remains held `[contract]` | F1, in place — there is no `flow_id` to poll or cancel, so D-36 reconciliation repeats only the held tuple. The server coalesces an in-flight claim, returns its one committed flow, or releases the tuple for one fresh provider start | `addSub.error.startFailed`, `addSub.retry` | 重试 sends the same tuple and classifies the answer as Default does: accepted/coalesced flow → RR-1/RR-2, singleton refusal → Already bound, still no flow → back here. It never opens a second provider start beside the first. 取消 dismisses; a claim released before flow creation has no Source binding `[derived]` |-| §1.5 | ① Default | Dialog opened | F5 | `addKey.title` … `addKey.submit`; `addKey.field.protocol`, `addKey.field.protocol.hint`, and all four `addKey.protocol.*` options | Auto detect is selected initially. Choosing a concrete interface constrains both 拉取型号 and 添加 to exactly that protocol. 添加 → ②; 拉取型号 → ②′; 取消 → dismiss |-| §1.5 | ①′ Pull result, **Pull origin** `[derived]` | ②′ came back with an inventory — including after a hint in ④′, and after 重试 reran the entire observation from ⑤′ | F5 — the request already succeeded | `addKey.pull.result`, `addKey.pull.empty`, and ①'s own keys, which all still render | Editing Base URL or API Key → ①, the report dropped; 拉取型号 again → ②′; 添加 → ②, which runs its own observation and reuses nothing from here; 取消 → dismiss |-| §1.5 | ② Adding | 添加 pressed — `POST /api/models/sources/observe` runs first, and `POST /api/models/sources` with one generated `client_nonce` goes out only on the outcome that has consent `[contract]` | → ③ / ④ / ⑤ / ⑦ through O1 | `addKey.adding`, `addKey.adding.detail` | O1 classifies both producers. An accepted explicit observation sends the complete `SourceCreate` with `accept_unavailable_inventory` false / omitted `[contract]`; its committed success envelope closes into 06. A classified create refusal returns to ③ / ④ / ⑤ exactly as the same observation would; only transport/no answer or a create response with no terminal observation classifier → ⑦ |-| §1.5 | ②′ Pulling, **Pull origin** `[derived]` | 拉取型号 pressed, or 重试 pressed from ③′ / ④′ / ⑤′ | → ③′ / ④′ / ⑤′ | `addKey.adding`, `addKey.adding.detail` | Success → ①′, persisting nothing |-| §1.5 | ③ Failure, **Add origin** | O1 received one of four closed unsuccessful outcomes from the explicit 添加 observation or Source create's repeated observation: `authentication_failed`, `unreachable`, `timeout` or `adapter_error` `[contract]` | F1 | `addKey.fail.subtitle`; exactly one outcome line: `authentication_failed` → `addKey.fail.auth` + `addKey.fail.auth.detail`, `unreachable` → `addKey.fail.address`, `timeout` → `addKey.fail.network`, `adapter_error` → `addKey.fail.unclassified`; `addKey.retry` | 重试 → ②, whichever producer returned the line — the retry re-runs the explicit observation before any create and does not depend on what the last one concluded |-| §1.5 | ③′ Failure, **Pull origin** `[derived]` | A probe run by 拉取型号 classified the failure | F1 | as ③ | 重试 → **another 拉取型号, not ②** |-| §1.5 | ④ Interface undetermined, **Add origin** | O1 received `SourceObservation.outcome: ambiguous` from the explicit 添加 observation or Source create's repeated observation: reachable, protocol null, and authentication authenticated or unknown `[contract]` | F1 | ①'s still-visible form and selector plus `addKey.undetermined.title`, `addKey.undetermined.detail`, and `addKey.retry` | Choose one concrete interface + 重试 → run the entire explicit observation against exactly that protocol; identified with discovery succeeded → send the complete `SourceCreate` with the same `protocol` constraint and `accept_unavailable_inventory` false / omitted `[contract]`, whose result re-enters O1; identified with discovery failed → ⑤; still ambiguous → back to ④ |-| §1.5 | ④′ Interface undetermined, **Pull origin** `[derived]` | The same outcome, from 拉取型号 | F1 | as ④ | Choose one concrete interface + 重试, still as a pull → identified: → ①′, persisting nothing; still undetermined: back to ④′ |-| §1.5 | ⑤ Identified, inventory unavailable, **Add origin** `[frame]` `d6bFlX` | O1 received `SourceObservation.outcome: observed`, protocol non-null, and `discovery: failed` from the explicit 添加 observation or Source create's repeated observation; the contract carries no request/status/reason evidence `[contract]` | F1 | `addKey.inventory.title`, `addKey.inventory.detail`, `addKey.retry`, `addKey.addAnyway` | 重试 → run **the entire explicit observation** again. 仍要添加 → send `SourceCreate` with **`accept_unavailable_inventory: true`** `[contract]`; false / omitted remains the clean path and may not commit this repeated discovery-failed observation. The server still repeats response-backed observation: only the same protocol-proved / discovery-failed cell may commit with `models: []`; every other classified result remains O1's own and the flag supplies no evidence. Only that committed success envelope closes into 06 |-| §1.5 | ⑤′ Identified, inventory unavailable, **Pull origin** `[derived]` | The same outcome, from 拉取型号 | F1 | as ⑤ without `addKey.addAnyway` | 重试 → run the entire observation again as a pull |-| §1.5 | ⑥ Engine unavailable, **Add origin** `[derived]` | The gateway is not running when 添加 is pressed | F1 | `addKey.fail.engineDown`, `addKey.retry` | F1 in full: the form keeps every value it holds and the primary becomes 重试. Pressing it **is** the recovery observation — nothing here watches for one — and re-attempts 添加 → ②, whose own outcomes then apply; the engine still down → back here; 取消 → dismiss |-| §1.5 | ⑥′ Engine unavailable, **Pull origin** `[derived]` | The gateway is not running when 拉取型号 is pressed | F1 | as ⑥ | The same, one control over: 重试 re-attempts 拉取型号 → ②′. Nothing was going to be persisted either way, so the two rows differ only in which request the press re-sends |-| §1.5 | ⑦ Save unconfirmed, **Add origin** `[derived]` | The observation 添加 owed has already come back with consent — clean in ②, identified by a hint in ④, or waived in ⑤ — and the complete `SourceCreate` then returned no terminal observation classifier or never answered. Every classified pre-commit observation instead leaves through O1 to ③ / ④ / ⑤. The generated `client_nonce` and every request field remain held `[contract]` | F1 | `addKey.fail.save`; after `source_create_in_progress`, `addKey.fail.inProgress`; `addKey.retry` | Each user press of 重试 first reads `GET /api/models/sources` for the exact nonce. Match → claim the committed Source and enter 06 through the ordinary projection read. Miss → resend the same request/nonce. A response-backed observation enters O1; nonce conflicts follow the exact branches here. `source_create_in_progress` returns to this actionable state with `addKey.fail.inProgress`; there is no timer, automatic list read or automatic mutation retry. A later user press alone repeats the list-read + same-nonce resend algorithm. `source_nonce_conflict` rereads the list and claims the committed Source; a classified pre-commit observation → ③ / ④ / ⑤; a released slot starts one fresh create. Committed never replays the original response, and no branch matches by URL/name or creates a second Source (D-36). 取消 dismisses; after a committed boundary it ends only the caller's wait and the next Source/Agent read owns the result. There is no ⑦′ because Pull origin persists nothing |+| §1.5 | ① Default | Dialog opened; Base URL or API key empty | F5 | `addKey.title`, `addKey.subtitle`, `addKey.field.name`, `addKey.field.baseUrl`, `addKey.field.baseUrl.hint`, `addKey.field.apiKey`, `addKey.field.apiKey.reveal`, `addKey.field.apiKey.conceal`, `addKey.field.protocol`, `addKey.protocol.auto`, `addKey.protocol.idleHint`, `addKey.protocol.manual`, `addKey.detect`, `addKey.cancel` | Interface type is a dimmed result area, not a required input. The collapsed disclosure `addKey.protocol.manual` holds Auto plus the three concrete interfaces as a probe constraint, never proof. Auto carries no glyph; a concrete option carries its protocol-family glyph. The collapsed row names whatever 检测 will send: Auto plus `addKey.protocol.idleHint`, or the chosen interface with its glyph and no hint, since only Auto identifies automatically. Expanding the disclosure replaces that row with the selector, which states the same selection as its pressed segment. 检测 is disabled. 取消 → dismiss |+| §1.5 | ① Ready `[derived]` | Base URL and API key filled; no fresh observation | F5 | ①'s keys, undimmed | 检测 → ②. A concrete disclosure selection constrains that observe. 取消 → dismiss |+| §1.5 | ①″ Identified `[derived]` | ② came back `observed`, protocol non-null, `discovery: succeeded` | F5 — the request already succeeded | `addKey.pull.result`, `addKey.pull.empty`, `addKey.protocol.anthropicMessages`, `addKey.protocol.openaiResponses`, `addKey.protocol.openaiChatCompletions`, `addKey.confirm`, `addKey.protocol.manual`, and ①'s still-visible form | Mint strip: protocol-family glyph + proved protocol label + count (or `addKey.pull.empty`). No model names. Editing Base URL, API key, or the protocol selection → ① Ready, the report dropped — §1.5's retirement property, of which this is the plainest case. A rename is not one of those three inputs and keeps the report. 确认添加 → ②″ with the proved protocol and `accept_unavailable_inventory` false / omitted `[contract]`. 取消 → dismiss |+| §1.5 | ② Detecting | 检测 pressed, or 重试 pressed from ③ / ④ / ⑤ / ⑥ — `POST /api/models/sources/observe` `[contract]` | → ③ / ④ / ⑤ / ⑥ through O1 | `addKey.protocol.detecting` | O1 classifies the explicit observation. Ready → ①″, persisting nothing. 取消 aborts the in-flight probe and returns to ① Ready with the form intact. A second detect cannot start while one is in flight |+| §1.5 | ②″ Saving `[derived]` | 确认添加 pressed from ①″, or 仍要添加 pressed from ⑤ — `POST /api/models/sources` with one generated `client_nonce` `[contract]` | → ③ / ④ / ⑤ / ⑦ through O1 | `addKey.saving`, `addKey.saving.detail` | Cancel is blocked. An accepted create closes into 06. A classified create refusal returns to ③ / ④ / ⑤ exactly as the same observation would; only transport/no answer or a create response with no terminal observation classifier → ⑦ |+| §1.5 | ③ Failure | O1 received one of four closed unsuccessful outcomes from the explicit 检测 observation or Source create's repeated observation: `authentication_failed`, `unreachable`, `timeout` or `adapter_error` `[contract]` | F1 | `addKey.fail.subtitle`; exactly one outcome line: `authentication_failed` → `addKey.fail.auth` + `addKey.fail.auth.detail`, `unreachable` → `addKey.fail.address`, `timeout` → `addKey.fail.network`, `adapter_error` → `addKey.fail.unclassified`; `addKey.retry` | 重试 → ②, whichever producer returned the line — the retry re-runs the explicit observation before any create and does not depend on what the last one concluded. 取消 → dismiss |+| §1.5 | ④ Interface undetermined | O1 received `SourceObservation.outcome: ambiguous` from the explicit 检测 observation or Source create's repeated observation: reachable, protocol null, and authentication authenticated or unknown `[contract]` | F1 | ①'s still-visible form plus `addKey.undetermined.title`, `addKey.undetermined.detail`, the four-segment selector expanded in place (concrete options carry protocol-family glyphs), `addKey.field.protocol.hint`, and `addKey.retry` | Choose one concrete interface + 重试 → ② against exactly that protocol; identified with discovery succeeded → ①″, persisting nothing; identified with discovery failed → ⑤; still ambiguous → back to ④. Retry stays disabled while Auto remains selected. 取消 → dismiss |+| §1.5 | ⑤ Identified, inventory unavailable `[frame]` `d6bFlX` | O1 received `SourceObservation.outcome: observed`, protocol non-null, and `discovery: failed` from the explicit 检测 observation or Source create's repeated observation; the contract carries no request/status/reason evidence `[contract]` | F1 | `addKey.inventory.title`, `addKey.inventory.detail`, `addKey.retry`, `addKey.addAnyway` | 重试 → ② (the entire explicit observation). 仍要添加 is offered whenever this inventory cell carries a proved protocol — it is not origin-scoped. 仍要添加 → ②″ with **`accept_unavailable_inventory: true`** `[contract]`; false / omitted remains the clean path and may not commit this repeated discovery-failed observation. The server still repeats response-backed observation: only the same protocol-proved / discovery-failed cell may commit with `models: []`; every other classified result remains O1's own and the flag supplies no evidence. Only that committed success envelope closes into 06. This state renders no form, so it offers no edit to retire its waived cell; §1.5's retirement property binds it regardless and needs no exception. 取消 → dismiss |+| §1.5 | ⑥ Engine unavailable `[derived]` | The gateway is not running when 检测 is pressed | F1 | `addKey.fail.engineDown`, `addKey.retry` | F1 in full: the form keeps every value it holds and the primary becomes 重试. Pressing it **is** the recovery observation — nothing here watches for one — and re-attempts 检测 → ②, whose own outcomes then apply; the engine still down → back here; 取消 → dismiss |+| §1.5 | ⑦ Save unconfirmed `[derived]` | The observation 确认添加 / 仍要添加 owed has already come back with consent — clean in ①″, identified after a hint in ④, or waived in ⑤ — and the complete `SourceCreate` then returned no terminal observation classifier or never answered. Every classified pre-commit observation instead leaves through O1 to ③ / ④ / ⑤. The generated `client_nonce` and every request field remain held `[contract]` | F1 | `addKey.fail.save`; after `source_create_in_progress`, `addKey.fail.inProgress`; `addKey.retry` | Each user press of 重试 first reads `GET /api/models/sources` for the exact nonce. Match → claim the committed Source and enter 06 through the ordinary projection read. Miss → resend the same request/nonce. A response-backed observation enters O1; nonce conflicts follow the exact branches here. `source_create_in_progress` returns to this actionable state with `addKey.fail.inProgress`; there is no timer, automatic list read or automatic mutation retry. A later user press alone repeats the list-read + same-nonce resend algorithm. `source_nonce_conflict` rereads the list and claims the committed Source; a classified pre-commit observation → ③ / ④ / ⑤; a released slot starts one fresh create. Committed never replays the original response, and no branch matches by URL/name or creates a second Source (D-36). 重试 resends the held request rather than the form, so F1 here keeps the form's values while locking every field: the request may not outlive the fields it was built from, and this state resolves that by making them uneditable rather than by retiring on an edit that cannot happen. §1.5's retirement property still binds it. 取消 dismisses; after a committed boundary it ends only the caller's wait and the next Source/Agent read owns the result || §1.6 | Ready | Source detail loaded and the table holds at least one model — discovered, added by hand, or both. When `last_discovered_at` is null the inventory has no age, `{{time}}` is absent by §0.9's rule, and the status line drops that segment `[contract]` | F5 | `sourceDetail.status.inUse`, `sourceDetail.status.listUpdated`, `sourceDetail.summary` | `iGcAi` → 01; a rendered 重新拉取 → Refetching; 添加模型 → Manual draft; a tier area → Tiers editing; a row's overflow → Removing a manual entry. The §1.6 action-capability row decides whether 重新拉取 exists || §1.6 | Retired discovered row | A model row carries `origin: discovered` and `retired: true` `[contract]` | F5 — a durable projection, not a request | `sourceDetail.entry.retired` | Keep the ordinary row chrome, switch its ink to muted and append the existing tag component with 已退役 / Retired. The row stays readable and never supplies. It renders no discovered-row delete action; refetch preserves the tombstone and cannot revive it. No new component or reactivation exit exists || §1.6 | Empty (no models) | The table is empty **and** a discovery has completed — `last_discovered_at` is non-null `[contract]` | F5 | `sourceDetail.empty` | Manual add, or a successful refetch |@@ -3309,29 +3307,72 @@ endpoint — a relay, an aggregator, something I host — with the smallest numbthings I have to know?* Answer: a URL and a key. **Everything else the productworks out for itself, and says so when it cannot.**-Five states are drawn: the left column is the happy path (① default → ② adding →-success destination), the right column is the three failures (③ unreachable /-unauthenticated / wrong address, ④ connected but the interface is undetermined, ⑤-identified but the inventory did not come back). The right column is ordered by how far-the attempt got before it stopped, which is also the order in which the product stops-refusing: ③ and ④ cannot save at all, ⑤ can.+Five states are drawn: the left column is the happy path (① default / ready → ②+detecting → ①″ identified → ②″ saving → success destination), the right column is+the three failures (③ unreachable / unauthenticated / wrong address, ④ connected but+the interface is undetermined, ⑤ identified but the inventory did not come back). The+right column is ordered by how far the attempt got before it stopped, which is also the+order in which the product stops refusing: ③ and ④ cannot save at all, ⑤ can.++**2026-09-03 owner ruling — detect-then-confirm** `[derived]`. This dated block+supersedes the origin-axis / 拉取型号 / one-shot 添加 material later in this section.+The dialog is now a single add flow:++- Field order is 名称(可选) → Base URL → API Key → 接口类型. Interface type is a+ **detection-result area**, not a required input. Idle is a dimmed row naming+ whatever 检测 is about to send — 自动探测 with `addKey.protocol.idleHint`, or the+ chosen interface with its glyph and no hint, because only Auto identifies+ automatically; Ready is the same row undimmed; Detecting is a spinner with+ `addKey.protocol.detecting`; Identified is a mint strip naming the proved protocol+ (protocol-family glyph before the label) and the model count — never the model+ names.+- Primary is two-step: **检测 / Detect** runs the non-persisting observe; **确认添加 /+ Confirm & add** persists with the proved protocol. There is no optional 拉取型号+ button, so the pull/add origin axis has no remaining work and its primed twins are+ retired. ⑤'s 仍要添加 stays, gated on an inventory outcome with a proved protocol+ rather than on origin.+- Manual override is a collapsed disclosure `addKey.protocol.manual`. A concrete+ selection remains a probe constraint, never proof. In ④ the selector is expanded+ in place; retry stays disabled while Auto is selected. The collapsed row and the+ expanded selector are one selection rendered two ways, so exactly one of them is on+ screen: expanding replaces the row, and the pressed segment is then the statement.+- Cancel while detecting aborts the probe and returns to the form with values intact.+ Cancel during persist stays blocked.+- Every surface that names a **concrete** interface type carries that protocol+ family's brand glyph (Anthropic mark for `anthropic`; OpenAI mark for both+ `openai_responses` and `openai_chat`). Auto detect has no glyph. Glyphs live in+ `protocolGlyph.tsx` and do not touch `vendorMeta.ts`.+- The persisting invariant is unchanged: every persisting exit requires a protocol+ proved by an observed response. ③/④ never persist.+- Evidence retires with the inputs it was proved against. Editing Base URL, the API+ key or the protocol selection returns **any** state whose primary would persist+ without observing again to ① Ready — ①″'s report, ⑤'s waived inventory, and the+ protocol a refused or unanswered create still holds. That is the property, stated+ over how a state exits rather than over the list of states that exist today. A+ state whose primary re-observes (③, ④, ⑤'s 重试, ⑥) keeps its line instead: that+ retry reads the fields as they now stand. The display name is in no observation, so+ ①″ survives a rename; it is in the create request, so a server-named refusal of+ that request does not survive one. Two of the covered states offer no edit to fire+ the rule — ⑤ renders no form and ⑦ locks every field — and that is why the rule is+ written over exits: whether a state happens to expose an editable field today+ decides only whether it fires, never whether it applies.**Element inventory**| Element | Displays | Data source | Interactive | On activate || --- | --- | --- | --- | --- |-| head sub-line | that Add performs one real connection | static | no | — |+| head sub-line | that Add detects the connection and interface first, then confirms | static | no | — || `f7Ao1U` 名称(可选) | free text | user | yes | — |-| Interface type | Auto detect plus Anthropic Messages, OpenAI Responses and OpenAI Chat Completions; Auto detect is selected by default | user | yes | Select the exact probe constraint used by both actions || `cXsiv` Base URL + hint | free text; the hint names an API root, and says a bare host uses the standard `/v1` path | user | yes | — || `mZBBw` API Key | masked value, reveal icon | user | yes | Toggle reveal |-| `zVU7c` / `V6CtoF` 拉取型号 + hint | an optional early pull, which Add performs anyway | — | yes | Enter ②′; render its result in place |-| `S0pOY2` 添加 | — | form validity | yes | Run the add action (connect + identify + fetch) |-| `OT0Xf` state ② | spinner, 连接中…, what is happening, 通常 1–3 秒 — **and state ②′ unchanged** | in-flight | 取消 only | Abort; from ②′, back to ① with the form intact |+| Interface type | result area last: idle/ready row naming the interface 检测 will send, detecting spinner, identified mint strip, or ④'s gold strip; protocol-family glyphs on every concrete protocol name | observation result; disclosure selection is a probe constraint | disclosure yes; ④ selector yes | Open `addKey.protocol.manual`, which replaces the row with the selector; a concrete choice constrains the next 检测 / ④ 重试 |+| `S0pOY2` 检测 / 确认添加 | 检测 while there is no fresh result; 确认添加 after ①″ | form validity | yes | 检测 → ②; 确认添加 → ②″ with the proved protocol |+| `OT0Xf` state ② | spinner, 识别接口中… | in-flight observe | 取消 only | Abort; return to ① Ready with the form intact |+| persist strip state ②″ | spinner, 保存中…, 正在保存这个供应商 | in-flight persist | none — cancel blocked | — || `C72yS` state ③ strip | classified outcome copy | observation result | no | — |-| `EJrDH` ③ foot | 取消 / 重试 | — | yes | Dismiss / re-run whatever failed |+| `EJrDH` ③ foot | 取消 / 重试 | — | yes | Dismiss / re-run the explicit observation || `vKiIo` state ④ strip | connected, interface undetermined | observation result | no | — |-| `WZyA8` selector | the same four interface choices from the form | selection | yes, Auto detect remains selected until changed | Select one concrete interface; enables 重试 |+| `WZyA8` selector | the same four interface choices, expanded in place, glyphs on concrete options | selection | yes, Auto detect remains selected until changed | Select one concrete interface; enables 重试 || `Nak7y` ④ foot | 取消 / 重试 (dimmed until a concrete interface is picked) | selection | yes | — || `d6bFlX` state ⑤ strip | the interface *was* identified, and the model list did not come back | observation result | no | — || `x0Gzg` ⑤ foot | 取消 / 仍要添加 / 重试 — **three** buttons, the only foot in the product with three | — | yes | Dismiss / save the source without an inventory / rerun the entire observation |@@ -3340,8 +3381,8 @@ refusing: ③ and ④ cannot save at all, ⑤ can.**Metrics** `[frame]`: dialog 560 wide, height auto in all five states — the framesets no fixed height, so a build that pins one is deviating, not matching. Head`padding [16,20]` `gap 4`; body `padding 20` `gap 14`; field `gap 6`; input 520×36-`radius 8` fill `#FFFFFF08`; field hint 10.5 JetBrains Mono `#9BA3B8B3`. 拉取型号-`padding [8,14]` `gap 6`, neutral. Result strip 520 wide `padding [11,13]` `gap 10`+`radius 8` fill `#FFFFFF08`; field hint 10.5 JetBrains Mono `#9BA3B8B3`. Protocol-family+glyphs are ~14px `currentColor`. Result strip 520 wide `padding [11,13]` `gap 10``radius 9`: red `#FF6B6B14`/`#FF6B6B40` for ③, gold `#FFC85714`/`#FFC85759` for ④**and for ⑤** (`AFl3g`), mint `#5BFFA014`/`#5BFFA040` for the success note. Theform-level selector uses `padding 3` `gap 3` on `#FFFFFF0A`/`$--border`; unselected@@ -3372,129 +3413,72 @@ outcome, reachability, authentication, protocol, discovery and models facts. Itreconstruct the removed request/status/reason evidence slots from adapter logs or HTTPdetails.-**添加 observes before it persists, and that ordering is what makes ③, ④ and ⑤ offers+**Detect observes before Confirm persists, and that ordering is what makes ③, ④ and ⑤ offersrather than notifications** `[contract]`. Each of them asks the user for adecision — retry, pick a concrete protocol, add anyway — and a decision offered after the row isalready stored is not a decision; ⑤ is the clearest case, because 仍要添加 is only an-offer if nothing was added when the inventory came back unusable. So 添加 runs the same-non-persisting observation 拉取型号 runs, and `POST /api/models/sources` goes out on one-of three paths, all of them past a consent: a clean observation, ④'s retry once a concrete selection-identified the protocol, and ⑤'s 仍要添加. An earlier version had the creation call go-first and the diagnosis come back from it, which needed the persisting route to answer-non-terminally — a response no contract gives it — and left every 重试 in this dialog-re-adding a source that already existed. The seam this draws is the one G-19 registers:-before the POST the transient credential is revoked on every settlement AC-26 names,-and after it the source exists and its questions belong to 06.--**Origin is an axis, not a state, and it is the whole reason this table has primed-twins** `[derived]`. 添加 and 拉取型号 run the *same* probe, so every outcome the probe-can produce is reachable from either button, and the diagnosis it renders — the-classification, its wording, its layout — is identical across a twin. What origin-changes is what the outcome is allowed to *do*, and that is the same three things every-time:--- **重试 repeats the operation that failed, not a different one.** From a pull, every- retry is another pull.-- **取消 returns to where the operation started, and this is the only place that says- so.** A pull is an optional operation *inside* the dialog, so its 取消 returns to ① with- the form's values intact; an add is what the dialog is for, so its 取消 dismisses. This- holds for the in-flight states exactly as it does for the outcome states: ② dismisses,- ②′ returns to ①. A cancelled in-flight add has its transient credential revoked- server-side **for as long as the operation is still the non-persisting submission**- (`[contract]` AC-26, which requires that revocation on every way the submission can- settle, cancellation included); what a cancel yields once the add has crossed into- persistence has one contracted boundary: before durable commit, cleanup completes- before cancellation settles; after commit, cancellation ends only this caller's wait- and the next Source/Agent read claims the committed result. **A cancelled pull revokes too**- `[contract]` AC-26, which names unsaved discovery separately from the connectivity test- and gives it its own independently provisioned transient ref, the same revocation on- success, failure, adapter error, timeout and cancellation, and the same durable- pending-revocation record when the revoke itself fails. The pull is the simpler half of- that rule rather than an exception to it: it can never persist (below), so it has no- commit boundary, so the pull's cleanup covers every way it can settle.-- **A pull-origin state can never persist.** Where a state's Add-origin form offers a- persisting exit, the pull-origin form does not offer it at all: ④′ reports its result- inline instead of saving, and ⑤′ drops 仍要添加 and keeps the ordinary two-button foot.--Stating it as an axis rather than as a list of special cases is the point, and it is why-the table's Exit column carries no 取消 clause per row: a fact restated once per row is a-fact with eight owners, and the eighth is the one that drifts — which is exactly what had-happened to ②, whose row said 取消 returned to ① while the axis said an add dismisses. An-earlier version primed ③ alone, which left ④ and ⑤ silently shared between the two-origins —-and both of their success paths persist a source and close the dialog. A user who-pressed the optional button, picked a concrete interface, and pressed 重试 would then have created a-source they never asked for, or lost the form to 取消; the same hole existed twice-because the fix had been written as a row rather than as a rule. 拉取型号 is labelled-可选 (D-4), and the promise that word makes is *nothing you do here commits anything* —-which is a property of the whole pull branch, not of one failure.--**②′ is the twin the earlier table was missing, and it needs no new pixels and no new-copy** `[derived]`. The probe a pull runs *is* the probe Add runs, so the period while it-is pending is the same period, and it renders the same `OT0Xf` body: spinner, 连接中…,-连上 + 认出接口 + 首次拉取型号列表 · 通常 1–3 秒, 取消 only. Every word of that sentence-is true of a pull, which is why the twin reuses `addKey.adding` and `addKey.adding.detail`-rather than earning keys of its own. The axis applies here as everywhere — 取消 lands on-① instead of dismissing, **and it revokes on the way out** `[contract]` AC-26. Nothing is-persisted, and that is a fact about the *source*, not about the credential: the pull ran-against an independently provisioned transient ref, so a cancel here is one of the five-ways AC-26 names and carries the same revocation and the same durable pending-revocation-record when the revoke itself fails. 可选 promises that nothing you do here commits-anything; it does not promise that nothing was provisioned. The third property has-nothing to bind to: an in-flight state offers no 重试.--Two consequences follow from ②′ occupying the body rather than sitting inside the form.-**A second pull cannot be started while one is in flight**, because 拉取型号 is not on-screen to press — the mechanism is absence, not a disabled button, which is why an-enumeration of this dialog's interactive elements does not and should not list it. And **取消 during ②′ is a real abort**, not-a dismissal: it stops the in-flight probe and returns the user to a form still holding-everything they typed. A build that leaves ① fully interactive during a pull has to-invent an answer for what a second press means and for which of two responses wins —-questions this dialog never has to ask.--*Postmortem.* The origin axis was stated for outcomes and quietly not for the in-flight-period, so 拉取型号 appeared to move from ① straight to a result. The rule that catches-this class: **an axis has to be applied to every state on the other side of it, including-the ones that are pure duration.** A state that only exists while something is pending is-the easiest one to forget, because nobody screenshots it and no static frame draws it-twice.--**The distinction has no visual carrier**, and that is what makes it worth stating so-precisely: the only way to get it right is to keep the origin in state, and the only way-to get it wrong is to reconstruct it from what is on screen. The property is not about-one pair: **no Pull-origin state persists anything**, and that quantifies over every-primed twin, ②′ included.--**A pull that succeeds lands in a state, not back in ①** `[derived]`. ②′ named ③′ / ④′ /-⑤′ for its three failures and, for the one outcome the user pressed 拉取型号 to get, said-only 「the inline model count in ①」 — a result reported by the state the register-describes as 「Dialog opened」. ①′ is that state written down: the form exactly as ①-renders it, plus `addKey.pull.result` reporting what came back, or `addKey.pull.empty`-when the source answered and listed nothing — the reachable zero this key has, and the-reason it takes a string rather than 「拉到 0 个型号」. It is also where ④′ lands when- the manual selection identifies the interface, and where ⑤′'s 重试 lands when the repeated observation-comes back usable: the same result by a longer road, which is the point of naming it once. Three-properties hold here because it is a Pull-origin state and for no other reason. Nothing-was persisted, so 添加 from here still runs its own observation and reuses none of-this. Editing Base URL or API Key drops the report, because a count is a fact about the-address it was fetched from. And 取消 dismisses with nothing to abort — the in-flight-abort belongs to ②′, which is where the request still is. A build without this row has to-decide all three from what is on screen, which is the reconstruction the paragraph above-names as the only way to get the origin wrong.+offer if nothing was added when the inventory came back unusable. So 检测 is the mandatory+non-persisting observation, and `POST /api/models/sources` goes out on one of three paths,+all of them past a consent: 确认添加 from ①″, ④'s retry once a concrete selection identified+the protocol and the user then confirmed, and ⑤'s 仍要添加. An earlier version had the+creation call go first and the diagnosis come back from it, which needed the persisting+route to answer non-terminally — a response no contract gives it — and left every 重试 in+this dialog re-adding a source that already existed. The seam this draws is the one G-19+registers: before the POST the transient credential is revoked on every settlement AC-26+names, and after it the source exists and its questions belong to 06.++**The origin axis is retired** `[derived]`. Until 2026-09-03 this dialog had two producers+of the same probe — 添加 and optional 拉取型号 — and every outcome was primed as an+add/pull twin so that a pull could never persist. Detect is now mandatory and Confirm is+the only persisting primary, so there is no optional pull branch and no remaining work for+those twins. ①′ / ②′ / ③′ / ④′ / ⑤′ / ⑥′ are tombstones. ⑤'s 仍要添加 is gated on a proved+protocol with unavailable inventory, not on origin.++Cancel is no longer an origin-dependent fork. ②'s 取消 aborts the in-flight observe and+returns to ① Ready with the form intact — a real abort, not a dismissal — and a second+detect cannot start while one is in flight. ②″ blocks cancel for the G-19 persist+boundary. Outcome-state 取消 dismisses. A cancelled in-flight observe revokes the+independently provisioned transient ref on every way AC-26 names (success, failure,+adapter error, timeout, cancellation), including the durable pending-revocation record+when the revoke itself fails. What a cancel yields once Confirm has crossed into+persistence is the contracted boundary: before durable commit, cleanup completes before+cancellation would have settled, except this dialog does not offer that cancel; after+commit, cancellation ends only this caller's wait and the next Source/Agent read claims+the committed result.++**② occupies the protocol result area rather than replacing the form** `[derived]`. The+period while Detect is pending renders `addKey.protocol.detecting` with a spinner in that+area, and the primary is the same detecting label, disabled. Every word of the older+`addKey.adding` / `addKey.adding.detail` pair described a one-shot add that observed and+persisted in one press; those keys remain in the locale files and are not this state's+copy.++**A successful Detect lands in ①″, not back in ① and not in a persist** `[derived]`. ①″ is+the form exactly as ① Ready renders it, plus the mint identified strip: protocol-family+glyph, proved protocol label, and `addKey.pull.result` or `addKey.pull.empty`. It is also+where ④ lands when the manual selection identifies the interface with discovery succeeded,+and where ⑤'s 重试 lands when the repeated observation comes back usable. Nothing was+persisted, so 确认添加 from here still runs Source-create's repeated observation and reuses+none of the client report as proof. Editing Base URL, API Key, or the protocol selection+drops the report, because a count is a fact about the address it was fetched from. And 取消+dismisses with nothing to abort — the in-flight abort belongs to ②, which is where the+request still is.**The form-level protocol selector is a probe constraint, not response proof**`[frame]` `[contract]`. The 2026-08-26 owner ruling supersedes the former-ambiguity-only probe-order hint: the selector is visible before the first request, with-Auto detect selected by default. Auto detect probes the supported interfaces in the-adapter's authoritative order. A concrete choice probes exactly that interface for both-拉取型号 and 添加. In either branch, persistence still requires a matching-protocol-shaped upstream response; the user choice cannot manufacture proof.--State ④ keeps the same selector visible and requires a concrete choice before 重试. The-primary is still a retry, not a save, and the strip always describes the latest attempt.-The stored Source records the proved protocol but no manual/automatic provenance marker:-the distinction matters during preflight, not during later invocation. Saved protocol-changes still require a new Source.+ambiguity-only probe-order hint; the 2026-09-03 ruling then moved the selector behind a+collapsed disclosure and made the visible row a detection-result area. Auto detect remains+the default. Auto detect probes the supported interfaces in the adapter's authoritative+order. A concrete choice probes exactly that interface on the next 检测 or ④ 重试.+Persistence still requires a matching protocol-shaped upstream response; the user choice+cannot manufacture proof.++State ④ keeps the same selector visible — expanded in place, not behind the disclosure —+and requires a concrete choice before 重试. The primary is still a retry, not a save, and+the strip always describes the latest attempt. A successful retry with discovery succeeded+lands ①″ and still persists nothing. The stored Source records the proved protocol but no+manual/automatic provenance marker: the distinction matters during preflight, not during+later invocation. Saved protocol changes still require a new Source.**State ⑤ is the one place in the product that saves something it could not fullyverify, and the rule that makes it safe is a property, not a permission** `[frame]`@@ -3571,7 +3555,7 @@ is revealed; the button carries the verb.| Key | 中文 | English || --- | --- | --- || `title` | 添加 API Key | Add API key |-| `subtitle` | 「添加」时自动连一次:认出接口 + 拉取型号列表 | Add connects once: it identifies the interface and fetches the model list |+| `subtitle` | 先检测连接与接口,确认后添加 | Detect the connection and interface first, then confirm to add || `field.name` | 名称(可选) | Name (optional) || `field.protocol` | 接口类型 | Interface type || `field.protocol.hint` | 不确定时用自动探测;已知类型时只验证所选接口 | Use Auto detect when unsure; choose a type to validate only that interface |@@ -3580,14 +3564,13 @@ is revealed; the button carries the verb.| `field.apiKey` | API Key | API key || `field.apiKey.reveal` | 显示 API Key | Show API key || `field.apiKey.conceal` | 隐藏 API Key | Hide API key |-| `test` | 拉取型号 | Fetch models |-| `test.hint` | 可选 ·「添加」时会自动拉一次 | Optional · Add fetches once anyway |-| `pull.result_one` | 拉到 {{count}} 个型号 | Fetched {{count}} model |-| `pull.result_other` | 拉到 {{count}} 个型号 | Fetched {{count}} models |-| `pull.empty` | 连上了,但这个来源没有可用型号 | Connected, but this source lists no models |-| `submit` | 添加 | Add |-| `adding` | 连接中… | Connecting… |-| `adding.detail` | 连上 + 验证接口 + 首次拉取型号列表 · 通常 1–3 秒 | Connect, validate the interface, fetch the model list · usually 1–3s |+| `pull.result_one` | 拉到 {{count}} 个模型 | Fetched {{count}} model |+| `pull.result_other` | 拉到 {{count}} 个模型 | Fetched {{count}} models |+| `pull.empty` | 已经连接,但这个供应商没有可用模型 | Connected, but this source lists no models |+| `detect` | 检测 | Detect |+| `confirm` | 确认添加 | Confirm & add |+| `saving` | 保存中… | Saving… |+| `saving.detail` | 正在保存这个供应商 | Saving this source || `fail.subtitle` | 认出接口是「添加」的前置条件 · 先按下面这条修,再重试 | Identifying the interface is a precondition of Add · fix what the line below names, then retry || `fail.auth` | 上游拒绝了这个凭据 | The upstream rejected this credential || `fail.auth.detail` | 检查 API Key、接口类型和 Base URL 的 API 根路径 | Check the API key, interface type, and the Base URL's API root path |@@ -3604,6 +3587,9 @@ is revealed; the button carries the verb.| `protocol.anthropicMessages` | Anthropic Messages | Anthropic Messages || `protocol.openaiResponses` | OpenAI Responses | OpenAI Responses || `protocol.openaiChatCompletions` | OpenAI Chat Completions | OpenAI Chat Completions |+| `protocol.idleHint` | 填好 Base URL 和 API Key 后自动识别 | Identified automatically once Base URL and API key are filled |+| `protocol.detecting` | 识别接口中… | Identifying the interface… |+| `protocol.manual` | 手动指定接口类型 | Manually specify interface type || `inventory.title` | 接口已经认出来了 —— 但这次没拿到它的型号清单 | The interface is identified — but its model list did not come back this time || `inventory.detail` | 接口已经确认;这次型号清单读取失败 | The interface is confirmed; the model list could not be read this time || `addAnyway` | 仍要添加 | Add anyway |@@ -3674,7 +3660,7 @@ normalized to `https://` before the probe and the normalized form is what thefield shows afterwards (so the user can see what was actually tried).**An omitted 名称 is filled at submit time, not at render time** `[derived]`. If the-field is blank when 添加 is pressed, the client sets `display_name` to the URL host+field is blank when 确认添加 is pressed, the client sets `display_name` to the URL hostbefore the request goes out, so the persisted value *is* the host. The rejectedalternative was a render-time fallback, and it is worth naming why it is wrong:`display_name` is a required non-null string `[contract]` FC-03 and creation fills andiff --git a/ui/e2e/b-add-api-key.spec.ts b/ui/e2e/b-add-api-key.spec.tsindex 4ebc8eb82..a44d4b572 100644--- a/ui/e2e/b-add-api-key.spec.ts+++ b/ui/e2e/b-add-api-key.spec.ts@@ -101,7 +101,8 @@ test.describe('B · add an API-key source', () => {// No protocol is chosen: "Auto detect" is the default, and the response// shape is the only evidence the product is allowed to use.await fillApiKeyForm(hub.addKeyDialog, { name, baseUrl: mockBaseUrl(), apiKey: 'e2e-add' });- await hub.addKeyDialog.getByRole('button', { name: copy('addKey.submit'), exact: true }).click();+ await hub.addKeyDialog.getByRole('button', { name: copy('addKey.detect'), exact: true }).click();+ await hub.addKeyDialog.getByRole('button', { name: copy('addKey.confirm'), exact: true }).click({ timeout: 30_000 });// Success is defined by where the user lands, not by a toast: the dialog// closes and the new source's detail panel opens.@@ -128,7 +129,7 @@ test.describe('B · add an API-key source', () => {baseUrl: mockBaseUrl(),apiKey: 'e2e-bad-key',});- await hub.addKeyDialog.getByRole('button', { name: copy('addKey.submit'), exact: true }).click();+ await hub.addKeyDialog.getByRole('button', { name: copy('addKey.detect'), exact: true }).click();// The three lines are one message: what went wrong, where to look, and that// Add cannot proceed until it is fixed. A test that asserted only the first@@ -154,7 +155,7 @@ test.describe('B · add an API-key source', () => {apiKey: 'e2e-mismatch',protocol: copy('addKey.protocol.anthropicMessages'),});- await hub.addKeyDialog.getByRole('button', { name: copy('addKey.submit'), exact: true }).click();+ await hub.addKeyDialog.getByRole('button', { name: copy('addKey.detect'), exact: true }).click();// "Connected and authenticated, but we cannot tell which interface" — the// distinction from a credential failure is the whole point of the copy.@@ -167,7 +168,7 @@ test.describe('B · add an API-key source', () => {).toBeEnabled();});- test('B3 · Fetch models reports the count, and only ids survive the save', async ({ hub, mock, api }) => {+ test('B3 · Detect reports the count, and only ids survive the save', async ({ hub, mock, api }) => {// The mock returns rich rows on purpose: `display_name`, `context_length`// and `pricing` all come back and all are dropped. §3 marks B3// `assert-current` — this documents the drop, it does not bless it.@@ -184,15 +185,15 @@ test.describe('B · add an API-key source', () => {await hub.addApiKeyButton.click();await fillApiKeyForm(hub.addKeyDialog, { name, baseUrl: mockBaseUrl(), apiKey: 'e2e-pull' });- // "Fetch models" is the optional pre-flight: it reports, it does not save.- await hub.addKeyDialog.getByRole('button', { name: copy('addKey.test'), exact: true }).click();+ // Detect is the mandatory pre-flight: it reports, it does not save.+ await hub.addKeyDialog.getByRole('button', { name: copy('addKey.detect'), exact: true }).click();await expect(hub.addKeyDialog).toContainText(copy('addKey.pull.result', { count: inventory.length }),{ timeout: 30_000 },);expect(await api.sources()).not.toContainEqual(expect.objectContaining({ display_name: name }));- await hub.addKeyDialog.getByRole('button', { name: copy('addKey.submit'), exact: true }).click();+ await hub.addKeyDialog.getByRole('button', { name: copy('addKey.confirm'), exact: true }).click({ timeout: 30_000 });await expect(hub.sourceDetailDialog).toBeVisible({ timeout: 30_000 });const created = (await api.sources()).find((source) => source.display_name === name);@@ -221,7 +222,7 @@ test.describe('B · add an API-key source', () => {await hub.goto();await hub.addApiKeyButton.click();await fillApiKeyForm(hub.addKeyDialog, { name, baseUrl: mockBaseUrl(), apiKey: 'e2e-empty' });- await hub.addKeyDialog.getByRole('button', { name: copy('addKey.submit'), exact: true }).click();+ await hub.addKeyDialog.getByRole('button', { name: copy('addKey.detect'), exact: true }).click();await expect(hub.addKeyDialog).toContainText(copy('addKey.inventory.title'), { timeout: 30_000 });const addAnyway = hub.addKeyDialog.getByRole('button', {diff --git a/ui/e2e/g-guards-copy.spec.ts b/ui/e2e/g-guards-copy.spec.tsindex be3bafc60..853bb1e6e 100644--- a/ui/e2e/g-guards-copy.spec.ts+++ b/ui/e2e/g-guards-copy.spec.ts@@ -135,7 +135,7 @@ test.describe('G · supply guards and failure copy', () => {baseUrl: mockBaseUrl(),apiKey: 'e2e-copy-probe',});- await hub.addKeyDialog.getByRole('button', { name: copy('addKey.submit'), exact: true }).click();+ await hub.addKeyDialog.getByRole('button', { name: copy('addKey.detect'), exact: true }).click();await expect(hub.addKeyDialog).toContainText(/modelHub\.errors\.|settings\.models\./);// The defect: the raw key is what reaches the user.await expectVisibleWithout(hub.addKeyDialog, /modelHub\.errors\./);diff --git a/ui/e2e/support/hub.ts b/ui/e2e/support/hub.tsindex 16ece57d0..478063e68 100644--- a/ui/e2e/support/hub.ts+++ b/ui/e2e/support/hub.ts@@ -307,6 +307,7 @@ export const fillApiKeyForm = async (await dialog.getByLabel(hub('addKey.field.name'), { exact: true }).fill(values.name);}if (values.protocol) {+ await dialog.getByRole('button', { name: hub('addKey.protocol.manual'), exact: true }).click();await dialog.getByRole('button', { name: values.protocol, exact: true }).click();}await dialog.getByLabel(hub('addKey.field.baseUrl'), { exact: true }).fill(values.baseUrl);diff --git a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx b/ui/src/components/settings/models/AddApiKeyDialog.test.tsxindex 725078734..5f9c14f0e 100644--- a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx+++ b/ui/src/components/settings/models/AddApiKeyDialog.test.tsx@@ -2,7 +2,7 @@import { cleanup, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { I18nextProvider } from 'react-i18next';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import i18n from '@/i18n';import { AddApiKeyDialog } from './AddApiKeyDialog';@@ -133,6 +133,10 @@ const renderReplacement = (return { onClose, settlement };};+const DETECT = /^Detect$|^检测$/;+const CONFIRM = /Confirm & add|确认添加/;+const RETRY = /^Retry$|^重试$/i;+const fillCredentials = async () => {const user = userEvent.setup();await user.type(screen.getByRole('textbox', { name: /^Base URL$/i }), 'https://relay.example/v1');@@ -140,6 +144,22 @@ const fillCredentials = async () => {return user;};+const openManualProtocol = async (user: ReturnType<typeof userEvent.setup>) => {+ await user.click(screen.getByRole('button', { name: /Manually specify interface type|手动指定接口类型/i }));+};++const clickDetect = async (user: ReturnType<typeof userEvent.setup>) => {+ await user.click(screen.getByRole('button', { name: DETECT }));+};++const clickConfirm = async (user: ReturnType<typeof userEvent.setup>) => {+ await user.click(await screen.findByRole('button', { name: CONFIRM }));+};++beforeEach(async () => {+ await i18n.changeLanguage('en');+});+afterEach(() => {cleanup();vi.restoreAllMocks();@@ -147,18 +167,44 @@ afterEach(() => {});describe('AddApiKeyDialog', () => {- it('pulls models without persisting and drops the report when credentials change', async () => {+ it('detects without persisting, names the protocol, and drops the report when credentials change', async () => {vi.spyOn(modelsApi, 'observeApiKeySource').mockResolvedValueOnce(observed());const create = vi.spyOn(modelsApi, 'createApiKeySource');renderDialog();const user = await fillCredentials();- await user.click(screen.getByRole('button', { name: /Fetch models|拉取模型/i }));- expect(await screen.findByText(/Fetched 2 models|拉到 2 个模型/i)).toBeTruthy();+ await clickDetect(user);+ expect(await screen.findByText(/OpenAI Chat Completions/)).toBeTruthy();+ expect(screen.getByText(/Fetched 2 models|拉到 2 个模型/i)).toBeTruthy();+ expect(screen.queryByText('model-a')).toBeNull();+ expect(screen.getByRole('button', { name: CONFIRM })).toBeTruthy();expect(create).not.toHaveBeenCalled();await user.type(screen.getByRole('textbox', { name: /^Base URL$/i }), '/changed');expect(screen.queryByText(/Fetched 2 models|拉到 2 个模型/i)).toBeNull();+ expect(screen.getByRole('button', { name: DETECT })).toBeTruthy();+ });++ it('puts protocol-family glyphs on concrete interface names and never on Auto detect', async () => {+ vi.spyOn(modelsApi, 'observeApiKeySource').mockResolvedValueOnce(+ observed({ protocol: 'anthropic' }),+ );+ renderDialog();+ expect(screen.getByText(/Identified automatically once Base URL and API key are filled|填好 Base URL 和 API Key 后自动识别/)).toBeTruthy();+ const user = await fillCredentials();+ await openManualProtocol(user);++ expect(screen.getByRole('button', { name: /Auto detect|自动探测/i }).querySelector('svg')).toBeNull();+ expect(screen.getByRole('button', { name: 'Anthropic Messages' }).querySelector('svg')).toBeTruthy();+ expect(screen.getByRole('button', { name: 'OpenAI Responses' }).querySelector('svg')).toBeTruthy();+ expect(screen.getByRole('button', { name: 'OpenAI Chat Completions' }).querySelector('svg')).toBeTruthy();++ await clickDetect(user);+ await waitFor(() => {+ const identified = document.querySelector('.model-hub-add-key-strip--success');+ expect(identified?.textContent).toMatch(/Anthropic Messages/);+ expect(identified?.querySelector('.model-hub-add-key-protocol-glyph')).toBeTruthy();+ });});it('sends one manually selected interface on the first observation and create', async () => {@@ -172,16 +218,18 @@ describe('AddApiKeyDialog', () => {renderDialog();const user = await fillCredentials();+ await openManualProtocol(user);expect(screen.getByRole('button', { name: /Auto detect|自动探测/i }).getAttribute('aria-pressed')).toBe('true');await user.click(screen.getByRole('button', { name: 'OpenAI Responses' }));- await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await clickDetect(user);+ await clickConfirm(user);await waitFor(() => expect(create).toHaveBeenCalledOnce());expect(observe.mock.calls[0][0].protocol).toBe('openai_responses');expect(create.mock.calls[0][0].protocol).toBe('openai_responses');});- it('turns an ambiguous auto-detection into one exact manual retry', async () => {+ it('turns an ambiguous auto-detection into one exact manual retry, then confirms', async () => {const observe = vi.spyOn(modelsApi, 'observeApiKeySource').mockResolvedValueOnce(observed({outcome: 'ambiguous',@@ -199,12 +247,16 @@ describe('AddApiKeyDialog', () => {const { onAdded } = renderDialog();const user = await fillCredentials();- await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await clickDetect(user);const retry = await screen.findByRole('button', { name: /^Retry$|^重试$/i });expect((retry as HTMLButtonElement).disabled).toBe(true);await user.click(screen.getByRole('button', { name: 'OpenAI Responses' }));await user.click(retry);+ expect(await screen.findByRole('button', { name: CONFIRM })).toBeTruthy();+ expect(create).not.toHaveBeenCalled();+ await clickConfirm(user);+await waitFor(() => expect(create).toHaveBeenCalledOnce());const secondObservation = observe.mock.calls[1][0];expect(secondObservation.protocol).toBe('openai_responses');@@ -223,7 +275,7 @@ describe('AddApiKeyDialog', () => {renderDialog();const user = await fillCredentials();- await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await clickDetect(user);await screen.findByRole('button', { name: /Add anyway|仍要添加/i });await user.click(screen.getByRole('button', { name: /^Retry$|^重试$/i }));await waitFor(() => expect(observe).toHaveBeenCalledTimes(2));@@ -251,7 +303,7 @@ describe('AddApiKeyDialog', () => {renderDialog();const user = await fillCredentials();- await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await clickDetect(user);await screen.findByRole('button', { name: /Add anyway|仍要添加/i });await user.click(screen.getByRole('button', { name: /^Retry$|^重试$/i }));@@ -271,7 +323,7 @@ describe('AddApiKeyDialog', () => {renderDialog();const user = await fillCredentials();- await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await clickDetect(user);await user.click(await screen.findByRole('button', { name: /Add anyway|仍要添加/i }));await user.click(await screen.findByRole('button', { name: /^Retry$|^重试$/i }));@@ -283,7 +335,7 @@ describe('AddApiKeyDialog', () => {expect(create.mock.calls[1][0].client_nonce).toBe(create.mock.calls[0][0].client_nonce);});- it('aborts an in-flight pull and returns to the form without dismissing', async () => {+ it('aborts an in-flight detect and returns to the form without dismissing', async () => {let wasAborted = false;vi.spyOn(modelsApi, 'observeApiKeySource').mockImplementation((_draft, signal) => new Promise((_resolve, reject) => {signal?.addEventListener('abort', () => {@@ -294,12 +346,12 @@ describe('AddApiKeyDialog', () => {const { onClose } = renderDialog();const user = await fillCredentials();- await user.click(screen.getByRole('button', { name: /Fetch models|拉取模型/i }));+ await clickDetect(user);await user.click(screen.getAllByRole('button', { name: /^Cancel$|^取消$/i }).at(-1)!);expect(wasAborted).toBe(true);expect(onClose).not.toHaveBeenCalled();- expect(screen.getByRole('button', { name: /Fetch models|拉取模型/i })).toBeTruthy();+ expect(screen.getByRole('button', { name: DETECT })).toBeTruthy();});it('reconciles a lost source-create response by nonce without posting twice', async () => {@@ -317,7 +369,8 @@ describe('AddApiKeyDialog', () => {const { onAdded } = renderDialog();const user = await fillCredentials();- await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await clickDetect(user);+ await clickConfirm(user);await user.click(await screen.findByRole('button', { name: /^Retry$|^重试$/i }));await waitFor(() => expect(onAdded).toHaveBeenCalledOnce());@@ -335,7 +388,8 @@ describe('AddApiKeyDialog', () => {renderDialog();const user = await fillCredentials();- await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await clickDetect(user);+ await clickConfirm(user);await user.click(await screen.findByRole('button', { name: /^Retry$|^重试$/i }));await waitFor(() => expect(create).toHaveBeenCalledTimes(2));@@ -351,7 +405,8 @@ describe('AddApiKeyDialog', () => {const { onAdded, onClose } = renderDialog();const user = await fillCredentials();- await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await clickDetect(user);+ await clickConfirm(user);await user.click(await screen.findByRole('button', { name: /^Retry$|^重试$/i }));await user.click(screen.getAllByRole('button', { name: /^Cancel$|^取消$/i }).at(-1)!);pendingInventory.resolve([]);@@ -374,7 +429,8 @@ describe('AddApiKeyDialog', () => {const { onAdded } = renderDialog();const user = await fillCredentials();- await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await clickDetect(user);+ await clickConfirm(user);await user.click(await screen.findByRole('button', { name: /^Retry$|^重试$/i }));await user.click(screen.getAllByRole('button', { name: /^Cancel$|^取消$/i }).at(-1)!);pendingInventory.resolve([{ ...source, client_nonce: nonce }]);@@ -388,14 +444,14 @@ describe('AddApiKeyDialog', () => {renderDialog();const user = await fillCredentials();const name = screen.getByRole('textbox', { name: /^Name|^名称/i });- const add = screen.getByRole('button', { name: /^Add$|^添加$/i }) as HTMLButtonElement;+ const detect = screen.getByRole('button', { name: DETECT }) as HTMLButtonElement;await user.type(name, ' ');- expect(add.disabled).toBe(true);+ expect(detect.disabled).toBe(true);await user.clear(name);await user.type(name, 'x'.repeat(SOURCE_DISPLAY_NAME_MAX_LENGTH + 1));- expect(add.disabled).toBe(true);- await user.click(add);+ expect(detect.disabled).toBe(true);+ await user.click(detect);expect(observe).not.toHaveBeenCalled();});@@ -403,12 +459,12 @@ describe('AddApiKeyDialog', () => {renderDialog();const user = await fillCredentials();const name = screen.getByRole('textbox', { name: /^Name|^名称/i });- const add = screen.getByRole('button', { name: /^Add$|^添加$/i }) as HTMLButtonElement;+ const detect = screen.getByRole('button', { name: DETECT }) as HTMLButtonElement;await user.type(name, '😀'.repeat(SOURCE_DISPLAY_NAME_MAX_LENGTH));- expect(add.disabled).toBe(false);+ expect(detect.disabled).toBe(false);await user.type(name, '😀');- expect(add.disabled).toBe(true);+ expect(detect.disabled).toBe(true);});it('keeps a server-named create validation failure editable and out of save reconciliation', async () => {@@ -430,7 +486,8 @@ describe('AddApiKeyDialog', () => {const name = screen.getByRole('textbox', { name: /^Name|^名称/i });await user.type(name, 'Relay');- await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await clickDetect(user);+ await clickConfirm(user);expect(await screen.findByText(i18n.t('settings.models.addKey.fail.unclassified'))).toBeTruthy();expect(screen.queryByText('modelHub.errors.discovery_failed')).toBeNull();@@ -439,10 +496,108 @@ describe('AddApiKeyDialog', () => {expect(list).not.toHaveBeenCalled();await user.clear(name);await user.type(name, 'Fixed relay');- expect(screen.getByRole('button', { name: /^Add$|^添加$/i })).toBeTruthy();+ expect(screen.getByRole('button', { name: DETECT })).toBeTruthy();expect(create).toHaveBeenCalledOnce();});+ it('retires the evidence of every exit that would persist without observing again', async () => {+ // One rule, stated over how a state exits rather than over which states exist:+ // ①″'s report and the protocol a server-named refusal still holds were each+ // proved against this endpoint, this credential and this probe constraint, so+ // changing any of those three ends both. Every combination is driven through+ // the UI so neither arm can quietly become its own special case.+ type Act = (user: ReturnType<typeof userEvent.setup>) => Promise<void>;+ const exits: Act[] = [+ async (user) => {+ await clickDetect(user);+ await screen.findByRole('button', { name: CONFIRM });+ },+ async (user) => {+ await clickDetect(user);+ await clickConfirm(user);+ await screen.findByRole('button', { name: RETRY });+ },+ ];+ const connectionEdits: Act[] = [+ async (user) => { await user.type(screen.getByRole('textbox', { name: /^Base URL$/i }), '/v2'); },+ async (user) => { await user.type(screen.getByLabelText(/^API key$/i), 'x'); },+ async (user) => {+ await openManualProtocol(user);+ await user.click(screen.getByRole('button', { name: 'Anthropic Messages' }));+ },+ ];++ for (const reachExit of exits) {+ for (const edit of connectionEdits) {+ vi.spyOn(modelsApi, 'observeApiKeySource').mockResolvedValue(observed());+ const create = vi.spyOn(modelsApi, 'createApiKeySource').mockRejectedValue(+ new ApiCallError('invalid_source', 'modelHub.errors.discovery_failed', true, [], [], [], 422),+ );+ renderDialog();+ const user = await fillCredentials();+ await reachExit(user);+ const persistedBefore = create.mock.calls.length;++ await edit(user);++ expect(screen.getByRole('button', { name: DETECT })).toBeTruthy();+ expect(screen.queryByRole('button', { name: CONFIRM })).toBeNull();+ expect(screen.queryByRole('button', { name: RETRY })).toBeNull();+ expect(create.mock.calls.length).toBe(persistedBefore);++ cleanup();+ vi.restoreAllMocks();+ }+ }+ });++ it('keeps a state whose own primary re-observes across the same edit', async () => {+ // The counterpart of the rule above, and the reason it is written over exits:+ // ④'s 重试 reads the fields as they now stand, so naming an interface there is+ // how the user answers it — not evidence to retire.+ vi.spyOn(modelsApi, 'observeApiKeySource').mockResolvedValue(observed({+ outcome: 'ambiguous',+ authenticated: 'unknown',+ protocol: null,+ discovery: 'not_attempted',+ models: [],+ }));+ renderDialog();+ const user = await fillCredentials();++ await clickDetect(user);+ await user.click(await screen.findByRole('button', { name: 'Anthropic Messages' }));++ expect(screen.getByRole('button', { name: RETRY })).toBeTruthy();+ expect(screen.queryByRole('button', { name: DETECT })).toBeNull();+ });++ it('names the interface Detect will send while the disclosure is closed', async () => {+ // The collapsed row and the expanded selector are one selection rendered two+ // ways, so the row states the active constraint rather than the default it+ // replaced, and the promise of automatic identification goes with it.+ const observe = vi.spyOn(modelsApi, 'observeApiKeySource').mockResolvedValue(observed());+ renderDialog();+ const user = await fillCredentials();+ const autoRow = document.querySelector('.model-hub-add-key-protocol-active');+ expect(autoRow?.textContent).toMatch(/Auto detect|自动探测/);+ expect(autoRow?.querySelector('.model-hub-add-key-protocol-glyph')).toBeNull();++ await openManualProtocol(user);+ expect(document.querySelector('.model-hub-add-key-protocol-active')).toBeNull();+ await user.click(screen.getByRole('button', { name: 'Anthropic Messages' }));+ await openManualProtocol(user);++ const chosenRow = document.querySelector('.model-hub-add-key-protocol-active');+ expect(chosenRow?.textContent).toMatch(/Anthropic Messages/);+ expect(chosenRow?.querySelector('.model-hub-add-key-protocol-glyph')).toBeTruthy();+ expect(screen.queryByText(i18n.t('settings.models.addKey.protocol.idleHint'))).toBeNull();++ await clickDetect(user);+ await screen.findByRole('button', { name: CONFIRM });+ expect(observe.mock.calls[0][0].protocol).toBe('anthropic');+ });+it('renders the safe observation cause when create rejects after probing', async () => {const failure = new ApiCallError('discovery_failed',@@ -465,7 +620,8 @@ describe('AddApiKeyDialog', () => {renderDialog();const user = await fillCredentials();- await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await clickDetect(user);+ await clickConfirm(user);expect(await screen.findByText(i18n.t('settings.models.addKey.fail.auth'))).toBeTruthy();expect(screen.queryByText(i18n.t('settings.models.addKey.fail.unclassified'))).toBeNull();@@ -487,7 +643,8 @@ describe('AddApiKeyDialog', () => {renderDialog();const user = await fillCredentials();- await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await clickDetect(user);+ await clickConfirm(user);expect(await screen.findByText(/model list did not come back|没拿到它的模型清单/i)).toBeTruthy();expect(screen.getByRole('button', { name: /Add anyway|仍要添加/i })).toBeTruthy();@@ -517,7 +674,8 @@ describe('AddApiKeyDialog', () => {renderDialog();const user = await fillCredentials();- await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await clickDetect(user);+ await clickConfirm(user);expect(await screen.findByText(/cannot tell which interface|无法判断是哪种接口/i)).toBeTruthy();expect(screen.queryByText(i18n.t('settings.models.addKey.fail.unclassified'))).toBeNull();diff --git a/ui/src/components/settings/models/AddApiKeyDialog.tsx b/ui/src/components/settings/models/AddApiKeyDialog.tsxindex e4407353d..8e7bdd0ab 100644--- a/ui/src/components/settings/models/AddApiKeyDialog.tsx+++ b/ui/src/components/settings/models/AddApiKeyDialog.tsx@@ -2,12 +2,12 @@ import * as React from 'react';import * as DialogPrimitive from '@radix-ui/react-dialog';import {CheckCircle2,+ ChevronDown,CircleX,Eye,EyeOff,Info,LoaderCircle,- PlugZap,TriangleAlert,X,} from 'lucide-react';@@ -49,6 +49,7 @@ import {type SourceProtocol,type SupplyGap,} from './types';+import { ProtocolGlyph } from './protocolGlyph';import { optionalTrimmedTextWithin } from './validation';type Phase =@@ -72,6 +73,56 @@ type Phase =const INITIAL_PHASE: Phase = { kind: 'form', report: null };type ProtocolSelection = 'auto' | SourceProtocol;+// A phase whose primary commits WITHOUT observing again is carrying evidence+// that only this endpoint, this credential and this probe constraint produced:+// ①″'s report, ⑤'s waived inventory, and the protocol a refused or unanswered+// create already proved. That is the property, not a list of the states that+// happen to be reachable today — a phase added later inherits the rule from how+// its own exit behaves. Phases whose primary re-observes (③ / ④ / ⑤'s 重试, ⑥)+// are deliberately absent: their retry reads the fields as they now stand, and+// §0.8 keeps the form intact across it.+const persistsWithoutObserving = (phase: Phase): boolean =>+ (phase.kind === 'form' && phase.report !== null)+ || phase.kind === 'inventory'+ || phase.kind === 'persist_failure'+ || phase.kind === 'save_unconfirmed';++const ProtocolSegments: React.FC<{+ id?: string;+ disabled: boolean;+ selection: ProtocolSelection;+ onSelect: (value: ProtocolSelection) => void;+}> = ({ id, disabled, selection, onSelect }) => {+ const { t } = useTranslation();+ return (+ <div+ id={id}+ role="group"+ aria-label={t('settings.models.addKey.field.protocol')}+ className="model-hub-add-key-segments flex max-w-full flex-wrap"+ >+ {(['auto', ...SOURCE_PROTOCOLS] as const).map((item) => (+ <button+ key={item}+ type="button"+ disabled={disabled}+ aria-pressed={selection === item}+ className={cn(+ 'model-hub-add-key-segment',+ selection === item && 'is-selected',+ )}+ onClick={() => onSelect(item)}+ >+ {item !== 'auto' && <ProtocolGlyph protocol={item} />}+ {t(item === 'auto'+ ? 'settings.models.addKey.protocol.auto'+ : PROTOCOL_COPY_KEYS[item])}+ </button>+ ))}+ </div>+ );+};+type ReplaceOutcome =| { kind: 'repaired' }| { kind: 'impact'; hops: RouteHopRef[]; gaps: SupplyGap[] };@@ -207,6 +258,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {const [apiKey, setApiKey] = React.useState('');const [protocolSelection, setProtocolSelection] = React.useState<ProtocolSelection>('auto');const [revealed, setRevealed] = React.useState(false);+ const [manualOpen, setManualOpen] = React.useState(false);const [phase, setPhase] = React.useState<Phase>(INITIAL_PHASE);const [replacePhase, setReplacePhase] = React.useState<ReplacePhase>({ kind: 'edit' });const [continuation] = React.useState(createContinuationSettlement);@@ -233,6 +285,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {setApiKey('');setProtocolSelection('auto');setRevealed(false);+ setManualOpen(false);setPhase(INITIAL_PHASE);setReplacePhase({ kind: 'edit' });}@@ -341,12 +394,10 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {...(protocol ? { protocol } : {}),}, controller.signal);const verdict = classifyObservation(observation);- let persistNext = false;- const landed = continuation.settle(seq, () => {+ continuation.settle(seq, () => {observationAbort.current = null;if (verdict.kind === 'ready') {- if (origin === 'pull') setPhase({ kind: 'form', report: observation });- else persistNext = true;+ setPhase({ kind: 'form', report: observation });} else if (verdict.kind === 'undetermined') {setPhase({ kind: 'undetermined', origin, observation });} else if (verdict.kind === 'inventory') {@@ -355,7 +406,6 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {setPhase({ kind: 'failure', origin, cause: verdict.cause });}});- if (landed === 'landed' && persistNext) await persist(seq, protocol);} catch (error) {if (isAbortError(error)) return;continuation.settle(seq, () => {@@ -367,7 +417,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {});});}- }, [apiKey, baseUrl, continuation, persist]);+ }, [apiKey, baseUrl, continuation]);const submitReplacement = React.useCallback(async (force: boolean) => {if (props.mode !== 'replace' || !apiKey.trim() || replacePhase.kind === 'submitting') return;@@ -461,7 +511,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {continuation.invalidate();observationAbort.current?.abort();observationAbort.current = null;- if ('origin' in phase && phase.origin === 'pull') {+ if (phase.kind === 'working' && phase.stage === 'observe') {setPhase(INITIAL_PHASE);return;}@@ -517,27 +567,39 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {};const addAnyway = async () => {- if (phase.kind !== 'inventory' || phase.origin !== 'add' || !phase.observation.protocol) return;+ if (phase.kind !== 'inventory' || !phase.observation.protocol) return;const seq = continuation.begin();await persist(seq, phase.observation.protocol, true);};+ // §0.8 ①″: editing Base URL, the API key, or the protocol selection returns+ // the dialog to ① Ready with the report dropped. The same three inputs are+ // what every persisting exit's evidence was proved against, so one retirement+ // covers the whole class instead of each handler picking its own phase.+ const retireProvedEvidence = () => {+ setPhase((current) => (persistsWithoutObserving(current) ? INITIAL_PHASE : current));+ };+const editEndpoint = (value: string) => {setBaseUrl(value);- if (phase.kind === 'form' && phase.report) setPhase(INITIAL_PHASE);+ retireProvedEvidence();};const editKey = (value: string) => {setApiKey(value);if (replaceMode && replacePhase.kind === 'failure') setReplacePhase({ kind: 'edit' });- if (phase.kind === 'form' && phase.report) setPhase(INITIAL_PHASE);+ retireProvedEvidence();};+ // The display name is in no observation, so it proves and unproves nothing —+ // ①″ keeps its report across a rename. It IS in the create request, so a+ // server-named refusal of that request stops describing the request the user+ // now holds.const editDisplayName = (value: string) => {setDisplayName(value);if (phase.kind === 'persist_failure') setPhase(INITIAL_PHASE);};const editProtocol = (value: ProtocolSelection) => {setProtocolSelection(value);- if (phase.kind === 'form' && phase.report) setPhase(INITIAL_PHASE);+ retireProvedEvidence();};const isWorking = phase.kind === 'working';@@ -549,6 +611,14 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {const canObserve = Boolean(baseUrl.trim() && apiKey.trim()) && !formLocked;const canSubmit = canObserve && displayNameValid;const selectedProtocol = protocolSelection === 'auto' ? undefined : protocolSelection;+ const protocolIdle = !baseUrl.trim() || !apiKey.trim();+ const detecting = isWorking && phase.kind === 'working' && phase.stage === 'observe';+ const identified = phase.kind === 'form' && phase.report !== null && Boolean(phase.report.protocol);+ const identifiedProtocol = identified && phase.kind === 'form' ? phase.report?.protocol ?? null : null;+ // The segments and the summary row are two renderings of one selection, so+ // only one of them is on screen at a time: expanded, the pressed segment IS+ // the statement; collapsed, the row carries it.+ const segmentsOpen = phase.kind === 'undetermined' || (manualOpen && !isWorking);const showForm = phase.kind !== 'inventory';const replaceTerminalFailure = replacePhase.kind === 'failure'&& replacePhase.failureClass === 'authoritative-terminal';@@ -655,40 +725,6 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {<Field className="model-hub-add-key-field" labelClassName="model-hub-add-key-label" label={t('settings.models.addKey.field.name')}>{(id) => <Input id={id} value={displayName} disabled={formLocked} aria-invalid={!displayNameValid} onChange={(event) => editDisplayName(event.target.value)} className="model-hub-add-key-input" />}</Field>- <Field- className="model-hub-add-key-field"- labelClassName="model-hub-add-key-label"- hintClassName="model-hub-add-key-hint"- label={t('settings.models.addKey.field.protocol')}- hint={t('settings.models.addKey.field.protocol.hint')}- >- {(id) => (- <div- id={id}- role="group"- aria-label={t('settings.models.addKey.field.protocol')}- className="model-hub-add-key-segments flex max-w-full flex-wrap"- >- {(['auto', ...SOURCE_PROTOCOLS] as const).map((selection) => (- <button- key={selection}- type="button"- disabled={formLocked}- aria-pressed={protocolSelection === selection}- className={cn(- 'model-hub-add-key-segment',- protocolSelection === selection && 'is-selected',- )}- onClick={() => editProtocol(selection)}- >- {t(selection === 'auto'- ? 'settings.models.addKey.protocol.auto'- : PROTOCOL_COPY_KEYS[selection])}- </button>- ))}- </div>- )}- </Field><Field className="model-hub-add-key-field" labelClassName="model-hub-add-key-label" hintClassName="model-hub-add-key-hint" label={t('settings.models.addKey.field.baseUrl')} hint={t('settings.models.addKey.field.baseUrl.hint')}>{(id) => <Input id={id} value={baseUrl} disabled={formLocked} autoComplete="url" spellCheck={false} onChange={(event) => editEndpoint(event.target.value)} className="model-hub-add-key-input font-mono" />}</Field>@@ -701,46 +737,88 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {onToggleReveal={() => setRevealed((value) => !value)}/>- {phase.kind === 'undetermined' && (- <div className="model-hub-add-key-strip model-hub-add-key-strip--advisory">- <Info className="model-hub-ink-gold size-3.5 shrink-0" />- <div className="flex min-w-0 flex-col gap-[3px]">- <span className="model-hub-add-key-strip-title model-hub-ink-gold">{t('settings.models.addKey.undetermined.title')}</span>- <span className="model-hub-add-key-strip-detail">{t('settings.models.addKey.undetermined.detail')}</span>+ <div className={cn(+ 'model-hub-add-key-protocol-area',+ protocolIdle && !isWorking && phase.kind !== 'undetermined' && 'is-idle',+ )}>+ <span className="model-hub-add-key-label">{t('settings.models.addKey.field.protocol')}</span>+ {phase.kind === 'undetermined' && (+ <div className="model-hub-add-key-strip model-hub-add-key-strip--advisory">+ <Info className="model-hub-ink-gold size-3.5 shrink-0" />+ <div className="flex min-w-0 flex-col gap-[3px]">+ <span className="model-hub-add-key-strip-title model-hub-ink-gold">{t('settings.models.addKey.undetermined.title')}</span>+ <span className="model-hub-add-key-strip-detail">{t('settings.models.addKey.undetermined.detail')}</span>+ </div></div>- </div>- )}-- {!isWorking && (- <div className="model-hub-add-key-test-row flex items-center justify-between gap-4">- <Button+ )}+ {detecting && (+ <div className="model-hub-add-key-protocol-detecting">+ <LoaderCircle className="model-hub-ink-mint size-3.5 shrink-0 animate-spin" />+ <span>{t('settings.models.addKey.protocol.detecting')}</span>+ </div>+ )}+ {identified && identifiedProtocol && (+ <div className="model-hub-add-key-strip model-hub-add-key-strip--success">+ <CheckCircle2 className="model-hub-ink-mint size-3.5 shrink-0" />+ <ProtocolGlyph protocol={identifiedProtocol} />+ <span>+ {t(PROTOCOL_COPY_KEYS[identifiedProtocol])}+ {' · '}+ {phase.kind === 'form' && phase.report && phase.report.models.length === 0+ ? t('settings.models.addKey.pull.empty')+ : t('settings.models.addKey.pull.result', {+ count: phase.kind === 'form' && phase.report ? phase.report.models.length : 0,+ })}+ </span>+ </div>+ )}+ {phase.kind === 'form' && !phase.report && !segmentsOpen && (+ <div className="model-hub-add-key-protocol-idle-row">+ {/* Whatever 检测 is about to send, and nothing else: a concrete+ choice is the active constraint even while the disclosure+ that made it is closed. */}+ <span className="model-hub-add-key-protocol-active">+ {selectedProtocol && <ProtocolGlyph protocol={selectedProtocol} />}+ {t(selectedProtocol+ ? PROTOCOL_COPY_KEYS[selectedProtocol]+ : 'settings.models.addKey.protocol.auto')}+ </span>+ {/* The hint promises automatic identification, which is only+ what Auto does. A named interface has already answered it. */}+ {!selectedProtocol && (+ <span className="model-hub-add-key-hint">{t('settings.models.addKey.protocol.idleHint')}</span>+ )}+ </div>+ )}+ {segmentsOpen && (+ <div className="model-hub-add-key-protocol-manual">+ <ProtocolSegments+ disabled={formLocked}+ selection={protocolSelection}+ onSelect={editProtocol}+ />+ <p className="model-hub-add-key-hint">{t('settings.models.addKey.field.protocol.hint')}</p>+ </div>+ )}+ {!isWorking && phase.kind !== 'undetermined' && (+ <buttontype="button"- variant="outline"- className="model-hub-add-key-secondary"- disabled={!canObserve}- onClick={() => void observe('pull', selectedProtocol)}+ className="model-hub-add-key-protocol-disclosure"+ aria-expanded={manualOpen}+ onClick={() => setManualOpen((open) => !open)}>- <PlugZap className="size-3" />- {t('settings.models.addKey.test')}- </Button>- <span className="model-hub-add-key-hint">{t('settings.models.addKey.test.hint')}</span>- </div>- )}+ <ChevronDown className={cn('size-3.5 shrink-0', manualOpen && 'rotate-180')} />+ {t('settings.models.addKey.protocol.manual')}+ </button>+ )}+ </div>- {phase.kind === 'form' && phase.report && (- <div className="model-hub-add-key-strip model-hub-add-key-strip--success">- <CheckCircle2 className="model-hub-ink-mint size-3.5 shrink-0" />- <span>{phase.report.models.length === 0- ? t('settings.models.addKey.pull.empty')- : t('settings.models.addKey.pull.result', { count: phase.report.models.length })}</span>- </div>- )}- {phase.kind === 'working' && (+ {phase.kind === 'working' && phase.stage === 'persist' && (<div className="model-hub-add-key-strip model-hub-add-key-strip--working"><LoaderCircle className="model-hub-ink-mint size-3.5 shrink-0 animate-spin" /><div className="flex min-w-0 flex-col gap-[3px]">- <span className="model-hub-add-key-strip-title text-foreground">{t('settings.models.addKey.adding')}</span>- <span className="model-hub-add-key-strip-detail">{t('settings.models.addKey.adding.detail')}</span>+ <span className="model-hub-add-key-strip-title text-foreground">{t('settings.models.addKey.saving')}</span>+ <span className="model-hub-add-key-strip-detail">{t('settings.models.addKey.saving.detail')}</span></div></div>)}@@ -827,12 +905,12 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {>{t('settings.models.addKey.cancel')}</Button>- {phase.kind === 'inventory' && phase.origin === 'add' && (+ {phase.kind === 'inventory' && (<Button type="button" variant="outline" className="model-hub-add-key-action" onClick={() => void addAnyway()}>{t('settings.models.addKey.addAnyway')}</Button>)}- {phase.kind === 'form' && (+ {phase.kind === 'form' && !phase.report && (<Buttontype="button"variant="brand"@@ -840,13 +918,26 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {disabled={!canSubmit}onClick={() => void observe('add', selectedProtocol)}>- {t('settings.models.addKey.submit')}+ {t('settings.models.addKey.detect')}+ </Button>+ )}+ {phase.kind === 'form' && phase.report?.protocol && (+ <Button+ type="button"+ variant="brand"+ className="model-hub-add-key-action"+ disabled={!canSubmit}+ onClick={() => void persist(continuation.begin(), phase.report?.protocol ?? undefined)}+ >+ {t('settings.models.addKey.confirm')}</Button>)}{phase.kind === 'working' && (<Button type="button" variant="brand" className="model-hub-add-key-action" disabled><LoaderCircle className="size-3 animate-spin" />- {t('settings.models.addKey.adding')}+ {t(phase.stage === 'persist'+ ? 'settings.models.addKey.saving'+ : 'settings.models.addKey.protocol.detecting')}</Button>)}{(phase.kind === 'failure' || phase.kind === 'persist_failure' || phase.kind === 'save_unconfirmed' || phase.kind === 'inventory' || phase.kind === 'undetermined') && (diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsxindex f41d8dd6d..a2c285c5b 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -285,7 +285,8 @@ describe('SettingsModelsPage surface branches', () => {await user.click(trigger);await user.type(screen.getByRole('textbox', { name: /^Base URL$/i }), 'https://relay.example/v1');await user.type(screen.getByLabelText(/^API key$/i), 'secret-key');- await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));+ await user.click(screen.getByRole('button', { name: /^Detect$|^检测$/ }));+ await user.click(await screen.findByRole('button', { name: /Confirm & add|确认添加/ }));const detail = await screen.findByRole('dialog', { name: 'Created API key' });await user.click(within(detail).getByRole('button', { name: /Close provider details|关闭供应商详情/i }));diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.cssindex 7dee916ad..58696a83e 100644--- a/ui/src/components/settings/models/modelHubSurface.css+++ b/ui/src/components/settings/models/modelHubSurface.css@@ -627,8 +627,58 @@font-family: "JetBrains Mono", ui-monospace, monospace;font-size: var(--model-hub-add-key-hint-size);}-.model-hub-add-key-test-row { min-height: 34px; }-.model-hub-add-key-secondary,+.model-hub-add-key-protocol-area {+ display: flex;+ width: 100%;+ flex-direction: column;+ gap: var(--model-hub-add-key-field-gap);+}+.model-hub-add-key-protocol-area.is-idle { opacity: 0.55; }+.model-hub-add-key-protocol-idle-row,+.model-hub-add-key-protocol-detecting,+.model-hub-add-key-protocol-manual {+ display: flex;+ gap: 3px;+}+.model-hub-add-key-protocol-idle-row {+ flex-direction: row;+ flex-wrap: wrap;+ align-items: baseline;+ gap: 8px;+}+.model-hub-add-key-protocol-active {+ display: inline-flex;+ align-items: center;+ gap: 6px;+}+.model-hub-add-key-protocol-manual {+ flex-direction: column;+}+.model-hub-add-key-protocol-detecting {+ flex-direction: row;+ align-items: center;+ gap: var(--model-hub-add-key-strip-gap);+ color: var(--foreground);+ font-size: var(--model-hub-add-key-strip-title-size);+ font-weight: 600;+}+.model-hub-add-key-protocol-disclosure {+ display: inline-flex;+ width: fit-content;+ align-items: center;+ gap: 6px;+ padding: 0;+ border: 0;+ background: transparent;+ color: var(--model-hub-muted-b3);+ font-size: var(--model-hub-add-key-hint-size);+ font-weight: 600;+}+.model-hub-add-key-protocol-glyph {+ width: 14px;+ height: 14px;+ flex-shrink: 0;+}.model-hub-add-key-action {height: auto;border-radius: var(--model-hub-add-key-action-radius);@@ -666,6 +716,9 @@font-size: var(--model-hub-add-key-strip-title-size);font-weight: 600;}+.model-hub-add-key-strip--success .model-hub-add-key-protocol-glyph {+ color: var(--mint-ink);+}.model-hub-add-key-strip-title {font-size: var(--model-hub-add-key-strip-title-size);font-weight: 600;@@ -688,6 +741,9 @@background: var(--model-hub-wash-0a);}.model-hub-add-key-segment {+ display: inline-flex;+ align-items: center;+ gap: 6px;border-radius: var(--model-hub-add-key-segment-radius);padding: var(--model-hub-add-key-segment-padding-y) var(--model-hub-add-key-segment-padding-x);color: var(--muted);diff --git a/ui/src/components/settings/models/protocolGlyph.tsx b/ui/src/components/settings/models/protocolGlyph.tsxnew file mode 100644index 000000000..417ace72a--- /dev/null+++ b/ui/src/components/settings/models/protocolGlyph.tsx@@ -0,0 +1,43 @@+import * as React from 'react';++import { cn } from '@/lib/utils';+import type { SourceProtocol } from './types';++type GlyphProps = React.SVGProps<SVGSVGElement>;++const glyphClassName = (className?: string) => cn('model-hub-add-key-protocol-glyph', className);++export const AnthropicGlyph: React.FC<GlyphProps> = ({ className, ...props }) => (+ <svg+ viewBox="0 0 24 24"+ aria-hidden="true"+ focusable="false"+ fill="currentColor"+ className={glyphClassName(className)}+ {...props}+ >+ <path d="M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z" />+ </svg>+);++export const OpenAIGlyph: React.FC<GlyphProps> = ({ className, ...props }) => (+ <svg+ viewBox="0 0 24 24"+ aria-hidden="true"+ focusable="false"+ fill="currentColor"+ className={glyphClassName(className)}+ {...props}+ >+ <path d="M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z" />+ </svg>+);++export const ProtocolGlyph: React.FC<{ protocol: SourceProtocol; className?: string }> = ({+ protocol,+ className,+}) => (+ protocol === 'anthropic'+ ? <AnthropicGlyph className={className} />+ : <OpenAIGlyph className={className} />+);diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex e6b2810cd..aab8a2eff 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1353,7 +1353,7 @@},"addKey": {"title": "Add API key",- "subtitle": "Add connects once: it identifies the interface and fetches the model list",+ "subtitle": "Detect the connection and interface first, then confirm to add","field": {"name": "Name (optional)","protocol": "Interface type",@@ -1364,16 +1364,17 @@"apiKey.reveal": "Show API key","apiKey.conceal": "Hide API key"},- "test": "Fetch models",- "test.hint": "Optional · Add fetches once anyway","pull": {"result_one": "Fetched {{count}} model","result_other": "Fetched {{count}} models","empty": "Connected, but this source lists no models"},- "submit": "Add",+ "detect": "Detect",+ "confirm": "Confirm & add","adding": "Connecting…","adding.detail": "Connect, validate the interface, fetch the model list · usually 1–3s",+ "saving": "Saving…",+ "saving.detail": "Saving this source","fail": {"subtitle": "Identifying the interface is a precondition of Add · fix what the line below names, then retry","auth": "The upstream rejected this credential",@@ -1395,7 +1396,10 @@"auto": "Auto detect","anthropicMessages": "Anthropic Messages","openaiResponses": "OpenAI Responses",- "openaiChatCompletions": "OpenAI Chat Completions"+ "openaiChatCompletions": "OpenAI Chat Completions",+ "idleHint": "Identified automatically once Base URL and API key are filled",+ "detecting": "Identifying the interface…",+ "manual": "Manually specify interface type"},"inventory": {"title": "The interface is identified — but its model list did not come back this time"diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 19ceda130..6ff3a0a49 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1353,7 +1353,7 @@},"addKey": {"title": "添加 API Key",- "subtitle": "添加时自动连接一次:识别接口并拉取模型列表",+ "subtitle": "先检测连接与接口,确认后添加","field": {"name": "名称(可选)","protocol": "接口类型",@@ -1364,16 +1364,17 @@"apiKey.reveal": "显示 API Key","apiKey.conceal": "隐藏 API Key"},- "test": "拉取模型",- "test.hint": "可选 ·「添加」时会自动拉一次","pull": {"result_one": "拉到 {{count}} 个模型","result_other": "拉到 {{count}} 个模型","empty": "已经连接,但这个供应商没有可用模型"},- "submit": "添加",+ "detect": "检测",+ "confirm": "确认添加","adding": "连接中…","adding.detail": "连接 + 验证接口 + 首次拉取模型列表 · 通常 1–3 秒",+ "saving": "保存中…",+ "saving.detail": "正在保存这个供应商","fail": {"subtitle": "认出接口是「添加」的前置条件 · 先按下面这条修,再重试","auth": "供应商拒绝了这个凭据",@@ -1395,7 +1396,10 @@"auto": "自动探测","anthropicMessages": "Anthropic Messages","openaiResponses": "OpenAI Responses",- "openaiChatCompletions": "OpenAI Chat Completions"+ "openaiChatCompletions": "OpenAI Chat Completions",+ "idleHint": "填好 Base URL 和 API Key 后自动识别",+ "detecting": "识别接口中…",+ "manual": "手动指定接口类型"},"inventory": {"title": "接口已经识别,但这次没有拿到模型清单"