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): batch overview chain reads

cyh25d031d4da86
diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.py
index 15c37fe8c..7838c7f6c 100644
--- a/core/handlers/model_hub/rpc.py
+++ b/core/handlers/model_hub/rpc.py
@@ -106,6 +106,8 @@ async def dispatch_model_hub_rpc(
)
if operation == "get_agent_chain":
return service.agent_chain(payload.get("backend"), payload.get("model_id"))
+ if operation == "get_agent_chains":
+ return service.agent_chains(payload.get("backend"))
if operation == "probe_agent":
return await service.probe_agent(
payload.get("backend"),
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index f4116c9ee..a9059bbe4 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -652,6 +652,24 @@ class ModelHubService:
return requested_model
return ""
+ def _agent_model_ids(
+ self,
+ agent: ModelHubAgentSupplyConfig,
+ requested_model: str,
+ ) -> list[str]:
+ primary = (
+ list(_builtin_model_ids(agent.backend))
+ if agent.menu_kind == "fixed"
+ else list(agent.menu.checked if agent.menu else ())
+ )
+ seen: set[str] = set()
+ model_ids: list[str] = []
+ for model_id in [*primary, requested_model, *agent.routes]:
+ if model_id and model_id not in seen:
+ seen.add(model_id)
+ model_ids.append(model_id)
+ return model_ids
+
def _unavailable_native_sources(
self,
config: ModelHubConfig,
@@ -3685,20 +3703,27 @@ class ModelHubService:
config: ModelHubConfig,
backend: str,
model_id: str,
+ *,
+ now: Optional[datetime] = None,
+ unavailable_source_ids: Optional[frozenset[str]] = None,
) -> dict:
agent = self._agent(config, backend)
if agent.mode == "direct":
raise self._direct_mode_error()
- now = self.now()
- unavailable = self._unavailable_native_sources(
- config,
- cast(BackendName, backend),
+ observed_at = now or self.now()
+ unavailable = (
+ unavailable_source_ids
+ if unavailable_source_ids is not None
+ else self._unavailable_native_sources(
+ config,
+ cast(BackendName, backend),
+ )
)
resolution = resolve_model_hub_turn(
config,
cast(BackendName, backend),
model_id,
- now=now,
+ now=observed_at,
unavailable_source_ids=unavailable,
)
chain: list[dict] = []
@@ -3756,6 +3781,30 @@ class ModelHubService:
raise ModelHubError("mapping_target_unavailable", status=409)
return self._agent_chain(self.store.load(), backend, model_id)
+ def agent_chains(self, backend: str) -> list[dict]:
+ if backend not in MODEL_HUB_BACKENDS:
+ raise ModelHubError("mapping_target_unavailable", status=409)
+ config = self.store.load()
+ agent = self._agent(config, backend)
+ if agent.mode == "direct":
+ raise self._direct_mode_error()
+ requested_model = self._requested_model(agent)
+ observed_at = self.now()
+ unavailable_source_ids = self._unavailable_native_sources(
+ config,
+ cast(BackendName, backend),
+ )
+ return [
+ self._agent_chain(
+ config,
+ backend,
+ model_id,
+ now=observed_at,
+ unavailable_source_ids=unavailable_source_ids,
+ )
+ for model_id in self._agent_model_ids(agent, requested_model)
+ ]
+
@staticmethod
def _probe_request(
source: ModelHubSourceConfig,
diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.json
index 092399696..940ffe6cd 100644
--- a/docs/plans/model-hub-contracts/api-response.schema.json
+++ b/docs/plans/model-hub-contracts/api-response.schema.json
@@ -22,6 +22,7 @@
{"method": "POST", "path": "/api/models/agents/<backend>/chains/reorder", "response_schema": "AgentResponse", "exercise": {"path": "/api/models/agents/claude/chains/reorder", "status": 200}},
{"method": "PATCH", "path": "/api/models/agents/<backend>/mode", "response_schema": "AgentResponse", "exercise": {"path": "/api/models/agents/claude/mode", "status": 200, "json": {"mode": "hub"}}},
{"method": "PUT", "path": "/api/models/agents/opencode/menu", "response_schema": "AgentResponse", "exercise": {"path": "/api/models/agents/opencode/menu", "status": 200, "json": {"menu": {"view": "featured", "checked": []}}}},
+ {"method": "GET", "path": "/api/models/agents/<backend>/chains", "response_schema": "ChainListResponse", "exercise": {"path": "/api/models/agents/claude/chains", "status": 200}},
{"method": "GET", "path": "/api/models/agents/<backend>/chain?model=<id>", "response_schema": "ChainResponse", "exercise": {"path": "/api/models/agents/claude/chain?model=claude-opus-4-6", "status": 200}},
{"method": "PUT", "path": "/api/models/agents/<backend>/chain?model=<id>", "response_schema": "ChainMutationResponse", "exercise": {"path": "/api/models/agents/claude/chain?model=claude-opus-4-6", "status": 200, "json": {"hops": [{"source_id": "src_conform001", "model_id": "claude-opus-4-6"}]}}},
{"method": "POST", "path": "/api/models/agents/<backend>/probe", "response_schema": "ProbeResponse", "exercise": {"path": "/api/models/agents/claude/probe", "status": 200, "json": {"model": "claude-opus-4-6"}}},
@@ -233,6 +234,16 @@
"chain": {"$ref": "model-hub/agent-chain.schema.json"}
}
},
+ "ChainListResponse": {
+ "type": "object",
+ "required": ["ok", "contract_version", "chains"],
+ "additionalProperties": false,
+ "properties": {
+ "ok": {"const": true},
+ "contract_version": {"const": 6},
+ "chains": {"type": "array", "items": {"$ref": "model-hub/agent-chain.schema.json"}}
+ }
+ },
"ChainMutationResponse": {
"type": "object",
"required": ["ok", "contract_version", "chain", "removed_hops", "interrupted"],
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index 2f402f470..3fd4cabac 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -41,6 +41,7 @@ compatibility path.
| 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. |
| 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. |
| GET `/api/models/agents/<backend>/chain?model=<id>` | → `{chain: AgentChain}` | Hub only. Direct returns the documented `direct_mode` error. |
| PUT `/api/models/agents/<backend>/chain?model=<id>` | `{hops: RouteHop[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{chain, removed_hops, interrupted}` | Replaces the exact Source/model pairs in submitted order after validating new or changed pairs; the handler never reads `sources.order`, and the submitted `hops` carry no Source-order semantics. It is the `mutation.route_replace` row of the authoritative mutation matrix. A visible noninterrupting hop removal is ordinary success; only a resulting protected-supply interruption enters the guard. |
| POST `/api/models/agents/<backend>/probe` | `{model?}` → `{probe: ProbeResult}` | Hub only. Direct returns the same `direct_mode` error. |
diff --git a/docs/plans/model-hub-ui-spec.md b/docs/plans/model-hub-ui-spec.md
index f41f17a2c..a228f233e 100644
--- a/docs/plans/model-hub-ui-spec.md
+++ b/docs/plans/model-hub-ui-spec.md
@@ -819,7 +819,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 per-model 当前 line is a third 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 |
@@ -835,10 +835,10 @@ state exit; held intent never bypasses the evidence column.
| §1.1 | Backend has no models | The group resolves to zero model rows `[derived]` | F5 | `gateway.group.emptyModels` | A model becomes available to that backend |
| §1.1 | No enabled Agent uses this backend | `mode` reads `hub` and `named_agents` is empty `[contract]` | F5 — a rendered report, not a request | `gateway.group.subtitle.gateway`, `gateway.group.mode.gateway`, `gateway.group.status.unused` | An enabled Agent begins using this backend; its live rollup enters the aggregate and selects Ready, waiting, degraded or interrupted |
| §1.1 | Per-model route unconfigured | The page-grain `model_supply` row reads `chain_length: 0`; this structural branch is evaluated before the forced `has_runnable_hop: false` reading `[contract]` | F5 for the page-grain statement; an outstanding or failed chain detail read remains F2 only for its other derived columns | server-owned `models.launch.route_unconfigured`, consumed verbatim | Render the existing route-unconfigured family in the current-text slot; never gold 供给已暂停 / Supply paused. A later page-grain payload with `chain_length > 0` leaves this structural state and is dispatched by `has_runnable_hop` |
-| §1.1 | Per-model supply paused | The page-grain `model_supply` row reads `chain_length > 0` and `has_runnable_hop: false` `[contract]` | F5 for the page-grain marker; an outstanding or failed chain detail read remains F2 only for its other derived columns | `legend.unavailable` in the existing current-text slot | Render 供给已暂停 / Supply paused immediately in `$--gold`; do not wait for the per-model chain read. A later page-grain payload with `has_runnable_hop: true` removes the marker; `chain_length: 0` instead enters Per-model route unconfigured. The chain read may still fill its other derived columns, but a pending or failed detail read cannot erase or replace this page-owned marker |
-| §1.1 | Takeover active | The chain read — `GET /api/models/agents/<backend>/chain?model=<id>` — returns non-null `current` different from `chain[0]`, while the head is unavailable for a recoverable quota/cooldown or live connection-backoff reason `[contract]` | F5 | `gateway.group.takenOver`, `gateway.row.currentTakeover`, `gateway.group.status.degraded` | Re-evaluate the complete predicate on every later chain payload. `current` back at the head → Ready. A head that is runnable / no longer recoverably unavailable also retires Takeover immediately under the derived-state predicate rule: if `current` still names the later hop, render the ordinary serving/current-hop projection without violet takeover ink or copy until a later payload changes `current`. A local clock alone changes no payload. This is frame 08 (§1.7) |
+| §1.1 | Per-model supply paused | The page-grain `model_supply` row reads `chain_length > 0` and `has_runnable_hop: false` `[contract]` | F5 for the page-grain marker; an outstanding or failed chain-collection member remains F2 only for its other derived columns | `legend.unavailable` in the existing current-text slot | Render 供给已暂停 / Supply paused immediately in `$--gold`; do not wait for the backend chain collection. A later page-grain payload with `has_runnable_hop: true` removes the marker; `chain_length: 0` instead enters Per-model route unconfigured. The collection member may still fill its other derived columns, but a pending or failed detail read cannot erase or replace this page-owned marker |
+| §1.1 | Takeover active | A member of `GET /api/models/agents/<backend>/chains` returns non-null `current` different from `chain[0]`, while the head is unavailable for a recoverable quota/cooldown or live connection-backoff reason `[contract]` | F5 | `gateway.group.takenOver`, `gateway.row.currentTakeover`, `gateway.group.status.degraded` | Re-evaluate the complete predicate on every later chain payload. `current` back at the head → Ready. A head that is runnable / no longer recoverably unavailable also retires Takeover immediately under the derived-state predicate rule: if `current` still names the later hop, render the ordinary serving/current-hop projection without violet takeover ink or copy until a later payload changes `current`. A local clock alone changes no payload. This is frame 08 (§1.7) |
| §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. That same chain read is outstanding for this row, or came back failed or refused, 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 | The read 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 every row in it, 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 | 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.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 |
@@ -1741,19 +1741,20 @@ dispatch arbitrates → each backend's models resolve to these sources today.
| `FZUYI` wire layer | one path per supply relation + endpoint dots | derived supply set | no | — |
| `ftWgW` legend info icon | the legend's note — **the string is measured from the frame, not specified here** (§0.2) | static | hover, focus **and** activation — the same three §1.0's title icon carries | Tooltip, the note standing as the icon's accessible description |
-**The 当前 line is a third read, and the page does not wait on it** `[contract]`. Every
+**The 当前 lines are a third read, and the page does not wait on it** `[contract]`. Every
element above it is drawn from the two page-level payloads — tile, name, count, the mode
and status line, the head buttons, the collapse row — but the serving hop is in neither:
`api.md` states that AgentSupply projects no backend-level serving head; `model_supply`
-carries row-grain configuration/runnability facts but no current hop. The one read that carries hops at all is
-`GET /api/models/agents/<backend>/chain?model=<id>`, per model and Hub only — a 直连
+carries row-grain configuration/runnability facts but no current hop. Overview reads every
+row's existing AgentChain shape through one `GET /api/models/agents/<backend>/chains`
+per Hub backend — a 直连
backend gets the documented `direct_mode` refusal. So 「Ready」 is defined on the two
payloads on purpose: waiting on the third would hold the whole page for one row's
projection, and on a 直连 group it would wait for a read the contract refuses. That
refusal is also why a 直连 group draws no 当前 line and no takeover rather than an empty
one — there is nothing there to be pending about.
-**When that read answers, `current` names the serving hop exactly** `[contract]`.
+**When a collection member answers, `current` names the serving hop exactly** `[contract]`.
`agent-chain.schema.json` requires either null or an exact member of `chain`; the page
renders that member and never substitutes the first runnable hop. Takeover is true only
when `current` is not the chain head and that head is unavailable for a recoverable
@@ -1763,9 +1764,9 @@ no takeover visual. Every later chain payload re-evaluates that complete predica
`current` still names the successor, that successor is rendered as the ordinary serving
hop without takeover ink or copy.
-**Until that read answers, only facts the page payload already proved may replace `—`**
-`[derived]`. Chain and takeover render `—` while the chain read is outstanding, and
-again when it comes back failed or refused. Current source does too when
+**Until that collection member answers, only facts the page payload already proved may replace `—`**
+`[derived]`. Chain and takeover render `—` while the collection is outstanding, and
+again when it fails, is refused or omits the member. Current source does too when
`has_runnable_hop` is true. When that page-grain field is false, however, the existing
current-text slot immediately renders a page-owned statement: `chain_length: 0` first
selects server-owned `models.launch.route_unconfigured`, while a nonempty chain selects
@@ -1787,8 +1788,8 @@ drew.
this one** `[derived]` D-35. 「Chain unresolved」 is the only failure state on this page
whose repair is not a control drawn beside it: the three columns render `—`, the frame
carries no per-row 重试, and a row left there would be waiting on a request nothing was
-going to send again. Collapsing a group and expanding it re-reads every row in it, which
-costs no new control and reads as what it already means. The page's own two triggers sit
+going to send again. Collapsing a group and expanding it re-reads that backend's collection
+once, which costs no new control and reads as what it already means. The page's own two triggers sit
beside it — any mutation re-renders the group, and the next load re-reads everything —
so the user-available repair and the ambient ones agree. What this row must not do is
resolve on a clock: a poll cadence is a number this file has no basis to pick, and 「no
@@ -1873,8 +1874,8 @@ collapse label count = |collapsed|
partitions a false value into structural `models.launch.route_unconfigured` at zero and
`legend.unavailable` for a nonempty chain. Which hop is current and why another is
unavailable belong to the third read (「Chain unresolved」 above), and **neither consumer
-may manufacture those details.** That read is per model, asynchronous, and allowed to
-fail, so visibility must not consume it. A row whose chain read is outstanding, failed
+may manufacture those details.** That read is per backend, asynchronous, and allowed to
+fail, so visibility must not consume it. A row whose collection member is outstanding, missing, failed
or refused keeps exactly the position and visibility the backend menu gave it. Expanding
reveals any paused or unconfigured row beyond the first six without changing its
classification.
@@ -5765,15 +5766,15 @@ failed region with no unread line and no 重试 — under the one engine reading
failed read *more* likely, not less. §1.1's *Chain unresolved* is this rule one grain
further down, and it is why that row exists instead of a transition into Unreachable.
-**D-35 — The collapse row is the chain read's re-read control.** Collapsing a group and
-expanding it re-issues the per-model chain read for every row in it. §1.1's *Chain
+**D-35 — The collapse row is the chain collection's re-read control.** Collapsing a group and
+expanding it re-issues one chain-collection read for that backend. §1.1's *Chain
unresolved* names it as the repair, and no per-row 重试 is added to the frame.
For a page-owned RO `unknown` whose exact-chain observation failed or did not match, this same
re-expansion is the only read retry: it reacquires one RO-O generation when Hub-observable,
retains the submitted pairs/stage and sends no mutation. A nonmatching answer installs the
current chain but does not settle or abandon the attempt; Direct-suspended keeps the evidence
and sends nothing.
-*Why:* that read is per row, allowed to fail, and drawn nowhere, so a row whose read
+*Why:* each collection member is row-grain, allowed to be unresolved, and drawn nowhere, so a row whose read
failed had `—` in three columns and nothing that would ask again — a dead end, which is
worse than the dead control D-9a rules out and is not licensed by it. A control already
on the frame, already meaning 「show me this group's rows」, re-reads them at no cost in
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 22154f7f8..4e48ab39a 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -372,6 +372,12 @@ scenarios:
kind: recovery
layer: scenario
test: tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py::test_mh_turn_takeover_is_silent_and_provenance_names_the_serving_hop
+ - id: MH-OVERVIEW-001
+ name: Overview batches model chains by backend and reserves exact reads for route editing
+ status: covered
+ kind: projection
+ layer: unit
+ test: ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-OVERVIEW-001
- id: MH-ENGINE-001
name: Local engine loss is terminal without Source mutation or replay
status: covered
diff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.py
index 9fb0ed693..a51638c23 100644
--- a/tests/test_instance_authorization.py
+++ b/tests/test_instance_authorization.py
@@ -342,6 +342,7 @@ def test_advertised_capability_namespaces_cover_current_and_future_routes() -> N
("POST", "/api/agents/default"),
("PATCH", "/api/agents/demo"),
("DELETE", "/api/agents/demo"),
+ ("GET", "/api/models/agents/codex/chains"),
("PUT", "/api/models/agents/codex/chain"),
("PUT", "/api/global-prompts"),
("POST", "/api/projects"),
@@ -491,6 +492,7 @@ def test_agents_page_load_reads_are_admitted_for_every_rank_that_sees_the_page()
("GET", "/api/agents/demo"),
("GET", "/api/running-agents"),
("GET", "/api/models/agents"),
+ ("GET", "/api/models/agents/claude/chains"),
)
catalog_reads = (
("GET", "/api/claude/models"),
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 05cc890c3..51c1f47c4 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -1889,6 +1889,44 @@ def test_agents_endpoint_projects_exact_chain_runnability(tmp_path):
assert blocked[model_id]["has_runnable_hop"] is False
+def test_agent_chains_returns_the_complete_overview_from_one_snapshot(tmp_path):
+ service, store, _adapter = _service(tmp_path)
+ agent = store.config.agents["claude"]
+ routed_extra = "claude-route-only"
+ selected_extra = "claude-selected-only"
+ agent.routes[routed_extra] = ModelHubRouteConfig()
+ store.requested_models["claude"] = selected_extra
+ expected_model_ids = list(
+ dict.fromkeys(
+ [
+ *service.get_agent_sources("claude")["builtin_models"],
+ selected_extra,
+ *agent.routes,
+ ]
+ )
+ )
+
+ load_count = 0
+ original_load = store.load
+
+ def counted_load():
+ nonlocal load_count
+ load_count += 1
+ return original_load()
+
+ store.load = counted_load
+ chains = service.agent_chains("claude")
+
+ assert load_count == 1
+ model_ids = [chain["model_id"] for chain in chains]
+ assert model_ids == expected_model_ids
+ assert selected_extra in model_ids
+ assert routed_extra in model_ids
+ assert len(model_ids) == len(set(model_ids))
+ for chain in chains:
+ _assert_valid("agent-chain.schema.json", chain)
+
+
def test_agents_endpoint_cli_presence_probe_errors_fail_closed(tmp_path):
service, _store, _adapter = _service(tmp_path)
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index ebfd7d2f4..df351ac73 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -545,7 +545,7 @@ describe('SettingsModelsPage surface branches', () => {
vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([takeoverAgent]);
vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);
vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);
- vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(takeoverChain);
+ vi.spyOn(modelsApi, 'getAgentChains').mockResolvedValue([takeoverChain]);
render(
<ToastProvider>
@@ -560,6 +560,51 @@ describe('SettingsModelsPage surface branches', () => {
expect(screen.getByText(/Now: 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 () => {
+ const secondModel = 'gpt-5.6-terra';
+ const agent: AgentSupply = {
+ ...takeoverAgent,
+ builtin_models: [takeoverChain.model_id, secondModel],
+ model_supply: [takeoverChain.model_id, secondModel].map((model_id) => ({
+ model_id,
+ chain_length: 2,
+ has_runnable_hop: true,
+ })),
+ routes: {
+ ...takeoverAgent.routes,
+ [secondModel]: { hops: takeoverAgent.routes![takeoverChain.model_id].hops },
+ },
+ };
+ const secondChain: AgentChain = { ...takeoverChain, model_id: secondModel };
+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);
+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([agent]);
+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);
+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);
+ const overviewRead = vi.spyOn(modelsApi, 'getAgentChains').mockResolvedValue([
+ takeoverChain,
+ secondChain,
+ ]);
+ const exactRead = vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(takeoverChain);
+
+ render(
+ <ToastProvider>
+ <I18nextProvider i18n={i18n}>
+ <SettingsModelsPage />
+ </I18nextProvider>
+ </ToastProvider>,
+ );
+
+ await waitFor(() => expect(overviewRead).toHaveBeenCalledOnce());
+ expect(overviewRead).toHaveBeenCalledWith('codex');
+ expect(exactRead).not.toHaveBeenCalled();
+
+ await userEvent.click(await screen.findByRole('button', {
+ name: /Open gpt-5\.6-sol route chain|打开 gpt-5\.6-sol 的路由链/i,
+ }));
+ await waitFor(() => expect(exactRead).toHaveBeenCalledOnce());
+ expect(exactRead).toHaveBeenCalledWith('codex', 'gpt-5.6-sol');
+ });
+
it('keeps a failed event read distinct from an empty history and retries it', async () => {
const hubAgent: AgentSupply = {
...directAgent('claude'),
@@ -621,7 +666,7 @@ describe('SettingsModelsPage surface branches', () => {
expect(screen.queryByRole('button', { name: /Gateway stopped|网关已停止/i })).toBeNull();
});
- it('lands the overview without waiting for a per-model chain read', async () => {
+ it('lands the overview without waiting for its backend chain collection', async () => {
const hubAgent: AgentSupply = {
...takeoverAgent,
backend: 'claude',
@@ -635,7 +680,7 @@ describe('SettingsModelsPage surface branches', () => {
vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([hubAgent]);
vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);
vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);
- vi.spyOn(modelsApi, 'getAgentChain').mockImplementation(() => new Promise(() => {}));
+ vi.spyOn(modelsApi, 'getAgentChains').mockImplementation(() => new Promise(() => {}));
render(
<ToastProvider>
@@ -697,6 +742,7 @@ describe('SettingsModelsPage surface branches', () => {
vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([hubAgent]);
vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);
vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);
+ const overviewRead = vi.spyOn(modelsApi, 'getAgentChains').mockResolvedValue([affectedChain]);
const chainRead = vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(affectedChain);
if (action === 'edit') {
vi.spyOn(modelsApi, 'patchSource').mockResolvedValueOnce({ source: updatedSource, ...impact });
@@ -712,7 +758,7 @@ describe('SettingsModelsPage surface branches', () => {
</ToastProvider>,
);
await userEvent.click((await screen.findByText('Retained source')).closest('button') as HTMLButtonElement);
- await waitFor(() => expect(chainRead).toHaveBeenCalled());
+ await waitFor(() => expect(overviewRead).toHaveBeenCalledOnce());
await userEvent.click(screen.getByRole('button', { name: /Manage Retained source|管理 Retained source/i }));
if (action === 'edit') {
@@ -767,7 +813,7 @@ describe('SettingsModelsPage surface branches', () => {
const head = { ...retainedSource, id: 'src_head', display_name: 'Paused source', state: { status: 'cooldown' as const, retry_at: '2099-01-01T00:00:00Z', detail_key: null } };
const relay = { ...retainedSource, id: 'src_relay', display_name: 'Replacement source', state: { status: 'active' as const, retry_at: null, detail_key: null } };
const direct = { ...takeoverAgent, mode: 'direct' as const, sources: null, routes: null, supply_status: null, model_supply: null };
- const pendingChain = deferred<AgentChain>();
+ const pendingChains = deferred<AgentChain[]>();
vi.spyOn(modelsApi, 'listSources').mockResolvedValue([head, relay]);
const agentRead = vi.spyOn(modelsApi, 'listAgents')
.mockResolvedValueOnce([takeoverAgent])
@@ -775,7 +821,7 @@ describe('SettingsModelsPage surface branches', () => {
vi.spyOn(modelsApi, 'setAgentMode').mockResolvedValueOnce(direct);
vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);
vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);
- const chainRead = vi.spyOn(modelsApi, 'getAgentChain').mockImplementation(() => pendingChain.promise);
+ const chainRead = vi.spyOn(modelsApi, 'getAgentChains').mockImplementation(() => pendingChains.promise);
render(
<ToastProvider>
@@ -791,8 +837,8 @@ describe('SettingsModelsPage surface branches', () => {
expect(await screen.findByRole('button', { name: /^Switch to Gateway$|^切换到网关$/i })).toBeTruthy();
await act(async () => {
- pendingChain.resolve(takeoverChain);
- await pendingChain.promise;
+ pendingChains.resolve([takeoverChain]);
+ await pendingChains.promise;
});
expect(screen.queryByRole('button', { name: /route chain|路由链/i })).toBeNull();
@@ -816,9 +862,8 @@ describe('SettingsModelsPage surface branches', () => {
.mockReturnValueOnce(pendingReconciliation.promise);
vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);
vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);
- vi.spyOn(modelsApi, 'getAgentChain')
- .mockReturnValueOnce(pendingOldChain.promise)
- .mockResolvedValueOnce(takeoverChain);
+ vi.spyOn(modelsApi, 'getAgentChains').mockImplementation(() => pendingOldChain.promise.then((chain) => [chain]));
+ vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(takeoverChain);
vi.spyOn(modelsApi, 'putAgentChain').mockResolvedValue({
chain: committedChain,
removed_hops: [],
@@ -858,6 +903,7 @@ describe('SettingsModelsPage surface branches', () => {
.mockResolvedValueOnce([]);
vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);
vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);
+ vi.spyOn(modelsApi, 'getAgentChains').mockResolvedValue([takeoverChain]);
vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(takeoverChain);
vi.spyOn(modelsApi, 'putAgentChain').mockResolvedValue({
chain: { ...takeoverChain, chain: [takeoverChain.chain[0]], current: takeoverChain.chain[0] },
@@ -900,7 +946,7 @@ describe('SettingsModelsPage surface branches', () => {
vi.spyOn(modelsApi, 'listSources').mockResolvedValue([retainedSource]);
vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);
vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);
- vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(takeoverChain);
+ vi.spyOn(modelsApi, 'getAgentChains').mockResolvedValue([takeoverChain]);
const setMode = vi.spyOn(modelsApi, 'setAgentMode').mockRejectedValueOnce(new TypeError('response lost'));
render(
@@ -929,7 +975,7 @@ describe('SettingsModelsPage surface branches', () => {
vi.spyOn(modelsApi, 'refreshSource').mockResolvedValueOnce({ source: head, discovered: head.models.length });
vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);
vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);
- vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(takeoverChain);
+ vi.spyOn(modelsApi, 'getAgentChains').mockResolvedValue([takeoverChain]);
render(
<ToastProvider>
@@ -960,7 +1006,7 @@ describe('SettingsModelsPage surface branches', () => {
.mockRejectedValueOnce(new TypeError('runtime unread'));
vi.spyOn(modelsApi, 'refreshSource').mockResolvedValueOnce({ source: head, discovered: head.models.length });
vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);
- vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(takeoverChain);
+ vi.spyOn(modelsApi, 'getAgentChains').mockResolvedValue([takeoverChain]);
render(
<ToastProvider>
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index ffc422cf3..1907bf145 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -88,8 +88,26 @@ const readChainRequests = async (requests: readonly ModelChainRequest[]): Promis
),
);
-const readAgentChains = async (agent: AgentSupply): Promise<ModelChainIndex> =>
- readChainRequests(modelChainRequests([agent]));
+const readAgentChains = async (agent: AgentSupply): Promise<ModelChainIndex> => {
+ const requests = modelChainRequests([agent]);
+ try {
+ const chains = new Map(
+ (await modelsApi.getAgentChains(agent.backend)).map((chain) => [chain.model_id, chain]),
+ );
+ return Object.fromEntries(requests.map(({ backend, modelId }) => {
+ const chain = chains.get(modelId);
+ return [
+ modelChainKey(backend, modelId),
+ chain?.backend === backend ? readyRegion(chain) : unreadRegion(),
+ ];
+ }));
+ } catch {
+ return Object.fromEntries(requests.map(({ backend, modelId }) => [
+ modelChainKey(backend, modelId),
+ unreadRegion(),
+ ]));
+ }
+};
const readExactAgentChain = async (
agent: AgentSupply,
diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.ts
index 5f3efd284..7a147e768 100644
--- a/ui/src/components/settings/models/modelsApi.ts
+++ b/ui/src/components/settings/models/modelsApi.ts
@@ -116,6 +116,8 @@ export type ModelsApi = {
putAgentSources(backend: AgentBackend, body: AgentSourcesPut): 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. */
+ getAgentChains(backend: AgentBackend): Promise<AgentChain[]>;
/** Total replacement of the exact stored chain. */
putAgentChain(backend: AgentBackend, model: string, body: AgentChainPut): Promise<AgentChainMutation>;
/** One real request through the chain. Hub mode only, same reason. */
@@ -451,6 +453,7 @@ export const modelsApi: ModelsApi = {
// `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),
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)),
probeAgent: (backend, model) => call<{ probe: ProbeResult }>(`/api/models/agents/${backend}/probe`, jsonInit('POST', model ? { model } : {})).then((r) => r.probe),
setAgentMode: (backend, mode) => call<{ agent?: AgentSupply } & AgentSupply>(`/api/models/agents/${backend}/mode`, jsonInit('PATCH', { mode })).then((r) => (r.agent ?? r) as AgentSupply),
diff --git a/ui/src/components/settings/models/regionRead.test.ts b/ui/src/components/settings/models/regionRead.test.ts
index 46d20bafe..1bd6b283e 100644
--- a/ui/src/components/settings/models/regionRead.test.ts
+++ b/ui/src/components/settings/models/regionRead.test.ts
@@ -105,10 +105,11 @@ describe('RegionRead', () => {
expect(dialog).not.toMatch(/runtime: RuntimeDependency \| null/);
});
- it('routes every per-model chain read through the per-backend latest authority', () => {
+ it('routes overview collections and exact chain reads through the per-backend latest authority', () => {
const page = readFileSync(join(__dirname, 'SettingsModelsPage.tsx'), 'utf8');
const definitionStart = page.indexOf('const readChainRequests');
const definitionEnd = page.indexOf('\n\nconst settleAgentChainIndex');
+ const definitions = page.slice(definitionStart, definitionEnd);
const withoutDefinition = `${page.slice(0, definitionStart)}${page.slice(definitionEnd)}`;
const affectedRefresh = page.slice(
page.indexOf('const refreshAffectedChains'),
@@ -123,6 +124,8 @@ describe('RegionRead', () => {
expect(definitionStart).toBeGreaterThanOrEqual(0);
expect(definitionEnd).toBeGreaterThan(definitionStart);
expect(withoutDefinition).not.toMatch(/modelsApi\.getAgentChain/);
+ expect(definitions).toMatch(/modelsApi\.getAgentChains\(agent\.backend\)/);
+ expect(definitions).toMatch(/modelsApi\.getAgentChain\(backend, modelId\)/);
expect(affectedRefresh).toMatch(/chainReadAuthority\.run[\s\S]*readChainRequests/);
expect(landing).toMatch(/readers\.chains\(affectedChains\)/);
expect(landing).not.toMatch(/getAgentChain/);
diff --git a/vibe/authorization.py b/vibe/authorization.py
index 2c6507e60..658ffa3d6 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -492,6 +492,7 @@ _MEMBER_HTTP_RULES = tuple(
# can_manage_agents: selecting among already-authenticated model sources.
# Adding or re-authenticating a source is credential work and stays Owner.
("GET", r"^/api/models/agents$"),
+ ("GET", r"^/api/models/agents/[^/]+/chains$"),
("GET", r"^/api/models/agents/[^/]+/chain$"),
("PUT", r"^/api/models/agents/[^/]+/chain$"),
("GET", r"^/api/models/agents/[^/]+/sources$"),
diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.py
index 87471debe..6eee2e8a4 100644
--- a/vibe/model_hub_client.py
+++ b/vibe/model_hub_client.py
@@ -219,6 +219,9 @@ class ModelHubRemoteService:
{"backend": backend, "model_id": model_id},
)
+ def agent_chains(self, backend: str) -> list[dict]:
+ return _rpc_sync("get_agent_chains", {"backend": backend})
+
async def probe_agent(
self,
backend: str,
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 9862fd204..95fff3ee7 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -4849,6 +4849,17 @@ async def model_hub_usage_get(starlette_request: FastAPIRequest):
return await _dispatch_native_ui_request(starlette_request, handler)
[email protected]("/api/models/agents/<backend>/chains", methods=["GET"])
+def model_hub_agent_chains_get(backend):
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ chains = _model_hub_service().agent_chains(backend)
+ return _model_hub_success(chains=chains)
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
@app.route("/api/models/agents/<backend>/chain", methods=["GET"])
def model_hub_agent_chain_get(backend):
from core.handlers.model_hub import ModelHubError