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(models): enable route chain editing (#1371)

Call Whitea8714d04516f
diff --git a/ui/src/components/settings/models/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsx
index cc4a34656..be8fd0888 100644
--- a/ui/src/components/settings/models/AgentCard.test.tsx
+++ b/ui/src/components/settings/models/AgentCard.test.tsx
@@ -147,7 +147,7 @@ describe('AgentCard', () => {
await userEvent.click(screen.getByRole('button', { name: /Open claude-opus-4-6 route chain/i }));
- expect(onOpenRoute).toHaveBeenCalledWith(hubAgent, 'claude-opus-4-6');
+ expect(onOpenRoute).toHaveBeenCalledWith(hubAgent, 'claude-opus-4-6', expect.any(HTMLElement));
});
it('replaces the gateway status slot and action with an in-place retry after leaving fails', async () => {
diff --git a/ui/src/components/settings/models/AgentCard.tsx b/ui/src/components/settings/models/AgentCard.tsx
index aae585c00..1759d4d32 100644
--- a/ui/src/components/settings/models/AgentCard.tsx
+++ b/ui/src/components/settings/models/AgentCard.tsx
@@ -38,7 +38,7 @@ const ModelRow: React.FC<{
modelId: string;
sources: Source[];
read: ModelChainRead | undefined;
- onOpenRoute: (agent: AgentSupply, modelId: string) => void;
+ onOpenRoute: (agent: AgentSupply, modelId: string, opener: HTMLElement) => void;
}> = ({ agent, modelId, sources, read, onOpenRoute }) => {
const { t } = useTranslation();
const current = currentLink(read);
@@ -58,7 +58,9 @@ const ModelRow: React.FC<{
return (
<button
type="button"
- onClick={() => onOpenRoute(agent, modelId)}
+ data-route-backend={agent.backend}
+ data-route-model={modelId}
+ onClick={(event) => onOpenRoute(agent, modelId, event.currentTarget)}
aria-label={t('settings.models.routeDialog.open', { model: modelId }) as string}
className="model-hub-model-row flex h-9 w-full min-w-0 items-center gap-2.5 overflow-hidden rounded-lg border border-border px-3 text-left"
>
@@ -82,7 +84,7 @@ const AgentModelCard: React.FC<{
onConnectHub: (agent: AgentSupply) => void;
onSwitchDirect: (agent: AgentSupply) => void;
onOpenOrder: (agent: AgentSupply) => void;
- onOpenRoute: (agent: AgentSupply, modelId: string) => void;
+ onOpenRoute: (agent: AgentSupply, modelId: string, opener: HTMLElement) => void;
onProbeSettled: (agent: AgentSupply) => void;
}> = ({ agent, runtime, sources, chains, pending, connecting, switchFailed, onConnectHub, onSwitchDirect, onOpenOrder, onOpenRoute, onProbeSettled }) => {
const { t } = useTranslation();
@@ -128,7 +130,11 @@ const AgentModelCard: React.FC<{
: 'bg-muted';
return (
<section className="overflow-hidden rounded-xl border border-border bg-background" data-agent-backend={agent.backend}>
- <div className="flex min-h-[66px] flex-col justify-center gap-[7px] border-b border-border px-3.5 py-3 sm:h-[66px] sm:py-0">
+ <div
+ tabIndex={-1}
+ data-agent-group-head={agent.backend}
+ className="flex min-h-[66px] flex-col justify-center gap-[7px] border-b border-border px-3.5 py-3 sm:h-[66px] sm:py-0"
+ >
<div className="flex min-w-0 flex-col items-stretch gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-3">
<div className="flex min-w-0 items-center gap-[9px]">
<span className={cn('flex size-[30px] shrink-0 items-center justify-center rounded-[9px]', ACCENT_TILE[accent])}><Icon className={cn('size-[15px]', ACCENT_ICON[accent])} /></span>
@@ -162,7 +168,7 @@ export const AgentCard: React.FC<{
onConnectHub: (agent: AgentSupply) => void;
onSwitchDirect: (agent: AgentSupply) => void;
onOpenOrder: (agent: AgentSupply) => void;
- onOpenRoute: (agent: AgentSupply, modelId: string) => void;
+ onOpenRoute: (agent: AgentSupply, modelId: string, opener: HTMLElement) => void;
onProbeSettled: (agent: AgentSupply) => void;
connectingBackend: string | null;
}> = ({ agents, pendingBackends, switchFailures, connectingBackend, ...props }) => <div className="flex flex-col gap-4">{agents.map((agent) => <AgentModelCard key={agent.backend} agent={agent} {...props} pending={pendingBackends.has(agent.backend)} switchFailed={switchFailures.has(agent.backend)} connecting={connectingBackend === agent.backend} />)}</div>;
diff --git a/ui/src/components/settings/models/GatewayModule.tsx b/ui/src/components/settings/models/GatewayModule.tsx
index b51b022ea..1f140506e 100644
--- a/ui/src/components/settings/models/GatewayModule.tsx
+++ b/ui/src/components/settings/models/GatewayModule.tsx
@@ -13,9 +13,10 @@ type GatewayModuleProps = Omit<React.ComponentProps<typeof AgentCard>, 'agents'>
runtime: FreshRuntimeProjection | null;
runtimeSnapshot: RuntimeDependency | null;
onRetry: () => void;
+ readFailureCopy?: string;
};
-export const GatewayModule: React.FC<GatewayModuleProps> = ({ runtime, runtimeSnapshot, supply, onRetry, ...props }) => {
+export const GatewayModule: React.FC<GatewayModuleProps> = ({ runtime, runtimeSnapshot, supply, onRetry, readFailureCopy, ...props }) => {
const { t } = useTranslation();
const agents = foldRegionRead<AgentSupply[], AgentSupply[] | undefined>(supply, {
loading: () => undefined,
@@ -36,7 +37,7 @@ export const GatewayModule: React.FC<GatewayModuleProps> = ({ runtime, runtimeSn
: supply.kind === 'unread'
? <div className="flex h-full min-h-36 flex-col items-center justify-center gap-3 px-4 text-center"><p className="text-[12px] text-muted">{t('settings.models.gateway.supply.unread')}</p><Button variant="outline" size="xs" onClick={onRetry}>{t('settings.models.gateway.retry')}</Button></div>
: <>
- {supply.kind === 'degraded' && supply.cause === 'read_failed' && <div className="mb-2 flex items-center justify-between gap-3 rounded-lg border border-destructive/25 bg-destructive/[0.08] px-3 py-2"><p className="text-[11px] text-destructive">{t('settings.models.gateway.supply.unread')}</p><Button variant="outline" size="xs" onClick={onRetry}>{t('settings.models.gateway.retry')}</Button></div>}
+ {supply.kind === 'degraded' && supply.cause === 'read_failed' && <div className="mb-2 flex items-center justify-between gap-3 rounded-lg border border-destructive/25 bg-destructive/[0.08] px-3 py-2"><p className="text-[11px] text-destructive">{readFailureCopy ?? t('settings.models.gateway.supply.unread')}</p><Button variant="outline" size="xs" onClick={onRetry}>{t('settings.models.gateway.retry')}</Button></div>}
<AgentCard agents={agents ?? []} runtime={runtime} {...props} />
</>}
</div>
diff --git a/ui/src/components/settings/models/GuardGapList.tsx b/ui/src/components/settings/models/GuardGapList.tsx
new file mode 100644
index 000000000..1a498d8d0
--- /dev/null
+++ b/ui/src/components/settings/models/GuardGapList.tsx
@@ -0,0 +1,47 @@
+import * as React from "react";
+import { useTranslation } from "react-i18next";
+
+import type { SupplyGap } from "./types";
+
+export const GuardGapList: React.FC<{ gaps: SupplyGap[] }> = ({ gaps }) => {
+ const { t, i18n } = useTranslation();
+ if (gaps.length === 0) return null;
+ return (
+ <>
+ <div className="model-hub-guard-label">
+ <p>{t("settings.models.guard.gap.label")}</p>
+ <span>
+ {t("settings.models.gateway.modelCount", { count: gaps.length })}
+ </span>
+ </div>
+ <div className="model-hub-guard-list">
+ {gaps.map((gap) => (
+ <div
+ key={`${gap.backend}:${gap.model_id}`}
+ className="model-hub-guard-hop"
+ >
+ <span className="min-w-0 flex-1">
+ <strong>
+ {t("settings.models.guard.gap.subject", {
+ backend: t(`settings.models.backends.${gap.backend}`, {
+ defaultValue: gap.backend,
+ }),
+ menuModel: gap.model_id,
+ })}
+ </strong>
+ {gap.agents.length > 0 && (
+ <span>
+ {t("settings.models.guard.gap.agents", {
+ agents: gap.agents.join(
+ i18n.language.startsWith("zh") ? "、" : ", ",
+ ),
+ })}
+ </span>
+ )}
+ </span>
+ </div>
+ ))}
+ </div>
+ </>
+ );
+};
diff --git a/ui/src/components/settings/models/OAuthConnectDialog.tsx b/ui/src/components/settings/models/OAuthConnectDialog.tsx
index 21f95b167..06584cac9 100644
--- a/ui/src/components/settings/models/OAuthConnectDialog.tsx
+++ b/ui/src/components/settings/models/OAuthConnectDialog.tsx
@@ -46,7 +46,7 @@ import {
subscriptionOptionOrder,
subscriptionVendorCopy,
} from './subscriptionOptions';
-import { SupplyGapNote } from './SupplyGapNote';
+import { GuardGapList } from './GuardGapList';
import { ACCENT_ICON, ACCENT_TILE } from './vendorMeta';
import type { Source, SupplyChannel, SupplyGap } from './types';
@@ -770,7 +770,8 @@ export const OAuthConnectDialog: React.FC<{
{/* Past tense (`gapsDone`), because this is not a confirm: the
credential change these pairs are the cost of has already
happened. Self-hides when the failure stranded nobody. */}
- <SupplyGapNote gaps={stranded} title={t('settings.models.repair.gapsDone') as string} />
+ <p className="text-[12px] font-semibold text-foreground">{t('settings.models.repair.gapsDone')}</p>
+ <GuardGapList gaps={stranded} />
</div>
)}
@@ -785,7 +786,7 @@ export const OAuthConnectDialog: React.FC<{
<span className="model-hub-ink-gold text-[12.5px] font-semibold leading-relaxed">
{t('settings.models.repair.gapsDone')}
</span>
- <SupplyGapNote gaps={repair.gaps} />
+ <GuardGapList gaps={repair.gaps} />
</div>
) : repair?.kind === 'unresolved' ? (
// Gold, not destructive, and not a green check: nothing failed —
diff --git a/ui/src/components/settings/models/RouteChainDialog.test.tsx b/ui/src/components/settings/models/RouteChainDialog.test.tsx
index cd5ad6392..a5129b240 100644
--- a/ui/src/components/settings/models/RouteChainDialog.test.tsx
+++ b/ui/src/components/settings/models/RouteChainDialog.test.tsx
@@ -1,61 +1,611 @@
// @vitest-environment jsdom
-import { readFileSync } from 'node:fs';
-import { join } from 'node:path';
+import { act, cleanup, render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { I18nextProvider } from "react-i18next";
+import { afterEach, describe, expect, it, vi } from "vitest";
-import { cleanup, render, screen } from '@testing-library/react';
-import { I18nextProvider } from 'react-i18next';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import i18n from "@/i18n";
+import { ApiCallError, modelsApi } from "./modelsApi";
+import {
+ RouteChainDialog,
+ type RouteCollectionObservation,
+} from "./RouteChainDialog";
+import { routeChainMatchesAttempt } from "./routeChainDraft";
+import { readyRegion } from "./regionRead";
+import type {
+ AgentChain,
+ AgentChainMutation,
+ AgentSupply,
+ Source,
+} from "./types";
-import i18n from '@/i18n';
-import { RouteChainDialog } from './RouteChainDialog';
-import { readyRegion } from './regionRead';
-import type { AgentChain, AgentSupply, Source } from './types';
-
-const agent: AgentSupply = { backend: 'claude', cli_present: true, mode: 'hub', menu_kind: 'fixed' };
+const agent: AgentSupply = {
+ backend: "claude",
+ cli_present: true,
+ mode: "hub",
+ menu_kind: "fixed",
+};
const sources: Source[] = [
- { id: 'src_a', last_discovered_at: null, kind: 'api_key', vendor: 'anthropic', display_name: 'aihub', protocol: 'anthropic', supply_channel: 'hub', billing: 'metered', state: { status: 'active', retry_at: null, detail_key: null }, models: [] },
- { id: 'src_b', last_discovered_at: null, kind: 'subscription', vendor: 'anthropic', display_name: 'Claude subscription', protocol: 'anthropic', supply_channel: 'native_cli', billing: 'monthly', state: { status: 'active', retry_at: null, detail_key: null }, models: [] },
+ {
+ id: "src_a",
+ last_discovered_at: null,
+ kind: "api_key",
+ vendor: "anthropic",
+ display_name: "API key",
+ protocol: "anthropic",
+ supply_channel: "hub",
+ billing: "metered",
+ state: { status: "active", retry_at: null, detail_key: null },
+ models: [],
+ },
+ {
+ id: "src_b",
+ last_discovered_at: null,
+ kind: "subscription",
+ vendor: "anthropic",
+ display_name: "Claude subscription",
+ protocol: "anthropic",
+ supply_channel: "native_cli",
+ billing: "monthly",
+ state: { status: "active", retry_at: null, detail_key: null },
+ models: [],
+ },
];
const chain: AgentChain = {
contract_version: 5,
- backend: 'claude',
- model_id: 'opus-5',
- current: { source_id: 'src_b', model_id: 'opus-5' },
+ backend: "claude",
+ model_id: "opus-5",
+ current: { source_id: "src_b", model_id: "opus-5" },
chain: [
- { source_id: 'src_a', model_id: 'claude-opus-5', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' },
- { source_id: 'src_b', model_id: 'opus-5', channel: 'native_cli', health: 'healthy', runnable: true, reason: null, retry_at: null },
+ {
+ source_id: "src_a",
+ model_id: "claude-opus-5",
+ channel: "hub",
+ health: "cooldown",
+ runnable: false,
+ reason: null,
+ retry_at: "2099-01-01T00:00:00Z",
+ },
+ {
+ source_id: "src_b",
+ model_id: "opus-5",
+ channel: "native_cli",
+ health: "healthy",
+ runnable: true,
+ reason: null,
+ retry_at: null,
+ },
],
- supply_state: 'ok',
+ supply_state: "ok",
+};
+const mutation = (
+ next: AgentChain = chain,
+ report: Partial<Pick<AgentChainMutation, "removed_hops" | "interrupted">> =
+ {},
+): AgentChainMutation => ({
+ chain: next,
+ removed_hops: report.removed_hops ?? [],
+ interrupted: report.interrupted ?? [],
+});
+const observation = <T,>(value: T) => ({ value, install: vi.fn() });
+const deferred = <T,>() => {
+ let resolve!: (value: T) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((accept, decline) => {
+ resolve = accept;
+ reject = decline;
+ });
+ return { promise, reject, resolve };
+};
+const renderDialog = (onCommitted = vi.fn()) => {
+ vi.spyOn(modelsApi, "getAgentChain").mockResolvedValue(chain);
+ return render(
+ <I18nextProvider i18n={i18n}>
+ <RouteChainDialog
+ selection={{ agent, modelId: "opus-5", read: readyRegion(chain) }}
+ sources={sources}
+ onClose={vi.fn()}
+ onCommitted={onCommitted}
+ readAgents={vi.fn().mockResolvedValue(observation([agent]))}
+ readSources={vi.fn().mockResolvedValue(observation(sources))}
+ />
+ </I18nextProvider>,
+ );
};
-afterEach(cleanup);
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
-describe('RouteChainDialog', () => {
- it('renders the contracted chain order and current hop', () => {
- render(<I18nextProvider i18n={i18n}><RouteChainDialog selection={{ agent, modelId: 'opus-5', read: readyRegion(chain) }} sources={sources} onClose={vi.fn()} /></I18nextProvider>);
+describe("RouteChainDialog", () => {
+ it("matches a suspended Direct attempt only by its exact ordered pairs", () => {
+ const attempt = {
+ backend: "claude" as const,
+ modelId: "opus-5",
+ stage: "initial" as const,
+ submitted: [
+ { source_id: "src_b", model_id: "opus-5" },
+ { source_id: "src_a", model_id: "claude-opus-5" },
+ ],
+ };
+ expect(
+ routeChainMatchesAttempt(
+ {
+ ...chain,
+ chain: [chain.chain[1], chain.chain[0]],
+ },
+ attempt,
+ ),
+ ).toBe(true);
+ expect(routeChainMatchesAttempt(chain, attempt)).toBe(false);
+ });
+ it("renders the exact read projection and keeps the current hop identifiable", async () => {
+ renderDialog();
+ await screen.findAllByRole("button", { name: "Remove hop" });
- expect(screen.getByText('opus-5 · Route chain')).toBeTruthy();
+ expect(screen.getByText("opus-5 · Route chain")).toBeTruthy();
const current = document.querySelector('[data-current="true"]');
- expect(current?.textContent).toContain('Claude subscription');
- expect(current?.textContent).toContain('opus-5');
+ expect(current?.textContent).toContain("Claude subscription");
+ expect(current?.textContent).toContain("opus-5");
+ const ordinals = [...document.querySelectorAll(".model-hub-route-ordinal")];
+ expect(ordinals[0]?.className).toContain("model-hub-accent-pill--mint");
+ expect(ordinals[1]?.className).toContain("model-hub-fill-white-0a");
+ expect(screen.getAllByRole("button", { name: "Remove hop" })).toHaveLength(
+ 2,
+ );
+ expect(
+ (screen.getByRole("button", { name: "Save" }) as HTMLButtonElement)
+ .disabled,
+ ).toBe(true);
+ });
+
+ it("saves the changed ordered hop array and consumes the response envelope", async () => {
+ const user = userEvent.setup();
+ const onCommitted = vi.fn();
+ const put = vi
+ .spyOn(modelsApi, "putAgentChain")
+ .mockResolvedValue(mutation());
+ renderDialog(onCommitted);
+ await screen.findAllByRole("button", { name: "Remove hop" });
+
+ await user.click(screen.getAllByRole("button", { name: "Remove hop" })[0]);
+ await user.click(screen.getByRole("button", { name: "Save" }));
+
+ await waitFor(() =>
+ expect(put).toHaveBeenCalledWith("claude", "opus-5", {
+ hops: [{ source_id: "src_b", model_id: "opus-5" }],
+ }),
+ );
+ expect(onCommitted).toHaveBeenCalledWith({
+ chain,
+ removed_hops: [],
+ interrupted: [],
+ });
+ expect(screen.getByText("Done").closest("button")).toBeTruthy();
+ });
+
+ it("renders the complete removed-hop impact after a successful save", async () => {
+ const user = userEvent.setup();
+ const removed = {
+ backend: "claude" as const,
+ menu_model: "opus-5",
+ source_id: "src_a",
+ model_id: "claude-opus-5",
+ position: 1,
+ };
+ vi.spyOn(modelsApi, "putAgentChain").mockResolvedValue(
+ mutation(chain, { removed_hops: [removed] }),
+ );
+ renderDialog();
+ await screen.findAllByRole("button", { name: "Remove hop" });
+
+ await user.click(screen.getAllByRole("button", { name: "Remove hop" })[0]);
+ await user.click(screen.getByRole("button", { name: "Save" }));
+
+ expect(await screen.findByText("Claude Code · opus-5")).toBeTruthy();
+ expect(screen.getByText("claude-opus-5 · Order #1")).toBeTruthy();
});
- it('draws every write control disabled while G-32 remains unresolved', () => {
- render(<I18nextProvider i18n={i18n}><RouteChainDialog selection={{ agent, modelId: 'opus-5', read: readyRegion(chain) }} sources={sources} onClose={vi.fn()} /></I18nextProvider>);
+ it("keeps Done available while page-owned M6 is pending and failed", async () => {
+ const user = userEvent.setup();
+ const removed = {
+ backend: "claude" as const,
+ menu_model: "opus-5",
+ source_id: "src_a",
+ model_id: "claude-opus-5",
+ position: 1,
+ };
+ const put = vi
+ .spyOn(modelsApi, "putAgentChain")
+ .mockResolvedValue(mutation(chain, { removed_hops: [removed] }));
+ const onCommitted = vi.fn();
+ const retry = vi.fn();
+ vi.spyOn(modelsApi, "getAgentChain").mockResolvedValue(chain);
+ const page = render(
+ <I18nextProvider i18n={i18n}>
+ <RouteChainDialog
+ selection={{ agent, modelId: "opus-5", read: readyRegion(chain) }}
+ sources={sources}
+ onClose={vi.fn()}
+ onCommitted={onCommitted}
+ commitReconciliation={{ pending: true, failed: false, retry }}
+ readAgents={vi.fn().mockResolvedValue(observation([agent]))}
+ readSources={vi.fn().mockResolvedValue(observation(sources))}
+ />
+ </I18nextProvider>,
+ );
+ await screen.findAllByRole("button", { name: "Remove hop" });
+ await user.click(screen.getAllByRole("button", { name: "Remove hop" })[0]);
+ await user.click(screen.getByRole("button", { name: "Save" }));
+
+ await waitFor(() => expect(put).toHaveBeenCalledTimes(1));
+ expect(
+ await screen.findByText(
+ "Route chain saved. Refreshing the model surface…",
+ ),
+ ).toBeTruthy();
+ expect(
+ screen.getByText(
+ "These are the items this save actually removed or interrupted.",
+ ),
+ ).toBeTruthy();
+ expect(screen.getByText("Done").closest("button")).toBeTruthy();
+ page.rerender(
+ <I18nextProvider i18n={i18n}>
+ <RouteChainDialog
+ selection={{ agent, modelId: "opus-5", read: readyRegion(chain) }}
+ sources={sources}
+ onClose={vi.fn()}
+ onCommitted={onCommitted}
+ commitReconciliation={{ pending: false, failed: true, retry }}
+ readAgents={vi.fn().mockResolvedValue(observation([agent]))}
+ readSources={vi.fn().mockResolvedValue(observation(sources))}
+ />
+ </I18nextProvider>,
+ );
+ expect(
+ await screen.findByText(
+ "The route chain was saved, but the model surface could not be refreshed.",
+ ),
+ ).toBeTruthy();
+ expect(
+ screen.getByText(
+ "These are the items this save actually removed or interrupted.",
+ ),
+ ).toBeTruthy();
+ await user.click(screen.getByRole("button", { name: "Retry" }));
+ expect(retry).toHaveBeenCalledTimes(1);
+ });
+
+ it("echoes the exact refusal plan on a forced confirmation", async () => {
+ const user = userEvent.setup();
+ const gap = {
+ backend: "claude" as const,
+ model_id: "opus-5",
+ agents: ["writer"],
+ };
+ const hop = {
+ backend: "claude" as const,
+ menu_model: "opus-5",
+ source_id: "src_a",
+ model_id: "claude-opus-5",
+ position: 1,
+ };
+ const put = vi
+ .spyOn(modelsApi, "putAgentChain")
+ .mockRejectedValueOnce(
+ new ApiCallError(
+ "source_last_supplier",
+ undefined,
+ true,
+ [gap],
+ [],
+ [hop],
+ ),
+ )
+ .mockResolvedValueOnce(mutation());
+ renderDialog();
+ await screen.findAllByRole("button", { name: "Remove hop" });
+
+ await user.click(screen.getAllByRole("button", { name: "Remove hop" })[1]);
+ await user.click(screen.getByRole("button", { name: "Save" }));
+ expect(
+ await screen.findByRole("button", { name: "Save anyway" }),
+ ).toBeTruthy();
+ expect(screen.getByText("Save the route chain for opus-5")).toBeTruthy();
+ expect(screen.getByText("Hops that will be removed")).toBeTruthy();
+ expect(screen.getByText("1 hop")).toBeTruthy();
+ expect(
+ screen.getByText((_, element) =>
+ element?.classList.contains("model-hub-guard-hop") === true &&
+ element.textContent?.includes("Order #1") === true,
+ ),
+ ).toBeTruthy();
+ expect(
+ screen.getByText("Some models will be left with no usable source."),
+ ).toBeTruthy();
+ expect(
+ screen.queryByText("Models that will be left with no source"),
+ ).toBeNull();
+ await user.click(screen.getByRole("button", { name: "Save anyway" }));
+
+ await waitFor(() =>
+ expect(put).toHaveBeenLastCalledWith("claude", "opus-5", {
+ hops: [{ source_id: "src_a", model_id: "claude-opus-5" }],
+ force: true,
+ would_remove_hops: [hop],
+ would_interrupt: [gap],
+ }),
+ );
+ });
+
+ it("re-reads the exact chain after an unconfirmed write and never retries the PUT", async () => {
+ const user = userEvent.setup();
+ const committedChain: AgentChain = {
+ ...chain,
+ current: { source_id: "src_b", model_id: "opus-5" },
+ chain: [chain.chain[1]],
+ };
+ const read = vi
+ .spyOn(modelsApi, "getAgentChain")
+ .mockResolvedValueOnce(chain)
+ .mockResolvedValueOnce(committedChain);
+ const put = vi
+ .spyOn(modelsApi, "putAgentChain")
+ .mockRejectedValueOnce(new TypeError("response lost"));
+ renderDialog();
+ await screen.findAllByRole("button", { name: "Remove hop" });
+
+ await user.click(screen.getAllByRole("button", { name: "Remove hop" })[0]);
+ await user.click(screen.getByRole("button", { name: "Save" }));
+ await user.click(await screen.findByRole("button", { name: "Retry" }));
+
+ await waitFor(() => expect(read).toHaveBeenCalledWith("claude", "opus-5"));
+ expect(put).toHaveBeenCalledTimes(1);
+ expect(screen.getByText("Done").closest("button")).toBeTruthy();
+ });
+
+ it("installs a nonmatching D-36 observation without treating it as a retryable write", async () => {
+ const user = userEvent.setup();
+ const observed: AgentChain = {
+ ...chain,
+ chain: [chain.chain[0]],
+ current: null,
+ supply_state: "interrupted",
+ };
+ const read = vi
+ .spyOn(modelsApi, "getAgentChain")
+ .mockResolvedValueOnce(chain)
+ .mockResolvedValueOnce(observed);
+ const put = vi
+ .spyOn(modelsApi, "putAgentChain")
+ .mockRejectedValueOnce(new TypeError("response lost"));
+ const onObserved = vi.fn();
+ render(
+ <I18nextProvider i18n={i18n}>
+ <RouteChainDialog
+ selection={{ agent, modelId: "opus-5", read: readyRegion(chain) }}
+ sources={sources}
+ onClose={vi.fn()}
+ onObserved={onObserved}
+ readAgents={vi.fn().mockResolvedValue(observation([agent]))}
+ readSources={vi.fn().mockResolvedValue(observation(sources))}
+ />
+ </I18nextProvider>,
+ );
+ await screen.findAllByRole("button", { name: "Remove hop" });
+ await user.click(screen.getAllByRole("button", { name: "Remove hop" })[0]);
+ await user.click(screen.getByRole("button", { name: "Save" }));
+ await user.click(await screen.findByRole("button", { name: "Retry" }));
+
+ await waitFor(() => expect(read).toHaveBeenCalledTimes(2));
+ expect(put).toHaveBeenCalledTimes(1);
+ expect(onObserved).toHaveBeenCalledWith(observed);
+ expect(screen.getByText("The save outcome is not confirmed")).toBeTruthy();
+ });
+
+ it("runs D-36 Agents-first and retries only a failed Source member", async () => {
+ const user = userEvent.setup();
+ const nonmatching: AgentChain = {
+ ...chain,
+ chain: [chain.chain[0]],
+ current: null,
+ supply_state: "interrupted",
+ };
+ const agentRead = deferred<RouteCollectionObservation<AgentSupply[]>>();
+ const readAgents = vi.fn().mockReturnValue(agentRead.promise);
+ const readSources = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("sources unread"))
+ .mockResolvedValueOnce(observation(sources));
+ const readChain = vi
+ .spyOn(modelsApi, "getAgentChain")
+ .mockResolvedValueOnce(chain)
+ .mockResolvedValueOnce(nonmatching)
+ .mockResolvedValueOnce(nonmatching);
+ const put = vi
+ .spyOn(modelsApi, "putAgentChain")
+ .mockRejectedValueOnce(new TypeError("response lost"));
+ render(
+ <I18nextProvider i18n={i18n}>
+ <RouteChainDialog
+ selection={{ agent, modelId: "opus-5", read: readyRegion(chain) }}
+ sources={sources}
+ onClose={vi.fn()}
+ readAgents={readAgents}
+ readSources={readSources}
+ />
+ </I18nextProvider>,
+ );
+ await screen.findAllByRole("button", { name: "Remove hop" });
+ await user.click(screen.getAllByRole("button", { name: "Remove hop" })[0]);
+ await user.click(screen.getByRole("button", { name: "Save" }));
+ await user.click(await screen.findByRole("button", { name: "Retry" }));
+ expect(readChain).toHaveBeenCalledTimes(1);
+ expect(readSources).not.toHaveBeenCalled();
+
+ agentRead.resolve(observation([agent]));
+ expect(
+ await screen.findByText("The current model surface could not be read"),
+ ).toBeTruthy();
+ expect(readChain).toHaveBeenCalledTimes(2);
+ expect(readSources).toHaveBeenCalledTimes(1);
+
+ await user.click(screen.getByRole("button", { name: "Retry" }));
+ await waitFor(() => expect(readSources).toHaveBeenCalledTimes(2));
+ expect(readChain).toHaveBeenCalledTimes(2);
+ await user.click(screen.getByRole("button", { name: "Retry" }));
+ await waitFor(() => expect(readChain).toHaveBeenCalledTimes(3));
+ expect(readSources).toHaveBeenCalledTimes(2);
+ expect(put).toHaveBeenCalledTimes(1);
+ });
+
+ it("returns an invalidated pending draft to editing after a named rejection", async () => {
+ const user = userEvent.setup();
+ const pending = deferred<AgentChainMutation>();
+ const editableAgent: AgentSupply = {
+ ...agent,
+ sources: {
+ order: ["src_a", "src_b"],
+ eligibility: [
+ { source_id: "src_a", eligible: true },
+ { source_id: "src_b", eligible: true },
+ ],
+ },
+ };
+ const editableSources: Source[] = [
+ {
+ ...sources[0],
+ models: [
+ { id: "claude-opus-5", origin: "discovered", reasoning_efforts: [] },
+ { id: "claude-sonnet-5", origin: "discovered", reasoning_efforts: [] },
+ ],
+ },
+ {
+ ...sources[1],
+ models: [
+ { id: "opus-5", origin: "discovered", reasoning_efforts: [] },
+ ],
+ },
+ ];
+ vi.spyOn(modelsApi, "getAgentChain").mockResolvedValue(chain);
+ vi.spyOn(modelsApi, "putAgentChain").mockReturnValue(pending.promise);
+ const props = {
+ selection: {
+ agent: editableAgent,
+ modelId: "opus-5",
+ read: readyRegion(chain),
+ },
+ onClose: vi.fn(),
+ readAgents: vi.fn().mockResolvedValue(observation([editableAgent])),
+ readSources: vi.fn().mockResolvedValue(observation(editableSources)),
+ };
+ const page = render(
+ <I18nextProvider i18n={i18n}>
+ <RouteChainDialog {...props} sources={editableSources} />
+ </I18nextProvider>,
+ );
+ await screen.findAllByRole("button", { name: "Remove hop" });
+ await user.click(screen.getByRole("button", { name: "Add a hop" }));
+ await user.click(screen.getByRole("button", { name: "Add" }));
+ await user.click(screen.getByRole("button", { name: "Save" }));
+ expect(await screen.findAllByText("Saving route chain…")).toHaveLength(2);
+
+ const refreshedSources = editableSources.map((source) =>
+ source.id === "src_a"
+ ? { ...source, models: source.models.slice(0, 1) }
+ : source,
+ );
+ page.rerender(
+ <I18nextProvider i18n={i18n}>
+ <RouteChainDialog {...props} sources={refreshedSources} />
+ </I18nextProvider>,
+ );
+ await act(async () => {
+ pending.reject(new ApiCallError("invalid_route"));
+ await pending.promise.catch(() => undefined);
+ });
+
+ expect(
+ await screen.findAllByText(
+ "This edited hop is unavailable after the refresh. Remove it before saving.",
+ ),
+ ).toHaveLength(2);
+ expect(screen.getAllByRole("button", { name: "Remove hop" })).toHaveLength(3);
+ expect(
+ (screen.getByRole("button", { name: "Save" }) as HTMLButtonElement)
+ .disabled,
+ ).toBe(true);
+ });
+
+ it("announces the one-based position of the hop focused after removal", async () => {
+ const user = userEvent.setup();
+ const threeHopChain: AgentChain = {
+ ...chain,
+ chain: [
+ chain.chain[0],
+ chain.chain[1],
+ {
+ ...chain.chain[0],
+ source_id: "src_c",
+ model_id: "claude-haiku-5",
+ },
+ ],
+ };
+ vi.spyOn(modelsApi, "getAgentChain").mockResolvedValue(threeHopChain);
+ render(
+ <I18nextProvider i18n={i18n}>
+ <RouteChainDialog
+ selection={{ agent, modelId: "opus-5", read: readyRegion(threeHopChain) }}
+ sources={sources}
+ onClose={vi.fn()}
+ readAgents={vi.fn().mockResolvedValue(observation([agent]))}
+ readSources={vi.fn().mockResolvedValue(observation(sources))}
+ />
+ </I18nextProvider>,
+ );
+ const removeButtons = await screen.findAllByRole("button", {
+ name: "Remove hop",
+ });
+
+ await user.click(removeButtons[1]);
- for (const name of ['Remove hop', 'Add a hop', 'Reorder by source order', 'Save']) {
- const controls = screen.getAllByRole('button', { name });
- expect(controls.length).toBeGreaterThan(0);
- expect(controls.every((control) => (control as HTMLButtonElement).disabled)).toBe(true);
- }
- expect(screen.getAllByRole('button', { name: 'Cancel' }).every((control) => !(control as HTMLButtonElement).disabled)).toBe(true);
+ expect(screen.getByText("Moved to hop 2.")).toBeTruthy();
+ await waitFor(() =>
+ expect(document.activeElement).toBe(
+ screen.getAllByRole("button", { name: "Reorder this hop" })[1],
+ ),
+ );
});
- it('has no mutation client or write callback wired into the frame', () => {
- const source = readFileSync(join(__dirname, 'RouteChainDialog.tsx'), 'utf8');
- const api = readFileSync(join(__dirname, 'modelsApi.ts'), 'utf8');
+ it("supports the grip keyboard contract and restores the draft on Escape", async () => {
+ const user = userEvent.setup();
+ renderDialog();
+ const grips = await screen.findAllByRole("button", {
+ name: "Reorder this hop",
+ });
- expect(source).not.toMatch(/modelsApi|putAgentChain|onCommit|onSave/);
- expect(api).not.toMatch(/putAgentChain|\/chain[^\n]*jsonInit\(['"]PUT/);
+ await user.click(grips[1]);
+ await user.keyboard("{Space}");
+ expect(grips[1].getAttribute("aria-grabbed")).toBe("true");
+ await user.keyboard("{ArrowUp}");
+ expect(screen.getByText("Moved to hop 1.")).toBeTruthy();
+ await waitFor(() =>
+ expect(document.activeElement).toBe(
+ screen.getAllByRole("button", { name: "Reorder this hop" })[0],
+ ),
+ );
+ await user.keyboard("{Escape}");
+ expect(screen.getByText("Reorder cancelled. Restored to hop 2.")).toBeTruthy();
+ const restoredGrips = screen.getAllByRole("button", {
+ name: "Reorder this hop",
+ });
+ expect(restoredGrips[1].getAttribute("aria-grabbed")).toBe("false");
+ await waitFor(() => expect(document.activeElement).toBe(restoredGrips[1]));
+ expect(
+ (screen.getByRole("button", { name: "Save" }) as HTMLButtonElement)
+ .disabled,
+ ).toBe(true);
});
});
diff --git a/ui/src/components/settings/models/RouteChainDialog.tsx b/ui/src/components/settings/models/RouteChainDialog.tsx
index 7f628cf6c..e21fd82b0 100644
--- a/ui/src/components/settings/models/RouteChainDialog.tsx
+++ b/ui/src/components/settings/models/RouteChainDialog.tsx
@@ -1,75 +1,1221 @@
-import * as React from 'react';
-import * as DialogPrimitive from '@radix-ui/react-dialog';
-import { GripVertical, Info, ListRestart, Plus, X } from 'lucide-react';
-import { useTranslation } from 'react-i18next';
-
-import { Button } from '@/components/ui/button';
-import { cn } from '@/lib/utils';
-import { equalHopIdentity } from './hopIdentity';
-import type { ModelChainRead } from './modelRows';
-import { foldRegionRead } from './regionRead';
-import type { AgentSupply, Source } from './types';
+import * as React from "react";
+import * as DialogPrimitive from "@radix-ui/react-dialog";
+import {
+ GripVertical,
+ Info,
+ ListOrdered,
+ LoaderCircle,
+ Plus,
+ X,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { Button } from "@/components/ui/button";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { cn } from "@/lib/utils";
+import { GuardGapList } from "./GuardGapList";
+import { equalHopIdentity, hopBelongsToSource } from "./hopIdentity";
+import { apiFailure, modelsApi, type GuardConfirmation } from "./modelsApi";
+import type { ModelChainRead } from "./modelRows";
+import {
+ routeCandidates,
+ reorderRouteDraft,
+ sameRouteDraft,
+ validateRouteDraft,
+ type RouteCandidate,
+} from "./routeChainDraft";
+import {
+ advanceRouteChainInteraction,
+ createRouteChainInteraction,
+ type RouteChainInteractionAction,
+} from "./routeChainInteraction";
+import type {
+ AgentChainMutation,
+ AgentSupply,
+ RouteHop,
+ RouteHopRef,
+ Source,
+} from "./types";
const sourceName = (sources: Source[], sourceId: string): string =>
sources.find((source) => source.id === sourceId)?.display_name ?? sourceId;
+type GuardState = {
+ hops: RouteHopRef[];
+ gaps: NonNullable<GuardConfirmation["would_interrupt"]>;
+};
+export type RouteReport = {
+ chain: AgentChainMutation["chain"];
+ removed_hops: RouteHopRef[] | null;
+ interrupted: AgentChainMutation["interrupted"] | null;
+};
+type Phase =
+ | "loading"
+ | "ready"
+ | "unread"
+ | "saving"
+ | "guard"
+ | "rejected"
+ | "unknown"
+ | "impact"
+ | "refreshing"
+ | "reconciling"
+ | "direct";
+type ReconcileMember = "agents" | "sources" | "chain";
+type UnknownObservation = "none" | "nonmatching" | "read_failed";
+
export type RouteChainSelection = {
agent: AgentSupply;
modelId: string;
read: ModelChainRead | undefined;
+ available?: boolean;
+};
+export type RouteCollectionObservation<T> = {
+ value: T;
+ install: () => void;
+};
+export type RouteCommitReconciliation = {
+ pending: boolean;
+ failed: boolean;
+ retry: () => void;
+};
+export type SuspendedRouteAttempt = {
+ backend: AgentSupply["backend"];
+ modelId: string;
+ stage: "initial" | "confirmed";
+ submitted: RouteHop[];
};
export const RouteChainDialog: React.FC<{
selection: RouteChainSelection | null;
sources: Source[];
onClose: () => void;
-}> = ({ selection, sources, onClose }) => {
+ onCommitted?: (result: RouteReport) => void;
+ commitReconciliation?: RouteCommitReconciliation | null;
+ onObserved?: (chain: AgentChainMutation["chain"]) => void;
+ readAgents: () => Promise<RouteCollectionObservation<AgentSupply[]>>;
+ readSources: () => Promise<RouteCollectionObservation<Source[]>>;
+ onDirectMode?: (
+ attempt: SuspendedRouteAttempt | null,
+ observedAgent: AgentSupply | null,
+ ) => void;
+}> = ({
+ selection,
+ sources,
+ onClose,
+ onCommitted,
+ commitReconciliation,
+ onObserved,
+ readAgents,
+ readSources,
+ onDirectMode,
+}) => {
const { t } = useTranslation();
+ const [phase, setPhase] = React.useState<Phase>("loading");
+ const [origin, setOrigin] = React.useState<RouteHop[]>([]);
+ const interactionRef = React.useRef(createRouteChainInteraction());
+ const [interaction, setInteraction] = React.useState(interactionRef.current);
+ const [chain, setChain] = React.useState<AgentChainMutation["chain"] | null>(
+ null,
+ );
+ const [guard, setGuard] = React.useState<GuardState | null>(null);
+ const [submitted, setSubmitted] = React.useState<RouteHop[] | null>(null);
+ const [submittedStage, setSubmittedStage] =
+ React.useState<SuspendedRouteAttempt["stage"]>("initial");
+ const [report, setReport] = React.useState<RouteReport | null>(null);
+ const [reconcileFailed, setReconcileFailed] = React.useState(false);
+ const [failedMembers, setFailedMembers] = React.useState<
+ ReadonlySet<ReconcileMember>
+ >(() => new Set());
+ const [unknownObservation, setUnknownObservation] =
+ React.useState<UnknownObservation>("none");
+ const [unknownSourceCurrent, setUnknownSourceCurrent] = React.useState(false);
+ const [selectorOpen, setSelectorOpen] = React.useState(false);
+ const [candidate, setCandidate] = React.useState<RouteCandidate | null>(null);
+ const [announcement, setAnnouncement] = React.useState<{
+ key: string;
+ params?: Record<string, unknown>;
+ } | null>(null);
+ const gripRefs = React.useRef<Array<HTMLButtonElement | null>>([]);
+ const removeRefs = React.useRef<Array<HTMLButtonElement | null>>([]);
+ const candidateRefs = React.useRef<Array<HTMLButtonElement | null>>([]);
+ const addButtonRef = React.useRef<HTMLButtonElement | null>(null);
+ const reseedButtonRef = React.useRef<HTMLButtonElement | null>(null);
+ const cancelButtonRef = React.useRef<HTMLButtonElement | null>(null);
+ const saveButtonRef = React.useRef<HTMLButtonElement | null>(null);
+ const savingStatusRef = React.useRef<HTMLSpanElement | null>(null);
+ const retryButtonRef = React.useRef<HTMLButtonElement | null>(null);
+ const doneButtonRef = React.useRef<HTMLButtonElement | null>(null);
+ const openedIdentity = React.useRef<string | null>(null);
+ const invalidSignature = React.useRef("");
+ const generation = React.useRef(0);
+
+ const agent = selection?.agent ?? null;
+ const modelId = selection?.modelId ?? "";
+ const selectionBackend = selection?.agent.backend;
+ const draft = interaction.draft;
+ const rovingIndex = interaction.focusIndex;
+ const grabbed = interaction.grab?.index ?? null;
+ const advanceInteraction = React.useCallback(
+ (action: RouteChainInteractionAction) => {
+ const next = advanceRouteChainInteraction(interactionRef.current, action);
+ interactionRef.current = next;
+ setInteraction(next);
+ return next;
+ },
+ [],
+ );
+ const candidates = agent ? routeCandidates(agent, sources, draft) : [];
+ const candidateGroups = candidates.reduce<
+ Array<{
+ source: Source;
+ items: Array<{ candidate: RouteCandidate; index: number }>;
+ }>
+ >((groups, item, index) => {
+ const previous = groups.at(-1);
+ if (previous?.source.id === item.source.id) {
+ previous.items.push({ candidate: item, index });
+ } else {
+ groups.push({ source: item.source, items: [{ candidate: item, index }] });
+ }
+ return groups;
+ }, []);
+ const backend = agent
+ ? (t(`settings.models.backends.${agent.backend}`, {
+ defaultValue: agent.backend,
+ }) as string)
+ : "";
+ const valid = agent
+ ? validateRouteDraft(agent, sources, origin, draft)
+ : { invalidIndexes: [], valid: false };
+ const dirty = !sameRouteDraft(origin, draft);
+ const announce = (key: string, params?: Record<string, unknown>) =>
+ setAnnouncement({ key, params });
+ const focusAfterRender = (ref: React.RefObject<HTMLElement | null>) => {
+ requestAnimationFrame(() => ref.current?.focus());
+ };
+
+ const readChain = React.useCallback(async () => {
+ if (!selectionBackend) return;
+ const token = ++generation.current;
+ setPhase("loading");
+ try {
+ const next = await modelsApi.getAgentChain(selectionBackend, modelId);
+ if (token !== generation.current) return;
+ const hops = next.chain.map(({ source_id, model_id }) => ({
+ source_id,
+ model_id,
+ }));
+ setChain(next);
+ onObserved?.(next);
+ setOrigin(hops);
+ advanceInteraction({ type: "reset", draft: hops, focusIndex: 0 });
+ setGuard(null);
+ setPhase("ready");
+ } catch (error) {
+ if (token !== generation.current) return;
+ if (apiFailure(error)?.code === "direct_mode") {
+ setPhase("direct");
+ onDirectMode?.(null, null);
+ return;
+ }
+ setPhase("unread");
+ requestAnimationFrame(() => retryButtonRef.current?.focus());
+ }
+ }, [advanceInteraction, modelId, onDirectMode, onObserved, selectionBackend]);
+
+ React.useEffect(() => {
+ const nextIdentity = selection
+ ? `${selection.agent.backend}\u0000${selection.modelId}`
+ : null;
+ if (nextIdentity === openedIdentity.current) return;
+ openedIdentity.current = nextIdentity;
+ generation.current += 1;
+ setGuard(null);
+ setSubmitted(null);
+ setSubmittedStage("initial");
+ setReport(null);
+ setReconcileFailed(false);
+ setFailedMembers(new Set());
+ setUnknownObservation("none");
+ setUnknownSourceCurrent(false);
+ setSelectorOpen(false);
+ setCandidate(null);
+ advanceInteraction({ type: "reset", draft: [], focusIndex: 0 });
+ if (selection) void readChain();
+ }, [advanceInteraction, readChain, selection]);
+
+ React.useEffect(() => {
+ if (
+ !selection ||
+ selection.available !== false ||
+ phase === "impact" ||
+ phase === "refreshing"
+ ) {
+ return;
+ }
+ generation.current += 1;
+ onClose();
+ }, [onClose, phase, selection]);
+
+ React.useEffect(() => {
+ if (selectorOpen) candidateRefs.current[0]?.focus();
+ }, [selectorOpen]);
+
+ React.useEffect(() => {
+ const signature = valid.invalidIndexes.join(",");
+ if (!signature) {
+ invalidSignature.current = "";
+ return;
+ }
+ if (phase !== "ready" && phase !== "rejected") return;
+ if (signature === invalidSignature.current) return;
+ invalidSignature.current = signature;
+ if (phase === "rejected") setPhase("ready");
+ setSelectorOpen(false);
+ setCandidate(null);
+ advanceInteraction({ type: "drop-grab" });
+ focusAfterRender({
+ current: removeRefs.current[valid.invalidIndexes[0]] ?? null,
+ });
+ }, [advanceInteraction, phase, valid.invalidIndexes]);
+
+ React.useEffect(() => {
+ if (!report || !commitReconciliation) return;
+ setReconcileFailed(commitReconciliation.failed);
+ setPhase(commitReconciliation.pending ? "refreshing" : "impact");
+ if (commitReconciliation.failed) focusAfterRender(retryButtonRef);
+ }, [commitReconciliation, report]);
+
+ const focusAfterSelectorClose = () => {
+ requestAnimationFrame(() => addButtonRef.current?.focus());
+ };
+
+ const close = () => {
+ if (phase === "guard") {
+ setGuard(null);
+ setPhase("ready");
+ focusAfterRender(saveButtonRef);
+ return;
+ }
+ if (phase !== "saving") {
+ if (phase !== "impact" && phase !== "refreshing") {
+ generation.current += 1;
+ }
+ onClose();
+ }
+ };
+ const remove = (index: number) => {
+ if (phase === "saving" || phase === "impact" || phase === "refreshing")
+ return;
+ const next = advanceInteraction({ type: "remove", index });
+ const nextDraft = next.draft;
+ const focusedIndex = next.focusIndex;
+ requestAnimationFrame(() => {
+ if (nextDraft.length > 0) {
+ gripRefs.current[focusedIndex]?.focus();
+ } else if (candidates.length > 0) {
+ addButtonRef.current?.focus();
+ } else if (reseedButtonRef.current && !reseedButtonRef.current.disabled) {
+ reseedButtonRef.current.focus();
+ } else {
+ cancelButtonRef.current?.focus();
+ }
+ });
+ if (nextDraft.length > 0) {
+ announce("settings.models.routeDialog.reorder.position", {
+ position: focusedIndex + 1,
+ });
+ }
+ };
+ const moveGrab = (action: RouteChainInteractionAction) => {
+ const previous = interactionRef.current;
+ const next = advanceInteraction(action);
+ if (next.focusIndex === previous.focusIndex) return;
+ requestAnimationFrame(() => gripRefs.current[next.focusIndex]?.focus());
+ announce("settings.models.routeDialog.reorder.position", {
+ position: next.focusIndex + 1,
+ });
+ };
+ const onGripKeyDown = (
+ event: React.KeyboardEvent<HTMLButtonElement>,
+ index: number,
+ ) => {
+ if (event.key === "Tab" && grabbed !== null) {
+ const next = advanceInteraction({ type: "drop-grab" });
+ announce("settings.models.routeDialog.reorder.dropped", {
+ position: next.focusIndex + 1,
+ });
+ } else if (
+ event.key === " " ||
+ event.key === "Space" ||
+ event.key === "Spacebar" ||
+ event.code === "Space"
+ ) {
+ event.preventDefault();
+ if (grabbed === index) {
+ const next = advanceInteraction({ type: "drop-grab" });
+ announce("settings.models.routeDialog.reorder.dropped", {
+ position: next.focusIndex + 1,
+ });
+ } else {
+ const next = advanceInteraction({ type: "begin-grab", index });
+ announce("settings.models.routeDialog.reorder.grabbed", {
+ position: next.focusIndex + 1,
+ });
+ }
+ } else if (event.key === "Escape" && grabbed !== null) {
+ event.preventDefault();
+ const next = advanceInteraction({ type: "cancel-grab" });
+ requestAnimationFrame(() => gripRefs.current[next.focusIndex]?.focus());
+ announce("settings.models.routeDialog.reorder.cancelled", {
+ position: next.focusIndex + 1,
+ });
+ } else if (event.key === "ArrowUp" || event.key === "ArrowDown") {
+ event.preventDefault();
+ if (grabbed === null) {
+ const target = Math.max(
+ 0,
+ Math.min(draft.length - 1, index + (event.key === "ArrowUp" ? -1 : 1)),
+ );
+ const next = advanceInteraction({ type: "focus", index: target });
+ gripRefs.current[next.focusIndex]?.focus();
+ } else {
+ moveGrab({
+ type: "move-grab",
+ direction: event.key === "ArrowUp" ? -1 : 1,
+ });
+ }
+ } else if (event.key === "Home" || event.key === "End") {
+ event.preventDefault();
+ if (grabbed === null) {
+ const next = advanceInteraction({
+ type: "focus",
+ index: event.key === "Home" ? 0 : draft.length - 1,
+ });
+ gripRefs.current[next.focusIndex]?.focus();
+ } else {
+ moveGrab({
+ type: "move-grab-edge",
+ edge: event.key === "Home" ? "start" : "end",
+ });
+ }
+ }
+ };
+ const beginCommitted = (
+ nextReport: RouteReport,
+ committedHops: RouteHop[],
+ ) => {
+ generation.current += 1;
+ setChain(nextReport.chain);
+ setReport(nextReport);
+ setOrigin(committedHops);
+ advanceInteraction({ type: "reset", draft: committedHops });
+ setUnknownObservation("none");
+ setUnknownSourceCurrent(false);
+ onCommitted?.(nextReport);
+ setPhase(
+ nextReport.removed_hops?.length || nextReport.interrupted?.length
+ ? "impact"
+ : "refreshing",
+ );
+ focusAfterRender(doneButtonRef);
+ };
+
+ const submit = async (confirmation?: GuardState) => {
+ if (!selection || !agent || phase === "saving" || !valid.valid || !dirty)
+ return;
+ const hops = (confirmation ? (submitted ?? draft) : draft).map((hop) => ({
+ ...hop,
+ }));
+ setSubmitted(hops);
+ setSubmittedStage(confirmation ? "confirmed" : "initial");
+ setPhase("saving");
+ setGuard(null);
+ requestAnimationFrame(() => savingStatusRef.current?.focus());
+ try {
+ const result = await modelsApi.putAgentChain(agent.backend, modelId, {
+ hops,
+ ...(confirmation
+ ? {
+ force: true as const,
+ would_remove_hops: confirmation.hops,
+ would_interrupt: confirmation.gaps,
+ }
+ : {}),
+ });
+ beginCommitted(
+ {
+ chain: result.chain,
+ removed_hops: result.removed_hops,
+ interrupted: result.interrupted,
+ },
+ hops,
+ );
+ } catch (error) {
+ const failure = apiFailure(error);
+ if (failure?.code === "direct_mode") {
+ setPhase("direct");
+ onDirectMode?.(
+ {
+ backend: agent.backend,
+ modelId,
+ stage: confirmation ? "confirmed" : "initial",
+ submitted: hops,
+ },
+ null,
+ );
+ return;
+ }
+ if (
+ failure?.code === "source_last_supplier" &&
+ failure.wouldInterrupt.length > 0
+ ) {
+ setGuard({
+ hops: failure.wouldRemoveHops,
+ gaps: failure.wouldInterrupt,
+ });
+ setPhase("guard");
+ focusAfterRender(cancelButtonRef);
+ return;
+ }
+ const nextPhase = failure?.serverNamed ? "rejected" : "unknown";
+ setPhase(nextPhase);
+ focusAfterRender(retryButtonRef);
+ }
+ };
+
+ const reconcileUnknownMembers = async (
+ token: number,
+ members: ReadonlySet<ReconcileMember>,
+ ) => {
+ if (!selectionBackend || !submitted) return;
+ const [sourceAnswer, chainAnswer] = await Promise.all([
+ members.has("sources")
+ ? readSources().then(
+ (observation) => ({ kind: "success" as const, observation }),
+ () => ({ kind: "failed" as const }),
+ )
+ : Promise.resolve({ kind: "skipped" as const }),
+ members.has("chain")
+ ? modelsApi.getAgentChain(selectionBackend, modelId).then(
+ (value) => ({ kind: "success" as const, value }),
+ (error) =>
+ apiFailure(error)?.code === "direct_mode"
+ ? { kind: "direct" as const }
+ : { kind: "failed" as const },
+ )
+ : Promise.resolve({ kind: "skipped" as const }),
+ ]);
+ if (token !== generation.current) return;
+ const sourceCurrent =
+ sourceAnswer.kind === "skipped"
+ ? unknownSourceCurrent
+ : sourceAnswer.kind === "success";
+ setUnknownSourceCurrent(sourceCurrent);
+ if (sourceAnswer.kind === "success") sourceAnswer.observation.install();
+
+ if (chainAnswer.kind === "direct") {
+ try {
+ const observation = await readAgents();
+ if (token !== generation.current) return;
+ observation.install();
+ const observedAgent = observation.value.find(
+ (row) => row.backend === selectionBackend,
+ );
+ onDirectMode?.(
+ {
+ backend: selectionBackend,
+ modelId,
+ stage: submittedStage,
+ submitted,
+ },
+ observedAgent ?? null,
+ );
+ } catch {
+ if (token !== generation.current) return;
+ setFailedMembers(new Set(["agents"]));
+ setReconcileFailed(true);
+ setPhase("unknown");
+ focusAfterRender(retryButtonRef);
+ }
+ return;
+ }
+
+ if (chainAnswer.kind === "success") {
+ onObserved?.(chainAnswer.value);
+ setChain(chainAnswer.value);
+ const observedHops = chainAnswer.value.chain.map(
+ ({ source_id, model_id }) => ({ source_id, model_id }),
+ );
+ if (sameRouteDraft(observedHops, submitted)) {
+ beginCommitted(
+ {
+ chain: chainAnswer.value,
+ removed_hops: null,
+ interrupted: null,
+ },
+ observedHops,
+ );
+ return;
+ }
+ setUnknownObservation("nonmatching");
+ } else if (chainAnswer.kind === "failed") {
+ setUnknownObservation("read_failed");
+ }
+
+ const failed = new Set<ReconcileMember>();
+ if (!sourceCurrent) failed.add("sources");
+ if (chainAnswer.kind === "failed") failed.add("chain");
+ setFailedMembers(failed);
+ setReconcileFailed(failed.size > 0);
+ setPhase("unknown");
+ focusAfterRender(retryButtonRef);
+ };
+
+ const retryUnknown = async () => {
+ if (!selectionBackend || !submitted || phase !== "unknown") return;
+ const token = ++generation.current;
+ cancelButtonRef.current?.focus();
+ setPhase("reconciling");
+ setReconcileFailed(false);
+
+ const retrySourceOnly =
+ failedMembers.size === 1 && failedMembers.has("sources");
+ const retryChainOnly =
+ (failedMembers.size === 1 && failedMembers.has("chain")) ||
+ (failedMembers.size === 0 &&
+ unknownObservation === "nonmatching" &&
+ unknownSourceCurrent);
+ if (retrySourceOnly) {
+ await reconcileUnknownMembers(token, new Set(["sources"]));
+ return;
+ }
+ if (retryChainOnly) {
+ await reconcileUnknownMembers(token, new Set(["chain"]));
+ return;
+ }
+ if (failedMembers.size > 0 && !failedMembers.has("agents")) {
+ await reconcileUnknownMembers(token, failedMembers);
+ return;
+ }
+
+ try {
+ const observation = await readAgents();
+ if (token !== generation.current) return;
+ observation.install();
+ const observedAgent = observation.value.find(
+ (row) => row.backend === selectionBackend,
+ );
+ if (!observedAgent) throw new Error("route_agent_missing");
+ if (observedAgent.mode === "direct") {
+ onDirectMode?.(
+ {
+ backend: selectionBackend,
+ modelId,
+ stage: submittedStage,
+ submitted,
+ },
+ observedAgent,
+ );
+ return;
+ }
+ await reconcileUnknownMembers(token, new Set(["sources", "chain"]));
+ } catch {
+ if (token !== generation.current) return;
+ setFailedMembers(new Set(["agents"]));
+ setReconcileFailed(true);
+ setPhase("unknown");
+ focusAfterRender(retryButtonRef);
+ }
+ };
+
+ const retryCommittedRead = () => {
+ if (!report || phase !== "impact" || !commitReconciliation?.failed) return;
+ doneButtonRef.current?.focus();
+ commitReconciliation.retry();
+ };
+ const chooseCandidate = (next: RouteCandidate) => {
+ setCandidate(next);
+ };
+ const moveCandidateFocus = (index: number) => {
+ const nextIndex = Math.max(0, Math.min(candidates.length - 1, index));
+ const next = candidates[nextIndex];
+ if (!next) return;
+ setCandidate(next);
+ candidateRefs.current[nextIndex]?.focus();
+ };
+ const onCandidateKeyDown = (
+ event: React.KeyboardEvent<HTMLButtonElement>,
+ index: number,
+ ) => {
+ if (event.key === "ArrowDown" || event.key === "ArrowRight") {
+ event.preventDefault();
+ moveCandidateFocus(index + 1);
+ } else if (event.key === "ArrowUp" || event.key === "ArrowLeft") {
+ event.preventDefault();
+ moveCandidateFocus(index - 1);
+ } else if (event.key === "Home") {
+ event.preventDefault();
+ moveCandidateFocus(0);
+ } else if (event.key === "End") {
+ event.preventDefault();
+ moveCandidateFocus(candidates.length - 1);
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ setSelectorOpen(false);
+ setCandidate(null);
+ focusAfterSelectorClose();
+ }
+ };
+ const addCandidate = () => {
+ if (!candidate) return;
+ const next = advanceInteraction({ type: "append", hop: candidate.hop });
+ setSelectorOpen(false);
+ setCandidate(null);
+ requestAnimationFrame(() => gripRefs.current[next.focusIndex]?.focus());
+ };
+ const renderHop = (hop: RouteHop, index: number) => {
+ const chainLink = chain?.chain.find((entry) =>
+ equalHopIdentity(entry, hop),
+ );
+ const missing = chainLink?.reason === "source_missing";
+ const joined = sources.some((source) => hopBelongsToSource(hop, source.id));
+ const displayedSource = missing
+ ? `${t("settings.models.routeDialog.sourceMissing")} · ${hop.source_id}`
+ : joined
+ ? sourceName(sources, hop.source_id)
+ : hop.source_id;
+ const chainCurrent = chain ? chain.current : null;
+ const current = equalHopIdentity(chainCurrent, hop);
+ return (
+ <div
+ key={`${hop.source_id}:${hop.model_id}:${index}`}
+ onDragOver={(event) => event.preventDefault()}
+ onDrop={(event) => {
+ event.preventDefault();
+ if (grabbed !== null) {
+ advanceInteraction({
+ type: "move-grab-to",
+ index,
+ });
+ advanceInteraction({ type: "drop-grab" });
+ }
+ }}
+ data-current={current || undefined}
+ className="model-hub-route-hop model-hub-fill-white-08 flex items-center border border-border"
+ >
+ <button
+ ref={(node) => {
+ gripRefs.current[index] = node;
+ }}
+ type="button"
+ aria-label={t("settings.models.routeDialog.grip") as string}
+ aria-grabbed={grabbed === index}
+ onMouseDown={(event) => event.currentTarget.focus()}
+ onClick={(event) => event.currentTarget.focus()}
+ draggable={phase === "ready"}
+ onDragStart={() => {
+ advanceInteraction({ type: "begin-grab", index });
+ }}
+ onDragEnd={() => {
+ advanceInteraction({ type: "drop-grab" });
+ }}
+ onFocus={() => advanceInteraction({ type: "focus", index })}
+ onKeyDown={(event) => onGripKeyDown(event, index)}
+ tabIndex={
+ grabbed === index || (grabbed === null && rovingIndex === index)
+ ? 0
+ : -1
+ }
+ className="model-hub-route-grip grid shrink-0 place-items-center"
+ >
+ <GripVertical aria-hidden="true" />
+ </button>
+ <span
+ className={cn(
+ "model-hub-route-ordinal grid shrink-0 place-items-center font-mono font-medium",
+ index === 0
+ ? "model-hub-accent-pill--mint"
+ : "model-hub-fill-white-0a text-muted",
+ )}
+ >
+ {index + 1}
+ </span>
+ <span className="model-hub-route-hop-copy flex min-w-0 flex-1 flex-col">
+ <span
+ className="model-hub-route-hop-name truncate font-semibold text-foreground"
+ title={displayedSource}
+ >
+ {missing ? (
+ <>
+ {t("settings.models.routeDialog.sourceMissing")}
+ <span className="font-mono"> · {hop.source_id}</span>
+ </>
+ ) : !joined ? (
+ <span className="font-mono">{hop.source_id}</span>
+ ) : (
+ sourceName(sources, hop.source_id)
+ )}
+ </span>
+ <span
+ className="model-hub-route-hop-model model-hub-ink-muted-b3 truncate font-mono"
+ title={hop.model_id}
+ >
+ {hop.model_id}
+ </span>
+ {valid.invalidIndexes.includes(index) && (
+ <span
+ id={`model-hub-route-invalid-${index}`}
+ className="model-hub-route-invalid"
+ >
+ {t("settings.models.routeDialog.invalidAfterRefresh")}
+ </span>
+ )}
+ </span>
+ <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"
+ }
+ onClick={() => remove(index)}
+ className="model-hub-route-remove model-hub-fill-white-0a grid shrink-0 place-items-center border border-border text-muted"
+ >
+ <X aria-hidden="true" />
+ </button>
+ </div>
+ );
+ };
+
if (!selection) return null;
- const { agent, modelId, read } = selection;
- const chain = read ? foldRegionRead(read, {
- loading: () => null,
- ready: (value) => value,
- unread: () => null,
- degraded: () => null,
- }) : null;
- const backend = t(`settings.models.backends.${agent.backend}`, { defaultValue: agent.backend }) as string;
+ const body =
+ phase === "loading" ? (
+ <div className="model-hub-route-body flex flex-1 items-center justify-center gap-2 text-muted">
+ <LoaderCircle className="size-4 animate-spin" />
+ {t("settings.models.routeDialog.loading")}
+ </div>
+ ) : phase === "unread" ? (
+ <div className="model-hub-route-body flex flex-1 flex-col items-center justify-center gap-3 text-muted">
+ <p>{t("settings.models.routeDialog.fail.read")}</p>
+ <Button
+ ref={retryButtonRef}
+ type="button"
+ onClick={() => {
+ cancelButtonRef.current?.focus();
+ void readChain();
+ }}
+ >
+ {t("settings.models.routeDialog.retry")}
+ </Button>
+ </div>
+ ) : phase === "direct" ? (
+ <div className="model-hub-route-body flex flex-1 items-center justify-center text-muted">
+ {t("settings.models.routeDialog.fail.read")}
+ </div>
+ ) : phase === "saving" ? (
+ <div className="model-hub-route-body flex flex-1 items-center justify-center gap-2 text-muted">
+ <LoaderCircle className="size-4 animate-spin" />
+ <span ref={savingStatusRef} role="status" tabIndex={-1}>
+ {t("settings.models.routeDialog.saving")}
+ </span>
+ </div>
+ ) : phase === "guard" && guard ? (
+ <div className="model-hub-route-body flex flex-1 flex-col gap-4">
+ <div className="model-hub-guard-label">
+ <p>{t("settings.models.guard.label")}</p>
+ <span>{t("settings.models.guard.count", { count: guard.hops.length })}</span>
+ </div>
+ <ul className="model-hub-guard-list">
+ {guard.hops.map((hop) => (
+ <li
+ key={`${hop.backend}:${hop.menu_model}:${hop.position}`}
+ className="model-hub-guard-hop"
+ >
+ <span className="min-w-0 flex-1">
+ <strong>
+ {t(`settings.models.backends.${hop.backend}`, {
+ defaultValue: hop.backend,
+ })} · {hop.menu_model}
+ </strong>
+ <span>
+ {hop.model_id} · {t("settings.models.guard.hop.position", {
+ n: hop.position,
+ })}
+ </span>
+ </span>
+ </li>
+ ))}
+ </ul>
+ <p className="model-hub-guard-hint text-destructive">
+ <Info aria-hidden="true" />
+ {t("settings.models.guard.hint.interrupt")}
+ </p>
+ </div>
+ ) : phase === "rejected" ? (
+ <div className="model-hub-route-body flex flex-1 flex-col items-center justify-center gap-3 text-muted">
+ <p>{t("settings.models.routeDialog.fail.save")}</p>
+ <Button
+ ref={retryButtonRef}
+ type="button"
+ disabled={!valid.valid}
+ onClick={() => {
+ generation.current += 1;
+ void submit();
+ }}
+ >
+ {t("settings.models.routeDialog.retry")}
+ </Button>
+ </div>
+ ) : phase === "unknown" || phase === "reconciling" ? (
+ <div className="model-hub-route-body flex flex-1 flex-col items-center justify-center gap-3 text-muted">
+ <p>
+ {t(
+ reconcileFailed
+ ? "settings.models.routeDialog.fail.reconcileRead"
+ : "settings.models.routeDialog.fail.unconfirmed",
+ )}
+ </p>
+ <Button
+ ref={retryButtonRef}
+ type="button"
+ disabled={phase === "reconciling"}
+ onClick={() => void retryUnknown()}
+ >
+ {t("settings.models.routeDialog.retry")}
+ </Button>
+ </div>
+ ) : phase === "impact" || phase === "refreshing" ? (
+ <div className="model-hub-route-body flex flex-1 flex-col gap-4">
+ <h3 className="model-hub-route-label font-bold">
+ {t("settings.models.routeDialog.impact.title")}
+ </h3>
+ {report?.removed_hops?.length ? (
+ <ul className="model-hub-guard-list">
+ {report.removed_hops.map((hop) => (
+ <li
+ key={`${hop.backend}:${hop.menu_model}:${hop.position}:${hop.source_id}:${hop.model_id}`}
+ className="model-hub-guard-hop"
+ >
+ <span className="min-w-0 flex-1">
+ <strong>
+ {t(`settings.models.backends.${hop.backend}`, {
+ defaultValue: hop.backend,
+ })} · {hop.menu_model}
+ </strong>
+ <span>
+ {hop.model_id} · {t("settings.models.guard.hop.position", {
+ n: hop.position,
+ })}
+ </span>
+ </span>
+ </li>
+ ))}
+ </ul>
+ ) : null}
+ <GuardGapList gaps={report?.interrupted ?? []} />
+ {Boolean(report?.removed_hops?.length || report?.interrupted?.length) && (
+ <p className="text-xs text-muted">
+ {t("settings.models.routeDialog.impact.detail")}
+ </p>
+ )}
+ {phase === "refreshing" && (
+ <p className="text-xs text-muted">
+ {t("settings.models.routeDialog.refreshing")}
+ </p>
+ )}
+ {reconcileFailed && (
+ <p className="text-xs text-muted">
+ {t("settings.models.routeDialog.impact.refreshFail")}
+ </p>
+ )}
+ {reconcileFailed && commitReconciliation?.failed && (
+ <Button
+ ref={retryButtonRef}
+ type="button"
+ disabled={phase === "refreshing"}
+ onClick={() => void retryCommittedRead()}
+ >
+ {t("settings.models.routeDialog.retry")}
+ </Button>
+ )}
+ </div>
+ ) : (
+ <div className="model-hub-route-body flex flex-col">
+ <h3 className="model-hub-route-label font-bold">
+ {t("settings.models.routeDialog.section")}
+ </h3>
+ <div className="model-hub-route-list flex flex-col border border-border bg-background">
+ {draft.length ? (
+ draft.map(renderHop)
+ ) : (
+ <div className="model-hub-route-empty text-xs text-muted">
+ {t("settings.models.routeDialog.empty")}
+ </div>
+ )}
+ <Popover
+ open={selectorOpen}
+ onOpenChange={(open) => {
+ setSelectorOpen(open);
+ setCandidate(open ? (candidates[0] ?? null) : null);
+ if (!open) focusAfterSelectorClose();
+ }}
+ >
+ <PopoverTrigger asChild>
+ <button
+ ref={addButtonRef}
+ type="button"
+ disabled={candidates.length === 0}
+ aria-describedby={
+ candidates.length === 0
+ ? "model-hub-route-add-none"
+ : undefined
+ }
+ className="model-hub-route-add model-hub-fill-white-05 flex w-full items-center justify-center gap-1.5 border border-border font-semibold text-muted disabled:opacity-60"
+ >
+ <Plus aria-hidden="true" />
+ {t("settings.models.routeDialog.addHop")}
+ </button>
+ </PopoverTrigger>
+ <PopoverContent
+ align="start"
+ sideOffset={6}
+ className="model-hub-route-selector flex w-[var(--radix-popover-trigger-width)] max-w-[calc(100vw-64px)] flex-col gap-2 rounded-lg border border-border bg-background p-2"
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ candidateRefs.current[0]?.focus();
+ }}
+ onCloseAutoFocus={(event) => {
+ event.preventDefault();
+ addButtonRef.current?.focus();
+ }}
+ >
+ <div className="model-hub-route-selector-label grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)] gap-2">
+ <span>{t("settings.models.routeDialog.add.source")}</span>
+ <span>{t("settings.models.routeDialog.add.model")}</span>
+ </div>
+ <div className="flex max-h-52 flex-col gap-2 overflow-auto">
+ {candidateGroups.map((group) => (
+ <section
+ key={group.source.id}
+ aria-label={group.source.display_name}
+ className="flex flex-col gap-1"
+ >
+ {group.items.map(
+ ({ candidate: item, index }, groupIndex) => (
+ <button
+ ref={(node) => {
+ candidateRefs.current[index] = node;
+ }}
+ key={`${item.hop.source_id}:${item.hop.model_id}`}
+ type="button"
+ aria-pressed={Boolean(
+ candidate &&
+ equalHopIdentity(candidate.hop, item.hop),
+ )}
+ tabIndex={
+ candidate &&
+ equalHopIdentity(candidate.hop, item.hop)
+ ? 0
+ : -1
+ }
+ onClick={() => chooseCandidate(item)}
+ onKeyDown={(event) =>
+ onCandidateKeyDown(event, index)
+ }
+ className="model-hub-route-candidate grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)] gap-2 rounded-md px-2 py-1 text-left text-xs text-foreground"
+ >
+ <span className="truncate">
+ {groupIndex === 0 ? group.source.display_name : ""}
+ </span>
+ <span className="truncate font-mono text-muted">
+ {item.hop.model_id}
+ </span>
+ </button>
+ ),
+ )}
+ </section>
+ ))}
+ </div>
+ <Button
+ type="button"
+ disabled={!candidate}
+ onClick={addCandidate}
+ >
+ {t("settings.models.routeDialog.add.confirm")}
+ </Button>
+ </PopoverContent>
+ </Popover>
+ </div>
+ <button
+ ref={reseedButtonRef}
+ type="button"
+ onClick={() => {
+ const sorted = reorderRouteDraft(agent as AgentSupply, draft);
+ advanceInteraction({ type: "reset", draft: sorted });
+ announce(
+ sameRouteDraft(sorted, draft)
+ ? "settings.models.routeDialog.reorder.unchanged"
+ : "settings.models.routeDialog.reorder.sorted",
+ );
+ }}
+ className="model-hub-route-reseed flex items-center gap-1.5 self-start font-semibold text-cyan"
+ >
+ <ListOrdered aria-hidden="true" />
+ {t("settings.models.routeDialog.reorder.label")}
+ </button>
+ {candidates.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("settings.models.routeDialog.hint")}
+ </span>
+ </p>
+ {valid.invalidIndexes.length > 0 && (
+ <p
+ id="model-hub-route-invalid-summary"
+ className="model-hub-route-invalid-summary"
+ >
+ {t("settings.models.routeDialog.invalidAfterRefresh")}
+ </p>
+ )}
+ <span className="sr-only" aria-live="polite">
+ {announcement ? t(announcement.key, announcement.params) : ""}
+ </span>
+ </div>
+ );
+
return (
- <DialogPrimitive.Root open onOpenChange={(open) => !open && onClose()}>
+ <DialogPrimitive.Root open onOpenChange={(open) => !open && close()}>
<DialogPrimitive.Portal>
<DialogPrimitive.Overlay className="model-hub-route-overlay fixed inset-0 z-50" />
- <DialogPrimitive.Content className="model-hub-route-dialog fixed left-1/2 top-1/2 z-50 flex -translate-x-1/2 -translate-y-1/2 flex-col gap-0 overflow-hidden border border-border-strong bg-surface p-0 shadow-xl">
+ <DialogPrimitive.Content
+ aria-busy={
+ phase === "saving" ||
+ phase === "refreshing" ||
+ phase === "reconciling"
+ }
+ className="model-hub-route-dialog fixed left-1/2 z-50 flex -translate-x-1/2 flex-col gap-0 overflow-hidden border border-border-strong bg-surface p-0"
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ cancelButtonRef.current?.focus();
+ }}
+ >
<header className="model-hub-route-head flex flex-col border-b border-border">
<span className="flex items-center justify-between gap-3">
- <DialogPrimitive.Title className="model-hub-route-title font-bold text-foreground">{t('settings.models.routeDialog.title', { model: modelId })}</DialogPrimitive.Title>
- <DialogPrimitive.Close aria-label={t('common.cancel') as string} title={t('common.cancel') as string} className="model-hub-route-close grid shrink-0 place-items-center text-muted"><X aria-hidden="true" /></DialogPrimitive.Close>
+ <DialogPrimitive.Title className="model-hub-route-title font-bold text-foreground">
+ {t(
+ phase === "guard"
+ ? "settings.models.guard.title.saveRoute"
+ : "settings.models.routeDialog.title",
+ { menuModel: modelId },
+ )}
+ </DialogPrimitive.Title>
+ <DialogPrimitive.Close
+ disabled={phase === "saving"}
+ aria-label={
+ t(
+ phase === "guard"
+ ? "settings.models.guard.cancel"
+ : phase === "impact" || phase === "refreshing"
+ ? "settings.models.routeDialog.impact.done"
+ : "settings.models.routeDialog.cancel",
+ ) as string
+ }
+ className="model-hub-route-close grid shrink-0 place-items-center"
+ >
+ <X aria-hidden="true" />
+ </DialogPrimitive.Close>
</span>
- <DialogPrimitive.Description className="model-hub-route-subtitle font-mono text-muted">{backend}</DialogPrimitive.Description>
+ <DialogPrimitive.Description className="model-hub-route-subtitle font-mono text-muted">
+ {phase === "guard"
+ ? t("settings.models.guard.subtitle.saveRoute")
+ : backend}
+ </DialogPrimitive.Description>
</header>
-
- <div className="model-hub-route-body flex flex-col">
- <h3 className="model-hub-route-label font-bold text-muted">{t('settings.models.routeDialog.label')}</h3>
- <div className="model-hub-route-list flex flex-col border border-border bg-background">
- {chain ? chain.chain.map((hop, index) => {
- const current = equalHopIdentity(chain.current, hop);
- return (
- <div key={`${hop.source_id}:${hop.model_id}:${index}`} data-current={current || undefined} className="model-hub-route-hop model-hub-fill-white-08 flex items-center border border-border">
- <GripVertical className="model-hub-ink-white-59 size-3.5 shrink-0" aria-hidden />
- <span className={cn('model-hub-route-ordinal grid shrink-0 place-items-center font-mono font-medium', current ? 'model-hub-accent-pill--mint' : 'model-hub-fill-white-0a text-muted')}>{index + 1}</span>
- <span className="model-hub-route-hop-copy flex min-w-0 flex-1 flex-col"><span className="model-hub-route-hop-name truncate font-semibold text-foreground">{sourceName(sources, hop.source_id)}</span><span className="model-hub-route-hop-model model-hub-ink-muted-b3 truncate font-mono">{hop.model_id}</span></span>
- <button type="button" disabled aria-label={t('settings.models.routeDialog.removeHop') as string} className="model-hub-route-remove model-hub-fill-white-0a grid shrink-0 place-items-center border border-border text-muted disabled:opacity-60"><X className="size-3.5" /></button>
- </div>
- );
- }) : <div className="model-hub-route-hop model-hub-fill-white-08 grid place-items-center border border-border font-mono text-xs text-muted">—</div>}
- <button type="button" disabled className="model-hub-route-add model-hub-fill-white-05 flex w-full items-center justify-center gap-1.5 border border-border font-semibold text-muted disabled:opacity-60"><Plus className="size-3.5" />{t('settings.models.routeDialog.addHop')}</button>
- </div>
- <button type="button" disabled className="model-hub-route-reseed flex items-center gap-1.5 self-start font-semibold text-cyan disabled:opacity-60"><ListRestart className="size-3" />{t('settings.models.routeDialog.reseed')}</button>
- <p className="model-hub-route-hint flex items-start gap-2 text-muted"><Info className="mt-0.5 size-3.5 shrink-0" />{t('settings.models.routeDialog.hint')}</p>
- </div>
-
+ {body}
<footer className="model-hub-route-foot model-hub-fill-white-05 flex items-center justify-end gap-2 border-t border-border">
- <Button variant="outline" className="model-hub-dialog-action" onClick={onClose}>{t('common.cancel')}</Button>
- <Button className="model-hub-dialog-action" disabled>{t('common.save')}</Button>
+ {phase === "impact" || phase === "refreshing" ? (
+ <Button
+ ref={doneButtonRef}
+ type="button"
+ className="model-hub-dialog-action"
+ onClick={close}
+ >
+ {t("settings.models.routeDialog.impact.done")}
+ </Button>
+ ) : phase === "guard" && guard ? (
+ <>
+ <Button
+ ref={cancelButtonRef}
+ type="button"
+ variant="outline"
+ className="model-hub-dialog-action"
+ onClick={() => {
+ setGuard(null);
+ setPhase("ready");
+ requestAnimationFrame(() => saveButtonRef.current?.focus());
+ }}
+ >
+ {t("settings.models.guard.cancel")}
+ </Button>
+ <Button
+ ref={saveButtonRef}
+ type="button"
+ className="model-hub-dialog-action"
+ onClick={() => void submit(guard)}
+ >
+ {t("settings.models.guard.confirm.saveRoute")}
+ </Button>
+ </>
+ ) : phase === "saving" ? (
+ <span role="status" className="text-xs text-muted">
+ {t("settings.models.routeDialog.saving")}
+ </span>
+ ) : (
+ <>
+ <Button
+ ref={cancelButtonRef}
+ type="button"
+ variant="outline"
+ className="model-hub-dialog-action"
+ onClick={close}
+ >
+ {t("settings.models.routeDialog.cancel")}
+ </Button>
+ <Button
+ ref={saveButtonRef}
+ type="button"
+ className="model-hub-dialog-action"
+ aria-describedby={
+ valid.invalidIndexes.length > 0
+ ? [
+ "model-hub-route-invalid-summary",
+ ...valid.invalidIndexes.map(
+ (index) => `model-hub-route-invalid-${index}`,
+ ),
+ ].join(" ")
+ : undefined
+ }
+ disabled={phase !== "ready" || !dirty || !valid.valid}
+ onClick={() => void submit()}
+ >
+ {t("settings.models.routeDialog.save")}
+ </Button>
+ </>
+ )}
</footer>
</DialogPrimitive.Content>
</DialogPrimitive.Portal>
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index 8e9997412..ef20b42ed 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -358,6 +358,98 @@ describe('SettingsModelsPage surface branches', () => {
expect(screen.queryByText(/Now: Replacement source \(takeover\)|当前 Replacement source(接管)/i)).toBeNull();
});
+ it('cannot let a pre-save chain read overwrite the committed route echo', async () => {
+ const head = { ...retainedSource, id: 'src_head', display_name: 'Paused source', state: { status: 'active' as const, retry_at: null, detail_key: null } };
+ const relay = { ...retainedSource, id: 'src_relay', display_name: 'Replacement source', state: { status: 'active' as const, retry_at: null, detail_key: null } };
+ const pendingOldChain = deferred<AgentChain>();
+ const pendingReconciliation = deferred<AgentSupply[]>();
+ const committedChain: AgentChain = {
+ ...takeoverChain,
+ current: { source_id: 'src_head', model_id: 'gpt-5.6-sol' },
+ chain: [{ ...takeoverChain.chain[0], health: 'healthy', runnable: true, retry_at: null }],
+ };
+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([head, relay]);
+ vi.spyOn(modelsApi, 'listAgents')
+ .mockResolvedValueOnce([takeoverAgent])
+ .mockReturnValueOnce(pendingReconciliation.promise);
+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);
+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);
+ vi.spyOn(modelsApi, 'getAgentChain')
+ .mockReturnValueOnce(pendingOldChain.promise)
+ .mockResolvedValueOnce(takeoverChain);
+ vi.spyOn(modelsApi, 'putAgentChain').mockResolvedValue({
+ chain: committedChain,
+ removed_hops: [],
+ interrupted: [],
+ });
+
+ render(
+ <ToastProvider>
+ <I18nextProvider i18n={i18n}>
+ <SettingsModelsPage />
+ </I18nextProvider>
+ </ToastProvider>,
+ );
+
+ await userEvent.click(await screen.findByRole('button', { name: /Open gpt-5\.6-sol route chain|打开 gpt-5\.6-sol 的路由链/i }));
+ const removeButtons = await screen.findAllByRole('button', { name: /^Remove hop$|^移除这一跳$/i });
+ await userEvent.click(removeButtons[1]);
+ await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));
+ await userEvent.click((await screen.findByText(/^Done$|^完成$/i)).closest('button') as HTMLButtonElement);
+ expect(await screen.findByText(/^Now: Paused source$|^当前 Paused source$/i)).toBeTruthy();
+
+ await act(async () => {
+ pendingOldChain.resolve(takeoverChain);
+ await pendingOldChain.promise;
+ });
+
+ expect(screen.getByText(/^Now: Paused source$|^当前 Paused source$/i)).toBeTruthy();
+ expect(screen.queryByText(/Now: Replacement source \(takeover\)|当前 Replacement source(接管)/i)).toBeNull();
+ });
+
+ it('installs a removed backend before the committed route closes and applies PF-1', async () => {
+ const head = { ...retainedSource, id: 'src_head', display_name: 'Paused source', state: { status: 'active' as const, retry_at: null, detail_key: null } };
+ const relay = { ...retainedSource, id: 'src_relay', display_name: 'Replacement source', state: { status: 'active' as const, retry_at: null, detail_key: null } };
+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([head, relay]);
+ vi.spyOn(modelsApi, 'listAgents')
+ .mockResolvedValueOnce([takeoverAgent])
+ .mockResolvedValueOnce([]);
+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);
+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);
+ vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(takeoverChain);
+ vi.spyOn(modelsApi, 'putAgentChain').mockResolvedValue({
+ chain: { ...takeoverChain, chain: [takeoverChain.chain[0]], current: takeoverChain.chain[0] },
+ removed_hops: [],
+ interrupted: [],
+ });
+
+ render(
+ <ToastProvider>
+ <I18nextProvider i18n={i18n}>
+ <SettingsModelsPage />
+ </I18nextProvider>
+ </ToastProvider>,
+ );
+
+ await userEvent.click(await screen.findByRole('button', { name: /Open gpt-5\.6-sol route chain|打开 gpt-5\.6-sol 的路由链/i }));
+ await userEvent.click((await screen.findAllByRole('button', { name: /^Remove hop$|^移除这一跳$/i }))[1]);
+ await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));
+
+ await waitFor(() =>
+ expect(document.querySelector('[data-agent-backend="codex"]')).toBeNull(),
+ );
+ await userEvent.click((await screen.findByText(/^Done$|^完成$/i)).closest('button') as HTMLButtonElement);
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ const firstRegisteredDestination = document.querySelector(
+ '.model-hub-shell-info',
+ );
+ await waitFor(() =>
+ expect(document.activeElement).toBe(firstRegisteredDestination),
+ );
+ expect(document.activeElement?.isConnected).toBe(true);
+ expect(document.activeElement?.closest('[data-agent-backend="codex"]')).toBeNull();
+ });
+
it('reconciles a lost Direct-mode response before rendering failure', async () => {
const direct = { ...takeoverAgent, mode: 'direct' as const, sources: null, routes: null, supply_status: null, model_supply: null };
const agentRead = vi.spyOn(modelsApi, 'listAgents')
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index 7fee2e07a..82b437bff 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -12,12 +12,19 @@ import { GatewayModule } from './GatewayModule';
import { InstallGatewayDialog } from './InstallGatewayDialog';
import { ModelHubInfoHint } from './ModelHubInfoHint';
import { RecentSwitchesCard } from './RecentSwitchesCard';
-import { RouteChainDialog } from './RouteChainDialog';
+import { RouteChainDialog, type RouteCollectionObservation, type RouteCommitReconciliation, type RouteReport } from './RouteChainDialog';
+import { routeChainMatchesAttempt } from './routeChainDraft';
import { SourceDetailPanel } from './SourceDetailPanel';
import { SourceOrderDrawer } from './SourceOrderDrawer';
import { SourcesCard } from './SourcesCard';
import { modelsSurfaceKindFromReads } from './modelHubSurfaceState';
+import { focusModelHubProjection } from './modelHubFocus';
import { buildSupplyRelations } from './supplyRelations';
+import {
+ emptySuspendedRouteAttempts,
+ holdSuspendedRouteAttempt,
+ releaseSuspendedRouteAttempt,
+} from './suspendedRouteAttempts';
import { SupplyGraph, SupplyLegend } from './SupplyGraph';
import './modelHubSurface.css';
import { agentsWithEcho, createLatestAsyncAuthority, createLatestAsyncAuthorityByKey, createLatestEntityAuthorityByKey, createPendingWrites, mapWithConcurrency } from './asyncLifetime';
@@ -32,6 +39,7 @@ import {
beginRegionRead,
failRegionRead,
foldRegionRead,
+ degradedRegion,
loadingRegion,
readyRegion,
regionFailed,
@@ -39,7 +47,8 @@ import {
unreadRegion,
type RegionRead,
} from './regionRead';
-import { agentHasLiveChainProjection, freshRuntimeProjection, pollRuntimeStatus, runtimeHasInstallAsset, startRuntimeWithStatusRefresh } from './runtimeLifecycle';
+import { freshRuntimeProjection, pollRuntimeStatus, runtimeHasInstallAsset, startRuntimeWithStatusRefresh } from './runtimeLifecycle';
+import { createRouteProjectionReconciler, type RouteProjectionStatus } from './routeProjectionReconciliation';
import { backendVisual } from './vendorMeta';
import type { AgentBackend, AgentSupply, ResolutionEvent, RuntimeDependency, Source } from './types';
@@ -61,6 +70,15 @@ const readAgentChains = async (agent: AgentSupply): Promise<ModelChainIndex> =>
),
);
+const readExactAgentChain = async (
+ agent: AgentSupply,
+ modelId: string,
+): Promise<ModelChainIndex> => ({
+ [modelChainKey(agent.backend, modelId)]: readyRegion(
+ await modelsApi.getAgentChain(agent.backend, modelId),
+ ),
+});
+
const settleAgentChainIndex = (
previous: ModelChainIndex,
agent: AgentSupply,
@@ -74,6 +92,17 @@ const settleAgentChainIndex = (
return next;
};
+const settleExactAgentChain = (
+ previous: ModelChainIndex,
+ incoming: ModelChainIndex,
+): ModelChainIndex => {
+ const next = { ...previous };
+ for (const [key, read] of Object.entries(incoming)) {
+ next[key] = settleRegionRead(previous[key] ?? loadingRegion(), read);
+ }
+ return next;
+};
+
const beginAgentChainIndex = (
previous: ModelChainIndex,
agent: AgentSupply,
@@ -160,10 +189,10 @@ export const RuntimePill: React.FC<{
: <span className={className}>{content}</span>;
};
-const ModelHubShell: React.FC<{ actions?: React.ReactNode; detailBack?: () => void; children: React.ReactNode }> = ({ actions, detailBack, children }) => {
+const ModelHubShell: React.FC<{ actions?: React.ReactNode; detailBack?: () => void; children: React.ReactNode; rootRef?: React.Ref<HTMLDivElement> }> = ({ actions, detailBack, children, rootRef }) => {
const { t } = useTranslation();
return (
- <div className="model-hub-shell">
+ <div ref={rootRef} className="model-hub-shell">
<header className="model-hub-shell-head">
{detailBack
? <button type="button" onClick={detailBack} aria-label={t('settings.models.sourceDetail.back') as string} title={t('settings.models.sourceDetail.back') as string} className="model-hub-detail-back"><ArrowLeft aria-hidden="true" /></button>
@@ -259,7 +288,19 @@ export const SettingsModelsPage: React.FC = () => {
const [apiKeyOpen, setApiKeyOpen] = React.useState(false);
const [orderBackend, setOrderBackend] = React.useState<AgentBackend | null>(null);
const [adoptAgent, setAdoptAgent] = React.useState<AgentSupply | null>(null);
- const [routeTarget, setRouteTarget] = React.useState<{ backend: AgentBackend; modelId: string } | null>(null);
+ const [routeTarget, setRouteTarget] = React.useState<{ agent: AgentSupply; modelId: string; opener: HTMLElement | null } | null>(null);
+ const [routeCommitStatus, setRouteCommitStatus] = React.useState<RouteProjectionStatus | null>(null);
+ const [routeCommitBackend, setRouteCommitBackend] = React.useState<AgentBackend | null>(null);
+ const [suspendedRouteAttempts, setSuspendedRouteAttempts] = React.useState(
+ emptySuspendedRouteAttempts,
+ );
+ const suspendedHubFrontiersRef = React.useRef(new Map<AgentBackend, AgentSupply>());
+ const suspendedSourceBaselinesRef = React.useRef(
+ new Map<AgentBackend, RegionRead<Source[]>>(),
+ );
+ const suspendedChainBaselinesRef = React.useRef(
+ new Map<AgentBackend, RegionRead<ModelChainIndex>>(),
+ );
const [selectedSourceId, setSelectedSourceId] = React.useState<string | null>(null);
const [agentWrites, setAgentWrites] = React.useState<ReadonlySet<string>>(() => new Set());
const [switchFailures, setSwitchFailures] = React.useState<ReadonlySet<string>>(() => new Set());
@@ -268,6 +309,7 @@ export const SettingsModelsPage: React.FC = () => {
const [sourceCollectionReads] = React.useState(() => createSourceCollectionReadAuthority(modelsApi));
const [agentCollectionReads] = React.useState(() => createAgentCollectionReadAuthority(modelsApi));
const overviewRef = React.useRef<HTMLDivElement>(null);
+ const pageRef = React.useRef<HTMLDivElement>(null);
const aliveRef = React.useRef(true);
const [sourceEntityAuthority] = React.useState(() => createLatestEntityAuthorityByKey(
(source: Source) => source.id,
@@ -330,14 +372,19 @@ export const SettingsModelsPage: React.FC = () => {
});
}, [runtimeHealth, runtimeRead.kind, runtimeRecoveryPending, startingRuntime]);
- const [chainReadAuthority] = React.useState(() => createLatestAsyncAuthorityByKey<AgentBackend, { agent: AgentSupply; chains: ModelChainIndex }>((_backend, incoming) => {
+ const [chainReadAuthority] = React.useState(() => createLatestAsyncAuthorityByKey<AgentBackend, { agent: AgentSupply; chains: ModelChainIndex; scope: 'backend' | 'model' }>((_backend, incoming) => {
if (!aliveRef.current) return;
- setChainsRead((previous) => readyRegion(settleAgentChainIndex(foldRegionRead<ModelChainIndex, ModelChainIndex>(previous, {
- loading: () => ({}),
- ready: (data) => data,
- unread: () => ({}),
- degraded: (staleData) => staleData,
- }), incoming.agent, incoming.chains)));
+ setChainsRead((previous) => {
+ const current = foldRegionRead<ModelChainIndex, ModelChainIndex>(previous, {
+ loading: () => ({}),
+ ready: (data) => data,
+ unread: () => ({}),
+ degraded: (staleData) => staleData,
+ });
+ return readyRegion(incoming.scope === 'backend'
+ ? settleAgentChainIndex(current, incoming.agent, incoming.chains)
+ : settleExactAgentChain(current, incoming.chains));
+ });
}));
const refreshAgentChains = React.useCallback(async (agent: AgentSupply) => {
@@ -350,11 +397,16 @@ export const SettingsModelsPage: React.FC = () => {
await chainReadAuthority.run(agent.backend, async () => ({
agent,
chains: await readAgentChains(agent),
+ scope: 'backend' as const,
}));
}, [chainReadAuthority]);
const refreshAllAgentChains = React.useCallback((agentRows: AgentSupply[]) => {
const hubAgents = agentRows.filter((agent) => agent.mode === 'hub');
+ const suspendedBackends = new Set(suspendedRouteAttempts.keys());
+ const probeAgents = hubAgents.filter((agent) =>
+ !suspendedBackends.has(agent.backend)
+ && agent.backend !== routeCommitBackend);
const activeBackends = new Set(hubAgents.map((agent) => agent.backend));
chainReadAuthority.invalidateExcept(activeBackends);
setChainsRead((previous) => readyRegion(Object.fromEntries(
@@ -365,8 +417,8 @@ export const SettingsModelsPage: React.FC = () => {
degraded: (staleData) => staleData,
})).filter(([key]) => activeBackends.has(key.split('\u0000')[0] as AgentBackend)),
)));
- for (const agent of hubAgents) void refreshAgentChains(agent);
- }, [chainReadAuthority, refreshAgentChains]);
+ for (const agent of probeAgents) void refreshAgentChains(agent);
+ }, [chainReadAuthority, refreshAgentChains, routeCommitBackend, suspendedRouteAttempts]);
React.useEffect(() => {
const freshSupply = foldRegionRead<AgentSupply[], AgentSupply[] | null>(supplyRead, {
@@ -596,18 +648,170 @@ export const SettingsModelsPage: React.FC = () => {
&& runtimeRead.kind === 'loading';
const directEmpty = modelsSurfaceKindFromReads(supplyRead, sourcesRead) === 'direct_empty';
const installedAgents = agents.filter((agent) => agent.cli_present);
+ const installedSupplyRead = foldRegionRead<AgentSupply[], RegionRead<AgentSupply[]>>(supplyRead, {
+ loading: () => loadingRegion(),
+ ready: () => readyRegion(installedAgents),
+ unread: (retryable) => unreadRegion(retryable),
+ degraded: (_staleData, cause, retryable) => degradedRegion(installedAgents, cause, retryable),
+ });
const selectSource = React.useCallback((sourceId: string | null) => {
sourceIntentAuthority.commit(() => setSelectedSourceId(sourceId));
}, [sourceIntentAuthority]);
const selectedSource = sources.find((source) => source.id === selectedSourceId) ?? null;
const orderAgent = agents.find((agent) => agent.backend === orderBackend && agent.mode === 'hub') ?? null;
- const routeAgent = agents.find((agent) => agent.backend === routeTarget?.backend && agentHasLiveChainProjection(runtime, agent)) ?? null;
- const routeSelection = routeTarget && routeAgent ? {
- agent: routeAgent,
+ const currentRouteAgent = routeTarget
+ ? installedAgents.find((agent) => agent.backend === routeTarget.agent.backend) ?? null
+ : null;
+ const routeSelection = routeTarget ? {
+ agent: currentRouteAgent ?? routeTarget.agent,
modelId: routeTarget.modelId,
- read: chains[modelChainKey(routeTarget.backend, routeTarget.modelId)],
+ read: chains[modelChainKey(routeTarget.agent.backend, routeTarget.modelId)],
+ available: supplyRead.kind !== 'ready' || currentRouteAgent !== null,
} : null;
- const supplyRelations = React.useMemo(() => buildSupplyRelations(agents, sources, chains, runtime), [agents, chains, runtime, sources]);
+ const focusRouteDestination = React.useCallback((target: NonNullable<typeof routeTarget>) => {
+ requestAnimationFrame(() => {
+ focusModelHubProjection({
+ root: pageRef.current,
+ activeTarget: target.opener,
+ backend: target.agent.backend,
+ modelId: target.modelId,
+ });
+ });
+ }, []);
+ const routeObserved = React.useCallback((next: RouteReport['chain']) => {
+ setChainsRead((previous) => readyRegion({
+ ...foldRegionRead<ModelChainIndex, ModelChainIndex>(previous, {
+ loading: () => ({}),
+ ready: (data) => data,
+ unread: () => ({}),
+ degraded: (staleData) => staleData,
+ }),
+ [modelChainKey(next.backend, next.model_id)]: readyRegion(next),
+ }));
+ }, []);
+ const readRouteAgents = React.useCallback(async (): Promise<RouteCollectionObservation<AgentSupply[]>> => {
+ const result = await agentCollectionReads.read();
+ if (result.kind === 'stale') throw new Error('route_agents_read_superseded');
+ return {
+ value: result.value,
+ install: () => setSupplyRead(readyRegion(result.value)),
+ };
+ }, [agentCollectionReads]);
+ const readRouteSources = React.useCallback(async (): Promise<RouteCollectionObservation<Source[]>> => {
+ const snapshot = sourceEntityAuthority.beginSnapshot();
+ const result = await sourceCollectionReads.read();
+ if (result.kind === 'stale') throw new Error('route_sources_read_superseded');
+ return {
+ value: result.value,
+ install: () => sourceEntityAuthority.settleSnapshot(snapshot, result.value),
+ };
+ }, [sourceCollectionReads, sourceEntityAuthority]);
+ const routeProjectionReconciler = React.useMemo(() => createRouteProjectionReconciler({
+ readAgents: readRouteAgents,
+ readSources: readRouteSources,
+ onFailure: (member) => {
+ if (member === 'agents') setSupplyRead(failRegionRead);
+ else setSourcesRead(failRegionRead);
+ },
+ onStatus: setRouteCommitStatus,
+ }), [readRouteAgents, readRouteSources]);
+ const routeCommitted = React.useCallback((result: RouteReport) => {
+ chainReadAuthority.invalidate(result.chain.backend);
+ routeObserved(result.chain);
+ setSuspendedRouteAttempts((attempts) =>
+ releaseSuspendedRouteAttempt(attempts, result.chain.backend),
+ );
+ suspendedHubFrontiersRef.current.delete(result.chain.backend);
+ suspendedSourceBaselinesRef.current.delete(result.chain.backend);
+ suspendedChainBaselinesRef.current.delete(result.chain.backend);
+ setRouteCommitBackend(result.chain.backend);
+ routeProjectionReconciler.start(result.chain.backend);
+ }, [chainReadAuthority, routeObserved, routeProjectionReconciler]);
+ React.useEffect(() => {
+ if (routeCommitStatus && !routeCommitStatus.pending && routeCommitStatus.failed.size === 0) {
+ setRouteCommitBackend(null);
+ }
+ }, [routeCommitStatus]);
+ const retryRouteCommit = React.useCallback(() => {
+ if (routeCommitStatus?.pending || !routeCommitStatus?.failed.size) return;
+ routeProjectionReconciler.retry();
+ }, [routeCommitStatus, routeProjectionReconciler]);
+ const routeCommitReconciliation = React.useMemo<RouteCommitReconciliation | null>(() => routeCommitStatus ? ({
+ pending: routeCommitStatus.pending,
+ failed: routeCommitStatus.failed.size > 0,
+ retry: retryRouteCommit,
+ }) : null, [retryRouteCommit, routeCommitStatus]);
+ React.useEffect(() => {
+ const heldBackends = new Set(suspendedRouteAttempts.keys());
+ for (const backend of suspendedHubFrontiersRef.current.keys()) {
+ if (!heldBackends.has(backend)) suspendedHubFrontiersRef.current.delete(backend);
+ }
+ for (const backend of suspendedSourceBaselinesRef.current.keys()) {
+ if (!heldBackends.has(backend)) suspendedSourceBaselinesRef.current.delete(backend);
+ }
+ for (const backend of suspendedChainBaselinesRef.current.keys()) {
+ if (!heldBackends.has(backend)) suspendedChainBaselinesRef.current.delete(backend);
+ }
+ const freshAgents = foldRegionRead<AgentSupply[], AgentSupply[] | null>(supplyRead, {
+ loading: () => null,
+ ready: (data) => data,
+ unread: () => null,
+ degraded: () => null,
+ });
+ for (const held of suspendedRouteAttempts.values()) {
+ const freshAgent = freshAgents?.find((row) => row.backend === held.backend) ?? null;
+ if (!freshAgent || freshAgent.mode !== 'hub') {
+ suspendedHubFrontiersRef.current.delete(held.backend);
+ suspendedSourceBaselinesRef.current.set(held.backend, sourcesRead);
+ continue;
+ }
+ if (sourcesRead === suspendedSourceBaselinesRef.current.get(held.backend) || sourcesRead.kind !== 'ready') continue;
+ if (suspendedHubFrontiersRef.current.get(held.backend) === freshAgent) continue;
+ suspendedHubFrontiersRef.current.set(held.backend, freshAgent);
+ suspendedChainBaselinesRef.current.set(held.backend, chainsRead);
+ void (async () => {
+ try {
+ await chainReadAuthority.run(held.backend, async () => ({
+ agent: freshAgent,
+ chains: await readExactAgentChain(freshAgent, held.modelId),
+ scope: 'model' as const,
+ }));
+ if (suspendedHubFrontiersRef.current.get(held.backend) !== freshAgent) return;
+ } catch {
+ if (suspendedHubFrontiersRef.current.get(held.backend) !== freshAgent) return;
+ setChainsRead((previous) => readyRegion({
+ ...foldRegionRead<ModelChainIndex, ModelChainIndex>(previous, {
+ loading: () => ({}),
+ ready: (data) => data,
+ unread: () => ({}),
+ degraded: (staleData) => staleData,
+ }),
+ [modelChainKey(held.backend, held.modelId)]: unreadRegion(),
+ }));
+ }
+ })();
+ }
+ }, [chainReadAuthority, chainsRead, sourcesRead, supplyRead, suspendedRouteAttempts]);
+ React.useEffect(() => {
+ for (const held of suspendedRouteAttempts.values()) {
+ if (!suspendedHubFrontiersRef.current.has(held.backend) || chainsRead === suspendedChainBaselinesRef.current.get(held.backend)) continue;
+ const observed = foldRegionRead(chainsRead, {
+ loading: () => null,
+ ready: (index) => foldRegionRead(index[modelChainKey(held.backend, held.modelId)] ?? unreadRegion(), {
+ loading: () => null,
+ ready: (data) => data,
+ unread: () => null,
+ degraded: () => null,
+ }),
+ unread: () => null,
+ degraded: () => null,
+ });
+ if (observed && routeChainMatchesAttempt(observed, held)) {
+ routeCommitted({ chain: observed, removed_hops: null, interrupted: null });
+ }
+ }
+ }, [chainsRead, routeCommitted, suspendedRouteAttempts]);
+ const supplyRelations = React.useMemo(() => buildSupplyRelations(installedAgents, sources, chains, runtime), [chains, installedAgents, runtime, sources]);
const takeoverCount = React.useMemo(() => new Set(
supplyRelations.filter(({ kind }) => kind === 'takeover').map(({ backend }) => backend),
).size, [supplyRelations]);
@@ -630,6 +834,7 @@ export const SettingsModelsPage: React.FC = () => {
return (
<ModelHubShell
+ rootRef={pageRef}
detailBack={selectedSourceId ? () => selectSource(null) : undefined}
actions={!landingLoading
? directEmpty && installedAgents.length === 0
@@ -657,9 +862,9 @@ export const SettingsModelsPage: React.FC = () => {
{tab === 'sources' ? <div className="model-hub-overview">
<div className="model-hub-overview-body">
<div ref={overviewRef} className="model-hub-overview-grid relative flex flex-col gap-4">
- <SourcesCard read={sourcesRead} onRetry={() => void retrySources()} onOpenSource={(source) => selectSource(source.id)} onAddApiKey={() => setApiKeyOpen(true)} />
+ <SourcesCard read={sourcesRead} readFailureCopy={routeCommitStatus?.failed.has('sources') ? t('settings.models.routeDialog.impact.refreshFail') : undefined} onRetry={() => routeCommitStatus?.failed.has('sources') ? retryRouteCommit() : void retrySources()} onOpenSource={(source) => selectSource(source.id)} onAddApiKey={() => setApiKeyOpen(true)} />
<div className="hidden lg:block" aria-hidden="true" />
- <GatewayModule supply={supplyRead} sources={sources} chains={chains} runtime={runtime} runtimeSnapshot={retainedRuntime} onRetry={() => void retrySupply()} pendingBackends={agentWrites} switchFailures={switchFailures} connectingBackend={adoptAgent?.backend ?? null} onConnectHub={setAdoptAgent} onSwitchDirect={switchToDirect} onOpenOrder={(agent) => setOrderBackend(agent.backend)} onOpenRoute={(agent, modelId) => setRouteTarget({ backend: agent.backend, modelId })} onProbeSettled={(agent) => void refreshAgentChains(agent)} />
+ <GatewayModule supply={installedSupplyRead} readFailureCopy={routeCommitStatus?.failed.has('agents') ? t('settings.models.routeDialog.impact.refreshFail') : undefined} sources={sources} chains={chains} runtime={runtime} runtimeSnapshot={retainedRuntime} onRetry={() => routeCommitStatus?.failed.has('agents') ? retryRouteCommit() : void retrySupply()} pendingBackends={agentWrites} switchFailures={switchFailures} connectingBackend={adoptAgent?.backend ?? null} onConnectHub={setAdoptAgent} onSwitchDirect={switchToDirect} onOpenOrder={(agent) => setOrderBackend(agent.backend)} onOpenRoute={(agent, modelId, opener) => setRouteTarget({ agent, modelId, opener })} onProbeSettled={(agent) => void refreshAgentChains(agent)} />
<SupplyGraph containerRef={overviewRef} relations={supplyRelations} />
</div>
<SupplyLegend relations={supplyRelations} />
@@ -670,7 +875,54 @@ export const SettingsModelsPage: React.FC = () => {
</div>}
<AddApiKeyDialog open={apiKeyOpen} sourceReads={sourceCollectionReads} onClose={() => setApiKeyOpen(false)} onAdded={(created) => void sourceAdded(created)} />
{orderAgent && <SourceOrderDrawer open agent={orderAgent} sources={sources} sourceReads={sourceCollectionReads} onClose={() => setOrderBackend(null)} onSaved={agentSaved} orderWrite={{ pending: agentWrites.has(orderAgent.backend), track: (work) => agentWriteRegistry.track(orderAgent.backend, work) }} />}
- <RouteChainDialog selection={routeSelection} sources={sources} onClose={() => setRouteTarget(null)} />
+ <RouteChainDialog
+ selection={routeSelection}
+ sources={sources}
+ onClose={() => {
+ const target = routeTarget;
+ setRouteTarget(null);
+ if (target) focusRouteDestination(target);
+ }}
+ onCommitted={routeCommitted}
+ commitReconciliation={routeCommitReconciliation}
+ onObserved={routeObserved}
+ readAgents={readRouteAgents}
+ readSources={readRouteSources}
+ onDirectMode={(attempt, observedAgent) => {
+ const landingBackend = attempt?.backend ?? routeTarget?.agent.backend;
+ if (landingBackend) {
+ suspendedSourceBaselinesRef.current.set(landingBackend, sourcesRead);
+ setSuspendedRouteAttempts((attempts) =>
+ attempt
+ ? holdSuspendedRouteAttempt(attempts, attempt)
+ : releaseSuspendedRouteAttempt(attempts, landingBackend),
+ );
+ }
+ const target = routeTarget;
+ setRouteTarget(null);
+ if (target) focusRouteDestination(target);
+ void (async () => {
+ let landing = observedAgent;
+ if (!landing) {
+ try {
+ const observation = await readRouteAgents();
+ observation.install();
+ landing = observation.value.find((row) => row.backend === landingBackend) ?? null;
+ } catch {
+ setSupplyRead(failRegionRead);
+ return;
+ }
+ }
+ if (landing?.mode !== 'hub') return;
+ try {
+ const sourceObservation = await readRouteSources();
+ sourceObservation.install();
+ } catch {
+ setSourcesRead(failRegionRead);
+ }
+ })();
+ }}
+ />
{adoptAgent && (
<EnableGatewayDialog
key={adoptAgent.backend}
diff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsx
index 23c26d6df..efc6a55e4 100644
--- a/ui/src/components/settings/models/SourceDetailPanel.test.tsx
+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx
@@ -12,7 +12,8 @@ import i18n from '@/i18n';
import { createPendingWrites } from './asyncLifetime';
import { modelsApi } from './modelsApi';
import type { SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';
-import { GuardGapList, SourceDetailPanel } from './SourceDetailPanel';
+import { GuardGapList } from './GuardGapList';
+import { SourceDetailPanel } from './SourceDetailPanel';
import type { Source } from './types';
const source: Source = {
diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsx
index af8f61343..fc249245c 100644
--- a/ui/src/components/settings/models/SourceDetailPanel.tsx
+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx
@@ -7,6 +7,7 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { ResponsiveMenu } from '@/components/ui/responsive-menu';
import { cn } from '@/lib/utils';
+import { GuardGapList } from './GuardGapList';
import { formatRelativeTime } from '@/lib/relativeTime';
import { apiFailure, modelsApi, type GuardConfirmation } from './modelsApi';
import type { SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';
@@ -52,26 +53,6 @@ type SourceReconciliation =
| { kind: 'source'; source: Source }
| { kind: 'gone'; sources: Source[]; snapshot: number };
-export const GuardGapList: React.FC<{ gaps: SupplyGap[] }> = ({ gaps }) => {
- const { t, i18n } = useTranslation();
- if (gaps.length === 0) return null;
- return (
- <>
- <div className="model-hub-guard-label"><p>{t('settings.models.guard.gap.label')}</p><span>{t('settings.models.gateway.modelCount', { count: gaps.length })}</span></div>
- <div className="model-hub-guard-list">
- {gaps.map((gap) => (
- <div key={`${gap.backend}:${gap.model_id}`} className="model-hub-guard-hop">
- <span className="min-w-0 flex-1">
- <strong>{t('settings.models.guard.gap.subject', { backend: t(`settings.models.backends.${gap.backend}`, { defaultValue: gap.backend }), menuModel: gap.model_id })}</strong>
- {gap.agents.length > 0 && <span>{t('settings.models.guard.gap.agents', { agents: gap.agents.join(i18n.language.startsWith('zh') ? '、' : ', ') })}</span>}
- </span>
- </div>
- ))}
- </div>
- </>
- );
-};
-
const enteredHost = (source: Source): string | null => {
if (!source.base_url || !isCustomEndpoint(source)) return null;
try {
diff --git a/ui/src/components/settings/models/SourcesCard.tsx b/ui/src/components/settings/models/SourcesCard.tsx
index 07afd988f..db370cc19 100644
--- a/ui/src/components/settings/models/SourcesCard.tsx
+++ b/ui/src/components/settings/models/SourcesCard.tsx
@@ -11,9 +11,10 @@ import type { Source } from './types';
export const SourcesCard: React.FC<{
read: RegionRead<Source[]>;
onRetry: () => void;
+ readFailureCopy?: string;
onOpenSource: (source: Source) => void;
onAddApiKey: () => void;
-}> = ({ read, onRetry, onOpenSource, onAddApiKey }) => {
+}> = ({ read, onRetry, readFailureCopy, onOpenSource, onAddApiKey }) => {
const { t } = useTranslation();
const sources = foldRegionRead<Source[], Source[] | undefined>(read, {
loading: () => undefined,
@@ -44,7 +45,7 @@ export const SourcesCard: React.FC<{
: read.kind === 'unread'
? <div className="flex h-full min-h-36 flex-col items-center justify-center gap-3 px-4 text-center"><p className="text-[12px] text-muted">{t('settings.models.upstream.unread')}</p><Button variant="outline" size="xs" onClick={onRetry}>{t('settings.models.upstream.retry')}</Button></div>
: <>
- {read.kind === 'degraded' && read.cause === 'read_failed' && <div className="mb-2 flex items-center justify-between gap-3 rounded-lg border border-destructive/25 bg-destructive/[0.08] px-3 py-2"><p className="text-[11px] text-destructive">{t('settings.models.upstream.unread')}</p><Button variant="outline" size="xs" onClick={onRetry}>{t('settings.models.upstream.retry')}</Button></div>}
+ {read.kind === 'degraded' && read.cause === 'read_failed' && <div className="mb-2 flex items-center justify-between gap-3 rounded-lg border border-destructive/25 bg-destructive/[0.08] px-3 py-2"><p className="text-[11px] text-destructive">{readFailureCopy ?? t('settings.models.upstream.unread')}</p><Button variant="outline" size="xs" onClick={onRetry}>{t('settings.models.upstream.retry')}</Button></div>}
{groups.length > 0
? groups.map((group) => <div key={group.id} className="space-y-2"><h3 className="model-hub-upstream-group-label flex h-[18px] items-center uppercase">{t(`settings.models.upstream.group.${group.id}`)}</h3>{group.sources.map((source) => <SourceRow key={source.id} source={source} onOpen={onOpenSource} />)}</div>)
: <p className="px-3 py-10 text-center text-[12px] text-muted">{t('settings.models.upstream.empty')}</p>}
diff --git a/ui/src/components/settings/models/SupplyGapNote.tsx b/ui/src/components/settings/models/SupplyGapNote.tsx
deleted file mode 100644
index 11e008c7f..000000000
--- a/ui/src/components/settings/models/SupplyGapNote.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-// The 「谁会没有来源」 list (api.md → `would_interrupt` / `interrupted_pairs`).
-//
-// The supply guard refuses a write by NAMING what it would strand, and the spec
-// says why that naming matters: 「删除后 pm 将没有可用来源」 is actionable where a
-// bare (backend, model) pair is not. So this renders the Agents first and the
-// model second, and falls back to the backend only when no named Agent runs the
-// pair — which is a real case (a configured Route or Agent selection supplies it) and not a reason
-// to drop the entry.
-//
-// One component for all three sites — the forced-delete confirm, the forced
-// key-replacement confirm, and the post-repair report — because the list is the
-// same list, and the previous per-site prose is exactly where two surfaces would
-// start describing the same refusal differently.
-import * as React from 'react';
-import { useTranslation } from 'react-i18next';
-
-import type { SupplyGap } from './types';
-
-export const SupplyGapNote: React.FC<{
- gaps: SupplyGap[];
- /** Rendered above the list. Omitted where the dialog's own description already
- * states the consequence — a second sentence saying it again is the kind of
- * line that is better deleted. */
- title?: string;
-}> = ({ gaps, title }) => {
- const { t } = useTranslation();
- if (gaps.length === 0) return null;
- const backendName = (backend: string) =>
- t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string;
-
- return (
- <div className="flex flex-col gap-1.5 rounded-lg border border-border bg-surface-2/60 px-3 py-2.5">
- {title ? <p className="text-[12px] font-semibold text-foreground">{title}</p> : null}
- <ul className="flex flex-col gap-1">
- {gaps.map((gap) => (
- <li key={`${gap.backend}:${gap.model_id}`} className="text-[12px] leading-relaxed text-muted">
- {/* ' · ' is this page's separator everywhere else (source sub-lines,
- the adoption note, the agent card's amber line) — locale-neutral
- on purpose. Agent names are user-chosen identifiers, so they join
- with a plain comma in both locales rather than through copy. */}
- {`${gap.agents.length > 0 ? gap.agents.join(', ') : backendName(gap.backend)} · ${gap.model_id}`}
- </li>
- ))}
- </ul>
- </div>
- );
-};
-
-export default SupplyGapNote;
diff --git a/ui/src/components/settings/models/asyncLifetime.test.ts b/ui/src/components/settings/models/asyncLifetime.test.ts
index aa1177df3..4cb7d573d 100644
--- a/ui/src/components/settings/models/asyncLifetime.test.ts
+++ b/ui/src/components/settings/models/asyncLifetime.test.ts
@@ -182,6 +182,19 @@ describe('latest async authority', () => {
expect(await codexRun).toBe('landed');
expect(landed).toEqual(['codex:still active']);
});
+
+ it('invalidates one pending generation before a write echo takes ownership', async () => {
+ const pending = deferred<string>();
+ const landed: string[] = [];
+ const authority = createLatestAsyncAuthorityByKey<string, string>((key, value) => landed.push(`${key}:${value}`));
+
+ const read = authority.run('claude', () => pending.promise);
+ authority.invalidate('claude');
+ pending.resolve('pre-commit chain');
+
+ expect(await read).toBe('stale');
+ expect(landed).toEqual([]);
+ });
});
describe('latest Source entity authority', () => {
diff --git a/ui/src/components/settings/models/asyncLifetime.ts b/ui/src/components/settings/models/asyncLifetime.ts
index 54e7e5dfd..da9f080d7 100644
--- a/ui/src/components/settings/models/asyncLifetime.ts
+++ b/ui/src/components/settings/models/asyncLifetime.ts
@@ -38,6 +38,8 @@ export const createLatestAsyncAuthorityByKey = <K, T>(
};
return {
+ /** Advances one key before an authoritative write echo is installed. */
+ invalidate: (key: K): void => advance(key),
/** Advances retired keys so their pending requests cannot regain ownership. */
invalidateExcept: (activeKeys: ReadonlySet<K>): void => {
for (const key of latestRequest.keys()) {
diff --git a/ui/src/components/settings/models/modelHubFocus.test.ts b/ui/src/components/settings/models/modelHubFocus.test.ts
new file mode 100644
index 000000000..8e59e24a8
--- /dev/null
+++ b/ui/src/components/settings/models/modelHubFocus.test.ts
@@ -0,0 +1,52 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from "vitest";
+
+import { focusModelHubProjection } from "./modelHubFocus";
+
+describe("model hub projection focus", () => {
+ it("uses PF-1 after an active route row and its backend disappear", () => {
+ const root = document.createElement("main");
+ root.innerHTML = '<button data-destination="first">First control</button>';
+ document.body.append(root);
+ const removed = document.createElement("button");
+
+ const focused = focusModelHubProjection({
+ root,
+ activeTarget: removed,
+ backend: "claude",
+ modelId: "model",
+ });
+
+ expect(focused).toBe(root.querySelector('[data-destination="first"]'));
+ expect(document.activeElement).toBe(focused);
+ root.remove();
+ });
+
+ it("prefers the exact model row and then the exact backend group", () => {
+ const root = document.createElement("main");
+ root.innerHTML = [
+ '<button data-destination="first">First control</button>',
+ '<div tabindex="-1" data-agent-group-head="claude">Claude</div>',
+ '<button data-route-backend="claude" data-route-model="model">Model</button>',
+ ].join("");
+ document.body.append(root);
+
+ const model = focusModelHubProjection({
+ root,
+ activeTarget: null,
+ backend: "claude",
+ modelId: "model",
+ });
+ expect(model?.dataset.routeModel).toBe("model");
+
+ model?.remove();
+ const group = focusModelHubProjection({
+ root,
+ activeTarget: null,
+ backend: "claude",
+ modelId: "model",
+ });
+ expect(group?.dataset.agentGroupHead).toBe("claude");
+ root.remove();
+ });
+});
diff --git a/ui/src/components/settings/models/modelHubFocus.ts b/ui/src/components/settings/models/modelHubFocus.ts
new file mode 100644
index 000000000..90a798366
--- /dev/null
+++ b/ui/src/components/settings/models/modelHubFocus.ts
@@ -0,0 +1,61 @@
+import type { AgentBackend } from "./types";
+
+const focusableSelector = [
+ "button:not([disabled]):not([aria-disabled='true'])",
+ "a[href]",
+ "input:not([disabled])",
+ "select:not([disabled])",
+ "textarea:not([disabled])",
+ "[tabindex='0']",
+].join(",");
+
+const focusValid = (
+ element: Element | null | undefined,
+): element is HTMLElement =>
+ element instanceof HTMLElement &&
+ element.isConnected &&
+ !element.hasAttribute("disabled") &&
+ element.getAttribute("aria-disabled") !== "true" &&
+ !element.closest("[inert]");
+
+const exactModelRow = (
+ root: HTMLElement,
+ backend: AgentBackend,
+ modelId: string,
+): HTMLElement | null =>
+ [...root.querySelectorAll<HTMLElement>("[data-route-backend]")].find(
+ (element) =>
+ element.dataset.routeBackend === backend &&
+ element.dataset.routeModel === modelId,
+ ) ?? null;
+
+const exactGroupHead = (
+ root: HTMLElement,
+ backend: AgentBackend,
+): HTMLElement | null =>
+ [...root.querySelectorAll<HTMLElement>("[data-agent-group-head]")].find(
+ (element) => element.dataset.agentGroupHead === backend,
+ ) ?? null;
+
+export const focusModelHubProjection = ({
+ root,
+ activeTarget,
+ backend,
+ modelId,
+}: {
+ root: HTMLElement | null;
+ activeTarget: HTMLElement | null;
+ backend: AgentBackend;
+ modelId: string;
+}): HTMLElement | null => {
+ if (!root) return null;
+ const candidates = [
+ activeTarget,
+ exactModelRow(root, backend, modelId),
+ exactGroupHead(root, backend),
+ root.querySelector<HTMLElement>(focusableSelector),
+ ];
+ const target = candidates.find(focusValid) ?? null;
+ target?.focus();
+ return target;
+};
diff --git a/ui/src/components/settings/models/modelHubStylePolicy.test.ts b/ui/src/components/settings/models/modelHubStylePolicy.test.ts
index dd2c7b015..5140e1280 100644
--- a/ui/src/components/settings/models/modelHubStylePolicy.test.ts
+++ b/ui/src/components/settings/models/modelHubStylePolicy.test.ts
@@ -29,4 +29,16 @@ describe('Model Hub visual token policy', () => {
expect(literals).toEqual([]);
});
+
+ it('pins the route dialog placement, shadow, and bounded body scroll to named roles', () => {
+ const dialog = surfaceCss.match(/\.model-hub-route-dialog\s*\{([^}]*)\}/)?.[1] ?? '';
+ const body = surfaceCss.match(/\.model-hub-route-body\s*\{([^}]*)\}/)?.[1] ?? '';
+
+ expect(dialog).toContain('top: min(');
+ expect(dialog).toContain('--model-hub-route-top: 300px');
+ expect(dialog).toContain('var(--model-hub-route-top)');
+ expect(dialog).toContain('box-shadow: var(--model-hub-dialog-shadow)');
+ expect(dialog).toMatch(/max-height:\s*calc\([\s\S]*100dvh - var\(--model-hub-route-viewport-inset\) -[\s\S]*var\(--model-hub-route-viewport-inset\)/);
+ expect(body).toContain('overflow-y: auto');
+ });
});
diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.css
index 4a70fb922..0779d349a 100644
--- a/ui/src/components/settings/models/modelHubSurface.css
+++ b/ui/src/components/settings/models/modelHubSurface.css
@@ -34,6 +34,7 @@
--model-hub-muted-b3: #9BA3B8B3;
--model-hub-muted-cc: #9BA3B8CC;
--model-hub-error-8a: #FF8A8A;
+ --model-hub-dialog-shadow: 0 16px 40px 0 #00000099;
}
.model-hub-accent-tile--cyan { background: var(--model-hub-cyan-1a); }
@@ -524,6 +525,8 @@
.model-hub-route-dialog {
--model-hub-route-width: 520px;
+ --model-hub-route-top: 300px;
+ --model-hub-route-viewport-inset: 16px;
--model-hub-route-radius: 14px;
--model-hub-route-head-height: 72px;
--model-hub-route-title-size: 15px;
@@ -542,33 +545,70 @@
--model-hub-route-add-height: 38px;
--model-hub-route-add-size: 11.5px;
--model-hub-route-hint-size: 11.5px;
- --model-hub-route-hint-line: 18px;
+ --model-hub-route-hint-line: 17px;
+ --model-hub-route-hint-gap: 7px;
--model-hub-dialog-foot-height: 61px;
--model-hub-dialog-action-height: 33px;
--model-hub-dialog-action-radius: 7px;
--model-hub-dialog-action-size: 12px;
- width: min(var(--model-hub-route-width), calc(100vw - 32px));
+ top: min(
+ var(--model-hub-route-top),
+ max(
+ var(--model-hub-route-viewport-inset),
+ calc(
+ 100dvh - var(--model-hub-route-head-height) -
+ var(--model-hub-route-body-height) -
+ var(--model-hub-dialog-foot-height) -
+ var(--model-hub-route-viewport-inset)
+ )
+ )
+ );
+ width: min(
+ var(--model-hub-route-width),
+ calc(
+ 100vw - var(--model-hub-route-viewport-inset) -
+ var(--model-hub-route-viewport-inset)
+ )
+ );
max-width: var(--model-hub-route-width);
+ max-height: calc(
+ 100dvh - var(--model-hub-route-viewport-inset) -
+ var(--model-hub-route-viewport-inset)
+ );
border-radius: var(--model-hub-route-radius);
+ border-color: var(--model-hub-white-24);
+ box-shadow: var(--model-hub-dialog-shadow);
}
-.model-hub-route-head { height: var(--model-hub-route-head-height); padding: 16px 20px; gap: 4px; }
-.model-hub-route-close { width: 26px; height: 26px; margin: -5px -5px -5px 0; }
+.model-hub-route-head { height: var(--model-hub-route-head-height); flex-shrink: 0; padding: 16px 20px; gap: 4px; border-color: var(--model-hub-white-14); }
+.model-hub-route-close { width: 26px; height: 26px; margin: -5px -5px -5px 0; color: var(--model-hub-white-59); }
.model-hub-route-close > svg { width: 15px; height: 15px; }
.model-hub-route-title { font-size: var(--model-hub-route-title-size); }
.model-hub-route-subtitle { font-size: var(--model-hub-route-subtitle-size); }
-.model-hub-route-body { min-height: var(--model-hub-route-body-height); padding: 20px; gap: var(--model-hub-route-body-gap); }
-.model-hub-route-label { font-size: var(--model-hub-route-label-size); }
-.model-hub-route-list { padding: var(--model-hub-route-list-padding); gap: var(--model-hub-route-list-gap); border-radius: var(--model-hub-route-list-radius); }
+.model-hub-route-body { height: var(--model-hub-route-body-height); min-height: 0; flex: 1 1 var(--model-hub-route-body-height); overflow-y: auto; padding: 20px; gap: var(--model-hub-route-body-gap); }
+.model-hub-route-label { color: var(--model-hub-white-73); font-size: var(--model-hub-route-label-size); letter-spacing: 1.1px; }
+.model-hub-route-list { padding: var(--model-hub-route-list-padding); gap: var(--model-hub-route-list-gap); border-color: var(--model-hub-white-14); border-radius: var(--model-hub-route-list-radius); }
.model-hub-route-hop { height: var(--model-hub-route-hop-height); padding-inline: 10px; gap: var(--model-hub-route-hop-gap); border-radius: var(--model-hub-route-hop-radius); }
.model-hub-route-ordinal { width: var(--model-hub-route-ordinal-size); height: var(--model-hub-route-ordinal-size); border-radius: var(--model-hub-route-ordinal-radius); font-size: 11px; }
.model-hub-route-hop-copy { gap: 3px; }
.model-hub-route-hop-name { font-size: 12px; }
.model-hub-route-hop-model { font-size: 10.5px; }
-.model-hub-route-remove { width: 26px; height: 26px; border-radius: 6px; }
-.model-hub-route-add { height: var(--model-hub-route-add-height); border-radius: var(--model-hub-route-hop-radius); font-size: var(--model-hub-route-add-size); }
+.model-hub-route-grip { width: 14px; height: 14px; color: var(--model-hub-white-4d); }
+.model-hub-route-grip > svg { width: 14px; height: 14px; }
+.model-hub-route-grip[aria-grabbed="true"] { color: var(--mint); }
+.model-hub-route-invalid,
+.model-hub-route-invalid-summary { color: var(--destructive); font-size: 10px; line-height: 14px; }
+.model-hub-route-selector-label { color: var(--model-hub-white-73); font-size: 10.5px; font-weight: 700; }
+.model-hub-route-candidate { min-height: 28px; }
+.model-hub-route-remove { width: 26px; height: 26px; border-radius: 6px; color: var(--foreground); }
+.model-hub-route-remove > svg { width: 13px; height: 13px; }
+.model-hub-route-add { height: var(--model-hub-route-add-height); border-radius: var(--model-hub-route-hop-radius); border-color: var(--model-hub-white-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-hint { font-size: var(--model-hub-route-hint-size); line-height: var(--model-hub-route-hint-line); }
-.model-hub-route-foot { height: var(--model-hub-dialog-foot-height); padding: 14px 20px; }
+.model-hub-route-reseed > svg { width: 12px; height: 12px; }
+.model-hub-route-hint { gap: var(--model-hub-route-hint-gap); color: var(--model-hub-white-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-foot { height: var(--model-hub-dialog-foot-height); flex-shrink: 0; padding: 14px 20px; border-color: var(--model-hub-white-14); }
.model-hub-source-detail {
--model-hub-source-gap: 16px;
@@ -716,7 +756,7 @@
width: min(var(--model-hub-guard-width), calc(100vw - 32px));
gap: 0;
border-radius: var(--model-hub-guard-radius);
- box-shadow: 0 16px 40px #00000099;
+ box-shadow: var(--model-hub-dialog-shadow);
}
.model-hub-guard-head {
padding: var(--model-hub-guard-head-padding-y) var(--model-hub-guard-head-padding-x);
@@ -1032,7 +1072,7 @@
.model-hub-adopt-dialog {
--model-hub-adopt-width: 560px;
--model-hub-adopt-radius: 14px;
- --model-hub-adopt-shadow: 0 16px 40px #00000099;
+ --model-hub-adopt-shadow: var(--model-hub-dialog-shadow);
--model-hub-adopt-head-padding-y: 16px;
--model-hub-adopt-head-padding-x: 20px;
--model-hub-adopt-head-gap: 4px;
diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.ts
index 8dc5b2c05..8e0642ae1 100644
--- a/ui/src/components/settings/models/modelsApi.ts
+++ b/ui/src/components/settings/models/modelsApi.ts
@@ -19,6 +19,7 @@ import {
mockRecommendedOrder,
} from './mockData';
import { canReauth, canReplaceKey, wasBlocked } from './repair';
+import { validateRouteDraft } from './routeChainDraft';
import { isUnhealthy } from './supply';
import type {
AdoptedBy,
@@ -26,6 +27,8 @@ import type {
AgentBackend,
AgentChain,
AgentChainLink,
+ AgentChainMutation,
+ AgentChainPut,
AgentMenu,
AgentMode,
AgentSourcesPut,
@@ -117,6 +120,8 @@ export type ModelsApi = {
putAgentSources(backend: AgentBackend, body: AgentSourcesPut): Promise<AgentSupply>;
/** Resolution chain for one model. Hub mode only — direct answers `direct_mode`. */
getAgentChain(backend: AgentBackend, model: string): Promise<AgentChain>;
+ /** Total replacement of the exact stored chain. */
+ putAgentChain(backend: AgentBackend, model: string, body: AgentChainPut): Promise<AgentChainMutation>;
/** One real request through the chain. Hub mode only, same reason. */
probeAgent(backend: AgentBackend, model?: string): Promise<ProbeResult>;
setAgentMode(backend: AgentBackend, mode: AgentMode): Promise<AgentSupply>;
@@ -141,7 +146,7 @@ export type ModelsApi = {
const isLive = () => MODELS_API_MODE === 'live';
// ── Live client ─────────────────────────────────────────────────────────
-class ApiCallError extends Error {
+export class ApiCallError extends Error {
code: string;
detail?: string;
/**
@@ -384,6 +389,7 @@ const liveApi: ModelsApi = {
// `contract_version` is deliberately absent (unlike every other write here).
putAgentSources: (backend, body) => call<{ agent: AgentSupply }>(`/api/models/agents/${backend}/sources`, jsonInit('PUT', body)).then((r) => r.agent),
getAgentChain: (backend, model) => call<{ chain: AgentChain }>(`/api/models/agents/${backend}/chain?model=${encodeURIComponent(model)}`).then((r) => r.chain),
+ putAgentChain: (backend, model, body) => call<AgentChainMutation>(`/api/models/agents/${backend}/chain?model=${encodeURIComponent(model)}`, jsonInit('PUT', body)),
probeAgent: (backend, model) => call<{ probe: ProbeResult }>(`/api/models/agents/${backend}/probe`, jsonInit('POST', model ? { model } : {})).then((r) => r.probe),
setAgentMode: (backend, mode) => call<{ agent?: AgentSupply } & AgentSupply>(`/api/models/agents/${backend}/mode`, jsonInit('PATCH', { mode })).then((r) => (r.agent ?? r) as AgentSupply),
putMenu: (menu) => call<{ agent?: AgentSupply } & AgentSupply>('/api/models/agents/opencode/menu', jsonInit('PUT', { menu })).then((r) => (r.agent ?? r) as AgentSupply),
@@ -477,16 +483,13 @@ class MockStore {
a.named_agents = (a.named_agents ?? []).map((n) => ({ ...n, effective_model_id: null, supply_status: null }));
return;
}
- const byId = new Map(this.sources.map((s) => [s.id, s]));
const routeFor = (model: string) => a.routes?.[model]?.hops ?? [];
- const chainFor = (model: string) => routeFor(model)
- .map((hop) => byId.get(hop.source_id))
- .filter((s): s is Source => Boolean(s));
+ const chainFor = (model: string) => this.chainFor(a, model).chain;
if (a.builtin_models) {
a.model_supply = a.builtin_models.map((m) => ({
model_id: m,
chain_length: routeFor(m).length,
- has_runnable_hop: chainFor(m).some(isRunnable),
+ has_runnable_hop: chainFor(m).some((link) => link.runnable),
}));
}
const selected = a.selected_model_id ?? null;
@@ -494,13 +497,13 @@ class MockStore {
a.supply_status = null;
} else {
const chain = chainFor(selected);
- const head = chain.find(isRunnable) ?? null;
- const blocked = chain.filter((s) => !isRunnable(s));
+ const head = chain.find((link) => link.runnable) ?? null;
+ const blocked = chain.filter((link) => !link.runnable);
if (!head) {
a.supply_status =
- chain.length > 0 && blocked.every((s) => s.state.status === 'cooldown') ? 'waiting' : 'interrupted';
+ chain.length > 0 && blocked.every((link) => link.health === 'cooldown' && link.reason === null) ? 'waiting' : 'interrupted';
} else {
- a.supply_status = head.id === chain[0]?.id && blocked.length === 0 ? 'ok' : 'degraded';
+ a.supply_status = head === chain[0] && blocked.length === 0 ? 'ok' : 'degraded';
}
}
const rollup = a.supply_status ?? null;
@@ -785,26 +788,28 @@ class MockStore {
const hops = agent.routes?.[model]?.hops ?? [];
const chain: AgentChainLink[] = hops
.map((hop) => ({ hop, source: byId.get(hop.source_id) }))
- .map(({ hop, source }) => ({
- source_id: hop.source_id,
- model_id: hop.model_id,
- source,
- }))
- .map(({ source_id, model_id, source }) => ({
- source_id,
- model_id,
- channel: source?.supply_channel ?? 'hub',
- health: source ? chainHealth(source) : 'error',
- runnable: source ? isRunnable(source) : false,
- // v4: process availability is a fact about the serving process — which
- // native CLI it can launch under its own login — and a browser mock has
- // no way to observe it. So it stands in for a runtime where every
- // configured CLI is launchable, rather than inventing an outage. The
- // unavailable branch is asserted in the unit tests, which can state the
- // fact instead of guessing it.
- reason: source ? null : 'source_missing',
- retry_at: source?.state.status === 'cooldown' ? source.state.retry_at ?? null : null,
- }));
+ .map(({ hop, source }) => {
+ const modelEntry = source?.models.find((entry) => entry.id === hop.model_id);
+ const callable = modelEntry !== undefined && modelEntry.retired !== true;
+ const reason = !source
+ ? 'source_missing' as const
+ : callable ? null : 'model_unsupported' as const;
+ return {
+ source_id: hop.source_id,
+ model_id: hop.model_id,
+ channel: source?.supply_channel ?? 'hub',
+ health: source && callable ? chainHealth(source) : 'error',
+ runnable: source !== undefined && callable && isRunnable(source),
+ // v4: process availability is a fact about the serving process — which
+ // native CLI it can launch under its own login — and a browser mock has
+ // no way to observe it. So it stands in for a runtime where every
+ // configured CLI is launchable, rather than inventing an outage. The
+ // unavailable branch is asserted in the unit tests, which can state the
+ // fact instead of guessing it.
+ reason,
+ retry_at: source && callable && source.state.status === 'cooldown' ? source.state.retry_at ?? null : null,
+ };
+ });
const supply_state: AgentChain['supply_state'] = chain.some((l) => l.runnable)
? 'ok'
: chain.length > 0 && chain.every((l) => l.health === 'cooldown' && l.reason === null)
@@ -831,6 +836,49 @@ class MockStore {
});
}
+ putAgentChain(backend: AgentBackend, model: string, body: AgentChainPut) {
+ const agent = this.agentOr404(backend);
+ if (agent.mode === 'direct') throw new ApiCallError('direct_mode');
+ const byId = new Map(this.sources.map((source) => [source.id, source]));
+ const previous = agent.routes?.[model]?.hops ?? [];
+ if (!validateRouteDraft(agent, this.sources, previous, body.hops).valid) {
+ throw new ApiCallError('model_unsupported');
+ }
+ const removed_hops: RouteHopRef[] = previous.flatMap((hop, index) => body.hops.some((next) => equalHopIdentity(next, hop))
+ ? []
+ : [{ backend, menu_model: model, ...hop, position: index + 1 }]);
+ const impactedAgents = (agent.named_agents ?? [])
+ .filter((entry) => entry.effective_model_id === model)
+ .map((entry) => entry.name);
+ const hasRunnableHop = body.hops.some((hop) => {
+ const source = byId.get(hop.source_id);
+ return source?.models.some((entry) => entry.id === hop.model_id && entry.retired !== true) === true
+ && isRunnable(source);
+ });
+ const gaps: SupplyGap[] = impactedAgents.length > 0 && !hasRunnableHop
+ ? [{ backend, model_id: model, agents: impactedAgents }]
+ : [];
+ const confirmed = body.force === true
+ && JSON.stringify(body.would_interrupt ?? []) === JSON.stringify(gaps)
+ && JSON.stringify(body.would_remove_hops ?? []) === JSON.stringify(removed_hops);
+ if (gaps.length > 0 && !confirmed) throw new ApiCallError('source_last_supplier', undefined, true, gaps, [], removed_hops);
+ agent.routes = { ...(agent.routes ?? {}), [model]: { hops: body.hops.map((hop) => ({ ...hop })) } };
+ this.syncAgents();
+ const settled = this.chainFor(agent, model);
+ return delay({
+ chain: {
+ contract_version: AGENT_CHAIN_CONTRACT_VERSION,
+ backend,
+ model_id: model,
+ current: settled.current,
+ chain: settled.chain,
+ supply_state: settled.supply_state,
+ },
+ removed_hops,
+ interrupted: gaps,
+ });
+ }
+
probeAgent(backend: AgentBackend, model?: string) {
this.syncAgents();
const agent = this.agentOr404(backend);
@@ -1267,6 +1315,7 @@ const mockApi: ModelsApi = {
getAgentSources: (backend) => mockStore.getAgentSources(backend),
putAgentSources: (backend, body) => mockStore.putAgentSources(backend, body),
getAgentChain: (backend, model) => mockStore.getAgentChain(backend, model),
+ putAgentChain: (backend, model, body) => mockStore.putAgentChain(backend, model, body),
probeAgent: (backend, model) => mockStore.probeAgent(backend, model),
setAgentMode: (backend, mode) => mockStore.setAgentMode(backend, mode),
putMenu: (menu) => mockStore.putMenu(menu),
diff --git a/ui/src/components/settings/models/repair.test.ts b/ui/src/components/settings/models/repair.test.ts
index 461ee7e8b..0b440a587 100644
--- a/ui/src/components/settings/models/repair.test.ts
+++ b/ui/src/components/settings/models/repair.test.ts
@@ -531,7 +531,7 @@ describe('probeArrival — an answer nobody wants can still be one the page owes
const frame = readFileSync(join(here, 'RouteChainDialog.tsx'), 'utf8');
expect(row).not.toMatch(/probeAgent|probeArrival/);
- expect(frame).not.toMatch(/probeAgent|probeArrival|modelsApi/);
+ expect(frame).not.toMatch(/probeAgent|probeArrival/);
});
});
diff --git a/ui/src/components/settings/models/routeChainDraft.test.ts b/ui/src/components/settings/models/routeChainDraft.test.ts
new file mode 100644
index 000000000..38f987991
--- /dev/null
+++ b/ui/src/components/settings/models/routeChainDraft.test.ts
@@ -0,0 +1,108 @@
+import { readFileSync } from "node:fs";
+
+import { describe, expect, it } from "vitest";
+
+import {
+ reorderRouteDraft,
+ routeCandidates,
+ validateRouteDraft,
+} from "./routeChainDraft";
+import type { AgentSupply, RouteHop, Source } from "./types";
+
+const source = (id: string, models: string[]): Source => ({
+ id,
+ last_discovered_at: null,
+ kind: "api_key",
+ vendor: "anthropic",
+ display_name: id.toUpperCase(),
+ protocol: "anthropic",
+ supply_channel: "hub",
+ billing: "metered",
+ state: { status: "active", retry_at: null, detail_key: null },
+ models: models.map((modelId) => ({
+ id: modelId,
+ origin: "discovered",
+ reasoning_efforts: [],
+ })),
+});
+
+const agent: AgentSupply = {
+ backend: "claude",
+ cli_present: true,
+ mode: "hub",
+ menu_kind: "fixed",
+ sources: {
+ order: ["src_b", "src_a"],
+ eligibility: [
+ { source_id: "src_a", eligible: true },
+ { source_id: "src_b", eligible: true },
+ ],
+ },
+};
+
+const sources = [
+ source("src_a", ["model-a", "model-b"]),
+ source("src_b", ["model-a"]),
+];
+
+describe("routeChainDraft", () => {
+ it("builds eligible candidates without duplicate exact hops", () => {
+ const candidates = routeCandidates(agent, sources, [
+ { source_id: "src_a", model_id: "model-a" },
+ ]);
+
+ expect(candidates.map(({ hop }) => hop)).toEqual([
+ { source_id: "src_b", model_id: "model-a" },
+ { source_id: "src_a", model_id: "model-b" },
+ ]);
+ });
+
+ it("keeps unchanged stale hops but validates changed and duplicate hops", () => {
+ const stale: RouteHop = { source_id: "missing", model_id: "old-model" };
+ const origin = [stale];
+
+ expect(validateRouteDraft(agent, sources, origin, origin)).toEqual({
+ invalidIndexes: [],
+ valid: true,
+ });
+ expect(validateRouteDraft(agent, sources, [], [stale])).toEqual({
+ invalidIndexes: [0],
+ valid: false,
+ });
+ expect(
+ validateRouteDraft(
+ agent,
+ sources,
+ [],
+ [
+ { source_id: "src_a", model_id: "model-a" },
+ { source_id: "src_a", model_id: "model-a" },
+ ],
+ ),
+ ).toEqual({ invalidIndexes: [0, 1], valid: false });
+ });
+
+ it("keeps the mock write path on the same persisted-pair validator", () => {
+ const api = readFileSync(new URL("./modelsApi.ts", import.meta.url), "utf8");
+
+ expect(api).toMatch(
+ /validateRouteDraft\(agent, this\.sources, previous, body\.hops\)/,
+ );
+ });
+
+ it("sorts listed sources first and preserves stable order for ties", () => {
+ const draft: RouteHop[] = [
+ { source_id: "missing", model_id: "stale-1" },
+ { source_id: "src_a", model_id: "model-b" },
+ { source_id: "src_b", model_id: "model-a" },
+ { source_id: "missing", model_id: "stale-2" },
+ ];
+
+ expect(reorderRouteDraft(agent, draft)).toEqual([
+ { source_id: "src_b", model_id: "model-a" },
+ { source_id: "src_a", model_id: "model-b" },
+ { source_id: "missing", model_id: "stale-1" },
+ { source_id: "missing", model_id: "stale-2" },
+ ]);
+ });
+});
diff --git a/ui/src/components/settings/models/routeChainDraft.ts b/ui/src/components/settings/models/routeChainDraft.ts
new file mode 100644
index 000000000..51c9a69f7
--- /dev/null
+++ b/ui/src/components/settings/models/routeChainDraft.ts
@@ -0,0 +1,132 @@
+import { eligibleSources } from "./eligibility";
+import type {
+ AgentBackend,
+ AgentChain,
+ AgentSupply,
+ RouteHop,
+ Source,
+} from "./types";
+
+export type RouteCandidate = {
+ hop: RouteHop;
+ source: Source;
+};
+
+export type DraftValidation = {
+ invalidIndexes: number[];
+ valid: boolean;
+};
+
+const identity = (hop: RouteHop): string =>
+ `${hop.source_id}\u0000${hop.model_id}`;
+
+/** Candidate inventory for V5. The server-owned eligibility projection is the
+ * only admission check; menu mapping is used only to name the upstream model. */
+export function routeCandidates(
+ agent: AgentSupply,
+ sources: Source[],
+ draft: RouteHop[],
+): RouteCandidate[] {
+ const used = new Set(draft.map(identity));
+ const sourceOrder = new Map(
+ (agent.sources?.order ?? []).map((id, index) => [id, index]),
+ );
+ return eligibleSources(sources, agent)
+ .flatMap((source) =>
+ source.models
+ .filter((model) => model.retired !== true)
+ .map((model) => ({
+ source,
+ hop: {
+ source_id: source.id,
+ // The selector may display a mapped menu identity, but PUT accepts the
+ // exact upstream model id owned by this Source.
+ model_id: model.id,
+ },
+ })),
+ )
+ .filter(({ hop }) => !used.has(identity(hop)))
+ .sort(
+ (left, right) =>
+ (sourceOrder.get(left.source.id) ?? Number.MAX_SAFE_INTEGER) -
+ (sourceOrder.get(right.source.id) ?? Number.MAX_SAFE_INTEGER) ||
+ left.source.display_name.localeCompare(right.source.display_name) ||
+ left.hop.model_id.localeCompare(right.hop.model_id),
+ );
+}
+
+/** V5: unchanged stale identities remain editable; only new/changed pairs need
+ * a live eligible inventory row. */
+export function validateRouteDraft(
+ agent: AgentSupply,
+ sources: Source[],
+ origin: RouteHop[],
+ draft: RouteHop[],
+): DraftValidation {
+ const unchanged = new Set(origin.map(identity));
+ const available = new Set(
+ eligibleSources(sources, agent).flatMap((source) =>
+ source.models
+ .filter((model) => model.retired !== true)
+ .map((model) => `${source.id}\u0000${model.id}`),
+ ),
+ );
+ const counts = new Map<string, number>();
+ draft.forEach((hop) =>
+ counts.set(identity(hop), (counts.get(identity(hop)) ?? 0) + 1),
+ );
+ const allInvalidIndexes = draft.flatMap((hop, index) => {
+ const key = identity(hop);
+ return counts.get(key)! > 1 || (!unchanged.has(key) && !available.has(key))
+ ? [index]
+ : [];
+ });
+ return {
+ invalidIndexes: allInvalidIndexes,
+ valid: allInvalidIndexes.length === 0,
+ };
+}
+
+/** Stable local sort used by the frame control. It never adds or removes hops. */
+export function reorderRouteDraft(
+ agent: AgentSupply,
+ draft: RouteHop[],
+): RouteHop[] {
+ const sourceOrder = new Map(
+ (agent.sources?.order ?? []).map((id, index) => [id, index]),
+ );
+ return draft
+ .map((hop, index) => ({ hop, index }))
+ .sort(
+ (left, right) =>
+ (sourceOrder.has(left.hop.source_id) ? 0 : 1) -
+ (sourceOrder.has(right.hop.source_id) ? 0 : 1) ||
+ (sourceOrder.get(left.hop.source_id) ?? 0) -
+ (sourceOrder.get(right.hop.source_id) ?? 0) ||
+ left.index - right.index,
+ )
+ .map(({ hop }) => hop);
+}
+
+export const sameRouteDraft = (left: RouteHop[], right: RouteHop[]): boolean =>
+ left.length === right.length &&
+ left.every((hop, index) => identity(hop) === identity(right[index]));
+
+export const routeChainMatchesAttempt = (
+ chain: AgentChain,
+ attempt: {
+ backend: AgentBackend;
+ modelId: string;
+ submitted: RouteHop[];
+ },
+): boolean => {
+ const { backend, model_id: menuModel } = chain;
+ return (
+ backend === attempt.backend &&
+ menuModel === attempt.modelId &&
+ sameRouteDraft(
+ chain.chain.map(({ source_id, model_id }) => ({ source_id, model_id })),
+ attempt.submitted,
+ )
+ );
+};
diff --git a/ui/src/components/settings/models/routeChainInteraction.test.ts b/ui/src/components/settings/models/routeChainInteraction.test.ts
new file mode 100644
index 000000000..d0834c1da
--- /dev/null
+++ b/ui/src/components/settings/models/routeChainInteraction.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ advanceRouteChainInteraction,
+ createRouteChainInteraction,
+} from "./routeChainInteraction";
+import type { RouteHop } from "./types";
+
+const hops: RouteHop[] = [
+ { source_id: "src_a", model_id: "model_a" },
+ { source_id: "src_b", model_id: "model_b" },
+ { source_id: "src_c", model_id: "model_c" },
+];
+
+describe("route chain interaction owner", () => {
+ it("moves focus and the grabbed identity together without replacing its snapshot", () => {
+ const grabbed = advanceRouteChainInteraction(
+ createRouteChainInteraction(hops),
+ { type: "begin-grab", index: 1 },
+ );
+ const moved = advanceRouteChainInteraction(grabbed, {
+ type: "move-grab",
+ direction: -1,
+ });
+
+ expect(moved.focusIndex).toBe(0);
+ expect(moved.grab?.index).toBe(0);
+ expect(moved.draft.map((hop) => hop.source_id)).toEqual([
+ "src_b",
+ "src_a",
+ "src_c",
+ ]);
+ expect(
+ advanceRouteChainInteraction(moved, { type: "cancel-grab" }).draft,
+ ).toEqual(hops);
+ });
+
+ it("owns the focus result for removals and appends", () => {
+ const removed = advanceRouteChainInteraction(
+ createRouteChainInteraction(hops),
+ { type: "remove", index: 1 },
+ );
+ expect(removed.focusIndex).toBe(1);
+
+ const appended = advanceRouteChainInteraction(removed, {
+ type: "append",
+ hop: hops[1],
+ });
+ expect(appended.focusIndex).toBe(2);
+ expect(appended.draft).toEqual([hops[0], hops[2], hops[1]]);
+ });
+});
diff --git a/ui/src/components/settings/models/routeChainInteraction.ts b/ui/src/components/settings/models/routeChainInteraction.ts
new file mode 100644
index 000000000..b6074a57e
--- /dev/null
+++ b/ui/src/components/settings/models/routeChainInteraction.ts
@@ -0,0 +1,130 @@
+import type { RouteHop } from "./types";
+
+type GrabState = {
+ index: number;
+ originIndex: number;
+ snapshot: RouteHop[];
+};
+
+export type RouteChainInteraction = {
+ draft: RouteHop[];
+ focusIndex: number;
+ grab: GrabState | null;
+};
+
+export type RouteChainInteractionAction =
+ | { type: "reset"; draft: RouteHop[]; focusIndex?: number }
+ | { type: "focus"; index: number }
+ | { type: "append"; hop: RouteHop }
+ | { type: "remove"; index: number }
+ | { type: "begin-grab"; index: number }
+ | { type: "move-grab"; direction: -1 | 1 }
+ | { type: "move-grab-edge"; edge: "start" | "end" }
+ | { type: "move-grab-to"; index: number }
+ | { type: "drop-grab" }
+ | { type: "cancel-grab" };
+
+const cloneDraft = (draft: RouteHop[]): RouteHop[] =>
+ draft.map((hop) => ({ ...hop }));
+
+const boundedIndex = (index: number, length: number): number =>
+ length === 0 ? 0 : Math.max(0, Math.min(length - 1, index));
+
+const moveGrabbed = (
+ state: RouteChainInteraction,
+ targetIndex: number,
+): RouteChainInteraction => {
+ if (!state.grab || state.draft.length === 0) return state;
+ const nextIndex = boundedIndex(targetIndex, state.draft.length);
+ if (nextIndex === state.grab.index) return state;
+ const draft = [...state.draft];
+ const [moved] = draft.splice(state.grab.index, 1);
+ draft.splice(nextIndex, 0, moved);
+ return {
+ draft,
+ focusIndex: nextIndex,
+ grab: { ...state.grab, index: nextIndex },
+ };
+};
+
+export const createRouteChainInteraction = (
+ draft: RouteHop[] = [],
+): RouteChainInteraction => ({
+ draft: cloneDraft(draft),
+ focusIndex: 0,
+ grab: null,
+});
+
+export function advanceRouteChainInteraction(
+ state: RouteChainInteraction,
+ action: RouteChainInteractionAction,
+): RouteChainInteraction {
+ switch (action.type) {
+ case "reset":
+ return {
+ draft: cloneDraft(action.draft),
+ focusIndex: boundedIndex(
+ action.focusIndex ?? state.focusIndex,
+ action.draft.length,
+ ),
+ grab: null,
+ };
+ case "focus":
+ return {
+ ...state,
+ focusIndex: boundedIndex(action.index, state.draft.length),
+ };
+ case "append":
+ return {
+ draft: [...state.draft, { ...action.hop }],
+ focusIndex: state.draft.length,
+ grab: null,
+ };
+ case "remove": {
+ const draft = state.draft.filter((_, index) => index !== action.index);
+ return {
+ draft,
+ focusIndex: boundedIndex(action.index, draft.length),
+ grab: null,
+ };
+ }
+ case "begin-grab": {
+ if (state.draft.length === 0) return state;
+ const index = boundedIndex(action.index, state.draft.length);
+ return {
+ ...state,
+ focusIndex: index,
+ grab: {
+ index,
+ originIndex: index,
+ snapshot: cloneDraft(state.draft),
+ },
+ };
+ }
+ case "move-grab":
+ return moveGrabbed(
+ state,
+ (state.grab?.index ?? state.focusIndex) + action.direction,
+ );
+ case "move-grab-edge":
+ return moveGrabbed(
+ state,
+ action.edge === "start" ? 0 : state.draft.length - 1,
+ );
+ case "move-grab-to":
+ return moveGrabbed(state, action.index);
+ case "drop-grab":
+ return state.grab ? { ...state, grab: null } : state;
+ case "cancel-grab":
+ return state.grab
+ ? {
+ draft: cloneDraft(state.grab.snapshot),
+ focusIndex: boundedIndex(
+ state.grab.originIndex,
+ state.grab.snapshot.length,
+ ),
+ grab: null,
+ }
+ : state;
+ }
+}
diff --git a/ui/src/components/settings/models/routeProjectionReconciliation.test.ts b/ui/src/components/settings/models/routeProjectionReconciliation.test.ts
new file mode 100644
index 000000000..8f3d6233a
--- /dev/null
+++ b/ui/src/components/settings/models/routeProjectionReconciliation.test.ts
@@ -0,0 +1,144 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { createRouteProjectionReconciler } from "./routeProjectionReconciliation";
+import type { AgentSupply, Source } from "./types";
+
+const agent: AgentSupply = {
+ backend: "claude",
+ cli_present: true,
+ menu_kind: "fixed",
+ mode: "hub",
+};
+const source: Source = {
+ id: "source",
+ last_discovered_at: null,
+ kind: "api_key",
+ vendor: "anthropic",
+ display_name: "Source",
+ protocol: "anthropic",
+ supply_channel: "hub",
+ billing: "metered",
+ state: { status: "active", retry_at: null, detail_key: null },
+ models: [],
+};
+
+const deferred = <T>() => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((accept) => {
+ resolve = accept;
+ });
+ return { promise, resolve };
+};
+
+describe("route projection reconciliation", () => {
+ it("installs Agents before acquiring Sources and survives presentation transfer", async () => {
+ const agents = deferred<{ value: AgentSupply[]; install: () => void }>();
+ const agentInstall = vi.fn();
+ const sourceInstall = vi.fn();
+ const readSources = vi.fn().mockResolvedValue({
+ value: [source],
+ install: sourceInstall,
+ });
+ const statuses = vi.fn();
+ const reconciler = createRouteProjectionReconciler({
+ readAgents: vi.fn().mockReturnValue(agents.promise),
+ readSources,
+ onFailure: vi.fn(),
+ onStatus: statuses,
+ });
+
+ reconciler.start("claude");
+ expect(readSources).not.toHaveBeenCalled();
+ agents.resolve({ value: [agent], install: agentInstall });
+ await vi.waitFor(() => expect(sourceInstall).toHaveBeenCalledTimes(1));
+ expect(agentInstall).toHaveBeenCalledTimes(1);
+ expect(readSources).toHaveBeenCalledTimes(1);
+ expect(statuses).toHaveBeenLastCalledWith({
+ pending: false,
+ failed: new Set(),
+ });
+ });
+
+ it("installs an authoritative collection that omits the edited backend", async () => {
+ const agentInstall = vi.fn();
+ const sourceInstall = vi.fn();
+ const readSources = vi.fn().mockResolvedValue({
+ value: [source],
+ install: sourceInstall,
+ });
+ const statuses = vi.fn();
+ const reconciler = createRouteProjectionReconciler({
+ readAgents: vi.fn().mockResolvedValue({ value: [], install: agentInstall }),
+ readSources,
+ onFailure: vi.fn(),
+ onStatus: statuses,
+ });
+
+ reconciler.start("claude");
+
+ await vi.waitFor(() => expect(sourceInstall).toHaveBeenCalledTimes(1));
+ expect(agentInstall).toHaveBeenCalledTimes(1);
+ expect(readSources).toHaveBeenCalledTimes(1);
+ expect(statuses).toHaveBeenLastCalledWith({
+ pending: false,
+ failed: new Set(),
+ });
+ });
+
+ it("retries an Agents failure before activating its deferred Source member", async () => {
+ const readAgents = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("unread"))
+ .mockResolvedValueOnce({ value: [agent], install: vi.fn() });
+ const readSources = vi
+ .fn()
+ .mockResolvedValue({ value: [source], install: vi.fn() });
+ const statuses = vi.fn();
+ const reconciler = createRouteProjectionReconciler({
+ readAgents,
+ readSources,
+ onFailure: vi.fn(),
+ onStatus: statuses,
+ });
+
+ reconciler.start("claude");
+ await vi.waitFor(() =>
+ expect(statuses).toHaveBeenLastCalledWith({
+ pending: false,
+ failed: new Set(["agents"]),
+ }),
+ );
+ expect(readSources).not.toHaveBeenCalled();
+ reconciler.retry();
+ await vi.waitFor(() => expect(readSources).toHaveBeenCalledTimes(1));
+ expect(readAgents).toHaveBeenCalledTimes(2);
+ });
+
+ it("retries only Sources after Agents has already settled", async () => {
+ const readAgents = vi
+ .fn()
+ .mockResolvedValue({ value: [agent], install: vi.fn() });
+ const readSources = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("unread"))
+ .mockResolvedValueOnce({ value: [source], install: vi.fn() });
+ const statuses = vi.fn();
+ const reconciler = createRouteProjectionReconciler({
+ readAgents,
+ readSources,
+ onFailure: vi.fn(),
+ onStatus: statuses,
+ });
+
+ reconciler.start("claude");
+ await vi.waitFor(() =>
+ expect(statuses).toHaveBeenLastCalledWith({
+ pending: false,
+ failed: new Set(["sources"]),
+ }),
+ );
+ reconciler.retry();
+ await vi.waitFor(() => expect(readSources).toHaveBeenCalledTimes(2));
+ expect(readAgents).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/ui/src/components/settings/models/routeProjectionReconciliation.ts b/ui/src/components/settings/models/routeProjectionReconciliation.ts
new file mode 100644
index 000000000..980e8642b
--- /dev/null
+++ b/ui/src/components/settings/models/routeProjectionReconciliation.ts
@@ -0,0 +1,84 @@
+import type { RouteCollectionObservation } from "./RouteChainDialog";
+import type { AgentSupply, Source } from "./types";
+import type { AgentBackend } from "./types";
+
+export type RouteProjectionMember = "agents" | "sources";
+
+export type RouteProjectionStatus = {
+ failed: ReadonlySet<RouteProjectionMember>;
+ pending: boolean;
+};
+
+type RouteProjectionReaders = {
+ readAgents: () => Promise<RouteCollectionObservation<AgentSupply[]>>;
+ readSources: () => Promise<RouteCollectionObservation<Source[]>>;
+ onFailure: (member: RouteProjectionMember) => void;
+ onStatus: (status: RouteProjectionStatus) => void;
+};
+
+/** M6 is page-owned: closing the modal changes presentation ownership but never
+ * cancels, restarts or broadens the projection generation. */
+export const createRouteProjectionReconciler = ({
+ readAgents,
+ readSources,
+ onFailure,
+ onStatus,
+}: RouteProjectionReaders) => {
+ let generation = 0;
+ let failed = new Set<RouteProjectionMember>();
+ let activeBackend: AgentBackend | null = null;
+
+ const publish = (pending: boolean) =>
+ onStatus({ pending, failed: new Set(failed) });
+
+ const settle = async (
+ token: number,
+ members: ReadonlySet<RouteProjectionMember>,
+ ) => {
+ failed = new Set();
+ publish(true);
+
+ if (members.has("agents")) {
+ try {
+ const observation = await readAgents();
+ if (token !== generation) return;
+ observation.install();
+ } catch {
+ if (token !== generation) return;
+ failed.add("agents");
+ onFailure("agents");
+ publish(false);
+ return;
+ }
+ }
+
+ if (members.has("sources") || members.has("agents")) {
+ try {
+ const observation = await readSources();
+ if (token !== generation) return;
+ observation.install();
+ } catch {
+ if (token !== generation) return;
+ failed.add("sources");
+ onFailure("sources");
+ }
+ }
+ if (token === generation) publish(false);
+ };
+
+ return {
+ start: (backend: AgentBackend) => {
+ activeBackend = backend;
+ const token = ++generation;
+ void settle(token, new Set(["agents"]));
+ },
+ retry: () => {
+ if (failed.size === 0 || !activeBackend) return;
+ const token = ++generation;
+ void settle(token, failed);
+ },
+ invalidate: () => {
+ generation += 1;
+ },
+ };
+};
diff --git a/ui/src/components/settings/models/suspendedRouteAttempts.test.ts b/ui/src/components/settings/models/suspendedRouteAttempts.test.ts
new file mode 100644
index 000000000..c97803cbf
--- /dev/null
+++ b/ui/src/components/settings/models/suspendedRouteAttempts.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ emptySuspendedRouteAttempts,
+ holdSuspendedRouteAttempt,
+ releaseSuspendedRouteAttempt,
+} from "./suspendedRouteAttempts";
+
+describe("suspended route attempts", () => {
+ it("settles only the matching backend", () => {
+ const claude = {
+ backend: "claude" as const,
+ modelId: "claude-model",
+ stage: "initial" as const,
+ submitted: [],
+ };
+ const codex = {
+ backend: "codex" as const,
+ modelId: "codex-model",
+ stage: "confirmed" as const,
+ submitted: [],
+ };
+ const held = holdSuspendedRouteAttempt(
+ holdSuspendedRouteAttempt(emptySuspendedRouteAttempts(), claude),
+ codex,
+ );
+
+ const remaining = releaseSuspendedRouteAttempt(held, "codex");
+
+ expect(remaining.get("claude")).toEqual(claude);
+ expect(remaining.has("codex")).toBe(false);
+ });
+});
diff --git a/ui/src/components/settings/models/suspendedRouteAttempts.ts b/ui/src/components/settings/models/suspendedRouteAttempts.ts
new file mode 100644
index 000000000..6149b76a8
--- /dev/null
+++ b/ui/src/components/settings/models/suspendedRouteAttempts.ts
@@ -0,0 +1,29 @@
+import type { SuspendedRouteAttempt } from "./RouteChainDialog";
+import type { AgentBackend } from "./types";
+
+export type SuspendedRouteAttempts = ReadonlyMap<
+ AgentBackend,
+ SuspendedRouteAttempt
+>;
+
+export const emptySuspendedRouteAttempts = (): SuspendedRouteAttempts =>
+ new Map();
+
+export const holdSuspendedRouteAttempt = (
+ attempts: SuspendedRouteAttempts,
+ attempt: SuspendedRouteAttempt,
+): SuspendedRouteAttempts => {
+ const next = new Map(attempts);
+ next.set(attempt.backend, attempt);
+ return next;
+};
+
+export const releaseSuspendedRouteAttempt = (
+ attempts: SuspendedRouteAttempts,
+ backend: AgentBackend,
+): SuspendedRouteAttempts => {
+ if (!attempts.has(backend)) return attempts;
+ const next = new Map(attempts);
+ next.delete(backend);
+ return next;
+};
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index ece91a181..843fd3e29 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -82,6 +82,8 @@ export type SuppliedModel = {
display_name?: string | null;
origin: ModelOrigin;
reasoning_efforts: string[];
+ /** Persistent retirement tombstone; retired entries stay readable but are not callable. */
+ retired?: boolean;
discovered_at?: string | null;
};
@@ -586,6 +588,19 @@ export type SourcePatch = {
export type AgentSourcesPut = { order: string[] };
/** PUT /api/models/agents/<backend>/chain?model=<id> — replaces exact hops. */
+export type AgentChainPut = {
+ hops: RouteHop[];
+ force?: boolean;
+ would_remove_hops?: RouteHopRef[];
+ would_interrupt?: SupplyGap[];
+};
+
+export type AgentChainMutation = {
+ chain: AgentChain;
+ removed_hops: RouteHopRef[];
+ interrupted: SupplyGap[];
+};
+
/**
* PUT /api/models/sources/<id>/credential — hub-channel api_key sources only.
* Also a TOTAL body that rejects unknown keys (`contract_version` included), so
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index c13a4ce60..d95dc5e37 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -997,12 +997,34 @@
"runtimeAction": "Resolve"
},
"routeDialog": {
- "title": "{{model}} · Route chain",
+ "title": "{{menuModel}} · Route chain",
"open": "Open {{model}} route chain",
"label": "Route chain for this model",
+ "section": "Route chain for this model",
"removeHop": "Remove hop",
"addHop": "Add a hop",
- "reseed": "Reorder by source order",
+ "add": { "source": "Source", "model": "Model", "confirm": "Add", "none": "No source/model pair is available to add" },
+ "sourceMissing": "Source missing",
+ "invalidAfterRefresh": "This edited hop is unavailable after the refresh. Remove it before saving.",
+ "reorder": {
+ "label": "Reorder by Source order",
+ "grabbed": "Hop {{position}} grabbed. Use arrow keys to move.",
+ "position": "Moved to hop {{position}}.",
+ "dropped": "Dropped at hop {{position}}.",
+ "cancelled": "Reorder cancelled. Restored to hop {{position}}.",
+ "sorted": "Reordered by Source order.",
+ "unchanged": "The route chain already matches Source order."
+ },
+ "grip": "Reorder this hop",
+ "loading": "Loading route chain…",
+ "cancel": "Cancel",
+ "save": "Save",
+ "saving": "Saving route chain…",
+ "refreshing": "Route chain saved. Refreshing the model surface…",
+ "fail": { "read": "The route chain could not be read", "save": "The route chain was not saved", "unconfirmed": "The save outcome is not confirmed", "reconcileRead": "The current model surface could not be read" },
+ "retry": "Retry",
+ "empty": "This route chain is empty. Add a hop, or leave it unconfigured.",
+ "impact": { "title": "The route chain was saved", "detail": "These are the items this save actually removed or interrupted.", "refreshFail": "The route chain was saved, but the model surface could not be refreshed.", "done": "Done" },
"hint": "This chain is stored configuration. Later source-order changes do not change it."
},
"recent": {
@@ -1306,15 +1328,18 @@
"cancel": "Cancel",
"title": {
"refetch": "Refetch models from {{source}}",
- "removeModel": "Remove {{model}} from {{source}}"
+ "removeModel": "Remove {{model}} from {{source}}",
+ "saveRoute": "Save the route chain for {{menuModel}}"
},
"subtitle": {
"refetch": "This refetch drops models from this source's inventory.",
- "removeModel": "This model disappears from this source's inventory."
+ "removeModel": "This model disappears from this source's inventory.",
+ "saveRoute": "This save leaves a configured model with no usable source"
},
"confirm": {
"refetch": "Refetch anyway",
- "removeModel": "Remove anyway"
+ "removeModel": "Remove anyway",
+ "saveRoute": "Save anyway"
}
},
"repair": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 2b0206fd1..1c76595f1 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -997,13 +997,35 @@
"runtimeAction": "去处理"
},
"routeDialog": {
- "title": "{{model}} · 路由链",
+ "title": "{{menuModel}} · 路由链",
"open": "打开 {{model}} 的路由链",
"label": "这个型号的路由链",
+ "section": "这个型号的路由链",
"removeHop": "移除这一跳",
"addHop": "添加一跳",
- "reseed": "按来源顺序重排",
- "hint": "这条链是写下来的配置。以后来源顺序怎么变,它都不变。"
+ "add": { "source": "来源", "model": "型号", "confirm": "添加", "none": "没有可添加的来源型号" },
+ "sourceMissing": "来源不存在",
+ "invalidAfterRefresh": "这个已编辑的跳在刷新后的来源中不可用。移除它后再保存。",
+ "reorder": {
+ "label": "按来源顺序重排",
+ "grabbed": "已抓取第 {{position}} 跳。使用方向键移动。",
+ "position": "已移到第 {{position}} 跳。",
+ "dropped": "已放到第 {{position}} 跳。",
+ "cancelled": "已取消重排,恢复到第 {{position}} 跳。",
+ "sorted": "已按来源顺序重排。",
+ "unchanged": "路由链已经符合来源顺序。"
+ },
+ "grip": "调整这一跳的顺序",
+ "loading": "正在读取路由链…",
+ "cancel": "取消",
+ "save": "保存",
+ "saving": "正在保存路由链…",
+ "refreshing": "路由链已保存,正在刷新模型页面…",
+ "fail": { "read": "路由链没读到", "save": "路由链没保存上", "unconfirmed": "保存结果还没确认", "reconcileRead": "当前模型页面暂时没读到" },
+ "retry": "重试",
+ "empty": "这条路由链是空的。添加一跳,或保持为空配置。",
+ "impact": { "title": "路由链已保存", "detail": "以下是这次保存实际移除或中断的项目。", "refreshFail": "路由链已保存,但模型页面暂时无法刷新。", "done": "完成" },
+ "hint": "这条链是写下来的配置。以后来源顺序怎么变,它都不变。"
},
"recent": {
"title": "最近切换",
@@ -1306,15 +1328,18 @@
"cancel": "取消",
"title": {
"refetch": "重新拉取 {{source}} 的型号",
- "removeModel": "从 {{source}} 移除 {{model}}"
+ "removeModel": "从 {{source}} 移除 {{model}}",
+ "saveRoute": "保存 {{menuModel}} 的路由链"
},
"subtitle": {
"refetch": "这次拉取会让部分型号从这个来源的清单里消失。",
- "removeModel": "这个型号会从这个来源的清单里消失。"
+ "removeModel": "这个型号会从这个来源的清单里消失。",
+ "saveRoute": "这次保存会让已配置的型号没有可用来源"
},
"confirm": {
"refetch": "仍要拉取",
- "removeModel": "仍要移除"
+ "removeModel": "仍要移除",
+ "saveRoute": "仍要保存"
}
},
"repair": {