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.

feat(model-hub): simplify route dialog layout (#2208)

Call Whiteb7fac11890b2
diff --git a/ui/e2e/d-routing.spec.ts b/ui/e2e/d-routing.spec.ts
index eb146726c..7f7da29e4 100644
--- a/ui/e2e/d-routing.spec.ts
+++ b/ui/e2e/d-routing.spec.ts
@@ -13,7 +13,7 @@ test.describe('D: inherited routes, manual editing, and default routing', () =>
await requireMockUpstream(mock);
});
- test('D: inherited routes are directly editable without pinning from inspection', async ({ api, hub, gateway, page }) => {
+ test('D: inherited routes open read only and are never pinned from inspection', async ({ api, hub, gateway, page }) => {
const original = await captureAgentChain(api, gateway);
try {
expect(await api.deleteAgentChain(gateway.backend, gateway.model)).toBe(true);
@@ -21,8 +21,9 @@ test.describe('D: inherited routes, manual editing, and default routing', () =>
await hub.openRoute(gateway.backend, gateway.model);
const dialog = hub.routeDialog;
await expect(dialog).toBeVisible();
- await expect(dialog.getByRole('button', { name: copy('routeDialog.addHop'), exact: true })).toBeVisible();
- await expect(dialog.getByRole('button', { name: copy('routeDialog.grip'), exact: true }).first()).toBeVisible();
+ await expect(dialog.getByRole('radio', { name: copy('routeDialog.mode.follow'), exact: true })).toHaveAttribute('aria-checked', 'true');
+ await expect(dialog.getByRole('button', { name: copy('routeDialog.addHop'), exact: true })).toHaveCount(0);
+ await expect(dialog.getByRole('button', { name: copy('routeDialog.grip'), exact: true })).toHaveCount(0);
await expect(labelledButton(dialog, copy('routeDialog.save'))).toBeDisabled();
await labelledButton(dialog, copy('routing.close')).click();
await expect(dialog).toHaveCount(0);
@@ -58,10 +59,10 @@ test.describe('D: inherited routes, manual editing, and default routing', () =>
y: labelBox!.y + labelBox!.height / 2 - openerBox!.y,
} });
await expect(dialog).toBeVisible();
+ expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toBeNull();
+ await dialog.getByRole('radio', { name: copy('routeDialog.mode.custom'), exact: true }).click();
await expect(dialog.getByRole('button', { name: copy('routeDialog.addHop'), exact: true })).toBeVisible();
await expect(dialog.getByRole('button', { name: copy('routeDialog.grip'), exact: true }).first()).toBeVisible();
- expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toBeNull();
- await labelledButton(dialog, copy('routing.pinRoute')).click();
await expect(labelledButton(dialog, copy('routeDialog.save'))).toBeEnabled();
await labelledButton(dialog, copy('routing.cancelChanges')).click();
await expect(dialog).toBeVisible();
diff --git a/ui/e2e/model-catalog/route-direct-edit.spec.ts b/ui/e2e/model-catalog/route-direct-edit.spec.ts
index 11800f4cd..d6e3e2e2f 100644
--- a/ui/e2e/model-catalog/route-direct-edit.spec.ts
+++ b/ui/e2e/model-catalog/route-direct-edit.spec.ts
@@ -8,6 +8,22 @@ const settled = (panel: Locator) => panel.evaluate(async (element: HTMLElement)
await Promise.all(element.getAnimations({ subtree: true }).map((animation) => animation.finished));
});
+// Rows are editable only on a custom route. On a phone the two row actions fold
+// into one menu, so every spec reaches them through the same path either way.
+const enterCustom = async (dialog: Locator, copy: (key: string) => string) => {
+ const custom = dialog.getByRole('radio', { name: copy('routeDialog.mode.custom'), exact: true });
+ if (await custom.getAttribute('aria-checked') !== 'true') await custom.click();
+ await expect(custom).toHaveAttribute('aria-checked', 'true');
+};
+const hopAction = async (dialog: Locator, copy: (key: string) => string, action: 'editHop' | 'removeHop', index = 0) => {
+ const page = dialog.page();
+ const direct = dialog.getByRole('button', { name: copy(`routeDialog.${action}`), exact: true });
+ if (await dialog.getByRole('button', { name: copy('routeDialog.hopActions'), exact: true }).count()) {
+ await dialog.getByRole('button', { name: copy('routeDialog.hopActions'), exact: true }).nth(index).click();
+ await page.getByRole('menuitem', { name: copy(`routeDialog.${action}`), exact: true }).click();
+ } else await direct.nth(index).click();
+};
+
for (const backend of ['claude', 'codex', 'opencode']) {
for (const lang of ['en', 'zh'] as const) {
for (const origin of ['automatic', 'passthrough', 'manual']) {
@@ -24,18 +40,26 @@ for (const backend of ['claude', 'codex', 'opencode']) {
const save = foot.getByRole('button', { name: copy('routeDialog.save'), exact: true });
const state = async () => JSON.parse(await page.getByTestId('route-state').innerText());
const baseline = (await state()).saved;
- await expect(dialog.getByRole('button', { name: copy('routeDialog.editHop'), exact: true })).toHaveCount(2);
+ await expect(dialog.locator('.model-hub-route-hop')).toHaveCount(2);
await expect(save).toBeDisabled();
+ // An inherited route is read only until the explicit Custom switch.
+ const inherited = origin !== 'manual';
+ await expect(dialog.locator('.model-hub-route-hop[data-editable]')).toHaveCount(inherited ? 0 : 2);
+ await enterCustom(dialog, copy);
+ await expect(dialog.locator('.model-hub-route-hop[data-editable]')).toHaveCount(2);
+ if (inherited) await expect(save).toBeEnabled();
+ else await expect(save).toBeDisabled();
// Real nested portal/touch dismissal must leave the parent and intent intact.
- await dialog.getByRole('button', { name: copy('routeDialog.editHop'), exact: true }).first().click();
+ await hopAction(dialog, copy, 'editHop');
await expect(page.locator('.model-hub-route-selector')).toBeVisible();
await page.keyboard.press('Escape');
await expect(page.locator('.model-hub-route-selector')).toHaveCount(0);
await expect(dialog).toBeVisible();
- await expect(save).toBeDisabled();
+ if (inherited) await expect(save).toBeEnabled();
+ else await expect(save).toBeDisabled();
- await dialog.getByRole('button', { name: copy('routeDialog.removeHop'), exact: true }).first().click();
+ await hopAction(dialog, copy, 'removeHop');
await expect(dialog.locator('.model-hub-route-hop-name')).toHaveText(['Provider B']);
await expect(save).toBeEnabled();
await foot.getByRole('button', { name: copy('routing.cancelChanges'), exact: true }).click();
@@ -46,7 +70,8 @@ for (const backend of ['claude', 'codex', 'opencode']) {
expect((await state()).saved).toEqual(baseline);
expect((await state()).writes).toEqual([]);
- await dialog.getByRole('button', { name: copy('routeDialog.editHop'), exact: true }).first().click();
+ await enterCustom(dialog, copy);
+ await hopAction(dialog, copy, 'editHop');
const selector = page.locator('.model-hub-route-selector');
await selector.getByRole('button', { name: copy('routeDialog.add.manual'), exact: true }).click();
await selector.getByLabel(copy('routing.exactModel'), { exact: true }).fill('exact/model-中文');
@@ -88,7 +113,7 @@ for (const lang of ['en', 'zh'] as const) {
expect(footBox!.y + footBox!.height).toBeLessThanOrEqual(page.viewportSize()!.height);
const overflow = await dialog.evaluate((element) => {
const box = element.getBoundingClientRect();
- return [...element.querySelectorAll<HTMLElement>('.model-hub-route-foot button, .model-hub-route-hop, .model-hub-route-origin-line, .model-hub-route-title')]
+ return [...element.querySelectorAll<HTMLElement>('.model-hub-route-foot button, .model-hub-route-hop, .model-hub-route-mode, .model-hub-route-pending, .model-hub-route-title')]
.filter((node) => {
const rect = node.getBoundingClientRect();
return rect.left < box.left - 1 || rect.right > box.right + 1
@@ -100,7 +125,8 @@ for (const lang of ['en', 'zh'] as const) {
};
await checkGeometry();
await page.screenshot({ path: test.info().outputPath(`route-${lang}-${theme}-clean.png`), scale: 'css' });
- await foot.getByRole('button', { name: copy('routing.pinRoute'), exact: true }).click();
+ await enterCustom(dialog, copy);
+ await expect(dialog.locator('.model-hub-route-pending')).toBeVisible();
await expect(save).toBeEnabled();
await checkGeometry();
await page.screenshot({ path: test.info().outputPath(`route-${lang}-${theme}-dirty.png`), scale: 'css' });
@@ -136,6 +162,7 @@ for (const lang of ['en', 'zh'] as const) {
const dialogBox = (await dialog.boundingBox())!;
expect(Math.abs(dialogBox.y + dialogBox.height / 2 - viewport.height / 2)).toBeLessThanOrEqual(1);
+ await enterCustom(dialog, copy);
await dialog.getByRole('button', { name: copy('routeDialog.addHop'), exact: true }).click();
const selector = page.locator('.model-hub-route-selector');
await expect(selector).toBeVisible();
@@ -177,6 +204,7 @@ test('MH-ROUTING-007: a panel with nothing to type by hand is a band shorter', a
await page.getByRole('button', { name: 'Open route', exact: true }).click();
const dialog = page.locator('.model-hub-route-dialog');
await expect(dialog.locator('.model-hub-route-hop')).toHaveCount(2);
+ await enterCustom(dialog, (key) => hub(key, {}, 'en'));
await dialog.getByRole('button', { name: hub('routeDialog.addHop', {}, 'en'), exact: true }).click();
const selector = page.locator('.model-hub-route-selector');
await expect(selector).toBeVisible();
@@ -216,6 +244,7 @@ for (const lang of ['en', 'zh'] as const) {
await page.getByRole('button', { name: 'Open route', exact: true }).click();
const dialog = page.locator('.model-hub-route-dialog');
await expect(dialog.locator('.model-hub-route-hop')).toHaveCount(2);
+ await enterCustom(dialog, copy);
await dialog.getByRole('button', { name: copy('routeDialog.addHop'), exact: true }).click();
const selector = page.locator('.model-hub-route-selector');
await expect(selector).toBeVisible();
@@ -292,7 +321,8 @@ for (const [label, width] of [['small', 390], ['large', 430]] as const) {
await page.goto('/e2e/model-catalog/fixture.html?view=route&backend=codex&lang=zh&stocked=1');
await page.getByRole('button', { name: 'Open route', exact: true }).click();
const dialog = page.locator('.model-hub-route-dialog');
- await dialog.getByRole('button', { name: copy('routeDialog.editHop'), exact: true }).first().click();
+ await enterCustom(dialog, copy);
+ await hopAction(dialog, copy, 'editHop');
const selector = page.locator('.model-hub-route-selector');
await expect(selector).toBeVisible();
await settled(selector);
@@ -350,7 +380,8 @@ test('MH-ROUTING-007: the picker keeps each source beside its own models', async
await page.goto('/e2e/model-catalog/fixture.html?view=route&backend=codex&lang=zh&stocked=1');
await page.getByRole('button', { name: 'Open route', exact: true }).click();
const dialog = page.locator('.model-hub-route-dialog');
- await dialog.getByRole('button', { name: copy('routeDialog.editHop'), exact: true }).first().click();
+ await enterCustom(dialog, copy);
+ await hopAction(dialog, copy, 'editHop');
const selector = page.locator('.model-hub-route-selector');
await expect(selector).toBeVisible();
await settled(selector);
@@ -407,7 +438,8 @@ test('MH-ROUTING-007: the pinned source does not take the row\'s clicks', async
await page.goto('/e2e/model-catalog/fixture.html?view=route&backend=codex&lang=zh&stocked=1');
await page.getByRole('button', { name: 'Open route', exact: true }).click();
const dialog = page.locator('.model-hub-route-dialog');
- await dialog.getByRole('button', { name: copy('routeDialog.editHop'), exact: true }).first().click();
+ await enterCustom(dialog, copy);
+ await hopAction(dialog, copy, 'editHop');
const selector = page.locator('.model-hub-route-selector');
await expect(selector).toBeVisible();
await settled(selector);
@@ -446,7 +478,8 @@ test('MH-ROUTING-007: a candidate row reads as clickable', async ({ page }) => {
await page.goto('/e2e/model-catalog/fixture.html?view=route&backend=codex&lang=zh&stocked=1');
await page.getByRole('button', { name: 'Open route', exact: true }).click();
const dialog = page.locator('.model-hub-route-dialog');
- await dialog.getByRole('button', { name: copy('routeDialog.editHop'), exact: true }).first().click();
+ await enterCustom(dialog, copy);
+ await hopAction(dialog, copy, 'editHop');
const selector = page.locator('.model-hub-route-selector');
await expect(selector).toBeVisible();
diff --git a/ui/e2e/model-routing-origin.spec.ts b/ui/e2e/model-routing-origin.spec.ts
index 878c4515e..892037706 100644
--- a/ui/e2e/model-routing-origin.spec.ts
+++ b/ui/e2e/model-routing-origin.spec.ts
@@ -5,7 +5,7 @@ import { expect, test } from './support/gateway';
import { labelledButton } from './support/hub';
import { captureAgentChain, restoreAgentChain } from './support/restore';
-test('MH-ROUTING-007 restore, undo, cancel, and save preserve explicit route intent', async ({ api, gateway, hub, page }) => {
+test('MH-ROUTING-007 follow-defaults switch, undo, cancel, and save preserve explicit route intent', async ({ api, gateway, hub, page }) => {
const original = await captureAgentChain(api, gateway);
const originalOrder = await api.defaultSourceOrder(gateway.backend);
const manual = { hops: [{ source_id: gateway.sources[0].id, model_id: `${gateway.model}/manual-original` }] };
@@ -43,20 +43,23 @@ test('MH-ROUTING-007 restore, undo, cancel, and save preserve explicit route int
expect(body.chain.manual_override).toBeNull();
expect(body.chain.route_origin).toBe(inherited.route_origin);
expect(identities(body.chain)).toEqual(identities(inherited));
- await expect(dialog.locator('.model-hub-route-preview')).toHaveAttribute('data-origin', inherited.route_origin!);
+ await expect(dialog.locator('.model-hub-route-pending')).toHaveAttribute('data-origin', inherited.route_origin!);
await expect(dialog.locator('.model-hub-route-hop-model')).toHaveText(inherited.chain.map((hop) => hop.model_id));
- await expect(labelledButton(dialog, copy('routing.undoRestore'))).toBeEnabled();
+ await expect(undo()).toBeEnabled();
await expect(labelledButton(dialog, copy('routeDialog.save'))).toBeEnabled();
expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toEqual(manual);
expect(mutations).toEqual([]);
};
+ const follow = dialog.getByRole('radio', { name: copy('routeDialog.mode.follow'), exact: true });
+ const custom = dialog.getByRole('radio', { name: copy('routeDialog.mode.custom'), exact: true });
+ const undo = () => labelledButton(dialog.locator('.model-hub-route-pending'), copy('routeDialog.mode.undo'));
const removeLast = async () => {
await expect(dialog.locator('.model-hub-route-hop')).toHaveCount(1);
await preview(() => dialog.getByRole('button', { name: copy('routeDialog.removeHop'), exact: true }).press('Enter'));
};
- await preview(() => labelledButton(dialog, copy('routing.restoreAutomatic')).click());
- await labelledButton(dialog, copy('routing.undoRestore')).click();
- await expect(labelledButton(dialog, copy('routing.restoreAutomatic'))).toBeVisible();
+ await preview(() => follow.click());
+ await undo().click();
+ await expect(custom).toHaveAttribute('aria-checked', 'true');
await expect(dialog.locator('.model-hub-route-hop-model')).toHaveText([manual.hops[0].model_id]);
expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toEqual(manual);
expect(mutations).toEqual([]);
@@ -75,7 +78,7 @@ test('MH-ROUTING-007 restore, undo, cancel, and save preserve explicit route int
await expect(dialog.locator('.model-hub-route-hop-name')).toHaveText([gateway.sources[0].display_name]);
await expect(dialog.locator('.model-hub-route-hop-model')).toHaveText([unsavedModel]);
await removeLast();
- await labelledButton(dialog, copy('routing.undoRestore')).click();
+ await undo().click();
await expect(dialog.locator('.model-hub-route-hop-name')).toHaveText([gateway.sources[0].display_name]);
await expect(dialog.locator('.model-hub-route-hop-model')).toHaveText([unsavedModel]);
await removeLast();
@@ -122,8 +125,8 @@ test('MH-ROUTING-007 restore, undo, cancel, and save preserve explicit route int
expect(identities(reloaded)).toEqual(identities(inherited));
await expect(hub.routeRow(gateway.backend, gateway.model).locator('button.model-hub-route-origin')).toHaveText(copy(`routing.origin.${reloaded.route_origin}`));
await hub.openRoute(gateway.backend, gateway.model);
- await expect(labelledButton(dialog, copy('routing.pinRoute'))).toBeVisible();
- await expect(dialog.getByRole('button', { name: copy('routeDialog.editHop'), exact: true }).first()).toBeVisible();
+ await expect(follow).toHaveAttribute('aria-checked', 'true');
+ await expect(dialog.getByRole('button', { name: copy('routeDialog.editHop'), exact: true })).toHaveCount(0);
await expect(labelledButton(dialog, copy('routeDialog.save'))).toBeDisabled();
await labelledButton(dialog, copy('routing.close')).click();
} finally {
diff --git a/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts b/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts
index 8d53d8795..9e80cb2da 100644
--- a/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts
+++ b/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts
@@ -64,6 +64,7 @@ for (const [width,chosen] of [[1200,"claude"],[390,"claude"],[1200,"codex"]] as
const card=page.locator(`[data-setup-screen-root="assistants"] .onboarding-assistant[aria-label="${chosen==='claude'?'Claude Code':'Codex'}"]`);
await card.getByRole('button',{name:en.onboarding.setup.configureRoute,exact:true}).click();
const add=()=>page.getByRole('button',{name:en.settings.models.routeDialog.addHop,exact:true});
+ await page.getByRole('radio',{name:en.settings.models.routeDialog.mode.custom,exact:true}).click();
await add().click();await page.getByRole('option',{name:/gpt-5/}).click();await page.getByRole('button',{name:en.settings.models.routeDialog.add.confirm,exact:true}).click();
await add().click();await page.getByRole('option',{name:/gpt-4.1/}).click();await page.getByRole('button',{name:en.settings.models.routeDialog.add.confirm,exact:true}).click();
await page.screenshot({path:info.outputPath('route.png'),fullPage:true});
diff --git a/ui/src/components/settings/models/RouteCandidatePopover.tsx b/ui/src/components/settings/models/RouteCandidatePopover.tsx
index f7815df6a..6a4ab04ff 100644
--- a/ui/src/components/settings/models/RouteCandidatePopover.tsx
+++ b/ui/src/components/settings/models/RouteCandidatePopover.tsx
@@ -15,6 +15,7 @@ import {
} from "@/components/ui/command";
import {
Popover,
+ PopoverAnchor,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
@@ -35,6 +36,10 @@ export const RouteCandidatePopover: React.FC<{
onReturnFocus?: () => void;
trigger: React.ReactElement;
width: "route" | "trigger";
+ /** Opened by another control (a phone's row menu) instead of `trigger`,
+ * which is then only the anchor the panel hangs from. */
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
}> = ({
candidates,
sources,
@@ -45,9 +50,17 @@ export const RouteCandidatePopover: React.FC<{
onReturnFocus,
trigger,
width,
+ open: controlledOpen,
+ onOpenChange,
}) => {
const { t } = useTranslation();
- const [open, setOpen] = React.useState(false);
+ const [innerOpen, setInnerOpen] = React.useState(false);
+ const controlled = controlledOpen !== undefined;
+ const open = controlled ? controlledOpen : innerOpen;
+ const setOpen = (next: boolean) => {
+ if (!controlled) setInnerOpen(next);
+ onOpenChange?.(next);
+ };
const [query, setQuery] = React.useState("");
const [candidate, setCandidate] = React.useState<RouteCandidate | null>(null);
const [customModel, setCustomModel] = React.useState('');
@@ -102,6 +115,31 @@ export const RouteCandidatePopover: React.FC<{
});
}, [matched, open]);
+ const prime = () => {
+ setCustomModel('');
+ setManualOpen(false);
+ setCustomSource(typedSources.find((source) => source.id === initialHop?.source_id)?.id ?? typedSources[0]?.id ?? '');
+ setQuery("");
+ setCandidate(
+ (initialHop
+ ? candidates.find(
+ (item) => candidateKey(item.hop) === candidateKey(initialHop),
+ )
+ : null) ??
+ candidates[0] ??
+ null,
+ );
+ };
+ // A controlled open arrives as a prop, not through Radix's onOpenChange, so
+ // it is primed here — before paint, so the panel never shows a stale pick.
+ const primeRef = React.useRef(prime);
+ React.useLayoutEffect(() => { primeRef.current = prime; });
+ const primedOpen = React.useRef(false);
+ React.useLayoutEffect(() => {
+ if (controlled && controlledOpen && !primedOpen.current) primeRef.current();
+ primedOpen.current = Boolean(controlled && controlledOpen);
+ }, [controlled, controlledOpen]);
+
const chooseCandidate = (next: string) => {
setCandidate(
matched.find((item) => candidateKey(item.hop) === next) ?? null,
@@ -114,19 +152,7 @@ export const RouteCandidatePopover: React.FC<{
open={open}
onOpenChange={(nextOpen) => {
if (nextOpen) {
- setCustomModel('');
- setManualOpen(false);
- setCustomSource(typedSources.find((source) => source.id === initialHop?.source_id)?.id ?? typedSources[0]?.id ?? '');
- setQuery("");
- setCandidate(
- (initialHop
- ? candidates.find(
- (item) => candidateKey(item.hop) === candidateKey(initialHop),
- )
- : null) ??
- candidates[0] ??
- null,
- );
+ prime();
} else {
pendingCandidateRef.current = null;
setQuery("");
@@ -135,7 +161,9 @@ export const RouteCandidatePopover: React.FC<{
setOpen(nextOpen);
}}
>
- <PopoverTrigger asChild>{trigger}</PopoverTrigger>
+ {controlled
+ ? <PopoverAnchor asChild>{trigger}</PopoverAnchor>
+ : <PopoverTrigger asChild>{trigger}</PopoverTrigger>}
{/* This picker is body-portalled inside a scroll-locked dialog. A modal
popover owns the nested scroll lock, while a bounded downward panel
stays attached to either the full-width Add trigger or a row action. */}
diff --git a/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsx b/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsx
index 84da77e62..986294eae 100644
--- a/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsx
+++ b/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsx
@@ -35,6 +35,7 @@ const mount = (chain: AgentChain) => {
/></I18nextProvider>);
return close;
};
+const mode = (name: 'Follow defaults' | 'Custom') => screen.getByRole('radio', { name });
const footer = () => within(document.querySelector<HTMLElement>('.model-hub-route-foot')!);
beforeEach(async () => {
@@ -49,15 +50,19 @@ beforeEach(async () => {
});
afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
-describe('direct route editing', () => {
- it.each(['claude', 'codex', 'opencode'] as const)('%s opens every origin directly editable without changing intent', async (backend) => {
+describe('route mode editing', () => {
+ it.each(['claude', 'codex', 'opencode'] as const)('%s opens inherited routes read only and manual routes editable, without changing intent', async (backend) => {
for (const origin of ['automatic', 'passthrough', 'manual'] as const) {
const put = vi.spyOn(modelsApi, 'putAgentChain');
const restore = vi.spyOn(modelsApi, 'restoreAgentChain');
mount(makeChain(backend, origin));
- expect(await screen.findAllByRole('button', { name: 'Edit hop' })).toHaveLength(2);
- expect(screen.queryByRole('button', { name: 'Edit route' })).toBeNull();
+ await screen.findAllByText('gpt-test');
+ const manual = origin === 'manual';
+ expect(mode(manual ? 'Custom' : 'Follow defaults').getAttribute('aria-checked')).toBe('true');
+ expect(screen.queryAllByRole('button', { name: 'Edit hop' })).toHaveLength(manual ? 2 : 0);
+ expect(screen.queryAllByRole('button', { name: 'Reorder this hop' })).toHaveLength(manual ? 2 : 0);
expect(footer().getByRole('button', { name: 'Save' })).toHaveProperty('disabled', true);
+ expect(footer().getByRole('button', { name: 'Cancel changes' })).toHaveProperty('disabled', true);
expect(put).not.toHaveBeenCalled();
expect(restore).not.toHaveBeenCalled();
cleanup();
@@ -66,12 +71,14 @@ describe('direct route editing', () => {
}
});
- it('cancels a changed inherited draft in place and observes current saved authority', async () => {
+ it('cancels a changed custom draft in place and observes current saved authority', async () => {
const user = userEvent.setup();
const chain = makeChain('codex', 'automatic');
const close = mount(chain);
const put = vi.spyOn(modelsApi, 'putAgentChain');
- await user.click((await screen.findAllByRole('button', { name: 'Remove hop' }))[0]);
+ await screen.findAllByText('gpt-test');
+ await user.click(mode('Custom'));
+ await user.click(screen.getAllByRole('button', { name: 'Remove hop' })[0]);
expect(footer().getByRole('button', { name: 'Save' })).toHaveProperty('disabled', false);
const latest = { ...chain, chain: [chain.chain[0]] };
vi.mocked(modelsApi.getAgentChain).mockResolvedValue(latest);
@@ -79,27 +86,35 @@ describe('direct route editing', () => {
await waitFor(() => expect(modelsApi.getAgentChain).toHaveBeenCalledTimes(2));
expect(await screen.findByText('Provider a')).toBeTruthy();
expect(screen.queryByText('Provider b')).toBeNull();
+ expect(mode('Follow defaults').getAttribute('aria-checked')).toBe('true');
expect(footer().getByRole('button', { name: 'Save' })).toHaveProperty('disabled', true);
expect(close).not.toHaveBeenCalled();
expect(put).not.toHaveBeenCalled();
});
- it('pins identical inherited hops only through explicit Pin and Save', async () => {
+ it('pins identical inherited hops only through the Custom switch and Save, and Undo drops the pin', async () => {
const user = userEvent.setup();
- const chain = makeChain('codex', 'automatic');
- mount(chain);
+ mount(makeChain('codex', 'automatic'));
const put = vi.spyOn(modelsApi, 'putAgentChain').mockResolvedValue({
chain: makeChain('codex', 'manual'), removed_hops: [], interrupted: [],
});
- await user.click(await screen.findByRole('button', { name: 'Pin current route' }));
+ await screen.findAllByText('gpt-test');
+ await user.click(mode('Custom'));
+ const note = screen.getByRole('status');
+ expect(note.classList.contains('model-hub-route-pending')).toBe(true);
+ await user.click(within(note).getByRole('button', { name: 'Undo' }));
+ expect(mode('Follow defaults').getAttribute('aria-checked')).toBe('true');
+ await waitFor(() => expect(document.activeElement).toBe(mode('Follow defaults')));
+ expect(footer().getByRole('button', { name: 'Save' })).toHaveProperty('disabled', true);
+ await user.click(mode('Custom'));
expect(put).not.toHaveBeenCalled();
await user.click(footer().getByRole('button', { name: 'Save' }));
await waitFor(() => expect(put).toHaveBeenCalledWith('codex', 'gpt-test', { hops }));
});
- it('does not pin from a dismissed picker, identical candidate or unmoved keyboard grab', async () => {
+ it('does not dirty a custom route from a dismissed picker, identical candidate or unmoved keyboard grab', async () => {
const user = userEvent.setup();
- const close = mount(makeChain('codex', 'passthrough'));
+ const close = mount(makeChain('codex', 'manual'));
const put = vi.spyOn(modelsApi, 'putAgentChain');
const edit = (await screen.findAllByRole('button', { name: 'Edit hop' }))[0];
await user.click(edit);
@@ -115,64 +130,87 @@ describe('direct route editing', () => {
grip.focus();
await user.keyboard('{Space}{Space}');
expect(footer().getByRole('button', { name: 'Save' })).toHaveProperty('disabled', true);
- expect(footer().queryByRole('button', { name: 'Cancel changes' })).toBeNull();
+ expect(footer().getByRole('button', { name: 'Cancel changes' })).toHaveProperty('disabled', true);
expect(put).not.toHaveBeenCalled();
});
- it.each(['automatic', 'restore'] as const)('Escape restores %s intent after moving a grabbed row', async (origin) => {
+ it.each(['manual', 'pin'] as const)('Escape restores %s intent after moving a grabbed row', async (origin) => {
const user = userEvent.setup();
- mount(makeChain('codex', origin === 'restore' ? 'manual' : 'automatic'));
- await screen.findAllByRole('button', { name: 'Edit hop' });
- if (origin === 'restore') {
- vi.spyOn(modelsApi, 'previewAgentChain').mockResolvedValue(makeChain('codex', 'automatic'));
- await user.click(screen.getByRole('button', { name: 'Restore automatic' }));
- await screen.findByRole('button', { name: 'Undo restore' });
- }
+ mount(makeChain('codex', origin === 'pin' ? 'automatic' : 'manual'));
+ await screen.findAllByText('gpt-test');
+ if (origin === 'pin') await user.click(mode('Custom'));
screen.getAllByRole('button', { name: 'Reorder this hop' })[0].focus();
await user.keyboard('{Space}{ArrowDown}');
expect(footer().getByRole('button', { name: 'Save' })).toHaveProperty('disabled', false);
await user.keyboard('{Escape}');
expect([...document.querySelectorAll('.model-hub-route-hop-name')].map((row) => row.textContent))
.toEqual(['Provider a', 'Provider b']);
- if (origin === 'restore') {
- expect(screen.getByRole('button', { name: 'Undo restore' })).toBeTruthy();
- expect(document.querySelector('.model-hub-route-preview')).not.toBeNull();
- await user.click(screen.getByRole('button', { name: 'Undo restore' }));
- } else {
- expect(screen.getByRole('button', { name: 'Pin current route' })).toBeTruthy();
- }
- expect(footer().getByRole('button', { name: 'Save' })).toHaveProperty('disabled', true);
+ expect(mode('Custom').getAttribute('aria-checked')).toBe('true');
+ // A pending pin survives the cancelled grab; a saved custom route is clean again.
+ expect(document.querySelector('.model-hub-route-pending') !== null).toBe(origin === 'pin');
+ expect(footer().getByRole('button', { name: 'Save' })).toHaveProperty('disabled', origin === 'manual');
});
- it('edits an inherited restore preview into a new manual draft and saves only that draft', async () => {
+ it('keeps a restore preview read only, and switching back to Custom returns the route that was left', async () => {
const user = userEvent.setup();
mount(makeChain('codex', 'manual'));
- vi.spyOn(modelsApi, 'previewAgentChain').mockResolvedValue(makeChain('codex', 'automatic'));
+ await user.click((await screen.findAllByRole('button', { name: 'Remove hop' }))[0]);
+ vi.spyOn(modelsApi, 'previewAgentChain').mockResolvedValue({ ...makeChain('codex', 'automatic'), chain: [] });
const restore = vi.spyOn(modelsApi, 'restoreAgentChain');
- const put = vi.spyOn(modelsApi, 'putAgentChain').mockResolvedValue({
- chain: makeChain('codex', 'manual'), removed_hops: [], interrupted: [],
- });
- await user.click(await screen.findByRole('button', { name: 'Restore automatic' }));
- await screen.findByRole('button', { name: 'Undo restore' });
- await user.click(screen.getAllByRole('button', { name: 'Remove hop' })[0]);
- expect(screen.queryByRole('button', { name: 'Undo restore' })).toBeNull();
- expect(document.querySelector('.model-hub-route-preview')).toBeNull();
- await user.click(footer().getByRole('button', { name: 'Save' }));
- await waitFor(() => expect(put).toHaveBeenCalledWith('codex', 'gpt-test', { hops: [hops[1]] }));
+ await user.click(mode('Follow defaults'));
+ await waitFor(() => expect(document.querySelector('.model-hub-route-pending')?.getAttribute('data-origin')).toBe('automatic'));
+ expect(screen.queryByRole('button', { name: 'Edit hop' })).toBeNull();
+ await user.click(mode('Custom'));
+ expect(document.querySelector('.model-hub-route-pending')).toBeNull();
+ expect([...document.querySelectorAll('.model-hub-route-hop-name')].map((row) => row.textContent)).toEqual(['Provider b']);
+ expect(footer().getByRole('button', { name: 'Save' })).toHaveProperty('disabled', false);
expect(restore).not.toHaveBeenCalled();
});
+ it('keeps focus on the pending Undo while removing the sole hop previews a restore', async () => {
+ const user = userEvent.setup();
+ vi.spyOn(modelsApi, 'previewAgentChain').mockReturnValue(new Promise(() => {}));
+ mount(makeChain('codex', 'manual'));
+ await user.click((await screen.findAllByRole('button', { name: 'Remove hop' }))[0]);
+ await user.click(screen.getByRole('button', { name: 'Remove hop' }));
+ expect(mode('Follow defaults')).toHaveProperty('disabled', true);
+ await waitFor(() => expect(document.activeElement).toBe(within(document.querySelector<HTMLElement>('.model-hub-route-pending')!).getByRole('button', { name: 'Undo' })));
+ });
+
+ it('does not reopen a nested menu on the next route after the selection is cleared', async () => {
+ const user = userEvent.setup();
+ const chain = makeChain('codex', 'manual');
+ vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(chain);
+ const agent: AgentSupply = {
+ backend: 'codex', cli_present: true, mode: 'hub', menu_kind: 'fixed',
+ sources: { order: sources.map((source) => source.id), eligibility: sources.map((source) => ({ source_id: source.id, eligible: true })) },
+ catalog_models: [{ id: 'gpt-test', display_name: null, origin: 'manual', models_dev_id: null, context_window: null, max_output_tokens: null, input_modalities: [], output_modalities: [], supports_tools: null, supports_reasoning: null, reasoning_efforts: [], locked: false, routeable: true }],
+ };
+ const view = (open: boolean) => <I18nextProvider i18n={i18n}><RouteChainDialog
+ selection={open ? { agent, modelId: chain.model_id, read: readyRegion(chain) } : null}
+ sources={sources} onClose={vi.fn()} onManageModel={vi.fn()} readAgents={vi.fn()} readSources={vi.fn()}
+ /></I18nextProvider>;
+ const { rerender } = render(view(true));
+ await user.click(await screen.findByRole('button', { name: 'Model actions' }));
+ expect(screen.getByRole('menuitem', { name: 'Edit model' })).toBeTruthy();
+ rerender(view(false));
+ rerender(view(true));
+ await screen.findAllByRole('button', { name: 'Edit hop' });
+ expect(screen.queryByRole('menuitem', { name: 'Edit model' })).toBeNull();
+ });
+
it('invalidates a pending restore on Cancel changes, without closing or applying the late preview', async () => {
const user = userEvent.setup();
let resolve!: (chain: AgentChain) => void;
vi.spyOn(modelsApi, 'previewAgentChain').mockReturnValue(new Promise((accept) => { resolve = accept; }));
const close = mount(makeChain('codex', 'manual'));
- await user.click(await screen.findByRole('button', { name: 'Restore automatic' }));
+ await screen.findAllByRole('button', { name: 'Edit hop' });
+ await user.click(mode('Follow defaults'));
await user.click(footer().getByRole('button', { name: 'Cancel changes' }));
await screen.findAllByRole('button', { name: 'Edit hop' });
await act(async () => resolve({ ...makeChain('codex', 'automatic'), chain: [] }));
expect(screen.getAllByRole('button', { name: 'Edit hop' })).toHaveLength(2);
- expect(screen.queryByRole('button', { name: 'Undo restore' })).toBeNull();
+ expect(document.querySelector('.model-hub-route-pending')).toBeNull();
expect(footer().getByRole('button', { name: 'Save' })).toHaveProperty('disabled', true);
expect(close).not.toHaveBeenCalled();
});
@@ -181,14 +219,16 @@ describe('direct route editing', () => {
const user = userEvent.setup();
const close = mount(makeChain('codex', 'automatic'));
const put = vi.spyOn(modelsApi, 'putAgentChain');
- await user.click(await screen.findByRole('button', { name: 'Pin current route' }));
+ await screen.findAllByText('gpt-test');
+ await user.click(mode('Custom'));
vi.mocked(modelsApi.getAgentChain).mockRejectedValueOnce(new Error('offline'));
await user.click(footer().getByRole('button', { name: 'Cancel changes' }));
expect(await screen.findByRole('button', { name: 'Retry' })).toBeTruthy();
- expect(screen.queryByRole('button', { name: 'Edit hop' })).toBeNull();
+ expect(screen.queryByRole('radiogroup')).toBeNull();
expect(footer().getByRole('button', { name: 'Save' })).toHaveProperty('disabled', true);
await user.click(screen.getByRole('button', { name: 'Retry' }));
- await screen.findByRole('button', { name: 'Pin current route' });
+ await screen.findByRole('radiogroup');
+ expect(mode('Follow defaults').getAttribute('aria-checked')).toBe('true');
expect(modelsApi.getAgentChain).toHaveBeenCalledTimes(3);
expect(put).not.toHaveBeenCalled();
expect(close).not.toHaveBeenCalled();
@@ -200,16 +240,17 @@ describe('direct route editing', () => {
const put = vi.spyOn(modelsApi, 'putAgentChain').mockRejectedValue(outcome === 'rejected'
? new ApiCallError('invalid_route')
: new Error('response lost'));
- await user.click(await screen.findByRole('button', { name: 'Pin current route' }));
+ await screen.findAllByText('gpt-test');
+ await user.click(mode('Custom'));
await user.click(footer().getByRole('button', { name: 'Save' }));
await screen.findByRole('button', { name: 'Retry' });
if (outcome === 'rejected') {
await user.click(footer().getByRole('button', { name: 'Cancel changes' }));
- await screen.findByRole('button', { name: 'Pin current route' });
+ await waitFor(() => expect(mode('Follow defaults').getAttribute('aria-checked')).toBe('true'));
expect(close).not.toHaveBeenCalled();
expect(modelsApi.getAgentChain).toHaveBeenCalledTimes(2);
} else {
- expect(footer().queryByRole('button', { name: 'Cancel changes' })).toBeNull();
+ expect(footer().getByRole('button', { name: 'Cancel changes' })).toHaveProperty('disabled', true);
expect(footer().queryByRole('button', { name: 'Close' })).toBeNull();
await user.click(screen.getByRole('button', { name: 'Close' }));
expect(close).toHaveBeenCalledTimes(1);
diff --git a/ui/src/components/settings/models/RouteChainDialog.test.tsx b/ui/src/components/settings/models/RouteChainDialog.test.tsx
index 43f6597e2..14d9bee99 100644
--- a/ui/src/components/settings/models/RouteChainDialog.test.tsx
+++ b/ui/src/components/settings/models/RouteChainDialog.test.tsx
@@ -124,6 +124,8 @@ const stocked = () => ({
},
] satisfies Source[],
});
+const mode = (name: 'Follow defaults' | 'Custom') => screen.getByRole('radio', { name });
+const pendingUndo = () => within(document.querySelector<HTMLElement>('.model-hub-route-pending')!).getByRole('button', { name: 'Undo' });
const observation = <T,>(value: T) => ({ value, install: vi.fn() });
const deferred = <T,>() => {
let resolve!: (value: T) => void;
@@ -229,8 +231,8 @@ describe("RouteChainDialog", () => {
/></I18nextProvider>);
await waitFor(() => expect(document.querySelectorAll('.model-hub-route-hop-name')).toHaveLength(2));
if (state === 'preview') {
- await user.click(screen.getByRole('button', { name: 'Restore automatic' }));
- await screen.findByRole('button', { name: 'Undo restore' });
+ await user.click(mode('Follow defaults'));
+ await waitFor(() => expect(document.querySelector('.model-hub-route-pending')?.getAttribute('data-origin')).toBe('automatic'));
}
const names = [...document.querySelectorAll('.model-hub-route-hop-name')];
const models = [...document.querySelectorAll('.model-hub-route-hop-model')];
@@ -243,8 +245,7 @@ describe("RouteChainDialog", () => {
}
});
const footer = within(document.querySelector<HTMLElement>('.model-hub-route-foot')!);
- const labels = state === 'inherited' ? ['Pin current route', 'Save']
- : state === 'preview' ? ['Undo restore', 'Cancel changes', 'Save'] : ['Restore automatic', 'Save'];
+ const labels = ['Cancel changes', 'Save'];
expect(footer.getAllByRole('button').map((button) => button.textContent)).toEqual(labels);
for (const label of labels) expect(footer.getByRole('button', { name: label }).hasAttribute('hidden')).toBe(false);
expect(screen.getByRole('dialog').classList.contains('overflow-hidden')).toBe(true);
@@ -261,14 +262,15 @@ describe("RouteChainDialog", () => {
sources={sources} onClose={vi.fn()} onManageModel={manage} readAgents={vi.fn()} readSources={vi.fn()}
/></I18nextProvider>);
const head = within(document.querySelector<HTMLElement>('.model-hub-route-head')!);
- await user.click(await head.findByRole('button', { name: 'Edit model' }));
- await user.click(head.getByRole('button', { name: 'Remove model' }));
+ await user.click(await head.findByRole('button', { name: 'Model actions' }));
+ 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]]);
// 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: 'Edit model' })).toBeNull();
- expect(head.queryByRole('button', { name: 'Remove model' })).toBeNull();
+ expect(head.queryByRole('button', { name: 'Model actions' })).toBeNull();
});
it('offers no catalog handoff for a locked row', async () => {
@@ -279,21 +281,7 @@ describe("RouteChainDialog", () => {
sources={sources} onClose={vi.fn()} onManageModel={vi.fn()} readAgents={vi.fn()} readSources={vi.fn()}
/></I18nextProvider>);
await screen.findAllByRole('button', { name: 'Remove hop' });
- expect(screen.queryByRole('button', { name: 'Edit model' })).toBeNull();
- });
-
- it('labels the origin line as the current route and explains the origin on hover', async () => {
- const user = userEvent.setup();
- vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(chain);
- render(<I18nextProvider i18n={i18n}><RouteChainDialog
- selection={{ agent, modelId: 'opus-5', read: readyRegion(chain) }}
- sources={sources} onClose={vi.fn()} readAgents={vi.fn()} readSources={vi.fn()}
- /></I18nextProvider>);
- await screen.findAllByRole('button', { name: 'Remove hop' });
- const line = document.querySelector<HTMLElement>('.model-hub-route-origin-line')!;
- expect(within(line).getByText('Current')).toBeTruthy();
- await user.hover(within(line).getByRole('button', { name: 'Manual' }));
- expect((await screen.findByText(/This model has a saved, fixed route/)).closest('.model-hub-origin-help')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'Model actions' })).toBeNull();
});
it('closes an unchanged inherited editor without creating manual intent', async () => {
@@ -308,26 +296,28 @@ describe("RouteChainDialog", () => {
sources={sources} onClose={close} readAgents={vi.fn()} readSources={vi.fn()}
/></I18nextProvider>);
- await screen.findAllByRole('button', { name: 'Edit hop' });
+ await screen.findAllByText('opus-5');
+ expect(screen.queryByRole('button', { name: 'Edit hop' })).toBeNull();
const footer = within(document.querySelector<HTMLElement>('.model-hub-route-foot')!);
// The header close is the only dismiss control while there is nothing to discard.
const dismiss = screen.getByRole('button', { name: 'Close' });
expect(dismiss.classList.contains('model-hub-route-close')).toBe(true);
expect(footer.queryByRole('button', { name: 'Close' })).toBeNull();
expect(footer.queryByRole('button', { name: 'Cancel' })).toBeNull();
- expect(screen.queryByRole('button', { name: 'Cancel changes' })).toBeNull();
- expect(screen.getByRole('button', { name: 'Add a hop' })).toBeTruthy();
+ expect(footer.getByRole('button', { name: 'Cancel changes' })).toHaveProperty('disabled', true);
+ // Inherited rows are read only; adding a hop starts from the Custom switch.
+ expect(screen.queryByRole('button', { name: 'Add a hop' })).toBeNull();
await user.click(dismiss);
expect(close).toHaveBeenCalledTimes(1);
expect(put).not.toHaveBeenCalled();
expect(restore).not.toHaveBeenCalled();
});
- it('cancels explicit pinning, restore preview and undo in place without writing', async () => {
+ it('cancels an explicit pin in place, and switching back from an unsaved pin needs no preview', async () => {
const user = userEvent.setup();
const inherited: AgentChain = { ...chain, manual_override: null, route_origin: 'automatic' };
vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(inherited);
- const preview = vi.spyOn(modelsApi, 'previewAgentChain').mockResolvedValue(inherited);
+ const preview = vi.spyOn(modelsApi, 'previewAgentChain');
const put = vi.spyOn(modelsApi, 'putAgentChain');
const restore = vi.spyOn(modelsApi, 'restoreAgentChain');
const close = vi.fn();
@@ -336,25 +326,21 @@ describe("RouteChainDialog", () => {
sources={sources} onClose={close} readAgents={vi.fn()} readSources={vi.fn()}
/></I18nextProvider>);
- await user.click(await screen.findByRole('button', { name: 'Pin current route' }));
+ await screen.findAllByText('opus-5');
+ await user.click(mode('Custom'));
const footer = within(document.querySelector<HTMLElement>('.model-hub-route-foot')!);
- expect(footer.getByRole('button', { name: 'Cancel changes' }).textContent).toBe('Cancel changes');
+ expect(footer.getByRole('button', { name: 'Cancel changes' })).toHaveProperty('disabled', false);
expect(footer.queryByRole('button', { name: 'Close' })).toBeNull();
expect(screen.getAllByRole('button', { name: 'Remove hop' })).toHaveLength(2);
- await user.click(screen.getByRole('button', { name: 'Restore automatic' }));
- await screen.findByRole('button', { name: 'Undo restore' });
- expect(preview).toHaveBeenCalledWith('claude', 'opus-5', { manual_override: null });
- expect(footer.getByRole('button', { name: 'Cancel changes' }).textContent).toBe('Cancel changes');
- expect(footer.queryByRole('button', { name: 'Close' })).toBeNull();
- expect(screen.getAllByRole('button', { name: 'Remove hop' })).toHaveLength(2);
+ await user.click(mode('Follow defaults'));
+ expect(preview).not.toHaveBeenCalled();
+ expect(screen.queryByRole('button', { name: 'Remove hop' })).toBeNull();
+ expect(footer.getByRole('button', { name: 'Cancel changes' })).toHaveProperty('disabled', true);
- await user.click(screen.getByRole('button', { name: 'Undo restore' }));
- expect(footer.getByRole('button', { name: 'Cancel changes' }).textContent).toBe('Cancel changes');
- expect(footer.queryByRole('button', { name: 'Close' })).toBeNull();
- expect(screen.getAllByRole('button', { name: 'Remove hop' })).toHaveLength(2);
+ await user.click(mode('Custom'));
await user.click(footer.getByRole('button', { name: 'Cancel changes' }));
- await screen.findByRole('button', { name: 'Pin current route' });
+ await waitFor(() => expect(mode('Follow defaults').getAttribute('aria-checked')).toBe('true'));
expect(close).not.toHaveBeenCalled();
expect(put).not.toHaveBeenCalled();
expect(restore).not.toHaveBeenCalled();
@@ -395,7 +381,8 @@ describe("RouteChainDialog", () => {
order: [alternateSubscription.id], eligibility: [{ source_id: alternateSubscription.id, eligible: true }],
} }, [alternateSubscription]);
- await user.click(await screen.findByRole('button', { name: 'Add a hop' }));
+ await user.click(await screen.findByRole('radio', { name: 'Custom' }));
+ await user.click(screen.getByRole('button', { name: 'Add a hop' }));
await user.click(screen.getByRole('option', { name: /sonnet-5/ }));
await user.click(screen.getByRole('button', { name: 'Add' }));
await user.click(screen.getByRole('button', { name: 'Save' }));
@@ -414,7 +401,8 @@ describe("RouteChainDialog", () => {
order: [], eligibility: [{ source_id: sources[0].id, eligible: true }],
} }, [sources[0]]);
- await user.click(await screen.findByRole('button', { name: 'Add a hop' }));
+ await user.click(await screen.findByRole('radio', { name: 'Custom' }));
+ await user.click(screen.getByRole('button', { name: 'Add a hop' }));
await user.click(screen.getByRole('button', { name: 'Enter a model ID manually' }));
await user.type(screen.getByLabelText('Exact model ID'), hop.model_id);
await user.click(screen.getByRole('button', { name: 'Add' }));
@@ -444,7 +432,8 @@ describe("RouteChainDialog", () => {
it('reads legacy empty storage only as server-normalized inheritance with no admissible targets', async () => {
renderEmptyRoute({ ...agent, sources: { order: [], eligibility: [] } }, []);
await screen.findByRole('button', { name: 'Configure default routing' });
- expect(screen.getByText('Unconfigured')).toBeTruthy();
+ expect(mode('Follow defaults').getAttribute('aria-checked')).toBe('true');
+ expect(screen.getByText(/No default provider can route this model/)).toBeTruthy();
expect(screen.queryByRole('button', { name: 'Restore automatic' })).toBeNull();
expect(screen.getByRole('button', { name: 'Save' })).toHaveProperty('disabled', true);
expect(screen.queryByText(/saved route is empty/)).toBeNull();
@@ -454,6 +443,7 @@ describe("RouteChainDialog", () => {
renderEmptyRoute({ ...agent, sources: {
order: [], eligibility: [{ source_id: sources[0].id, eligible: true }],
} }, [sources[0]]);
+ await userEvent.setup().click(await screen.findByRole('radio', { name: 'Custom' }));
await screen.findByRole('button', { name: 'Add a hop' });
expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(true);
expect(screen.queryByText(/saved route is empty/)).toBeNull();
@@ -469,25 +459,21 @@ describe("RouteChainDialog", () => {
await user.click(screen.getByRole('button', { name: 'Remove hop' }));
};
- it.each(['manual', 'automatic'] as const)('previews clear from %s, undoes only the previous unsaved draft and cancels without writes', async (origin) => {
+ it('previews clear from manual, undoes only the previous unsaved draft and cancels without writes', async () => {
const user = userEvent.setup();
const preview = vi.spyOn(modelsApi, 'previewAgentChain').mockResolvedValue(inherited);
const put = vi.spyOn(modelsApi, 'putAgentChain');
const restore = vi.spyOn(modelsApi, 'restoreAgentChain');
const close = vi.fn();
renderDialog(vi.fn(), close);
- if (origin === 'automatic') {
- vi.mocked(modelsApi.getAgentChain).mockResolvedValue(inherited);
- cleanup();
- render(<I18nextProvider i18n={i18n}><RouteChainDialog selection={{ agent, modelId: 'opus-5', read: readyRegion(inherited) }} sources={sources} onClose={close} readAgents={vi.fn()} readSources={vi.fn()} /></I18nextProvider>);
- await screen.findAllByRole('button', { name: 'Edit hop' });
- }
await clear(user);
await screen.findByText('After restore: automatic matching');
expect(preview).toHaveBeenCalledWith('claude', 'opus-5', { manual_override: null });
- expect(screen.getAllByRole('button', { name: 'Remove hop' })).toHaveLength(2);
- expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(origin === 'automatic');
- await user.click(screen.getByRole('button', { name: 'Undo restore' }));
+ expect(mode('Follow defaults').getAttribute('aria-checked')).toBe('true');
+ expect(document.querySelectorAll('.model-hub-route-hop-model')).toHaveLength(2);
+ expect(screen.queryByRole('button', { name: 'Remove hop' })).toBeNull();
+ expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(false);
+ await user.click(pendingUndo());
expect(screen.getAllByRole('button', { name: 'Remove hop' })).toHaveLength(1);
expect(document.querySelector('.model-hub-route-hop-model')?.textContent).toBe('opus-5');
await user.click(screen.getByRole('button', { name: 'Remove hop' }));
@@ -500,6 +486,20 @@ describe("RouteChainDialog", () => {
expect(chain.manual_override?.hops).toHaveLength(2);
});
+ it('clearing an unsaved pin of inherited routing returns to it locally', async () => {
+ const user = userEvent.setup();
+ const preview = vi.spyOn(modelsApi, 'previewAgentChain');
+ vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(inherited);
+ render(<I18nextProvider i18n={i18n}><RouteChainDialog selection={{ agent, modelId: 'opus-5', read: readyRegion(inherited) }} sources={sources} onClose={vi.fn()} readAgents={vi.fn()} readSources={vi.fn()} /></I18nextProvider>);
+ await screen.findAllByText('opus-5');
+ await user.click(mode('Custom'));
+ await clear(user);
+ expect(preview).not.toHaveBeenCalled();
+ expect(mode('Follow defaults').getAttribute('aria-checked')).toBe('true');
+ expect(document.querySelectorAll('.model-hub-route-hop-model')).toHaveLength(2);
+ 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 () => {
const user = userEvent.setup();
const gap = { backend: 'claude' as const, model_id: 'opus-5', agents: ['writer'] };
@@ -539,7 +539,7 @@ describe("RouteChainDialog", () => {
renderDialog();
await clear(user);
await screen.findByRole('alert');
- expect(screen.getByRole('button', { name: 'Undo restore' })).toBeTruthy();
+ expect(pendingUndo()).toBeTruthy();
expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(true);
expect(screen.queryByText('Manual', { exact: true })).toBeNull();
await user.click(screen.getByRole('button', { name: 'Retry' }));
@@ -548,7 +548,7 @@ describe("RouteChainDialog", () => {
await screen.findByText('After restore: original-name passthrough');
expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(false);
expect(restore).not.toHaveBeenCalled();
- await user.click(screen.getByRole('button', { name: 'Undo restore' }));
+ await user.click(pendingUndo());
expect(document.querySelector('.model-hub-route-hop-model')?.textContent).toBe('opus-5');
});
@@ -562,7 +562,7 @@ describe("RouteChainDialog", () => {
const footer = within(document.querySelector<HTMLElement>('.model-hub-route-foot')!);
expect((footer.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(true);
await user.click(action === 'undo'
- ? footer.getByRole('button', { name: 'Undo restore' })
+ ? pendingUndo()
: screen.getByRole('button', { name: 'Close' }));
await act(async () => pending.resolve(inherited));
expect(screen.queryByText('After restore: automatic matching')).toBeNull();
@@ -584,7 +584,7 @@ describe("RouteChainDialog", () => {
const view = (covered: boolean) => <I18nextProvider i18n={i18n}><RouteChainDialog {...props} covered={covered} /></I18nextProvider>;
const { rerender } = render(view(false));
await clear(user);
- await user.click(screen.getByRole('button', { name: /Default routing/ }));
+ await user.click(screen.getByRole('button', { name: 'Adjust default routing' }));
expect(openDefaults).toHaveBeenCalledOnce();
rerender(view(true));
rerender(view(false));
@@ -595,7 +595,7 @@ describe("RouteChainDialog", () => {
await user.click(screen.getByRole('button', { name: 'Retry' }));
await screen.findByText('After restore: unconfigured');
expect(preview).toHaveBeenCalledTimes(3);
- await user.click(screen.getByRole('button', { name: 'Undo restore' }));
+ await user.click(pendingUndo());
expect(document.querySelector('.model-hub-route-hop-model')?.textContent).toBe('opus-5');
});
@@ -612,13 +612,14 @@ describe("RouteChainDialog", () => {
await user.click(screen.getByRole('button', { name: copy.routeDialog.removeHop }));
expect(screen.getByText(copy.routing.previewLoading)).toBeTruthy();
const footer = within(document.querySelector<HTMLElement>('.model-hub-route-foot')!);
- expect(footer.getAllByRole('button').map((button) => button.textContent)).toEqual([copy.routing.undoRestore, copy.routing.cancelChanges, copy.routeDialog.save]);
+ expect(footer.getAllByRole('button').map((button) => button.textContent)).toEqual([copy.routing.cancelChanges, copy.routeDialog.save]);
+ const note = within(document.querySelector<HTMLElement>('.model-hub-route-pending')!);
expect((footer.getByRole('button', { name: copy.routeDialog.save }) as HTMLButtonElement).disabled).toBe(true);
await act(async () => pending.reject(new Error('offline')));
expect(screen.getByRole('alert').textContent).toContain(copy.routing.previewFailed);
await user.click(screen.getByRole('button', { name: copy.routeDialog.retry }));
await screen.findByText(copy.routing.preview.automatic);
- await user.click(footer.getByRole('button', { name: copy.routing.undoRestore }));
+ await user.click(note.getByRole('button', { name: copy.routeDialog.mode.undo }));
expect(screen.getByText(copy.routing.undoDone)).toBeTruthy();
});
@@ -652,7 +653,7 @@ describe("RouteChainDialog", () => {
const props = { selection: { agent, modelId: 'opus-5', read: readyRegion(inherited) }, sources, onClose: vi.fn(), readAgents: vi.fn(), readSources: vi.fn() };
const view = (covered: boolean) => <I18nextProvider i18n={i18n}><RouteChainDialog {...props} covered={covered} /></I18nextProvider>;
const { rerender } = render(view(false));
- await screen.findByRole('button', { name: 'Pin current route' });
+ await screen.findByRole('radio', { name: 'Follow defaults' });
rerender(view(true));
rerender(view(false));
await waitFor(() => expect(read).toHaveBeenCalledTimes(2));
@@ -670,14 +671,14 @@ describe("RouteChainDialog", () => {
const { rerender } = render(view(false));
await screen.findAllByRole('button', { name: 'Remove hop' });
await user.click(screen.getAllByRole('button', { name: 'Remove hop' })[0]);
- await user.click(screen.getByRole('button', { name: 'Restore automatic' }));
- await screen.findByRole('button', { name: 'Undo restore' });
+ await user.click(mode('Follow defaults'));
+ await screen.findByText('After restore: automatic matching');
rerender(view(true));
rerender(view(false));
await waitFor(() => expect(preview).toHaveBeenCalledTimes(2));
await waitFor(() => expect(document.querySelectorAll('.model-hub-route-hop-model')).toHaveLength(1));
expect(document.querySelector('.model-hub-route-hop-model')?.textContent).toBe('claude-opus-5');
- await user.click(screen.getByRole('button', { name: 'Undo restore' }));
+ await user.click(pendingUndo());
expect(document.querySelector('.model-hub-route-hop-model')?.textContent).toBe('opus-5');
});
@@ -691,11 +692,11 @@ describe("RouteChainDialog", () => {
renderDialog(vi.fn(), close);
await screen.findAllByRole('button', { name: 'Remove hop' });
await user.click(screen.getAllByRole('button', { name: 'Remove hop' })[0]);
- await user.click(screen.getByRole('button', { name: 'Restore automatic' }));
+ await user.click(mode('Follow defaults'));
await screen.findByText('After restore: original-name passthrough');
expect(preview).toHaveBeenCalledWith('claude', 'opus-5', { manual_override: null });
- expect(screen.getAllByRole('button', { name: 'Remove hop' })).toHaveLength(2);
- await user.click(screen.getByRole('button', { name: 'Undo restore' }));
+ expect(document.querySelectorAll('.model-hub-route-hop-model')).toHaveLength(2);
+ await user.click(pendingUndo());
expect(screen.getAllByRole('button', { name: 'Remove hop' })).toHaveLength(1);
expect(document.querySelector('.model-hub-route-hop-model')?.textContent).toBe('opus-5');
await user.click(screen.getByRole('button', { name: 'Cancel changes' }));
@@ -712,8 +713,8 @@ describe("RouteChainDialog", () => {
const restore = vi.spyOn(modelsApi, 'restoreAgentChain').mockResolvedValue(mutation(inherited));
const put = vi.spyOn(modelsApi, 'putAgentChain');
renderDialog();
- await user.click(await screen.findByRole('button', { name: 'Restore automatic' }));
- await screen.findByRole('button', { name: 'Undo restore' });
+ await user.click(await screen.findByRole('radio', { name: 'Follow defaults' }));
+ await screen.findByText('After restore: automatic matching');
await user.click(screen.getByRole('button', { name: 'Save' }));
await waitFor(() => expect(restore).toHaveBeenCalledWith('claude', 'opus-5', undefined));
expect(put).not.toHaveBeenCalled();
@@ -728,7 +729,7 @@ describe("RouteChainDialog", () => {
cleanup();
const put = vi.spyOn(modelsApi, 'putAgentChain').mockResolvedValue(mutation(chain));
render(<I18nextProvider i18n={i18n}><RouteChainDialog selection={{ agent, modelId: 'opus-5', read: readyRegion(inherited) }} sources={[]} onClose={vi.fn()} readAgents={vi.fn()} readSources={vi.fn()} /></I18nextProvider>);
- await user.click(await screen.findByRole('button', { name: 'Pin current route' }));
+ await user.click(await screen.findByRole('radio', { name: 'Custom' }));
await user.click(screen.getByRole('button', { name: 'Save' }));
await waitFor(() => expect(put).toHaveBeenCalledWith('claude', 'opus-5', { hops: chain.manual_override!.hops }));
});
diff --git a/ui/src/components/settings/models/RouteChainDialog.tsx b/ui/src/components/settings/models/RouteChainDialog.tsx
index 1ba7452fe..93b759944 100644
--- a/ui/src/components/settings/models/RouteChainDialog.tsx
+++ b/ui/src/components/settings/models/RouteChainDialog.tsx
@@ -2,15 +2,15 @@ import type { TranslationKey } from '@/i18n/types';
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import {
+ ChevronRight,
GripVertical,
Info,
ListOrdered,
LoaderCircle,
+ MoreHorizontal,
Pencil,
- Pin,
Plus,
RefreshCw,
- RotateCcw,
Trash2,
Undo2,
X,
@@ -18,11 +18,14 @@ import {
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
+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 { RouteCandidatePopover } from "./RouteCandidatePopover";
-import { RouteOriginBadge } from "./RouteOriginBadge";
-import { RouteRecordedTurn } from './RouteRecordedTurn';
+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";
@@ -51,6 +54,8 @@ import type {
const sourceName = (sources: Source[], sourceId: string): string =>
sources.find((source) => source.id === sourceId)?.display_name ?? sourceId;
+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[];
@@ -175,10 +180,15 @@ export const RouteChainDialog: React.FC<{
const editRefs = React.useRef<Array<HTMLButtonElement | null>>([]);
const removeRefs = React.useRef<Array<HTMLButtonElement | null>>([]);
const addButtonRef = React.useRef<HTMLButtonElement | null>(null);
- const reseedButtonRef = React.useRef<HTMLButtonElement | null>(null);
+ const modeRef = React.useRef<HTMLDivElement | null>(null);
+ const pendingUndoRef = React.useRef<HTMLButtonElement | null>(null);
const cancelButtonRef = React.useRef<HTMLButtonElement | null>(null);
const closeButtonRef = React.useRef<HTMLButtonElement | null>(null);
- const [originHelp, setOriginHelp] = React.useState(false);
+ const isMobile = useIsMobile();
+ const [headMenu, setHeadMenu] = React.useState(false);
+ const [hopMenu, setHopMenu] = React.useState<number | null>(null);
+ const [replacing, setReplacing] = React.useState<number | null>(null);
+ const [recordDetails, setRecordDetails] = React.useState(false);
const saveButtonRef = React.useRef<HTMLButtonElement | null>(null);
const savingStatusRef = React.useRef<HTMLSpanElement | null>(null);
const retryButtonRef = React.useRef<HTMLButtonElement | null>(null);
@@ -191,6 +201,7 @@ export const RouteChainDialog: React.FC<{
const agent = selection?.agent ?? null;
const modelId = selection?.modelId ?? "";
const selectionBackend = selection?.agent.backend;
+ const recordedTurn = useRecordedTurn(selectionBackend, modelId);
// Only an editable catalog row can be handed over: a locked row (Claude Code's
// `Default`) offers no actions in the catalog either, and a server that
// predates backend catalogs sends no list to answer from.
@@ -247,17 +258,37 @@ export const RouteChainDialog: React.FC<{
const manageableModel = Boolean(
onManageModel && catalogRow && !catalogRow.locked && phase === "ready" && !dirty && !restoring,
);
- const draftOrigin = manualDraft ? (draft.length ? 'manual' : null) : (preview ?? chain)?.route_origin ?? null;
+ // A switch that saving would apply: back to defaults over a saved route, or
+ // onto a route of this model's own over inherited routing.
+ const pendingSwitch: "restore" | "pin" | null = !manualDraft && savedOverride !== null
+ ? "restore"
+ : manualDraft && savedOverride === null
+ ? "pin"
+ : null;
const announce = (key: TranslationKey, params?: Record<string, unknown>) =>
setAnnouncement({ key, params });
const focusAfterRender = (ref: React.RefObject<HTMLElement | null>) => {
requestAnimationFrame(() => ref.current?.focus());
};
- // The footer carries a dismiss control only while there is a draft to
+ // The footer's dismiss control is live only while there is a draft to
// discard; otherwise the header close is the dialog's single way out, so
// every "return focus to the way out" path resolves through here.
- const focusDismiss = () =>
- (cancelButtonRef.current ?? closeButtonRef.current)?.focus();
+ const focusDismiss = () => {
+ const cancel = cancelButtonRef.current;
+ (cancel && !cancel.disabled ? cancel : closeButtonRef.current)?.focus();
+ };
+ const focusMode = () =>
+ requestAnimationFrame(() =>
+ modeRef.current?.querySelector<HTMLButtonElement>('[aria-checked="true"]')?.focus(),
+ );
+ // A restore preview disables the mode switch while it reads, so focus waits
+ // on its Undo instead; a local revert leaves the switch live.
+ const focusAfterFollow = () =>
+ requestAnimationFrame(() => {
+ const undo = pendingUndoRef.current;
+ if (undo && !undo.disabled) undo.focus();
+ else modeRef.current?.querySelector<HTMLButtonElement>('[aria-checked="true"]')?.focus();
+ });
const readChain = React.useCallback(async () => {
if (!selectionBackend) return;
@@ -317,6 +348,10 @@ export const RouteChainDialog: React.FC<{
setFailedMembers(new Set());
setUnknownObservation("none");
setUnknownSourceCurrent(false);
+ setHeadMenu(false);
+ setHopMenu(null);
+ setReplacing(null);
+ setRecordDetails(false);
advanceInteraction({ type: "reset", draft: [], focusIndex: 0 });
if (selection) void readChain();
}, [advanceInteraction, readChain, selection]);
@@ -348,7 +383,8 @@ export const RouteChainDialog: React.FC<{
setSelectorEpoch((current) => current + 1);
advanceInteraction({ type: "drop-grab" });
focusAfterRender({
- current: removeRefs.current[valid.invalidIndexes[0]] ?? null,
+ current: removeRefs.current[valid.invalidIndexes[0]]
+ ?? editRefs.current[valid.invalidIndexes[0]] ?? null,
});
}, [advanceInteraction, phase, valid.invalidIndexes]);
@@ -390,8 +426,8 @@ export const RouteChainDialog: React.FC<{
if (phase === "saving" || phase === "impact" || phase === "refreshing")
return;
if (draft.length === 1) {
- void restoreAutomatic();
- focusAfterRender(reseedButtonRef);
+ followDefaults();
+ focusAfterFollow();
return;
}
const next = advanceInteraction({ type: "remove", index });
@@ -402,8 +438,6 @@ export const RouteChainDialog: React.FC<{
gripRefs.current[focusedIndex]?.focus();
} else if (addCandidates.length > 0) {
addButtonRef.current?.focus();
- } else if (reseedButtonRef.current && !reseedButtonRef.current.disabled) {
- reseedButtonRef.current.focus();
} else {
focusDismiss();
}
@@ -791,6 +825,46 @@ export const RouteChainDialog: React.FC<{
restoreUndo.current = null;
announce('settings.models.routing.undoDone');
};
+ // Undoing an unsaved pin is local: saved routing already follows defaults,
+ // and the inherited route this dialog last read is what stays in force.
+ const revertToInherited = () => {
+ previewGeneration.current += 1;
+ restoreUndo.current = null;
+ setPreview(null);
+ setPreviewPending(false);
+ setPreviewFailed(false);
+ setManualDraft(false);
+ advanceInteraction({ type: 'reset', draft: origin });
+ setSelectorEpoch((current) => current + 1);
+ };
+ const followDefaults = () => {
+ if (savedOverride === null) revertToInherited();
+ else void restoreAutomatic();
+ };
+ const switchMode = (next: RouteMode) => {
+ if (phase !== 'ready' || previewPending) return;
+ if (next === 'custom') {
+ if (manualDraft) return;
+ // Returning from a pending restore brings back the route that was left.
+ if (restoreUndo.current) undoRestore();
+ else setManualDraft(true);
+ } else if (manualDraft) {
+ followDefaults();
+ focusAfterFollow();
+ }
+ };
+ const undoSwitch = () => {
+ if (restoreUndo.current) undoRestore();
+ else revertToInherited();
+ focusMode();
+ };
+ // 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 recordedHopIndex = recordedTurn.record
+ ? draft.findIndex((hop) => recordedOn(recordedTurn.record, hop))
+ : -1;
const renderHop = (hop: RouteHop, index: number) => {
const visibleChain = preview ?? chain;
const chainLink = visibleChain?.chain.find((entry) =>
@@ -812,11 +886,77 @@ export const RouteChainDialog: React.FC<{
draft.filter((_, draftIndex) => draftIndex !== index),
)
: [];
+ const roving = grabbed === null && rovingIndex === index ? 0 : -1;
+ const editLabel = t("settings.models.routeDialog.editHop") as string;
+ const removeLabel = t("settings.models.routeDialog.removeHop") as string;
+ const replaceHop = (nextCandidate: RouteCandidate) => {
+ const next = advanceInteraction({
+ type: "replace",
+ index,
+ hop: nextCandidate.hop,
+ });
+ announce("settings.models.routeDialog.edit.replaced", {
+ position: index + 1,
+ });
+ requestAnimationFrame(() =>
+ gripRefs.current[next.focusIndex]?.focus(),
+ );
+ };
+ const actionClass = "model-hub-route-action grid shrink-0 place-items-center text-muted";
+ // Phones fold both row actions into one menu; the picker then hangs from
+ // that menu's button instead of a pencil of its own.
+ const mobileActions = (
+ <ResponsiveMenu
+ open={hopMenu === index}
+ onOpenChange={(open) => setHopMenu(open ? index : null)}
+ sheetTitle={displayedSource}
+ sheetDescription={hop.model_id}
+ trigger={
+ <button
+ ref={(node) => {
+ editRefs.current[index] = node;
+ }}
+ type="button"
+ aria-label={t("settings.models.routeDialog.hopActions") as string}
+ tabIndex={roving}
+ disabled={actionsDisabled}
+ className={cn(actionClass, "model-hub-route-more")}
+ >
+ <MoreHorizontal aria-hidden="true" />
+ </button>
+ }
+ >
+ <button
+ type="button"
+ role="menuitem"
+ className={MENU_ITEM}
+ onClick={() => {
+ setHopMenu(null);
+ requestAnimationFrame(() => setReplacing(index));
+ }}
+ >
+ <Pencil aria-hidden="true" />
+ {editLabel}
+ </button>
+ <button
+ type="button"
+ role="menuitem"
+ className={cn(MENU_ITEM, "text-destructive-ink hover:bg-destructive/[0.08]")}
+ onClick={() => {
+ setHopMenu(null);
+ remove(index);
+ }}
+ >
+ <X aria-hidden="true" />
+ {removeLabel}
+ </button>
+ </ResponsiveMenu>
+ );
return (
<div
key={`${hop.source_id}:${hop.model_id}:${index}`}
- onDragOver={(event) => event.preventDefault()}
- onDrop={(event) => {
+ onDragOver={editable ? (event) => event.preventDefault() : undefined}
+ onDrop={editable ? (event) => {
event.preventDefault();
if (grabbed !== null) {
advanceInteraction({
@@ -825,11 +965,12 @@ export const RouteChainDialog: React.FC<{
});
advanceInteraction({ type: "drop-grab" });
}
- }}
+ } : undefined}
data-current={current || undefined}
- className="model-hub-route-hop model-hub-fill-08 flex items-center border border-border"
+ data-editable={editable || undefined}
+ className="model-hub-route-hop flex items-center"
>
- <button
+ {editable && <button
ref={(node) => {
gripRefs.current[index] = node;
}}
@@ -855,7 +996,7 @@ export const RouteChainDialog: React.FC<{
className="model-hub-route-grip grid shrink-0 place-items-center"
>
<GripVertical aria-hidden="true" />
- </button>
+ </button>}
<span
className={cn(
"model-hub-route-ordinal grid shrink-0 place-items-center font-mono font-medium",
@@ -897,65 +1038,55 @@ export const RouteChainDialog: React.FC<{
</span>
)}
</span>
- <span className="model-hub-route-actions flex shrink-0 items-center">
+ {index === recordedHopIndex && recordedTurn.record && (
+ <RecordedTurnBadge record={recordedTurn.record} onOpen={() => setRecordDetails(true)} />
+ )}
+ {editable && <span className="model-hub-route-actions flex shrink-0 items-center">
<RouteCandidatePopover
key={`edit:${selectorEpoch}:${index}`}
candidates={replacementCandidates}
sources={targetSources}
confirmLabel={t("settings.models.routeDialog.edit.confirm") as string}
initialHop={hop}
- label={t("settings.models.routeDialog.editHop") as string}
+ label={editLabel}
width="route"
onReturnFocus={() => editRefs.current[index]?.focus()}
- onApply={(nextCandidate) => {
- const next = advanceInteraction({
- type: "replace",
- index,
- hop: nextCandidate.hop,
- });
- announce("settings.models.routeDialog.edit.replaced", {
- position: index + 1,
- });
- requestAnimationFrame(() =>
- gripRefs.current[next.focusIndex]?.focus(),
- );
- }}
- trigger={
+ onApply={replaceHop}
+ {...(isMobile ? {
+ open: replacing === index,
+ onOpenChange: (open: boolean) => setReplacing(open ? index : null),
+ } : {})}
+ trigger={isMobile ? <span className="model-hub-route-menu-anchor">{mobileActions}</span> : (
<button
ref={(node) => {
editRefs.current[index] = node;
}}
type="button"
- aria-label={t("settings.models.routeDialog.editHop") as string}
- title={t("settings.models.routeDialog.editHop") as string}
- tabIndex={grabbed === null && rovingIndex === index ? 0 : -1}
- disabled={
- phase === "saving" ||
- phase === "impact" ||
- phase === "refreshing"
- }
- className="model-hub-route-action model-hub-route-edit model-hub-fill-0a grid shrink-0 place-items-center border border-border text-muted"
+ aria-label={editLabel}
+ title={editLabel}
+ tabIndex={roving}
+ disabled={actionsDisabled}
+ className={cn(actionClass, "model-hub-route-edit")}
>
<Pencil aria-hidden="true" />
</button>
- }
+ )}
/>
- <button
+ {!isMobile && <button
ref={(node) => {
removeRefs.current[index] = node;
}}
type="button"
- aria-label={t("settings.models.routeDialog.removeHop") as string}
- tabIndex={grabbed === null && rovingIndex === index ? 0 : -1}
- disabled={
- phase === "saving" || phase === "impact" || phase === "refreshing"
- }
+ aria-label={removeLabel}
+ title={removeLabel}
+ tabIndex={roving}
+ disabled={actionsDisabled}
onClick={() => remove(index)}
- className="model-hub-route-action model-hub-route-remove model-hub-fill-0a grid shrink-0 place-items-center border border-border text-muted"
+ className={cn(actionClass, "model-hub-route-remove")}
>
<X aria-hidden="true" />
- </button>
- </span>
+ </button>}
+ </span>}
</div>
);
};
@@ -1114,25 +1245,25 @@ export const RouteChainDialog: React.FC<{
</div>
) : (
<div className="model-hub-route-body flex flex-col">
- {!unresolvedPreview && !(manualDraft && draft.length === 0) && <div className="model-hub-route-origin-line">
- {/* The line reads as the route in force unless an unsaved pin is
- about to replace it, which `manualPending` already says itself. */}
- {!(manualDraft && dirty) && <span className="model-hub-route-origin-now">{t('settings.models.routing.originNow')}</span>}
- <RouteOriginBadge origin={draftOrigin} backend={agent!.backend} open={originHelp} onOpenChange={setOriginHelp} />
- <span>{t(manualDraft ? (dirty ? 'settings.models.routing.manualPending' : 'settings.models.routing.frozen') : 'settings.models.routing.follows', { backend })}</span>
- </div>}
- {unresolvedPreview && <div className="model-hub-route-preview" role="status">
- {previewPending && <strong>{t('settings.models.routing.previewLoading')}</strong>}
- <span>{t('settings.models.routing.restorePending')}</span>
- </div>}
- {preview && <div className="model-hub-route-preview" data-origin={preview.route_origin ?? 'unconfigured'} role="status">
- <strong>{t(`settings.models.routing.preview.${preview.route_origin ?? 'unconfigured'}`, { defaultValue: `settings.models.routing.preview.${preview.route_origin ?? 'unconfigured'}` })}</strong>
- <span>{t('settings.models.routing.restorePending')}</span>
- </div>}
- {!unresolvedPreview && <><h3 className="model-hub-route-label font-bold">
- {t(preview ? 'settings.models.routing.afterSave' : "settings.models.routeDialog.section")}
- </h3>
- <div inert={previewPending} className="model-hub-route-list flex flex-col border border-border bg-background">
+ <div className="model-hub-route-mode flex flex-col">
+ <div ref={modeRef}>
+ <SegmentedRadio<RouteMode>
+ ariaLabel={t("settings.models.routeDialog.mode.label") as string}
+ value={manualDraft ? "custom" : "follow"}
+ onChange={switchMode}
+ disabled={phase !== "ready" || previewPending}
+ className="model-hub-route-mode-switch"
+ options={[
+ { id: "follow", label: t("settings.models.routeDialog.mode.follow") as string },
+ { id: "custom", label: t("settings.models.routeDialog.mode.custom") as string },
+ ]}
+ />
+ </div>
+ <p className="model-hub-route-mode-copy text-muted">
+ {t(manualDraft ? "settings.models.routing.manualHint" : "settings.models.routing.follows", { backend })}
+ </p>
+ </div>
+ {!unresolvedPreview && <div inert={previewPending} className="model-hub-route-list flex flex-col">
{draft.length ? (
draft.map(renderHop)
) : (
@@ -1141,49 +1272,46 @@ export const RouteChainDialog: React.FC<{
{!manualDraft && onOpenDefaults && <Button variant="outline" onClick={onOpenDefaults}><ListOrdered aria-hidden />{t('settings.models.routing.configureDefaults')}</Button>}
</div>
)}
- {canEditRoute && <RouteCandidatePopover
+ </div>}
+ <div className="model-hub-route-tools flex flex-wrap items-center justify-between">
+ {!unresolvedPreview && manualDraft && canEditRoute ? <RouteCandidatePopover
key={`add:${selectorEpoch}`}
candidates={addCandidates}
sources={targetSources}
confirmLabel={t("settings.models.routeDialog.add.confirm") as string}
label={t("settings.models.routeDialog.addHop") as string}
- width="trigger"
+ width="route"
onApply={addCandidate}
onReturnFocus={() => addButtonRef.current?.focus()}
trigger={
- <button
+ <Button
ref={addButtonRef}
type="button"
+ variant="outline"
+ size="sm"
disabled={targetSources.length === 0 || previewPending}
aria-describedby={
addCandidates.length === 0
? "model-hub-route-add-none"
: undefined
}
- className="model-hub-route-add model-hub-fill-05 flex w-full items-center justify-center gap-1.5 border border-border font-semibold text-muted disabled:opacity-60"
+ className="model-hub-route-add"
>
<Plus aria-hidden="true" />
{t("settings.models.routeDialog.addHop")}
- </button>
+ </Button>
}
- />}
- </div></>}
- {onOpenDefaults && <button type="button" onClick={onOpenDefaults} className="model-hub-route-reseed flex items-center gap-1.5 self-start font-semibold text-cyan-ink">
- <ListOrdered aria-hidden="true" />
- {t('settings.models.routing.defaultRouting')}
- <span className="text-muted">{(agent?.sources?.order ?? []).map((id) => sourceName(sources, id)).join(' → ')}</span>
- </button>}
+ /> : <span />}
+ {onOpenDefaults && <button type="button" onClick={onOpenDefaults} className="model-hub-route-defaults flex items-center text-muted">
+ {t(manualDraft ? 'settings.models.routeDialog.mode.viewDefaults' : 'settings.models.routeDialog.mode.adjustDefaults')}
+ <ChevronRight aria-hidden="true" />
+ </button>}
+ </div>
{addCandidates.length === 0 && (
<span className="sr-only" id="model-hub-route-add-none">
{t("settings.models.routeDialog.add.none")}
</span>
)}
- <p className="model-hub-route-hint flex items-start">
- <Info aria-hidden="true" className="shrink-0" />
- <span className="model-hub-route-hint-copy">
- {t(manualDraft ? 'settings.models.routing.manualHint' : 'settings.models.routing.editHint')}
- </span>
- </p>
{previewFailed && <div role="alert" className="text-destructive-ink text-xs"><p>{t('settings.models.routing.previewFailed')}</p><Button variant="ghost" size="sm" disabled={previewPending} onClick={() => void restoreAutomatic()}><RefreshCw aria-hidden />{t('settings.models.routeDialog.retry')}</Button></div>}
{manualDraft && valid.invalidIndexes.length > 0 && (
<p
@@ -1193,6 +1321,20 @@ export const RouteChainDialog: React.FC<{
{t("settings.models.routeDialog.invalidAfterRefresh")}
</p>
)}
+ {/* Next to Save, which is what it describes: above the rows it would push
+ the Add trigger down and take the room its picker opens into. */}
+ {(pendingSwitch || restoring) && <div className="model-hub-route-pending flex items-center justify-between" role="status" data-origin={preview?.route_origin ?? undefined}>
+ <span className="flex min-w-0 flex-col">
+ {previewPending && <strong>{t('settings.models.routing.previewLoading')}</strong>}
+ {preview && <strong>{t(`settings.models.routing.preview.${preview.route_origin ?? 'unconfigured'}`, { defaultValue: `settings.models.routing.preview.${preview.route_origin ?? 'unconfigured'}` })}</strong>}
+ <span>{t(pendingSwitch === 'pin' ? 'settings.models.routing.manualPending' : 'settings.models.routing.restorePending')}</span>
+ </span>
+ <button ref={pendingUndoRef} type="button" disabled={phase !== 'ready'} onClick={undoSwitch} className="model-hub-route-pending-undo flex shrink-0 items-center font-semibold">
+ <Undo2 aria-hidden="true" />
+ {t('settings.models.routeDialog.mode.undo')}
+ </button>
+ </div>}
+ <RouteRecordedTurn turn={recordedTurn} matched={recordedHopIndex >= 0} onOpenDetails={() => setRecordDetails(true)} />
<span className="sr-only" aria-live="polite">
{announcement ? t(announcement.key, announcement.params) : ""}
</span>
@@ -1234,28 +1376,46 @@ export const RouteChainDialog: React.FC<{
</DialogPrimitive.Title>
<span className="model-hub-route-head-actions flex shrink-0 items-center gap-1.5">
{manageableModel && (
- <>
- <Button
+ <ResponsiveMenu
+ open={headMenu}
+ onOpenChange={setHeadMenu}
+ sheetTitle={modelId}
+ trigger={
+ <button
+ type="button"
+ aria-label={t("settings.models.routeDialog.modelActions") as string}
+ title={t("settings.models.routeDialog.modelActions") as string}
+ className="model-hub-route-close grid shrink-0 place-items-center"
+ >
+ <MoreHorizontal aria-hidden="true" />
+ </button>
+ }
+ >
+ <button
type="button"
- variant="outline"
- size="sm"
- className="model-hub-route-head-action"
- onClick={() => onManageModel?.("edit", draft)}
+ role="menuitem"
+ className={MENU_ITEM}
+ onClick={() => {
+ setHeadMenu(false);
+ onManageModel?.("edit", draft);
+ }}
>
<Pencil aria-hidden="true" />
{t("settings.models.routeDialog.editModel")}
- </Button>
- <Button
+ </button>
+ <button
type="button"
- variant="destructive"
- size="sm"
- className="model-hub-route-head-action"
- onClick={() => onManageModel?.("remove", draft)}
+ role="menuitem"
+ className={cn(MENU_ITEM, "text-destructive-ink hover:bg-destructive/[0.08]")}
+ onClick={() => {
+ setHeadMenu(false);
+ onManageModel?.("remove", draft);
+ }}
>
<Trash2 aria-hidden="true" />
{t("settings.models.routeDialog.removeModel")}
- </Button>
- </>
+ </button>
+ </ResponsiveMenu>
)}
<DialogPrimitive.Close
ref={closeButtonRef}
@@ -1282,7 +1442,7 @@ export const RouteChainDialog: React.FC<{
</DialogPrimitive.Description>
</header>
{body}
- <RouteRecordedTurn key={`${selectionBackend}:${modelId}`} backend={selectionBackend!} modelId={modelId} />
+ <RecordedTurnDetails record={recordedTurn.record} open={recordDetails} onOpenChange={setRecordDetails} />
<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
@@ -1323,25 +1483,16 @@ export const RouteChainDialog: React.FC<{
</span>
) : (
<>
- {(manualDraft || restoring) && <Button ref={reseedButtonRef} variant="outline" className="model-hub-dialog-action mr-auto" disabled={phase !== 'ready'} onClick={() => restoring ? undoRestore() : void restoreAutomatic()}>
- {previewPending ? <LoaderCircle className="animate-spin" aria-hidden /> : restoreUndo.current ? <Undo2 aria-hidden /> : <RotateCcw aria-hidden />}
- {t(restoreUndo.current ? 'settings.models.routing.undoRestore' : 'settings.models.routing.restoreAutomatic')}
- </Button>}
- {!manualDraft && !restoring && draft.length > 0 && <Button
- variant="outline"
- className="model-hub-dialog-action mr-auto"
- disabled={phase !== 'ready' || !valid.valid}
- onClick={() => setManualDraft(true)}
- ><Pin aria-hidden />{t('settings.models.routing.pinRoute')}</Button>}
- {canDiscardDraft && <Button
+ <Button
ref={cancelButtonRef}
type="button"
variant="outline"
className="model-hub-dialog-action"
+ disabled={!canDiscardDraft}
onClick={cancelChanges}
>
{t('settings.models.routing.cancelChanges')}
- </Button>}
+ </Button>
<Button
ref={saveButtonRef}
type="button"
diff --git a/ui/src/components/settings/models/RouteRecordedTurn.test.tsx b/ui/src/components/settings/models/RouteRecordedTurn.test.tsx
index b2af7543b..a23392323 100644
--- a/ui/src/components/settings/models/RouteRecordedTurn.test.tsx
+++ b/ui/src/components/settings/models/RouteRecordedTurn.test.tsx
@@ -8,16 +8,32 @@ import { I18nextProvider } from 'react-i18next';
import { afterEach, describe, expect, expectTypeOf, it, vi } from 'vitest';
import i18n from '@/i18n';
import { modelsApi } from './modelsApi';
-import { RouteRecordedTurn } from './RouteRecordedTurn';
+import * as React from 'react';
+import { RecordedTurnBadge, RecordedTurnDetails, RouteRecordedTurn } from './RouteRecordedTurn';
+import { recordedOn, useRecordedTurn } from './recordedTurn';
import { PERSISTED_TURN_CONTRACT_VERSIONS } from './types';
-import type { TurnProvenance } from './types';
+import type { RouteHop, TurnProvenance } from './types';
const record: TurnProvenance = {
contract_version: 10, turn_id: 'turn-recorded', ts: '2026-09-05T15:00:00Z', agent: 'codex', requested_model_id: 'requested-model',
outcome: 'failed_terminal', failed_attempts: [], served: null, canceled_attempt: null, model_supply_state: null, blockers: [],
terminal_error: { source_id: 'src_historical', configured_model_id: 'historical-model', channel: 'hub', reason: 'invalid_parameter', stream_started: false, http_status: 404, upstream_error_code: 'model_not_found' },
};
-const view = (modelId = 'requested-model') => <I18nextProvider i18n={i18n}><RouteRecordedTurn backend="codex" modelId={modelId} /></I18nextProvider>;
+// Composes the pieces the way the route dialog does: a badge on the hop the error
+// names, the standalone record only when no hop carries it, one details dialog.
+function Harness({ modelId, hops }: { modelId: string; hops: RouteHop[] }) {
+ const turn = useRecordedTurn('codex', modelId);
+ const [open, setOpen] = React.useState(false);
+ const matched = hops.some((hop) => recordedOn(turn.record, hop));
+ return <>
+ {hops.map((hop) => <div key={hop.source_id} data-hop={hop.source_id}>
+ {recordedOn(turn.record, hop) && turn.record && <RecordedTurnBadge record={turn.record} onOpen={() => setOpen(true)} />}
+ </div>)}
+ <RouteRecordedTurn turn={turn} matched={matched} onOpenDetails={() => setOpen(true)} />
+ <RecordedTurnDetails record={turn.record} open={open} onOpenChange={setOpen} />
+ </>;
+}
+const view = (modelId = 'requested-model', hops: RouteHop[] = []) => <I18nextProvider i18n={i18n}><Harness modelId={modelId} hops={hops} /></I18nextProvider>;
afterEach(() => { cleanup(); vi.restoreAllMocks(); });
describe('recorded turn error', () => {
@@ -38,6 +54,17 @@ describe('recorded turn error', () => {
await user.click(screen.getByRole('button', { name: 'View error details' }));
expect(screen.getByRole('dialog').querySelector('pre')?.textContent).toBe(JSON.stringify(record, null, 2));
});
+ it('marks the hop the error names instead of repeating the record below the route', async () => {
+ const user = userEvent.setup();
+ vi.spyOn(modelsApi, 'getAgentProvenance').mockResolvedValue(record);
+ render(view('requested-model', [{ source_id: 'src_other', model_id: 'historical-model' }, { source_id: 'src_historical', model_id: 'historical-model' }]));
+ const badge = await screen.findByRole('button', { name: 'Latest recorded turn · Upstream returned model not found' });
+ expect(badge.closest('[data-hop]')?.getAttribute('data-hop')).toBe('src_historical');
+ expect(badge.textContent).toBe('404');
+ expect(document.querySelector('.model-hub-recorded-turn')).toBeNull();
+ await user.click(badge);
+ expect(screen.getByRole('dialog').querySelector('pre')?.textContent).toBe(JSON.stringify(record, null, 2));
+ });
it.each(PERSISTED_TURN_CONTRACT_VERSIONS)('reads v%s terminal errors without rewriting records or inventing model-not-found evidence', async (version) => {
const user = userEvent.setup();
const historical: TurnProvenance = { ...record, contract_version: version, terminal_error: { source_id: 'src_old', configured_model_id: 'old-model', channel: 'hub', reason: 'invalid_parameter', stream_started: false } };
diff --git a/ui/src/components/settings/models/RouteRecordedTurn.tsx b/ui/src/components/settings/models/RouteRecordedTurn.tsx
index a3a6f75de..b6af62036 100644
--- a/ui/src/components/settings/models/RouteRecordedTurn.tsx
+++ b/ui/src/components/settings/models/RouteRecordedTurn.tsx
@@ -1,48 +1,79 @@
-import * as React from 'react';
-import { FileText, RefreshCw } from 'lucide-react';
+import { AlertTriangle, FileText, RefreshCw } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';
-import { modelsApi } from './modelsApi';
-import type { AgentBackend, TurnProvenance } from './types';
+import type { RecordedError, RecordedTurn } from './recordedTurn';
-export function RouteRecordedTurn({ backend, modelId }: { backend: AgentBackend; modelId: string }) {
- const { t, i18n } = useTranslation();
- const [record, setRecord] = React.useState<TurnProvenance | null>(null);
- const [failed, setFailed] = React.useState(false);
- const [attempt, setAttempt] = React.useState(0);
- const [details, setDetails] = React.useState(false);
- React.useEffect(() => {
- let active = true;
- setRecord(null);
- setFailed(false);
- setDetails(false);
- void modelsApi.getAgentProvenance(backend, modelId).then((value) => {
- if (active) setRecord(value);
- }, () => { if (active) setFailed(true); });
- return () => { active = false; };
- }, [backend, modelId, attempt]);
- if (failed) return <div className="model-hub-recorded-turn" role="alert">
- <span>{t('settings.models.routing.historyFailed')}</span>
- <Button variant="ghost" size="sm" onClick={() => setAttempt((value) => value + 1)}><RefreshCw aria-hidden />{t('settings.models.order.retry')}</Button>
- </div>;
- if (!record?.terminal_error || record.agent !== backend || record.requested_model_id !== modelId) return null;
+function useReason(record: RecordedError) {
+ const { t } = useTranslation();
const error = record.terminal_error;
- const reason = error.upstream_error_code === 'model_not_found'
+ return error.upstream_error_code === 'model_not_found'
? t('settings.models.routing.modelNotFound')
: t(`settings.models.routing.errorReason.${error.reason}`);
- return <section className="model-hub-recorded-turn">
- <strong>{t('settings.models.routing.latestRecorded')} · {reason}</strong>
+}
+
+function RecordedSummary({ record }: { record: RecordedError }) {
+ const { i18n } = useTranslation();
+ const error = record.terminal_error;
+ return <>
<time dateTime={record.ts}>{new Date(record.ts).toLocaleString(i18n.language)}</time>
<span className="font-mono">{error.source_id ?? '—'} · {error.configured_model_id ?? '—'}</span>
{error.upstream_error_code && <span className="font-mono">{error.upstream_error_code}</span>}
- <Button variant="ghost" size="sm" className="self-start text-cyan-ink" onClick={() => setDetails(true)}><FileText aria-hidden />{t('settings.models.routing.errorDetails')}</Button>
- <Dialog open={details} onOpenChange={setDetails}>
- <DialogContent className="max-h-[85dvh] overflow-y-auto">
- <DialogTitle>{t('settings.models.routing.latestRecorded')}</DialogTitle>
- <DialogDescription>{record.turn_id}</DialogDescription>
- <pre className="whitespace-pre-wrap break-words text-xs">{JSON.stringify(record, null, 2)}</pre>
- </DialogContent>
- </Dialog>
+ </>;
+}
+
+/** Inline mark on the hop the recorded turn failed on; opens the full record. */
+export function RecordedTurnBadge({ record, onOpen }: { record: RecordedError; onOpen: () => void }) {
+ const { t } = useTranslation();
+ const reason = useReason(record);
+ const label = `${t('settings.models.routing.latestRecorded')} · ${reason}`;
+ return <button type="button" className="model-hub-recorded-turn-badge flex shrink-0 items-center font-mono" aria-label={label} title={label} onClick={onOpen}>
+ <AlertTriangle aria-hidden="true" />
+ {record.terminal_error.http_status ?? record.terminal_error.upstream_error_code ?? t('settings.models.routing.errorShort')}
+ </button>;
+}
+
+export function RecordedTurnDetails({ record, open, onOpenChange }: { record: RecordedError | null; open: boolean; onOpenChange: (open: boolean) => void }) {
+ const { t } = useTranslation();
+ if (!record) return null;
+ return <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-h-[85dvh] overflow-y-auto">
+ <DialogTitle>{t('settings.models.routing.latestRecorded')}</DialogTitle>
+ <DialogDescription>{record.turn_id}</DialogDescription>
+ <DetailsSummary record={record} />
+ <pre className="whitespace-pre-wrap break-words text-xs">{JSON.stringify(record, null, 2)}</pre>
+ </DialogContent>
+ </Dialog>;
+}
+
+function DetailsSummary({ record }: { record: RecordedError }) {
+ const reason = useReason(record);
+ return <div className="model-hub-recorded-turn-summary flex flex-col text-xs">
+ <strong>{reason}</strong>
+ <RecordedSummary record={record} />
+ </div>;
+}
+
+/**
+ * The recorded turn where no hop can carry it: a read failure, or an error on a
+ * hop the route no longer has — the record stays true to what was sent then.
+ */
+export function RouteRecordedTurn({ turn, matched, onOpenDetails }: { turn: RecordedTurn; matched: boolean; onOpenDetails: () => void }) {
+ const { t } = useTranslation();
+ if (turn.failed) return <div className="model-hub-recorded-turn" role="alert">
+ <span>{t('settings.models.routing.historyFailed')}</span>
+ <Button variant="ghost" size="sm" onClick={turn.retry}><RefreshCw aria-hidden />{t('settings.models.order.retry')}</Button>
+ </div>;
+ if (!turn.record || matched) return null;
+ return <UnmatchedRecord record={turn.record} onOpenDetails={onOpenDetails} />;
+}
+
+function UnmatchedRecord({ record, onOpenDetails }: { record: RecordedError; onOpenDetails: () => void }) {
+ const { t } = useTranslation();
+ const reason = useReason(record);
+ return <section className="model-hub-recorded-turn">
+ <strong>{t('settings.models.routing.latestRecorded')} · {reason}</strong>
+ <RecordedSummary record={record} />
+ <Button variant="ghost" size="sm" className="self-start text-cyan-ink" onClick={onOpenDetails}><FileText aria-hidden />{t('settings.models.routing.errorDetails')}</Button>
</section>;
}
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index 712bd1923..34676df26 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -2029,7 +2029,8 @@ describe('SettingsModelsPage surface branches', () => {
], [agent]);
const opener = await screen.findByRole('button', { name: /Open gpt-5\.6-sol route chain|打开 gpt-5\.6-sol 的路由链/i });
await userEvent.click(opener);
- await userEvent.click(await screen.findByRole('button', { name: /^Edit model$|^编辑模型$/i }));
+ await userEvent.click(await screen.findByRole('button', { name: /^Model actions$|^模型操作$/i }));
+ await userEvent.click(await screen.findByRole('menuitem', { name: /^Edit model$|^编辑模型$/i }));
await waitFor(() => expect(document.querySelector('.model-hub-route-head')).toBeNull());
// Edit opens the model editor over the catalog; leave both by keyboard.
for (let open = 0; open < 3 && screen.queryAllByRole('dialog').length; open += 1) {
diff --git a/ui/src/components/settings/models/modelHubStylePolicy.test.ts b/ui/src/components/settings/models/modelHubStylePolicy.test.ts
index 3680da467..66a2daad3 100644
--- a/ui/src/components/settings/models/modelHubStylePolicy.test.ts
+++ b/ui/src/components/settings/models/modelHubStylePolicy.test.ts
@@ -168,7 +168,7 @@ describe('Model Hub visual token policy', () => {
return values;
};
expect(declarations('.model-hub-route-hop')).toMatchObject({
- 'min-height': 'var(--model-hub-route-hop-height)', height: 'auto', padding: '6px 10px',
+ 'min-height': 'var(--model-hub-route-hop-height)', height: 'auto', padding: '6px 8px',
});
for (const selector of ['.model-hub-route-hop-name', '.model-hub-route-hop-model']) {
expect(declarations(selector)).toMatchObject({ 'overflow-wrap': 'anywhere', 'white-space': 'normal' });
diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.css
index fabef4def..c871b6489 100644
--- a/ui/src/components/settings/models/modelHubSurface.css
+++ b/ui/src/components/settings/models/modelHubSurface.css
@@ -552,11 +552,14 @@
.model-hub-route-origin:focus-visible { outline: 1px solid currentColor; outline-offset: 2px; }
.model-hub-model-open:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }
.model-hub-origin-help { width: 340px; max-width: calc(100vw - 32px); white-space: pre-line; font-size: 12px; line-height: 1.6; }
-.model-hub-route-origin-line { display: flex; gap: 12px; align-items: center; color: var(--muted); font-size: 12px; }
-.model-hub-route-origin-now { flex-shrink: 0; margin-right: -4px; font-weight: 600; color: var(--foreground); }
-.model-hub-route-preview { display: flex; flex-direction: column; gap: 8px; padding: 16px; border-radius: 8px; background: var(--model-hub-mint-1a); color: var(--mint-ink); font-size: 12px; }
-.model-hub-route-preview[data-origin="passthrough"] { background: var(--model-hub-gold-1a); color: var(--gold-ink); }
-.model-hub-route-preview[data-origin="unconfigured"] { background: var(--model-hub-wash-08); color: var(--muted); }
+.model-hub-route-mode { gap: 6px; }
+.model-hub-route-mode-copy { font-size: 11.5px; line-height: 17px; }
+/* A switch that saving would apply, and the one way back from it. */
+.model-hub-route-pending { gap: 12px; padding: 8px 12px; border: 1px solid var(--model-hub-gold-4d); border-radius: 8px; background: var(--model-hub-gold-1a); color: var(--gold-ink); font-size: 11.5px; line-height: 17px; overflow-wrap: anywhere; }
+.model-hub-route-pending-undo { gap: 4px; color: inherit; }
+.model-hub-route-pending-undo:hover:not(:disabled) { text-decoration: underline; text-underline-offset: 2px; }
+.model-hub-route-pending-undo:disabled { opacity: 0.6; }
+.model-hub-route-pending-undo > svg { width: 12px; height: 12px; }
.model-hub-route-ordinal[data-origin="automatic"] { color: var(--mint-ink); background: var(--model-hub-mint-1a); }
.model-hub-route-ordinal[data-origin="passthrough"] { color: var(--gold-ink); background: var(--model-hub-gold-1a); }
.model-hub-route-custom { display: grid; grid-template-columns: minmax(80px, auto) minmax(0, 1fr); gap: var(--model-hub-route-custom-gap, 8px); align-items: center; padding: 0 12px var(--model-hub-route-custom-pad-block-end, 12px); font-size: 12px; }
@@ -566,8 +569,13 @@
depends on may not be a different height on the machine that renders it. */
.model-hub-route-custom label { line-height: var(--model-hub-route-custom-label-height, 18px); }
.model-hub-default-counts { margin-top: auto; padding: 20px; font-size: 12px; color: var(--muted); }
-.model-hub-recorded-turn { display: flex; flex-direction: column; gap: 6px; margin: 0 20px 16px; padding: 12px; border-left: 2px solid var(--destructive-ink); font-size: 12px; overflow-wrap: anywhere; color: var(--muted); }
+.model-hub-recorded-turn { display: flex; flex-direction: column; gap: 6px; padding: 12px; border-left: 2px solid var(--destructive-ink); font-size: 12px; overflow-wrap: anywhere; color: var(--muted); }
.model-hub-recorded-turn strong { color: var(--destructive-ink); }
+.model-hub-recorded-turn-badge { gap: 4px; height: 22px; padding: 0 7px; border-radius: 999px; background: var(--model-hub-danger-fill); color: var(--destructive-ink); font-size: 10.5px; }
+.model-hub-recorded-turn-badge:hover { background: var(--model-hub-danger-border); }
+.model-hub-recorded-turn-badge > svg { width: 11px; height: 11px; }
+.model-hub-recorded-turn-summary { gap: 4px; color: var(--muted); overflow-wrap: anywhere; }
+.model-hub-recorded-turn-summary strong { color: var(--destructive-ink); }
@media (max-width: 640px) {
.model-hub-model-row { height: 72px; }
}
@@ -1044,8 +1052,6 @@
box-shadow: var(--model-hub-dialog-shadow);
}
.model-hub-route-head { min-height: var(--model-hub-route-head-height); flex-shrink: 0; padding: 16px 20px; gap: 4px; border-color: var(--model-hub-wash-14); }
-.model-hub-route-head-action { height: 26px; padding: 0 10px; font-size: 11.5px; }
-.model-hub-route-head-action > svg { width: 13px; height: 13px; }
.model-hub-route-close { width: 26px; height: 26px; margin: -5px -5px -5px 0; color: var(--model-hub-ink-59); }
.model-hub-route-close > svg { width: 15px; height: 15px; }
.model-hub-route-title {
@@ -1073,23 +1079,20 @@
letter-spacing: 1.1px;
}
.model-hub-route-list {
- --model-hub-route-list-gap: 6px;
- --model-hub-route-list-padding: 8px;
- --model-hub-route-list-radius: 10px;
- padding: var(--model-hub-route-list-padding);
+ --model-hub-route-list-gap: 2px;
gap: var(--model-hub-route-list-gap);
- border-color: var(--model-hub-wash-14);
- border-radius: var(--model-hub-route-list-radius);
}
.model-hub-route-hop {
--model-hub-route-hop-gap: 10px;
--model-hub-route-hop-height: 52px;
min-height: var(--model-hub-route-hop-height);
height: auto;
- padding: 6px 10px;
+ padding: 6px 8px;
gap: var(--model-hub-route-hop-gap);
border-radius: var(--model-hub-route-hop-radius);
}
+.model-hub-route-hop[data-editable]:hover,
+.model-hub-route-hop[data-editable]:focus-within { background: var(--model-hub-wash-08); }
.model-hub-route-ordinal {
--model-hub-route-ordinal-radius: 6px;
--model-hub-route-ordinal-size: 22px;
@@ -1351,31 +1354,18 @@
border-radius: var(--model-hub-dialog-action-radius);
font-size: var(--model-hub-route-selector-confirm-size);
}
-.model-hub-route-actions { gap: 4px; }
-.model-hub-route-action { width: 26px; height: 26px; border-radius: 6px; color: var(--foreground); }
+.model-hub-route-actions { gap: 2px; }
+.model-hub-route-action { width: 26px; height: 26px; border-radius: 6px; }
+.model-hub-route-action:hover:not(:disabled) { background: var(--model-hub-wash-0f); color: var(--foreground); }
+.model-hub-route-remove:hover:not(:disabled) { color: var(--destructive-ink); }
.model-hub-route-action > svg { width: 13px; height: 13px; }
-.model-hub-route-add {
- --model-hub-route-add-size: 11.5px;
- --model-hub-route-add-height: 38px;
- height: var(--model-hub-route-add-height);
- border-radius: var(--model-hub-route-hop-radius);
- border-color: var(--model-hub-wash-14);
- font-size: var(--model-hub-route-add-size);
-}
-.model-hub-route-add > svg { width: 13px; height: 13px; }
-.model-hub-route-reseed { font-size: 12px; }
-.model-hub-route-reseed > svg { width: 12px; height: 12px; }
-.model-hub-route-hint {
- --model-hub-route-hint-gap: 7px;
- --model-hub-route-hint-line: 17px;
- --model-hub-route-hint-size: 11.5px;
- gap: var(--model-hub-route-hint-gap);
- color: var(--model-hub-ink-73);
- font-size: var(--model-hub-route-hint-size);
- line-height: var(--model-hub-route-hint-line);
-}
-.model-hub-route-hint > svg { width: 13px; height: 13px; }
-.model-hub-route-hint-copy { width: 420px; max-width: calc(100% - 20px); }
+.model-hub-route-tools { gap: 8px; }
+.model-hub-route-defaults { gap: 2px; font-size: 12px; }
+.model-hub-route-defaults:hover { color: var(--foreground); }
+.model-hub-route-defaults > svg { width: 12px; height: 12px; }
+.model-hub-route-menu-anchor { display: inline-flex; }
+.model-hub-route-menu-item { gap: 8px; padding: 10px; font-size: 13px; }
+.model-hub-route-menu-item > svg { width: 14px; height: 14px; }
.model-hub-route-foot { height: var(--model-hub-dialog-foot-height); flex-shrink: 0; padding: 14px 20px; border-color: var(--model-hub-wash-14); }
@media (max-width: 640px) {
.model-hub-route-foot { flex-wrap: wrap; min-height: var(--model-hub-dialog-foot-height); height: auto; }
diff --git a/ui/src/components/settings/models/recordedTurn.ts b/ui/src/components/settings/models/recordedTurn.ts
new file mode 100644
index 000000000..d84af8fd5
--- /dev/null
+++ b/ui/src/components/settings/models/recordedTurn.ts
@@ -0,0 +1,32 @@
+import * as React from 'react';
+import { modelsApi } from './modelsApi';
+import type { AgentBackend, RouteHop, TurnProvenance } from './types';
+
+export type RecordedError = TurnProvenance & { terminal_error: NonNullable<TurnProvenance['terminal_error']> };
+export type RecordedTurn = { record: RecordedError | null; failed: boolean; retry: () => void };
+
+/** The latest recorded turn for this exact model, kept only when it ended in an error. */
+export function useRecordedTurn(backend: AgentBackend | undefined, modelId: string): RecordedTurn {
+ const [record, setRecord] = React.useState<TurnProvenance | null>(null);
+ const [failed, setFailed] = React.useState(false);
+ const [attempt, setAttempt] = React.useState(0);
+ React.useEffect(() => {
+ let active = true;
+ setRecord(null);
+ setFailed(false);
+ if (!backend) return;
+ void modelsApi.getAgentProvenance(backend, modelId).then((value) => {
+ if (active) setRecord(value);
+ }, () => { if (active) setFailed(true); });
+ return () => { active = false; };
+ }, [backend, modelId, attempt]);
+ const retry = React.useCallback(() => setAttempt((value) => value + 1), []);
+ const shown = record?.terminal_error && record.agent === backend && record.requested_model_id === modelId
+ ? record as RecordedError : null;
+ return { record: shown, failed, retry };
+}
+
+/** The recorded error names the hop that failed; it is drawn on that hop when the route still has it. */
+export const recordedOn = (record: RecordedError | null, hop: RouteHop): boolean =>
+ record !== null && record.terminal_error.source_id === hop.source_id
+ && record.terminal_error.configured_model_id === hop.model_id;
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index c6fa26bad..e3bd3b145 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1248,22 +1248,16 @@
"passthrough": "Passthrough",
"unconfigured": "Unconfigured"
},
- "originNow": "Current",
"help": {
"automatic": "Matched by model name.\nSource order follows {{backend}} default routing.",
"manual": "This model has a saved, fixed route.\nDefault routing does not change it. Restore automatic in route settings to follow defaults.",
"passthrough": "No matching model was found in the provider lists.\nThe original model name is sent to eligible API-key providers in default order for the upstream to handle.",
"unconfigured": "No route is configured for this model. Open route settings to configure defaults or restore automatic routing."
},
- "frozen": "This model uses a saved, fixed route",
- "follows": "Follows {{backend}} default routing",
+ "follows": "Follows {{backend}} default routing. Changes to default routing apply here automatically.",
"manualHint": "Only this model. Changes to default routing do not overwrite these route entries.",
- "editHint": "Editing and saving gives this model a manual route.",
- "restoreAutomatic": "Restore automatic",
- "undoRestore": "Undo restore",
"undoDone": "Previous manual draft restored.",
"restorePending": "Not saved yet. The saved route is still in use.",
- "afterSave": "Route after saving",
"preview": {
"automatic": "After restore: automatic matching",
"passthrough": "After restore: original-name passthrough",
@@ -1275,15 +1269,14 @@
"noDefaults": "No default provider can route this model. Add a matching provider or an eligible API-key provider.",
"inventoryNotProvided": "Model list not provided",
"configureDefaults": "Configure default routing",
- "defaultRouting": "Default routing",
"close": "Close",
- "pinRoute": "Pin current route",
"cancelChanges": "Cancel changes",
"manualPending": "After saving, this model will use a manual route and no longer follow default routing.",
"exactModel": "Exact model ID",
"moveUp": "Move source up",
"moveDown": "Move source down",
- "counts": "{{inherited}} models follow defaults · {{manual}} fixed routes"
+ "counts": "{{inherited}} models follow defaults · {{manual}} fixed routes",
+ "errorShort": "Error"
},
"order": {
"title": "{{backend}} · Default routing",
@@ -1726,7 +1719,6 @@
"open": "Open {{model}} route chain",
"openWithMapping": "Open {{model}} route chain · {{mapping}}",
"label": "Route chain for this model",
- "section": "Route chain for this model",
"removeHop": "Remove hop",
"editHop": "Edit hop",
"addHop": "Add a hop",
@@ -1776,7 +1768,17 @@
"refreshFail": "The route chain was saved, but the display could not be refreshed.",
"done": "Done"
},
- "hint": "This model has a saved, fixed route. Default routing changes do not overwrite it."
+ "hint": "This model has a saved, fixed route. Default routing changes do not overwrite it.",
+ "mode": {
+ "label": "Routing mode",
+ "follow": "Follow defaults",
+ "custom": "Custom",
+ "undo": "Undo",
+ "viewDefaults": "View default routing",
+ "adjustDefaults": "Adjust default routing"
+ },
+ "hopActions": "Hop actions",
+ "modelActions": "Model actions"
},
"recent": {
"title": "Recent switches",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 98e68dfec..a107a8238 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1248,22 +1248,16 @@
"passthrough": "透传",
"unconfigured": "未配置"
},
- "originNow": "当前",
"help": {
"automatic": "已按模型名自动匹配。\n供应商顺序跟随 {{backend}} 的默认路由。",
"manual": "此模型已保存固定路由。\n不随默认路由调整,可在路由设置中恢复自动。",
"passthrough": "未在供应商列表中匹配到此模型。\n按默认顺序向符合条件的 API Key 供应商透传原模型名,由上游处理。",
"unconfigured": "此模型暂无路由。可在路由设置中配置默认路由或恢复自动。"
},
- "frozen": "此模型使用已保存的固定路由",
- "follows": "跟随 {{backend}} 的默认路由",
+ "follows": "跟随 {{backend}} 的默认路由,默认路由调整后自动生效。",
"manualHint": "仅此模型。默认路由的调整不会覆盖这些路由项。",
- "editHint": "编辑并保存后,此模型将使用手动路由。",
- "restoreAutomatic": "恢复自动",
- "undoRestore": "撤销恢复",
"undoDone": "已恢复之前的手动草稿。",
"restorePending": "尚未保存,当前仍使用已保存的路由。",
- "afterSave": "保存后的路由",
"preview": {
"automatic": "恢复后:自动匹配",
"passthrough": "恢复后:原名透传",
@@ -1275,15 +1269,14 @@
"noDefaults": "暂无可路由此模型的默认供应商。请加入匹配的供应商或符合条件的 API Key 供应商。",
"inventoryNotProvided": "模型列表未提供",
"configureDefaults": "设置默认路由",
- "defaultRouting": "默认路由",
"close": "关闭",
- "pinRoute": "固定当前路由",
"cancelChanges": "取消修改",
"manualPending": "保存后,此模型将使用手动路由,不再跟随默认路由。",
"exactModel": "准确模型 ID",
"moveUp": "上移供应商",
"moveDown": "下移供应商",
- "counts": "{{inherited}} 个模型跟随默认路由 · {{manual}} 个固定路由"
+ "counts": "{{inherited}} 个模型跟随默认路由 · {{manual}} 个固定路由",
+ "errorShort": "错误"
},
"order": {
"title": "{{backend}} · 默认路由",
@@ -1726,7 +1719,6 @@
"open": "打开 {{model}} 的路由",
"openWithMapping": "打开 {{model}} 的路由 · {{mapping}}",
"label": "这个模型的路由",
- "section": "这个模型的路由",
"removeHop": "移除这个路由项",
"editHop": "修改这个路由项",
"addHop": "添加路由项",
@@ -1776,7 +1768,17 @@
"refreshFail": "路由已保存,但暂时无法刷新显示。",
"done": "完成"
},
- "hint": "此模型已保存固定路由,默认路由的调整不会覆盖它。"
+ "hint": "此模型已保存固定路由,默认路由的调整不会覆盖它。",
+ "mode": {
+ "label": "路由方式",
+ "follow": "跟随默认",
+ "custom": "自定义",
+ "undo": "撤销",
+ "viewDefaults": "查看默认路由",
+ "adjustDefaults": "调整默认路由"
+ },
+ "hopActions": "路由项操作",
+ "modelActions": "模型操作"
},
"recent": {
"title": "最近切换",