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.

96.3 KB
Raw Blame
import * as React from 'react';
import { ArrowDownToLine, Activity, Gauge, LoaderCircle, RefreshCw, Route, ScrollText, Wrench } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';

import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';
import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover';
import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
import { useToast } from '@/context/ToastContext';
import { cn } from '@/lib/utils';
import { AddApiKeyDialog } from './AddApiKeyDialog';
import { webFetchTool } from './webFetch';
import { AddSearchServiceDialog } from './AddSearchServiceDialog';
import { searchServicesActive, webSearchTool, KEYLESS_EXA_SOURCE_ID, keylessExaSource } from './searchServices';
import { BackendModelCatalogDialog, type CatalogFocus } from './BackendModelCatalogDialog';
import { OAuthConnectDialog } from './OAuthConnectDialog';
import { GatewayModule } from './GatewayModule';
import { MigrationDialog } from './MigrationDialog';
import { ModelHubInfoHint } from './ModelHubInfoHint';
import { RecentSwitchesCard } from './RecentSwitchesCard';
import { RouteChainDialog, type RouteCollectionObservation, type RouteReport, type SuspendedRouteAttempt } from './RouteChainDialog';
import { routeChainMatchesAttempt } from './routeChainDraft';
import { SourceDetailPanel } from './SourceDetailPanel';
import { SourceOrderDrawer } from './SourceOrderDrawer';
import { SourcesCard } from './SourcesCard';
import { agentUsesHubRuntime, modelsSurfaceKindFromReads } from './modelHubSurfaceState';
import { focusDialogReturn, focusModelHubProjection } from './modelHubFocus';
import { MODEL_HUB_MANAGE_PARAM } from './modelHubRoutes';
import { buildSupplyRelations } from './supplyRelations';
import {
  emptySuspendedRouteAttempts,
  holdSuspendedRouteAttempt,
  releaseSuspendedRouteAttempt,
} from './suspendedRouteAttempts';
import { SupplyGraph, SupplyLegend } from './SupplyGraph';
import { QuotaTab } from './QuotaTab';
import { ToolsTab } from './ToolsTab';
import { UsageTab } from './UsageTab';
import { useHostedTools } from './useHostedTools';
import './modelHubSurface.css';
import { agentsWithEcho, createLatestAsyncAuthority, createLatestAsyncAuthorityByKeySet, createLatestEntityAuthorityByKey, createPendingWrites, mapWithConcurrency } from './asyncLifetime';
import { createAgentCollectionReadAuthority, createSourceCollectionReadAuthority } from './collectionReadAuthority';
import { emptyFeed, feedAfterHeadRead, feedAfterTailRead, feedTailCursor, type EventFeed } from './eventFeed';
import { modelsApi, type SourceCreated } from './modelsApi';
import { convergeMutation, createIntentAuthority } from './mutationConvergence';
import {
  readSurfaceLanding,
  sourceMutationReadFailed,
  SOURCE_MUTATION_TOAST,
  type PresentSourceMutationCommit,
  type SourceMutationLanding,
  type SourceMutationLandingReads,
  type SourceMutationSettlement,
  type TrackSourceMutation,
} from './mutationSettlement';
import { chainKeyBackend, modelChainKey, modelChainRequests, type ModelChainIndex, type ModelChainRequest } from './modelRows';
import {
  beginRegionRead,
  failRegionRead,
  foldRegionRead,
  degradedRegion,
  loadingRegion,
  readRegion,
  readyRegion,
  settleRegionRead,
  unreadRegion,
  type RegionRead,
} from './regionRead';
import { freshRuntimeProjection, pollRuntimeStatus, resumeInstallAndStartRuntime, runtimeCanAttemptInstall, runtimeIsRunning } from './runtimeLifecycle';
import { createRouteProjectionReconciler, type RouteProjectionStatus } from './routeProjectionReconciliation';
import { canReauth, reauthBodyKey, reauthCost } from './repair';
import { resumeGatewayAdoption } from './gatewayAdoption';
import { groupMigrationCandidates } from './migrationGrouping';
import { SUBSCRIPTION_MENU_ROWS } from './subscriptionOptions';
import { VendorGlyph } from './vendorGlyph';
import { USAGE_DEFAULT_WINDOW, type AgentBackend, type AgentMode, type AgentSupply, type ResolutionEvent, type QuotaSummary, type RuntimeDependency, type Source, type UsageReport, type UsageWindowKey } from './types';
import { backendDisplayOrder, getBackendUiMeta, isNativeCliBackend, type NativeCliBackend } from '@/lib/agentBackends';

const CHAIN_READ_CONCURRENCY = 6;
const EVENT_PAGE = 20;
type ModelsTranslate = (key: string, options?: Record<string, unknown>) => string;

const useModelsTranslation = () => {
  const translation = useTranslation();
  return {
    ...translation,
    t: translation.t as unknown as ModelsTranslate,
  };
};

type RouteTarget = {
  agent: AgentSupply;
  modelId: string;
  opener: HTMLElement | null;
};
// The 添加订阅 menu's rows, derived from the one subscription-vendor vocabulary rather
// than restated here. `subscriptionOptions.ts` owns which vendors are offered and
// what custody each has, so this menu cannot drift out of the same order the
// dialog's chooser reads.
const SUBSCRIPTION_PICKER_OPTIONS = SUBSCRIPTION_MENU_ROWS;
type SubscriptionPickerVendor = (typeof SUBSCRIPTION_PICKER_OPTIONS)[number]['vendor'];

const readChainRequests = async (requests: readonly ModelChainRequest[]): Promise<ModelChainIndex> => Object.fromEntries(
  await mapWithConcurrency(
    requests,
    CHAIN_READ_CONCURRENCY,
    async ({ backend, modelId }) => {
      const key = modelChainKey(backend, modelId);
      try {
        return [key, readyRegion(await modelsApi.getAgentChain(backend, modelId))] as const;
      } catch {
        return [key, unreadRegion()] as const;
      }
    },
  ),
);

const readAgentChains = async (agent: AgentSupply): Promise<ModelChainIndex> => {
  const requests = modelChainRequests([agent]);
  try {
    const chains = new Map(
      (await modelsApi.getAgentChains(agent.backend)).map((chain) => [chain.model_id, chain]),
    );
    return Object.fromEntries(requests.map(({ backend, modelId }) => {
      const chain = chains.get(modelId);
      return [
        modelChainKey(backend, modelId),
        chain?.backend === backend ? readyRegion(chain) : unreadRegion(),
      ];
    }));
  } catch {
    return Object.fromEntries(requests.map(({ backend, modelId }) => [
      modelChainKey(backend, modelId),
      unreadRegion(),
    ]));
  }
};

const readExactAgentChain = async (
  agent: AgentSupply,
  modelId: string,
): Promise<ModelChainIndex> => ({
  [modelChainKey(agent.backend, modelId)]: readyRegion(
    await modelsApi.getAgentChain(agent.backend, modelId),
  ),
});

/**
 * Installs exactly the chains this read still owns.
 *
 * There is no backend-wide sweep here. A read owns chain keys, not a backend,
 * so a key it does not own belongs to a newer read and has to be left exactly
 * as that read left it. Retiring the keys of models a backend no longer has is
 * `beginAgentChainIndex`'s job, which reseeds the backend from the Agent's
 * current catalogue before every whole-backend read.
 */
const settleChainIndex = (
  previous: ModelChainIndex,
  incoming: ModelChainIndex,
  owned: ReadonlySet<string>,
): ModelChainIndex => {
  const next = { ...previous };
  for (const [key, read] of Object.entries(incoming)) {
    if (!owned.has(key)) continue;
    next[key] = settleRegionRead(previous[key] ?? loadingRegion(), read);
  }
  return next;
};

const beginAgentChainIndex = (
  previous: ModelChainIndex,
  agent: AgentSupply,
): ModelChainIndex => {
  const prefix = `${agent.backend}\u0000`;
  const next = Object.fromEntries(Object.entries(previous).filter(([key]) => !key.startsWith(prefix)));
  for (const { backend, modelId } of modelChainRequests([agent])) {
    const key = modelChainKey(backend, modelId);
    next[key] = beginRegionRead(previous[key] ?? loadingRegion());
  }
  return next;
};

type AuthorizedSurfaceLanding = {
  landing: SourceMutationLandingReads;
  sourceSnapshot: number;
};

export const RuntimePill: React.FC<{
  read: RegionRead<RuntimeDependency>;
  starting: boolean;
  directCount?: number;
}> = ({ read, starting, directCount }) => {
  const { t } = useModelsTranslation();
  const projection = foldRegionRead<RuntimeDependency, { runtime: RuntimeDependency; authoritative: boolean } | null>(read, {
    loading: () => null,
    ready: (runtime) => ({ runtime, authoritative: true }),
    unread: () => null,
    degraded: (runtime) => ({ runtime, authoritative: false }),
  });
  if (!projection) {
    const key = read.kind === 'loading' ? 'starting' : 'unread';
    return <span className={cn('model-hub-runtime-pill', read.kind !== 'loading' && 'model-hub-runtime-pill--error')}><span className="model-hub-runtime-dot" />{read.kind === 'loading' && <LoaderCircle className="animate-spin" />}{t(`settings.models.shell.${key}`)}</span>;
  }
  const { runtime, authoritative } = projection;
  const health = runtime.status.health;
  const unread = read.kind === 'degraded' && read.cause === 'read_failed';
  const canInstall = health === 'not_installed' && runtimeCanAttemptInstall(runtime);
  const allDirect = authoritative && !starting && health === 'ok' && directCount !== undefined && directCount > 0;
  const key = unread
    ? 'unread'
    : starting
    ? 'starting'
    : health === 'installing'
      ? 'starting'
    : runtime.enabled && !runtimeIsRunning(runtime)
      ? 'unavailable'
    : health === 'ok'
      ? allDirect ? 'allDirect' : 'running'
        : health === 'degraded'
          ? 'degraded'
        : health === 'down'
          ? 'stopped'
          : health === 'not_started'
            ? 'notStarted'
            : canInstall
              ? 'notInstalled'
              : 'unsupported';
  const className = cn(
    'model-hub-runtime-pill',
    (health === 'down' || health === 'degraded' || unread) && 'model-hub-runtime-pill--error',
    allDirect && 'model-hub-runtime-pill--direct',
  );
  return <span className={className}><span className="model-hub-runtime-dot" />{(starting || health === 'installing') && <LoaderCircle className="animate-spin" />}{t(`settings.models.shell.${key}`, allDirect ? { count: directCount } : undefined)}</span>;
};

