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.

55.1 KB
Raw Blame
import type { TranslationKey } from '@/i18n/types';
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import {
  ChevronRight,
  GripVertical,
  ListOrdered,
  LoaderCircle,
  MoreHorizontal,
  Pencil,
  Plus,
  RefreshCw,
  Trash2,
  Undo2,
  X,
} from "lucide-react";
import { useTranslation } from "react-i18next";

import { Button } from "@/components/ui/button";
import { Select } from "@/components/ui/select";
import { ResponsiveMenu } from "@/components/ui/responsive-menu";
import { SegmentedRadio } from "@/components/ui/segmented";
import { cn } from "@/lib/utils";
import { getBackendUiMeta } from "@/lib/agentBackends";
import { useIsMobile } from "@/lib/useIsMobile";
import { GuardDialog } from "./GuardDialog";
import { Field } from "./dialogFields";
import { GuardImpact, type GuardPlan } from "./GuardImpact";
import { confirmGuardPlan, sendAgreed, unansweredRefusal } from "./guardedWrite";
import { RouteCandidatePopover } from "./RouteCandidatePopover";
import { RecordedTurnBadge, RecordedTurnDetails, RouteRecordedTurn } from './RouteRecordedTurn';
import { recordedOn, useRecordedTurn } from './recordedTurn';
import { eligibleSources } from "./eligibility";
import { equalHopIdentity, hopBelongsToSource } from "./hopIdentity";
import { apiFailure, modelsApi } from "./modelsApi";
import type { ModelChainRead } from "./modelRows";
import {
  routeCandidates,
  sameManualOverride,
  sameRouteDraft,
  validateRouteDraft,
  type RouteCandidate,
} from "./routeChainDraft";
import {
  advanceRouteChainInteraction,
  createRouteChainInteraction,
  type RouteChainInteractionAction,
} from "./routeChainInteraction";
import type {
  AgentChainMutation,
  AgentSupply,
  RouteHop,
  RouteHopRef,
  Source,
  ManualRouteOverride,
  AgentChain,
  CacheTtl,
} from "./types";

const sourceName = (sources: Source[], sourceId: string): string =>
  sources.find((source) => source.id === sourceId)?.display_name ?? sourceId;
const MENU_ITEM = "model-hub-route-menu-item flex w-full items-center rounded-md text-left font-semibold hover:bg-surface-2";
type RouteMode = "follow" | "custom";

export type RouteReport = {
  chain: AgentChainMutation["chain"];
  removed_hops: RouteHopRef[] | null;
  interrupted: AgentChainMutation["interrupted"] | null;
};
type Phase =
  | "loading"
  | "ready"
  | "unread"
  | "saving"
  | "rejected"
  | "unknown"
  | "reconciling"
  | "direct";
type ReconcileMember = "agents" | "sources" | "chain";
type UnknownObservation = "none" | "nonmatching" | "read_failed";

export type RouteChainSelection = {
  agent: AgentSupply;
  modelId: string;
  read: ModelChainRead | undefined;
  available?: boolean;
};
export type RouteCollectionObservation<T> = {
  value: T;
  install: () => void;
};
export type SuspendedRouteAttempt = {
  backend: AgentSupply["backend"];
  modelId: string;
  stage: "initial" | "confirmed";
  submitted: RouteHop[];
  manual_override: ManualRouteOverride | null;
};

