Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(ui): replace route save dialog with toast (#2119)

Call White1377b65c9c65
diff --git a/docs/plans/model-hub-ui-spec.md b/docs/plans/model-hub-ui-spec.md
index 3ea6d52ff..c54ef829c 100644
--- a/docs/plans/model-hub-ui-spec.md
+++ b/docs/plans/model-hub-ui-spec.md
@@ -100,9 +100,10 @@ Lost-response reconciliation compares normalized `manual_override` as well as ef
pairs: equal arrays can represent different saved intent. Preview is read-only with runtime
stopped and never starts the engine. A valid empty value follows the actual inherited plan;
only inherited emptiness offers Configure default routing. Removing the final manual hop
-previews that plan through existing Restore/Undo/Save/guard/Done, never a saveable empty
-Manual state. Undo restores the previous unsaved draft; the saved nonempty override stays
-untouched until confirmed successful Save. Backend changes
+previews that plan through existing Restore/Undo/Save/guard, never a saveable empty Manual
+state. Undo restores the previous unsaved draft; the saved nonempty override stays untouched
+until confirmed successful Save, which closes the editor and reports `common.saved` through the
+shared toast. Backend changes
cannot leak drafts. Origin, runtime health, request errors and draft state remain separate.
### Latest recorded turn detail
@@ -370,7 +371,7 @@ half named in its Missing cell has an owner.
| G-29 | 05 add-by-key, ⑦'s lost-response reconciliation — **registered against Source-create nonce totality** | ~~anything the client holds *before* the send that the committed Source can afterwards be recognized by~~ nothing | The client generates `SourceCreate.client_nonce` before send. A list read finds exact `Source.client_nonce` after commit; in-flight and committed retries return distinct `409` conflicts, released/list-miss retries are fresh. A committed retry never replays an old response; it returns `source_nonce_conflict` and the client rereads the list to claim the Source. |
| G-30 | 04 add-subscription, *Start failed* entered by a lost response — **registered against OAuth start nonce totality** | ~~a way to reach a flow whose `flow_id` never arrived~~ nothing | The client generates `client_nonce` before start; the server claims the exact `(client_nonce, vendor, channel)` tuple before provider work. Concurrent retry coalesces to one pending start/result, every resulting flow echoes the nonce, and nonce-bearing cancellation remains bounded by its non-null `expires_at`. §1.4 retries the held tuple without opening a second provider start. |
| G-31 | 01/08 model rows and takeover visuals — **registered against `AgentChain.current`** | ~~the chain's **current** hop, on the one read that is supposed to carry it~~ nothing | `agent-chain.schema.json` now requires `current`, either null or an exact member of `chain`; §1.1 renders the current-source line and takeover predicate from that field rather than the first runnable hop. |
-| G-32 | 02 route-chain editor — **registered by §1.2** | ~~the editor's interaction contract: how it sequences a save, what it does with a guarded refusal, what it reconciles against when the response is lost, and what the failure line reads~~ nothing | §1.2 now registers the local draft, non-forced save, exact-plan `409` confirmation, full `{chain, removed_hops, interrupted}` success consumption, M6 projection reconciliation, D-36 lost-response readback, failure copy, keyboard contract and atomic ET/AS transition totality. The shared guard contract carries no `guard_token`: confirmation is the exact echo of both refusal arrays, and a changed plan is presented again before any force commit. R6 and M6 make every response member and every invalidated projection explicit. Kept as a registered row so the former specification absence and its closing section remain auditable |
+| G-32 | 02 route-chain editor — **registered by §1.2** | ~~the editor's interaction contract: how it sequences a save, what it does with a guarded refusal, what it reconciles against when the response is lost, and what the failure line reads~~ nothing | §1.2 now registers the local draft, non-forced save, exact-plan `409` confirmation, full `{chain, removed_hops, interrupted}` success consumption, immediate editor close with shared `common.saved` toast, page-owned M6 projection reconciliation, D-36 lost-response readback, failure copy, keyboard contract and atomic ET/AS transition totality. The shared guard contract carries no `guard_token`: confirmation is the exact echo of both refusal arrays, and a changed plan is presented again before any force commit. R6 and M6 make every response member and every invalidated projection explicit. Kept as a registered row so the former specification absence and its closing section remain auditable |
| G-33 | 04 add-subscription, a flow whose declaration carries a device code | anywhere to display or copy `presentation.device_code` | **The remaining contracted value has nowhere to land.** `oauth-flow.schema.json`'s Form B is `auth_url + device_code + expects none`. This round gives every `presentation.instructions_key` a PD-4 helper-line consumer, including the null/unresolved fallback for Form B, so that former half is closed. The paste-back exhibit accepts and submits Forms A and C, but Form B submits nothing and instead needs a read-only device code the user copies out. The new input cannot render that output, so G-33 remains independently open |
| G-34 | §1.4 / §1.11, E6 materialization failure — **registered against the OAuth terminal-response matrix** | ~~the contracted error-envelope shape that carries any committed, non-reconstructible impact from that failed materialization attempt~~ nothing | The standard error envelope carries exact nonempty `interrupted_pairs` if and only if acquisition-stage Source mutation already produced that report; otherwise the member is absent, never `[]`. R5 renders a present report before the mandatory attempt-scope reread and treats absence only as no response report, never as proof that materialization changed nothing. |
@@ -696,18 +697,18 @@ registration, not something a reviewer is expected to infer from prose.
| --- | --- | --- | --- | --- | --- |
| C1 — existing capability-gated actions | Preserve every action the containing surface already offers; add the frame delta beside it | [x] Opening 02 preserves the model row, group actions and Source cards behind it; the dialog adds only per-model Route editing | [x] Edit / Remove sit beside the existing capability-gated Reauthorize / Replace key producers | [x] The blocked card covers both `needs_action` and `error`: Hub error keeps Refetch, native unclassified login failure keeps Reauthorize, and the card target / healthy-source overflow producers remain | [x] The existing Add subscription trigger remains the owner; the menu adds only vendor selection |
| C2 — valid local draft | Preserve the exact valid draft across no-op exits and F1/F3; prevent a predictably invalid submit | [x] V5 validates new/changed exact pairs; F1/F3 keep the complete ordered `hops` draft and hold the refusal plan separately | [x] V1/V2 define the normalized display name and Base URL draft; F1/F3 retain it | [x] The channel-selected acknowledgement copy, typed key, flow intent and any paste value remain with their owning state | [x] N/A — a row activation passes one closed vendor value and holds no editable draft |
-| 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 |
+| 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 successful route save closes the editor immediately, uses PF-1 for the initial landing, preserves the user's current valid focus during each background projection install, and uses PF-1 only when that focus disappears or becomes ineligible. The pending landing target remains through failed M6 subsets so a successful Retry can resolve the fallback. There is no mounted route Done state | [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] 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 |
+| C6 — committed-report exit | Once a mutation has committed, every surface that mounts a report makes every dismissal path that report's Done-equivalent exit and may neither restore a pre-write origin nor discard held response or D-36 commit evidence. A page-owned committed state may intentionally mount no Done-equivalent; it retains the evidence in the receiving page and exposes only the registered read-only Retry for an acquired failed subset. A failed projection member adds Retry only for that subset and MUST NOT remove a mounted Done-equivalent where the surface has one | [x] A successful route save closes the editor immediately after R6 or exact D-36 commit evidence is installed and emits the shared `common.saved` toast. M6 retains the exact response members page-side, installs successful members monotonically, marks only acquired failures stale and exposes Retry through the receiving page; no route impact report or Done-equivalent remains mounted | [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 |
-| C10 — mutation attempt scope and commit evidence | For every mutation covered by this frame group, name every projection its attempt may invalidate before the response is observed; both a received success envelope and authoritative D-36 commit evidence MUST pass through the owning M row before visible exit, with response-only members marked unavailable rather than invented | [x] R6 owns every received member; exact ordered D-36 readback enters Route committed, reconciling / M6 with `removed_hops` / `interrupted` unavailable | [x] R1/R2 own received save/delete envelopes; D-36 inferred save/delete commits enter the same M1/M2 reads with response-only impact arrays unavailable | [x] RR-1–RR-10 name repair attempt scope; R3/R4 classify received Source outcome, while RR-7 inferred repair commit enters M3/M4 with its absent response tail explicitly unavailable | [x] N/A — vendor selection commits nothing; create's later mutation remains owned by §1.4/RR-3 rather than the menu |
+| 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 M6 is page-owned after the editor closes. It 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 exposes Retry on the affected page projection only | [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 |
+| C10 — mutation attempt scope and commit evidence | For every mutation covered by this frame group, name every projection its attempt may invalidate before the response is observed; both a received success envelope and authoritative D-36 commit evidence MUST pass through the owning M row before visible exit, with response-only members marked unavailable rather than invented | [x] R6 owns every received member; exact ordered D-36 readback enters page-owned Route M6 with `removed_hops` / `interrupted` unavailable. The editor closes only after that evidence is installed; the shared success toast is presentation feedback, not a substitute for M6 | [x] R1/R2 own received save/delete envelopes; D-36 inferred save/delete commits enter the same M1/M2 reads with response-only impact arrays unavailable | [x] RR-1–RR-10 name repair attempt scope; R3/R4 classify received Source outcome, while RR-7 inferred repair commit enters M3/M4 with its absent response tail explicitly unavailable | [x] N/A — vendor selection commits nothing; create's later mutation remains owned by §1.4/RR-3 rather than the menu |
| C11 — workflow progress evidence | A broad transport or state class may not stand in for a later workflow milestone; register what each returned stage or external gesture proves and the exact next gesture/read it authorizes | [x] The route write has no accepted/intermediate state: only R6 or exact ordered D-36 readback proves commit; a shaped rejection is terminal for that attempt, while a nonmatching read is only an observation and never proves an unanswered PUT terminal or authorizes its resend | [x] Save/delete expose no intermediate accepted state: only an envelope or D-36 subject read proves commit, and both route through C10 | [x] Paste `starting` / `awaiting_action` proves action is still required; `verifying` proves submission acceptance. Opening a vendor link proves no recovery and enters the channel observation phase: Hub Refetch, native acknowledged Reauthorize | [x] Vendor selection transfers one closed value into §1.4 Default; it is not evidence that OAuth acquisition or login began |
| C12 — delayed required presentation | If a required presentation value may be absent now and supplied later, name the bounded read owner that can deliver it without starting another producer or browser context | [x] N/A — route replacement has no delayed server-declared presentation | [x] N/A — frame 11 has no server-declared presentation | [x] PD-5 gives a paste form whose `auth_url` is null to the held flow's 2s status-read owner; the first non-null value invokes PD-2 on the original context | [x] Vendor selection transfers to §1.4; it does not own a flow or delayed presentation value |
| C13 — terminal / absence attempt scope | Every terminal code and authoritative subject absence after a producer attempt MUST account for that attempt's full invalidation scope before visible handoff; scope is selected by the evidence milestone, never by channel alone | [x] The producer has no terminal-flow or subject-absence code; `direct_mode` enters DM-1/DM-2/DM-3 without claiming a target projection, while every proven commit still passes M6 | [x] Every `source_not_found` and inferred deletion enters M0; M2 is M0's deletion-attempt reconciliation | [x] Create E4 owns no pre-existing Source scope and create E6 re-reads `Source[]`. Every acquired-flow reauth terminal failure enters RR-5's full M3 read for Hub or native; a pre-flow reauth acquisition failure retains RR-6–RR-9's selected-Source read for either channel | [x] N/A — the menu has made no producer attempt and owns no terminal code |
-| C14 — non-mutating failure exit | Every modal failure state MUST offer an exit that sends no mutation; a committed-state exit preserves write evidence and marks unread dependent projections stale rather than restoring the origin | [x] Terminal rejection may abandon through ET-8a; a mounted unknown attempt is read-only and ET-8b explicitly abandons it, while only a forced Direct handoff transfers unknown evidence to the page session. Neither a nonmatching observation nor a read failure may resend the old attempt. Every exit reveals all successful members already installed; committed exits preserve evidence | [x] Edit/remove failures cancel to their held draft/origin; Committed projection stale has Done-equivalent dismissal in addition to read-only Retry | [x] OAuth/repair failures can dismiss through their registered cleanup or Done-equivalent committed exit; neither path resends repair | [x] The menu's Escape / outside exit sends nothing and restores Add subscription focus |
+| C14 — non-mutating failure exit | Every modal failure state MUST offer an exit that sends no mutation; a committed-state exit preserves write evidence and marks unread dependent projections stale rather than restoring the origin | [x] Terminal rejection may abandon through ET-8a; a mounted unknown attempt is read-only and ET-8b explicitly abandons it, while only a forced Direct handoff transfers unknown evidence to the page session. Neither a nonmatching observation nor a read failure may resend the old attempt. A proven commit closes the editor, reveals the installed page authority and leaves any M6 retry on that page; it never restores the origin or opens a Done report | [x] Edit/remove failures cancel to their held draft/origin; Committed projection stale has Done-equivalent dismissal in addition to read-only Retry | [x] OAuth/repair failures can dismiss through their registered cleanup or Done-equivalent committed exit; neither path resends repair | [x] The menu's Escape / outside exit sends nothing and restores Add subscription focus |
| C15 — page-form landing evidence | Every response, terminal or absence branch that changes the mounted page form MUST name the authoritative payload or read that selects the destination. Successful authority is consumed monotonically: sibling failure cannot erase it, exact mode evidence cannot be overwritten, and a later failure cannot roll the page back to an older projection | [x] AR is the sole composite-read result owner. It records each member's acquisition eligibility and observation epoch against every causal frontier that can invalidate that member, dispatches each successful AgentSupply for mode/page authority immediately, uses only exact AgentChain GET equality as D-36 Route evidence, and recalculates the applicable member set after either AgentSupply Direct or chain `direct_mode`. A failed Agents prerequisite defers rather than fabricates companion observations. LF is the closed landing read-set owner: exact Direct retains every settled independent Source authority; each exact Hub landing installs AgentSupply immediately, establishes a new Source landing frontier and cannot call Sources current until a successor Source observation satisfies it. DM errors retire an illegal editor but never invent a landing payload; PF-1 is fallback-only after installation | [x] R1/R2 and M0–M2 hand their exact returned or reread Source/absence evidence to the page. Their complete-surface results dispatch returned mode before installing a page form; an error class selects no destination by itself | [x] R3/R4 and M0/M3/M4 hand their exact returned or reread Source evidence to the page. Their complete-surface results dispatch returned mode before installing a page form; flow/error classes select failure handling, never a healthy landing | [x] N/A — the menu changes only its own reversible phase and hands one explicit local vendor selection to §1.4; no response or terminal branch changes the page form |
| C16 — atomic event-transition totality | Every state-changing event MUST register one atomic owner for authority dispatch, cleanup, visible feedback, destination focus and next owner; unlisted transitions are forbidden. ET owns gestures/non-RO single producers, AR owns mode-neutral composite-read member settlement and prerequisite-gated acquisition, RO owns mutation-attempt settlement and exact-chain observation independently from page form, LF/AS own landing read-set/install actions, PF-1/FF-1 own focus eligibility and fallback, and CA alone admits **and dispatches** async controls. One row cannot group events whose outcomes differ. Every prerequisite failure must settle its acquired member while deferring ineligible dependants; every successful member must install before an owner/phase transfer; CA predicates must be a positive exhaustive/mutually-exclusive phase partition; every rendered dismissal must map to exactly one edge; every post-install focus transfer must exhaust PF-1's FF-1-filtered candidates; selector active-candidate and selection must have one owner | [x] AR records `(workflow generation, member, acquisition eligibility, observation epoch, member settlement, required causal-frontier set, decisive page evidence)`: `deferred-by-prerequisite` members are neither pending, failed, stale nor completion obligations, and successful Agents mode alone activates their applicable frontiers. RO separately records `attempt settlement × Route observation × owner × observation legality`: terminal rejection never enters D-36, unknown never emits a recovery PUT, and exact nonmatch cannot settle an attempt. Every successful Agents/Source/AgentChain member installs monotonically before cleanup, dismissal or page transfer. Mounted RO-O delegates its admitted member result to AR-D, while the owner table settles page-session results and names cleanup, destination, feedback, focus and next work. LF closes each returned mode's companion read set and every Hub post-Source success invokes the same RO hook. RL closes every started read with generation, cancellation/disown owner and late-result disposition; AP cites every consumed wire member's route/schema provenance. CA positively partitions every exact async phase so one row or none, never two, can emit; all rendered dismissal gestures use the registered settlement × owner × busy edge. PF-1 filters active target, exact row, exact group and destination-page control through FF-1 in order. ET-5a/ET-5d make the one active candidate the selected pair from which confirmation derives. Visible feedback cites a registered key or closed copy block | [x] §1.10's state rows consume R1/R2 and M0–M2, clear their modal phase under DP-1/DP-2/DP-4, render the registered F/copy treatment and name the source overflow or receiving page as focus owner | [x] §1.11's state rows consume R3/R4 and RR/M0/M3/M4, settle flow/key transient ownership, retain the registered report/failure copy and name the invoking card or receiving projection as focus owner | [x] Closed/Open and the §1.4 handoff name the explicit vendor event, menu cleanup, visible destination and Add subscription / receiving-surface focus; no server response edge belongs to frame 13 |
@@ -734,7 +735,7 @@ register rather than borrowing a similar-looking tail from another route:
| 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. |
-| R6 | §1.2 Route save or Restore | `model-hub.md` Source-mutation matrix, `mutation.route_replace` / `mutation.route_restore` | `chain`, `removed_hops`, `interrupted` | Hold `chain` as the authoritative post-commit AgentChain and write evidence. Render each non-empty `removed_hops` and `interrupted` block in Route impact reported; an empty member skips only its own block. If both arrays are empty, skip the report but retain both exact empty values. M6 owns every Route-derived projection before handoff. |
+| R6 | §1.2 Route save or Restore | `model-hub.md` Source-mutation matrix, `mutation.route_replace` / `mutation.route_restore` | `chain`, `removed_hops`, `interrupted` | Hold `chain` as the authoritative post-commit AgentChain and write evidence. Retain each non-empty `removed_hops` and `interrupted` array in page-owned M6; the arrays are reconciliation evidence and are not mounted in a post-save route dialog. If both arrays are empty, retain both exact empty values. M6 owns every Route-derived projection before the editor closes. |
**Mutation / authoritative absence → projection invalidation register** `[contract]` `[derived]`. A complete
response or an authoritative D-36 subject read can prove the write; an exact absent read or
@@ -761,7 +762,39 @@ commit evidence into an unconfirmed write:
| 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 |
-| M6 | R6 route replacement, or an authoritative exact ordered AgentChain from `GET /api/models/agents/<backend>/chain?model=<id>` matching submitted `hops` under D-36 | `Source[]` including `adopted_by`, complete `AgentSupply[]` including mode/model supply and any present routes projection, and the Route-chain index; the attempt may change membership, mappings, order, runnability, current-hop presentation and page form | R6 receipt or AR-D6's matching exact-chain observation establishes a Route-commit frontier and starts AR-M. The returned/read chain is held as the Route member's self-satisfying CF-R evidence, but its applicability is deferred until mode is known. At entry Agents is `acquired`; Source and Route applicability are `deferred-by-prerequisite`, not pending. An Agents failure settles as the exact failed subset while those dependants remain excluded from completion/stale accounting. An explicit Agents-only Retry succeeds into an exact mode; only then do applicable companions become `ready`. Source acquires one frontier-satisfying generation; Hub activates the already-held commit chain as acquired/successful without another GET, while Direct makes Route not applicable. A Hub landing adds CF-H before Source acquisition. Earlier Source/Agents successes remain installed as latest-known authority but cannot satisfy a later frontier. Keep R6's entire envelope when received; inference marks `removed_hops` / `interrupted` unavailable. AP records `AgentSupply.routes` as optional and deliberately unconsumed here | AR-M consumes each successful acquired member monotonically and closes only when every activated applicable member settles at or after its required frontiers. Deferred members cannot block settlement or render stale. Either exact AgentSupply Direct or chain `direct_mode` takes the same decisive edge: retain every successful independent member, disown only pending/not-applicable Route work, and acquire an authoritative Agents landing read whose exact returned mode alone selects the page form. CA admits Retry only after settlement, for exactly the acquired failed subset, and never overlaps generations. Mounted completion retains report/evidence and Done; transferred completion preserves any FF-1-valid active target and otherwise uses PF-1. ET-20 alone acknowledges/closes/transfers; no path resends or questions the route write |
+| M6 | R6 route replacement, or an authoritative exact ordered AgentChain from `GET /api/models/agents/<backend>/chain?model=<id>` matching submitted `hops` under D-36 | `Source[]` including `adopted_by`, complete `AgentSupply[]` including mode/model supply and any present routes projection, and the Route-chain index; the attempt may change membership, mappings, order, runnability, current-hop presentation and page form | R6 receipt or AR-D6's matching exact-chain observation establishes a Route-commit frontier and starts page-owned AR-M. The returned/read chain is held as the Route member's self-satisfying CF-R evidence, but its applicability is deferred until mode is known. At entry Agents is `acquired`; Source and Route applicability are `deferred-by-prerequisite`, not pending. An Agents failure settles as the exact failed subset while those dependants remain excluded from completion/stale accounting. An explicit Agents-only Retry succeeds into an exact mode; only then do applicable companions become `ready`. Source acquires one frontier-satisfying generation; Hub activates the already-held commit chain as acquired/successful without another GET, while Direct makes Route not applicable. A Hub landing adds CF-H before Source acquisition. Earlier Source/Agents successes remain installed as latest-known authority but cannot satisfy a later frontier. Keep R6's entire envelope when received; inference marks `removed_hops` / `interrupted` unavailable. AP records `AgentSupply.routes` as optional and deliberately unconsumed here | AR-M consumes each successful acquired member monotonically and closes only when every activated applicable member settles at or after its required frontiers. Deferred members cannot block settlement or render stale. Either exact AgentSupply Direct or chain `direct_mode` takes the same decisive edge: retain every successful independent member, disown only pending/not-applicable Route work, and acquire an authoritative Agents landing read whose exact returned mode alone selects the page form. CA admits Retry only after settlement, for exactly the acquired failed subset, and never overlaps generations. M6 settles page-side; the editor closes at commit, background installs preserve the current FF-1-valid focus and use PF-1 only when it disappears, and the pending landing target remains through failed subsets until successful settlement. No route Done action acknowledges the write |
+
+**Consecutive route commits and page Retry** `[derived]`. M6 owns collection reads,
+not a lock on further route saves. It retains each exact report until its
+post-commit Agents/Sources obligations settle. In-flight reads remain serialized;
+a new save during a read requires a subsequent generation acquired after that
+save. An older failed report may join that newer generation because the collection
+reads cover both commit frontiers; its exact response tails remain held and are
+never reconstructed. Failure cannot indefinitely prevent the newer generation
+from starting, and a successful newer collection must not resurrect an older
+failure banner. Retry is read-only and inert while M6 is pending, with focus
+handed off before disabling it. Suspended D-36 attempts retain their own original
+opener; inferred commits use their exact backend/model identity and never borrow
+the currently open editor's target. The newest outstanding committed route owns
+the fallback even while its reads are queued behind an older batch; the active
+batch's settlement releases only its own reports, not that queued commit.
+An animation-frame fallback selects that identity at execution, not scheduling;
+if the same report has settled in between, its captured opener remains an
+eligible fallback. A newer identity never borrows an older report's opener.
+
+**M6 failure visibility across unrelated reads** `[derived]`. A ready region from
+another refresh or a Source entity echo does not itself settle M6's retained
+failed subset. Compose that subset into the receiving Sources/Gateway cards'
+stale-data and Retry presentation independently of the latest region-read kind,
+without replacing the actual authoritative read or hiding newly observed data.
+Page-form selection uses that same composed view so a direct/empty landing
+cannot remove the only Retry. M6's read-only Retry settles its acquired failed
+subset, then clears this presentation and releases its retained report and
+chain-probe exclusion.
+Each successful member clears its own retained failure in the published view
+immediately after installation. In particular, Agents recovery dispatches the
+exact mode/page authority before awaiting Sources, while the batch remains
+pending and preserves any still-failed Source obligation.
**Repair-reconciliation totality** `[contract]` `[derived]`. This is the one machine for
create OAuth, reauth and credential replacement. A Source snapshot and a mutation result
@@ -795,7 +828,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; 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 | Repair impact reported; Repair unresolved and their Committed projection stale states. Page-owned Route M6 and committed Source save/removal are deliberately excluded: they retain evidence in the receiving page and have no modal report or Done-equivalent | 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
@@ -927,12 +960,12 @@ state exit; held intent never bypasses the evidence column.
| §1.2 | Dirty | The nonempty manual draft or inherited null differs from the reversible normalized intent; a final-hop removal is a Restore preview, not empty Manual | F5 — every edit is local | Same normal-frame keys as Ready | ET-5a–ET-7f, ET-8a and ET-9a own every selector, local edit, grab, exit and submission edge |
| §1.2 | Invalid after refresh `[derived]` | ET-17e holds refreshed Hub AgentSupply/Source/chain authorities and at least one new or changed draft pair is now V5-invalid; unchanged persisted stale pairs do not enter this state | F5 — the refresh completed and no mutation is sent | Same normal-frame keys as Dirty plus `route.invalidAfterRefresh` on every offending row | ET-5a–ET-8a and ET-17e own repair, exit and focus. Every offending row stays removable; Save remains disabled with the rendered invalid lines as its description |
| §1.2 | Saving | 保存 or guard confirmation activated — nonempty manual intent sends PUT and inherited intent sends DELETE on `/api/models/agents/<backend>/chain?model=<id>`; the first request is non-forced and a confirmed retry carries `force: true` plus both exact refusal arrays `[contract]` | DP-2: the request owns the dialog and every dismissal path until classification | `route.saving` | ET-9a/ET-13b, ET-10, ET-12, ET-14, ET-15 and ET-18a own the complete response dispatch and destination focus for every answer/no-answer branch |
-| §1.2 | Route committed, reconciling `[derived]` | R6 success carries two empty impact arrays, or AR-D6 proves the desired Route from the exact chain endpoint while response-only arrays are unavailable; exact commit evidence is held while the active AR-M generation has an acquired member pending, a ready member awaiting acquisition, or an acquired member whose observation has not satisfied every required causal frontier. Mode-dependent deferred members are not pending obligations | F2 applies only to acquired members that AR-M3 marks stale; an Agents-first failure makes Agents the exact stale/Retry subset while Source/Route remain deferred. The Route write/desired state is already proven | `route.refreshing`, `route.impact.done` | ET-11 or ET-17c owns mutually exclusive entry; AR-M/AR-MD, ET-18aM/ET-18aP, ET-19, AS and ET-20 own member eligibility/epochs/frontiers, Direct handoff, Retry, page installation and the sole user exit |
-| §1.2 | Route committed, refreshed `[derived]` | AR-M2 completed a mounted report-free M6 generation with every activated applicable member satisfying all causal frontiers and no member deferred behind an unresolved prerequisite; it installed the exact page behind the still-mounted modal and holds commit evidence until acknowledgement | F5 — no request remains and no impact report exists | `route.impact.title`, `route.impact.done` | ET-20 is the only exit. The page projection is already installed, and modal close invokes PF-1 because Done unmounts |
+| §1.2 | Route committed, reconciling `[derived]` | R6 success carries two empty impact arrays, or AR-D6 proves the desired Route from the exact chain endpoint while response-only arrays are unavailable; exact commit evidence is held by page-owned M6 while the active AR-M generation has an acquired member pending, a ready member awaiting acquisition, or an acquired member whose observation has not satisfied every required causal frontier. Mode-dependent deferred members are not pending obligations. The editor closes immediately after the evidence is accepted | F2 applies only to acquired members that AR-M3 marks stale; an Agents-first failure makes Agents the exact stale/Retry subset while Source/Route remain deferred. The Route write/desired state is already proven | `common.saved` toast, then the existing page stale/Retry treatment | ET-11 or ET-17c owns entry; AR-M/AR-MD, ET-18aM/ET-18aP, ET-19, AS and ET-20 own member eligibility/epochs/frontiers, Direct handoff, Retry and page installation. Background installs preserve the current FF-1-valid focus; PF-1 runs only when that focus disappears or becomes ineligible, and the pending landing target survives failed subsets. No modal exit remains |
+| §1.2 | Route committed, refreshed `[derived]` | AR-M2 completed a page-owned M6 generation with every activated applicable member satisfying all causal frontiers and no member deferred behind an unresolved prerequisite; it installed the exact page projection and clears the transient route reconciliation status | F5 — no request remains and no impact report is rendered | Existing page projection; the success toast has already announced the commit | ET-20 records settlement and clears the pending landing target after the final focus decision; there is no mounted route dialog or Done action |
| §1.2 | Route save refused `[derived]` `[contract]` | A non-forced or forced save returned the current exact refusal plan: nonempty manual PUT guards interruption; Restore/last-hop removal additionally guards effective hop removal | F3 — shared `Qp6FI`; G-23 remains the drawing gap for the detailed SupplyGap block | `guard.title.saveRoute`, `guard.subtitle.saveRoute`, `guard.confirm.saveRoute`, `guard.label`, `guard.count`, `guard.hop.position`, `guard.hint.interrupt`, `guard.gap.label`, `guard.gap.subject`, `guard.gap.agents`, `gateway.modelCount`, `guard.cancel` | ET-12, ET-13a and ET-13b separately own plan replacement, cancellation and confirmation |
| §1.2 | Route save rejected `[derived]` | The server definitively rejected the route write outside the guarded-plan and `direct_mode` branches, so this attempt is `terminal-rejected` and did not commit | F1, in place; no D-36 read is started | `route.fail.save`, `route.retry`, `route.cancel` | ET-14 owns terminal entry. CA-R1 admits one explicit Retry only after ordinary V5 validation; ET-14a creates a **new** workflow generation and ordinary PUT or DELETE according to normalized intent, never a recovery/replay of the rejected attempt. ET-8a owns the non-mutating exit |
| §1.2 | Route save outcome unresolved `[derived]` | The route write initially produced no exact Route authority: either no HTTP/API answer or DM-2's shaped `direct_mode` response. The exact submitted draft and whether this was the non-forced or confirmed stage remain held while attempt settlement is `unknown`; an exact nonmatching chain is installed as the newest Route observation but does not settle that attempt. Direct changes only observation legality | F1; D-36 is read-only for this entire workflow | Mounted: `route.fail.unconfirmed` before/after nonmatch, `route.fail.reconcileRead` after a read or Source failure, `route.retry` only for the admitted read subset, and `route.cancel`. Page-owned Hub failure reuses the row's Chain-unresolved/D-35 read treatment; page-owned Direct makes no false Route claim | ET-15/DM-2, RO/AR-D/ET-16, LF/AS, ET-17 and ET-18a own entry, legality changes and D-36 reads. Every successful read installs before transition. Mounted dismissal explicitly abandons the old attempt through ET-8b and retains installed authority; it never transfers a recovery PUT right. CA-D admits exactly one read Retry; page-owned Retry is D-35 only. Reload is the sole implicit evidence drop and never resends |
-| §1.2 | Route impact reported `[derived]` `[contract]` | R6 holds a successful route-replace or route-restore response with non-empty `removed_hops` and/or `interrupted`; the complete returned `chain` remains held while AR-M independently settles every activated member after all of that member's required causal frontiers | F2 only for the exact AR-M3 acquired failed subset; deferred companions are neither stale nor Retryable. The write already succeeded and DP-4 owns every exit | Report block keys always; `route.refreshing` while an acquired member is pending or a successful prerequisite is activating companions; `route.impact.refreshFail` and `route.retry` only in the settled-failure subphase; neither retry key after AR-M2 success | ET-10, AR-M/AR-MD, ET-18aM, ET-19, AS and ET-20 own report entry, acquisition eligibility/member settlement/Direct handoff/Retry/install and the sole user exit; successful authority is installed immediately and never dismisses the report |
+| §1.2 | Route commit evidence with impact `[derived]` `[contract]` | R6 holds a successful route-replace or route-restore response with non-empty `removed_hops` and/or `interrupted`; the complete returned `chain` remains held by page-owned M6 while AR-M independently settles every activated member after all of that member's required causal frontiers. The impact arrays are retained as reconciliation evidence, not mounted as a second dialog after save | F2 only for the exact AR-M3 acquired failed subset; deferred companions are neither stale nor Retryable. The write already succeeded and the page owns every retry | `common.saved` toast followed by the existing page stale/Retry treatment; route impact blocks and `route.impact.done` are not rendered | ET-10, AR-M/AR-MD, ET-18aM, ET-19, AS and ET-20 own evidence retention, acquisition eligibility/member settlement/Direct handoff/Retry/install and focus preservation/fallback. The editor closes at commit and has no sole modal exit |
| §1.3 | Ready | Drawer opened and the eligible sources resolved | F1, in the region the list would have filled → Sources unread | `order.title`, `order.subtitle`, `order.section.ordered`, `order.section.ordered.note`, `order.section.heldOut` | 取消 / 关闭 / Escape → close, discarding uncommitted moves; 保存顺序 → Saving |
| §1.3 | Sources unread | The eligible-source read came back failed while the page behind the drawer is still rendering a healthy runtime `[derived]` | F1, in place | `order.fail.read`, `order.retry` | 重试 → the read runs again, and what it answers with decides: at least one eligible source → Ready, none → Zero eligible sources, another failure → back here; 取消 / 关闭 / Escape → close, having changed nothing |
| §1.3 | Zero eligible sources | No source is eligible for this backend | F5 | `order.empty.noEligible` | 关闭. A source becomes eligible → Ready. 保存顺序 is disabled |
@@ -2181,22 +2214,22 @@ removal succeeds ordinarily and appears in `removed_hops`; only nonempty
activate the existing guard even without interruption. Every refusal carries its exact
current plan and mutates nothing. ET-13a and ET-13b own abandoning and confirming it.
-**R6 and M6 own the success before the dialog may disappear** `[contract]` `[derived]`.
+**R6 and M6 own the success before the editor closes** `[contract]` `[derived]`.
The returned `chain` is the post-write projection and commit evidence. Later reads may
-update live projections, but never replace that held response evidence while its report
-or M6 handoff is mounted. Each non-empty `removed_hops` / `interrupted` array renders once using the
-shared hop and SupplyGap blocks, while an empty member skips only its block. ET-10 starts
-M6 as the report mounts; ET-11 starts the same read for a two-empty R6 envelope, while
-ET-17c starts it when the exact chain endpoint is the first matching authority after a lost
-response. In every case the exact evidence and modal stay mounted while AR-M has an acquired
-member pending; a mode-dependent deferred member is not itself pending. Each successful
-acquired member is installed/held immediately; a
-successful AgentSupply installs its exact page behind the modal and leaves Done focused even
-if a sibling later fails. Direct mode makes Route-chain members not applicable and disowns
-their reads; it does not turn them into stale failures. No settlement acknowledges, closes or
-transfers the report. ET-20's Done-equivalent family is the only user-initiated
-ownership-transfer exit; it may hand an in-flight M6 read to the page but never starts,
-cancels or repeats it.
+update live projections, but never replace that held response evidence while page-owned M6
+is active. Each non-empty `removed_hops` / `interrupted` array remains exact reconciliation
+evidence; it is not remounted as a Route impact dialog after save. ET-10 starts page-owned
+M6 for an R6 response with impact; ET-11 starts the same read for a two-empty R6 envelope,
+while ET-17c starts it when the exact chain endpoint is the first matching authority after a
+lost response. The editor closes as soon as the commit evidence is accepted, emits the shared
+`common.saved` toast, and returns focus through PF-1. Every successful acquired member is
+installed/held immediately; background installs preserve the current FF-1-valid focus and
+use PF-1 only when that focus disappears or becomes ineligible. The pending landing target
+remains through failed subsets so a later successful Retry can resolve the fallback. Direct
+mode makes Route-chain members not applicable and disowns their reads; it does not turn them
+into stale failures. M6 never
+resends or questions the route write, and it exposes any acquired failed subset through the
+receiving page's existing Retry treatment.
Route membership changes also change Source `adopted_by`, AgentSupply/model-supply and
row/current projections, so installing only the returned chain is not a complete handoff.
AR-M failure never questions the write or discards a successful member: a report stays
@@ -2317,7 +2350,7 @@ feedback, focus and next work for its exact-chain answer:
| Owner + result | Mandatory installation before cleanup | Cleanup / destination | Visible feedback / focus | Next owner |
| --- | --- | --- | --- | --- |
-| Mounted editor + match | Install exact matching AgentChain | Set settlement `terminal-committed`, establish CF-R and keep the modal mounted in Route committed, reconciling | `route.refreshing`; focus `route.impact.done` | M6/AR-M; acquire every member successor required by CF-R |
+| Mounted editor + match | Install exact matching AgentChain | Set settlement `terminal-committed`, establish CF-R, start page-owned M6 and close the editor | `common.saved` toast; PF-1 after close | M6/AR-M; acquire every member successor required by CF-R |
| Mounted editor + nonmatch | Install exact nonmatching AgentChain as the row's newest Route authority | Keep settlement `unknown`; Source may finish independently. The modal remains read-only and may explicitly abandon through ET-8b | Existing unresolved/failure copy; Source failure adds only `route.fail.reconcileRead`. Focus the admitted read Retry or Cancel | No mutation owner. A new exact-chain read may be admitted after active members settle; user abandonment closes the workflow, and a later row activation starts a new editor workflow from installed authority |
| Mounted editor + read failure | None | Keep `unknown`, settle the exact-chain generation and retain draft/latest installed Hub authority | `route.fail.reconcileRead`; focus the admitted read Retry | A newly admitted mounted RO-O read only |
| Page session + match | Install exact matching AgentChain | Set settlement `terminal-committed`, establish CF-R and retain exact Hub page without remounting the editor | Page Chain-unresolved marker clears; preserve current FF-1-valid page target or PF-1 | M6 as page-owned reconciliation; acquire the Agents-first frontier sequence before settlement |
@@ -2358,9 +2391,9 @@ total; intentionally unconsumed members remain recorded rather than being descri
| AR-D8 — exact chain read failure | Non-Direct exact-chain observation fails | Record `read-failed@epoch`; attempt remains `unknown`. No commit frontier exists | No new Route authority | Retain every successful Source/Agents member already installed | Agents, Sources and exact chain | Chain failed plus any still-pending/failed Source | Settle only chain failure; no success or axis is rolled back | After all pending members settle, ET-17b; Retry only the exact failed read subset, never an already-successful member or mutation |
| AR-D9 — Source member settles, mode-neutral | The post-Hub-landing Source generation returns success or failure before or after AR-D6/AR-D7/AR-D8 | Success or failure settles only Source at its acquisition epoch and changes no attempt/observation axis. If a later commit/Hub frontier applies, acquire a successor instead of treating this slot as current/stale | Source carries no page-form or Route-attempt evidence | **Install Source success before any transition**; mark only a frontier-satisfying failure stale | The mode-selected set is unchanged | Source alone becomes current, failed or pending for a newer frontier | Chain settlement cannot undo Source; Source settlement cannot undo Route observation | Re-evaluate the product table. A Source-only failure Retry never rereads Agents or exact chain |
| AR-M1 — acquired member settles, mode-neutral | Active M6 + an `acquired` Source, Agents or Route-chain member returns success or failure | Settle only that member. It closes its slot only if its acquisition epoch satisfies every required frontier; otherwise retain it as latest-known and make one successor `ready` for acquisition. Activating the held commit chain is an immediate successful settlement, not a request | Only an exact successful Agents mode payload may select LF/AS page form. Source success/failure, Agents failure and non-Direct Route settlement carry no page-form evidence | Install/hold a success monotonically; mark only a frontier-satisfying acquired failure stale. Successful Agents invokes LF/AS; every other result updates only its member authority/staleness | Before decisive mode, Agents is applicable/acquired and Source/Route applicability is deferred. Exact Direct activates Source and makes Route not applicable; exact Hub activates Source and the held self-satisfying Route evidence. Agents remains applicable in both | Acquired pending members; deferred companions before mode; exact acquired failures after settlement | Sibling failure cannot undo a success. A failed prerequisite leaves dependants deferred and does not make them stale; ignore predecessor-epoch results | Keep the currently installed Direct/Hub page and mounted/transferred ownership unchanged. Agents-first failure settles through AR-M3 with Agents alone retryable; successful Agents Retry activates companions. A late Direct-mode Source result settles only Source and never resurrects Hub |
-| AR-MD — decisive Direct | Active M6 + exact AgentSupply `mode: direct` **or** Route-chain `direct_mode` | The Route-commit frontier remains held; Route slots are provisionally not applicable until the landing Agents member settles | Both producers take this one reducer edge; the landing AgentSupply then recomputes applicability/acquisition eligibility from its exact mode | Preserve every successful independent member. A current Direct AgentSupply self-satisfies Agents; chain Direct acquires that landing read through ET-18aM/ET-18aP | Landing Direct: Source + Agents activated, Route not applicable. Landing Hub: Source + Agents activated; Route uses the held commit chain when it is the CF-R evidence, otherwise a chain-Direct handoff acquires one newly applicable exact chain | Landing Agents when chain supplied Direct; if it returns Hub, Sources also requires its new landing frontier and Route becomes applicable. Before landing, every mode-dependent companion remains deferred | Cancel/disown only prior pending Route work and ignore its late results; never discard a successful Source/Agents member | Mounted report remains mounted or receiving page enters Partial until AS dispatch; Retry only the current acquired failed subset |
-| AR-M2 — all activated frontiers satisfied | Active M6 + no acquired member pending/failed and every activated applicable member has an observation satisfying all frontiers required by that member | Complete activated surface settles reconciliation. No deferred member can coexist with a successful decisive mode; before mode, only Agents is an activated obligation | The latest exact mode-selected set controls page form | Keep every exact activated member and commit evidence | Latest mode-selected set | None; not-applicable Route members are neither current nor stale | Settle generation; ignore duplicate/disowned/predecessor results | Mounted evidence remains until ET-20 or transferred page remains; Retry absent |
-| AR-M3 — acquired failed subset settles | Active M6 + no acquired member pending/unsatisfied + one or more acquired failures after their frontiers. An Agents-first failure qualifies with Source/Route still deferred | Commit frontier held; the acquired generation settles partially current without pretending deferred members were observed | Any already-successful mode/authority remains decisive; an Agents-first failure supplies no new page form | Keep every successful acquired member installed and commit evidence held | Before mode: Agents acquired, Source/Route deferred. After mode: exact activated set | Exact failed acquired subset is visibly stale; deferred members are neither visible stale nor Retryable | Settle; ignore later results from it | Mounted → ET-19a; transferred → ET-19c; Retry exactly the acquired failed subset, including Agents alone before mode |
+| AR-MD — decisive Direct | Active M6 + exact AgentSupply `mode: direct` **or** Route-chain `direct_mode` | The Route-commit frontier remains held; Route slots are provisionally not applicable until the landing Agents member settles | Both producers take this one reducer edge; the landing AgentSupply then recomputes applicability/acquisition eligibility from its exact mode | Preserve every successful independent member. A current Direct AgentSupply self-satisfies Agents; chain Direct acquires that landing read through ET-18aM/ET-18aP | Landing Direct: Source + Agents activated, Route not applicable. Landing Hub: Source + Agents activated; Route uses the held commit chain when it is the CF-R evidence, otherwise a chain-Direct handoff acquires one newly applicable exact chain | Landing Agents when chain supplied Direct; if it returns Hub, Sources also requires its new landing frontier and Route becomes applicable. Before landing, every mode-dependent companion remains deferred | Cancel/disown only prior pending Route work and ignore its late results; never discard a successful Source/Agents member | The editor is already closed; the receiving page remains Partial until AS dispatch; Retry only the current acquired failed subset |
+| AR-M2 — all activated frontiers satisfied | Active M6 + no acquired member pending/failed and every activated applicable member has an observation satisfying all frontiers required by that member | Complete activated surface settles reconciliation. No deferred member can coexist with a successful decisive mode; before mode, only Agents is an activated obligation | The latest exact mode-selected set controls page form | Keep every exact activated member and commit evidence | Latest mode-selected set | None; not-applicable Route members are neither current nor stale | Settle generation; ignore duplicate/disowned/predecessor results | Page-owned evidence settles; preserve current FF-1-valid focus, use PF-1 only when it disappears, and clear the landing target |
+| AR-M3 — acquired failed subset settles | Active M6 + no acquired member pending/unsatisfied + one or more acquired failures after their frontiers. An Agents-first failure qualifies with Source/Route still deferred | Commit frontier held; the acquired generation settles partially current without pretending deferred members were observed | Any already-successful mode/authority remains decisive; an Agents-first failure supplies no new page form | Keep every successful acquired member installed and commit evidence held | Before mode: Agents acquired, Source/Route deferred. After mode: exact activated set | Exact failed acquired subset is visibly stale; deferred members are neither visible stale nor Retryable | Settle; ignore later results from it | Page-owned M6 exposes Retry exactly for the acquired failed subset, including Agents alone before mode |
| AR-M4 — retry acquired failed subset | Settled AR-M3 + explicit admitted Retry | All causal frontiers remain held; successor epochs for only the failed acquired subset become pending. Deferred companions stay deferred during an Agents Retry | No prior success is reread or discarded | Retain installed members/evidence | Recompute only after a successful decisive Agents result; then activate the exact mode-selected companions | Prior acquired failed subset becomes pending; no deferred member is sent | CA first hands focus off, then disables Retry; predecessor/disowned results are ignored | Same mounted/receiving phase; Retry exactly the failed subset. Successful Agents Retry dispatches LF/AS and acquires newly ready companions once |
AR-D presentation and read eligibility are derived only after its independent reducers run:
@@ -2460,8 +2493,9 @@ can pass, not the resolver.
Modal-closing AS/ET edges cite PF-1 because their modal target unmounts. Transferred M6
AS-5b/AS-6b invokes it only when the refreshed projection removes the user's current page
-target or makes it ineligible; otherwise focus stays where the user moved it. Mounted
-AS-5a/AS-6a always leave admitted Done focused. The event table remains the sole destination
+target or makes it ineligible; otherwise focus stays where the user moved it. Page-owned
+AS-5a/AS-6a preserve the current FF-1-valid focus after each relevant install and invoke
+PF-1 only when that focus disappears or becomes ineligible. The event table remains the sole destination
owner. Its **Visible feedback** cell MUST cite a key in the copy register below or name an
existing registered state/copy block; a prose-only announcement is not an implementation
contract.
@@ -2511,8 +2545,8 @@ generation is ignored and cannot install authority, feedback or focus.
| ET-8c — Cancel changes | Ready or terminal-rejected + reversible local draft/restore proposal | Disown local preview and prior opening generations; acquire a fresh exact-chain GET without mutation | Drop selector, grab, local intent and rejected submission evidence; keep the dialog mounted | Loading then Ready from saved authority, or Route unread | Existing loading/read-failure copy; unchanged intent disables Save | Stable footer Close, then Retry on failed read | Dialog-owned chain GET; never a recovery PUT/DELETE |
| ET-8b — explicit unknown-attempt abandonment | Attempt settlement is `unknown`, owner is mounted editor, legality is Hub-observable or Direct-suspended, and the latest successful members are already installed | Send no mutation/read; explicitly abandon this old workflow and disown every mounted AR-D/RO generation before close | Close selector; restore/cancel any grab; discard submitted pairs/stage and all old-workflow rights. Ignore every later result from disowned generations | Reveal the latest installed authority, including an AgentSupply, Source or matching/nonmatching AgentChain installed before this edge | Exact latest projection with no old-attempt Retry. A later row open starts from current authority as a new workflow; it never resumes or replays this attempt | Preserve an FF-1-valid page target, otherwise PF-1 after modal close | None |
| ET-9a — first Route save | V5-valid nonempty manual draft or ready inherited preview | Freeze normalized intent and send nonempty PUT or inherited DELETE without `force` or plan echoes | Close selector; settle any grab | Saving | `route.saving` | Programmatically focusable progress status | One owned Route PUT or DELETE matching the immutable intent |
-| ET-10 — R6 success with impact | Saving + exact R6 envelope with either array nonempty | Consume every R6 member, establish CF-R, mount its report and start AR-M with Agents acquired and Source/Route applicability deferred | Release mutation/refusal ownership; retain the entire envelope and held self-satisfying chain | Route impact reported with AR-M pending | Impact title/detail and each nonempty block | `route.impact.done` | Agents landing read; mode then acquires Sources under Direct or after CF-H under Hub and activates/drops the held Route evidence |
-| ET-11 — two-empty R6 commit | Saving + exact R6 envelope whose two impact arrays are empty | Preserve the exact envelope, establish CF-R and start AR-M with Agents acquired and Source/Route applicability deferred | Release mutation ownership; retain the held self-satisfying chain; no origin can be restored | Route committed, reconciling | `route.refreshing` | `route.impact.done` | Agents landing read; mode then acquires Sources under Direct or after CF-H under Hub and activates/drops the held Route evidence |
+| ET-10 — R6 success with impact | Saving + exact R6 envelope with either array nonempty | Consume every R6 member, establish CF-R, start page-owned AR-M with Agents acquired and Source/Route applicability deferred, and close the editor | Release mutation/refusal ownership; retain the entire envelope and held self-satisfying chain in page-owned M6 | Page-owned Route reconciliation | `common.saved` toast; page stale/Retry copy only if an acquired member later fails | PF-1 after close; preserve current FF-1-valid focus on installs and use PF-1 only if it disappears | Agents landing read; mode then acquires Sources under Direct or after CF-H under Hub and activates/drops the held Route evidence |
+| ET-11 — two-empty R6 commit | Saving + exact R6 envelope whose two impact arrays are empty | Preserve the exact envelope, establish CF-R, start page-owned AR-M with Agents acquired and Source/Route applicability deferred, and close the editor | Release mutation ownership; retain the held self-satisfying chain in page-owned M6; no origin can be restored | Route committed, reconciling on the page | `common.saved` toast; no mounted `route.refreshing` or Done state | PF-1 after close; preserve current FF-1-valid focus on installs and retain the landing target through failed Retry | Agents landing read; mode then acquires Sources under Direct or after CF-H under Hub and activates/drops the held Route evidence |
| ET-12 — guarded 409 | Saving + immutable draft + complete current refusal arrays | Validate guard code and both arrays; a later 409 atomically replaces both | Release mutation ownership only after the current plan is held | Route save refused | Shared Qp6FI copy and current arrays | `guard.cancel` | None until explicit user action |
| ET-13a — abandon guard | Route save refused + immutable draft/current arrays | Send/read nothing | Drop the refusal plan only | Dirty | Normal draft | `route.save` | None |
| ET-13b — confirm guard and send | Route save refused + immutable draft/current arrays | Revalidate exact echoes, then send the same draft with `force: true` and both arrays | Drop the rendered refusal as the immutable values freeze into the request | Saving | `route.saving` | Programmatically focusable progress status | One owned Route PUT or DELETE matching the immutable intent |
@@ -2523,29 +2557,29 @@ generation is ignored and cannot install authority, feedback or focus.
| ET-16b — AR-D1 failure handoff | AR-D1 selected after the Agents member failed | Do not choose a page form | Clear active generation/busy; retain error body/draft and latest page authority | Originating failure | `route.fail.reconcileRead` | FF-1-valid `route.retry` | None until a newly admitted ET-16a |
| ET-17a — AR-D3 Hub comparison begins | AR-D3 selected after AS-2 installs the exact Hub AgentSupply | Under the same workflow generation read current Sources and the exact chain endpoint; record a member epoch for each and never inspect AP-2 for equality | Keep modal/draft; CA-D2 retains its completed handoff and Retry admission | Originating failure, Hub reconciliation pending over the installed Hub page; accumulator enters AR-D4 | Existing failure copy | Preserve CA-D2's FF-1-valid owner | One Source read + one exact-chain read in the current AR-D generation |
| ET-17b — settled AR-D read failure | The orthogonal unknown-attempt product has no pending member and at least one failed Source/chain slot, except the dedicated nonmatching-observation + Source failure row ET-17f | Preserve every attempt/observation axis and successful installed member; do not restart an already-authoritative read | Clear active generation/busy; retain draft and latest installed page projection | Route save outcome unresolved | `route.fail.reconcileRead` | FF-1-valid `route.retry` | CA-D3 admits a successor for exactly the failed Source/chain subset; CA-D4 owns its pending phase |
-| ET-17c — AR-D6 matching chain proves commit | AR-D6 selected from an exact AgentChain whose manual_override matches normalized submitted intent | The exact AgentChain is already installed; record `matching@epoch`, settle the attempt `terminal-committed`, mark response-only tails unavailable and establish CF-R before transferring to AR-M | Clear comparison busy; discard obsolete read Retry state; retain earlier successes as latest-known but frontier-insufficient | Route committed, reconciling | `route.refreshing` | FF-1-valid `route.impact.done` | Acquire Agents first; LF-H then establishes CF-H and acquires Sources. Keep the matching chain self-satisfied |
+| ET-17c — AR-D6 matching chain proves commit | AR-D6 selected from an exact AgentChain whose manual_override matches normalized submitted intent | The exact AgentChain is already installed; record `matching@epoch`, settle the attempt `terminal-committed`, mark response-only tails unavailable, establish CF-R and transfer to page-owned M6 while closing the editor | Clear comparison busy; discard obsolete read Retry state; retain earlier successes as latest-known but frontier-insufficient | Page-owned Route committed, reconciling | `common.saved` toast; page stale/Retry copy only if an acquired member later fails | PF-1 after close; preserve current FF-1-valid focus on installs and retain the landing target through failed Retry | Acquire Agents first; LF-H then establishes CF-H and acquires Sources. Keep the matching chain self-satisfied |
| ET-17d — repeat exact observation after nonmatch | Attempt remains `unknown`; AR-D7 holds an installed `nonmatching@epoch`; AR-D9 holds Source success satisfying current CF-H; CA-D7 admits the read | Acquire one successor exact-chain GET under the same read-only workflow; send no PUT and do not run V5 as a mutation gate | Retain draft/evidence and every installed authority; CA-D2 owns focus transfer plus Retry busy/inert admission | Route save outcome unresolved, exact read pending | Existing unresolved copy | CA-D2 handoff | One exact-chain successor; match enters ET-17c, nonmatch updates the observation epoch, failure enters ET-17b |
| ET-17e — independent refresh invalidates local draft | Ready, Dirty or Route save rejected with no mutation owned + newly installed authoritative Source/chain projection that makes a new/changed pair fail V5 | Install the authority first and re-run V5; send no PUT | Clear selector/grab state invalidated by the refresh; when present discard terminal rejection evidence while retaining editable rows | Invalid after refresh | `route.invalidAfterRefresh` on every offender | First offending row's FF-1-valid Remove action | None |
| ET-17f — nonmatching observation + Source failure | AR-D7 holds installed `nonmatching@epoch` and AR-D9 settles a Source failure satisfying current CF-H, in either response order | Preserve attempt `unknown` and the exact observation; classify only Sources stale | Clear active generation/busy; retain draft, AgentSupply and installed exact chain authority | Route save outcome unresolved with Source stale | `route.fail.reconcileRead` | FF-1-valid `route.retry` | CA-D5 admits only ET-17g; Agents/chain and the mutation are not eligible |
| ET-17g — Source-only reconciliation Retry | ET-17f + CA-D5 admission | Reissue only `GET /api/models/sources` under the same latest CF-H; preserve attempt `unknown` and the nonmatching observation | Retain all settled authority; CA-D6 owns focus handoff plus Retry busy/inert admission | Same unresolved failure, Source reconciliation pending | Existing failure copy | CA-D6 handoff | One Source successor; success admits only CA-D7/ET-17d's newer exact read, failure returns ET-17f |
| ET-17h — generic failed-read-subset Retry | ET-17b + exact failed Source/chain subset + CA-D3 admission | Reissue only that subset; preserve every settled RO axis and successful member | Retain all authority/draft; CA-D4 owns focus handoff plus Retry busy/inert admission | Same failure, subset reconciliation pending | Existing failure copy | CA-D4 handoff | One successor per failed member; each result re-enters its independent AR-D edge |
| ET-18a — reversible decisive `direct_mode` handoff | Loading, Saving or AR-D5 + matching DM-1/DM-2/DM-3 evidence and no CF-R commit frontier | Error evidence selects no page form; retain every successful independent member and start/transfer the page's Agents read. DM-2 first sets attempt settlement `unknown`; every handoff changes owner to page session and legality to Direct-suspended without changing settlement or observation | Close modal/selector and cancel grab. Discard editable presentation; for unknown retain generation/submitted pairs/stage in the page session. Disown only pending illegal Route siblings | Page §1.0 Partial over every latest successful Source/Agents projection | Existing Partial copy; never label Direct from the error or claim a Route outcome | Stable owning backend group head | Page Agents read; result enters LF-D/LF-H. LF-H's post-Source hook re-evaluates RO-O; every late disowned sibling result is ignored |
-| ET-18aM — mounted M6 chain-Direct handoff | Mounted report/committed modal + AR-MD selected from chain `direct_mode` | Keep CF-R/commit evidence and successful independent members; start the landing Agents read without deriving a page form from the error | Retain modal and enabled Done; disown only prior pending Route work | Same mounted report/committed phase over last installed page until AS-5a/AS-6a | Existing report/refresh copy | Keep FF-1-valid `route.impact.done` | Landing Agents dispatches mode; Hub establishes CF-H and acquires every required Source/Route successor, Direct does not |
+| ET-18aM — page-owned M6 chain-Direct handoff | Page-owned AR-MD selected from chain `direct_mode` after the editor has already closed | Keep CF-R/commit evidence and successful independent members; start the landing Agents read without deriving a page form from the error | Disown only prior pending Route work; the editor is already gone | Page §1.0 Partial over the last installed page | Existing Partial copy plus held committed evidence | Reapply PF-1 after the landing install | Landing Agents dispatches mode; Hub establishes CF-H and acquires every required Source/Route successor, Direct does not |
| ET-18aP — transferred M6 chain-Direct handoff | Receiving page + AR-MD selected from chain `direct_mode` | Keep CF-R/commit evidence and successful independent members; start the page-owned landing Agents read | Retain installed page members; disown only prior pending Route work | Page §1.0 Partial over the last installed page | Existing Partial copy plus held committed evidence | Preserve current FF-1-valid page target, otherwise PF-1 | Landing Agents dispatches mode; Hub establishes CF-H and acquires every required Source/Route successor, Direct does not |
| ET-18b — reversible error-handoff Agents read failure | ET-18a Partial + last-good page projection + optional unknown page-session RO state | Classify only the read failure | Clear pending; keep last-good projection explicitly stale and retain all RO axes/evidence unchanged; CA-P1 admits page Retry | Page §1.0 Partial/F2 | Existing F2 cause and page Retry | FF-1-valid page Retry | None until ET-18c; M6 landing-read failure instead remains in AR-M and settles through ET-19a/ET-19c |
| ET-18c — retry error-handoff Agents read | ET-18b + stale page projection + CA-P1 admission | Reissue only `GET /api/models/agents` | Retain stale projection and all RO axes/evidence; CA-P2 owns focus transfer plus Retry busy/inert admission | Page §1.0 Partial pending | Existing F2 copy | CA-P2 handoff | Page Agents read; success enters LF-D/LF-H and its AS install/post-Source hook |
-| ET-19a — mounted AR-M3 failed subset | Mounted report/committed modal + AR-M3 settled generation | Failure cannot negate commit or any successful installed member | Clear generation pending; retain modal/evidence and mark only the acquired failed member set stale. Mode-dependent deferred members remain unrendered/non-stale | Same impact report, or report-free Committed projection stale | `route.impact.refreshFail` plus prior report/refresh copy | FF-1-valid `route.retry` | None until CA-M2 admits ET-19b |
-| ET-19b — mounted failed-subset Retry | ET-19a + exact acquired failed subset + CA-M2 admission | Start AR-M4 for exactly that subset; an Agents-only Retry leaves companions deferred until its success dispatches mode | Keep modal/evidence/successful members; CA-M1 owns focus transfer plus Retry busy/inert admission | Same report or report-free state, retry pending | Prior report/refresh copy | CA-M1 handoff | One AR-M successor generation for the acquired failed subset; successful Agents activates/acquires applicable companions once |
+| ET-19a — page-owned AR-M3 failed subset | Page-owned AR-M3 settled generation | Failure cannot negate commit or any successful installed member | Clear generation pending; retain evidence and mark only the acquired failed member set stale. Mode-dependent deferred members remain unrendered/non-stale | Page with partial current authority | `route.impact.refreshFail` plus the existing page Retry | Preserve current page focus only if FF-1-valid; otherwise use PF-1 | None until CA-M2 admits ET-19b |
+| ET-19b — page-owned failed-subset Retry | ET-19a + exact acquired failed subset + CA-M2 admission | Start AR-M4 for exactly that subset; an Agents-only Retry leaves companions deferred until its success dispatches mode | Keep evidence/successful members; CA-M1 owns Retry busy/inert admission | Same page projection, retry pending | Prior page copy | CA-M1 handoff | One AR-M successor generation for the acquired failed subset; successful Agents activates/acquires applicable companions once |
| ET-19c — transferred AR-M3 failed subset | ET-20 receiving page + AR-M3 settled generation | Failure cannot negate commit or any successful installed member | Clear generation pending; retain evidence and mark only acquired failed members stale; deferred companions remain non-stale | Receiving page with partial current authority | `route.impact.refreshFail` | Preserve current page focus only if FF-1-valid; otherwise use PF-1 | None until CA-M4 admits ET-19d |
| ET-19d — page-owned failed-subset Retry | ET-19c + exact acquired failed subset + CA-M4 admission | Start AR-M4 for exactly that subset; an Agents-only Retry leaves companions deferred until its success dispatches mode | Keep evidence/current members; CA-M3 owns focus transfer plus Retry busy/inert admission | Same receiving page, retry pending | Existing stale line | CA-M3 handoff | One AR-M successor generation for the acquired failed subset; successful Agents activates/acquires applicable companions once |
-| ET-20 — committed Done-equivalent exit | Mounted report, reconciling, refreshed or stale phase + exact commit evidence | Done, title-close, Escape and outside send no mutation/read | Close modal and transfer any active AR-M generation/evidence; never restore origin | Receiving page with exact installed successes plus markers only for acquired pending/stale members; deferred companions stay unrendered until their prerequisite activates them | Held evidence plus the registered pending/stale marker as applicable | PF-1 after modal Done unmounts, over the exact installed page | Transferred AR-M if active; otherwise none, or later CA-M4/ET-19d after failure |
+| ET-20 — page-owned committed settlement | Page-owned reconciling, refreshed or stale phase + exact commit evidence | No modal action is emitted; M6 settles the active generation and preserves the exact evidence | Keep page ownership; never restore the origin or create a second dialog | Receiving page with exact installed successes plus markers only for acquired pending/stale members; deferred companions stay unrendered until their prerequisite activates them | Held evidence plus the registered pending/stale marker as applicable | Preserve current FF-1-valid focus after each install and at final settlement; use PF-1 only if it disappears; clear the pending landing target after the final decision | Transferred AR-M if active; otherwise none, or later CA-M4/ET-19d after failure |
| AS-1 — AR-D2 Direct install | AR-D2 + exact AgentSupply `mode: direct` | LF-D installs that exact Direct row before any Source/chain read | Settle the Agents member and close modal. Preserve attempt settlement/observation, change owner to page session and legality to Direct-suspended; retain generation/pairs/stage exactly when settlement is unknown | Actual Direct page; an unknown attempt remains page-session-owned and suspended | Exact Direct projection; mode makes no Route claim | PF-1 because the modal target unmounts | No read while Direct; any later LF-H post-Source hook re-evaluates RO-O from axes, not producer |
| AS-2 — AR-D3 Hub install | AR-D3 + exact Hub AgentSupply | LF-H installs that exact Hub row as the latest reversible page authority, establishes CF-H for Sources and deliberately does not consume AP-2 for commit comparison | Clear only Agents-member pending; retain generation/modal/draft/stage and CA-D2 admission | Originating failure over actual Hub page | Existing failure copy | Preserve CA-D2's FF-1-valid owner | ET-17a acquires the post-CF-H Source generation and exact-chain read in the same workflow generation |
| AS-3 — reversible error-handoff Direct dispatch | ET-18a/ET-18c + exact AgentSupply `mode: direct` | LF-D installs that exact Direct row and keeps every successful independent Source authority already carried | Clear page-read pending and stale Hub row; retain RO settlement/observation/owner and set legality Direct-suspended | Actual Direct page | Exact Direct projection | Preserve an FF-1-valid page target or use PF-1 | No companion read; an M6 landing read dispatches through AS-5a/AS-5b instead |
| AS-4 — reversible error-handoff Hub dispatch | ET-18a/ET-18c + exact AgentSupply `mode: hub` | LF-H installs that exact Hub row, keeps successful independent authority and starts M5's Source read; never resurrect the editor | Clear Agents pending; retain the old Source list explicitly stale until M5 settles and retain all RO axes/evidence | Actual Hub page with Sources pending/stale until LF-H closes | Exact Hub projection plus `upstream.unread` only after Source failure | Preserve an FF-1-valid page target or use PF-1 | M5 Source success invokes the common LF-H post-Source hook; M6 landing uses AS-6a/AS-6b instead |
-| AS-5a — mounted AR-M Direct install | Mounted evidence + current successful M6 AgentSupply `mode: direct`, whether it supplied AR-MD or answered ET-18aM | Dispatch mode immediately, install the exact current Direct page behind the modal, activate Source when it was deferred and make all Route-chain members not applicable | Retain modal/evidence and acquired Source/Agents state; cancel/disown pending Route reads and remove their failed/pending slots from stale/Retry | Same mounted report/committed phase over actual Direct page | Registered report/refresh/stale block only for acquired applicable members | Keep FF-1-valid `route.impact.done` | AR-M acquires/continues activated pending members, or CA admits only an acquired failed subset after settlement |
+| AS-5a — page-owned AR-M Direct install | Page-owned evidence + current successful M6 AgentSupply `mode: direct`, whether it supplied AR-MD or answered ET-18aM | Dispatch mode immediately, install the exact current Direct page, activate Source when it was deferred and make all Route-chain members not applicable | Retain evidence and acquired Source/Agents state; cancel/disown pending Route reads and remove their failed/pending slots from stale/Retry | Actual Direct page | Registered acquired pending/stale block only for applicable members | Reapply PF-1 after installation | AR-M acquires/continues activated pending members, or CA admits only an acquired failed subset after settlement |
| AS-5b — transferred AR-M Direct install | Transferred AR-M + current successful M6 AgentSupply `mode: direct`, whether it supplied AR-MD or answered ET-18aP | Dispatch mode immediately, install the exact current Direct page, activate Source when it was deferred and make all Route-chain members not applicable | Retain evidence and acquired Source/Agents state; cancel/disown pending Route reads and remove their failed/pending slots from stale/Retry | Actual Direct page with exact acquired pending/stale markers | Exact Direct projection plus registered acquired pending/stale block | Preserve the current active page target only if FF-1-valid; otherwise PF-1 | AR-M acquires/continues activated pending members, or CA admits only an acquired failed subset after settlement |
-| AS-6a — mounted AR-M Hub install | Mounted evidence + successful M6 AgentSupply `mode: hub`, including the landing read after chain Direct | Dispatch mode immediately, install the exact Hub page behind the modal, activate Source/Route companions and establish CF-H for Sources; the payload self-satisfies Agents | Retain modal/evidence and independent authority. Acquire one Source successor unless its generation was acquired after this exact landing. Activate the held self-satisfying commit chain without a read; only a chain-Direct handoff with no exact Hub chain authority acquires one newly applicable chain epoch | Same mounted report/committed phase over actual Hub page | Registered report/refresh/stale block for acquired AR-M members | Keep FF-1-valid `route.impact.done` | AR-M continues every acquired member missing its required frontier, including Sources and any newly acquired chain, or CA admits an acquired failed subset after settlement |
+| AS-6a — page-owned AR-M Hub install | Page-owned evidence + successful M6 AgentSupply `mode: hub`, including the landing read after chain Direct | Dispatch mode immediately, install the exact Hub page, activate Source/Route companions and establish CF-H for Sources; the payload self-satisfies Agents | Retain evidence and independent authority. Acquire one Source successor unless its generation was acquired after this exact landing. Activate the held self-satisfying commit chain without a read; only a chain-Direct handoff with no exact Hub chain authority acquires one newly applicable chain epoch | Actual Hub page | Registered acquired pending/stale block for AR-M members | Reapply PF-1 after installation | AR-M continues every acquired member missing its required frontier, including Sources and any newly acquired chain, or CA admits an acquired failed subset after settlement |
| AS-6b — transferred AR-M Hub install | Transferred AR-M + successful M6 AgentSupply `mode: hub`, including the landing read after chain Direct | Dispatch mode immediately, install the exact Hub page, activate Source/Route companions and establish CF-H for Sources; the payload self-satisfies Agents | Retain evidence and independent authority. Acquire one Source successor unless its generation was acquired after this exact landing. Activate the held self-satisfying commit chain without a read; only a chain-Direct handoff with no exact Hub chain authority acquires one newly applicable chain epoch | Actual Hub page with exact acquired pending/stale markers | Exact Hub projection plus registered acquired pending/stale block | Preserve the current active page target only if FF-1-valid; otherwise PF-1 | AR-M continues every acquired member missing its required frontier, including Sources and any newly acquired chain, or CA admits an acquired failed subset after settlement |
**Frame-02 control × state totality** `[frame]` `[derived]`. This is the exhaustive static
@@ -2580,9 +2614,9 @@ products select no enabled CA-D row:
| CA-D5 | Source-only reconciliation Retry | **Source-only idle**: attempt `unknown` + `nonmatching@epoch` + failed Source and no member is pending | Rendered, enabled | None while admitted | Emit ET-17g for Sources only |
| CA-D6 | Source-only reconciliation Retry | **Source-only busy**: ET-17g's Source successor is active while attempt remains `unknown` and the nonmatching observation stays installed | Rendered busy, disabled/inert | If Retry is active, move first to enabled Cancel, otherwise enabled title-close, before changing admission | None; cannot reread Agents/chain or overlap a Source generation |
| CA-D7 | Post-nonmatch exact-read Retry | **Post-nonmatch read idle**: attempt `unknown` + installed `nonmatching@epoch` + frontier-satisfying Source success, with no read pending | Rendered, enabled | None while admitted | Emit ET-17d and acquire one newer exact-chain GET; no activation in this workflow can send PUT |
-| CA-M1 | Mounted M6 Retry | An acquired AR-M member is pending, AR-M4 Retry is pending, or AR-M2 succeeded; deferred companions alone never make Retry busy | Absent; if layout reserves it, disabled/inert | If Retry is active, move first to enabled `route.impact.done`, otherwise its enabled title-close, before changing admission | None |
-| CA-M2 | Mounted M6 Retry | Settled ET-19a / AR-M3 exact acquired failed subset, including Agents-only with companions deferred | Rendered, enabled | None while admitted | Emit ET-19b for exactly the held acquired failed subset |
-| CA-M3 | Page M6 Retry | An acquired transferred AR-M member is pending, AR-M4 Retry is pending, or AR-M2 succeeded; deferred companions alone never make Retry busy | Absent; if layout reserves it, disabled/inert | If Retry is active, move first to the receiving page's registered FF-1-valid fallback before changing admission | None |
+| CA-M1 | Page-owned M6 Retry | An acquired AR-M member is pending, AR-M4 Retry is pending, or AR-M2 succeeded; deferred companions alone never make Retry busy | Absent; if layout reserves it, disabled/inert | Preserve the receiving page's FF-1-valid focus before changing admission | None |
+| CA-M2 | Page-owned M6 Retry | Settled ET-19a / AR-M3 exact acquired failed subset, including Agents-only with companions deferred | Rendered and enabled on the affected page projection | None while admitted | Emit ET-19b for exactly the held acquired failed subset |
+| CA-M3 | Page M6 Retry | An acquired transferred AR-M member is pending, AR-M4 Retry is pending, or AR-M2 succeeded; deferred companions alone never make Retry busy | Absent; if layout reserves it, disabled/inert | Preserve the receiving page's registered FF-1-valid fallback before changing admission | None |
| CA-M4 | Page M6 Retry | Settled ET-19c / AR-M3 exact acquired failed subset, including Agents-only with companions deferred | Rendered, enabled | None while admitted | Emit ET-19d for exactly the held acquired failed subset |
| CA-P1 | Error-handoff page Retry | ET-18b settled landing-Agents read failure | Rendered, enabled | None while admitted | Emit ET-18c and acquire one landing-Agents successor |
| CA-P2 | Error-handoff page Retry | Initial or ET-18c landing-Agents read pending | Rendered busy, disabled/inert | If Retry is active, move first to the page's registered FF-1-valid fallback before changing admission | None |
@@ -2613,9 +2647,8 @@ products select no enabled CA-D row:
| Route save rejected | 取消 button / title-bar close | `route.cancel` | Enabled whenever no new PUT is owned | Distinct Tab stops; activation emits ET-8a |
| Route save outcome unresolved | 重试 | `route.retry` | CA-D1–D7's positive phase partition is the sole owner. Each enabled row issues only its registered read; busy phases are disabled/inert and no phase emits PUT | First command in Tab order only when enabled; activation delegates to the current CA-D row |
| Route save outcome unresolved with attempt `unknown` | 取消 button / title-bar close | `route.cancel` | Enabled whenever no read response is being synchronously installed; an owned read may be disowned | Distinct Tab stops; activation emits ET-8b and abandons the old workflow |
-| Route committed, reconciling / refreshed / Route impact reported / mounted AR-M stale | 完成 | `route.impact.done` | Enabled before, during and after AR-M settlement | First command in Tab order; activation emits ET-20 |
-| Route committed, reconciling / refreshed / Route impact reported / mounted AR-M stale | Title-bar close | `route.impact.done` | Enabled before, during and after AR-M settlement | Independent Tab stop; activation emits ET-20 |
-| Route impact reported / report-free stale | 重试 | `route.retry` | CA-M2 renders/enables it only after ET-19a settles an acquired failed subset, including Agents alone while companions are deferred; CA-M1 makes it absent/inert during acquired pending/retry and after success | Normal Tab order only when enabled; activation delegates to the current CA row |
+| Route committed, reconciling / refreshed / page-owned AR-M stale | No modal control | `common.saved` / existing page retry copy | The editor is already closed; only the receiving page renders pending/stale state | Preserve the current FF-1-valid focus during installs/settlement; use PF-1 only when it disappears or becomes ineligible |
+| Route report-free stale | 重试 | `route.retry` | CA-M2 renders/enables it only after ET-19a settles an acquired failed subset, including Agents alone while companions are deferred; CA-M1 makes it absent/inert during acquired pending/retry and after success | Page Tab order only when enabled; activation delegates to the current CA row |
| Receiving page with transferred stale subset | 重试 | `route.retry` | CA-M4 renders/enables it only after ET-19c settles an acquired failed subset, including Agents alone while companions are deferred; CA-M3 makes it absent/inert during acquired pending/retry and after success | Page Tab order only when enabled; activation delegates to the current CA row |
**Dismissal is closed by `commit class × modal owner × busy ownership`** `[derived]`.
@@ -2632,7 +2665,7 @@ more-specific ET-5b/ET-7e edge before this matrix.
| `unknown`, including matching read pending, nonmatching/read-failed observation, Source pending/failed/retrying | Mounted editor | None or disownable AR-D read generation | ET-8b | ET-8b | ET-8b | ET-8b |
| Refused guarded plan | Mounted guard | No request | ET-13a | ET-13a | ET-13a | ET-13a |
| Mutation request in flight: Saving | Mounted editor | Non-cancellable PUT response | Inert / absent | Inert / absent | Inert | Inert |
-| `committed`: reconciling / report / mounted stale | Mounted report/committed modal | None or transferable AR-M read generation | ET-20 Done-equivalent | ET-20 | ET-20 | ET-20 |
+| `committed`: page-owned reconciling / stale | No route modal; the receiving page owns M6 | None or transferable AR-M read generation | No route dismissal edge | No route dismissal edge | No route dismissal edge | No route dismissal edge |
**Keyboard event register** `[derived]`. Focus remains trapped while the modal is mounted;
the static table above defines which controls participate. This table defines emitted key
@@ -2651,7 +2684,7 @@ focus:
| `Enter` / `Space` on 添加一跳 / selector confirmation | ET-5a opens / ET-5c appends |
| `Enter` / `Space` on 保存 | ET-9a; Enter never submits implicitly from a row/selector |
| `Enter` / `Space` on 重试 | Route unread (not CA-covered) → ET-4. Every CA-covered Retry delegates to its one row: when enabled, pointer/Enter/Space all emit that row's `Activation`; when disabled/inert, all emit nothing |
-| `Enter` / `Space` on guard primary / 完成 | ET-13b / ET-20 |
+| `Enter` / `Space` on guard primary | ET-13b |
Ordinals renumber contiguously after ET-6a/ET-6b/ET-7c. Grab state and every new position use the
same `aria-grabbed` + live-region treatment as §1.3. No prose in this register may add a
@@ -2696,7 +2729,7 @@ shared `models.hub.guard.*` owner.
| `impact.title` `[derived]` `[contract]` | 路由链已保存 | The route chain was saved |
| `impact.detail` `[derived]` `[contract]` | 以下是这次保存实际移除或中断的项目。 | These are the items this save actually removed or interrupted. |
| `impact.refreshFail` `[derived]` | 路由链已保存,但模型页面暂时无法刷新。 | The route chain was saved, but the model surface could not be refreshed. |
-| `impact.done` `[derived]` | 完成 | Done |
+| `impact.done` `[legacy/unrendered]` | 保存成功后不显示 | Retained for compatibility; not rendered after a successful route save |
| Key under `models.hub.guard.*` | 中文 | English |
| --- | --- | --- |
diff --git a/docs/plans/route-save-toast-delivery.md b/docs/plans/route-save-toast-delivery.md
new file mode 100644
index 000000000..6c4cf1131
--- /dev/null
+++ b/docs/plans/route-save-toast-delivery.md
@@ -0,0 +1,171 @@
+# Route save toast: reconciliation scope decision
+
+## Review inventory
+
+The delivery owner inspected all 17 review threads, including resolved and
+outdated threads, and the current diff and consuming tests before continuing
+from `b86dce2b7`.
+
+| Findings-bearing head | Root-cause classes |
+| --- | --- |
+| `aa80bc4ecd` | Browser-test and specification alignment; success announcement; post-install focus |
+| `e3e0ad7a2c` | Focus ownership/lifetime; coalesced toast lifetime |
+| `69347353a1` | Focus ownership/lifetime; remaining modal specification; commit-evidence lifetime |
+| `36bac711dd` | Commit-evidence lifetime across consecutive saves |
+| `45a049bb5c` | Inferred-commit focus ownership; failed reconciliation blocking subsequent saves; Retry admission |
+| `31043043a1` | Retained reconciliation failure hidden by a later unrelated region refresh |
+| `b86dce2b7a` | Successful member settlement published too late; queued commit excluded from focus ownership |
+
+There are seven findings-bearing heads without a clean pass. Focus and evidence
+ownership recur across heads, so the review-loop circuit breaker applies.
+Passing CI on `45a049bb5c` does not close the review gate.
+
+## Diagnosis and bounded decision
+
+The editor is no longer the lifetime owner after commit. The page must retain
+each exact response and its original focus context independently of the next
+editor. Likewise, waiting for a failed read to be retried cannot occupy the
+single in-flight collection-read slot indefinitely.
+
+Keep page-owned reconciliation and the existing collection authorities. Serialize
+in-flight reads, but carry failed reports into the next new commit's collection
+refresh. Those later Agents/Sources reads are acquired after both commit frontiers
+and can settle both reports without reconstructing either response tail. A report
+committed during an in-flight read waits for a subsequent read, not the older one.
+Retry still reads only the failed subset and its newly enabled dependants.
+
+Retain the original opener with the suspended attempt, then pass it explicitly
+when commit is inferred. Use the committed chain's backend/model identity for
+fallback, never the currently open editor. Move focus before disabling a page
+Retry and keep its handler owned by reconciliation while busy.
+
+An independent local review identified the same admission issue on an automatic
+start: a suspended commit can be inferred while the user focuses another
+commit's failed Retry. The owner reproduced it in the consuming page test.
+Focus handoff therefore belongs at every M6 pending transition, not just the
+Retry click handler. Only the registered focused Retry is moved; other valid
+user focus remains untouched.
+The independent re-review of that correction found no further actionable defect.
+
+This is a reversible UI-lifecycle correction. It changes neither API contracts,
+mutation admission nor the requested immediate close with the shared saved toast.
+Do not introduce a second failure stack or resurrect stale failure banners after
+a newer M6 collection has settled those obligations successfully.
+
+## Cross-refresh visibility decision
+
+The sixth reviewed head exposed a rendering boundary, not a missing retry in the
+queue. The M6 obligation and the latest region observation have different
+lifetimes: a Source echo, presence refresh, or another mutation's full read may
+replace a region with ready data without settling the retained route report.
+The shared card rendered only the region's failure and could hide the sole M6
+Retry while its backend remained excluded from chain probes.
+
+Keep the underlying authoritative region reads unchanged. Compose the retained
+M6 failed subset into the reads used to select the page form and render its
+Sources/Gateway cards, reusing the existing stale-data and Retry surfaces. This
+keeps newly read data visible and Retry available even after an unrelated ready
+or refreshing projection; it does not certify an entity echo as a full,
+frontier-satisfying collection read. Include the direct/empty page-form edge so
+it cannot hide the failure surface either. Only M6 settlement clears its failure
+and releases the held reports and chain-probe exclusion.
+
+Integrate upstream source-toast PR #2121 without restoring either success
+modal. Preserve its per-chain read ownership and Source-dialog return focus
+while retaining this PR's per-report reconciliation and route focus ownership.
+The two merge conflicts are in the page and workflow specification; the scope
+remains a reversible UI correction with unchanged mutation/API contracts.
+
+## Member settlement and queued focus decision
+
+The seventh reviewed head exposes two remaining publication boundaries. The
+reader already installs Agents before acquiring Sources, but its failure
+snapshot is published only at batch completion. The receiving page therefore
+keeps a cleared failure visible until an independent request finishes. Publish
+the removal of an acquired Agents failure immediately after its successful
+installation; keep the batch pending, other failures and held reports intact.
+
+The published single report is used for focus, whereas the report list is used
+for batch settlement and cleanup. Their lifetimes are not identical: save B
+becomes the latest focus owner immediately, even while its reads wait for A.
+Publish the newest outstanding report, including the queued tail, as the focus
+identity. Keep the batch's report list unchanged so A cannot settle or release
+B's evidence. Both asynchronous refocus and pre-disable Retry handoff already
+consume this identity; preserve valid user-moved focus in either case.
+
+The owner verified these consumers and the existing queued-report and page
+focus tests before choosing this scope. Neither finding requires new queue
+state, a second focus registry, or changed API/mutation contracts. Regressions
+must inspect the intermediate Agents-success/Sources-pending state and the
+older-install/newer-opener-removal state, not only final batch completion.
+
+Independent review found one more boundary in the same focus class: the page
+captured that identity before scheduling an animation frame. A newer inferred
+commit between installation and frame execution could still focus the older
+route, after which preservation of valid focus made the mistake permanent.
+The owner reproduced that exact interleaving in a consuming-page test. Resolve
+the identity and opener again when the frame executes, without merely skipping
+the old callback: the newer batch may still be waiting. Retain the captured
+opener only for the same report after its settlement cleanup, and continue
+preserving valid user-moved focus. This extends the same bounded publication
+fix to its final consumer; report settlement and read ownership remain unchanged.
+
+## Validation contract
+
+Run tests and builds from the task worktree's `ui/`, not the control checkout.
+Cover both Agents and Sources failures, new commits arriving before and after a
+failure, repeated Retry activation, exact response-tail retention, and suspended
+inference with another editor open. Existing focus-preservation and automatic
+close browser scenarios must continue to pass.
+
+## Local verification at `31043043a`
+
+- The affected Model Hub and shared toast suite passes all 1,439 tests across
+ 85 files with two workers. An initial higher-concurrency run timed out in one
+ unchanged API-key validation test; its isolated file and the complete rerun
+ both passed without changing the test or its timeout.
+- All 150 model-catalog browser cases pass, including desktop/mobile,
+ English/Chinese, and the automatic route-dialog close flows.
+- The production build, test type checks, lint-baseline gate, and whitespace
+ checks pass from this task worktree.
+- Local checks do not replace the new exact-head CI and automatic review gates.
+
+## Local verification after the cross-refresh fix and base integration
+
+- All four consuming-page regressions fail without the display composition and
+ pass with it: Agents/Sources failure crossed with normal/direct-empty landings.
+ They cover the intermediate Source echo, newly observed data, failed-subset
+ Retry, one route PUT, and release of the retained backend's chain probes.
+- The affected Model Hub, shared toast, and settings layout suite passes all
+ 1,494 tests across 85 files with two workers. The four regressions also pass
+ after adding the intermediate echo assertion.
+- All 150 model-catalog and eight model-provider browser cases pass.
+- The production build, test type checks, lint-baseline gate, and whitespace
+ checks pass from this task worktree.
+- Independent read-only review compared the integrated tree against both
+ parents and found no actionable defect or semantic merge regression. It
+ confirmed M6 ownership and focus behavior, the direct-empty branch, and
+ preservation of the upstream Source toast and per-chain read authority.
+- The new pushed head still requires its own Actions and automatic review;
+ prior-head results and local verification do not close those gates.
+
+## Local verification after the member/focus publication fix
+
+- Four new regression cases fail against the previous production code: two
+ intermediate Agents-recovery cases with and without an older Sources failure,
+ immediate Direct landing while Sources is pending, and a queued save losing
+ its opener to the older read. The user-moved-focus control passes unchanged.
+- The added same-frame inferred-commit regression also fails before frame-time
+ identity lookup and passes after it; its user-moved-focus control passes in
+ both versions. All seven added cases pass with the complete fix.
+ The existing queue test also confirms
+ that the newest queued focus identity does not enter the older batch's
+ settlement/cleanup report list.
+- All 96 targeted reconciliation/page/focus tests and the full 1,501-test
+ Model Hub/toast/settings-layout suite (85 files, two workers) pass.
+- All 150 model-catalog desktop/mobile browser cases pass. Production build,
+ test type checks, lint-baseline gate and whitespace checks pass from this
+ task worktree.
+- Independent review of the complete six-file increment found no further
+ actionable defect and separately passed 36 focused tests, including both
+ frame-execution regressions. No queue or API redesign is needed.
diff --git a/ui/e2e/model-catalog/route-direct-edit.spec.ts b/ui/e2e/model-catalog/route-direct-edit.spec.ts
index 25f75a216..11800f4cd 100644
--- a/ui/e2e/model-catalog/route-direct-edit.spec.ts
+++ b/ui/e2e/model-catalog/route-direct-edit.spec.ts
@@ -59,7 +59,6 @@ for (const backend of ['claude', 'codex', 'opencode']) {
method: 'PUT',
hops: [{ source_id: 'src_a', model_id: 'exact/model-中文' }, { source_id: 'src_b', model_id: 'gpt-test' }],
}]);
- await foot.getByRole('button', { name: copy('routeDialog.impact.done'), exact: true }).click();
await expect(dialog).toHaveCount(0);
expect(apiRequests).toEqual([]);
});
diff --git a/ui/e2e/model-routing-origin.spec.ts b/ui/e2e/model-routing-origin.spec.ts
index dbfd3e995..878c4515e 100644
--- a/ui/e2e/model-routing-origin.spec.ts
+++ b/ui/e2e/model-routing-origin.spec.ts
@@ -114,9 +114,6 @@ test('MH-ROUTING-007 restore, undo, cancel, and save preserve explicit route int
await expect.poll(async () => (await api.agentChain(gateway.backend, gateway.model)).manual_override).toBeNull();
expect(identities(await api.agentChain(gateway.backend, gateway.model))).toEqual(identities(inherited));
expect(mutations).toEqual(['DELETE', 'DELETE']);
- const done = labelledButton(dialog, copy('routeDialog.impact.done'));
- await expect(done).toBeEnabled();
- await done.click();
await expect(dialog).toHaveCount(0);
await page.reload();
const reloaded = await api.agentChain(gateway.backend, gateway.model);
diff --git a/ui/src/components/settings/models/GatewayModule.test.tsx b/ui/src/components/settings/models/GatewayModule.test.tsx
index df075b860..8885cd1c9 100644
--- a/ui/src/components/settings/models/GatewayModule.test.tsx
+++ b/ui/src/components/settings/models/GatewayModule.test.tsx
@@ -84,4 +84,31 @@ describe('GatewayModule region failure treatment', () => {
await userEvent.click(screen.getByRole('button', { name: /^Retry$|^重试$/i }));
expect(onRetry).toHaveBeenCalledOnce();
});
+
+ it('disables the page retry while route reconciliation is pending', () => {
+ render(
+ <I18nextProvider i18n={i18n}>
+ <GatewayModule
+ supply={failRegionRead(readyRegion([agent]))}
+ retryDisabled
+ onRetry={vi.fn()}
+ runtime={null}
+ runtimeSnapshot={null}
+ sources={[]}
+ chains={{}}
+ pendingBackends={new Set()}
+ switchFailures={new Set()}
+ connectingBackend={null}
+ onConnectHub={vi.fn()}
+ onSwitchDirect={vi.fn()}
+ onOpenModels={vi.fn()}
+ onOpenOrder={vi.fn()}
+ onOpenRoute={vi.fn()}
+ onProbeSettled={vi.fn()}
+ />
+ </I18nextProvider>,
+ );
+
+ expect((screen.getByRole('button', { name: /^Retry$|^重试$/i }) as HTMLButtonElement).disabled).toBe(true);
+ });
});
diff --git a/ui/src/components/settings/models/GatewayModule.tsx b/ui/src/components/settings/models/GatewayModule.tsx
index 257d32ea6..ee3d03994 100644
--- a/ui/src/components/settings/models/GatewayModule.tsx
+++ b/ui/src/components/settings/models/GatewayModule.tsx
@@ -14,10 +14,12 @@ type GatewayModuleProps = Omit<React.ComponentProps<typeof AgentCard>, 'agents'>
runtime: FreshRuntimeProjection | null;
runtimeSnapshot: RuntimeDependency | null;
onRetry: () => void;
+ retryDisabled?: boolean;
+ retryRef?: React.Ref<HTMLButtonElement>;
readFailureCopy?: string;
};
-export const GatewayModule: React.FC<GatewayModuleProps> = ({ runtime, runtimeSnapshot, supply, onRetry, readFailureCopy, ...props }) => {
+export const GatewayModule: React.FC<GatewayModuleProps> = ({ runtime, runtimeSnapshot, supply, onRetry, retryDisabled = false, retryRef, readFailureCopy, ...props }) => {
const { t } = useTranslation();
const agents = foldRegionRead<AgentSupply[], AgentSupply[] | undefined>(supply, {
loading: () => undefined,
@@ -39,9 +41,9 @@ export const GatewayModule: React.FC<GatewayModuleProps> = ({ runtime, runtimeSn
{supply.kind === 'loading' && agents === undefined
? <div className="flex h-full min-h-36 items-center justify-center"><LoaderCircle className="size-4 animate-spin text-muted" /></div>
: supply.kind === 'unread'
- ? <div className="flex h-full min-h-36 flex-col items-center justify-center gap-3 px-4 text-center"><p className="text-[12px] text-muted">{t('settings.models.gateway.supply.unread')}</p><Button variant="outline" size="xs" onClick={onRetry}>{t('settings.models.gateway.retry')}</Button></div>
+ ? <div className="flex h-full min-h-36 flex-col items-center justify-center gap-3 px-4 text-center"><p className="text-[12px] text-muted">{t('settings.models.gateway.supply.unread')}</p><Button ref={retryRef} variant="outline" size="xs" disabled={retryDisabled} onClick={onRetry}>{t('settings.models.gateway.retry')}</Button></div>
: <>
- {supply.kind === 'degraded' && supply.cause === 'read_failed' && <div className="mb-2 flex items-center justify-between gap-3 rounded-lg border border-destructive/25 bg-destructive/[0.08] px-3 py-2"><p className="text-[11px] text-destructive-ink">{readFailureCopy ?? t('settings.models.gateway.supply.unread')}</p><Button variant="outline" size="xs" onClick={onRetry}>{t('settings.models.gateway.retry')}</Button></div>}
+ {supply.kind === 'degraded' && supply.cause === 'read_failed' && <div className="mb-2 flex items-center justify-between gap-3 rounded-lg border border-destructive/25 bg-destructive/[0.08] px-3 py-2"><p className="text-[11px] text-destructive-ink">{readFailureCopy ?? t('settings.models.gateway.supply.unread')}</p><Button ref={retryRef} variant="outline" size="xs" disabled={retryDisabled} onClick={onRetry}>{t('settings.models.gateway.retry')}</Button></div>}
<AgentCard agents={agents ?? []} runtime={runtime} {...props} />
</>}
</div>
diff --git a/ui/src/components/settings/models/RouteChainDialog.test.tsx b/ui/src/components/settings/models/RouteChainDialog.test.tsx
index ffb716a75..69a696177 100644
--- a/ui/src/components/settings/models/RouteChainDialog.test.tsx
+++ b/ui/src/components/settings/models/RouteChainDialog.test.tsx
@@ -453,7 +453,7 @@ describe("RouteChainDialog", () => {
expect(chain.manual_override?.hops).toHaveLength(2);
});
- it('clears to no-key Unconfigured, confirms the exact DELETE guard and shows actual impact then Done', async () => {
+ it('clears to no-key Unconfigured, confirms the exact DELETE guard and closes after saving', async () => {
const user = userEvent.setup();
const gap = { backend: 'claude' as const, model_id: 'opus-5', agents: ['writer'] };
const hop = { backend: 'claude' as const, menu_model: 'opus-5', ...chain.manual_override!.hops[0], position: 1 };
@@ -464,16 +464,17 @@ describe("RouteChainDialog", () => {
const put = vi.spyOn(modelsApi, 'putAgentChain');
const committed = vi.fn();
vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(chain);
+ const close = vi.fn();
render(<I18nextProvider i18n={i18n}><RouteChainDialog
selection={{ agent: { ...agent, sources: { order: [], eligibility: [] } }, modelId: 'opus-5', read: readyRegion(chain) }}
- sources={[]} onClose={vi.fn()} onCommitted={committed} readAgents={vi.fn()} readSources={vi.fn()}
+ sources={[]} onClose={close} onCommitted={committed} readAgents={vi.fn()} readSources={vi.fn()}
/></I18nextProvider>);
await clear(user);
await screen.findByText('After restore: unconfigured');
expect(restore).not.toHaveBeenCalled();
await user.click(screen.getByRole('button', { name: 'Save' }));
await user.click(await screen.findByRole('button', { name: 'Save anyway' }));
- await within(document.querySelector<HTMLElement>('.model-hub-route-foot')!).findByRole('button', { name: 'Done' });
+ await waitFor(() => expect(close).toHaveBeenCalledOnce());
expect(restore.mock.calls).toEqual([
['claude', 'opus-5', undefined],
['claude', 'opus-5', { force: true, would_remove_hops: [hop], would_interrupt: [gap] }],
@@ -744,10 +745,11 @@ describe("RouteChainDialog", () => {
it("saves the changed ordered hop array and consumes the response envelope", async () => {
const user = userEvent.setup();
const onCommitted = vi.fn();
+ const onClose = vi.fn();
const put = vi
.spyOn(modelsApi, "putAgentChain")
.mockResolvedValue(mutation());
- renderDialog(onCommitted);
+ renderDialog(onCommitted, onClose);
await screen.findAllByRole("button", { name: "Remove hop" });
await user.click(screen.getAllByRole("button", { name: "Remove hop" })[0]);
@@ -763,7 +765,7 @@ describe("RouteChainDialog", () => {
removed_hops: [],
interrupted: [],
});
- expect(screen.getByText("Done").closest("button")).toBeTruthy();
+ expect(onClose).toHaveBeenCalledOnce();
});
it("MH-ROUTE-EDIT-001 replaces one hop in place and saves the exact order", async () => {
@@ -811,8 +813,9 @@ describe("RouteChainDialog", () => {
);
});
- it("renders the complete removed-hop impact after a successful save", async () => {
+ it("closes through the owner after a successful save with impact", async () => {
const user = userEvent.setup();
+ const onClose = vi.fn();
const removed = {
backend: "claude" as const,
menu_model: "opus-5",
@@ -823,85 +826,13 @@ describe("RouteChainDialog", () => {
vi.spyOn(modelsApi, "putAgentChain").mockResolvedValue(
mutation(chain, { removed_hops: [removed] }),
);
- renderDialog();
+ renderDialog(vi.fn(), onClose);
await screen.findAllByRole("button", { name: "Remove hop" });
await user.click(screen.getAllByRole("button", { name: "Remove hop" })[0]);
await user.click(screen.getByRole("button", { name: "Save" }));
- expect(await screen.findByText("Claude Code · opus-5")).toBeTruthy();
- expect(screen.getByText("claude-opus-5 · Order #1")).toBeTruthy();
- });
-
- it("keeps Done available while page-owned M6 is pending and failed", async () => {
- const user = userEvent.setup();
- const removed = {
- backend: "claude" as const,
- menu_model: "opus-5",
- source_id: "src_a",
- model_id: "claude-opus-5",
- position: 1,
- };
- const put = vi
- .spyOn(modelsApi, "putAgentChain")
- .mockResolvedValue(mutation(chain, { removed_hops: [removed] }));
- const onCommitted = vi.fn();
- const retry = vi.fn();
- vi.spyOn(modelsApi, "getAgentChain").mockResolvedValue(chain);
- const page = render(
- <I18nextProvider i18n={i18n}>
- <RouteChainDialog
- selection={{ agent, modelId: "opus-5", read: readyRegion(chain) }}
- sources={sources}
- onClose={vi.fn()}
- onCommitted={onCommitted}
- commitReconciliation={{ pending: true, failed: false, retry }}
- readAgents={vi.fn().mockResolvedValue(observation([agent]))}
- readSources={vi.fn().mockResolvedValue(observation(sources))}
- />
- </I18nextProvider>,
- );
- await screen.findAllByRole("button", { name: "Remove hop" });
- await user.click(screen.getAllByRole("button", { name: "Remove hop" })[0]);
- await user.click(screen.getByRole("button", { name: "Save" }));
-
- await waitFor(() => expect(put).toHaveBeenCalledTimes(1));
- expect(
- await screen.findByText(
- "Route chain saved. Refreshing the model surface…",
- ),
- ).toBeTruthy();
- expect(
- screen.getByText(
- "These are the items this save actually removed or interrupted.",
- ),
- ).toBeTruthy();
- expect(screen.getByText("Done").closest("button")).toBeTruthy();
- page.rerender(
- <I18nextProvider i18n={i18n}>
- <RouteChainDialog
- selection={{ agent, modelId: "opus-5", read: readyRegion(chain) }}
- sources={sources}
- onClose={vi.fn()}
- onCommitted={onCommitted}
- commitReconciliation={{ pending: false, failed: true, retry }}
- readAgents={vi.fn().mockResolvedValue(observation([agent]))}
- readSources={vi.fn().mockResolvedValue(observation(sources))}
- />
- </I18nextProvider>,
- );
- expect(
- await screen.findByText(
- "The route chain was saved, but the model surface could not be refreshed.",
- ),
- ).toBeTruthy();
- expect(
- screen.getByText(
- "These are the items this save actually removed or interrupted.",
- ),
- ).toBeTruthy();
- await user.click(screen.getByRole("button", { name: "Retry" }));
- expect(retry).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
});
it("echoes the exact refusal plan on a forced confirmation", async () => {
@@ -981,7 +912,8 @@ describe("RouteChainDialog", () => {
const put = vi
.spyOn(modelsApi, "putAgentChain")
.mockRejectedValueOnce(new TypeError("response lost"));
- renderDialog();
+ const onClose = vi.fn();
+ renderDialog(vi.fn(), onClose);
await screen.findAllByRole("button", { name: "Remove hop" });
await user.click(screen.getAllByRole("button", { name: "Remove hop" })[0]);
@@ -990,7 +922,7 @@ describe("RouteChainDialog", () => {
await waitFor(() => expect(read).toHaveBeenCalledWith("claude", "opus-5"));
expect(put).toHaveBeenCalledTimes(1);
- expect(screen.getByText("Done").closest("button")).toBeTruthy();
+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
});
it("installs a nonmatching D-36 observation without treating it as a retryable write", async () => {
diff --git a/ui/src/components/settings/models/RouteChainDialog.tsx b/ui/src/components/settings/models/RouteChainDialog.tsx
index ce31ef970..e00dded41 100644
--- a/ui/src/components/settings/models/RouteChainDialog.tsx
+++ b/ui/src/components/settings/models/RouteChainDialog.tsx
@@ -493,7 +493,7 @@ export const RouteChainDialog: React.FC<{
? "impact"
: "refreshing",
);
- focusAfterRender(doneButtonRef);
+ onClose();
};
const submit = async (confirmation?: GuardState) => {
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index ebfa12a79..0ceaadf56 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -1496,7 +1496,8 @@ describe('SettingsModelsPage surface branches', () => {
const removeButtons = await screen.findAllByRole('button', { name: /^Remove hop$|^移除这个路由项$/i });
await userEvent.click(removeButtons[1]);
await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));
- await userEvent.click((await screen.findByText(/^Done$|^完成$/i)).closest('button') as HTMLButtonElement);
+ expect(await screen.findByText(/^Saved$|^已保存$/i)).toBeTruthy();
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
expect(await screen.findByTitle(headMappingTitle)).toBeTruthy();
await act(async () => {
@@ -1540,7 +1541,6 @@ describe('SettingsModelsPage surface branches', () => {
await waitFor(() =>
expect(document.querySelector('[data-agent-backend="codex"]')).toBeNull(),
);
- await userEvent.click((await screen.findByText(/^Done$|^完成$/i)).closest('button') as HTMLButtonElement);
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
const firstRegisteredDestination = document.querySelector(
'.model-hub-shell-info',
@@ -1552,6 +1552,549 @@ describe('SettingsModelsPage surface branches', () => {
expect(document.activeElement?.closest('[data-agent-backend="codex"]')).toBeNull();
});
+ const saveRouteForFocusTest = async (emptySources = false) => {
+ const sources = emptySources ? [] : [
+ { ...retainedSource, id: 'src_head', display_name: 'Paused source' },
+ { ...retainedSource, id: 'src_relay', display_name: 'Replacement source' },
+ ];
+ vi.spyOn(modelsApi, 'getAgentChains').mockResolvedValue([takeoverChain]);
+ vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(takeoverChain);
+ vi.spyOn(modelsApi, 'putAgentChain').mockResolvedValue({
+ chain: { ...takeoverChain, manual_override: { hops: [takeoverChain.chain[0]] }, chain: [takeoverChain.chain[0]], current: takeoverChain.chain[0] },
+ removed_hops: [],
+ interrupted: [],
+ });
+ renderPage(sources, [takeoverAgent]);
+ const opener = await screen.findByRole('button', { name: /Open gpt-5\.6-sol route chain|打开 gpt-5\.6-sol 的路由链/i });
+ await userEvent.click(opener);
+ await userEvent.click((await screen.findAllByRole('button', { name: /^Remove hop$|^移除这个路由项$/i }))[1]);
+ return { opener, sources };
+ };
+
+ // Flush real animation frames, not a waitFor that can pass before a queued
+ // focus callback has had the chance to steal (or repair) focus.
+ const flushRouteFocus = async () => {
+ await act(async () => {
+ await new Promise<void>((resolve) => requestAnimationFrame(() => {
+ requestAnimationFrame(() => resolve());
+ }));
+ });
+ };
+
+ it('MH-ROUTING-007 preserves user-moved focus after each delayed route projection install', async () => {
+ const { opener, sources } = await saveRouteForFocusTest();
+ const agentsRead = deferred<AgentSupply[]>();
+ const sourcesRead = deferred<Source[]>();
+ vi.mocked(modelsApi.listAgents).mockReturnValueOnce(agentsRead.promise);
+ vi.mocked(modelsApi.listSources).mockReturnValueOnce(sourcesRead.promise);
+ await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await flushRouteFocus();
+ expect(document.activeElement).toBe(opener);
+
+ const destination = screen.getByRole('button', { name: /Add API key|添加 API Key/i });
+ destination.focus();
+ await act(async () => { agentsRead.resolve([takeoverAgent]); });
+ await flushRouteFocus();
+ expect(document.activeElement).toBe(destination);
+ await act(async () => { sourcesRead.resolve(sources); });
+ await flushRouteFocus();
+ expect(document.activeElement).toBe(destination);
+ });
+
+ it('MH-ROUTING-007 restores page focus when a delayed route projection removes the opener', async () => {
+ const { opener } = await saveRouteForFocusTest();
+ const agentsRead = deferred<AgentSupply[]>();
+ vi.mocked(modelsApi.listAgents).mockReturnValueOnce(agentsRead.promise);
+ await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await flushRouteFocus();
+ expect(document.activeElement).toBe(opener);
+ await act(async () => { agentsRead.resolve([]); });
+ await flushRouteFocus();
+ expect(opener.isConnected).toBe(false);
+ expect(document.activeElement).toBe(document.querySelector('.model-hub-shell-info'));
+ });
+
+ it('MH-ROUTING-007 shows recovered Direct authority before the pending Sources read settles', async () => {
+ await saveRouteForFocusTest(true);
+ const sources = deferred<Source[]>();
+ vi.mocked(modelsApi.listAgents)
+ .mockRejectedValueOnce(new Error('Agents offline'))
+ .mockResolvedValue([directAgent('codex')]);
+ vi.mocked(modelsApi.listSources).mockReturnValueOnce(sources.promise);
+ await userEvent.click(screen.getByRole('button', { name: /^Save$/i }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await userEvent.click(await screen.findByRole('button', { name: /^Retry$/i }));
+ expect(await screen.findByText(/^Currently: direct$/i)).toBeTruthy();
+ expect(screen.queryByRole('button', { name: /^Retry$/i })).toBeNull();
+ expect(modelsApi.listSources).toHaveBeenCalledTimes(2);
+ await flushRouteFocus();
+ expect(document.activeElement?.closest('.model-hub-shell')).toBeTruthy();
+ await act(async () => { sources.resolve([]); });
+ await flushRouteFocus();
+ expect(screen.getByText(/^Currently: direct$/i)).toBeTruthy();
+ expect(modelsApi.putAgentChain).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([false, true])(
+ 'MH-ROUTING-007 uses the newest queued route fallback (user moved focus: %s)',
+ async (moveFocus) => {
+ const sources = [
+ { ...retainedSource, id: 'src_head', display_name: 'Paused source' },
+ { ...retainedSource, id: 'src_relay', display_name: 'Replacement source' },
+ ];
+ const claudeChain = { ...takeoverChain, backend: 'claude' as const };
+ const claudeAgent = { ...takeoverAgent, backend: 'claude' as const };
+ vi.spyOn(modelsApi, 'getAgentChains').mockImplementation((backend) =>
+ Promise.resolve([backend === 'claude' ? claudeChain : takeoverChain]));
+ vi.spyOn(modelsApi, 'getAgentChain').mockImplementation((backend) =>
+ Promise.resolve(backend === 'claude' ? claudeChain : takeoverChain));
+ vi.spyOn(modelsApi, 'putAgentChain').mockImplementation(async (backend) => ({
+ chain: {
+ ...(backend === 'claude' ? claudeChain : takeoverChain),
+ manual_override: { hops: [takeoverChain.chain[0]] },
+ chain: [takeoverChain.chain[0]],
+ current: takeoverChain.chain[0],
+ },
+ removed_hops: [],
+ interrupted: [],
+ }));
+ renderPage(sources, [takeoverAgent, claudeAgent]);
+ const firstAgents = deferred<AgentSupply[]>();
+ const firstSources = deferred<Source[]>();
+ const secondAgents = deferred<AgentSupply[]>();
+ const secondSources = deferred<Source[]>();
+ await screen.findAllByRole('button', { name: /Open gpt-5\.6-sol route chain/i });
+ vi.mocked(modelsApi.listAgents)
+ .mockReturnValueOnce(firstAgents.promise)
+ .mockReturnValueOnce(secondAgents.promise);
+ vi.mocked(modelsApi.listSources)
+ .mockReturnValueOnce(firstSources.promise)
+ .mockReturnValueOnce(secondSources.promise);
+ let latestOpener: HTMLElement | null = null;
+ for (const backend of ['codex', 'claude']) {
+ const group = document.querySelector(`[data-agent-backend="${backend}"]`) as HTMLElement;
+ latestOpener = within(group).getByRole('button', { name: /Open gpt-5\.6-sol route chain/i });
+ await userEvent.click(latestOpener);
+ await userEvent.click((await screen.findAllByRole('button', { name: /^Remove hop$/i }))[1]);
+ await userEvent.click(screen.getByRole('button', { name: /^Save$/i }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await flushRouteFocus();
+ expect(document.activeElement).toBe(latestOpener);
+ }
+ expect(modelsApi.listAgents).toHaveBeenCalledTimes(2);
+ const destination = screen.getByRole('button', { name: /Add API key/i });
+ if (moveFocus) destination.focus();
+
+ // A's read may remove B's opener, but only B's later read can settle B.
+ const withoutLatestRoute = [takeoverAgent, directAgent('claude')];
+ await act(async () => { firstAgents.resolve(withoutLatestRoute); });
+ await flushRouteFocus();
+ expect(latestOpener?.isConnected).toBe(false);
+ const expectedFocus = moveFocus ? destination : document.querySelector('[data-agent-group-head="claude"]');
+ expect(expectedFocus).not.toBeNull();
+ expect(document.activeElement).toBe(expectedFocus);
+ await act(async () => { firstSources.resolve(sources); });
+ await waitFor(() => expect(modelsApi.listAgents).toHaveBeenCalledTimes(3));
+ await act(async () => { secondAgents.resolve(withoutLatestRoute); });
+ await flushRouteFocus();
+ expect(document.activeElement).toBe(expectedFocus);
+ await act(async () => { secondSources.resolve(sources); });
+ await flushRouteFocus();
+ expect(document.activeElement).toBe(expectedFocus);
+ expect(modelsApi.putAgentChain).toHaveBeenCalledTimes(2);
+ },
+ );
+
+ it.each([false, true])(
+ 'MH-ROUTING-007 resolves the newest inferred commit at frame execution (user moved: %s)',
+ async (moveFocus) => {
+ const sources = [
+ { ...retainedSource, id: 'src_head', display_name: 'Paused source' },
+ { ...retainedSource, id: 'src_relay', display_name: 'Replacement source' },
+ ];
+ const claudeChain = { ...takeoverChain, backend: 'claude' as const };
+ const claudeAgent = { ...takeoverAgent, backend: 'claude' as const };
+ const codexWithoutModels = {
+ ...takeoverAgent, selected_model_id: null, selected_model_explicit: false,
+ builtin_models: [], model_supply: [], routes: {}, named_agents: [],
+ };
+ const inferred = deferred<AgentChain>();
+ const agentsA = deferred<AgentSupply[]>();
+ const sourcesA = deferred<Source[]>();
+ const agentsB = deferred<AgentSupply[]>();
+ const sourcesB = deferred<Source[]>();
+ vi.spyOn(modelsApi, 'getAgentChains').mockImplementation((backend) =>
+ Promise.resolve([backend === 'claude' ? claudeChain : takeoverChain]));
+ const exactRead = vi.spyOn(modelsApi, 'getAgentChain')
+ .mockResolvedValueOnce(takeoverChain)
+ .mockImplementation((backend) =>
+ backend === 'claude' ? Promise.resolve(claudeChain) : inferred.promise);
+ vi.spyOn(modelsApi, 'putAgentChain')
+ .mockRejectedValueOnce(new ApiCallError('direct_mode'))
+ .mockResolvedValueOnce({
+ chain: {
+ ...claudeChain, manual_override: { hops: [claudeChain.chain[0]] },
+ chain: [claudeChain.chain[0]], current: claudeChain.chain[0],
+ },
+ removed_hops: [], interrupted: [],
+ });
+ renderPage(sources, [takeoverAgent, claudeAgent]);
+ await screen.findAllByRole('button', { name: /Open gpt-5\.6-sol route chain/i });
+ const codexGroup = document.querySelector('[data-agent-backend="codex"]') as HTMLElement;
+ const codexOpener = within(codexGroup).getByRole('button', { name: /Open gpt-5\.6-sol route chain/i });
+ // Leave Codex suspended with its exact-chain evidence still pending.
+ await userEvent.click(codexOpener);
+ await userEvent.click((await screen.findAllByRole('button', { name: /^Remove hop$/i }))[1]);
+ await userEvent.click(screen.getByRole('button', { name: /^Save$/i }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await waitFor(() => expect(exactRead).toHaveBeenCalledTimes(2));
+ await flushRouteFocus();
+
+ const claudeGroup = document.querySelector('[data-agent-backend="claude"]') as HTMLElement;
+ const claudeOpener = within(claudeGroup).getByRole('button', { name: /Open gpt-5\.6-sol route chain/i });
+ await userEvent.click(claudeOpener);
+ await userEvent.click((await screen.findAllByRole('button', { name: /^Remove hop$/i }))[1]);
+ vi.mocked(modelsApi.listAgents)
+ .mockReturnValueOnce(agentsA.promise).mockReturnValueOnce(agentsB.promise);
+ vi.mocked(modelsApi.listSources)
+ .mockReturnValueOnce(sourcesA.promise).mockReturnValueOnce(sourcesB.promise);
+ await userEvent.click(screen.getByRole('button', { name: /^Save$/i }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await flushRouteFocus();
+ codexOpener.focus();
+ expect(document.activeElement).toBe(codexOpener);
+
+ // Hold frames only after both editors finish their normal close/focus.
+ const frames: FrameRequestCallback[] = [];
+ const frameSpy = vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {
+ frames.push(callback);
+ return frames.length;
+ });
+ const drainFrames = async () => {
+ await act(async () => {
+ for (const callback of frames.splice(0)) callback(0);
+ });
+ };
+ try {
+ // A removes the focused row and schedules its fallback.
+ await act(async () => { agentsA.resolve([codexWithoutModels, claudeAgent]); });
+ expect(codexOpener.isConnected).toBe(false);
+ expect(document.activeElement).toBe(document.body);
+ expect(frames.length).toBeGreaterThan(0);
+ // B is inferred in the same frame, before that callback executes.
+ await act(async () => {
+ inferred.resolve({
+ ...takeoverChain, manual_override: { hops: [takeoverChain.chain[0]] },
+ chain: [takeoverChain.chain[0]], current: takeoverChain.chain[0],
+ });
+ });
+ expect(screen.getByRole('status').textContent).toContain('×2');
+ const destination = screen.getByRole('button', { name: /Add API key/i });
+ if (moveFocus) destination.focus();
+ const expectedFocus = moveFocus ? destination : document.querySelector('[data-agent-group-head="codex"]');
+ expect(expectedFocus).not.toBeNull();
+ await drainFrames();
+ const firstFocus = document.activeElement;
+
+ // Finish both batches: an incorrect but valid A target would persist.
+ const readsBeforeNextBatch = vi.mocked(modelsApi.listAgents).mock.calls.length;
+ await act(async () => { sourcesA.resolve(sources); });
+ expect(modelsApi.listAgents).toHaveBeenCalledTimes(readsBeforeNextBatch + 1);
+ await act(async () => { agentsB.resolve([codexWithoutModels, claudeAgent]); });
+ await drainFrames();
+ await act(async () => { sourcesB.resolve(sources); });
+ await drainFrames();
+ expect(modelsApi.putAgentChain).toHaveBeenCalledTimes(2);
+ expect({
+ atFrame: firstFocus === expectedFocus,
+ afterSettlement: document.activeElement === expectedFocus,
+ wronglyFocusedClaude: document.activeElement === claudeOpener,
+ }).toEqual({ atFrame: true, afterSettlement: true, wronglyFocusedClaude: false });
+ } finally {
+ frameSpy.mockRestore();
+ }
+ },
+ );
+
+ for (const member of ['agents', 'sources'] as const) {
+ it(`MH-ROUTING-007 retains the route fallback through failed ${member} retries`, async () => {
+ const { opener, sources } = await saveRouteForFocusTest();
+ const reader = member === 'agents'
+ ? vi.mocked(modelsApi.listAgents)
+ : vi.mocked(modelsApi.listSources);
+ reader.mockRejectedValueOnce(new TypeError('offline'));
+ await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await flushRouteFocus();
+ const retry = await screen.findByRole('button', { name: /^Retry$|^重试$/i });
+ reader.mockRejectedValueOnce(new TypeError('still offline'));
+ await userEvent.click(retry);
+ await flushRouteFocus();
+ expect(document.activeElement).toBe(opener);
+
+ const nextRead = deferred<AgentSupply[] & Source[]>();
+ reader.mockReturnValueOnce(nextRead.promise);
+ await userEvent.click(retry);
+ await flushRouteFocus();
+ expect(document.activeElement).toBe(opener);
+ expect((retry as HTMLButtonElement).disabled).toBe(true);
+ const agentCalls = vi.mocked(modelsApi.listAgents).mock.calls.length;
+ const sourceCalls = vi.mocked(modelsApi.listSources).mock.calls.length;
+ const presenceCalls = vi.mocked(modelsApi.refreshAgentPresence).mock.calls.length;
+ await userEvent.click(retry);
+ expect(modelsApi.listAgents).toHaveBeenCalledTimes(agentCalls);
+ expect(modelsApi.listSources).toHaveBeenCalledTimes(sourceCalls);
+ expect(modelsApi.refreshAgentPresence).toHaveBeenCalledTimes(presenceCalls);
+ await act(async () => { nextRead.resolve((member === 'agents' ? [takeoverAgent] : sources) as AgentSupply[] & Source[]); });
+ await flushRouteFocus();
+ expect(retry.isConnected).toBe(false);
+ expect(document.activeElement).toBe(opener);
+ });
+ }
+
+ it.each([
+ { member: 'agents' as const, empty: false },
+ { member: 'sources' as const, empty: false },
+ { member: 'agents' as const, empty: true },
+ { member: 'sources' as const, empty: true },
+ ])('MH-ROUTING-007 keeps failed $member Retry after unrelated refresh (empty: $empty)', async ({ member, empty }) => {
+ const { sources } = await saveRouteForFocusTest();
+ const failedReader = member === 'agents'
+ ? vi.mocked(modelsApi.listAgents)
+ : vi.mocked(modelsApi.listSources);
+ failedReader.mockRejectedValueOnce(new Error('route reconciliation offline'));
+ await userEvent.click(screen.getByRole('button', { name: /^Save$/i }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ const initialRetry = await screen.findByRole('button', { name: /^Retry$/i });
+ await flushRouteFocus();
+
+ // An unrelated Source refetch first installs an entity echo, then a complete
+ // surface read. Neither is a settlement of the retained route batch.
+ const echoed = { ...sources[0], display_name: 'Refreshed source' };
+ const freshSources = empty ? [] : [echoed, sources[1]];
+ const freshAgents = empty ? [directAgent('codex')] : [takeoverAgent];
+ const sourceRefresh = vi.spyOn(modelsApi, 'refreshSource')
+ .mockResolvedValue({ source: echoed, discovered: 0 });
+ const fullSources = deferred<Source[]>();
+ const fullAgents = deferred<AgentSupply[]>();
+ vi.mocked(modelsApi.listSources)
+ .mockReturnValueOnce(fullSources.promise)
+ .mockResolvedValue(freshSources);
+ vi.mocked(modelsApi.listAgents)
+ .mockReturnValueOnce(fullAgents.promise)
+ .mockResolvedValue(freshAgents);
+ const chainReads = vi.mocked(modelsApi.getAgentChains).mock.calls.length;
+ await userEvent.click(screen.getByText('Paused source').closest('button') as HTMLButtonElement);
+ await userEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: /^Refetch$/i }));
+ await waitFor(() => expect(sourceRefresh).toHaveBeenCalledOnce());
+ expect(initialRetry.isConnected).toBe(true);
+ await act(async () => {
+ fullSources.resolve(freshSources);
+ fullAgents.resolve(freshAgents);
+ });
+ await closeSourceDetails();
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await flushRouteFocus();
+
+ const retry = screen.getByRole('button', { name: /^Retry$/i }) as HTMLButtonElement;
+ expect(retry.disabled).toBe(false);
+ expect(screen.queryByText(/^Currently: direct$/i)).toBeNull();
+ if (!empty) expect(screen.getByText('Refreshed source')).toBeTruthy();
+ expect(modelsApi.getAgentChains).toHaveBeenCalledTimes(chainReads);
+ const agentsBeforeRetry = vi.mocked(modelsApi.listAgents).mock.calls.length;
+ const sourcesBeforeRetry = vi.mocked(modelsApi.listSources).mock.calls.length;
+ await userEvent.click(retry);
+ await waitFor(() => expect(retry.isConnected).toBe(false));
+ expect(modelsApi.listAgents).toHaveBeenCalledTimes(agentsBeforeRetry + (member === 'agents' ? 1 : 0));
+ expect(modelsApi.listSources).toHaveBeenCalledTimes(sourcesBeforeRetry + 1);
+ expect(modelsApi.putAgentChain).toHaveBeenCalledTimes(1);
+ if (empty) {
+ expect(await screen.findByText(/^Currently: direct$/i)).toBeTruthy();
+ } else {
+ // M6 settlement releases its backend again; an unrelated ready read must
+ // not leave the backend silently excluded from all future chain probes.
+ await waitFor(() => expect(vi.mocked(modelsApi.getAgentChains).mock.calls.length).toBeGreaterThan(chainReads));
+ }
+ });
+
+ it('MH-ROUTING-007 keeps the previous retry fallback when another route opens', async () => {
+ const { opener } = await saveRouteForFocusTest();
+ const agentsRead = deferred<AgentSupply[]>();
+ vi.mocked(modelsApi.listAgents)
+ .mockRejectedValueOnce(new TypeError('offline'))
+ .mockReturnValueOnce(agentsRead.promise);
+ await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await flushRouteFocus();
+ const retry = await screen.findByRole('button', { name: /^Retry$|^重试$/i });
+
+ // Opening a second route must not erase the first commit's page-owned
+ // landing target while its read-only Retry remains active.
+ await userEvent.click(opener);
+ await screen.findAllByRole('button', { name: /^Remove hop$|^移除这个路由项$/i });
+ await userEvent.click(
+ screen.getAllByRole('button', { name: /^Close$|^关闭$/i })
+ .find((button) => button.classList.contains('model-hub-dialog-action'))!,
+ );
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await flushRouteFocus();
+
+ await userEvent.click(retry);
+ await act(async () => { agentsRead.resolve([takeoverAgent]); });
+ await waitFor(() => expect(retry.isConnected).toBe(false));
+ await flushRouteFocus();
+ expect(document.activeElement).toBe(opener);
+ });
+
+ it.each([false, true])(
+ 'MH-ROUTING-007 preserves a suspended attempt focus origin (another editor: %s)',
+ async (anotherEditor) => {
+ const sources = [
+ { ...retainedSource, id: 'src_head', display_name: 'Paused source' },
+ { ...retainedSource, id: 'src_relay', display_name: 'Replacement source' },
+ ];
+ const otherModel = 'gpt-other';
+ const otherChain = { ...takeoverChain, model_id: otherModel };
+ const agent = {
+ ...takeoverAgent,
+ builtin_models: [takeoverChain.model_id, otherModel],
+ model_supply: [...takeoverAgent.model_supply!, { ...takeoverAgent.model_supply![0], model_id: otherModel }],
+ };
+ const inferred = deferred<AgentChain>();
+ const retryRead = deferred<AgentSupply[]>();
+ vi.spyOn(modelsApi, 'getAgentChains').mockResolvedValue([takeoverChain, otherChain]);
+ const chainRead = vi.spyOn(modelsApi, 'getAgentChain')
+ .mockResolvedValueOnce(takeoverChain)
+ .mockImplementation((_backend, modelId) =>
+ modelId === otherModel ? Promise.resolve(otherChain) : inferred.promise);
+ vi.spyOn(modelsApi, 'putAgentChain').mockRejectedValueOnce(new ApiCallError('direct_mode'));
+ renderPage(sources, [agent]);
+ const opener = await screen.findByRole('button', { name: /Open gpt-5\.6-sol route chain/i });
+ await userEvent.click(opener);
+ await userEvent.click((await screen.findAllByRole('button', { name: /^Remove hop$/i }))[1]);
+ await userEvent.click(screen.getByRole('button', { name: /^Save$/i }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ // The Direct handoff lands in Hub again and acquires the suspended exact
+ // chain read only after its fresh Sources projection.
+ await waitFor(() => expect(chainRead).toHaveBeenCalledTimes(2));
+ if (anotherEditor) {
+ await userEvent.click(screen.getByRole('button', { name: /Open gpt-other route chain/i }));
+ await screen.findAllByRole('button', { name: /^Remove hop$/i });
+ }
+ vi.mocked(modelsApi.listAgents)
+ .mockRejectedValueOnce(new TypeError('offline after inferred commit'))
+ .mockReturnValueOnce(retryRead.promise);
+ await act(async () => {
+ inferred.resolve({
+ ...takeoverChain,
+ manual_override: { hops: [takeoverChain.chain[0]] },
+ chain: [takeoverChain.chain[0]],
+ current: takeoverChain.chain[0],
+ });
+ });
+ await flushRouteFocus();
+ if (anotherEditor) {
+ expect(document.activeElement?.closest('[role="dialog"]')).toBeTruthy();
+ await userEvent.click(
+ within(screen.getByRole('dialog')).getAllByRole('button', { name: /^Close$/i })
+ .find((button) => button.classList.contains('model-hub-dialog-action'))!,
+ );
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await flushRouteFocus();
+ }
+ const retry = await screen.findByRole('button', { name: /^Retry$/i });
+ await userEvent.click(retry);
+ // A's commit cannot borrow B's opener from the current dialog selection.
+ expect(document.activeElement).toBe(opener);
+ expect((retry as HTMLButtonElement).disabled).toBe(true);
+ await act(async () => { retryRead.resolve([agent]); });
+ await waitFor(() => expect(retry.isConnected).toBe(false));
+ await flushRouteFocus();
+ expect(document.activeElement).toBe(opener);
+ expect(modelsApi.putAgentChain).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it('MH-ROUTING-007 transfers Retry focus before a background inferred commit disables it', async () => {
+ const sources = [
+ { ...retainedSource, id: 'src_head', display_name: 'Paused source' },
+ { ...retainedSource, id: 'src_relay', display_name: 'Replacement source' },
+ ];
+ const claudeChain = { ...takeoverChain, backend: 'claude' as const };
+ const claudeAgent = { ...takeoverAgent, backend: 'claude' as const };
+ const inferred = deferred<AgentChain>();
+ const reconciliation = deferred<AgentSupply[]>();
+ vi.spyOn(modelsApi, 'getAgentChains').mockImplementation((backend) =>
+ Promise.resolve([backend === 'claude' ? claudeChain : takeoverChain]));
+ const exactRead = vi.spyOn(modelsApi, 'getAgentChain')
+ .mockResolvedValueOnce(takeoverChain)
+ .mockImplementation((backend) =>
+ backend === 'claude' ? Promise.resolve(claudeChain) : inferred.promise);
+ vi.spyOn(modelsApi, 'putAgentChain')
+ .mockRejectedValueOnce(new ApiCallError('direct_mode'))
+ .mockResolvedValueOnce({
+ chain: {
+ ...claudeChain,
+ manual_override: { hops: [claudeChain.chain[0]] },
+ chain: [claudeChain.chain[0]],
+ current: claudeChain.chain[0],
+ },
+ removed_hops: [],
+ interrupted: [],
+ });
+ renderPage(sources, [takeoverAgent, claudeAgent]);
+ const codexGroup = await waitFor(() => {
+ const group = document.querySelector('[data-agent-backend="codex"]');
+ expect(group).not.toBeNull();
+ return group as HTMLElement;
+ });
+ const codexOpener = within(codexGroup).getByRole('button', {
+ name: /Open gpt-5\.6-sol route chain/i,
+ });
+ await userEvent.click(codexOpener);
+ await userEvent.click((await screen.findAllByRole('button', { name: /^Remove hop$/i }))[1]);
+ await userEvent.click(screen.getByRole('button', { name: /^Save$/i }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await waitFor(() => expect(exactRead).toHaveBeenCalledTimes(2));
+
+ const claudeGroup = document.querySelector('[data-agent-backend="claude"]') as HTMLElement;
+ await userEvent.click(within(claudeGroup).getByRole('button', {
+ name: /Open gpt-5\.6-sol route chain/i,
+ }));
+ await userEvent.click((await screen.findAllByRole('button', { name: /^Remove hop$/i }))[1]);
+ vi.mocked(modelsApi.listSources).mockRejectedValueOnce(new Error('post-commit sources failed'));
+ await userEvent.click(screen.getByRole('button', { name: /^Save$/i }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ const retry = await screen.findByRole('button', { name: /^Retry$/i }) as HTMLButtonElement;
+ await flushRouteFocus();
+ expect(retry.disabled).toBe(false);
+ retry.focus();
+ expect(document.activeElement).toBe(retry);
+
+ // The late Codex evidence starts a new collection batch while focus is on
+ // Claude's old failure Retry, without clicking Retry or opening an editor.
+ vi.mocked(modelsApi.listAgents).mockReturnValueOnce(reconciliation.promise);
+ await act(async () => {
+ inferred.resolve({
+ ...takeoverChain,
+ manual_override: { hops: [takeoverChain.chain[0]] },
+ chain: [takeoverChain.chain[0]],
+ current: takeoverChain.chain[0],
+ });
+ });
+ await flushRouteFocus();
+ expect(retry.disabled).toBe(true);
+ expect(document.activeElement).toBe(codexOpener);
+
+ await act(async () => { reconciliation.resolve([takeoverAgent, claudeAgent]); });
+ await waitFor(() => expect(retry.isConnected).toBe(false));
+ await flushRouteFocus();
+ expect(document.activeElement).toBe(codexOpener);
+ expect(modelsApi.putAgentChain).toHaveBeenCalledTimes(2);
+ });
+
it('keeps the source projection intact after a lost Direct-mode response', async () => {
const direct = { ...takeoverAgent, mode: 'direct' as const, sources: null, routes: null, supply_status: null, model_supply: null };
const staleSource = {
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index a7980c9a3..2d0b8bae3 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -17,7 +17,7 @@ import { GatewayModule } from './GatewayModule';
import { MigrationDialog } from './MigrationDialog';
import { ModelHubInfoHint } from './ModelHubInfoHint';
import { RecentSwitchesCard } from './RecentSwitchesCard';
-import { RouteChainDialog, type RouteCollectionObservation, type RouteCommitReconciliation, type RouteReport } from './RouteChainDialog';
+import { RouteChainDialog, type RouteCollectionObservation, type RouteCommitReconciliation, type RouteReport, type SuspendedRouteAttempt } from './RouteChainDialog';
import { routeChainMatchesAttempt } from './routeChainDraft';
import { SourceDetailPanel } from './SourceDetailPanel';
import { SourceOrderDrawer } from './SourceOrderDrawer';
@@ -73,6 +73,11 @@ import type { UsageWindowOption } from './usageProjection';
const CHAIN_READ_CONCURRENCY = 6;
const EVENT_PAGE = 20;
+type RouteTarget = {
+ agent: AgentSupply;
+ modelId: string;
+ opener: HTMLElement | null;
+};
// Frame 13's rows, derived from the one subscription-vendor vocabulary rather
// than restated here. `subscriptionOptions.ts` owns which vendors are offered and
// what custody each has, so this menu cannot drift out of the same order the
@@ -386,9 +391,18 @@ export const SettingsModelsPage: React.FC = () => {
const [orderBackend, setOrderBackend] = React.useState<AgentBackend | null>(null);
const [menuBackend, setMenuBackend] = React.useState<AgentBackend | null>(null);
const [adoptAgent, setAdoptAgent] = React.useState<AgentSupply | null>(null);
- const [routeTarget, setRouteTarget] = React.useState<{ agent: AgentSupply; modelId: string; opener: HTMLElement | null } | null>(null);
+ const [routeTarget, setRouteTarget] = React.useState<RouteTarget | null>(null);
+ const pendingRouteOpenersRef = React.useRef(new Map<RouteReport, HTMLElement | null>());
+ const suspendedRouteOpenersRef = React.useRef(new WeakMap<SuspendedRouteAttempt, HTMLElement | null>());
+ const sourcesRetryRef = React.useRef<HTMLButtonElement>(null);
+ const supplyRetryRef = React.useRef<HTMLButtonElement>(null);
+ const routeCommitStatusRef = React.useRef<RouteProjectionStatus | null>(null);
const [routeCommitStatus, setRouteCommitStatus] = React.useState<RouteProjectionStatus | null>(null);
- const [routeCommitBackend, setRouteCommitBackend] = React.useState<AgentBackend | null>(null);
+ const routeCommitBackends = React.useMemo(
+ () => new Set([...pendingRouteOpenersRef.current.keys()].map((report) => report.chain.backend)),
+ // Status changes notify us when a report is queued or settled.
+ [routeCommitStatus],
+ );
const [suspendedRouteAttempts, setSuspendedRouteAttempts] = React.useState(
emptySuspendedRouteAttempts,
);
@@ -530,7 +544,7 @@ export const SettingsModelsPage: React.FC = () => {
const suspendedBackends = new Set(suspendedRouteAttempts.keys());
const probeAgents = hubAgents.filter((agent) =>
!suspendedBackends.has(agent.backend)
- && agent.backend !== routeCommitBackend);
+ && !routeCommitBackends.has(agent.backend));
const activeBackends = new Set(hubAgents.map((agent) => agent.backend));
chainReadAuthority.invalidateExcept((key) => activeBackends.has(chainKeyBackend(key)));
setChainsRead((previous) => readyRegion(Object.fromEntries(
@@ -542,7 +556,7 @@ export const SettingsModelsPage: React.FC = () => {
})).filter(([key]) => activeBackends.has(chainKeyBackend(key))),
)));
for (const agent of probeAgents) void refreshAgentChains(agent);
- }, [chainReadAuthority, refreshAgentChains, routeCommitBackend, suspendedRouteAttempts]);
+ }, [chainReadAuthority, refreshAgentChains, routeCommitBackends, suspendedRouteAttempts]);
React.useEffect(() => {
const freshSupply = foldRegionRead<AgentSupply[], AgentSupply[] | null>(supplyRead, {
@@ -923,7 +937,16 @@ export const SettingsModelsPage: React.FC = () => {
const landingLoading = sourcesRead.kind === 'loading'
&& supplyRead.kind === 'loading'
&& runtimeRead.kind === 'loading';
- const directEmpty = modelsSurfaceKindFromReads(supplyRead, sourcesRead) === 'direct_empty';
+ // A newer region observation (including a Source entity echo) does not settle
+ // a retained M6 failure. Compose its Retry into the receiving view without
+ // changing the actual read authority or discarding newly observed data.
+ const sourcesDisplayRead = routeCommitStatus?.failed.has('sources')
+ ? failRegionRead(sourcesRead)
+ : sourcesRead;
+ const supplyDisplayRead = routeCommitStatus?.failed.has('agents')
+ ? failRegionRead(supplyRead)
+ : supplyRead;
+ const directEmpty = modelsSurfaceKindFromReads(supplyDisplayRead, sourcesDisplayRead) === 'direct_empty';
const installedAgents = agents.filter((agent) => agent.cli_present);
const hubBackends = agents.filter((agent) => agent.mode === 'hub').map((agent) => agent.backend);
const activeBackends = supplyRead.kind === 'ready' ? new Set(hubBackends) : undefined;
@@ -952,7 +975,7 @@ export const SettingsModelsPage: React.FC = () => {
void startRuntime();
}
};
- const installedSupplyRead = foldRegionRead<AgentSupply[], RegionRead<AgentSupply[]>>(supplyRead, {
+ const installedSupplyRead = foldRegionRead<AgentSupply[], RegionRead<AgentSupply[]>>(supplyDisplayRead, {
loading: () => loadingRegion(),
ready: () => readyRegion(installedAgents),
unread: (retryable) => unreadRegion(retryable),
@@ -1014,13 +1037,37 @@ export const SettingsModelsPage: React.FC = () => {
read: chains[modelChainKey(routeTarget.agent.backend, routeTarget.modelId)],
available: supplyRead.kind !== 'ready' || currentRouteAgent !== null,
} : null;
- const focusRouteDestination = React.useCallback((target: NonNullable<typeof routeTarget>) => {
+ const focusRouteDestination = React.useCallback((
+ target: RouteTarget,
+ preserveCurrentFocus = false,
+ ) => {
requestAnimationFrame(() => {
focusModelHubProjection({
root: pageRef.current,
activeTarget: target.opener,
backend: target.agent.backend,
modelId: target.modelId,
+ preserveCurrentFocus,
+ });
+ });
+ }, []);
+ const refocusPendingRouteDestination = React.useCallback(() => {
+ const report = routeCommitStatusRef.current?.report;
+ if (!report || !pendingRouteOpenersRef.current.has(report)) return;
+ const opener = pendingRouteOpenersRef.current.get(report) ?? null;
+ requestAnimationFrame(() => {
+ // Another commit can be inferred between installation and this frame.
+ // Its focus identity wins, even while its collection reads are queued.
+ const latestReport = routeCommitStatusRef.current?.report ?? report;
+ const latestOpener = pendingRouteOpenersRef.current.has(latestReport)
+ ? pendingRouteOpenersRef.current.get(latestReport) ?? null
+ : latestReport === report ? opener : null;
+ focusModelHubProjection({
+ root: pageRef.current,
+ activeTarget: latestOpener,
+ backend: latestReport.chain.backend,
+ modelId: latestReport.chain.model_id,
+ preserveCurrentFocus: true,
});
});
}, []);
@@ -1040,18 +1087,24 @@ export const SettingsModelsPage: React.FC = () => {
if (result.kind === 'stale') throw new Error('route_agents_read_superseded');
return {
value: result.value,
- install: () => setSupplyRead(readyRegion(result.value)),
+ install: () => {
+ setSupplyRead(readyRegion(result.value));
+ refocusPendingRouteDestination();
+ },
};
- }, [agentCollectionReads]);
+ }, [agentCollectionReads, refocusPendingRouteDestination]);
const readRouteSources = React.useCallback(async (): Promise<RouteCollectionObservation<Source[]>> => {
const snapshot = sourceEntityAuthority.beginSnapshot();
const result = await sourceCollectionReads.read();
if (result.kind === 'stale') throw new Error('route_sources_read_superseded');
return {
value: result.value,
- install: () => sourceEntityAuthority.settleSnapshot(snapshot, result.value),
+ install: () => {
+ sourceEntityAuthority.settleSnapshot(snapshot, result.value);
+ refocusPendingRouteDestination();
+ },
};
- }, [sourceCollectionReads, sourceEntityAuthority]);
+ }, [refocusPendingRouteDestination, sourceCollectionReads, sourceEntityAuthority]);
const routeProjectionReconciler = React.useMemo(() => createRouteProjectionReconciler({
readAgents: readRouteAgents,
readSources: readRouteSources,
@@ -1059,9 +1112,36 @@ export const SettingsModelsPage: React.FC = () => {
if (member === 'agents') setSupplyRead(failRegionRead);
else setSourcesRead(failRegionRead);
},
- onStatus: setRouteCommitStatus,
- }), [readRouteAgents, readRouteSources]);
- const routeCommitted = React.useCallback((result: RouteReport) => {
+ onStatus: (status) => {
+ // Every pending transition removes Retry admission, including an inferred
+ // commit arriving while the user has focused an older failed read's Retry.
+ if (status.pending && (
+ document.activeElement === sourcesRetryRef.current
+ || document.activeElement === supplyRetryRef.current
+ )) {
+ focusModelHubProjection({
+ root: pageRef.current,
+ activeTarget: pendingRouteOpenersRef.current.get(status.report) ?? null,
+ backend: status.report.chain.backend,
+ modelId: status.report.chain.model_id,
+ });
+ }
+ routeCommitStatusRef.current = status;
+ setRouteCommitStatus(status);
+ if (!status.pending) {
+ refocusPendingRouteDestination();
+ if (status.failed.size === 0) {
+ for (const report of status.reports) pendingRouteOpenersRef.current.delete(report);
+ }
+ }
+ },
+ }), [readRouteAgents, readRouteSources, refocusPendingRouteDestination]);
+ React.useEffect(() => () => routeProjectionReconciler.invalidate(), [routeProjectionReconciler]);
+ const routeCommitted = React.useCallback((
+ result: RouteReport,
+ opener: HTMLElement | null,
+ ) => {
+ pendingRouteOpenersRef.current.set(result, opener);
chainReadAuthority.invalidate([modelChainKey(result.chain.backend, result.chain.model_id)]);
routeObserved(result.chain);
setSuspendedRouteAttempts((attempts) =>
@@ -1070,18 +1150,14 @@ export const SettingsModelsPage: React.FC = () => {
suspendedHubFrontiersRef.current.delete(result.chain.backend);
suspendedSourceBaselinesRef.current.delete(result.chain.backend);
suspendedChainBaselinesRef.current.delete(result.chain.backend);
- setRouteCommitBackend(result.chain.backend);
- routeProjectionReconciler.start(result.chain.backend);
- }, [chainReadAuthority, routeObserved, routeProjectionReconciler]);
- React.useEffect(() => {
- if (routeCommitStatus && !routeCommitStatus.pending && routeCommitStatus.failed.size === 0) {
- setRouteCommitBackend(null);
- }
- }, [routeCommitStatus]);
+ routeProjectionReconciler.start(result);
+ showToast(t('common.saved'), 'success');
+ }, [chainReadAuthority, routeObserved, routeProjectionReconciler, showToast, t]);
const retryRouteCommit = React.useCallback(() => {
- if (routeCommitStatus?.pending || !routeCommitStatus?.failed.size) return;
+ const status = routeCommitStatusRef.current;
+ if (status?.pending || !status?.failed.size) return;
routeProjectionReconciler.retry();
- }, [routeCommitStatus, routeProjectionReconciler]);
+ }, [routeProjectionReconciler]);
const routeCommitReconciliation = React.useMemo<RouteCommitReconciliation | null>(() => routeCommitStatus ? ({
pending: routeCommitStatus.pending,
failed: routeCommitStatus.failed.size > 0,
@@ -1152,7 +1228,10 @@ export const SettingsModelsPage: React.FC = () => {
degraded: () => null,
});
if (observed && routeChainMatchesAttempt(observed, held)) {
- routeCommitted({ chain: observed, removed_hops: null, interrupted: null });
+ routeCommitted(
+ { chain: observed, removed_hops: null, interrupted: null },
+ suspendedRouteOpenersRef.current.get(held) ?? null,
+ );
}
}
}, [chainsRead, routeCommitted, suspendedRouteAttempts]);
@@ -1325,7 +1404,7 @@ export const SettingsModelsPage: React.FC = () => {
onOpenChange={(open) => { if (!open) closeSubscriptionPicker(); }}
>
<PopoverAnchor virtualRef={subscriptionAnchorRef} />
- <SourcesCard read={sourcesRead} activeBackends={activeBackends} readFailureCopy={routeCommitStatus?.failed.has('sources') ? t('settings.models.routeDialog.impact.refreshFail') : undefined} onRetry={() => routeCommitStatus?.failed.has('sources') ? retryRouteCommit() : void retrySources()} onOpenSource={(source, opener) => selectSource({ sourceId: source.id, returnFocus: () => opener })} onAddApiKey={(opener) => { apiKeyTriggerRef.current = opener; setApiKeyOpen(true); }} onAddSubscription={toggleSubscriptionPicker} subscriptionPickerOpen={subscriptionPickerOpen} subscriptionTriggerRef={subscriptionTriggerRef} />
+ <SourcesCard read={sourcesDisplayRead} activeBackends={activeBackends} retryRef={sourcesRetryRef} retryDisabled={routeCommitStatus?.pending === true} readFailureCopy={routeCommitStatus?.failed.has('sources') ? t('settings.models.routeDialog.impact.refreshFail') : undefined} onRetry={() => routeCommitStatus?.failed.has('sources') ? retryRouteCommit() : void retrySources()} onOpenSource={(source, opener) => selectSource({ sourceId: source.id, returnFocus: () => opener })} onAddApiKey={(opener) => { apiKeyTriggerRef.current = opener; setApiKeyOpen(true); }} onAddSubscription={toggleSubscriptionPicker} subscriptionPickerOpen={subscriptionPickerOpen} subscriptionTriggerRef={subscriptionTriggerRef} />
<PopoverContent
role="menu"
aria-label={t('settings.models.upstream.addSubscription')}
@@ -1419,7 +1498,7 @@ export const SettingsModelsPage: React.FC = () => {
</PopoverContent>
</Popover>
<div className="hidden xl:block" aria-hidden="true" />
- <GatewayModule supply={installedSupplyRead} readFailureCopy={routeCommitStatus?.failed.has('agents') ? t('settings.models.routeDialog.impact.refreshFail') : undefined} sources={sources} chains={chains} runtime={runtime} runtimeSnapshot={retainedRuntime} onRetry={() => routeCommitStatus?.failed.has('agents') ? retryRouteCommit() : void retrySupply()} pendingBackends={agentWrites} switchFailures={switchFailures} connectingBackend={adoptAgent?.backend ?? null} onConnectHub={switchToGateway} onSwitchDirect={switchToDirect} onOpenModels={(agent) => setMenuBackend(agent.backend)} onOpenOrder={(agent) => setOrderBackend(agent.backend)} onOpenRoute={(agent, modelId, opener) => setRouteTarget({ agent, modelId, opener })} onProbeSettled={(agent) => void refreshAgentChains(agent)} />
+ <GatewayModule supply={installedSupplyRead} retryRef={supplyRetryRef} retryDisabled={routeCommitStatus?.pending === true} readFailureCopy={routeCommitStatus?.failed.has('agents') ? t('settings.models.routeDialog.impact.refreshFail') : undefined} sources={sources} chains={chains} runtime={runtime} runtimeSnapshot={retainedRuntime} onRetry={() => routeCommitStatus?.failed.has('agents') ? retryRouteCommit() : void retrySupply()} pendingBackends={agentWrites} switchFailures={switchFailures} connectingBackend={adoptAgent?.backend ?? null} onConnectHub={switchToGateway} onSwitchDirect={switchToDirect} onOpenModels={(agent) => setMenuBackend(agent.backend)} onOpenOrder={(agent) => setOrderBackend(agent.backend)} onOpenRoute={(agent, modelId, opener) => setRouteTarget({ agent, modelId, opener })} onProbeSettled={(agent) => void refreshAgentChains(agent)} />
<SupplyGraph containerRef={overviewRef} relations={supplyRelations} />
</div>
<SupplyLegend relations={supplyRelations} />
@@ -1506,7 +1585,7 @@ export const SettingsModelsPage: React.FC = () => {
setRouteTarget(null);
if (target) focusRouteDestination(target);
}}
- onCommitted={routeCommitted}
+ onCommitted={(result) => routeCommitted(result, routeTarget?.opener ?? null)}
commitReconciliation={routeCommitReconciliation}
onObserved={routeObserved}
readAgents={readRouteAgents}
@@ -1514,6 +1593,9 @@ export const SettingsModelsPage: React.FC = () => {
onDirectMode={(attempt, observedAgent) => {
const landingBackend = attempt?.backend ?? routeTarget?.agent.backend;
if (landingBackend) {
+ if (attempt && routeTarget) {
+ suspendedRouteOpenersRef.current.set(attempt, routeTarget.opener);
+ }
suspendedSourceBaselinesRef.current.set(landingBackend, sourcesRead);
setSuspendedRouteAttempts((attempts) =>
attempt
diff --git a/ui/src/components/settings/models/SourcesCard.test.tsx b/ui/src/components/settings/models/SourcesCard.test.tsx
index 764128ac3..8ab0cd986 100644
--- a/ui/src/components/settings/models/SourcesCard.test.tsx
+++ b/ui/src/components/settings/models/SourcesCard.test.tsx
@@ -102,4 +102,21 @@ describe('SourcesCard footer', () => {
await userEvent.click(screen.getByRole('button', { name: /^Retry$|^重试$/i }));
expect(onRetry).toHaveBeenCalledOnce();
});
+
+ it('disables the page retry while route reconciliation is pending', () => {
+ render(
+ <I18nextProvider i18n={i18n}>
+ <SourcesCard
+ read={failRegionRead(readyRegion([retained]))}
+ retryDisabled
+ onRetry={vi.fn()}
+ onOpenSource={vi.fn()}
+ onAddApiKey={vi.fn()}
+ onAddSubscription={vi.fn()}
+ />
+ </I18nextProvider>,
+ );
+
+ expect((screen.getByRole('button', { name: /^Retry$|^重试$/i }) as HTMLButtonElement).disabled).toBe(true);
+ });
});
diff --git a/ui/src/components/settings/models/SourcesCard.tsx b/ui/src/components/settings/models/SourcesCard.tsx
index 9054933c2..5a416206d 100644
--- a/ui/src/components/settings/models/SourcesCard.tsx
+++ b/ui/src/components/settings/models/SourcesCard.tsx
@@ -11,6 +11,8 @@ import type { AgentBackend, Source } from './types';
export const SourcesCard: React.FC<{
read: RegionRead<Source[]>;
onRetry: () => void;
+ retryDisabled?: boolean;
+ retryRef?: React.Ref<HTMLButtonElement>;
readFailureCopy?: string;
onOpenSource: (source: Source, opener: HTMLButtonElement) => void;
onAddApiKey: (opener: HTMLButtonElement) => void;
@@ -18,7 +20,7 @@ export const SourcesCard: React.FC<{
subscriptionPickerOpen?: boolean;
subscriptionTriggerRef?: React.Ref<HTMLButtonElement>;
activeBackends?: ReadonlySet<AgentBackend>;
-}> = ({ read, onRetry, readFailureCopy, onOpenSource, onAddApiKey, onAddSubscription, subscriptionPickerOpen, subscriptionTriggerRef, activeBackends }) => {
+}> = ({ read, onRetry, retryDisabled = false, retryRef, readFailureCopy, onOpenSource, onAddApiKey, onAddSubscription, subscriptionPickerOpen, subscriptionTriggerRef, activeBackends }) => {
const { t } = useTranslation();
const sources = foldRegionRead<Source[], Source[] | undefined>(read, {
loading: () => undefined,
@@ -49,9 +51,9 @@ export const SourcesCard: React.FC<{
{read.kind === 'loading' && sources === undefined
? <div className="flex h-full min-h-36 items-center justify-center"><LoaderCircle className="size-4 animate-spin text-muted" /></div>
: read.kind === 'unread'
- ? <div className="flex h-full min-h-36 flex-col items-center justify-center gap-3 px-4 text-center"><p className="text-[12px] text-muted">{t('settings.models.upstream.unread')}</p><Button variant="outline" size="xs" onClick={onRetry}>{t('settings.models.upstream.retry')}</Button></div>
+ ? <div className="flex h-full min-h-36 flex-col items-center justify-center gap-3 px-4 text-center"><p className="text-[12px] text-muted">{t('settings.models.upstream.unread')}</p><Button ref={retryRef} variant="outline" size="xs" disabled={retryDisabled} onClick={onRetry}>{t('settings.models.upstream.retry')}</Button></div>
: <>
- {read.kind === 'degraded' && read.cause === 'read_failed' && <div className="mb-2 flex items-center justify-between gap-3 rounded-lg border border-destructive/25 bg-destructive/[0.08] px-3 py-2"><p className="text-[11px] text-destructive-ink">{readFailureCopy ?? t('settings.models.upstream.unread')}</p><Button variant="outline" size="xs" onClick={onRetry}>{t('settings.models.upstream.retry')}</Button></div>}
+ {read.kind === 'degraded' && read.cause === 'read_failed' && <div className="mb-2 flex items-center justify-between gap-3 rounded-lg border border-destructive/25 bg-destructive/[0.08] px-3 py-2"><p className="text-[11px] text-destructive-ink">{readFailureCopy ?? t('settings.models.upstream.unread')}</p><Button ref={retryRef} variant="outline" size="xs" disabled={retryDisabled} onClick={onRetry}>{t('settings.models.upstream.retry')}</Button></div>}
{groups.length > 0
? groups.map((group) => <div key={group.id} className="space-y-2.5"><h3 className="model-hub-upstream-group-label flex h-[18px] items-center uppercase">{t(`settings.models.upstream.group.${group.id}`)}</h3>{group.sources.map((source) => <SourceRow key={source.id} source={source} onOpen={onOpenSource} activeBackends={activeBackends} />)}</div>)
: <p className="px-3 py-10 text-center text-[12px] text-muted">{t('settings.models.upstream.empty')}</p>}
diff --git a/ui/src/components/settings/models/modelHubFocus.test.ts b/ui/src/components/settings/models/modelHubFocus.test.ts
index 8e59e24a8..cf74a9efd 100644
--- a/ui/src/components/settings/models/modelHubFocus.test.ts
+++ b/ui/src/components/settings/models/modelHubFocus.test.ts
@@ -49,4 +49,46 @@ describe("model hub projection focus", () => {
expect(group?.dataset.agentGroupHead).toBe("claude");
root.remove();
});
+
+ it("preserves the current focus when a background projection installs", () => {
+ const root = document.createElement("main");
+ root.innerHTML = [
+ '<button data-destination="current">Current</button>',
+ '<button data-route-backend="claude" data-route-model="model">Model</button>',
+ ].join("");
+ document.body.append(root);
+ const current = root.querySelector<HTMLElement>('[data-destination="current"]')!;
+ current.focus();
+
+ const focused = focusModelHubProjection({
+ root,
+ activeTarget: null,
+ backend: "claude",
+ modelId: "model",
+ preserveCurrentFocus: true,
+ });
+
+ expect(focused).toBe(current);
+ expect(document.activeElement).toBe(current);
+ root.remove();
+ });
+
+ it("focuses the opener inside a remounted nonfocusable model row", () => {
+ const root = document.createElement("main");
+ root.innerHTML = [
+ '<button data-destination="first">First control</button>',
+ '<div data-route-backend="claude" data-route-model="模型">',
+ '<button data-opener>Open route</button></div>',
+ ].join("");
+ document.body.append(root);
+ const focused = focusModelHubProjection({
+ root,
+ activeTarget: document.createElement("button"),
+ backend: "claude",
+ modelId: "模型",
+ });
+ expect(focused).toBe(root.querySelector("[data-opener]"));
+ expect(document.activeElement).toBe(focused);
+ root.remove();
+ });
});
diff --git a/ui/src/components/settings/models/modelHubFocus.ts b/ui/src/components/settings/models/modelHubFocus.ts
index e818848bf..5f673521d 100644
--- a/ui/src/components/settings/models/modelHubFocus.ts
+++ b/ui/src/components/settings/models/modelHubFocus.ts
@@ -14,20 +14,24 @@ const focusValid = (
): element is HTMLElement =>
element instanceof HTMLElement &&
element.isConnected &&
+ (element.matches(focusableSelector) || element.hasAttribute("tabindex")) &&
!element.hasAttribute("disabled") &&
element.getAttribute("aria-disabled") !== "true" &&
- !element.closest("[inert]");
+ !element.closest("[inert], [hidden]");
const exactModelRow = (
root: HTMLElement,
backend: AgentBackend,
modelId: string,
-): HTMLElement | null =>
- [...root.querySelectorAll<HTMLElement>("[data-route-backend]")].find(
+): HTMLElement | null => {
+ const row = [...root.querySelectorAll<HTMLElement>("[data-route-backend]")].find(
(element) =>
element.dataset.routeBackend === backend &&
element.dataset.routeModel === modelId,
- ) ?? null;
+ );
+ const opener = row?.querySelector<HTMLElement>(focusableSelector) ?? null;
+ return focusValid(row) ? row : opener;
+};
const exactGroupHead = (
root: HTMLElement,
@@ -42,14 +46,23 @@ export const focusModelHubProjection = ({
activeTarget,
backend,
modelId,
+ preserveCurrentFocus = false,
}: {
root: HTMLElement | null;
activeTarget: HTMLElement | null;
backend: AgentBackend;
modelId: string;
+ preserveCurrentFocus?: boolean;
}): HTMLElement | null => {
if (!root) return null;
+ const currentFocus =
+ preserveCurrentFocus &&
+ document.activeElement instanceof HTMLElement &&
+ document.activeElement !== document.body
+ ? document.activeElement
+ : null;
const candidates = [
+ currentFocus,
activeTarget,
exactModelRow(root, backend, modelId),
exactGroupHead(root, backend),
diff --git a/ui/src/components/settings/models/routeProjectionReconciliation.test.ts b/ui/src/components/settings/models/routeProjectionReconciliation.test.ts
index 8f3d6233a..05f54508d 100644
--- a/ui/src/components/settings/models/routeProjectionReconciliation.test.ts
+++ b/ui/src/components/settings/models/routeProjectionReconciliation.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from "vitest";
import { createRouteProjectionReconciler } from "./routeProjectionReconciliation";
+import type { RouteReport } from "./RouteChainDialog";
import type { AgentSupply, Source } from "./types";
const agent: AgentSupply = {
@@ -21,6 +22,20 @@ const source: Source = {
state: { status: "active", retry_at: null, detail_key: null },
models: [],
};
+const report: RouteReport = {
+ chain: {
+ contract_version: 10,
+ backend: "claude",
+ model_id: "模型/opus",
+ manual_override: null,
+ route_origin: null,
+ chain: [],
+ current: null,
+ supply_state: "interrupted",
+ },
+ removed_hops: [],
+ interrupted: [],
+};
const deferred = <T>() => {
let resolve!: (value: T) => void;
@@ -47,13 +62,15 @@ describe("route projection reconciliation", () => {
onStatus: statuses,
});
- reconciler.start("claude");
+ reconciler.start(report);
expect(readSources).not.toHaveBeenCalled();
agents.resolve({ value: [agent], install: agentInstall });
await vi.waitFor(() => expect(sourceInstall).toHaveBeenCalledTimes(1));
expect(agentInstall).toHaveBeenCalledTimes(1);
expect(readSources).toHaveBeenCalledTimes(1);
expect(statuses).toHaveBeenLastCalledWith({
+ report,
+ reports: [report],
pending: false,
failed: new Set(),
});
@@ -74,12 +91,14 @@ describe("route projection reconciliation", () => {
onStatus: statuses,
});
- reconciler.start("claude");
+ reconciler.start(report);
await vi.waitFor(() => expect(sourceInstall).toHaveBeenCalledTimes(1));
expect(agentInstall).toHaveBeenCalledTimes(1);
expect(readSources).toHaveBeenCalledTimes(1);
expect(statuses).toHaveBeenLastCalledWith({
+ report,
+ reports: [report],
pending: false,
failed: new Set(),
});
@@ -101,9 +120,11 @@ describe("route projection reconciliation", () => {
onStatus: statuses,
});
- reconciler.start("claude");
+ reconciler.start(report);
await vi.waitFor(() =>
expect(statuses).toHaveBeenLastCalledWith({
+ report,
+ reports: [report],
pending: false,
failed: new Set(["agents"]),
}),
@@ -130,9 +151,11 @@ describe("route projection reconciliation", () => {
onStatus: statuses,
});
- reconciler.start("claude");
+ reconciler.start(report);
await vi.waitFor(() =>
expect(statuses).toHaveBeenLastCalledWith({
+ report,
+ reports: [report],
pending: false,
failed: new Set(["sources"]),
}),
@@ -141,4 +164,293 @@ describe("route projection reconciliation", () => {
await vi.waitFor(() => expect(readSources).toHaveBeenCalledTimes(2));
expect(readAgents).toHaveBeenCalledTimes(1);
});
+
+ it.each([false, true])("publishes Agents recovery while Sources is pending (older Sources failure: %s)", async (sourceFailed) => {
+ const sources = deferred<{ value: Source[]; install: () => void }>();
+ const agentInstall = vi.fn();
+ const readAgents = vi.fn().mockResolvedValue({ value: [agent], install: agentInstall });
+ const readSources = vi.fn().mockReturnValue(sources.promise);
+ const statuses = vi.fn();
+ const reconciler = createRouteProjectionReconciler({
+ readAgents, readSources, onFailure: vi.fn(), onStatus: statuses,
+ });
+ if (sourceFailed) {
+ readSources.mockRejectedValueOnce(new Error("older Sources failure"));
+ reconciler.start({ ...report });
+ await vi.waitFor(() => expect(statuses.mock.lastCall?.[0].failed).toEqual(new Set(["sources"])));
+ }
+ readAgents.mockRejectedValueOnce(new Error("Agents failure"));
+ reconciler.start(report);
+ await vi.waitFor(() => expect(statuses.mock.lastCall?.[0]).toMatchObject({
+ pending: false,
+ failed: new Set(sourceFailed ? ["agents", "sources"] : ["agents"]),
+ }));
+ const heldReports = statuses.mock.lastCall![0].reports;
+ reconciler.retry();
+ await vi.waitFor(() => expect(readSources).toHaveBeenCalledTimes(sourceFailed ? 2 : 1));
+ expect(agentInstall).toHaveBeenCalledTimes(sourceFailed ? 2 : 1);
+ expect(statuses).toHaveBeenLastCalledWith({
+ report, reports: heldReports, pending: true,
+ failed: new Set(sourceFailed ? ["sources"] : []),
+ });
+ // An intermediate success is not batch completion or admission to Retry.
+ reconciler.retry();
+ expect(readAgents).toHaveBeenCalledTimes(sourceFailed ? 3 : 2);
+ sources.resolve({ value: [source], install: vi.fn() });
+ await vi.waitFor(() => expect(statuses).toHaveBeenLastCalledWith({
+ report, reports: heldReports, pending: false, failed: new Set(),
+ }));
+ });
+
+ it("queues later reads but immediately publishes the newest commit for focus", async () => {
+ const firstAgents = deferred<{ value: AgentSupply[]; install: () => void }>();
+ const firstSources = deferred<{ value: Source[]; install: () => void }>();
+ const secondAgents = deferred<{ value: AgentSupply[]; install: () => void }>();
+ const secondSources = deferred<{ value: Source[]; install: () => void }>();
+ const firstReport = { ...report, chain: { ...report.chain, model_id: "first" } };
+ const secondReport = { ...report, chain: { ...report.chain, model_id: "second" } };
+ const statuses = vi.fn();
+ const readAgents = vi.fn()
+ .mockReturnValueOnce(firstAgents.promise)
+ .mockReturnValueOnce(secondAgents.promise);
+ const readSources = vi.fn()
+ .mockReturnValueOnce(firstSources.promise)
+ .mockReturnValueOnce(secondSources.promise);
+ const reconciler = createRouteProjectionReconciler({
+ readAgents,
+ readSources,
+ onFailure: vi.fn(),
+ onStatus: statuses,
+ });
+
+ reconciler.start(firstReport);
+ reconciler.start(secondReport);
+ expect(readAgents).toHaveBeenCalledTimes(1);
+ expect(statuses).toHaveBeenLastCalledWith({
+ report: secondReport,
+ reports: [firstReport],
+ pending: true,
+ failed: new Set(),
+ });
+
+ firstAgents.resolve({ value: [agent], install: vi.fn() });
+ await vi.waitFor(() => expect(readSources).toHaveBeenCalledTimes(1));
+ expect(statuses).toHaveBeenLastCalledWith({
+ report: secondReport,
+ reports: [firstReport],
+ pending: true,
+ failed: new Set(),
+ });
+
+ firstSources.resolve({ value: [source], install: vi.fn() });
+ await vi.waitFor(() => expect(readAgents).toHaveBeenCalledTimes(2));
+ expect(statuses).toHaveBeenLastCalledWith({
+ report: secondReport,
+ reports: [secondReport],
+ pending: true,
+ failed: new Set(),
+ });
+
+ secondAgents.resolve({ value: [agent], install: vi.fn() });
+ await vi.waitFor(() => expect(readSources).toHaveBeenCalledTimes(2));
+ secondSources.resolve({ value: [source], install: vi.fn() });
+ await vi.waitFor(() => expect(statuses).toHaveBeenLastCalledWith({
+ report: secondReport,
+ reports: [secondReport],
+ pending: false,
+ failed: new Set(),
+ }));
+ expect(statuses.mock.calls.map(([status]) => status.report)).toEqual([
+ firstReport,
+ secondReport,
+ secondReport,
+ secondReport,
+ secondReport,
+ ]);
+ const firstSettlement = statuses.mock.calls.find(([status]) => !status.pending)![0];
+ expect(firstSettlement.report).toBe(secondReport);
+ expect(firstSettlement.reports).toEqual([firstReport]);
+ });
+
+ it.each(["agents", "sources"] as const)(
+ "settles an older %s failure with the next commit's newer collection reads",
+ async (member) => {
+ const secondAgents = deferred<{ value: AgentSupply[]; install: () => void }>();
+ const firstReport: RouteReport = {
+ ...report,
+ removed_hops: [{ backend: "claude", menu_model: "模型/opus", position: 1, source_id: "source", model_id: "模型/opus" }],
+ };
+ const secondReport: RouteReport = { ...report, chain: { ...report.chain, backend: "codex" } };
+ const statuses = vi.fn();
+ const readAgents = vi.fn().mockResolvedValue({ value: [agent], install: vi.fn() });
+ const readSources = vi.fn().mockResolvedValue({ value: [source], install: vi.fn() });
+ (member === "agents" ? readAgents : readSources).mockRejectedValueOnce(new Error("offline"));
+ const reconciler = createRouteProjectionReconciler({
+ readAgents,
+ readSources,
+ onFailure: vi.fn(),
+ onStatus: statuses,
+ });
+
+ reconciler.start(firstReport);
+ await vi.waitFor(() => expect(statuses).toHaveBeenLastCalledWith({
+ report: firstReport,
+ reports: [firstReport],
+ pending: false,
+ failed: new Set([member]),
+ }));
+
+ readAgents.mockReturnValueOnce(secondAgents.promise);
+ reconciler.start(secondReport);
+ await vi.waitFor(() => expect(readAgents).toHaveBeenCalledTimes(2));
+ expect(statuses).toHaveBeenLastCalledWith({
+ report: secondReport,
+ reports: [firstReport, secondReport],
+ pending: true,
+ failed: new Set([member]),
+ });
+
+ secondAgents.resolve({ value: [agent], install: vi.fn() });
+ await vi.waitFor(() => expect(statuses).toHaveBeenLastCalledWith({
+ report: secondReport,
+ reports: [firstReport, secondReport],
+ pending: false,
+ failed: new Set(),
+ }));
+ // No stale failure is republished; both exact reports reached settlement.
+ expect(statuses.mock.lastCall?.[0].reports[0]).toBe(firstReport);
+ expect(statuses.mock.lastCall?.[0].reports[1]).toBe(secondReport);
+ reconciler.retry();
+ expect(readAgents).toHaveBeenCalledTimes(2);
+ expect(readSources).toHaveBeenCalledTimes(member === "agents" ? 1 : 2);
+ });
+
+ it("continues a queued commit after failure, then retries only the remaining shared failure", async () => {
+ const firstRead = deferred<{ value: AgentSupply[]; install: () => void }>();
+ const secondReport = { ...report, chain: { ...report.chain, model_id: "second" } };
+ const sources = deferred<{ value: Source[]; install: () => void }>();
+ const statuses = vi.fn();
+ const readAgents = vi.fn()
+ .mockReturnValueOnce(firstRead.promise.then(() => { throw new Error("offline"); }))
+ .mockResolvedValue({ value: [agent], install: vi.fn() });
+ const readSources = vi.fn()
+ .mockRejectedValueOnce(new Error("source offline"))
+ .mockReturnValueOnce(sources.promise);
+ const reconciler = createRouteProjectionReconciler({
+ readAgents, readSources, onFailure: vi.fn(), onStatus: statuses,
+ });
+ reconciler.start(report);
+ reconciler.start(secondReport);
+ firstRead.resolve({ value: [agent], install: vi.fn() });
+ await vi.waitFor(() => expect(statuses).toHaveBeenLastCalledWith({
+ report: secondReport, reports: [report, secondReport],
+ pending: false, failed: new Set(["sources"]),
+ }));
+ reconciler.retry();
+ reconciler.retry();
+ expect(readAgents).toHaveBeenCalledTimes(2);
+ expect(readSources).toHaveBeenCalledTimes(2);
+ expect(statuses).toHaveBeenLastCalledWith({
+ report: secondReport, reports: [report, secondReport],
+ pending: true, failed: new Set(["sources"]),
+ });
+ sources.resolve({ value: [source], install: vi.fn() });
+ await vi.waitFor(() => expect(statuses).toHaveBeenLastCalledWith({
+ report: secondReport, reports: [report, secondReport],
+ pending: false, failed: new Set(),
+ }));
+ });
+
+ it("keeps both acquired failures when a later Agents read fails before Sources", async () => {
+ const secondReport = { ...report, chain: { ...report.chain, model_id: "second" } };
+ const statuses = vi.fn();
+ const readAgents = vi.fn().mockResolvedValue({ value: [agent], install: vi.fn() });
+ const readSources = vi.fn()
+ .mockRejectedValueOnce(new Error("first Sources failed"))
+ .mockResolvedValue({ value: [source], install: vi.fn() });
+ const reconciler = createRouteProjectionReconciler({
+ readAgents, readSources, onFailure: vi.fn(), onStatus: statuses,
+ });
+ reconciler.start(report);
+ await vi.waitFor(() => expect(statuses).toHaveBeenLastCalledWith({
+ report, reports: [report], pending: false, failed: new Set(["sources"]),
+ }));
+ readAgents.mockRejectedValueOnce(new Error("second Agents failed"));
+ reconciler.start(secondReport);
+ await vi.waitFor(() => expect(statuses).toHaveBeenLastCalledWith({
+ report: secondReport, reports: [report, secondReport],
+ pending: false, failed: new Set(["agents", "sources"]),
+ }));
+ expect(readSources).toHaveBeenCalledTimes(1);
+ reconciler.retry();
+ await vi.waitFor(() => expect(statuses).toHaveBeenLastCalledWith({
+ report: secondReport, reports: [report, secondReport],
+ pending: false, failed: new Set(),
+ }));
+ expect(readAgents).toHaveBeenCalledTimes(3);
+ expect(readSources).toHaveBeenCalledTimes(2);
+ });
+
+ it("ignores an in-flight generation after page disposal", async () => {
+ const agents = deferred<{ value: AgentSupply[]; install: () => void }>();
+ const install = vi.fn();
+ const readSources = vi.fn();
+ const statuses = vi.fn();
+ const reconciler = createRouteProjectionReconciler({
+ readAgents: () => agents.promise, readSources,
+ onFailure: vi.fn(), onStatus: statuses,
+ });
+ reconciler.start(report);
+ reconciler.start({ ...report });
+ reconciler.invalidate();
+ agents.resolve({ value: [agent], install });
+ await agents.promise;
+ await Promise.resolve();
+ expect(install).not.toHaveBeenCalled();
+ expect(readSources).not.toHaveBeenCalled();
+ expect(statuses).toHaveBeenCalledTimes(2);
+ });
+
+ it.each(["nonempty", "empty", "unavailable"] as const)(
+ "retains exact %s commit tails through pending, failure, Retry and settlement",
+ async (tail) => {
+ const committed: RouteReport = {
+ chain: report.chain,
+ removed_hops: tail === "unavailable" ? null : tail === "empty" ? [] : [{
+ backend: "claude", menu_model: "模型/opus", position: 1,
+ source_id: source.id, model_id: "模型/opus",
+ }],
+ interrupted: tail === "unavailable" ? null : tail === "empty" ? [] : [{
+ backend: "claude", model_id: "模型/opus", agents: ["写作 Agent"],
+ }],
+ };
+ const sources = deferred<{ value: Source[]; install: () => void }>();
+ const statuses = vi.fn();
+ const reconciler = createRouteProjectionReconciler({
+ readAgents: vi.fn().mockResolvedValue({ value: [agent], install: vi.fn() }),
+ readSources: vi.fn()
+ .mockRejectedValueOnce(new Error("offline"))
+ .mockReturnValueOnce(sources.promise),
+ onFailure: vi.fn(),
+ onStatus: statuses,
+ });
+
+ reconciler.start(committed);
+ expect(statuses).toHaveBeenLastCalledWith({
+ report: committed, reports: [committed], pending: true, failed: new Set(),
+ });
+ await vi.waitFor(() => expect(statuses).toHaveBeenLastCalledWith({
+ report: committed, reports: [committed], pending: false, failed: new Set(["sources"]),
+ }));
+ reconciler.retry();
+ expect(statuses).toHaveBeenLastCalledWith({
+ report: committed, reports: [committed], pending: true, failed: new Set(["sources"]),
+ });
+ sources.resolve({ value: [source], install: vi.fn() });
+ await vi.waitFor(() => expect(statuses).toHaveBeenLastCalledWith({
+ report: committed, reports: [committed], pending: false, failed: new Set(),
+ }));
+ for (const [status] of statuses.mock.calls) expect(status.report).toBe(committed);
+ },
+ );
});
diff --git a/ui/src/components/settings/models/routeProjectionReconciliation.ts b/ui/src/components/settings/models/routeProjectionReconciliation.ts
index 980e8642b..9c53ac42e 100644
--- a/ui/src/components/settings/models/routeProjectionReconciliation.ts
+++ b/ui/src/components/settings/models/routeProjectionReconciliation.ts
@@ -1,10 +1,13 @@
-import type { RouteCollectionObservation } from "./RouteChainDialog";
+import type { RouteCollectionObservation, RouteReport } from "./RouteChainDialog";
import type { AgentSupply, Source } from "./types";
-import type { AgentBackend } from "./types";
export type RouteProjectionMember = "agents" | "sources";
export type RouteProjectionStatus = {
+ /** Latest outstanding commit for focus, including a save queued mid-read. */
+ report: RouteReport;
+ /** Only the active batch's reports; queued commits need a later read frontier. */
+ reports: readonly RouteReport[];
failed: ReadonlySet<RouteProjectionMember>;
pending: boolean;
};
@@ -16,8 +19,8 @@ type RouteProjectionReaders = {
onStatus: (status: RouteProjectionStatus) => void;
};
-/** M6 is page-owned: closing the modal changes presentation ownership but never
- * cancels, restarts or broadens the projection generation. */
+/** One page-owned collection reader, with exact evidence for every outstanding
+ * commit. Failed reports do not block a later commit's newer collection reads. */
export const createRouteProjectionReconciler = ({
readAgents,
readSources,
@@ -25,60 +28,81 @@ export const createRouteProjectionReconciler = ({
onStatus,
}: RouteProjectionReaders) => {
let generation = 0;
- let failed = new Set<RouteProjectionMember>();
- let activeBackend: AgentBackend | null = null;
+ let pending = false;
+ const failed = new Set<RouteProjectionMember>();
+ let reports: RouteReport[] = [];
+ const queuedReports: RouteReport[] = [];
- const publish = (pending: boolean) =>
- onStatus({ pending, failed: new Set(failed) });
-
- const settle = async (
- token: number,
- members: ReadonlySet<RouteProjectionMember>,
- ) => {
- failed = new Set();
- publish(true);
+ const publish = () => {
+ const report = queuedReports[queuedReports.length - 1] ?? reports[reports.length - 1];
+ if (report) onStatus({ report, reports: [...reports], pending, failed: new Set(failed) });
+ };
- if (members.has("agents")) {
- try {
- const observation = await readAgents();
- if (token !== generation) return;
- observation.install();
- } catch {
- if (token !== generation) return;
- failed.add("agents");
- onFailure("agents");
- publish(false);
- return;
+ const settle = async (members: ReadonlySet<RouteProjectionMember>) => {
+ const token = ++generation;
+ pending = true;
+ publish();
+ try {
+ if (members.has("agents")) {
+ try {
+ const observation = await readAgents();
+ if (token !== generation) return;
+ observation.install();
+ // Successful mode authority applies now, not after Sources settles.
+ if (failed.delete("agents")) publish();
+ } catch {
+ if (token !== generation) return;
+ failed.add("agents");
+ onFailure("agents");
+ return;
+ }
}
- }
-
- if (members.has("sources") || members.has("agents")) {
- try {
- const observation = await readSources();
- if (token !== generation) return;
- observation.install();
- } catch {
- if (token !== generation) return;
- failed.add("sources");
- onFailure("sources");
+ if (members.has("sources") || members.has("agents")) {
+ try {
+ const observation = await readSources();
+ if (token !== generation) return;
+ observation.install();
+ failed.delete("sources");
+ } catch {
+ if (token !== generation) return;
+ failed.add("sources");
+ onFailure("sources");
+ }
+ }
+ } finally {
+ if (token === generation) {
+ pending = false;
+ publish();
+ if (failed.size === 0) reports = [];
+ beginNext();
}
}
- if (token === generation) publish(false);
+ };
+
+ const beginNext = () => {
+ if (pending || queuedReports.length === 0) return;
+ // All reads in this batch begin after every included commit. A newer full
+ // collection can satisfy older failed obligations without losing evidence.
+ reports.push(...queuedReports.splice(0));
+ void settle(new Set(["agents"]));
};
return {
- start: (backend: AgentBackend) => {
- activeBackend = backend;
- const token = ++generation;
- void settle(token, new Set(["agents"]));
+ start: (committed: RouteReport) => {
+ queuedReports.push(committed);
+ if (pending) publish();
+ else beginNext();
},
retry: () => {
- if (failed.size === 0 || !activeBackend) return;
- const token = ++generation;
- void settle(token, failed);
+ if (pending || failed.size === 0) return;
+ void settle(new Set(failed));
},
invalidate: () => {
generation += 1;
+ pending = false;
+ reports = [];
+ queuedReports.length = 0;
+ failed.clear();
},
};
};
diff --git a/ui/src/context/ToastProvider.test.tsx b/ui/src/context/ToastProvider.test.tsx
new file mode 100644
index 000000000..831bdb106
--- /dev/null
+++ b/ui/src/context/ToastProvider.test.tsx
@@ -0,0 +1,53 @@
+/* @vitest-environment jsdom */
+
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { ToastProvider } from './ToastProvider';
+import { useToast } from './ToastContext';
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+const Trigger = () => {
+ const { showToast } = useToast();
+ return <button type="button" onClick={() => showToast('Saved')}>Save</button>;
+};
+
+describe('ToastProvider', () => {
+ it('announces toast messages through a polite status region', async () => {
+ render(
+ <ToastProvider>
+ <Trigger />
+ </ToastProvider>,
+ );
+
+ await userEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ const toast = screen.getByRole('status');
+ expect(toast.textContent).toContain('Saved');
+ expect(toast.getAttribute('aria-live')).toBe('polite');
+ expect(toast.getAttribute('aria-atomic')).toBe('true');
+ });
+
+ it('refreshes the dismissal lifetime when a visible toast is coalesced', () => {
+ vi.useFakeTimers();
+ render(
+ <ToastProvider>
+ <Trigger />
+ </ToastProvider>,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ act(() => vi.advanceTimersByTime(2500));
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ act(() => vi.advanceTimersByTime(2999));
+ expect(screen.getByRole('status')).toBeTruthy();
+ act(() => vi.advanceTimersByTime(1));
+ expect(screen.queryByRole('status')).toBeNull();
+ });
+});
diff --git a/ui/src/context/ToastProvider.tsx b/ui/src/context/ToastProvider.tsx
index ffe4b5c05..926248e9d 100644
--- a/ui/src/context/ToastProvider.tsx
+++ b/ui/src/context/ToastProvider.tsx
@@ -16,6 +16,9 @@ interface Toast {
action?: ToastAction;
}
+type ToastTimer = number;
+type RecentToast = { id: number; expiresAt: number; timer: ToastTimer };
+
let toastId = 0;
// Dedupe window — within this many ms, an identical message replaces the
@@ -30,7 +33,7 @@ export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ childre
const [toasts, setToasts] = useState<Toast[]>([]);
// Ref so dedupe lookups don't rerender. Maps message -> {id, expiresAt}
// for currently-visible toasts; we evict on auto-dismiss.
- const recentRef = useRef<Map<string, { id: number; expiresAt: number }>>(new Map());
+ const recentRef = useRef<Map<string, RecentToast>>(new Map());
const showToast = useCallback(
(message: string, type: ToastType = 'success', action?: ToastAction) => {
@@ -41,30 +44,51 @@ export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ childre
const now = Date.now();
const existing = recentRef.current.get(message);
if (shouldCoalesceToast(!!action, existing, now)) {
+ window.clearTimeout(existing!.timer);
setToasts((prev) =>
prev.map((t) => (t.id === existing!.id ? { ...t, repeats: t.repeats + 1, type } : t)),
);
+ const timer = window.setTimeout(() => {
+ setToasts((prev) => prev.filter((t) => t.id !== existing!.id));
+ const tracked = recentRef.current.get(message);
+ if (tracked && tracked.id === existing!.id) recentRef.current.delete(message);
+ }, PLAIN_TOAST_MS);
+ recentRef.current.set(message, {
+ id: existing!.id,
+ expiresAt: now + DEDUPE_WINDOW_MS,
+ timer,
+ });
return;
}
const id = ++toastId;
// Only track plain toasts for dedupe; actionable ones are always distinct.
- if (!action) recentRef.current.set(message, { id, expiresAt: now + DEDUPE_WINDOW_MS });
setToasts((prev) => [...prev, { id, message, type, repeats: 0, action }]);
// Auto dismiss (longer for actionable toasts so undo is reachable).
- setTimeout(() => {
+ const timer = window.setTimeout(() => {
setToasts((prev) => prev.filter((t) => t.id !== id));
// Best-effort cleanup of the dedupe map — the entry may have been
// re-issued under a different id during the window.
const tracked = recentRef.current.get(message);
if (tracked && tracked.id === id) recentRef.current.delete(message);
}, action ? ACTION_TOAST_MS : PLAIN_TOAST_MS);
+ if (!action) recentRef.current.set(message, {
+ id,
+ expiresAt: now + DEDUPE_WINDOW_MS,
+ timer,
+ });
},
[],
);
const dismissToast = useCallback((id: number) => {
setToasts((prev) => prev.filter((t) => t.id !== id));
+ for (const [message, tracked] of recentRef.current) {
+ if (tracked.id !== id) continue;
+ window.clearTimeout(tracked.timer);
+ recentRef.current.delete(message);
+ break;
+ }
}, []);
// Stable value identity so the ~34 consumers of useToast don't re-render every
@@ -80,6 +104,9 @@ export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ childre
{toasts.map((toast) => (
<div
key={toast.id}
+ role="status"
+ aria-live="polite"
+ aria-atomic="true"
className={`flex items-center gap-3 px-4 py-3 rounded-lg shadow-lg border animate-slide-in ${
toast.type === 'success'
? 'bg-mint/10 border-mint/30 text-mint-ink'