Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(model-hub): ask once in an independent dialog and drop done screens (#2218)

Call White5345ed95b946
diff --git a/docs/plans/model-hub-e2e-test-plan.md b/docs/plans/model-hub-e2e-test-plan.md
index 4cd943a75..1b315cccf 100644
--- a/docs/plans/model-hub-e2e-test-plan.md
+++ b/docs/plans/model-hub-e2e-test-plan.md
@@ -49,7 +49,7 @@ Out of scope (documented, not dropped silently):
| B4 | discovery fails | save succeeds with pending verification; preserve manual inventory and allow manual addition without refetching | assert |
| B5 | replay create with same `client_nonce` | idempotent, no duplicate source | assert |
| B6 | replace key happy + rollback; rename; patch base URL | C22/C23 contracts | assert |
-| B7 | sole owned default source + exact one-hop manual route, verified by reads → delete source → guard 409 → echo plan → force | actual inherited supply gap; the guard lists the interrupted agents before the forced press and the commit announces itself in one toast with no second decision; malformed echo rejected; canonical route and exact captured default order restored independently (only the owned deleted ID may be omitted) | assert |
+| B7 | sole owned default source + exact one-hop manual route, verified by reads → delete source → guard 409 → echo plan → force | actual inherited supply gap; the one delete confirm is the whole decision, so the 409 is resent forced with its plan echoed without reopening the dialog, and the commit announces itself in one toast; malformed echo rejected; canonical route and exact captured default order restored independently (only the owned deleted ID may be omitted) | assert |
| B8 | force transport asymmetry (`?force=` vs body) | document current split (B6 issue); decide normalization | baseline |
| B9 | refetch after upstream inventory change | added/removed diff; **`discovered_at` preserved for pre-existing models** (currently overwritten — fix-first, see B-list) | fix-first |
| B10 | inspect provider inventory and add/remove a manual model | no reasoning column, provenance badge, tier editor or empty advanced toggle; manual creation needs only a model ID. Compatibility API tests retain existing metadata ownership coverage | assert |
diff --git a/docs/plans/model-hub-ui-spec.md b/docs/plans/model-hub-ui-spec.md
index c54ef829c..7baddc4cf 100644
--- a/docs/plans/model-hub-ui-spec.md
+++ b/docs/plans/model-hub-ui-spec.md
@@ -962,7 +962,7 @@ state exit; held intent never bypasses the evidence column.
| §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 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 refused `[derived]` `[contract]` | A non-forced save returned the current exact refusal plan: nonempty manual PUT guards interruption; Restore/last-hop removal additionally guards effective hop removal. A forced save never lands here — RS-6 resends it | F3 — shared `Qp6FI`, an independent modal over the unchanged draft; 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 the refusal, 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 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 |
@@ -2176,7 +2176,7 @@ control only sorts the one route draft held by frame 02.
| RS-3 — ordinary success | R6 `{chain, removed_hops, interrupted}` | Hold all three members; cardinality is evidence consumed by ET-10/ET-11, which alone select the report or report-free M6 edge |
| RS-4 — guarded refusal | Existing HTTP 409 guard envelope and both complete refusal arrays | Nonempty manual PUT guards protected-supply interruption; inherited DELETE Restore guards actual effective removal or supply loss. Render the applicable existing guard and evidence blocks. The refusal persists nothing and retains draft intent |
| RS-5 — confirm | immutable submitted intent + both exact arrays from the currently displayed refusal | Re-send the same PUT or DELETE with `force: true`, `would_remove_hops` and `would_interrupt`; confirmation never changes the submitted intent |
-| RS-6 — plan changed | a forced request returns another guarded 409 | ET-12 replaces both displayed arrays with the recomputed plan and requires another explicit confirmation; the old preview is discarded |
+| RS-6 — plan changed | a forced request returns another guarded 409 | The user already answered the one question, so the same intent is resent forced with the recomputed arrays echoed, a bounded number of times, without reopening the guard; a plan that never settles ends as that attempt's terminal refusal |
| RS-7 — impact disappeared | the forced request recomputes an empty guarded plan | The server returns ordinary R6 success; ET-10/ET-11 consume the actual envelope and the UI fabricates no refusal |
| RS-8 — shaped rejection | a non-guard, non-`direct_mode` error response | Settle that attempt terminal-rejected. Retry revalidates retained intent, freezes a new generation and sends one ordinary non-forced PUT or DELETE as appropriate. It never runs D-36 or reuses prior force/plan evidence |
| RS-9 — no response / no Route authority | transport no-answer or `direct_mode` without an exact Route result | ET-15/ET-18a set attempt settlement `unknown`. D-36 may read only: matching proves commit; nonmatching or failed observation never proves the old write terminal and never emits a recovery mutation. The user may abandon; any later edit begins a distinct workflow from newly read authority |
@@ -2547,9 +2547,9 @@ generation is ignored and cannot install authority, feedback or focus.
| 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, 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-12 — guarded 409 | Saving + immutable draft + complete current refusal arrays from a non-forced save | Validate guard code and both arrays | Release mutation ownership only after the current plan is held | Route save refused | Independent shared Qp6FI modal over the unchanged draft, 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 |
+| 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 | The mounted guard turns busy as the immutable values freeze into the request, and stays until the answer lands | Saving | Busy guard confirmation | The busy guard | One owned Route PUT or DELETE matching the immutable intent, plus RS-6's bounded forced resends |
| ET-14 — definitive non-guard rejection | Saving + submitted draft; DM-2 is reserved for ET-18a | Exclude guard and `direct_mode`, then settle this attempt `terminal-rejected` | Release mutation ownership; retain only the locally validated draft for an explicit new workflow | Route save rejected | `route.fail.save` | FF-1-valid `route.retry` | None; rejection never enters D-36 |
| ET-14a — explicit new attempt after rejection | Route save rejected + retained draft + CA-R1 admission | Re-run ordinary V5; when valid create a new workflow generation and send ordinary non-forced nonempty PUT or inherited DELETE. The prior terminal attempt supplies no request identity, force flag, plan echo or replay right | Clear old rejection feedback only as the new generation acquires mutation ownership | Saving | `route.saving` | Programmatically focusable progress status | One new owned Route PUT or DELETE matching normalized intent; any returned guard begins a new Qp6FI phase |
| ET-15 — no response evidence | Saving + submitted draft + initial/confirmed stage | Set attempt settlement `unknown`; infer neither commit nor refusal | Release mutation ownership; retain immutable attempt evidence | Route save outcome unresolved | `route.fail.unconfirmed` | `route.retry` | None until a read-only Retry |
diff --git a/ui/e2e/b-add-api-key.spec.ts b/ui/e2e/b-add-api-key.spec.ts
index 53fa93b2c..4880ec08b 100644
--- a/ui/e2e/b-add-api-key.spec.ts
+++ b/ui/e2e/b-add-api-key.spec.ts
@@ -199,7 +199,7 @@ test.describe('B · add an API-key source', () => {
});
});
- test('B6 · replacing the key reuses the same dialog, and reports what it did', async ({ hub, mock, api, gateway }) => {
+ test('B6 · replacing the key reuses the same dialog, then closes on a toast', async ({ hub, mock, api, gateway }) => {
// The only spec in the suite that may have to sit out a 30-second cooldown
// before its precondition even exists. See `settleKeyVerdict`.
test.setTimeout(300_000);
@@ -350,8 +350,9 @@ test.describe('B · add an API-key source', () => {
await dialog.getByRole('button', { name: copy('repair.replaceSubmit'), exact: true }).click();
// The upstream still lists the same models, so the new key costs the route
- // nothing — a plain repair, and the dialog says which of the two it was.
- await expect(dialog).toContainText(copy('repair.repaired'), { timeout: 30_000 });
+ // nothing: a plain repair, which closes the dialog and says so in a toast.
+ await expect(hub.toasts.filter({ hasText: copy('repair.repaired') })).toHaveCount(1, { timeout: 30_000 });
+ await expect(dialog).toHaveCount(0);
// And the row it was raised from is no longer stopped. A dialog that
// reports a repair over a source still marked blocked has reported a
// repair that did not happen.
diff --git a/ui/e2e/g-guards-copy.spec.ts b/ui/e2e/g-guards-copy.spec.ts
index c6e9c63a6..d3457a2f1 100644
--- a/ui/e2e/g-guards-copy.spec.ts
+++ b/ui/e2e/g-guards-copy.spec.ts
@@ -24,7 +24,7 @@ test.describe('G · supply guards and failure copy', () => {
await requireMockUpstream(mock);
});
- test('B7 · removing the only source of a route is refused, explained, then reported', async ({ hub, api, gateway }) => {
+ test('B7 · removing the only source of a route asks once, then reports', async ({ hub, api, gateway }) => {
const source = gateway.sources[0];
const supplied = source.models[0]?.id;
expect(
@@ -56,35 +56,22 @@ test.describe('G · supply guards and failure copy', () => {
await hub.manageMenuTrigger(source.display_name).click();
await hub.manageItem('delete_source').click();
- // 1 · the plain confirm. The menu item opens it with no evidence in it,
+ // 1 · the one confirm. The menu item opens it with no evidence in it,
// because the client has not asked the server anything yet — it only knows
- // that deleting a source is destructive.
+ // that deleting a source is destructive, and its subtitle says the source
+ // leaves every Agent and route that uses it.
const guard = hub.dialogTitled(copy('guard.title.deleteSource', { source: source.display_name }));
- const confirm = guard.getByRole('button', {
- name: copy('guard.confirm.deleteSource'),
- exact: true,
- });
await expect(guard).toBeVisible({ timeout: 30_000 });
await expect(guard).toContainText(copy('guard.subtitle.deleteSource'));
await expectVisibleWithout(guard, copy('guard.label'));
- // 2 · confirming ATTEMPTS the delete, and the SERVER refuses it. The same
- // dialog comes back carrying the refusal's own plan — which hops go, and
- // which models are left with nothing. That two-step shape is the scenario:
- // a source nothing routes through is deleted on the first confirm, and the
- // evidence below appears only because something is actually at stake.
- await confirm.click();
- await expect(guard).toContainText(copy('guard.label'), { timeout: 30_000 });
- await expect(guard).toContainText(copy('guard.gap.label'));
- await expect(guard).toContainText(copy('guard.hint.interrupt'));
- await expect(guard).toContainText(gateway.model);
+ // 2 · confirming is the whole decision. The server refuses the first
+ // attempt with its plan, and the client resends it forced with that plan
+ // echoed — the user already agreed to what the subtitle named, so the
+ // dialog never comes back to ask a second time.
+ await guard.getByRole('button', { name: copy('guard.confirm.deleteSource'), exact: true }).click();
- // 3 · confirm again, which re-sends the delete echoing that plan back.
- await confirm.click();
-
- // 4 · the removal announces itself once, in the toast layer. Step 2 is
- // where the facts were put to the user and step 3 is where they accepted
- // them, so restating the same plan in a modal would only ask again.
+ // 3 · the removal announces itself once, in the toast layer.
await expect(hub.toasts.filter({ hasText: copy('sourceDetail.remove.settlement.title') }))
.toBeVisible({ timeout: 30_000 });
await expect(hub.guardDialog).toHaveCount(0);
diff --git a/ui/e2e/model-provider/fixture.tsx b/ui/e2e/model-provider/fixture.tsx
index c503b87e3..1cfc58376 100644
--- a/ui/e2e/model-provider/fixture.tsx
+++ b/ui/e2e/model-provider/fixture.tsx
@@ -7,6 +7,7 @@ import zh from '../../src/i18n/zh.json';
import '../../src/index.css';
import '../../src/components/settings/models/modelHubSurface.css';
import { Button } from '../../src/components/ui/button';
+import { ToastProvider } from '../../src/context/ToastProvider';
import { AddApiKeyDialog } from '../../src/components/settings/models/AddApiKeyDialog';
import { SourceDetailPanel } from '../../src/components/settings/models/SourceDetailPanel';
import { SourcesCard } from '../../src/components/settings/models/SourcesCard';
@@ -128,4 +129,4 @@ function IdentityFixture() {
</I18nextProvider>;
}
-createRoot(document.getElementById('root')!).render(params.has('identity') ? <IdentityFixture /> : <Fixture />);
+createRoot(document.getElementById('root')!).render(<ToastProvider>{params.has('identity') ? <IdentityFixture /> : <Fixture />}</ToastProvider>);
diff --git a/ui/e2e/model-routing-origin.spec.ts b/ui/e2e/model-routing-origin.spec.ts
index 892037706..7c03bd8d6 100644
--- a/ui/e2e/model-routing-origin.spec.ts
+++ b/ui/e2e/model-routing-origin.spec.ts
@@ -104,10 +104,13 @@ test('MH-ROUTING-007 follow-defaults switch, undo, cancel, and save preserve exp
};
expect(await refused.json()).toMatchObject({ ok: false, contract_version: 10, error: 'source_in_route_chain', ...plan });
expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toEqual(manual);
- await expect(dialog.locator('.model-hub-guard-hop')).toHaveCount(1);
- await expect(dialog.locator('.model-hub-guard-hop strong')).toHaveText(`${copy(`backends.${gateway.backend}`)} · ${gateway.model}`);
- await expect(dialog.locator('.model-hub-guard-hop > span > span')).toHaveText(`${manual.hops[0].model_id} · ${copy('guard.hop.position', { n: 1 })}`);
- const confirm = labelledButton(dialog, copy('guard.confirm.saveRoute'));
+ // The one question is its own modal over the chain the user was editing.
+ const guard = hub.dialogTitled(copy('guard.title.saveRoute', { menuModel: gateway.model }));
+ await expect(guard).toBeVisible();
+ await expect(guard.locator('.model-hub-guard-hop')).toHaveCount(1);
+ await expect(guard.locator('.model-hub-guard-hop strong')).toHaveText(`${copy(`backends.${gateway.backend}`)} · ${gateway.model}`);
+ await expect(guard.locator('.model-hub-guard-hop > span > span')).toHaveText(`${copy('gateway.row.current', { source: gateway.sources[0].display_name, model: manual.hops[0].model_id })} · ${copy('guard.hop.position', { n: 1 })}`);
+ const confirm = labelledButton(guard, copy('guard.confirm.saveRoute'));
await expect(confirm).toBeVisible();
const committedPromise = page.waitForResponse((response) => response.url() === chainUrl && response.request().method() === 'DELETE');
await confirm.click();
@@ -117,6 +120,7 @@ test('MH-ROUTING-007 follow-defaults switch, undo, cancel, and save preserve exp
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']);
+ await expect(guard).toHaveCount(0);
await expect(dialog).toHaveCount(0);
await page.reload();
const reloaded = await api.agentChain(gateway.backend, gateway.model);
diff --git a/ui/src/components/onboarding/AssistantSetup.test.tsx b/ui/src/components/onboarding/AssistantSetup.test.tsx
index f86d30a85..bdce361c2 100644
--- a/ui/src/components/onboarding/AssistantSetup.test.tsx
+++ b/ui/src/components/onboarding/AssistantSetup.test.tsx
@@ -16,13 +16,13 @@ import { INITIAL_SETUP_FLOW_STATE } from './setupFlow';
const mock = vi.hoisted(() => ({ api: {
detectCli: vi.fn(), installAgent: vi.fn(), getConfig: vi.fn(), getBackendRuntime: vi.fn(), getBackendConnection: vi.fn(), mutateConfig: vi.fn(), getClaudeAuth: vi.fn(), getCodexAuth: vi.fn(), getOpencodeProviders: vi.fn(), saveClaudeAuth: vi.fn(),
listVibeAgents: vi.fn(), getVibeAgent: vi.fn(),
-}, models: { getAgentChain: vi.fn(), getAgentChains: vi.fn(), previewAgentChain: vi.fn(), putAgentChain: vi.fn(), listSources: vi.fn() } }));
+}, showToast: vi.fn(), models: { getAgentChain: vi.fn(), getAgentChains: vi.fn(), previewAgentChain: vi.fn(), putAgentChain: vi.fn(), listSources: vi.fn() } }));
vi.mock('../../context/ApiContext', () => ({ useApi: () => mock.api }));
vi.mock('../settings/models/modelsApi', async (importOriginal) => {
const actual = await importOriginal<typeof import('../settings/models/modelsApi')>();
return { ...actual, modelsApi: { ...actual.modelsApi, ...mock.models } };
});
-vi.mock('../../context/ToastContext', () => ({ useToast: () => ({ showToast: vi.fn() }) }));
+vi.mock('../../context/ToastContext', () => ({ useToast: () => ({ showToast: mock.showToast }) }));
vi.mock('../settings/models/useModelHubCapability', () => ({ useModelHubCapability: () => false }));
vi.mock('../settings/shared/useOpencodePermission', () => ({ useOpencodePermission: () => ({ permissionAllowed: true, statusLoaded: true }) }));
vi.mock('../settings/providers/BackendProviderConfig', () => ({ BackendProviderConfig: ({ backend }: { backend: string }) => <div>Existing provider: {backend}</div> }));
@@ -302,7 +302,7 @@ describe('assistant installation presentation', () => {
expect(await row('Claude Code').findByRole('button', { name: 'API Key connected' })).toBeTruthy();
expect(screen.getByRole('button', { name: 'Enter workspace' }).hasAttribute('disabled')).toBe(false);
});
- it('opens the setup route editor when the backend is already Hub-owned', async () => {
+ it('opens the setup route editor when the backend is already Hub-owned, and reports its save', async () => {
const saved = { ...data(), capabilities: { model_hub: { enabled: true } } }; saved.agents.claude.status = 'ok';
mock.api.getBackendConnection.mockImplementation(async (backend) => ({
ok: true,
@@ -325,9 +325,12 @@ describe('assistant installation presentation', () => {
mock.models.listSources.mockResolvedValue([]);
const chain = {
contract_version: 10, backend: 'claude', model_id: 'opus-5',
- manual_override: { hops: [{ source_id: 'src_a', model_id: 'opus-5' }] },
+ manual_override: { hops: [{ source_id: 'src_a', model_id: 'opus-5' }, { source_id: 'src_b', model_id: 'opus-5' }] },
route_origin: 'manual', current: { source_id: 'src_a', model_id: 'opus-5' },
- chain: [{ source_id: 'src_a', model_id: 'opus-5', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }],
+ chain: [
+ { source_id: 'src_a', model_id: 'opus-5', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null },
+ { source_id: 'src_b', model_id: 'opus-5', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null },
+ ],
supply_state: 'ok',
};
mock.models.getAgentChains.mockResolvedValue([chain]);
@@ -350,6 +353,15 @@ describe('assistant installation presentation', () => {
expect(await screen.findByRole('dialog')).toBeTruthy();
expect(screen.getByTestId('location').textContent).toBe('/');
expect(enter.hasAttribute('disabled')).toBe(true);
+
+ // The dialog closes on commit, so the shared toast is the save's only report.
+ const savedChain = { ...chain, manual_override: { hops: [chain.manual_override.hops[1]] }, chain: [chain.chain[1]] };
+ mock.models.putAgentChain.mockResolvedValue({ chain: savedChain, removed_hops: [], interrupted: [] });
+ fireEvent.click((await screen.findAllByRole('button', { name: 'Remove hop' }))[0]);
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect(mock.models.putAgentChain).toHaveBeenCalledOnce();
+ expect(mock.showToast).toHaveBeenCalledWith(en.common.saved, 'success');
});
it('an available update keeps Continue and configuration usable', async () => {
const saved = data(); saved.agents.claude.status = 'ok';
diff --git a/ui/src/components/onboarding/providers/AddSourceDialog.test.tsx b/ui/src/components/onboarding/providers/AddSourceDialog.test.tsx
index c5c2c74a7..375e213f0 100644
--- a/ui/src/components/onboarding/providers/AddSourceDialog.test.tsx
+++ b/ui/src/components/onboarding/providers/AddSourceDialog.test.tsx
@@ -805,16 +805,9 @@ describe('AddSourceDialog — what comes back from an authorization', () => {
added_to: ['claude'],
adopted_by: ['claude'],
}));
- // The read happens BEHIND the flow's own success panel, which owns the report
- // of where the source landed and the handoff that dismisses it. Replacing that
- // with this dialog's spinner would discard the one thing worth reading.
- expect(screen.getByTestId('oauth-stub')).toBeTruthy();
- expect(onClose).not.toHaveBeenCalled();
-
- act(() => oauth.current?.onClose());
-
- // And when the flow does hand back, there is nothing left to add here.
- await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
+ // The arrival is the end of the frame, as a saved key is: the flow's toast has
+ // already said so, and nobody should have to dismiss a report to leave.
+ expect(onClose).toHaveBeenCalledTimes(1);
});
it('asks for one read when a landing reports itself twice', async () => {
@@ -840,10 +833,8 @@ describe('AddSourceDialog — what comes back from an authorization', () => {
});
expect(onAdded).not.toHaveBeenCalledWith(null);
- // And the extra call changed nothing about the handback: the flow's own panel
- // still owns the close, and this frame still goes with it.
- act(() => oauth.current?.onClose());
- await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
+ // And the extra call changed nothing about the handback: the frame closed once.
+ expect(onClose).toHaveBeenCalledTimes(1);
});
it('returns to the frame it was launched from when nothing arrived', async () => {
diff --git a/ui/src/components/onboarding/providers/AddSourceDialog.tsx b/ui/src/components/onboarding/providers/AddSourceDialog.tsx
index db88a9df8..6b31175be 100644
--- a/ui/src/components/onboarding/providers/AddSourceDialog.tsx
+++ b/ui/src/components/onboarding/providers/AddSourceDialog.tsx
@@ -212,8 +212,8 @@ export const AddSourceDialog: React.FC<{
const [phase, setPhase] = React.useState<WritePhase>({ kind: 'idle' });
const [continuation] = React.useState(createContinuationSettlement);
const clientNonce = React.useRef(sourceClientNonce());
- // Set when an authorization really produced a source. It is what tells that
- // flow's own close apart from a cancellation: both arrive the same way.
+ // Set when an authorization really produced a source, so the argument-less
+ // report that follows it is not read as a second, separate change.
const authorizedLanded = React.useRef(false);
// Permission as of now, not as of the press. A submit that first reads the inventory
// back can be inside that await when the engine stops, and the value the press saw is
@@ -309,14 +309,14 @@ export const AddSourceDialog: React.FC<{
void onAdded(null).catch(() => undefined);
return;
}
- // A source did arrive — and the flow's own success panel is still on screen,
- // holding the report of where it landed for the 1400ms it owns. Tearing that
- // down here to show this dialog's spinner would take the one thing the person
- // was waiting to read. So read back behind it, and let its close be what
- // closes this frame. The shipped host does exactly this.
+ // A source did arrive, and the flow has already said so in its toast. That
+ // is the end of this frame, as it is for a key that saved: the screen reads
+ // the inventory back behind it and shows where the source landed.
authorizedLanded.current = true;
void onAdded({ source, ...(placement ?? { added_to: [], adopted_by: source.adopted_by ?? [] }) })
.catch(() => undefined);
+ continuation.invalidate();
+ onClose();
};
const writing = phase.kind === 'saving' || phase.kind === 'checking';
@@ -543,17 +543,10 @@ export const AddSourceDialog: React.FC<{
open
vendor={subscriptionVendor}
sources={sources}
- onClose={() => {
- if (!authorizedLanded.current) {
- // Cancelled, failed, or abandoned: back to the frame it was launched
- // from, with the method and the draft it was launched with.
- setPhase({ kind: 'idle' });
- return;
- }
- authorizedLanded.current = false;
- continuation.invalidate();
- onClose();
- }}
+ // Cancelled, failed, or abandoned: back to the frame it was launched
+ // from, with the method and the draft it was launched with. A flow that
+ // produced a source never gets here; its arrival already closed the frame.
+ onClose={() => setPhase({ kind: 'idle' })}
onConnected={authorized}
/>
)}
diff --git a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx b/ui/src/components/settings/models/AddApiKeyDialog.test.tsx
index f0f1ec563..fb744afc5 100644
--- a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx
+++ b/ui/src/components/settings/models/AddApiKeyDialog.test.tsx
@@ -1,5 +1,5 @@
// @vitest-environment jsdom
-import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { cleanup, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { I18nextProvider } from 'react-i18next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -21,6 +21,9 @@ import {
type SupplyGap,
} from './types';
+const showToast = vi.hoisted(() => vi.fn());
+vi.mock('@/context/ToastContext', () => ({ useToast: () => ({ showToast }) }));
+
const source: Source = {
id: 'src_new',
last_discovered_at: null,
@@ -172,6 +175,7 @@ afterEach(() => {
cleanup();
vi.restoreAllMocks();
vi.unstubAllGlobals();
+ showToast.mockReset();
});
describe('AddApiKeyDialog · save reconciliation', () => {
@@ -345,7 +349,7 @@ describe('AddApiKeyDialog · replacement', () => {
} }));
});
- it('uses the existing guard shape before force and reports the committed impact', async () => {
+ it('asks once in its own modal, echoes the plan, then closes on a toast', async () => {
const hop: RouteHopRef = {
backend: 'claude',
menu_model: 'sonnet',
@@ -368,15 +372,17 @@ describe('AddApiKeyDialog · replacement', () => {
removed_hops: [hop],
interrupted: [gap],
});
- renderReplacement();
+ const { onClose } = renderReplacement();
const user = userEvent.setup();
await user.type(screen.getByLabelText(/^New API key$|^新的 API Key$/i), 'sk-force');
await user.click(screen.getByRole('button', { name: /^Replace$|^更换$/i }));
- expect(await screen.findByRole('dialog', { name: /Replace key for|更换.*Key/i })).toBeTruthy();
- expect(screen.getByText(/pm-claude/)).toBeTruthy();
- await user.click(screen.getByRole('button', { name: /^Replace anyway$|^仍要更换$/i }));
+ const guard = await screen.findByRole('dialog', { name: /Replace key for|更换.*Key/i });
+ expect(within(guard).getByText(/pm-claude/)).toBeTruthy();
+ // The key the user typed stays behind the question, in its own dialog.
+ expect((screen.getByLabelText(/^New API key$|^新的 API Key$/i) as HTMLInputElement).value).toBe('sk-force');
+ await user.click(within(guard).getByRole('button', { name: /^Replace anyway$|^仍要更换$/i }));
await waitFor(() => expect(replace).toHaveBeenCalledTimes(2));
expect(replace.mock.calls).toEqual([
@@ -388,11 +394,35 @@ describe('AddApiKeyDialog · replacement', () => {
would_interrupt: [gap],
}],
]);
- expect(await screen.findByText(/^Removed hops$|^已移除的路由项$/i)).toBeTruthy();
- expect(screen.getByText(/now have no usable source|现在没有可用供应商/i)).toBeTruthy();
+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());
+ expect(showToast).toHaveBeenCalledWith(i18n.t('settings.models.repair.gaps'), 'warning');
+ expect(screen.queryByText(/^Removed hops$|^已移除的路由项$/i)).toBeNull();
+ });
+
+ it('ends a confirmed replacement whose plan never settles as a failure, not a second question', async () => {
+ const replace = vi.spyOn(modelsApi, 'replaceCredential').mockImplementation(async () => {
+ throw new ApiCallError('source_model_in_route_chain', undefined, true, [], [], [{
+ backend: 'claude',
+ menu_model: 'sonnet',
+ position: replace.mock.calls.length,
+ source_id: blockedSource.id,
+ model_id: 'claude-sonnet-4-5',
+ }]);
+ });
+ const { onClose } = renderReplacement();
+ const user = userEvent.setup();
+
+ await user.type(screen.getByLabelText(/^New API key$|^新的 API Key$/i), 'sk-never-settles');
+ await user.click(screen.getByRole('button', { name: /^Replace$|^更换$/i }));
+ await user.click(await screen.findByRole('button', { name: /^Replace anyway$|^仍要更换$/i }));
+
+ expect(await screen.findByText(/Couldn't replace the key|更换失败/i)).toBeTruthy();
+ expect(screen.queryByRole('button', { name: /^Replace anyway$|^仍要更换$/i })).toBeNull();
+ expect(replace).toHaveBeenCalledTimes(4);
+ expect(onClose).not.toHaveBeenCalled();
});
- it('requires confirmation again when the server recomputes a different replacement plan', async () => {
+ it('resends a confirmed replacement with the recomputed plan instead of asking again', async () => {
const firstHop: RouteHopRef = {
backend: 'claude',
menu_model: 'sonnet',
@@ -429,24 +459,22 @@ describe('AddApiKeyDialog · replacement', () => {
removed_hops: [nextHop],
interrupted: [],
});
- renderReplacement();
+ const { onClose } = renderReplacement();
const user = userEvent.setup();
await user.type(screen.getByLabelText(/^New API key$|^新的 API Key$/i), 'sk-changing-plan');
await user.click(screen.getByRole('button', { name: /^Replace$|^更换$/i }));
await user.click(await screen.findByRole('button', { name: /^Replace anyway$|^仍要更换$/i }));
- expect(await screen.findByText(/^gpt-5\.4/)).toBeTruthy();
+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());
+ expect(replace).toHaveBeenCalledTimes(3);
+ expect(screen.queryByText(/^gpt-5\.4/)).toBeNull();
expect(replace.mock.calls[1][1]).toEqual({
key: 'sk-changing-plan',
force: true,
would_remove_hops: [firstHop],
would_interrupt: [],
});
-
- await user.click(screen.getByRole('button', { name: /^Replace anyway$|^仍要更换$/i }));
-
- await waitFor(() => expect(replace).toHaveBeenCalledTimes(3));
expect(replace.mock.calls[2][1]).toEqual({
key: 'sk-changing-plan',
force: true,
@@ -499,39 +527,34 @@ describe('AddApiKeyDialog · replacement', () => {
const settled = neverResolvingSettlement({
readInventory: vi.fn().mockResolvedValue({ snapshot: 2, sources: [current] }),
});
- const closeTimer = vi.spyOn(window, 'setTimeout');
- renderReplacement(blockedSource, settled);
+ const { onClose } = renderReplacement(blockedSource, settled);
const user = userEvent.setup();
await user.type(screen.getByLabelText(/^New API key$|^新的 API Key$/i), 'sk-terminal');
await user.click(screen.getByRole('button', { name: /^Replace$|^更换$/i }));
if (outcome === 'impact') {
await user.click(await screen.findByRole('button', { name: /^Replace anyway$|^仍要更换$/i }));
- }
-
- if (outcome === 'impact') {
- expect(await screen.findByText(/^Removed hops$|^已移除的路由项$/i)).toBeTruthy();
- expect(screen.getByText(/pm-claude/)).toBeTruthy();
expect(replace.mock.calls.at(-1)?.[1]).toEqual({
key: 'sk-terminal',
force: true,
would_remove_hops: [hop],
would_interrupt: [gap],
});
- } else {
- expect(await screen.findByText(i18n.t('settings.models.repair.repaired'))).toBeTruthy();
}
- const close = screen.getByRole('button', { name: /^Close$|^关闭$/i }) as HTMLButtonElement;
- expect(close.disabled).toBe(false);
- expect(screen.queryByRole('button', { name: /^Retry$|^重试$/i })).toBeNull();
+ // The outcome closes the dialog on the spot and says itself in one toast;
+ // nothing waits on the trailing collection reconciliation.
+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());
+ expect(showToast).toHaveBeenCalledOnce();
+ expect(showToast).toHaveBeenCalledWith(
+ ...(outcome === 'impact'
+ ? [i18n.t('settings.models.repair.gaps'), 'warning']
+ : [i18n.t('settings.models.repair.repaired'), 'success']),
+ );
expect(settled.source).toHaveBeenCalledWith(current);
expect(settled.unread).not.toHaveBeenCalled();
if (path === 'inventory') expect(settled.readInventory).toHaveBeenCalledOnce();
else expect(settled.readInventory).not.toHaveBeenCalled();
- expect(closeTimer.mock.calls.filter(([, delay]) => delay === 1400)).toHaveLength(
- outcome === 'repaired' ? 1 : 0,
- );
},
);
@@ -542,8 +565,7 @@ describe('AddApiKeyDialog · replacement', () => {
const settled = neverResolvingSettlement({
readInventory: vi.fn().mockResolvedValue({ snapshot: 2, sources: [blockedSource] }),
});
- const closeTimer = vi.spyOn(window, 'setTimeout');
- renderReplacement(blockedSource, settled);
+ const { onClose } = renderReplacement(blockedSource, settled);
const user = userEvent.setup();
await user.type(screen.getByLabelText(/^New API key$|^新的 API Key$/i), 'sk-uncommitted');
@@ -551,12 +573,11 @@ describe('AddApiKeyDialog · replacement', () => {
expect(await screen.findByText(/Couldn't replace the key|更换失败/i)).toBeTruthy();
expect(screen.getByRole('button', { name: /^Retry$|^重试$/i })).toBeTruthy();
- expect(screen.queryByText(i18n.t('settings.models.repair.repaired'))).toBeNull();
- expect(screen.queryByText(/^Removed hops$|^已移除的路由项$/i)).toBeNull();
expect(settled.readInventory).toHaveBeenCalledOnce();
expect(settled.source).not.toHaveBeenCalled();
expect(settled.unread).not.toHaveBeenCalled();
- expect(closeTimer.mock.calls.filter(([, delay]) => delay === 1400)).toHaveLength(0);
+ expect(onClose).not.toHaveBeenCalled();
+ expect(showToast).not.toHaveBeenCalled();
});
it.each([
@@ -588,7 +609,7 @@ describe('AddApiKeyDialog · replacement', () => {
expect(screen.getAllByRole('button', { name: /^Cancel$|^取消$/i }))
.toSatisfy((buttons: HTMLButtonElement[]) => buttons.every((button) => !button.disabled));
expect(screen.queryByRole('button', { name: /^Retry$|^重试$/i }) !== null).toBe(retries);
- expect(screen.queryByText(i18n.t('settings.models.repair.repaired'))).toBeNull();
+ expect(showToast).not.toHaveBeenCalled();
expect(settled.source).not.toHaveBeenCalled();
if (path === 'response') {
diff --git a/ui/src/components/settings/models/AddApiKeyDialog.tsx b/ui/src/components/settings/models/AddApiKeyDialog.tsx
index ca97a994a..e4c803d04 100644
--- a/ui/src/components/settings/models/AddApiKeyDialog.tsx
+++ b/ui/src/components/settings/models/AddApiKeyDialog.tsx
@@ -2,7 +2,6 @@ import type { TranslationKey } from '@/i18n/types';
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import {
- CheckCircle2,
CircleX,
LoaderCircle,
Save,
@@ -12,6 +11,7 @@ import {
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
+import { useToast } from '@/context/ToastContext';
import { ApiKeyField, ApiKeySourceForm } from './ApiKeySourceForm';
import {
apiKeySourceCreate,
@@ -23,7 +23,9 @@ import {
} from './apiKeySourceDraft';
import { classifyModelHubFailure, type ModelHubFailureClass } from './asyncLifetime';
import type { CollectionReadAuthority } from './collectionReadAuthority';
-import { GuardImpact } from './GuardImpact';
+import { GuardDialog } from './GuardDialog';
+import { GuardImpact, type GuardPlan } from './GuardImpact';
+import { confirmGuardPlan, guardedFailure, sendAgreed } from './guardedWrite';
import { apiFailure, modelsApi, type SourceCreated } from './modelsApi';
import {
createContinuationSettlement,
@@ -34,10 +36,9 @@ import {
type TrackSourceMutation,
} from './mutationSettlement';
import { reconcileUnknownWrite } from './reconcileUnknownWrite';
-import { mayHaveWritten, REPAIR_LINE_KEY, wasBlocked } from './repair';
+import { mayHaveWritten, REPAIR_TOAST, wasBlocked } from './repair';
import { serverText } from './serverCopy';
import {
- type RouteHopRef,
type Source,
type SupplyGap,
} from './types';
@@ -50,23 +51,18 @@ type Phase =
const INITIAL_PHASE: Phase = { kind: 'form' };
-type ReplaceOutcome =
- | { kind: 'repaired' }
- | { kind: 'impact'; hops: RouteHopRef[]; gaps: SupplyGap[] };
-
-const replacementOutcomeFromEvidence = (
- hops: RouteHopRef[] = [],
- gaps: SupplyGap[] = [],
-): ReplaceOutcome => {
- if (hops.length > 0 || gaps.length > 0) return { kind: 'impact', hops, gaps };
- return { kind: 'repaired' };
-};
+/**
+ * A landed replacement is announced in one toast, in the repair verdict's own
+ * words and order. Which hops it cost was the guard's question, answered before
+ * the write, so the toast says only what is still wrong: an Agent the write
+ * stranded, or a source that is still stopped.
+ */
+const replacementToast = (source: Source, gaps: SupplyGap[] = []) =>
+ REPAIR_TOAST[gaps.length > 0 ? 'gaps' : wasBlocked(source.state) ? 'unresolved' : 'repaired'];
type ReplacePhase =
| { kind: 'edit' }
| { kind: 'submitting' }
- | { kind: 'guard'; hops: RouteHopRef[]; gaps: SupplyGap[] }
- | { kind: 'done'; outcome: ReplaceOutcome }
| { kind: 'failure'; failureClass: ModelHubFailureClass };
type AddApiKeyDialogProps = {
@@ -101,64 +97,58 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
const addOnAdded = replaceMode ? null : props.onAdded;
const replaceSourceId = replaceMode ? props.source.id : null;
const { t } = useTranslation();
+ const { showToast } = useToast();
const [draft, setDraft] = React.useState<ApiKeySourceDraft>(EMPTY_API_KEY_DRAFT);
const apiKey = draft.apiKey;
const [revealed, setRevealed] = React.useState(false);
const [phase, setPhase] = React.useState<Phase>(INITIAL_PHASE);
const [replacePhase, setReplacePhase] = React.useState<ReplacePhase>({ kind: 'edit' });
+ const [guard, setGuard] = React.useState<GuardPlan | null>(null);
const [continuation] = React.useState(createContinuationSettlement);
const [createdDelivery] = React.useState(createSourceCreatedDelivery);
const clientNonce = React.useRef(sourceClientNonce());
- const replaceCloseTimer = React.useRef<number | null>(null);
React.useEffect(() => {
if (addOnAdded) createdDelivery.update(addOnAdded, onClose);
}, [addOnAdded, createdDelivery, onClose]);
React.useEffect(() => {
continuation.invalidate();
- if (replaceCloseTimer.current !== null) {
- window.clearTimeout(replaceCloseTimer.current);
- replaceCloseTimer.current = null;
- }
if (open) {
clientNonce.current = sourceClientNonce();
setDraft(EMPTY_API_KEY_DRAFT);
setRevealed(false);
setPhase(INITIAL_PHASE);
setReplacePhase({ kind: 'edit' });
+ setGuard(null);
}
- return () => {
- continuation.invalidate();
- if (replaceCloseTimer.current !== null) {
- window.clearTimeout(replaceCloseTimer.current);
- replaceCloseTimer.current = null;
- }
- };
+ return () => continuation.invalidate();
}, [continuation, open, replaceSourceId]);
const publishReplacementEvidence = React.useCallback((
seq: ContinuationTicket,
settlement: SourceMutationSettlement,
source: Source,
- hops?: RouteHopRef[],
gaps?: SupplyGap[],
) => {
- const outcome = replacementOutcomeFromEvidence(hops, gaps);
- const landed = continuation.settle(seq, () => setReplacePhase({ kind: 'done', outcome }));
- if (landed === 'landed' && outcome.kind === 'repaired') {
- replaceCloseTimer.current = window.setTimeout(onClose, 1400);
- }
+ continuation.settle(seq, () => {
+ const toast = replacementToast(source, gaps);
+ showToast(t(toast.key) as string, toast.tone);
+ onClose();
+ });
// Entity settlement applies synchronously; collection reconciliation is
// trailing work and cannot gate an outcome already established by evidence.
void settlement.source(source).catch(() => undefined);
- }, [continuation, onClose]);
+ }, [continuation, onClose, showToast, t]);
const publishReplacementFailure = React.useCallback((
seq: ContinuationTicket,
failureClass: ModelHubFailureClass,
settle?: () => Promise<SourceMutationLanding>,
) => {
- continuation.settle(seq, () => setReplacePhase({ kind: 'failure', failureClass }));
+ continuation.settle(seq, () => {
+ setGuard(null);
+ setReplacePhase({ kind: 'failure', failureClass });
+ });
if (settle) void settle().catch(() => undefined);
}, [continuation]);
@@ -174,41 +164,37 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
}
}, [continuation, createdDelivery, draft]);
- const submitReplacement = React.useCallback(async (force: boolean) => {
+ // `plan` is the guard's question already answered: the write echoes it, and a
+ // plan that moved before the forced write lands is resent, not asked again.
+ const submitReplacement = React.useCallback(async (plan: GuardPlan | null) => {
if (props.mode !== 'replace' || !apiKey.trim() || replacePhase.kind === 'submitting') return;
- const confirmation = force && replacePhase.kind === 'guard'
- ? {
- force: true as const,
- would_remove_hops: replacePhase.hops,
- would_interrupt: replacePhase.gaps,
- }
- : null;
- if (force && !confirmation) return;
const key = apiKey.trim();
const seq = continuation.begin();
setReplacePhase({ kind: 'submitting' });
await props.trackMutation(async (latest, settlement) => {
+ let sent = plan;
try {
- const answer = await modelsApi.replaceCredential(
- latest.id,
- confirmation ? { key, ...confirmation } : { key },
- );
+ const answer = await sendAgreed(plan !== null, plan, (next) => {
+ sent = next;
+ return modelsApi.replaceCredential(latest.id, next ? { key, ...confirmGuardPlan(next) } : { key });
+ });
publishReplacementEvidence(
seq,
settlement,
answer.source,
- answer.removed_hops,
answer.interrupted,
);
} catch (error) {
const failure = apiFailure(error);
- if (failure && (failure.wouldRemoveHops.length > 0 || failure.wouldInterrupt.length > 0)) {
+ // Only an unconfirmed attempt asks: a confirmed one already resent the
+ // moving plan within its bound, and ends as the failure below.
+ const refusal = plan === null ? guardedFailure(error) : null;
+ if (refusal) {
settlement.release();
- continuation.settle(seq, () => setReplacePhase({
- kind: 'guard',
- hops: failure.wouldRemoveHops,
- gaps: failure.wouldInterrupt,
- }));
+ continuation.settle(seq, () => {
+ setGuard(refusal);
+ setReplacePhase({ kind: 'edit' });
+ });
return;
}
let failureClass = classifyModelHubFailure(failure);
@@ -236,8 +222,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
seq,
settlement,
current,
- confirmation?.would_remove_hops,
- confirmation?.would_interrupt,
+ sent?.gaps,
);
return;
}
@@ -249,15 +234,11 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
publishReplacementFailure(seq, failureClass);
}
});
- }, [apiKey, continuation, props, publishReplacementEvidence, publishReplacementFailure, replacePhase]);
+ }, [apiKey, continuation, props, publishReplacementEvidence, publishReplacementFailure, replacePhase.kind]);
const cancel = React.useCallback(() => {
if (replaceMode) {
if (replacePhase.kind === 'submitting') return;
- if (replacePhase.kind === 'guard') {
- setReplacePhase({ kind: 'edit' });
- return;
- }
continuation.invalidate();
onClose();
return;
@@ -315,9 +296,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
const canSubmit = draftComplete(draft) && !formLocked;
const replaceTerminalFailure = replacePhase.kind === 'failure'
&& replacePhase.failureClass === 'authoritative-terminal';
- const replaceFieldLocked = replacePhase.kind === 'submitting'
- || replacePhase.kind === 'done'
- || replaceTerminalFailure;
+ const replaceFieldLocked = replacePhase.kind === 'submitting' || replaceTerminalFailure;
return (
<DialogPrimitive.Root open={open} onOpenChange={(next) => !next && canCancel && cancel()}>
<DialogPrimitive.Portal>
@@ -331,9 +310,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
<div className="flex items-center justify-between gap-3">
<DialogPrimitive.Title className="model-hub-add-key-title font-bold text-foreground">
{replaceMode
- ? replacePhase.kind === 'guard'
- ? t('settings.models.guard.title.replaceKey', { source: props.source.display_name })
- : t('settings.models.repair.replaceTitle', { name: props.source.display_name })
+ ? t('settings.models.repair.replaceTitle', { name: props.source.display_name })
: t('settings.models.addKey.title')}
</DialogPrimitive.Title>
<Button
@@ -341,7 +318,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
variant="ghost"
size="icon"
className="model-hub-ink-59 size-[27px]"
- aria-label={t(replacePhase.kind === 'guard' ? 'settings.models.guard.cancel' : 'settings.models.addKey.cancel')}
+ aria-label={t('settings.models.addKey.cancel')}
disabled={!canCancel}
onClick={cancel}
>
@@ -350,20 +327,12 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
</div>
<DialogPrimitive.Description className="model-hub-add-key-subtitle model-hub-ink-muted-b3 font-mono">
{replaceMode
- ? replacePhase.kind === 'guard'
- ? t('settings.models.guard.subtitle.replaceKey')
- : t('settings.models.repair.replaceBody')
+ ? t('settings.models.repair.replaceBody')
: t('settings.models.addKey.saveFirstHint')}
</DialogPrimitive.Description>
</header>
- {replaceMode && replacePhase.kind === 'guard' && (
- <div className="model-hub-guard-body">
- <GuardImpact hops={replacePhase.hops} gaps={replacePhase.gaps} />
- </div>
- )}
-
- {replaceMode && replacePhase.kind !== 'guard' && (
+ {replaceMode && (
<div className="model-hub-add-key-body flex flex-col">
<ApiKeyField
value={apiKey}
@@ -373,7 +342,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
label={t('settings.models.repair.replaceLabel')}
onChange={editKey}
onToggleReveal={() => setRevealed((value) => !value)}
- onEnter={replaceTerminalFailure ? undefined : () => void submitReplacement(false)}
+ onEnter={replaceTerminalFailure ? undefined : () => void submitReplacement(null)}
/>
{replacePhase.kind === 'submitting' && (
<div className="model-hub-add-key-strip model-hub-add-key-strip--working">
@@ -392,24 +361,6 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
</span>
</div>
)}
- {replacePhase.kind === 'done' && replacePhase.outcome.kind === 'impact' && (
- <div className="flex flex-col gap-2 rounded-lg border border-gold/40 bg-gold/[0.08] px-3.5 py-3">
- <span className="model-hub-ink-gold text-[12.5px] font-semibold leading-relaxed">
- {t('settings.models.repair.refreshed')}
- </span>
- <GuardImpact
- hops={replacePhase.outcome.hops}
- gaps={replacePhase.outcome.gaps}
- committed
- />
- </div>
- )}
- {replacePhase.kind === 'done' && replacePhase.outcome.kind === 'repaired' && (
- <div className="model-hub-ink-mint flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium">
- <CheckCircle2 className="size-4 shrink-0" />
- {t(REPAIR_LINE_KEY.repaired)}
- </div>
- )}
</div>
)}
@@ -454,28 +405,22 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
disabled={!canCancel}
onClick={cancel}
>
- {t(replacePhase.kind === 'done'
- ? 'common.close'
- : replacePhase.kind === 'guard'
- ? 'settings.models.guard.cancel'
- : 'settings.models.addKey.cancel')}
+ {t('settings.models.addKey.cancel')}
</Button>
- {replacePhase.kind !== 'done' && !replaceTerminalFailure && (
+ {!replaceTerminalFailure && (
<Button
type="button"
- variant={replacePhase.kind === 'guard' ? 'destructive' : 'brand'}
+ variant="brand"
className="model-hub-add-key-action"
disabled={replacePhase.kind === 'submitting' || !apiKey.trim()}
- onClick={() => void submitReplacement(replacePhase.kind === 'guard')}
+ onClick={() => void submitReplacement(null)}
>
{replacePhase.kind === 'submitting' && <LoaderCircle className="size-3 animate-spin" />}
{t(replacePhase.kind === 'submitting'
? 'settings.models.repair.replacing'
- : replacePhase.kind === 'guard'
- ? 'settings.models.guard.confirm.replaceKey'
- : replacePhase.kind === 'failure'
- ? 'settings.models.addKey.retry'
- : 'settings.models.repair.replaceSubmit')}
+ : replacePhase.kind === 'failure'
+ ? 'settings.models.addKey.retry'
+ : 'settings.models.repair.replaceSubmit')}
</Button>
)}
</>
@@ -501,6 +446,19 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
</>
)}
</footer>
+ {replaceMode && (
+ <GuardDialog
+ open={guard !== null}
+ title={t('settings.models.guard.title.replaceKey', { source: props.source.display_name })}
+ subtitle={t('settings.models.guard.subtitle.replaceKey')}
+ confirmLabel={t('settings.models.guard.confirm.replaceKey')}
+ busy={replacePhase.kind === 'submitting'}
+ onCancel={() => setGuard(null)}
+ onConfirm={() => { if (guard) void submitReplacement(guard); }}
+ >
+ {guard && <GuardImpact hops={guard.hops} gaps={guard.gaps} />}
+ </GuardDialog>
+ )}
</DialogPrimitive.Content>
</DialogPrimitive.Portal>
</DialogPrimitive.Root>
diff --git a/ui/src/components/settings/models/AdoptionNote.test.tsx b/ui/src/components/settings/models/AdoptionNote.test.tsx
deleted file mode 100644
index 57dfa040d..000000000
--- a/ui/src/components/settings/models/AdoptionNote.test.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-import * as React from 'react';
-import { renderToStaticMarkup } from 'react-dom/server';
-import { beforeEach, describe, expect, it } from 'vitest';
-import { I18nextProvider } from 'react-i18next';
-
-import i18n from '@/i18n';
-import { AdoptionNote } from './AdoptionNote';
-
-beforeEach(async () => { await i18n.changeLanguage('en'); });
-
-const render = (addedTo: React.ComponentProps<typeof AdoptionNote>['addedTo']) => renderToStaticMarkup(
- <I18nextProvider i18n={i18n}>
- <AdoptionNote addedTo={addedTo} adoptedBy={addedTo?.map(({ backend, menu_model }) => ({ backend, menu_model })) ?? null} />
- </I18nextProvider>,
-);
-
-describe('AdoptionNote', () => {
- it('renders exact add-time Route locations', () => {
- const html = render([{ backend: 'claude', menu_model: 'claude-opus-4-6', source_id: 'src_a', model_id: 'claude-opus-4-6', position: 2 }]);
- expect(html).toContain('Claude Code');
- expect(html).toContain('claude-opus-4-6');
- });
-
- it('states that an unmatched source remains available for explicit routing', () => {
- expect(render([])).toContain('route');
- });
-});
diff --git a/ui/src/components/settings/models/AdoptionNote.tsx b/ui/src/components/settings/models/AdoptionNote.tsx
deleted file mode 100644
index 4c84480e9..000000000
--- a/ui/src/components/settings/models/AdoptionNote.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-import * as React from 'react';
-import { useTranslation } from 'react-i18next';
-
-import type { AddedTo, AdoptedBy } from './types';
-
-export const AdoptionNote: React.FC<{
- addedTo: AddedTo[] | null;
- adoptedBy: AdoptedBy[] | null;
-}> = ({ addedTo, adoptedBy }) => {
- const { t } = useTranslation();
- if (!addedTo || !adoptedBy) return null;
- if (addedTo.length === 0) {
- return <p className="text-[12px] leading-relaxed text-muted">{t('settings.models.adoption.none')}</p>;
- }
- const backendName = (backend: string) =>
- t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string;
- const locations = addedTo.map((entry) =>
- t('settings.models.adoption.route', {
- backend: backendName(entry.backend),
- model: entry.menu_model,
- position: entry.position,
- }),
- );
- return (
- <p className="text-[12px] leading-relaxed text-muted">
- {t('settings.models.adoption.enabled', { list: locations.join(' · ') })}
- </p>
- );
-};
-
-export default AdoptionNote;
diff --git a/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx b/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx
index 38a7f1b5f..4d09ad9d8 100644
--- a/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx
+++ b/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx
@@ -50,10 +50,6 @@ const staleCandidates = (changed: Record<string, RouteHop[]>) => new ApiCallErro
changed,
);
-/** The confirmation lives inside the row it is about, and its Cancel is one of
- * three on screen. */
-const confirmation = () => within(screen.getByRole('alert').parentElement as HTMLElement);
-
const enabledAddModels = () => waitFor(() => {
const button = screen.getByRole('button', { name: 'Add models' }) as HTMLButtonElement;
expect(button.disabled).toBe(false);
@@ -187,42 +183,54 @@ describe('BackendModelCatalogDialog', () => {
expect(write.mock.calls[0][1].models.map((entry: BackendModel) => entry.id)).toEqual(['alpha']);
});
- it('does not ask a focused removal twice about the route its one confirmation covered', async () => {
+ it('forces a confirmed focused removal through the guard without asking again, even when the plan moves', async () => {
const user = userEvent.setup();
- const hops = [{ backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position: 1 }];
- vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha'), model('beta')]));
+ const shown = [{ backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position: 1 }];
+ const moved = [{ backend: 'claude' as const, menu_model: 'beta', source_id: 'src_b', model_id: 'beta-max', position: 1 }];
+ const gaps = [{ backend: 'claude' as const, model_id: 'beta', agents: [] }];
+ const refusal = (hops: typeof shown, interrupt: typeof gaps = []) => new ApiCallError(
+ 'backend_model_in_route', 'modelHub.errors.backend_model_in_route', true, interrupt, [], hops, 409,
+ );
+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha'), model('beta')], {
+ routes: { beta: { hops: [{ source_id: 'src_a', model_id: 'beta-air' }] } },
+ }));
const write = vi.spyOn(modelsApi, 'putAgentModels')
- .mockRejectedValueOnce(new ApiCallError(
- 'backend_model_in_route', 'modelHub.errors.backend_model_in_route', true, [], [], hops, 409,
- ))
+ .mockRejectedValueOnce(refusal(shown))
+ .mockRejectedValueOnce(refusal(moved, gaps))
.mockResolvedValue(agent([model('alpha')]));
- const { onClose } = renderDialog({ focus: { modelId: 'beta', action: 'remove', route: [{ source_id: 'src_a', model_id: 'beta-air' }] } });
+ const { onClose } = renderDialog({ focus: { modelId: 'beta', action: 'remove' } });
const confirm = await screen.findByRole('dialog', { name: 'Remove beta?' });
await user.click(within(confirm).getByRole('button', { name: 'Remove' }));
await waitFor(() => expect(onClose).toHaveBeenCalledWith({ removed: true }));
- expect(write).toHaveBeenCalledTimes(2);
- expect(write.mock.calls[1][1]).toMatchObject({ force: true, would_remove_hops: hops, would_interrupt: [] });
+ expect(screen.queryByRole('dialog', { name: 'Save the model list?' })).toBeNull();
+ expect(write).toHaveBeenCalledTimes(3);
+ expect(write.mock.calls[0][1].force).toBeUndefined();
+ expect(write.mock.calls[1][1]).toMatchObject({ force: true, would_remove_hops: shown, would_interrupt: [] });
+ expect(write.mock.calls[2][1]).toMatchObject({ force: true, would_remove_hops: moved, would_interrupt: gaps });
});
- it('asks a focused removal again when the refused route is not the one it showed', async () => {
+ it('keeps a confirmed focused removal on screen until its forced resend lands', async () => {
const user = userEvent.setup();
- const hops = [{ backend: 'claude' as const, menu_model: 'beta', source_id: 'src_b', model_id: 'beta-max', position: 1 }];
- vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha'), model('beta')]));
+ const hops = [{ backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position: 1 }];
+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha'), model('beta')], {
+ routes: { beta: { hops: [{ source_id: 'src_a', model_id: 'beta-air' }] } },
+ }));
+ let settle: (value: ReturnType<typeof agent>) => void = () => {};
const write = vi.spyOn(modelsApi, 'putAgentModels')
.mockRejectedValueOnce(new ApiCallError(
'backend_model_in_route', 'modelHub.errors.backend_model_in_route', true, [], [], hops, 409,
))
- .mockResolvedValue(agent([model('alpha')]));
- renderDialog({ focus: { modelId: 'beta', action: 'remove', route: [{ source_id: 'src_a', model_id: 'beta-air' }] } });
+ .mockReturnValueOnce(new Promise((resolve) => { settle = resolve; }));
+ const { onClose } = renderDialog({ focus: { modelId: 'beta', action: 'remove' } });
const confirm = await screen.findByRole('dialog', { name: 'Remove beta?' });
await user.click(within(confirm).getByRole('button', { name: 'Remove' }));
- await waitFor(() => expect(write).toHaveBeenCalledTimes(1));
- const again = await screen.findByRole('dialog', { name: 'Remove beta?' });
- await waitFor(() => expect(within(again).getByRole('button', { name: 'Remove' })).toHaveProperty('disabled', false));
- expect(write).toHaveBeenCalledTimes(1);
- await user.click(within(again).getByRole('button', { name: 'Remove' }));
await waitFor(() => expect(write).toHaveBeenCalledTimes(2));
- expect(write.mock.calls[1][1]).toMatchObject({ force: true, would_remove_hops: hops });
+ // The forced resend is still out: the question that started it is the only
+ // surface this focused save has, so it stays, inert, until the answer lands.
+ expect(screen.getByRole('dialog', { name: 'Remove beta?' })).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Remove' })).toHaveProperty('disabled', true);
+ await act(async () => { settle(agent([model('alpha')])); });
+ await waitFor(() => expect(onClose).toHaveBeenCalledWith({ removed: true }));
});
it('keeps a focused editor on screen and inert while its save is pending', async () => {
@@ -488,30 +496,26 @@ describe('BackendModelCatalogDialog', () => {
}));
});
- it('shows what a removal takes with it, then echoes the guard byte for byte whatever order it was clicked in', async () => {
+ it('removes rows on the click, asks once on save in its own dialog, then echoes the guard byte for byte', async () => {
const user = userEvent.setup();
const catalog = [model('alpha'), model('beta'), model('gamma')];
/**
* The server's plan, in the server's order: it walks the baseline it was
- * sent, so `beta` comes before `gamma` no matter which the user clicked
- * first. Written once, because it is the fixture for every half of the
- * property below — what each question shows, and what the forced save
- * carries, are these same bytes.
+ * sent, so `beta` comes before `gamma` no matter which the user removed
+ * first. What the dialog shows and what the forced save carries are these
+ * same bytes. The route on `src_gone` is one the baseline never showed —
+ * the server's plan is the whole account, not the dialog's projection.
*/
const hops = [
{ backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position: 1 },
{ backend: 'claude' as const, menu_model: 'beta', source_id: 'src_gone', model_id: 'beta-backup', position: 2 },
{ backend: 'claude' as const, menu_model: 'gamma', source_id: 'src_a', model_id: 'gamma-air', position: 1 },
];
- const routed = (menuModel: string) => hops.filter((hop) => hop.menu_model === menuModel);
vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(catalog, {
- routes: Object.fromEntries(['beta', 'gamma'].map((menuModel) => [
- menuModel,
- { hops: routed(menuModel).map(({ source_id, model_id }) => ({ source_id, model_id })) },
- ])),
+ routes: { beta: { hops: [{ source_id: 'src_a', model_id: 'beta-air' }] } },
}));
const write = vi.spyOn(modelsApi, 'putAgentModels')
- .mockRejectedValueOnce(new ApiCallError(
+ .mockRejectedValue(new ApiCallError(
'backend_model_in_route',
'modelHub.errors.backend_model_in_route',
true,
@@ -519,71 +523,106 @@ describe('BackendModelCatalogDialog', () => {
[],
hops,
409,
- ))
- .mockResolvedValue(agent([model('alpha')]));
- renderDialog();
-
- // A route is the only thing a removal takes with it that the user did not
- // name, so it is the only removal that asks — and it asks on the click,
- // from the routes the dialog already holds, not after a round-trip.
- await user.click(await screen.findByRole('button', { name: 'Remove alpha' }));
- expect(screen.queryByRole('alert')).toBeNull();
- expect(screen.getByText('2 models')).toBeTruthy();
+ ));
+ const { onClose } = renderDialog();
- await user.click(screen.getByRole('button', { name: 'Remove beta' }));
- const asked = screen.getByRole('alert');
- // The shared guard body, as the Route dialog shows it: every hop the plan
- // names, at the order it sits at, and however many there are.
- expect(asked.textContent).toContain('2 hops');
- for (const hop of routed('beta')) {
- expect(within(asked).getByText(`${hop.model_id} · Order #${hop.position}`)).toBeTruthy();
+ // The trash removes the row, routed or not: nothing is asked in the list.
+ for (const menuModel of ['gamma', 'beta']) {
+ await user.click(await screen.findByRole('button', { name: `Remove ${menuModel}` }));
}
- // Whether anything is stranded is the guard's answer, not this dialog's, so
- // the preview says what it knows and stays silent about the rest. Both
- // readings are withheld, not just the alarming one: 「still has another
- // source available」 is the dangerous half here, because it is a promise
- // about supply this dialog cannot see, made in the confirmation the user
- // decides on.
- expect(within(asked).queryByText('Models that will be left with no source')).toBeNull();
- expect(asked.textContent).not.toContain('These models still have another source available.');
- expect(asked.textContent).not.toContain('Some models will be left with no usable source.');
- expect(screen.getByText('2 models')).toBeTruthy();
-
- // Asking is not doing.
- await user.click(confirmation().getByRole('button', { name: 'Cancel' }));
expect(screen.queryByRole('alert')).toBeNull();
- expect(screen.getByText('2 models')).toBeTruthy();
+ expect(screen.getByText('1 model')).toBeTruthy();
- // Answered in the order the user chose, which is the reverse of the order
- // the server will report them in.
- const clicked = ['gamma', 'beta'];
- for (const menuModel of clicked) {
- await user.click(screen.getByRole('button', { name: `Remove ${menuModel}` }));
- await user.click(confirmation().getByRole('button', { name: 'Remove' }));
- }
- expect(screen.getByText('0 models')).toBeTruthy();
await user.click(screen.getByRole('button', { name: 'Save' }));
+ const guard = await screen.findByRole('dialog', { name: 'Save the model list?' });
+ expect(guard.textContent).toContain('3 hops');
+ for (const hop of hops) {
+ expect(within(guard).getByText(`${hop.model_id} · Order #${hop.position}`)).toBeTruthy();
+ }
+ // The removed rows stay removed behind the question: nothing re-inserts them.
+ expect(screen.queryByText('beta')).toBeNull();
+ expect(screen.queryByText('gamma')).toBeNull();
+
+ // Cancel returns to the draft exactly as the user left it. (The header's
+ // close button carries the same name and takes the same path.)
+ await user.click(within(guard).getAllByRole('button', { name: 'Cancel' }).at(-1)!);
+ expect(screen.queryByRole('dialog', { name: 'Save the model list?' })).toBeNull();
+ expect(screen.getByText('1 model')).toBeTruthy();
+ expect(write).toHaveBeenCalledTimes(1);
+ expect(onClose).not.toHaveBeenCalled();
- await waitFor(() => expect(write).toHaveBeenCalledTimes(2));
- // Nothing was asked twice: the guard named the consequences the user had
- // already accepted, so the retry is the dialog's own business rather than a
- // second confirmation of the same removal.
- expect(screen.queryByRole('alert')).toBeNull();
+ write.mockReset();
+ write
+ .mockRejectedValueOnce(new ApiCallError(
+ 'backend_model_in_route', 'modelHub.errors.backend_model_in_route', true, [], [], hops, 409,
+ ))
+ .mockResolvedValue(agent([model('alpha')]));
+ await user.click(screen.getByRole('button', { name: 'Save' }));
+ const again = await screen.findByRole('dialog', { name: 'Save the model list?' });
+ await user.click(within(again).getByRole('button', { name: 'Remove anyway' }));
+ await waitFor(() => expect(onClose).toHaveBeenCalledWith(undefined));
+ expect(write).toHaveBeenCalledTimes(2);
const [first, second] = write.mock.calls.map(([, body]) => body as Record<string, unknown>);
- // The first attempt claims no agreement at all. Only the server states what
- // a write would take with it, so until it has, there is nothing to echo.
+ // The first attempt claims no agreement: only the server states what a
+ // write would take with it.
expect(Object.keys(first)).toEqual(['baseline', 'models']);
- // The second is the refusal itself, byte for byte and in the server's own
- // order — byte-equal because that is how the server reads it, element by
- // element against what it sent, so the same consequences in another order
- // is a different answer and not the one it asked for.
+ // The confirmed one is the refusal itself, byte for byte and in the
+ // server's order, which is not the order the rows were removed in.
expect(second.force).toBe(true);
expect(JSON.stringify(second.would_remove_hops)).toBe(JSON.stringify(hops));
expect(JSON.stringify(second.would_interrupt)).toBe(JSON.stringify([]));
- // And the fixture earns that: the order the rows were clicked in is not the
- // order the echo carries, so nothing reassembled from the questions could
- // have passed the line above.
- expect(clicked).not.toEqual([...new Set(hops.map((hop) => hop.menu_model))]);
+ });
+
+ it('keeps the confirmed guard mounted and busy until the forced save lands', async () => {
+ const user = userEvent.setup();
+ const hops = [{ backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position: 1 }];
+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha'), model('beta')]));
+ let settle: (value: ReturnType<typeof agent>) => void = () => {};
+ vi.spyOn(modelsApi, 'putAgentModels')
+ .mockRejectedValueOnce(new ApiCallError(
+ 'backend_model_in_route', 'modelHub.errors.backend_model_in_route', true, [], [], hops, 409,
+ ))
+ .mockReturnValueOnce(new Promise((resolve) => { settle = resolve; }));
+ let pending = false;
+ const { onClose } = renderDialog({
+ catalogWrite: {
+ get pending() { return pending; },
+ track: async (work) => { pending = true; try { await work(); } finally { pending = false; } },
+ },
+ });
+ await user.click(await screen.findByRole('button', { name: 'Remove beta' }));
+ await user.click(screen.getByRole('button', { name: 'Save' }));
+ const guard = await screen.findByRole('dialog', { name: 'Save the model list?' });
+ await user.click(within(guard).getByRole('button', { name: 'Remove anyway' }));
+ expect(screen.getByRole('dialog', { name: 'Save the model list?' })).toBeTruthy();
+ await act(async () => { settle(agent([model('alpha')])); });
+ await waitFor(() => expect(onClose).toHaveBeenCalledWith(undefined));
+ });
+
+ it('ends a confirmed save whose plan never settles as a failure, not a second question', async () => {
+ const user = userEvent.setup();
+ const hops = (position: number) => [
+ { backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position },
+ ];
+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha'), model('beta')]));
+ let refusals = 0;
+ const write = vi.spyOn(modelsApi, 'putAgentModels').mockImplementation(async () => {
+ refusals += 1;
+ throw new ApiCallError(
+ 'backend_model_in_route', 'modelHub.errors.backend_model_in_route', true, [], [], hops(refusals), 409,
+ );
+ });
+ const { onClose } = renderDialog();
+ await user.click(await screen.findByRole('button', { name: 'Remove beta' }));
+ await user.click(screen.getByRole('button', { name: 'Save' }));
+ const guard = await screen.findByRole('dialog', { name: 'Save the model list?' });
+ await user.click(within(guard).getByRole('button', { name: 'Remove anyway' }));
+ expect(await screen.findByText(i18n.t('settings.models.gateway.catalog.saveRouted'))).toBeTruthy();
+ // One question, then the initial write plus the bounded resends: the plan
+ // that kept moving is reported, not asked about a second time.
+ expect(screen.queryByRole('dialog', { name: 'Save the model list?' })).toBeNull();
+ expect(write).toHaveBeenCalledTimes(4);
+ expect(onClose).not.toHaveBeenCalled();
});
it('re-asks with the current suppliers when the ones it displayed went stale', async () => {
@@ -829,6 +868,8 @@ describe('BackendModelCatalogDialog', () => {
refusal: ApiCallError;
/** The same question, asked again with what the server actually holds. */
reasked: () => Promise<unknown>;
+ /** The user's answer, through to the save it sends — and only one: a
+ * confirmation that needed another Save press would be a second ask. */
answer: (user: ReturnType<typeof userEvent.setup>) => Promise<void>;
/** Exactly the list the answered save sends. Exact, not 「contains」: a row
* rebuilt from its candidate keeps the id and loses the edit. */
@@ -838,13 +879,13 @@ describe('BackendModelCatalogDialog', () => {
};
/**
- * The plan the server holds and the client could not see.
+ * The plan the server holds.
*
* Written once, because it is the fixture for both halves of the property:
- * what the confirmation shows and what the answered save echoes are the same
- * two arrays. It strands a model on purpose — a refusal that interrupts
- * something is still a question the user may answer, so the ask must carry
- * the interruption rather than be withheld because of it.
+ * what the guard dialog shows and what the answered save echoes are the
+ * same two arrays. It strands a model on purpose — a refusal that
+ * interrupts something is still a question the user may answer, so the ask
+ * must carry the interruption rather than be withheld because of it.
*/
const GUARDED = {
hops: [{ backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position: 1 }],
@@ -878,22 +919,19 @@ describe('BackendModelCatalogDialog', () => {
},
answer: async (user) => {
await user.click(screen.getByRole('button', { name: 'Add 1 model' }));
+ await user.click(await screen.findByRole('button', { name: 'Save' }));
},
models: [ALPHA, model('beta'), { ...candidateBackendModel(shown), context_window: 2000 }],
agreement: { expected_suppliers: { 'glm-5.2': [{ source_id: 'src_b', model_id: 'glm-5.2' }] } },
},
{
- what: 'a route the client could not see guarded the removal',
- // No route in the read at all: it was created after the baseline, which
- // is why the client removed the row without asking and only the server
- // could refuse it. And why the list is not read again — the refusal
- // answers the exact write that was sent, so the draft is rebased onto
- // the same baseline it was built from.
+ what: 'the route guard refused the removal',
+ // The list is not read again: the refusal answers the exact write that
+ // was sent, so the draft stays on the baseline it was built from.
read: agent(CATALOG),
arrange: async (user) => {
// A removal cannot carry an edit, so the work at stake is the rest of
- // the draft: this refusal hands the removal back, and rebasing it in
- // is where an edit goes missing.
+ // the draft, which the question must leave exactly as it was.
await widen(user, 'alpha');
await user.click(await screen.findByRole('button', { name: 'Remove beta' }));
expect(screen.queryByRole('alert')).toBeNull();
@@ -907,13 +945,10 @@ describe('BackendModelCatalogDialog', () => {
GUARDED.hops,
409,
),
- // Asked through the same confirmation that records what a save may
- // force, and showing the whole plan the server named rather than the
- // empty one the client had — the same evidence body the Route dialog
- // shows, so a removal here and a route change there answer the same
- // question with the same words.
+ // Asked once, in its own dialog, with the whole plan the server named —
+ // the same evidence body every guarded Model Hub write shows.
reasked: async () => {
- const asked = await screen.findByRole('alert');
+ const asked = await screen.findByRole('dialog', { name: 'Save the model list?' });
for (const hop of GUARDED.hops) {
expect(within(asked).getByText(`${hop.model_id} · Order #${hop.position}`)).toBeTruthy();
}
@@ -925,7 +960,7 @@ describe('BackendModelCatalogDialog', () => {
return asked;
},
answer: async (user) => {
- await user.click(confirmation().getByRole('button', { name: 'Remove' }));
+ await user.click(screen.getByRole('button', { name: 'Remove anyway' }));
},
models: [EDITED],
// Both arrays, because both were shown: an echo of one would claim a
@@ -958,7 +993,6 @@ describe('BackendModelCatalogDialog', () => {
expect(read).toHaveBeenCalledTimes(1);
await member.answer(user);
- await user.click(await screen.findByRole('button', { name: 'Save' }));
// One save per answer, carrying the draft the user built and the
// agreement the server itself stated. Asserted on the last call because
@@ -1065,49 +1099,6 @@ describe('BackendModelCatalogDialog', () => {
expect(body.expected_suppliers).toEqual({ 'glm-5.2': [] });
});
- it('restores a refused removal to its own place, so cancelling it leaves nothing edited', async () => {
- const user = userEvent.setup();
- // A removal the server refuses was never a decision, so undoing it may not
- // cost the row its place: the requested list is the one it is already gone
- // from, and appending it back would answer 「are you sure?」 with a
- // reordered catalog the user never asked for. Cancelling then has to leave
- // the draft equal to the baseline, rows and order — the only state that
- // can honestly report itself as unedited.
- const rowOrder = () => screen.getAllByRole('button', { name: /^Reorder / })
- .map((row) => row.getAttribute('aria-label')?.replace('Reorder ', ''));
- vi.spyOn(modelsApi, 'getAgentSources')
- .mockResolvedValue(agent([model('alpha'), model('beta'), model('gamma')]));
- const write = vi.spyOn(modelsApi, 'putAgentModels').mockRejectedValue(new ApiCallError(
- 'backend_model_in_route',
- 'modelHub.errors.backend_model_in_route',
- true,
- [],
- [],
- GUARDED.hops,
- 409,
- ));
- const { onSaved, onClose } = renderDialog();
-
- await user.click(await screen.findByRole('button', { name: 'Remove beta' }));
- expect(rowOrder()).toEqual(['alpha', 'gamma']);
- await user.click(screen.getByRole('button', { name: 'Save' }));
-
- // Handed back into its own row, between the two it sat between — not after
- // the rows that outlived it.
- expect(await screen.findByRole('alert')).toBeTruthy();
- expect(rowOrder()).toEqual(['alpha', 'beta', 'gamma']);
-
- await user.click(confirmation().getByRole('button', { name: 'Cancel' }));
- expect(rowOrder()).toEqual(['alpha', 'beta', 'gamma']);
- // And nothing left to send, because nothing is different: a draft still
- // reporting itself as edited would offer a write that repeats the
- // baseline back to the server.
- expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(true);
- expect(write).toHaveBeenCalledTimes(1);
- expect(onSaved).not.toHaveBeenCalled();
- expect(onClose).not.toHaveBeenCalled();
- });
-
it('promises what the refreshed offer holds, whichever picks the refusal disputes', async () => {
const user = userEvent.setup();
// One refusal carrying both answers at once: a pick the offer has dropped
@@ -1234,231 +1225,6 @@ describe('BackendModelCatalogDialog', () => {
expect(write).toHaveBeenCalledTimes(1);
});
- it('asks about every removal the guard held back, not just the first', async () => {
- const user = userEvent.setup();
- const catalog = [model('alpha'), model('beta'), model('gamma')];
- const routed = agent(catalog, {
- routes: {
- beta: { hops: [{ source_id: 'src_a', model_id: 'beta-air' }] },
- gamma: { hops: [{ source_id: 'src_a', model_id: 'gamma-air' }] },
- },
- });
- vi.spyOn(modelsApi, 'getAgentSources')
- .mockResolvedValueOnce(agent(catalog))
- .mockResolvedValue(routed);
- /** One hop per held-back removal. The fixture for the whole property:
- * each question shows its own hop, and the answered save echoes all of
- * them — so neither half may state the plan a second time. */
- const hops = [
- { backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position: 1 },
- { backend: 'claude' as const, menu_model: 'gamma', source_id: 'src_a', model_id: 'gamma-air', position: 1 },
- ];
- const write = vi.spyOn(modelsApi, 'putAgentModels')
- .mockRejectedValueOnce(new ApiCallError(
- 'backend_model_in_route',
- 'modelHub.errors.backend_model_in_route',
- true,
- [],
- [],
- hops,
- 409,
- ))
- .mockResolvedValue(agent([model('alpha')]));
- renderDialog();
-
- await user.click(await screen.findByRole('button', { name: 'Remove beta' }));
- await user.click(screen.getByRole('button', { name: 'Remove gamma' }));
- await user.click(screen.getByRole('button', { name: 'Save' }));
-
- // One question at a time, because the confirmation lives in the row it is
- // about — but every held-back removal gets one, carrying its own hop and
- // no one else's. A row handed back with no question is a removal the user
- // asked for that nobody answered; a question carrying the whole refusal
- // would ask each row to confirm the others.
- for (const hop of hops) {
- const asked = await screen.findByRole('alert');
- expect(within(asked).getByText(`${hop.model_id} · Order #${hop.position}`)).toBeTruthy();
- expect(asked.textContent).toContain('1 hop');
- await user.click(confirmation().getByRole('button', { name: 'Remove' }));
- }
- expect(screen.queryByRole('alert')).toBeNull();
-
- await user.click(screen.getByRole('button', { name: 'Save' }));
-
- await waitFor(() => expect(write).toHaveBeenLastCalledWith('claude', expect.objectContaining({
- models: [model('alpha')],
- force: true,
- would_remove_hops: hops,
- would_interrupt: [],
- })));
- });
-
- it('shows the row of whichever question is pending, whatever the search says', async () => {
- const user = userEvent.setup();
- // A question pending and a filter that matches none of the rows it is
- // about. The confirmation renders inside its row, so a filter that hid
- // that row would leave the draft holding a model the user removed, Save
- // disabled behind an unanswered question, and nothing on screen to
- // explain either — a dead end reachable by typing.
- const catalog = [model('alpha'), model('beta'), model('gamma')];
- const routed = agent(catalog, {
- routes: {
- beta: { hops: [{ source_id: 'src_a', model_id: 'beta-air' }] },
- gamma: { hops: [{ source_id: 'src_a', model_id: 'gamma-air' }] },
- },
- });
- vi.spyOn(modelsApi, 'getAgentSources')
- .mockResolvedValueOnce(agent(catalog))
- .mockResolvedValue(routed);
- const hops = [
- { backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position: 1 },
- { backend: 'claude' as const, menu_model: 'gamma', source_id: 'src_a', model_id: 'gamma-air', position: 1 },
- ];
- const write = vi.spyOn(modelsApi, 'putAgentModels')
- .mockRejectedValueOnce(new ApiCallError(
- 'backend_model_in_route',
- 'modelHub.errors.backend_model_in_route',
- true,
- [],
- [],
- hops,
- 409,
- ))
- .mockResolvedValue(agent([model('alpha')]));
- renderDialog();
-
- await user.click(await screen.findByRole('button', { name: 'Remove beta' }));
- await user.click(screen.getByRole('button', { name: 'Remove gamma' }));
- await user.click(screen.getByRole('button', { name: 'Save' }));
- await screen.findByRole('alert');
- await user.type(screen.getByLabelText('Search name or model ID'), 'alpha');
-
- for (const hop of hops) {
- // Whichever question is pending, its row is on screen with its own hop
- // and its own controls — and it is the only held-back row the search
- // lets through, so what put it there was the queue, not the query.
- const asked = await screen.findByRole('alert');
- expect(within(asked).getByText(`${hop.model_id} · Order #${hop.position}`)).toBeTruthy();
- expect(screen.getByText(hop.menu_model)).toBeTruthy();
- for (const other of hops.filter((entry) => entry !== hop)) {
- expect(screen.queryByText(other.menu_model)).toBeNull();
- }
- await user.click(confirmation().getByRole('button', { name: 'Remove' }));
- }
-
- // Queue empty, so the search is back in charge of the whole list.
- expect(screen.queryByRole('alert')).toBeNull();
- await user.click(screen.getByRole('button', { name: 'Save' }));
-
- await waitFor(() => expect(write).toHaveBeenLastCalledWith('claude', expect.objectContaining({
- models: [model('alpha')],
- force: true,
- would_remove_hops: hops,
- would_interrupt: [],
- })));
- });
-
- it('discards a queued question whose row has already left the draft, and forces nothing on its behalf', async () => {
- const user = userEvent.setup();
- // The queue outlives the question on screen, and the rows behind the head
- // keep their own controls — so the user can remove one before its turn
- // comes. There is then nothing left to remove and nowhere to ask, because
- // the confirmation renders inside the row, so the question goes with the
- // row. Left pending it would be worse than invisible: it is the head, and
- // the row that could advance the queue is the one that is gone, so every
- // question behind it goes unasked and the removals the user did ask for
- // can never be confirmed — the guard would refuse the list forever.
- //
- // Discarding it keeps the queue live but settles nothing: the consequence
- // the server named for that row was never displayed. So the save that
- // follows goes out unforced, and the two properties hold together — the
- // dialog never stalls, and it never vouches for what it did not show.
- const catalog = [model('alpha'), model('beta'), model('gamma'), model('delta')];
- vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(catalog, {
- // The one route this dialog can see. The others were created after the
- // read, which is why only the server could refuse them.
- routes: { delta: { hops: [{ source_id: 'src_a', model_id: 'delta-air' }] } },
- }));
- const hops = [
- { backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position: 1 },
- { backend: 'claude' as const, menu_model: 'gamma', source_id: 'src_a', model_id: 'gamma-air', position: 1 },
- ];
- const refusal = () => new ApiCallError(
- 'backend_model_in_route',
- 'modelHub.errors.backend_model_in_route',
- true,
- [],
- [],
- hops,
- 409,
- );
- const write = vi.spyOn(modelsApi, 'putAgentModels')
- .mockRejectedValueOnce(refusal())
- // The same refusal, because nothing was accepted and so nothing about
- // the routes changed: an unforced save asks the guard the same question
- // and gets the same answer.
- .mockRejectedValueOnce(refusal())
- .mockResolvedValue(agent([model('alpha'), model('delta')]));
- renderDialog();
-
- await user.click(await screen.findByRole('button', { name: 'Remove beta' }));
- await user.click(screen.getByRole('button', { name: 'Remove gamma' }));
- await user.click(screen.getByRole('button', { name: 'Save' }));
-
- // Both removals come back with a question each, the first of them on
- // screen with the server's own hop.
- const asked = await screen.findByRole('alert');
- expect(within(asked).getByText('beta-air · Order #1')).toBeTruthy();
-
- // The user answers the second one their own way instead: gamma has no
- // route this dialog knows of, so it simply leaves — and takes both the
- // pending question and its own queued one with it.
- await user.click(screen.getByRole('button', { name: 'Remove gamma' }));
- expect(screen.queryByRole('alert')).toBeNull();
-
- // A question about a row that is still here, so the queue gets another
- // chance to reach the one about the row that is not.
- await user.click(screen.getByRole('button', { name: 'Remove delta' }));
- expect(within(screen.getByRole('alert')).getByText('delta-air · Order #1')).toBeTruthy();
- await user.click(confirmation().getByRole('button', { name: 'Cancel' }));
-
- // Nothing is asked in gamma's name. The dialog is answering the user
- // again — not holding a question with no row to hold it, behind which
- // beta's removal could never be confirmed.
- expect(screen.queryByRole('alert')).toBeNull();
- expect(screen.getByText('delta')).toBeTruthy();
-
- await user.click(screen.getByRole('button', { name: 'Remove beta' }));
- await user.click(screen.getByRole('button', { name: 'Save' }));
-
- // The list is byte-for-byte the one the guard refused — and that is not
- // enough. Both questions left without ever being answered, so the two
- // hops the server named were never put to the user, and a `force` here
- // would be the client vouching for a consequence nobody was shown.
- await waitFor(() => expect(write).toHaveBeenCalledTimes(2));
- expect(write.mock.calls[1]?.[1]).toEqual({ baseline: catalog, models: [model('alpha'), model('delta')] });
-
- // So the guard refuses it again, with the same two hops, and the
- // questions come back — the round-trip the swallow cost, in exchange for
- // the user seeing what they are agreeing to.
- const reasked = await screen.findByRole('alert');
- expect(within(reasked).getByText('beta-air · Order #1')).toBeTruthy();
- await user.click(confirmation().getByRole('button', { name: 'Remove' }));
- expect(within(screen.getByRole('alert')).getByText('gamma-air · Order #1')).toBeTruthy();
- await user.click(confirmation().getByRole('button', { name: 'Remove' }));
-
- // Answered now, both of them, against the server's own account. This is
- // the only way the echo is reached, so it carries the refusal whole and
- // in the server's order rather than a transcript of the asking.
- await user.click(screen.getByRole('button', { name: 'Save' }));
- await waitFor(() => expect(write).toHaveBeenLastCalledWith('claude', expect.objectContaining({
- models: [model('alpha'), model('delta')],
- force: true,
- would_remove_hops: hops,
- would_interrupt: [],
- })));
- expect(write).toHaveBeenCalledTimes(3);
- });
});
it('treats a lost answer as saved once the re-read shows the intent already applied', async () => {
diff --git a/ui/src/components/settings/models/BackendModelCatalogDialog.tsx b/ui/src/components/settings/models/BackendModelCatalogDialog.tsx
index 81a733173..243db86dc 100644
--- a/ui/src/components/settings/models/BackendModelCatalogDialog.tsx
+++ b/ui/src/components/settings/models/BackendModelCatalogDialog.tsx
@@ -30,19 +30,16 @@ import {
catalogModelIds,
chosenCandidate,
draftRowFor,
- echoableRefusal,
heldRowFor,
offeredCandidates,
- orderWithRestored,
readBackendCatalogBaseline,
sameCatalog,
- samePlanContents,
type BackendCatalogBaseline,
- type BackendCatalogIntent,
type ChosenCandidate,
} from './backendCatalog';
import { BackendModelEditorDialog } from './BackendModelEditorDialog';
import { BackendModelPickerDialog } from './BackendModelPickerDialog';
+import { GuardDialog } from './GuardDialog';
import { GuardImpact, type GuardPicture, type GuardPlan } from './GuardImpact';
import { apiFailure, modelsApi } from './modelsApi';
import { movedOrder, sameIds } from './reorder';
@@ -53,9 +50,6 @@ import type {
BackendModel,
BackendModelsPut,
ModelCandidate,
- RouteHop,
- RouteHopRef,
- SupplyGap,
} from './types';
type ReadState = 'loading' | 'ready' | 'error';
@@ -71,21 +65,8 @@ type ReadState = 'loading' | 'ready' | 'error';
export type CatalogFocus = {
modelId: string;
action: 'edit' | 'remove';
- /** The route the opener showed for this row, in order — what a focused
- * removal's one confirmation stands for. */
- route?: readonly RouteHop[];
};
-/** Whether a refused plan removes exactly the route the opener showed. */
-const sameShownRoute = (hops: readonly RouteHopRef[], modelId: string, route: readonly RouteHop[]): boolean =>
- hops.length === route.length
- && [...hops].sort((left, right) => left.position - right.position).every((hop, index) => (
- hop.menu_model === modelId
- && hop.position === index + 1
- && hop.source_id === route[index].source_id
- && hop.model_id === route[index].model_id
- ));
-
/** Same shape the Source order drawer announces with: the key alone would tell a
* screen-reader user something moved without telling them where to. */
type AnnouncementKey = 'grabbed' | 'moved' | 'dropped' | 'grabCancelled';
@@ -104,99 +85,26 @@ const matchesQuery = (model: BackendModel, query: string, renderedLabel: string)
|| renderedLabel.toLowerCase().includes(needle);
};
-/**
- * One removal, waiting on an answer, carrying the account of its consequence
- * the user is being shown.
- *
- * The plan travels with the question because a re-ask after the guard refused
- * is about the server's plan and a first ask is about the baseline's — the
- * question is not answerable without the plan it was raised from. `account`
- * names whose plan it is, and that is the whole reason the field exists:
- * agreeing to what the dialog projected from the routes it holds is not
- * agreeing to what the server refused. Only a `guard` answer can settle a
- * refusal, so only a `guard` answer is allowed to discharge what one owes.
- */
-type RemovalQuestion = { modelId: string; plan: GuardPicture; account: 'draft' | 'guard' };
-
-/** A guard refusal, as received, together with the write it refused. Both
- * halves are needed to use it: the arrays are what a retry echoes, and the
- * write is what makes them true — the same refusal says nothing about a
- * different list. */
-type StoredRefusal = {
- hops: readonly RouteHopRef[];
- gaps: readonly SupplyGap[];
- baseline: readonly BackendModel[];
- models: readonly BackendModel[];
- /**
- * The held-back removals still owed an answer against the server's own plan.
- *
- * This is the acceptance bit: empty means accepted, and only an accepted
- * refusal may be echoed with `force`. It is separate from the write above
- * because the two answer different questions — the write says 「is this the
- * same save the server refused?」 and this says 「did the user accept that
- * refusal?」 — and the reachable path that made one stand in for the other is
- * why it exists. A queued question can be taken off the screen by removing
- * its row through the ordinary trash action, which recomputes from the
- * baseline and shows the dialog's own projection instead; answer the rest and
- * the draft is byte-for-byte the refused list again, so equality alone would
- * have forced a plan whose interruptions were never displayed.
- *
- * Discharged one id at a time, and only by a `guard` answer. A swallowed
- * question therefore leaves the save unforced, the server refuses it again
- * with the same arrays, and the question comes back — one extra round-trip,
- * and no loop, because acceptance is the only route to `force`.
- */
- owed: ReadonlySet<string>;
-};
-
-/**
- * The guard's refusal, split into the questions it forces.
- *
- * The server reports one plan for the whole write and the confirmation lives
- * inside a row, so each held-back removal is asked with the part of that plan
- * that names it: hops by the menu model they serve, gaps by the model they
- * would strand. Splitting decides what to SHOW and nothing else — what the next
- * save echoes is the refusal exactly as it arrived, never these pieces
- * reassembled (C3) — so a split that cannot cover every element still asks
- * everything it can rather than editing the plan down to what it understood.
- *
- * Anything the refusal names that this write does not remove belongs to no
- * question this dialog can ask, so it produces none; with nothing to ask at
- * all, the caller falls through to the failure sentence instead of retrying
- * forever.
- */
-const refusalPlans = (
- hops: readonly RouteHopRef[],
- gaps: readonly SupplyGap[],
- removed: ReadonlySet<string>,
- backend: AgentBackend,
-): RemovalQuestion[] => {
- const plans = new Map<string, GuardPlan>();
- const planFor = (modelId: string): GuardPlan | null => {
- if (!removed.has(modelId)) return null;
- const existing = plans.get(modelId);
- if (existing) return existing;
- const created: GuardPlan = { hops: [], gaps: [] };
- plans.set(modelId, created);
- return created;
- };
- for (const hop of hops) planFor(hop.menu_model)?.hops.push(hop);
- for (const gap of gaps) {
- if (gap.backend === backend) planFor(gap.model_id)?.gaps.push(gap);
- }
- return [...plans].map(([modelId, plan]) => ({ modelId, plan, account: 'guard' as const }));
-};
+/** A focused removal the user is being asked about, with the route preview the
+ * confirmation shows. */
+type FocusedRemoval = { modelId: string; plan: GuardPicture };
/** The stale-candidate refusal (C1), named by the route's own `error` rather
* than by status: nothing was committed and nothing was interrupted, so it is
* answered by asking again with today's suppliers, not by a failure sentence. */
const CANDIDATES_CHANGED = 'candidate_suppliers_changed';
-/** The route guard (C3). Like the refusal above it commits nothing, so it is
- * answered by asking again with the plan the server actually has — not by a
- * sentence about a save that never happened. */
+/** The route guard (C3). Like the refusal above it commits nothing: it is the
+ * server naming what this write would take with it, and it is answered by
+ * the user's one confirmation rather than by a failure sentence. */
const MODEL_IN_ROUTE = 'backend_model_in_route';
+/** How many times a confirmed save is resent when the guard's plan moved
+ * between the confirmation and the forced write. The user already agreed to
+ * remove these models, so a changed plan is resent rather than asked again;
+ * the bound only stops a plan that never settles from looping. */
+const FORCED_RESENDS = 2;
+
/** The ids a picker may not offer: everything the draft holds, less the ones it
* was reopened to ask about. A re-ask is about a row the draft still holds (the
* addition was refused, not applied), so counting it as 「already in the list」
@@ -248,12 +156,14 @@ export const BackendModelCatalogDialog: React.FC<{
const [saveFailedKey, setSaveFailedKey] = React.useState<TranslationKey | null>(null);
const [editing, setEditing] = React.useState<{ model: BackendModel | null; seedId?: string } | null>(null);
const [picking, setPicking] = React.useState<{ seed: ReadonlySet<string> } | null>(null);
- const [removing, setRemoving] = React.useState<RemovalQuestion | null>(null);
+ const [removing, setRemoving] = React.useState<FocusedRemoval | null>(null);
const [grabbedId, setGrabbedId] = React.useState<string | null>(null);
/** A focused opening that fell back to the full list. */
const [expanded, setExpanded] = React.useState(false);
/** The focused removal the user confirmed, kept on screen while it saves. */
- const [answered, setAnswered] = React.useState<RemovalQuestion | null>(null);
+ const [answered, setAnswered] = React.useState<FocusedRemoval | null>(null);
+ /** The guard's refusal of the last save, waiting on the user's one answer. */
+ const [guardPlan, setGuardPlan] = React.useState<GuardPlan | null>(null);
/** The focused edit the user committed, kept on screen while it saves. */
const [savingEdit, setSavingEdit] = React.useState<{ model: BackendModel | null; seedId?: string } | null>(null);
const [announcement, setAnnouncement] = React.useState<Announcement>(null);
@@ -271,58 +181,6 @@ export const BackendModelCatalogDialog: React.FC<{
* the list on screen is the decision, and this is what it was made against.
*/
const chosenRef = React.useRef(new Map<string, ChosenCandidate>());
- /**
- * Per removed id, the consequence the user was shown and accepted (C3).
- *
- * A record of what was asked, never a source of what is sent: the arrays a
- * forced write carries come from `refusalRef` and from nowhere else. This one
- * answers a different question — 「does the server's refusal say what the user
- * already agreed to?」 — and its only effect is whether the same consequence is
- * put to them a second time.
- */
- const previewRef = React.useRef(new Map<string, GuardPicture>());
- /**
- * The last guard refusal, stored exactly as it arrived and bound to the write
- * it refused.
- *
- * The single source of a forced body (C3). The two arrays are the server's
- * own, kept verbatim and in the server's order, because that is what the
- * server compares the echo against — a client that rebuilt them from what it
- * showed would be answering with its own sentence and be refused for the
- * wording, not the meaning.
- *
- * The write is stored with them so the echo cannot outlive its subject. A
- * refusal answers one exact `baseline` + `models` pair; the moment the draft
- * moves, the plan describes consequences of a write nobody is making any
- * more, and `putBody` finds it no longer matching rather than having to be
- * told to forget it.
- */
- const refusalRef = React.useRef<StoredRefusal | null>(null);
- /** Removals the guard held back, still owed an answer, each with the plan the
- * server refused them for. The confirmation lives inside the row it is about,
- * so they are asked one at a time — and all of them, because a row that came
- * back unasked is a removal the user requested and nobody ever answered. */
- const guardedRef = React.useRef<RemovalQuestion[]>([]);
-
- /**
- * Ask the next held-back removal, or stop asking. Also how an ordinary
- * confirmation closes: with nothing held back, this is `setRemoving(null)`.
- *
- * A queued question whose row has since left the draft is discarded rather
- * than asked. The confirmation renders inside the row it is about, so a
- * question about a row that no longer exists — a fresh baseline the server no
- * longer holds it in, an addition withdrawn on the way here — has nothing to
- * remove and nowhere to appear: asking it would leave the dialog waiting on an
- * answer the user has no controls to give. Discarding it is not losing the
- * user's intent either; the row it named is already gone.
- */
- const askNextGuarded = () => {
- const held = new Set(draftRef.current.map((model) => model.id));
- let next = guardedRef.current.shift();
- while (next && !held.has(next.modelId)) next = guardedRef.current.shift();
- setRemoving(next ?? null);
- };
-
const applyBaseline = React.useCallback((observed: BackendCatalogBaseline, models: BackendModel[]) => {
baselineRef.current = observed;
setBaseline(observed);
@@ -355,13 +213,11 @@ export const BackendModelCatalogDialog: React.FC<{
// All of these describe decisions taken against one baseline, so a dialog
// that is reading a new one starts with none of them.
chosenRef.current = new Map();
- previewRef.current = new Map();
- refusalRef.current = null;
- guardedRef.current = [];
setPicking(null);
setRemoving(null);
setExpanded(false);
setAnswered(null);
+ setGuardPlan(null);
loadBaseline(false);
return () => { readAttempt.current += 1; };
}, [loadBaseline, open]);
@@ -389,21 +245,7 @@ export const BackendModelCatalogDialog: React.FC<{
const retryable = editable && saveFailedKey !== null;
const filtering = query.trim() !== '';
const displayLabel = (model: BackendModel): string => model.display_name ?? model.id;
- /**
- * The rows on screen.
- *
- * A pending removal question is always one of them, whatever the query says.
- * Its confirmation renders inside its own row (the shape every guarded Model
- * Hub mutation asks in), so a filter that hides that row hides the only
- * controls that can answer it — and the draft has already restored the row, so
- * Save stays disabled with nothing on screen to explain why. Deriving
- * visibility from the queue rather than keeping the two beside each other is
- * what makes 「a question that is pending is on screen」 a property of this one
- * line instead of a rule every path that advances the queue has to remember.
- */
- const visible = draft.filter((model) => (
- model.id === removing?.modelId || matchesQuery(model, query.trim(), displayLabel(model))
- ));
+ const visible = draft.filter((model) => matchesQuery(model, query.trim(), displayLabel(model)));
const movableIds = draft.filter((model) => !model.locked).map((model) => model.id);
const takenIds = new Set(draft.map((model) => model.id));
const effortSuggestions = [...new Set(draft.flatMap((model) => model.reasoning_efforts))];
@@ -483,15 +325,15 @@ export const BackendModelCatalogDialog: React.FC<{
};
/**
- * A preview of what a removal would take with it, from the routes this dialog
- * already holds.
+ * A preview of what a focused removal would take with it, from the routes this
+ * dialog already holds.
*
- * It exists so the question can be asked when the user clicks the trash,
- * rather than after a round-trip — but it is a picture, not a plan, and
- * nothing it produces is ever sent. Only the server states the consequences
- * of a write (C3); this reads the baseline's own hops in their one-based
- * positions so that the picture matches the statement, and when it does the
- * save goes through without asking the same question twice.
+ * With no list behind it, the focused confirmation is asked before any
+ * round-trip, so it shows what the baseline already says — but it is a
+ * picture, not a plan, and nothing it produces is ever sent. Only the server
+ * states the consequences of a write (C3), and agreeing to this confirmation
+ * is agreeing to the removal, so a guard refusal of that save is resent with
+ * the server's own plan instead of being asked a second time.
*
* The gaps are `null`, not empty: whether a removal strands an Agent is the
* guard's answer, and this dialog holds no supply to answer it from. Empty
@@ -512,44 +354,13 @@ export const BackendModelCatalogDialog: React.FC<{
gaps: null,
});
- /** The row leaves the draft; its route leaves with it when the list saves. */
- const dropModel = (modelId: string, plan: GuardPicture) => {
+ /** The row leaves the draft; its route leaves with it when the list saves,
+ * after the one confirmation the save asks if the server says it has one. */
+ const dropModel = (modelId: string) => {
chosenRef.current.delete(modelId);
- if (plan.hops.length > 0 || (plan.gaps?.length ?? 0) > 0) previewRef.current.set(modelId, plan);
- else previewRef.current.delete(modelId);
mutate(draftRef.current.filter((entry) => entry.id !== modelId));
};
- /**
- * The user answers one removal question: the row leaves, and if the question
- * was the guard's own, the refusal is one answer closer to being echoable.
- *
- * Only a `guard` answer discharges anything. The same confirmation renders for
- * a removal the dialog itself asked about, and what that one shows is the
- * dialog's projection from the routes it holds — accepting it says nothing
- * about the plan the server refused, which may name interruptions the
- * projection had no way to know about.
- */
- const acceptRemoval = (question: RemovalQuestion) => {
- dropModel(question.modelId, question.plan);
- const refusal = refusalRef.current;
- if (question.account !== 'guard' || !refusal || !refusal.owed.has(question.modelId)) return;
- const owed = new Set(refusal.owed);
- owed.delete(question.modelId);
- refusalRef.current = { ...refusal, owed };
- };
-
- const removeModel = (model: BackendModel) => {
- const plan = removalPreview(model.id);
- // A route is the only thing a removal takes with it that the user did not
- // name, so it is the only removal that asks first.
- if (plan.hops.length > 0) {
- setRemoving({ modelId: model.id, plan, account: 'draft' });
- return;
- }
- dropModel(model.id, plan);
- };
-
/**
* The opener's named row, opened on once the catalog has been read.
*
@@ -561,7 +372,7 @@ export const BackendModelCatalogDialog: React.FC<{
const openFocus = useLatestRef((model: BackendModel) => {
// With no list behind it, the confirmation is the only place the removal
// can be answered, so it asks even when no route goes with the row.
- if (focus?.action === 'remove') setRemoving({ modelId: model.id, plan: removalPreview(model.id), account: 'draft' });
+ if (focus?.action === 'remove') setRemoving({ modelId: model.id, plan: removalPreview(model.id) });
else setEditing({ model });
});
const focusOpened = React.useRef<CatalogFocus | null>(null);
@@ -577,7 +388,9 @@ export const BackendModelCatalogDialog: React.FC<{
const direct = focus !== null && !expanded;
// A list this build cannot write, a read that failed and a save that failed
// all need the list to explain themselves.
- const needsList = legacy || readState === 'error' || saveFailedKey !== null;
+ // A guard question the focused surface did not already answer is asked over
+ // the list, where the removal it names can still be undone.
+ const needsList = legacy || readState === 'error' || saveFailedKey !== null || guardPlan !== null;
React.useEffect(() => {
if (direct && needsList) setExpanded(true);
}, [direct, needsList]);
@@ -648,11 +461,7 @@ export const BackendModelCatalogDialog: React.FC<{
const withdrawn = new Set([...seed].filter((id) => !confirmed.has(id) && !saved.has(id)));
if (picked.length === 0 && withdrawn.size === 0) return;
for (const id of withdrawn) chosenRef.current.delete(id);
- for (const pick of picked) {
- chosenRef.current.set(pick.candidate.id, pick);
- // Re-adding a row voids the removal that was confirmed for it.
- previewRef.current.delete(pick.candidate.id);
- }
+ for (const pick of picked) chosenRef.current.set(pick.candidate.id, pick);
const held = new Set(draftRef.current.map((model) => model.id));
const additions = picked
.filter((pick) => !held.has(pick.candidate.id))
@@ -688,26 +497,17 @@ export const BackendModelCatalogDialog: React.FC<{
* is not matched again, so a promise about it would describe nothing this
* write does.
*
- * The forced arrays are produced HERE and only here, from the stored refusal
- * and only from it, verbatim and in the server's own order (C3). That is what
- * makes the echo an echo: the server compares it against what it sent, and
- * it compares element by element, so a plan reassembled from per-row pieces
- * would carry the order they were clicked in and be refused for saying the
- * same thing differently. Nothing this dialog composes can reach these two
- * fields — there is no path to them that does not pass through a refusal the
- * server wrote.
- *
- * Whether a stored refusal has earned that echo is `echoableRefusal`'s
- * question, asked against this write rather than against a flag someone has
- * to remember to clear.
+ * The forced arrays are the guard refusal's own, verbatim and in the server's
+ * order (C3): the server compares the echo element by element against what it
+ * sent, so `confirmed` is only ever a plan the server wrote about this exact
+ * write — never one this dialog composed.
*/
- const putBody = (baselineModels: BackendModel[], requested: BackendModel[]): BackendModelsPut => {
+ const putBody = (baselineModels: BackendModel[], requested: BackendModel[], confirmed?: GuardPlan): BackendModelsPut => {
const body: BackendModelsPut = { baseline: baselineModels, models: requested };
- const refusal = refusalRef.current;
- if (refusal && echoableRefusal(refusal, baselineModels, requested)) {
+ if (confirmed) {
body.force = true;
- body.would_remove_hops = [...refusal.hops];
- body.would_interrupt = [...refusal.gaps];
+ body.would_remove_hops = [...confirmed.hops];
+ body.would_interrupt = [...confirmed.gaps];
}
const baselineIds = new Set(baselineModels.map((model) => model.id));
const expected = Object.fromEntries(
@@ -720,20 +520,45 @@ export const BackendModelCatalogDialog: React.FC<{
return body;
};
- const save = () => {
+ /**
+ * Save the draft.
+ *
+ * `agreed` is whether the user has already answered the removal question for
+ * this save — the guard dialog's confirm, or the focused removal's own. With
+ * it, a guard refusal is resent forced with the server's plan; without it,
+ * the refusal opens the one guard dialog. `confirmed` is the plan the forced
+ * write echoes.
+ *
+ * Every resend runs inside this one tracked write, so the promise it returns
+ * — and the confirmation surface waiting on it — spans the whole sequence.
+ * The guard stays mounted, busy, until the save settles, and only an
+ * unanswered refusal leaves it open.
+ */
+ const save = (agreed = false, confirmed?: GuardPlan): Promise<void> | undefined => {
const base = baselineRef.current;
// A pre-catalog server has no baseline to send, so there is nothing this
// branch could honestly PUT.
if (!base || base.models === null) return;
const baselineModels = base.models;
- const requested = draftRef.current;
- const intent = backendCatalogIntent(baselineModels, requested);
setSaveFailedKey(null);
- const body = putBody(baselineModels, requested);
return catalogWrite.track(async () => {
+ setGuardPlan(await sendCatalog(baselineModels, agreed, confirmed));
+ });
+ };
+
+ /** Runs the save to its end; resolves with the question still owed, if any. */
+ const sendCatalog = async (
+ baselineModels: BackendModel[],
+ agreed: boolean,
+ confirmed: GuardPlan | undefined,
+ ): Promise<GuardPlan | null> => {
+ let plan = confirmed;
+ for (let resends = 0; ;) {
+ const requested = draftRef.current;
+ const intent = backendCatalogIntent(baselineModels, requested);
let echoed: AgentSupply;
try {
- echoed = await modelsApi.putAgentModels(backend, body);
+ echoed = await modelsApi.putAgentModels(backend, putBody(baselineModels, requested, plan));
} catch (error) {
const failure = apiFailure(error);
if (failure?.code === CANDIDATES_CHANGED) {
@@ -800,7 +625,7 @@ export const BackendModelCatalogDialog: React.FC<{
if (withdrawn.size > 0) mutate(draftRef.current.filter((model) => !withdrawn.has(model.id)));
if (reask.length > 0) {
setPicking({ seed: new Set(reask) });
- return;
+ return null;
}
// Nothing left to ask, and the list already shows what changed: a drop
// is its own answer, and a sentence about it would be this dialog
@@ -810,102 +635,30 @@ export const BackendModelCatalogDialog: React.FC<{
// did not make. It terminates: every pass either drops at least one
// pick from the map that `disputed` is drawn from, or asks instead.
if (withdrawn.size > 0) {
- void save();
- return;
+ plan = undefined;
+ continue;
}
// Nothing to ask and nothing to drop: a refusal about ids this write
// promised nothing for is not one this dialog can answer, so it keeps
// the failure sentence below rather than resolving into silence.
}
- // The route guard. Nothing was committed, so this is not a failed save
- // but an unanswered question: the server has now stated what this exact
- // write would take with it, and the only thing missing is the user's
- // agreement to it.
- //
- // The statement is kept whole and unedited, bound to the write it
- // answers, because that is what the retry will echo. What follows
- // decides only whether the user has to be asked.
+ // The route guard. Nothing was committed: the server has stated what
+ // this exact write would take with it, and only the user's agreement is
+ // missing. A user who already agreed is not asked again — the write goes
+ // again echoing the server's plan, even when that plan differs from the
+ // one they saw, because what they agreed to was removing these models.
+ // A plan that keeps moving past the bound ends as the refusal below,
+ // never as a second question. Otherwise the plan opens the one guard
+ // dialog, and the draft stays exactly as the user left it behind it.
const refusal = failure?.code === MODEL_IN_ROUTE ? failure : null;
- const guardedPlans = refusal
- ? refusalPlans(refusal.wouldRemoveHops, refusal.wouldInterrupt, intent.removed, backend)
- : [];
- if (refusal && guardedPlans.length > 0) {
- // Does the server's plan say what the user already accepted? Compared
- // as contents, not as sequence: the previews were recorded row by row
- // as the trash was clicked, the server walks its own baseline, and two
- // orders of the same consequences are not a disagreement about them.
- const shown = [...previewRef.current]
- .filter(([modelId]) => intent.removed.has(modelId))
- .map(([, plan]) => plan);
- // A picture contributes no gaps, because it never claimed any: so a
- // server plan that names an interruption is by construction not
- // covered by what the user has already accepted, and the question is
- // re-asked with the server's own words.
- //
- // A focused removal is the exception for its hops, but only for the
- // route its opener showed. Its one confirmation already said that
- // route goes with the row, and the picture cannot see an automatic
- // route at all — so re-asking over the same hops would be the same
- // question twice. A route that changed since it was shown is not what
- // the user confirmed, and is asked with the server's own words.
- const shownRoute = direct && focus?.route
- && sameShownRoute(refusal.wouldRemoveHops, focus.modelId, focus.route);
- const agreed = (shownRoute || samePlanContents(refusal.wouldRemoveHops, shown.flatMap((plan) => plan.hops)))
- && samePlanContents(refusal.wouldInterrupt, shown.flatMap((plan) => plan.gaps ?? []));
- refusalRef.current = {
- hops: refusal.wouldRemoveHops,
- gaps: refusal.wouldInterrupt,
- baseline: baselineModels,
- models: requested,
- // An agreement that already covers this plan owes nothing: the user
- // has seen these consequences, and `agreed` is that statement.
- // Otherwise every removal being handed back owes an answer, and the
- // echo waits for the last of them.
- //
- // What the split could not attribute to any removed row is owed by
- // nobody, because there is no row for it to be asked in. It still
- // travels in the echo once every question that COULD be asked has
- // been answered — the alternative is a save the user can never make
- // — and that residue is a recorded decision, not an oversight.
- owed: agreed ? new Set() : new Set(guardedPlans.map((question) => question.modelId)),
- };
- // Already agreed, and this attempt did not carry the agreement: the
- // user answered this question before they pressed Save, and asking it
- // again would only be the dialog telling them what they just told it.
- // The same list goes again, this time echoing the server's own plan.
- // It terminates — that retry is forced, so it cannot take this branch
- // a second time.
- if (agreed && body.force !== true) {
- void save();
- return;
+ if (refusal && (refusal.wouldRemoveHops.length > 0 || refusal.wouldInterrupt.length > 0)) {
+ const next: GuardPlan = { hops: refusal.wouldRemoveHops, gaps: refusal.wouldInterrupt };
+ if (!agreed) return next;
+ if (resends < FORCED_RESENDS) {
+ plan = next;
+ resends += 1;
+ continue;
}
- // Not what was shown — a route created since the baseline was read, or
- // an Agent stranded by a removal that looked free — so every held-back
- // removal comes back into the draft and is asked again, through the
- // same confirmation, now carrying the server's own plan. The baseline
- // is deliberately NOT re-read: the refusal above answers this
- // `baseline` + `models` pair, and reading a newer list would leave the
- // dialog holding a plan about a write it can no longer make.
- //
- // It comes back to its own place, not to the end. The requested order
- // is the list with the row already gone, so the baseline is what says
- // where it belongs — and a removal the user then cancels leaves the
- // draft equal to the baseline, rows and order, which is the only state
- // that can honestly report itself as unedited.
- const heldBack = new Set(guardedPlans.map((question) => question.modelId));
- const held: BackendCatalogIntent = {
- ...intent,
- removed: new Set([...intent.removed].filter((id) => !heldBack.has(id))),
- order: orderWithRestored(intent.order, baselineModels.map((model) => model.id), heldBack),
- };
- mutate(applyBackendCatalogIntent(baselineModels, held));
- // What the user accepted for these rows was the preview, and it is not
- // what the server says. Confirming a question below records the
- // server's own account in its place.
- for (const modelId of heldBack) previewRef.current.delete(modelId);
- guardedRef.current = [...guardedPlans];
- askNextGuarded();
- return;
}
// A route that named its failure has decided what it did, and for this
// endpoint 「decided」 can still mean 「wrote」: the server commits the
@@ -928,7 +681,7 @@ export const BackendModelCatalogDialog: React.FC<{
applyBaseline(observed, current);
await Promise.resolve(onSaved(observed.agent)).catch(() => {});
closeSaved();
- return;
+ return null;
}
applyBaseline(observed, current ? applyBackendCatalogIntent(current, intent) : []);
await Promise.resolve(onObserved(observed.agent)).catch(() => {});
@@ -937,16 +690,17 @@ export const BackendModelCatalogDialog: React.FC<{
// its own sentence even when the re-read happens to agree with the
// draft, because that write never landed at all.
setSaveFailedKey(landed && unloaded ? 'settings.models.gateway.catalog.saveNotApplied' : reason);
- return;
+ return null;
} catch {
setReadState('error');
}
setSaveFailedKey(reason);
- return;
+ return null;
}
await Promise.resolve(onSaved(echoed)).catch(() => {});
closeSaved();
- });
+ return null;
+ }
};
const rowActions = (model: BackendModel) => (
@@ -965,7 +719,7 @@ export const BackendModelCatalogDialog: React.FC<{
className="model-hub-catalog-action model-hub-catalog-action--danger"
aria-label={t('settings.models.gateway.catalog.remove', { model: model.display_name ?? model.id }) as string}
disabled={busy}
- onClick={() => removeModel(model)}
+ onClick={() => dropModel(model.id)}
>
<Trash2 className="size-[15px]" aria-hidden="true" />
</button>
@@ -982,56 +736,6 @@ export const BackendModelCatalogDialog: React.FC<{
);
};
- /**
- * The question a routed removal asks, inside the row it is about.
- *
- * A route is a consequence the user did not choose when they chose the model,
- * so it is shown before it is taken — through the same evidence body every
- * other guarded Model Hub mutation shows, because the question is the same
- * question and an answer to it means the same thing. It renders the plan the
- * question was raised from: the baseline's route on a first ask, the server's
- * own refusal on a re-ask. Answering it removes the row and its route
- * together, in one transaction, when the list saves (C3).
- *
- * The page's Sources travel with it so each hop names its supplier. This
- * dialog still holds no Source concept — it does not resolve one, order one or
- * write one — but 「no hidden mappings」 is a rule about what the user is shown
- * before they agree, and 「a hop at position 2 disappears」 without whose hop it
- * was is exactly the hidden half.
- */
- const removeConfirmation = (model: BackendModel) => {
- if (removing?.modelId !== model.id) return null;
- const { plan } = removing;
- const asked = removing;
- return (
- <div className="model-hub-catalog-confirm">
- <div className="model-hub-catalog-consequence" role="alert">
- <GuardImpact hops={plan.hops} gaps={plan.gaps} sourceNames={sourceNames} />
- </div>
- <div className="flex items-center gap-2">
- <Button
- type="button"
- variant="outline"
- className="model-hub-catalog-confirm-action rounded-md text-[12.5px] font-semibold"
- disabled={busy}
- onClick={askNextGuarded}
- >
- {t('settings.models.gateway.catalog.cancel')}
- </Button>
- <Button
- type="button"
- variant="destructive"
- className="model-hub-catalog-confirm-action rounded-md text-[12.5px] font-bold"
- disabled={busy}
- onClick={() => { acceptRemoval(asked); askNextGuarded(); }}
- >
- {t('settings.models.gateway.catalog.removeConfirm')}
- </Button>
- </div>
- </div>
- );
- };
-
return (
<>
<Dialog
@@ -1146,7 +850,6 @@ export const BackendModelCatalogDialog: React.FC<{
key={model.id}
model={model}
grabbed={grabbedId === model.id}
- confirming={removing?.modelId === model.id}
draggable={!filtering && !busy}
registerGrip={(node) => {
if (node) grips.current.set(model.id, node);
@@ -1155,7 +858,6 @@ export const BackendModelCatalogDialog: React.FC<{
onGripKeyDown={(event) => handleGripKey(model.id, event)}
body={rowBody(model)}
actions={rowActions(model)}
- note={removeConfirmation(model)}
/>
)
))}
@@ -1190,7 +892,7 @@ export const BackendModelCatalogDialog: React.FC<{
type="button"
variant="brand"
className="model-hub-catalog-control rounded-md px-5 text-[12.5px] font-semibold"
- onClick={save}
+ onClick={() => void save()}
disabled={!editable || (!dirty && !retryable) || busy}
>
{busy && <LoaderCircle className="animate-spin" aria-hidden="true" />}
@@ -1251,6 +953,21 @@ export const BackendModelCatalogDialog: React.FC<{
onCommit={commitEdit}
/>
)}
+
+ {/* The save's one question. Cancel leaves the draft as the user left
+ it, so a removal they reconsider is re-added from the list and a
+ save they abandon is abandoned with the dialog's own Cancel. */}
+ <GuardDialog
+ open={guardPlan !== null}
+ title={t('settings.models.gateway.catalog.guardTitle')}
+ subtitle={t('settings.models.gateway.catalog.guardSubtitle')}
+ confirmLabel={t('settings.models.guard.confirm.removeModel')}
+ busy={busy}
+ onCancel={() => setGuardPlan(null)}
+ onConfirm={() => { if (guardPlan) void save(true, guardPlan); }}
+ >
+ {guardPlan && <GuardImpact hops={guardPlan.hops} gaps={guardPlan.gaps} sourceNames={sourceNames} />}
+ </GuardDialog>
</DialogContent>
</Dialog>
{open && direct && (editing ?? savingEdit) && (
@@ -1287,10 +1004,12 @@ export const BackendModelCatalogDialog: React.FC<{
cancelLabel={t('settings.models.gateway.catalog.cancel') as string}
confirmDisabled={busy}
onConfirm={() => {
+ // This confirmation is the removal's one question, so the save
+ // it starts is already agreed: a guard refusal is resent with
+ // the server's plan rather than asked again.
setAnswered(asked);
- acceptRemoval(asked);
- askNextGuarded();
- return save()?.finally(() => setAnswered(null));
+ dropModel(asked.modelId);
+ return save(true)?.finally(() => setAnswered(null));
}}
>
{(asked.plan.hops.length > 0 || (asked.plan.gaps?.length ?? 0) > 0) && (
@@ -1308,14 +1027,12 @@ export const BackendModelCatalogDialog: React.FC<{
const CatalogRow: React.FC<{
model: BackendModel;
grabbed: boolean;
- confirming: boolean;
draggable: boolean;
registerGrip: (node: HTMLButtonElement | null) => void;
onGripKeyDown: (event: React.KeyboardEvent<HTMLButtonElement>) => void;
body: React.ReactNode;
actions: React.ReactNode;
- note: React.ReactNode;
-}> = ({ model, grabbed, confirming, draggable, registerGrip, onGripKeyDown, body, actions, note }) => {
+}> = ({ model, grabbed, draggable, registerGrip, onGripKeyDown, body, actions }) => {
const { t } = useTranslation();
const controls = useDragControls();
return (
@@ -1323,10 +1040,7 @@ const CatalogRow: React.FC<{
value={model.id}
dragListener={false}
dragControls={controls}
- className={cn(
- 'model-hub-catalog-row flex min-w-0 list-none flex-col justify-center',
- confirming && 'is-confirming',
- )}
+ className="model-hub-catalog-row flex min-w-0 list-none flex-col justify-center"
>
<div className="flex min-w-0 items-center gap-3">
<button
@@ -1347,7 +1061,6 @@ const CatalogRow: React.FC<{
{body}
{actions}
</div>
- {note}
</Reorder.Item>
);
};
diff --git a/ui/src/components/settings/models/GuardDialog.tsx b/ui/src/components/settings/models/GuardDialog.tsx
new file mode 100644
index 000000000..82d165f19
--- /dev/null
+++ b/ui/src/components/settings/models/GuardDialog.tsx
@@ -0,0 +1,67 @@
+import * as React from 'react';
+import * as DialogPrimitive from '@radix-ui/react-dialog';
+import { Loader2, X } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Button } from '@/components/ui/button';
+
+/**
+ * The one confirmation a guarded Model Hub write asks.
+ *
+ * A guard refusal commits nothing and names what the write would take with it,
+ * so this modal shows that account (`children`, normally `GuardImpact`) and
+ * asks once. It is its own modal rather than a phase of the surface that made
+ * the write: the list, form or chain the user was editing stays exactly as they
+ * left it behind the question, and Cancel returns them to it unchanged.
+ *
+ * Confirming is final. A caller sends the write with the server's plan echoed
+ * back, and if the guard refuses that forced write because the plan moved in
+ * between, the caller resends with the new plan instead of opening this dialog
+ * a second time — the user has already answered the question it puts.
+ */
+export const GuardDialog: React.FC<{
+ open: boolean;
+ title: React.ReactNode;
+ subtitle: React.ReactNode;
+ confirmLabel: React.ReactNode;
+ busy: boolean;
+ onCancel: () => void;
+ onConfirm: () => void;
+ children?: React.ReactNode;
+}> = ({ open, title, subtitle, confirmLabel, busy, onCancel, onConfirm, children }) => {
+ const { t } = useTranslation();
+ return (
+ <DialogPrimitive.Root open={open} onOpenChange={(next) => { if (!next && !busy) onCancel(); }}>
+ <DialogPrimitive.Portal>
+ <DialogPrimitive.Overlay className="model-hub-guard-overlay fixed inset-0 z-50" />
+ <DialogPrimitive.Content
+ className="model-hub-guard-dialog fixed left-1/2 top-1/2 z-50 flex max-h-[calc(100dvh-2rem)] -translate-x-1/2 -translate-y-1/2 flex-col overflow-y-auto border border-border-strong bg-surface outline-none"
+ onEscapeKeyDown={(event) => { if (busy) event.preventDefault(); }}
+ onPointerDownOutside={(event) => { if (busy) event.preventDefault(); }}
+ >
+ <header className="model-hub-guard-head">
+ <div className="flex items-center justify-between gap-3">
+ <DialogPrimitive.Title className="model-hub-guard-title text-foreground">{title}</DialogPrimitive.Title>
+ <DialogPrimitive.Close asChild>
+ <Button type="button" variant="ghost" size="icon" className="model-hub-guard-close" disabled={busy} aria-label={t('settings.models.guard.cancel')} title={t('settings.models.guard.cancel')}>
+ <X aria-hidden />
+ </Button>
+ </DialogPrimitive.Close>
+ </div>
+ <DialogPrimitive.Description className="model-hub-guard-subtitle">{subtitle}</DialogPrimitive.Description>
+ </header>
+ {children ? <div className="model-hub-guard-body">{children}</div> : null}
+ <footer className="model-hub-guard-foot">
+ <Button type="button" variant="outline" className="model-hub-guard-action" onClick={onCancel} disabled={busy}>
+ {t('settings.models.guard.cancel')}
+ </Button>
+ <Button type="button" variant="destructive" className="model-hub-guard-action" onClick={onConfirm} disabled={busy}>
+ {busy && <Loader2 className="animate-spin" />}
+ {confirmLabel}
+ </Button>
+ </footer>
+ </DialogPrimitive.Content>
+ </DialogPrimitive.Portal>
+ </DialogPrimitive.Root>
+ );
+};
diff --git a/ui/src/components/settings/models/OAuthConnectDialog.test.ts b/ui/src/components/settings/models/OAuthConnectDialog.test.ts
index 839904687..02c8ee521 100644
--- a/ui/src/components/settings/models/OAuthConnectDialog.test.ts
+++ b/ui/src/components/settings/models/OAuthConnectDialog.test.ts
@@ -206,6 +206,46 @@ describe('add-subscription start recovery', () => {
});
});
+describe('reauth terminal', () => {
+ const finishedReauth = (repaired: OAuthResult['repaired']) => {
+ const flow = {
+ flow_id: 'oaf_reauth_done',
+ intent: 'reauth' as const,
+ vendor: 'anthropic',
+ channel: 'native_cli' as const,
+ state: 'success' as const,
+ presentation: { expects: 'none' as const },
+ expires_at: '2099-01-01T00:00:00Z',
+ };
+ vi.spyOn(modelsApi, 'reauthSource').mockResolvedValue(flow);
+ vi.spyOn(modelsApi, 'getOAuthStatus').mockResolvedValue({ flow, created: null, repaired });
+ vi.spyOn(modelsApi, 'cancelOAuth').mockResolvedValue(undefined);
+ };
+
+ // The toast is the whole report of a clean repair; a success panel held open on
+ // a timer after it only makes the person wait to be let go.
+ it('closes a clean repair as soon as it lands', async () => {
+ finishedReauth({ source: subscription(), recovered: true, interrupted_pairs: [] });
+ const onClose = vi.fn();
+ renderDialog({ reauth: subscription(), onClose });
+
+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1), { timeout: 500 });
+ });
+
+ it('keeps a repair that stranded models on screen to be read', async () => {
+ finishedReauth({
+ source: subscription(),
+ recovered: true,
+ interrupted_pairs: [{ backend: 'claude', model_id: 'claude-opus-5', agents: [] }],
+ });
+ const onClose = vi.fn();
+ renderDialog({ reauth: subscription(), onClose });
+
+ expect(await screen.findByText(/claude-opus-5/)).toBeTruthy();
+ expect(onClose).not.toHaveBeenCalled();
+ });
+});
+
describe('OAuth failure class behavior', () => {
it('keeps a held flow when its timeout reread is inconclusive', async () => {
vi.useFakeTimers();
diff --git a/ui/src/components/settings/models/OAuthConnectDialog.tsx b/ui/src/components/settings/models/OAuthConnectDialog.tsx
index 5b9ba5d29..7f6238b0a 100644
--- a/ui/src/components/settings/models/OAuthConnectDialog.tsx
+++ b/ui/src/components/settings/models/OAuthConnectDialog.tsx
@@ -24,7 +24,6 @@ import { cn } from '@/lib/utils';
import { useToast } from '@/context/ToastContext';
import type { TranslationKey } from '@/i18n/types';
import { OAuthDeviceCodeRow, OAuthLinkRow, OAuthSubmitRow } from '../oauth/OAuthFlowParts';
-import { AdoptionNote } from './AdoptionNote';
import {
classifyOAuthFailure,
createFlowAuthority,
@@ -45,7 +44,7 @@ import {
preopenProviderTab,
takeProviderTabForNavigation,
} from './providerTab';
-import { REPAIR_LINE_KEY, REPAIR_TOAST, repairOutcome, repairSettles, type RepairOutcome } from './repair';
+import { REPAIR_TOAST, repairOutcome, repairSettles, type RepairOutcome } from './repair';
import {
NATIVE_SUBSCRIPTION_EXISTS_FAILURE,
PASTE_REJECTED_KEY,
@@ -121,18 +120,8 @@ export const OAuthConnectDialog: React.FC<{
);
const [startAttempt, setStartAttempt] = React.useState(0);
const [startFailureCode, setStartFailureCode] = React.useState<string | null>(null);
- // Which Agents took the new subscription in, frozen at commit (api.md). Same
- // note as the API-key dialog: connecting a credential is not the same as
- // putting it into service, and an Agent with no accepted match is absent.
- //
- // `null` means the terminal response did not report a creation — which is not
- // 「没有 Agent 采用」 and must not be rendered as it.
- //
- // The whole tail rather than the adopter list alone, held as one value: the note
- // reads both halves, and two states can hold one half of an older arrival.
- const [adoption, setAdoption] = React.useState<Adoption | null>(null);
- // The reauth counterpart of `adoption`, read through the same owner the key
- // replacement uses so 「did that fix it?」 has one answer on the page.
+ // What a finished reauth says about the source it repaired, read through the
+ // same owner the key replacement uses so 「did that fix it?」 has one answer.
const [repair, setRepair] = React.useState<RepairOutcome | null>(null);
// What a FAILED reauth stranded on its way down. Not the same thing as
// `repair`'s gap report: that one describes a write that landed, this one
@@ -146,7 +135,6 @@ export const OAuthConnectDialog: React.FC<{
// terminal side effects.
const flowAuthorityRef = React.useRef<FlowAuthority | null>(null);
const settleRef = React.useRef<((result: OAuthResult) => void) | null>(null);
- const successTimer = React.useRef<number | null>(null);
// Mirrored for the flow effect, which is built once per attempt and would
// otherwise read this from the render that built it — i.e. always `false`.
const submittingRef = React.useRef(false);
@@ -341,19 +329,16 @@ export const OAuthConnectDialog: React.FC<{
t(toast?.key ?? 'settings.models.oauth.status.success') as string,
toast?.tone ?? 'success',
);
- // Same shape as the adoption auto-close below, on the same footing now that
- // both halves are server facts: 「nothing was stranded」 is a field the
- // server sends, so a clean repair may dismiss itself while a gap report
- // stays on screen to be read. An absent tail says nothing to read either,
- // so it closes too.
- if (!verdict || repairSettles(verdict))
- successTimer.current = window.setTimeout(() => onCloseRef.current(), 1400);
+ // The toast is the whole report of a clean repair, so the journey ends
+ // with it: 「nothing was stranded」 is a field the server sends, and only a
+ // verdict that leaves something to read keeps the dialog on screen. An
+ // absent tail says nothing to read either, so it closes too.
+ if (!verdict || repairSettles(verdict)) onCloseRef.current();
} else if (step.action === 'succeed') {
// The Source already exists. The status/submit call that first reports
// success materializes it server-side and consumes the flow binding doing
// it — there is nothing left to finalize, and a POST /sources afterwards
// is refused as `flow_not_found` on a connect that in fact succeeded.
- setAdoption(created ? { added_to: created.added_to, adopted_by: created.adopted_by } : null);
showToast(t('settings.models.oauth.status.success') as string, 'success');
if (created) onConnectedRef.current(created.source, created);
}
@@ -485,7 +470,6 @@ export const OAuthConnectDialog: React.FC<{
setCode('');
setPasteError(null);
setSubmitting(false);
- setAdoption(null);
setRepair(null);
setStranded([]);
void (async () => {
@@ -580,7 +564,6 @@ export const OAuthConnectDialog: React.FC<{
cancelled = true;
stop();
settleRef.current = null;
- if (successTimer.current !== null) window.clearTimeout(successTimer.current);
transition({ kind: 'reset' });
// Read ownership BEFORE releasing it. React runs this cleanup ahead of the
// next effect body, so at this instant the ref is still ours whenever it is
@@ -957,11 +940,9 @@ export const OAuthConnectDialog: React.FC<{
)}
{success && isReauth ? (
- // A repair reports on the source it repaired, not on a new connection:
- // 「已恢复可用」 when the login cleared the blocker, 「已更新」 when there
- // was nothing to clear, 「仍然不可用」 when the flow finished and the
- // source came back stopped anyway, and the stranded pairs when
- // something is still without a source. Only the last stays on screen.
+ // A repair reports on the source it repaired, not on a new connection.
+ // A clean one closed on its toast; only a verdict that leaves something
+ // to read stays: the stranded pairs, or a source that came back stopped.
repair?.kind === 'gaps' ? (
<div className="flex flex-col gap-2 rounded-lg border border-gold/40 bg-gold/[0.08] px-3.5 py-3">
<span className="model-hub-ink-gold text-[12.5px] font-semibold leading-relaxed">
@@ -979,26 +960,13 @@ export const OAuthConnectDialog: React.FC<{
<TriangleAlert className="size-4 shrink-0" />
{t('settings.models.repair.unresolved')}
</div>
- ) : (
- <div className="model-hub-ink-mint flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium">
- <CheckCircle2 className="size-4 shrink-0" />
- {repair
- ? t(REPAIR_LINE_KEY[repair.kind])
- : t('settings.models.oauth.connected')}
- </div>
- )
+ ) : null
) : success ? (
- <div className="flex flex-col gap-2">
- <div className="model-hub-ink-mint flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium">
- <CheckCircle2 className="size-4 shrink-0" />
- {t('settings.models.oauth.connected')}
- </div>
- {/* Only when the response actually reported the creation: an absent
- `adopted_by` is not an empty one, and 「没有 Agent 采用」 would be
- a claim this response never made. The two halves come off ONE
- value, so the note can never read a skip list from one arrival
- against an adopter list from another. */}
- <AdoptionNote addedTo={adoption?.added_to ?? null} adoptedBy={adoption?.adopted_by ?? null} />
+ // A create that handed its source over has already closed into it; this
+ // line is for a success whose response reported no source to hand over.
+ <div className="model-hub-ink-mint flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium">
+ <CheckCircle2 className="size-4 shrink-0" />
+ {t('settings.models.oauth.connected')}
</div>
) : (
active && (
diff --git a/ui/src/components/settings/models/RouteChainDialog.test.tsx b/ui/src/components/settings/models/RouteChainDialog.test.tsx
index 14d9bee99..6365d3783 100644
--- a/ui/src/components/settings/models/RouteChainDialog.test.tsx
+++ b/ui/src/components/settings/models/RouteChainDialog.test.tsx
@@ -266,8 +266,7 @@ describe("RouteChainDialog", () => {
await user.click(screen.getByRole('menuitem', { name: 'Edit model' }));
await user.click(head.getByRole('button', { name: 'Model actions' }));
await user.click(screen.getByRole('menuitem', { name: 'Remove model' }));
- const shown = [{ source_id: 'src_a', model_id: 'claude-opus-5' }, { source_id: 'src_b', model_id: 'opus-5' }];
- expect(manage.mock.calls).toEqual([['edit', shown], ['remove', shown]]);
+ expect(manage.mock.calls).toEqual([['edit'], ['remove']]);
// An unsaved draft would be dropped by leaving, so the handoff steps aside.
await user.click(screen.getAllByRole('button', { name: 'Remove hop' })[0]);
expect(head.queryByRole('button', { name: 'Model actions' })).toBeNull();
@@ -500,7 +499,7 @@ describe("RouteChainDialog", () => {
expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(true);
});
- it('clears to no-key Unconfigured, confirms the exact DELETE guard and closes after saving', async () => {
+ it('clears to no-key Unconfigured, confirms the exact DELETE guard once 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 };
@@ -520,14 +519,16 @@ describe("RouteChainDialog", () => {
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' }));
+ const guard = within(await screen.findByRole('dialog', { name: 'Save the route chain for opus-5' }));
+ expect(guard.getByText('Agents pinned to it: writer')).toBeTruthy();
+ await user.click(guard.getByRole('button', { name: 'Save anyway' }));
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] }],
]);
expect(committed).toHaveBeenCalledWith(mutation(unconfigured, { removed_hops: [hop], interrupted: [gap] }));
- expect(screen.getByText('Agents pinned to it: writer')).toBeTruthy();
+ expect(screen.queryByRole('dialog', { name: 'Save the route chain for opus-5' })).toBeNull();
expect(put).not.toHaveBeenCalled();
});
@@ -639,8 +640,7 @@ describe("RouteChainDialog", () => {
await waitFor(() => expect((screen.getByRole('button', { name: 'Retry' }) as HTMLButtonElement).disabled).toBe(false));
expect(committed).not.toHaveBeenCalled();
await user.click(screen.getByRole('button', { name: 'Retry' }));
- await within(document.querySelector<HTMLElement>('.model-hub-route-foot')!).findByRole('button', { name: 'Done' });
- expect(committed).toHaveBeenCalledWith({ chain: unconfigured, removed_hops: null, interrupted: null });
+ await waitFor(() => expect(committed).toHaveBeenCalledWith({ chain: unconfigured, removed_hops: null, interrupted: null }));
expect(restore).toHaveBeenCalledOnce();
expect(put).not.toHaveBeenCalled();
});
@@ -883,7 +883,7 @@ describe("RouteChainDialog", () => {
await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
});
- it("echoes the exact refusal plan on a forced confirmation", async () => {
+ it("asks once in its own modal over the draft, then echoes the exact refusal plan", async () => {
const user = userEvent.setup();
const gap = {
backend: "claude" as const,
@@ -897,52 +897,82 @@ describe("RouteChainDialog", () => {
model_id: "claude-opus-5",
position: 1,
};
+ const refusal = () =>
+ new ApiCallError("source_last_supplier", undefined, true, [gap], [], [hop]);
const put = vi
.spyOn(modelsApi, "putAgentChain")
- .mockRejectedValueOnce(
- new ApiCallError(
- "source_last_supplier",
- undefined,
- true,
- [gap],
- [],
- [hop],
- ),
- )
+ .mockRejectedValueOnce(refusal())
+ .mockRejectedValueOnce(refusal())
.mockResolvedValueOnce(mutation());
- 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" })[1]);
await user.click(screen.getByRole("button", { name: "Save" }));
- expect(
- await screen.findByRole("button", { name: "Save anyway" }),
- ).toBeTruthy();
- expect(screen.getByText("Save the route chain for opus-5")).toBeTruthy();
- expect(screen.getByText("Hops that will be removed")).toBeTruthy();
- expect(screen.getByText("1 hop")).toBeTruthy();
- expect(
- screen.getByText((_, element) =>
- element?.classList.contains("model-hub-guard-hop") === true &&
- element.textContent?.includes("Order #1") === true,
- ),
- ).toBeTruthy();
- expect(
- screen.getByText("Some models will be left with no usable source."),
- ).toBeTruthy();
- expect(
- screen.queryByText("Models that will be left with no source"),
- ).toBeNull();
- await user.click(screen.getByRole("button", { name: "Save anyway" }));
+ const dialog = await screen.findByRole("dialog", { name: "Save the route chain for opus-5" });
+ const guard = within(dialog);
+ expect(guard.getByText("Hops that will be removed")).toBeTruthy();
+ expect(guard.getByText("1 hop")).toBeTruthy();
+ // The hop names the supplier it went through, in the page's own mapping copy.
+ expect(guard.getByText("API key → claude-opus-5 · Order #1")).toBeTruthy();
+ expect(guard.getByText("Models that will be left with no source")).toBeTruthy();
+ expect(guard.getByText("Agents pinned to it: writer")).toBeTruthy();
+ expect(guard.getByText("Some models will be left with no usable source.")).toBeTruthy();
+
+ // Cancel returns to the chain exactly as it was left, still saveable.
+ await user.click(guard.getAllByRole("button", { name: "Cancel" }).at(-1)!);
+ expect(screen.queryByRole("dialog", { name: "Save the route chain for opus-5" })).toBeNull();
+ expect(screen.getAllByRole("button", { name: "Remove hop" })).toHaveLength(1);
+ expect(put).toHaveBeenCalledTimes(1);
- await waitFor(() =>
- expect(put).toHaveBeenLastCalledWith("claude", "opus-5", {
- hops: [{ source_id: "src_a", model_id: "claude-opus-5" }],
- force: true,
- would_remove_hops: [hop],
- would_interrupt: [gap],
- }),
+ await user.click(screen.getByRole("button", { name: "Save" }));
+ await user.click(
+ within(await screen.findByRole("dialog", { name: "Save the route chain for opus-5" }))
+ .getByRole("button", { name: "Save anyway" }),
+ );
+
+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
+ expect(put).toHaveBeenLastCalledWith("claude", "opus-5", {
+ hops: [{ source_id: "src_a", model_id: "claude-opus-5" }],
+ force: true,
+ would_remove_hops: [hop],
+ would_interrupt: [gap],
+ });
+ });
+
+ it("resends a confirmed save with the recomputed plan instead of asking again", async () => {
+ const user = userEvent.setup();
+ const gap = { backend: "claude" as const, model_id: "opus-5", agents: ["writer"] };
+ const firstHop = {
+ backend: "claude" as const,
+ menu_model: "opus-5",
+ source_id: "src_a",
+ model_id: "claude-opus-5",
+ position: 1,
+ };
+ const nextHop = { ...firstHop, position: 2 };
+ const put = vi
+ .spyOn(modelsApi, "putAgentChain")
+ .mockRejectedValueOnce(new ApiCallError("source_last_supplier", undefined, true, [gap], [], [firstHop]))
+ .mockRejectedValueOnce(new ApiCallError("source_last_supplier", undefined, true, [gap], [], [nextHop]))
+ .mockResolvedValueOnce(mutation());
+ const onClose = vi.fn();
+ renderDialog(vi.fn(), onClose);
+ await screen.findAllByRole("button", { name: "Remove hop" });
+
+ await user.click(screen.getAllByRole("button", { name: "Remove hop" })[1]);
+ await user.click(screen.getByRole("button", { name: "Save" }));
+ await user.click(
+ within(await screen.findByRole("dialog", { name: "Save the route chain for opus-5" }))
+ .getByRole("button", { name: "Save anyway" }),
);
+
+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
+ expect(put).toHaveBeenCalledTimes(3);
+ expect(put.mock.calls[1][2]).toMatchObject({ force: true, would_remove_hops: [firstHop] });
+ expect(put.mock.calls[2][2]).toMatchObject({ force: true, would_remove_hops: [nextHop] });
+ expect(screen.queryByRole("dialog", { name: "Save the route chain for opus-5" })).toBeNull();
});
it("re-reads the exact chain after an unconfirmed write and never retries the PUT", async () => {
diff --git a/ui/src/components/settings/models/RouteChainDialog.tsx b/ui/src/components/settings/models/RouteChainDialog.tsx
index 527780658..4c3927288 100644
--- a/ui/src/components/settings/models/RouteChainDialog.tsx
+++ b/ui/src/components/settings/models/RouteChainDialog.tsx
@@ -4,7 +4,6 @@ import * as DialogPrimitive from "@radix-ui/react-dialog";
import {
ChevronRight,
GripVertical,
- Info,
ListOrdered,
LoaderCircle,
MoreHorizontal,
@@ -22,13 +21,15 @@ import { ResponsiveMenu } from "@/components/ui/responsive-menu";
import { SegmentedRadio } from "@/components/ui/segmented";
import { cn } from "@/lib/utils";
import { useIsMobile } from "@/lib/useIsMobile";
-import { GuardGapList } from "./GuardGapList";
+import { GuardDialog } from "./GuardDialog";
+import { GuardImpact, type GuardPlan } from "./GuardImpact";
+import { confirmGuardPlan, guardedFailure, sendAgreed } from "./guardedWrite";
import { RouteCandidatePopover } from "./RouteCandidatePopover";
import { RecordedTurnBadge, RecordedTurnDetails, RouteRecordedTurn } from './RouteRecordedTurn';
import { recordedOn, useRecordedTurn } from './recordedTurn';
import { eligibleSources } from "./eligibility";
import { equalHopIdentity, hopBelongsToSource } from "./hopIdentity";
-import { apiFailure, modelsApi, type GuardConfirmation } from "./modelsApi";
+import { apiFailure, modelsApi } from "./modelsApi";
import type { ModelChainRead } from "./modelRows";
import {
routeCandidates,
@@ -57,10 +58,6 @@ const sourceName = (sources: Source[], sourceId: string): string =>
const MENU_ITEM = "model-hub-route-menu-item flex w-full items-center rounded-md text-left font-semibold hover:bg-surface-2";
type RouteMode = "follow" | "custom";
-type GuardState = {
- hops: RouteHopRef[];
- gaps: NonNullable<GuardConfirmation["would_interrupt"]>;
-};
export type RouteReport = {
chain: AgentChainMutation["chain"];
removed_hops: RouteHopRef[] | null;
@@ -71,11 +68,8 @@ type Phase =
| "ready"
| "unread"
| "saving"
- | "guard"
| "rejected"
| "unknown"
- | "impact"
- | "refreshing"
| "reconciling"
| "direct";
type ReconcileMember = "agents" | "sources" | "chain";
@@ -91,11 +85,6 @@ export type RouteCollectionObservation<T> = {
value: T;
install: () => void;
};
-export type RouteCommitReconciliation = {
- pending: boolean;
- failed: boolean;
- retry: () => void;
-};
export type SuspendedRouteAttempt = {
backend: AgentSupply["backend"];
modelId: string;
@@ -109,7 +98,6 @@ export const RouteChainDialog: React.FC<{
sources: Source[];
onClose: () => void;
onCommitted?: (result: RouteReport) => void;
- commitReconciliation?: RouteCommitReconciliation | null;
onObserved?: (chain: AgentChainMutation["chain"]) => void;
onOpenDefaults?: () => void;
covered?: boolean;
@@ -122,13 +110,12 @@ export const RouteChainDialog: React.FC<{
/** Hand this model over to the catalog dialog, which is the one writer of the
* model list — the Route dialog only names the model and the intent, so the
* edit and removal protocols (guard, refusal, save) stay in one place. */
- onManageModel?: (action: "edit" | "remove", route: RouteHop[]) => void;
+ onManageModel?: (action: "edit" | "remove") => void;
}> = ({
selection,
sources,
onClose,
onCommitted,
- commitReconciliation,
onObserved,
onOpenDefaults,
covered = false,
@@ -159,11 +146,10 @@ export const RouteChainDialog: React.FC<{
const [chain, setChain] = React.useState<AgentChainMutation["chain"] | null>(
null,
);
- const [guard, setGuard] = React.useState<GuardState | null>(null);
+ const [guard, setGuard] = React.useState<GuardPlan | null>(null);
const [submitted, setSubmitted] = React.useState<RouteHop[] | null>(null);
const [submittedStage, setSubmittedStage] =
React.useState<SuspendedRouteAttempt["stage"]>("initial");
- const [report, setReport] = React.useState<RouteReport | null>(null);
const [reconcileFailed, setReconcileFailed] = React.useState(false);
const [failedMembers, setFailedMembers] = React.useState<
ReadonlySet<ReconcileMember>
@@ -192,7 +178,6 @@ export const RouteChainDialog: React.FC<{
const saveButtonRef = React.useRef<HTMLButtonElement | null>(null);
const savingStatusRef = React.useRef<HTMLSpanElement | null>(null);
const retryButtonRef = React.useRef<HTMLButtonElement | null>(null);
- const doneButtonRef = React.useRef<HTMLButtonElement | null>(null);
const openedIdentity = React.useRef<string | null>(null);
const invalidSignature = React.useRef("");
const generation = React.useRef(0);
@@ -343,7 +328,6 @@ export const RouteChainDialog: React.FC<{
setGuard(null);
setSubmitted(null);
setSubmittedStage("initial");
- setReport(null);
setReconcileFailed(false);
setFailedMembers(new Set());
setUnknownObservation("none");
@@ -357,18 +341,11 @@ export const RouteChainDialog: React.FC<{
}, [advanceInteraction, readChain, selection]);
React.useEffect(() => {
- if (
- !selection ||
- selection.available !== false ||
- phase === "impact" ||
- phase === "refreshing"
- ) {
- return;
- }
+ if (!selection || selection.available !== false) return;
generation.current += 1;
previewGeneration.current += 1;
onClose();
- }, [onClose, phase, selection]);
+ }, [onClose, selection]);
React.useEffect(() => {
const signature = valid.invalidIndexes.join(",");
@@ -388,25 +365,10 @@ export const RouteChainDialog: React.FC<{
});
}, [advanceInteraction, phase, valid.invalidIndexes]);
- React.useEffect(() => {
- if (!report || !commitReconciliation) return;
- setReconcileFailed(commitReconciliation.failed);
- setPhase(commitReconciliation.pending ? "refreshing" : "impact");
- if (commitReconciliation.failed) focusAfterRender(retryButtonRef);
- }, [commitReconciliation, report]);
-
const close = () => {
- if (phase === "guard") {
- setGuard(null);
- setPhase("ready");
- focusAfterRender(saveButtonRef);
- return;
- }
if (phase !== "saving") {
previewGeneration.current += 1;
- if (phase !== "impact" && phase !== "refreshing") {
- generation.current += 1;
- }
+ generation.current += 1;
onClose();
}
};
@@ -423,8 +385,7 @@ export const RouteChainDialog: React.FC<{
focusAfterRender(cancelButtonRef);
};
const remove = (index: number) => {
- if (phase === "saving" || phase === "impact" || phase === "refreshing")
- return;
+ if (phase === "saving") return;
if (draft.length === 1) {
followDefaults();
focusAfterFollow();
@@ -539,21 +500,17 @@ export const RouteChainDialog: React.FC<{
setPreviewPending(false);
setPreviewFailed(false);
restoreUndo.current = null;
- setReport(nextReport);
+ setGuard(null);
setOrigin(committedHops);
advanceInteraction({ type: "reset", draft: committedHops });
setUnknownObservation("none");
setUnknownSourceCurrent(false);
onCommitted?.(nextReport);
- setPhase(
- nextReport.removed_hops?.length || nextReport.interrupted?.length
- ? "impact"
- : "refreshing",
- );
+ setPhase("ready");
onClose();
};
- const submit = async (confirmation?: GuardState) => {
+ const submit = async (confirmation?: GuardPlan) => {
if (!selection || !agent || phase === "saving" || covered || previewPending || unresolvedPreview || (!manualDraft && previewFailed) || (manualDraft && !valid.valid) || !dirty)
return;
const hops = (confirmation ? (submitted ?? draft) : draft).map((hop) => ({
@@ -563,19 +520,16 @@ export const RouteChainDialog: React.FC<{
if (!confirmation) submittedOverride.current = manualDraft ? { hops } : null;
setSubmittedStage(confirmation ? "confirmed" : "initial");
setPhase("saving");
- setGuard(null);
- requestAnimationFrame(() => savingStatusRef.current?.focus());
+ // A confirmed save keeps its question mounted, busy, until the answer lands;
+ // an initial one shows the progress status in the dialog itself.
+ if (!confirmation) requestAnimationFrame(() => savingStatusRef.current?.focus());
try {
- const guardFields = confirmation
- ? {
- force: true as const,
- would_remove_hops: confirmation.hops,
- would_interrupt: confirmation.gaps,
- }
- : {};
- const result = submittedOverride.current === null
- ? await modelsApi.restoreAgentChain(agent.backend, modelId, confirmation ? guardFields as GuardConfirmation : undefined)
- : await modelsApi.putAgentChain(agent.backend, modelId, { hops, ...guardFields });
+ const result = await sendAgreed(confirmation !== undefined, confirmation ?? null, (plan) => {
+ const guardFields = plan ? confirmGuardPlan(plan) : undefined;
+ return submittedOverride.current === null
+ ? modelsApi.restoreAgentChain(agent.backend, modelId, guardFields)
+ : modelsApi.putAgentChain(agent.backend, modelId, { hops, ...guardFields });
+ });
beginCommitted(
{
chain: result.chain,
@@ -587,6 +541,7 @@ export const RouteChainDialog: React.FC<{
} catch (error) {
const failure = apiFailure(error);
if (failure?.code === "direct_mode") {
+ setGuard(null);
setPhase("direct");
onDirectMode?.(
{
@@ -600,18 +555,17 @@ export const RouteChainDialog: React.FC<{
);
return;
}
- if (
- (failure?.code === "source_last_supplier" || failure?.code === 'source_in_route_chain') &&
- (failure.wouldInterrupt.length > 0 || failure.wouldRemoveHops.length > 0)
- ) {
- setGuard({
- hops: failure.wouldRemoveHops,
- gaps: failure.wouldInterrupt,
- });
- setPhase("guard");
- focusAfterRender(cancelButtonRef);
+ const refusal = failure?.code === "source_last_supplier" || failure?.code === "source_in_route_chain"
+ ? guardedFailure(error)
+ : null;
+ // Only an initial save reaches here with a plan: a confirmed one resends
+ // the recomputed plan itself, so the question is asked once per save.
+ if (refusal && !confirmation) {
+ setGuard(refusal);
+ setPhase("ready");
return;
}
+ setGuard(null);
const nextPhase = failure?.serverNamed ? "rejected" : "unknown";
setPhase(nextPhase);
focusAfterRender(retryButtonRef);
@@ -765,11 +719,6 @@ export const RouteChainDialog: React.FC<{
}
};
- const retryCommittedRead = () => {
- if (!report || phase !== "impact" || !commitReconciliation?.failed) return;
- doneButtonRef.current?.focus();
- commitReconciliation.retry();
- };
const addCandidate = (candidate: RouteCandidate) => {
const next = advanceInteraction({ type: "append", hop: candidate.hop });
requestAnimationFrame(() => gripRefs.current[next.focusIndex]?.focus());
@@ -861,7 +810,7 @@ export const RouteChainDialog: React.FC<{
// Follow-default rows are the inherited route, read only; editing starts from
// the Custom switch, so no row gesture can pin a route by accident.
const editable = manualDraft;
- const actionsDisabled = phase === "saving" || phase === "impact" || phase === "refreshing";
+ const actionsDisabled = phase === "saving";
const recordedHopIndex = recordedTurn.record
? draft.findIndex((hop) => recordedOn(recordedTurn.record, hop))
: -1;
@@ -1092,6 +1041,10 @@ export const RouteChainDialog: React.FC<{
};
if (!selection) return null;
+ // A confirmed save answers inside its own question, so the chain it is about
+ // stays on screen behind it rather than turning into a progress line.
+ const savingInline = phase === "saving" && guard === null;
+ const sourceNames = Object.fromEntries(sources.map((source) => [source.id, source.display_name]));
const body =
phase === "loading" ? (
<div className="model-hub-route-body flex flex-1 items-center justify-center gap-2 text-muted">
@@ -1116,45 +1069,13 @@ export const RouteChainDialog: React.FC<{
<div className="model-hub-route-body flex flex-1 items-center justify-center text-muted">
{t("settings.models.routeDialog.fail.read")}
</div>
- ) : phase === "saving" ? (
+ ) : savingInline ? (
<div className="model-hub-route-body flex flex-1 items-center justify-center gap-2 text-muted">
<LoaderCircle className="size-4 animate-spin" />
<span ref={savingStatusRef} role="status" tabIndex={-1}>
{t("settings.models.routeDialog.saving")}
</span>
</div>
- ) : phase === "guard" && guard ? (
- <div className="model-hub-route-body flex flex-1 flex-col gap-4">
- <div className="model-hub-guard-label">
- <p>{t("settings.models.guard.label")}</p>
- <span>{t("settings.models.guard.count", { count: guard.hops.length })}</span>
- </div>
- <ul className="model-hub-guard-list">
- {guard.hops.map((hop) => (
- <li
- key={`${hop.backend}:${hop.menu_model}:${hop.position}`}
- className="model-hub-guard-hop"
- >
- <span className="min-w-0 flex-1">
- <strong>
- {t(`settings.models.backends.${hop.backend}`, {
- defaultValue: hop.backend,
- })} · {hop.menu_model}
- </strong>
- <span>
- {hop.model_id} · {t("settings.models.guard.hop.position", {
- n: hop.position,
- })}
- </span>
- </span>
- </li>
- ))}
- </ul>
- <p className="model-hub-guard-hint text-destructive-ink">
- <Info aria-hidden="true" />
- {t("settings.models.guard.hint.interrupt")}
- </p>
- </div>
) : phase === "rejected" ? (
<div className="model-hub-route-body flex flex-1 flex-col items-center justify-center gap-3 text-muted">
<p>{t("settings.models.routeDialog.fail.save")}</p>
@@ -1188,61 +1109,6 @@ export const RouteChainDialog: React.FC<{
{t("settings.models.routeDialog.retry")}
</Button>
</div>
- ) : phase === "impact" || phase === "refreshing" ? (
- <div className="model-hub-route-body flex flex-1 flex-col gap-4">
- <h3 className="model-hub-route-label font-bold">
- {t("settings.models.routeDialog.impact.title")}
- </h3>
- {report?.removed_hops?.length ? (
- <ul className="model-hub-guard-list">
- {report.removed_hops.map((hop) => (
- <li
- key={`${hop.backend}:${hop.menu_model}:${hop.position}:${hop.source_id}:${hop.model_id}`}
- className="model-hub-guard-hop"
- >
- <span className="min-w-0 flex-1">
- <strong>
- {t(`settings.models.backends.${hop.backend}`, {
- defaultValue: hop.backend,
- })} · {hop.menu_model}
- </strong>
- <span>
- {hop.model_id} · {t("settings.models.guard.hop.position", {
- n: hop.position,
- })}
- </span>
- </span>
- </li>
- ))}
- </ul>
- ) : null}
- <GuardGapList gaps={report?.interrupted ?? []} />
- {Boolean(report?.removed_hops?.length || report?.interrupted?.length) && (
- <p className="text-xs text-muted">
- {t("settings.models.routeDialog.impact.detail")}
- </p>
- )}
- {phase === "refreshing" && (
- <p className="text-xs text-muted">
- {t("settings.models.routeDialog.refreshing")}
- </p>
- )}
- {reconcileFailed && (
- <p className="text-xs text-muted">
- {t("settings.models.routeDialog.impact.refreshFail")}
- </p>
- )}
- {reconcileFailed && commitReconciliation?.failed && (
- <Button
- ref={retryButtonRef}
- type="button"
- disabled={phase === "refreshing"}
- onClick={() => void retryCommittedRead()}
- >
- {t("settings.models.routeDialog.retry")}
- </Button>
- )}
- </div>
) : (
<div className="model-hub-route-body flex flex-col">
<div className="model-hub-route-mode flex flex-col">
@@ -1347,12 +1213,7 @@ export const RouteChainDialog: React.FC<{
<DialogPrimitive.Portal>
<DialogPrimitive.Overlay className="model-hub-route-overlay fixed inset-0 z-50" />
<DialogPrimitive.Content
- aria-busy={
- phase === "saving" ||
- previewPending ||
- phase === "refreshing" ||
- phase === "reconciling"
- }
+ aria-busy={phase === "saving" || previewPending || phase === "reconciling"}
className="model-hub-route-dialog fixed left-1/2 top-1/2 z-50 flex -translate-x-1/2 -translate-y-1/2 flex-col gap-0 overflow-hidden border border-border-strong bg-surface p-0"
onOpenAutoFocus={(event) => {
event.preventDefault();
@@ -1368,12 +1229,7 @@ export const RouteChainDialog: React.FC<{
<header className="model-hub-route-head flex flex-col border-b border-border">
<span className="flex items-center justify-between gap-3">
<DialogPrimitive.Title className="model-hub-route-title font-bold text-foreground">
- {t(
- phase === "guard"
- ? "settings.models.guard.title.saveRoute"
- : "settings.models.routeDialog.title",
- { menuModel: modelId },
- )}
+ {t("settings.models.routeDialog.title", { menuModel: modelId })}
</DialogPrimitive.Title>
<span className="model-hub-route-head-actions flex shrink-0 items-center gap-1.5">
{manageableModel && (
@@ -1398,7 +1254,7 @@ export const RouteChainDialog: React.FC<{
className={MENU_ITEM}
onClick={() => {
setHeadMenu(false);
- onManageModel?.("edit", draft);
+ onManageModel?.("edit");
}}
>
<Pencil aria-hidden="true" />
@@ -1410,7 +1266,7 @@ export const RouteChainDialog: React.FC<{
className={cn(MENU_ITEM, "text-destructive-ink hover:bg-destructive/[0.08]")}
onClick={() => {
setHeadMenu(false);
- onManageModel?.("remove", draft);
+ onManageModel?.("remove");
}}
>
<Trash2 aria-hidden="true" />
@@ -1421,15 +1277,7 @@ export const RouteChainDialog: React.FC<{
<DialogPrimitive.Close
ref={closeButtonRef}
disabled={phase === "saving"}
- aria-label={
- t(
- phase === "guard"
- ? "settings.models.guard.cancel"
- : phase === "impact" || phase === "refreshing"
- ? "settings.models.routeDialog.impact.done"
- : "settings.models.routing.close",
- ) as string
- }
+ aria-label={t("settings.models.routing.close") as string}
className="model-hub-route-close grid shrink-0 place-items-center"
>
<X aria-hidden="true" />
@@ -1437,48 +1285,27 @@ export const RouteChainDialog: React.FC<{
</span>
</span>
<DialogPrimitive.Description className="model-hub-route-subtitle font-mono text-muted">
- {phase === "guard"
- ? t("settings.models.guard.subtitle.saveRoute")
- : backend}
+ {backend}
</DialogPrimitive.Description>
</header>
{body}
<RecordedTurnDetails record={recordedTurn.record} open={recordDetails} onOpenChange={setRecordDetails} />
+ <GuardDialog
+ open={guard !== null}
+ title={t("settings.models.guard.title.saveRoute", { menuModel: modelId })}
+ subtitle={t("settings.models.guard.subtitle.saveRoute")}
+ confirmLabel={t("settings.models.guard.confirm.saveRoute")}
+ busy={phase === "saving"}
+ onCancel={() => {
+ setGuard(null);
+ focusAfterRender(saveButtonRef);
+ }}
+ onConfirm={() => { if (guard) void submit(guard); }}
+ >
+ {guard && <GuardImpact hops={guard.hops} gaps={guard.gaps} sourceNames={sourceNames} />}
+ </GuardDialog>
<footer className="model-hub-route-foot model-hub-fill-05 flex items-center justify-end gap-2 border-t border-border">
- {phase === "impact" || phase === "refreshing" ? (
- <Button
- ref={doneButtonRef}
- type="button"
- className="model-hub-dialog-action"
- onClick={close}
- >
- {t("settings.models.routeDialog.impact.done")}
- </Button>
- ) : phase === "guard" && guard ? (
- <>
- <Button
- ref={cancelButtonRef}
- type="button"
- variant="outline"
- className="model-hub-dialog-action"
- onClick={() => {
- setGuard(null);
- setPhase("ready");
- requestAnimationFrame(() => saveButtonRef.current?.focus());
- }}
- >
- {t("settings.models.guard.cancel")}
- </Button>
- <Button
- ref={saveButtonRef}
- type="button"
- className="model-hub-dialog-action"
- onClick={() => void submit(guard)}
- >
- {t("settings.models.guard.confirm.saveRoute")}
- </Button>
- </>
- ) : phase === "saving" ? (
+ {savingInline ? (
<span role="status" className="text-xs text-muted">
{t("settings.models.routeDialog.saving")}
</span>
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index 7421b8f47..e2f742595 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -503,7 +503,7 @@ describe('SettingsModelsPage surface branches', () => {
expect((callback.match(/void refresh\(\)/g) ?? []).length).toBe(2);
});
- it('issues exactly one surface refresh for a successful subscription create', async () => {
+ it('reads the surface once for a successful subscription create, plus the close\'s own reread', async () => {
const created = {
...nativeSubscription,
id: 'src_created_subscription',
@@ -537,12 +537,15 @@ describe('SettingsModelsPage surface branches', () => {
await user.click(screen.getByRole('button', { name: /Sign in|去登录/i }));
await waitFor(() => expect(status).toHaveBeenCalledWith(terminal.flow_id));
+ // The sign-in hands straight over to the provider it created: its toast is the
+ // report, so there is no success panel to wait out first.
+ const detail = await screen.findByRole('dialog', { name: 'Created subscription' });
expect(screen.getAllByRole('dialog')).toHaveLength(1);
- expect(screen.queryByRole('dialog', { name: 'Created subscription' })).toBeNull();
- await waitFor(() => expect(listSources).toHaveBeenCalledTimes(refreshesBeforeCreate + 1));
- await act(async () => Promise.resolve());
- expect(listSources).toHaveBeenCalledTimes(refreshesBeforeCreate + 1);
- const detail = await screen.findByRole('dialog', { name: 'Created subscription' }, { timeout: 2500 });
+ // One read for the landing, with the flow's trailing stale-row notice folded
+ // into it, and the one every closed flow owes its rows after the cancel settles.
+ await waitFor(() => expect(listSources).toHaveBeenCalledTimes(refreshesBeforeCreate + 2));
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); });
+ expect(listSources).toHaveBeenCalledTimes(refreshesBeforeCreate + 2);
await user.click(within(detail).getByRole('button', { name: /Close provider details|关闭供应商详情/i }));
await waitFor(() => expect(document.activeElement).toBe(trigger));
});
@@ -2610,6 +2613,45 @@ describe('SettingsModelsPage quota region', () => {
// The finished sign-in closes its dialog; focus returns to the quota card's button, not the document.
await waitFor(() => expect(document.activeElement).toBe(trigger), { timeout: 4000 });
}, 12000);
+ it('returns focus to the quota tab when the re-read a clean re-login started removes its button', async () => {
+ const started = {
+ flow_id: 'flow_reauth',
+ intent: 'reauth' as const,
+ vendor: 'anthropic',
+ channel: 'native_cli' as const,
+ state: 'starting' as const,
+ presentation: { expects: 'none' as const },
+ };
+ vi.spyOn(modelsApi, 'reauthSource').mockResolvedValue(started);
+ vi.spyOn(modelsApi, 'getOAuthStatus').mockResolvedValue({ flow: { ...started, state: 'success' as const }, created: null, repaired: null });
+ renderPage([nativeSubscription]);
+ const expired = {
+ source_id: nativeSubscription.id, vendor: 'anthropic', display_name: nativeSubscription.display_name,
+ account_label: null, plan: null, fetched_at: null, state: 'auth_expired' as const,
+ error_key: 'models.quota.error.auth_expired', windows: [],
+ };
+ const read = vi.mocked(modelsApi.getQuota);
+ read.mockResolvedValue({ refresh_interval_seconds: 300, sources: [expired] });
+ await screen.findByText('Claude native login');
+ await openQuota();
+ const trigger = await screen.findByRole('button', { name: /^Sign in again$|^重新登录$/ });
+ await userEvent.click(trigger);
+ await userEvent.click(await screen.findByRole('button', { name: /^Start sign-in$|^开始登录$/i }));
+ // The new grant reads healthy, so the re-read lands without the button, and
+ // only after the dialog has already handed focus back to it.
+ const healthy = deferred<QuotaSummary>();
+ read.mockReturnValue(healthy.promise);
+ await waitFor(() => expect(document.activeElement).toBe(trigger), { timeout: 4000 });
+ await act(async () => healthy.resolve({
+ refresh_interval_seconds: 300,
+ sources: [{
+ ...expired, state: 'ok', error_key: undefined, fetched_at: new Date().toISOString(),
+ windows: [{ id: 'five_hour', kind: 'session', label: 'five_hour', used_pct: 40, window_seconds: 18_000, resets_at: new Date(Date.now() + 3_600_000).toISOString() }],
+ }],
+ }));
+ expect(screen.queryByRole('button', { name: /^Sign in again$|^重新登录$/ })).toBeNull();
+ expect(document.activeElement).toBe(screen.getByRole('tab', { name: /^Subscription quota$|^订阅额度$/ }));
+ }, 12000);
it('returns focus to the quota tab when a refresh removed the re-login button behind its confirmation', async () => {
renderPage([nativeSubscription]);
vi.mocked(modelsApi.getQuota).mockResolvedValue({
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index 38a139b20..ebe9b7b0f 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -19,7 +19,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, type SuspendedRouteAttempt } from './RouteChainDialog';
+import { RouteChainDialog, type RouteCollectionObservation, type RouteReport, type SuspendedRouteAttempt } from './RouteChainDialog';
import { routeChainMatchesAttempt } from './routeChainDraft';
import { SourceDetailPanel } from './SourceDetailPanel';
import { SourceOrderDrawer } from './SourceOrderDrawer';
@@ -440,7 +440,7 @@ export const SettingsModelsPage: React.FC = () => {
// the dialog's own subject. Separate from `subscriptionVendor` because the two
// journeys start from different surfaces — this one from the source detail,
// which replaces the overview that holds 添加订阅 — and only the create path
- // owns the success-landing timer and reconcile flag below.
+ // owns the success landing and reconcile flag below.
const [reauthSource, setReauthSource] = React.useState<Source | null>(null);
// A quota read can be the first to see a refused grant while the Source row
// is still healthy, so its re-login cannot route through the detail panel's
@@ -449,12 +449,14 @@ export const SettingsModelsPage: React.FC = () => {
const [quotaReauthSource, setQuotaReauthSource] = React.useState<Source | null>(null);
// A re-login started from a quota card has no detail heading to return to.
const quotaReauthOpenerRef = React.useRef<HTMLElement | null>(null);
+ // The card button focus went back to when that re-login closed, until the
+ // quota re-read its success started has landed.
+ const quotaFocusHoldRef = React.useRef<HTMLElement | null>(null);
const subscriptionTriggerRef = React.useRef<HTMLButtonElement>(null);
const apiKeyTriggerRef = React.useRef<HTMLButtonElement | null>(null);
const subscriptionAnchorRef = subscriptionTriggerRef as React.RefObject<HTMLButtonElement>;
const subscriptionPickerRefs = React.useRef<Partial<Record<SubscriptionPickerVendor, HTMLButtonElement | null>>>({});
const subscriptionPickerHandoffRef = React.useRef(false);
- const subscriptionCloseTimer = React.useRef<number | null>(null);
// A successful OAuth terminal reports the same moved rows twice: first with
// the created source, then as the generic stale-row notification. The source
// callback owns the one full reconciliation; consume the trailing notification
@@ -766,6 +768,13 @@ export const SettingsModelsPage: React.FC = () => {
degraded: () => null,
});
const rereadQuota = React.useCallback(() => { void readQuota(false); }, [readQuota]);
+ // A clean re-login closes before the quota re-read it started lands, and a
+ // healthy answer removes the card button focus just went back to.
+ React.useLayoutEffect(() => {
+ const held = quotaFocusHoldRef.current;
+ quotaFocusHoldRef.current = null;
+ if (held && !held.isConnected && document.activeElement === document.body) focusQuotaOpener(held);
+ }, [quotaSettled]);
const resetQuotaRereads = usePendingRereads(tab === 'quota', quotaPendingKey, quotaSettled, rereadQuota);
React.useEffect(() => {
@@ -1321,11 +1330,6 @@ export const SettingsModelsPage: React.FC = () => {
if (status?.pending || !status?.failed.size) return;
routeProjectionReconciler.retry();
}, [routeProjectionReconciler]);
- const routeCommitReconciliation = React.useMemo<RouteCommitReconciliation | null>(() => routeCommitStatus ? ({
- pending: routeCommitStatus.pending,
- failed: routeCommitStatus.failed.size > 0,
- retry: retryRouteCommit,
- }) : null, [retryRouteCommit, routeCommitStatus]);
React.useEffect(() => {
const heldBackends = new Set(suspendedRouteAttempts.keys());
for (const backend of suspendedHubFrontiersRef.current.keys()) {
@@ -1437,8 +1441,8 @@ export const SettingsModelsPage: React.FC = () => {
void refresh();
return;
}
- // Keep the success panel as the only active dialog until its handoff timer
- // closes it. The provider dialog then opens and owns its normal autofocus.
+ // The toast already said it connected, so the sign-in dialog hands straight
+ // over to the provider it created, which then owns its normal autofocus.
sourceEntityAuthority.landLatest(source);
selectSource({
sourceId: source.id,
@@ -1446,17 +1450,9 @@ export const SettingsModelsPage: React.FC = () => {
});
subscriptionSuccessReconcileRef.current = true;
void refresh();
- if (subscriptionCloseTimer.current !== null) window.clearTimeout(subscriptionCloseTimer.current);
- subscriptionCloseTimer.current = window.setTimeout(() => {
- subscriptionCloseTimer.current = null;
- setSubscriptionVendor(null);
- }, 1400);
+ setSubscriptionVendor(null);
}, [refresh, selectSource, sourceEntityAuthority]);
const closeSubscription = React.useCallback(() => {
- if (subscriptionCloseTimer.current !== null) {
- window.clearTimeout(subscriptionCloseTimer.current);
- subscriptionCloseTimer.current = null;
- }
setSubscriptionVendor(null);
window.setTimeout(() => subscriptionTriggerRef.current?.focus(), 0);
}, []);
@@ -1484,6 +1480,7 @@ export const SettingsModelsPage: React.FC = () => {
// quota card, back to its button, or to the quota tab once it is gone.
const opener = quotaReauthOpenerRef.current;
quotaReauthOpenerRef.current = null;
+ quotaFocusHoldRef.current = opener;
window.setTimeout(() => (opener ? focusQuotaOpener(opener) : sourceDetailHeadingRef.current?.focus()), 0);
}, []);
const closeSubscriptionPicker = React.useCallback(() => {
@@ -1505,9 +1502,6 @@ export const SettingsModelsPage: React.FC = () => {
if (subscriptionPickerOpen) closeSubscriptionPicker();
else openSubscriptionPicker();
}, [closeSubscriptionPicker, openSubscriptionPicker, subscriptionPickerOpen]);
- React.useEffect(() => () => {
- if (subscriptionCloseTimer.current !== null) window.clearTimeout(subscriptionCloseTimer.current);
- }, []);
return (
<ModelHubShell
@@ -1807,18 +1801,17 @@ export const SettingsModelsPage: React.FC = () => {
setRouteTarget(null);
if (target) focusRouteDestination(target);
}}
- onManageModel={(action, route) => {
+ onManageModel={(action) => {
// The catalog dialog is the one writer of the model list; the route
// dialog steps aside while it edits or removes the model it was
// showing, then reopens on that model.
if (!routeTarget) return;
catalogOriginRef.current = routeTarget;
setRouteTarget(null);
- setCatalogFocus({ modelId: routeTarget.modelId, action, route });
+ setCatalogFocus({ modelId: routeTarget.modelId, action });
setMenuBackend(routeTarget.agent.backend);
}}
onCommitted={(result) => routeCommitted(result, routeTarget?.opener ?? null)}
- commitReconciliation={routeCommitReconciliation}
onObserved={routeObserved}
readAgents={readRouteAgents}
readSources={readRouteSources}
diff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsx
index 56f57dcb3..987ef3391 100644
--- a/ui/src/components/settings/models/SourceDetailPanel.test.tsx
+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx
@@ -2,7 +2,7 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import * as React from 'react';
-import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';
+import { act, cleanup, render as renderRaw, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { I18nextProvider } from 'react-i18next';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -88,11 +88,10 @@ const submitManagementWrite = async (action: UnknownWriteAction, forced: boolean
return;
}
+ // A deletion is confirmed before its first attempt, so a guard refusal is
+ // forced through with no second click.
await userEvent.click(screen.getByRole('menuitem', { name: /^Remove source$|^移除供应商$/i }));
await userEvent.click(screen.getByRole('button', { name: /^Remove source$|^移除供应商$/i }));
- if (forced) {
- await userEvent.click(await screen.findByRole('button', { name: /^Remove source$|^移除供应商$/i }));
- }
};
const noReauth = () => {
@@ -136,6 +135,9 @@ const settlement = (overrides: Partial<SourceMutationSettlement> = {}): SourceMu
readInventory: async () => ({ snapshot: beginSourceSnapshot(), sources: await modelsApi.listSources() }),
...overrides,
});
+// The panel always mounts its key-replacement dialog, and that dialog reports
+// a saved key through the page's toast, so every panel render needs one.
+const render = (ui: React.ReactElement) => renderRaw(ui, { wrapper: ToastProvider });
const immediateTrack: TrackSourceMutation = async (work) => work(source, settlement());
// The surface owner announces a committed mutation and reconciles it behind that
// announcement — no second decision stands between the write and its settlement.
@@ -154,19 +156,15 @@ const CommittedPanel: React.FC<CommittedPanelProps> = (props) => (
type MutationScheduler = <T>(work: () => Promise<T>) => Promise<T>;
const renderPanel = (adoptedBy: Source['adopted_by'] = undefined) => render(
- <ToastProvider>
- <I18nextProvider i18n={i18n}>
- <CommittedPanel source={{ ...source, adopted_by: adoptedBy }} trackMutation={immediateTrack} onReauth={noReauth} />
- </I18nextProvider>
- </ToastProvider>,
+ <I18nextProvider i18n={i18n}>
+ <CommittedPanel source={{ ...source, adopted_by: adoptedBy }} trackMutation={immediateTrack} onReauth={noReauth} />
+ </I18nextProvider>,
);
const renderProtocol = (protocol: SourceProtocol, models: Source['models'] = source.models) => render(
- <ToastProvider>
- <I18nextProvider i18n={i18n}>
- <CommittedPanel source={{ ...source, protocol, models }} trackMutation={immediateTrack} onReauth={noReauth} />
- </I18nextProvider>
- </ToastProvider>,
+ <I18nextProvider i18n={i18n}>
+ <CommittedPanel source={{ ...source, protocol, models }} trackMutation={immediateTrack} onReauth={noReauth} />
+ </I18nextProvider>,
);
const EchoPanel: React.FC<{
@@ -197,11 +195,9 @@ const renderEchoPanel = (
reconcile: React.ComponentProps<typeof EchoPanel>['reconcile'] = vi.fn(),
scheduler?: MutationScheduler,
) => render(
- <ToastProvider>
- <I18nextProvider i18n={i18n}>
- <EchoPanel reconcile={reconcile} scheduler={scheduler} />
- </I18nextProvider>
- </ToastProvider>,
+ <I18nextProvider i18n={i18n}>
+ <EchoPanel reconcile={reconcile} scheduler={scheduler} />
+ </I18nextProvider>,
);
afterEach(() => {
@@ -436,7 +432,7 @@ describe('SourceDetailPanel', () => {
expect(commits[0].impact).toEqual({ hops, gaps });
});
- it('echoes a non-empty server plan exactly when deleting a source', async () => {
+ it('forces a guarded source deletion with the server plan, byte for byte, without asking twice', async () => {
const hops = [{ backend: 'claude' as const, menu_model: 'claude-opus-4-6', position: 2, source_id: source.id, model_id: 'model-a' }];
const gaps = [{ backend: 'claude' as const, model_id: 'claude-opus-4-6', agents: ['Release bot'] }];
const requests: { url: string; init?: RequestInit }[] = [];
@@ -457,8 +453,6 @@ describe('SourceDetailPanel', () => {
await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));
await userEvent.click(screen.getByRole('menuitem', { name: /^Remove source$|^移除供应商$/i }));
await userEvent.click(screen.getByRole('button', { name: /^Remove source$|^移除供应商$/i }));
- expect(await screen.findAllByText(/claude-opus-4-6/)).toHaveLength(2);
- await userEvent.click(screen.getByRole('button', { name: /^Remove source$|^移除供应商$/i }));
await waitFor(() => expect(requests).toHaveLength(2));
expect(requests[0].url).not.toContain('force=true');
@@ -603,7 +597,6 @@ describe('SourceDetailPanel', () => {
await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));
await userEvent.click(screen.getByRole('menuitem', { name: /^Remove source$|^移除供应商$/i }));
await userEvent.click(screen.getByRole('button', { name: /^Remove source$|^移除供应商$/i }));
- await userEvent.click(await screen.findByRole('button', { name: /^Remove source$|^移除供应商$/i }));
await userEvent.click(await screen.findByRole('button', { name: /^Try again$|^重试$/i }));
await waitFor(() => expect(requests).toHaveLength(3));
@@ -947,9 +940,9 @@ describe('SourceDetailPanel', () => {
it('routes every full-Source mutation family through the shared per-Source queue', () => {
const detail = readFileSync(join(process.cwd(), 'src/components/settings/models/SourceDetailPanel.tsx'), 'utf8');
- expect(detail).toMatch(/const refetch = \(confirmation\?: GuardConfirmation\)[\s\S]*?return trackMutation\(async \(latest, settlement\)/);
+ expect(detail).toMatch(/const refetch = \(plan: ManageGuardPlan \| null = null\)[\s\S]*?return trackMutation\(async \(latest, settlement\)/);
expect(detail).toMatch(/const addManualModel = \(\)[\s\S]*?return trackMutation\(async \(latest, settlement\)/);
- expect(detail).toMatch(/const remove = \(model: SuppliedModel, confirmation\?: GuardConfirmation\)[\s\S]*?return trackMutation\(async \(latest, settlement\)/);
+ expect(detail).toMatch(/const remove = \(model: SuppliedModel, plan: ManageGuardPlan \| null = null\)[\s\S]*?return trackMutation\(async \(latest, settlement\)/);
expect(detail).toMatch(/const submitEdit = \(draft: SourceEditDraft, patch: SourcePatch, plan: ManageGuardPlan \| null\)[\s\S]*?return trackMutation\(async \(latest, settlement\)/);
expect(detail).toMatch(/const submitDelete = \(plan: ManageGuardPlan \| null\)[\s\S]*?return trackMutation\(async \(latest, settlement\)/);
});
@@ -1032,9 +1025,9 @@ describe('SourceDetailPanel', () => {
{ 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}>
+ render(<I18nextProvider i18n={locale}>
<CommittedPanel source={{ ...source, kind, supply_channel, verification_pending: 'vp_fixture' }} trackMutation={immediateTrack} onReauth={noReauth} />
- </I18nextProvider></ToastProvider>);
+ </I18nextProvider>);
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') });
@@ -1098,7 +1091,7 @@ describe('SourceDetailPanel', () => {
expect(bodies[1]).toEqual({ force: true, would_remove_hops: hops, would_interrupt: gaps });
});
- it('requires confirmation again when a forced removal receives a new guard plan', async () => {
+ it('forces a confirmed removal through a guard plan that moved, without asking again', async () => {
const firstHops = [{ backend: 'claude' as const, menu_model: 'menu-a', position: 1, source_id: source.id, model_id: 'model-a' }];
const nextHops = [{ backend: 'codex' as const, menu_model: 'menu-b', position: 3, source_id: source.id, model_id: 'model-a' }];
const bodies: unknown[] = [];
@@ -1118,11 +1111,77 @@ describe('SourceDetailPanel', () => {
await userEvent.click(screen.getByRole('menuitem', { name: /^Remove$|^移除$/i }));
await userEvent.click(await screen.findByRole('button', { name: /^Remove anyway$|^仍要移除$/i }));
- expect(await screen.findByText(/menu-b/)).toBeTruthy();
- expect(bodies[1]).toEqual({ force: true, would_remove_hops: firstHops, would_interrupt: [] });
- await userEvent.click(screen.getByRole('button', { name: /^Remove anyway$|^仍要移除$/i }));
+ // The user answered once, against the first plan. The moved plan is resent
+ // under that answer, echoed as the server named it, and nothing asks again.
await waitFor(() => expect(bodies).toHaveLength(3));
+ expect(bodies[1]).toEqual({ force: true, would_remove_hops: firstHops, would_interrupt: [] });
expect(bodies[2]).toEqual({ force: true, would_remove_hops: nextHops, would_interrupt: [] });
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect(screen.queryByText(/menu-b/)).toBeNull();
+ });
+
+ it.each([
+ {
+ flow: 'refetch',
+ path: `/api/models/sources/${source.id}/refresh`,
+ error: 'source_in_route_chain',
+ guard: /^Refetch models from|^从.*重新拉取模型/,
+ failure: /fetch did not come back|拉取没有回来/,
+ start: async () => {
+ await userEvent.click(screen.getByRole('button', { name: /^Refetch$|^重新拉取$/i }));
+ await userEvent.click(await screen.findByRole('button', { name: /^Refetch anyway$|^仍要拉取$/i }));
+ },
+ },
+ {
+ flow: 'remove',
+ path: `/api/models/sources/${source.id}/models/model-a`,
+ error: 'source_model_in_route_chain',
+ guard: /^Remove model-a from|^从.*移除 model-a/,
+ failure: /model was not removed|这个模型没有移除/,
+ start: async () => {
+ await userEvent.click(screen.getByRole('button', { name: /Remove model-a|移除 model-a/i }));
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Remove$|^移除$/i }));
+ await userEvent.click(await screen.findByRole('button', { name: /^Remove anyway$|^仍要移除$/i }));
+ },
+ },
+ {
+ flow: 'edit',
+ path: `/api/models/sources/${source.id}`,
+ error: 'source_last_supplier',
+ guard: /save changes|保存.*更改/i,
+ failure: /source was not saved|供应商没有保存/,
+ start: async () => {
+ await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Edit source$|^编辑供应商$/i }));
+ const name = screen.getByLabelText(/^Display name$|^显示名称$/i);
+ await userEvent.clear(name);
+ await userEvent.type(name, 'Moving plan');
+ await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));
+ await userEvent.click(await screen.findByRole('button', { name: /^Save anyway$|^仍要保存$/i }));
+ },
+ },
+ ])('ends a confirmed $flow whose plan never settles as a failure, not a second question', async ({ path, error, guard, failure, start }) => {
+ let refusals = 0;
+ vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input).split('?')[0];
+ if (url === '/api/csrf-token') return Response.json({ csrf_token: 'csrf' });
+ if (url === '/api/models/sources') return Response.json({ sources: [source] });
+ if (url === path) {
+ refusals += 1;
+ const hops = [{ backend: 'claude', menu_model: 'claude-opus-4-6', position: refusals, source_id: source.id, model_id: 'model-a' }];
+ return Response.json({ error, would_remove_hops: hops, would_interrupt: [] }, { status: 409 });
+ }
+ throw new Error(`unexpected request: ${url}`);
+ }));
+ renderEchoPanel();
+
+ await start();
+
+ // One question, then the initial write plus the bounded resends: the plan
+ // that kept moving is reported, not asked about a second time.
+ expect(await screen.findByText(failure)).toBeTruthy();
+ expect(screen.queryByRole('dialog', { name: guard })).toBeNull();
+ expect(refusals).toBe(4);
});
it('names every model and Agent that a guarded change would interrupt', () => {
diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsx
index 203d287ef..ced2f81ae 100644
--- a/ui/src/components/settings/models/SourceDetailPanel.tsx
+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx
@@ -13,7 +13,9 @@ import { AddApiKeyDialog } from './AddApiKeyDialog';
import { PROTOCOL_COPY_KEYS } from './addApiKeyState';
import { classifyModelHubFailure } from './asyncLifetime';
import { Field } from './dialogFields';
+import { GuardDialog } from './GuardDialog';
import { GuardImpact } from './GuardImpact';
+import { confirmGuardPlan, guardedFailure, sendAgreed } from './guardedWrite';
import { ModelHubInfoHint } from './ModelHubInfoHint';
import { SourcePrivateValue, SourcePrivacyToggle } from './SourcePrivacy';
import { useSourceDetailsHidden } from './sourcePrivacyPreference';
@@ -33,7 +35,7 @@ import type {
ManageStage,
SourceEditDraft,
} from './manage';
-import { apiFailure, modelsApi, type GuardConfirmation } from './modelsApi';
+import { apiFailure, modelsApi } from './modelsApi';
import {
SOURCE_PROVIDER_COPY_KEYS,
sourceProviderIdentity,
@@ -130,12 +132,6 @@ type GuardedAction =
| { kind: 'refetch'; plan: ManageGuardPlan }
| { kind: 'removeModel'; model: SuppliedModel; plan: ManageGuardPlan };
-const confirmGuardPlan = (plan: ManageGuardPlan): GuardConfirmation => ({
- force: true,
- would_remove_hops: plan.hops,
- would_interrupt: plan.gaps,
-});
-
const GUARD_COPY_KIND: Record<GuardedAction['kind'], 'refetch' | 'removeModel'> = {
refetch: 'refetch',
removeModel: 'removeModel',
@@ -209,12 +205,7 @@ export const SourceDetailPanel: React.FC<{
dispatchManageStage({ type: 'begin_delete' });
};
- const guardedFailure = (error: unknown): ManageGuardPlan | null => {
- const failure = apiFailure(error);
- if (!failure || (failure.wouldRemoveHops.length === 0 && failure.wouldInterrupt.length === 0)) return null;
- return { hops: failure.wouldRemoveHops, gaps: failure.wouldInterrupt };
- };
- const refetch = (confirmation?: GuardConfirmation) => {
+ const refetch = (plan: ManageGuardPlan | null = null) => {
if (busy) return Promise.resolve();
setResult(null);
setRefetchFailed(false);
@@ -222,7 +213,9 @@ export const SourceDetailPanel: React.FC<{
return trackMutation(async (latest, settlement) => {
const before = new Set(latest.models.map((model) => model.id));
try {
- const answer = await modelsApi.refreshSource(latest.id, confirmation);
+ const answer = await sendAgreed(plan !== null, plan, (next) => (
+ modelsApi.refreshSource(latest.id, next ? confirmGuardPlan(next) : undefined)
+ ));
const after = new Set(answer.source.models.map((model) => model.id));
const added = [...after].filter((id) => !before.has(id));
const removed = [...before].filter((id) => !after.has(id));
@@ -232,11 +225,14 @@ export const SourceDetailPanel: React.FC<{
} catch (error) {
if (apiFailure(error)?.code === 'source_not_found') await settlement.gone(latest.id);
else {
- const refusal = guardedFailure(error);
+ // A confirmed refetch was already answered: a plan that kept moving
+ // past the resend bound ends as a failure, never a second question.
+ const refusal = plan === null ? guardedFailure(error) : null;
if (refusal) {
setGuard({ kind: 'refetch', plan: refusal });
settlement.release();
} else {
+ setGuard(null);
setRefetchFailed(true);
try {
const inventory = await settlement.readInventory();
@@ -348,7 +344,7 @@ export const SourceDetailPanel: React.FC<{
settlement.release();
setRemoveFailure({ modelId: model.id, retryRead: reconciliation.kind === 'unread' });
};
- const remove = (model: SuppliedModel, confirmation?: GuardConfirmation) => {
+ const remove = (model: SuppliedModel, plan: ManageGuardPlan | null = null) => {
if (busy) return Promise.resolve();
setResult(null);
setRefetchFailed(false);
@@ -361,17 +357,22 @@ export const SourceDetailPanel: React.FC<{
return;
}
try {
- const echoed = await modelsApi.deleteCustomModel(latest.id, model.id, confirmation);
+ const echoed = await sendAgreed(plan !== null, plan, (next) => (
+ modelsApi.deleteCustomModel(latest.id, model.id, next ? confirmGuardPlan(next) : undefined)
+ ));
setGuard(null);
await settlement.source(echoed);
} catch (error) {
if (apiFailure(error)?.code === 'source_not_found') await settlement.gone(latest.id);
else {
- const refusal = guardedFailure(error);
+ const refusal = plan === null ? guardedFailure(error) : null;
if (refusal) {
setGuard({ kind: 'removeModel', model, plan: refusal });
settlement.release();
- } else await reconcileRemoval(latest.id, model, settlement);
+ } else {
+ setGuard(null);
+ await reconcileRemoval(latest.id, model, settlement);
+ }
}
}
}).finally(() => setPendingAction(null));
@@ -478,11 +479,13 @@ export const SourceDetailPanel: React.FC<{
});
setPendingAction('other');
return trackMutation(async (latest, settlement) => {
+ // A plan here is the guard's question already answered.
+ let sent = plan;
try {
- const answer = await modelsApi.patchSource(
- latest.id,
- plan ? { ...patch, ...confirmGuardPlan(plan) } : patch,
- );
+ const answer = await sendAgreed(forced, plan, (next) => {
+ sent = next;
+ return modelsApi.patchSource(latest.id, next ? { ...patch, ...confirmGuardPlan(next) } : patch);
+ });
const impact = committedPlan(answer.removed_hops, answer.interrupted);
await commitManagementMutation(
'edit',
@@ -500,9 +503,9 @@ export const SourceDetailPanel: React.FC<{
(scope) => settlement.gone(latest.id, undefined, scope),
);
} else if (classifyModelHubFailure(failure) === 'inconclusive') {
- await reconcileEditWrite(latest, draft, patch, plan, settlement);
+ await reconcileEditWrite(latest, draft, patch, sent, settlement);
} else {
- const refusal = guardedFailure(error);
+ const refusal = forced ? null : guardedFailure(error);
if (refusal) {
dispatchManageStage({ type: 'guard_edit', draft, patch, plan: refusal });
settlement.release();
@@ -511,8 +514,8 @@ export const SourceDetailPanel: React.FC<{
type: 'fail_edit',
draft,
patch,
- plan,
- forced,
+ plan: sent,
+ forced: sent !== null,
retryRead: false,
before: latest,
});
@@ -524,15 +527,18 @@ export const SourceDetailPanel: React.FC<{
};
const submitDelete = (plan: ManageGuardPlan | null) => {
if (busy) return Promise.resolve();
- const forced = plan !== null;
dispatchManageStage({ type: 'submit_delete', plan });
setPendingAction('other');
return trackMutation(async (latest, settlement) => {
+ // Deleting is confirmed before the first attempt, and that confirmation
+ // says it removes the source from every route that uses it — so whatever
+ // plan the guard names is already agreed to.
+ let sent = plan;
try {
- const answer = await modelsApi.deleteSource(
- latest.id,
- plan ? confirmGuardPlan(plan) : undefined,
- );
+ const answer = await sendAgreed(true, plan, (next) => {
+ sent = next;
+ return modelsApi.deleteSource(latest.id, next ? confirmGuardPlan(next) : undefined);
+ });
const impact = committedPlan(answer.removed_hops, answer.interrupted);
await commitManagementMutation(
'delete',
@@ -552,16 +558,10 @@ export const SourceDetailPanel: React.FC<{
(scope) => settlement.gone(latest.id, undefined, scope),
);
} else if (classifyModelHubFailure(failure) === 'inconclusive') {
- await reconcileDeleteWrite(latest, plan, settlement);
+ await reconcileDeleteWrite(latest, sent, settlement);
} else {
- const refusal = guardedFailure(error);
- if (refusal) {
- dispatchManageStage({ type: 'guard_delete', plan: refusal });
- settlement.release();
- } else {
- dispatchManageStage({ type: 'fail_delete', plan, forced, retryRead: false, before: latest });
- settlement.release();
- }
+ dispatchManageStage({ type: 'fail_delete', plan: sent, forced: sent !== null, retryRead: false, before: latest });
+ settlement.release();
}
}
}).finally(() => setPendingAction(null));
@@ -622,12 +622,12 @@ export const SourceDetailPanel: React.FC<{
if (manageStage.kind === 'confirming_edit') {
void submitEdit(manageStage.draft, manageStage.patch, manageStage.plan);
}
- if (manageStage.kind === 'confirming_delete') void submitDelete(manageStage.plan);
+ if (manageStage.kind === 'confirming_delete') void submitDelete(null);
};
const confirmGuard = () => {
if (!guard) return;
- if (guard.kind === 'refetch') void refetch(confirmGuardPlan(guard.plan));
- if (guard.kind === 'removeModel') void remove(guard.model, confirmGuardPlan(guard.plan));
+ if (guard.kind === 'refetch') void refetch(guard.plan);
+ if (guard.kind === 'removeModel') void remove(guard.model, guard.plan);
};
const adoptedBy = activeSourceAdoption(source.adopted_by, activeBackends);
const adoptedBackends = [...new Set((adoptedBy ?? []).map(({ backend }) => t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string))];
@@ -842,38 +842,23 @@ export const SourceDetailPanel: React.FC<{
</DialogPrimitive.Content>
</DialogPrimitive.Portal>
</DialogPrimitive.Root>
- <DialogPrimitive.Root open={guard !== null || manageGuardOpen} onOpenChange={(open) => {
- if (!open && !busy) {
- if (manageGuardOpen) cancelManage();
- else setGuard(null);
- }
- }}>
- <DialogPrimitive.Portal>
- <DialogPrimitive.Overlay className="model-hub-guard-overlay fixed inset-0 z-50" />
- <DialogPrimitive.Content
- className="model-hub-guard-dialog fixed left-1/2 top-1/2 z-50 flex max-h-[calc(100dvh-2rem)] -translate-x-1/2 -translate-y-1/2 flex-col overflow-y-auto border border-border-strong bg-surface outline-none"
- onEscapeKeyDown={(event) => { if (busy) event.preventDefault(); }}
- onPointerDownOutside={(event) => { if (busy) event.preventDefault(); }}
- >
- <header className="model-hub-guard-head">
- <div className="flex items-center justify-between gap-3">
- <DialogPrimitive.Title className="model-hub-guard-title text-foreground">{manageGuardOpen
- ? t(`settings.models.guard.title.${manageCopyKind}`, { source: source.display_name })
- : t(`settings.models.guard.title.${guard ? GUARD_COPY_KIND[guard.kind] : 'refetch'}`, { model: guard?.kind === 'removeModel' ? guard.model.id : undefined, source: source.display_name })}</DialogPrimitive.Title>
- <DialogPrimitive.Close asChild><Button type="button" variant="ghost" size="icon" className="model-hub-guard-close" disabled={busy} aria-label={t('settings.models.guard.cancel')} title={t('settings.models.guard.cancel')}><X aria-hidden /></Button></DialogPrimitive.Close>
- </div>
- <DialogPrimitive.Description className="model-hub-guard-subtitle">{manageGuardOpen
- ? t(`settings.models.guard.subtitle.${manageCopyKind}`)
- : t(`settings.models.guard.subtitle.${guard ? GUARD_COPY_KIND[guard.kind] : 'refetch'}`)}</DialogPrimitive.Description>
- </header>
- {manageGuardOpen && managePlan && <div className="model-hub-guard-body"><GuardImpact hops={managePlan.hops} gaps={managePlan.gaps} /></div>}
- {!manageGuardOpen && guard?.plan && <div className="model-hub-guard-body"><GuardImpact hops={guard.plan.hops} gaps={guard.plan.gaps} /></div>}
- {manageGuardOpen
- ? <footer className="model-hub-guard-foot"><Button variant="outline" className="model-hub-guard-action" onClick={cancelManage} disabled={busy}>{t('settings.models.guard.cancel')}</Button><Button variant="destructive" className="model-hub-guard-action" onClick={confirmManage} disabled={busy}>{busy && <Loader2 className="animate-spin" />}{t(`settings.models.guard.confirm.${manageCopyKind}`)}</Button></footer>
- : <footer className="model-hub-guard-foot"><Button variant="outline" className="model-hub-guard-action" onClick={() => setGuard(null)} disabled={busy}>{t('settings.models.guard.cancel')}</Button><Button variant="destructive" className="model-hub-guard-action" onClick={confirmGuard} disabled={busy}>{busy && <Loader2 className="animate-spin" />}{t(`settings.models.guard.confirm.${guard ? GUARD_COPY_KIND[guard.kind] : 'refetch'}`)}</Button></footer>}
- </DialogPrimitive.Content>
- </DialogPrimitive.Portal>
- </DialogPrimitive.Root>
+ <GuardDialog
+ open={guard !== null || manageGuardOpen}
+ title={manageGuardOpen
+ ? t(`settings.models.guard.title.${manageCopyKind}`, { source: source.display_name })
+ : t(`settings.models.guard.title.${guard ? GUARD_COPY_KIND[guard.kind] : 'refetch'}`, { model: guard?.kind === 'removeModel' ? guard.model.id : undefined, source: source.display_name })}
+ subtitle={manageGuardOpen
+ ? t(`settings.models.guard.subtitle.${manageCopyKind}`)
+ : t(`settings.models.guard.subtitle.${guard ? GUARD_COPY_KIND[guard.kind] : 'refetch'}`)}
+ confirmLabel={t(`settings.models.guard.confirm.${manageGuardOpen ? manageCopyKind : guard ? GUARD_COPY_KIND[guard.kind] : 'refetch'}`)}
+ busy={busy}
+ onCancel={manageGuardOpen ? cancelManage : () => setGuard(null)}
+ onConfirm={manageGuardOpen ? confirmManage : confirmGuard}
+ >
+ {manageGuardOpen
+ ? managePlan && <GuardImpact hops={managePlan.hops} gaps={managePlan.gaps} />
+ : guard?.plan && <GuardImpact hops={guard.plan.hops} gaps={guard.plan.gaps} />}
+ </GuardDialog>
</div>
);
};
diff --git a/ui/src/components/settings/models/asyncLifetime.test.ts b/ui/src/components/settings/models/asyncLifetime.test.ts
index 40e835e67..b636cf4ed 100644
--- a/ui/src/components/settings/models/asyncLifetime.test.ts
+++ b/ui/src/components/settings/models/asyncLifetime.test.ts
@@ -359,7 +359,7 @@ describe('Source entity landing through the shared authority', () => {
const sourceRetry = page.slice(page.indexOf('const retrySources'), page.indexOf('const retrySupply'));
const supplyRetry = page.slice(page.indexOf('const retrySupply'), page.indexOf('const retryEvents'));
- expect(detail).toMatch(/trackMutation\(async \(latest, settlement\)[\s\S]*?modelsApi\.refreshSource\(latest\.id, confirmation\)/);
+ expect(detail).toMatch(/trackMutation\(async \(latest, settlement\)[\s\S]*?modelsApi\.refreshSource\(latest\.id, next \? confirmGuardPlan\(next\) : undefined\)/);
expect(detail).toMatch(/await settlement\.source\(answer\.source\)/);
expect(page).toMatch(/sourceWriteRegistry\.track\(sourceId[\s\S]*?sourceEntityAuthority\.current\(sourceId\)[\s\S]*?sourceEntityAuthority\.begin\(sourceId\)[\s\S]*?const settlement: SourceMutationSettlement/);
expect(page).toMatch(/source: async \(echoed, scope\)[\s\S]*?sourceEntityAuthority\.settle\(generation/);
diff --git a/ui/src/components/settings/models/backendCatalog.test.ts b/ui/src/components/settings/models/backendCatalog.test.ts
index 7adc1ce7a..ec9c14c7d 100644
--- a/ui/src/components/settings/models/backendCatalog.test.ts
+++ b/ui/src/components/settings/models/backendCatalog.test.ts
@@ -15,16 +15,13 @@ import {
backendModelId,
draftRowFor,
draftWithId,
- echoableRefusal,
heldRowFor,
offeredCandidates,
- orderWithRestored,
MODELS_DEV_FIELDS,
pickerGroups,
readBackendCatalogBaseline,
retireModelsDevMatch,
sameBackendModel,
- samePlanContents,
} from './backendCatalog';
import type {
AgentSupply,
@@ -525,45 +522,6 @@ describe('backendCatalogIntent', () => {
});
});
-describe('orderWithRestored', () => {
- const BASELINE = ['a', 'b', 'c', 'd'];
-
- const without = (...ids: string[]) => BASELINE.filter((id) => !ids.includes(id));
-
- it('puts a cancelled removal back where the baseline had it, wherever that was', () => {
- // The property, stated for every position rather than for the one that
- // happens to be interesting: undoing a removal restores the baseline
- // exactly. A row that came back at the end would answer 「are you sure?」
- // with a reordered catalog the user never asked for — and one that reports
- // itself as edited afterwards can never be saved back to what it was.
- for (const id of BASELINE) {
- expect(orderWithRestored(without(id), BASELINE, new Set([id])), id).toEqual(BASELINE);
- }
- // Including all of them at once, in any combination: the restored rows keep
- // their baseline sequence among themselves, so neighbours cannot swap.
- expect(orderWithRestored(without('b', 'c'), BASELINE, new Set(['b', 'c']))).toEqual(BASELINE);
- expect(orderWithRestored([], BASELINE, new Set(BASELINE))).toEqual(BASELINE);
- });
-
- it('leaves every other edit alone', () => {
- // A refusal answers one removal; it says nothing about a reorder or an
- // addition the user also made, and those are still theirs afterwards. So
- // the baseline decides positions and is never replayed as the order.
- expect(orderWithRestored(['d', 'a', 'c'], BASELINE, new Set(['b'])))
- .toEqual(['d', 'a', 'b', 'c']);
- expect(orderWithRestored(['a', 'c', 'd', 'new'], BASELINE, new Set(['b'])))
- .toEqual(['a', 'b', 'c', 'd', 'new']);
- expect(orderWithRestored(['a', 'b', 'c', 'd'], BASELINE, new Set())).toEqual(BASELINE);
- });
-
- it('restores an id whose baseline neighbours are all gone', () => {
- // Nothing to anchor to is still an answer: the front, because a row with no
- // surviving predecessor had none in the baseline either.
- expect(orderWithRestored(['d'], BASELINE, new Set(['b']))).toEqual(['b', 'd']);
- expect(orderWithRestored(['new'], BASELINE, new Set(['c']))).toEqual(['c', 'new']);
- });
-});
-
describe('applyBackendCatalogIntent', () => {
it('replays edits onto a newer catalog and keeps a concurrent addition visible', () => {
const intent = backendCatalogIntent([model('a'), model('b')], [model('b'), model('a', { display_name: 'A' })]);
@@ -824,105 +782,3 @@ describe('offeredCandidates', () => {
});
});
-describe('samePlanContents', () => {
- const hop = (position: number) => ({
- source_id: 'src', model_id: 'kimi-k3', backend: 'claude', menu_model: 'kimi-k3', position,
- });
- const gap = (agents: string[]) => ({ backend: 'claude', model_id: 'kimi-k3', agents });
-
- /** Every ordering of a list. */
- const orderings = <T>(list: readonly T[]): T[][] => (
- list.length <= 1
- ? [[...list]]
- : list.flatMap((head, index) => orderings([...list.slice(0, index), ...list.slice(index + 1)])
- .map((rest) => [head, ...rest]))
- );
-
- it('reads any two orderings of the same consequences as one plan', () => {
- // The decision it serves: 「is the server's refusal the one the user already
- // confirmed?」. The preview follows the order the user clicked and the
- // refusal follows the server's own walk of the baseline, so an order that
- // differs between them is not a disagreement about what would happen — and
- // asking the same question twice for it is the bug.
- const plan = [hop(1), hop(2), gap(['reviewer'])];
- const every = orderings(plan);
- expect(every).toHaveLength(6);
- expect(every.filter((ordering) => !samePlanContents(plan, ordering))).toEqual([]);
- });
-
- it('reads consequences that are not the same as a different plan', () => {
- // What makes the automatic retry safe: a server whose answer moved between
- // the question and the retry has to ask it again.
- const plan = [hop(1), hop(2)];
- const moved = [
- [], // nothing left
- [hop(1)], // one fewer
- [hop(1), hop(2), hop(3)], // one more
- [hop(1), hop(1)], // one replaced by a copy of the other
- [hop(1), hop(9)], // one altered
- ];
- expect(moved.filter((other) => samePlanContents(plan, other))).toEqual([]);
- // Including inside an element, where no story explains a reordering: one
- // side produced that list, so a different order there is a real change.
- expect(samePlanContents([gap(['a', 'b'])], [gap(['b', 'a'])])).toBe(false);
- });
-
- it('reads no difference into how the same element happens to be written', () => {
- // Both halves are JSON off a wire, and neither side controls the other's
- // key order or how it spells a field it has nothing to say about.
- expect(samePlanContents(
- [{ source_id: 'src', model_id: 'kimi-k3', position: 1 }],
- [{ position: 1, model_id: 'kimi-k3', source_id: 'src', menu_model: undefined }],
- )).toBe(true);
- });
-});
-
-describe('echoableRefusal', () => {
- const BASELINE = [model('alpha'), model('beta'), model('gamma')];
- const REQUESTED = [model('alpha')];
- const stored = (owed: readonly string[]) => ({
- baseline: BASELINE,
- models: REQUESTED,
- owed: new Set(owed),
- });
-
- it('permits an echo only where the refusal was accepted AND still describes this write', () => {
- // Two independent facts decide it, so what is stated here is their product
- // rather than a list of cases: whether every held-back removal has been
- // answered against the server's own plan, and whether the write is still
- // the one the server refused. `force` asserts both at once — 「the user saw
- // this consequence, and it is the consequence of what I am sending」 — so
- // the answer is their conjunction, and each dimension is free to grow
- // without the expectations being rewritten.
- const ACCEPTANCE = [
- { what: 'every question answered', owed: [], accepted: true },
- { what: 'one still owed', owed: ['beta'], accepted: false },
- { what: 'every one still owed', owed: ['beta', 'gamma'], accepted: false },
- ];
- const SUBJECT = [
- { what: 'the write it refused', baseline: BASELINE, requested: REQUESTED, same: true },
- { what: 'a draft that removed more since', baseline: BASELINE, requested: [], same: false },
- { what: 'a draft that put a row back', baseline: BASELINE, requested: BASELINE, same: false },
- { what: 'a draft that added a row', baseline: BASELINE, requested: [...REQUESTED, model('delta')], same: false },
- { what: 'the same ids, one row edited', baseline: BASELINE, requested: [model('alpha', { display_name: 'Alpha' })], same: false },
- { what: 'a newer server catalog', baseline: [...BASELINE, model('delta')], requested: REQUESTED, same: false },
- ];
- const cells = ACCEPTANCE.flatMap((acceptance) => SUBJECT.map((subject) => ({
- what: `${acceptance.what} · ${subject.what}`,
- echoable: echoableRefusal(stored(acceptance.owed), subject.baseline, subject.requested),
- accepted: acceptance.accepted,
- same: subject.same,
- })));
- expect(cells.filter((cell) => cell.echoable !== (cell.accepted && cell.same))).toEqual([]);
- // And the product is the whole point: neither fact on its own permits an
- // echo, so exactly one cell of the matrix does.
- expect(cells.filter((cell) => cell.echoable).map((cell) => cell.what))
- .toEqual(['every question answered · the write it refused']);
- });
-
- it('permits nothing when there is no refusal to echo', () => {
- // The state a fresh dialog saves from, and the one it returns to after a
- // reopen: there is no server plan, so there is nothing to force.
- expect(echoableRefusal(null, BASELINE, REQUESTED)).toBe(false);
- });
-});
diff --git a/ui/src/components/settings/models/backendCatalog.ts b/ui/src/components/settings/models/backendCatalog.ts
index 6786fb3d3..97dd8129d 100644
--- a/ui/src/components/settings/models/backendCatalog.ts
+++ b/ui/src/components/settings/models/backendCatalog.ts
@@ -466,70 +466,6 @@ export const sameBackendModel = (left: BackendModel, right: BackendModel): boole
export const sameCatalog = (left: readonly BackendModel[], right: readonly BackendModel[]): boolean =>
left.length === right.length && left.every((model, index) => sameBackendModel(model, right[index]));
-/** A value written so that two equal values always read the same: object keys in
- * one fixed order, absent and undefined fields spelled the same way. */
-const canonicalJson = (value: unknown): string => {
- if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
- if (value !== null && typeof value === 'object') {
- const fields = Object.entries(value as Record<string, unknown>)
- .filter(([, field]) => field !== undefined)
- .sort(([left], [right]) => (left < right ? -1 : 1));
- return `{${fields.map(([key, field]) => `${JSON.stringify(key)}:${canonicalJson(field)}`).join(',')}}`;
- }
- return JSON.stringify(value) ?? 'null';
-};
-
-/**
- * Whether two halves of a guard plan name the same consequences, in whatever
- * order each of them happens to list them.
- *
- * It exists for one decision and produces nothing that is sent: it answers
- * 「is the server's refusal the one the user already confirmed?」, so a retry
- * that would ask the same question twice can be automatic instead. The arrays
- * the client echoes with `force` are always the server's own, verbatim and in
- * the server's order (C3) — which is exactly why comparing as a set is safe
- * here. Both orders are legitimate: the client's preview follows the order the
- * user clicked, the server's follows its own walk of the baseline, and neither
- * is a disagreement about what would happen.
- *
- * Only that outer list is read as a set. A list nested inside one element — a
- * gap's `agents`, say — has no such story: one side produced it, so an order
- * that differs there is a real change and the user is asked again. Strictness
- * costs a question; laxity would skip one.
- */
-export const samePlanContents = (left: readonly unknown[], right: readonly unknown[]): boolean =>
- left.length === right.length
- && sameList(left.map(canonicalJson).sort(), right.map(canonicalJson).sort());
-
-/**
- * Whether a stored guard refusal may still be echoed back with `force`.
- *
- * `force` is the client saying 「the user has been shown this consequence and
- * still wants it」, and two independent things have to be true before it can
- * say that honestly. `owed` empty is the acceptance: every removal the server
- * refused has been put to the user and confirmed. The two catalogs are the
- * subject: the refusal answers *this* save — same starting point, same request
- * — and not a later, different one.
- *
- * Neither implies the other, so neither alone is enough. A refusal the user
- * never answered must not be forced however exactly its catalogs match, and an
- * accepted one must not be carried onto a save it was never about. Either way
- * the fallback is the same and is not a failure: the save goes out unforced and
- * the server asks again.
- */
-export const echoableRefusal = (
- refusal: {
- baseline: readonly BackendModel[];
- models: readonly BackendModel[];
- owed: ReadonlySet<string>;
- } | null,
- baseline: readonly BackendModel[],
- requested: readonly BackendModel[],
-): boolean => refusal !== null
- && refusal.owed.size === 0
- && sameCatalog(refusal.baseline, baseline)
- && sameCatalog(refusal.models, requested);
-
export type BackendCatalogIntent = {
removed: ReadonlySet<string>;
/** Rows this caller added or changed, keyed by id. */
@@ -557,41 +493,6 @@ export const backendCatalogIntent = (
};
};
-/**
- * An order with cancelled removals put back where they were.
- *
- * A removal the server refuses was never a decision, so undoing it may not cost
- * the row its place: the requested order is the list with the row already gone,
- * and appending it back would answer 「are you sure?」 with a reordered catalog
- * the user never asked for. The baseline is what says where it belongs — each
- * restored id goes back after its nearest baseline predecessor that is still on
- * screen, or at the front when it had none — so a removal that is cancelled
- * leaves the draft byte-identical to the baseline, and the position is recovered
- * from the two lists rather than from a snapshot somebody has to remember to
- * take.
- *
- * Only the restored ids move. Anything else the user did to the order is a
- * separate edit the refusal said nothing about, and an independent reorder is
- * still theirs afterwards — which is why the baseline is read for positions
- * rather than replayed as the order. Walking the baseline in its own order is
- * what keeps two restored neighbours in their original sequence, since the
- * earlier one is on screen by the time the later one looks for its anchor.
- */
-export const orderWithRestored = (
- requested: readonly string[],
- baseline: readonly string[],
- restored: ReadonlySet<string>,
-): string[] => {
- const order = requested.filter((id) => !restored.has(id));
- const before = new Map(baseline.map((id, index) => [id, baseline.slice(0, index)]));
- for (const id of baseline) {
- if (!restored.has(id)) continue;
- const anchor = [...(before.get(id) ?? [])].reverse().find((previous) => order.includes(previous));
- order.splice(anchor === undefined ? 0 : order.indexOf(anchor) + 1, 0, id);
- }
- return order;
-};
-
/**
* The user's edits, replayed onto a newer catalog.
*
diff --git a/ui/src/components/settings/models/guardedWrite.ts b/ui/src/components/settings/models/guardedWrite.ts
new file mode 100644
index 000000000..bd288323d
--- /dev/null
+++ b/ui/src/components/settings/models/guardedWrite.ts
@@ -0,0 +1,43 @@
+import type { GuardPlan } from './GuardImpact';
+import { apiFailure, type GuardConfirmation } from './modelsApi';
+
+/** The confirmation a forced write echoes: the server's own plan, verbatim. */
+export const confirmGuardPlan = (plan: GuardPlan): GuardConfirmation => ({
+ force: true,
+ would_remove_hops: plan.hops,
+ would_interrupt: plan.gaps,
+});
+
+/** The plan a guard refusal names, or null when the failure is anything else. */
+export const guardedFailure = (error: unknown): GuardPlan | null => {
+ const failure = apiFailure(error);
+ if (!failure || (failure.wouldRemoveHops.length === 0 && failure.wouldInterrupt.length === 0)) return null;
+ return { hops: failure.wouldRemoveHops, gaps: failure.wouldInterrupt };
+};
+
+const FORCED_RESENDS = 2;
+
+/**
+ * Send a guarded write, echoing `plan` as its confirmation when there is one.
+ *
+ * Once the user has `agreed`, a guard that refuses the write names the plan as
+ * it stands now, and that answer already covers it: the write goes again with
+ * the new plan rather than asking the same question twice. Bounded, so a plan
+ * that never settles still ends as the refusal it is. `write` receives the plan
+ * each attempt echoes, so a caller can tell which one its outcome belongs to.
+ */
+export const sendAgreed = async <T,>(
+ agreed: boolean,
+ plan: GuardPlan | null,
+ write: (plan: GuardPlan | null) => Promise<T>,
+): Promise<T> => {
+ for (let resends = 0; ; resends += 1) {
+ try {
+ return await write(plan);
+ } catch (error) {
+ const moved = agreed && resends < FORCED_RESENDS ? guardedFailure(error) : null;
+ if (!moved) throw error;
+ plan = moved;
+ }
+ }
+};
diff --git a/ui/src/components/settings/models/manage.test.ts b/ui/src/components/settings/models/manage.test.ts
index bf380cc8c..de9f88667 100644
--- a/ui/src/components/settings/models/manage.test.ts
+++ b/ui/src/components/settings/models/manage.test.ts
@@ -167,7 +167,7 @@ describe('source management capabilities', () => {
submitting_edit: { kind: 'submitting_edit', draft, patch, plan: null, forced: false, surface: 'edit' },
confirming_edit: { kind: 'confirming_edit', draft, patch, plan },
edit_failed: { kind: 'edit_failed', draft, patch, plan, forced: true, retryRead: true, before },
- confirming_delete: { kind: 'confirming_delete', plan },
+ confirming_delete: { kind: 'confirming_delete' },
submitting_delete: { kind: 'submitting_delete', plan, forced: true },
delete_failed: { kind: 'delete_failed', plan, forced: true, retryRead: true, before },
committed_edit: { kind: 'committed_edit' },
diff --git a/ui/src/components/settings/models/manage.ts b/ui/src/components/settings/models/manage.ts
index 43d494ddf..e82934d15 100644
--- a/ui/src/components/settings/models/manage.ts
+++ b/ui/src/components/settings/models/manage.ts
@@ -60,7 +60,7 @@ export type ManageStage =
| { kind: 'submitting_edit'; draft: SourceEditDraft; patch: SourcePatch; plan: ManageGuardPlan | null; forced: boolean; surface: 'edit' | 'guard' }
| { kind: 'confirming_edit'; draft: SourceEditDraft; patch: SourcePatch; plan: ManageGuardPlan }
| { kind: 'edit_failed'; draft: SourceEditDraft; patch: SourcePatch; plan: ManageGuardPlan | null; forced: boolean; retryRead: boolean; before: Source }
- | { kind: 'confirming_delete'; plan: ManageGuardPlan | null }
+ | { kind: 'confirming_delete' }
| { kind: 'submitting_delete'; plan: ManageGuardPlan | null; forced: boolean }
| { kind: 'delete_failed'; plan: ManageGuardPlan | null; forced: boolean; retryRead: boolean; before: Source }
| { kind: 'committed_edit' }
@@ -118,11 +118,7 @@ export const MANAGE_STAGE_RETRY = {
forced: stage.forced,
surface: 'edit',
}),
- confirming_delete: (stage) => ({
- kind: 'submitting_delete',
- plan: stage.plan,
- forced: stage.plan !== null,
- }),
+ confirming_delete: () => ({ kind: 'submitting_delete', plan: null, forced: false }),
submitting_delete: keepManageStage,
delete_failed: (stage) => ({
kind: 'submitting_delete',
@@ -179,7 +175,6 @@ export type ManageStageEvent =
| { type: 'submit_edit'; draft: SourceEditDraft; patch: SourcePatch; plan: ManageGuardPlan | null; surface: 'edit' | 'guard' }
| { type: 'submit_delete'; plan: ManageGuardPlan | null }
| { type: 'guard_edit'; draft: SourceEditDraft; patch: SourcePatch; plan: ManageGuardPlan }
- | { type: 'guard_delete'; plan: ManageGuardPlan }
| { type: 'fail_edit'; draft: SourceEditDraft; patch: SourcePatch; plan: ManageGuardPlan | null; forced: boolean; retryRead: boolean; before: Source }
| { type: 'fail_delete'; plan: ManageGuardPlan | null; forced: boolean; retryRead: boolean; before: Source }
| { type: 'commit'; action: ManageCommitAction }
@@ -201,7 +196,7 @@ const applyManageStageTransition = <Event,>(
export const transitionManageStage = (stage: ManageStage, event: ManageStageEvent): ManageStage => {
switch (event.type) {
case 'begin_edit': return { kind: 'editing', draft: event.draft };
- case 'begin_delete': return { kind: 'confirming_delete', plan: null };
+ case 'begin_delete': return { kind: 'confirming_delete' };
case 'submit_edit': return {
kind: 'submitting_edit',
draft: event.draft,
@@ -221,7 +216,6 @@ export const transitionManageStage = (stage: ManageStage, event: ManageStageEven
patch: event.patch,
plan: event.plan,
};
- case 'guard_delete': return { kind: 'confirming_delete', plan: event.plan };
case 'fail_edit': return {
kind: 'edit_failed',
draft: event.draft,
diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.css
index 7842f3eb3..297371045 100644
--- a/ui/src/components/settings/models/modelHubSurface.css
+++ b/ui/src/components/settings/models/modelHubSurface.css
@@ -1598,12 +1598,11 @@
dialog's own chrome — head, title, subtitle, close, foot, action — has one
reader each, so each metric sits on the class that reads it. The evidence
BODY below is a different kind of thing: `GuardImpact` and `GuardGapList` are
- shared, and they mount inside four separate dialogs — this one, the catalog
- dialog's in-row removal confirmation, the Add-key replace phase, and the
- route chain's guard phase. A body token declared on this root reached exactly
- one of them; in the other three `var()` named a property no ancestor
- declares, which is invalid at computed-value time, so the declaration drew
- nothing: the label lost its gap AND its size, and the count lost its padding
+ shared, and they also mount outside this dialog — in the catalog dialog's
+ focused removal confirmation, which is a plain ConfirmDialog. A body token
+ declared on this root would reach only this dialog; elsewhere `var()` would
+ name a property no ancestor declares, which is invalid at computed-value
+ time, so the declaration would draw nothing: the label lost its gap AND its size, and the count lost its padding
AND its size, which is not a pill missing a margin but 「Hops that will be
removed2 hops」 in one unbroken run at the inherited font.
@@ -3351,12 +3350,6 @@
background: var(--model-hub-catalog-row-locked-fill);
}
.model-hub-catalog-row--static { min-height: 48px; }
-/* A row being asked about is the row the answer applies to, so the question
- * stays inside it and the stronger border says which one is waiting. */
-.model-hub-catalog-row.is-confirming { border-color: var(--border-strong); }
-.model-hub-catalog-row.is-confirming .model-hub-catalog-action--danger {
- background: var(--model-hub-wash-14);
-}
.model-hub-catalog-grip {
display: inline-flex;
@@ -3418,25 +3411,9 @@
font-weight: 600;
color: var(--model-hub-danger-ink);
}
-/* The removal question, drawn as the row's own lower half: full-bleed to the
- * row's border on three sides, which is why the negative margins are the row's
- * own padding tokens rather than numbers. */
-.model-hub-catalog-confirm {
- display: flex;
- flex-direction: column;
- gap: 10px;
- margin:
- var(--model-hub-catalog-row-pad-y)
- calc(-1 * var(--model-hub-catalog-row-pad-x))
- calc(-1 * var(--model-hub-catalog-row-pad-y));
- padding: 12px var(--model-hub-catalog-row-pad-x);
- border-top: 1px solid var(--border);
- background: var(--model-hub-wash-05);
-}
-/* The guard's evidence, at row scale. The body is the same one the Route dialog
- * shows and brings its own parts, so this only has to stack them and set the
- * scale — the dialog's own wrapper is sized for a dialog and would push the row
- * open. Same gap as the question it sits in. */
+/* The guard's evidence inside the focused removal's confirmation. The body is
+ * the same one the guard dialog shows and brings its own parts, so this only has
+ * to stack them and set the scale. */
.model-hub-catalog-consequence {
--model-hub-catalog-consequence-size: 12px;
display: flex;
@@ -3445,12 +3422,6 @@
font-size: var(--model-hub-catalog-consequence-size);
color: var(--foreground);
}
-.model-hub-catalog-confirm-action {
- --model-hub-catalog-confirm-pad-x: 14px;
- --model-hub-catalog-confirm-height: 32px;
- height: var(--model-hub-catalog-confirm-height);
- padding: 0 var(--model-hub-catalog-confirm-pad-x);
-}
.model-hub-catalog-legacy {
padding: 0 2px 4px;
diff --git a/ui/src/components/settings/models/repair.ts b/ui/src/components/settings/models/repair.ts
index bc0696ff4..bcd660bc0 100644
--- a/ui/src/components/settings/models/repair.ts
+++ b/ui/src/components/settings/models/repair.ts
@@ -237,11 +237,11 @@ export const repairOutcome = (tail: SourceRepaired): RepairOutcome =>
* Provable from the tail alone: 「nothing was stranded, and the source came back
* working」 is two fields the server sends.
*
- * An allowlist rather than `!== 'gaps'`: L4's rule is that the 1.4s dismissal is
- * for a plain success and 「every other verdict leaves an instruction on screen
- * that 1.4s is not long enough to read」. Written as an exclusion, the next verdict
- * added would inherit the auto-close silently, which is the wrong default for a
- * verdict that exists because something did not work.
+ * An allowlist rather than `!== 'gaps'`: a plain success closes on its toast,
+ * and every other verdict leaves an instruction on screen that a toast cannot
+ * hold. Written as an exclusion, the next verdict added would inherit the close
+ * silently, which is the wrong default for a verdict that exists because
+ * something did not work.
*/
export const repairSettles = (outcome: RepairOutcome): boolean =>
outcome.kind === 'repaired' || outcome.kind === 'refreshed';
diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsx
index 422b46eff..8f1ca7707 100644
--- a/ui/src/components/steps/AgentDetection.tsx
+++ b/ui/src/components/steps/AgentDetection.tsx
@@ -138,7 +138,6 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
// Which backend's "Configure provider" modal is open (wizard mode only).
const [providerModal, setProviderModal] = useState<{ backend: RuntimeBackendId; method: 'oauth' | 'api_key' } | null>(null);
const [routeSelection, setRouteSelection] = useState<RouteChainSelection | null>(null);
- const [routeReconciliation, setRouteReconciliation] = useState({ pending: false, failed: false });
const committedRouteRefresh = useRef(false);
const canEditSetupRoute = Boolean(onNavigate && agentReads);
const [routeRead, setRouteRead] = useState<{
@@ -1032,15 +1031,10 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
}}
onCommitted={() => {
committedRouteRefresh.current = true;
- setRouteReconciliation({ pending: true, failed: false });
- if (routeSelection) void refreshRouteOwnership(routeSelection.agent.backend)
- .then((ok) => setRouteReconciliation({ pending: false, failed: !ok }));
+ if (routeSelection) void refreshRouteOwnership(routeSelection.agent.backend);
+ // The dialog closes on commit, so the shared toast is the save's only report.
+ showToast(t('common.saved'), 'success');
}}
- commitReconciliation={{ ...routeReconciliation, retry: () => {
- setRouteReconciliation({ pending: true, failed: false });
- if (routeSelection) void refreshRouteOwnership(routeSelection.agent.backend)
- .then((ok) => setRouteReconciliation({ pending: false, failed: !ok }));
- } }}
readAgents={async () => {
const value = await agentReads.readValue();
return { value, install: () => setRouteRead((current) => ({ ...current, supplies: value })) };
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 0913e9d49..234eb53f7 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1023,6 +1023,8 @@
"reorder": "Reorder {{model}}",
"removeConfirm": "Remove",
"removeTitle": "Remove {{model}}?",
+ "guardTitle": "Save the model list?",
+ "guardSubtitle": "Removing these models also removes their routes.",
"empty": "No models yet. Add the first one.",
"noMatch": "No model matches this search",
"legacy": "This model engine build does not offer an editable model list yet. These are the models it currently exposes.",
@@ -1760,7 +1762,6 @@
"cancel": "Cancel",
"save": "Save",
"saving": "Saving route chain…",
- "refreshing": "Route chain saved. Refreshing…",
"fail": {
"read": "The route chain could not be read",
"save": "The route chain was not saved",
@@ -1770,10 +1771,7 @@
"retry": "Retry",
"empty": "This model follows default routing, but no eligible provider can route it.",
"impact": {
- "title": "The route chain was saved",
- "detail": "These are the items this save actually removed or interrupted.",
- "refreshFail": "The route chain was saved, but the display could not be refreshed.",
- "done": "Done"
+ "refreshFail": "The route chain was saved, but the display could not be refreshed."
},
"hint": "This model has a saved, fixed route. Default routing changes do not overwrite it.",
"mode": {
@@ -1969,11 +1967,6 @@
"noSources": "On the gateway · no source enabled yet, the next turn will fail",
"nothingRunnable": "On the gateway · no enabled source can serve right now, the next turn will fail"
},
- "adoption": {
- "enabled": "Added to {{list}}",
- "route": "{{backend}} · {{model}} · hop {{position}}",
- "none": "Connected. Add it to a model's route when you want to use it."
- },
"supplyMode": {
"title": "Supply mode",
"currentHub": "Current: Gateway",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 08d4d2a48..1635da9c4 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1023,6 +1023,8 @@
"reorder": "调整 {{model}} 的顺序",
"removeConfirm": "移除",
"removeTitle": "移除 {{model}}?",
+ "guardTitle": "保存模型列表?",
+ "guardSubtitle": "移除这些模型会同时移除它们的路由。",
"empty": "还没有模型,先添加一个。",
"noMatch": "没有匹配的模型",
"legacy": "当前模型引擎版本还不支持编辑模型列表,以下是它当前提供的模型。",
@@ -1760,7 +1762,6 @@
"cancel": "取消",
"save": "保存",
"saving": "正在保存路由…",
- "refreshing": "路由已保存,正在刷新…",
"fail": {
"read": "路由暂时不可用",
"save": "路由没有保存",
@@ -1770,10 +1771,7 @@
"retry": "重试",
"empty": "此模型跟随默认路由,但目前没有符合条件的供应商。",
"impact": {
- "title": "路由已保存",
- "detail": "以下是这次保存实际移除或中断的项目。",
- "refreshFail": "路由已保存,但暂时无法刷新显示。",
- "done": "完成"
+ "refreshFail": "路由已保存,但暂时无法刷新显示。"
},
"hint": "此模型已保存固定路由,默认路由的调整不会覆盖它。",
"mode": {
@@ -1969,11 +1967,6 @@
"noSources": "已接入模型网关 · 还没有启用任何供应商,下一个回合会失败",
"nothingRunnable": "已接入模型网关 · 已启用的供应商当前都不可用,下一个回合会失败"
},
- "adoption": {
- "enabled": "已加入 {{list}}",
- "route": "{{backend}} · {{model}} · 第 {{position}} 个路由项",
- "none": "已连接。需要使用时,把它加到对应模型的路由中。"
- },
"supplyMode": {
"title": "模型管理方式",
"currentHub": "当前:模型网关",