export const RouteChainDialog: React.FC<{
  selection: RouteChainSelection | null;
  sources: Source[];
  onClose: () => void;
  onCommitted?: (result: RouteReport) => void;
  onObserved?: (chain: AgentChainMutation["chain"]) => void;
  onOpenDefaults?: () => void;
  covered?: boolean;
  readAgents: () => Promise<RouteCollectionObservation<AgentSupply[]>>;
  readSources: () => Promise<RouteCollectionObservation<Source[]>>;
  onDirectMode?: (
    attempt: SuspendedRouteAttempt | null,
    observedAgent: AgentSupply | null,
  ) => void;
  /** Hand this model over to the catalog dialog, which is the one writer of the
   *  model list — the Route dialog only names the model and the intent, so the
   *  edit and removal protocols (guard, refusal, save) stay in one place. */
  onManageModel?: (action: "edit" | "remove") => void;
}> = ({
  selection,
  sources,
  onClose,
  onCommitted,
  onObserved,
  onOpenDefaults,
  covered = false,
  readAgents,
  readSources,
  onDirectMode,
  onManageModel,
}) => {
  const { t } = useTranslation();
  const [phase, setPhase] = React.useState<Phase>("loading");
  const [origin, setOrigin] = React.useState<RouteHop[]>([]);
  const [savedOverride, setSavedOverride] = React.useState<ManualRouteOverride | null>(null);
  const [cacheTtlDraft, setCacheTtlDraft] = React.useState<CacheTtl | null>(null);
  // This is draft routing intent, not whether the rows can be edited.
  const [manualDraft, setManualDraft] = React.useState(false);
  const [preview, setPreview] = React.useState<AgentChain | null>(null);
  const [previewPending, setPreviewPending] = React.useState(false);
  const [previewFailed, setPreviewFailed] = React.useState(false);
  const [saveErrorCode, setSaveErrorCode] = React.useState<string | null>(null);
  const previewGeneration = React.useRef(0);
  const restoreUndo = React.useRef<{ hops: RouteHop[]; manual: boolean; cacheTtl: CacheTtl | null } | null>(null);
  const grabIntent = React.useRef<{
    manual: boolean;
    cacheTtl: CacheTtl | null;
    preview: AgentChain | null;
    undo: { hops: RouteHop[]; manual: boolean; cacheTtl: CacheTtl | null } | null;
  } | null>(null);
  const submittedOverride = React.useRef<ManualRouteOverride | null>(null);
  const interactionRef = React.useRef(createRouteChainInteraction());
  const [interaction, setInteraction] = React.useState(interactionRef.current);
  const [chain, setChain] = React.useState<AgentChainMutation["chain"] | null>(
    null,
  );
  const [guard, setGuard] = React.useState<GuardPlan | null>(null);
  const [submitted, setSubmitted] = React.useState<RouteHop[] | null>(null);
  const [submittedStage, setSubmittedStage] =
    React.useState<SuspendedRouteAttempt["stage"]>("initial");
  const [reconcileFailed, setReconcileFailed] = React.useState(false);
  const [failedMembers, setFailedMembers] = React.useState<
    ReadonlySet<ReconcileMember>
  >(() => new Set());
  const [unknownObservation, setUnknownObservation] =
    React.useState<UnknownObservation>("none");
  const [unknownSourceCurrent, setUnknownSourceCurrent] = React.useState(false);
  const [selectorEpoch, setSelectorEpoch] = React.useState(0);
  const [announcement, setAnnouncement] = React.useState<{
    key: TranslationKey;
    params?: Record<string, unknown>;
  } | null>(null);
  const gripRefs = React.useRef<Array<HTMLButtonElement | null>>([]);
  const editRefs = React.useRef<Array<HTMLButtonElement | null>>([]);
  const removeRefs = React.useRef<Array<HTMLButtonElement | null>>([]);
  const addButtonRef = React.useRef<HTMLButtonElement | null>(null);
  const modeRef = React.useRef<HTMLDivElement | null>(null);
  const pendingUndoRef = React.useRef<HTMLButtonElement | null>(null);
  const cancelButtonRef = React.useRef<HTMLButtonElement | null>(null);
  const closeButtonRef = React.useRef<HTMLButtonElement | null>(null);
  const isMobile = useIsMobile();
  const [headMenu, setHeadMenu] = React.useState(false);
  const [hopMenu, setHopMenu] = React.useState<number | null>(null);
  const [replacing, setReplacing] = React.useState<number | null>(null);
  const [recordDetails, setRecordDetails] = React.useState(false);
  const saveButtonRef = React.useRef<HTMLButtonElement | null>(null);
  const savingStatusRef = React.useRef<HTMLSpanElement | null>(null);
  const retryButtonRef = React.useRef<HTMLButtonElement | null>(null);
  const openedIdentity = React.useRef<string | null>(null);
  const invalidSignature = React.useRef("");
  const generation = React.useRef(0);
  React.useEffect(() => () => { generation.current += 1; previewGeneration.current += 1; }, []);

  const agent = selection?.agent ?? null;
  const modelId = selection?.modelId ?? "";
  const selectionBackend = selection?.agent.backend;
  const recordedTurn = useRecordedTurn(selectionBackend, modelId);
  // Only an editable catalog row can be handed over: a locked row (Claude Code's
  // `Default`) offers no actions in the catalog either, and a server that
  // predates backend catalogs sends no list to answer from.
  const catalogRow = agent?.catalog_models?.find((model) => model.id === modelId) ?? null;
  const draft = interaction.draft;
  const rovingIndex = interaction.focusIndex;
  const grabbed = interaction.grab?.index ?? null;
  const advanceInteraction = React.useCallback(
    (action: RouteChainInteractionAction) => {
      const previous = interactionRef.current;
      const next = advanceRouteChainInteraction(previous, action);
      if (action.type === "begin-grab") {
        grabIntent.current = { manual: manualDraft, cacheTtl: cacheTtlDraft, preview, undo: restoreUndo.current };
      }
      if (action.type === "cancel-grab" && previous.grab && grabIntent.current) {
        setManualDraft(grabIntent.current.manual);
        setCacheTtlDraft(grabIntent.current.cacheTtl);
        setPreview(grabIntent.current.preview);
        restoreUndo.current = grabIntent.current.undo;
      } else if (action.type !== "reset" && !sameRouteDraft(previous.draft, next.draft)) {
        // Focusing or opening a picker is not a request to pin inherited routing.
        setManualDraft(true);
        previewGeneration.current += 1;
        restoreUndo.current = null;
        setPreview(null);
        setPreviewPending(false);
        setPreviewFailed(false);
      }
      if (!next.grab) grabIntent.current = null;
      interactionRef.current = next;
      setInteraction(next);
      return next;
    },
    [cacheTtlDraft, manualDraft, preview],
  );
  const addCandidates = agent ? routeCandidates(agent, sources, draft) : [];
  const targetSources = agent ? eligibleSources(sources, agent) : [];
  const canEditRoute = draft.length > 0 || addCandidates.length > 0
    || targetSources.some((source) => source.kind === 'api_key' && source.protocol !== 'search');
  const backend = agent ? getBackendUiMeta(agent.backend).label : "";
  const valid = agent
    ? validateRouteDraft(agent, sources, origin, draft)
    : { invalidIndexes: [], valid: false };
  const restoring = restoreUndo.current !== null;
  const unresolvedPreview = restoring && preview === null;
  const dirty = manualDraft
    ? savedOverride === null || !sameManualOverride(savedOverride, { hops: draft, cache_ttl: cacheTtlDraft })
    : savedOverride !== null;
  const canDiscardDraft = (phase === "ready" || phase === "rejected") && (dirty || restoring);
  // A handoff leaves this dialog, so it is offered only on a settled, unedited
  // route: mid-write phases own an exchange the user must finish, and an unsaved
  // draft would be discarded without asking.
  const manageableModel = Boolean(
    onManageModel && catalogRow && !catalogRow.locked && phase === "ready" && !dirty && !restoring,
  );
  // A switch that saving would apply: back to defaults over a saved route, or
  // onto a route of this model's own over inherited routing.
  const pendingSwitch: "restore" | "pin" | null = !manualDraft && savedOverride !== null
    ? "restore"
    : manualDraft && savedOverride === null
      ? "pin"
      : null;
  const announce = (key: TranslationKey, params?: Record<string, unknown>) =>
    setAnnouncement({ key, params });
  const focusAfterRender = (ref: React.RefObject<HTMLElement | null>) => {
    requestAnimationFrame(() => ref.current?.focus());
  };
  // The footer's dismiss control is live only while there is a draft to
  // discard; otherwise the header close is the dialog's single way out, so
  // every "return focus to the way out" path resolves through here.
  const focusDismiss = () => {
    const cancel = cancelButtonRef.current;
    (cancel && !cancel.disabled ? cancel : closeButtonRef.current)?.focus();
  };
  const focusMode = () =>
    requestAnimationFrame(() =>
      modeRef.current?.querySelector<HTMLButtonElement>('[aria-checked="true"]')?.focus(),
    );
  // A restore preview disables the mode switch while it reads, so focus waits
  // on its Undo instead; a local revert leaves the switch live.
  const focusAfterFollow = () =>
    requestAnimationFrame(() => {
      const undo = pendingUndoRef.current;
      if (undo && !undo.disabled) undo.focus();
      else modeRef.current?.querySelector<HTMLButtonElement>('[aria-checked="true"]')?.focus();
    });

  const readChain = React.useCallback(async () => {
    if (!selectionBackend) return;
    const token = ++generation.current;
    previewGeneration.current += 1;
    restoreUndo.current = null;
    setPreview(null);
    setPreviewPending(false);
    setPreviewFailed(false);
    setPhase("loading");
    try {
      const next = await modelsApi.getAgentChain(selectionBackend, modelId);
      if (token !== generation.current) return;
      const hops = next.chain.map(({ source_id, model_id }) => ({
        source_id,
        model_id,
      }));
      setChain(next);
      setSavedOverride(next.manual_override);
      setCacheTtlDraft(next.manual_override?.cache_ttl ?? null);
      setManualDraft(next.manual_override !== null);
      setPreview(null);
      setPreviewFailed(false);
      onObserved?.(next);
      setOrigin(hops);
      advanceInteraction({ type: "reset", draft: hops, focusIndex: 0 });
      setGuard(null);
      setPhase("ready");
    } catch (error) {
      if (token !== generation.current) return;
      if (apiFailure(error)?.code === "direct_mode") {
        setPhase("direct");
        onDirectMode?.(null, null);
        return;
      }
      setPhase("unread");
      requestAnimationFrame(() => retryButtonRef.current?.focus());
    }
  }, [advanceInteraction, modelId, onDirectMode, onObserved, selectionBackend]);

  React.useEffect(() => {
    const nextIdentity = selection
      ? `${selection.agent.backend}\u0000${selection.modelId}`
      : null;
    if (nextIdentity === openedIdentity.current) return;
    openedIdentity.current = nextIdentity;
    generation.current += 1;
    previewGeneration.current += 1;
    restoreUndo.current = null;
    setPreview(null);
    setPreviewPending(false);
    setPreviewFailed(false);
    setGuard(null);
    setSubmitted(null);
    setSubmittedStage("initial");
    setReconcileFailed(false);
    setFailedMembers(new Set());
    setUnknownObservation("none");
    setUnknownSourceCurrent(false);
    setHeadMenu(false);
    setHopMenu(null);
    setReplacing(null);
    setRecordDetails(false);
    advanceInteraction({ type: "reset", draft: [], focusIndex: 0 });
    if (selection) void readChain();
  }, [advanceInteraction, readChain, selection]);

  React.useEffect(() => {
    if (!selection || selection.available !== false) return;
    generation.current += 1;
    previewGeneration.current += 1;
    onClose();
  }, [onClose, selection]);

  React.useEffect(() => {
    const signature = valid.invalidIndexes.join(",");
    if (!signature) {
      invalidSignature.current = "";
      return;
    }
    if (phase !== "ready" && phase !== "rejected") return;
    if (signature === invalidSignature.current) return;
    invalidSignature.current = signature;
    if (phase === "rejected") setPhase("ready");
    setSelectorEpoch((current) => current + 1);
    advanceInteraction({ type: "drop-grab" });
    focusAfterRender({
      current: removeRefs.current[valid.invalidIndexes[0]]
        ?? editRefs.current[valid.invalidIndexes[0]] ?? null,
    });
  }, [advanceInteraction, phase, valid.invalidIndexes]);

  const close = () => {
    if (phase !== "saving") {
      previewGeneration.current += 1;
      generation.current += 1;
      onClose();
    }
  };
  const cancelChanges = () => {
    if (!canDiscardDraft) return;
    setSubmitted(null);
    submittedOverride.current = null;
    setSubmittedStage("initial");
    setSelectorEpoch((current) => current + 1);
    setAnnouncement(null);
    // Cancel local intent, not server state. Defaults or saved overrides may
    // have changed elsewhere; a failed read must stay visibly unread.
    void readChain();
    focusAfterRender(cancelButtonRef);
  };
  const remove = (index: number) => {
    if (phase === "saving") return;
    if (draft.length === 1) {
      followDefaults();
      focusAfterFollow();
      return;
    }
    const next = advanceInteraction({ type: "remove", index });
    const nextDraft = next.draft;
    const focusedIndex = next.focusIndex;
    requestAnimationFrame(() => {
      if (nextDraft.length > 0) {
        gripRefs.current[focusedIndex]?.focus();
      } else if (addCandidates.length > 0) {
        addButtonRef.current?.focus();
      } else {
        focusDismiss();
      }
    });
    if (nextDraft.length > 0) {
      announce("settings.models.routeDialog.reorder.position", {
        position: focusedIndex + 1,
      });
    }
  };
  const moveGrab = (action: RouteChainInteractionAction) => {
    const previous = interactionRef.current;
    const next = advanceInteraction(action);
    if (next.focusIndex === previous.focusIndex) return;
    requestAnimationFrame(() => gripRefs.current[next.focusIndex]?.focus());
    announce("settings.models.routeDialog.reorder.position", {
      position: next.focusIndex + 1,
    });
  };
  const cancelGrab = () => {
    if (!interactionRef.current.grab) return;
    const next = advanceInteraction({ type: "cancel-grab" });
    requestAnimationFrame(() => gripRefs.current[next.focusIndex]?.focus());
    announce("settings.models.routeDialog.reorder.cancelled", {
      position: next.focusIndex + 1,
    });
  };
  const onGripKeyDown = (
    event: React.KeyboardEvent<HTMLButtonElement>,
    index: number,
  ) => {
    if (event.key === "Tab" && grabbed !== null) {
      const next = advanceInteraction({ type: "drop-grab" });
      announce("settings.models.routeDialog.reorder.dropped", {
        position: next.focusIndex + 1,
      });
    } else if (
      event.key === " " ||
      event.key === "Space" ||
      event.key === "Spacebar" ||
      event.code === "Space"
    ) {
      event.preventDefault();
      if (grabbed === index) {
        const next = advanceInteraction({ type: "drop-grab" });
        announce("settings.models.routeDialog.reorder.dropped", {
          position: next.focusIndex + 1,
        });
      } else {
        const next = advanceInteraction({ type: "begin-grab", index });
        announce("settings.models.routeDialog.reorder.grabbed", {
          position: next.focusIndex + 1,
        });
      }
    } else if (event.key === "Escape" && grabbed !== null) {
      event.preventDefault();
      event.stopPropagation();
    } else if (event.key === "ArrowUp" || event.key === "ArrowDown") {
      event.preventDefault();
      if (grabbed === null) {
        const target = Math.max(
          0,
          Math.min(draft.length - 1, index + (event.key === "ArrowUp" ? -1 : 1)),
        );
        const next = advanceInteraction({ type: "focus", index: target });
        gripRefs.current[next.focusIndex]?.focus();
      } else {
        moveGrab({
          type: "move-grab",
          direction: event.key === "ArrowUp" ? -1 : 1,
        });
      }
    } else if (event.key === "Home" || event.key === "End") {
      event.preventDefault();
      if (grabbed === null) {
        const next = advanceInteraction({
          type: "focus",
          index: event.key === "Home" ? 0 : draft.length - 1,
        });
        gripRefs.current[next.focusIndex]?.focus();
      } else {
        moveGrab({
          type: "move-grab-edge",
          edge: event.key === "Home" ? "start" : "end",
        });
      }
    }
  };
  const beginCommitted = (
    nextReport: RouteReport,
    committedHops: RouteHop[],
  ) => {
    generation.current += 1;
    previewGeneration.current += 1;
    setChain(nextReport.chain);
    setSavedOverride(nextReport.chain.manual_override);
    setCacheTtlDraft(nextReport.chain.manual_override?.cache_ttl ?? null);
    setManualDraft(nextReport.chain.manual_override !== null);
    setPreview(null);
    setPreviewPending(false);
    setPreviewFailed(false);
    setSaveErrorCode(null);
    restoreUndo.current = null;
    setGuard(null);
    setOrigin(committedHops);
    advanceInteraction({ type: "reset", draft: committedHops });
    setUnknownObservation("none");
    setUnknownSourceCurrent(false);
    onCommitted?.(nextReport);
    setPhase("ready");
    onClose();
  };

  const submit = async (confirmation?: GuardPlan) => {
    if (!selection || !agent || phase === "saving" || covered || previewPending || unresolvedPreview || (!manualDraft && previewFailed) || (manualDraft && !valid.valid) || !dirty)
      return;
    const hops = (confirmation ? (submitted ?? draft) : draft).map((hop) => ({
      ...hop,
    }));
    setSubmitted(hops);
    const submittedManualOverride = manualDraft
      ? { hops, ...(cacheTtlDraft === null ? {} : { cache_ttl: cacheTtlDraft }) }
      : null;
    if (!confirmation) submittedOverride.current = submittedManualOverride;
    setSubmittedStage(confirmation ? "confirmed" : "initial");
    setSaveErrorCode(null);
    setPhase("saving");
    // A confirmed save keeps its question mounted, busy, until the answer lands;
    // an initial one shows the progress status in the dialog itself.
    if (!confirmation) requestAnimationFrame(() => savingStatusRef.current?.focus());
    try {
      const result = await sendAgreed(confirmation !== undefined, confirmation ?? null, (plan) => {
        const guardFields = plan ? confirmGuardPlan(plan) : undefined;
        return submittedOverride.current === null
          ? modelsApi.restoreAgentChain(agent.backend, modelId, guardFields)
          : modelsApi.putAgentChain(agent.backend, modelId, { ...submittedManualOverride!, ...guardFields });
      });
      beginCommitted(
        {
          chain: result.chain,
          removed_hops: result.removed_hops,
          interrupted: result.interrupted,
        },
        result.chain.chain.map(({ source_id, model_id }) => ({ source_id, model_id })),
      );
    } catch (error) {
      const failure = apiFailure(error);
      if (failure?.code === "direct_mode") {
        setGuard(null);
        setPhase("direct");
        onDirectMode?.(
          {
            backend: agent.backend,
            modelId,
            stage: confirmation ? "confirmed" : "initial",
            submitted: hops,
            manual_override: submittedOverride.current,
          },
          null,
        );
        return;
      }
      const refusal = failure?.code === "source_last_supplier" || failure?.code === "source_in_route_chain"
        ? unansweredRefusal(error, confirmation !== undefined, confirmation ?? null)
        : null;
      // A confirmed save resends the recomputed plan itself, so the question is
      // asked once per save — unless that plan stops an Agent it did not show.
      if (refusal) {
        setGuard(refusal);
        setPhase("ready");
        return;
      }
      setGuard(null);
      setSaveErrorCode(failure?.code ?? null);
      if (failure?.code === "cache_ttl_unsupported") {
        setPhase("ready");
        focusAfterRender(retryButtonRef);
        return;
      }
      const nextPhase = failure?.serverNamed ? "rejected" : "unknown";
      setPhase(nextPhase);
      focusAfterRender(retryButtonRef);
    }
  };

  const reconcileUnknownMembers = async (
    token: number,
    members: ReadonlySet<ReconcileMember>,
  ) => {
    if (!selectionBackend || !submitted) return;
    const [sourceAnswer, chainAnswer] = await Promise.all([
      members.has("sources")
        ? readSources().then(
            (observation) => ({ kind: "success" as const, observation }),
            () => ({ kind: "failed" as const }),
          )
        : Promise.resolve({ kind: "skipped" as const }),
      members.has("chain")
        ? modelsApi.getAgentChain(selectionBackend, modelId).then(
            (value) => ({ kind: "success" as const, value }),
            (error) =>
              apiFailure(error)?.code === "direct_mode"
                ? { kind: "direct" as const }
                : { kind: "failed" as const },
          )
        : Promise.resolve({ kind: "skipped" as const }),
    ]);
    if (token !== generation.current) return;
    const sourceCurrent =
      sourceAnswer.kind === "skipped"
        ? unknownSourceCurrent
        : sourceAnswer.kind === "success";
    setUnknownSourceCurrent(sourceCurrent);
    if (sourceAnswer.kind === "success") sourceAnswer.observation.install();

    if (chainAnswer.kind === "direct") {
      try {
        const observation = await readAgents();
        if (token !== generation.current) return;
        observation.install();
        const observedAgent = observation.value.find(
          (row) => row.backend === selectionBackend,
        );
        onDirectMode?.(
          {
            backend: selectionBackend,
            modelId,
            stage: submittedStage,
            submitted,
            manual_override: submittedOverride.current,
          },
          observedAgent ?? null,
        );
      } catch {
        if (token !== generation.current) return;
        setFailedMembers(new Set(["agents"]));
        setReconcileFailed(true);
        setPhase("unknown");
        focusAfterRender(retryButtonRef);
      }
      return;
    }

    if (chainAnswer.kind === "success") {
      onObserved?.(chainAnswer.value);
      setChain(chainAnswer.value);
      const observedHops = chainAnswer.value.chain.map(
        ({ source_id, model_id }) => ({ source_id, model_id }),
      );
      if (sameManualOverride(chainAnswer.value.manual_override, submittedOverride.current)) {
        beginCommitted(
          {
            chain: chainAnswer.value,
            removed_hops: null,
            interrupted: null,
          },
          observedHops,
        );
        return;
      }
      setUnknownObservation("nonmatching");
    } else if (chainAnswer.kind === "failed") {
      setUnknownObservation("read_failed");
    }

    const failed = new Set<ReconcileMember>();
    if (!sourceCurrent) failed.add("sources");
    if (chainAnswer.kind === "failed") failed.add("chain");
    setFailedMembers(failed);
    setReconcileFailed(failed.size > 0);
    setPhase("unknown");
    focusAfterRender(retryButtonRef);
  };

  const retryUnknown = async () => {
    if (!selectionBackend || !submitted || phase !== "unknown") return;
    const token = ++generation.current;
    focusDismiss();
    setPhase("reconciling");
    setReconcileFailed(false);

    const retrySourceOnly =
      failedMembers.size === 1 && failedMembers.has("sources");
    const retryChainOnly =
      (failedMembers.size === 1 && failedMembers.has("chain")) ||
      (failedMembers.size === 0 &&
        unknownObservation === "nonmatching" &&
        unknownSourceCurrent);
    if (retrySourceOnly) {
      await reconcileUnknownMembers(token, new Set(["sources"]));
      return;
    }
    if (retryChainOnly) {
      await reconcileUnknownMembers(token, new Set(["chain"]));
      return;
    }
    if (failedMembers.size > 0 && !failedMembers.has("agents")) {
      await reconcileUnknownMembers(token, failedMembers);
      return;
    }

    try {
      const observation = await readAgents();
      if (token !== generation.current) return;
      observation.install();
      const observedAgent = observation.value.find(
        (row) => row.backend === selectionBackend,
      );
      if (!observedAgent) throw new Error("route_agent_missing");
      if (observedAgent.mode === "direct") {
        onDirectMode?.(
          {
            backend: selectionBackend,
            modelId,
            stage: submittedStage,
            submitted,
            manual_override: submittedOverride.current,
          },
          observedAgent,
        );
        return;
      }
      await reconcileUnknownMembers(token, new Set(["sources", "chain"]));
    } catch {
      if (token !== generation.current) return;
      setFailedMembers(new Set(["agents"]));
      setReconcileFailed(true);
      setPhase("unknown");
      focusAfterRender(retryButtonRef);
    }
  };

  const addCandidate = (candidate: RouteCandidate) => {
    const next = advanceInteraction({ type: "append", hop: candidate.hop });
    requestAnimationFrame(() => gripRefs.current[next.focusIndex]?.focus());
  };
  const restoreAutomatic = React.useCallback(async () => {
    if (!agent || previewPending || phase !== 'ready') return;
    const token = ++previewGeneration.current;
    // Record intent before reading: failure must not leave a saveable empty Manual draft.
    if (restoreUndo.current === null) {
      restoreUndo.current = { hops: draft.map((hop) => ({ ...hop })), manual: manualDraft, cacheTtl: cacheTtlDraft };
    }
    setManualDraft(false);
    setCacheTtlDraft(null);
    setPreview(null);
    setPreviewPending(true);
    setPreviewFailed(false);
    advanceInteraction({ type: 'drop-grab' });
    setSelectorEpoch((current) => current + 1);
    try {
      const next = await modelsApi.previewAgentChain(agent.backend, modelId, { manual_override: null });
      if (token !== previewGeneration.current) return;
      setPreview(next);
      advanceInteraction({ type: 'reset', draft: next.chain.map(({ source_id, model_id }) => ({ source_id, model_id })) });
      setAnnouncement({ key: 'settings.models.routing.restorePending' });
    } catch {
      if (token === previewGeneration.current) setPreviewFailed(true);
    } finally {
      if (token === previewGeneration.current) setPreviewPending(false);
    }
  }, [advanceInteraction, agent, cacheTtlDraft, draft, manualDraft, modelId, phase, previewPending]);
  const wasCovered = React.useRef(covered);
  React.useEffect(() => {
    const leaving = !wasCovered.current && covered;
    const returning = wasCovered.current && !covered;
    wasCovered.current = covered;
    if (leaving && restoreUndo.current !== null) {
      previewGeneration.current += 1;
      setPreview(null);
      setPreviewPending(false);
      setPreviewFailed(false);
    }
    if (!returning || manualDraft) return;
    // Defaults can change while this dialog is hidden; explicit drafts remain local.
    if (restoreUndo.current) void restoreAutomatic();
    else void readChain();
  }, [covered, manualDraft, readChain, restoreAutomatic]);
  const undoRestore = () => {
    previewGeneration.current += 1;
    setPreview(null);
    setPreviewPending(false);
    setPreviewFailed(false);
    const restored = restoreUndo.current;
    setManualDraft(restored?.manual ?? savedOverride !== null);
    setCacheTtlDraft(restored ? restored.cacheTtl : savedOverride?.cache_ttl ?? null);
    advanceInteraction({ type: 'reset', draft: restoreUndo.current?.hops ?? origin });
    restoreUndo.current = null;
    announce('settings.models.routing.undoDone');
  };
  // Undoing an unsaved pin is local: saved routing already follows defaults,
  // and the inherited route this dialog last read is what stays in force.
  const revertToInherited = () => {
    previewGeneration.current += 1;
    restoreUndo.current = null;
    setPreview(null);
    setPreviewPending(false);
    setPreviewFailed(false);
    setManualDraft(false);
    setCacheTtlDraft(null);
    advanceInteraction({ type: 'reset', draft: origin });
    setSelectorEpoch((current) => current + 1);
  };
  const followDefaults = () => {
    if (savedOverride === null) revertToInherited();
    else void restoreAutomatic();
  };
  const switchMode = (next: RouteMode) => {
    if (phase !== 'ready' || previewPending) return;
    if (next === 'custom') {
      if (manualDraft) return;
      // Returning from a pending restore brings back the route that was left.
      if (restoreUndo.current) undoRestore();
      else {
        setManualDraft(true);
        setCacheTtlDraft(null);
      }
    } else if (manualDraft) {
      followDefaults();
      focusAfterFollow();
    }
  };
  const undoSwitch = () => {
    if (restoreUndo.current) undoRestore();
    else revertToInherited();
    focusMode();
  };
  // Follow-default rows are the inherited route, read only; editing starts from
  // the Custom switch, so no row gesture can pin a route by accident.
  const editable = manualDraft;
  const actionsDisabled = phase === "saving";
  const recordedHopIndex = recordedTurn.record
    ? draft.findIndex((hop) => recordedOn(recordedTurn.record, hop))
    : -1;
  const renderHop = (hop: RouteHop, index: number) => {
    const visibleChain = preview ?? chain;
    const chainLink = visibleChain?.chain.find((entry) =>
      equalHopIdentity(entry, hop),
    );
    const missing = chainLink?.reason === "source_missing";
    const joined = sources.some((source) => hopBelongsToSource(hop, source.id));
    const displayedSource = missing
      ? `${t("settings.models.routeDialog.sourceMissing")} · ${hop.source_id}`
      : joined
        ? sourceName(sources, hop.source_id)
        : hop.source_id;
    const chainCurrent = visibleChain?.current ?? null;
    const current = equalHopIdentity(chainCurrent, hop);
    const replacementCandidates = agent
      ? routeCandidates(
          agent,
          sources,
          draft.filter((_, draftIndex) => draftIndex !== index),
        )
      : [];
    const roving = grabbed === null && rovingIndex === index ? 0 : -1;
    const editLabel = t("settings.models.routeDialog.editHop") as string;
    const removeLabel = t("settings.models.routeDialog.removeHop") as string;
    const replaceHop = (nextCandidate: RouteCandidate) => {
      const next = advanceInteraction({
        type: "replace",
        index,
        hop: nextCandidate.hop,
      });
      announce("settings.models.routeDialog.edit.replaced", {
        position: index + 1,
      });
      requestAnimationFrame(() =>
        gripRefs.current[next.focusIndex]?.focus(),
      );
    };
    const actionClass = "model-hub-route-action grid shrink-0 place-items-center text-muted";
    // Phones fold both row actions into one menu; the picker then hangs from
    // that menu's button instead of a pencil of its own.
    const mobileActions = (
      <ResponsiveMenu
        open={hopMenu === index}
        onOpenChange={(open) => setHopMenu(open ? index : null)}
        sheetTitle={displayedSource}
        sheetDescription={hop.model_id}
        trigger={
          <button
            ref={(node) => {
              editRefs.current[index] = node;
            }}
            type="button"
            aria-label={t("settings.models.routeDialog.hopActions") as string}
            tabIndex={roving}
            disabled={actionsDisabled}
            className={cn(actionClass, "model-hub-route-more")}
          >
            <MoreHorizontal aria-hidden="true" />
          </button>
        }
      >
        <button
          type="button"
          role="menuitem"
          className={MENU_ITEM}
          onClick={() => {
            setHopMenu(null);
            requestAnimationFrame(() => setReplacing(index));
          }}
        >
          <Pencil aria-hidden="true" />
          {editLabel}
        </button>
        <button
          type="button"
          role="menuitem"
          className={cn(MENU_ITEM, "text-destructive-ink hover:bg-destructive/[0.08]")}
          onClick={() => {
            setHopMenu(null);
            remove(index);
          }}
        >
          <X aria-hidden="true" />
          {removeLabel}
        </button>
      </ResponsiveMenu>
    );
    return (
      <div
        key={`${hop.source_id}:${hop.model_id}:${index}`}
        onDragOver={editable ? (event) => event.preventDefault() : undefined}
        onDrop={editable ? (event) => {
          event.preventDefault();
          if (grabbed !== null) {
            advanceInteraction({
              type: "move-grab-to",
              index,
            });
            advanceInteraction({ type: "drop-grab" });
          }
        } : undefined}
        data-current={current || undefined}
        data-editable={editable || undefined}
        className="model-hub-route-hop flex items-center"
      >
        {editable && <button
          ref={(node) => {
            gripRefs.current[index] = node;
          }}
          type="button"
          aria-label={t("settings.models.routeDialog.grip") as string}
          aria-grabbed={grabbed === index}
          onMouseDown={(event) => event.currentTarget.focus()}
          onClick={(event) => event.currentTarget.focus()}
          draggable={phase === "ready"}
          onDragStart={() => {
            advanceInteraction({ type: "begin-grab", index });
          }}
          onDragEnd={() => {
            advanceInteraction({ type: "drop-grab" });
          }}
          onFocus={() => advanceInteraction({ type: "focus", index })}
          onKeyDown={(event) => onGripKeyDown(event, index)}
          tabIndex={
            grabbed === index || (grabbed === null && rovingIndex === index)
              ? 0
              : -1
          }
          className="model-hub-route-grip grid shrink-0 place-items-center"
        >
          <GripVertical aria-hidden="true" />
        </button>}
        <span
          className={cn(
            "model-hub-route-ordinal grid shrink-0 place-items-center font-mono font-medium",
            index === 0
              ? "model-hub-accent-pill--mint"
              : "model-hub-fill-0a text-muted",
          )}
        >
          {index + 1}
        </span>
        <span className="model-hub-route-hop-copy flex min-w-0 flex-1 flex-col">
          <span
            className="model-hub-route-hop-name font-semibold text-foreground"
            title={displayedSource}
          >
            {missing ? (
              <>
                {t("settings.models.routeDialog.sourceMissing")}
                <span className="font-mono"> · {hop.source_id}</span>
              </>
            ) : !joined ? (
              <span className="font-mono">{hop.source_id}</span>
            ) : (
              sourceName(sources, hop.source_id)
            )}
          </span>
          <span
            className="model-hub-route-hop-model model-hub-ink-muted-b3 font-mono"
            title={hop.model_id}
          >
            {hop.model_id}
          </span>
          {valid.invalidIndexes.includes(index) && (
            <span
              id={`model-hub-route-invalid-${index}`}
              className="model-hub-route-invalid"
            >
              {t("settings.models.routeDialog.invalidAfterRefresh")}
            </span>
          )}
        </span>
        {index === recordedHopIndex && recordedTurn.record && (
          <RecordedTurnBadge record={recordedTurn.record} onOpen={() => setRecordDetails(true)} />
        )}
        {editable && <span className="model-hub-route-actions flex shrink-0 items-center">
          <RouteCandidatePopover
            key={`edit:${selectorEpoch}:${index}`}
            candidates={replacementCandidates}
            sources={targetSources}
            confirmLabel={t("settings.models.routeDialog.edit.confirm") as string}
            initialHop={hop}
            label={editLabel}
            width="route"
            onReturnFocus={() => editRefs.current[index]?.focus()}
            onApply={replaceHop}
            {...(isMobile ? {
              open: replacing === index,
              onOpenChange: (open: boolean) => setReplacing(open ? index : null),
            } : {})}
            trigger={isMobile ? <span className="model-hub-route-menu-anchor">{mobileActions}</span> : (
              <button
                ref={(node) => {
                  editRefs.current[index] = node;
                }}
                type="button"
                aria-label={editLabel}
                title={editLabel}
                tabIndex={roving}
                disabled={actionsDisabled}
                className={cn(actionClass, "model-hub-route-edit")}
              >
                <Pencil aria-hidden="true" />
              </button>
            )}
          />
          {!isMobile && <button
            ref={(node) => {
              removeRefs.current[index] = node;
            }}
            type="button"
            aria-label={removeLabel}
            title={removeLabel}
            tabIndex={roving}
            disabled={actionsDisabled}
            onClick={() => remove(index)}
            className={cn(actionClass, "model-hub-route-remove")}
          >
            <X aria-hidden="true" />
          </button>}
        </span>}
      </div>
    );
  };

  if (!selection) return null;
  // A confirmed save answers inside its own question, so the chain it is about
  // stays on screen behind it rather than turning into a progress line.
  const savingInline = phase === "saving" && guard === null;
  const sourceNames = Object.fromEntries(sources.map((source) => [source.id, source.display_name]));
  const body =
    phase === "loading" ? (
      <div className="model-hub-route-body flex flex-1 items-center justify-center gap-2 text-muted">
        <LoaderCircle className="size-4 animate-spin" />
        {t("settings.models.routeDialog.loading")}
      </div>
    ) : phase === "unread" ? (
      <div className="model-hub-route-body flex flex-1 flex-col items-center justify-center gap-3 text-muted">
        <p>{t("settings.models.routeDialog.fail.read")}</p>
        <Button
          ref={retryButtonRef}
          type="button"
          onClick={() => {
            focusDismiss();
            void readChain();
          }}
        >
          {t("settings.models.routeDialog.retry")}
        </Button>
      </div>
    ) : phase === "direct" ? (
      <div className="model-hub-route-body flex flex-1 items-center justify-center text-muted">
        {t("settings.models.routeDialog.fail.read")}
      </div>
    ) : savingInline ? (
      <div className="model-hub-route-body flex flex-1 items-center justify-center gap-2 text-muted">
        <LoaderCircle className="size-4 animate-spin" />
        <span ref={savingStatusRef} role="status" tabIndex={-1}>
          {t("settings.models.routeDialog.saving")}
        </span>
      </div>
    ) : phase === "rejected" ? (
      <div className="model-hub-route-body flex flex-1 flex-col items-center justify-center gap-3 text-muted">
        <p>{saveErrorCode === "cache_ttl_unsupported"
          ? t("errors.cache_ttl_unsupported")
          : t("settings.models.routeDialog.fail.save")}</p>
        <Button
          ref={retryButtonRef}
          type="button"
          disabled={manualDraft && !valid.valid}
          onClick={() => {
            generation.current += 1;
            void submit();
          }}
        >
          {t("settings.models.routeDialog.retry")}
        </Button>
      </div>
    ) : phase === "unknown" || phase === "reconciling" ? (
      <div className="model-hub-route-body flex flex-1 flex-col items-center justify-center gap-3 text-muted">
        <p>
          {t(
            reconcileFailed
              ? "settings.models.routeDialog.fail.reconcileRead"
              : "settings.models.routeDialog.fail.unconfirmed",
          )}
        </p>
        <Button
          ref={retryButtonRef}
          type="button"
          disabled={phase === "reconciling"}
          onClick={() => void retryUnknown()}
        >
          {t("settings.models.routeDialog.retry")}
        </Button>
      </div>
    ) : (
      <div className="model-hub-route-body flex flex-col">
        <div className="model-hub-route-mode flex flex-col">
          <div ref={modeRef}>
            <SegmentedRadio<RouteMode>
              ariaLabel={t("settings.models.routeDialog.mode.label") as string}
              value={manualDraft ? "custom" : "follow"}
              onChange={switchMode}
              disabled={phase !== "ready" || previewPending}
              className="model-hub-route-mode-switch"
              options={[
                { id: "follow", label: t("settings.models.routeDialog.mode.follow") as string },
                { id: "custom", label: t("settings.models.routeDialog.mode.custom") as string },
              ]}
            />
          </div>
          <p className="model-hub-route-mode-copy text-muted">
            {t(manualDraft ? "settings.models.routing.manualHint" : "settings.models.routing.follows", { backend })}
          </p>
          {agent?.backend === "vibey" && manualDraft && (
            <Field
              className="mt-3 text-sm"
              label={t("settings.models.routing.cacheTtl.label")}
              hint={t("settings.models.routing.cacheTtl.help")}
            >
              {(id) => (
                <>
                  <Select
                    id={id}
                    wrapperClassName="w-fit"
                    value={cacheTtlDraft ?? ""}
                    onChange={(event) => setCacheTtlDraft((event.target.value || null) as CacheTtl | null)}
                    disabled={phase !== "ready" || previewPending}
                  >
                    <option value="">{t("settings.models.routing.cacheTtl.default")}</option>
                    <option value="5m">{t("settings.models.routing.cacheTtl.5m")}</option>
                    <option value="30m">{t("settings.models.routing.cacheTtl.30m")}</option>
                    <option value="1h">{t("settings.models.routing.cacheTtl.1h")}</option>
                    <option value="12h">{t("settings.models.routing.cacheTtl.12h")}</option>
                  </Select>
                  {saveErrorCode === "cache_ttl_unsupported" && (
                    <span role="alert" className="text-xs text-danger">
                      {t("errors.cache_ttl_unsupported")}
                    </span>
                  )}
                </>
              )}
            </Field>
          )}
        </div>
        {!unresolvedPreview && <div inert={previewPending} className="model-hub-route-list flex flex-col">
          {draft.length ? (
            draft.map(renderHop)
          ) : (
            <div className="model-hub-route-empty text-xs text-muted">
              <p>{t(manualDraft ? 'settings.models.routing.draftEmpty' : 'settings.models.routing.noDefaults')}</p>
              {!manualDraft && onOpenDefaults && <Button variant="outline" onClick={onOpenDefaults}><ListOrdered aria-hidden />{t('settings.models.routing.configureDefaults')}</Button>}
            </div>
          )}
        </div>}
        <div className="model-hub-route-tools flex flex-wrap items-center justify-between">
          {!unresolvedPreview && manualDraft && canEditRoute ? <RouteCandidatePopover
            key={`add:${selectorEpoch}`}
            candidates={addCandidates}
            sources={targetSources}
            confirmLabel={t("settings.models.routeDialog.add.confirm") as string}
            label={t("settings.models.routeDialog.addHop") as string}
            width="route"
            align="start"
            onApply={addCandidate}
            onReturnFocus={() => addButtonRef.current?.focus()}
            trigger={
              <Button
                ref={addButtonRef}
                type="button"
                variant="outline"
                size="sm"
                disabled={targetSources.length === 0 || previewPending}
                aria-describedby={
                  addCandidates.length === 0
                    ? "model-hub-route-add-none"
                    : undefined
                }
                className="model-hub-route-add"
              >
                <Plus aria-hidden="true" />
                {t("settings.models.routeDialog.addHop")}
              </Button>
            }
          /> : <span />}
          {onOpenDefaults && <button type="button" onClick={onOpenDefaults} className="model-hub-route-defaults flex items-center text-muted">
            {t(manualDraft ? 'settings.models.routeDialog.mode.viewDefaults' : 'settings.models.routeDialog.mode.adjustDefaults')}
            <ChevronRight aria-hidden="true" />
          </button>}
        </div>
        {addCandidates.length === 0 && (
          <span className="sr-only" id="model-hub-route-add-none">
            {t("settings.models.routeDialog.add.none")}
          </span>
        )}
        {previewFailed && <div role="alert" className="text-destructive-ink text-xs"><p>{t('settings.models.routing.previewFailed')}</p><Button variant="ghost" size="sm" disabled={previewPending} onClick={() => void restoreAutomatic()}><RefreshCw aria-hidden />{t('settings.models.routeDialog.retry')}</Button></div>}
        {manualDraft && valid.invalidIndexes.length > 0 && (
          <p
            id="model-hub-route-invalid-summary"
            className="model-hub-route-invalid-summary"
          >
            {t("settings.models.routeDialog.invalidAfterRefresh")}
          </p>
        )}
        {/* Next to Save, which is what it describes: above the rows it would push
            the Add trigger down and take the room its picker opens into. */}
        {(pendingSwitch || restoring) && <div className="model-hub-route-pending flex items-center justify-between" role="status" data-origin={preview?.route_origin ?? undefined}>
          <span className="flex min-w-0 flex-col">
            {previewPending && <strong>{t('settings.models.routing.previewLoading')}</strong>}
            {preview && <strong>{t(`settings.models.routing.preview.${preview.route_origin ?? 'unconfigured'}`, { defaultValue: `settings.models.routing.preview.${preview.route_origin ?? 'unconfigured'}` })}</strong>}
            <span>{t(pendingSwitch === 'pin' ? 'settings.models.routing.manualPending' : 'settings.models.routing.restorePending')}</span>
          </span>
          <button ref={pendingUndoRef} type="button" disabled={phase !== 'ready'} onClick={undoSwitch} className="model-hub-route-pending-undo flex shrink-0 items-center font-semibold">
            <Undo2 aria-hidden="true" />
            {t('settings.models.routeDialog.mode.undo')}
          </button>
        </div>}
        <RouteRecordedTurn turn={recordedTurn} matched={recordedHopIndex >= 0} onOpenDetails={() => setRecordDetails(true)} />
        <span className="sr-only" aria-live="polite">
          {announcement ? t(announcement.key, announcement.params) : ""}
        </span>
      </div>
    );

  return (
    <DialogPrimitive.Root open={!covered} onOpenChange={(open) => !open && close()}>
      <DialogPrimitive.Portal>
        <DialogPrimitive.Overlay className="model-hub-route-overlay fixed inset-0 z-50" />
        <DialogPrimitive.Content
          aria-busy={phase === "saving" || previewPending || phase === "reconciling"}
          className="model-hub-route-dialog fixed left-1/2 top-1/2 z-50 flex -translate-x-1/2 -translate-y-1/2 flex-col gap-0 overflow-hidden border border-border-strong bg-surface p-0"
          onOpenAutoFocus={(event) => {
            event.preventDefault();
            focusDismiss();
          }}
          onEscapeKeyDown={(event) => {
            if (phase === "ready" && interactionRef.current.grab) {
              event.preventDefault();
              cancelGrab();
            }
          }}
        >
          <header className="model-hub-route-head flex flex-col border-b border-border">
            <span className="flex items-center justify-between gap-3">
              <DialogPrimitive.Title className="model-hub-route-title font-bold text-foreground">
                {t("settings.models.routeDialog.title", { menuModel: modelId })}
              </DialogPrimitive.Title>
              <span className="model-hub-route-head-actions flex shrink-0 items-center gap-1.5">
                {manageableModel && (
                  <ResponsiveMenu
                    open={headMenu}
                    onOpenChange={setHeadMenu}
                    sheetTitle={modelId}
                    trigger={
                      <button
                        type="button"
                        aria-label={t("settings.models.routeDialog.modelActions") as string}
                        title={t("settings.models.routeDialog.modelActions") as string}
                        className="model-hub-route-close grid shrink-0 place-items-center"
                      >
                        <MoreHorizontal aria-hidden="true" />
                      </button>
                    }
                  >
                    <button
                      type="button"
                      role="menuitem"
                      className={MENU_ITEM}
                      onClick={() => {
                        setHeadMenu(false);
                        onManageModel?.("edit");
                      }}
                    >
                      <Pencil aria-hidden="true" />
                      {t("settings.models.routeDialog.editModel")}
                    </button>
                    <button
                      type="button"
                      role="menuitem"
                      className={cn(MENU_ITEM, "text-destructive-ink hover:bg-destructive/[0.08]")}
                      onClick={() => {
                        setHeadMenu(false);
                        onManageModel?.("remove");
                      }}
                    >
                      <Trash2 aria-hidden="true" />
                      {t("settings.models.routeDialog.removeModel")}
                    </button>
                  </ResponsiveMenu>
                )}
                <DialogPrimitive.Close
                  ref={closeButtonRef}
                  disabled={phase === "saving"}
                  aria-label={t("settings.models.routing.close") as string}
                  className="model-hub-route-close grid shrink-0 place-items-center"
                >
                  <X aria-hidden="true" />
                </DialogPrimitive.Close>
              </span>
            </span>
            <DialogPrimitive.Description className="model-hub-route-subtitle font-mono text-muted">
              {backend}
            </DialogPrimitive.Description>
          </header>
          {body}
          <RecordedTurnDetails record={recordedTurn.record} open={recordDetails} onOpenChange={setRecordDetails} />
          <GuardDialog
            open={guard !== null}
            title={t("settings.models.guard.title.saveRoute", { menuModel: modelId })}
            subtitle={t("settings.models.guard.subtitle.saveRoute")}
            confirmLabel={t("settings.models.guard.confirm.saveRoute")}
            busy={phase === "saving"}
            onCancel={() => {
              setGuard(null);
              focusAfterRender(saveButtonRef);
            }}
            onConfirm={() => { if (guard) void submit(guard); }}
          >
            {guard && <GuardImpact hops={guard.hops} gaps={guard.gaps} sourceNames={sourceNames} />}
          </GuardDialog>
          <footer className="model-hub-route-foot model-hub-fill-05 flex items-center justify-end gap-2 border-t border-border">
            {savingInline ? (
              <span role="status" className="text-xs text-muted">
                {t("settings.models.routeDialog.saving")}
              </span>
            ) : (
              <>
                <Button
                  ref={cancelButtonRef}
                  type="button"
                  variant="outline"
                  className="model-hub-dialog-action"
                  disabled={!canDiscardDraft}
                  onClick={cancelChanges}
                >
                  {t('settings.models.routing.cancelChanges')}
                </Button>
                <Button
                  ref={saveButtonRef}
                  type="button"
                  className="model-hub-dialog-action"
                  aria-describedby={
                    manualDraft && valid.invalidIndexes.length > 0
                      ? [
                          "model-hub-route-invalid-summary",
                          ...valid.invalidIndexes.map(
                            (index) => `model-hub-route-invalid-${index}`,
                          ),
                        ].join(" ")
                      : undefined
                  }
                  disabled={phase !== "ready" || covered || previewPending || unresolvedPreview || (!manualDraft && previewFailed) || !dirty || (manualDraft && !valid.valid)}
                  onClick={() => void submit()}
                >
                  {t("settings.models.routeDialog.save")}
                </Button>
              </>
            )}
          </footer>
        </DialogPrimitive.Content>
      </DialogPrimitive.Portal>
    </DialogPrimitive.Root>
  );
};

export default RouteChainDialog;