Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(model-hub): clarify standby source status (#1713)

Call White41ce125acbff
diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.py
index f71c90719..9b27f396d 100644
--- a/core/handlers/model_hub/rpc.py
+++ b/core/handlers/model_hub/rpc.py
@@ -102,6 +102,11 @@ async def dispatch_model_hub_rpc(
)
if operation == "reorder_agent_chains":
await _refresh_agent_presence(service)
+ if "order" in payload:
+ return await service.reorder_agent_chains(
+ payload.get("backend"),
+ payload.get("order"),
+ )
return await service.reorder_agent_chains(payload.get("backend"))
if operation == "set_agent_mode":
await _refresh_agent_presence(service)
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 626becf0e..6274f30b6 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -115,6 +115,7 @@ from .usage import USAGE_DEFAULT_WINDOW_DAYS, BoundedUsageLedger, SourceIdentity
CONTRACT_VERSION = 6
AGENT_CHAIN_CONTRACT_VERSION = 6
PROBE_RESULT_CONTRACT_VERSION = 6
+_REORDER_ORDER_UNSET = object()
# Settlement generations are minted per attempt start and live only in this
# runtime's ledger, which restarts with the process. Every generation this
# runtime mints is therefore strictly greater than this pre-attempt value, and
@@ -1659,6 +1660,7 @@ class ModelHubService:
result = [
{"backend": backend, "menu_model": menu_model}
for backend in MODEL_HUB_BACKENDS
+ if config.agents[backend].mode == "hub"
for menu_model, route in config.agents[backend].routes.items()
if any(hop.source_id == source_id for hop in route.hops)
]
@@ -3241,32 +3243,43 @@ class ModelHubService:
),
)
+ def _validate_agent_source_order(
+ self,
+ config: ModelHubConfig,
+ backend: str,
+ order: object,
+ ) -> list[str]:
+ if not isinstance(order, list):
+ raise self._invalid_source_order()
+ seen: set[str] = set()
+ by_id = {source.id: source for source in config.sources}
+ for source_id in order:
+ if (
+ not isinstance(source_id, str)
+ or source_id in seen
+ or source_id not in by_id
+ or not self._eligible_for_agent(by_id[source_id], backend)
+ ):
+ raise self._invalid_source_order()
+ seen.add(source_id)
+ return list(order)
+
async def set_agent_sources(self, backend: str, payload: object) -> dict:
if backend not in MODEL_HUB_BACKENDS or not isinstance(payload, dict):
raise self._invalid_source_order()
if set(payload) != {"order"}:
rejected = sorted(set(payload) - {"order"})
raise self._invalid_source_order(rejected_keys=rejected)
- order = payload.get("order")
- if not isinstance(order, list):
- raise self._invalid_source_order()
async with self._mutation_lock:
previous = self.store.load()
config = self._clone_config(previous)
agent = self._agent(config, backend)
- seen: set[str] = set()
- by_id = {source.id: source for source in config.sources}
- for source_id in order:
- if (
- not isinstance(source_id, str)
- or source_id in seen
- or source_id not in by_id
- or not self._eligible_for_agent(by_id[source_id], backend)
- ):
- raise self._invalid_source_order()
- seen.add(source_id)
- agent.sources.order = list(order)
+ agent.sources.order = self._validate_agent_source_order(
+ config,
+ backend,
+ payload.get("order"),
+ )
await self._commit_synced(previous, config)
return self._agent_payload(config, agent)
@@ -3548,11 +3561,23 @@ class ModelHubService:
committed = self.store.load()
return self._agent_payload(committed, self._agent(committed, backend))
- async def reorder_agent_chains(self, backend: str) -> dict:
+ async def reorder_agent_chains(
+ self,
+ backend: str,
+ order: object = _REORDER_ORDER_UNSET,
+ ) -> dict:
async with self._mutation_lock:
previous = self.store.load()
config = self._clone_config(previous)
agent = self._agent(config, backend)
+ if order is not _REORDER_ORDER_UNSET:
+ # The optional order lets the UI commit the persisted priority and
+ # its application to existing routes in one mutation.
+ agent.sources.order = self._validate_agent_source_order(
+ config,
+ backend,
+ order,
+ )
source_positions = {
source_id: position
for position, source_id in enumerate(agent.sources.order)
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index fac22e655..65a07f14b 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -38,7 +38,7 @@ compatibility path.
| GET `/api/models/agents` | → `{agents: AgentSupply[]}` | Backend records include server-authoritative `cli_present` and `named_agents`, the enabled named-Agent live projection. The default read returns the current presence snapshot; `?refresh_cli_presence=1` first refreshes deep npm-only discovery and returns the resulting snapshot. |
| GET `/api/models/agents/<backend>/sources` | → `{agent: AgentSupply}` | Returns the authoritative effective order and eligibility. |
| PUT `/api/models/agents/<backend>/sources` | `{order: string[]}` → `{agent: AgentSupply}` | Stores and re-echoes the complete canonical order; no policy state exists. This route never touches a Route chain and has no guarded `409` branch. |
-| POST `/api/models/agents/<backend>/chains/reorder` | → `{agent: AgentSupply}` | Idempotently reorders every stored Route by the current Source order without adding, removing, remapping, matching, or guarding. The total order is defined below. |
+| POST `/api/models/agents/<backend>/chains/reorder` | `{order?: string[]}` → `{agent: AgentSupply}` | With `order`, atomically stores the complete Source order and idempotently reorders every stored Route by it; with no body, applies the already stored order. In either form it adds, removes, remaps, matches, and guards nothing. The total order is defined below. |
| PATCH `/api/models/agents/<backend>/mode` | `{mode}` → `{agent: AgentSupply}` | Explicit `hub` / `direct` switch. A qualifying Direct → Gateway switch atomically adopts the recognized CLI login as the first native Source; other switches create nothing. |
| PUT `/api/models/agents/opencode/menu` | `{menu}` → `{agent: AgentSupply}` | Open-menu configuration. |
| GET `/api/models/agents/<backend>/chains` | → `{chains: AgentChain[]}` | Hub only. Returns the complete Overview model set in menu order, followed by a selected model or configured Route not already present. All members share one config snapshot and observation time. Direct returns the documented `direct_mode` error. |
@@ -59,9 +59,10 @@ compatibility path.
| POST `/api/models/runtime/start` | → `{runtime: RuntimeDependency}` | Persists `enabled: true` and explicitly starts the managed engine. Service startup restores this intent. Uses the existing mutation authentication and CSRF guards; status reads never start it. |
| POST `/api/models/runtime/stop` | → `{runtime: RuntimeDependency}` | Explicitly stops the managed engine, persists `enabled: false`, and returns it to `not_started`. The mutation is rejected with `runtime_in_use` while any Agent backend is configured for Hub mode, so disabling the shared runtime cannot strand a configured route. |
-The removed global route `PUT /api/models/priority` has no replacement. Backend Source
-order is explicit configuration through the sources route; exact per-model order is
-explicit configuration through the chain route.
+The removed product-global route `PUT /api/models/priority` has no replacement. Backend
+Source order has two explicit operations: the sources route stores it without touching
+Routes, while `chains/reorder` can store the same order and apply it to existing Routes
+atomically. Exact per-model order is explicit configuration through the chain route.
## Unsaved Source observation
@@ -216,7 +217,7 @@ every other existing field and enum meaning remains unchanged.
| --- | --- | --- | --- |
| `Source.client_nonce` | Source create commit | lost-create reconciliation | Exact optional echo of `SourceCreate.client_nonce`, written only at commit; unique across live Sources and live-process reservations, and never used for routing. |
| `Source.models[].retired` | discovered-model DELETE | Source detail inventory | Omission means false; only a discovered row may be true; true rows remain readable and never supply. |
-| `Source.adopted_by` | Source read assembler | Source cards and Source detail status | Complete unique persisted-reference projection sorted by backend then menu model; clients do not derive it from `hops`. |
+| `Source.adopted_by` | Source read assembler | Source cards and Source detail status | Complete unique persisted-reference projection for backends currently in Hub mode, sorted by backend then menu model; clients do not derive it from `hops`. Routes retained by Direct-mode backends are excluded because they bypass the gateway. |
| `AgentSupply.cli_present` | backend CLI detector | zero-installed-backend state | Boolean installation fact only; it does not imply login or process readiness. |
| `AgentSupply.model_supply[].has_runnable_hop` | exact-chain live annotator | backend-group collapse predicate | Uses the AgentChain runnability axiom rather than inferring liveness from configured membership. `chain_length: 0` forces false; a nonzero length may carry either value. |
| `RuntimeDependency.enabled` | explicit runtime start/stop mutation | Gateway switch and service-start recovery | Persisted user intent, independent of observed process health. Missing in older config defaults to false; an older response without the field falls back to observed health in the UI. |
@@ -353,7 +354,8 @@ its process availability but carries `in_current_model_chain: null`.
## Per-backend source order
-The request is total:
+The storage-only PUT requires, and the atomic reorder POST may accept, the same total
+order body:
```json
{"order": ["src_anthkey01", "src_relay9c1x"]}
@@ -365,13 +367,16 @@ The request is total:
- Add Source and native import invoke `placement-v1` once and persist its chosen
position. Refresh, restart, health changes, and turns never recompute this order.
-The whole-order PUT is intentionally outside the §4.5 Source-mutation envelope matrix.
+The storage-only PUT is intentionally outside the §4.5 Source-mutation envelope matrix.
It stores only `sources.order`, never reads or writes a Route chain, and therefore never
-returns a guarded `409`. This is the G-9 tombstone: adding a guard branch would imply an
-order save is allowed to mutate supply, which violates S-1.
+returns a guarded `409`. This is the G-9 tombstone: adding a guard branch would imply
+that this storage-only route can remove supply, which violates S-1.
`POST /api/models/agents/<backend>/chains/reorder` is the only server-side post-creation
operation that implicitly reads and applies the stored Source order to existing Routes.
+When the optional `order` body is present, storing that complete order and applying it
+to existing Routes happen under the same mutation lock and persistence boundary; an
+omitted body preserves the stored-order-only form for internal callers.
For each Route, give every hop its original zero-based index `i` and sort by this total key:
```text
diff --git a/docs/plans/model-hub-ui-spec.md b/docs/plans/model-hub-ui-spec.md
index 09071c5bc..751523199 100644
--- a/docs/plans/model-hub-ui-spec.md
+++ b/docs/plans/model-hub-ui-spec.md
@@ -103,8 +103,10 @@ derived, and a chain with no runnable hop renders none of takeover's visual sema
and **AC-31** (Direct is a mode and the first state of an existing install; Native names
a hop and never a mode) land directly on frames 08, 09 and 10. The second move is
**S-1**, and it is larger: a configured chain is now stored configuration executed as
-written, with no runtime Source/model matching, no `follow | custom` state, and no
-second projection derived from a backend order. The third is the remainder of #1215's
+written, with no runtime Source/model matching and no `follow | custom` state. The
+backend order remains a separate projection; the explicit `chains/reorder` operation
+may apply its stable ordering to existing hops without matching, adding, removing or
+remapping them. The third is the remainder of #1215's
own review — five commits between `ca45aeb6` and the squash, sixteen contract files,
1245 insertions against 1000 deletions — and it is the one move this document did not
re-read commit by commit. It did not have to: the contract artefacts in this worktree
@@ -258,24 +260,24 @@ half named in its Missing cell has an owner.
| # | Surface | Missing | Evidence / disposition (contract baseline `1993f4fd0`) |
| --- | --- | --- | --- |
| G-3 | 06 model inventory — **retirement is contracted; its discovered-row affordance remains open** | a way to retire a *discovered* model from the drawn inventory; ~~a place to remember that it was retired~~ | `DELETE /api/models/sources/<source_id>/models/<model_id>` now persists `models[].retired: true` for a discovered row instead of deleting it. `source.schema.json` keeps that row readable, never supplying, and refresh never revives it; §4.5 applies the same exact-hop and last-supplier guards. §1.6 registers that representation as the ordinary row chrome with muted ink and the existing tag component. Frame 06 still draws removal only for manual entries, so no registered control invokes the discovered-row route; only that producer half remains live instead of treating wire reachability as a UI consumer. |
-| G-9 | ~~03 order save that drops sources~~ **withdrawn — this was never a gap** | ~~the guarded-change response for the whole-order `PUT`~~ nothing | The row read the absence of a `409` branch on the whole-order `PUT` (§1.3 Saving names the route; a withdrawn row deliberately does not, so it can excuse nothing) as something `api.md` still owed, on the strength of FC-12's 「row-for-row」 clause. It owed nothing. `model-hub.md` §4.5's Source-mutation envelope matrix is declared **authoritative and exhaustive** over 「all Source/inventory mutations, including writes that cannot remove supply」, and its eight rows do not include this route; FC-12 names 「the explicit backend Source-order PUT」 as a separate item from the mirroring clause. So the whole-order write's success echo, with 「no policy state exists」 beside it, *is* the mirror, and the absent `409` is the contract agreeing with S-1 and D-9 that reordering reaches no existing chain. Kept as a withdrawn row rather than deleted, because the number is cited in this file's own history and because a gap register that silently loses entries cannot be audited. The row names no route and quotes no body, so there is nothing left in it for a checker to excuse — but a withdrawn row is still a *number* the register defines, and a citation resolves against numbers, not against verdicts. So the rule that keeps it inert is written here rather than enforced: **no surface may carry `[contract-gap]` G-9**, and the number is not reused |
+| G-9 | ~~03 order save that drops sources~~ **withdrawn — this was never a gap** | ~~the guarded-change response for the whole-order `PUT`~~ nothing | The row read the absence of a `409` branch on the whole-order `PUT` (§1.3 Saving names the route; a withdrawn row deliberately does not, so it can excuse nothing) as something `api.md` still owed, on the strength of FC-12's 「row-for-row」 clause. It owed nothing. `model-hub.md` §4.5's Source-mutation envelope matrix is declared **authoritative and exhaustive** over 「all Source/inventory mutations, including writes that cannot remove supply」, and its eight rows do not include this route; FC-12 names 「the explicit backend Source-order PUT」 as a separate item from the mirroring clause. The PUT still has no guard and only stores the order; the separate `chains/reorder` operation now applies that order to existing Routes. Kept as a withdrawn row rather than deleted, because the number is cited in this file's own history and because a gap register that silently loses entries cannot be audited. The row names no route and quotes no body, so there is nothing left in it for a checker to excuse — but a withdrawn row is still a *number* the register defines, and a citation resolves against numbers, not against verdicts. So the rule that keeps it inert is written here rather than enforced: **no surface may carry `[contract-gap]` G-9**, and the number is not reused |
| G-10 | 01 shell pill, install in flight — **and 08's 安装并切换**, the other press that promises one — **registered against the runtime install contract** | ~~a server-side install state, and the route that enters it~~ nothing | `POST /api/models/runtime/install` is the idempotent producer. `RuntimeDependency.status.health: installing` survives reload, successful verification settles at `not_started`, and failure settles at `not_installed` with the closed `status.error_key`. §1.0 and §1.9 consume that one machine; any mounted surface observing durable `installing` owns the derived 2s status loop, while a held initiating sequence only decides whether settlement lands at Not started or continues through Starting. Unmount stops the loop; reload owns G-10's first read and restores no intent. |
| G-11 | 09 direct-only home, zero backends — **registered against AgentSupply** | ~~an installation flag per agent backend, and the payload that carries it~~ nothing | Every `GET /api/models/agents` row now carries server-authoritative `cli_present`; the zero-installed state is exactly all rows false. §1.8 derives `installedAgents` once from that field and uses the same set for mode dispatch, rows and the count pill. Source presence is evaluated first so an empty installed set cannot hide retained Sources; only `sources == []` + the empty set enters No backend found. |
| G-12 | 01 upstream card and 06 header, `needs_action` — **registered by frame 12** | ~~the control that replaces a dead credential~~ nothing | §1.11 registers the two repair producers drawn on the source cards: 更换 Key sends the credential-replacement flow to `PUT /api/models/sources/<id>/credential`, and 重新授权 starts `POST /api/models/sources/<id>/reauth`. §1.1 and §1.6 cite that owner instead of pointing at each other. Kept as a registered row so the former absence and its closing frame remain auditable |
-| G-13 | 03 order drawer, chains that already exist — **the route is contracted; its action remains open** | an action that re-applies the current order to chains built before it; ~~the route behind it~~ | `POST /api/models/agents/<backend>/chains/reorder` is the sole explicit operation that reorders every stored Route by the current Source order. It is idempotent, adds/removes/remaps nothing and has no guard, closing the wire half. Frame 03 still draws only order editing, so no registered control invokes that route; §1.3 keeps the surface half `[contract-gap]` G-13 rather than silently attaching it to 保存顺序. |
+| G-13 | 03 order drawer, chains that already exist — **registered by the global priority save** | ~~an action that re-applies the current order to chains built before it~~ ~~the route behind it~~ | `POST /api/models/agents/<backend>/chains/reorder` is the sole explicit operation that stores a supplied Source order and reorders every stored Route by it. The combined mutation is idempotent, adds/removes/remaps nothing and has no guard; a failure leaves the drawer draft untouched for retry. |
| G-14 | 08 adopt-gateway confirm, `effects.1` — **registered against the mode transaction** | ~~the adoption itself: turning the backend's existing CLI login into that backend's first `native_cli` Source~~ nothing | A qualifying `direct` → `hub` mode `PATCH` now atomically adopts the recognized CLI login as the first singleton `native_cli` Source and returns the updated `AgentSupply`; an absent or unrecognized login or an existing native Source creates and reorders nothing, and repeats create no duplicate. §1.9's consequence pair states both branches and never treats `cli_present` as recognition evidence; its M5 handoff rereads Sources before the committed result lands because the response cannot carry the possibly created Source. |
| G-15 | 06 source detail, a source's own name and Base URL — **registered by frame 11** | ~~any affordance that edits them~~ nothing | §1.10 registers the overflow action, edit dialog and guarded `PATCH /api/models/sources/<id>` producer drawn in frame 11. Kept as a registered row so the former absence and its closing frame remain auditable |
| G-16 | 01 upstream card and 06 source detail — **registered by frame 11** | ~~any affordance that removes a source~~ nothing | §1.10 registers the overflow action and the source-removal guard dialog drawn in frame 11 for `DELETE /api/models/sources/<id>`. The existing 06 model-row 移除 remains a different operation. Kept as a registered row so the former ambiguity and its closing frame remain auditable |
| G-17 | 04 add-subscription, a flow that expects something pasted back — **registered by the 04 paste-back exhibit** | ~~the field that takes it, and the control that sends it~~ nothing | §1.4 registers `nOgMQ`'s paste-back dialog and its `POST /api/models/oauth/submit` producer. The drawn `paste_code` variant supplies the frame geometry; `presentation.expects` selects the registered code or callback-URL copy without changing that geometry. Kept as a registered row so the former absence and its closing exhibit remain auditable |
| G-18 | 05 add-by-key, 拉取型号 and the observation 添加 runs before it saves — **registered against Source observation** | ~~the route that carries a non-persisting observation of a source that does not exist yet~~ nothing | `POST /api/models/sources/observe` accepts `{vendor, base_url?, key, protocol?}` and returns `SourceObservation` without persisting a Source or returning a credential reference. Omission auto-detects; a value restricts observation to one interface and still requires matching response proof. §1.5 consumes its closed outcome/reachability/authentication/protocol/discovery/models facts. |
| G-19 | 05 add-by-key, 取消 pressed while a persisting add is in flight — **registered against the Source-create commit boundary** | ~~what the server is left holding when the cancel lands after the transient phase~~ nothing | Before durable Source commit, AC-26 cleanup completes before cancellation settles. After commit, cancellation ends only the caller's wait: the Source and placements remain committed and the next Source/Agent read owns the outcome. §1.5 registers that boundary instead of promising a post-commit abort. |
-| G-20 | 01 source card and 06 status bar on every Source read — **registered against `Source.adopted_by`** | ~~a *read* that carries `adopted_by`~~ nothing | Every Source returned by `GET /api/models/sources` now carries server-derived, complete, unique `adopted_by`, sorted by backend then menu model. Creation responses echo the same projection at top level. §1.0 owns the grouping/de-duplication rendering and never derives it from chains. |
+| G-20 | 01 source card and 06 status bar on every Source read — **registered against `Source.adopted_by`** | ~~a *read* that carries `adopted_by`~~ nothing | Every Source returned by `GET /api/models/sources` now carries server-derived, complete, unique `adopted_by` for Hub-mode backends, sorted by backend then menu model. Creation responses echo the same projection at top level. §1.0 owns the grouping/de-duplication rendering and never derives it from chains. |
| G-21 | 01 upstream card, 添加订阅 → 04 — **registered by frame 13** | ~~the step that picks which vendor the subscription is for~~ nothing | §1.12 registers the vendor menu drawn in frame 13. Claude 订阅 passes `anthropic` and ChatGPT 订阅 passes `openai` into §1.4 before that dialog renders its vendor-specific title, options and `POST /api/models/oauth/start` request. Kept as a registered row so the producer/consumer break and its closing frame remain auditable |
| G-22 | 06 for a source just added — the add flow's terminal, reached from §1.4's *Awaiting sign-in* and §1.5's ② | an element that renders `added_to` | **The contract answers a question no frame asks.** `POST /api/models/sources` and the `create` OAuth terminal both return `added_to: AddedTo[]`, an entry naming `backend`, `menu_model`, `source_id`, `model_id` and `position`, the last one-based in the persisted Route chain after commit `[contract]`. Add-time placement (`model-hub.md` §4.2) is what makes it worth showing: the source the user just added has been written into chains they did not open, and this array is the only statement of where. Unlike persisted `Source.adopted_by`, `added_to` has one-response lifetime: later Source and Agent reads carry no placement report, so the landing cannot be recovered by a later read. Nothing in this document claims to render it; §1.3 names this number rather than specifying an element, because §0.2 leaves drawing to the frame |
| G-23 | `Qp6FI`, the shared guarded-change confirm — both callers, §1.6's *Refetch refused* and *Guard refused* | a body block that lists `would_interrupt` | **The refusal carries a list and the dialog draws a sentence.** `would_interrupt` is `SupplyGap[]`, each entry `{backend, model_id, agents}` with `model_id` the protected **menu** model and `agents` the enabled named Vibe Agents that pinned it `[contract]`, and `model-hub.md` requires that 「the confirm copy names affected Agents when any exist」. `Qp6FI` as measured has exactly one label, one count pill, one row list and one hint line, and all four are the `would_remove_hops` side; the only rendering of the gap array is `guard.hint.interrupt`, one sentence that reports the array is non-empty. The strings are specified — `guard.gap.label`, `guard.gap.subject`, `guard.gap.agents`, with `gateway.modelCount` as the pill — because copy is this document's register and an authority requires these; the block that holds them is drawing, so it is a gap rather than an invention. The same absence makes `source_last_supplier` unrenderable: its `api.md` example carries `would_remove_hops: []` beside a populated `would_interrupt`, which this dialog would draw as an empty list under a bare sentence |
| G-24 | 01 run pill, *Unsupported host* — **registered against RuntimeDependency** | ~~a host-platform or installability discriminator in the runtime payload~~ nothing | Every runtime response now carries server-authoritative `host_platform`; an exact match in `manifest.assets[].platform` is the support predicate. §1.0 never substitutes the browser platform. |
| G-25 | 01 gateway group, the unavailable marker — **registered against AgentSupply model supply; collapse ownership retired 2026-08-23** | ~~a per-model fact that separates a chain with a live hop from one whose hops are all stale~~ nothing | `model_supply[].has_runnable_hop` now carries that server-derived fact under the same runnability axiom as AgentChain. §1.1 uses it only to choose the row marker: a nonempty chain with no runnable hop renders `legend.unavailable`; the forced-false `chain_length: 0` subset branches first to the existing `models.launch.route_unconfigured` treatment instead of borrowing paused-supply copy. The six-row prefix owns collapse independently of this field. |
-| G-26 | 03 order drawer, a reorder — **registered against the same explicit reorder contract as G-13** | ~~a policy value that reads the stored Source order~~ nothing | `POST /api/models/agents/<backend>/chains/reorder` consumes the current Source-order sequence with a stable total sort over every stored Route. The order PUT remains chain-byte-identical; invocation is explicit and separate. |
+| G-26 | 03 order drawer, a reorder — **registered against the same explicit reorder contract as G-13** | ~~a policy value that reads the stored Source order~~ nothing | `POST /api/models/agents/<backend>/chains/reorder` stores the supplied Source-order sequence and applies a stable total sort over every stored Route in the same mutation. A source outside the order remains a later Route hop when it is already configured there. |
| G-27 | 05 add-by-key, the persisting `POST /api/models/sources` — **registered against `source-create.schema.json`** | ~~the request shape that route accepts~~ nothing | The schema is the complete request: required `vendor` and write-only `key`; optional `display_name`, `base_url`, `protocol`, `client_nonce` and `accept_unavailable_inventory` `[contract]`. The client-selected protocol is a one-interface probe constraint, never response proof or discovered inventory. §1.5 sends the consent boolean true only from ⑤, where a repeated observation still has to prove the protocol before a failed inventory may commit. |
| G-28 | `Qp6FI` guarded-change hop rows — **registered against `RouteHopRef.position`** | ~~the hop's position, on the reference the refusal returns~~ nothing | `guard-refusal.schema.json` carries one-based pre-mutation `position` on every `RouteHopRef`. §1.6 and §1.10 render it directly and issue no per-chain lookup. |
| G-29 | 05 add-by-key, ⑦'s lost-response reconciliation — **registered against Source-create nonce totality** | ~~anything the client holds *before* the send that the committed Source can afterwards be recognized by~~ nothing | The client generates `SourceCreate.client_nonce` before send. A list read finds exact `Source.client_nonce` after commit; in-flight and committed retries return distinct `409` conflicts, released/list-miss retries are fresh. A committed retry never replays an old response; it returns `source_nonce_conflict` and the client rereads the list to claim the Source. |
@@ -425,8 +427,9 @@ verification — neither side is careless, and neither can be found by reading o
global, or one subset per backend?* The frames drew one product-global order with
native sources held out of it (「全局顺序」, 「跟随全局顺序」, 「全局 #n」, and 03's
「不参与排序」 section); `model-hub.md` §3 at the spec lane's head defines 来源顺序 as
-an ordered subset eligible for **one backend** and 「never product-global」, bans 优先级
-as a global noun, and computes the order by a rule whose first step *includes* the
+an ordered subset eligible for **one backend** and 「never product-global」, bans a
+standalone 优先级 as a global noun, and computes the order by a rule whose first step
+*includes* the
native singleton. The owner ruled for the behaviour spec, and frame 03 was rebuilt as a
per-backend editor. What that editor contains is §1.3's to state — and it has changed
once since, because the first rebuild carried a follow-versus-custom ownership state
@@ -557,7 +560,7 @@ list is supposed to empty — by being decided elsewhere:
`AgentSupply.sources`, the backend's stored Source order; source cards read
`adopted_by`; the stored chain is a third projection owned by §1.2; **none may stand in
for another**. D-28 carries the rule, the reason, the restatement that the Source order
- is an add-time placement default and never a runtime filter, and the note that S-1
+ is a backend priority and never a runtime capability filter, and the note that S-1
deleted the field the ruling originally named.
One earlier item left the same way: takeover-count agreement across grains landed as
@@ -731,8 +734,9 @@ promise is how a user ends up with the same source listed twice. So the promise
what the evidence covers, and 重试 out of a no-answer failure re-reads the collection it
was writing into before it re-sends — a row already sitting there closes as the success it
is, rather than colliding with itself. An unguarded idempotent replacement may owe nothing
-extra: §1.3's 保存顺序 sends one array to one route, and sending it twice lands the same
-order. §1.2 is deliberately different even though it also replaces an array: the write
+extra: §1.3's 保存顺序 sends the same complete order to the atomic chains/reorder
+operation, so retrying the save lands the same result without a persisted half-state.
+§1.2 is deliberately different even though it also replaces an array: the write
has a guarded plan and response-only impact evidence, so D-36 reads the exact Route before
any resend and an inferred commit marks that evidence unavailable. Which side a state
falls on is decided by the producer's identity/guard/response semantics, not by the F1
@@ -804,7 +808,7 @@ state exit; held intent never bypasses the evidence column.
| §1.0 | Status unread | Status request fails with no retained live snapshot | F2; H1 retains any initiating sequence | `shell.unread`, `shell.closed.unread.*` | Internal configuration remains hidden until a live `ok` / `degraded` snapshot is available. A retained live snapshot may remain visible under F2, but the switch is disabled because the read is not authoritative |
| §1.0 | Partial | Sources load, per-backend supply does not | F1 on a first paint, in the region the group rollups would have filled; F2 on any later read, which keeps the rollups already drawn | `gateway.supply.unread`, `gateway.retry` on a first paint; `—` on a later one, which states nothing new because nothing it was showing changed `[derived]` | 重试 → the supply read runs again and what comes back decides, read against the source list this page is already holding (D-33): a reading with at least one source → Ready, or whichever rollup §1.1 names for it; a reading while `sources == []` → Empty (no sources), which a first-paint retry reaches whenever the list that succeeded beside it was the empty one; another failure → back here |
| §1.0 | Sources unread | The mirror: `GET /api/models/sources` fails while `health` and per-backend supply both answer `[derived]` | F1, in the region the list would have filled | `upstream.unread`, `upstream.retry` | The list decides, not the fact that one arrived: 重试 answers with at least one source → Ready, and with `sources == []` → Empty (no sources); a later payload carrying the list is read the same two ways |
-| §1.1 | Ready | Sources + per-backend supply both loaded — the two page-level payloads every group-level element is drawn from. The 当前 lines are members of one third, per-backend chain-collection read, owned by Chain unresolved below, and this state neither waits on it nor fails with it | F5 | `gateway.group.subtitle.direct`, `gateway.group.subtitle.gateway`, `gateway.group.mode.direct`, `gateway.group.mode.gateway`, `gateway.group.status.ok` | Card → 06; 来源顺序 → 03; model row → 02; 切换到网关 → 10; 切换到直连 → Leaving the gateway; collapse row → Group expanded |
+| §1.1 | Ready | Sources + per-backend supply both loaded — the two page-level payloads every group-level element is drawn from. The 当前 lines are members of one third, per-backend chain-collection read, owned by Chain unresolved below, and this state neither waits on it nor fails with it | F5 | `gateway.group.subtitle.direct`, `gateway.group.subtitle.gateway`, `gateway.group.mode.direct`, `gateway.group.mode.gateway`, `gateway.group.status.ok` | Card → 06; 来源顺序 → 03; model row → 02; 切换到网关 → 10; 切到直连 → Leaving the gateway; collapse row → Group expanded |
| §1.1 | Empty | `sources == []` | F5 | `upstream.empty` | 添加订阅 → 13, then a vendor row → 04; 添加 API Key → 05 |
| §1.1 | Loading | First paint | → §1.0 Unreachable / §1.0 Sources unread / §1.0 Partial — the same three §1.0 disperses first paint into, because this row is that same first paint seen from the module | — | The payload decides where it lands, not the fact that it arrived — the same reading §1.0 makes one module up: `sources == []` → Empty; anything else → Ready, whose per-source and per-group rows below are drawn from that same payload |
| §1.1 | Per-source `cooldown` | Source reports cooling `[spec §4.5]` | F5 — a rendered report, not a request | `upstream.state.unavailableRetry` while `retry_at` is still ahead, `upstream.state.unavailableDue` once it has passed `[derived]`, `legend.unavailable` | A later payload reports the source in a different state → that state. `retry_at` is when it becomes worth asking again, not evidence that asking worked, so nothing here promotes the source on a clock — and the two keys are that same fact said in copy: the clock running out changes the sentence and not the state |
@@ -825,7 +829,7 @@ state exit; held intent never bypasses the evidence column.
| §1.1 | Serving past a blocked head | The serving hop is not the head, and the head is blocked by something waiting does not clear — **stated as the negation of the row above, not as a list of causes.** `runnable = health-permits AND process-available` `[contract]`, so a head is here whenever it is not runnable and its block is not a recoverable quota/cooldown or live connection-backoff reason: the head's source reading `needs_action` or `error`, a source that is `healthy` while the native CLI it needs is unavailable in this process (`reason: native_cli_unavailable` `[contract]`), and a head the chain reports as `source_missing` or `model_unsupported` `[contract]`. Defined by negation because the set of non-self-healing blockers is the contract's to extend, and a row enumerated by cause has to be reopened every time it does | F5 | `gateway.group.status.degraded` | The head becomes runnable again → Ready; the head enters a recoverable quota/cooldown or live connection-backoff while a later hop serves → Takeover active. Both are readings of a later payload and neither is a clock (D-16) — including the user-cleared blocks, which are reported by the same read as the rest |
| §1.1 | Chain unresolved | Row grain, not group. The backend chain collection is outstanding, failed or refused, or omitted this row, while the two page payloads are in hand | F2 read at row grain — the group keeps everything those two payloads drew. A page-grain `chain_length: 0` row keeps `models.launch.route_unconfigured`; otherwise a row whose `has_runnable_hop` is true renders `—` in its three derived columns and a false row keeps `legend.unavailable` in the current-text slot. Every case renders `—` only in the other unresolved columns. The engine is not implicated and nothing on the head changes | `models.launch.route_unconfigured` for the empty Route; `legend.unavailable` only for a nonempty false row | Its collection member answers → Ready, Takeover active, Per-model route unconfigured or Per-model supply paused. What re-issues it is the collapse row (D-35): collapsing and re-expanding the group re-reads the backend collection once, and it is the drawn control this row's repair uses, there being no per-row 重试 on the frame. The two triggers beside it are the page's own — any mutation that re-renders the group (*Ready* above) and the next load — so a row that failed is never waiting on a request nobody will send |
| §1.1 | Group expanded | Collapse row activated | F5 | `gateway.collapse` | Collapse toggled back → Ready |
-| §1.1 | Leaving the gateway | 切换到直连 pressed on a gateway group `[frame]` D-30 — `PATCH /api/models/agents/<backend>/mode` | F1, in place on the group head | `gateway.switchToDirect`, `gateway.fail.switchToDirect`, `gateway.retry` | Success → the group re-renders in its 直连 form; when it was the last gateway backend the page is decided by the sources that are still there, not by the switch — no source left → 09, at least one source retained → **01**, which is §1.8's own *Retained sources* branch and not this frame; a failure keeps the group on the gateway and puts the line and 重试 on the group head, which is the slot the re-rendered form would have used |
+| §1.1 | Leaving the gateway | 切到直连 pressed on a gateway group `[frame]` D-30 — `PATCH /api/models/agents/<backend>/mode` | F1, in place on the group head | `gateway.switchToDirect`, `gateway.fail.switchToDirect`, `gateway.retry` | Success → the group re-renders in its 直连 form; when it was the last gateway backend the page is decided by the sources that are still there, not by the switch — no source left → 09, at least one source retained → **01**, which is §1.8's own *Retained sources* branch and not this frame; a failure keeps the group on the gateway and puts the line and 重试 on the group head, which is the slot the re-rendered form would have used |
| §1.2 | Loading route | A model row opens 02 with the exact `(backend, menu_model)` held; `GET /api/models/agents/<backend>/chain?model=<id>` owns the dialog body | F1 → Route unread | `route.title`, `route.loading`, `route.cancel` | ET-1–ET-4, ET-8a and ET-18a own opening, response dispatch, focus, retry and the non-mutating exit; an unlisted answer cannot leave this state |
| §1.2 | Route unread `[derived]` | The dialog-owned opening chain read failed while the containing page remains mounted | F1, in place | `route.fail.read`, `route.retry`, `route.cancel` | ET-3/ET-4/ET-8a own entry, Retry and the non-mutating exit; the independent dialog read never rewrites the held page row |
| §1.2 | Ready | The exact AgentChain is held and the local pair projection is byte-identical to its opening `chain` | F5 | `route.title`, `route.section`, `route.addHop`, `route.reorder`, `route.hint`, `route.cancel`, `route.save`; `route.removeHop` / `route.grip` when `hops` is nonempty; `route.empty` only when it is empty; `route.add.none` when no candidate remains; `route.add.source`, `route.add.model`, `route.add.search`, `route.add.confirm` while the Add selector is open, and `route.add.noMatch` only while a typed filter excludes every candidate; `route.sourceMissing` only on a hop whose authoritative chain annotation reads `reason: source_missing`; `route.reorder.grabbed`, `route.reorder.position`, `route.reorder.dropped`, `route.reorder.cancelled`, `route.reorder.sorted`, `route.reorder.unchanged` only for their registered live-region event | ET-5a–ET-7f, ET-8a and ET-9a own every selector, local edit, grab, exit and submission edge |
@@ -843,7 +847,7 @@ state exit; held intent never bypasses the evidence column.
| §1.3 | Zero eligible sources | No source is eligible for this backend | F5 | `order.empty.noEligible` | 关闭. A source becomes eligible → Ready. 保存顺序 is disabled |
| §1.3 | Empty order, held-out sources remaining | The ordered section is empty and the held-out section is not | F5 | `order.empty.ordered` | 排进来 → Dirty. 保存顺序 stays enabled — an empty order is a real configuration |
| §1.3 | Dirty (uncommitted moves) | 排进来, 移出, a drag, or a keyboard move | F5 — nothing has been sent, so nothing can fail | `order.action.include`, `order.action.exclude` | 保存顺序 → Saving; 取消 → discard, close |
-| §1.3 | Saving | 保存顺序 pressed — the whole order in one `PUT /api/models/agents/<backend>/sources` with `{order: string[]}` `[contract]`, which stores and re-echoes it and touches no chain | F1 | `order.save`, `order.fail.save`, `order.retry` | Success → close; 重试 → Saving again, with every move still held |
+| §1.3 | Saving | 保存顺序 pressed — send `{order: string[]}` to `POST /api/models/agents/<backend>/chains/reorder`, which stores the order and applies it to existing Routes in one mutation `[contract]` | F1 | `order.save`, `order.fail.save`, `order.retry` | Success → close; failure → keep every move held and 重试 the same save |
| §1.4 | Default | A frame 13 vendor row has supplied the vendor | F5 | `addSub.title` … `addSub.hint.chatgpt` | The recommended option is pre-selected; selecting the other replaces it. 去登录 synchronously preallocates PD-1's blank browser context, then sends `POST /api/models/oauth/start`; RR-1/RR-2 classify any accepted flow **before** presentation: non-terminal transfers the context to PD-2, then `presentation.expects: none` → Awaiting sign-in, a paste presentation in E3a `starting` / `awaiting_action` → Awaiting paste-back, and a paste presentation already in E3b `verifying` → Awaiting paste-back completion; each navigates when `presentation.auth_url` is non-null now or on a later flow read. Terminal → immediate status read with no form reopened. Refused because that backend already holds its one `native_cli` Source `[contract]` → Already bound, and any other answer that is not a flow → Start failed; either path closes an unused blank context. Polling, re-render and reconciliation never auto-open a second context `[derived]` |
| §1.4 | Second pass `[derived]` | Re-opened while this backend already holds its one `native_cli` source `[contract]` | F5 | `addSub.opt.added` | The native row is inert whichever account that source holds; the hub row stays choosable and is selected on open, whatever the recommendation says |
| §1.4 | Awaiting sign-in | An acquired flow carries `presentation.expects: none` and no `device_code`; Form B remains G-33. `GET /api/models/oauth/status/<flow_id>` is polled every 2s until the §1.4 evidence-class matrix selects an exit `[contract]` | → OAuth failed / OAuth materialization failed. E2 transport/outage evidence, including `engine_down`, is inconclusive and the next 2s tick retries under the same bound (D-16); E4 or E8/E9 with the held Source present/unread stops at OAuth failed; only E6's two materialization codes stop at OAuth materialization failed | `addSub.signIn`; PD-4 resolves `presentation.instructions_key` and uses the device-code helper on null or lookup failure | PD-2 keeps the authorization link actionable. E5 `success` → `intent: create` closes **into 06 for the source that terminal names** with `added_to` and `adopted_by` in hand; `intent: reauth` → §1.11's R3 repair terminal `[contract]`; E4 → OAuth failed; E8/E9 first run RR-5's registered read, then absent → M0 / Source gone, present or unread → OAuth failed (the unread branch retains read-only Retry); E7 → M0 / Source gone; the polling bound passes with no terminal reading → OAuth failed — the bound is `OAuthFlow.expires_at` when the flow carries one `[contract]` and 15 minutes from acquisition when it does not `[derived]`; dismissed any of the three ways → Dismissing |
@@ -877,14 +881,14 @@ state exit; held intent never bypasses the evidence column.
| §1.6 | Refetching | 重新拉取 pressed — `POST /api/models/sources/<source_id>/refresh`, guarded | F3 when the response is a guard refusal, F2 otherwise → Refetch failed | `sourceDetail.action.refetch` | Any answer this page can read → Refetch result, **whatever the row count comes back as, none included**. An emptying refetch is not a different kind of answer, and it is the one where the diff is worth most: every id the source used to advertise has just left the discovered slice, so it is where `sourceDetail.refetch.removed` names the largest set it will ever name. Leaving straight for Empty (no models) — as this row read until this round — dropped that report at that exact moment, and replaced it with a sentence that says a fetch returned nothing and not what stopped being there. The empty table is still an empty table: *Refetch result* renders `sourceDetail.empty` under the removal line, and of §1.6's two empty readings only that one is reachable from here, since this refetch completing is what makes `last_discovered_at` non-null. It is where *Refetch result* lands rather than what this state enters; a refusal → Refetch refused |
| §1.6 | Refetch result `[derived]` | A refresh came back usable — the response carries the complete updated source `[contract]`, and this page still holds the list it was rendering, so what changed is a comparison of two payloads it has | F5 — the request already succeeded | `sourceDetail.refetch.added`, `sourceDetail.refetch.removed`, `sourceDetail.refetch.unchangedOnly`, and the keys for whatever the table now is: Ready's own while any row is left, `sourceDetail.empty` when the answer emptied it. The diff line and the table's own copy are two statements about one payload, and the second never cancels the first | Any next action, or the next load → Ready, or → Empty (no models) when the answered list was empty: the diff is a report about one fetch and nothing re-derives it, so what remains afterwards is the table's own reading. 重新拉取 again → Refetching |
| §1.6 | Refetch refused | The refresh came back refused, naming the hops a shorter inventory would remove | F3 — `Qp6FI`, the same confirm this page already starts for a removal | `guard.title.refetch`, `guard.subtitle.refetch`, `guard.confirm.refetch`, `guard.label`, `guard.count`, `guard.hop.position`, `guard.hint.safe`, `guard.hint.interrupt`, `guard.gap.label`, `guard.gap.subject`, `guard.gap.agents`, `gateway.modelCount`, `guard.cancel` | 仍要拉取 re-sends the same `POST` with `force` → Refetching; 取消 restores the exact held §1.6 origin by C5 |
-| §1.6 | Refetch failed | The refresh came back a classified failure, **or never answered at all** — F2's own 「otherwise」 lands both here. For the classified one `api.md` has the server update the **source-global state**, preserve the last successful model list and timestamp, and return the normal safe error `[contract]`, so the source changed state and the answer does not carry which. For a lost answer even that is not known: F1's rule leaves the outcome unknown, and a refresh that did commit has already replaced the discovered inventory — on the `force` path, after removing the hops the guard named | F2 lands here. The **previous list is kept only where the contract keeps it**, which is the classified branch and is the contract's guarantee rather than this page's choice; a lost answer guarantees nothing, which is why the re-read below is a reconciliation and not a status refresh | `sourceDetail.fail.refetch`; the status word is not this row's and comes from whichever state the re-read below lands on | The failure line goes on the bar, and the page re-reads `GET /api/models/sources` — the only read that answers with this source, there being no single-source route `[contract]`. **That read settles the mutation as well as the status**, because the page has held `source_id` since it sent the refresh and the list answers with the complete `Source`, models included `[contract]` (D-36): what it renders afterwards is that source as read, so a refresh that committed unseen is visible rather than papered over by the list this page was holding. The state it finds dispatches through this section's own status mapping: `cooldown` → Cooling, `needs_action` → Needs action, `error` → Unclassified error, `standby` or an `active` nothing adopts → Not supplying, an adopted `active` → Ready. The source absent from that list → Source gone. The re-read itself failing → the bar keeps the status word and the page keeps the list it was already rendering, a failed read being no reading at all (D-16), and the line above stays true of both. 重新拉取 stays enabled throughout → Refetching |
+| §1.6 | Refetch failed | The refresh came back a classified failure, **or never answered at all** — F2's own 「otherwise」 lands both here. For the classified one `api.md` has the server update the **source-global state**, preserve the last successful model list and timestamp, and return the normal safe error `[contract]`, so the source changed state and the answer does not carry which. For a lost answer even that is not known: F1's rule leaves the outcome unknown, and a refresh that did commit has already replaced the discovered inventory — on the `force` path, after removing the hops the guard named | F2 lands here. The **previous list is kept only where the contract keeps it**, which is the classified branch and is the contract's guarantee rather than this page's choice; a lost answer guarantees nothing, which is why the re-read below is a reconciliation and not a status refresh | `sourceDetail.fail.refetch`; the status word is not this row's and comes from whichever state the re-read below lands on | The failure line goes on the bar, and the page re-reads `GET /api/models/sources` — the only read that answers with this source, there being no single-source route `[contract]`. **That read settles the mutation as well as the status**, because the page has held `source_id` since it sent the refresh and the list answers with the complete `Source`, models included `[contract]` (D-36): what it renders afterwards is that source as read, so a refresh that committed unseen is visible rather than papered over by the list this page was holding. The state it finds dispatches through this section's own status mapping: `cooldown` → Cooling, `needs_action` → Needs action, `error` → Unclassified error; `active` or `standby` with no Hub-mode backend adopting it → Not supplying, and either status with a Hub-mode backend adopting it → Ready. The source absent from that list → Source gone. The re-read itself failing → the bar keeps the status word and the page keeps the list it was already rendering, a failed read being no reading at all (D-16), and the line above stays true of both. 重新拉取 stays enabled throughout → Refetching |
| §1.6 | Tiers editing | A row's tier area was activated | F5 — nothing is sent until a tier is committed | `sourceDetail.tiers.add`, `sourceDetail.tiers.inputHint`, `sourceDetail.tiers.empty`, `sourceDetail.tiers.addFirst` | Enter, or a chip's × → Tier commit; Enter on an empty input, or on a value this row already carries, commits nothing and stays here — `minLength: 1` and `uniqueItems` `[contract]`; blur / Escape → Ready, discarding whatever is still uncommitted in the input |
| §1.6 | Tier commit | A tier was added by Enter **or** removed by a chip's × — either way `PATCH /api/models/sources/<source_id>/models/<model_id>` carries the complete `reasoning_efforts` list `[contract]` | F1, on the row: the row keeps the pre-request list, states the failure and offers 重试 — an add leaves its text in the input, a removal puts its chip back | `sourceDetail.fail.tier`, `sourceDetail.retry` | Success → the answered list is what the row renders, still in Tiers editing |
| §1.6 | Manual draft | 添加模型 pressed | F5 — a local draft, sent by nothing | `sourceDetail.entry.manual`, `sourceDetail.addRow.hint` | 添加 is enabled only once the id field holds a value this source's table does not already list `[derived]`: blank, whitespace-only, or an already-listed id leaves it **disabled**, the same answer 「Tiers editing」 gives an empty or duplicate tier, and `sourceDetail.addRow.hint` is what the row states meanwhile. Enabled 添加 → Manual commit; 取消 discards the row and nothing is persisted |
| §1.6 | Manual commit | 添加 pressed on an enabled 添加 — `POST /api/models/sources/<source_id>/models` | F1, on the draft row: **the row and everything typed in it are kept**, and the primary becomes 重试 | `sourceDetail.fail.addModel`, `sourceDetail.retry` | Success → the row becomes an ordinary 手动添加 row → Ready |
| §1.6 | Removing a manual entry | The row menu's 移除 — `DELETE /api/models/sources/<source_id>/models/<model_id>`, guarded | F3 when the response is a guard refusal, F1 otherwise | `sourceDetail.fail.removeModel`, `sourceDetail.retry`, `sourceDetail.row.remove` | Success → the row is gone → Ready while any row is left; removing the last one → Empty (no models) or Never fetched by `last_discovered_at`, the same two readings §1.6 gives every other empty table |
| §1.6 | Guard refused | The `DELETE` came back refused, naming the hops it would remove | F3 — `Qp6FI`, this product's one guarded-change confirm | `guard.title.removeModel`, `guard.subtitle.removeModel`, `guard.confirm.removeModel`, `guard.label`, `guard.count`, `guard.hop.position`, `guard.hint.safe`, `guard.hint.interrupt`, `guard.gap.label`, `guard.gap.subject`, `guard.gap.agents`, `gateway.modelCount`, `guard.cancel` | 仍要移除 re-sends the same `DELETE` with `force` → Removing a manual entry; 取消 restores the exact held §1.6 origin by C5 |
-| §1.6 | Not supplying | The source is `standby`, or `active` with nothing adopting it `[contract]` | F5 | `upstream.state.standby` | The source starts supplying again — only the bar changes |
+| §1.6 | Not supplying | The source is `active` or `standby`, and no Hub-mode backend adopts it `[contract]` | F5 | `upstream.state.standby` | A Hub-mode backend adopts the source — only the bar changes |
| §1.6 | Cooling | The source is `cooldown` `[contract]` | F5 | `upstream.state.unavailableRetry` while `retry_at` is still ahead, `upstream.state.unavailableDue` once it has passed `[derived]` | A later payload reports the source in another state → that state; `retry_at` passing is not that payload — it changes which of the two keys the bar renders and nothing else. Separate from *Not supplying* because the two answer different questions — standby says nothing is drawing from this source, cooling says nothing *can* yet and names when that changes. This section's own status mapping gives `cooldown` the gold `upstream.state.unavailableRetry`; a row that folded it into the muted standby word dropped the one fact the mapping exists to carry |
| §1.6 | Needs action | The source is `needs_action` `[spec §4.5]` | F5 | `sourceDetail.status.needsAction.oauthExpired`, `sourceDetail.status.needsAction.balanceExhausted`, `sourceDetail.status.needsAction.credentialRevoked`, `sourceDetail.status.needsAction.accountBanned` | The reported cause clears. The bar states which cause `state.detail_key` carries and the table stays live; frame 12 owns the card-level repair controls, while this page keeps 重新拉取 enabled only when the §1.6 action-capability row renders it |
| §1.6 | Unclassified error | The source is `error` `[spec §4.5]` | F5 | `sourceDetail.status.error` | The source leaves `error`. The bar reads 异常 and claims no cause; the table and every action the capability row renders stay live |
@@ -972,7 +976,7 @@ a different key.
| `{{health}}` | One of exactly five words — `gateway.group.status.ok`, `gateway.group.status.degraded`, `gateway.group.status.waiting`, `gateway.group.status.interrupted`, `gateway.group.status.unused`. The first four are the closed aggregate over `named_agents[].supply_status`; the fifth means no enabled Agent uses this backend. Supply health, not an HTTP status: nothing here is a code, and the group renders it whether or not any request was made. | Always present | `gateway.group.subtitle.gateway` |
| `{{reason}}` | The §1.9 classified cause, from that state's closed and total copy set. No consumer interpolates an upstream string here. Source observation exposes no reason member. | Always present | `adopt.fail.detail` |
| `{{mode}}` | One of exactly two words — `gateway.group.mode.direct` or `gateway.group.mode.gateway`. The subtitle interpolates the word rather than carrying two whole strings, because the health half varies independently of it. | Always present | `gateway.group.subtitle.direct`, `gateway.group.subtitle.gateway` |
-| `{{backends}}` | The backends that have this source configured into a route, by product name, joined by `、` / `,` — `adopted_by`'s projection, grouped and de-duplicated, never a computation over live chains (§1.0). | Always present — `upstream.state.supplying` is entered only when the list is non-empty; a source no backend has configured is 备用 instead | `upstream.state.supplying` |
+| `{{backends}}` | The backends in Hub mode that have this source configured into a route, by product name, joined by `、` / `,` — `adopted_by`'s projection, grouped and de-duplicated, never a computation over live chains (§1.0). | Always present — `upstream.state.supplying` is entered only when the list is non-empty; a source no Hub-mode backend has configured is 可用 · 当前未供给 instead | `upstream.state.supplying` |
| `{{component}}` | The gateway component's name, as the manifest names it `[contract]`. | Always present | `adopt.effects.install`, `install.effects.1` |
| `{{duration}}` | A rough install time — 约 1 分钟 / about a minute. It is an estimate stated as one, never a countdown. | Always present | `adopt.effects.install`, `install.effects.1` |
@@ -1062,12 +1066,12 @@ sections. §1.8 states the direct-only body condition.
| Element | Displays | Data source | Interactive | On activate |
| --- | --- | --- | --- | --- |
-| `title` + info icon | Page name | static | icon: hover, focus **and** activation `[derived]` | Tooltip: `shell.gatewayInfo.body`, which is the icon's accessible description; `shell.gatewayInfo.label` is its accessible name |
+| `title` + info icon | Page name | static | icon: hover, focus **and** activation `[derived]` | Tooltip: `shell.modelsInfo.body`, which is the icon's accessible description; `shell.modelsInfo.label` is its accessible name |
| Run pill | Engine liveness | `runtime-dependency.schema.json` → `status.health` `[contract]` | see the mapping below | see the mapping below |
| Tabs ×3 | Section switch | — | yes | 来源与网关 / 用量 / 日志; the active one gets the mint underline |
-| Upstream module | Source inventory | `GET /api/models/sources` `[spec]` | rows: yes | Open 06 for that source |
+| Upstream module | Source inventory + info icon | `GET /api/models/sources` `[spec]` | info icon and rows: yes | Tooltip: `upstream.info`; open 06 for that source |
| Dispatch rail | That upstream feeds gateway | derived, decorative | no | — |
-| Gateway module | One group per backend, each with model rows | per-backend supply + chains `[spec]` | rows, collapse, 「来源顺序」, mode switch | Open 02 / expand / open 03 for **that backend** / open 10's confirm |
+| Gateway module | One group per backend, each with model rows + info icon | per-backend supply + chains `[spec]` | info icon, rows, collapse, 「调整优先级」, mode switch | Tooltip: `gateway.info`; open 02 / expand / open 03 for **that backend** / open 10's confirm |
| Legend | Colour → meaning | static; kept in bijection with the inks the page draws | no | — |
**The Logs tab owns the switch-history feed** `[derived]`. It is absent from the
@@ -1079,11 +1083,11 @@ An unread feed keeps the card and its retry action distinct from the authoritati
暂无切换记录 empty state. The removed 高级 placeholder has no surviving surface or copy:
request logging and diagnostics must return as real capabilities, not as a dead row.
-**The info icon is a control, and its string is this file's** `[derived]`. Hover is not
-an affordance a keyboard or a touch user has, and this tooltip is the only place the page
-says what the gateway *is* — so the icon is a focusable button, activating it toggles the
-tooltip, Escape dismisses it, `shell.gatewayInfo.label` is its accessible name and
-`shell.gatewayInfo.body` its accessible description. The string is registered here
+**The info icons are controls, and their strings are this file's** `[derived]`. Hover is not
+an affordance a keyboard or a touch user has, and each tooltip explains the title beside it
+— so every icon is a focusable button, activating it toggles the
+tooltip, Escape dismisses it, `shell.modelsInfo.label` is its accessible name and
+`shell.modelsInfo.body` its accessible description. The string is registered here
because no frame carries it, which is the one way this icon differs from §1.1's legend
icon: that note is measured off the frame (§0.2), so that row states the trigger and
this one states the trigger and the text. An explanation reachable only by hover is
@@ -1384,8 +1388,8 @@ unable to outlive its surface, which is the cheaper answer wherever it is availa
| `shell.closed.stopping.body` `[derived]` | 运行时停止期间会隐藏网关配置。 | Gateway configuration is hidden while the runtime stops. |
| `shell.closed.unread.title` `[derived]` | 暂时无法读取网关状态 | Model gateway status unavailable |
| `shell.closed.unread.body` `[derived]` | 确认运行状态前不会显示网关配置。 | Configuration stays hidden until the runtime state can be confirmed. |
-| `shell.gatewayInfo.label` `[derived]` | 什么是网关 | What the gateway is |
-| `shell.gatewayInfo.body` `[derived]` | 网关是本机的一层调度:它持有你添加的来源,按你配置的顺序供给各个 Agent。 | The gateway is a dispatch layer on this machine: it holds the sources you add and supplies them to your Agents in the order you configure. |
+| `shell.modelsInfo.label` `[derived]` | 什么是模型 | What a model is |
+| `shell.modelsInfo.body` `[derived]` | 模型是 Agent 使用的型号。你可以查看每个型号现在能否运行、由谁供给,需要时为单个型号指定路由。 | A model is what an Agent uses to generate a response. You can see whether each model can run, which source supplies it, and set a route for one when needed. |
| `install.title` `[derived]` | 安装网关组件 | Install the gateway component |
| `install.subtitle` `[derived]` | 只安装组件,后端保持现在的方式 | Installs the component only; the backends keep working the way they do now |
| `install.section.effects` `[derived]` | 会发生什么 | What will happen |
@@ -1409,17 +1413,19 @@ unable to outlive its surface, which is the cheaper answer wherever it is availa
| `recent.yesterday` | 昨天 | Yesterday |
| `recent.empty` | 暂无切换记录 | No switches yet |
| `recent.deletedSource` | 已删除 | deleted |
-| `upstream.heading` | 来源 | Sources |
+| `upstream.heading` | 上游来源 | Upstream sources |
+| `upstream.infoLabel` `[derived]` | 什么是上游来源 | What upstream sources are |
+| `upstream.info` `[derived]` | 上游来源是账号或 API Key。网关从这里获取型号,再按路由供给 Agent。 | An upstream source is an account or API key. The gateway gets models from it and supplies them to Agents through routes. |
| `upstream.count_one` | {{count}} 个 | {{count}} source |
| `upstream.count_other` | {{count}} 个 | {{count}} sources |
| `upstream.group.native` | 本机原生 | Native · on this machine |
-| `upstream.group.hub` | 网关持有 | Held by the gateway |
+| `upstream.group.hub` | 接入网关 | Connected to gateway |
| `upstream.kind.nativeCredential` | 原生 · 本机凭据 | Native · local credential |
| `upstream.kind.subscription` | 订阅 | Subscription |
| `upstream.kind.apiKey` | API Key | API key |
| `upstream.state.supplyingNative` `[spec]` | 正在供给 {{backend}}(原生) | Supplying {{backend}} (native) |
| `upstream.state.supplying` `[spec]` | 正在供给 {{backends}} | Supplying {{backends}} |
-| `upstream.state.standby` | 备用 | Standby |
+| `upstream.state.standby` | 可用 · 当前未供给 | Available · not currently supplying |
| `upstream.state.unavailableRetry` | 暂不可用 · {{delay}} 后自动重试 | Unavailable · retrying automatically after {{delay}} |
| `upstream.state.unavailableDue` `[derived]` | 暂不可用 · 已到重试时间 | Unavailable · the retry is due |
| `upstream.state.supplyStopped` `[frame]` | · 已停止供给 | · stopped supplying |
@@ -1447,10 +1453,12 @@ unable to outlive its surface, which is the cheaper answer wherever it is availa
| `upstream.repair.impact.done` `[derived]` | 完成 | Done |
| `upstream.repair.unresolved` `[derived]` | 仍然不可用 | Still not working |
| `upstream.repair.fail` `[derived]` | 没能完成这次凭据修复 | The credential repair did not finish |
-| `gateway.heading` | 网关 | Gateway |
-| `gateway.sourceOrder` | 来源顺序 | Source order |
+| `gateway.heading` | 网关路由 | Gateway routes |
+| `gateway.infoLabel` `[derived]` | 什么是网关路由 | What gateway routes are |
+| `gateway.info` `[derived]` | 网关路由决定每个 Agent 的型号在已有路由中的来源里先使用哪个上游来源;当额度不足、触发限流、服务端、认证或网络出错导致请求无法完成时,自动切换下一优先级。 | Gateway routes decide which upstream source each Agent's model uses first among the sources already configured in its route. When quota, rate-limit, server, authentication, or network failures prevent a request, the next priority is used automatically. |
+| `gateway.sourceOrder` | 调整优先级 | Adjust priority |
| `gateway.switchToGateway` | 切换到网关 | Switch to gateway |
-| `gateway.switchToDirect` | 切换到直连 | Switch to direct |
+| `gateway.switchToDirect` | 切到直连 | Switch to direct |
| `gateway.modelCount_one` | {{count}} 个型号 | {{count}} model |
| `gateway.modelCount_other` | {{count}} 个型号 | {{count}} models |
| `gateway.group.subtitle.direct` `[frame]` | {{mode}} | {{mode}} |
@@ -1468,8 +1476,8 @@ unable to outlive its surface, which is the cheaper answer wherever it is availa
| `gateway.fail.switchToDirect` `[derived]` | 没能切回直连 | The switch back to direct did not go through |
| `gateway.retry` `[derived]` | 重试 | Retry |
| `gateway.group.emptyModels` `[derived]` | 这个后端没有可用型号 | This backend has no models |
-| `gateway.row.current` | 当前 {{source}} | Now: {{source}} |
-| `gateway.row.currentTakeover` | 当前 {{source}}(接管) | Now: {{source}} (takeover) |
+| `gateway.row.current` | 来自 {{source}} | From: {{source}} |
+| `gateway.row.currentTakeover` | 来自 {{source}}(接管) | From: {{source}} (takeover) |
| `models.launch.route_unconfigured` `[contract]` | 模型 {{model}} 尚未配置路由。请前往 Models 配置。 | Model {{model}} has no configured route. Open Models to configure one. |
| `gateway.moreModels_one` | 还有 {{count}} 个型号 | {{count}} more model |
| `gateway.moreModels_other` | 还有 {{count}} 个型号 | {{count}} more models |
@@ -1567,7 +1575,7 @@ different inputs, so a surface that derives one from the other is right by accid
the first `degraded`-without-reroute payload.
**A source's supply line renders `adopted_by`, not the chain** `[contract]`.
-`upstream.state.supplying*` names which backends have this source
+`upstream.state.supplying*` names which Hub-mode backends have this source
**configured into a route** — the same reading §1.6's 使用中 gets one surface over, and
for the same reason. *Stable* is the operative word in the field's own definition: the
array is unchanged by a cooldown, a revoked credential, or a takeover that routes past
@@ -1712,15 +1720,15 @@ dispatch arbitrates → each backend's models resolve to these sources today.
| Element | Displays | Data source | Interactive | On activate |
| --- | --- | --- | --- | --- |
-| `heujA` upstream card | tile icon by kind, name, kind pill, mono detail line, one status line | one source | yes (whole card) | Open 06 for that source |
+| `heujA` upstream card | tile icon by kind, name on its own line, interface and kind pills on the next line, mono detail line, one status line | one source | yes (whole card) | Open 06 for that source |
| `uf3re` detail | account label, or `host/path · masked key` — **and every field it can draw is nullable, so the line is specified by omission, exactly as §0.9 and §1.6 rule the same hole** `[contract]`. `account_label`, `base_url` and `masked_credential` are each `["string","null"]` in `source.schema.json`, so a segment with no value is dropped, never rendered empty and never left behind a dangling `·`; `base_url: null` is the vendor's official endpoint (§0.9's `{{host}}`) and is not synthesized into a hostname (§1.6). When nothing is left the whole line is omitted rather than filled — a subscription that reports no account label is the common case, and the card still identifies itself from four required fields (icon and pill by `kind`, name by `display_name`, state by `state`). Repeating the kind pill or the card's own name here would be the only alternative, and it would say nothing the card has not already said | source | no | — |
-| `YcOFo` status | which backends have this source configured into a route — `adopted_by` (§1.0) | the complete server-derived Source projection, never a computation over chains (D-28) | no | — |
+| `YcOFo` status | which Hub-mode backends have this source configured into a route — `adopted_by` (§1.0) | the complete server-derived Source projection, never a computation over chains (D-28) | no | — |
| `wmROQ` / `Xitl7` footer buttons | Add subscription / Add API key | — | yes | 添加订阅 opens frame 13; its selected vendor opens 04. 添加 API Key opens 05 |
| `f8w6Xp` + `pnYa0` rail | dispatch happens between the columns | decorative | no | — |
| `GLylJ` backend group | backend tile, name, model count, head buttons, and one `{{mode}} · {{health}}` line | per-backend mode + supply health | head: buttons only | — |
-| `ehGRK` / `bGsC7` 「来源顺序」 | — | — | yes | Open 03 **for that backend** |
+| `ehGRK` / `bGsC7` 「调整优先级」 | — | — | yes | Open 03 **for that backend** |
| `IyKyp` 「切换到网关」 | — | backend in 直连 | yes | Open the 10 confirm for that backend |
-| `z02Ep` / `gbrq2` 「切换到直连」 | — | backend on the gateway | yes | That backend leaves the gateway immediately — **no confirm** (D-30) |
+| `z02Ep` / `gbrq2` 「切到直连」 | — | backend on the gateway | yes | That backend leaves the gateway immediately — **no confirm** (D-30) |
| `Exx0a` model row | model id (mono 12), a chain chip, current-source text; `legend.unavailable` occupies that text slot when the page-grain row has no runnable hop | `AgentSupply.model_supply[].has_runnable_hop`; per-model AgentChain and its `current` member | yes | Open 02 for `(backend, model)` |
| `ZM1pm` collapse row | `还有 N 个型号` | count of hidden rows | yes | Expand in place |
| `FZUYI` wire layer | one path per supply relation + endpoint dots | derived supply set | no | — |
@@ -1782,7 +1790,7 @@ exit keys on elapsed time」 is the rule the two source rows above are written t
**The three head buttons are mutually constrained** `[frame]`, and the constraint is
the whole model in one line: a backend is either on the gateway or not. On the gateway
-it carries 来源顺序 + 切换到直连; in 直连 it carries 切换到网关 and **nothing else** —
+it carries 调整优先级 + 切到直连; in 直连 it carries 切换到网关 and **nothing else** —
Claude Code's head has no order button, because a direct backend consults no source
order and an editor there would edit a list nothing reads. D-9a states the rule, and it
is a set equality over the three groups.
@@ -1793,11 +1801,12 @@ rail 72, gateway module takes the rest. Everything inside those tracks is
and never a derived row width — a literal there is a number that goes stale the first
time a track moves.
-**Card and row metrics** `[frame]`: upstream card `fill_container`×80, `padding [0,12]`,
-`gap 10`, `radius 10`; tile 34×34 `radius 9`; name 12.5/700 Inter; detail 10.5
-JetBrains Mono `#9BA3B8CC`; status dot 5px + text 10.5/600. Backend group
-`$--background` fill, `radius 12`, `$--border`; head 66 tall, `padding [0,14]`,
-`gap 7`, bottom border, backend name 14/700 Inter, tile 30×30 `radius 9`, count pill
+**Card and row metrics** `[frame]`: upstream card `fill_container`×96 minimum, auto height,
+`padding [8,12]`, `gap 10`, `radius 10`; tile 34×34 `radius 9`; name 12.5/700 Inter
+on its own line, interface and kind pills on the next line; detail 10.5 JetBrains Mono
+`#9BA3B8CC`; status dot 5px + text 10.5/600. Backend group `$--background` fill,
+`radius 12`, `$--border`; head 66 minimum with auto growth when its action row wraps,
+desktop `padding [4,14]` and mobile `padding [12,14]`, `gap 7`, bottom border, backend name 14/700 Inter, tile 30×30 `radius 9`, count pill
`padding [3,8]` `radius 999`; head button `padding [9,12]` `radius 8` fill
`#FFFFFF0A` stroke `$--border-strong`, label 11.5/700; head status line dot 5px +
11/600 + 13px info `#FFFFFF40`. `rows` container `padding 8`, `gap 8`; model row 36
@@ -1980,7 +1989,8 @@ under an explicit user gesture and produces only that one local draft: it never
placement or matching. The per-model write body remains only explicit `hops`; Source order
is neither sent nor interpreted by that route. This control never calls
`POST /api/models/agents/<backend>/chains/reorder`, because that route changes every
-stored Route and no frame here registers that broader action (G-13).
+stored Route. Frame 03's global-priority save owns that broader action (G-13); this
+control only sorts the one route draft held by frame 02.
**Save sequencing is total** `[contract]` `[derived]`:
@@ -2229,7 +2239,7 @@ cannot name the reducer/CA result for one row is incomplete.
| RT-2 — M6 chain becomes Direct | AR-M has installed Hub Agents; its chain member returns `direct_mode` | AR-MD provisionally removes prior Route work, preserves independent successes and uses ET-18aM/ET-18aP to acquire landing Agents authority. Direct keeps Route not applicable; Hub acquires a new post-landing chain epoch |
| RT-3 — Direct after Source success | Source settles successfully before either AR-D5 or AR-MD | Keep that Source installed/carried; disown only pending siblings. The landing Agents result, not the Direct error, selects the page form |
| RT-4 — active Retry loses admission | Activate Retry in save reconciliation, mounted M6, transferred M6 or error-handoff page phases | CA synchronously moves focus to the destination phase's first FF-1-valid owner before disabling/inerting Retry; ET supplies no competing focus patch |
-| RT-5 — local Source-order draft sort | Activate frame-02 sort, then save its explicit pairs | Follow `model-hub.md` §4.2/§4.6 and `api.md`'s negative fixture: the local gesture may reorder the draft; the per-model PUT transmits only explicit `hops`, its server path never reads `sources.order`, and G-13 remains open for the all-chain producer |
+| RT-5 — local Source-order draft sort | Activate frame-02 sort, then save its explicit pairs | Follow `model-hub.md` §4.2/§4.6 and `api.md`'s negative fixture: the local gesture may reorder the draft; the per-model PUT transmits only explicit `hops`, its server path never reads `sources.order`; frame 03 separately applies the global priority through the all-chain reorder operation |
| RT-6 — Hub landing closes Sources | DM-1–DM-3 owns the landing Agents read; before it settles another client completes Direct → Hub and atomically creates a native Source | LF-H installs exact Hub AgentSupply, invokes M5's Source read outside M6 and calls the landing current only after that read. Failure keeps AgentSupply, marks only Sources stale and retries only Sources |
| RT-7 — CA activation modality | For every enabled CA row, activate its control once by pointer, Enter and Space; repeat for disabled/inert rows | All three enabled gestures emit that row's one `Activation`, including CA-P1 → ET-18c. Every disabled/inert gesture emits nothing; no keyboard enumeration may restate CA IDs |
| RT-8 — DM-2 unknown crosses ordinary M5 | Route PUT returns shaped `direct_mode`; LF-D installs Direct; the ordinary §1.9 mode PATCH later returns exact Hub | DM-2 creates `(unknown, page session, Direct-suspended)` before modal handoff. M5/LF-H closes Source, the common hook changes legality and RO-O sends exactly one chain GET: match enters M6; nonmatch installs current Route and remains page-owned unknown; neither branch sends PUT |
@@ -2522,7 +2532,7 @@ shared `models.hub.guard.*` owner.
| `reorder.cancelled` `[derived]` | 已取消重排,恢复到第 {{position}} 跳。 | Reorder cancelled. Restored to hop {{position}}. |
| `reorder.sorted` `[derived]` | 已按来源顺序重排。 | Reordered by Source order. |
| `reorder.unchanged` `[derived]` | 路由链已经符合来源顺序。 | The route chain already matches Source order. |
-| `hint` `[frame]` | 这条链是写下来的配置。以后来源顺序怎么变,它都不变。 | This chain is stored configuration. Later Source-order changes do not change it. |
+| `hint` `[frame]` | 这条链是写下来的配置。以后调整来源顺序时,其中的来源会按新的顺序重排。 | This chain is stored configuration. Later Source order changes reorder its hops to match. |
| `empty` `[derived]` | 这条路由链是空的。添加一跳,或保持为空配置。 | This route chain is empty. Add a hop, or leave it unconfigured. |
| `removeHop` `[derived]` | 移除这一跳 | Remove this hop |
| `grip` `[derived]` | 调整这一跳的顺序 | Reorder this hop |
@@ -2551,21 +2561,16 @@ shared `models.hub.guard.*` owner.
### 1.3 Frame 03 `qZhJ3` — Source-order drawer (per backend)
-**The question it answers:** *for one backend, which sources is the gateway willing to
-draw on, and in what order does the user keep them?* One ordered list, scoped to one
-backend — the list add-time placement writes into, not a value any current policy reads
-back out.
-
-**It governs placement configuration, not execution** `[spec]` S-1. A chain is stored
-configuration executed exactly as stored, so saving this list reaches no turn and changes
-no existing chain. `PUT /api/models/agents/<backend>/sources` owns only the stored order.
-The separate contracted consumer is explicit:
-`POST /api/models/agents/<backend>/chains/reorder` applies the current Source-order
-sequence to every stored Route with a stable total sort, without adding, removing or
-remapping a hop `[contract]`. Frame 03 draws no control for that operation, so 保存顺序
-never invokes it implicitly. This separation closes G-26 and G-13's wire half while
-keeping G-13's missing producer `[contract-gap]`; it preserves the frame's promise that
-an order edit itself is non-destructive.
+**The question it answers:** *for one backend, which upstream sources should the gateway
+try first, and what should it try next when the first one cannot serve the request?* One
+ordered list, scoped to one backend, controls both the persisted priority and the order
+of that backend's existing Route hops.
+
+**It governs global route priority** `[spec]`. `POST /api/models/agents/<backend>/chains/reorder`
+stores the supplied complete order and applies the current Source-order sequence to every
+stored Route with a stable total sort, without adding, removing or remapping a hop
+`[contract]`. The combined mutation is atomic; if it fails, the drawer keeps the draft and
+retries the same save, so no partial success is presented as complete.
The scope in that sentence is the whole point of the frame, and it is what the frame
used to get wrong. An earlier version drew one product-global order with native
@@ -2574,7 +2579,7 @@ eligible for **one backend** and never product-global. The owner ruled for the
behaviour spec and the frame was rebuilt. See §0.6 E-1 — kept as a closed conflict
rather than deleted, because the resolution went against the drawing.
-**Entry point.** The 来源顺序 button on a backend's group head in the gateway module
+**Entry point.** The 调整优先级 button on a backend's group head in the gateway module
— `ehGRK` on Codex, `bGsC7` on OpenCode in frame 01, redrawn as `N50iJ7` / `nzwR3` in
03's own dimmed background `[frame]`. **A backend in 直连 mode has no
such button** — Claude Code's head carries only 切换到网关 `[frame]`. This is not an
@@ -2604,30 +2609,18 @@ rule, and it is a set equality.
**The ordinal badge inks the first position, and only the first** `[frame]`. Rank 1 is
mint; every later rank is the muted neutral. Mint here is **control ink, not relation
-ink** (§1.0): it means *first in this stored order* — a position in the list this drawer
-writes, and nothing past it. Not a starting point anything walks, and not a claim about
-which source is carrying traffic. The badge moves only when the order is edited
-`[derived]`.
+ink** (§1.0): it means *first in this stored order*. On save, the explicit
+`chains/reorder` operation uses that order to sort each existing Route's hops; the badge
+still does not claim that this source is healthy or carrying the current request. The
+badge moves only when the order is edited `[derived]`.
**This drawer must not claim live supply, and the reason is the contract, not caution**
-`[contract]`. §4.2 makes the order 「a visible Gateway default for Add-time placement,
-not a runtime capability filter」, puts 「The only order runtime can execute is the exact
-hop order stored for that model」 beside it, and rules out the rest by name: 「No
-adapter, UI consumer, refresh path, or runtime resolver may implement or rerun
-placement」. So nothing walks this list at request time, and a badge inked as 「supplying
-right now」 would be asserting that the per-backend list is the per-model one.
-
-**What does get walked is the other list, and saying which is what keeps this one
-honest** `[contract]`. Execution reads a model's own stored chain, whose next turn takes
-「the FIRST item with `runnable: true`」 — so skipping a source that is cooling, out of
-quota or process-unavailable is real behaviour; it happens one grain down, in a sequence
-this drawer never writes. Routing configuration is per backend *and* per model, so two
-models on the same backend can hold entirely different chains and neither has to begin
-at rank 1. Frame 08 draws exactly that distance: ChatGPT is Codex's first source and is
-paused, while aihub answers — because Codex's chain moved down its own hops, not because
-anything re-read this drawer. A backend-level surface that inked rank 1 as the live
-answer would therefore be wrong on the one frame in this set where the distinction is
-visible, and wrong silently — the badge would look confident and describe nobody.
+`[contract]`. The per-backend order is a persisted priority and an explicit input to
+`chains/reorder`, while execution still reads each model's exact stored chain and takes
+the first runnable hop. A source can therefore be first in the priority list while its
+hop is cooling, out of quota or process-unavailable. The list controls ordering; the
+chain's live annotations decide which hop answers. A backend-level surface that inked
+rank 1 as the live answer would still be wrong when another hop is runnable.
The rule generalises past this drawer: **a surface may only assert a fact whose inputs
it displays.** The per-model current source is owned by the frame that shows models —
@@ -2645,7 +2638,7 @@ stop one of them from making the claim at all.
| 排进来 `MJZ2I` | Add a held-out source to the order | yes | Append at the end, then focus the moved row `[derived]` |
| 移出 `A2Hz9O` / `FjqVJ` | Take an ordered source out of the order | yes | Move the row to the held-out section, then focus the moved row `[derived]` |
| 取消 / 关闭 `fUvS9` | Leave without saving; the icon is the button's second press and carries `order.cancel` as its name (§1.0) | yes | Close, discarding uncommitted moves |
-| 保存顺序 | Commit | yes | Persist, close |
+| 保存顺序 | Commit | yes | Persist the order, apply it to existing Routes, close |
**排进来 and 移出 are one control in two directions, and both are drawn** `[frame]`. The
held-out row carries `MJZ2I`; each ordered row carries the same button reversed —
@@ -2657,16 +2650,14 @@ order was drag-and-drop would make the two directions unequal for no reason: one
button, the other a gesture — and the gesture is the direction with no keyboard
equivalent that produces the same result.
-**Shortening the order is not a guarded change, and this drawer starts no confirmation
-at all** `[contract]`. The drawer saves the whole order in one request —
-`PUT /api/models/agents/<backend>/sources` with `{order: string[]}`, the route this frame
-owns — and returns `{agent: AgentSupply}`: the backend's supply read back with the order
-it just stored, and no policy state beside it. Taking a source
-out of this list removes it from *this list*: a chain that names that source keeps naming
-it, because the order is read at add time and a stored chain is executed exactly as
-stored (S-1, D-9). The separate explicit `chains/reorder` route can reconcile them, but
-this frame does not invoke it. There is nothing for a guard to refuse, so 保存顺序 sends,
-succeeds, and closes.
+**Changing the order is not a guarded change, and this drawer starts no confirmation
+at all** `[contract]`. The drawer sends the complete order to the explicit
+`POST /api/models/agents/<backend>/chains/reorder` route. That response is the
+authoritative `AgentSupply` echo after the order has been stored and existing Routes
+have been stably reordered in one mutation. A source removed from the priority list
+remains a valid Route hop when it is still present in a chain; the reorder operation only
+places listed Sources first and preserves every hop pair. There is nothing for a guard to
+refuse, and a failed request leaves the draft available for retry.
*An earlier version of this section had it removing hops.* It read the order save as
「a save that drops sources is not a different kind of change from any other that would
@@ -2691,8 +2682,9 @@ it look intended.
**There is no mode, and the drawer has no ownership state** `[frame]` `[spec]`. Every
element on this surface is either part of one stored order or an action that edits it:
two sections, the rows in them, and a foot that commits or discards. The order the user
-sees is the order a new chain is built from, and the only way it changes is that somebody
-changes it here or a new source is placed by the add transaction.
+sees is the backend's global priority and the order applied to existing Routes on save;
+the only way it changes is that somebody changes it here or a new source is placed by the
+add transaction.
*This section used to specify the opposite, and what it lost is worth naming.* An earlier
version drew a 跟随推荐 / 自定义 segmented control, a three-state ownership machine, a
hint row reading 「顺序已改成「自定义」:新来源不会自动排进来。」 and a 恢复推荐顺序 escape.
@@ -2750,22 +2742,24 @@ keyboard produces is byte-identical to the one a drag produces — they must wri
same value through the same commit path, not two paths that agree today. Every binding in
the table above commits through that one path, and so does every button on a row.
-**The subtitle says what this drawer stores and what its Save does not do** `[contract]`.
-It does not promise runtime resolution or automatic chain rewriting: the only order a
-turn executes is the exact hop order stored for that model, and the only operation that
-reapplies this Source order is the separate explicit `chains/reorder` route. Therefore
-the subtitle says changing this order changes no configured Route chain. A future frame
-may register the explicit operation; this one must not attach it to 保存顺序.
+**The subtitle says what this drawer stores and what its Save applies** `[contract]`.
+The `chains/reorder` request persists the complete Source order and applies it to every
+existing Route using the stable sort defined in `model-hub.md` §4.6. Therefore the first
+source is tried first and the next priority is used automatically for fallback-eligible
+quota, rate-limit, server, authentication, and network failures. If the request fails,
+the drawer keeps the same draft and retries it; no partial priority state is visible.
**Copy** — namespace `models.hub.order.*`
| Key | 中文 | English |
| --- | --- | --- |
-| `title` | {{backend}} · 来源顺序 | {{backend}} · Source order |
-| `subtitle` | 这个后端存下来的来源顺序。改动它不会改动任何已配置的路由链。 | The Source order this backend stores. Changing it changes no configured Route chain. |
+| `title` | {{backend}} · 全局路由优先级 | {{backend}} · Global route priority |
+| `subtitle` | 在每个型号已有路由中的来源里,排在前面的上游将优先被使用。当额度不足、触发限流、服务端、认证或网络出错导致请求无法完成时,自动切换下一优先级。 | Among sources already configured in each model's route, those at the top are used first. When quota, rate-limit, server, authentication, or network failures prevent a request, the next priority is used automatically. |
+| `infoLabel` `[derived]` | 什么是全局路由优先级 | What global route priority is |
| `section.ordered` | 排在这条顺序里 | In this order |
| `section.ordered.note` | 拖动排序 | Drag to reorder |
| `section.heldOut` | 未排入这条顺序 | Not in this order |
+| `section.heldOut.note` | 这些来源仍保留在已有路由里,排在这条顺序之后。要从路由中移除,请编辑对应型号的网关路由。 | These sources remain in existing routes after the ordered sources. To remove one from a route, edit that model's gateway route. |
| `action.include` | 排进来 | Add to order |
| `action.exclude` | 移出 | Remove from order |
| `empty.noEligible` `[derived]` | 这个后端还没有可用来源。 | No source is available to this backend yet. |
@@ -2792,19 +2786,17 @@ result would have used, the primary becomes 重试」 (§0.8) — so each owes o
drawer that carried neither would be specifying a treatment it cannot render. The label is
shared because it is the same word in the same place on a surface that never shows both
lines at once: a drawer with no list to reorder has nothing to save. Both lines say what
-did not happen and nothing about why. The save sends one array to one route, the drawer keeps
-every move the user made, and the frozen rule against enumerating request-level failure
+did not happen and nothing about why. The save sends the complete order to the atomic
+reorder operation, while the drawer keeps every move the user made, and the frozen rule against enumerating request-level failure
kinds means a 401, a 409 and a timeout are the same sentence here — the same shape
§1.6 gives `fail.tier`.
-**The copy says placement, not execution** `[derived]`, and that is not a wording
-preference. 保存顺序 stores an order and touches no chain (§0.8), which four paragraphs
-above is named as the property that makes this list safe to edit — so a subtitle
-promising that the first usable source *answers* describes a rewrite this save does not
-perform. A user whose chains have diverged from the current placement would reorder the
-list expecting live traffic to move, and nothing would move. The two section labels
-carry the same correction: 排在这条顺序里 and 未排入这条顺序 name the thing being edited,
-where 排在链里 named a chain this drawer does not write.
+**The copy says priority and fallback** `[derived]`. 保存顺序 stores the source order and
+applies it to existing Route hops (§4.6), so the first listed upstream is tried first and
+the next priority is used automatically for fallback-eligible quota, rate-limit, server,
+authentication, and network failures.
+The two section labels remain about membership in the priority list: 排在这条顺序里 and
+未排入这条顺序.
**Extreme data** `[derived]`
@@ -2823,12 +2815,11 @@ where 排在链里 named a chain this drawer does not write.
configuration — it means *place no source automatically when a new route is built* —
and refusing to save it would trap a user who genuinely wants that in a drawer they
cannot leave without undoing their work. What it does **not** mean is that the backend
- stops being supplied. This save writes an order and rewrites no chain, which is the
- property stated four paragraphs above as the reason this list is safe to edit at all;
- every hop already stored keeps serving, and frame 01 goes on rendering whatever those
- chains resolve to. 没有可用来源 appears when a backend has no runnable hop, which an
- empty order neither causes nor prevents — it decides only what the next 加入 finds
- waiting for it.
+ stops being supplied. This save stores the order and stably reorders existing
+ Route hops without changing their membership or mappings; frame 01 goes on rendering
+ whichever hop is runnable first. 没有可用来源 appears when a backend has no runnable
+ hop, which an empty priority order neither causes nor prevents — it decides only what
+ the next 加入 finds waiting for it.
- **Exactly one source**: it renders at rank 1 with the mint badge, the grip is present
but inert, and the drawer is still reachable — the order is trivially satisfied, not
meaningless.
@@ -3689,7 +3680,7 @@ them do I actually want, and what reasoning tiers does each accept?* Nothing els
**The back icon is named rather than inferred** `[derived]`. `iGcAi` is this page's only
route back to 01 and draws no text, so `sourceDetail.back` carries its accessible name in
both locales — the same treatment `field.apiKey.reveal` gets one frame over and
-`shell.gatewayInfo.label` gets on 01, for the same reason: a glyph is not a name, and an
+`shell.modelsInfo.label` gets on 01, for the same reason: a glyph is not a name, and an
icon-only control whose destination cannot be heard is a control a keyboard or
screen-reader user cannot use. It names the destination and not the gesture —
返回来源列表 rather than 返回 — because *back* on a page reached from several places says
@@ -3777,7 +3768,8 @@ the two would disagree the first time it grew.
The 移出 in §1.3's drawer is not a caller, because it is not yet a request. It moves a row
between two sections of an open drawer and sends nothing; 取消 discards it, and only
-保存顺序 turns it into anything a guard could refuse. A guard hung on the click would fire
+保存顺序 persists the order and applies the reorder operation in one request. That request
+has no guard, so no confirmation is needed. A guard hung on the click would fire
on an edit the user can still take back, and would not fire on the edit that actually
lands. The two unguarded model operations do not come here either: adding an entry and
editing an entry's tiers touch neither an entry's identity nor any chain that references
@@ -3908,15 +3900,14 @@ text:
| `Source.state.status` `[contract]` | Ink | Key |
| --- | --- | --- |
-| `active`, and `adopted_by` is non-empty `[contract]` | `$--mint` | `sourceDetail.status.inUse` |
-| `active`, and `adopted_by` is empty `[contract]` | `$--muted` | `upstream.state.standby` |
-| `standby` | `$--muted` | `upstream.state.standby` |
+| `active` or `standby`, and `adopted_by` is non-empty `[contract]` | `$--mint` | `sourceDetail.status.inUse` (detail) / `upstream.state.supplying` (card) |
+| `active` or `standby`, and `adopted_by` is empty `[contract]` | `$--muted` | `upstream.state.standby` |
| `cooldown` | `$--gold` | `upstream.state.unavailableRetry`, or `upstream.state.unavailableDue` once `retry_at` has passed `[derived]` |
| `needs_action` | `#FF6B6B` | the `sourceDetail.status.needsAction.*` row `state.detail_key` selects `[derived]` `[contract]` |
| `error` | `#FF6B6B` | `sourceDetail.status.error` `[derived]` |
-The split of `active` is the one place this bar reads a second field: 使用中 claims a backend has
-this source configured into a route, which is `adopted_by` (§1.0), not a source state. A
+The split of the two healthy statuses is the one place this bar reads a second field: 使用中
+claims a Hub-mode backend has this source configured into a route, which is `adopted_by` (§1.0), not a source state. A
source can be perfectly healthy and be in nobody's chain, and saying 使用中 there would be
the same lie as saying it about a dead credential, in the flattering direction.
@@ -3927,7 +3918,7 @@ credential and a takeover that routes past this hop entirely. So 使用中 is a
about configuration, and the copy is written to be true of a standby hop that a chain
still points at. A card that promised live supply would need the per-chain runnability
read, which is a different projection D-28 keeps separate — and it would go stale the
-moment a hop it named entered cooldown. `standby` and unadopted `active`
+moment a hop it named entered cooldown. Unadopted `standby` and unadopted `active`
land on one word deliberately — they differ in *why* nothing is drawing from the source,
and this bar is not where that difference is actionable.
@@ -4709,7 +4700,7 @@ way 08's is.
| Failure strip `[derived]` | `fail.title` over `fail.detail`, in the Failed state only | no | — |
**The dialog names the exit by location, not by promise** `[frame]`. The second
-可以撤回 bullet reads 「回退入口:这一页的 Claude Code 卡片 → 切换到直连」. "You can
+可以撤回 bullet reads 「回退入口:这一页的 Claude Code 卡片 → 切到直连」. "You can
change this later" is the standard phrasing and it is nearly useless: it is exactly what
a user hears before spending twenty minutes failing to find the control. Naming the
control and the surface it lives on costs one line and converts a reassurance into an
@@ -4741,7 +4732,7 @@ difference is not an inconsistency: that frame's entry condition is *every backe
| `effects.4` | 正在进行的对话不受影响,下一次请求开始生效 | Conversations in progress are unaffected; the change applies from the next request |
| `section.undo` | 可以撤回 | You can undo this |
| `undo.1` | 随时可以切换回直连 | You can switch back to direct at any time |
-| `undo.2` | 回退入口:这一页的 {{backend}} 卡片 → 切换到直连 | Where to undo: the {{backend}} card on this page → Switch to direct |
+| `undo.2` | 回退入口:这一页的 {{backend}} 卡片 → 切到直连 | Where to undo: the {{backend}} card on this page → Switch to direct |
| `undo.3` | 切回后,你添加的来源会留着,只是不再供给 {{backend}} | If you switch back, the sources you added stay; they just stop supplying {{backend}} |
| `effects.install` `[derived]` D-26 | 先安装网关组件({{component}},约 {{duration}}),再切换 | The gateway component ({{component}}, about {{duration}}) is installed first, then the switch happens |
| `cancel` | 取消 | Cancel |
@@ -5377,20 +5368,19 @@ instead (§1.6, E-2), and the reasoning it replaced that with is better: the hin
never a decision the user can revisit, so making it findable buys nothing and teaches
everyone else that protocols are their problem.
-**D-9 — The source order is a placement default that belongs to one backend, and it is
-never read at runtime.** One order per gateway-mode backend. It decides where a source
-lands in the chains built from the moment it is saved; execution reads the stored chain
-and nothing else (S-1), and no later state of this list reaches a chain that already
-exists unless the user acts on that chain.
+**D-9 — The source order is a backend-scoped priority, persisted separately and applied
+explicitly to existing Routes.** One order per gateway-mode backend. The atomic
+`chains/reorder` operation stores the complete order and stably places listed Sources
+first in every existing Route while preserving each exact hop pair. Runtime then reads
+the stored chain and chooses its first runnable hop among the sources already configured
+there. No later state of the list changes a chain until the user saves the drawer again.
*Why:* N sources × M models of hand-wiring is a configuration surface nobody can hold in
-their head, so the order carries the default and the chain carries the decision. Keeping
-the two apart is what lets a user edit either one without wondering what the other did
-behind them: a reordered list that silently rewrote live chains would make every edit a
-change of unknown blast radius. Per-backend rather than global because eligibility
-already differs per backend: a global list would have to render entries that cannot
-apply, and a user cannot form an opinion about an ordering whose members are conditional.
-
-**D-9a — A backend in 直连 mode exposes no order surface at all.** No 来源顺序 button
+their head, so a backend-level priority gives one clear way to update all existing
+chains without inventing a second per-model policy. The operation changes order only,
+never membership or mappings. Per-backend rather than global because eligibility already
+differs per backend: a global list would have to render entries that cannot apply.
+
+**D-9a — A backend in 直连 mode exposes no order surface at all.** No 调整优先级 button
on its group head, and the drawer is unreachable for it.
*Why:* a direct backend consults no source order, so the editor would edit a list
nothing reads — the most expensive kind of dead control, because it looks like it
@@ -5465,8 +5455,8 @@ is caught by users.
**D-18 — Placement is the mode surface; there is no mode switch widget.** A backend's
mode is expressed by *where its configuration lives* — a 直连 backend has a
-切换到网关 action and nothing else, a 网关 backend has 来源顺序, model rows and
-切换到直连.
+切换到网关 action and nothing else, a 网关 backend has 调整优先级, model rows and
+切到直连.
*Why:* a mode toggle would make the two modes look like two settings of one thing,
inviting the user to flip it and see. They are two different configuration models with
different surfaces; making the surfaces differ is what teaches that, and it costs no
@@ -5504,7 +5494,7 @@ is cyan there.
means different things in each.** Wires: cyan = 原生, mint = 网关供给, violet =
接管, `#FFFFFF26` = 已启用 · 当前未被使用, gold = 供给已暂停. State text:
mint = 使用中 / 正常, gold = 降级 / 暂不可用 / 冷却 / 供给暂不可用, rose = 需处理 /
-异常 / 无可用来源, muted = 备用 / 暂无 Agent 使用, cyan = 原生 provenance only, violet-tint
+异常 / 无可用来源, muted = 可用 · 当前未供给 / 暂无 Agent 使用, cyan = 原生 provenance only, violet-tint
`#7C5BFFCC` = a takeover hop label. The group-status vocabulary (§1.1) is assigned here
in full — 正常 mint, 降级 gold, 供给暂不可用 gold, 无可用来源 rose,
暂无 Agent 使用 muted — and
@@ -5585,34 +5575,33 @@ nobody has drawn yet: any future add path inherits the same test.
**D-28 — A backend-order surface reads `AgentSupply.sources`, that backend's stored Source
order; a source card reads `adopted_by`. Neither substitutes for the other.** §1.3 owns
-the first reading — it is the list `PUT /api/models/agents/<backend>/sources` writes and
-re-echoes `{agent: AgentSupply}` — and §1.0 owns the second; this decision is only about
-the prohibition on deriving either from the other.
+the first reading — it is the list the atomic `POST /api/models/agents/<backend>/chains/reorder`
+stores and re-echoes in `{agent: AgentSupply}` —
+and §1.0 owns the second; this decision is only about the prohibition on deriving either
+from the other.
*Why:* the two diverge on an ordinary page, not only in edge cases, and they diverge in
-**both** directions. `adopted_by` names backends some persisted Route chain references,
-de-duplicated by backend and carrying no position. The Source order names the sources a
-user placed under a backend, in a sequence, and `agent-supply.schema.json` calls it
-「stored configuration and an Add-time placement input」. Those are different sets in each
-direction: a source can sit in a backend's order while no chain on that backend names it —
-the order is a default for placement, and §1.2 edits chains independently of it — and a
-source can be adopted by a backend whose order does not contain it, because a chain may
-name any source and 移出 does not rewrite chains (§1.3 says exactly this: 「a source outside
-this backend's order is still a source」). Read the order into the card and it reports
-adoption that nothing routes; read `adopted_by` into the drawer and every held-out source
-and every ordered-but-unreferenced source vanishes from the list the drawer exists to edit,
-while the field's missing position makes an order impossible to reconstruct at all.
+**both** directions. `adopted_by` names Hub-mode backends whose persisted Route chains
+reference the source, de-duplicated by backend and carrying no position. The Source order
+names the sources a user placed under a backend, in a sequence, and `agent-supply.schema.json`
+calls it 「stored configuration and an Add-time placement input」. Those are different sets
+in each direction: a source can sit in a backend's order while no chain on that backend
+names it, and a source can be adopted by a backend whose order does not contain it,
+because a chain may name any source and 移出 does not remove the hop. Read the order into
+the card and it reports a priority rather than adoption; read `adopted_by` into the drawer
+and every held-out source and every ordered-but-unreferenced source vanishes from the list
+the drawer exists to edit, while the field's missing position makes an order impossible to
+reconstruct at all.
*And neither is the stored chain, which is a third projection with its own owner.* §1.2's
route-chain editor is where hop order lives, at per-model grain. The prohibition covers
that pair too: a card that read a chain would have to pick one hop — first, serving, any —
and each answer is a different sentence that changes under the user with no edit and no
-notification. **Naming the Source order here does not make it runtime state.**
-`model-hub.md` §4.2 is explicit that it is 「a visible Gateway default for Add-time
-placement, not a runtime capability filter」 and that 「the only order runtime can execute is
-the exact hop order stored for that model」; D-9 says the same from this side, which is why
-reordering the drawer reaches no existing chain and needs no guard. This decision assigns
-each surface the projection it displays; it does not promote any of the three into an input
-for another.
+notification. **Naming the Source order here does not make it live supply state.**
+`model-hub.md` §4.2 is explicit that it is a visible Gateway priority and that runtime
+executes the exact hop order stored for each model. The drawer's atomic chains/reorder
+save is the explicit bridge: it stores the priority and applies it to existing Routes
+without changing hop membership or mappings. This decision assigns each surface
+the projection it displays; it does not promote any of the three into an input for another.
Neither projection reports live supply, and the card must not be written as though one
did. `api.md` calls `adopted_by` 「the stable Source-card projection of persisted
@@ -5651,7 +5640,7 @@ files does not "fix" the page title to match them. Note that the design file's f
names do contain 模型网关: they are canvas labels for the author, and D-17 already says
a frame's shell is not the shipped shell.
-**D-30 — 切换到直连 commits on the press; only 切换到网关 gets a confirm.** Adopting the
+**D-30 — 切到直连 commits on the press; only 切换到网关 gets a confirm.** Adopting the
gateway opens frame 10 (§1.9); leaving it sends `PATCH /api/models/agents/<backend>/mode`
straight from the group head with no intermediate surface, and F1 in place is the whole
of its failure handling.
diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.md
index 1d55df978..27f77e13c 100644
--- a/docs/plans/model-hub.md
+++ b/docs/plans/model-hub.md
@@ -143,7 +143,7 @@ apply to UI nouns, not precise technical prose in this specification.
| Provider (as a UI noun) | **Banned** | The UI manages concrete Sources; vendor may appear as metadata, and “upstream provider” remains valid architecture prose |
| 账号池 / account pool | **Banned** | It implies operator tooling and multi-tenant pooling that Avibe does not ship |
| 中转站 / relay station as a category | **Banned** | It is an API Key Source with a custom Base URL; helper copy may use it as an example |
-| 优先级 / priority as a standalone global noun | **Banned** | Name the owning model Route chain; ordinal copy such as “first upstream” is allowed |
+| 优先级 / priority as a standalone global noun | **Banned**, except in the backend-scoped UI title “全局路由优先级” / “Global route priority” | The title names one backend's shared Source order; otherwise name the owning model Route chain and use ordinal copy such as “first upstream” |
**Copy-density rule (owner-approved interaction baseline, 2026-08-07 afternoon).**
Use the glossary nouns in controls and status. Put explanations behind a compact info
@@ -167,9 +167,11 @@ model entries), billing type (包月 | 按量 ¥), state (§4.5), and usage
(subscription cycle % / monthly spend). Existing `last_discovered_at` records the last
successful full inventory replacement; it is not a connectivity-check timestamp.
Every Source read also carries the server-derived
-`adopted_by: [{backend, menu_model}]` projection of its persisted Route references.
-That unique projection is sorted by backend then menu model. It is reloadable Source-
-card data, not persisted Source state, and clients never reconstruct it from live chains.
+`adopted_by: [{backend, menu_model}]` projection of persisted Route references for
+backends currently in Hub mode. That unique projection is sorted by backend then menu
+model. It is reloadable Source-card data, not persisted Source state, and clients never
+reconstruct it from live chains. Routes retained while a backend is in Direct mode are
+not included because that backend bypasses the gateway.
The Source workflow is complete at both entry points:
@@ -406,13 +408,14 @@ the user later places an already-added Source in a cross-vendor chain.
The same model may be supplied by multiple Sources; §4.3 alone executes the exact
stored route for that model.
-### 4.2 Gateway strategy — add-time defaults, then explicit configuration
+### 4.2 Gateway strategy — add-time defaults, global priority, then explicit configuration
One record per Agent backend owns `mode`, its menu, one stored Source order, and one
-stored Route chain for each menu model. The Source order is a visible Gateway default
-for Add-time placement, not a runtime capability filter. There is no backend
-Source-order policy discriminator and no per-model route policy. The only order runtime
-can execute is the exact hop order stored for that model.
+stored Route chain for each menu model. The Source order is the visible Gateway priority
+and the Add-time placement input. Saving that priority atomically stores the complete
+order and applies it to existing Routes without changing their hop membership or
+mappings. There is no backend Source-order policy discriminator
+and no per-model route policy. Runtime executes the exact hop order stored for each model.
Matching is an **Add Source write-time operation**. After connectivity, protocol, and
inventory have been observed, the add transaction proposes exact Source/model matches,
@@ -451,7 +454,9 @@ metadata for audit/display; routing and placement never read or mutate it.
The explicit `POST /api/models/agents/<backend>/chains/reorder` operation is the sole
server-side post-creation operation that implicitly applies the stored Source-order
-sequence to existing Routes. It reorders existing hops only, preserves every exact
+sequence to existing Routes. When the UI supplies an `order` body, persisting that
+order and applying it to existing Routes are one mutation; an omitted body applies the
+already stored order. It reorders existing hops only, preserves every exact
`(source_id, model_id)` member and mapping, and never reruns matching. Its complete stable
order is defined in §4.6. A user-authored per-model `hops` PUT carries only the submitted
explicit hop order, and its server handler never reads `sources.order`; an editor may use
@@ -804,8 +809,8 @@ Three classes, because the action owed by the user differs in each.
| Status | zh (UI) | Heals itself | Meaning |
| --- | --- | --- | --- |
-| `active` | 使用中 | — | currently serving |
-| `standby` | 备用 | — | healthy, but not currently serving any configured route |
+| `active` | 正常 | — | healthy source; route use is shown by the persisted reference projection |
+| `standby` | 正常 | — | healthy source; when `adopted_by` is non-empty it is shown as supplying the configured route |
| `cooldown` | 暂不可用 (gold) | **yes** | shaped quota/rate/server result; persisted `retry_at` known; recovers unattended |
| `needs_action` | 需处理 (rose) | **no** | OAuth expired, balance exhausted, key revoked/banned — dead until the user acts |
| `error` | 异常 | **no** | unclassified failure — no `retry_at`, so nothing clears it unattended |
@@ -1230,9 +1235,11 @@ present even when empty.
The request carrier shown in each row is the only one. The final `api.md`, server/client
envelopes, confirmation UI, and route tests mirror this matrix row-for-row.
`PUT /api/models/agents/<backend>/sources` is intentionally outside the matrix: it
-changes only the Add-time Source-order sequence, never a Route chain or its members, and
-must not gain a guarded `409` branch. This is the G-9 behavioral tombstone; a guard here
-would imply the forbidden behavior of rewriting Routes during Source-order storage.
+changes only the persisted Source-order sequence, never a Route chain or its members, and
+must not gain a guarded `409` branch. The UI uses the explicit
+`POST /api/models/agents/<backend>/chains/reorder` operation with the complete order;
+that operation stores the order and applies it to existing Routes in one mutation while
+preserving the PUT's storage-only contract.
Automatic background discovery never performs this cascade: when neither literal
inventory nor sanctioned-alias evidence remains, it records the model as
`model_unsupported`, keeps the configured hop visible and non-runnable, and waits for
@@ -1344,7 +1351,8 @@ Source deletion removes its id from every backend order in the same transaction
preserves the relative order of survivors. Serialization/reload rejects a dangling id.
`POST /api/models/agents/<backend>/chains/reorder` applies that sequence to every
-existing Route without changing Route membership or mappings. For an original hop at
+existing Route without changing Route membership or mappings. When its optional `order`
+body is present, it stores that sequence in the same mutation. For an original hop at
index `i`, use stable key `(0, source_order_index, i)` when its Source appears in the
current order and `(1, i, i)` otherwise, then sort lexicographically. Thus all listed
Sources come first in configured order, hops sharing a listed Source retain their
@@ -1432,8 +1440,8 @@ drag handle, or persisted policy. Configuration lives at one of the two real own
the Source or the Gateway chain.
A Source card's “Supplying …” line consumes the existing
-`adopted_by: [{backend, menu_model}]` projection: group its configured rows
-by backend, de-duplicate backend names, and combine them with the current §4.3
+`adopted_by: [{backend, menu_model}]` projection for Hub-mode backends: group its
+configured rows by backend, de-duplicate backend names, and combine them with the current §4.3
runnability projection. No parallel “supplying backends” field is stored. If this
projection proves insufficient in implementation, the lane reports the exact missing
fact for a targeted expansion of `adopted_by`; it does not add a sibling field.
@@ -1542,8 +1550,8 @@ through explicit OAuth add, not native-file import. The import entry points are
open after upgrade, the setup wizard, and the backend-page banner.
- **Add-source closing loop (v3).** Creating a Source returns
`added_to: [{backend, menu_model, source_id, model_id, position}]` for every exact hop
- written by the one-time match. `adopted_by: [{backend, menu_model}]` is the stable
- Source-card projection of those persisted references; transient health and process
+written by the one-time match. `adopted_by: [{backend, menu_model}]` is the stable
+Source-card projection of those persisted Hub-mode references; transient health and process
availability do not change it. A Source with no automatic match reports an empty
`added_to` and remains available for an explicit route edit, without a separate “not
enabled” state.
@@ -1599,8 +1607,9 @@ one pinned hop it receives.
## 9. Explicit non-goals (v3)
-- **No product-global or backend-wide priority list.** Execution ordering exists only
- inside one `(backend, menu model)` Route chain.
+- **No product-global priority list.** The backend-scoped Source order is explicitly in
+ scope, and execution ordering remains configurable inside each `(backend, menu model)`
+ Route chain.
- **Per-model ordering is explicitly in scope.** Owner ruling 2026-08-07
supersedes v2's “No per-model ordering” non-goal. The scope is exactly §4.3 and
§4.6's stored configured-chain input;
@@ -1701,7 +1710,7 @@ directions into questions that later lanes must answer before writing mechanical
attribution reuses `adopted_by`, and saved Source details has only guarded
「重新拉取」 with no latency or “last checked” copy.
- [ ] §6 reports the exact hops Add Source wrote through `added_to`, and Source-card
- `adopted_by` reflects only persisted route references.
+ `adopted_by` reflects only persisted Hub-mode route references.
- [ ] §6 reserves Direct for `mode: direct`, labels a `native_cli` Gateway hop Native,
and defines a visible, reversible Direct ↔ Gateway action for every backend.
- [ ] §9 explicitly supersedes the old no-per-model-ordering non-goal and states that
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 7c4e8d470..306597c6f 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -1117,6 +1117,22 @@ def test_runtime_install_crosses_the_controller_rpc_boundary(monkeypatch):
assert calls == [("runtime_install", None)]
+def test_reorder_client_preserves_explicit_null_order(monkeypatch):
+ from vibe import model_hub_client
+
+ calls = []
+
+ async def rpc(operation, payload=None):
+ calls.append((operation, payload))
+ return {"sources": {"order": []}, "routes": {}}
+
+ monkeypatch.setattr(model_hub_client, "_rpc", rpc)
+
+ asyncio.run(ModelHubRemoteService().reorder_agent_chains("claude", None))
+
+ assert calls == [("reorder_agent_chains", {"backend": "claude", "order": None})]
+
+
def test_runtime_start_is_allowlisted_by_controller_rpc(tmp_path):
from core.handlers.model_hub.rpc import dispatch_model_hub_rpc
@@ -2421,6 +2437,31 @@ def test_source_adoption_projection_is_sorted_by_backend_and_menu_model(tmp_path
]
+def test_source_adoption_projection_ignores_routes_for_direct_backends(tmp_path):
+ service, store, _adapter = _service(tmp_path)
+ source = ModelHubSourceConfig(
+ id="src_direct_adopted",
+ kind="api_key",
+ vendor="anthropic",
+ display_name="Direct source",
+ protocol="anthropic",
+ supply_channel="hub",
+ billing="metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[ModelHubModelConfig(id="claude-opus-4-6", provenance="discovered")],
+ credential_ref="cred_direct_adopted",
+ )
+ store.config.sources = [source]
+ store.config.agents["claude"].routes = {
+ "claude-opus-4-6": ModelHubRouteConfig(
+ hops=(ModelHubRouteHopConfig(source.id, "claude-opus-4-6"),)
+ )
+ }
+ store.config.agents["claude"].mode = "direct"
+
+ assert service.list_sources()[0]["adopted_by"] == []
+
+
def test_direct_to_hub_adoption_does_not_leak_partial_state_on_save_failure(tmp_path):
class FailingStore(MemoryStore):
def save(self, config):
@@ -2479,6 +2520,197 @@ def test_reorder_agent_chains_applies_source_order_without_changing_pairs(tmp_pa
]
+def test_reorder_agent_chains_commits_source_order_with_route_reorder(tmp_path):
+ service, store, _ = _service(tmp_path)
+ model_id = "claude-opus-4-6"
+ _set_claude_route_fixture(
+ store,
+ ("src_first0001", "src_second001"),
+ model_id,
+ )
+
+ agent = asyncio.run(
+ service.reorder_agent_chains(
+ "claude",
+ ["src_second001", "src_first0001"],
+ )
+ )
+
+ assert store.config.agents["claude"].sources.order == [
+ "src_second001",
+ "src_first0001",
+ ]
+ assert agent["sources"]["order"] == ["src_second001", "src_first0001"]
+ assert [hop["source_id"] for hop in agent["routes"][model_id]["hops"]] == [
+ "src_second001",
+ "src_first0001",
+ ]
+
+
+def test_new_source_is_appended_to_route_hops(tmp_path):
+ service, store, _ = _service(tmp_path)
+ model_id = "claude-opus-4-6"
+ _set_claude_route_fixture(store, ("src_listed01", "src_heldout1"), model_id)
+ store.config.agents["claude"].sources.order = ["src_listed01"]
+ new_source = ModelHubSourceConfig(
+ id="src_new0001",
+ kind="api_key",
+ vendor="anthropic",
+ display_name="src_new0001",
+ protocol="anthropic",
+ supply_channel="hub",
+ billing="metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[ModelHubModelConfig(id=model_id, provenance="discovered")],
+ credential_ref="cred_src_new0001",
+ )
+ config = service._clone_config(store.config)
+
+ service._apply_source_placement(config, new_source)
+
+ agent = config.agents["claude"]
+ assert agent.sources.order == ["src_listed01", "src_new0001"]
+ assert [hop.source_id for hop in agent.routes[model_id].hops] == [
+ "src_listed01",
+ "src_heldout1",
+ "src_new0001",
+ ]
+
+
+def test_new_source_preserves_explicit_route_order(tmp_path):
+ service, store, _ = _service(tmp_path)
+ model_id = "claude-opus-4-6"
+ _set_claude_route_fixture(store, ("src_explicit01", "src_listed01"), model_id)
+ store.config.agents["claude"].sources.order = ["src_listed01"]
+ store.config.agents["claude"].routes[model_id] = ModelHubRouteConfig(
+ hops=(
+ ModelHubRouteHopConfig("src_explicit01", model_id),
+ ModelHubRouteHopConfig("src_listed01", model_id),
+ )
+ )
+ new_source = ModelHubSourceConfig(
+ id="src_new0001",
+ kind="api_key",
+ vendor="anthropic",
+ display_name="src_new0001",
+ protocol="anthropic",
+ supply_channel="hub",
+ billing="metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[ModelHubModelConfig(id=model_id, provenance="discovered")],
+ credential_ref="cred_src_new0001",
+ )
+ config = service._clone_config(store.config)
+
+ service._apply_source_placement(config, new_source)
+
+ agent = config.agents["claude"]
+ assert agent.sources.order == ["src_listed01", "src_new0001"]
+ assert [hop.source_id for hop in agent.routes[model_id].hops] == [
+ "src_explicit01",
+ "src_listed01",
+ "src_new0001",
+ ]
+
+
+def test_reorder_route_accepts_source_order_atomically(monkeypatch, tmp_path):
+ service, store, _ = _service(tmp_path)
+ model_id = "claude-opus-4-6"
+ _set_claude_route_fixture(
+ store,
+ ("src_first0001", "src_second001"),
+ model_id,
+ )
+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
+ client = app.test_client()
+ base_url = "http://127.0.0.1:15131"
+
+ response = client.post(
+ "/api/models/agents/claude/chains/reorder",
+ json={"order": ["src_second001", "src_first0001"]},
+ headers=csrf_headers(client, base_url),
+ base_url=base_url,
+ )
+
+ assert response.status_code == 200
+ payload = response.get_json()
+ _assert_envelope(payload)
+ assert payload["agent"]["sources"]["order"] == [
+ "src_second001",
+ "src_first0001",
+ ]
+ assert [hop["source_id"] for hop in payload["agent"]["routes"][model_id]["hops"]] == [
+ "src_second001",
+ "src_first0001",
+ ]
+
+
+def test_reorder_route_rejects_explicit_null_order(monkeypatch, tmp_path):
+ service, _, _ = _service(tmp_path)
+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
+ client = app.test_client()
+ base_url = "http://127.0.0.1:15131"
+
+ response = client.post(
+ "/api/models/agents/claude/chains/reorder",
+ json={"order": None},
+ headers=csrf_headers(client, base_url),
+ base_url=base_url,
+ )
+
+ assert response.status_code == 400
+ payload = response.get_json()
+ _assert_envelope(payload, ok=False)
+ assert payload["error"] == "invalid_source_order"
+
+
+ ("body", "content_type"),
+ [(b"null", "application/json"), (b"null", "text/plain")],
+)
+def test_reorder_route_rejects_non_object_body(monkeypatch, tmp_path, body, content_type):
+ service, _, _ = _service(tmp_path)
+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
+ client = app.test_client()
+ base_url = "http://127.0.0.1:15131"
+ headers = {**csrf_headers(client, base_url), "content-type": content_type}
+
+ response = client.post(
+ "/api/models/agents/claude/chains/reorder",
+ content=body,
+ headers=headers,
+ base_url=base_url,
+ )
+
+ assert response.status_code == 400
+ payload = response.get_json()
+ _assert_envelope(payload, ok=False)
+ assert payload["error"] == "invalid_source_order"
+
+
+def test_reorder_route_rejects_malformed_json(monkeypatch, tmp_path):
+ service, _, _ = _service(tmp_path)
+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
+ client = app.test_client()
+ base_url = "http://127.0.0.1:15131"
+ headers = {
+ **csrf_headers(client, base_url),
+ "content-type": "application/json",
+ }
+
+ response = client.post(
+ "/api/models/agents/claude/chains/reorder",
+ content=b'{"order":',
+ headers=headers,
+ base_url=base_url,
+ )
+
+ assert response.status_code == 400
+ payload = response.get_json()
+ _assert_envelope(payload, ok=False)
+ assert payload["error"] == "invalid_source_order"
+
+
def test_ui_model_hub_default_is_controller_rpc_client(monkeypatch):
monkeypatch.setattr(ui_server, "_MODEL_HUB_SERVICE", None)
diff --git a/ui/src/components/settings/models/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsx
index f7913df82..62d3bb35f 100644
--- a/ui/src/components/settings/models/AgentCard.test.tsx
+++ b/ui/src/components/settings/models/AgentCard.test.tsx
@@ -110,12 +110,58 @@ describe('AgentCard', () => {
it('offers only gateway enablement and ignores stale chain data in direct mode', () => {
const key = modelChainKey('claude', 'claude-opus-4-6');
render(<I18nextProvider i18n={i18n}><AgentCard agents={[{ ...hubAgent, mode: 'direct', sources: null, routes: null, supply_status: null, model_supply: null }]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ contract_version: 6, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
- expect(screen.queryByText(/Source order/i)).toBeNull();
+ expect(screen.queryByText(/Adjust priority/i)).toBeNull();
expect(screen.queryByRole('button', { name: /route chain/i })).toBeNull();
expect(screen.queryByText(/Backup/)).toBeNull();
expect(screen.queryByText(/takeover/i)).toBeNull();
});
+ it.each([
+ ['en', 'Adjust priority', 'Switch to direct', 'Switch to gateway'],
+ ['zh', '调整优先级', '切到直连', '切换到网关'],
+ ] as const)('uses explicit gateway action labels and icons in %s', (lng, orderCopy, directCopy, gatewayCopy) => {
+ const directAgent: AgentSupply = {
+ ...hubAgent,
+ backend: 'codex',
+ mode: 'direct',
+ sources: null,
+ routes: null,
+ supply_status: null,
+ model_supply: null,
+ named_agents: [],
+ };
+ render(
+ <I18nextProvider i18n={localeInstance(lng)}>
+ <AgentCard
+ agents={[hubAgent, directAgent]}
+ sources={[]}
+ chains={{}}
+ pendingBackends={new Set()}
+ switchFailures={new Set()}
+ connectingBackend={null}
+ onConnectHub={vi.fn()}
+ onSwitchDirect={vi.fn()}
+ onOpenOrder={vi.fn()}
+ onOpenRoute={vi.fn()}
+ onProbeSettled={vi.fn()}
+ />
+ </I18nextProvider>,
+ );
+
+ const order = screen.getByRole('button', { name: orderCopy });
+ const direct = screen.getByRole('button', { name: directCopy });
+ const gateway = screen.getByRole('button', { name: gatewayCopy });
+ expect(order.querySelector('svg')).toBeTruthy();
+ expect(direct.querySelector('svg')).toBeTruthy();
+ expect(gateway.querySelector('svg')).toBeTruthy();
+ expect(order.parentElement?.parentElement?.className).toContain('sm:flex-wrap');
+ expect(order.parentElement?.className).toContain('items-center');
+ expect(order.parentElement?.className).toContain('min-w-0');
+ expect(order.parentElement?.parentElement?.parentElement?.className).toContain('sm:min-h-[66px]');
+ expect(order.parentElement?.parentElement?.parentElement?.className).not.toContain('sm:h-[66px]');
+ expect(gateway.className).toContain('bg-primary');
+ });
+
it('renders the AgentSupply collapse projection and rereads chains on expand and collapse', async () => {
const onProbeSettled = vi.fn();
const models = Array.from({ length: COLLAPSED_MODEL_LIMIT + 2 }, (_, index) => `model-${index + 1}`);
diff --git a/ui/src/components/settings/models/AgentCard.tsx b/ui/src/components/settings/models/AgentCard.tsx
index d9dd16dd6..d1a9bf186 100644
--- a/ui/src/components/settings/models/AgentCard.tsx
+++ b/ui/src/components/settings/models/AgentCard.tsx
@@ -1,5 +1,5 @@
import * as React from 'react';
-import { ChevronDown, ChevronRight, ChevronUp, RefreshCw } from 'lucide-react';
+import { ArrowDownUp, ChevronDown, ChevronRight, ChevronUp, PlugZap, PowerOff, RefreshCw } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Badge } from '@/components/ui/badge';
@@ -134,9 +134,9 @@ const AgentModelCard: React.FC<{
<div
tabIndex={-1}
data-agent-group-head={agent.backend}
- className="flex min-h-[66px] flex-col justify-center gap-[7px] border-b border-border px-3.5 py-3 sm:h-[66px] sm:py-0"
+ className="flex min-h-[66px] flex-col justify-center gap-[7px] border-b border-border px-3.5 py-3 sm:min-h-[66px] sm:py-1"
>
- <div className="flex min-w-0 flex-col items-stretch gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-3">
+ <div className="flex min-w-0 flex-col items-stretch gap-2 sm:flex-row sm:flex-wrap sm:items-center sm:justify-between sm:gap-3">
<div className="flex min-w-0 items-center gap-[9px]">
<span className={cn('flex size-[30px] shrink-0 items-center justify-center rounded-[9px]', ACCENT_TILE[accent])}><Icon className={cn('size-[15px]', ACCENT_ICON[accent])} /></span>
<span className="flex min-w-0 items-center gap-[7px]">
@@ -146,7 +146,7 @@ const AgentModelCard: React.FC<{
</Badge>
</span>
</div>
- {agent.mode === 'hub' ? <div className="flex shrink-0 flex-wrap gap-2"><Button variant="secondary" size="sm" className="model-hub-agent-head-action rounded-md px-3 text-[11.5px] font-bold" onClick={() => onOpenOrder(agent)} disabled={pending}>{t('settings.models.gateway.sourceOrder')}</Button><Button variant="outline" size="sm" className="model-hub-agent-head-action rounded-md px-3 text-[11.5px] font-bold" onClick={() => onSwitchDirect(agent)} disabled={pending}>{t(switchFailed ? 'settings.models.gateway.retry' : 'settings.models.gateway.switchToDirect')}</Button></div> : <Button variant="secondary" size="sm" className="model-hub-agent-head-action shrink-0 self-start rounded-md px-3 text-[11.5px] font-bold sm:self-auto" onClick={() => onConnectHub(agent)} disabled={connecting}>{t('settings.models.gateway.switchToGateway')}</Button>}
+ {agent.mode === 'hub' ? <div className="flex min-w-0 flex-1 flex-wrap items-center justify-end gap-2"><Button variant="secondary" size="sm" className="model-hub-agent-head-action rounded-md px-3 text-[11.5px] font-bold" onClick={() => onOpenOrder(agent)} disabled={pending}><ArrowDownUp aria-hidden="true" />{t('settings.models.gateway.sourceOrder')}</Button><Button variant="outline" size="sm" className="model-hub-agent-head-action rounded-md px-3 text-[11.5px] font-bold" onClick={() => onSwitchDirect(agent)} disabled={pending}><PowerOff aria-hidden="true" />{t(switchFailed ? 'settings.models.gateway.retry' : 'settings.models.gateway.switchToDirect')}</Button></div> : <Button variant="default" size="sm" className="model-hub-agent-head-action shrink-0 self-start rounded-md px-3 text-[11.5px] font-bold sm:self-auto" onClick={() => onConnectHub(agent)} disabled={connecting}><PlugZap aria-hidden="true" />{t('settings.models.gateway.switchToGateway')}</Button>}
</div>
<span className={cn('model-hub-agent-head-status flex items-center gap-1.5 text-[11px] font-semibold sm:ml-[42px]', statusClass)}>
<span className={cn('size-[5px] shrink-0 rounded-full', statusDot)} />
diff --git a/ui/src/components/settings/models/GatewayModule.test.tsx b/ui/src/components/settings/models/GatewayModule.test.tsx
index 6a55e5bca..1154f003e 100644
--- a/ui/src/components/settings/models/GatewayModule.test.tsx
+++ b/ui/src/components/settings/models/GatewayModule.test.tsx
@@ -47,7 +47,7 @@ describe('GatewayModule region failure treatment', () => {
</I18nextProvider>,
);
- const panel = screen.getByRole('heading', { name: /Gateway|网关/i }).closest('section');
+ const panel = screen.getByRole('heading', { name: /Gateway routes|网关路由/i }).closest('section');
expect(panel?.className).toContain('w-full');
expect(panel?.className).toContain('min-w-0');
});
diff --git a/ui/src/components/settings/models/GatewayModule.tsx b/ui/src/components/settings/models/GatewayModule.tsx
index 66444c6a5..fa245d186 100644
--- a/ui/src/components/settings/models/GatewayModule.tsx
+++ b/ui/src/components/settings/models/GatewayModule.tsx
@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { AgentCard } from './AgentCard';
+import { ModelHubInfoHint } from './ModelHubInfoHint';
import { foldRegionRead, type RegionRead } from './regionRead';
import type { FreshRuntimeProjection } from './runtimeLifecycle';
import type { AgentSupply, RuntimeDependency } from './types';
@@ -28,10 +29,13 @@ export const GatewayModule: React.FC<GatewayModuleProps> = ({ runtime, runtimeSn
return (
<section className="relative z-20 flex max-h-full min-h-[420px] w-full min-w-0 flex-col self-start overflow-hidden rounded-[14px] border border-border bg-surface">
<header className="flex h-14 shrink-0 items-center justify-between border-b border-border px-3.5">
- <h2 className="text-[16px] font-bold leading-[23px] text-foreground">{t('settings.models.gateway.heading')}</h2>
+ <span className="flex items-center gap-[7px]">
+ <h2 className="text-[16px] font-bold leading-[23px] text-foreground">{t('settings.models.gateway.heading')}</h2>
+ <ModelHubInfoHint label={t('settings.models.gateway.infoLabel')} content={t('settings.models.gateway.info')} className="model-hub-overview-info" />
+ </span>
{listening && <span className="model-hub-pill model-hub-fill-0a border border-border text-muted">{listening.host}:{listening.port}</span>}
</header>
- <div className="min-h-0 flex-1 overflow-y-auto p-2">
+ <div className="min-h-0 flex-1 overflow-y-auto px-2 pb-2 pt-3">
{supply.kind === 'loading' && agents === undefined
? <div className="flex h-full min-h-36 items-center justify-center"><LoaderCircle className="size-4 animate-spin text-muted" /></div>
: supply.kind === 'unread'
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index bdfbf72a3..5340de39d 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -373,7 +373,7 @@ describe('SettingsModelsPage surface branches', () => {
expect(toggle.getAttribute('aria-checked')).toBe('true');
expect((toggle as HTMLButtonElement).disabled).toBe(true);
expect(await screen.findByText('Retained source')).toBeTruthy();
- expect(screen.getByRole('button', { name: /^Switch to direct$|^切换到直连$/i })).toBeTruthy();
+ expect(screen.getByRole('button', { name: /^Switch to direct$|^切到直连$/i })).toBeTruthy();
expect(screen.queryAllByRole('tab')).toHaveLength(3);
});
@@ -692,7 +692,7 @@ describe('SettingsModelsPage surface branches', () => {
expect(await screen.findByText(/^1 takeover active$|^1 处接管中$/i)).toBeTruthy();
expect(screen.getByText(/^Taken over$|^接管中$/i)).toBeTruthy();
- expect(screen.getByText(/Now: Replacement source \(takeover\)|当前 Replacement source(接管)/i)).toBeTruthy();
+ expect(screen.getByText(/From: Replacement source \(takeover\)|来自 Replacement source(接管)/i)).toBeTruthy();
});
it('[MH-OVERVIEW-001] reads overview chains once per backend and keeps exact reads for the route dialog', async () => {
@@ -738,6 +738,7 @@ describe('SettingsModelsPage surface branches', () => {
}));
await waitFor(() => expect(exactRead).toHaveBeenCalledOnce());
expect(exactRead).toHaveBeenCalledWith('codex', 'gpt-5.6-sol');
+ expect(screen.getByText(/Later Source order changes reorder its hops to match\.|以后调整来源顺序时,其中的来源会按新的顺序重排。/i)).toBeTruthy();
});
it('keeps a failed event read distinct from an empty history and retries it', async () => {
@@ -967,7 +968,7 @@ describe('SettingsModelsPage surface branches', () => {
);
await waitFor(() => expect(chainRead).toHaveBeenCalledOnce());
- await userEvent.click(screen.getByRole('button', { name: /^Switch to direct$|^切换到直连$/i }));
+ await userEvent.click(screen.getByRole('button', { name: /^Switch to direct$|^切到直连$/i }));
await waitFor(() => expect(agentRead).toHaveBeenCalledTimes(2));
expect(await screen.findByRole('button', { name: /^Switch to Gateway$|^切换到网关$/i })).toBeTruthy();
@@ -978,7 +979,7 @@ describe('SettingsModelsPage surface branches', () => {
expect(screen.queryByRole('button', { name: /route chain|路由链/i })).toBeNull();
expect(screen.queryByText(/^Taken over$|^接管中$/i)).toBeNull();
- expect(screen.queryByText(/Now: Replacement source \(takeover\)|当前 Replacement source(接管)/i)).toBeNull();
+ expect(screen.queryByText(/From: Replacement source \(takeover\)|来自 Replacement source(接管)/i)).toBeNull();
});
it('cannot let a pre-save chain read overwrite the committed route echo', async () => {
@@ -1018,15 +1019,15 @@ describe('SettingsModelsPage surface branches', () => {
await userEvent.click(removeButtons[1]);
await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));
await userEvent.click((await screen.findByText(/^Done$|^完成$/i)).closest('button') as HTMLButtonElement);
- expect(await screen.findByText(/^Now: Paused source$|^当前 Paused source$/i)).toBeTruthy();
+ expect(await screen.findByText(/^From: Paused source$|^来自 Paused source$/i)).toBeTruthy();
await act(async () => {
pendingOldChain.resolve(takeoverChain);
await pendingOldChain.promise;
});
- expect(screen.getByText(/^Now: Paused source$|^当前 Paused source$/i)).toBeTruthy();
- expect(screen.queryByText(/Now: Replacement source \(takeover\)|当前 Replacement source(接管)/i)).toBeNull();
+ expect(screen.getByText(/^From: Paused source$|^来自 Paused source$/i)).toBeTruthy();
+ expect(screen.queryByText(/From: Replacement source \(takeover\)|来自 Replacement source(接管)/i)).toBeNull();
});
it('installs a removed backend before the committed route closes and applies PF-1', async () => {
@@ -1073,12 +1074,18 @@ describe('SettingsModelsPage surface branches', () => {
expect(document.activeElement?.closest('[data-agent-backend="codex"]')).toBeNull();
});
- it('reconciles a lost Direct-mode response before rendering failure', async () => {
+ it('keeps the source projection intact after a lost Direct-mode response', async () => {
const direct = { ...takeoverAgent, mode: 'direct' as const, sources: null, routes: null, supply_status: null, model_supply: null };
+ const staleSource = {
+ ...retainedSource,
+ id: 'src_head',
+ display_name: 'Paused source',
+ adopted_by: [{ backend: 'codex' as const, menu_model: 'gpt-5.6-sol' }],
+ };
const agentRead = vi.spyOn(modelsApi, 'listAgents')
.mockResolvedValueOnce([takeoverAgent])
.mockResolvedValueOnce([direct]);
- vi.spyOn(modelsApi, 'listSources').mockResolvedValue([retainedSource]);
+ const sourceRead = vi.spyOn(modelsApi, 'listSources').mockResolvedValue([staleSource]);
vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);
vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);
vi.spyOn(modelsApi, 'getAgentChains').mockResolvedValue([takeoverChain]);
@@ -1092,12 +1099,23 @@ describe('SettingsModelsPage surface branches', () => {
</ToastProvider>,
);
- await userEvent.click(await screen.findByRole('button', { name: /^Switch to direct$|^切换到直连$/i }));
+ await userEvent.click(await screen.findByRole('button', { name: /^Switch to direct$|^切到直连$/i }));
expect(await screen.findByRole('button', { name: /^Switch to Gateway$|^切换到网关$/i })).toBeTruthy();
expect(screen.queryByText(/did not go through|没切换成功/i)).toBeNull();
expect(setMode).toHaveBeenCalledOnce();
expect(agentRead).toHaveBeenCalledTimes(2);
+ await waitFor(() => expect(sourceRead).toHaveBeenCalledOnce());
+ expect(screen.queryByText(/Could not read the source list · the gateway itself is fine|来源列表没读到 · 网关本身正常/i)).toBeNull();
+ expect(screen.queryByText(/Supplying Codex|正在供给 Codex/i)).toBeNull();
+ expect(screen.getByText(/Available · not currently supplying|可用 · 当前未供给/i)).toBeTruthy();
+ });
+
+ it('does not compete for source inventory during Direct-mode recovery', () => {
+ const page = readFileSync(join(process.cwd(), 'src/components/settings/models/SettingsModelsPage.tsx'), 'utf8');
+ const recovery = page.slice(page.indexOf('const switchToDirect'), page.indexOf('const loadOlderEvents'));
+ expect(recovery).not.toMatch(/sourceCollectionReads\.read\(/);
+ expect(recovery).not.toMatch(/void refresh\(\)/);
});
it('keeps retained supply rows but clears derived chain claims when a later supply read fails', async () => {
@@ -1120,14 +1138,14 @@ describe('SettingsModelsPage surface branches', () => {
</ToastProvider>,
);
- expect(await screen.findByText(/Now: Replacement source \(takeover\)|当前 Replacement source(接管)/i)).toBeTruthy();
+ expect(await screen.findByText(/From: Replacement source \(takeover\)|来自 Replacement source(接管)/i)).toBeTruthy();
await userEvent.click(screen.getByText('Paused source').closest('button') as HTMLButtonElement);
await userEvent.click(await screen.findByRole('button', { name: /^Refetch$|^重新拉取$/i }));
await waitFor(() => expect(agentRead).toHaveBeenCalledTimes(2));
await userEvent.click(screen.getByRole('button', { name: /^Back to sources$|^返回来源$/i }));
expect(await screen.findByText(/Could not read this backend's supply|没有读到后端列表/i)).toBeTruthy();
- expect(screen.queryByText(/Now: Replacement source \(takeover\)|当前 Replacement source(接管)/i)).toBeNull();
+ expect(screen.queryByText(/From: Replacement source \(takeover\)|来自 Replacement source(接管)/i)).toBeNull();
expect(screen.getAllByText('—').length).toBeGreaterThan(0);
});
@@ -1151,14 +1169,14 @@ describe('SettingsModelsPage surface branches', () => {
</ToastProvider>,
);
- expect(await screen.findByText(/Now: Replacement source \(takeover\)|当前 Replacement source(接管)/i)).toBeTruthy();
+ expect(await screen.findByText(/From: Replacement source \(takeover\)|来自 Replacement source(接管)/i)).toBeTruthy();
await userEvent.click(screen.getByText('Paused source').closest('button') as HTMLButtonElement);
await userEvent.click(await screen.findByRole('button', { name: /^Refetch$|^重新拉取$/i }));
await waitFor(() => expect(runtimeRead).toHaveBeenCalledTimes(2));
await userEvent.click(screen.getByRole('button', { name: /^Back to sources$|^返回来源$/i }));
expect(await screen.findByText(/^Gateway status unavailable$|^网关状态未读到$/i)).toBeTruthy();
- expect(screen.queryByText(/Now: Replacement source \(takeover\)|当前 Replacement source(接管)/i)).toBeNull();
+ expect(screen.queryByText(/From: Replacement source \(takeover\)|来自 Replacement source(接管)/i)).toBeNull();
expect(screen.queryByText(/^Taken over$|^接管中$/i)).toBeNull();
expect(screen.getAllByText('—').length).toBeGreaterThan(0);
});
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index 0b30dbd51..168e42d3d 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -262,8 +262,8 @@ const ModelHubShell: React.FC<{ actions?: React.ReactNode; detailBack?: () => vo
: <span className="flex items-center gap-[9px]">
<h1>{t('settings.models.shell.title')}</h1>
<ModelHubInfoHint
- label={t('settings.models.shell.gatewayInfo.label')}
- content={t('settings.models.shell.gatewayInfo.body')}
+ label={t('settings.models.shell.modelsInfo.label')}
+ content={t('settings.models.shell.modelsInfo.body')}
className="model-hub-shell-info"
/>
</span>}
@@ -877,6 +877,7 @@ export const SettingsModelsPage: React.FC = () => {
const directEmpty = modelsSurfaceKindFromReads(supplyRead, sourcesRead) === 'direct_empty';
const installedAgents = agents.filter((agent) => agent.cli_present);
const hubBackends = agents.filter((agent) => agent.mode === 'hub').map((agent) => agent.backend);
+ const activeBackends = supplyRead.kind === 'ready' ? new Set(hubBackends) : undefined;
const stopBlocked = runtimeEnabled && (supplyRead.kind !== 'ready' || hubBackends.length > 0);
const runtimeSwitchUnsupported = !runtimeEnabled
&& runtimeHealth === 'not_installed'
@@ -1201,8 +1202,9 @@ export const SettingsModelsPage: React.FC = () => {
? <RuntimeClosedState read={runtimeRead} runtime={retainedRuntime} starting={startingRuntime} stopping={stoppingRuntime} />
: selectedSourceId
? selectedSource
- ? <SourceDetailPanel
+ ? <SourceDetailPanel
source={selectedSource}
+ activeBackends={activeBackends}
headingRef={sourceDetailHeadingRef}
trackMutation={trackSourceMutation(selectedSource.id)}
onReauth={setReauthSource}
@@ -1227,7 +1229,7 @@ export const SettingsModelsPage: React.FC = () => {
onOpenChange={(open) => { if (!open) closeSubscriptionPicker(); }}
>
<PopoverAnchor virtualRef={subscriptionAnchorRef} />
- <SourcesCard read={sourcesRead} readFailureCopy={routeCommitStatus?.failed.has('sources') ? t('settings.models.routeDialog.impact.refreshFail') : undefined} onRetry={() => routeCommitStatus?.failed.has('sources') ? retryRouteCommit() : void retrySources()} onOpenSource={(source) => selectSource(source.id)} onAddApiKey={() => setApiKeyOpen(true)} onAddSubscription={toggleSubscriptionPicker} subscriptionPickerOpen={subscriptionPickerOpen} subscriptionTriggerRef={subscriptionTriggerRef} />
+ <SourcesCard read={sourcesRead} activeBackends={activeBackends} readFailureCopy={routeCommitStatus?.failed.has('sources') ? t('settings.models.routeDialog.impact.refreshFail') : undefined} onRetry={() => routeCommitStatus?.failed.has('sources') ? retryRouteCommit() : void retrySources()} onOpenSource={(source) => selectSource(source.id)} onAddApiKey={() => setApiKeyOpen(true)} onAddSubscription={toggleSubscriptionPicker} subscriptionPickerOpen={subscriptionPickerOpen} subscriptionTriggerRef={subscriptionTriggerRef} />
<PopoverContent
role="menu"
aria-label={t('settings.models.upstream.addSubscription')}
diff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsx
index af41c10a0..42a577235 100644
--- a/ui/src/components/settings/models/SourceDetailPanel.test.tsx
+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx
@@ -1176,11 +1176,11 @@ describe('SourceDetailPanel', () => {
it('explains standby beside the label rather than in a place the reader must find', async () => {
renderPanel([]);
- expect(screen.getByText(/^Standby$|^备用$/i)).toBeTruthy();
+ expect(screen.getByText(i18n.t('settings.models.upstream.state.standby'))).toBeTruthy();
// Reached by keyboard, not by hover alone: the sentence is the only thing on
// the bar that says a just-added source is fine, so it cannot be pointer-only.
- const hint = screen.getByRole('button', { name: /What standby means|备用是什么意思/i });
+ const hint = screen.getByRole('button', { name: /What this status means|这个状态是什么意思/i });
hint.focus();
await userEvent.keyboard('{Enter}');
expect(await screen.findByText(/serves a route through it|它就会显示为使用中/i)).toBeTruthy();
diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsx
index abc104f3e..35e1f838e 100644
--- a/ui/src/components/settings/models/SourceDetailPanel.tsx
+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx
@@ -47,12 +47,13 @@ import {
import { handOffProviderTab } from './providerTab';
import { reconcileUnknownWrite } from './reconcileUnknownWrite';
import { REPAIR_DESTINATION, REPAIR_LABEL_KEY, reauthBodyKey, reauthCost, repairAction } from './repair';
-import { sourceStatePresentation } from './sourceStatePresentation';
+import { activeSourceAdoption, sourceStatePresentation } from './sourceStatePresentation';
import { tierMutationPayload, type TierMutationIntent } from './tierMutation';
import { TIER_SUGGESTIONS } from './tierSuggestions';
import { useDeadlineClock } from './useDeadlineClock';
import { ACCENT_ICON, ACCENT_TILE, isCustomEndpoint, sourceVisual } from './vendorMeta';
import type {
+ AgentBackend,
RouteHopRef,
Source,
SourcePatch,
@@ -379,7 +380,9 @@ export const SourceDetailPanel: React.FC<{
onMutationCommitted: PresentSourceMutationCommit;
/** Stable focus target for callers that navigate into this detail surface. */
headingRef?: React.Ref<HTMLHeadingElement>;
-}> = ({ source, trackMutation, onReauth, onMutationCommitted, headingRef }) => {
+ /** Authoritative backends still using the gateway, when the Agent read is ready. */
+ activeBackends?: ReadonlySet<AgentBackend>;
+}> = ({ source, trackMutation, onReauth, onMutationCommitted, headingRef, activeBackends }) => {
const { t, i18n } = useTranslation();
const now = useDeadlineClock(source.state.status === 'cooldown' ? source.state.retry_at : null);
const { Icon, accent } = sourceVisual(source);
@@ -814,9 +817,10 @@ export const SourceDetailPanel: React.FC<{
if (guard.kind === 'refetch') void refetch(confirmGuardPlan(guard.plan));
if (guard.kind === 'removeModel') void remove(guard.model, confirmGuardPlan(guard.plan));
};
- const adoptedBackends = [...new Set((source.adopted_by ?? []).map(({ backend }) => t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string))];
+ const adoptedBy = activeSourceAdoption(source.adopted_by, activeBackends);
+ const adoptedBackends = [...new Set((adoptedBy ?? []).map(({ backend }) => t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string))];
const state = sourceStatePresentation(source.state, 'detail', i18n.language, now, {
- known: source.adopted_by !== undefined,
+ known: adoptedBy !== undefined,
backends: adoptedBackends,
native: source.supply_channel === 'native_cli',
});
diff --git a/ui/src/components/settings/models/SourceOrderDrawer.test.tsx b/ui/src/components/settings/models/SourceOrderDrawer.test.tsx
index d74227e08..9ddce16ae 100644
--- a/ui/src/components/settings/models/SourceOrderDrawer.test.tsx
+++ b/ui/src/components/settings/models/SourceOrderDrawer.test.tsx
@@ -65,6 +65,7 @@ afterEach(() => {
beforeEach(() => {
vi.spyOn(modelsApi, 'listSources').mockResolvedValue(sources);
+ vi.spyOn(modelsApi, 'reorderAgentChains').mockResolvedValue(agent);
});
describe('SourceOrderDrawer keyboard ordering', () => {
@@ -73,6 +74,10 @@ describe('SourceOrderDrawer keyboard ordering', () => {
vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent);
renderDrawer();
const handles = await screen.findAllByRole('button', { name: 'Reorder source' });
+ expect(screen.getByRole('heading', { name: 'Claude Code · Global route priority' })).toBeTruthy();
+ expect(screen.getByText("Among sources already configured in each model's route, those at the top are used first. When quota, rate-limit, server, authentication, or network failures prevent a request, the next priority is used automatically.")).toBeTruthy();
+ expect(screen.getByText("These sources remain in existing routes after the ordered sources. To remove one from a route, edit that model's gateway route.")).toBeTruthy();
+ expect(handles[0].className).toContain('cursor-grab');
handles[0].focus();
await user.keyboard('[Space]');
@@ -104,7 +109,7 @@ describe('SourceOrderDrawer keyboard ordering', () => {
it('reads the current order on open and keeps the moved draft after a failed save', async () => {
const user = userEvent.setup();
const getAgentSources = vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent);
- const putAgentSources = vi.spyOn(modelsApi, 'putAgentSources').mockRejectedValue(new Error('offline'));
+ const reorderAgentChains = vi.spyOn(modelsApi, 'reorderAgentChains').mockRejectedValue(new Error('offline'));
renderDrawer();
await user.click((await screen.findAllByRole('button', { name: 'Remove from order' }))[0]);
@@ -115,7 +120,39 @@ describe('SourceOrderDrawer keyboard ordering', () => {
expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy();
expect(screen.getByText('This order is empty. Add a source from below.')).toBeTruthy();
expect(getAgentSources).toHaveBeenCalledWith('claude');
- expect(putAgentSources).toHaveBeenCalledWith('claude', { order: [] });
+ expect(reorderAgentChains).toHaveBeenCalledWith('claude', []);
+ });
+
+ it('applies the saved priority to existing route chains', async () => {
+ const user = userEvent.setup();
+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent);
+ const reorderAgentChains = vi.spyOn(modelsApi, 'reorderAgentChains').mockResolvedValue(agent);
+ renderDrawer();
+
+ await user.click((await screen.findAllByRole('button', { name: 'Remove from order' }))[0]);
+ await user.click(screen.getByRole('button', { name: 'Save order' }));
+
+ await waitFor(() => expect(reorderAgentChains).toHaveBeenCalledWith('claude', ['src_b']));
+ });
+
+ it('allows reapplying an unchanged saved priority to existing route chains', async () => {
+ const user = userEvent.setup();
+ const savedAgent: AgentSupply = {
+ ...agent,
+ sources: {
+ order: ['src_b', 'src_a'],
+ eligibility: sources.map((item) => ({ source_id: item.id, eligible: true })),
+ },
+ };
+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(savedAgent);
+ const reorderAgentChains = vi.spyOn(modelsApi, 'reorderAgentChains').mockResolvedValue(savedAgent);
+ renderDrawer({ agent: savedAgent });
+
+ const save = await screen.findByRole('button', { name: 'Save order' });
+ expect(save.hasAttribute('disabled')).toBe(false);
+ await user.click(save);
+
+ await waitFor(() => expect(reorderAgentChains).toHaveBeenCalledWith('claude', ['src_b', 'src_a']));
});
it('keeps a read failure inside the drawer and retries the collection read', async () => {
diff --git a/ui/src/components/settings/models/SourceOrderDrawer.tsx b/ui/src/components/settings/models/SourceOrderDrawer.tsx
index 1aa604467..42c681adf 100644
--- a/ui/src/components/settings/models/SourceOrderDrawer.tsx
+++ b/ui/src/components/settings/models/SourceOrderDrawer.tsx
@@ -67,7 +67,7 @@ const OrderedRow: React.FC<{
disabled={busy || inert}
onPointerDown={(event) => !inert && controls.start(event)}
onKeyDown={onKeyDown}
- className={cn('model-hub-order-grip', grabbed && 'is-grabbed')}
+ className={cn('model-hub-order-grip cursor-grab active:cursor-grabbing disabled:cursor-not-allowed', grabbed && 'is-grabbed')}
>
<GripVertical />
</button>
@@ -94,7 +94,6 @@ export const SourceOrderDrawer: React.FC<{
const [viewSources, setViewSources] = React.useState(sources);
const [readState, setReadState] = React.useState<ReadState>('loading');
const [order, setOrder] = React.useState<string[]>([]);
- const [dirty, setDirty] = React.useState(false);
const [saveFailed, setSaveFailed] = React.useState(false);
const [grabbedId, setGrabbedId] = React.useState<string | null>(null);
const [announcement, setAnnouncement] = React.useState<OrderAnnouncement>(null);
@@ -111,7 +110,6 @@ export const SourceOrderDrawer: React.FC<{
setViewSources(nextSources);
saved.current = nextOrder;
setOrder(nextOrder);
- setDirty(false);
setSaveFailed(false);
setGrabbedId(null);
setAnnouncement(null);
@@ -160,7 +158,6 @@ export const SourceOrderDrawer: React.FC<{
const persist = (next: string[]) => {
if (sameIds(next, order)) return;
setOrder(next);
- setDirty(!sameIds(next, saved.current));
setSaveFailed(false);
};
const focusHandle = (sourceId: string) => handles.current.get(sourceId)?.focus();
@@ -191,7 +188,6 @@ export const SourceOrderDrawer: React.FC<{
const sourceId = grabbedId;
const restored = grabbedFrom.current;
setOrder(restored);
- setDirty(!sameIds(restored, saved.current));
setAnnouncement({ key: 'grabCancelled', source: byId.get(sourceId)?.display_name ?? sourceId });
setGrabbedId(null);
requestAnimationFrame(() => focusHandle(sourceId));
@@ -234,10 +230,9 @@ export const SourceOrderDrawer: React.FC<{
if (saving || readState !== 'ready' || available.length === 0) return;
void orderWrite.track(async () => {
try {
- const echoed = await modelsApi.putAgentSources(agent.backend, { order });
+ const echoed = await modelsApi.reorderAgentChains(agent.backend, order);
saved.current = echoed.sources?.order ?? order;
setOrder(saved.current);
- setDirty(false);
setSaveFailed(false);
await Promise.resolve(onSaved(echoed)).catch(() => {});
onClose();
@@ -252,7 +247,9 @@ export const SourceOrderDrawer: React.FC<{
const backend = t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend });
const title = t('settings.models.order.title', { backend });
const announcementText = announcement ? t(`settings.models.order.${announcement.key}`, announcement) : '';
- const saveEnabled = readState === 'ready' && available.length > 0 && (dirty || order.length === 0);
+ // Saving is also the explicit action for reapplying the stored priority to
+ // routes that may have been edited independently since the last save.
+ const saveEnabled = readState === 'ready' && available.length > 0;
return (
<DialogPrimitive.Root open={open} onOpenChange={(next) => !next && !saving && onClose()}>
@@ -272,7 +269,7 @@ export const SourceOrderDrawer: React.FC<{
<div className="flex min-w-0 items-center gap-[7px]">
<DialogPrimitive.Title className="model-hub-order-title truncate font-bold text-foreground">{title}</DialogPrimitive.Title>
<ModelHubInfoHint
- label={t('settings.models.order.subtitle')}
+ label={t('settings.models.order.infoLabel')}
content={t('settings.models.order.subtitle')}
className="model-hub-order-info"
/>
@@ -354,7 +351,10 @@ export const SourceOrderDrawer: React.FC<{
</Reorder.Group>}
</section>
<section className="model-hub-order-section">
- <div className="model-hub-order-section-head"><h3>{t('settings.models.order.section.heldOut')}</h3></div>
+ <div className="model-hub-order-section-head model-hub-order-section-head--held-out">
+ <h3>{t('settings.models.order.section.heldOut')}</h3>
+ <span className="model-hub-order-section-explanation">{t('settings.models.order.section.heldOut.note')}</span>
+ </div>
<div className="flex flex-col gap-2">
{heldOut.map((source) => (
<div key={source.id} className="model-hub-order-row model-hub-order-row--held">
diff --git a/ui/src/components/settings/models/SourceRow.test.tsx b/ui/src/components/settings/models/SourceRow.test.tsx
index caeb18599..8b8f826e1 100644
--- a/ui/src/components/settings/models/SourceRow.test.tsx
+++ b/ui/src/components/settings/models/SourceRow.test.tsx
@@ -29,6 +29,11 @@ describe('SourceRow', () => {
expect(screen.getByText('Anthropic · Anthropic Messages')).toBeTruthy();
});
+ it('explains that a healthy source is not currently supplying a route', () => {
+ render(<I18nextProvider i18n={i18n}><SourceRow source={source} onOpen={vi.fn()} /></I18nextProvider>);
+ expect(screen.getByText(/Available · not currently supplying|可用 · 当前未供给/i)).toBeTruthy();
+ });
+
it('labels a custom upstream by host and protocol', () => {
render(
<I18nextProvider i18n={i18n}>
@@ -54,10 +59,24 @@ describe('SourceRow', () => {
});
it('consumes persisted adoption when the source projection carries it', () => {
- render(<I18nextProvider i18n={i18n}><SourceRow source={{ ...source, state: { ...source.state, status: 'active' }, adopted_by: [{ backend: 'codex', menu_model: 'gpt-5' }] }} onOpen={vi.fn()} /></I18nextProvider>);
+ render(<I18nextProvider i18n={i18n}><SourceRow source={{ ...source, state: { ...source.state, status: 'standby' }, adopted_by: [{ backend: 'codex', menu_model: 'gpt-5' }] }} onOpen={vi.fn()} /></I18nextProvider>);
expect(screen.getByText(/Supplying Codex|正在供给 Codex/i)).toBeTruthy();
});
+ it('does not show a cached adoption after that backend switches to direct mode', () => {
+ render(
+ <I18nextProvider i18n={i18n}>
+ <SourceRow
+ source={{ ...source, state: { ...source.state, status: 'standby' }, adopted_by: [{ backend: 'codex', menu_model: 'gpt-5' }] }}
+ activeBackends={new Set(['claude'])}
+ onOpen={vi.fn()}
+ />
+ </I18nextProvider>,
+ );
+ expect(screen.queryByText(/Supplying Codex|正在供给 Codex/i)).toBeNull();
+ expect(screen.getByText(/Available · not currently supplying|可用 · 当前未供给/i)).toBeTruthy();
+ });
+
it('advances cooldown copy when its retry deadline passes', () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-08-11T14:00:00Z'));
diff --git a/ui/src/components/settings/models/SourceRow.tsx b/ui/src/components/settings/models/SourceRow.tsx
index c0e41e536..dbba81b69 100644
--- a/ui/src/components/settings/models/SourceRow.tsx
+++ b/ui/src/components/settings/models/SourceRow.tsx
@@ -9,12 +9,16 @@ import {
sourceDetail,
sourceProviderIdentity,
} from './sourcePresentation';
-import { sourceStatePresentation } from './sourceStatePresentation';
+import { activeSourceAdoption, sourceStatePresentation } from './sourceStatePresentation';
import { useDeadlineClock } from './useDeadlineClock';
import { ACCENT_ICON, ACCENT_PILL, ACCENT_TILE, sourceVisual } from './vendorMeta';
-import type { Source } from './types';
+import type { AgentBackend, Source } from './types';
-export const SourceRow: React.FC<{ source: Source; onOpen: (source: Source) => void }> = ({ source, onOpen }) => {
+export const SourceRow: React.FC<{
+ source: Source;
+ onOpen: (source: Source) => void;
+ activeBackends?: ReadonlySet<AgentBackend>;
+}> = ({ source, onOpen, activeBackends }) => {
const { t, i18n } = useTranslation();
const now = useDeadlineClock(source.state.status === 'cooldown' ? source.state.retry_at : null);
const { Icon, accent } = sourceVisual(source);
@@ -23,9 +27,10 @@ export const SourceRow: React.FC<{ source: Source; onOpen: (source: Source) => v
const providerCopyKey = SOURCE_PROVIDER_COPY_KEYS[providerIdentity];
const providerLabel = providerCopyKey ? t(providerCopyKey) : providerIdentity;
const interfaceLabel = `${providerLabel} · ${t(PROTOCOL_COPY_KEYS[source.protocol])}`;
- const adoptedBackends = [...new Set((source.adopted_by ?? []).map(({ backend }) => t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string))];
+ const adoptedBy = activeSourceAdoption(source.adopted_by, activeBackends);
+ const adoptedBackends = [...new Set((adoptedBy ?? []).map(({ backend }) => t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string))];
const state = sourceStatePresentation(source.state, 'card', i18n.language, now, {
- known: source.adopted_by !== undefined,
+ known: adoptedBy !== undefined,
backends: adoptedBackends,
native: source.supply_channel === 'native_cli',
});
@@ -34,14 +39,14 @@ export const SourceRow: React.FC<{ source: Source; onOpen: (source: Source) => v
: source.kind === 'subscription'
? 'subscription'
: 'apiKey';
- const adopted = source.state.status === 'active' && (source.adopted_by?.length ?? 0) > 0;
+ const adopted = (source.state.status === 'active' || source.state.status === 'standby') && (adoptedBy?.length ?? 0) > 0;
return (
<button
type="button"
data-source-id={source.id}
onClick={() => onOpen(source)}
className={cn(
- 'flex h-20 w-full items-center gap-2.5 rounded-[10px] border border-border bg-background px-3 text-left transition-colors hover:border-border-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
+ 'flex h-auto min-h-[96px] w-full items-center gap-2.5 rounded-[10px] border border-border bg-background px-3 py-2 text-left transition-colors hover:border-border-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
adopted && source.supply_channel === 'native_cli' && 'border-cyan/30 bg-cyan/[0.04]',
adopted && source.supply_channel === 'hub' && 'border-mint/30 bg-mint/[0.04]',
source.state.status === 'cooldown' && 'border-gold/20 bg-gold/[0.04]',
@@ -51,8 +56,8 @@ export const SourceRow: React.FC<{ source: Source; onOpen: (source: Source) => v
<Icon className={cn('size-[17px]', ACCENT_ICON[accent])} />
</span>
<span className="min-w-0 flex-1">
- <span className="flex min-w-0 items-center gap-1.5">
- <span className="truncate text-[12.5px] font-bold leading-[18px] text-foreground" title={source.display_name}>{source.display_name}</span>
+ <span className="block min-w-0 truncate text-[12.5px] font-bold leading-[18px] text-foreground" title={source.display_name}>{source.display_name}</span>
+ <span className="mt-1 flex min-w-0 flex-wrap items-center gap-1.5">
<span
className="model-hub-pill model-hub-source-interface-pill border"
title={interfaceLabel}
diff --git a/ui/src/components/settings/models/SourcesCard.test.tsx b/ui/src/components/settings/models/SourcesCard.test.tsx
index 5bf158eee..433802015 100644
--- a/ui/src/components/settings/models/SourcesCard.test.tsx
+++ b/ui/src/components/settings/models/SourcesCard.test.tsx
@@ -32,11 +32,24 @@ describe('SourcesCard footer', () => {
</I18nextProvider>,
);
- const panel = screen.getByRole('heading', { name: /Sources|来源/i }).closest('section');
+ const panel = screen.getByRole('heading', { name: /Upstream sources|上游来源/i }).closest('section');
expect(panel?.className).toContain('w-full');
expect(panel?.className).toContain('min-w-0');
});
+ it('keeps the source title on its own line above the interface and kind tags', () => {
+ render(
+ <I18nextProvider i18n={i18n}>
+ <SourcesCard read={readyRegion([retained])} onRetry={vi.fn()} onOpenSource={vi.fn()} onAddApiKey={vi.fn()} onAddSubscription={vi.fn()} />
+ </I18nextProvider>,
+ );
+
+ const title = screen.getByText('Retained source');
+ expect(title.className).toContain('block');
+ expect(title.nextElementSibling?.className).toContain('flex');
+ expect(title.closest('button')?.className).toContain('min-h-[96px]');
+ });
+
it('exposes the upstream info note to keyboard activation and Escape dismissal', async () => {
const user = userEvent.setup();
render(
@@ -45,13 +58,13 @@ describe('SourcesCard footer', () => {
</I18nextProvider>,
);
- const info = screen.getByRole('button', { name: /What the gateway is|什么是网关/i });
+ const info = screen.getByRole('button', { name: /What upstream sources are|什么是上游来源/i });
await user.tab();
expect(document.activeElement).toBe(info);
await user.keyboard('[Enter]');
- expect(await screen.findByText(/dispatch layer|调度/i)).toBeTruthy();
+ expect(await screen.findByText(/account or API key|账号或 API Key/i)).toBeTruthy();
await user.keyboard('[Escape]');
- await waitFor(() => expect(screen.queryByText(/dispatch layer|调度/i)).toBeNull());
+ await waitFor(() => expect(screen.queryByText(/account or API key|账号或 API Key/i)).toBeNull());
});
it('draws the two Frame 01 commands and dispatches each action', async () => {
diff --git a/ui/src/components/settings/models/SourcesCard.tsx b/ui/src/components/settings/models/SourcesCard.tsx
index e0e3080df..ce442e93c 100644
--- a/ui/src/components/settings/models/SourcesCard.tsx
+++ b/ui/src/components/settings/models/SourcesCard.tsx
@@ -6,7 +6,7 @@ import { Button } from '@/components/ui/button';
import { ModelHubInfoHint } from './ModelHubInfoHint';
import { foldRegionRead, type RegionRead } from './regionRead';
import { SourceRow } from './SourceRow';
-import type { Source } from './types';
+import type { AgentBackend, Source } from './types';
export const SourcesCard: React.FC<{
read: RegionRead<Source[]>;
@@ -17,7 +17,8 @@ export const SourcesCard: React.FC<{
onAddSubscription: () => void;
subscriptionPickerOpen?: boolean;
subscriptionTriggerRef?: React.Ref<HTMLButtonElement>;
-}> = ({ read, onRetry, readFailureCopy, onOpenSource, onAddApiKey, onAddSubscription, subscriptionPickerOpen, subscriptionTriggerRef }) => {
+ activeBackends?: ReadonlySet<AgentBackend>;
+}> = ({ read, onRetry, readFailureCopy, onOpenSource, onAddApiKey, onAddSubscription, subscriptionPickerOpen, subscriptionTriggerRef, activeBackends }) => {
const { t } = useTranslation();
const sources = foldRegionRead<Source[], Source[] | undefined>(read, {
loading: () => undefined,
@@ -39,8 +40,8 @@ export const SourcesCard: React.FC<{
<span className="flex items-center gap-[7px]">
<h2 className="text-[16px] font-bold leading-[23px] text-foreground">{t('settings.models.upstream.heading')}</h2>
<ModelHubInfoHint
- label={t('settings.models.shell.gatewayInfo.label')}
- content={t('settings.models.shell.gatewayInfo.body')}
+ label={t('settings.models.upstream.infoLabel')}
+ content={t('settings.models.upstream.info')}
className="model-hub-upstream-info"
/>
</span>
@@ -54,7 +55,7 @@ export const SourcesCard: React.FC<{
: <>
{read.kind === 'degraded' && read.cause === 'read_failed' && <div className="mb-2 flex items-center justify-between gap-3 rounded-lg border border-destructive/25 bg-destructive/[0.08] px-3 py-2"><p className="text-[11px] text-destructive-ink">{readFailureCopy ?? t('settings.models.upstream.unread')}</p><Button variant="outline" size="xs" onClick={onRetry}>{t('settings.models.upstream.retry')}</Button></div>}
{groups.length > 0
- ? groups.map((group) => <div key={group.id} className="space-y-2.5"><h3 className="model-hub-upstream-group-label flex h-[18px] items-center uppercase">{t(`settings.models.upstream.group.${group.id}`)}</h3>{group.sources.map((source) => <SourceRow key={source.id} source={source} onOpen={onOpenSource} />)}</div>)
+ ? groups.map((group) => <div key={group.id} className="space-y-2.5"><h3 className="model-hub-upstream-group-label flex h-[18px] items-center uppercase">{t(`settings.models.upstream.group.${group.id}`)}</h3>{group.sources.map((source) => <SourceRow key={source.id} source={source} onOpen={onOpenSource} activeBackends={activeBackends} />)}</div>)
: <p className="px-3 py-10 text-center text-[12px] text-muted">{t('settings.models.upstream.empty')}</p>}
</>}
</div>
diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.css
index 16d6836bd..ae17f675f 100644
--- a/ui/src/components/settings/models/modelHubSurface.css
+++ b/ui/src/components/settings/models/modelHubSurface.css
@@ -367,10 +367,9 @@
.model-hub-overview-chevron,
.model-hub-overview-info { color: var(--model-hub-ink-40); }
-/* The agent group head is a fixed 66px band holding a 36px action row and a
- 16px status row with a 7px gap; the frame's 59px of content is centred in it,
- so the inset is the half-pixel 3.5 rather than a round number. Both rows have
- to be pinned, because inherited line-height alone grows them past that. */
+/* The agent group head keeps a 66px minimum while holding a 36px action row and a
+ 16px status row with a 7px gap. Its height may grow when compact layouts wrap
+ the action row, while the row and status line dimensions stay pinned. */
.model-hub-agent-head-action {
height: var(--model-hub-agent-head-action-height, 36px);
padding-block: 0;
@@ -1322,6 +1321,24 @@
letter-spacing: 0;
line-height: normal;
}
+.model-hub-order-section-head--held-out {
+ flex-wrap: wrap;
+ row-gap: 4px;
+}
+.model-hub-order-section-head--held-out > .model-hub-order-section-explanation {
+ display: block;
+ flex: 1 1 100%;
+ min-width: 0;
+ padding: 0;
+ border: 0;
+ border-radius: 0;
+ background: transparent;
+ color: var(--muted);
+ font-size: var(--model-hub-order-meta-size);
+ font-weight: 400;
+ letter-spacing: 0;
+ line-height: 15px;
+}
.model-hub-order-row {
height: var(--model-hub-order-row-height);
padding-inline: var(--model-hub-order-row-padding-x);
diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.ts
index 2a976a92b..7783a2908 100644
--- a/ui/src/components/settings/models/modelsApi.ts
+++ b/ui/src/components/settings/models/modelsApi.ts
@@ -116,6 +116,8 @@ export type ModelsApi = {
getAgentSources(backend: AgentBackend): Promise<AgentSupply>;
/** Total write of the exact stored source order. */
putAgentSources(backend: AgentBackend, body: AgentSourcesPut): Promise<AgentSupply>;
+ /** Store an optional source order and apply it to every existing route atomically. */
+ reorderAgentChains(backend: AgentBackend, order?: string[]): Promise<AgentSupply>;
/** Resolution chain for one model. Hub mode only — direct answers `direct_mode`. */
getAgentChain(backend: AgentBackend, model: string): Promise<AgentChain>;
/** Complete overview chain projection for one Hub backend. */
@@ -455,6 +457,10 @@ export const modelsApi: ModelsApi = {
// The body is TOTAL and closed: the route rejects unknown keys, so
// `contract_version` is deliberately absent (unlike every other write here).
putAgentSources: (backend, body) => call<{ agent: AgentSupply }>(`/api/models/agents/${backend}/sources`, jsonInit('PUT', body)).then((r) => r.agent),
+ reorderAgentChains: (backend, order) => call<{ agent: AgentSupply }>(
+ `/api/models/agents/${backend}/chains/reorder`,
+ jsonInit('POST', order === undefined ? undefined : { order }),
+ ).then((r) => r.agent),
getAgentChain: (backend, model) => call<{ chain: AgentChain }>(`/api/models/agents/${backend}/chain?model=${encodeURIComponent(model)}`).then((r) => r.chain),
getAgentChains: (backend) => call<{ chains: AgentChain[] }>(`/api/models/agents/${backend}/chains`).then((r) => r.chains),
putAgentChain: (backend, model, body) => call<AgentChainMutation>(`/api/models/agents/${backend}/chain?model=${encodeURIComponent(model)}`, jsonInit('PUT', body)),
diff --git a/ui/src/components/settings/models/sourceStatePresentation.test.ts b/ui/src/components/settings/models/sourceStatePresentation.test.ts
index 72dc8bb0c..ae8721267 100644
--- a/ui/src/components/settings/models/sourceStatePresentation.test.ts
+++ b/ui/src/components/settings/models/sourceStatePresentation.test.ts
@@ -48,6 +48,18 @@ describe('sourceStatePresentation', () => {
})).toMatchObject({ key: 'settings.models.sourceDetail.status.inUse', dotClass: 'bg-mint' });
});
+ it('uses persisted route adoption for healthy gateway sources in standby', () => {
+ expect(sourceStatePresentation(state('standby'), 'card', 'zh', 0, {
+ known: true,
+ backends: ['Claude Code', 'Codex'],
+ native: false,
+ })).toMatchObject({
+ key: 'settings.models.upstream.state.supplying',
+ values: { backends: 'Claude Code、Codex' },
+ dotClass: 'bg-mint',
+ });
+ });
+
it('renders a future cooldown as a localized duration', () => {
const view = sourceStatePresentation(
state('cooldown', { retry_at: '2026-08-11T10:05:00Z' }),
diff --git a/ui/src/components/settings/models/sourceStatePresentation.ts b/ui/src/components/settings/models/sourceStatePresentation.ts
index 6521b352a..a4e0cff74 100644
--- a/ui/src/components/settings/models/sourceStatePresentation.ts
+++ b/ui/src/components/settings/models/sourceStatePresentation.ts
@@ -1,4 +1,4 @@
-import type { NeedsActionDetailKey, SourceState, SourceStatus } from './types';
+import type { AgentBackend, AdoptedBy, NeedsActionDetailKey, SourceState, SourceStatus } from './types';
export type SourceStateSurface = 'card' | 'detail';
@@ -17,6 +17,18 @@ export type SourceStatePresentation = {
dotClass: string;
};
+/**
+ * Keep the cached Source adoption projection readable while removing backends
+ * that the authoritative Agent projection has already switched to direct mode.
+ * An omitted active-backend set means the Agent read is not authoritative yet.
+ */
+export const activeSourceAdoption = (
+ adoptedBy: AdoptedBy[] | undefined,
+ activeBackends?: ReadonlySet<AgentBackend>,
+): AdoptedBy[] | undefined => activeBackends && adoptedBy
+ ? adoptedBy.filter(({ backend }) => activeBackends.has(backend))
+ : adoptedBy;
+
/**
* A healthy source that no route currently reaches. It is the state a source
* lands in the moment it is added, and 备用 next to a key just created reads as
@@ -90,7 +102,7 @@ export const sourceStatePresentation = (
if (state.status === 'active' && !adoption.known) {
return { key: null, textClass: 'text-muted', dotClass: 'bg-muted' };
}
- if (state.status === 'active' && adoption.backends.length > 0) {
+ if ((state.status === 'active' || state.status === 'standby') && adoption.backends.length > 0) {
if (surface === 'detail') {
return {
key: 'settings.models.sourceDetail.status.inUse',
diff --git a/ui/src/components/settings/models/vocabulary.test.ts b/ui/src/components/settings/models/vocabulary.test.ts
index f01b5cd61..ca601dcb0 100644
--- a/ui/src/components/settings/models/vocabulary.test.ts
+++ b/ui/src/components/settings/models/vocabulary.test.ts
@@ -19,8 +19,10 @@ describe('Models page vocabulary', () => {
expect(zh.settings.models.billing.metered).toBe('按量付费');
expect(en.settings.models.billing.monthly).toBe('Subscription');
expect(en.settings.models.billing.metered).toBe('Pay as you go');
- expect(zh.settings.models.order.subtitle).toContain('不会改动任何已配置的路由链');
- expect(en.settings.models.order.subtitle).toContain('changes no configured Route chain');
+ expect(zh.settings.models.order.subtitle).toBe('在每个型号已有路由中的来源里,排在前面的上游将优先被使用。当额度不足、触发限流、服务端、认证或网络出错导致请求无法完成时,自动切换下一优先级。');
+ expect(en.settings.models.order.subtitle).toBe("Among sources already configured in each model's route, those at the top are used first. When quota, rate-limit, server, authentication, or network failures prevent a request, the next priority is used automatically.");
+ expect(zh.settings.models.order.section['heldOut.note']).toBe('这些来源仍保留在已有路由里,排在这条顺序之后。要从路由中移除,请编辑对应型号的网关路由。');
+ expect(en.settings.models.order.section['heldOut.note']).toBe("These sources remain in existing routes after the ordered sources. To remove one from a route, edit that model's gateway route.");
expect('policy' in zh.settings.models.agents).toBe(false);
});
});
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 199091812..fa09b35a7 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -774,9 +774,9 @@
"body": "Configuration stays hidden until the runtime state can be confirmed."
}
},
- "gatewayInfo": {
- "label": "What the gateway is",
- "body": "The gateway is a dispatch layer on this machine: it holds the sources you add and supplies them to your Agents in the order you configure."
+ "modelsInfo": {
+ "label": "What a model is",
+ "body": "A model is what an Agent uses to generate a response. You can see whether each model can run, which source supplies it, and set a route for one when needed."
},
"tab": {
"hub": "Sources & gateway",
@@ -886,8 +886,10 @@
"retry": "Try again"
},
"gateway": {
- "heading": "Gateway",
- "sourceOrder": "Source order",
+ "heading": "Gateway routes",
+ "infoLabel": "What gateway routes are",
+ "info": "Gateway routes decide which upstream source each Agent's model uses first among the sources already configured in its route. When quota, rate-limit, server, authentication, or network failures prevent a request, the next priority is used automatically.",
+ "sourceOrder": "Adjust priority",
"switchToGateway": "Switch to gateway",
"switchToDirect": "Switch to direct",
"fail": {
@@ -904,8 +906,8 @@
"unread": "Could not read this backend's supply · the gateway itself is fine"
},
"row": {
- "current": "Now: {{source}}",
- "currentTakeover": "Now: {{source}} (takeover)"
+ "current": "From: {{source}}",
+ "currentTakeover": "From: {{source}} (takeover)"
},
"group": {
"subtitle": {
@@ -960,12 +962,14 @@
"andMore_other": "{{count}} more"
},
"upstream": {
- "heading": "Sources",
+ "heading": "Upstream sources",
+ "infoLabel": "What upstream sources are",
+ "info": "An upstream source is an account or API key. The gateway gets models from it and supplies them to Agents through routes.",
"count_one": "{{count}} source",
"count_other": "{{count}} sources",
"group": {
"native": "Native · on this machine",
- "hub": "Held by the gateway"
+ "hub": "Connected to gateway"
},
"kind": {
"nativeCredential": "Native · local credential",
@@ -984,7 +988,7 @@
"state": {
"supplyingNative": "Supplying {{backend}} (native)",
"supplying": "Supplying {{backends}}",
- "standby": "Standby",
+ "standby": "Available · not currently supplying",
"unavailableRetry": "Unavailable · retrying automatically after {{delay}}",
"unavailableDue": "Unavailable · the retry is due"
}
@@ -1006,7 +1010,7 @@
"count_other": "{{count}} sources",
"group": {
"native": "Native · on this machine",
- "hub": "Held by the gateway"
+ "hub": "Connected to gateway"
},
"subtitle": "Manage shared accounts and model inventories; source order is set on each agent card",
"modelCount_one": "{{count}} model",
@@ -1027,13 +1031,15 @@
"oauthSignedOut": "CLI subscription is signed out"
},
"order": {
- "title": "{{backend}} · Source order",
- "subtitle": "The Source order this backend stores. Changing it changes no configured Route chain.",
+ "title": "{{backend}} · Global route priority",
+ "subtitle": "Among sources already configured in each model's route, those at the top are used first. When quota, rate-limit, server, authentication, or network failures prevent a request, the next priority is used automatically.",
+ "infoLabel": "What global route priority is",
"reorder": "Reorder source",
"section": {
"ordered": "In this order",
"ordered.note": "Drag to reorder",
- "heldOut": "Not in this order"
+ "heldOut": "Not in this order",
+ "heldOut.note": "These sources remain in existing routes after the ordered sources. To remove one from a route, edit that model's gateway route."
},
"action": {
"include": "Add to order",
@@ -1216,7 +1222,7 @@
"retry": "Retry",
"empty": "This route chain is empty. Add a hop, or leave it unconfigured.",
"impact": { "title": "The route chain was saved", "detail": "These are the items this save actually removed or interrupted.", "refreshFail": "The route chain was saved, but the model surface could not be refreshed.", "done": "Done" },
- "hint": "This chain is stored configuration. Later source-order changes do not change it."
+ "hint": "This chain is stored configuration. Later Source order changes reorder its hops to match."
},
"recent": {
"title": "Recent switches",
@@ -1451,7 +1457,7 @@
"accountBanned": "Account restricted"
},
"error": "Error",
- "standbyHintLabel": "What standby means",
+ "standbyHintLabel": "What this status means",
"standbyHint": "This source is healthy. It reads as in use once a backend in Gateway mode serves a route through it.",
"listUpdated": "· model list updated {{time}}"
},
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 3dd5e540d..105c73e81 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -774,9 +774,9 @@
"body": "确认运行状态前不会显示网关配置。"
}
},
- "gatewayInfo": {
- "label": "什么是网关",
- "body": "网关是本机的一层调度:它持有你添加的来源,按你配置的顺序供给各个 Agent。"
+ "modelsInfo": {
+ "label": "什么是模型",
+ "body": "模型是 Agent 使用的型号。你可以查看每个型号现在能否运行、由谁供给,需要时为单个型号指定路由。"
},
"tab": {
"hub": "来源与网关",
@@ -847,7 +847,7 @@
},
"undo": {
"1": "随时可以切换回直连",
- "2": "回退入口:这一页的 {{backend}} 卡片 → 切换到直连",
+ "2": "回退入口:这一页的 {{backend}} 卡片 → 切到直连",
"3": "切回后,你添加的来源会留着,只是不再供给 {{backend}}"
},
"cancel": "取消",
@@ -886,10 +886,12 @@
"retry": "重试"
},
"gateway": {
- "heading": "网关",
- "sourceOrder": "来源顺序",
+ "heading": "网关路由",
+ "infoLabel": "什么是网关路由",
+ "info": "网关路由决定每个 Agent 的型号在已有路由中的来源里先使用哪个上游来源;当额度不足、触发限流、服务端、认证或网络出错导致请求无法完成时,自动切换下一优先级。",
+ "sourceOrder": "调整优先级",
"switchToGateway": "切换到网关",
- "switchToDirect": "切换到直连",
+ "switchToDirect": "切到直连",
"fail": {
"switchToDirect": "没能切回直连"
},
@@ -904,8 +906,8 @@
"unread": "后端供给情况没读到 · 网关本身正常"
},
"row": {
- "current": "当前 {{source}}",
- "currentTakeover": "当前 {{source}}(接管)"
+ "current": "来自 {{source}}",
+ "currentTakeover": "来自 {{source}}(接管)"
},
"group": {
"subtitle": {
@@ -960,12 +962,14 @@
"andMore_other": "另有 {{count}} 个来源"
},
"upstream": {
- "heading": "来源",
+ "heading": "上游来源",
+ "infoLabel": "什么是上游来源",
+ "info": "上游来源是账号或 API Key。网关从这里获取型号,再按路由供给 Agent。",
"count_one": "{{count}} 个",
"count_other": "{{count}} 个",
"group": {
"native": "本机原生",
- "hub": "网关持有"
+ "hub": "接入网关"
},
"kind": {
"nativeCredential": "原生 · 本机凭据",
@@ -984,7 +988,7 @@
"state": {
"supplyingNative": "正在供给 {{backend}}(原生)",
"supplying": "正在供给 {{backends}}",
- "standby": "备用",
+ "standby": "可用 · 当前未供给",
"unavailableRetry": "暂不可用 · {{delay}} 后自动重试",
"unavailableDue": "暂不可用 · 已到重试时间"
}
@@ -1006,7 +1010,7 @@
"count_other": "{{count}} 个",
"group": {
"native": "本机原生",
- "hub": "网关持有"
+ "hub": "接入网关"
},
"subtitle": "管理全局共用的账号和型号清单;来源顺序在各 Agent 卡片中调整",
"modelCount_one": "{{count}} 个型号",
@@ -1027,13 +1031,15 @@
"oauthSignedOut": "CLI 订阅未登录"
},
"order": {
- "title": "{{backend}} · 来源顺序",
- "subtitle": "这个后端存下来的来源顺序。改动它不会改动任何已配置的路由链。",
+ "title": "{{backend}} · 全局路由优先级",
+ "subtitle": "在每个型号已有路由中的来源里,排在前面的上游将优先被使用。当额度不足、触发限流、服务端、认证或网络出错导致请求无法完成时,自动切换下一优先级。",
+ "infoLabel": "什么是全局路由优先级",
"reorder": "调整来源顺序",
"section": {
"ordered": "排在这条顺序里",
"ordered.note": "拖动排序",
- "heldOut": "未排入这条顺序"
+ "heldOut": "未排入这条顺序",
+ "heldOut.note": "这些来源仍保留在已有路由里,排在这条顺序之后。要从路由中移除,请编辑对应型号的网关路由。"
},
"action": {
"include": "排进来",
@@ -1216,7 +1222,7 @@
"retry": "重试",
"empty": "这条路由链是空的。添加一跳,或保持为空配置。",
"impact": { "title": "路由链已保存", "detail": "以下是这次保存实际移除或中断的项目。", "refreshFail": "路由链已保存,但模型页面暂时无法刷新。", "done": "完成" },
- "hint": "这条链是写下来的配置。以后来源顺序怎么变,它都不变。"
+ "hint": "这条链是写下来的配置。以后调整来源顺序时,其中的来源会按新的顺序重排。"
},
"recent": {
"title": "最近切换",
@@ -1451,7 +1457,7 @@
"accountBanned": "账号被限制"
},
"error": "异常",
- "standbyHintLabel": "备用是什么意思",
+ "standbyHintLabel": "这个状态是什么意思",
"standbyHint": "这个来源是健康的。当网关模式下的某个后端通过它供给一条路由时,它就会显示为使用中。",
"listUpdated": "· 型号列表更新于 {{time}}"
},
diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.py
index f4c9eead1..a40911b39 100644
--- a/vibe/model_hub_client.py
+++ b/vibe/model_hub_client.py
@@ -13,6 +13,7 @@ from vibe.internal_client import default_socket_path
_TRANSPORT_ERRORS = (httpx.ConnectError, httpx.TimeoutException, OSError)
_RPC_TIMEOUT_SECONDS = 300.0
+_REORDER_ORDER_UNSET = object()
def _decode(response: httpx.Response) -> Any:
@@ -155,8 +156,11 @@ class ModelHubRemoteService:
{"backend": backend, "sources": sources},
)
- async def reorder_agent_chains(self, backend: str) -> dict:
- return await _rpc("reorder_agent_chains", {"backend": backend})
+ async def reorder_agent_chains(self, backend: str, order: object = _REORDER_ORDER_UNSET) -> dict:
+ payload = {"backend": backend}
+ if order is not _REORDER_ORDER_UNSET:
+ payload["order"] = order
+ return await _rpc("reorder_agent_chains", payload)
async def set_agent_mode(self, backend: str, mode: object) -> dict:
return await _rpc("set_agent_mode", {"backend": backend, "mode": mode})
diff --git a/vibe/ui_compat.py b/vibe/ui_compat.py
index 8746a982d..8abf091aa 100644
--- a/vibe/ui_compat.py
+++ b/vibe/ui_compat.py
@@ -46,6 +46,7 @@ class CompatRequest:
def __init__(self, request: FastAPIRequest, json_payload: Any = None) -> None:
self._request = request
self._json_payload = json_payload
+ self._body_present = json_payload is not None
@property
def method(self) -> str:
@@ -71,6 +72,10 @@ class CompatRequest:
def json(self) -> Any:
return self._json_payload
+ @property
+ def has_body(self) -> bool:
+ return self._body_present
+
async def load_json(self) -> Any:
"""Parse and cache JSON when a shared request hook needs the body."""
@@ -361,6 +366,7 @@ class CompatApp(FastAPI):
path: str,
methods: list[str] | tuple[str, ...] | None = None,
defaults: dict[str, Any] | None = None,
+ allow_malformed_json: bool = False,
**kwargs: Any,
):
methods = tuple(methods or ("GET",))
@@ -375,6 +381,7 @@ class CompatApp(FastAPI):
func,
route_regex,
defaults,
+ allow_malformed_json=allow_malformed_json,
)
endpoint.__name__ = f"{func.__name__}_compat_endpoint"
@@ -453,6 +460,7 @@ class CompatApp(FastAPI):
break
if response is None:
if parse_json:
+ compat_request._body_present = bool(await starlette_request.body())
compat_request._json_payload = await _read_json_payload(starlette_request)
response = normalize_response(await run_maybe_async(func))
except Exception as exc:
@@ -490,6 +498,8 @@ class CompatApp(FastAPI):
func: Callable[..., Any],
route_regex: re.Pattern[str],
defaults: dict[str, Any],
+ *,
+ allow_malformed_json: bool = False,
) -> Response:
remote_addr = _test_remote_addr_from_scope(starlette_request.scope)
if remote_addr:
@@ -506,7 +516,13 @@ class CompatApp(FastAPI):
response = normalize_response(result)
break
if response is None:
- compat_request._json_payload = await _read_json_payload(starlette_request)
+ compat_request._body_present = bool(await starlette_request.body())
+ try:
+ compat_request._json_payload = await _read_json_payload(starlette_request)
+ except HTTPException as exc:
+ if not allow_malformed_json or exc.detail != "Malformed JSON":
+ raise
+ compat_request._json_payload = None
route_args = defaults | _extract_path_args(route_regex, compat_request.path)
response = normalize_response(await run_maybe_async(func, **route_args))
except Exception as exc:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index ffaa49f04..0bef3a1f7 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -4594,12 +4594,29 @@ async def model_hub_agent_sources_put(backend):
return _model_hub_error(exc)
[email protected]("/api/models/agents/<backend>/chains/reorder", methods=["POST"])
+ "/api/models/agents/<backend>/chains/reorder",
+ methods=["POST"],
+ allow_malformed_json=True,
+)
async def model_hub_agent_chains_reorder_post(backend):
from core.handlers.model_hub import ModelHubError
try:
- agent = await _model_hub_service().reorder_agent_chains(backend)
+ payload = request.json
+ if payload is None:
+ if request.has_body:
+ raise ModelHubError("invalid_source_order")
+ payload = {}
+ if not isinstance(payload, dict) or set(payload) - {"order"}:
+ raise ModelHubError("invalid_source_order")
+ if "order" in payload:
+ agent = await _model_hub_service().reorder_agent_chains(
+ backend,
+ payload["order"],
+ )
+ else:
+ agent = await _model_hub_service().reorder_agent_chains(backend)
return _model_hub_success(agent=agent)
except ModelHubError as exc:
return _model_hub_error(exc)