Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(model-hub): simplify routing saves and connection status (#2059)
Call White2283ed91e914
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 252df60db..40e71f3e7 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -128,7 +128,10 @@ failure preserves manual entries and does not block saving. Custom Auto withoutis rejected before credential provisioning. Manual models remain manual; no inventoryis invented. The Source carries an opaque `verification_pending` marker, independently of itsrouting health, and may be configured and invoked. List/detail surfaces label it-unverified, not healthy/in use. Successful inventory discovery never clears this flag.+Saved / 已保存 in neutral styling, not unverified, healthy or in use; real error,+needs-action and cooldown states retain precedence. The accessible hint describes+stored configuration, not a guaranteed connection or a universally available Test action.+Successful inventory discovery never clears this flag.A newly stored Hub credential starts pending unless an add-time observationauthenticated it, so an explicit unverified save and a native-config import alwaysstart pending while an observed api-key create does not. A call captures the persisted marker before invocation; anydiff --git a/docs/plans/model-hub-e2e-test-plan.md b/docs/plans/model-hub-e2e-test-plan.mdindex b5bb82d5e..851fcd2f5 100644--- a/docs/plans/model-hub-e2e-test-plan.md+++ b/docs/plans/model-hub-e2e-test-plan.md@@ -98,7 +98,7 @@ Out of scope (documented, not dropped silently):| ID | Steps | Expect | Status ||---|---|---|---|| G1 | guard echo with a gap missing `agents` | no confirm-loop (B7) — fix-first; baseline documents | fix-first |-| G2 | Sources PUT and compatibility chains/reorder change defaults | same effective guard plan and canonical projection; manual arrays unchanged; omitted reorder order is read-only | assert |+| G2 | Sources PUT and compatibility chains/reorder change defaults | same effective guard plan and canonical projection; manual arrays unchanged; omitted reorder order is read-only. Default-routing UI Save automatically echoes one exact refusal plan without a second confirmation; changed-plan refusal keeps the draft, and lost responses reconcile before any new write | assert || G3 | malformed JSON on mode/chain routes | error code distinguishable from business refusals (B13) | fix-first |### H. Cross-protocol functional floor (owner ruling baseline)@@ -116,7 +116,7 @@ Out of scope (documented, not dropped silently):| RM-2 | Automatic matching precedes passthrough, and live health/transport restrictions never choose another tier | All backends with API-key unknown passthrough only, unmatched subscription-only defaults Unconfigured, known-model subscription admission and stale-hop retention, native Claude aliases/date/version rules, complete non-retired evidence, literal API matching, native-only matching with Hub-only invocation, tombstones and empty inventories || RM-3 | One planning input produces identical effective hops/origin in preview, read/list, summaries, adoption, guards, probe, launch and execution | Real API/controller boundaries, assert canonical model ids and Source ids; unknown inventory carries no invented reasoning tiers || RM-4 | Restore/Undo/Cancel/Save preserve normalized draft and persistence truth, including final-hop removal | Browser GET -> edit -> remove final hop or Restore -> preview null -> Undo to prior unsaved draft or Cancel -> reload; inherited Save uses DELETE, nonempty manual Save uses PUT even when equal to automatic. Cover actual inherited origin/targets or Unconfigured, no empty Manual save, failed saves, stale preview, confirmation, Done and duplicate submission |-| RM-5 | Effective removal confirmation is exact and atomic for defaults/Restore/inventory/catalog/Source writes | Refuse, alter state, retry stale plan, confirm current plan; no partial writes. Empty PUT and DELETE have identical effective-removal/supply guards, idempotency, admission/lease and rollback behavior; only nonempty manual PUT retains the visible-edit interruption-only guard. A cascade removing the final hop drops its override before recomputing inherited impact; pure reorders preserve nonempty manual arrays and need no confirmation |+| RM-5 | Effective removal wire confirmation is exact and atomic for defaults/Restore/inventory/catalog/Source writes | Refuse, alter state, retry stale plan, confirm current plan; no partial writes. Default-routing Save performs one automatic exact-plan confirmation with no second user action, stops on a changed-plan refusal and reconciles lost responses before replay; Restore/inventory/catalog/Source UI confirmations remain. Empty PUT and DELETE have identical effective-removal/supply guards, idempotency, admission/lease and rollback behavior; only nonempty manual PUT retains the visible-edit interruption-only guard. A cascade removing the final hop drops its override before recomputing inherited impact; pure reorders preserve nonempty manual arrays and need no confirmation || RM-6 | Pinned CPA reaches the selected upstream with the exact canonical unknown model, without fake inventory or cross-Source fallback | Real backend launch -> correlation/gateway -> adapter -> pinned CPA -> local upstream; Hub API-key credentials on all API protocols and admitted non-ASCII ids/payloads; no subscription expansion || RM-7 | Transport registration remains separate from inventory and capabilities | Compare truthful SourceBinding.model_ids/Source.models with deterministic route_model_ids and compiler union; load absent field as empty; unchanged target sets do not restart; registration changes drain active transport leases before supervised restart, block new invocations behind the barrier and release leases on completion/close/cancellation independently of service settlement; prove sync cancellation/rollback and concurrent Save without deadlock; Hub OAuth registration remains unchanged || RM-8 | Request-only unknown-model errors preserve Source health and existing failure/stream boundaries | Typed upstream model_not_found, exact Source/model attribution, no fallback or global health transition |@@ -135,6 +135,7 @@ the end-to-end properties above; these are actual consuming tests, not proposed| Property | Existing consuming test || --- | --- |+| G2/RM-5: one-click defaults, bounded exact-plan handshake and lost-response reconciliation | `ui/src/components/settings/models/SourceOrderDrawer.test.tsx` || RM-1/RM-3/RM-11: absent/empty parity across consumers | `tests/test_model_hub_routing_modes.py::test_empty_override_equals_absence_at_all_route_consumers` || RM-4/RM-5: empty PUT equals guarded Restore; final-hop deletion inherits | `tests/test_model_hub_routing_modes.py::test_empty_put_has_exact_restore_guard_and_final_hop_deletion_inherits` || RM-9: original invalid input never becomes automatic | `tests/test_model_hub_routing_modes.py::test_invalid_empty_intent_is_validated_before_normalization` |diff --git a/docs/plans/model-hub-routing-modes.md b/docs/plans/model-hub-routing-modes.mdindex 46fc8e908..f268c4354 100644--- a/docs/plans/model-hub-routing-modes.md+++ b/docs/plans/model-hub-routing-modes.md@@ -185,7 +185,11 @@ Approved design: `avibe-docs/design.pen`, frames `bmi25` (dark), `ziils` (light)the row dialog. Escape and outside interaction dismiss help. Avoid nested buttons.- Rename Adjust priority to Default routing. It edits one backend's defaultmembership/order; manual routes are independent. Show affected inherited/manual- counts without implying historical authorship or runtime health.+ counts without implying historical authorship or runtime health. One Save authorizes+ the inherited-route impact without a second user confirmation. On a named impact+ refusal, echo the exact server plan once; a changed plan or another failure preserves+ the draft. Read canonical defaults after an ambiguous write before writing again.+ This does not remove the server guard or change manual-route/Source confirmations.- Owner amendment 2026-09-08: route dialogs open directly editable. Only actualedits or explicit Pin current route stage manual intent; opening/picker dismissaland no-op edits preserve inheritance. Keep add/edit/remove/reorder and exactdiff --git a/docs/plans/model-hub-save-first-testing.md b/docs/plans/model-hub-save-first-testing.mdindex 7ec838849..dd25b8be3 100644--- a/docs/plans/model-hub-save-first-testing.md+++ b/docs/plans/model-hub-save-first-testing.md@@ -15,6 +15,10 @@ not subscription OAuth admission or credential replacement.- `verification_pending` remains until a real invocation succeeds for thatcredential identity. Existing explicit observation APIs remain available toolder callers; the dialog does not call them.+- Pending Sources use neutral Saved / 已保存 presentation, not a warning or+ health claim. Error, needs-action and cooldown states retain precedence. The+ accessible connection hint describes saved configuration and successful-call+ status updates without promising a Test entry for subscriptions/native Sources.- Test is a separate, explicitly initiated action on a saved API-key Source.It offers all non-retired discovered or manual models without reordering theinventory. A centrally maintained ordered preference list selects the firstdiff --git a/docs/plans/model-hub-ui-spec.md b/docs/plans/model-hub-ui-spec.mdindex 8ff0523c5..0bd163b28 100644--- a/docs/plans/model-hub-ui-spec.md+++ b/docs/plans/model-hub-ui-spec.md@@ -347,11 +347,11 @@ half named in its Missing cell has an owner.| # | Surface | Missing | Evidence / disposition (contract baseline `1993f4fd0`) || --- | --- | --- | --- || G-3 | 06 model inventory — **retirement is contracted; its discovered-row affordance remains open** | a way to retire a *discovered* model from the drawn inventory; ~~a place to remember that it was retired~~ | `DELETE /api/models/sources/<source_id>/models/<model_id>` now persists `models[].retired: true` for a discovered row instead of deleting it. `source.schema.json` keeps that row readable, never supplying, and refresh never revives it; §4.5 applies the same exact-hop and last-supplier guards. §1.6 registers that representation as the ordinary row chrome with muted ink and the existing tag component. Frame 06 still draws removal only for manual entries, so no registered control invokes the discovered-row route; only that producer half remains live instead of treating wire reachability as a UI consumer. |-| G-9 | Default membership guard, revised 2026-09-06 | Existing exact-plan fields | Sources PUT and compatibility reorder compare effective plans. Pure reorder needs no guard; removal may require confirmation. Closed by the routing contract. |+| G-9 | Default membership guard | Existing exact-plan fields | Sources PUT and compatibility reorder compare effective plans. Pure reorder needs no guard; membership removal may require an exact-plan wire confirmation. Default routing Save performs that handshake once without a second user confirmation (§1.3). || G-10 | 01 shell pill, install in flight — **and 08's 安装并切换**, the other press that promises one — **registered against the runtime install contract** | ~~a server-side install state, and the route that enters it~~ nothing | `POST /api/models/runtime/install` is the idempotent producer. `RuntimeDependency.status.health: installing` survives reload, successful verification settles at `not_started`, and failure settles at `not_installed` with the closed `status.error_key`. §1.0 and §1.9 consume that one machine; any mounted surface observing durable `installing` owns the derived 2s status loop, while a held initiating sequence only decides whether settlement lands at Not started or continues through Starting. Unmount stops the loop; reload owns G-10's first read and restores no intent. || G-11 | 09 direct-only home, zero backends — **registered against AgentSupply** | ~~an installation flag per agent backend, and the payload that carries it~~ nothing | Every `GET /api/models/agents` row now carries server-authoritative `cli_present`; the zero-installed state is exactly all rows false. §1.8 derives `installedAgents` once from that field and uses the same set for mode dispatch, rows and the count pill. Source presence is evaluated first so an empty installed set cannot hide retained Sources; only `sources == []` + the empty set enters No backend found. || G-12 | 01 upstream card and 06 header, `needs_action` — **registered by frame 12** | ~~the control that replaces a dead credential~~ nothing | §1.11 registers the two repair producers drawn on the source cards: 更换 Key sends the credential-replacement flow to `PUT /api/models/sources/<id>/credential`, and 重新授权 starts `POST /api/models/sources/<id>/reauth`. §1.1 and §1.6 cite that owner instead of pointing at each other. Kept as a registered row so the former absence and its closing frame remain auditable |-| G-13 | Default routing save | Complete default order and guard plan | Sources PUT preserves manual arrays and returns authoritative AgentSupply. Failed saves retain the draft. |+| G-13 | Default routing save | Complete default order and guard plan | One Save applies defaults and their inherited-route impact, automatically echoing one exact server plan if needed. Sources PUT preserves manual arrays and returns authoritative AgentSupply. A changed plan or failed save retains the draft; an ambiguous outcome is read back before another write. || G-14 | 08 adopt-gateway confirm, `effects.1` — **registered against the mode transaction** | ~~the adoption itself: turning the backend's existing CLI login into that backend's first `native_cli` Source~~ nothing | A qualifying `direct` → `hub` mode `PATCH` now atomically adopts the recognized CLI login as the first singleton `native_cli` Source and returns the updated `AgentSupply`; an absent or unrecognized login or an existing native Source creates and reorders nothing, and repeats create no duplicate. §1.9's consequence pair states both branches and never treats `cli_present` as recognition evidence; its M5 handoff rereads Sources before the committed result lands because the response cannot carry the possibly created Source. || G-15 | 06 source detail, a source's own name and Base URL — **registered by frame 11** | ~~any affordance that edits them~~ nothing | §1.10 registers the overflow action, edit dialog and guarded `PATCH /api/models/sources/<id>` producer drawn in frame 11. Kept as a registered row so the former absence and its closing frame remain auditable || G-16 | 01 upstream card and 06 source detail — **registered by frame 11** | ~~any affordance that removes a source~~ nothing | §1.10 registers the overflow action and the source-removal guard dialog drawn in frame 11 for `DELETE /api/models/sources/<id>`. The existing 06 model-row 移除 remains a different operation. Kept as a registered row so the former ambiguity and its closing frame remain auditable |@@ -823,7 +823,8 @@ was writing into before it re-sends — a row already sitting there closes as this, rather than colliding with itself. An unguarded idempotent replacement may owe nothingextra only when its computed guard plan is empty. §1.3 default membership saves mayhave effective impact: retain the draft, read canonical defaults after ambiguous results,-and apply the existing exact-plan confirmation before another write.+and, on a fresh Save, apply §1.3's bounded automatic exact-plan handshake without+a second user confirmation.§1.2 is deliberately different even though it also replaces an array: the writehas a guarded plan and response-only impact evidence, so D-36 reads the exact Route beforeany resend and an inferred commit marks that evidence unavailable. Which side a state@@ -2708,12 +2709,17 @@ server projections without claiming historical human authorship or current healtRead `AgentSupply.sources.order` and eligibility; save the complete subset with`PUT /api/models/agents/<backend>/sources`. Optional `force`, `would_remove_hops`-and `would_interrupt` follow the existing exact-plan guard. Pure reordering needs no-guard; membership removal can remove effective hops or supply and must display the-actual refusal, echoing both arrays unchanged on confirmation. Success returns the-authoritative `{agent: AgentSupply}`; reconcile chains and adoption through existing-reads. A failed or ambiguous save keeps the draft and reads canonical defaults before-another write. Switching backends cannot reuse another backend's draft.+and `would_interrupt` follow the existing exact-plan guard. One Save authorizes the+selected defaults and their inherited-route impact; there is no secondary confirmation+surface. Pure reordering needs no guard. If the initial request receives a named+`source_in_route_chain` or `source_last_supplier` refusal with a nonempty impact plan,+automatically retry once with `force: true` and both arrays echoed unchanged. A second+refusal, including a changed plan, is a save failure, not another automatic retry.+Success returns the authoritative `{agent: AgentSupply}`; reconcile chains and adoption+through existing reads. Failed saves retain the draft. An ambiguous result from either+request requires reading canonical defaults before any later write; an observed matching+order closes successfully without replay. Switching backends cannot reuse another+backend's draft. Manual-route and Source-management confirmations are unchanged.Both include and exclude actions exist. Sources outside defaults remain available formanual routes. Empty defaults are valid and leave inherited routes Unconfigured; existing@@ -2739,7 +2745,7 @@ independent. Helpers must respect existing fallback and streaming boundaries.| Dialog footer action | Restore automatic | 恢复自动 || Draft recovery | Undo restore | 撤销恢复 |-Reuse existing localized Save/Cancel/Retry and guard-impact copy. Origin-help behavior+Reuse existing localized Save/Cancel/Retry and save-failure copy. Origin-help behaviorfollows the routing revision above. Compatibility chains/reorder is not the new UI savepath; when called it uses the same default guards and preserves manual arrays.@@ -3299,11 +3305,16 @@ held evidence as before. The footer wraps on narrow screens. This supersedes theobservation prerequisite in the earlier state tables, not cancellation, settlementor focus ownership. No upstream observation gates this exit; the bounded inventoryrequest it attempts fills the model list and can never admit the Source.-Source list/detail show `sourceDetail.status.unverified` in existing advisory ink;-error/cooldown states retain visual precedence. Adoption and model discovery cannot-replace this label with healthy/in-use copy. Only an actual successful model call-retires verification as defined by the Source contract. Ambiguity copy must not-claim authentication success.+Source list/detail now show `sourceDetail.status.saved` (Saved / 已保存) in neutral+muted text and dot styling while verification is pending; this replaces the earlier+advisory unverified presentation. Error, needs-action and cooldown states retain visual+precedence. The keyboard-accessible connection hint explains that configuration is+stored and status updates after a successful model request with the current configuration.+It is shared by API-key, Hub-subscription and native Sources, so it must not promise+an optional Test entry that some Sources do not have. Adoption and model discovery+cannot replace this label with healthy/in-use copy. Only an actual successful model+call retires verification as defined by the Source contract. Saved is not an+authentication or health claim.**2026-09-07 owner ruling, later the same day — ①″ is reachable again under a pin ora declaration.** The model-independent probe the ruling above introduced cannot@@ -3318,9 +3329,10 @@ where it landed before, 未验证保存 included. This adds no state, no stringfooter action: `addKey.protocol.catalogPinned.hint` still says the pin is notcredential proof, `addKey.pull.result` counts the models that list returned, and theunverified exit becomes the fallback rather than the only way out. A Source that left-through ①″ has nothing pending, so list/detail do not label it-`sourceDetail.status.unverified`; that label keeps its meaning — nothing upstream has-accepted this credential yet.+through ①″ has nothing pending on this legacy observed-create path, so list/detail+use its ordinary health presentation rather than the pending Saved label. Current+save-first creation retains the marker until successful invocation; Saved describes+persisted configuration, not whether an upstream has accepted the credential.**Element inventory**@@ -3723,7 +3735,9 @@ How that is satisfied is an implementation choice — search, grouping, recent usomething else. This file deliberately names no control for it: naming one would turn aproperty into a fixture and freeze the weakest implementation that happens to pass.-**The removal confirmation is one surface, and every guarded change uses it** `[frame]`.+**Source-management and model-route removal confirmations share one surface** `[frame]`.+Default routing Save is the exception defined in §1.3: it uses the same server guard+without this second user confirmation.`Qp6FI` is 520 wide, `$--surface`, `radius 14`, `$--border-strong`, with the standardouter shadow. Head `kCVJB` `padding [16,20]` `gap 4` with a bottom border: title `R4NNdG`Inter 15 / 700 naming the exact operation (「从 aihub 移除 ernie-5.0」), subtitle `I8g2k`diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.mdindex 44d77b172..661c257f8 100644--- a/docs/plans/model-hub.md+++ b/docs/plans/model-hub.md@@ -414,8 +414,11 @@ of health and routing eligibility. It marks a credential nothing upstream hasaccepted yet, so an API-key create whose add-time observation authenticated thecredential stores none — superseding, for that path only, the earlier rule that everyobserved create is marked. Native-config imports, Hub OAuth admission and every-credential or endpoint replacement still get one. Source list/detail use the-existing advisory treatment instead of healthy/in-use copy. Inventory never clears it.+credential or endpoint replacement still get one. Source list/detail use neutral+Saved / 已保存 instead of advisory unverified or healthy/in-use copy; real+error, needs-action and cooldown states retain precedence. The shared accessible+connection hint explains saved configuration and successful-call status updates,+without promising a Test entry for every Source kind. Inventory never clears it.A call captures the marker before invocation; any successful same-credential callwith that marker, including the existing backend probe, clears it in a fresh sharedconfig transaction. Later same-credential attempts do not invalidate success.diff --git a/ui/e2e/model-catalog/gateway-layout.spec.ts b/ui/e2e/model-catalog/gateway-layout.spec.tsindex 1d8e6b13e..c50151ddb 100644--- a/ui/e2e/model-catalog/gateway-layout.spec.ts+++ b/ui/e2e/model-catalog/gateway-layout.spec.ts@@ -53,6 +53,14 @@ for (const backend of ['claude', 'codex', 'opencode']) {await expect(mapping).toContainText('Primary');expect(mappingBox.y).toBeGreaterThanOrEqual(idBox.y + idBox.height);expect(Math.abs(mappingBox.x - idBox.x)).toBeLessThanOrEqual(1);+ for (const row of await card.locator('[data-route-model]').all()) {+ const [rowBox, badgeBox, chevronBox] = await Promise.all([+ box(row), box(row.locator('.model-hub-route-origin')), box(row.locator('.model-hub-overview-chevron')),+ ]);+ expect(Math.abs(centerY(badgeBox) - centerY(chevronBox))).toBeLessThanOrEqual(1);+ expect(Math.abs(centerY(badgeBox) - centerY(rowBox))).toBeLessThanOrEqual(1);+ expect(badgeBox.x + badgeBox.width).toBeLessThan(chevronBox.x);+ }expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);if (width === widths[0]) {await main.screenshot({ path: testInfo.outputPath('gateway-layout.png'), scale: 'css' });diff --git a/ui/e2e/model-catalog/gatewayFixture.tsx b/ui/e2e/model-catalog/gatewayFixture.tsxindex c7eb41f3c..fa777a9c4 100644--- a/ui/e2e/model-catalog/gatewayFixture.tsx+++ b/ui/e2e/model-catalog/gatewayFixture.tsx@@ -13,6 +13,7 @@ export function GatewayFixture() {const backend = requestedBackend === 'claude' || requestedBackend === 'codex' ? requestedBackend : 'opencode';const direct = params.get('mode') === 'direct';const ids = ['claude-fable-5', 'claude-opus-4-8', 'claude-fable-5-1', 'claude-opus-5', 'claude-sonnet-5'];+ const origins = ['automatic', 'passthrough', 'manual', 'automatic', 'automatic'] as const;const source: Source = {id: 'src_fixture', display_name: 'Primary', kind: 'api_key', vendor: 'anthropic',protocol: 'anthropic', supply_channel: 'hub', billing: 'metered', last_discovered_at: null,@@ -24,7 +25,7 @@ export function GatewayFixture() {catalog_models: status === 'empty' ? [] : ids.map((id) => ({ ...blankBackendModel(), id })),sources: { order: [source.id], eligibility: [{ source_id: source.id, eligible: true }] },model_supply: status === 'unknown' ? [] : ids.map((model_id, index) => ({- model_id, route_origin: 'automatic', chain_length: status === 'unconfigured' ? 0 : 1,+ model_id, route_origin: origins[index], chain_length: status === 'unconfigured' ? 0 : 1,has_runnable_hop: status === 'available' || (status === 'partial' && index === 0),})),named_agents: [{@@ -33,8 +34,9 @@ export function GatewayFixture() {route_reason: 'route_unconfigured', supply_status: 'interrupted',}],};- const chains = Object.fromEntries(ids.map((model_id) => [modelChainKey(backend, model_id), readyRegion<AgentChain>({- contract_version: 10, backend, model_id, route_origin: 'automatic', manual_override: null,+ const chains = Object.fromEntries(ids.map((model_id, index) => [modelChainKey(backend, model_id), readyRegion<AgentChain>({+ contract_version: 10, backend, model_id, route_origin: origins[index],+ manual_override: origins[index] === 'manual' ? { hops: [{ source_id: source.id, model_id }] } : null,current: { source_id: source.id, model_id }, supply_state: 'ok',chain: [{ source_id: source.id, model_id, channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }],})]));diff --git a/ui/src/components/settings/models/AgentCard.tsx b/ui/src/components/settings/models/AgentCard.tsxindex a6ef48f18..e3bad2ad6 100644--- a/ui/src/components/settings/models/AgentCard.tsx+++ b/ui/src/components/settings/models/AgentCard.tsx@@ -97,10 +97,7 @@ const ModelRow: React.FC<{><button type="button" className="model-hub-model-open absolute inset-0 rounded-[inherit]" aria-label={openRouteLabel} onClick={(event) => onOpenRoute(agent, modelId, event.currentTarget)} /><span className="pointer-events-none flex min-w-0 flex-1 flex-col justify-center gap-0.5 pr-1">- <span className="flex min-w-0 items-center gap-[7px]">- <span className="min-w-0 flex-1 truncate font-mono text-[12px] font-medium text-foreground" title={modelId}>{modelId}</span>- <span className="pointer-events-auto relative shrink-0"><RouteOriginBadge origin={routeOrigin} backend={agent.backend} open={originHelpOpen} onOpenChange={onHelpOpenChange} /></span>- </span>+ <span className="min-w-0 truncate font-mono text-[12px] font-medium text-foreground" title={modelId}>{modelId}</span>{hasCurrentMapping ? (<spanclassName={cn('model-hub-model-current min-w-0 truncate text-left text-[10.5px]', takeover && 'model-hub-model-current--takeover')}@@ -113,6 +110,7 @@ const ModelRow: React.FC<{<span className={cn('model-hub-model-current min-w-0 truncate text-left text-[10.5px]', supplyState === 'paused' && 'model-hub-ink-gold')} title={currentCopy}>{currentCopy}</span>)}</span>+ <span className="relative flex shrink-0 items-center"><RouteOriginBadge origin={routeOrigin} backend={agent.backend} open={originHelpOpen} onOpenChange={onHelpOpenChange} /></span><ChevronRight className="model-hub-overview-chevron pointer-events-none size-[15px] shrink-0" aria-hidden="true" /></div>);diff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsxindex 3401fb9c2..85daff016 100644--- a/ui/src/components/settings/models/SourceDetailPanel.test.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx@@ -1052,6 +1052,26 @@ describe('SourceDetailPanel', () => {await waitFor(() => expect(screen.queryByText(/serves a route through it|它就会显示为使用中/i)).toBeNull());});+ it.each((['en', 'zh'] as const).flatMap((lng) => [+ { lng, kind: 'api_key', supply_channel: 'hub', hasTest: true },+ { lng, kind: 'subscription', supply_channel: 'hub', hasTest: false },+ { lng, kind: 'subscription', supply_channel: 'native_cli', hasTest: false },+ { lng, kind: 'api_key', supply_channel: 'native_cli', hasTest: false },+ ] as const))('explains saved $kind/$supply_channel status without promising a test entry in $lng', async ({ lng, kind, supply_channel, hasTest }) => {+ const locale = i18n.cloneInstance({ lng });+ render(<ToastProvider><I18nextProvider i18n={locale}>+ <ReportOwnedPanel source={{ ...source, kind, supply_channel, verification_pending: 'vp_fixture' }} trackMutation={immediateTrack} onReauth={noReauth} />+ </I18nextProvider></ToastProvider>);+ expect(screen.getByText(locale.t('settings.models.sourceDetail.status.saved'))).toBeTruthy();+ expect(Boolean(screen.queryByRole('button', { name: locale.t('settings.models.sourceTest.open') }))).toBe(hasTest);+ const hint = screen.getByRole('button', { name: locale.t('settings.models.sourceDetail.status.savedHintLabel') });+ hint.focus();+ await userEvent.keyboard('{Enter}');+ const explanation = await screen.findByText(locale.t('settings.models.sourceDetail.status.savedHint'));+ expect(explanation.textContent).toMatch(/successful.*request|成功调用/);+ expect(explanation.textContent).not.toMatch(/test|测试/i);+ });+it('sends a manual-model removal before showing any guarded-change confirm', async () => {const remove = vi.spyOn(modelsApi, 'deleteCustomModel').mockResolvedValueOnce(source);renderPanel();diff --git a/ui/src/components/settings/models/SourceOrderDrawer.test.tsx b/ui/src/components/settings/models/SourceOrderDrawer.test.tsxindex 6fa90df0f..48739d8bc 100644--- a/ui/src/components/settings/models/SourceOrderDrawer.test.tsx+++ b/ui/src/components/settings/models/SourceOrderDrawer.test.tsx@@ -188,20 +188,65 @@ describe('SourceOrderDrawer keyboard ordering', () => {await waitFor(() => expect(modelsApi.putAgentSources).toHaveBeenCalledWith('claude', { order: ['src_b', 'src_a'] }));});- it('echoes the exact effective-removal guard before saving default membership', async () => {+ it('MH-ROUTING-003: saves default membership and exact route impact with one click', async () => {const user = userEvent.setup();const hops = [{ backend: 'claude' as const, menu_model: 'model-a', position: 1, source_id: 'src_a', model_id: 'model-a' }];+ const gaps = [{ backend: 'claude' as const, model_id: 'model-a', agents: ['Release bot'] }];+ const committed = { ...agent, sources: { ...agent.sources!, order: ['src_b'] } };vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent);const put = vi.spyOn(modelsApi, 'putAgentSources')- .mockRejectedValueOnce(new ApiCallError('source_in_route_chain', undefined, true, [], [], hops))- .mockResolvedValueOnce({ ...agent, sources: { ...agent.sources!, order: ['src_b'] } });- renderDrawer();+ .mockRejectedValueOnce(new ApiCallError('source_in_route_chain', undefined, true, gaps, [], hops))+ .mockResolvedValueOnce(committed);+ const onSaved = vi.fn();+ const onClose = vi.fn();+ renderDrawer({ onSaved, onClose });await user.click((await screen.findAllByRole('button', { name: 'Remove from order' }))[0]);await user.click(screen.getByRole('button', { name: 'Save default routing' }));- await screen.findByText('Review affected routes');- expect(put).toHaveBeenCalledTimes(1);+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());+ expect(put).toHaveBeenCalledTimes(2);+ expect(put).toHaveBeenLastCalledWith('claude', { order: ['src_b'], force: true, would_remove_hops: hops, would_interrupt: gaps });+ expect(onSaved).toHaveBeenCalledWith(committed);+ expect(screen.queryByText('Review affected routes')).toBeNull();+ });++ it('retains the draft when the route impact changes during the save without looping', async () => {+ const user = userEvent.setup();+ const gaps = [{ backend: 'claude' as const, model_id: 'model-a', agents: ['Release bot'] }];+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent);+ const put = vi.spyOn(modelsApi, 'putAgentSources')+ .mockRejectedValueOnce(new ApiCallError('source_last_supplier', undefined, true, gaps))+ .mockRejectedValueOnce(new ApiCallError('source_last_supplier', undefined, true, [+ ...gaps, { backend: 'claude', model_id: 'model-b', agents: ['New agent'] },+ ]));+ const onClose = vi.fn();+ renderDrawer({ onClose });+ await user.click((await screen.findAllByRole('button', { name: 'Remove from order' }))[0]);+ await user.click(screen.getByRole('button', { name: 'Save default routing' }));+ await screen.findByRole('button', { name: 'Retry' });+ expect(put).toHaveBeenCalledTimes(2);+ expect(put).toHaveBeenLastCalledWith('claude', { order: ['src_b'], force: true, would_remove_hops: [], would_interrupt: gaps });+ expect(screen.getByRole('button', { name: 'Reorder source' }).closest('li')?.textContent).toContain('Backup');+ expect(screen.getByRole('button', { name: 'Add to order' })).toBeTruthy();+ expect(onClose).not.toHaveBeenCalled();+ });++ it('reconciles a lost response to the automatic confirmation without replaying the write', async () => {+ const user = userEvent.setup();+ const committed = { ...agent, sources: { ...agent.sources!, order: ['src_b'] } };+ const gaps = [{ backend: 'claude' as const, model_id: 'model-a', agents: ['Release bot'] }];+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValueOnce(agent).mockResolvedValueOnce(committed);+ const put = vi.spyOn(modelsApi, 'putAgentSources')+ .mockRejectedValueOnce(new ApiCallError('source_last_supplier', undefined, true, gaps))+ .mockRejectedValueOnce(new TypeError('response lost'));+ const onSaved = vi.fn();+ const onClose = vi.fn();+ renderDrawer({ onSaved, onClose });+ await user.click((await screen.findAllByRole('button', { name: 'Remove from order' }))[0]);await user.click(screen.getByRole('button', { name: 'Save default routing' }));- await waitFor(() => expect(put).toHaveBeenLastCalledWith('claude', { order: ['src_b'], force: true, would_remove_hops: hops, would_interrupt: [] }));+ await user.click(await screen.findByRole('button', { name: 'Retry' }));+ await waitFor(() => expect(onSaved).toHaveBeenCalledWith(committed));+ expect(onClose).toHaveBeenCalledOnce();+ expect(put).toHaveBeenCalledTimes(2);});it('reconciles an unknown order write without resubmitting the mutation', async () => {const user = userEvent.setup();diff --git a/ui/src/components/settings/models/SourceOrderDrawer.tsx b/ui/src/components/settings/models/SourceOrderDrawer.tsxindex 5129c9c1b..cfe091ff0 100644--- a/ui/src/components/settings/models/SourceOrderDrawer.tsx+++ b/ui/src/components/settings/models/SourceOrderDrawer.tsx@@ -10,8 +10,7 @@ import { ModelHubInfoHint } from './ModelHubInfoHint';import { PROTOCOL_COPY_KEYS } from './addApiKeyState';import type { PendingWrite } from './asyncLifetime';import type { CollectionReadAuthority } from './collectionReadAuthority';-import { apiFailure, modelsApi, type GuardConfirmation } from './modelsApi';-import { GuardGapList } from './GuardGapList';+import { apiFailure, modelsApi } from './modelsApi';import { mayHaveWritten } from './repair';import { movedOrder, sameIds } from './reorder';import { combineSourceOrderReads } from './sourceOrderComposition';@@ -101,7 +100,6 @@ export const SourceOrderDrawer: React.FC<{const [readState, setReadState] = React.useState<ReadState>('loading');const [order, setOrder] = React.useState<string[]>([]);const [saveFailed, setSaveFailed] = React.useState(false);- const [guard, setGuard] = React.useState<GuardConfirmation | null>(null);const [unknownWrite, setUnknownWrite] = React.useState(false);const [grabbedId, setGrabbedId] = React.useState<string | null>(null);const [announcement, setAnnouncement] = React.useState<OrderAnnouncement>(null);@@ -119,7 +117,6 @@ export const SourceOrderDrawer: React.FC<{setSaved(nextOrder);setOrder(nextOrder);setSaveFailed(false);- setGuard(null);setUnknownWrite(false);setGrabbedId(null);setAnnouncement(null);@@ -236,7 +233,7 @@ export const SourceOrderDrawer: React.FC<{}};- const save = (confirmation?: GuardConfirmation) => {+ const save = () => {if (saving || readState !== 'ready') return;void orderWrite.track(async () => {try {@@ -251,7 +248,20 @@ export const SourceOrderDrawer: React.FC<{setSaveFailed(true);return;}- const echoed = await modelsApi.putAgentSources(agent.backend, { order, ...confirmation });+ const echoed = await modelsApi.putAgentSources(agent.backend, { order }).catch((error: unknown) => {+ const failure = apiFailure(error);+ if (!failure || mayHaveWritten(failure)+ || !['source_in_route_chain', 'source_last_supplier'].includes(failure.code)+ || !(failure.wouldRemoveHops.length || failure.wouldInterrupt.length)) throw error;+ // Saving the default order authorizes its inherited-route changes.+ // Echo the server's exact impact once; a changed plan still fails.+ return modelsApi.putAgentSources(agent.backend, {+ order,+ force: true,+ would_remove_hops: failure.wouldRemoveHops,+ would_interrupt: failure.wouldInterrupt,+ });+ });const nextOrder = echoed.sources?.order ?? order;setSaved(nextOrder);setOrder(nextOrder);@@ -260,10 +270,6 @@ export const SourceOrderDrawer: React.FC<{onClose();} catch (error) {const failure = apiFailure(error);- if (failure && (failure.wouldRemoveHops.length || failure.wouldInterrupt.length)) {- setGuard({ force: true, would_remove_hops: failure.wouldRemoveHops, would_interrupt: failure.wouldInterrupt });- return;- }setUnknownWrite(mayHaveWritten(failure));// F1: the request failed, not the user's draft. Keep every move and let// the same primary retry the exact order.@@ -286,10 +292,7 @@ export const SourceOrderDrawer: React.FC<{<DialogPrimitive.ContentclassName="model-hub-order-drawer fixed inset-y-0 right-0 z-50 flex flex-col overflow-hidden bg-surface outline-none"onEscapeKeyDown={(event) => {- if (guard) {- event.preventDefault();- setGuard(null);- } else if (grabbedId) {+ if (grabbedId) {event.preventDefault();cancelGrab();} else if (saving) event.preventDefault();@@ -317,11 +320,6 @@ export const SourceOrderDrawer: React.FC<{</header><div className="model-hub-order-body flex min-h-0 flex-1 flex-col overflow-y-auto">- {guard ? <div className="model-hub-order-section" role="alert">- <h3>{t('settings.models.routing.guardTitle')}</h3>- <ul className="model-hub-guard-list">{guard.would_remove_hops?.map((hop) => <li key={`${hop.backend}:${hop.menu_model}:${hop.position}`} className="model-hub-guard-hop"><span>{hop.menu_model} · {hop.model_id} · {hop.source_id}</span></li>)}</ul>- <GuardGapList gaps={guard.would_interrupt ?? []} />- </div> : <>{readState === 'loading' && (<div className="model-hub-order-state"><LoaderCircle className="model-hub-ink-mint size-4 animate-spin" />{t('common.loading')}</div>)}@@ -424,20 +422,19 @@ export const SourceOrderDrawer: React.FC<{</>)}<p aria-live="polite" className="sr-only">{announcementText}</p>- </>}{readState === 'ready' && <p className="model-hub-default-counts">{t('settings.models.routing.counts', { inherited: inheritedCount, manual: manualCount })}</p>}</div><footer className="model-hub-order-foot flex shrink-0 items-center justify-end border-t border-border">{saveFailed && <span className="mr-auto text-[11px] text-destructive-ink">{t('settings.models.order.fail.save')}</span>}- <Button type="button" variant="outline" className="model-hub-order-action" disabled={saving} onClick={() => guard ? setGuard(null) : onClose()}>+ <Button type="button" variant="outline" className="model-hub-order-action" disabled={saving} onClick={onClose}>{t('settings.models.order.cancel')}</Button>{readState === 'error'? <Button type="button" variant="brand" className="model-hub-order-action" onClick={() => void read()}>{t('settings.models.order.retry')}</Button>- : <Button type="button" variant="brand" className="model-hub-order-action" disabled={!saveEnabled || saving} onClick={() => save(guard ?? undefined)}>+ : <Button type="button" variant="brand" className="model-hub-order-action" disabled={!saveEnabled || saving} onClick={save}>{saving && <LoaderCircle className="size-3 animate-spin" />}- {guard ? t('settings.models.routing.confirmDefaults') : saveFailed ? t('settings.models.order.retry') : t('settings.models.order.save')}+ {saveFailed ? t('settings.models.order.retry') : t('settings.models.order.save')}</Button>}</footer></DialogPrimitive.Content>diff --git a/ui/src/components/settings/models/SourceRow.test.tsx b/ui/src/components/settings/models/SourceRow.test.tsxindex 1d5c2c882..b5fefd4dc 100644--- a/ui/src/components/settings/models/SourceRow.test.tsx+++ b/ui/src/components/settings/models/SourceRow.test.tsx@@ -20,6 +20,17 @@ afterEach(() => {});describe('SourceRow', () => {+ it.each(['en', 'zh'])('shows a saved source without a warning or a health claim in %s', (lng) => {+ const locale = i18n.cloneInstance({ lng });+ render(<I18nextProvider i18n={locale}><SourceRow source={{+ ...source, verification_pending: 'vp_fixture', adopted_by: [{ backend: 'codex', menu_model: 'gpt-5' }],+ }} onOpen={vi.fn()} /></I18nextProvider>);+ const label = screen.getByText(locale.t('settings.models.sourceDetail.status.saved'));+ expect(label.classList.contains('text-muted')).toBe(true);+ expect(label.querySelector('.bg-muted')).not.toBeNull();+ expect(screen.queryByText(/Supplying Codex|正在使用 Codex/)).toBeNull();+ });+it('opens the Source detail without exposing inline source mutations', async () => {const onOpen = vi.fn();render(<I18nextProvider i18n={i18n}><SourceRow source={source} onOpen={onOpen} /></I18nextProvider>);diff --git a/ui/src/components/settings/models/sourceStatePresentation.test.ts b/ui/src/components/settings/models/sourceStatePresentation.test.tsindex a6a101f0b..dddccdd69 100644--- a/ui/src/components/settings/models/sourceStatePresentation.test.ts+++ b/ui/src/components/settings/models/sourceStatePresentation.test.ts@@ -21,14 +21,19 @@ const state = (status: SourceStatus, over: Partial<SourceState> = {}): SourceSta});describe('sourceStatePresentation', () => {- it.each(['card', 'detail'] as const)('keeps unverified %s sources distinct from adopted healthy sources', (surface) => {+ it.each(['card', 'detail'] as const)('presents saved %s sources neutrally while preserving real errors', (surface) => {for (const status of SOURCE_STATUSES) {const current = state(status);const adoption = { known: true, backends: ['Codex'], native: false };const presentation = sourceStatePresentation(current, surface, 'en', 0, { ...adoption, verificationPending: true });if (status === 'active' || status === 'standby') {- expect(presentation.key).toBe('settings.models.sourceDetail.status.unverified');- expect(presentation.dotClass).toBe('bg-gold');+ expect(presentation.key).toBe('settings.models.sourceDetail.status.saved');+ expect(presentation.textClass).toBe('text-muted');+ expect(presentation.dotClass).toBe('bg-muted');+ expect(presentation.hint).toEqual({+ labelKey: 'settings.models.sourceDetail.status.savedHintLabel',+ bodyKey: 'settings.models.sourceDetail.status.savedHint',+ });} else {expect(presentation).toEqual(sourceStatePresentation(current, surface, 'en', 0, adoption));}diff --git a/ui/src/components/settings/models/sourceStatePresentation.ts b/ui/src/components/settings/models/sourceStatePresentation.tsindex 9dd51dec3..b0eab3239 100644--- a/ui/src/components/settings/models/sourceStatePresentation.ts+++ b/ui/src/components/settings/models/sourceStatePresentation.ts@@ -102,9 +102,13 @@ export const sourceStatePresentation = (): SourceStatePresentation => {if (adoption.verificationPending && (state.status === 'active' || state.status === 'standby')) {return {- key: 'settings.models.sourceDetail.status.unverified',- textClass: 'model-hub-ink-gold',- dotClass: 'bg-gold',+ key: 'settings.models.sourceDetail.status.saved',+ hint: {+ labelKey: 'settings.models.sourceDetail.status.savedHintLabel',+ bodyKey: 'settings.models.sourceDetail.status.savedHint',+ },+ textClass: 'text-muted',+ dotClass: 'bg-muted',};}if (state.status === 'active' && !adoption.known) {diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 1777fcfc6..b4cf4c1fb 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1243,9 +1243,7 @@"exactModel": "Exact model ID","moveUp": "Move source up","moveDown": "Move source down",- "counts": "{{inherited}} models follow defaults · {{manual}} fixed routes",- "guardTitle": "Review affected routes",- "confirmDefaults": "Save default routing"+ "counts": "{{inherited}} models follow defaults · {{manual}} fixed routes"},"order": {"title": "{{backend}} · Default routing",@@ -1733,7 +1731,9 @@"error": "Error","standbyHintLabel": "What this status means","standbyHint": "This source is healthy. It reads as in use once a backend in Gateway mode serves a route through it.",- "unverified": "Not yet verified",+ "saved": "Saved",+ "savedHintLabel": "About this connection",+ "savedHint": "Your configuration is saved. This source has not completed a successful model request with its current configuration yet. The status updates after a successful request.","listUpdated": "· model list updated {{time}}"},"summary_one": "{{host}} · {{count}} model",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex cd131a876..e6c718b44 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1243,9 +1243,7 @@"exactModel": "准确模型 ID","moveUp": "上移供应商","moveDown": "下移供应商",- "counts": "{{inherited}} 个模型跟随默认路由 · {{manual}} 个固定路由",- "guardTitle": "确认受影响的路由",- "confirmDefaults": "保存默认路由"+ "counts": "{{inherited}} 个模型跟随默认路由 · {{manual}} 个固定路由"},"order": {"title": "{{backend}} · 默认路由",@@ -1733,7 +1731,9 @@"error": "异常","standbyHintLabel": "这个状态是什么意思","standbyHint": "这个供应商当前可用。当模型网关中的某个后端通过它调用模型时,它就会显示为使用中。",- "unverified": "尚未验证",+ "saved": "已保存",+ "savedHintLabel": "关于连接状态",+ "savedHint": "配置已保存,这个供应商尚未用当前配置成功调用过模型。成功调用后会自动更新状态。","listUpdated": "· 模型列表更新于 {{time}}"},"summary_one": "{{host}} · {{count}} 个模型",