const RuntimeClosedState: React.FC<{
  read: RegionRead<RuntimeDependency>;
  runtime: RuntimeDependency | null;
  starting: boolean;
  onRetry?: () => void;
}> = ({ read, runtime, starting, onRetry }) => {
  const { t } = useModelsTranslation();
  const health = runtime?.status.health ?? null;
  const key = starting
      ? 'starting'
      : read.kind === 'unread'
        ? 'unread'
        : health === 'installing'
          ? 'installing'
          : runtime?.enabled && health !== null && !runtimeIsRunning(runtime)
            ? 'enabledDown'
          : health === 'not_installed' && runtime?.manifest.resolution === 'unsupported'
            ? 'unsupported'
            : health === 'not_installed'
              ? 'notInstalled'
              : health === 'down'
                ? 'down'
                : 'off';
  const busy = starting || health === 'installing';
  return (
    <section className="model-hub-runtime-closed" aria-live="polite">
      <span className="model-hub-runtime-closed-icon" aria-hidden="true">
        {busy ? <LoaderCircle className="animate-spin" /> : <RefreshCw />}
      </span>
      <h2>{t(`settings.models.shell.closed.${key}.title`)}</h2>
      <p>{t(`settings.models.shell.closed.${key}.body`)}</p>
      {onRetry && <Button variant="secondary" size="sm" className="mt-4" disabled={busy} onClick={onRetry}>{t('settings.models.gateway.retry')}</Button>}
    </section>
  );
};

const ModelHubShell: React.FC<{ status?: React.ReactNode; actions?: React.ReactNode; children: React.ReactNode; rootRef?: React.Ref<HTMLDivElement> }> = ({ status, actions, children, rootRef }) => {
  const { t } = useModelsTranslation();
  return (
    <div ref={rootRef} className="model-hub-shell">
      <header className="model-hub-shell-head">
        <div className="model-hub-shell-identity">
          <span className="model-hub-shell-title">
            <h1>{t('settings.models.shell.title')}</h1>
            <ModelHubInfoHint
              label={t('settings.models.shell.modelsInfo.label')}
              content={t('settings.models.shell.modelsInfo.body')}
              className="model-hub-shell-info"
            />
          </span>
          {status}
        </div>
        {actions}
      </header>
      {children}
    </div>
  );
};

/** The service refreshes each Source at most this often; polling faster buys nothing. */
const QUOTA_POLL_MS = 5 * 60_000;
/** A read the service is still running past its page deadline lands soon after;
 *  re-read at this pace, a bounded number of times, rather than wait a whole poll. */
export const QUOTA_PENDING_REREAD_MS = 5_000;
export const QUOTA_PENDING_REREADS = 3;

/**
 * Re-read a report whose reading the service says is still landing — a quota
 * read past its deadline, or prices whose first fetch is running — soon, a
 * bounded number of times in a row. `pendingKey` is null while no settled
 * reading is on screen and '' when nothing is pending; `settled` counts settled
 * reads, so one that lands still pending re-arms the timer. Returns the reset a
 * fresh open or a manual refresh calls.
 */
function usePendingRereads(active: boolean, pendingKey: string | null, settled: number, reread: () => void) {
  const rereads = React.useRef(0);
  React.useEffect(() => {
    if (!active || pendingKey === null) return undefined;
    if (pendingKey === '') {
      rereads.current = 0;
      return undefined;
    }
    if (rereads.current >= QUOTA_PENDING_REREADS) return undefined;
    const timer = window.setTimeout(() => {
      rereads.current += 1;
      reread();
    }, QUOTA_PENDING_REREAD_MS);
    return () => window.clearTimeout(timer);
  }, [active, pendingKey, settled, reread]);
  return React.useCallback(() => { rereads.current = 0; }, []);
}

/** Back to the re-login button of a quota card, or to the selected tab once a refresh has removed it. */
const focusQuotaOpener = (opener: HTMLElement) =>
  (opener.isConnected ? opener : document.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]'))?.focus();

type HubTab = 'sources' | 'tools' | 'quota' | 'usage' | 'logs';

const HubTabs: React.FC<{ tab: HubTab; onChange: (tab: HubTab) => void }> = ({ tab, onChange }) => {
  const { t } = useModelsTranslation();
  return (
    <div role="tablist" className="model-hub-tabs flex min-w-0 items-end gap-1 overflow-x-auto border-b border-border">
      {(['sources', 'tools', 'quota', 'usage', 'logs'] as const).map((id) => (
        <button key={id} type="button" role="tab" aria-selected={tab === id} onClick={() => onChange(id)} className={cn('flex h-[41px] shrink-0 items-center gap-[7px] whitespace-nowrap border-b-2 px-3.5 text-[13px] transition-colors', tab === id ? 'border-mint font-semibold text-foreground' : 'border-transparent font-normal text-muted hover:text-foreground')}>
          {id === 'sources' ? <Route className="size-3.5" /> : id === 'tools' ? <Wrench className="size-3.5" /> : id === 'quota' ? <Gauge className="size-3.5" /> : id === 'usage' ? <Activity className="size-3.5" /> : <ScrollText className="size-3.5" />}
          {t(`settings.models.shell.tab.${id === 'sources' ? 'hub' : id}`)}
        </button>
      ))}
    </div>
  );
};

const DirectHome: React.FC<{
  agents: (AgentSupply & { backend: NativeCliBackend })[];
  switchFailures: ReadonlySet<string>;
  connectingBackend: string | null;
  onSwitch: (agent: AgentSupply) => void;
}> = ({ agents, switchFailures, connectingBackend, onSwitch }) => {
  const { t } = useModelsTranslation();
  if (agents.length === 0) {
    return <section className="model-hub-direct-empty"><h2>{t('settings.models.direct.empty.title')}</h2><p>{t('settings.models.direct.empty.body')}</p><span>{t('settings.models.direct.empty.install')}</span></section>;
  }
  return (
    <div className="model-hub-direct">
      <div className="model-hub-direct-grid grid">
        <section className="model-hub-direct-card overflow-hidden border border-border bg-surface">
          <div className="model-hub-direct-head flex items-center gap-3 border-b border-border px-5 py-3">
            <div><h2 className="text-[16px] font-bold text-foreground">{t('settings.models.direct.card.current')}</h2><p className="mt-1 text-[11.5px] text-muted">{t('settings.models.direct.card.current.sub')}</p></div>
          </div>
          <div className="model-hub-direct-content flex flex-col">
            {[...agents].sort((left, right) => backendDisplayOrder(left.backend) - backendDisplayOrder(right.backend)).map((agent) => {
              const { Icon, tileCls, iconCls, label } = getBackendUiMeta(agent.backend);
              const switchFailed = switchFailures.has(agent.backend);
              return (
                <div key={agent.backend} className="model-hub-direct-row model-hub-direct-row--backend flex flex-wrap items-center gap-2.5 bg-background px-3 sm:flex-nowrap">
                  <span className={cn('flex size-[34px] shrink-0 items-center justify-center rounded-[9px]', tileCls)}><Icon className={cn('size-[17px]', iconCls)} /></span>
                  <span className="model-hub-direct-backend-copy">
                    <span className="flex min-w-0 items-center gap-1.5">
                      <span className="model-hub-direct-backend-name truncate text-foreground">{label}</span>
                      <span className="model-hub-pill model-hub-direct-kind-pill border">{t('settings.models.direct.pill.direct')}</span>
                    </span>
                    {switchFailed
                      ? <span role="status" className="truncate text-[11px] font-semibold leading-normal text-destructive-ink">{t('settings.models.gateway.fail.switchToGateway')}</span>
                      : <span className="model-hub-direct-backend-detail truncate" title={t(`settings.models.direct.backend.${agent.backend}.detail`) as string}>{t(`settings.models.direct.backend.${agent.backend}.detail`)}</span>}
                  </span>
                  <Button variant="secondary" size="sm" className="model-hub-direct-switch h-auto rounded-lg px-3 py-[9px] text-[11.5px] font-bold" onClick={() => onSwitch(agent)} disabled={connectingBackend === agent.backend}>{t(switchFailed ? 'settings.models.gateway.retry' : 'settings.models.direct.action.switchToGateway')}</Button>
                </div>
              );
            })}
          </div>
        </section>
        <section className="model-hub-direct-card overflow-hidden border border-border bg-surface">
          <div className="model-hub-direct-head flex items-center border-b border-border px-5 py-3"><h2 className="text-[16px] font-bold text-foreground">{t('settings.models.direct.benefits.title')}</h2></div>
          <div className="model-hub-direct-content flex flex-col">{(['1', '2', '3'] as const).map((key) => <div key={key} className="model-hub-direct-row flex items-start gap-2.5 bg-background px-3 py-[11px]"><span className="model-hub-ink-mint grid size-5 shrink-0 place-items-center rounded-full bg-mint-soft text-[10.5px] font-bold">{key}</span><span className="model-hub-direct-benefit-copy"><span className="model-hub-direct-benefit-title-row flex items-center gap-1.5"><span className="text-[12.5px] font-semibold text-foreground">{t(`settings.models.direct.benefits.${key}`)}</span></span><span className="model-hub-direct-benefit-detail">{t(`settings.models.direct.benefits.${key}.detail`)}</span></span></div>)}</div>
        </section>
      </div>
      <p className="model-hub-direct-note flex items-center justify-center border text-center text-[11.5px]">{t('settings.models.direct.note.perBackend')}</p>
    </div>
  );
};

const TakeoverPill: React.FC<{ count: number }> = ({ count }) => {
  const { t } = useModelsTranslation();
  if (count === 0) return null;
  return <span className="model-hub-takeover-pill"><span className="model-hub-runtime-dot" />{t('settings.models.takeover.pill', { count })}</span>;
};

