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.

52.2 KB
Raw Blame
import type { TranslationKey } from '@/i18n/types';
// One model-catalog dialog for every backend.
//
// It replaces OpenCodeMenuDialog, which existed because OpenCode was the only
// backend whose menu the user could edit. That distinction was never a product
// idea — it was the shape of the old data. With one catalog per backend, one
// dialog edits it, and Claude Code's `Default` is not a special case in the UI
// but an ordinary row the server marked `locked`.
//
// It shows the catalog and nothing else: no Source, no Route, no fallback, no
// mapping. Which supplier serves a model is a Route question, and the Route rows
// on the Agent card are where it stays answered.
import * as React from 'react';
import { Reorder, useDragControls } from 'framer-motion';
import { GripVertical, Lock, LoaderCircle, Pencil, Plus, Search, Trash2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';

import { Button } from '@/components/ui/button';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
import { getBackendUiMeta } from '@/lib/agentBackends';
import { useLatestRef } from '@/lib/useLatestRef';
import type { PendingWrite } from './asyncLifetime';
import {
  applyBackendCatalogIntent,
  backendCatalogIntent,
  backendCatalogIntentApplied,
  backendModelId,
  catalogModelIds,
  chosenCandidate,
  draftRowFor,
  heldRowFor,
  offeredCandidates,
  readBackendCatalogBaseline,
  sameCatalog,
  type BackendCatalogBaseline,
  type ChosenCandidate,
} from './backendCatalog';
import { BackendModelEditorDialog } from './BackendModelEditorDialog';
import { BackendModelPickerDialog } from './BackendModelPickerDialog';
import { GuardDialog } from './GuardDialog';
import { GuardImpact, type GuardPicture, type GuardPlan } from './GuardImpact';
import { agreementCovers } from './guardedWrite';
import { apiFailure, modelsApi } from './modelsApi';
import { movedOrder, sameIds } from './reorder';
import { catalogSaveFailureKey, catalogSaveLeftUnloaded } from './serverCopy';
import type {
  AgentBackend,
  AgentSupply,
  BackendModel,
  BackendModelsPut,
  ModelCandidate,
} from './types';

type ReadState = 'loading' | 'ready' | 'error';

/**
 * A model the opener already had on screen, and what it wants done to it.
 *
 * The Route dialog names one of its own rows and hands it over rather than
 * growing an edit or removal path of its own: everything that makes those
 * writes safe — the removal guard, the refusal replay, the single save — lives
 * here, and a second implementation of it would be a second protocol.
 */
export type CatalogFocus = {
  modelId: string;
  action: 'edit' | 'remove';
};

/** Same shape the Source order drawer announces with: the key alone would tell a
 *  screen-reader user something moved without telling them where to. */
type AnnouncementKey = 'grabbed' | 'moved' | 'dropped' | 'grabCancelled';

type Announcement = {
  key: AnnouncementKey;
  model: string;
  position: number;
  count: number;
} | null;

const matchesQuery = (model: BackendModel, query: string, renderedLabel: string): boolean => {
  if (query === '') return true;
  const needle = query.toLowerCase();
  return model.id.toLowerCase().includes(needle)
    || renderedLabel.toLowerCase().includes(needle);
};

/** A focused removal the user is being asked about, with the route preview the
 *  confirmation shows. */
type FocusedRemoval = { modelId: string; plan: GuardPicture };

/** The stale-candidate refusal (C1), named by the route's own `error` rather
 *  than by status: nothing was committed and nothing was interrupted, so it is
 *  answered by asking again with today's suppliers, not by a failure sentence. */
const CANDIDATES_CHANGED = 'candidate_suppliers_changed';

/** The route guard (C3). Like the refusal above it commits nothing: it is the
 *  server naming what this write would take with it, and it is answered by
 *  the user's one confirmation rather than by a failure sentence. */
const MODEL_IN_ROUTE = 'backend_model_in_route';

/** How many times a confirmed save is resent when the guard's plan moved
 *  between the confirmation and the forced write. The user already agreed to
 *  remove these models, so a changed plan is resent rather than asked again;
 *  the bound only stops a plan that never settles from looping. */
const FORCED_RESENDS = 2;

/** The ids a picker may not offer: everything the draft holds, less the ones it
 *  was reopened to ask about. A re-ask is about a row the draft still holds (the
 *  addition was refused, not applied), so counting it as 「already in the list」
 *  would show the user their own pending addition as an unpickable row and leave
 *  the question it was reopened to ask unanswerable. */
const offerable = (taken: ReadonlySet<string>, seed: ReadonlySet<string>): ReadonlySet<string> => {
  if (seed.size === 0) return taken;
  const listed = new Set(taken);
  for (const id of seed) listed.delete(id);
  return listed;
};

/** Nothing pre-picked, held once so opening the picker is not a new object each
 *  render — the picker applies its seed when it opens. */
const NO_SEED: ReadonlySet<string> = new Set();

export const BackendModelCatalogDialog: React.FC<{
  open: boolean;
  backend: AgentBackend;
  /** Whether this role may read Sources. The candidates read names them, so the
   *  action that opens it is offered exactly where the page's other
   *  Source-reading surfaces are (C4). */
  canReadSources: boolean;
  /** Source id → name, for the removal confirmation's hops. The catalog names no
   *  Source of its own (that stays with the Route), but a removal that takes a
   *  Route with it has to say whose hop goes away — so the page's own Sources
   *  answer it, and an id they do not cover simply goes unnamed. */
  sourceNames: Readonly<Record<string, string>>;
  /** `removed` says the focused model left the saved list, so an opener that
   *  was showing it has nothing to return to. */
  onClose: (result?: { removed: boolean }) => void;
  onSaved: (echoed: AgentSupply) => void | Promise<void>;
  onObserved: (observed: AgentSupply) => void | Promise<void>;
  catalogWrite: PendingWrite;
  /** Open straight onto one row's edit or removal, for an opener that already
   *  named the model. Applied once the catalog it names has been read, and
   *  shown without the list: the editor or the removal confirmation is the
   *  whole dialog, and answering it saves. The list appears only when that
   *  answer needs it — a row it cannot open, or a save it has to explain. */
  focus?: CatalogFocus | null;
}> = ({ open, backend, canReadSources, sourceNames, onClose, onSaved, onObserved, catalogWrite, focus = null }) => {
  const { t } = useTranslation();
  const [baseline, setBaseline] = React.useState<BackendCatalogBaseline | null>(null);
  const baselineRef = React.useRef<BackendCatalogBaseline | null>(null);
  const [readState, setReadState] = React.useState<ReadState>('loading');
  const [draft, setDraft] = React.useState<BackendModel[]>([]);
  const draftRef = React.useRef<BackendModel[]>([]);
  const [query, setQuery] = React.useState('');
  const [saveFailedKey, setSaveFailedKey] = React.useState<TranslationKey | null>(null);
  const [editing, setEditing] = React.useState<{ model: BackendModel | null; seedId?: string } | null>(null);
  const [picking, setPicking] = React.useState<{ seed: ReadonlySet<string> } | null>(null);
  const [removing, setRemoving] = React.useState<FocusedRemoval | null>(null);
  const [grabbedId, setGrabbedId] = React.useState<string | null>(null);
  /** A focused opening that fell back to the full list. */
  const [expanded, setExpanded] = React.useState(false);
  /** The focused removal the user confirmed, kept on screen while it saves. */
  const [answered, setAnswered] = React.useState<FocusedRemoval | null>(null);
  /** The guard's refusal of the last save, waiting on the user's one answer. */
  const [guardPlan, setGuardPlan] = React.useState<GuardPlan | null>(null);
  /** The focused edit the user committed, kept on screen while it saves. */
  const [savingEdit, setSavingEdit] = React.useState<{ model: BackendModel | null; seedId?: string } | null>(null);
  const [announcement, setAnnouncement] = React.useState<Announcement>(null);
  const readAttempt = React.useRef(0);
  const grips = React.useRef(new Map<string, HTMLButtonElement>());
  const grabbedFrom = React.useRef<string[] | null>(null);
  /**
   * The picks this draft holds an agreement for (C1), each still paired with the
   * suppliers its row displayed.
   *
   * One object per pick, and this is its only home: a set of added ids beside a
   * map of expectations is two records of one agreement, and the id can leave
   * the set while its promise stays behind — which is how a save comes to send
   * a projection nobody agreed to. Kept in a ref because it is not rendered;
   * the list on screen is the decision, and this is what it was made against.
   */
  const chosenRef = React.useRef(new Map<string, ChosenCandidate>());
  const applyBaseline = React.useCallback((observed: BackendCatalogBaseline, models: BackendModel[]) => {
    baselineRef.current = observed;
    setBaseline(observed);
    draftRef.current = models;
    setDraft(models);
    setReadState('ready');
  }, []);

  const loadBaseline = React.useCallback((preserveDraft: boolean) => {
    const attempt = ++readAttempt.current;
    setReadState('loading');
    void (async () => {
      try {
        const observed = await readBackendCatalogBaseline(modelsApi, backend);
        if (attempt !== readAttempt.current) return;
        const server = observed.models ?? [];
        const previous = baselineRef.current?.models;
        const next = preserveDraft && previous
          ? applyBackendCatalogIntent(server, backendCatalogIntent(previous, draftRef.current))
          : server;
        applyBaseline(observed, next);
      } catch {
        if (attempt === readAttempt.current) setReadState('error');
      }
    })();
  }, [applyBaseline, backend]);

  React.useEffect(() => {
    if (!open) return;
    // All of these describe decisions taken against one baseline, so a dialog
    // that is reading a new one starts with none of them.
    chosenRef.current = new Map();
    setPicking(null);
    setRemoving(null);
    setExpanded(false);
    setAnswered(null);
    setGuardPlan(null);
    loadBaseline(false);
    return () => { readAttempt.current += 1; };
  }, [loadBaseline, open]);

  const mutate = (next: BackendModel[]) => {
    draftRef.current = next;
    setDraft(next);
    setRemoving(null);
    setSaveFailedKey(null);
  };

  // The server sent no `catalog_models`, so this build is talking to a release
  // that predates the catalog. The legacy list is still worth showing — it is
  // what the backend really exposes — but the dialog will not offer to write a
  // baseline it assembled itself.
  const legacy = baseline !== null && baseline.models === null;
  const legacyIds = legacy && baseline ? catalogModelIds(baseline.agent) : [];
  const ready = readState === 'ready' && baseline !== null;
  const editable = ready && !legacy;
  const busy = catalogWrite.pending;
  const dirty = editable && !sameCatalog(baseline?.models ?? [], draft);
  /** A save that failed after the re-read rebased the draft leaves nothing to
   *  send and everything still to do — a catalog the backend never loaded reads
   *  as settled, so pressing Save again has to stay possible. */
  const retryable = editable && saveFailedKey !== null;
  const filtering = query.trim() !== '';
  const displayLabel = (model: BackendModel): string => model.display_name ?? model.id;
  const visible = draft.filter((model) => matchesQuery(model, query.trim(), displayLabel(model)));
  const movableIds = draft.filter((model) => !model.locked).map((model) => model.id);
  const takenIds = new Set(draft.map((model) => model.id));
  const effortSuggestions = [...new Set(draft.flatMap((model) => model.reasoning_efforts))];
  /** Reordering permutes which movable row sits in which movable slot; a locked
   *  row keeps its absolute index, so the order sent never moves one. */
  const reorderMovable = (nextIds: string[]) => {
    const byId = new Map(draft.map((model) => [model.id, model]));
    let cursor = 0;
    mutate(draft.map((model) => (model.locked ? model : byId.get(nextIds[cursor++]) as BackendModel)));
  };

  const label = (modelId: string): string => {
    const model = draft.find((entry) => entry.id === modelId);
    return model ? displayLabel(model) : modelId;
  };

  const announce = (key: AnnouncementKey, modelId: string, order: string[] = movableIds) => {
    setAnnouncement({
      key,
      model: label(modelId),
      position: order.indexOf(modelId) + 1,
      count: order.length,
    });
  };

  const focusGrip = (modelId: string) => {
    requestAnimationFrame(() => grips.current.get(modelId)?.focus());
  };

  const cancelGrab = () => {
    const restored = grabbedFrom.current;
    grabbedFrom.current = null;
    const focused = grabbedId;
    setGrabbedId(null);
    if (restored && !sameIds(restored, movableIds)) reorderMovable(restored);
    if (focused) {
      announce('grabCancelled', focused, restored ?? movableIds);
      focusGrip(focused);
    }
  };

  const handleGripKey = (modelId: string, event: React.KeyboardEvent<HTMLButtonElement>) => {
    const index = movableIds.indexOf(modelId);
    if (index < 0) return;
    if (event.key === ' ') {
      event.preventDefault();
      if (grabbedId === modelId) {
        grabbedFrom.current = null;
        setGrabbedId(null);
        announce('dropped', modelId);
      } else {
        grabbedFrom.current = movableIds;
        setGrabbedId(modelId);
        announce('grabbed', modelId);
      }
      return;
    }
    if (event.key === 'Escape' && grabbedId === modelId) {
      event.preventDefault();
      event.stopPropagation();
      cancelGrab();
      return;
    }
    if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return;
    event.preventDefault();
    const delta = event.key === 'ArrowUp' ? -1 : 1;
    if (grabbedId === modelId) {
      const next = movedOrder(movableIds, index, delta);
      if (sameIds(next, movableIds)) return;
      reorderMovable(next);
      announce('moved', modelId, next);
      focusGrip(modelId);
      return;
    }
    const neighbour = movableIds[index + delta];
    if (neighbour) focusGrip(neighbour);
  };

  /**
   * A preview of what a focused removal would take with it, from the routes this
   * dialog already holds.
   *
   * With no list behind it, the focused confirmation is asked before any
   * round-trip, so it shows what the baseline already says — but it is a
   * picture, not a plan, and nothing it produces is ever sent. Only the server
   * states the consequences of a write (C3), and agreeing to this confirmation
   * is agreeing to the removal, so a guard refusal of that save is resent with
   * the server's own plan instead of being asked a second time.
   *
   * The gaps are `null`, not empty: whether a removal strands an Agent is the
   * guard's answer, and this dialog holds no supply to answer it from. Empty
   * would have made `GuardImpact` read 「these models still have another source
   * available」 — a promise about the rest of the Hub, made by the one surface
   * that cannot see it, in the confirmation the user decides on. So the picture
   * shows its hops and says nothing about interruption; the guard refuses with
   * the real gaps before anything commits, and those are what the user is then
   * shown.
   */
  const removalPreview = (modelId: string): GuardPicture => ({
    hops: (baseline?.agent.routes?.[modelId]?.hops ?? []).map((hop, index) => ({
      ...hop,
      backend,
      menu_model: modelId,
      position: index + 1,
    })),
    gaps: null,
  });

  /** The row leaves the draft; its route leaves with it when the list saves,
   *  after the one confirmation the save asks if the server says it has one. */
  const dropModel = (modelId: string) => {
    chosenRef.current.delete(modelId);
    mutate(draftRef.current.filter((entry) => entry.id !== modelId));
  };

  /**
   * The opener's named row, opened on once the catalog has been read.
   *
   * It runs the same two handlers the row's own buttons run, so a handoff and a
   * click are the same act — and it runs at most once per `focus`, because the
   * question it opens (an editor, a removal confirmation) is the user's from
   * that moment on and a re-read must not re-ask it.
   */
  const openFocus = useLatestRef((model: BackendModel) => {
    // With no list behind it, the confirmation is the only place the removal
    // can be answered, so it asks even when no route goes with the row.
    if (focus?.action === 'remove') setRemoving({ modelId: model.id, plan: removalPreview(model.id) });
    else setEditing({ model });
  });
  const focusOpened = React.useRef<CatalogFocus | null>(null);
  React.useEffect(() => {
    if (!open || !focus) { focusOpened.current = null; return; }
    if (!editable || focusOpened.current === focus) return;
    focusOpened.current = focus;
    // A locked row offers neither action in the list, so it offers neither here.
    const model = draftRef.current.find((entry) => entry.id === focus.modelId);
    if (model && !model.locked) openFocus.current(model);
    else setExpanded(true);
  }, [editable, focus, open, openFocus]);
  const direct = focus !== null && !expanded;
  // A list this build cannot write, a read that failed and a save that failed
  // all need the list to explain themselves.
  // A guard question the focused surface did not already answer is asked over
  // the list, where the removal it names can still be undone.
  const needsList = legacy || readState === 'error' || saveFailedKey !== null || guardPlan !== null;
  React.useEffect(() => {
    if (direct && needsList) setExpanded(true);
  }, [direct, needsList]);
  /** A save closes the dialog; a focused opener learns whether its row survived. */
  const closeSaved = () => {
    onClose(focus !== null && !draftRef.current.some((entry) => entry.id === focus.modelId) ? { removed: true } : undefined);
  };

  const commitEdit = (model: BackendModel) => {
    const existing = draft.findIndex((entry) => entry.id === model.id);
    // A row written by hand promises nothing about its suppliers, so an id
    // created here carries no displayed projection into the save. Editing an
    // existing row keeps whatever it already carried: the editor holds its id
    // fixed, so the projection is still about the same addition.
    if (existing < 0) chosenRef.current.delete(model.id);
    // `origin` is how a row was FIRST created, and the server holds it immutable
    // for an id it already stores — so it is read back off the saved list here
    // rather than taken from the editor. Add mode stamps `models_dev` on a
    // typeahead pick and only learns the final id at that moment, so a row the
    // user removed and then re-added by hand arrives claiming a creation path
    // the server will refuse. The saved answer is the one that survives; asking
    // the saved list and not the draft is what keeps a genuinely new row's own
    // creation path intact.
    const saved = (baselineRef.current?.models ?? []).find((entry) => entry.id === model.id);
    const kept = saved ? { ...model, origin: saved.origin } : model;
    mutate(existing >= 0
      ? draft.map((entry, index) => (index === existing ? { ...kept, locked: entry.locked, routeable: entry.routeable } : entry))
      : [...draft, kept]);
    setEditing(null);
  };

  /**
   * Picks, poured into the draft.
   *
   * Each arrives as the agreement itself — the candidate and the suppliers its
   * row displayed — and is stored whole. The server matches the addition at
   * commit time, so this states which projection the user agreed to, and a
   * changed one is re-asked instead of silently seeding a route the picker never
   * displayed (C1). A pick the draft already holds is exactly that re-ask: the
   * refused save left the row alone and left only the agreement undone, so
   * confirming supplies it without rebuilding a row the user may have edited.
   *
   * A seeded id that comes back unpicked has no agreement any more, and this
   * dialog has no way to add a row without one — the picker is where a supplier
   * promise is made, and a pending addition that survived with none would be
   * sent as if it had been written by hand, which is precisely the silent
   * re-send the re-ask exists to prevent. So it leaves the draft with its
   * promise. Never a saved row: a disagreement about suppliers may not delete
   * something the server already holds, and it cannot — a seed only ever names
   * pending additions.
   *
   * 「Confirm none of them」 is therefore the same operation as 「dismiss the
   * re-ask」, and the picker's Cancel is wired to exactly this call with no picks:
   * a re-ask the user walks away from has answered every seeded id with 「not
   * this」, and leaving those rows behind is what let a refused projection be
   * re-sent by the next Save with no way to stop it. An ordinary add has an empty
   * seed, so the same call still means 「nothing happened」.
   *
   * Which ROW an id lands as is not decided here — `draftRowFor` owns that, so a
   * re-added row comes back as the one the user already has rather than as a
   * fresh synthesis of the proposal.
   */
  const addCandidates = (picked: ChosenCandidate[]) => {
    const seed = picking?.seed ?? NO_SEED;
    setPicking(null);
    const confirmed = new Set(picked.map((pick) => pick.candidate.id));
    const saved = new Set((baselineRef.current?.models ?? []).map((model) => model.id));
    const withdrawn = new Set([...seed].filter((id) => !confirmed.has(id) && !saved.has(id)));
    if (picked.length === 0 && withdrawn.size === 0) return;
    for (const id of withdrawn) chosenRef.current.delete(id);
    for (const pick of picked) chosenRef.current.set(pick.candidate.id, pick);
    const held = new Set(draftRef.current.map((model) => model.id));
    const additions = picked
      .filter((pick) => !held.has(pick.candidate.id))
      .map((pick) => draftRowFor(pick.candidate, draftRef.current, baselineRef.current?.models ?? []));
    mutate([...draftRef.current.filter((model) => !withdrawn.has(model.id)), ...additions]);
  };

  /**
   * What the server offers right now, or `null` when that could not be read.
   *
   * A 409 answers a pick, a pick came from the picker, and the picker is only
   * offered where Sources are readable (C4) — so a read that does not arrive
   * here is a failed read, not a role forbidden to take one, and `null` is the
   * whole of what this dialog learned about the offer. The caller decides what
   * to do with not knowing; it may not guess.
   */
  const offeredNow = async (): Promise<Map<string, ModelCandidate> | null> => {
    try {
      return offeredCandidates(await modelsApi.getAgentModelCandidates(backend));
    } catch {
      return null;
    }
  };

  /**
   * The one write this dialog makes.
   *
   * `baseline` + `models` is the whole list settling through a single optimistic
   * merge (C1). The other three fields exist only because two of that merge's
   * consequences are not derivable from the list: `force` answers the route
   * guard, and `expected_suppliers` states, per addition, the projection the
   * picker displayed for it. Only per addition: a row the baseline already holds
   * is not matched again, so a promise about it would describe nothing this
   * write does.
   *
   * The forced arrays are the guard refusal's own, verbatim and in the server's
   * order (C3): the server compares the echo element by element against what it
   * sent, so `confirmed` is only ever a plan the server wrote about this exact
   * write — never one this dialog composed.
   */
  const putBody = (baselineModels: BackendModel[], requested: BackendModel[], confirmed?: GuardPlan): BackendModelsPut => {
    const body: BackendModelsPut = { baseline: baselineModels, models: requested };
    if (confirmed) {
      body.force = true;
      body.would_remove_hops = [...confirmed.hops];
      body.would_interrupt = [...confirmed.gaps];
    }
    const baselineIds = new Set(baselineModels.map((model) => model.id));
    const expected = Object.fromEntries(
      requested.flatMap((model) => {
        const pick = baselineIds.has(model.id) ? undefined : chosenRef.current.get(model.id);
        return pick ? [[model.id, pick.expected_suppliers] as const] : [];
      }),
    );
    if (Object.keys(expected).length > 0) body.expected_suppliers = expected;
    return body;
  };

  /**
   * Save the draft.
   *
   * `agreed` is whether the user has already answered the removal question for
   * this save — the guard dialog's confirm, or the focused removal's own. With
   * it, a guard refusal is resent forced with the server's plan; without it,
   * the refusal opens the one guard dialog. `confirmed` is the plan the forced
   * write echoes, and the plan the user was shown. An agreement given without
   * one is the focused confirmation's, which shows only the hops this dialog
   * can see. Either way it covers only the Agents it showed (`agreementCovers`):
   * a refusal naming any other is asked over the list, never forced past the user.
   *
   * Every resend runs inside this one tracked write, so the promise it returns
   * — and the confirmation surface waiting on it — spans the whole sequence.
   * The guard stays mounted, busy, until the save settles, and only an
   * unanswered refusal leaves it open.
   */
  const save = (agreed = false, confirmed?: GuardPlan): Promise<void> | undefined => {
    const base = baselineRef.current;
    // A pre-catalog server has no baseline to send, so there is nothing this
    // branch could honestly PUT.
    if (!base || base.models === null) return;
    const baselineModels = base.models;
    setSaveFailedKey(null);
    return catalogWrite.track(async () => {
      setGuardPlan(await sendCatalog(baselineModels, agreed, confirmed));
    });
  };

  /** Runs the save to its end; resolves with the question still owed, if any. */
  const sendCatalog = async (
    baselineModels: BackendModel[],
    agreed: boolean,
    confirmed: GuardPlan | undefined,
  ): Promise<GuardPlan | null> => {
    let plan = confirmed;
    for (let resends = 0; ;) {
      const requested = draftRef.current;
      const intent = backendCatalogIntent(baselineModels, requested);
      let echoed: AgentSupply;
      try {
        echoed = await modelsApi.putAgentModels(backend, putBody(baselineModels, requested, plan));
      } catch (error) {
        const failure = apiFailure(error);
        if (failure?.code === CANDIDATES_CHANGED) {
          // Nothing was committed, so there is no list to re-read and nothing to
          // report: the answer is the same question again, and the draft is
          // still the user's. The rows stay exactly as they built them — a
          // context window they widened or a name they wrote is theirs, and
          // rebuilding the row from its candidate would spend those edits to
          // answer a question about suppliers. Only the projection is in doubt,
          // so only the projection waits: it stays as displayed until the re-ask
          // replaces it, which leaves the guard armed rather than granting an
          // agreement the user never gave if they dismiss the picker instead of
          // answering it.
          //
          // The refusal is reconciled HERE, where the evidence arrives, and
          // before anything reopens — so no later path has to remember to undo a
          // projection the server has already refused.
          //
          // What `changed` reports is suppliers, and suppliers are not the
          // question of whether an id is still on offer: a built-in the server
          // still serves with none of them is a legitimate candidate whose route
          // starts empty (C1), so reading an empty list as a withdrawal deletes
          // a row the user may still add. Only one thing withdraws an id — the
          // server no longer offering it — and only a candidates read says that
          // (C4), so the refusal is reconciled against one, taken HERE, because
          // an answer where every pick is withdrawn opens no picker and a read
          // that only the picker performs would never happen.
          //
          // Withdrawn takes the row and the agreement together: the row that
          // disappears and the count that falls are the whole report, and the
          // entry goes with it so nothing is left describing a row this dialog
          // no longer has. An offered id keeps its row and takes the read's own
          // candidate as its agreement — both halves from one read, including an
          // empty supplier list, which re-asks as a row with no chips and saves
          // as an empty promise the server seeds an empty route for. Only picks:
          // a supplier disagreement may not delete a row the server already
          // holds, and one this write promised nothing for is no part of it.
          const saved = new Set(baselineModels.map((model) => model.id));
          const disputed = Object.entries(failure.changedSuppliers)
            .filter(([modelId]) => chosenRef.current.has(modelId) && !saved.has(modelId));
          // A read that failed knows nothing about what is offered, so it
          // withdraws nothing and every disputed pick is asked again, promising
          // the suppliers the refusal itself named — the freshest word there is
          // when the read that would supersede it never arrived. The picker
          // reads on its way in, so a withdrawal invisible here is still caught
          // there; a row deleted on a failed read would be this dialog spending
          // the user's list on its own missing evidence.
          const offered = disputed.length > 0 ? await offeredNow() : null;
          const withdrawn = new Set(
            offered ? disputed.filter(([modelId]) => !offered.has(modelId)).map(([modelId]) => modelId) : [],
          );
          const reask: string[] = [];
          for (const [modelId, suppliers] of disputed) {
            if (withdrawn.has(modelId)) {
              chosenRef.current.delete(modelId);
              continue;
            }
            const fresh = offered?.get(modelId);
            const pick = chosenRef.current.get(modelId);
            if (fresh) chosenRef.current.set(modelId, chosenCandidate(fresh));
            else if (pick) chosenRef.current.set(modelId, { ...pick, expected_suppliers: [...suppliers] });
            reask.push(modelId);
          }
          if (withdrawn.size > 0) mutate(draftRef.current.filter((model) => !withdrawn.has(model.id)));
          if (reask.length > 0) {
            setPicking({ seed: new Set(reask) });
            return null;
          }
          // Nothing left to ask, and the list already shows what changed: a drop
          // is its own answer, and a sentence about it would be this dialog
          // reporting its own edit back to the user. But the save they pressed is
          // still owed — nothing was committed — so it goes again on the reduced
          // list rather than costing them a second press for a withdrawal they
          // did not make. It terminates: every pass either drops at least one
          // pick from the map that `disputed` is drawn from, or asks instead.
          if (withdrawn.size > 0) {
            plan = undefined;
            continue;
          }
          // Nothing to ask and nothing to drop: a refusal about ids this write
          // promised nothing for is not one this dialog can answer, so it keeps
          // the failure sentence below rather than resolving into silence.
        }
        // The route guard. Nothing was committed: the server has stated what
        // this exact write would take with it, and only the user's agreement is
        // missing. A user who already agreed is not asked again — the write goes
        // again echoing the server's plan, even when that plan differs from the
        // one they saw, because what they agreed to was removing these models.
        // An agreement covers only the Agents it showed, so a plan naming any
        // other is asked over the list rather than forced past them.
        // A plan that keeps moving past the bound ends as the refusal below,
        // never as a second question. Otherwise the plan opens the one guard
        // dialog, and the draft stays exactly as the user left it behind it.
        const refusal = failure?.code === MODEL_IN_ROUTE ? failure : null;
        if (refusal && (refusal.wouldRemoveHops.length > 0 || refusal.wouldInterrupt.length > 0)) {
          const next: GuardPlan = { hops: refusal.wouldRemoveHops, gaps: refusal.wouldInterrupt };
          if (!agreed || !agreementCovers(confirmed ?? null, next)) return next;
          if (resends < FORCED_RESENDS) {
            plan = next;
            resends += 1;
            continue;
          }
        }
        // A route that named its failure has decided what it did, and for this
        // endpoint 「decided」 can still mean 「wrote」: the server commits the
        // catalog and only then asks the backend to load it, so `engine_down`
        // names rows that reached the disk and never reached the runtime. That
        // is a failed save with a persisted list behind it, and no re-read can
        // turn it into a success. Only an answer this client never got to read
        // leaves the outcome genuinely unknown — and only that may be settled by
        // reading the server's own catalog back.
        const decided = failure?.serverNamed === true;
        const unloaded = decided && catalogSaveLeftUnloaded(failure?.code, failure?.detail);
        const reason = decided
          ? catalogSaveFailureKey(failure?.detail)
          : 'settings.models.gateway.catalog.saveFailed';
        try {
          const observed = await readBackendCatalogBaseline(modelsApi, backend);
          const current = observed.models;
          const landed = current !== null && backendCatalogIntentApplied(current, intent);
          if (current && landed && !decided) {
            applyBaseline(observed, current);
            await Promise.resolve(onSaved(observed.agent)).catch(() => {});
            closeSaved();
            return null;
          }
          applyBaseline(observed, current ? applyBackendCatalogIntent(current, intent) : []);
          await Promise.resolve(onObserved(observed.agent)).catch(() => {});
          // Stored and out of use at the same time, and only for the code that
          // can leave a list that way: a validation or conflict refusal keeps
          // its own sentence even when the re-read happens to agree with the
          // draft, because that write never landed at all.
          setSaveFailedKey(landed && unloaded ? 'settings.models.gateway.catalog.saveNotApplied' : reason);
          return null;
        } catch {
          setReadState('error');
        }
        setSaveFailedKey(reason);
        return null;
      }
      await Promise.resolve(onSaved(echoed)).catch(() => {});
      closeSaved();
      return null;
    }
  };

  const rowActions = (model: BackendModel) => (
    <div className="flex shrink-0 items-center gap-1.5">
      <button
        type="button"
        className="model-hub-catalog-action"
        aria-label={t('settings.models.gateway.catalog.edit', { model: model.display_name ?? model.id }) as string}
        disabled={busy}
        onClick={() => setEditing({ model })}
      >
        <Pencil className="size-[15px]" aria-hidden="true" />
      </button>
      <button
        type="button"
        className="model-hub-catalog-action model-hub-catalog-action--danger"
        aria-label={t('settings.models.gateway.catalog.remove', { model: model.display_name ?? model.id }) as string}
        disabled={busy}
        onClick={() => dropModel(model.id)}
      >
        <Trash2 className="size-[15px]" aria-hidden="true" />
      </button>
    </div>
  );

  const rowBody = (model: BackendModel) => {
    const renderedLabel = displayLabel(model);
    return (
      <span className="flex min-w-0 flex-1 flex-col">
        <span className="model-hub-catalog-name truncate">{renderedLabel}</span>
        {renderedLabel !== model.id && <span className="model-hub-catalog-id truncate font-mono">{model.id}</span>}
      </span>
    );
  };

  return (
    <>
      <Dialog
        open={open && !direct}
        onOpenChange={(next) => { if (!next && !busy) onClose(); }}
      >
        <DialogContent
          mobileSheetHeight="tall"
          closeLabel={t('common.close') as string}
          className="model-hub-catalog-dialog flex h-[min(642px,calc(100dvh-32px))] w-[min(680px,calc(100vw-32px))] max-w-[680px] 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 max-md:p-0 max-md:pt-2"
          onEscapeKeyDown={(event) => { if (busy || grabbedId) event.preventDefault(); }}
          onPointerDownOutside={(event) => { if (busy) event.preventDefault(); }}
        >
          <DialogHeader className="model-hub-catalog-head shrink-0 justify-center border-b border-border">
            <DialogTitle className="model-hub-catalog-title">
              {t('settings.models.gateway.catalog.title', { backend: getBackendUiMeta(backend).label })}
            </DialogTitle>
            <DialogDescription className="sr-only">{t('settings.models.gateway.catalog.description')}</DialogDescription>
          </DialogHeader>

          <div className="model-hub-catalog-body flex min-h-0 flex-1 flex-col">
            <div className="flex min-w-0 shrink-0 flex-col gap-2 sm:flex-row sm:items-center">
              <div className="model-hub-catalog-control model-hub-catalog-search flex min-w-0 flex-1 items-center gap-2">
                <Search className="size-4 shrink-0 text-muted" aria-hidden="true" />
                <Input
                  variant="bare"
                  value={query}
                  onChange={(event) => setQuery(event.target.value)}
                  placeholder={t('settings.models.gateway.catalog.search') as string}
                  aria-label={t('settings.models.gateway.catalog.search') as string}
                  className="min-w-0 flex-1 text-[12.5px]"
                  disabled={!editable || busy}
                />
              </div>
              {/* One action for both paths. The picker offers what this backend
                  and the user's providers already have, and hands off to the
                  editor for anything they do not — so 「add a model」 is one
                  decision with a fallback, not two entry points the user has to
                  choose between up front. It reads Sources, so it is offered
                  only where the page's other Source-reading surfaces are. */}
              {canReadSources && (
                <Button
                  type="button"
                  variant="brand"
                  className="model-hub-catalog-control shrink-0 rounded-md px-4 text-[12.5px]"
                  disabled={!editable || busy}
                  onClick={() => setPicking({ seed: NO_SEED })}
                >
                  <Plus aria-hidden="true" />
                  {t('settings.models.gateway.catalog.add')}
                </Button>
              )}
            </div>

            {ready && (draft.length > 0 || legacyIds.length > 0) && (
              <div className="model-hub-catalog-columns flex shrink-0 items-center justify-between">
                <span>{t('settings.models.gateway.catalog.columnModel')}</span>
                <span>{legacy ? t('settings.models.gateway.catalog.columnState') : t('settings.models.gateway.catalog.columnActions')}</span>
              </div>
            )}

            <div className="min-h-0 flex-1 overflow-y-auto">
              {!ready ? (
                <div className="flex flex-col items-center gap-3 px-4 py-12 text-center text-[12.5px] text-muted">
                  {readState === 'loading' ? (
                    <LoaderCircle className="size-5 animate-spin" aria-hidden="true" />
                  ) : (
                    <>
                      <p>{t('settings.models.gateway.catalog.baselineUnavailable')}</p>
                      <Button type="button" variant="outline" size="sm" onClick={() => loadBaseline(true)}>
                        {t('settings.models.gateway.retry')}
                      </Button>
                    </>
                  )}
                </div>
              ) : legacy ? (
                <div className="flex flex-col gap-2">
                  <p className="model-hub-catalog-legacy">{t('settings.models.gateway.catalog.legacy')}</p>
                  {legacyIds.map((modelId) => (
                    <div key={modelId} className="model-hub-catalog-row model-hub-catalog-row--static flex min-w-0 items-center gap-3">
                      <span className="model-hub-catalog-name min-w-0 flex-1 truncate font-mono">{modelId}</span>
                    </div>
                  ))}
                </div>
              ) : visible.length === 0 ? (
                <p className="px-1 py-10 text-center text-[12.5px] text-muted">
                  {t(filtering ? 'settings.models.gateway.catalog.noMatch' : 'settings.models.gateway.catalog.empty')}
                </p>
              ) : (
                <Reorder.Group
                  axis="y"
                  as="ul"
                  values={movableIds}
                  onReorder={reorderMovable}
                  className="flex list-none flex-col gap-[var(--model-hub-catalog-row-gap)] p-0"
                >
                  {visible.map((model) => (
                    model.locked
                      ? (
                        <li key={model.id} className="model-hub-catalog-row model-hub-catalog-row--locked flex min-w-0 flex-col justify-center">
                          <div className="flex min-w-0 items-center gap-3">
                            <Lock className="model-hub-catalog-grip-icon shrink-0" aria-hidden="true" />
                            {rowBody(model)}
                            <span className="model-hub-pill model-hub-fill-0a shrink-0 border border-border text-muted">
                              {t('settings.models.gateway.catalog.lockedBadge')}
                            </span>
                          </div>
                        </li>
                      )
                      : (
                        <CatalogRow
                          key={model.id}
                          model={model}
                          grabbed={grabbedId === model.id}
                          draggable={!filtering && !busy}
                          registerGrip={(node) => {
                            if (node) grips.current.set(model.id, node);
                            else grips.current.delete(model.id);
                          }}
                          onGripKeyDown={(event) => handleGripKey(model.id, event)}
                          body={rowBody(model)}
                          actions={rowActions(model)}
                        />
                      )
                  ))}
                </Reorder.Group>
              )}
            </div>
            <p aria-live="polite" className="sr-only">
              {announcement ? t(`settings.models.gateway.catalog.${announcement.key}`, announcement) : ''}
            </p>
          </div>

          <DialogFooter className="model-hub-catalog-foot shrink-0 items-center border-t border-border sm:justify-between">
            <div className="flex min-w-0 flex-col gap-0.5">
              <span className="model-hub-catalog-count">
                {t('settings.models.gateway.modelCount', { count: legacy ? legacyIds.length : draft.length })}
              </span>
              {saveFailedKey && (
                <span className="model-hub-catalog-blocked" role="status">{t(saveFailedKey)}</span>
              )}
            </div>
            <div className="flex w-full flex-col-reverse gap-2 sm:w-auto sm:flex-row">
              <Button
                type="button"
                variant="outline"
                className="model-hub-catalog-control rounded-md px-5 text-[12.5px] font-semibold"
                onClick={() => onClose()}
                disabled={busy}
              >
                {t('settings.models.gateway.catalog.cancel')}
              </Button>
              <Button
                type="button"
                variant="brand"
                className="model-hub-catalog-control rounded-md px-5 text-[12.5px] font-semibold"
                onClick={() => void save()}
                disabled={!editable || (!dirty && !retryable) || busy}
              >
                {busy && <LoaderCircle className="animate-spin" aria-hidden="true" />}
                {t(busy ? 'settings.models.gateway.catalog.saving' : 'settings.models.gateway.catalog.save')}
              </Button>
            </div>
          </DialogFooter>
          {/* Portals keep their visual layers, but must be descendants of this
              content so Radix treats their delayed touch clicks as inside. */}
          {picking && (
            <BackendModelPickerDialog
              open
              backend={backend}
              listedIds={offerable(takenIds, picking.seed)}
              seedPicked={picking.seed}
              // 「Add none of these」 — the same answer as confirming with nothing
              // picked, and the same call, because a re-ask the user dismisses has
              // declined every id it seeded. An ordinary add seeds nothing, so this
              // still just closes.
              onCancel={() => addCandidates([])}
              onAdd={addCandidates}
              // The editor is the other door an id becomes a row through, so leaving
              // by it answers this picker's two standing questions in the same order
              // every other exit answers them, through the same call.
              //
              // `addCandidates([])` first, for the same reason Cancel makes that
              // call: walking out through the editor confirms none of a re-ask's
              // seeded ids, and a seeded projection this dialog keeps is one the
              // next Save would send as if it had been agreed.
              //
              // Then the id, resolved BEFORE the row lookup and through the rule the
              // editor itself commits under (`backendModelId`, which `draftWithId`
              // applies there). The lookup is a total function of the id, so the id
              // it is asked about has to be the one the row would be saved as: asked
              // about a typed `foo` it finds the user's saved `foo`,
              // and the editor — resolving the id only on commit — would then write
              // a blank row onto it, dropping the limits, modalities, capabilities
              // and name they had described. The resolver is idempotent, so the
              // editor re-applying it to this seed changes nothing.
              onCustom={(typed) => {
                addCandidates([]);
                const seedId = backendModelId(typed);
                const existing = heldRowFor(seedId, draftRef.current, baselineRef.current?.models ?? []);
                setEditing(existing ? { model: existing } : { model: null, seedId });
              }}
            />
          )}

          {editing && (
            <BackendModelEditorDialog
              open
              backend={backend}
              model={editing.model}
              seedId={editing.seedId}
              takenIds={takenIds}
              effortSuggestions={effortSuggestions}
              onCancel={() => setEditing(null)}
              onCommit={commitEdit}
            />
          )}

          {/* The save's one question. Cancel leaves the draft as the user left
              it, so a removal they reconsider is re-added from the list and a
              save they abandon is abandoned with the dialog's own Cancel. */}
          <GuardDialog
            open={guardPlan !== null}
            title={t('settings.models.gateway.catalog.guardTitle')}
            // With no route hops, the plan is only the Agents that still select a
            // removed row, so the route sentence would describe nothing it shows.
            subtitle={guardPlan && guardPlan.hops.length === 0
              ? t('settings.models.gateway.catalog.guardSubtitleInUse')
              : t('settings.models.gateway.catalog.guardSubtitle')}
            confirmLabel={t('settings.models.guard.confirm.removeModel')}
            busy={busy}
            onCancel={() => setGuardPlan(null)}
            onConfirm={() => { if (guardPlan) void save(true, guardPlan); }}
          >
            {guardPlan && <GuardImpact hops={guardPlan.hops} gaps={guardPlan.gaps} sourceNames={sourceNames} />}
          </GuardDialog>
        </DialogContent>
      </Dialog>
      {open && direct && (editing ?? savingEdit) && (
        <BackendModelEditorDialog
          open
          backend={backend}
          model={(editing ?? savingEdit)!.model}
          seedId={(editing ?? savingEdit)!.seedId}
          takenIds={takenIds}
          effortSuggestions={effortSuggestions}
          busy={busy || savingEdit !== null}
          onCancel={() => onClose()}
          onCommit={(model) => {
            // With no list behind it, the editor is the only thing on screen,
            // so it stays — inert — until the write it started settles.
            setSavingEdit(editing);
            commitEdit(model);
            const pending = save();
            if (pending) void pending.finally(() => setSavingEdit(null));
            else setSavingEdit(null);
          }}
        />
      )}
      {open && direct && (removing ?? answered) && (() => {
        const asked = (removing ?? answered)!;
        const row = draft.find((entry) => entry.id === asked.modelId);
        return (
          <ConfirmDialog
            open
            destructive
            onOpenChange={(next) => { if (!next && !busy) onClose(); }}
            title={t('settings.models.gateway.catalog.removeTitle', { model: row ? displayLabel(row) : asked.modelId })}
            confirmLabel={t('settings.models.gateway.catalog.removeConfirm') as string}
            cancelLabel={t('settings.models.gateway.catalog.cancel') as string}
            confirmDisabled={busy}
            onConfirm={() => {
              // This confirmation is the removal's one question, so the save
              // it starts is already agreed: a guard refusal is resent with
              // the server's plan rather than asked again.
              setAnswered(asked);
              dropModel(asked.modelId);
              return save(true)?.finally(() => setAnswered(null));
            }}
          >
            {(asked.plan.hops.length > 0 || (asked.plan.gaps?.length ?? 0) > 0) && (
              <div className="model-hub-catalog-consequence" role="alert">
                <GuardImpact hops={asked.plan.hops} gaps={asked.plan.gaps} sourceNames={sourceNames} />
              </div>
            )}
          </ConfirmDialog>
        );
      })()}
    </>
  );
};

const CatalogRow: React.FC<{
  model: BackendModel;
  grabbed: boolean;
  draggable: boolean;
  registerGrip: (node: HTMLButtonElement | null) => void;
  onGripKeyDown: (event: React.KeyboardEvent<HTMLButtonElement>) => void;
  body: React.ReactNode;
  actions: React.ReactNode;
}> = ({ model, grabbed, draggable, registerGrip, onGripKeyDown, body, actions }) => {
  const { t } = useTranslation();
  const controls = useDragControls();
  return (
    <Reorder.Item
      value={model.id}
      dragListener={false}
      dragControls={controls}
      className="model-hub-catalog-row flex min-w-0 list-none flex-col justify-center"
    >
      <div className="flex min-w-0 items-center gap-3">
        <button
          ref={registerGrip}
          type="button"
          aria-label={t('settings.models.gateway.catalog.reorder', { model: model.display_name ?? model.id }) as string}
          aria-grabbed={grabbed}
          disabled={!draggable}
          onPointerDown={(event) => { if (draggable) controls.start(event); }}
          onKeyDown={onGripKeyDown}
          className={cn(
            'model-hub-catalog-grip cursor-grab active:cursor-grabbing disabled:cursor-not-allowed',
            grabbed && 'is-grabbed',
          )}
        >
          <GripVertical className="model-hub-catalog-grip-icon" aria-hidden="true" />
        </button>
        {body}
        {actions}
      </div>
    </Reorder.Item>
  );
};

export default BackendModelCatalogDialog;