Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(model-hub): announce a committed source mutation in one toast (#2121)
Call Whitec0da803035a5
diff --git a/docs/plans/model-hub-e2e-test-plan.md b/docs/plans/model-hub-e2e-test-plan.mdindex 597096277..4cd943a75 100644--- a/docs/plans/model-hub-e2e-test-plan.md+++ b/docs/plans/model-hub-e2e-test-plan.md@@ -49,7 +49,7 @@ Out of scope (documented, not dropped silently):| B4 | discovery fails | save succeeds with pending verification; preserve manual inventory and allow manual addition without refetching | assert || B5 | replay create with same `client_nonce` | idempotent, no duplicate source | assert || B6 | replace key happy + rollback; rename; patch base URL | C22/C23 contracts | assert |-| B7 | sole owned default source + exact one-hop manual route, verified by reads → delete source → guard 409 → echo plan → force | actual inherited supply gap; impact report lists interrupted agents; malformed echo rejected; canonical route and exact captured default order restored independently (only the owned deleted ID may be omitted) | assert |+| B7 | sole owned default source + exact one-hop manual route, verified by reads → delete source → guard 409 → echo plan → force | actual inherited supply gap; the guard lists the interrupted agents before the forced press and the commit announces itself in one toast with no second decision; malformed echo rejected; canonical route and exact captured default order restored independently (only the owned deleted ID may be omitted) | assert || B8 | force transport asymmetry (`?force=` vs body) | document current split (B6 issue); decide normalization | baseline || B9 | refetch after upstream inventory change | added/removed diff; **`discovered_at` preserved for pre-existing models** (currently overwritten — fix-first, see B-list) | fix-first || B10 | inspect provider inventory and add/remove a manual model | no reasoning column, provenance badge, tier editor or empty advanced toggle; manual creation needs only a model ID. Compatibility API tests retain existing metadata ownership coverage | assert |@@ -340,7 +340,7 @@ Core flows against a live instance: capability gate redirect, runtimeinstall/start/stop toggle incl. blocked-stop copy, add-API-key dialog fullbranches (auto-detect / manual protocol / pull models / empty-inventoryadd-anyway / replace key) against the mock upstream, guard refusal → confirm-→ impact report (incl. B7 echo probe as fixme), source detail+→ committed toast (incl. B7 echo probe as fixme), source detailrename/refetch/tier edit, route chain dialog add/remove/keyboard reorder,global priority drawer, usage & logs tabs render with real metered data,error-copy assertions (fixme where copy is known-missing per B1/D-3),diff --git a/docs/plans/model-hub-ui-spec.md b/docs/plans/model-hub-ui-spec.mdindex 0bd163b28..3ea6d52ff 100644--- a/docs/plans/model-hub-ui-spec.md+++ b/docs/plans/model-hub-ui-spec.md@@ -699,7 +699,7 @@ registration, not something a reviewer is expected to infer from prose.| C3 — focus return target | Name the mounted, focusable and currently admitted control that receives focus when a transient surface closes. A named target is invalid unless all three predicates hold after the destination projection is installed; a background install preserves the active target only while the same predicates remain true and otherwise invokes the registered fallback | [x] A no-op exit reveals the latest installed authoritative page projection, which is the opening row only until a newer reconciliation payload is installed. Every named target passes FF-1; a modal-closing landing uses PF-1's ordered active-target → exact-model-row → exact-backend-group → destination-page-control candidates because any earlier candidate may unmount, transferred M6 preserves a still-admitted active target, and mounted M6 keeps enabled Done | [x] A no-op close returns to the admitted source overflow trigger. A committed page landing uses PF-1 after installation; an in-modal receiving surface keeps its registered eligible focus | [x] A no-op repair exit returns to the admitted invoking card, vendor-observation action or menu control. A committed page landing uses PF-1 after installation; an in-modal result keeps its registered eligible focus | [x] Escape, outside dismissal and a no-op return from 04 restore the admitted Add subscription trigger; a committed 04 exit hands focus to its named eligible receiving surface || C4 — in-flight response owner | A busy state with no cancellation route cannot be dismissed; if cancellation is contracted, name the state that owns its late response | [x] Saving owns the route `PUT`; Cancel, close, Escape and outside dismissal stay disabled until its response is classified | [x] Saving source and Removing source disable Cancel, close, Escape and outside dismissal until the request settles | [x] Pre-flow reauth and credential replacement are locked while busy; after a flow is acquired §1.4 Dismissing owns cancellation and any late answer | [x] N/A — the menu sends no request; selection transfers ownership synchronously to §1.4 || C5 — existing visual state | Hold the exact rendered origin; a no-op exit must not manufacture another state | [x] The exact opening AgentChain and invoking row are held; abandoning a reversible draft restores that origin | [x] Edit/remove dialogs hold the exact §1.6 origin | [x] Blocked-card, vendor-observation, source-detail and key-entry origins are held exactly | [x] Closed is the same footer/trigger state that existed before Open |-| C6 — committed-report exit | Once a mutation has committed, every dismissal path is the report's Done-equivalent exit and may neither restore a pre-write origin nor discard held response or D-36 commit evidence. A failed projection member adds read-only Retry for only that subset and MUST NOT remove Done or any equivalent dismissal | [x] Route impact reported retains R6 through AR-M3; successful members remain installed while failed members become stale. Empty-tail and matching-readback commits enter Route committed, reconciling, whose DP-4 exits retain evidence and transfer the active generation | [x] Save/remove impact reports retain their envelopes and every Done exit through M1/M2 read failure; inferred commits retain their exact Source/absence evidence through the same reads | [x] Repair impact retains R3/R4's distinct envelopes through M3/M4 read failure, and Repair unresolved retains R3 through M3; Retry is additive and no path restores the invoking origin | [x] N/A — the menu commits nothing and owns no response report |+| C6 — committed-report exit | Once a mutation has committed, every dismissal path is the report's Done-equivalent exit and may neither restore a pre-write origin nor discard held response or D-36 commit evidence. A failed projection member adds read-only Retry for only that subset and MUST NOT remove Done or any equivalent dismissal | [x] Route impact reported retains R6 through AR-M3; successful members remain installed while failed members become stale. Empty-tail and matching-readback commits enter Route committed, reconciling, whose DP-4 exits retain evidence and transfer the active generation | [x] N/A — a committed save or removal mounts no report: frame 11's guard already put the exact plan to the user and took the destructive press for it, so the commit announces itself in one toast and holds nothing open. Received and inferred evidence still survives M1/M2 read failure through Committed projection stale | [x] Repair impact retains R3/R4's distinct envelopes through M3/M4 read failure, and Repair unresolved retains R3 through M3; Retry is additive and no path restores the invoking origin | [x] N/A — the menu commits nothing and owns no response report || C7 — authoritative field validation | Register every editable field against the authority that normalizes or rejects it; no field may rely on a generic request failure as its validator | [x] V5 consumes exact-pair uniqueness, server eligibility and retirement; API-key targets may be absent from inventory, while subscriptions retain known-model admission and unchanged stale pairs | [x] V1/V2 register every frame-11 field, including the complete Base URL normalizer | [x] V3/V4 register the replacement key and paste-back value; the shared reauth acknowledgement is the contracted literal `true`, not a free-form draft | [x] N/A — vendor rows emit closed enum values and expose no editable field || C8 — acknowledgement consequence coverage | For every capability that requires acknowledgement, register every applicable channel, the exact confirmed request value and one complete consequence sentence that is true for that channel before the irreversible boundary | [x] N/A — route replacement has no capability acknowledgement; F3 confirms an exact current server impact plan under the guard-totality table | [x] The existing overflow reauth action transfers its exact Source/channel to §1.11's shared confirmation phase; frame 11 adds no alternate shortcut | [x] Hub and `native_cli` both confirm and send literal `true`, but select separate complete bodies: Hub names only the failure-time cost and safe cancellation; native names the immediate shared-login outage and selected-Source-only recovery | [x] N/A — vendor selection starts create intent and crosses no existing-credential boundary || C9 — report-free reconciliation failure | For every committed mutation that skips its report because impact arrays are empty or unavailable after D-36 inference, register the pending/failure states, held write evidence and read-only Retry | [x] Route committed, reconciling holds the returned chain plus empty tails, or the exact matching AgentChain GET readback plus unavailable response tails, while AR-M is pending. An Agents-first failure settles as the exact failed Retry subset while mode-dependent companions remain deferred and non-stale; every other AR-M3 result likewise retains every success and retries only its exact acquired failed subset | [x] M1, or M2 through M0, enters Committed projection stale with the updated Source or committed absence plus exact empty/unavailable disposition held; Retry repeats only its complete-surface read | [x] A non-blocked M3/M4 empty envelope or RR-7 inferred commit with an unavailable response tail enters the same state; a blocked R3 result stays in Repair unresolved instead | [x] N/A — the menu commits nothing and invalidates no projection |@@ -729,8 +729,8 @@ register rather than borrowing a similar-looking tail from another route:| ID | Producer | Exact authority | Envelope members | Member-by-member disposition || --- | --- | --- | --- | --- |-| R1 | §1.10 source metadata `PATCH` | `model-hub.md` Source-mutation matrix, `mutation.source_metadata` | `source`, `removed_hops`, `interrupted` | `source` is held as the updated Source projection. `removed_hops` and `interrupted` each render their non-empty block in Source save impact reported; an empty member skips only its own block. M1 owns every invalidated projection before handoff. |-| R2 | §1.10 source `DELETE` | `model-hub.md` Source-mutation matrix, `mutation.source_delete` | `removed_hops`, `interrupted` | Each array renders its non-empty block in Source removal impact reported; two empty arrays skip the report. The absent `source` is intentional because the Source was deleted. M2 owns the complete post-delete projection read on either path. |+| R1 | §1.10 source metadata `PATCH` | `model-hub.md` Source-mutation matrix, `mutation.source_metadata` | `source`, `removed_hops`, `interrupted` | `source` is held as the updated Source projection. `removed_hops` and `interrupted` are read scope, not a block to render: each names the Route chains M1 must reconcile, and the guard already put that same plan to the user before the write. M1 owns every invalidated projection behind the commit's toast. |+| R2 | §1.10 source `DELETE` | `model-hub.md` Source-mutation matrix, `mutation.source_delete` | `removed_hops`, `interrupted` | Each array names the Route chains M2 must reconcile; cardinality selects no state, because frame 11's refusal already put that plan to the user and took the forced press for it. The absent `source` is intentional because the Source was deleted. M2 owns the complete post-delete projection read on every path. || R3 | §1.11 reauth acquisition and OAuth terminal | `api.md` OAuth completion, terminal `intent: reauth` | acquisition `flow`; terminal `flow`, `source`, `recovered`, `interrupted_pairs` | RR-1/RR-2 consume the acquisition `flow`; only a non-terminal flow owns presentation/polling, while a terminal flow is status-read first. §1.4 consumes the terminal `flow`. Hold `source` and classify its complete `state` before reading array cardinality: `needs_action` / `error` → Repair unresolved, rendering any non-empty `interrupted_pairs` there; non-blocked + non-empty pairs → Repair impact reported; non-blocked + empty pairs → M3 handoff. `interrupted_pairs` is evidence to render, never the repair verdict. `recovered` remains past-state evidence and selects no copy. M3 owns the affected projections. || R4 | §1.11 credential replacement | `model-hub.md` Source-mutation matrix, `mutation.credential_replace` | `source`, `removed_hops`, `interrupted` | Hold `source`. Render non-empty `removed_hops` and `interrupted` blocks in Repair impact reported; each empty member skips only its block. This producer has no `recovered` or `interrupted_pairs` member: those names belong only to R3's OAuth terminal. M4 owns the affected projections. || R5 | §1.4 / §1.11 E6 materialization error | `api.md` OAuth terminal-response matrix, `oauth_terminal.materialization_*` | standard `ok`, `contract_version`, `error`, optional `detail`; conditional `interrupted_pairs`; `flow` absent | `ok: false` and `error` select E6; `contract_version` is validated and not rendered. Optional `detail` selects no copy and is not surfaced because only registered localized keys may render. If `interrupted_pairs` is present it is exact, nonempty historical impact: render every SupplyGap row in OAuth materialization failed and hold the report through RR-5. If absent, render no report; absence is not an empty success tail and proves nothing about Source outcome. RR-5 still reconciles the full attempt scope. |@@ -755,9 +755,9 @@ commit evidence into an unconfirmed write:| ID | Authoritative evidence | Invalidated projections | Required reconciliation | Failure disposition || --- | --- | --- | --- | --- |-| M0 | Exact Source absence from `GET /api/models/sources` or a source-bound `source_not_found`; M2 supplies the same evidence after deletion | `Source[]`, every backend's Source order in `AgentSupply[]`, and every Route chain | Remove the exact Source locally, drop its overlay, retain the absence evidence and read the complete model surface before declaring dependent projections current. Every §1.6/§1.10/§1.11 caller enters this owner; M2's post-delete read is this same M0 reconciliation and may hand in its already-settled result rather than duplicate it | Enter Committed projection stale with the Source absence and last good dependent projections explicitly stale; reuse the source-removal refresh-failure line. Retry repeats only M0, while DP-4's committed exits remain legal. None resends a mutation, restores the Source, invents impact or questions the absence |-| M1 | R1 source metadata / Base URL, or D-36 reread matching every requested normalized field | `Source[]`; a Base URL inventory change may also change `AgentSupply[]` runnability and Route chains through the guarded cascade | After a non-empty impact report's Done-equivalent exit, before handing off an impact-free received success, **or before closing an inferred commit**, read the complete model surface. Keep R1's exact envelope when received; for inference hold the reread Source and mark `removed_hops` / `interrupted` unavailable | A report stays rendered with `sourceDetail.edit.impact.refreshFail`, read-only Retry and every DP-4 Done-equivalent exit; a report-free failure enters Committed projection stale with the exact evidence held |-| M2 | R2 source deletion, or D-36 reread proving the exact Source absent | `Source[]`, every backend's Source order in `AgentSupply[]`, and every Route chain | After the report's Done-equivalent exit, or immediately for a received two-empty-array / inferred commit, remove the exact Source locally and enter M0. This is M0's deletion-attempt complete-surface read, not a second owner. Keep received arrays when available and otherwise mark both response-only arrays unavailable | A mounted report stays rendered with `sourceDetail.remove.impact.refreshFail`, read-only Retry and every DP-4 Done-equivalent exit; a report-free failure enters Committed projection stale through M0 with the exact evidence held |+| M0 | Exact Source absence from `GET /api/models/sources` or a source-bound `source_not_found`; M2 supplies the same evidence after deletion | `Source[]`, every backend's Source order in `AgentSupply[]`, and every Route chain | Remove the exact Source locally, drop its overlay, retain the absence evidence and read the complete model surface before declaring dependent projections current. Every §1.6/§1.10/§1.11 caller enters this owner; M2's post-delete read is this same M0 reconciliation and may hand in its already-settled result rather than duplicate it | Enter Committed projection stale with the Source absence and last good dependent projections explicitly stale; the page's `toast.refreshFailed` names that read. Retry repeats only M0, while DP-4's committed exits remain legal. None resends a mutation, restores the Source, invents impact or questions the absence |+| M1 | R1 source metadata / Base URL, or D-36 reread matching every requested normalized field | `Source[]`; a Base URL inventory change may also change `AgentSupply[]` runnability and Route chains through the guarded cascade | Behind the commit's own announcement — for a received success of either impact cardinality **and for an inferred commit** — read the complete model surface. No user step stands between the write and this read. Keep R1's exact envelope when received; for inference hold the reread Source and mark `removed_hops` / `interrupted` unavailable | Enter Committed projection stale with the exact evidence held: only the failed members are marked stale and Retryable, and `toast.refreshFailed` names that read. Nothing reports the save itself as unconfirmed |+| M2 | R2 source deletion, or D-36 reread proving the exact Source absent | `Source[]`, every backend's Source order in `AgentSupply[]`, and every Route chain | Immediately on every committed path — received arrays of either cardinality or an inferred commit — remove the exact Source locally and enter M0 behind the removal's own announcement. This is M0's deletion-attempt complete-surface read, not a second owner. Keep received arrays when available and otherwise mark both response-only arrays unavailable | Enter Committed projection stale through M0 with the exact evidence held: only the failed members are marked stale and Retryable, and `toast.refreshFailed` names that read. Nothing reports the deletion as unconfirmed || M3 | R3 OAuth reauth terminal, RR-5 acquired-flow terminal failure, or RR-7 reread proving a held blocked Source clear | the returned or reread Source; every affected Agent-supply/order and Route-chain projection; for `native_cli`, every same-backend sibling invalidated when login started | After a received Repair impact / unresolved report takes its Done-equivalent exit, before handing off a received non-blocked empty-impact terminal, **before an RR-5 terminal-failure handoff**, or before rendering RR-7 inferred repair, read the complete model surface. Keep R3's tail when received; RR-5 has no success tail; RR-7 marks it unavailable | A received report stays rendered with `upstream.repair.impact.refreshFail`, read-only Retry and every DP-4 Done-equivalent exit; a report-free failure enters Committed projection stale with the exact evidence held || M4 | R4 credential replacement, or RR-7 reread proving a held blocked Source clear | the returned or reread Source plus every Agent-supply and Route-chain projection the credential attempt may have changed | Use the same complete-surface timing as M3. Retain R4's standard mutation envelope when received; for RR-7 hold the reread Source and mark `removed_hops` / `interrupted` unavailable | A received report stays rendered with `upstream.repair.impact.refreshFail`, read-only Retry and every DP-4 Done-equivalent exit; a report-free failure enters Committed projection stale with the exact evidence held || M5 | Any authoritative Hub landing carrying exact `AgentSupply.mode: hub`, including §1.9's successful `direct` → `hub` mode `PATCH` and D-36's held-origin Agents read proving that switch committed | `Source[]`; a qualifying mode transition may have created the backend's singleton native Source, while the returned or reread `AgentSupply` is already authoritative for mode/backend supply | Dispatch the payload through LF-H without retaining its producer identity. Hold the exact `AgentSupply` as write evidence where a mode mutation is proven and otherwise as landing evidence; acquire one landing-owned `GET /api/models/sources` epoch before declaring the Hub landing current. A successful read hands both current projections to 01, never reconstructs a Source from AgentSupply, then invokes LF-H's producer-independent post-Source hook | Keep the exact AgentSupply installed, mark only the last-good Source list stale and render `upstream.unread` with read-only `upstream.retry`; Retry repeats only M5's Source read. Ordinary navigation remains legal. The failure neither resends/questions a proven mode switch nor settles/questions RO's independent Route outcome; its later success still invokes the same post-Source hook |@@ -795,7 +795,7 @@ state in frame 02, frames 11/12 and the shared §1.4 machine names one of these| DP-1 — reversible draft | §1.2 Ready/Dirty/read or save failures and Route save refused; §1.4 Default and no-flow failures; Edit open, Remove confirmation, Reauth confirmation, Key entry, guarded refusals and pre-success F1 states | Starts/retries the named producer or its mandatory reconciliation | Restore the exact held origin, or close a create dialog that has no Source origin. §1.2's unknown-outcome exit instead hands the row to Chain unresolved because its origin is no longer authoritative | Same as Cancel where the frame affords that dismissal | No successful response is held. Preserve valid draft through F1/F3; a no-op return restores the invoking control's focus. An unknown write never presents its pre-write origin as current || DP-2 — in-flight, no cancellation route | Saving route, Saving source, Removing source, pre-flow Reauthorizing, Replacing key | Disabled while owned | Disabled | Disabled | The state remains mounted until its response is classified; the response totality matrix owns every success member || DP-3 — in-flight OAuth with contracted cancellation | Awaiting sign-in/paste-back/completion, Submitting paste-back and their retryable flow states | Submit/retry follows §1.4 | Close visually into Dismissing | Same as Cancel | RR-10 owns the late cancel and reread sequence; any late submit/poll also re-reads after it settles, and the departed surface never reopens |-| DP-4 — committed evidence | Route committed, reconciling; Route impact reported; Source save impact reported; Source removal impact reported; Repair impact reported; Repair unresolved and Committed projection stale | A report/result runs its registered Done exit. A report-free pending read exposes the same Done command; Committed projection stale keeps read-only Retry beside it | Not rendered | Close, Escape and outside press are always the Done-equivalent committed exit, including while a report-free read is pending or the projection is stale | Never restore the pre-write origin. Preserve the exact success envelope, D-36 chain/Source/absence evidence or authoritative direct absence; a pending exit transfers the owning read to the receiving page, while a stale exit carries the evidence there, marks unread dependent projections stale and leaves its refresh-failure line visible. Retry repeats only the registered M read. No exit questions or repeats the mutation, invents an unavailable member, or treats a read failure as failed commit |+| DP-4 — committed evidence | Route committed, reconciling; Route impact reported; Repair impact reported; Repair unresolved and Committed projection stale | A report/result runs its registered Done exit. A report-free pending read exposes the same Done command; Committed projection stale keeps read-only Retry beside it | Not rendered | Close, Escape and outside press are always the Done-equivalent committed exit, including while a report-free read is pending or the projection is stale | Never restore the pre-write origin. Preserve the exact success envelope, D-36 chain/Source/absence evidence or authoritative direct absence; a pending exit transfers the owning read to the receiving page, while a stale exit carries the evidence there, marks unread dependent projections stale and leaves its refresh-failure line visible. Retry repeats only the registered M read. No exit questions or repeats the mutation, invents an unavailable member, or treats a read failure as failed commit |**Editable-field authority register** `[contract]` `[derived]`. C2 owns preservation;C7 owns validity. Save/submit is disabled for an invalid row, so F1 is never used as a@@ -918,7 +918,7 @@ state exit; held intent never bypasses the evidence column.| §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. 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 | 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; `gateway.retry` in the group's collapse-row slot while any member of the collection is unread or failed | Its collection member answers → Ready, Takeover active, Per-model route unconfigured or Per-model supply paused. What re-issues it is group-grain (D-35): the 重试 drawn in the collapse row's slot re-reads the backend collection, and the collapse toggle beside it re-reads the same collection on either press, 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 |@@ -980,7 +980,7 @@ state exit; held intent never bypasses the evidence column.| §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 |-| §1.6 | Source gone | The selected source is not in a `GET /api/models/sources` read this page makes, or any source-bound mutation registered in §1.6, §1.10 or §1.11 answers `source_not_found` `[contract]` — removed by another tab, another API client, or a guarded cascade while the surface was open. This entry has precedence over every caller's F1/F3 branch; those treatments apply only after the absence reading is excluded. Distinct from every empty reading above, which is about this source's *models*; here the subject of the page is what is gone, and the list may still hold others, so §1.0's Empty does not answer either | M0 owns the read: preserve exact absence, remove the Source locally and refresh Sources + Agent supply/order + every Route chain. F2 if that read fails; the absence itself remains authoritative | `sourceDetail.gone`; on stale dependent projections reuse `sourceDetail.remove.impact.refreshFail`, `sourceDetail.retry`, `sourceDetail.remove.impact.done` | Drop the detail/card overlay immediately. M0 success hands current projections to 01. On read failure → Committed projection stale with the exact absence and last-good dependent projections. Retry repeats only M0; DP-4's Done, back, close, Escape, outside press and ordinary navigation remain legal non-mutating exits. No caller may bypass M0, re-send the mutation, restore the Source, question the absence or invent impact (C13/C14) |+| §1.6 | Source gone | The selected source is not in a `GET /api/models/sources` read this page makes, or any source-bound mutation registered in §1.6, §1.10 or §1.11 answers `source_not_found` `[contract]` — removed by another tab, another API client, or a guarded cascade while the surface was open. This entry has precedence over every caller's F1/F3 branch; those treatments apply only after the absence reading is excluded. Distinct from every empty reading above, which is about this source's *models*; here the subject of the page is what is gone, and the list may still hold others, so §1.0's Empty does not answer either | M0 owns the read: preserve exact absence, remove the Source locally and refresh Sources + Agent supply/order + every Route chain. F2 if that read fails; the absence itself remains authoritative | `sourceDetail.gone`; on stale dependent projections reuse `sourceDetail.retry` and the page's `toast.refreshFailed` | Drop the detail/card overlay immediately. M0 success hands current projections to 01. On read failure → Committed projection stale with the exact absence and last-good dependent projections. Retry repeats only M0; DP-4's Done, back, close, Escape, outside press and ordinary navigation remain legal non-mutating exits. No caller may bypass M0, re-send the mutation, restore the Source, question the absence or invent impact (C13/C14) || §1.7 | Nominal | **No route is taken over or exhausted** — every configured chain is serving its own first stored hop. AC-30 makes takeover 「a projection of visible configuration plus live runnability」 rather than a stored sibling state `[contract]`, so the subject of this frame is chains and the predicate is read per chain: a Source no chain draws from, and a non-head hop that is unavailable while the head still serves, are both outside it. Reading it globally — 「no source is unavailable」 — activated 08 for an unhealthy Source nothing was using, and left the frame with no valid state whenever one existed | F5 | — | A head enters a recoverable quota/cooldown or live connection-backoff while a later candidate serves → Takeover; a head stops being runnable for something waiting does not clear → §1.1 *Serving past a blocked head*, which is not this frame || §1.7 | Takeover | The head is unavailable **for a recoverable quota/cooldown or live connection-backoff reason** and a next candidate is serving `[contract]` — §4.3 derives takeover from exactly that pair, and the paragraph below says what the other blocker kinds render instead | F5 | `takeover.pill`, `takeover.chip` | Re-evaluate the complete predicate on every authoritative chain payload under §0.8's shared derived-state rule. As soon as it is false, retire Takeover: a recovered head serving → Nominal; `current` still naming the successor after the head recovers → the ordinary serving/current-hop projection, with no violet latch and no wait for another turn || §1.7 | Exhausted | The head is unavailable and **no** candidate remains | F5 | `gateway.supply.none` | Any candidate recovers → Takeover or Nominal |@@ -995,15 +995,15 @@ state exit; held intent never bypasses the evidence column.| §1.9 | Failed | A step this confirm promised did not go through | F1 lands here | `adopt.fail.title`, `adopt.fail.detail`, `adopt.fail.reason.transport`, `adopt.fail.reason.refused`, `adopt.fail.reason.notReady`, `adopt.fail.reason.unknown`, `settings.models.install.fail.detail` | The dialog stays open, states the failure, keeps 取消 enabled and the primary retryable. The install step consumes the closed `settings.models.install.fail.detail` verbatim from `RuntimeDependency.status.error_key`; start and mode request failures render `adopt.fail.detail`, whose `{{request}}`, optional `{{status}}` and total `{{reason}}` come only from that request state. **重试 re-reads before it resumes** `[derived]`: `installing` stays busy; `not_installed` with the install error retries install; `not_started` or `down` resumes at runtime start; `ok` or `degraded` resumes at the mode `PATCH`; `GET /api/models/agents` reading `mode: hub` holds that AgentSupply as D-36 commit evidence and enters M5 instead of resending or closing. The install route is not retried from `down`, where the contract makes it a no-op. No branch replays a step the authoritative reads already prove complete (D-36) || §1.9 | Dependency missing `[derived]` D-26 `[contract]` | Runtime `health` is `not_installed` with `error_key: null` on a supported `host_platform` (§1.0) | F1 → Failed | `adopt.effects.install`, `adopt.confirm.install` | The confirm gains one line naming the component and roughly how long it takes, and the primary becomes 安装并切换 — one press holds H1's `install_start_switch` across three contracted steps: runtime install → runtime start → mode `PATCH`. `installing` keeps the dialog mounted across reload-equivalent reads; `not_started` advances to start only because that sequence is held; live advances from Starting to the mode `PATCH`; M5's acceptance of committed AgentSupply evidence releases the sequence and makes M5 the sole owner of the Source read. An install failure renders the closed `status.error_key` and retains the sequence in Failed; a later Retry resumes at the first step the authoritative reads do not prove complete. 取消 is unchanged before commit and unavailable while a step owns its response || §1.10 | Edit open | 编辑来源 chosen from 06's source overflow; that menu's capability-gated credential actions remain beside Edit / Remove (C1) | F5 | `sourceDetail.edit.title`, `sourceDetail.edit.name`, `sourceDetail.edit.baseUrl`, `sourceDetail.edit.hint`, `sourceDetail.edit.cancel`, `sourceDetail.edit.save` | V1/V2 are the exhaustive field gates. 保存 is enabled only when every changed normalized value is valid and at least one differs from the held Source; 保存 → Saving source. 取消 / close / outside press → dismiss unchanged and return focus to the overflow trigger (C2/C3/C7) |-| §1.10 | Saving source | 保存 pressed — `PATCH /api/models/sources/<id>` with the normalized changed `display_name` and/or `base_url` `[contract]` | F3 when a Base URL change is refused; F1 otherwise → Source save failed. The request owns the dialog: Cancel, close, Escape and outside dismissal are disabled until it settles (C4) | `sourceDetail.edit.saving` | R1 owns the complete success envelope: non-empty impact → Source save impact reported; empty impact → hold the returned `source` while M1 reads the complete model surface, then close. A guard refusal → Source save refused; `source_not_found` → §1.6 Source gone |+| §1.10 | Saving source | 保存 pressed — `PATCH /api/models/sources/<id>` with the normalized changed `display_name` and/or `base_url` `[contract]` | F3 when a Base URL change is refused; F1 otherwise → Source save failed. The request owns the dialog: Cancel, close, Escape and outside dismissal are disabled until it settles (C4) | `sourceDetail.edit.saving` | R1 owns the complete success envelope → Source save committed, whatever the impact cardinality. A guard refusal → Source save refused; `source_not_found` → §1.6 Source gone || §1.10 | Source save refused | The guarded `PATCH` names the hops or supply gaps the Base URL change would remove `[contract]` | F3 — shared `Qp6FI` | `guard.title.editSource`, `guard.subtitle.editSource`, `guard.confirm.editSource`, `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 `PATCH` with `force: true` → Saving source; 取消 → Edit open with both values kept |-| §1.10 | Source save failed `[derived]` | The `PATCH` failed or never answered | F1, in the edit dialog | `sourceDetail.edit.fail`, `sourceDetail.retry` | 重试 first re-reads `GET /api/models/sources` by the held source id (D-36): the requested normalized fields already present are authoritative commit evidence → M1 with the reread Source held and response-only `removed_hops` / `interrupted` explicitly unavailable, then close only after its complete-surface read; source absent → §1.6 Source gone; otherwise re-send → Saving source |-| §1.10 | Source save impact reported `[derived]` `[contract]` | R1 holds a successful metadata response with non-empty `removed_hops` and/or `interrupted` | F2 for M1's complete-surface read; the write already succeeded and the authoritative response is held. DP-4 owns every exit | `sourceDetail.edit.impact.title`, `sourceDetail.edit.impact.detail`, `sourceDetail.edit.impact.done`, `sourceDetail.edit.impact.refreshFail`, `sourceDetail.impact.removedHops`, `sourceDetail.impact.interruptedModels`, `guard.hop.position`, `guard.gap.subject`, `guard.gap.agents`, `gateway.modelCount`, `sourceDetail.retry` | Render each non-empty array once: the existing hop block for `removed_hops`, the §1.11 SupplyGap block for `interrupted`. 完成, close, Escape or outside press first run M1's complete model-surface read; success returns with the current surface. Failure keeps this report and envelope mounted, adds the refresh-failure line and read-only 重试, and leaves 完成 plus every DP-4 equivalent exit active; those exits carry the held evidence and mark dependent projections stale. 重试 repeats only M1. No path restores the pre-write origin or lets a reread replace response evidence |+| §1.10 | Source save failed `[derived]` | The `PATCH` failed or never answered | F1, in the edit dialog | `sourceDetail.edit.fail`, `sourceDetail.retry` | 重试 first re-reads `GET /api/models/sources` by the held source id (D-36): the requested normalized fields already present are authoritative commit evidence → Source save committed with the reread Source held and response-only `removed_hops` / `interrupted` explicitly unavailable; source absent → §1.6 Source gone; otherwise re-send → Saving source |+| §1.10 | Source save committed `[derived]` `[contract]` | R1 holds a successful metadata response, or D-36 inferred the commit | F2 for M1's complete-surface read; the write already succeeded and the authoritative response is held | `sourceDetail.edit.settlement.title`; on a failed read `toast.refreshFailed` and `sourceDetail.retry` | Close the dialog, return to 01 with the returned Source installed, and announce the commit exactly once in the page toast. **No report is mounted and no exit is owed** `[derived]`: the same `removed_hops` / `interrupted` plan was already put to the user by frame 11's guard and accepted by the destructive press, so restating it afterwards would ask a settled question again. The impact is instead M1's read scope, which runs behind the toast. A failed read enters Committed projection stale for only the members that failed; nothing there questions the save || §1.10 | Remove confirmation `[derived]` | 移除来源 chosen from 06's source overflow; the exact §1.6 source-detail state behind it is held | F5 — no request has been sent | `guard.title.removeSource`, `guard.hint.removeSource`, `guard.confirm.removeSource`, `guard.cancel` | 移除来源 → Removing source with the initial non-forced delete; 取消 / close / outside press restores the held §1.6 origin by C5 |-| §1.10 | Removing source | The destructive primary was activated in Remove confirmation or Source remove refused — `DELETE /api/models/sources/<id>` is non-forced on the first path and carries `?force=true` only on the second `[contract]` | F3 on refusal; F1 otherwise → Source remove failed. The request owns the dialog and all dismissal paths are disabled until it settles (C4) | `sourceDetail.remove.checking` | R2 owns the complete success envelope: either array non-empty → Source removal impact reported; both empty → remove the exact Source locally, run M2's complete model-surface read, then §1.6 Source gone. An initial guard refusal → Source remove refused; `source_not_found` → §1.6 Source gone |+| §1.10 | Removing source | The destructive primary was activated in Remove confirmation or Source remove refused — `DELETE /api/models/sources/<id>` is non-forced on the first path and carries `?force=true` only on the second `[contract]` | F3 on refusal; F1 otherwise → Source remove failed. The request owns the dialog and all dismissal paths are disabled until it settles (C4) | `sourceDetail.remove.checking` | R2 owns the complete success envelope → Source removal committed, whatever the impact cardinality. An initial guard refusal → Source remove refused; `source_not_found` → §1.6 Source gone || §1.10 | Source remove refused | The non-forced delete returned the guarded envelope; frame 11 renders its source-removal variant while retaining the held §1.6 origin | F3 — shared refusal semantics and the frame 11 dialog | `guard.title.removeSource`, `guard.confirm.removeSource`, `guard.label.removeSource`, `guard.count`, `guard.hop.position.removeSource`, `guard.hint.removeSource`, `guard.gap.label`, `guard.gap.subject`, `guard.gap.agents`, `gateway.modelCount`, `guard.cancel` | 移除来源 re-sends the same `DELETE` with `force` → Removing source; 取消 / close / outside press restores the held origin by C5 |-| §1.10 | Source remove failed `[derived]` | Either delete request failed or never answered | F1, in place | `sourceDetail.remove.fail`, `sourceDetail.retry` | 重试 re-reads `GET /api/models/sources` by the held id (D-36): absence is authoritative delete-commit evidence → M2 with both response-only impact arrays explicitly unavailable, then §1.6 Source gone only after its complete-surface read; present → re-send the same stage, non-forced before refusal and forced after one |-| §1.10 | Source removal impact reported `[derived]` `[contract]` | R2 holds a successful delete response with non-empty `removed_hops` and/or `interrupted`; the source is already gone | F2 for M2's complete-surface read after a DP-4 exit; the read cannot negate the held delete response | `sourceDetail.remove.impact.title`, `sourceDetail.remove.impact.detail`, `sourceDetail.remove.impact.done`, `sourceDetail.remove.impact.refreshFail`, `sourceDetail.impact.removedHops`, `sourceDetail.impact.interruptedModels`, `guard.hop.position.removeSource`, `guard.gap.subject`, `guard.gap.agents`, `gateway.modelCount`, `sourceDetail.retry` | Render the authoritative success arrays before any reread, even when they differ from the earlier refusal preview. 完成, close, Escape or outside press first run M2's complete model-surface read; success drops the detail into 01 with the current surface. Failure keeps the report and envelope mounted, states only that the surface refresh failed, adds read-only 重试, and leaves 完成 plus every DP-4 equivalent exit active; those exits carry the held delete evidence and mark dependent projections stale. 重试 repeats only M2. It never says the committed deletion is unconfirmed |+| §1.10 | Source remove failed `[derived]` | Either delete request failed or never answered | F1, in place | `sourceDetail.remove.fail`, `sourceDetail.retry` | 重试 re-reads `GET /api/models/sources` by the held id (D-36): absence is authoritative delete-commit evidence → Source removal committed with both response-only impact arrays explicitly unavailable; present → re-send the same stage, non-forced before refusal and forced after one |+| §1.10 | Source removal committed `[derived]` `[contract]` | R2 holds a successful delete response, or D-36 proved the exact Source absent; the source is already gone | F2 for M2's complete-surface read; the read cannot negate the held delete response | `sourceDetail.remove.settlement.title`; on a failed read `toast.refreshFailed` and `sourceDetail.retry` | Drop the detail into 01, remove the exact Source locally and announce the removal exactly once in the page toast. **No report is mounted and no exit is owed** `[derived]`: the refusal that preceded the forced delete already showed this plan and the second destructive press accepted it. The authoritative success arrays are still newer evidence than that preview, and they are consumed as M2's read scope rather than rendered again. A failed read enters Committed projection stale through M0 for only the members that failed; it never says the committed deletion is unconfirmed || §1.11 | Blocked source card | Frame 12's card delta is rendered for a source whose status is `needs_action` or `error`; both states reuse the same geometry and card target | F5 | `needs_action`: the selected `sourceDetail.status.needsAction.*` plus `upstream.state.supplyStopped` and its registered cause action. `error`: `sourceDetail.status.error` plus `upstream.state.supplyStopped`; Hub uses `sourceDetail.action.refetch`, while an unclassified `native_cli` login failure uses `upstream.repair.reauthorize` | Card → 06. For `needs_action`, OAuth expiry → Reauth confirmation; revoked key → Key entry; a known subscription vendor's balance/account link opens its §1.4 static destination → Vendor recovery observation; an `api_key` Source keeps the non-linked service-provider fallback. For `error`, Hub 重新拉取 → §1.6 Refetching; native 重新授权 → Reauth confirmation. A later payload always dispatches the status it actually reports || §1.11 | Vendor recovery observation `[derived]` `[contract]` | A subscription's 补充额度 or 联系厂商 destination was activated from Blocked source card. Opening the external page proves no recovery; the same single-action card shell stays mounted and enters this channel-selected observation phase | F5 — no model mutation or hidden poll is sent | the original cause plus `upstream.state.supplyStopped`; Hub `sourceDetail.action.refetch`; native `upstream.repair.reauthorizeToRefresh` | Hub 重新拉取 → §1.6 Refetching. Native 重新登录以刷新订阅状态 → Reauth confirmation and MUST pass its existing acknowledgement before reauth. A later payload that changes the Source state leaves this phase; a reload that still reads the blocker reconstructs Blocked source card. No branch treats opening or returning from the vendor page as recovery evidence || §1.11 | Reauth confirmation `[derived]` `[contract]` | 重新授权 or 重新登录以刷新订阅状态 pressed for a Hub or `native_cli` source from Blocked source card, Vendor recovery observation or the capability-gated source overflow | F5 — no request has been sent | `upstream.repair.reauthConfirm.title`; exactly one of `upstream.repair.reauthConfirm.detail.onFailure` or `upstream.repair.reauthConfirm.detail.immediate`; `upstream.repair.reauthConfirm.confirm`, `upstream.repair.reauthConfirm.cancel` | The confirmation phase and literal request value are shared, but the complete consequence body is selected by channel: Hub renders only `onFailure`; `native_cli` renders only `immediate`. 继续登录 synchronously preallocates PD-1's blank context, then sends `POST /api/models/sources/<id>/reauth` with `{acknowledge_irreversible: true}` → Reauthorizing; 取消 / close / Escape restores the exact invoking card/menu/observation origin and its focus target (C2/C3/C5/C8) |@@ -1013,7 +1013,7 @@ state exit; held intent never bypasses the evidence column.| §1.11 | Key replacement refused `[derived]` `[contract]` | The non-forced credential replacement returned the shared guarded `409`; the typed key and exact Key entry origin are held | F3 — shared `Qp6FI`, with only the operation strings below changed | `guard.title.replaceKey`, `guard.subtitle.replaceKey`, `guard.confirm.replaceKey`, `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 held `{key, force: true}` → Replacing key; 取消 / close / Escape → Key entry with the typed key kept, by C2/C5 || §1.11 | Repair impact reported `[derived]` `[contract]` | R3 holds a successful OAuth repair whose returned Source is non-blocked and whose `interrupted_pairs` is non-empty, or R4 holds a successful key replacement with non-empty `removed_hops` and/or `interrupted`; the complete returned `source` is held | F2 for M3/M4's complete-surface read; the successful response is already in hand and DP-4 owns every exit | `upstream.repair.impact.title`, `upstream.repair.impact.detail`, `upstream.repair.impact.refreshFail`, `sourceDetail.impact.removedHops`, `sourceDetail.impact.interruptedModels`, `guard.hop.position`, `guard.gap.subject`, `guard.gap.agents`, `gateway.modelCount`, `upstream.repair.impact.done`, `upstream.retry` | Render every non-empty response array under its matching hop or SupplyGap block. 完成, close, Escape or outside press first run M3/M4's complete model-surface read; success returns with the current surface. Failure keeps the exact report and envelope mounted, adds the refresh-failure line and read-only 重试, and leaves 完成 plus every DP-4 equivalent exit active; those exits carry the evidence and mark dependent projections stale. 重试 repeats only M3/M4. The reread never replaces response evidence or restores the invoking origin || §1.11 | Repair unresolved `[derived]` `[contract]` | R3 holds a successful OAuth repair whose returned `source.state` is still `needs_action` or `error`, regardless of `recovered` and whether `interrupted_pairs` is empty | F2 for M3's complete-surface read; this is a successful terminal with a blocked result, not an F1 failure | `upstream.repair.unresolved`, optional `sourceDetail.impact.interruptedModels`, `guard.gap.subject`, `guard.gap.agents`, `gateway.modelCount`, `upstream.repair.impact.refreshFail`, `upstream.repair.impact.done`, `upstream.retry` | Keep the result visible in the gold needs-action treatment and render every non-empty `interrupted_pairs` block as independent evidence below it. 完成, close, Escape or outside press first run M3's complete model-surface read; success returns with the current blocked projection. Failure keeps this exact result and R3 envelope mounted, adds the refresh-failure line and read-only 重试, and leaves 完成 plus every DP-4 equivalent exit active; those exits carry the result and mark dependent projections stale. 重试 repeats only M3. Never show repaired/refreshed copy or auto-close from an empty array (C6/C10) |-| §1.2 / §1.6 / §1.9 / §1.10 / §1.11 | Committed projection stale `[derived]` | M0 has authoritative Source absence; an M1/M2/M3/M4 mutation or R3 terminal has commit evidence and its complete read failed; M5 holds committed mode-switch AgentSupply and its Source read failed; or M6/AR-M3 holds Route commit evidence with a settled acquired failed member subset. Hold the exact success envelope when received; inference holds its authoritative subject and marks response-only members unavailable. Every successful acquired projection stays installed; deferred companions are not stale | F2 — the operation-specific sentence names only the failed read/member, never the completed write, authoritative absence, deferred member or successful sibling | M0/M2 `sourceDetail.remove.impact.refreshFail`; M1 `sourceDetail.edit.impact.refreshFail`; M3/M4 `upstream.repair.impact.refreshFail`; M5 `upstream.unread`; M6 `route.impact.refreshFail`; the admitted owning Retry and, where mounted, its Done key | M0–M4 render committed Source/absence with last-good dependent projections stale; M5 renders held AgentSupply with Source stale; M6 renders every acquired AR-M success exactly and marks only AR-M3's acquired failed subset stale. Before mode, an Agents failure therefore shows only Agents stale while Source/Route remain deferred and absent from stale/Retry. Direct mode removes Route-chain members from the set rather than marking them stale. M0–M5 Retry repeats their owning read; M6 Retry repeats only the acquired failed subset through CA-M2/CA-M4. A successful Agents Retry activates exact mode companions once. DP-4 exits and page navigation remain legal. Never resend mutation, invent impact, discard evidence, roll back installed authority or describe the write/absence as uncertain (C6/C9/C10/C14/C15) |+| §1.2 / §1.6 / §1.9 / §1.10 / §1.11 | Committed projection stale `[derived]` | M0 has authoritative Source absence; an M1/M2/M3/M4 mutation or R3 terminal has commit evidence and its complete read failed; M5 holds committed mode-switch AgentSupply and its Source read failed; or M6/AR-M3 holds Route commit evidence with a settled acquired failed member subset. Hold the exact success envelope when received; inference holds its authoritative subject and marks response-only members unavailable. Every successful acquired projection stays installed; deferred companions are not stale | F2 — the operation-specific sentence names only the failed read/member, never the completed write, authoritative absence, deferred member or successful sibling | M0/M1/M2 `toast.refreshFailed`; M3/M4 `upstream.repair.impact.refreshFail`; M5 `upstream.unread`; M6 `route.impact.refreshFail`; the admitted owning Retry and, where mounted, its Done key | M0–M4 render committed Source/absence with last-good dependent projections stale; M5 renders held AgentSupply with Source stale; M6 renders every acquired AR-M success exactly and marks only AR-M3's acquired failed subset stale. Before mode, an Agents failure therefore shows only Agents stale while Source/Route remain deferred and absent from stale/Retry. Direct mode removes Route-chain members from the set rather than marking them stale. M0–M5 Retry repeats their owning read; M6 Retry repeats only the acquired failed subset through CA-M2/CA-M4. A successful Agents Retry activates exact mode companions once. DP-4 exits and page navigation remain legal. Never resend mutation, invent impact, discard evidence, roll back installed authority or describe the write/absence as uncertain (C6/C9/C10/C14/C15) || §1.11 | Repair failed `[derived]` | The pre-flow reauth request or credential replacement failed before its terminal could be confirmed; the repair intent, channel acknowledgement, exact origin status and any typed key remain held | F1, on the repair surface | `upstream.repair.fail`, `upstream.retry` | RR-6–RR-9 first perform the evidence-milestone read C10 registers: a pre-flow reauth acquisition failure reads the held Source id for Hub or native, while uncertain credential replacement reads M4's complete model surface. Then absent → M0 / Source gone; a held `needs_action`/`error` origin that is now clear → RR-7's M3/M4 handoff before rendering the reread Source as repaired; a still-blocked origin → remain here; any origin already non-blocked → remain regardless of present snapshot, because health is not mutation evidence. 重试 repeats the held producer. After a flow is acquired, E8/E9 and reauth E6 run RR-5's complete M3 read before OAuth failed / Source gone; E4 is create-only and E2 remains inconclusive. Every branch preserves `intent: reauth` || §1.12 | Closed | 添加订阅 is rendered in 01's upstream footer | F5 | `upstream.addSubscription` | Activate → Open || §1.12 | Open | The frame 13 vendor menu is visible and focus is on its first row; the Add subscription trigger remains held as the focus owner | F5 | `addSubMenu.vendor.claude`, `addSubMenu.vendor.chatgpt`, `addSubMenu.recommendation.native`, `addSubMenu.recommendation.gateway` | Claude 订阅 → §1.4 with `vendor: anthropic`; ChatGPT 订阅 → §1.4 with `vendor: openai`. Selection closes the menu; if 04 later dismisses back to 01, focus returns explicitly to Add subscription, while a committed exit gives focus to 06. Escape / outside press → Closed with the same trigger focus (C3) |@@ -1886,14 +1886,20 @@ those columns and nothing else, which is §1.0's Partial rule read at row grain:sub-tree that failed degrades, and the group keeps everything the other two payloadsdrew.-**A read that can fail has to be re-issuable, and the collapse row is what re-issues-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 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+**A read that can fail has to be re-issuable, and the collapse row's slot is where this+one is re-issued** `[derived]` D-35. 「Chain unresolved」 is the only failure state on this+page whose repair is not drawn on the row it belongs to: 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. The repair is therefore group-grain, in the full-width slot under+the rows, and it is two controls rather than one. 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; a `gateway.retry` beside it re-reads the same collection and is drawn only+while a member is unread or failed. Neither stands in for the other, because the toggle is+drawn only when there are rows to hide: a group within the six-row limit has none to+borrow, and a group past it would otherwise hide its repair behind a control that says+nothing about the failure. The page's own two triggers sit beside them — any mutation+re-renders the group, and the next load re-reads everything — so the user-available repairs+and the ambient ones agree. What this row must not do isresolve on a clock: a poll cadence is a number this file has no basis to pick, and 「noexit keys on elapsed time」 is the rule the two source rows above are written to.@@ -4971,32 +4977,36 @@ same shell** `[frame]` `[contract]`. Choosing the overflow action opens frame 11remove dialog with the selected source identity and the transaction-scope helper, but noaffected-hop or supply-gap rows: the client has no server evidence for those yet and doesnot scan chains to invent them. Its first 移除来源 press sends the non-forced delete.-A success removes the source; empty impact skips the report and reconciles through M2,-while non-empty impact is reported below before that same read. A guarded `409` fills the+A success removes the source and reconciles through M2 whatever its impact+cardinality; the removal says so once, in the page toast. A guarded `409` fills thesame dialog with the server's staged consequence,and only the next destructive press re-sends with`?force=true`. The confirmation therefore protects even a source with no route impact,while every consequence row remains evidentiary.The forced response is newer evidence than its refusal preview `[contract]`. R2 therefore-holds and renders the returned `removed_hops` and `interrupted` before any surface reread; a-second client may have changed chains or protected Agent selections between the two-requests. The terminal report composes frame 11's existing hop block with §1.11's existing-`SupplyGap` block, omits whichever array is empty, and keeps both exact success arrays until-完成; M2 then reads Sources, Agents/source orders and Route chains together. With two empty-arrays the report is skipped, the exact Source is removed locally and the same M2 read runs.-R1 applies the same response-total rule to a Base-URL save: the returned `source` is the next-projection, non-empty impact evidence is shown first, and M1 reconciles the complete surface.+holds the returned `removed_hops` and `interrupted` and reconciles against them rather than+against the preview; a second client may have changed chains or protected Agent selections+between the two requests. What it does not do is put them back on screen. The user was shown+that plan by the guard and pressed the destructive button for it, so a post-commit report+would restate a settled decision as if it were still open — and the one command such a report+can offer, 完成, is a step the user owes nothing for. The arrays are consumed as M2's read+scope instead: it reads Sources, Agents/source orders and Route chains together, behind a+single `remove.settlement.title` toast, on both the two-empty and the non-empty path. R1+applies the same rule to a Base-URL save: the returned `source` is the next projection, the+impact arrays scope M1's complete-surface read, and `edit.settlement.title` announces it.The same M rows also own D-36 commit inference. If a lost metadata response is reconciled bythe requested normalized fields appearing on the held Source, M1 runs before close; if a lostdelete is reconciled by that exact Source being absent, M2 transfers the evidence into M0.Every other exact Source absence enters that same owner directly, so `source_not_found` cannotjump from a modal to 01 with stale orders or chains. Those readscannot recover `removed_hops` or `interrupted`, so both members are marked unavailable rather-than empty and no impact report is invented. If any report-free read fails, C9 enters+than empty and no impact is invented. If any of these reads fails, C9 entersCommitted projection stale with exactly the returned or inferred write evidence and the last-good dependent projections marked stale. Its Retry repeats the same M1/M2 read and cannot-repeat the edit or deletion; DP-4's Done-equivalent exits preserve that evidence and stale mark.+good dependent projections marked stale, under the page's own `toast.refreshFailed` line. Its+Retry repeats the same M1/M2 read and cannot repeat the edit or deletion. The failure is a+read verdict and says only that: the commit itself is never described as unconfirmed, and no+state holds the user to acknowledging it `[derived]`.The frame draws position pills directly from each refusal row's contracted one-based`RouteHopRef.position`; it issues no per-chain lookup. It still inherits G-23 for a non-empty `would_interrupt`, because the registered@@ -5006,31 +5016,43 @@ menu models and Agents. That remaining open gap is not filled from inference her**States** — §0.8, rows marked §1.10. The dialogs trap focus; Tab stays inside. DP-1reversible states make Escape and the head close equivalent to 取消 and restore focus tothe source overflow trigger. DP-2 disables every dismissal path while Saving source or-Removing source owns a request. DP-4 committed reports instead make close, Escape and an-outside press equivalent to 完成; Committed projection stale adds the same exits beside its-read-only Retry and carries the stale-dependent-projection marker to the receiving surface.-Neither takes Cancel semantics, repeats the committed mutation or restores the held+Removing source owns a request. A committed save or removal mounts nothing to dismiss: it+closes into 01 and announces itself once in the page toast, so §1.10 registers no DP-4 report+of its own. Committed projection stale is the one committed state it can still reach, and it+carries read-only Retry plus the stale-dependent-projection marker on the receiving surface+without taking Cancel semantics, repeating the committed mutation or restoring the heldpre-write origin (C3/C4/C6/C9). Enter submits Edit only when V1/V2 are valid and focus is ina single-line field; both destructive stages require activating the focused button andare not default Enter actions `[derived]`.+The announcement states the **outcome**, not the flow it arrived through `[derived]`. The two+part company on exactly one path: an edit whose Source turns out to be absent is still the+edit flow, but nothing was updated, so it announces §1.6's `sourceDetail.gone` rather than+`edit.settlement.title` — the same fact its panel is showing — and the dialog stays open on+that absence instead of closing behind a save that did not happen. A deletion answered+`source_not_found` keeps `remove.settlement.title`: already absent is the outcome that flow+asked for. Only a removal closes into 01.+**Copy** is registered in the existing owners: source-menu and edit strings under`models.hub.sourceDetail.*`, and refusal strings under `models.hub.guard.*`. Dynamic head-metadata is data and receives no copy key. The two response reports add only their-operation-specific shell strings and reuse the existing hop / `SupplyGap` row copy:+metadata is data and receives no copy key. A committed mutation adds one announcement per+outcome and nothing else; the hop / `SupplyGap` row copy it would have reused stays registered+for §1.11's repair report, which still has one:-| Key under `models.hub.sourceDetail.*` | 中文 | English |-| --- | --- | --- |-| `edit.impact.title` `[derived]` `[contract]` | 来源已更新,部分供给受到影响 | The source was updated, and some supply was affected |-| `edit.impact.detail` `[derived]` `[contract]` | 以下路由或型号已被移除或中断。 | The following routes or models were removed or interrupted. |-| `edit.impact.refreshFail` `[derived]` | 来源已更新,但模型页面暂时无法刷新。 | The source was updated, but the model surface could not be refreshed. |-| `edit.impact.done` `[derived]` | 完成 | Done |-| `remove.impact.title` `[derived]` `[contract]` | 来源已移除,部分供给受到影响 | The source was removed, and some supply was affected |-| `remove.impact.detail` `[derived]` `[contract]` | 以下是这次移除实际影响的路由和型号。 | These are the routes and models actually affected by this removal. |-| `remove.impact.refreshFail` `[derived]` | 来源已移除,但模型页面暂时无法刷新。 | The source was removed, but the model surface could not be refreshed. |-| `remove.impact.done` `[derived]` | 完成 | Done |-| `impact.removedHops` `[derived]` `[contract]` | 已移除的跳 | Removed hops |-| `impact.interruptedModels` `[derived]` `[contract]` | 已中断的型号 | Interrupted models |+| Key under `models.hub.sourceDetail.*` | 中文 | English | Outcome |+| --- | --- | --- | --- |+| `edit.settlement.title` `[derived]` `[contract]` | 供应商已更新 | The source was updated | `updated` |+| `remove.settlement.title` `[derived]` `[contract]` | 供应商已移除 | The source was removed | `removed` |+| `gone` — §1.6's own key, reused `[derived]` | 这个供应商已经不在了。 | This provider is no longer available. | `gone` |+| `impact.removedHops` `[derived]` `[contract]` | 已移除的跳 | Removed hops | — |+| `impact.interruptedModels` `[derived]` `[contract]` | 已中断的型号 | Interrupted models | — |++Each is a page toast, not a dialog: it states what happened and is gone, because the impact+it would otherwise repeat was already confirmed before the write. `gone` is the one line the+toast shares with a surface — the open panel says the same thing — so the two never disagree.+A failed surface read after any of these outcomes reuses the page's own+`models.hub.toast.refreshFailed` (刷新失败,请重试 / Couldn't refresh, please retry) beside the+stale region's `sourceDetail.retry` `[derived]`.---@@ -5676,11 +5698,13 @@ failed region with no unread line and no 重试 — under the one engine readingfailed read *more* likely, not less. §1.1's *Chain unresolved* is this rule one grainfurther down, and it is why that row exists instead of a transition into Unreachable.-**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,+**D-35 — The chain collection's re-read control is group-grain, in the collapse row's+slot.** Collapsing a group and expanding it re-issues one chain-collection read for that+backend, and **amended 2026-09-23** an explicit `gateway.retry` is drawn beside that+toggle whenever a member of the collection is unread or failed. §1.1's *Chain unresolved*+names both as its 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, either+press is that read retry: it reacquires one RO-O generation when Hub-observable,retains the submitted pairs/stage and sends no mutation. A nonmatching answer installs thecurrent chain but does not settle or abandon the attempt; Direct-suspended keeps the evidenceand sends nothing.@@ -5690,7 +5714,14 @@ worse than the dead control D-9a rules out and is not licensed by it. A controlon the frame, already meaning 「show me this group's rows」, re-reads them at no cost insurface. The two alternatives were a per-row button on a surface with one row per model,and a poll cadence this file has no basis to choose; the frame rules out the first and-「no exit keys on elapsed time」 rules out the second.+「no exit keys on elapsed time」 rules out the second. *Amended 2026-09-23:* the toggle+alone was not enough, because a group only draws one when it has rows to hide. At or+under the six-row limit there was no collapse row to borrow, and over it the toggle took+the slot — so the groups that could ask again were exactly the ones whose failure the+limit happened not to reach. Both controls now share the slot: the toggle keeps+re-reading, because expanding is already a request for rows, and the 重试 beside it is+the control that says a read failed. Neither is per-row, so the frame's objection to the+first alternative is untouched.**D-36 — A lost response is reconcilable exactly when the client already holds itssubject's identifier.** F1 leaves a mutation's outcome unknown and the repair is alwaysdiff --git a/ui/e2e/g-guards-copy.spec.ts b/ui/e2e/g-guards-copy.spec.tsindex b002cb6c4..c6e9c63a6 100644--- a/ui/e2e/g-guards-copy.spec.ts+++ b/ui/e2e/g-guards-copy.spec.ts@@ -14,7 +14,7 @@ import {requireRuntimeRunning,} from './support/fixtures';import { expect, test } from './support/gateway';-import { fillApiKeyForm, labelledButton } from './support/hub';+import { fillApiKeyForm } from './support/hub';import { captureAgentChain, restoreAgentChain } from './support/restore';test.describe('G · supply guards and failure copy', () => {@@ -82,15 +82,12 @@ test.describe('G · supply guards and failure copy', () => {// 3 · confirm again, which re-sends the delete echoing that plan back.await confirm.click();- // 4 · the impact report. Not a toast: the same facts restated in the past- // tense, so a user who confirmed too fast can still read what they did.- const report = hub.mutationReport('delete');- await expect(report).toBeVisible({ timeout: 30_000 });- await expect(report).toContainText(copy('sourceDetail.remove.impact.title'));- await expect(report).toContainText(copy('guard.result.label'));- await expect(report).toContainText(copy('guard.result.gapLabel'));- await labelledButton(report, copy('sourceDetail.remove.impact.done')).click();- await expect(report).toHaveCount(0);+ // 4 · the removal announces itself once, in the toast layer. Step 2 is+ // where the facts were put to the user and step 3 is where they accepted+ // them, so restating the same plan in a modal would only ask again.+ await expect(hub.toasts.filter({ hasText: copy('sourceDetail.remove.settlement.title') }))+ .toBeVisible({ timeout: 30_000 });+ await expect(hub.guardDialog).toHaveCount(0);await expect.poll(async () => (await api.sources()).some((s) => s.id === source.id), { timeout: 15_000 })diff --git a/ui/e2e/model-provider/fixture.tsx b/ui/e2e/model-provider/fixture.tsxindex b4a117c70..3e2ff6974 100644--- a/ui/e2e/model-provider/fixture.tsx+++ b/ui/e2e/model-provider/fixture.tsx@@ -11,7 +11,7 @@ import { AddApiKeyDialog } from '../../src/components/settings/models/AddApiKeyDimport { SourceDetailPanel } from '../../src/components/settings/models/SourceDetailPanel';import { createSourceCollectionReadAuthority } from '../../src/components/settings/models/collectionReadAuthority';import { modelsApi } from '../../src/components/settings/models/modelsApi';-import { readSurfaceLanding, sourceMutationLanding, type TrackSourceMutation } from '../../src/components/settings/models/mutationSettlement';+import { readSurfaceLanding, type TrackSourceMutation } from '../../src/components/settings/models/mutationSettlement';import { CONTRACT_VERSION, type Source } from '../../src/components/settings/models/types';const params = new URLSearchParams(location.search);@@ -70,14 +70,14 @@ export function Fixture() {chains: async () => ({}),}, []);if (reads.sources.kind === 'ready') setSource(saved);- return sourceMutationLanding(reads, [], true);+ return reads;};const trackMutation: TrackSourceMutation = async (work) => {try {return await work(saved, {source: async (next) => { setSource(next); return reconcile(); },unread: reconcile,- gone: async () => ({ verdict: 'degraded', reads: null, affectedChains: [] }),+ gone: async () => null,readInventory: async () => ({ sources: [saved], snapshot: 1 }),release: () => {},});diff --git a/ui/e2e/support/hub.ts b/ui/e2e/support/hub.tsindex a622b5ced..c9a654457 100644--- a/ui/e2e/support/hub.ts+++ b/ui/e2e/support/hub.ts@@ -283,11 +283,11 @@ export class ModelHubPage {return this.page.locator('.model-hub-guard-dialog').filter({ hasText: title });}- /** The after-the-fact report of a committed source mutation. It shares the- * guard's chrome — deliberately, since it restates the same facts — but it- * carries the action it is reporting, which is what tells them apart. */- mutationReport(action: 'edit' | 'delete'): Locator {- return this.page.locator(attr('data-source-mutation-report', action));+ /** The global toast layer. A committed source mutation announces itself here+ * and nowhere else: the guard already made the user confirm the impact before+ * the write, so what is left is one line, not a second decision. */+ get toasts(): Locator {+ return this.page.locator('div.fixed.right-4.z-50 > div');}get routeDialog(): Locator {diff --git a/ui/src/components/settings/SettingsLayout.test.tsx b/ui/src/components/settings/SettingsLayout.test.tsxindex 9dcc4e1bf..43a4b8668 100644--- a/ui/src/components/settings/SettingsLayout.test.tsx+++ b/ui/src/components/settings/SettingsLayout.test.tsx@@ -491,8 +491,14 @@ describe('SettingsLayout', () => {renderLayout('/settings', { gateModelHub: true });expect(await screen.findByText('backends-body')).toBeTruthy();- expect(window.localStorage.getItem(SETTINGS_LAST_SECTION_STORAGE_KEY))- .toBe('/settings/backends');+ // The redirect lands in the DOM one commit before the trail effect records+ // where it landed, so reading storage the instant the page appears catches a+ // real but momentary disagreement. The contract is that the memory follows+ // the redirect, not that it arrives in the same commit.+ await waitFor(() => {+ expect(window.localStorage.getItem(SETTINGS_LAST_SECTION_STORAGE_KEY))+ .toBe('/settings/backends');+ });});it.each([diff --git a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx b/ui/src/components/settings/models/AddApiKeyDialog.test.tsxindex 8133de28d..f0f1ec563 100644--- a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx+++ b/ui/src/components/settings/models/AddApiKeyDialog.test.tsx@@ -70,21 +70,9 @@ const renderDialog = (onClose = vi.fn(), onAdded = vi.fn()) => {const replacementSettlement = (overrides: Partial<SourceMutationSettlement> = {},): SourceMutationSettlement => ({- source: vi.fn().mockResolvedValue({- verdict: 'landed',- reads: {} as SourceMutationLandingReads,- affectedChains: [],- } satisfies SourceMutationLanding),- gone: vi.fn().mockResolvedValue({- verdict: 'landed',- reads: {} as SourceMutationLandingReads,- affectedChains: [],- } satisfies SourceMutationLanding),- unread: vi.fn().mockResolvedValue({- verdict: 'landed',- reads: {} as SourceMutationLandingReads,- affectedChains: [],- } satisfies SourceMutationLanding),+ source: vi.fn().mockResolvedValue({} as SourceMutationLandingReads satisfies SourceMutationLanding),+ gone: vi.fn().mockResolvedValue({} as SourceMutationLandingReads satisfies SourceMutationLanding),+ unread: vi.fn().mockResolvedValue({} as SourceMutationLandingReads satisfies SourceMutationLanding),release: vi.fn(),readInventory: vi.fn().mockResolvedValue({ snapshot: 1, sources: [blockedSource] }),...overrides,diff --git a/ui/src/components/settings/models/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsxindex ac841480b..ece391732 100644--- a/ui/src/components/settings/models/AgentCard.test.tsx+++ b/ui/src/components/settings/models/AgentCard.test.tsx@@ -577,6 +577,26 @@ describe('AgentCard', () => {expect(onProbeSettled).toHaveBeenCalledWith(expect.objectContaining({ backend: 'claude' }));});+ it('keeps a chain reread reachable when a long group also offers collapse', async () => {+ // The two controls used to share one slot, with collapse taking it. Past the+ // collapsed limit that left a backend whose chains could not be read with no+ // affordance saying so, which is why the page's own refresh line has to keep+ // answering for route chains.+ const onProbeSettled = vi.fn();+ const models = Array.from({ length: COLLAPSED_MODEL_LIMIT + 2 }, (_, index) => `model-${index + 1}`);+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[{+ ...hubAgent,+ builtin_models: models,+ model_supply: models.map((modelId) => ({ route_origin: "manual" as const, model_id: modelId, chain_length: 1, has_runnable_hop: true })),+ routes: {},+ }]} sources={[]} chains={{ [modelChainKey('claude', models[0] as string)]: { kind: 'unread', retryable: true } }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={onProbeSettled} /></I18nextProvider>);++ expect(screen.getByRole('button', { name: /more model/i })).toBeTruthy();+ await userEvent.click(screen.getByRole('button', { name: /^Retry$|^重试$/i }));+ expect(onProbeSettled).toHaveBeenCalledOnce();+ expect(onProbeSettled).toHaveBeenCalledWith(expect.objectContaining({ backend: 'claude' }));+ });+it('opens Frame 02 with the exact backend and model context', async () => {const onOpenRoute = vi.fn();render(<I18nextProvider i18n={i18n}><AgentCard agents={[hubAgent]} sources={[]} chains={{}} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={onOpenRoute} onProbeSettled={vi.fn()} /></I18nextProvider>);diff --git a/ui/src/components/settings/models/AgentCard.tsx b/ui/src/components/settings/models/AgentCard.tsxindex e3bad2ad6..41f73633e 100644--- a/ui/src/components/settings/models/AgentCard.tsx+++ b/ui/src/components/settings/models/AgentCard.tsx@@ -10,7 +10,7 @@ import { ResponsiveMenu } from '@/components/ui/responsive-menu';import { cn } from '@/lib/utils';import { catalogModelIds } from './backendCatalog';import { COLLAPSED_MODEL_LIMIT, collapsedModelRows, modelChainKey, modelSupplyState, type ModelChainIndex, type ModelChainRead } from './modelRows';-import { foldRegionRead } from './regionRead';+import { foldRegionRead, regionFailed } from './regionRead';import { gatewayRouteStatus } from './supply';import { agentHasLiveChainProjection, type FreshRuntimeProjection } from './runtimeLifecycle';import { currentChainLink, isTakeoverChain } from './takeover';@@ -195,7 +195,7 @@ const AgentModelCard: React.FC<{const needsChainRepair = chainProjectionLive&& allModels.some((modelId) => {const read = chains[modelChainKey(agent.backend, modelId)];- return read?.kind === 'unread' || (read?.kind === 'degraded' && read.cause === 'read_failed');+ return read !== undefined && regionFailed(read);});const hasTakeover = chainProjectionLive&& allModels.some((modelId) => isTakeoverRead(chains[modelChainKey(agent.backend, modelId)]));@@ -302,7 +302,7 @@ const AgentModelCard: React.FC<{) : <Button variant="default" size="xs" className="model-hub-agent-head-action shrink-0 rounded-md px-2.5 text-[11px] font-semibold" onClick={() => onConnectHub(agent)} disabled={connecting}><PlugZap aria-hidden="true" />{t('settings.models.gateway.switchToGateway')}</Button>}</div></div>- {agent.mode === 'hub' && (models.length === 0 ? <div className="flex flex-col items-center gap-3 px-4 py-10 text-center sm:px-5"><p className="text-[12.5px] text-muted">{t('settings.models.gateway.group.emptyModels')}</p><ManageModelsButton disabled={pending} onClick={() => onOpenModels(agent)} /></div> : <div className="space-y-2 p-2">{noUsableSource && <p className="px-3 py-1 text-[11px] font-semibold text-muted">{t('settings.models.gateway.supply.none')}</p>}{models.map((modelId) => <ModelRow key={modelId} agent={agent} modelId={modelId} sources={sources} read={chainProjectionLive ? chains[modelChainKey(agent.backend, modelId)] : undefined} originHelpOpen={activeOriginHelp === modelChainKey(agent.backend, modelId)} onOriginHelpChange={onOriginHelpChange} onOpenRoute={onOpenRoute} />)}{canCollapse ? <button type="button" onClick={toggleCollapsed} className="model-hub-model-collapse flex h-6 w-full items-center gap-1.5 hover:text-foreground">{expanded ? <ChevronUp /> : <ChevronDown />}{expanded ? t('settings.models.gateway.collapse') : t('settings.models.gateway.moreModels', { count: collapsed.hidden.length })}</button> : needsChainRepair ? <button type="button" onClick={retryChains} className="model-hub-model-collapse flex h-6 w-full items-center gap-1.5 hover:text-foreground"><RefreshCw />{t('settings.models.gateway.retry')}</button> : null}</div>)}+ {agent.mode === 'hub' && (models.length === 0 ? <div className="flex flex-col items-center gap-3 px-4 py-10 text-center sm:px-5"><p className="text-[12.5px] text-muted">{t('settings.models.gateway.group.emptyModels')}</p><ManageModelsButton disabled={pending} onClick={() => onOpenModels(agent)} /></div> : <div className="space-y-2 p-2">{noUsableSource && <p className="px-3 py-1 text-[11px] font-semibold text-muted">{t('settings.models.gateway.supply.none')}</p>}{models.map((modelId) => <ModelRow key={modelId} agent={agent} modelId={modelId} sources={sources} read={chainProjectionLive ? chains[modelChainKey(agent.backend, modelId)] : undefined} originHelpOpen={activeOriginHelp === modelChainKey(agent.backend, modelId)} onOriginHelpChange={onOriginHelpChange} onOpenRoute={onOpenRoute} />)}{(canCollapse || needsChainRepair) && <div className="flex h-6 w-full items-center">{canCollapse && <button type="button" onClick={toggleCollapsed} className="model-hub-model-collapse flex h-6 flex-1 items-center gap-1.5 hover:text-foreground">{expanded ? <ChevronUp /> : <ChevronDown />}{expanded ? t('settings.models.gateway.collapse') : t('settings.models.gateway.moreModels', { count: collapsed.hidden.length })}</button>}{needsChainRepair && <button type="button" onClick={retryChains} className="model-hub-model-collapse model-hub-model-collapse--repair flex h-6 items-center gap-1.5 hover:text-foreground"><RefreshCw />{t('settings.models.gateway.retry')}</button>}</div>}</div>)}{agent.mode === 'hub' && <AgentSupplyIssues agent={agent} />}</section>);diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsxindex 48473e04a..ebfa12a79 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -13,7 +13,6 @@ import { OWNER_INSTANCE_CAPABILITIES } from '@/lib/sessionInfo';import { MANAGE_COMMIT_ACTIONS } from './manage';import type { ModelsSurfaceKind } from './modelHubSurfaceState';import { ApiCallError, modelsApi } from './modelsApi';-import { SOURCE_MUTATION_REPORT_PROJECTIONS } from './mutationSettlement';import { SettingsModelsPage } from './SettingsModelsPage';import { hasNativeSubscriptionCustody, SUBSCRIPTION_VENDORS } from './subscriptionOptions';import { CONTRACT_VERSION, type AgentBackend, type AgentChain, type AgentSupply, type BackendModel, type MigrationItem, type RuntimeDependency, type RuntimeManifest, type Source, type UsageSummary } from './types';@@ -138,6 +137,59 @@ const usageSummary: UsageSummary = {days: [{ day: '2026-08-18', requests: 12, token_reports: 12, input_tokens: 148230, cached_input_tokens: 96010, output_tokens: 4120 }],};+/**+ * One Hub agent whose only route runs through the retained Source, the chain+ * that route reads, and the impact the server reports for a write touching it.+ * Shared because the impact-scoped chain read is what every committed mutation+ * turns on, and each case would otherwise restate the same three shapes.+ */+const REFRESH_FAILED = /^Couldn't refresh, please retry$|^刷新失败,请重试$/;++const routedModelId = 'claude-opus-4-6';++const routedHubAgent: AgentSupply = {+ ...takeoverAgent,+ backend: 'claude',+ selected_model_id: routedModelId,+ sources: {+ order: [retainedSource.id],+ eligibility: [{ source_id: retainedSource.id, eligible: true }],+ },+ routes: { [routedModelId]: { hops: [{ source_id: retainedSource.id, model_id: routedModelId }] } },+ model_supply: [{ route_origin: 'manual' as const, model_id: routedModelId, chain_length: 1, has_runnable_hop: true }],+ builtin_models: [routedModelId],+};++const routedChain: AgentChain = {+ manual_override: { hops: [{ source_id: retainedSource.id, model_id: routedModelId }] },+ route_origin: 'manual' as const,+ contract_version: 10,+ backend: 'claude',+ model_id: routedModelId,+ current: { source_id: retainedSource.id, model_id: routedModelId },+ chain: [{+ source_id: retainedSource.id,+ model_id: routedModelId,+ channel: 'hub',+ health: 'healthy',+ runnable: true,+ reason: null,+ retry_at: null,+ }],+ supply_state: 'ok',+};++const routedImpact = {+ removed_hops: [{+ backend: 'claude' as const,+ menu_model: routedModelId,+ position: 1,+ source_id: retainedSource.id,+ model_id: routedModelId,+ }],+ interrupted: [{ backend: 'claude' as const, model_id: routedModelId, agents: ['Release bot'] }],+};+const deferred = <T,>() => {let resolve!: (value: T) => void;const promise = new Promise<T>((done) => {@@ -1170,58 +1222,25 @@ describe('SettingsModelsPage surface branches', () => {});it.each(MANAGE_COMMIT_ACTIONS)(- '[MH-SRC-DELETE-001] keeps the page-owned $action impact readable until every referenced projection lands',+ '[MH-SRC-DELETE-001] announces a committed $action once and reconciles every referenced projection with no second decision',async (action) => {- const modelId = 'claude-opus-4-6';+ // The guard already made the user confirm this exact impact before the+ // write, so repeating it afterwards asked them to decide something that+ // had already happened. What the commit still owes is the announcement+ // and the surface read: the toast lands immediately, the read runs behind+ // it, and the page settles on its own once every referenced projection —+ // including the impact-scoped chain — comes back.const updatedSource = { ...retainedSource, display_name: 'Updated source' };- const hubAgent: AgentSupply = {- ...takeoverAgent,- backend: 'claude',- selected_model_id: modelId,- sources: {- order: [retainedSource.id],- eligibility: [{ source_id: retainedSource.id, eligible: true }],- },- routes: { [modelId]: { hops: [{ source_id: retainedSource.id, model_id: modelId }] } },- model_supply: [{ route_origin: "manual" as const, model_id: modelId, chain_length: 1, has_runnable_hop: true }],- builtin_models: [modelId],- };- const affectedChain: AgentChain = { manual_override: {hops:[{source_id:retainedSource.id,model_id:modelId}]}, route_origin: "manual" as const,- contract_version: 10,- backend: 'claude',- model_id: modelId,- current: { source_id: retainedSource.id, model_id: modelId },- chain: [{- source_id: retainedSource.id,- model_id: modelId,- channel: 'hub',- health: 'healthy',- runnable: true,- reason: null,- retry_at: null,- }],- supply_state: 'ok',- };- const impact = {- removed_hops: [{- backend: 'claude' as const,- menu_model: modelId,- position: 1,- source_id: retainedSource.id,- model_id: modelId,- }],- interrupted: [{ backend: 'claude' as const, model_id: modelId, agents: ['Release bot'] }],- };const sourceRead = vi.spyOn(modelsApi, 'listSources').mockResolvedValue([retainedSource]);- vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([hubAgent]);+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([routedHubAgent]);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);+ const overviewRead = vi.spyOn(modelsApi, 'getAgentChains').mockResolvedValue([routedChain]);+ const chainRead = vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(routedChain);if (action === 'edit') {- vi.spyOn(modelsApi, 'patchSource').mockResolvedValueOnce({ source: updatedSource, ...impact });+ vi.spyOn(modelsApi, 'patchSource').mockResolvedValueOnce({ source: updatedSource, ...routedImpact });} else {- vi.spyOn(modelsApi, 'deleteSource').mockResolvedValueOnce(impact);+ vi.spyOn(modelsApi, 'deleteSource').mockResolvedValueOnce(routedImpact);}render(@@ -1236,6 +1255,10 @@ describe('SettingsModelsPage surface branches', () => {expect(within(sourceDialog).getByRole('textbox', { name: /Search model IDs|搜索模型 ID/i })).toBeTruthy();await waitFor(() => expect(overviewRead).toHaveBeenCalledOnce());+ const chainLanding = deferred<AgentChain>();+ chainRead.mockImplementationOnce(() => chainLanding.promise);+ sourceRead.mockResolvedValue(action === 'edit' ? [updatedSource] : []);+await userEvent.click(screen.getByRole('button', { name: /Manage Retained source|管理 Retained source/i }));if (action === 'edit') {await userEvent.click(screen.getByRole('menuitem', { name: /^Edit source$|^编辑供应商$/i }));@@ -1248,43 +1271,69 @@ describe('SettingsModelsPage surface branches', () => {await userEvent.click(screen.getByRole('button', { name: /^Remove source$|^移除供应商$/i }));}- const report = await screen.findByRole('dialog', {- name: action === 'edit' ? /source was updated|供应商已更新/i : /source was removed|供应商已移除/i,- });- expect(report.dataset.reportProjections?.split(' ')).toEqual(- Object.keys(SOURCE_MUTATION_REPORT_PROJECTIONS),+ const settled = await screen.findByText(+ action === 'edit' ? /^The source was updated$|^供应商已更新$/ : /^The source was removed$|^供应商已移除$/,);- expect(report.textContent).toContain(modelId);- expect(report.textContent).toContain('Release bot');-- const chainLanding = deferred<AgentChain>();- chainRead.mockImplementationOnce(() => chainLanding.promise);- sourceRead.mockResolvedValue(action === 'edit' ? [updatedSource] : []);- const done = within(report).getAllByRole('button', { name: /^Done$|^完成$/i })- .find((button) => button.classList.contains('model-hub-guard-action'));- await userEvent.click(done!);+ expect(settled.closest('[role="dialog"]')).toBeNull();+ expect(screen.queryByRole('dialog', {+ name: action === 'edit' ? /source was updated|供应商已更新/i : /source was removed|供应商已移除/i,+ })).toBeNull();+ // The impact evidence still decides which chains the commit must re-read;+ // only the modal that used to gate that read is gone.+ await waitFor(() => expect(chainRead).toHaveBeenLastCalledWith('claude', routedModelId));+ await act(async () => {+ chainLanding.resolve(routedChain);+ await chainLanding.promise;+ });if (action === 'edit') {await waitFor(() => expect(document.querySelector('.model-hub-source-title')?.textContent).toBe(updatedSource.display_name));} else {await waitFor(() => expect(document.querySelector('.model-hub-source-title')).toBeNull());}- expect(screen.getByRole('dialog', {- name: action === 'edit' ? /source was updated|供应商已更新/i : /source was removed|供应商已移除/i,- })).toBeTruthy();- expect(chainRead).toHaveBeenLastCalledWith('claude', modelId);-- await act(async () => {- chainLanding.resolve(affectedChain);- await chainLanding.promise;- });- await waitFor(() => expect(screen.queryByRole('dialog', {- name: action === 'edit' ? /source was updated|供应商已更新/i : /source was removed|供应商已移除/i,- })).toBeNull());+ // Every projection came back, so nothing may tell the user the page is+ // behind the server. This is the line the bug that opened the lane showed+ // after a save that had in fact landed.+ expect(screen.queryByText(REFRESH_FAILED)).toBeNull();},);+ it('says the page could not refresh when a route the write touched cannot be read', async () => {+ // The other half of the same decision. A route that could not be re-read+ // after a committed write is a real gap between the page and the server, and+ // the chain card's own Retry is not always on screen to say so — a backend+ // with enough models renders the collapse control in its place. So the page+ // keeps this line, alongside the announcement: the write did commit, and the+ // two statements are about different things.+ const updatedSource = { ...retainedSource, display_name: 'Updated source' };+ renderPage([retainedSource], [routedHubAgent]);+ const overviewRead = vi.spyOn(modelsApi, 'getAgentChains').mockResolvedValue([routedChain]);+ const chainRead = vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(routedChain);+ vi.spyOn(modelsApi, 'patchSource').mockResolvedValueOnce({ source: updatedSource, ...routedImpact });++ await userEvent.click((await screen.findByText('Retained source')).closest('button') as HTMLButtonElement);+ await screen.findByRole('dialog', { name: 'Retained source' });+ // The per-backend overview read has to settle first: it shares the chain+ // authority's key with the impact-scoped read, so letting it land later+ // would make this a supersession case instead of the read failure at issue.+ await waitFor(() => expect(overviewRead).toHaveBeenCalledOnce());++ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([updatedSource]);+ chainRead.mockRejectedValue(new ApiCallError('chain_unavailable'));++ await userEvent.click(screen.getByRole('button', { name: /Manage Retained source|管理 Retained source/i }));+ await userEvent.click(screen.getByRole('menuitem', { name: /^Edit source$|^编辑供应商$/i }));+ const name = screen.getByLabelText(/^Display name$|^显示名称$/i);+ await userEvent.clear(name);+ await userEvent.type(name, updatedSource.display_name);+ await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));++ expect(await screen.findByText(/^The source was updated$|^供应商已更新$/)).toBeTruthy();+ expect(await screen.findByText(REFRESH_FAILED)).toBeTruthy();+ await waitFor(() => expect(chainRead).toHaveBeenLastCalledWith('claude', routedModelId));+ });+it('[MH-SRC-DELETE-002] returns to the list once a removal commits, whichever way the route answered', async () => {// The dialog renders one selected source, so a committed removal leaves it// nothing to show, and returning to the list is the whole outcome the user@@ -1314,9 +1363,46 @@ describe('SettingsModelsPage surface branches', () => {expect(deleteWrite).toHaveBeenLastCalledWith(removed.id, undefined);// Not merely closed: the placeholder never became something to read past.expect(screen.queryByText(/no longer available|已经不在了/i)).toBeNull();+ // The row that opened this dialog left with the removal, so the recorded+ // return target is disconnected. Focus has to land back inside the Hub+ // rather than on `document.body`, where the next Tab would restart at the+ // top of the document instead of near the list being worked in. The shell+ // rather than the overview is what both rounds share: the second removal+ // empties the Hub, which unmounts the overview along with the last row.+ expect(document.activeElement).not.toBe(document.body);+ expect(document.activeElement?.closest('.model-hub-shell')).toBeTruthy();+ if (survivors.length) {+ expect(document.activeElement?.closest('.model-hub-overview-grid')).toBeTruthy();+ }}});+ it('reports an edit whose Source turned out to be gone as gone, not as updated', async () => {+ // The commit envelope carries the OUTCOME, not the flow: this is still the+ // edit flow, but nothing was updated, and announcing 「已更新」 over a panel+ // saying the provider is no longer there tells the user two things at once.+ renderPage([retainedSource]);+ const patch = vi.spyOn(modelsApi, 'patchSource').mockRejectedValueOnce(new ApiCallError('source_not_found'));++ await userEvent.click((await screen.findByText('Retained source')).closest('button') as HTMLButtonElement);+ await screen.findByRole('dialog', { name: 'Retained source' });+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);++ await userEvent.click(screen.getByRole('button', { name: /Manage Retained source|管理 Retained source/i }));+ await userEvent.click(screen.getByRole('menuitem', { name: /^Edit source$|^编辑供应商$/i }));+ const name = screen.getByLabelText(/^Display name$|^显示名称$/i);+ await userEvent.clear(name);+ await userEvent.type(name, 'Renamed source');+ await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));++ await waitFor(() => expect(patch).toHaveBeenCalledOnce());+ expect(screen.queryByText(/^The source was updated$|^供应商已更新$/)).toBeNull();+ // The Save press gets an answer OUTSIDE the dialog — the toast — saying the+ // same thing the panel under it now says, rather than one each.+ await waitFor(() => expect(screen.getAllByText(/no longer available|已经不在了/i)+ .some((node) => node.closest('[role="dialog"]') === null)).toBe(true));+ });+it('states in the dialog that a source disappeared with no removal of ours', async () => {// The other half of the same behavior: a refetch that finds the source gone// is not a removal this dialog can close on, so it holds the placeholder —diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex 6798af361..a7980c9a3 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -20,11 +20,10 @@ import { RecentSwitchesCard } from './RecentSwitchesCard';import { RouteChainDialog, type RouteCollectionObservation, type RouteCommitReconciliation, type RouteReport } from './RouteChainDialog';import { routeChainMatchesAttempt } from './routeChainDraft';import { SourceDetailPanel } from './SourceDetailPanel';-import { SourceMutationReport } from './SourceMutationReport';import { SourceOrderDrawer } from './SourceOrderDrawer';import { SourcesCard } from './SourcesCard';import { modelsSurfaceKindFromReads } from './modelHubSurfaceState';-import { focusModelHubProjection } from './modelHubFocus';+import { focusDialogReturn, focusModelHubProjection } from './modelHubFocus';import { buildSupplyRelations } from './supplyRelations';import {emptySuspendedRouteAttempts,@@ -34,21 +33,22 @@ import {import { SupplyGraph, SupplyLegend } from './SupplyGraph';import { UsageTab } from './UsageTab';import './modelHubSurface.css';-import { agentsWithEcho, createLatestAsyncAuthority, createLatestAsyncAuthorityByKey, createLatestEntityAuthorityByKey, createPendingWrites, mapWithConcurrency } from './asyncLifetime';+import { agentsWithEcho, createLatestAsyncAuthority, createLatestAsyncAuthorityByKeySet, createLatestEntityAuthorityByKey, createPendingWrites, mapWithConcurrency } from './asyncLifetime';import { createAgentCollectionReadAuthority, createSourceCollectionReadAuthority } from './collectionReadAuthority';import { emptyFeed, feedAfterHeadRead, feedAfterTailRead, feedTailCursor, type EventFeed } from './eventFeed';import { modelsApi, type SourceCreated } from './modelsApi';import { convergeMutation, createIntentAuthority } from './mutationConvergence';import {readSurfaceLanding,- sourceMutationLanding,+ sourceMutationReadFailed,+ SOURCE_MUTATION_TOAST,type PresentSourceMutationCommit,type SourceMutationLanding,type SourceMutationLandingReads,type SourceMutationSettlement,type TrackSourceMutation,} from './mutationSettlement';-import { modelChainKey, modelChainRequests, type ModelChainIndex, type ModelChainRequest } from './modelRows';+import { chainKeyBackend, modelChainKey, modelChainRequests, type ModelChainIndex, type ModelChainRequest } from './modelRows';import {beginRegionRead,failRegionRead,@@ -63,7 +63,6 @@ import {} from './regionRead';import { freshRuntimeProjection, pollRuntimeStatus, resumeInstallAndStartRuntime, runtimeCanAttemptInstall, runtimeIsRunning } from './runtimeLifecycle';import { createRouteProjectionReconciler, type RouteProjectionStatus } from './routeProjectionReconciliation';-import { useSourceMutationReport } from './useSourceMutationReport';import { handOffProviderTab } from './providerTab';import { resumeGatewayAdoption } from './gatewayAdoption';import { SUBSCRIPTION_MENU_ROWS, hasNativeSubscriptionCustody } from './subscriptionOptions';@@ -126,25 +125,23 @@ const readExactAgentChain = async (),});-const settleAgentChainIndex = (- previous: ModelChainIndex,- agent: AgentSupply,- incoming: ModelChainIndex,-): ModelChainIndex => {- const prefix = `${agent.backend}\u0000`;- const next = Object.fromEntries(Object.entries(previous).filter(([key]) => !key.startsWith(prefix)));- for (const [key, read] of Object.entries(incoming)) {- next[key] = settleRegionRead(previous[key] ?? loadingRegion(), read);- }- return next;-};--const settleExactAgentChain = (+/**+ * Installs exactly the chains this read still owns.+ *+ * There is no backend-wide sweep here. A read owns chain keys, not a backend,+ * so a key it does not own belongs to a newer read and has to be left exactly+ * as that read left it. Retiring the keys of models a backend no longer has is+ * `beginAgentChainIndex`'s job, which reseeds the backend from the Agent's+ * current catalogue before every whole-backend read.+ */+const settleChainIndex = (previous: ModelChainIndex,incoming: ModelChainIndex,+ owned: ReadonlySet<string>,): ModelChainIndex => {const next = { ...previous };for (const [key, read] of Object.entries(incoming)) {+ if (!owned.has(key)) continue;next[key] = settleRegionRead(previous[key] ?? loadingRegion(), read);}return next;@@ -163,10 +160,6 @@ const beginAgentChainIndex = (return next;};-type ChainAuthorityLanding =- | { scope: 'backend'; agent: AgentSupply; chains: ModelChainIndex }- | { scope: 'models'; chains: ModelChainIndex };-type AuthorizedSurfaceLanding = {landing: SourceMutationLandingReads;sourceSnapshot: number;@@ -414,7 +407,6 @@ export const SettingsModelsPage: React.FC = () => {const [sourceCollectionReads] = React.useState(() => createSourceCollectionReadAuthority(modelsApi));const [agentCollectionReads] = React.useState(() => createAgentCollectionReadAuthority(modelsApi));const [presenceRefreshing, setPresenceRefreshing] = React.useState(false);- const sourceMutationReport = useSourceMutationReport();const overviewRef = React.useRef<HTMLDivElement>(null);const pageRef = React.useRef<HTMLDivElement>(null);const aliveRef = React.useRef(true);@@ -488,19 +480,18 @@ export const SettingsModelsPage: React.FC = () => {});}, [runtimeHealth, runtimeRead.kind, runtimeRecoveryPending, startingRuntime]);- const [chainReadAuthority] = React.useState(() => createLatestAsyncAuthorityByKey<AgentBackend, ChainAuthorityLanding>((_backend, incoming) => {+ const [chainReadAuthority] = React.useState(() => createLatestAsyncAuthorityByKeySet<string, ModelChainIndex>((incoming, owned) => {if (!aliveRef.current) return;- setChainsRead((previous) => {- const current = foldRegionRead<ModelChainIndex, ModelChainIndex>(previous, {+ setChainsRead((previous) => readyRegion(settleChainIndex(+ foldRegionRead<ModelChainIndex, ModelChainIndex>(previous, {loading: () => ({}),ready: (data) => data,unread: () => ({}),degraded: (staleData) => staleData,- });- return readyRegion(incoming.scope === 'backend'- ? settleAgentChainIndex(current, incoming.agent, incoming.chains)- : settleExactAgentChain(current, incoming.chains));- });+ }),+ incoming,+ owned,+ )));}));const refreshAgentChains = React.useCallback(async (agent: AgentSupply) => {@@ -510,36 +501,28 @@ export const SettingsModelsPage: React.FC = () => {unread: () => ({}),degraded: (staleData) => staleData,}), agent)));- await chainReadAuthority.run(agent.backend, async () => ({- agent,- chains: await readAgentChains(agent),- scope: 'backend' as const,- }));+ await chainReadAuthority.run(+ modelChainRequests([agent]).map(({ backend, modelId }) => modelChainKey(backend, modelId)),+ () => readAgentChains(agent),+ );}, [chainReadAuthority]);const refreshAffectedChains = React.useCallback(async (requests: readonly ModelChainRequest[],): Promise<ModelChainIndex> => {- const byBackend = new Map<AgentBackend, ModelChainRequest[]>();- for (const request of requests) {- const backendRequests = byBackend.get(request.backend) ?? [];- backendRequests.push(request);- byBackend.set(request.backend, backendRequests);- }- const landings = await Promise.all([...byBackend].map(async ([backend, backendRequests]) => {- let incoming: ModelChainIndex = {};- const result = await chainReadAuthority.run(backend, async () => {- incoming = await readChainRequests(backendRequests);- return { scope: 'models' as const, chains: incoming };- });- return result === 'landed'- ? incoming- : Object.fromEntries(backendRequests.map(({ backend: requestBackend, modelId }) => [- modelChainKey(requestBackend, modelId),- unreadRegion(),- ]));- }));- return Object.assign({}, ...landings);+ let incoming: ModelChainIndex = {};+ const owned = await chainReadAuthority.run(+ requests.map(({ backend, modelId }) => modelChainKey(backend, modelId)),+ async () => {+ incoming = await readChainRequests(requests);+ return incoming;+ },+ );+ // What drops out here is exactly the chains a newer read took over, and that+ // read is the one installing them — a superseded key is not an unreadable+ // one. Every key this read still owns stays, failed or not, because no other+ // read is going to answer for it.+ return Object.fromEntries(Object.entries(incoming).filter(([key]) => owned.has(key)));}, [chainReadAuthority]);const refreshAllAgentChains = React.useCallback((agentRows: AgentSupply[]) => {@@ -549,14 +532,14 @@ export const SettingsModelsPage: React.FC = () => {!suspendedBackends.has(agent.backend)&& agent.backend !== routeCommitBackend);const activeBackends = new Set(hubAgents.map((agent) => agent.backend));- chainReadAuthority.invalidateExcept(activeBackends);+ chainReadAuthority.invalidateExcept((key) => activeBackends.has(chainKeyBackend(key)));setChainsRead((previous) => readyRegion(Object.fromEntries(Object.entries(foldRegionRead<ModelChainIndex, ModelChainIndex>(previous, {loading: () => ({}),ready: (data) => data,unread: () => ({}),degraded: (staleData) => staleData,- })).filter(([key]) => activeBackends.has(key.split('\u0000')[0] as AgentBackend)),+ })).filter(([key]) => activeBackends.has(chainKeyBackend(key))),)));for (const agent of probeAgents) void refreshAgentChains(agent);}, [chainReadAuthority, refreshAgentChains, routeCommitBackend, suspendedRouteAttempts]);@@ -679,12 +662,13 @@ export const SettingsModelsPage: React.FC = () => {}, affectedChains);return { landing: outcome.landing, sourceSnapshot };});- const landing = sourceMutationLanding(- outcome.landing,- affectedChains,- aliveRef.current && result === 'landed',- );- if (aliveRef.current && result === 'landed' && landing.verdict === 'degraded') {+ if (!aliveRef.current || result === 'stale') return null;+ const landing = outcome.landing;+ // Every region this read installs is in scope, route chains included: a+ // chain card's own Retry is not always rendered, so dropping the page line+ // would leave a real read failure with nothing that says so. What is out of+ // scope is supersession, which no longer reaches here as a failure.+ if (landing !== null && sourceMutationReadFailed(landing)) {showToast(t('settings.models.toast.refreshFailed') as string, 'error');}return landing;@@ -995,11 +979,28 @@ export const SettingsModelsPage: React.FC = () => {* `sourceDetail.gone` stays for the case a close cannot cover: the source* disappeared out of band — removed from another surface, or found missing by* an edit or a refetch — with no delete of ours to close the dialog.+ *+ * The commit reports itself in one toast and the surface read runs behind it.+ * A post-commit modal would only repeat the impact the guard already made the+ * user confirm before the write, and it turned an ordinary superseded or+ * failed read into a second decision about a change that already landed. The+ * write is done; what a failed read owes the user is the page's own stale+ * projection and Retry, which every region already carries.*/const presentSourceMutation = React.useCallback<PresentSourceMutationCommit>(async (commit) => {- if (commit.action === 'delete') selectSource(null);- await sourceMutationReport.present(commit);- }, [selectSource, sourceMutationReport.present]);+ // Only a removal closes the dialog. An edit that found its Source absent+ // leaves it open on `sourceDetail.gone`, which is the same fact the toast+ // states — the page never announces an update that did not happen.+ if (commit.outcome === 'removed') selectSource(null);+ const toast = SOURCE_MUTATION_TOAST[commit.outcome];+ showToast(t(toast.key) as string, toast.tone);+ try {+ await commit.settle();+ } catch {+ // `refresh` already owns what a read can say: a failed projection keeps+ // its own stale treatment and Retry, and raises the page's refresh toast.+ }+ }, [selectSource, showToast, t]);const selectedSource = sources.find((source) => source.id === selectedSourceId) ?? null;const sourceDetailOpen = selectedSourceId !== null && subscriptionVendor === null;const orderAgent = agents.find((agent) => agent.backend === orderBackend && agent.mode === 'hub') ?? null;@@ -1061,7 +1062,7 @@ export const SettingsModelsPage: React.FC = () => {onStatus: setRouteCommitStatus,}), [readRouteAgents, readRouteSources]);const routeCommitted = React.useCallback((result: RouteReport) => {- chainReadAuthority.invalidate(result.chain.backend);+ chainReadAuthority.invalidate([modelChainKey(result.chain.backend, result.chain.model_id)]);routeObserved(result.chain);setSuspendedRouteAttempts((attempts) =>releaseSuspendedRouteAttempt(attempts, result.chain.backend),@@ -1116,10 +1117,10 @@ export const SettingsModelsPage: React.FC = () => {suspendedChainBaselinesRef.current.set(held.backend, chainsRead);void (async () => {try {- await chainReadAuthority.run(held.backend, async () => ({- chains: await readExactAgentChain(freshAgent, held.modelId),- scope: 'models' as const,- }));+ await chainReadAuthority.run(+ [modelChainKey(held.backend, held.modelId)],+ () => readExactAgentChain(freshAgent, held.modelId),+ );if (suspendedHubFrontiersRef.current.get(held.backend) !== freshAgent) return;} catch {if (suspendedHubFrontiersRef.current.get(held.backend) !== freshAgent) return;@@ -1438,10 +1439,18 @@ export const SettingsModelsPage: React.FC = () => {onCloseAutoFocus={(event) => {const returnFocus = sourceDetailReturnFocusRef.current;sourceDetailReturnFocusRef.current = null;- const target = returnFocus?.();- if (!target?.isConnected) return;- event.preventDefault();- target.focus();+ // A removal deletes the row that opened this dialog, so the return+ // target is already disconnected. The overview is the nearest+ // neighbourhood to fall back into — except when the removal took the+ // last Source with it, which unmounts the overview too and leaves the+ // shell as the smallest surface still standing. Either beats+ // `document.body`, where the next Tab restarts at the top of the page.+ if (focusDialogReturn({+ root: overviewRef.current ?? pageRef.current,+ returnTarget: returnFocus?.() ?? null,+ })) {+ event.preventDefault();+ }}}onEscapeKeyDown={(event) => {// Radix observes Escape before React's row handlers; marked editors own it locally.@@ -1465,11 +1474,6 @@ export const SettingsModelsPage: React.FC = () => {: <section className="grid min-h-0 flex-1 place-items-center px-5 py-12 text-center text-[12px] text-muted">{t('settings.models.sourceDetail.gone')}</section>}</DialogContent></Dialog>- <SourceMutationReport- report={sourceMutationReport.report}- onComplete={() => { void sourceMutationReport.complete(); }}- onDismiss={sourceMutationReport.dismiss}- /><AddApiKeyDialog open={apiKeyOpen} sourceReads={sourceCollectionReads} onClose={() => setApiKeyOpen(false)} onAdded={(created) => void sourceAdded(created)} />{subscriptionVendor && (<OAuthConnectDialogdiff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsxindex 85daff016..e30d1d65e 100644--- a/ui/src/components/settings/models/SourceDetailPanel.test.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx@@ -2,7 +2,7 @@import { readFileSync } from 'node:fs';import { join } from 'node:path';import * as React from 'react';-import { cleanup, render, screen, waitFor, within } from '@testing-library/react';+import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { I18nextProvider } from 'react-i18next';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -13,6 +13,8 @@ import { classifyModelHubFailure, createPendingWrites } from './asyncLifetime';import { MANAGE_DESTINATION, type ManageKind } from './manage';import { ApiCallError, modelsApi } from './modelsApi';import type {+ PresentSourceMutationCommit,+ SourceMutationCommit,SourceMutationLanding,SourceMutationLandingReads,SourceMutationSettlement,@@ -21,7 +23,6 @@ import type {import { GuardGapList } from './GuardGapList';import { REPAIR_DESTINATION, REPAIR_LABEL_KEY, repairAction, type RepairKind } from './repair';import { SourceDetailPanel } from './SourceDetailPanel';-import { SourceMutationReport } from './SourceMutationReport';import {COOLDOWN_DETAIL_KEYS,ERROR_DETAIL_KEYS,@@ -29,7 +30,6 @@ import {SOURCE_STATUSES,} from './types';import type { Source, SourceDetailKey, SourceKind, SourceProtocol, SupplyChannel } from './types';-import { useSourceMutationReport } from './useSourceMutationReport';const source: Source = {id: 'src_detail',@@ -119,11 +119,15 @@ const deferred = <T,>() => {let sourceSnapshot = 0;const beginSourceSnapshot = () => ++sourceSnapshot;-const mutationLanding = (- verdict: SourceMutationLanding['verdict'] = 'landed',-): SourceMutationLanding => verdict === 'landed'- ? { verdict, reads: {} as SourceMutationLandingReads, affectedChains: [] }- : { verdict, reads: null, affectedChains: [] };+/**+ * Whether this mutation's own read published the surface, or a newer read took+ * the surface over before it could land. There is no third answer: a region the+ * read could not complete rides inside the published surface as its own failed+ * `RegionRead`, which the page draws as stale with its own Retry.+ */+type LandingOutcome = 'landed' | 'superseded';+const mutationLanding = (outcome: LandingOutcome = 'landed'): SourceMutationLanding =>+ outcome === 'landed' ? {} as SourceMutationLandingReads : null;const settlement = (overrides: Partial<SourceMutationSettlement> = {}): SourceMutationSettlement => ({source: vi.fn().mockResolvedValue(mutationLanding()),gone: vi.fn().mockResolvedValue(mutationLanding()),@@ -133,26 +137,26 @@ const settlement = (overrides: Partial<SourceMutationSettlement> = {}): SourceMu...overrides,});const immediateTrack: TrackSourceMutation = async (work) => work(source, settlement());-type ReportOwnedPanelProps = Omit<React.ComponentProps<typeof SourceDetailPanel>, 'onMutationCommitted'>;-const ReportOwnedPanel: React.FC<ReportOwnedPanelProps> = (props) => {- const owner = useSourceMutationReport();- return (- <>- <SourceDetailPanel {...props} onMutationCommitted={owner.present} />- <SourceMutationReport- report={owner.report}- onComplete={() => { void owner.complete(); }}- onDismiss={owner.dismiss}- />- </>- );+// The surface owner announces a committed mutation and reconciles it behind that+// announcement — no second decision stands between the write and its settlement.+// These panel tests keep that presenter minimal on purpose: the toast belongs to+// the page, so what is proved here is the envelope the panel hands over and the+// settlement it runs, not the copy the page chooses for it.+const commits: SourceMutationCommit[] = [];+const presentCommit: PresentSourceMutationCommit = async (commit) => {+ commits.push(commit);+ await commit.settle();};+type CommittedPanelProps = Omit<React.ComponentProps<typeof SourceDetailPanel>, 'onMutationCommitted'>;+const CommittedPanel: React.FC<CommittedPanelProps> = (props) => (+ <SourceDetailPanel {...props} onMutationCommitted={presentCommit} />+);type MutationScheduler = <T>(work: () => Promise<T>) => Promise<T>;const renderPanel = (adoptedBy: Source['adopted_by'] = undefined) => render(<ToastProvider><I18nextProvider i18n={i18n}>- <ReportOwnedPanel source={{ ...source, adopted_by: adoptedBy }} trackMutation={immediateTrack} onReauth={noReauth} />+ <CommittedPanel source={{ ...source, adopted_by: adoptedBy }} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider></ToastProvider>,);@@ -160,16 +164,15 @@ const renderPanel = (adoptedBy: Source['adopted_by'] = undefined) => render(const renderProtocol = (protocol: SourceProtocol, models: Source['models'] = source.models) => render(<ToastProvider><I18nextProvider i18n={i18n}>- <ReportOwnedPanel source={{ ...source, protocol, models }} trackMutation={immediateTrack} onReauth={noReauth} />+ <CommittedPanel source={{ ...source, protocol, models }} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider></ToastProvider>,);const EchoPanel: React.FC<{- reconcile?: () => Promise<SourceMutationLanding['verdict'] | void> | SourceMutationLanding['verdict'] | void;+ reconcile?: () => Promise<LandingOutcome | void> | LandingOutcome | void;scheduler?: MutationScheduler;}> = ({ reconcile = vi.fn(), scheduler = async (work) => work() }) => {- const owner = useSourceMutationReport();const [current, setCurrent] = React.useState<Source | null>(source);const currentRef = React.useRef<Source | null>(current);currentRef.current = current;@@ -182,18 +185,9 @@ const EchoPanel: React.FC<{unread: async () => mutationLanding((await reconcile()) ?? 'landed'),}));});- return (- <>- {current- ? <SourceDetailPanel source={current} trackMutation={trackMutation} onReauth={noReauth} onMutationCommitted={owner.present} />- : <p data-testid="source-gone">Source gone</p>}- <SourceMutationReport- report={owner.report}- onComplete={() => { void owner.complete(); }}- onDismiss={owner.dismiss}- />- </>- );+ return current+ ? <SourceDetailPanel source={current} trackMutation={trackMutation} onReauth={noReauth} onMutationCommitted={presentCommit} />+ : <p data-testid="source-gone">Source gone</p>;};// Typed off the prop rather than off `vi.fn()`: the default would otherwise@@ -212,6 +206,7 @@ const renderEchoPanel = (afterEach(() => {cleanup();+ commits.length = 0;sourceSnapshot = 0;vi.restoreAllMocks();vi.unstubAllGlobals();@@ -238,7 +233,7 @@ describe('SourceDetailPanel', () => {const pending = new Promise<Source>(() => {});const add = vi.spyOn(modelsApi, 'addCustomModel').mockReturnValue(pending);const refetch = vi.spyOn(modelsApi, 'refreshSource');- render(<I18nextProvider i18n={i18n}><ReportOwnedPanel source={source} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><CommittedPanel source={source} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider>);const user = userEvent.setup();await user.click(screen.getByRole('button', { name: /Add model|添加模型/ }));await user.type(screen.getByPlaceholderText(/Model ID|模型 ID/), 'manual-model');@@ -253,7 +248,7 @@ describe('SourceDetailPanel', () => {it('shows refetch progress only on refetch while a manual draft is open', async () => {vi.spyOn(modelsApi, 'refreshSource').mockReturnValue(new Promise(() => {}));const add = vi.spyOn(modelsApi, 'addCustomModel');- render(<I18nextProvider i18n={i18n}><ReportOwnedPanel source={source} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><CommittedPanel source={source} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider>);await userEvent.click(screen.getByRole('button', { name: /Add model|添加模型/ }));const refetch = screen.getByRole('button', { name: /^Refetch$|^重新拉取$/i });await userEvent.click(refetch);@@ -269,7 +264,7 @@ describe('SourceDetailPanel', () => {const headingRef = React.createRef<HTMLHeadingElement>();render(<I18nextProvider i18n={i18n}>- <ReportOwnedPanel source={source} headingRef={headingRef} trackMutation={immediateTrack} onReauth={noReauth} />+ <CommittedPanel source={source} headingRef={headingRef} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider>,);@@ -381,7 +376,7 @@ describe('SourceDetailPanel', () => {it('renders the proved protocol through its product-facing locale key', async () => {render(<I18nextProvider i18n={i18n}>- <ReportOwnedPanel+ <CommittedPanelsource={{ ...source, vendor: 'custom', protocol: 'openai_chat' }}trackMutation={immediateTrack}onReauth={noReauth}@@ -395,12 +390,14 @@ describe('SourceDetailPanel', () => {expect(screen.queryByText('openai_chat')).toBeNull();});- it('holds a committed edit impact envelope until the user completes the report', async () => {+ it('hands a committed edit its exact server impact and settles it with no second decision', async () => {const updated = { ...source, display_name: 'Impacted source' };+ const hops = [{ backend: 'claude' as const, menu_model: 'claude-opus-4-6', position: 1, source_id: source.id, model_id: 'model-a' }];+ const gaps = [{ backend: 'claude' as const, model_id: 'claude-opus-4-6', agents: ['Release bot'] }];vi.spyOn(modelsApi, 'patchSource').mockResolvedValueOnce({source: updated,- removed_hops: [{ backend: 'claude', menu_model: 'claude-opus-4-6', position: 1, source_id: source.id, model_id: 'model-a' }],- interrupted: [{ backend: 'claude', model_id: 'claude-opus-4-6', agents: ['Release bot'] }],+ removed_hops: hops,+ interrupted: gaps,});renderEchoPanel();@@ -411,14 +408,11 @@ describe('SourceDetailPanel', () => {await userEvent.type(name, updated.display_name);await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));- const impactDialog = await screen.findByRole('dialog', { name: /source was updated|供应商已更新/i });- expect(screen.queryByRole('heading', { name: updated.display_name })).toBeNull();- const done = within(impactDialog)- .getAllByRole('button', { name: /^Done$|^完成$/i })- .find((button) => button.classList.contains('model-hub-guard-action'));- expect(done).toBeTruthy();- await userEvent.click(done!);expect(await screen.findByRole('heading', { name: updated.display_name })).toBeTruthy();+ expect(screen.queryByRole('dialog')).toBeNull();+ expect(commits).toHaveLength(1);+ expect(commits[0].outcome).toBe('updated');+ expect(commits[0].impact).toEqual({ hops, gaps });});it('echoes a non-empty server plan exactly when deleting a source', async () => {@@ -453,14 +447,9 @@ describe('SourceDetailPanel', () => {would_remove_hops: hops,would_interrupt: gaps,});- expect(screen.queryByTestId('source-gone')).toBeNull();- const impactDialog = await screen.findByRole('dialog', { name: /source was removed|供应商已移除/i });- const done = within(impactDialog)- .getAllByRole('button', { name: /^Done$|^完成$/i })- .find((button) => button.classList.contains('model-hub-guard-action'));- expect(done).toBeTruthy();- await userEvent.click(done!);expect(await screen.findByTestId('source-gone')).toBeTruthy();+ expect(screen.queryByRole('dialog')).toBeNull();+ expect(commits.at(-1)?.impact).toEqual({ hops, gaps });});it('sends no force when deleting a source with an empty server plan', async () => {@@ -633,19 +622,11 @@ describe('SourceDetailPanel', () => {await submitManagementWrite(action, forced);await waitFor(() => expect(inventory).toHaveBeenCalledOnce());- if (outcome === 'committed' && forced) {- const impact = await screen.findByRole('dialog', {- name: action === 'edit' ? /source was updated|供应商已更新/i : /source was removed|供应商已移除/i,- });- expect(impact.textContent).toContain('claude-opus-4-6');- const done = within(impact)- .getAllByRole('button', { name: /^Done$|^完成$/i })- .find((button) => button.classList.contains('model-hub-guard-action'));- expect(done).toBeTruthy();- await userEvent.click(done!);- }-if (outcome === 'committed') {+ if (forced) {+ await waitFor(() => expect(commits).toHaveLength(1));+ expect(commits[0].impact?.hops.map((hop) => hop.menu_model)).toEqual(['claude-opus-4-6']);+ }if (action === 'edit') expect(await screen.findByRole('heading', { name: 'Unknown edit' })).toBeTruthy();else expect(await screen.findByTestId('source-gone')).toBeTruthy();return;@@ -720,11 +701,9 @@ describe('SourceDetailPanel', () => {});it.each(['edit', 'delete'] as const)(- 'keeps the exact committed $action impact mounted until settlement lands',+ 'settles a committed $action once and leaves a superseded read to the surface that owns it',async (action) => {- const reconcile = vi.fn()- .mockResolvedValueOnce('degraded')- .mockResolvedValueOnce('landed');+ const reconcile = vi.fn().mockResolvedValue('superseded');const hops = [{ backend: 'claude' as const, menu_model: 'claude-opus-4-6', position: 1, source_id: source.id, model_id: 'model-a' }];const gaps = [{ backend: 'claude' as const, model_id: 'claude-opus-4-6', agents: ['Release bot'] }];if (action === 'edit') {@@ -744,42 +723,28 @@ describe('SourceDetailPanel', () => {gone: async () => mutationLanding(await reconcile()),}));render(- <ToastProvider>- <I18nextProvider i18n={i18n}>- <ReportOwnedPanel source={source} trackMutation={trackMutation} onReauth={noReauth} />- </I18nextProvider>- </ToastProvider>,+ <I18nextProvider i18n={i18n}>+ <CommittedPanel source={source} trackMutation={trackMutation} onReauth={noReauth} />+ </I18nextProvider>,);await submitManagementWrite(action, false);- const impact = await screen.findByRole('dialog', {- name: action === 'edit' ? /source was updated|供应商已更新/i : /source was removed|供应商已移除/i,- });- const committedEvidence = () => Array.from(impact.querySelectorAll('.model-hub-guard-hop'))- .map((node) => node.textContent);- const evidenceBeforeRetry = committedEvidence();- expect(impact.textContent).toContain(hops[0].menu_model);- expect(impact.textContent).toContain(gaps[0].agents[0]);-- const done = within(impact).getAllByRole('button', { name: /^Done$|^完成$/i })- .find((button) => button.classList.contains('model-hub-guard-action'));- expect(done).toBeTruthy();- await userEvent.click(done!);- expect(await within(impact).findByText(/could not be refreshed|暂时无法刷新/i)).toBeTruthy();- expect(committedEvidence()).toEqual(evidenceBeforeRetry);- expect(within(impact).getAllByRole('button', { name: /Dismiss unverified result|放弃未验证结果/i })- .some((button) => button.classList.contains('model-hub-guard-action'))).toBe(true);-- await userEvent.click(within(impact).getByRole('button', { name: /^Try again$|^重试$/i }));- await waitFor(() => expect(screen.queryByRole('dialog', {- name: action === 'edit' ? /source was updated|供应商已更新/i : /source was removed|供应商已移除/i,- })).toBeNull());- expect(reconcile).toHaveBeenCalledTimes(2);++ // The write reports itself once. A reconcile that never published is the+ // surface's business — it already renders stale regions with their own+ // Retry — so nothing here holds the user to a second decision and nothing+ // re-runs the settlement.+ await waitFor(() => expect(reconcile).toHaveBeenCalledOnce());+ expect(commits).toHaveLength(1);+ expect(commits[0].outcome).toBe(action === 'edit' ? 'updated' : 'removed');+ expect(commits[0].impact).toEqual({ hops, gaps });+ expect(screen.queryByRole('dialog')).toBeNull();+ expect(reconcile).toHaveBeenCalledOnce();},);- it('releases tracked work when degraded impact is explicitly dismissed', async () => {- const reconcile = vi.fn().mockResolvedValueOnce('degraded');+ it('releases tracked work as soon as a superseded settlement returns', async () => {+ const landing = deferred<LandingOutcome>();const hops = [{ backend: 'claude' as const, menu_model: 'claude-opus-4-6', position: 1, source_id: source.id, model_id: 'model-a' }];vi.spyOn(modelsApi, 'patchSource').mockResolvedValueOnce({source: { ...source, display_name: 'Dismissible impact' },@@ -790,7 +755,7 @@ describe('SourceDetailPanel', () => {let trackedSettled = false;const trackMutation: TrackSourceMutation = (work) => {const operation = work(source, settlement({- source: async () => mutationLanding(await reconcile()),+ source: async () => mutationLanding(await landing.promise),}));tracked = operation;void operation.then(@@ -800,58 +765,45 @@ describe('SourceDetailPanel', () => {return operation;};render(- <ToastProvider>- <I18nextProvider i18n={i18n}>- <ReportOwnedPanel source={source} trackMutation={trackMutation} onReauth={noReauth} />- </I18nextProvider>- </ToastProvider>,+ <I18nextProvider i18n={i18n}>+ <CommittedPanel source={source} trackMutation={trackMutation} onReauth={noReauth} />+ </I18nextProvider>,);await submitManagementWrite('edit', false);- const impact = await screen.findByRole('dialog', { name: /source was updated|供应商已更新/i });- const closeBeforeLanding = within(impact).getAllByRole('button', { name: /^Done$|^完成$/i })- .find((button) => button.classList.contains('model-hub-guard-close'));- expect(closeBeforeLanding).toBeTruthy();- expect((closeBeforeLanding as HTMLButtonElement).disabled).toBe(true);- const done = within(impact).getAllByRole('button', { name: /^Done$|^完成$/i })- .find((button) => button.classList.contains('model-hub-guard-action'));- await userEvent.click(done!);-- const dismissButtons = await within(impact).findAllByRole('button', { name: /Dismiss unverified result|放弃未验证结果/i });- expect(dismissButtons.some((button) => button.classList.contains('model-hub-guard-action'))).toBe(true);- const dismissClose = dismissButtons.find((button) => button.classList.contains('model-hub-guard-close'));- expect(dismissClose).toBeTruthy();- expect((dismissClose as HTMLButtonElement).disabled).toBe(false);+ // Tracked work spans the settlement read, not a dialog the user must close:+ // it stays held while the read is in flight and is released when that read+ // returns, including when a newer read superseded it.+ await waitFor(() => expect(commits).toHaveLength(1));expect(trackedSettled).toBe(false);- await userEvent.click(dismissClose!);- await waitFor(() => expect(screen.queryByRole('dialog', { name: /source was updated|供应商已更新/i })).toBeNull());+ landing.resolve('superseded');expect(tracked).toBeDefined();- await tracked;+ await act(async () => { await tracked; });expect(trackedSettled).toBe(true);+ expect(screen.queryByRole('dialog')).toBeNull();});- it('keeps a deletion report readable after settlement unmounts its Source panel', async () => {+ it('finishes a deletion settlement that its own Source panel no longer outlives', async () => {vi.spyOn(modelsApi, 'deleteSource').mockResolvedValueOnce({removed_hops: heldHops,interrupted: heldGaps,});- const landing = deferred<SourceMutationLanding['verdict']>();+ const landing = deferred<LandingOutcome>();renderEchoPanel(() => landing.promise);await submitManagementWrite('delete', false);- const impact = await screen.findByRole('dialog', { name: /source was removed|供应商已移除/i });- const done = within(impact).getAllByRole('button', { name: /^Done$|^完成$/i })- .find((button) => button.classList.contains('model-hub-guard-action'));- expect(done).toBeTruthy();- await userEvent.click(done!);+ // The removal takes the panel that committed it off screen. The settlement+ // belongs to the surface, so it keeps running against an unmounted panel and+ // the evidence it was scoped to survives that unmount.expect(await screen.findByTestId('source-gone')).toBeTruthy();- expect(screen.getByRole('dialog', { name: /source was removed|供应商已移除/i })).toBeTruthy();- expect(impact.textContent).toContain(heldHops[0].menu_model);- expect(impact.textContent).toContain(heldGaps[0].agents[0]);+ expect(screen.queryByRole('dialog')).toBeNull();+ expect(commits).toHaveLength(1);+ expect(commits[0].impact).toEqual({ hops: heldHops, gaps: heldGaps });landing.resolve('landed');- await waitFor(() => expect(screen.queryByRole('dialog', { name: /source was removed|供应商已移除/i })).toBeNull());+ await act(async () => { await landing.promise; });+ expect(screen.getByTestId('source-gone')).toBeTruthy();});it.each((['edit', 'delete'] as const).flatMap((action) => [@@ -882,7 +834,7 @@ describe('SourceDetailPanel', () => {);it('omits native refetch because that channel has no stored discovery credential', () => {- render(<I18nextProvider i18n={i18n}><ReportOwnedPanel source={{ ...source, kind: 'subscription', supply_channel: 'native_cli' }} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><CommittedPanel source={{ ...source, kind: 'subscription', supply_channel: 'native_cli' }} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider>);expect(screen.queryByRole('button', { name: /^Refetch$|^重新拉取$/i })).toBeNull();});@@ -931,7 +883,7 @@ describe('SourceDetailPanel', () => {vi.spyOn(modelsApi, 'listSources').mockResolvedValueOnce([reconciled]);const applySource = vi.fn().mockResolvedValue(undefined);const trackMutation: TrackSourceMutation = (work) => work(source, settlement({ source: applySource }));- render(<I18nextProvider i18n={i18n}><ReportOwnedPanel source={source} trackMutation={trackMutation} onReauth={noReauth} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><CommittedPanel source={source} trackMutation={trackMutation} onReauth={noReauth} /></I18nextProvider>);await userEvent.click(screen.getByRole('button', { name: /^Refetch$|^重新拉取$/i }));@@ -1060,7 +1012,7 @@ describe('SourceDetailPanel', () => {] as const))('explains saved $kind/$supply_channel status without promising a test entry in $lng', async ({ lng, kind, supply_channel, hasTest }) => {const locale = i18n.cloneInstance({ lng });render(<ToastProvider><I18nextProvider i18n={locale}>- <ReportOwnedPanel source={{ ...source, kind, supply_channel, verification_pending: 'vp_fixture' }} trackMutation={immediateTrack} onReauth={noReauth} />+ <CommittedPanel source={{ ...source, kind, supply_channel, verification_pending: 'vp_fixture' }} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider></ToastProvider>);expect(screen.getByText(locale.t('settings.models.sourceDetail.status.saved'))).toBeTruthy();expect(Boolean(screen.queryByRole('button', { name: locale.t('settings.models.sourceTest.open') }))).toBe(hasTest);@@ -1148,7 +1100,7 @@ describe('SourceDetailPanel', () => {const list = vi.spyOn(modelsApi, 'listSources').mockResolvedValueOnce([{ ...source, models: [] }]);const onMutation = vi.fn().mockResolvedValue(undefined);const trackMutation: TrackSourceMutation = (work) => work(source, settlement({ source: onMutation }));- render(<I18nextProvider i18n={i18n}><ReportOwnedPanel source={source} trackMutation={trackMutation} onReauth={noReauth} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><CommittedPanel source={source} trackMutation={trackMutation} onReauth={noReauth} /></I18nextProvider>);await userEvent.click(screen.getByRole('button', { name: /Remove model-a|移除 model-a/i }));await userEvent.click(screen.getByRole('menuitem', { name: /^Remove$|^移除$/i }));@@ -1194,7 +1146,7 @@ describe('SourceDetailPanel', () => {vi.spyOn(modelsApi, 'listSources').mockResolvedValueOnce([]);const onGone = vi.fn().mockResolvedValue(undefined);const trackMutation: TrackSourceMutation = (work) => work(source, settlement({ gone: onGone }));- render(<I18nextProvider i18n={i18n}><ReportOwnedPanel source={source} trackMutation={trackMutation} onReauth={noReauth} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><CommittedPanel source={source} trackMutation={trackMutation} onReauth={noReauth} /></I18nextProvider>);await userEvent.click(screen.getByRole('button', { name: /Remove model-a|移除 model-a/i }));await userEvent.click(screen.getByRole('menuitem', { name: /^Remove$|^移除$/i }));@@ -1234,7 +1186,7 @@ describe('SourceDetailPanel', () => {for (const shape of shapes) {const view = render(<I18nextProvider i18n={i18n}>- <ReportOwnedPanel source={shape} trackMutation={immediateTrack} onReauth={vi.fn()} />+ <CommittedPanel source={shape} trackMutation={immediateTrack} onReauth={vi.fn()} /></I18nextProvider>,);const action = repairAction(shape);@@ -1260,7 +1212,7 @@ describe('SourceDetailPanel', () => {it('opens key replacement from the revoked hub credential repair tap', async () => {render(<I18nextProvider i18n={i18n}>- <ReportOwnedPanel+ <CommittedPanelsource={{...source,state: {@@ -1284,7 +1236,7 @@ describe('SourceDetailPanel', () => {it('confirms a native re-login with the cost it pays at start before handing the source up', async () => {const native = blockedSubscription('native_cli');const onReauth = vi.fn();- render(<I18nextProvider i18n={i18n}><ReportOwnedPanel source={native} trackMutation={immediateTrack} onReauth={onReauth} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><CommittedPanel source={native} trackMutation={immediateTrack} onReauth={onReauth} /></I18nextProvider>);await userEvent.click(screen.getByRole('button', { name: /^Sign in$|^重新登录$/i }));@@ -1299,7 +1251,7 @@ describe('SourceDetailPanel', () => {});it('warns a hub re-login about the cost it can pay, not the one it cannot', async () => {- render(<I18nextProvider i18n={i18n}><ReportOwnedPanel source={blockedSubscription('hub')} trackMutation={immediateTrack} onReauth={vi.fn()} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><CommittedPanel source={blockedSubscription('hub')} trackMutation={immediateTrack} onReauth={vi.fn()} /></I18nextProvider>);await userEvent.click(screen.getByRole('button', { name: /^Sign in$|^重新登录$/i }));diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsxindex 1a65d6f9c..b6c12e925 100644--- a/ui/src/components/settings/models/SourceDetailPanel.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx@@ -40,6 +40,7 @@ import {sourceMutationReadScope,type PresentSourceMutationCommit,type SourceMutationLanding,+ type SourceMutationOutcome,type SourceMutationReadScope,type SourceMutationSettlement,type TrackSourceMutation,@@ -161,7 +162,7 @@ export const SourceDetailPanel: React.FC<{* invalidates is wider than the one row this panel owns.*/onReauth: (source: Source) => void;- /** Owns every post-commit report and read verdict outside this entity panel. */+ /** Owns how a committed mutation is announced, and the surface read behind it. */onMutationCommitted: PresentSourceMutationCommit;/** Stable focus target for callers that navigate into this detail surface. */headingRef?: React.Ref<HTMLHeadingElement>;@@ -372,14 +373,21 @@ export const SourceDetailPanel: React.FC<{}}).finally(() => setPendingAction(null));};+ /**+ * `action` is the flow this panel is in and drives its stage machine;+ * `outcome` is what the write left behind and is the only thing the surface+ * may announce. They part company on exactly one path: an edit whose Source+ * turns out to be absent is still the edit flow, but nothing was updated.+ */const commitManagementMutation = async (action: ManageCommitAction,+ outcome: SourceMutationOutcome,impact: ManageGuardPlan | null,settle: (scope: SourceMutationReadScope) => Promise<SourceMutationLanding>,) => {dispatchManageStage({ type: 'commit', action });const scope = sourceMutationReadScope(impact);- await onMutationCommitted({ action, impact, settle: () => settle(scope) });+ await onMutationCommitted({ outcome, impact, settle: () => settle(scope) });dispatchManageStage({ type: 'settled' });};const reconcileEditWrite = async (@@ -409,6 +417,7 @@ export const SourceDetailPanel: React.FC<{: null;await commitManagementMutation('edit',+ current ? 'updated' : 'gone',current ? plan : null,(scope) => applyReconciliation(before.id, reconciliation.value, settlement, scope),);@@ -439,6 +448,7 @@ export const SourceDetailPanel: React.FC<{if (reconciliation.kind === 'committed') {await commitManagementMutation('delete',+ 'removed',plan,(scope) => settlement.gone(before.id, reconciliation.value, scope),);@@ -473,6 +483,7 @@ export const SourceDetailPanel: React.FC<{const impact = committedPlan(answer.removed_hops, answer.interrupted);await commitManagementMutation('edit',+ 'updated',impact,(scope) => settlement.source(answer.source, scope),);@@ -481,6 +492,7 @@ export const SourceDetailPanel: React.FC<{if (failure?.code === 'source_not_found') {await commitManagementMutation('edit',+ 'gone',null,(scope) => settlement.gone(latest.id, undefined, scope),);@@ -521,14 +533,18 @@ export const SourceDetailPanel: React.FC<{const impact = committedPlan(answer.removed_hops, answer.interrupted);await commitManagementMutation('delete',+ 'removed',impact,(scope) => settlement.gone(latest.id, undefined, scope),);} catch (error) {const failure = apiFailure(error);if (failure?.code === 'source_not_found') {+ // Already absent is the outcome this flow asked for, so it reports as+ // a removal rather than as a surprise the user has to interpret.await commitManagementMutation('delete',+ 'removed',null,(scope) => settlement.gone(latest.id, undefined, scope),);diff --git a/ui/src/components/settings/models/SourceMutationReport.tsx b/ui/src/components/settings/models/SourceMutationReport.tsxdeleted file mode 100644index 346fc38e9..000000000--- a/ui/src/components/settings/models/SourceMutationReport.tsx+++ /dev/null@@ -1,104 +0,0 @@-import type { TranslationKey } from '@/i18n/types';-import * as React from 'react';-import * as DialogPrimitive from '@radix-ui/react-dialog';-import { Loader2, X } from 'lucide-react';-import { useTranslation } from 'react-i18next';--import { Button } from '@/components/ui/button';-import { GuardImpact } from './GuardImpact';-import { SOURCE_MUTATION_REPORT_PROJECTIONS } from './mutationSettlement';-import type { SourceMutationReportState } from './useSourceMutationReport';--export const SourceMutationReport: React.FC<{- report: SourceMutationReportState | null;- onComplete: () => void;- onDismiss: () => void;-}> = ({ report, onComplete, onDismiss }) => {- const { t } = useTranslation();- const impact = report?.commit.impact ?? null;- const action = report?.commit.action ?? 'edit';- const copyKind = action === 'edit' ? 'edit' : 'remove';- const titleKey: TranslationKey = impact- ? `settings.models.sourceDetail.${copyKind}.impact.title`- : `settings.models.sourceDetail.${copyKind}.settlement.title`;- const detailKey: TranslationKey = impact- ? `settings.models.sourceDetail.${copyKind}.impact.detail`- : 'settings.models.sourceDetail.impact.refreshFail';- const actionKey: TranslationKey = report?.landingFailed- ? 'settings.models.sourceDetail.retry'- : `settings.models.sourceDetail.${copyKind}.impact.done`;-- return (- <DialogPrimitive.Root- open={report !== null}- onOpenChange={(open) => { if (!open && report?.landingFailed && !report.busy) onDismiss(); }}- >- <DialogPrimitive.Portal>- <DialogPrimitive.Overlay className="model-hub-guard-overlay fixed inset-0 z-50" />- <DialogPrimitive.Content- data-source-mutation-report={action}- data-report-projections={Object.keys(SOURCE_MUTATION_REPORT_PROJECTIONS).join(' ')}- className="model-hub-guard-dialog fixed left-1/2 top-1/2 z-50 flex max-h-[calc(100dvh-2rem)] -translate-x-1/2 -translate-y-1/2 flex-col overflow-y-auto border border-border-strong bg-surface outline-none"- onEscapeKeyDown={(event) => { if (!report?.landingFailed || report.busy) event.preventDefault(); }}- onPointerDownOutside={(event) => event.preventDefault()}- >- <header className="model-hub-guard-head">- <div className="flex items-center justify-between gap-3">- <DialogPrimitive.Title className="model-hub-guard-title text-foreground">- {t(titleKey)}- </DialogPrimitive.Title>- <DialogPrimitive.Close asChild>- <Button- type="button"- variant="ghost"- size="icon"- className="model-hub-guard-close"- disabled={!report?.landingFailed || report.busy}- aria-label={t(report?.landingFailed ? 'settings.models.sourceDetail.dismissUnverified' : actionKey)}- title={t(report?.landingFailed ? 'settings.models.sourceDetail.dismissUnverified' : actionKey)}- >- <X aria-hidden />- </Button>- </DialogPrimitive.Close>- </div>- <DialogPrimitive.Description className="model-hub-guard-subtitle">- {t(detailKey)}- </DialogPrimitive.Description>- </header>- {impact && (- <div className="model-hub-guard-body">- <GuardImpact hops={impact.hops} gaps={impact.gaps} committed />- {report?.landingFailed && (- <p data-manage-impact-failure className="text-[11.5px] text-destructive-ink">- {t('settings.models.sourceDetail.impact.refreshFail')}- </p>- )}- </div>- )}- <footer className="model-hub-guard-foot">- {report?.landingFailed && (- <Button- type="button"- variant="outline"- className="model-hub-guard-action"- onClick={onDismiss}- disabled={report.busy}- >- {t('settings.models.sourceDetail.dismissUnverified')}- </Button>- )}- <Button- type="button"- className="model-hub-guard-action"- onClick={onComplete}- disabled={!report || report.busy}- >- {report?.busy && <Loader2 className="animate-spin" />}- {t(actionKey)}- </Button>- </footer>- </DialogPrimitive.Content>- </DialogPrimitive.Portal>- </DialogPrimitive.Root>- );-};diff --git a/ui/src/components/settings/models/SourceTestDialog.test.tsx b/ui/src/components/settings/models/SourceTestDialog.test.tsxindex 6bd31a048..3b6221dc7 100644--- a/ui/src/components/settings/models/SourceTestDialog.test.tsx+++ b/ui/src/components/settings/models/SourceTestDialog.test.tsx@@ -5,7 +5,12 @@ import { I18nextProvider } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import i18n from '@/i18n';import { modelsApi } from './modelsApi';-import type { SourceMutationLanding, SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';+import type {+ SourceMutationLanding,+ SourceMutationLandingReads,+ SourceMutationSettlement,+ TrackSourceMutation,+} from './mutationSettlement';import { readyRegion, unreadRegion } from './regionRead';import { SourceTestDialog } from './SourceTestDialog';import { CONTRACT_VERSION, type Source, type SourceProbeResult } from './types';@@ -23,19 +28,17 @@ const answer = (patch: Partial<SourceProbeResult> = {}): SourceProbeResult => ({source_id: source.id, model_id: 'gpt-5.6-luna', protocol: source.protocol,reachable: true, latency_ms: 123, error: null, ...patch,});-const landing = (sources: Source[] = [source]): SourceMutationLanding => ({- verdict: 'landed', affectedChains: [], reads: {- sources: readyRegion(sources), supply: readyRegion([]), chains: readyRegion({}),- runtime: readyRegion({- contract_version: CONTRACT_VERSION,- manifest: { name: 'cliproxyapi', resolution: 'unresolved', assets: [] },- status: { verified: false, health: 'not_started' },- }),- },+const landing = (sources: Source[] = [source]): SourceMutationLandingReads => ({+ sources: readyRegion(sources), supply: readyRegion([]), chains: readyRegion({}),+ runtime: readyRegion({+ contract_version: CONTRACT_VERSION,+ manifest: { name: 'cliproxyapi', resolution: 'unresolved', assets: [] },+ status: { verified: false, health: 'not_started' },+ }),});const settlement = {unread: vi.fn(),- gone: vi.fn().mockResolvedValue({ verdict: 'degraded', reads: null, affectedChains: [] }),+ gone: vi.fn().mockResolvedValue(null),} as unknown as SourceMutationSettlement;const track: TrackSourceMutation = (work) => work(source, settlement);const view = (current = source) => <I18nextProvider i18n={i18n}>@@ -95,7 +98,7 @@ describe('SourceTestDialog', () => {expect(settlement.unread).toHaveBeenCalledTimes(1);});- it.each([true, false])('publishes no verdict before reconciliation completes: reachable=%s', async (reachable) => {+ it.each([true, false])('publishes no result before reconciliation completes: reachable=%s', async (reachable) => {vi.spyOn(modelsApi, 'probeSource').mockResolvedValue(answer({ reachable }));let resolve!: (value: SourceMutationLanding) => void;vi.mocked(settlement.unread).mockReturnValue(new Promise((done) => { resolve = done; }));@@ -109,7 +112,7 @@ describe('SourceTestDialog', () => {expect(screen.queryByRole('alert')).toBeNull();});- it.each([true, false])('does not retry or publish a verdict after rejected reconciliation: reachable=%s', async (reachable) => {+ it.each([true, false])('does not retry or publish a result after rejected reconciliation: reachable=%s', async (reachable) => {const probe = vi.spyOn(modelsApi, 'probeSource').mockResolvedValue(answer({ reachable }));vi.mocked(settlement.unread).mockRejectedValue(new Error('Source list unavailable'));render(view());@@ -120,7 +123,7 @@ describe('SourceTestDialog', () => {expect(probe).toHaveBeenCalledTimes(1);});- it.each(['unread', 'stale', 'deleted', 'credential', 'marker', 'base_url', 'protocol', 'model'])('requires a current matching Source after reconciliation: %s', async (change) => {+ it.each(['unread', 'superseded', 'deleted', 'credential', 'marker', 'base_url', 'protocol', 'model'])('requires a current matching Source after reconciliation: %s', async (change) => {vi.spyOn(modelsApi, 'probeSource').mockResolvedValue(answer());const current = { ...source };if (change === 'credential') current.credential_ref = 'cred_replacement';@@ -128,9 +131,12 @@ describe('SourceTestDialog', () => {if (change === 'base_url') current.base_url = 'https://other.example/v1';if (change === 'protocol') current.protocol = 'anthropic';if (change === 'model') current.models = [];- const result = landing(change === 'deleted' ? [] : [current]);- if (change === 'unread') result.reads!.sources = unreadRegion();- if (change === 'stale') result.verdict = 'degraded';+ const reads = landing(change === 'deleted' ? [] : [current]);+ if (change === 'unread') reads.sources = unreadRegion();+ // `superseded`: a newer read took the surface over, so this mutation's own+ // read never published one — indistinguishable here from a read it could+ // not complete, and equally unable to confirm the probe.+ const result: SourceMutationLanding = change === 'superseded' ? null : reads;vi.mocked(settlement.unread).mockResolvedValue(result);render(view());await userEvent.click(screen.getByRole('button', { name: 'Run test' }));diff --git a/ui/src/components/settings/models/SourceTestDialog.tsx b/ui/src/components/settings/models/SourceTestDialog.tsxindex d7c7f54f8..1140c2482 100644--- a/ui/src/components/settings/models/SourceTestDialog.tsx+++ b/ui/src/components/settings/models/SourceTestDialog.tsx@@ -60,14 +60,15 @@ export const SourceTestDialog: React.FC<{return;}// Reconciliation, not an old dialog snapshot, owns the current identity.- // Its failure must neither publish a verdict nor retry the same read.+ // A read this dialog cannot complete leaves the probe unconfirmed rather+ // than retrying the same read here.const landing = await settlement.unread();- const current = landing.verdict === 'landed' ? foldRegionRead<Source[], Source | undefined>(landing.reads.sources, {+ const current = landing === null ? undefined : foldRegionRead<Source[], Source | undefined>(landing.sources, {loading: () => undefined,ready: (sources) => sources.find((item) => item.id === latest.id),unread: () => undefined,degraded: () => undefined,- }) : undefined;+ });const matches = current && current.credential_ref === latest.credential_ref&& current.base_url === latest.base_url && current.protocol === latest.protocol&& (!current.verification_pending || current.verification_pending === latest.verification_pending)diff --git a/ui/src/components/settings/models/SourcesCard.tsx b/ui/src/components/settings/models/SourcesCard.tsxindex 5a123af8e..9054933c2 100644--- a/ui/src/components/settings/models/SourcesCard.tsx+++ b/ui/src/components/settings/models/SourcesCard.tsx@@ -60,6 +60,10 @@ export const SourcesCard: React.FC<{<div className="flex h-14 shrink-0 items-center gap-2 border-t border-border px-3.5"><Buttonref={subscriptionTriggerRef}+ // Survives every list state this card can reach — loading, unread,+ // empty, or a row removed out from under the keyboard — which is what+ // makes it the card's focus anchor of last resort.+ data-model-hub-focus-anchor=""variant="default"size="xs"aria-haspopup="menu"diff --git a/ui/src/components/settings/models/asyncLifetime.test.ts b/ui/src/components/settings/models/asyncLifetime.test.tsindex 3cb279f09..40e835e67 100644--- a/ui/src/components/settings/models/asyncLifetime.test.ts+++ b/ui/src/components/settings/models/asyncLifetime.test.ts@@ -67,7 +67,7 @@ import {classifyOAuthFailure,createFlowAuthority,createLatestAsyncAuthority,- createLatestAsyncAuthorityByKey,+ createLatestAsyncAuthorityByKeySet,createLatestEntityAuthorityByKey,createPendingWrites,failureLanded,@@ -149,54 +149,86 @@ describe('latest async authority', () => {expect(landed).toEqual(['newest']);});- it('orders reads per key without making independent backends supersede each other', async () => {+ it('orders reads per key without making independent keys supersede each other', async () => {const olderClaude = deferred<string>();const newerClaude = deferred<string>();const codex = deferred<string>();const landed: string[] = [];- const authority = createLatestAsyncAuthorityByKey<string, string>((key, value) => landed.push(`${key}:${value}`));+ const authority = createLatestAsyncAuthorityByKeySet<string, string>((value, owned) => landed.push(`${[...owned].join('+')}:${value}`));- const olderRun = authority.run('claude', () => olderClaude.promise);- const codexRun = authority.run('codex', () => codex.promise);- const newerRun = authority.run('claude', () => newerClaude.promise);+ const olderRun = authority.run(['claude'], () => olderClaude.promise);+ const codexRun = authority.run(['codex'], () => codex.promise);+ const newerRun = authority.run(['claude'], () => newerClaude.promise);newerClaude.resolve('new');codex.resolve('independent');await Promise.all([newerRun, codexRun]);olderClaude.resolve('old');- expect(await olderRun).toBe('stale');+ expect([...await olderRun]).toEqual([]);expect(landed).toEqual(['claude:new', 'codex:independent']);});+ // The reason ownership is per key and not per read. A read that covers one key+ // must not take a wider read's other keys away from it: those keys would keep+ // whatever they had, with the wider read reporting that someone else now owns+ // them and that someone never touching them.+ it('leaves a wider read owning every key the narrower one did not claim', async () => {+ const wider = deferred<string>();+ const landed: string[] = [];+ const authority = createLatestAsyncAuthorityByKeySet<string, string>((value, owned) => landed.push(`${[...owned].sort().join('+')}:${value}`));++ const widerRun = authority.run(['claude:opus', 'claude:sonnet'], () => wider.promise);+ await authority.run(['claude:sonnet'], () => Promise.resolve('exact sonnet'));+ wider.resolve('both models');++ expect([...await widerRun]).toEqual(['claude:opus']);+ expect(landed).toEqual(['claude:sonnet:exact sonnet', 'claude:opus:both models']);+ });+it('invalidates pending generations whose keys lose active ownership', async () => {const claude = deferred<string>();const codex = deferred<string>();const landed: string[] = [];- const authority = createLatestAsyncAuthorityByKey<string, string>((key, value) => landed.push(`${key}:${value}`));+ const authority = createLatestAsyncAuthorityByKeySet<string, string>((value, owned) => landed.push(`${[...owned].join('+')}:${value}`));- const claudeRun = authority.run('claude', () => claude.promise);- const codexRun = authority.run('codex', () => codex.promise);- authority.invalidateExcept(new Set(['codex']));+ const claudeRun = authority.run(['claude'], () => claude.promise);+ const codexRun = authority.run(['codex'], () => codex.promise);+ authority.invalidateExcept((key) => key === 'codex');claude.resolve('no longer owned');codex.resolve('still active');- expect(await claudeRun).toBe('stale');- expect(await codexRun).toBe('landed');+ expect([...await claudeRun]).toEqual([]);+ expect([...await codexRun]).toEqual(['codex']);expect(landed).toEqual(['codex:still active']);});it('invalidates one pending generation before a write echo takes ownership', async () => {const pending = deferred<string>();const landed: string[] = [];- const authority = createLatestAsyncAuthorityByKey<string, string>((key, value) => landed.push(`${key}:${value}`));+ const authority = createLatestAsyncAuthorityByKeySet<string, string>((value, owned) => landed.push(`${[...owned].join('+')}:${value}`));- const read = authority.run('claude', () => pending.promise);- authority.invalidate('claude');+ const read = authority.run(['claude'], () => pending.promise);+ authority.invalidate(['claude']);pending.resolve('pre-commit chain');- expect(await read).toBe('stale');+ expect([...await read]).toEqual([]);expect(landed).toEqual([]);});++ it('swallows a failure nobody is waiting on and rethrows one that still owns a key', async () => {+ const authority = createLatestAsyncAuthorityByKeySet<string, string>(() => undefined);+ let failSuperseded = () => {};+ const superseded = new Promise<string>((_resolve, reject) => {+ failSuperseded = () => reject(new Error('read failed'));+ });++ const supersededRun = authority.run(['claude'], () => superseded);+ await authority.run(['claude'], () => Promise.resolve('newer'));+ failSuperseded();++ expect([...await supersededRun]).toEqual([]);+ await expect(authority.run(['codex'], () => Promise.reject(new Error('read failed')))).rejects.toThrow('read failed');+ });});describe('latest Source entity authority', () => {diff --git a/ui/src/components/settings/models/asyncLifetime.ts b/ui/src/components/settings/models/asyncLifetime.tsindex 35a1e6f0e..cab16132d 100644--- a/ui/src/components/settings/models/asyncLifetime.ts+++ b/ui/src/components/settings/models/asyncLifetime.ts@@ -28,35 +28,55 @@ export const createLatestAsyncAuthority = <T>(land: (value: T) => void) => {};};-/** Gives each independent key its own latest-result generation. */-export const createLatestAsyncAuthorityByKey = <K, T>(- land: (key: K, value: T) => void,+/**+ * Orders reads at the granularity of the keys they install. A read claims the+ * keys it will write before it starts, and when it returns it still owns every+ * claimed key that no newer read has claimed since.+ *+ * Ownership is per key rather than per read so that two reads covering+ * different keys never supersede each other, and a read that loses part of its+ * claim still installs — and still answers for — the rest.+ */+export const createLatestAsyncAuthorityByKeySet = <K, T>(+ land: (value: T, owned: ReadonlySet<K>) => void,) => {const latestRequest = new Map<K, number>();- const advance = (key: K) => {- latestRequest.set(key, (latestRequest.get(key) ?? 0) + 1);+ const advance = (key: K): number => {+ const request = (latestRequest.get(key) ?? 0) + 1;+ latestRequest.set(key, request);+ return request;+ };+ const stillOwned = (claimed: ReadonlyMap<K, number>): Set<K> => {+ const owned = new Set<K>();+ for (const [key, request] of claimed) {+ if (latestRequest.get(key) === request) owned.add(key);+ }+ return owned;};return {- /** Advances one key before an authoritative write echo is installed. */- invalidate: (key: K): void => advance(key),- /** Advances retired keys so their pending requests cannot regain ownership. */- invalidateExcept: (activeKeys: ReadonlySet<K>): void => {- for (const key of latestRequest.keys()) {- if (!activeKeys.has(key)) advance(key);+ /** Advances keys before an authoritative write echo is installed. */+ invalidate: (keys: readonly K[]): void => {+ for (const key of keys) advance(key);+ },+ /** Advances retired keys so their pending reads cannot regain ownership. */+ invalidateExcept: (active: (key: K) => boolean): void => {+ for (const key of [...latestRequest.keys()]) {+ if (!active(key)) advance(key);}},- run: async (key: K, read: () => Promise<T>): Promise<'landed' | 'stale'> => {- const request = (latestRequest.get(key) ?? 0) + 1;- latestRequest.set(key, request);+ run: async (keys: readonly K[], read: () => Promise<T>): Promise<ReadonlySet<K>> => {+ const claimed = new Map<K, number>();+ for (const key of keys) claimed.set(key, advance(key));try {const value = await read();- if (latestRequest.get(key) !== request) return 'stale';- land(key, value);- return 'landed';+ const owned = stillOwned(claimed);+ if (owned.size > 0) land(value, owned);+ return owned;} catch (error) {- if (latestRequest.get(key) !== request) return 'stale';- throw error;+ const owned = stillOwned(claimed);+ if (owned.size > 0) throw error;+ return owned;}},};diff --git a/ui/src/components/settings/models/eventFeed.test.ts b/ui/src/components/settings/models/eventFeed.test.tsindex 98b213de2..a4a375c09 100644--- a/ui/src/components/settings/models/eventFeed.test.ts+++ b/ui/src/components/settings/models/eventFeed.test.ts@@ -217,10 +217,12 @@ describe('the page reads the feed through this owner', () => {it('lets the ancillary feed read fail without losing the rows', () => {// A slow or broken /events must not enter the operational first-paint barrier.- const landing = mutationSettlement.slice(- mutationSettlement.indexOf('export const readSurfaceLanding'),- mutationSettlement.indexOf('\n\nexport type SourceMutationLanding ='),- );+ const landingStart = mutationSettlement.indexOf('export const readSurfaceLanding');+ // Ends on the reader's own closing brace rather than on whatever declaration+ // follows it, so a neighbour gaining a doc comment cannot silently widen the+ // slice into code this assertion was never about.+ const landing = mutationSettlement.slice(landingStart, mutationSettlement.indexOf('\n};', landingStart));+ expect(landingStart).toBeGreaterThanOrEqual(0);expect(landing).not.toMatch(/listEvents|events/);expect(page).toMatch(/createLatestAsyncAuthority<RegionRead<ResolutionEvent\[\]>>/);expect(page).toMatch(/createLatestAsyncAuthority<AuthorizedSurfaceLanding>/);diff --git a/ui/src/components/settings/models/modelHubFocus.ts b/ui/src/components/settings/models/modelHubFocus.tsindex 90a798366..e818848bf 100644--- a/ui/src/components/settings/models/modelHubFocus.ts+++ b/ui/src/components/settings/models/modelHubFocus.ts@@ -59,3 +59,35 @@ export const focusModelHubProjection = ({target?.focus();return target;};++/**+ * Where keyboard focus goes when a dialog closes over the element that opened+ * it. A removed Source takes its own row with it, so the recorded return target+ * is disconnected by the time the dialog hands focus back; without a fallback+ * the browser drops focus on `document.body` and the next Tab restarts at the+ * top of the document instead of near the list the user was working in.+ *+ * `root` is the neighbourhood the caller nominates — the smallest surface still+ * standing around where that element was — so its first focusable is the closest+ * thing left to it.+ */+export const focusDialogReturn = ({+ root,+ returnTarget,+}: {+ root: HTMLElement | null;+ returnTarget: HTMLElement | null;+}): HTMLElement | null => {+ const candidates = [+ returnTarget,+ // Declared rather than 「first focusable」: the read that follows a removal+ // re-renders the list, so the first focusable at close time may itself be+ // the row that is about to go, and focus would fall to the body one tick+ // later. An anchor is chosen for outliving exactly that.+ root?.querySelector<HTMLElement>('[data-model-hub-focus-anchor]') ?? null,+ root?.querySelector<HTMLElement>(focusableSelector) ?? null,+ ];+ const target = candidates.find(focusValid) ?? null;+ target?.focus();+ return target;+};diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.cssindex bd9cb3046..676f94b99 100644--- a/ui/src/components/settings/models/modelHubSurface.css+++ b/ui/src/components/settings/models/modelHubSurface.css@@ -588,6 +588,9 @@font-weight: 500;}.model-hub-model-collapse svg { width: 13px; height: 13px; }+.model-hub-model-collapse--repair {+ --model-hub-model-collapse-ink: var(--model-hub-danger-ink);+}.model-hub-footer-action {--model-hub-footer-action-font-size: 11.5px;diff --git a/ui/src/components/settings/models/modelRows.ts b/ui/src/components/settings/models/modelRows.tsindex bbf3e1549..a18ee6784 100644--- a/ui/src/components/settings/models/modelRows.ts+++ b/ui/src/components/settings/models/modelRows.ts@@ -15,6 +15,10 @@ export type ModelChainRequest = {export const modelChainKey = (backend: AgentBackend, modelId: string): string =>`${backend}\u0000${modelId}`;+/** The backend half of a chain key, for reads that own chains rather than backends. */+export const chainKeyBackend = (key: string): AgentBackend =>+ key.slice(0, key.indexOf('\u0000')) as AgentBackend;+/** Manual inventory is a credential-backed capability; subscriptions are read-only. */export function manualModelSources(sources: Source[]): Source[] {return sources.filter((source) => source.kind === 'api_key');diff --git a/ui/src/components/settings/models/mutationSettlement.test.ts b/ui/src/components/settings/models/mutationSettlement.test.tsindex 2b45c4f07..483de150a 100644--- a/ui/src/components/settings/models/mutationSettlement.test.ts+++ b/ui/src/components/settings/models/mutationSettlement.test.ts@@ -4,27 +4,29 @@ import { fileURLToPath } from 'node:url';import { describe, expect, it, vi } from 'vitest';-import { modelChainKey, type ModelChainIndex } from './modelRows';+import en from '../../../i18n/en.json';+import zh from '../../../i18n/zh.json';+import { FIRST_PAINT_REGION_WHITELIST } from './firstPaintRegions';+import { modelChainKey, type ModelChainIndex, type ModelChainRequest } from './modelRows';import type { SourceCreated } from './modelsApi';import {createContinuationSettlement,createSourceCreatedDelivery,readSurfaceLanding,- SOURCE_MUTATION_REPORT_PROJECTIONS,- sourceMutationLanding,+ sourceMutationReadFailed,sourceMutationReadScope,+ SOURCE_MUTATION_OUTCOMES,+ SOURCE_MUTATION_TOAST,type SourceMutationLandingReads,} from './mutationSettlement';-import { failRegionRead, readyRegion, unreadRegion } from './regionRead';+import { readyRegion, unreadRegion } from './regionRead';import type { AgentChain, AgentSupply, RuntimeDependency, Source } from './types';-// Fails exactly one projection, keyed generically so each key carries its own-// value type into `failRegionRead`. Indexing the reads with a union key hands-// the compiler four candidate types for one inference site and it picks one.-const degradeProjection = <K extends keyof SourceMutationLandingReads>(- reads: SourceMutationLandingReads,- projection: K,-): SourceMutationLandingReads => ({ ...reads, [projection]: failRegionRead(reads[projection]) });+const translated = (bundle: unknown, key: string): unknown =>+ key.split('.').reduce<unknown>((node, part) => {+ if (!node || typeof node !== 'object') return undefined;+ return (node as Record<string, unknown>)[part];+ }, bundle);describe('mutation settlement fences', () => {it('atomically rejects every effect belonging to an invalidated attempt', () => {@@ -63,19 +65,21 @@ describe('mutation settlement fences', () => {expect(detail).toContain('settlement.gone');});- it('lands only after every projection referenced by the report was read', async () => {+ it('reads the whole first-paint surface plus exactly the chains the impact named', async () => {const impact = {hops: [{ backend: 'claude' as const, menu_model: 'claude-opus-4-6', position: 1, source_id: 'src', model_id: 'model-a' }],gaps: [{ backend: 'codex' as const, model_id: 'gpt-5.6-sol', agents: ['release'] }],};const affectedChains = sourceMutationReadScope(impact).affectedChains;const calls: string[] = [];+ let requested: readonly ModelChainRequest[] = [];const reads = await readSurfaceLanding({sources: async () => { calls.push('sources'); return [] as Source[]; },supply: async () => { calls.push('supply'); return [] as AgentSupply[]; },runtime: async () => { calls.push('runtime'); return {} as RuntimeDependency; },chains: async (requests) => {calls.push('chains');+ requested = requests;return Object.fromEntries(requests.map(({ backend, modelId }) => [modelChainKey(backend, modelId),readyRegion({} as AgentChain),@@ -83,31 +87,17 @@ describe('mutation settlement fences', () => {},}, affectedChains);- expect(new Set(calls)).toEqual(new Set(Object.keys(SOURCE_MUTATION_REPORT_PROJECTIONS)));- expect(new Set(Object.keys(reads))).toEqual(new Set(Object.keys(SOURCE_MUTATION_REPORT_PROJECTIONS)));- expect(sourceMutationLanding(reads, affectedChains, true).verdict).toBe('landed');-- for (const projection of Object.keys(- SOURCE_MUTATION_REPORT_PROJECTIONS,- ) as (keyof typeof SOURCE_MUTATION_REPORT_PROJECTIONS)[]) {- expect(- sourceMutationLanding(degradeProjection(reads, projection), affectedChains, true).verdict,- projection,- ).toBe('degraded');- }-- for (const request of affectedChains) {- const key = modelChainKey(request.backend, request.modelId);- const missing = readyRegion<ModelChainIndex>({- ...Object.fromEntries(affectedChains.map(({ backend, modelId }) => [- modelChainKey(backend, modelId),- readyRegion({} as AgentChain),- ] as const)),- [key]: unreadRegion<AgentChain>(),- });- expect(sourceMutationLanding({ ...reads, chains: missing }, affectedChains, true).verdict, key)- .toBe('degraded');- }+ // A region that draws the surface must be read by the mutation that changes+ // it, so the whitelist — not a second list kept here — names the coverage.+ const expected = new Set([...Object.keys(FIRST_PAINT_REGION_WHITELIST), 'chains']);+ expect(new Set(calls)).toEqual(expected);+ expect(new Set(Object.keys(reads))).toEqual(expected);++ // The impact evidence is the whole chain scope: no route the write did not+ // touch is refetched, and every one it did touch is.+ expect(requested).toEqual(affectedChains);+ expect(affectedChains).toHaveLength(2);+ expect(reads.chains.kind).toBe('ready');});it('routes every management settlement through one post-await announcement', () => {@@ -122,10 +112,84 @@ describe('mutation settlement fences', () => {);expect(refresh).toMatch(/Promise<SourceMutationLanding>/);- expect(refresh).toContain('sourceMutationLanding(');+ // The page-wide refresh line answers for every region this read installs,+ // route chains included. What it must never answer for is supersession —+ // `refreshAffectedChains` reports no keys there rather than unread ones, so+ // a newer read winning cannot arrive here as a page that could not refresh.+ expect(refresh).toContain('sourceMutationReadFailed(landing)');+ expect(refresh).toContain("t('settings.models.toast.refreshFailed')");expect(settlement).toMatch(/Promise<SourceMutationLanding>/);expect(settlement).toContain('return refresh(affectedChains)');expect((detail.match(/dispatchManageStage\(\{ type: 'settled' \}\)/g) ?? []).length).toBe(1);expect(committed).toMatch(/await onMutationCommitted[\s\S]*dispatchManageStage\(\{ type: 'settled' \}\)/);});});++/**+ * The commit envelope is the only thing the page sees of a write, so the word it+ * carries is the word the user reads. The finding this block exists for: an edit+ * whose Source turned out to be absent still announced 「供应商已更新」 over a panel+ * saying the provider is no longer there.+ */+describe('committed mutation outcomes', () => {+ it('answers for every outcome a commit can carry', () => {+ expect(Object.keys(SOURCE_MUTATION_TOAST).sort()).toEqual([...SOURCE_MUTATION_OUTCOMES].sort());+ });++ it.each(Object.entries(SOURCE_MUTATION_TOAST))('has copy in both locales for %s', (_outcome, toast) => {+ for (const bundle of [en, zh]) expect(typeof translated(bundle, toast.key)).toBe('string');+ });++ it('never celebrates an outcome that is not the one the user asked for', () => {+ // Tone tracks the outcome, not the branch that renders it: `gone` reaches the+ // page from the EDIT flow, and green over 「已经不在了」 is the contradiction.+ expect(SOURCE_MUTATION_TOAST.updated.tone).toBe('success');+ expect(SOURCE_MUTATION_TOAST.removed.tone).toBe('success');+ expect(SOURCE_MUTATION_TOAST.gone.tone).toBe('warning');+ });++ it('says the same thing as the surface under it when a Source is gone', () => {+ // One fact, one sentence: the toast reuses the detail surface's own copy+ // rather than adding a second wording for the same state.+ expect(SOURCE_MUTATION_TOAST.gone.key).toBe('settings.models.sourceDetail.gone');+ });+});++/**+ * The page's refresh line answers one question — is anything on screen older+ * than the server — and the bug that opened this lane was it answering a+ * different one, saying a save that had landed could not be confirmed.+ */+describe('post-mutation read failure', () => {+ const landing = (chains: ModelChainIndex): SourceMutationLandingReads => ({+ sources: readyRegion([] as Source[]),+ supply: readyRegion([] as AgentSupply[]),+ runtime: readyRegion({} as RuntimeDependency),+ chains: readyRegion(chains),+ });+ const chainKey = modelChainKey('claude', 'claude-opus-4-6');++ it('stays silent when every projection came back', () => {+ expect(sourceMutationReadFailed(landing({ [chainKey]: readyRegion({} as AgentChain) }))).toBe(false);+ });++ it('counts a route request that failed inside a readable index', () => {+ // The index itself resolves — `refreshAffectedChains` catches per request —+ // so a check that stopped at the index would call an unreadable route a+ // clean refresh.+ expect(sourceMutationReadFailed(landing({ [chainKey]: unreadRegion<AgentChain>() }))).toBe(true);+ });++ it('never counts a read a newer read took over', () => {+ // Supersession reports no keys rather than unread ones. This is the case the+ // user hit: the save had landed, and the page said it could not refresh.+ expect(sourceMutationReadFailed(landing({}))).toBe(false);+ });++ it('counts a first-paint region that could not be read', () => {+ expect(sourceMutationReadFailed({+ ...landing({}),+ supply: unreadRegion<AgentSupply[]>(),+ })).toBe(true);+ });+});diff --git a/ui/src/components/settings/models/mutationSettlement.ts b/ui/src/components/settings/models/mutationSettlement.tsindex 9a5312976..5e66fbbd8 100644--- a/ui/src/components/settings/models/mutationSettlement.ts+++ b/ui/src/components/settings/models/mutationSettlement.ts@@ -1,3 +1,4 @@+import type { TranslationKey } from '@/i18n/types';import type { SourceCreated } from './modelsApi';import { readFirstPaintRegions } from './firstPaintRegions';import { modelChainKey, type ModelChainIndex, type ModelChainRequest } from './modelRows';@@ -58,14 +59,6 @@ type SourceMutationProjectionValues = {chains: ModelChainIndex;};-/** Every projection named by the committed Source report must be read before it lands. */-export const SOURCE_MUTATION_REPORT_PROJECTIONS = {- sources: 'the Source inventory after the mutation',- supply: 'the backend supply projection after the mutation',- runtime: 'the runtime projection that qualifies live chain claims',- chains: 'every route chain named by the impact evidence',-} as const satisfies Record<keyof SourceMutationProjectionValues, string>;-export type SourceMutationLandingReads = {[K in keyof SourceMutationProjectionValues]: RegionRead<SourceMutationProjectionValues[K]>;};@@ -92,17 +85,42 @@ export const readSurfaceLanding = async (return { ...surface, chains };};-export type SourceMutationLanding =- | {- verdict: 'landed';- reads: SourceMutationLandingReads;- affectedChains: ModelChainRequest[];- }- | {- verdict: 'degraded';- reads: SourceMutationLandingReads | null;- affectedChains: ModelChainRequest[];- };+/**+ * What a mutation's own read of the model surface published, or `null` when a+ * newer read took the surface over before this one could land.+ *+ * There is deliberately no pass/fail verdict over the whole surface. That+ * verdict existed for the post-commit report, which asked the user to accept a+ * write that had already landed; with the report gone, each region answers for+ * itself through its own `RegionRead` — stale projection, Retry, and whatever+ * the surface that owns it says about a read it could not complete.+ */+export type SourceMutationLanding = SourceMutationLandingReads | null;++/**+ * Whether this read left any projection it installs showing something older+ * than the server — the question the page's refresh line answers.+ *+ * The chain index has to be opened rather than trusted: a route request that+ * failed lands as an unread entry INSIDE a perfectly readable index, so a check+ * that stopped at the index would call a route nobody could re-read a clean+ * refresh.+ *+ * What is deliberately not a failure is a key that is simply absent. A read the+ * newer read took over reports no keys at all rather than unread ones, so «a+ * newer read won» can never arrive here as «the page could not refresh» — the+ * confusion that made a successful save look unconfirmed.+ */+export const sourceMutationReadFailed = (landing: SourceMutationLandingReads): boolean => {+ const chains = foldRegionRead<ModelChainIndex, ModelChainIndex>(landing.chains, {+ loading: () => ({}),+ ready: (index) => index,+ unread: () => ({}),+ degraded: (staleIndex) => staleIndex,+ });+ return Object.values(landing).some((read) => regionFailed(read))+ || Object.values(chains).some((read) => regionFailed(read));+};export type SourceMutationImpact = { hops: RouteHopRef[]; gaps: SupplyGap[] };@@ -111,47 +129,45 @@ export type SourceMutationReadScope = { affectedChains: ModelChainRequest[] };export const SOURCE_MUTATION_ACTIONS = ['edit', 'delete'] as const;export type SourceMutationAction = (typeof SOURCE_MUTATION_ACTIONS)[number];+/**+ * What the write actually left behind, which is not always what was asked for:+ * an edit whose Source turns out to be absent lands `gone`, not `updated`.+ *+ * This is deliberately NOT the action. The action is the flow the user is in and+ * belongs to the panel's stage machine; the outcome is what the surface may tell+ * them, and announcing 「已更新」 over a panel that says the provider is no longer+ * there is exactly the mismatch a separate word prevents.+ */+export const SOURCE_MUTATION_OUTCOMES = ['updated', 'removed', 'gone'] as const;+export type SourceMutationOutcome = (typeof SOURCE_MUTATION_OUTCOMES)[number];++/**+ * The line AND the tone for each outcome, decided together — same rule as+ * `REPAIR_TOAST`: tone is a property of the outcome, not of the branch that+ * happens to render it, and a Record over the full union makes the next outcome+ * added answer for its own tone instead of inheriting green.+ *+ * `gone` reuses the copy the detail surface already shows for the same fact, so+ * the toast and the panel under it say one thing rather than two.+ */+export const SOURCE_MUTATION_TOAST: Record<+ SourceMutationOutcome,+ { key: TranslationKey; tone: 'success' | 'warning' }+> = {+ updated: { key: 'settings.models.sourceDetail.edit.settlement.title', tone: 'success' },+ removed: { key: 'settings.models.sourceDetail.remove.settlement.title', tone: 'success' },+ gone: { key: 'settings.models.sourceDetail.gone', tone: 'warning' },+};+export type SourceMutationCommit = {- action: SourceMutationAction;+ outcome: SourceMutationOutcome;impact: SourceMutationImpact | null;settle: () => Promise<SourceMutationLanding>;};export type PresentSourceMutationCommit = (commit: SourceMutationCommit) => Promise<void>;-/** A landed verdict is proof that every report projection was current and readable. */-export const sourceMutationLanding = (- reads: SourceMutationLandingReads | null,- affectedChains: ModelChainRequest[],- applied: boolean,-): SourceMutationLanding => {- const reportProjectionFailed = reads- ? (- Object.keys(- SOURCE_MUTATION_REPORT_PROJECTIONS,- ) as (keyof SourceMutationLandingReads)[]- ).some((projection) => regionFailed(reads[projection]))- : true;-- if (!reads || !applied || reportProjectionFailed) {- return { verdict: 'degraded', reads, affectedChains };- }- const chains = foldRegionRead<ModelChainIndex, ModelChainIndex | null>(reads.chains, {- loading: () => null,- ready: (data) => data,- unread: () => null,- degraded: () => null,- });- const chainReadsLanded = chains !== null && affectedChains.every(({ backend, modelId }) => {- const read = chains[modelChainKey(backend, modelId)];- return Boolean(read && !regionFailed(read));- });- return chainReadsLanded- ? { verdict: 'landed', reads, affectedChains }- : { verdict: 'degraded', reads, affectedChains };-};--/** The report evidence is the authority for which exact route projections must land. */+/** The impact evidence is the authority for which exact route projections to read. */export const sourceMutationReadScope = (impact: SourceMutationImpact | null,): SourceMutationReadScope => {diff --git a/ui/src/components/settings/models/regionRead.test.ts b/ui/src/components/settings/models/regionRead.test.tsindex c85f6b7ff..bb301c43f 100644--- a/ui/src/components/settings/models/regionRead.test.ts+++ b/ui/src/components/settings/models/regionRead.test.ts@@ -78,10 +78,12 @@ describe('RegionRead', () => {expect(called).toEqual(keys);expect(Object.keys(landing)).toEqual(keys);const settlement = readFileSync(join(__dirname, 'mutationSettlement.ts'), 'utf8');- const barrier = settlement.slice(- settlement.indexOf('export const readSurfaceLanding'),- settlement.indexOf('\n\nexport type SourceMutationLanding ='),- );+ const barrierStart = settlement.indexOf('export const readSurfaceLanding');+ // Ends on the reader's own closing brace rather than on whatever declaration+ // follows it, so a neighbour gaining a doc comment cannot silently widen the+ // slice into code this assertion was never about.+ const barrier = settlement.slice(barrierStart, settlement.indexOf('\n};', barrierStart));+ expect(barrierStart).toBeGreaterThanOrEqual(0);expect(barrier).not.toMatch(/listEvents|events/);});@@ -97,10 +99,13 @@ describe('RegionRead', () => {expect(violations).toEqual([]);});- it('routes overview collections and exact chain reads through the per-backend latest authority', () => {+ it('routes overview collections and exact chain reads through the per-chain latest authority', () => {const page = readFileSync(join(__dirname, 'SettingsModelsPage.tsx'), 'utf8');const definitionStart = page.indexOf('const readChainRequests');- const definitionEnd = page.indexOf('\n\nconst settleAgentChainIndex');+ // Ends on the last reader's own closing line rather than on whatever+ // declaration follows it: anchored on a neighbour, a doc comment added there+ // silently widens this slice into code it was never about.+ const definitionEnd = page.indexOf('\n});', page.indexOf('const readExactAgentChain')) + '\n});'.length;const definitions = page.slice(definitionStart, definitionEnd);const withoutDefinition = `${page.slice(0, definitionStart)}${page.slice(definitionEnd)}`;const affectedRefresh = page.slice(@@ -108,13 +113,14 @@ describe('RegionRead', () => {page.indexOf('\n\n const refreshAllAgentChains'),);const settlement = readFileSync(join(__dirname, 'mutationSettlement.ts'), 'utf8');- const landing = settlement.slice(- settlement.indexOf('export const readSurfaceLanding'),- settlement.indexOf('\n\nexport type SourceMutationLanding ='),- );+ const landingStart = settlement.indexOf('export const readSurfaceLanding');+ const landingEnd = settlement.indexOf('\n};', landingStart);+ const landing = settlement.slice(landingStart, landingEnd);expect(definitionStart).toBeGreaterThanOrEqual(0);expect(definitionEnd).toBeGreaterThan(definitionStart);+ expect(landingStart).toBeGreaterThanOrEqual(0);+ expect(landingEnd).toBeGreaterThan(landingStart);expect(withoutDefinition).not.toMatch(/modelsApi\.getAgentChain/);expect(definitions).toMatch(/modelsApi\.getAgentChains\(agent\.backend\)/);expect(definitions).toMatch(/modelsApi\.getAgentChain\(backend, modelId\)/);@@ -122,6 +128,6 @@ describe('RegionRead', () => {expect(landing).toMatch(/readers\.chains\(affectedChains\)/);expect(landing).not.toMatch(/getAgentChain/);expect(page).not.toMatch(/\breadChains\b/);- expect(page).toMatch(/chainReadAuthority\.invalidateExcept\(activeBackends\)/);+ expect(page).toMatch(/chainReadAuthority\.invalidateExcept\(\(key\) => activeBackends\.has\(chainKeyBackend\(key\)\)\)/);});});diff --git a/ui/src/components/settings/models/useSourceMutationReport.test.tsx b/ui/src/components/settings/models/useSourceMutationReport.test.tsxdeleted file mode 100644index 3c19ce06b..000000000--- a/ui/src/components/settings/models/useSourceMutationReport.test.tsx+++ /dev/null@@ -1,87 +0,0 @@-// @vitest-environment jsdom-import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';-import { I18nextProvider } from 'react-i18next';-import { afterEach, describe, expect, it, vi } from 'vitest';--import i18n from '@/i18n';-import { SourceMutationReport } from './SourceMutationReport';-import type { SourceMutationCommit, SourceMutationLanding } from './mutationSettlement';-import { useSourceMutationReport } from './useSourceMutationReport';--const deferred = <T,>() => {- let resolve!: (value: T) => void;- const promise = new Promise<T>((done) => { resolve = done; });- return { promise, resolve };-};--const degradedLanding = (): SourceMutationLanding => ({- verdict: 'degraded',- reads: null,- affectedChains: [],-});--afterEach(cleanup);--describe('page-owned Source mutation reports', () => {- it('queues overlapping reports without destroying either mutation holder', async () => {- const editLanding = deferred<SourceMutationLanding>();- const deleteLanding = deferred<SourceMutationLanding>();- const commits: SourceMutationCommit[] = [- { action: 'edit', impact: null, settle: () => editLanding.promise },- { action: 'delete', impact: null, settle: () => deleteLanding.promise },- ];- const editReleased = vi.fn();- const deleteReleased = vi.fn();- const Owner = () => {- const owner = useSourceMutationReport();- return (- <>- <button- type="button"- onClick={() => { void owner.present(commits[0]).then(editReleased); }}- >- Present edit report- </button>- <button- type="button"- onClick={() => { void owner.present(commits[1]).then(deleteReleased); }}- >- Present delete report- </button>- <SourceMutationReport- report={owner.report}- onComplete={() => { void owner.complete(); }}- onDismiss={owner.dismiss}- />- </>- );- };- render(<I18nextProvider i18n={i18n}><Owner /></I18nextProvider>);- fireEvent.click(screen.getByRole('button', { name: 'Present edit report' }));- fireEvent.click(screen.getByRole('button', { name: 'Present delete report' }));-- await act(async () => {- editLanding.resolve(degradedLanding());- await editLanding.promise;- });- expect(screen.getByRole('dialog', { name: /^The source was updated$/i })).toBeTruthy();-- await act(async () => {- deleteLanding.resolve(degradedLanding());- await deleteLanding.promise;- });- expect(screen.getByRole('dialog', { name: /^The source was updated$/i })).toBeTruthy();- expect(screen.queryByRole('dialog', { name: /^The source was removed$/i })).toBeNull();- expect(editReleased).not.toHaveBeenCalled();- expect(deleteReleased).not.toHaveBeenCalled();-- fireEvent.click(screen.getAllByRole('button', { name: 'Dismiss unverified result' })[0]);- await waitFor(() => expect(editReleased).toHaveBeenCalledOnce());- expect(deleteReleased).not.toHaveBeenCalled();- expect(screen.getByRole('dialog', { name: /^The source was removed$/i })).toBeTruthy();-- fireEvent.click(screen.getAllByRole('button', { name: 'Dismiss unverified result' })[0]);- await waitFor(() => expect(deleteReleased).toHaveBeenCalledOnce());- expect(screen.queryByRole('dialog')).toBeNull();- });-});diff --git a/ui/src/components/settings/models/useSourceMutationReport.ts b/ui/src/components/settings/models/useSourceMutationReport.tsdeleted file mode 100644index cde4277fc..000000000--- a/ui/src/components/settings/models/useSourceMutationReport.ts+++ /dev/null@@ -1,96 +0,0 @@-import * as React from 'react';--import type {- PresentSourceMutationCommit,- SourceMutationCommit,- SourceMutationLanding,-} from './mutationSettlement';--export type SourceMutationReportState = {- commit: SourceMutationCommit;- landingFailed: boolean;- busy: boolean;-};--type HeldSourceMutationReport = {- state: SourceMutationReportState;- resolve: () => void;-};--const settleCommit = async (- commit: SourceMutationCommit,-): Promise<SourceMutationLanding | null> => {- try {- return await commit.settle();- } catch {- return null;- }-};--/** Page-owned post-commit evidence; a Source panel may disappear without releasing it. */-export const useSourceMutationReport = () => {- const [report, setReport] = React.useState<SourceMutationReportState | null>(null);- const queueRef = React.useRef<HeldSourceMutationReport[]>([]);- const mountedRef = React.useRef(true);-- const resolveHeldReports = React.useCallback(() => {- const held = queueRef.current;- queueRef.current = [];- for (const entry of held) entry.resolve();- }, []);-- const releaseCurrent = React.useCallback(() => {- const [current, ...remaining] = queueRef.current;- if (!current) return;- queueRef.current = remaining;- current.resolve();- setReport(remaining[0]?.state ?? null);- }, []);-- const hold = React.useCallback((- commit: SourceMutationCommit,- landingFailed: boolean,- ): Promise<void> => {- if (!mountedRef.current) return Promise.resolve();- return new Promise((resolve) => {- const held = { state: { commit, landingFailed, busy: false }, resolve };- queueRef.current.push(held);- if (queueRef.current.length === 1) setReport(held.state);- });- }, []);-- const present = React.useCallback<PresentSourceMutationCommit>(async (commit) => {- if (commit.impact) {- await hold(commit, false);- return;- }- const landing = await settleCommit(commit);- if (landing?.verdict === 'landed') return;- await hold(commit, true);- }, [hold]);-- const complete = React.useCallback(async () => {- const current = queueRef.current[0];- if (!current || current.state.busy) return;- current.state = { ...current.state, busy: true };- setReport(current.state);- const landing = await settleCommit(current.state.commit);- if (!mountedRef.current || queueRef.current[0] !== current) return;- if (landing?.verdict === 'landed') {- releaseCurrent();- return;- }- current.state = { ...current.state, landingFailed: true, busy: false };- setReport(current.state);- }, [releaseCurrent]);-- React.useEffect(() => {- mountedRef.current = true;- return () => {- mountedRef.current = false;- resolveHeldReports();- };- }, [resolveHeldReports]);-- return { report, present, complete, dismiss: releaseCurrent };-};diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 04b8c25aa..afc86c284 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1755,28 +1755,15 @@"displayNameCredential": "A display name cannot contain a credential","baseUrlCredential": "Remove credentials and credential-shaped query parameters from the Base URL"},- "impact": {- "title": "The source was updated, and some supply was affected",- "detail": "These routes or models were removed or interrupted.",- "done": "Done"- },"settlement": {"title": "The source was updated"}},"remove": {- "impact": {- "title": "The source was removed, and some supply was affected",- "detail": "These are the routes and models actually affected by this removal.",- "done": "Done"- },"settlement": {"title": "The source was removed"}},- "impact": {- "refreshFail": "The change committed, but the model surface could not be refreshed. Try the reconciliation again."- },"refetch": {"added": "New","removed_one": "This fetch removed {{count}} model: {{models}}",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 98ed50dc6..d034e074a 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1755,28 +1755,15 @@"displayNameCredential": "显示名称不能包含凭据","baseUrlCredential": "请从 Base URL 中移除凭据和疑似凭据的查询参数"},- "impact": {- "title": "供应商已更新,部分路由受到影响",- "detail": "以下路由或模型已被移除或中断。",- "done": "完成"- },"settlement": {"title": "供应商已更新"}},"remove": {- "impact": {- "title": "供应商已移除,部分路由受到影响",- "detail": "以下是这次移除实际影响的路由和模型。",- "done": "完成"- },"settlement": {"title": "供应商已移除"}},- "impact": {- "refreshFail": "变更已经提交,但模型页面暂时无法刷新。请再次重试对账。"- },"refetch": {"added": "新增","removed_one": "本次拉取移除了 {{count}} 个模型:{{models}}",