export const SettingsModelsPage: React.FC = () => {
  const { t } = useModelsTranslation();
  const { showToast } = useToast();
  const navigate = useNavigate();
  // An Agent named in the warning list is a destination, not a label: the page
  // that can fix it is Agents, and it has to open on the one that needs the fix.
  const openAgentDefinition = React.useCallback(
    (name: string) => navigate(`/agents?tab=definitions&agent=${encodeURIComponent(name)}`),
    [navigate],
  );
  /** The catalog's 「Add models」 action reads the candidates endpoint, which
   *  names Sources — so it is offered on the same capability that lets a role
   *  administer this instance's Agents, and read here rather than in the dialog
   *  because the page is where this surface's authorization already lands. */
  const { capabilities } = useInstanceAuthorization();
  const [sourcesRead, setSourcesRead] = React.useState<RegionRead<Source[]>>(loadingRegion);
  const [supplyRead, setSupplyRead] = React.useState<RegionRead<AgentSupply[]>>(loadingRegion);
  const [chainsRead, setChainsRead] = React.useState<RegionRead<ModelChainIndex>>(loadingRegion);
  const [runtimeRead, setRuntimeRead] = React.useState<RegionRead<RuntimeDependency>>(loadingRegion);
  const [eventsRead, setEventsRead] = React.useState<RegionRead<EventFeed>>(loadingRegion);
  const [loadingEvents, setLoadingEvents] = React.useState(false);
  const [tab, setTab] = React.useState<HubTab>('sources');
  const [usageRead, setUsageRead] = React.useState<RegionRead<UsageReport>>(loadingRegion);
  const [usageWindow, setUsageWindow] = React.useState<UsageWindowKey>(USAGE_DEFAULT_WINDOW);
  const [quotaRead, setQuotaRead] = React.useState<RegionRead<QuotaSummary>>(loadingRegion);
  const [refreshingQuota, setRefreshingQuota] = React.useState(false);
  const [startingRuntime, setStartingRuntime] = React.useState(false);
  const [runtimeRecoveryPending, setRuntimeRecoveryPending] = React.useState(false);
  const [migrationOpen, setMigrationOpen] = React.useState(false);
  const [migrationBackend, setMigrationBackend] = React.useState<AgentBackend | null>(null);
  /** Whether the header's migrate entry has anything to open onto: the same
   *  groups the dialog would list, so the button and the dialog cannot
   *  disagree. `null` until a scan answers; a failed scan keeps the entry,
   *  because the dialog is where that failure is explained. */
  const [migrationAvailable, setMigrationAvailable] = React.useState<boolean | null>(null);
  /** Bumped by the explicit refresh, so a native login made since is noticed. */
  const [migrationScanEpoch, setMigrationScanEpoch] = React.useState(0);
  const [apiKeyOpen, setApiKeyOpen] = React.useState(false);
  const [searchServiceOpen, setSearchServiceOpen] = React.useState(false);
  const [serviceDetailView, setServiceDetailView] = React.useState(false);
  const [subscriptionPickerOpen, setSubscriptionPickerOpen] = React.useState(false);
  const [subscriptionPickerIndex, setSubscriptionPickerIndex] = React.useState(0);
  const [subscriptionVendor, setSubscriptionVendor] = React.useState<string | null>(null);
  // The source a re-login is FOR, held as the snapshot `OAuthConnectDialog`
  // documents its `reauth` prop to be: a native re-auth writes 需处理 onto the row
  // before the login starts, so re-reading the live row mid-flow would rewrite
  // the dialog's own subject. Separate from `subscriptionVendor` because the two
  // journeys start from different surfaces — this one from the source detail,
  // which replaces the overview that holds 添加订阅 — and only the create path
  // owns the success landing and reconcile flag below.
  const [reauthSource, setReauthSource] = React.useState<Source | null>(null);
  // A quota read can be the first to see a refused grant while the Source row
  // is still healthy, so its re-login cannot route through the detail panel's
  // repair button (which only a blocked row shows). It asks the same question
  // here, then starts the same journey.
  const [quotaReauthSource, setQuotaReauthSource] = React.useState<Source | null>(null);
  // A re-login started from a quota card has no detail heading to return to.
  const quotaReauthOpenerRef = React.useRef<HTMLElement | null>(null);
  // The card button focus went back to when that re-login closed, until the
  // quota re-read its success started has landed.
  const quotaFocusHoldRef = React.useRef<HTMLElement | null>(null);
  const subscriptionTriggerRef = React.useRef<HTMLButtonElement>(null);
  const apiKeyTriggerRef = React.useRef<HTMLButtonElement | null>(null);
  const subscriptionAnchorRef = subscriptionTriggerRef as React.RefObject<HTMLButtonElement>;
  const subscriptionPickerRefs = React.useRef<Partial<Record<SubscriptionPickerVendor, HTMLButtonElement | null>>>({});
  const subscriptionPickerHandoffRef = React.useRef(false);
  // A successful OAuth terminal reports the same moved rows twice: first with
  // the created source, then as the generic stale-row notification. The source
  // callback owns the one full reconciliation; consume the trailing notification
  // so it cannot launch a second refresh that overwrites a successful landing.
  const subscriptionSuccessReconcileRef = React.useRef(false);
  const sourceDetailHeadingRef = React.useRef<HTMLHeadingElement>(null);
  const sourceDetailReturnFocusRef = React.useRef<(() => HTMLElement | null) | null>(null);
  const [orderBackend, setOrderBackend] = React.useState<AgentBackend | null>(null);
  const [menuBackend, setMenuBackend] = React.useState<AgentBackend | null>(null);
  const [catalogFocus, setCatalogFocus] = React.useState<CatalogFocus | null>(null);
  // The route the catalog was opened from. Its action unmounted with the route
  // dialog, so closing the catalog returns focus to that model row instead.
  const catalogOriginRef = React.useRef<RouteTarget | null>(null);
  const [adoptAgent, setAdoptAgent] = React.useState<AgentSupply | null>(null);
  const [routeTarget, setRouteTarget] = React.useState<RouteTarget | null>(null);
  const pendingRouteOpenersRef = React.useRef(new Map<RouteReport, HTMLElement | null>());
  const suspendedRouteOpenersRef = React.useRef(new WeakMap<SuspendedRouteAttempt, HTMLElement | null>());
  const sourcesRetryRef = React.useRef<HTMLButtonElement>(null);
  const supplyRetryRef = React.useRef<HTMLButtonElement>(null);
  const routeCommitStatusRef = React.useRef<RouteProjectionStatus | null>(null);
  const [routeCommitStatus, setRouteCommitStatus] = React.useState<RouteProjectionStatus | null>(null);
  const routeCommitBackends = React.useMemo(
    () => new Set([...pendingRouteOpenersRef.current.keys()].map((report) => report.chain.backend)),
    // Status changes notify us when a report is queued or settled.
    [routeCommitStatus],
  );
  const [suspendedRouteAttempts, setSuspendedRouteAttempts] = React.useState(
    emptySuspendedRouteAttempts,
  );
  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());
  // A failed switch is kept with the mode it failed to leave: it stays visible
  // while that mode holds and clears once the backend has moved on.
  const [switchFailureModes, setSwitchFailureModes] = React.useState<ReadonlyMap<string, AgentMode>>(() => new Map());
  const switchFailures = React.useMemo<ReadonlySet<string>>(() => new Set(switchFailureModes.keys()), [switchFailureModes]);
  const markSwitchFailed = (backend: string, mode: AgentMode) => {
    setSwitchFailureModes((previous) => new Map(previous).set(backend, mode));
  };
  const clearSwitchFailure = (backend: string) => {
    setSwitchFailureModes((previous) => {
      if (!previous.has(backend)) return previous;
      const next = new Map(previous);
      next.delete(backend);
      return next;
    });
  };
  const [agentWriteRegistry] = React.useState(() => createPendingWrites(setAgentWrites));
  const [sourceIntentAuthority] = React.useState(createIntentAuthority);
  const [sourceCollectionReads] = React.useState(() => createSourceCollectionReadAuthority(modelsApi));
  const [agentCollectionReads] = React.useState(() => createAgentCollectionReadAuthority(modelsApi));
  const [presenceRefreshing, setPresenceRefreshing] = React.useState(false);
  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,
    (inventory) => {
      if (aliveRef.current) setSourcesRead(readyRegion(inventory));
    },
  ));
  const [sourceWriteRegistry] = React.useState(() => createPendingWrites(() => {}));
  React.useEffect(() => {
    aliveRef.current = true;
    return () => { aliveRef.current = false; };
  }, []);

  const sources = foldRegionRead<Source[], Source[]>(sourcesRead, {
    loading: () => [],
    ready: (data) => data,
    unread: () => [],
    degraded: (staleData) => staleData,
  });
  const agents = foldRegionRead<AgentSupply[], AgentSupply[]>(supplyRead, {
    loading: () => [],
    ready: (data) => data,
    unread: () => [],
    degraded: (staleData) => staleData,
  });
  // `?manage=<backend>` is a model picker's 「Add model」 exit. Once the supply
  // read can say whether that backend is on the Hub, open its catalog (or
  // nothing, if it is not) and drop the parameter so a reload or Back does not
  // open it again. The replace keeps the Settings overlay's origin in state.
  const [searchParams, setSearchParams] = useSearchParams();
  const location = useLocation();
  const requestedCatalogBackend = searchParams.get(MODEL_HUB_MANAGE_PARAM);
  const supplyKnown = supplyRead.kind === 'ready' || supplyRead.kind === 'degraded';
  React.useEffect(() => {
    if (requestedCatalogBackend === null || !supplyKnown) return;
    const requested = agents.find((agent) => agent.backend === requestedCatalogBackend && agent.mode === 'hub');
    if (requested) {
      catalogOriginRef.current = null;
      setCatalogFocus(null);
      setMenuBackend(requested.backend);
    }
    const next = new URLSearchParams(searchParams);
    next.delete(MODEL_HUB_MANAGE_PARAM);
    setSearchParams(next, { replace: true, state: location.state });
  }, [agents, location.state, requestedCatalogBackend, searchParams, setSearchParams, supplyKnown]);
  const chains = foldRegionRead<ModelChainIndex, ModelChainIndex>(chainsRead, {
    loading: () => ({}),
    ready: (data) => data,
    unread: () => ({}),
    degraded: () => ({}),
  });
  const runtime = freshRuntimeProjection(runtimeRead);
  const retainedRuntime = foldRegionRead<RuntimeDependency, RuntimeDependency | null>(runtimeRead, {
    loading: () => null,
    ready: (data) => data,
    unread: () => null,
    degraded: (staleData) => staleData,
  });
  const feed = foldRegionRead<EventFeed, EventFeed>(eventsRead, {
    loading: () => emptyFeed,
    ready: (data) => data,
    unread: () => emptyFeed,
    degraded: (staleData) => staleData,
  });
  const runtimeHealth = retainedRuntime?.status.health ?? null;
  const runtimeRunning = retainedRuntime !== null
    && runtimeIsRunning(retainedRuntime)
    && runtimeRead.kind !== 'unread';
  const runtimeEnabled = retainedRuntime !== null
    && (retainedRuntime.enabled ?? runtimeIsRunning(retainedRuntime))
    && runtimeRead.kind !== 'unread';
  const runtimeConfigurationVisible = runtimeRunning || (runtimeEnabled && runtimeHealth !== 'installing');
  React.useEffect(() => {
    // Re-asked whenever the dialog closes, since applying it is what empties
    // the scan.
    if (!runtimeConfigurationVisible || migrationOpen) return;
    let cancelled = false;
    modelsApi.scanMigration()
      .then((scan) => {
        if (!cancelled) setMigrationAvailable(groupMigrationCandidates(scan.items, () => true).length > 0);
      })
      .catch(() => {
        if (!cancelled) setMigrationAvailable(true);
      });
    return () => { cancelled = true; };
  }, [migrationOpen, migrationScanEpoch, runtimeConfigurationVisible]);
  React.useEffect(() => {
    const runtimeCanRecover = runtimeRead.kind === 'unread'
      || (runtimeRead.kind === 'degraded' && runtimeRead.cause === 'read_failed')
      || runtimeRecoveryPending
      || runtimeHealth === 'not_started'
      || runtimeHealth === 'not_installed'
      || runtimeHealth === 'installing'
      || runtimeHealth === 'down'
      || runtimeHealth === 'degraded';
    if (!runtimeCanRecover || startingRuntime) return undefined;
    return pollRuntimeStatus(modelsApi, (nextRuntime) => {
      if (!aliveRef.current) return;
      setRuntimeRead(readyRegion(nextRuntime));
      setRuntimeRecoveryPending(false);
    });
  }, [runtimeHealth, runtimeRead.kind, runtimeRecoveryPending, startingRuntime]);

  const [chainReadAuthority] = React.useState(() => createLatestAsyncAuthorityByKeySet<string, ModelChainIndex>((incoming, owned) => {
    if (!aliveRef.current) return;
    setChainsRead((previous) => readyRegion(settleChainIndex(
      foldRegionRead<ModelChainIndex, ModelChainIndex>(previous, {
        loading: () => ({}),
        ready: (data) => data,
        unread: () => ({}),
        degraded: (staleData) => staleData,
      }),
      incoming,
      owned,
    )));
  }));

  const refreshAgentChains = React.useCallback(async (agent: AgentSupply) => {
    setChainsRead((previous) => readyRegion(beginAgentChainIndex(foldRegionRead<ModelChainIndex, ModelChainIndex>(previous, {
      loading: () => ({}),
      ready: (data) => data,
      unread: () => ({}),
      degraded: (staleData) => staleData,
    }), agent)));
    await chainReadAuthority.run(
      modelChainRequests([agent]).map(({ backend, modelId }) => modelChainKey(backend, modelId)),
      () => readAgentChains(agent),
    );
  }, [chainReadAuthority]);

  const refreshAffectedChains = React.useCallback(async (
    requests: readonly ModelChainRequest[],
  ): Promise<ModelChainIndex> => {
    let incoming: ModelChainIndex = {};
    const owned = await chainReadAuthority.run(
      requests.map(({ backend, modelId }) => modelChainKey(backend, modelId)),
      async () => {
        incoming = await readChainRequests(requests);
        return incoming;
      },
    );
    // What drops out here is exactly the chains a newer read took over, and that
    // read is the one installing them — a superseded key is not an unreadable
    // one. Every key this read still owns stays, failed or not, because no other
    // read is going to answer for it.
    return Object.fromEntries(Object.entries(incoming).filter(([key]) => owned.has(key)));
  }, [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)
      && !routeCommitBackends.has(agent.backend));
    const activeBackends = new Set(hubAgents.map((agent) => agent.backend));
    chainReadAuthority.invalidateExcept((key) => activeBackends.has(chainKeyBackend(key)));
    setChainsRead((previous) => readyRegion(Object.fromEntries(
      Object.entries(foldRegionRead<ModelChainIndex, ModelChainIndex>(previous, {
        loading: () => ({}),
        ready: (data) => data,
        unread: () => ({}),
        degraded: (staleData) => staleData,
      })).filter(([key]) => activeBackends.has(chainKeyBackend(key))),
    )));
    for (const agent of probeAgents) void refreshAgentChains(agent);
  }, [chainReadAuthority, refreshAgentChains, routeCommitBackends, suspendedRouteAttempts]);

  React.useEffect(() => {
    const freshSupply = foldRegionRead<AgentSupply[], AgentSupply[] | null>(supplyRead, {
      loading: () => null,
      ready: (data) => data,
      unread: () => null,
      degraded: () => null,
    });
    if (freshSupply) {
      refreshAllAgentChains(freshSupply);
      setSwitchFailureModes((previous) => new Map(
        [...previous].filter(([backend, mode]) => freshSupply.some((agent) => agent.backend === backend && agent.mode === mode)),
      ));
    }
  }, [refreshAllAgentChains, supplyRead]);

  const [eventReadAuthority] = React.useState(() => createLatestAsyncAuthority<RegionRead<ResolutionEvent[]>>((incoming) => {
    if (!aliveRef.current) return;
    setEventsRead((previous) => {
      if (incoming.kind !== 'ready') return failRegionRead(previous);
      const previousFeed = foldRegionRead<EventFeed, EventFeed | undefined>(previous, {
        loading: () => undefined,
        ready: (data) => data,
        unread: () => undefined,
        degraded: (staleData) => staleData,
      });
      const freshEvents = foldRegionRead<ResolutionEvent[], ResolutionEvent[] | null>(incoming, {
        loading: () => null,
        ready: (data) => data,
        unread: () => null,
        degraded: () => null,
      });
      if (!freshEvents) return failRegionRead(previous);
      return readyRegion(previousFeed
        ? feedAfterHeadRead(previousFeed, freshEvents)
        : feedAfterTailRead(emptyFeed, freshEvents, EVENT_PAGE, null));
    });
  }));

  const [usageSettled, setUsageSettled] = React.useState(0);
  const [usageReadAuthority] = React.useState(() => createLatestAsyncAuthority<RegionRead<UsageReport>>((incoming) => {
    if (!aliveRef.current) return;
    setUsageRead((previous) => settleRegionRead(previous, incoming));
    setUsageSettled((count) => count + 1);
  }));

  const refreshUsage = React.useCallback(async (window: UsageWindowKey) => {
    setUsageRead(beginRegionRead);
    await usageReadAuthority.run(() => readRegion(() => modelsApi.getUsageSummary(window)));
  }, [usageReadAuthority]);

  /**
   * The usage report is read lazily, when the tab is opened.
   *
   * It is deliberately NOT a first-paint region (see `firstPaintRegions.ts`,
   * whose whitelist is a policy list of exactly the three reads the landing
   * cannot be drawn without): a report nobody is looking at must not delay the
   * surface that decides routing. Re-reading on every open is the point — the
   * figure is live, and `beginRegionRead` keeps the previous one on screen while
   * the new one lands, so returning to the tab never flashes empty. A window
   * change is the same read with a different span, which is why one effect owns
   * both.
   */
  /** A first install has no price table yet: while its fetch runs, re-read so the prices land on screen. */
  const usagePendingKey = foldRegionRead<UsageReport, string | null>(usageRead, {
    loading: () => null,
    ready: (data) => (data.pricing?.pending ? 'pricing' : ''),
    unread: () => null,
    degraded: () => null,
  });
  const rereadUsage = React.useCallback(() => { void refreshUsage(usageWindow); }, [refreshUsage, usageWindow]);
  const resetUsageRereads = usePendingRereads(tab === 'usage', usagePendingKey, usageSettled, rereadUsage);

  React.useEffect(() => {
    if (tab !== 'usage') return;
    resetUsageRereads();
    void refreshUsage(usageWindow);
  }, [tab, usageWindow, refreshUsage, resetUsageRereads]);

  const retryUsage = React.useCallback(async () => {
    resetUsageRereads();
    await refreshUsage(usageWindow);
  }, [refreshUsage, resetUsageRereads, usageWindow]);

  // Counts settled reads, so a re-read that lands with the same pending set
  // still re-arms the timer below.
  const [quotaSettled, setQuotaSettled] = React.useState(0);
  const [quotaReadAuthority] = React.useState(() => createLatestAsyncAuthority<RegionRead<QuotaSummary>>((incoming) => {
    if (!aliveRef.current) return;
    setQuotaRead((previous) => settleRegionRead(previous, incoming));
    setQuotaSettled((count) => count + 1);
  }));

  const readQuota = React.useCallback(async (force: boolean) => {
    setQuotaRead(beginRegionRead);
    await quotaReadAuthority.run(() => readRegion(() => (force ? modelsApi.refreshQuota() : modelsApi.getQuota())));
  }, [quotaReadAuthority]);

  /**
   * Subscription quota is read lazily too, for the same reason as usage: it is
   * a report, and the landing that decides routing must not wait on a vendor.
   * While the tab stays open it re-reads on the service's own cadence; the
   * service caches per Source, so an interval tick costs a vendor call only
   * when that Source's reading is actually due.
   */
  /**
   * What the service named as still landing: the Sources still reading, and
   * prices whose first fetch is running. Null while no settled reading is on
   * screen, '' when nothing is pending.
   */
  const quotaPendingKey = foldRegionRead<QuotaSummary, string | null>(quotaRead, {
    loading: () => null,
    ready: (data) => [...(data.pending ?? []), ...(data.value?.pending ? ['\u0001pricing'] : [])].join('\u0000'),
    unread: () => null,
    degraded: () => null,
  });
  const rereadQuota = React.useCallback(() => { void readQuota(false); }, [readQuota]);
  // A clean re-login closes before the quota re-read it started lands, and a
  // healthy answer removes the card button focus just went back to.
  React.useLayoutEffect(() => {
    const held = quotaFocusHoldRef.current;
    quotaFocusHoldRef.current = null;
    if (held && !held.isConnected && document.activeElement === document.body) focusQuotaOpener(held);
  }, [quotaSettled]);
  const resetQuotaRereads = usePendingRereads(tab === 'quota', quotaPendingKey, quotaSettled, rereadQuota);

  React.useEffect(() => {
    if (tab !== 'quota') return undefined;
    resetQuotaRereads();
    void readQuota(false);
    const timer = window.setInterval(() => { void readQuota(false); }, QUOTA_POLL_MS);
    return () => window.clearInterval(timer);
  }, [tab, readQuota, resetQuotaRereads]);

  const refreshQuotaNow = React.useCallback(async () => {
    resetQuotaRereads();
    setRefreshingQuota(true);
    try {
      await readQuota(true);
    } finally {
      if (aliveRef.current) setRefreshingQuota(false);
    }
  }, [readQuota, resetQuotaRereads]);

  const retryQuota = React.useCallback(async () => {
    await readQuota(false);
  }, [readQuota]);

  const refreshEventHead = React.useCallback(async () => {
    setEventsRead(beginRegionRead);
    await eventReadAuthority.run(async () => {
      try {
        return readyRegion(await modelsApi.listEvents(EVENT_PAGE));
      } catch {
        return unreadRegion<ResolutionEvent[]>();
      }
    });
  }, [eventReadAuthority]);

  React.useEffect(() => {
    if (tab !== 'logs') return;
    void refreshEventHead();
  }, [refreshEventHead, tab]);

  const [refreshAuthority] = React.useState(() => createLatestAsyncAuthority<AuthorizedSurfaceLanding>(({ landing, sourceSnapshot }) => {
    if (!aliveRef.current) return;
    const freshSources = foldRegionRead<Source[], Source[] | null>(landing.sources, {
      loading: () => null,
      ready: (data) => data,
      unread: () => null,
      degraded: () => null,
    });
    if (freshSources) sourceEntityAuthority.settleSnapshot(sourceSnapshot, freshSources);
    else setSourcesRead((previous) => settleRegionRead(previous, landing.sources));
    setSupplyRead((previous) => settleRegionRead(previous, landing.supply));
    setRuntimeRead((previous) => {
      const next = settleRegionRead(previous, landing.runtime);
      if (next.kind === 'ready') setRuntimeRecoveryPending(false);
      return next;
    });
    if (landing.supply.kind !== 'ready') setChainsRead(failRegionRead);
  }));

  const refresh = React.useCallback(async (
    affectedChains: ModelChainRequest[] = [],
  ): Promise<SourceMutationLanding> => {
    const outcome: { landing: SourceMutationLandingReads | null } = { landing: null };
    const result = await refreshAuthority.run(async () => {
      const sourceSnapshot = sourceEntityAuthority.beginSnapshot();
      outcome.landing = await readSurfaceLanding({
        sources: sourceCollectionReads.readValue,
        supply: agentCollectionReads.readValue,
        runtime: () => modelsApi.getRuntimeStatus(),
        chains: refreshAffectedChains,
      }, affectedChains);
      return { landing: outcome.landing, sourceSnapshot };
    });
    if (!aliveRef.current || result === 'stale') return null;
    const landing = outcome.landing;
    // Every region this read installs is in scope, route chains included: a
    // chain card's own Retry is not always rendered, so dropping the page line
    // would leave a real read failure with nothing that says so. What is out of
    // scope is supersession, which no longer reaches here as a failure.
    if (landing !== null && sourceMutationReadFailed(landing)) {
      showToast(t('settings.models.toast.refreshFailed') as string, 'error');
    }
    return landing;
  }, [agentCollectionReads, refreshAffectedChains, refreshAuthority, showToast, sourceCollectionReads, sourceEntityAuthority, t]);

  const trackSourceMutation = React.useCallback((sourceId: string): TrackSourceMutation => async <T,>(work: (source: Source, settlement: SourceMutationSettlement) => Promise<T>): Promise<T> => {
    let result!: T;
    await sourceWriteRegistry.track(sourceId, async () => {
      const current = sourceEntityAuthority.current(sourceId);
      if (!current) throw new Error(`Source ${sourceId} is no longer available`);
      const generation = sourceEntityAuthority.begin(sourceId);
      let settled = false;
      const finish = async (
        apply: () => void,
        affectedChains: ModelChainRequest[] = [],
      ): Promise<SourceMutationLanding> => {
        if (!settled) {
          settled = true;
          apply();
        }
        return refresh(affectedChains);
      };
      const settlement: SourceMutationSettlement = {
        source: async (echoed, scope) => finish(
          () => { sourceEntityAuthority.settle(generation, echoed); },
          scope?.affectedChains,
        ),
        gone: async (goneId, inventory, scope) => finish(() => {
          if (inventory) {
            sourceEntityAuthority.settleSnapshotEntries(
              inventory.snapshot,
              inventory.sources.filter((source) => source.id !== goneId),
            );
          }
          if (goneId === sourceId) sourceEntityAuthority.settleRemoval(generation);
        }, scope?.affectedChains),
        unread: async (scope) => finish(
          () => { sourceEntityAuthority.abandon(generation); },
          scope?.affectedChains,
        ),
        release: () => {
          if (settled) return;
          settled = true;
          sourceEntityAuthority.abandon(generation);
        },
        readInventory: async () => {
          const snapshot = sourceEntityAuthority.beginSnapshot();
          return { snapshot, sources: await sourceCollectionReads.readValue() };
        },
      };
      try {
        result = await work(current, settlement);
      } finally {
        settlement.release();
      }
    });
    return result;
  }, [refresh, sourceCollectionReads, sourceEntityAuthority, sourceWriteRegistry]);

  const refreshAgentPresence = React.useCallback(async () => {
    setPresenceRefreshing(true);
    try {
      const result = await agentCollectionReads.refresh();
      if (!aliveRef.current || result.kind === 'stale') return;
      setSupplyRead(readyRegion(result.value));
    } finally {
      if (aliveRef.current) setPresenceRefreshing(false);
    }
  }, [agentCollectionReads]);

  React.useEffect(() => {
    let current = true;
    void refresh().then(() => {
      if (!current) return;
      void refreshAgentPresence().catch(() => {
        // The fast snapshot remains authoritative if optional deep discovery fails.
      });
    });
    return () => { current = false; };
  }, [refresh, refreshAgentPresence]);

  const retrySources = React.useCallback(async () => {
    setSourcesRead(beginRegionRead);
    await refresh();
  }, [refresh]);

  const retrySupply = React.useCallback(async () => {
    if (presenceRefreshing) return;
    try {
      await refreshAgentPresence();
    } catch {
      if (aliveRef.current) setSupplyRead(failRegionRead);
    }
  }, [presenceRefreshing, refreshAgentPresence]);

  const retryEvents = React.useCallback(async () => {
    await refreshEventHead();
  }, [refreshEventHead]);

  const applyAgentEcho = React.useCallback((echoed: AgentSupply) => {
    setSupplyRead((previous) => readyRegion(agentsWithEcho(foldRegionRead(previous, {
      loading: () => [],
      ready: (data) => data,
      unread: () => [],
      degraded: (staleData) => staleData,
    }), echoed)));
  }, []);
  const agentSaved = React.useCallback(async (echoed: AgentSupply) => {
    await convergeMutation({
      entity: echoed,
      applyEntity: applyAgentEcho,
      reconcile: refresh,
    });
  }, [applyAgentEcho, refresh]);
  const catalogSaved = React.useCallback(async (echoed: AgentSupply) => {
    await agentSaved(echoed);
    if (aliveRef.current) showToast(t('settings.models.gateway.catalog.saved') as string, 'success');
  }, [agentSaved, showToast, t]);
  const switchToDirect = (agent: AgentSupply) => {
    clearSwitchFailure(agent.backend);
    void agentWriteRegistry.track(agent.backend, async () => {
      try {
        const echoed = await modelsApi.setAgentMode(agent.backend, 'direct');
        clearSwitchFailure(agent.backend);
        setAdoptAgent(null);
        await agentSaved(echoed);
      } catch {
        try {
          const result = await agentCollectionReads.read();
          if (result.kind === 'stale') return;
          const authoritative = result.value;
          setSupplyRead(readyRegion(authoritative));
          const committed = authoritative.some((row) => row.backend === agent.backend && row.mode === 'direct');
          if (committed) clearSwitchFailure(agent.backend);
          else markSwitchFailed(agent.backend, 'hub');
        } catch {
          markSwitchFailed(agent.backend, 'hub');
        }
      }
    });
  };
  const enterGateway = async (backend: AgentBackend) => {
    const echoed = await modelsApi.setAgentMode(backend, 'hub');
    clearSwitchFailure(backend);
    await agentSaved(echoed);
  };
  // Migration is optional: declining it still switches the backend it was
  // offered for, which keeps its native login beside the gateway.
  const declineMigration = (backend: AgentBackend) => {
    void agentWriteRegistry.track(backend, async () => {
      try {
        await enterGateway(backend);
      } catch {
        markSwitchFailed(backend, 'direct');
      }
    });
  };
  const switchToGateway = (agent: AgentSupply) => {
    if (agentWrites.has(agent.backend)) return;
    setAdoptAgent(agent);
    clearSwitchFailure(agent.backend);
    void agentWriteRegistry.track(agent.backend, async () => {
      try {
        const result = await resumeGatewayAdoption(modelsApi, agentCollectionReads, agent.backend);
        if (result.runtime) setRuntimeRead(readyRegion(result.runtime));
        if (!result.ok) {
          markSwitchFailed(agent.backend, 'direct');
          return;
        }
        if (result.candidates.length > 0) {
          setMigrationBackend(agent.backend);
          setMigrationOpen(true);
          return;
        }
        await enterGateway(agent.backend);
      } catch {
        markSwitchFailed(agent.backend, 'direct');
      } finally {
        if (aliveRef.current) setAdoptAgent(null);
      }
    });
  };
  const loadOlderEvents = React.useCallback(async () => {
    const cursor = feedTailCursor(feed);
    if (!cursor) return;
    setLoadingEvents(true);
    try {
      const events = await modelsApi.listEvents(EVENT_PAGE, cursor);
      if (aliveRef.current) {
        setEventsRead((previous) => readyRegion(feedAfterTailRead(foldRegionRead(previous, {
          loading: () => emptyFeed,
          ready: (data) => data,
          unread: () => emptyFeed,
          degraded: (staleData) => staleData,
        }), events, EVENT_PAGE, cursor)));
      }
    } catch {
      if (aliveRef.current) showToast(t('settings.models.toast.refreshFailed') as string, 'error');
    } finally {
      if (aliveRef.current) setLoadingEvents(false);
    }
  }, [feed, showToast, t]);
  const startRuntime = async () => {
    if (startingRuntime) return;
    setStartingRuntime(true);
    try {
      if (!retainedRuntime) {
        setRuntimeRead(failRegionRead);
        setRuntimeRecoveryPending(true);
        showToast(t('settings.models.errors.startFailed') as string, 'error');
        return;
      }
      const result = await resumeInstallAndStartRuntime(
        modelsApi,
        retainedRuntime,
        (nextRuntime) => {
          if (aliveRef.current) setRuntimeRead(readyRegion(nextRuntime));
        },
      );
      setRuntimeRead((previous) => result.runtime === null
        ? failRegionRead(previous)
        : readyRegion(result.runtime));
      setRuntimeRecoveryPending(result.runtime === null || result.failedStep !== null);
      if (result.failedStep) showToast(t('settings.models.errors.startFailed') as string, 'error');
    } finally {
      setStartingRuntime(false);
    }
  };
  const landingLoading = sourcesRead.kind === 'loading'
    && supplyRead.kind === 'loading'
    && runtimeRead.kind === 'loading';
  // A newer region observation (including a Source entity echo) does not settle
  // a retained M6 failure. Compose its Retry into the receiving view without
  // changing the actual read authority or discarding newly observed data.
  const sourcesDisplayRead = routeCommitStatus?.failed.has('sources')
    ? failRegionRead(sourcesRead)
    : sourcesRead;
  const supplyDisplayRead = routeCommitStatus?.failed.has('agents')
    ? failRegionRead(supplyRead)
    : supplyRead;
  const directEmpty = modelsSurfaceKindFromReads(supplyDisplayRead, sourcesDisplayRead) === 'direct_empty';
  const installedAgents = agents.filter(
    (agent) => !getBackendUiMeta(agent.backend).capabilities.supports_cli || agent.cli_present,
  );
  const installedNativeAgents = installedAgents.filter(
    (agent): agent is AgentSupply & { backend: NativeCliBackend } => isNativeCliBackend(agent.backend),
  );
  const hubBackends = agents.filter(agentUsesHubRuntime).map((agent) => agent.backend);
  const activeBackends = supplyRead.kind === 'ready' ? new Set(hubBackends) : undefined;
  const canRetryRuntime = runtimeRead.kind === 'ready'
    && !runtimeRunning
    && runtimeHealth !== 'installing'
    && retainedRuntime?.manifest.resolution !== 'unsupported';
  const installedSupplyRead = foldRegionRead<AgentSupply[], RegionRead<AgentSupply[]>>(supplyDisplayRead, {
    loading: () => loadingRegion(),
    ready: () => readyRegion(installedAgents),
    unread: (retryable) => unreadRegion(retryable),
    degraded: (_staleData, cause, retryable) => degradedRegion(installedAgents, cause, retryable),
  });
  type SourceDetailSelection = {
    sourceId: string;
    returnFocus: () => HTMLElement | null;
    serviceView?: boolean;
  };
  const applySourceDetailSelection = React.useCallback((selection: SourceDetailSelection | null) => {
    if (selection) sourceDetailReturnFocusRef.current = selection.returnFocus;
    setSelectedSourceId(selection?.sourceId ?? null);
    setServiceDetailView(selection?.serviceView ?? false);
  }, []);
  const selectSource = React.useCallback((selection: SourceDetailSelection | null) => {
    sourceIntentAuthority.commit(() => applySourceDetailSelection(selection));
  }, [applySourceDetailSelection, sourceIntentAuthority]);
  /**
   * A committed delete leaves the detail dialog with no entity to render, so the
   * page closes it and returns the user to the list. It goes through
   * `selectSource` rather than a panel-owned flag because selection is page
   * state, and the same commit supersedes any older continuation still holding
   * an intent to re-open this row.
   *
   * `sourceDetail.gone` stays for the case a close cannot cover: the source
   * disappeared out of band — removed from another surface, or found missing by
   * an edit or a refetch — with no delete of ours to close the dialog.
   *
   * The commit reports itself in one toast and the surface read runs behind it.
   * A post-commit modal would only repeat the impact the guard already made the
   * user confirm before the write, and it turned an ordinary superseded or
   * failed read into a second decision about a change that already landed. The
   * write is done; what a failed read owes the user is the page's own stale
   * projection and Retry, which every region already carries.
   */
  const presentSourceMutation = React.useCallback<PresentSourceMutationCommit>(async (commit) => {
    // Only a removal closes the dialog. An edit that found its Source absent
    // leaves it open on `sourceDetail.gone`, which is the same fact the toast
    // states — the page never announces an update that did not happen.
    if (commit.outcome === 'removed') selectSource(null);
    const toast = SOURCE_MUTATION_TOAST[commit.outcome];
    showToast(t(toast.key) as string, toast.tone);
    try {
      await commit.settle();
    } catch {
      // `refresh` already owns what a read can say: a failed projection keeps
      // its own stale treatment and Retry, and raises the page's refresh toast.
    }
  }, [selectSource, showToast, t]);
  const selectedSource = sources.find((source) => source.id === selectedSourceId)
    ?? (selectedSourceId === KEYLESS_EXA_SOURCE_ID
      ? { ...keylessExaSource(), display_name: t('settings.models.searchServices.vendorName.exa-mcp') as string }
      : null);
  // Read while the tab is open, or while a Source's detail shows its capability
  // chips, and again when that Source changes: an edit can change its identity,
  // which drops its evidence on the server.
  // The open Source's identity as evidence follows it (`retry.source_identity`).
  const selectedSourceIdentity = selectedSource
    ? JSON.stringify([
        selectedSource.id, selectedSource.kind, selectedSource.vendor, selectedSource.protocol, selectedSource.supply_channel,
        selectedSource.base_url ?? null, selectedSource.credential_ref ?? null, selectedSource.credential_generation ?? null,
      ])
    : null;
  const hostedTools = useHostedTools(runtimeConfigurationVisible && (tab === 'tools' || tab === 'sources' || selectedSource !== null), selectedSourceIdentity, tab);
  const hostedStatus = foldRegionRead(hostedTools.read, {
    loading: () => null, unread: () => null, ready: (data) => data, degraded: (data) => data,
  });
  const searchTool = webSearchTool(hostedStatus);
  const fetchTool = webFetchTool(hostedStatus);
  const openSearchServices = (opener: HTMLButtonElement) => {
    apiKeyTriggerRef.current = opener;
    setSearchServiceOpen(true);
  };
  const openSearchSource = (sourceId: string) => selectSource({
    sourceId,
    serviceView: true,
    // Source selection refreshes the Tools read and can remount its rows. Resolve
    // the live row at close, or the current tab while that read is still out.
    returnFocus: () => [...(pageRef.current?.querySelectorAll<HTMLButtonElement>('[data-search-source]') ?? [])]
      .find((button) => button.dataset.searchSource === sourceId)
      ?? pageRef.current?.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]') ?? null,
  });
  // A committed Source change (a model added, removed or refetched, or its
  // identity) can drop that Source's evidence on the server, so the
  // hosted-tools report follows it once the Sources settle.
  const presentSourceMutationAndTools = React.useCallback<PresentSourceMutationCommit>(async (commit) => {
    await presentSourceMutation(commit);
    void hostedTools.refresh();
  }, [presentSourceMutation, hostedTools.refresh]);
  const sourceDetailOpen = selectedSourceId !== null && subscriptionVendor === null;
  const orderAgent = agents.find((agent) => agent.backend === orderBackend && agent.mode === 'hub') ?? null;
  const menuAgent = agents.find((agent) => agent.backend === menuBackend && agent.mode === 'hub') ?? null;
  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.agent.backend, routeTarget.modelId)],
    available: supplyRead.kind !== 'ready' || currentRouteAgent !== null,
  } : null;
  // Focus moves to the route's destination only after the commit that closed the
  // dialog asking for it. A close that comes from an effect or a promise renders
  // later than a frame can fire, and a frame that fires first focuses into a dialog
  // still trapping focus, which then unmounts and drops focus on the body.
  const routeFocusRequestRef = React.useRef<{ target: RouteTarget; preserveCurrentFocus: boolean } | null>(null);
  const [routeFocusEpoch, setRouteFocusEpoch] = React.useState(0);
  const focusRouteDestination = React.useCallback((
    target: RouteTarget,
    preserveCurrentFocus = false,
  ) => {
    routeFocusRequestRef.current = { target, preserveCurrentFocus };
    setRouteFocusEpoch((epoch) => epoch + 1);
  }, []);
  React.useEffect(() => {
    const request = routeFocusRequestRef.current;
    if (!request) return;
    routeFocusRequestRef.current = null;
    const frame = requestAnimationFrame(() => {
      focusModelHubProjection({
        root: pageRef.current,
        activeTarget: request.target.opener,
        backend: request.target.agent.backend,
        modelId: request.target.modelId,
        preserveCurrentFocus: request.preserveCurrentFocus,
      });
    });
    // A newer request, or leaving the page, supersedes this one.
    return () => cancelAnimationFrame(frame);
  }, [routeFocusEpoch]);
  const refocusPendingRouteDestination = React.useCallback(() => {
    const report = routeCommitStatusRef.current?.report;
    if (!report || !pendingRouteOpenersRef.current.has(report)) return;
    const opener = pendingRouteOpenersRef.current.get(report) ?? null;
    requestAnimationFrame(() => {
      // Another commit can be inferred between installation and this frame.
      // Its focus identity wins, even while its collection reads are queued.
      const latestReport = routeCommitStatusRef.current?.report ?? report;
      const latestOpener = pendingRouteOpenersRef.current.has(latestReport)
        ? pendingRouteOpenersRef.current.get(latestReport) ?? null
        : latestReport === report ? opener : null;
      focusModelHubProjection({
        root: pageRef.current,
        activeTarget: latestOpener,
        backend: latestReport.chain.backend,
        modelId: latestReport.chain.model_id,
        preserveCurrentFocus: true,
      });
    });
  }, []);
  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));
        refocusPendingRouteDestination();
      },
    };
  }, [agentCollectionReads, refocusPendingRouteDestination]);
  const readRouteSources = React.useCallback(async (): Promise<RouteCollectionObservation<Source[]>> => {
    const snapshot = sourceEntityAuthority.beginSnapshot();
    const result = await sourceCollectionReads.read();
    if (result.kind === 'stale') throw new Error('route_sources_read_superseded');
    return {
      value: result.value,
      install: () => {
        sourceEntityAuthority.settleSnapshot(snapshot, result.value);
        refocusPendingRouteDestination();
      },
    };
  }, [refocusPendingRouteDestination, sourceCollectionReads, sourceEntityAuthority]);
  const routeProjectionReconciler = React.useMemo(() => createRouteProjectionReconciler({
    readAgents: readRouteAgents,
    readSources: readRouteSources,
    onFailure: (member) => {
      if (member === 'agents') setSupplyRead(failRegionRead);
      else setSourcesRead(failRegionRead);
    },
    onStatus: (status) => {
      // Every pending transition removes Retry admission, including an inferred
      // commit arriving while the user has focused an older failed read's Retry.
      if (status.pending && (
        document.activeElement === sourcesRetryRef.current
        || document.activeElement === supplyRetryRef.current
      )) {
        focusModelHubProjection({
          root: pageRef.current,
          activeTarget: pendingRouteOpenersRef.current.get(status.report) ?? null,
          backend: status.report.chain.backend,
          modelId: status.report.chain.model_id,
        });
      }
      routeCommitStatusRef.current = status;
      setRouteCommitStatus(status);
      if (!status.pending) {
        refocusPendingRouteDestination();
        if (status.failed.size === 0) {
          for (const report of status.reports) pendingRouteOpenersRef.current.delete(report);
        }
      }
    },
  }), [readRouteAgents, readRouteSources, refocusPendingRouteDestination]);
  React.useEffect(() => () => routeProjectionReconciler.invalidate(), [routeProjectionReconciler]);
  const routeCommitted = React.useCallback((
    result: RouteReport,
    opener: HTMLElement | null,
  ) => {
    pendingRouteOpenersRef.current.set(result, opener);
    chainReadAuthority.invalidate([modelChainKey(result.chain.backend, result.chain.model_id)]);
    routeObserved(result.chain);
    setSuspendedRouteAttempts((attempts) =>
      releaseSuspendedRouteAttempt(attempts, result.chain.backend),
    );
    suspendedHubFrontiersRef.current.delete(result.chain.backend);
    suspendedSourceBaselinesRef.current.delete(result.chain.backend);
    suspendedChainBaselinesRef.current.delete(result.chain.backend);
    routeProjectionReconciler.start(result);
    showToast(t('common.saved'), 'success');
  }, [chainReadAuthority, routeObserved, routeProjectionReconciler, showToast, t]);
  const retryRouteCommit = React.useCallback(() => {
    const status = routeCommitStatusRef.current;
    if (status?.pending || !status?.failed.size) return;
    routeProjectionReconciler.retry();
  }, [routeProjectionReconciler]);
  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(
            [modelChainKey(held.backend, held.modelId)],
            () => readExactAgentChain(freshAgent, held.modelId),
          );
          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 },
          suspendedRouteOpenersRef.current.get(held) ?? null,
        );
      }
    }
  }, [chainsRead, routeCommitted, suspendedRouteAttempts]);
  const supplyRelations = React.useMemo(() => buildSupplyRelations(installedAgents, sources, chains, runtime), [chains, installedAgents, runtime, sources]);
  /** The Sources this page has read, by id — for the surfaces that show a hop and
   *  have to name whose it is. Only what was read: an id no Source answers for is
   *  left unnamed rather than rendered raw. */
  const sourceNames = React.useMemo(
    () => Object.fromEntries(sources.map((source) => [source.id, source.display_name])),
    [sources],
  );
  const takeoverCount = React.useMemo(() => new Set(
    supplyRelations.filter(({ kind }) => kind === 'takeover').map(({ backend }) => backend),
  ).size, [supplyRelations]);
  const sourceAdded = async (created: SourceCreated) => {
    await convergeMutation({
      entity: created,
      applyEntity: (answer) => {
        sourceEntityAuthority.landLatest(answer.source);
      },
      intent: {
        authority: sourceIntentAuthority,
        apply: () => {
          setApiKeyOpen(false);
          setSearchServiceOpen(false);
          applySourceDetailSelection({
            sourceId: created.source.id,
            serviceView: searchServiceOpen,
            returnFocus: () => apiKeyTriggerRef.current,
          });
        },
      },
      reconcile: refresh,
    });
  };
  const subscriptionAdded = React.useCallback((source?: Source) => {
    if (!source) {
      if (subscriptionSuccessReconcileRef.current) {
        subscriptionSuccessReconcileRef.current = false;
        return;
      }
      void refresh();
      return;
    }
    // The toast already said it connected, so the sign-in dialog hands straight
    // over to the provider it created, which then owns its normal autofocus.
    sourceEntityAuthority.landLatest(source);
    selectSource({
      sourceId: source.id,
      returnFocus: () => subscriptionTriggerRef.current,
    });
    subscriptionSuccessReconcileRef.current = true;
    void refresh();
    setSubscriptionVendor(null);
  }, [refresh, selectSource, sourceEntityAuthority]);
  const closeSubscription = React.useCallback(() => {
    setSubscriptionVendor(null);
    window.setTimeout(() => subscriptionTriggerRef.current?.focus(), 0);
  }, []);
  /**
   * A re-login's whole obligation to this page: re-read everything.
   *
   * Not `subscriptionAdded`, even though the reauth journey also calls back with
   * no source. That callback's no-source branch can be CONSUMED by the create
   * path's success flag, and a reauth has no success landing to coalesce with —
   * it terminates on the row it started from. And the read has to be the wide
   * one: `_materialize_reauth` can leave other agents without a source, so
   * `/agents` and the chains behind it are stale too, not just this row.
   */
  const sourceReauthed = React.useCallback(() => {
    void refresh();
    // The Source now holds a new grant; the open quota tab re-reads for it
    // instead of showing the expired one until the next tick.
    if (tab === 'quota') void readQuota(false);
  }, [readQuota, refresh, tab]);
  const closeReauth = React.useCallback(() => {
    setReauthSource(null);
    // Back to the detail heading rather than to the button that opened this: a
    // repair that worked unmounts that button (the row is no longer stopped), and
    // Radix would restore focus to a node that is gone — i.e. to <body>. From a
    // quota card, back to its button, or to the quota tab once it is gone.
    const opener = quotaReauthOpenerRef.current;
    quotaReauthOpenerRef.current = null;
    quotaFocusHoldRef.current = opener;
    window.setTimeout(() => (opener ? focusQuotaOpener(opener) : sourceDetailHeadingRef.current?.focus()), 0);
  }, []);
  const closeSubscriptionPicker = React.useCallback(() => {
    subscriptionPickerHandoffRef.current = false;
    setSubscriptionPickerOpen(false);
  }, []);
  const focusSubscriptionPickerOption = React.useCallback((index: number) => {
    const bounded = Math.max(0, Math.min(index, SUBSCRIPTION_PICKER_OPTIONS.length - 1));
    setSubscriptionPickerIndex(bounded);
    const { vendor } = SUBSCRIPTION_PICKER_OPTIONS[bounded];
    subscriptionPickerRefs.current[vendor]?.focus();
  }, []);
  const openSubscriptionPicker = React.useCallback(() => {
    subscriptionPickerHandoffRef.current = false;
    setSubscriptionPickerIndex(0);
    setSubscriptionPickerOpen(true);
  }, []);
  const toggleSubscriptionPicker = React.useCallback(() => {
    if (subscriptionPickerOpen) closeSubscriptionPicker();
    else openSubscriptionPicker();
  }, [closeSubscriptionPicker, openSubscriptionPicker, subscriptionPickerOpen]);

  return (
    <ModelHubShell
      rootRef={pageRef}
      status={!landingLoading && <RuntimePill read={runtimeRead} starting={startingRuntime} directCount={directEmpty ? installedNativeAgents.length : undefined} />}
      actions={!landingLoading && runtimeConfigurationVisible
        ? <div className="model-hub-shell-actions">
              {runtimeConfigurationVisible && migrationAvailable === true && (
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  className="h-8 gap-1.5 rounded-lg px-2.5 text-[11px] font-semibold"
                  onClick={() => setMigrationOpen(true)}
                >
                  <ArrowDownToLine className="size-3.5" aria-hidden="true" />
                  {t('settings.models.migration.open')}
                </Button>
              )}
              {runtimeConfigurationVisible && !directEmpty && <TakeoverPill count={takeoverCount} />}
              {runtimeConfigurationVisible && <Button
                type="button"
                variant="ghost"
                size="icon"
                className="size-8"
                disabled={presenceRefreshing}
                aria-label={t('settings.models.direct.action.refreshAgents')}
                title={t('settings.models.direct.action.refreshAgents')}
                onClick={() => { setMigrationScanEpoch((epoch) => epoch + 1); void retrySupply(); }}
              ><RefreshCw aria-hidden className={cn('size-3.5', presenceRefreshing && 'animate-spin')} /></Button>}
              {canRetryRuntime && <Button variant="secondary" size="sm" disabled={startingRuntime} onClick={() => void startRuntime()}>{t('settings.models.gateway.retry')}</Button>}
            </div>
        : undefined}
    >
      {landingLoading ? <div className="text-[13px] text-muted">{t('common.loading')}</div>
        : !runtimeConfigurationVisible
          ? <RuntimeClosedState read={runtimeRead} runtime={retainedRuntime} starting={startingRuntime} onRetry={canRetryRuntime ? () => void startRuntime() : undefined} />
          : <div className="space-y-[22px]">
                  {/* The tab strip belongs to the Hub, not to the source
                      inventory. Usage and switch history both outlive the Sources
                      they name, so deleting the last Source may not remove the only
                      route to either record. The direct-only body of `sources` is
                      DirectHome (ui/design: models/page/direct). */}
                  <HubTabs tab={tab} onChange={setTab} />
                  {tab === 'quota' ? <QuotaTab
                      quota={quotaRead}
                      refreshing={refreshingQuota}
                      onRefresh={refreshQuotaNow}
                      onRetry={retryQuota}
                      onRequestReauth={(sourceId) => {
                        const target = sources.find((source) => source.id === sourceId);
                        if (target && canReauth(target)) {
                          quotaReauthOpenerRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
                          setQuotaReauthSource(target);
                          return;
                        }
                        // Not a Source this page can sign in again: show it instead.
                        const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;
                        selectSource({ sourceId, returnFocus: () => opener });
                      }}
                    />
                    : tab === 'tools' ? <ToolsTab read={hostedTools.read} sources={sources} pending={hostedTools.pending} onSave={(tool, body) => void hostedTools.save(tool, body)} onClear={(tool, body) => void hostedTools.clear(tool, body)} onRetry={() => void hostedTools.refresh()} onAddService={openSearchServices} onOpenService={openSearchSource} onRetryService={(sourceId) => void hostedTools.retryService(sourceId)} onRetryFetch={(sourceId) => void hostedTools.retryFetch(sourceId)} />
                    : tab === 'usage' ? <UsageTab usage={usageRead} windowKey={usageWindow} onWindowChange={setUsageWindow} onRetry={retryUsage} />
                    : tab === 'logs' ? <RecentSwitchesCard events={eventsRead} sources={sourcesRead} onRetry={retryEvents} loadingMore={loadingEvents} onLoadMore={loadOlderEvents} />
                    : directEmpty ? <DirectHome agents={installedNativeAgents} switchFailures={switchFailures} connectingBackend={adoptAgent?.backend ?? null} onSwitch={switchToGateway} />
                    : <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">
                        <Popover
                          open={subscriptionPickerOpen}
                          onOpenChange={(open) => { if (!open) closeSubscriptionPicker(); }}
                        >
                          <PopoverAnchor virtualRef={subscriptionAnchorRef} />
                          <SourcesCard read={sourcesDisplayRead} searchTool={searchTool} onAddSearchService={openSearchServices} activeBackends={activeBackends} retryRef={sourcesRetryRef} retryDisabled={routeCommitStatus?.pending === true} readFailureCopy={routeCommitStatus?.failed.has('sources') ? t('settings.models.routeDialog.impact.refreshFail') : undefined} onRetry={() => routeCommitStatus?.failed.has('sources') ? retryRouteCommit() : void retrySources()} onOpenSource={(source, opener) => selectSource({ sourceId: source.id, returnFocus: () => opener })} onAddApiKey={(opener) => { apiKeyTriggerRef.current = opener; setApiKeyOpen(true); }} onAddSubscription={toggleSubscriptionPicker} subscriptionPickerOpen={subscriptionPickerOpen} subscriptionTriggerRef={subscriptionTriggerRef} />
                          <PopoverContent
                            role="menu"
                            aria-label={t('settings.models.upstream.addSubscription')}
                            align="start"
                            sideOffset={8}
                            collisionPadding={12}
                            className="flex w-[300px] max-w-[calc(100vw-24px)] flex-col gap-0.5 rounded-[10px] border-border-strong bg-surface p-1.5 text-foreground !shadow-[var(--model-hub-menu-shadow)]"
                            onOpenAutoFocus={(event) => {
                              event.preventDefault();
                              window.requestAnimationFrame(() => {
                                const { vendor } = SUBSCRIPTION_PICKER_OPTIONS[subscriptionPickerIndex];
                                subscriptionPickerRefs.current[vendor]?.focus();
                              });
                            }}
                            onCloseAutoFocus={(event) => {
                              event.preventDefault();
                              if (subscriptionPickerHandoffRef.current) {
                                subscriptionPickerHandoffRef.current = false;
                                return;
                              }
                              window.setTimeout(() => subscriptionTriggerRef.current?.focus(), 0);
                            }}
                            onInteractOutside={(event) => {
                              if (subscriptionTriggerRef.current?.contains(event.target as Node)) event.preventDefault();
                            }}
                            onKeyDown={(event) => {
                              if (event.key === 'ArrowDown' || event.key === 'ArrowRight') {
                                event.preventDefault();
                                focusSubscriptionPickerOption(subscriptionPickerIndex + 1);
                              } else if (event.key === 'ArrowUp' || event.key === 'ArrowLeft') {
                                event.preventDefault();
                                focusSubscriptionPickerOption(subscriptionPickerIndex - 1);
                              } else if (event.key === 'Home') {
                                event.preventDefault();
                                focusSubscriptionPickerOption(0);
                              } else if (event.key === 'End') {
                                event.preventDefault();
                                focusSubscriptionPickerOption(SUBSCRIPTION_PICKER_OPTIONS.length - 1);
                              }
                            }}
                          >
                            {SUBSCRIPTION_PICKER_OPTIONS.map(({ vendor, recommendation }, index) => {
                              const vendorLabel = t(`settings.models.subscriptionPicker.vendor.${vendor}`);
                              // A hub-only vendor has no native channel to recommend against, so
                              // it carries no badge rather than a 网关推荐 over its only custody.
                              const recommendationLabel = recommendation
                                ? t(`settings.models.subscriptionPicker.recommendation.${recommendation}`)
                                : null;
                              return (
                                <Button
                                  key={vendor}
                                  ref={(node) => { subscriptionPickerRefs.current[vendor] = node; }}
                                  type="button"
                                  role="menuitem"
                                  variant="ghost"
                                  className={cn(
                                    'model-hub-subscription-menu-row h-auto w-full min-w-0 justify-start gap-2 rounded-[7px] px-2.5 py-[9px] text-left focus-visible:ring-0 focus-visible:ring-offset-0',
                                    subscriptionPickerIndex === index &&
                                      'model-hub-subscription-menu-row--active',
                                  )}
                                  tabIndex={subscriptionPickerIndex === index ? 0 : -1}
                                  onClick={() => {
                                    subscriptionPickerHandoffRef.current = true;
                                    setSubscriptionPickerOpen(false);
                                    setSubscriptionVendor(vendor);
                                  }}
                                >
                                  <VendorGlyph vendor={vendor} />
                                  <span className="min-w-0 flex-1 truncate text-[12.5px] font-semibold" title={vendorLabel}>{vendorLabel}</span>
                                  {recommendationLabel && (
                                    <Badge
                                      variant="recommendation"
                                      className={cn(
                                        recommendation === 'native'
                                          ? 'model-hub-accent-tile--mint model-hub-accent-ink--mint border-transparent'
                                          : 'model-hub-accent-pill--neutral',
                                      )}
                                    >
                                      {recommendationLabel}
                                    </Badge>
                                  )}
                                </Button>
                              );
                            })}
                          </PopoverContent>
                        </Popover>
                        <div className="hidden xl:block" aria-hidden="true" />
                        <GatewayModule supply={installedSupplyRead} retryRef={supplyRetryRef} retryDisabled={routeCommitStatus?.pending === true} readFailureCopy={routeCommitStatus?.failed.has('agents') ? t('settings.models.routeDialog.impact.refreshFail') : undefined} sources={sources} chains={chains} runtime={runtime} runtimeSnapshot={retainedRuntime} onRetry={() => routeCommitStatus?.failed.has('agents') ? retryRouteCommit() : void retrySupply()} pendingBackends={agentWrites} switchFailures={switchFailures} connectingBackend={adoptAgent?.backend ?? null} onConnectHub={switchToGateway} onSwitchDirect={switchToDirect} onOpenModels={(agent) => { catalogOriginRef.current = null; setCatalogFocus(null); setMenuBackend(agent.backend); }} onOpenOrder={(agent) => setOrderBackend(agent.backend)} onOpenRoute={(agent, modelId, opener) => setRouteTarget({ agent, modelId, opener })} onProbeSettled={(agent) => void refreshAgentChains(agent)} onOpenAgent={openAgentDefinition} />
                        <SupplyGraph containerRef={overviewRef} relations={supplyRelations} />
                      </div>
                      <SupplyLegend relations={supplyRelations} />
                    </div>
                  </div>}
                </div>}
      {runtimeConfigurationVisible && <>
      <Dialog open={sourceDetailOpen} onOpenChange={(open) => { if (!open) selectSource(null); }}>
        <DialogContent
          mobileSheetHeight="tall"
          closeLabel={t('settings.models.sourceDetail.close') as string}
          className="model-hub-source-dialog flex h-[min(624px,calc(100dvh-32px))] w-[min(720px,calc(100vw-32px))] max-w-[720px] flex-col gap-0 overflow-hidden rounded-[14px] border-border-strong bg-surface p-0 shadow-[var(--model-hub-dialog-shadow)] max-md:w-full max-md:max-w-none max-md:rounded-t-2xl"
          onOpenAutoFocus={(event) => {
            event.preventDefault();
            sourceDetailHeadingRef.current?.focus();
          }}
          onCloseAutoFocus={(event) => {
            const returnFocus = sourceDetailReturnFocusRef.current;
            sourceDetailReturnFocusRef.current = null;
            // A removal deletes the row that opened this dialog, so the return
            // target is already disconnected. The overview is the nearest
            // neighbourhood to fall back into — except when the removal took the
            // last Source with it, which unmounts the overview too and leaves the
            // shell as the smallest surface still standing. Either beats
            // `document.body`, where the next Tab restarts at the top of the page.
            if (focusDialogReturn({
              root: overviewRef.current ?? pageRef.current,
              returnTarget: returnFocus?.() ?? null,
            })) {
              event.preventDefault();
            }
          }}
          onEscapeKeyDown={(event) => {
            // Radix observes Escape before React's row handlers; marked editors own it locally.
            if (event.target instanceof Element && event.target.closest('[data-source-dialog-local-escape]')) {
              event.preventDefault();
            }
          }}
        >
          <DialogTitle className="sr-only">{selectedSource?.display_name ?? t('settings.models.sourceDetail.gone')}</DialogTitle>
          <DialogDescription className="sr-only">{t('settings.models.sourceDetail.footnote')}</DialogDescription>
          {selectedSource
            ? <SourceDetailPanel
                key={selectedSource.id}
                source={selectedSource}
                serviceView={serviceDetailView}
                onManageSource={() => setServiceDetailView(false)}
                onOpenUsage={() => { selectSource(null); setTab('usage'); }}
                onSaveFetch={(body) => void hostedTools.save('web_fetch', body)}
                onRetryFetch={(sourceId) => void hostedTools.retryFetch(sourceId)}
                onSaveSearch={(body) => void hostedTools.save('web_search', body)}
                onRetryService={(sourceId) => void hostedTools.retryService(sourceId)}
                hostedTools={hostedTools.read}
                onRetryHostedTools={() => void hostedTools.refresh()}
                hostedPending={hostedTools.pending}
                // A chip clears its own (Source, model); the answer is the hosted-tools read, which owns that evidence.
                onClearHostedRefusal={(tool, modelId) => void hostedTools.clear(tool, { source_id: selectedSource.id, model_id: modelId })}
                activeBackends={activeBackends}
                headingRef={sourceDetailHeadingRef}
                trackMutation={trackSourceMutation(selectedSource.id)}
                onReauth={setReauthSource}
                onMutationCommitted={presentSourceMutationAndTools}
              />
            : <section className="grid min-h-0 flex-1 place-items-center px-5 py-12 text-center text-[12px] text-muted">{t('settings.models.sourceDetail.gone')}</section>}
        </DialogContent>
      </Dialog>
      {searchServiceOpen && searchServicesActive(searchTool) && searchTool && <AddSearchServiceDialog tool={searchTool} fetchTool={fetchTool} pending={hostedTools.pending.has('web_search')} sourceReads={sourceCollectionReads} onClose={() => setSearchServiceOpen(false)} onAdded={(created) => void sourceAdded(created)} onViewOrder={() => { setSearchServiceOpen(false); setTab('tools'); }} onOpenSource={(sourceId) => {
        setSearchServiceOpen(false);
        selectSource({ sourceId, returnFocus: () => apiKeyTriggerRef.current, serviceView: true });
      }} />}
      <AddApiKeyDialog open={apiKeyOpen} sourceReads={sourceCollectionReads} onClose={() => setApiKeyOpen(false)} onAdded={(created) => void sourceAdded(created)} />
      {subscriptionVendor && (
        <OAuthConnectDialog
          open
          vendor={subscriptionVendor}
          sources={sources}
          onClose={closeSubscription}
          onConnected={subscriptionAdded}
        />
      )}
      {quotaReauthSource && (
        <ConfirmDialog
          open
          onOpenChange={(open) => {
            if (open) return;
            setQuotaReauthSource(null);
            const opener = quotaReauthOpenerRef.current;
            quotaReauthOpenerRef.current = null;
            if (opener) window.setTimeout(() => focusQuotaOpener(opener), 0);
          }}
          title={t('settings.models.repair.reauthTitle', { name: quotaReauthSource.display_name })}
          description={t(reauthBodyKey(quotaReauthSource))}
          confirmLabel={t('settings.models.repair.reauthConfirm') as string}
          destructive={reauthCost(quotaReauthSource) === 'immediate'}
          onConfirm={() => {
            const target = quotaReauthSource;
            setQuotaReauthSource(null);
            setReauthSource(target);
          }}
        />
      )}
      {reauthSource && (
        <OAuthConnectDialog
          open
          vendor={reauthSource.vendor}
          reauth={reauthSource}
          sources={sources}
          onClose={closeReauth}
          onConnected={sourceReauthed}
        />
      )}
      {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) }} />}
      {menuAgent && <BackendModelCatalogDialog open backend={menuAgent.backend} canReadSources={capabilities.can_manage_agents} sourceNames={sourceNames} focus={catalogFocus} onClose={(result) => {
        setMenuBackend(null);
        setCatalogFocus(null);
        const origin = catalogOriginRef.current;
        catalogOriginRef.current = null;
        if (!origin) return;
        // The route dialog handed its model over and comes back once the
        // catalog answers, unless the answer removed the model it was showing.
        if (result?.removed) focusRouteDestination(origin);
        else setRouteTarget(origin);
      }} onSaved={catalogSaved} onObserved={applyAgentEcho} catalogWrite={{ pending: agentWrites.has(menuAgent.backend), track: (work) => agentWriteRegistry.track(menuAgent.backend, work) }} />}
      <RouteChainDialog
        selection={routeSelection}
        covered={orderBackend !== null}
        onOpenDefaults={() => { if (routeTarget) setOrderBackend(routeTarget.agent.backend); }}
        sources={sources}
        onClose={() => {
          const target = routeTarget;
          setRouteTarget(null);
          if (target) focusRouteDestination(target);
        }}
        onManageModel={(action) => {
          // The catalog dialog is the one writer of the model list; the route
          // dialog steps aside while it edits or removes the model it was
          // showing, then reopens on that model.
          if (!routeTarget) return;
          catalogOriginRef.current = routeTarget;
          setRouteTarget(null);
          setCatalogFocus({ modelId: routeTarget.modelId, action });
          setMenuBackend(routeTarget.agent.backend);
        }}
        onCommitted={(result) => routeCommitted(result, routeTarget?.opener ?? null)}
        onObserved={routeObserved}
        readAgents={readRouteAgents}
        readSources={readRouteSources}
        onDirectMode={(attempt, observedAgent) => {
          const landingBackend = attempt?.backend ?? routeTarget?.agent.backend;
          if (landingBackend) {
            if (attempt && routeTarget) {
              suspendedRouteOpenersRef.current.set(attempt, routeTarget.opener);
            }
            suspendedSourceBaselinesRef.current.set(landingBackend, sourcesRead);
            setSuspendedRouteAttempts((attempts) =>
              attempt
                ? 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);
            }
          })();
        }}
      />
      </>}
      {migrationOpen && (
        <MigrationDialog
          open
          eligible={migrationBackend
            ? (item) => item.backend === migrationBackend
            : undefined}
          onDecline={migrationBackend ? () => declineMigration(migrationBackend) : undefined}
          onClose={() => {
            setMigrationOpen(false);
            setMigrationBackend(null);
          }}
          onApplied={() => {
            setMigrationOpen(false);
            setMigrationBackend(null);
            void refresh();
            void refreshAgentPresence();
          }}
        />
      )}
    </ModelHubShell>
  );
};

export default SettingsModelsPage;