A local-first multi-agent app development platform, built on PenguinHarness
/**
* Model config page.
*
* Model entries are persisted as two independent fields, `provider` and `model_id`;
* the (provider, model_id) pair is the entry's unique key — **zero
* concatenation** anywhere in the pipeline, `model_id` is sent to AgentHub verbatim as the
* upstream request id. The dialog's identity section = (group dropdown, upstream id input);
* changing either one is a rename, submitted as a paired `renamedFrom` (the server uses it
* to migrate the credential and pointers).
*
* The list is purely for "finding a model": grouped by vendor (group header = logo + vendor
* name + count + the collapse chevron), with one card per model within a group — the card
* shows only the display name + status badges (default / vision / fast / free / discount), while
* context, pricing, and key status are folded into a single line of small text. Clicking a card opens the config dialog
* (credentials, context, pricing, vision toggle, plus set as default / set as vision model /
* delete). The group header's right side holds the group's actions in a fixed order
* (group-header.ts): its balance (pin and refresh before the amount, a divider after it),
* Connect with its status, Enter key, the speed test, and — on the groups that take
* hand-added models (custom, vLLM, user-defined) — Add model, which reuses the same dialog
* with that group pre-filled. The protocol follows group semantics: custom / user-defined
* groups pick or detect it, a group that pins one (vLLM) hands it to every entry. The "get
* model id / API key" external links sit next to the corresponding input's label in the
* dialogs, never in the header. Nothing is pitched above the groups: a group carries its own
* Connect action (with a status dot), and that is the one entry to authorizing it. The group
* list ends with an "add group" action (user-defined
* groups share custom's semantics; the group appears once the first model saves successfully —
* groups are carried by the model entry's provider field, not persisted separately). The
* header also holds an owner-only "sync presets" action next to the search box (union-merge
* with the built-in catalog, see catalog-sync.ts).
*
* Saving does a PUT full-table replace (models not present are deleted; an empty apiKey
* means keep the existing value); only the owner can edit.
*/
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { DragEvent as ReactDragEvent, ReactNode } from "react";
import type {
CredentialInfo,
ModelProtocolDetectRequest,
ModelRefDto,
ModelsResponse,
ModelsUpdateRequest,
ModelTestRequest,
ModelUpdateEntry,
ModelVisionDetectRequest,
VaultEntryInfo,
} from "@adelie/server/api";
import {
Button,
Checkbox,
Chevron,
ConfirmModal,
EmptyState,
FieldError,
FieldLabel,
GlyphIcon,
ICONS,
ICON_SIZE,
Input,
Link,
Modal,
NoticeStrip,
PageFrame,
PageHeader,
PasswordInput,
ProviderLogo,
Segmented,
Select,
SkeletonList,
Spinner,
Switch,
TodoNotice,
buttonClass,
toastError,
toastInfo,
toastSuccess,
} from "@adelie/ui";
import * as api from "../../api/endpoints";
import { ApiError } from "../../api/client";
import { S } from "../../lib/strings";
import { apiErrorText, refusalText } from "../../lib/api-error";
import { useDocumentTitle } from "../../lib/use-document-title";
import { useProject } from "../../state/project";
import { useAuth } from "../../state/auth";
import { USD_TO_CNY, useTheme } from "../../state/theme";
import type { Currency } from "../../state/theme";
import { AiCreateModal } from "../ai-create";
import { AiCreateButtons } from "../ai-create/ai-create-buttons";
import { formatDateTime, humanizeTokens } from "../../lib/format";
import {
MODEL_PROVIDERS,
PENGUIN_GO_PROVIDER_ID,
canonicalClientType,
catalogEntryFor,
fastModeProtocol,
isAddableGroup,
modelHomepageUrl,
providerClientType,
providerEnvFallbackKey,
providerInfo,
unroutableVendorModel,
} from "@adelie/core/model-catalog";
import type {
FastModeProtocol,
ModelProviderBridgeAuth,
ModelProviderInfo,
} from "@adelie/core/model-catalog";
import {
allGroupKeys,
discountedPrice,
fractionOff,
groupModelRows,
hasConfiguredKey,
isFreeModel,
sameModelRef,
userProviderInfo,
} from "./model-grouping";
import {
commitModelGroupOrder,
loadModelGroupOrder,
saveModelGroupOrder,
} from "./model-group-order";
import { TAG_INK, TAG_SHAPE, modelTags } from "./model-tags";
import { protocolPathForModel } from "./protocol-path";
import { ProtocolSuffixMenu } from "./protocol-suffix";
import {
DEFAULT_CUSTOM_CLIENT_TYPE,
detectableBaseUrl,
displayWidthCh,
envHintKeyFor,
isCustomLikeGroup,
isGenericProtocolClientType,
needsProtocolDetectOnSave,
protocolForPersist,
protocolSelectorValue,
} from "./protocol-types";
import type { ProtocolClientType } from "./protocol-types";
import {
isGroupExpanded,
loadExpandedProviders,
saveExpandedProviders,
toggleExpandedProvider,
} from "./model-group-expansion";
import { clearDraftModelRef } from "../chat/draft-cache";
import { syncRowsWithCatalog } from "./catalog-sync";
import { useUpdateBadges } from "../../lib/use-update-badges";
import { dismissTodo } from "../../lib/todo-dismissals";
import { noticeCounts } from "../../lib/bulk-update";
import { refreshProjectTodos } from "../../lib/use-project-todos";
import { buildImportedRows } from "./group-import";
import { groupImportRefusal } from "./group-import-refusal";
import { tpsTone, ttftTone } from "./speed-test";
import type { SpeedResult, SpeedTone } from "./speed-test";
import { toneDot, toneInk } from "../../lib/tone";
import { KeyAuthDialog } from "./key-auth-dialog";
import type { KeyAuthTexts } from "./key-auth-dialog";
import {
HEADER_BUTTON,
HEADER_LABEL,
HEADER_SQUARE,
HEADER_TEXT,
dividerAfterBalance,
groupHeaderActions,
groupKeyFromEnv,
groupKeyStored,
} from "./group-header";
import type { GroupHeaderAction } from "./group-header";
import { GroupBalance } from "./group-balance";
import { isPinned, usePinnedBalance } from "./balance";
import { refusalOf } from "./write-outcome";
import type { WriteOutcome } from "./write-outcome";
import { modelTestRefusal } from "./model-test-refusal";
import type { ModelTestAnswer } from "./model-test-refusal";
import { detectProtocolRefusal } from "./detect-refusal";
import type { DetectPress } from "./detect-refusal";
import { visionProbeRefusal } from "./vision-refusal";
/**
* The authorization flows a group's Connect dialog can run, keyed by the flow named in that
* group's catalog descriptor. Everything the two differ in lives here — the four
* endpoint calls and the copy — because everything else about the dialog is shared, and a
* group picks its entry by carrying `bridgeAuth` rather than by being named in this file.
*/
const KEY_AUTH: Record<
ModelProviderBridgeAuth["flow"],
{ endpoints: api.KeyAuthEndpoints; texts: KeyAuthTexts }
> = {
"penguin-go": {
endpoints: api.platformAuthEndpoints,
texts: {
intro: S.models.platformKeyIntro,
appliedBody: S.models.platformKeyAppliedBody,
errors: S.models.platformKeyErrors,
},
},
modelscope: {
endpoints: api.modelScopeAuthEndpoints,
texts: {
intro: S.models.modelScopeKeyIntro,
appliedBody: S.models.modelScopeKeyAppliedBody,
errors: S.models.modelScopeKeyErrors,
},
},
};
/** Display currency follows the user setting (pricing is always stored in USD/million tokens; conversion happens only for display and input). */
const CURRENCY_SYMBOL: Record<Currency, string> = { USD: "$", CNY: "¥" };
/** Trailing-zero-trimmed price storage value (keeps up to 6 decimal places, for USD persistence). */
function trimNum(v: number): string {
if (!Number.isFinite(v)) return "0";
return String(Math.round(v * 1e6) / 1e6);
}
/** Trailing-zero-trimmed display/input value (keeps up to 4 decimal places): absorbs floating-point noise from USD<->CNY(x7) round trips. */
function trim4(v: number): string {
if (!Number.isFinite(v)) return "0";
return String(Math.round(v * 1e4) / 1e4);
}
/** USD/million-token string -> display string in the selected currency (with symbol). */
function displayPrice(usdStr: string, currency: Currency): string {
const n = Number(usdStr || "0");
const v = currency === "CNY" ? n * USD_TO_CNY : n;
return `${CURRENCY_SYMBOL[currency]}${trim4(v)}`;
}
/** USD storage string -> input string in the selected currency (for edit-form initialization; empty value passes through). */
function usdToInput(usdStr: string, currency: Currency): string {
const t = usdStr.trim();
if (!t) return "";
const n = Number(t);
if (!Number.isFinite(n)) return t;
return currency === "CNY" ? trim4(n * USD_TO_CNY) : trim4(n);
}
/** Input string in the selected currency -> USD storage string (converted before submit; empty/invalid passes through). */
function inputToUsd(inputStr: string, currency: Currency): string {
const t = inputStr.trim();
if (!t) return "";
const n = Number(t);
if (!Number.isFinite(n)) return t;
return currency === "CNY" ? trimNum(n / USD_TO_CNY) : trimNum(n);
}
/**
* The one group-header action glyph this page draws itself (a 24x24 line path), an arrow entering
* a door: authorize with the provider and come back with a key. Add, bulk key, the catalog sync
* and delete read `ICONS.plus`, `ICONS.key`, `ICONS.rotateCw` and `ICONS.trash`.
*/
const SIGN_IN_ICON = "M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4M10 17l5-5-5-5M15 12H3";
/** Speed-test glyphs (24x24 line paths): gauge for the group action, clock = TTFT, zap = TPS. */
const GAUGE_ICON = "M12 14l3.5-3.5M20.49 17A10 10 0 1 0 3.5 17";
const CLOCK_ICON = "M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20ZM12 7v5l3.5 2";
const ZAP_ICON = "M13 2 3 14h9l-1 8 10-12h-9l1-8Z";
/** Metric tone -> text color classes for the card speed badges. */
const TONE_CLASS: Record<SpeedTone, string> = {
green: toneInk.success,
yellow: toneInk.attention,
red: toneInk.danger,
};
/**
* In-page Map key for a paired reference — the same NUL-separated shape the server uses, and
* never persisted. Keys every per-model side table the page holds: speed results, spend totals.
*/
const refMapKey = (provider: string, modelId: string) => `${provider}\u0000${modelId}`;
/**
* Context window (tokens) recorded for a custom or user-group model whose field is left blank.
*
* A million, not the 128000 the rest of the app assumes for an *unknown* window. The two answer
* different questions: the assumption exists so a model with nothing on file still gets a
* conservative compaction threshold, while this is a value the dialog is about to WRITE, on an
* entry the user is adding by hand — and models being added by hand today are large-window ones.
* Guessing low there costs real capacity (the ring reads full, compaction fires early) for a
* model that can hold far more; guessing high costs a number the user narrows once, when the
* endpoint turns out to serve less. Preset entries left blank still mean "unknown" and stay
* blank.
*/
const CUSTOM_CONTEXT_DEFAULT = 1000000;
/** Numeric input filter: context window keeps digits only. */
export function digitsOnly(v: string): string {
return v.replace(/[^\d]/g, "");
}
/** Numeric input filter: pricing keeps digits and **at most one** decimal point. */
export function decimalOnly(v: string): string {
const cleaned = v.replace(/[^\d.]/g, "");
const i = cleaned.indexOf(".");
return i === -1 ? cleaned : cleaned.slice(0, i + 1) + cleaned.slice(i + 1).replace(/\./g, "");
}
/**
* The client type an entry carries after it is moved into `provider`.
*
* A group that pins a protocol takes it unconditionally — that is what the pin means, and
* the entry the user dragged in has to speak what the rest of the group speaks. Moving to
* Custom keeps a generic protocol client type (protocol detection / the in-field picker
* manage those) and otherwise switches to the generic OpenAI Chat Completions client — an
* unroutable or vendor-pinned type must not leak into a custom group. Every other group
* keeps the current value: a first-party group auto-routes by id, and the gateways that
* pin nothing at group level leave their rows on the pin their preset already gave them.
*/
export function clientTypeAfterProviderChange(provider: string, current: string): string {
const pinned = providerClientType(provider);
if (pinned !== undefined) return pinned;
if (provider !== "custom") return current;
return current.trim() !== "" && isGenericProtocolClientType(current) ? current : "openai-chat";
}
/**
* Who asked for a detection run. Only the failure wording differs: a manual run reports a
* failure, a save-triggered one reports the fallback it is proceeding with.
*/
type DetectMode = "manual" | "save";
/**
* What a detection run yields. The server probes neighbouring forms of the URL that was
* typed, so it reports back which one actually served the protocol; `baseUrl` carries that
* form only when it differs from what the field held, i.e. only when the field needs
* correcting.
*/
interface DetectOutcome {
clientType: string;
baseUrl?: string;
}
/** Local edit state for one model row (string-typed for form use; parsed uniformly on save). */
export interface RowState {
/**
* Vendor id (entry field, i.e. group membership): a value not in the catalog list is a
* user-defined group, kept **verbatim** — an operation that only edits the key,
* for instance, must not silently rewrite it to custom; each forms its own group when
* displayed (see model-grouping).
*/
provider: string;
/** Upstream model id (i.e. the stored model_id, sent to AgentHub verbatim). */
modelId: string;
/**
* The identity as loaded (paired reference): differing from the current (provider,
* modelId) in either field means a rename — submitted as a paired renamedFrom, which the
* server uses to migrate the credential and pointers. null for a new entry.
*/
original: ModelRefDto | null;
/**
* What the model is called: the user's own name, or the built-in catalog's. Absent means the
* model has no name (a custom one, or a catalog row loaded before the name was filled in) and
* asks the server to inherit the catalog's; the empty string means a name the user cleared,
* which is a different request — see rowToEntry.
*/
displayName?: string;
/**
* Whether to treat this as a vision model (effective semantics): the server already
* resolves this via "TOML vision annotation -> built-in catalog -> default support";
* preset models are annotated by the catalog, custom models are editable (supported by
* default).
*/
vision: boolean;
/** Environment variable name used as fallback when api_key is empty (given by the server based on catalog/protocol). */
envKey?: string;
/** Masked preview of the env-fallback value (first-party official entries only; the plaintext never leaves the server). */
envKeyMasked?: string;
contextWindow: string;
/** Per-model max output tokens ("" = inherit the Agent setting): caps output per request; user-only, never preset by the catalog. */
maxTokens: string;
/**
* Per-model fast mode (premium faster serving tier, AgentHub `fast_mode`): off by default;
* user-only, never preset by the catalog, editable on every model (preset ones included).
* Models without a fast tier reject requests carrying it, hence the standing hint while ON.
*/
fastMode: boolean;
/**
* AgentHub client protocol. Empty for preset models (auto-routed from the model id) and
* for a NEW custom model, which starts with nothing selected until the user picks from
* the base URL field's suffix or a detection run fills it in; gateway groups start on
* their preset pin. Never persisted empty for a custom-like entry — see protocolForPersist.
*/
clientType: string;
/** Price buckets in USD per million tokens: the list price, any promotion kept in `discount`. */
cacheRead: string;
cacheWrite: string;
output: string;
/**
* The running promotion the server reports for this row: a fraction off the list price above
* (0.5 = half price), stored outside the config file and applied when usage is priced. Absent
* when the row has none.
*/
discount?: number;
/**
* Set only by the "sync presets" merge: the row states its catalog promotion on save —
* `discount`, or none to clear one — instead of leaving the server to keep or clear what it
* has stored (see rowToEntry and catalog-sync.ts).
*/
discountDeclared?: boolean;
/** Current base_url input; compared against originalBaseUrl to decide omit/override/clear (null). */
baseUrl: string;
originalBaseUrl: string;
/** Newly entered API key; empty means keep the existing value. */
apiKeyInput: string;
clearApiKey: boolean;
credential?: CredentialInfo;
}
/** The row's current paired reference (the config's unique key). */
export function rowRef(row: Pick<RowState, "provider" | "modelId">): ModelRefDto {
return { provider: row.provider, modelId: row.modelId };
}
/**
* After saving a model config, which entries the defaultModel / visionModel pointers should
* point to (always paired references).
*
* The key case is a **rename** (either provider or model_id changes): if a pointer still
* points at the old reference, what gets submitted is a reference no longer present in
* models, and the server responds with a flat 400 (it validates that defaultModel/
* visionModel must be in models).
*/
export function nextPointers(args: {
/** The paired reference being edited; null for a new model. */
editing: ModelRefDto | null;
/** The paired reference after saving (differing from editing in either field means a rename). */
ref: ModelRefDto;
action: DialogAction;
defaultModel: ModelRefDto | undefined;
visionModel: ModelRefDto | undefined;
}): { defaultModel: ModelRefDto | undefined; visionModel: ModelRefDto | undefined } {
const { editing, ref, action, defaultModel, visionModel } = args;
const isNew = editing === null;
const renamedFrom = !isNew && !sameModelRef(editing, ref) ? editing : null;
const follow = (p: ModelRefDto | undefined) => (sameModelRef(p, renamedFrom) ? ref : p);
return {
defaultModel:
action === "setDefault"
? ref
: // The first model added (when there was no previous default) is auto-set as default.
isNew && !defaultModel
? ref
: follow(defaultModel),
visionModel: action === "setVisionModel" ? ref : follow(visionModel),
};
}
/** Fields in the config dialog that can be highlighted red on error (keys match RowState field names, so they can be cleared per edit action). */
type FieldErrors = Partial<
Record<
"modelId" | "baseUrl" | "contextWindow" | "maxTokens" | "cacheRead" | "cacheWrite" | "output",
string
>
>;
/**
* Preset model (present in the built-in catalog): id and vision annotation are read-only,
* only credentials/pricing/context are configurable. Determined by the built-in catalog
* (not by vendor group): a model added via a group header belongs to that vendor group but
* isn't in the catalog, so it's still treated as a custom model when edited (vision is
* checkable, base URL is required, an empty context falls back to the default). Matches
* the catalog using the **identity as loaded** (original's paired reference).
*/
function isPreset(row: RowState): boolean {
return (
row.original !== null &&
catalogEntryFor(row.original.provider, row.original.modelId) !== undefined
);
}
/**
* What to tell the owner of an entry its vendor group cannot route — `null` when there is
* nothing wrong with it. The two answers are different advice, and giving the wrong one is
* worse than giving none:
*
* - `"sync"` — the catalog knows this exact `(provider, model_id)` pair, so this is a
* built-in model whose stored entry predates the protocol the catalog now pins for it
* (`deepseek-flash` is the live example: AgentHub routes DeepSeek on a substring its
* released id no longer carries, so the preset pins `deepseek-v4`, and a Project written
* before that pin holds the row without it). Syncing presets writes the pin back. Telling
* this owner to move a built-in model into a custom group would send them away from the
* one action that fixes it.
* - `"custom"` — the catalog does not know it, so it was added by hand into a group that
* carries built-in models only, and it belongs under a custom group where a protocol can
* be picked or detected.
*
* Judged on the CURRENT reference rather than the identity as loaded (isPreset): an id the
* user has just retyped is not the catalog's row any more, and a sync would not touch it.
*/
export function unroutableFix(
provider: string,
modelId: string,
clientType: string,
): "sync" | "custom" | null {
if (!unroutableVendorModel(provider, modelId, clientType)) return null;
return catalogEntryFor(provider, modelId.trim()) !== undefined ? "sync" : "custom";
}
/**
* Whether this row already has (or will have, after this edit) an API key: the shared
* hasConfiguredKey rule — a stored key or an env fallback the server proved is set — plus the two
* edit-only notions the DTO shape cannot carry. A key typed into the dialog counts before it is
* saved, and `clearApiKey` drops the **stored** key only: an environment variable cannot be
* cleared from here, so an env-backed row keeps its key through a clear.
*/
export function hasKey(row: RowState): boolean {
if (row.clearApiKey) return hasConfiguredKey({ ...row, credential: undefined });
return row.apiKeyInput.trim() !== "" || hasConfiguredKey(row);
}
/**
* The model card's key status line, most specific first: a stored key (not being cleared) shows
* its mask; a key typed but not yet saved has no mask of its own and just reads as configured;
* otherwise a detected first-party env fallback shows that variable's value under the same mask
* (the server reports envKeyMasked for official vendor entries only), so an env-backed row reads
* like a configured one. hasKey guards the whole ladder, so the card and the chat model picker can
* never disagree about which rows count as "not configured".
*/
export function keyStatusText(row: RowState): string {
if (!hasKey(row)) return S.models.noKey;
if (row.credential?.apiKeyMasked && !row.clearApiKey) return row.credential.apiKeyMasked;
if (row.apiKeyInput.trim() !== "") return S.models.keyConfigured;
return row.envKeyMasked ?? S.models.keyConfigured;
}
/**
* A counter that advances on every clock hour, for prices that change with the time of day.
*
* DeepSeek's off-peak rate starts and ends on the hour, and every window a catalog schedule can
* express is hour-aligned, so waking once an hour is enough to keep a card honest — a page left
* open at 08:59 would otherwise still be promising half price at 09:05. It re-aims at the next
* hour each time rather than running on a fixed interval, so it neither drifts nor fires 60
* times to catch one transition.
*/
function useHourTick(): number {
const [tick, setTick] = useState(0);
useEffect(() => {
let timer: ReturnType<typeof setTimeout>;
const schedule = (): void => {
const now = new Date();
const next = new Date(now);
next.setMinutes(0, 0, 0);
next.setHours(next.getHours() + 1);
timer = setTimeout(() => {
setTick((n) => n + 1);
schedule();
}, next.getTime() - now.getTime());
};
schedule();
return () => clearTimeout(timer);
}, []);
return tick;
}
/**
* What to call a model in prose — its display name, or its upstream id when it has none.
*
* The blank test is `trim()`, not `!== undefined`: the display name is optional and the dialog
* clears it to an empty string, so `displayName ?? modelId` would quote an empty name back at
* the user — which is how a save confirmation came to read 「」.
*/
export function modelLabelOf(displayName: string | undefined, modelId: string): string {
return displayName?.trim() || modelId;
}
/**
* What to store for one price bucket on submit: the value as typed, or — when the field still
* holds exactly what was loaded into it — the stored number byte for byte.
*
* Loading rounds the stored USD to four decimals so it is typeable (`usdToInput`), so
* re-encoding an untouched field would commit that rounding as the new price: a silent edit of
* a number nobody changed. Small, but not nothing — a catalog row listed at CNY 0.05 per
* million lands on $0.0071 instead of $0.00714285…, which is a price change: the save would
* cancel the row's promotion, and a scheduled row would leave the catalog's peak price and
* lose its off-peak mark. Editing the field is what makes the typed value authoritative.
*/
export function priceToSubmit(
formValue: string,
storedUsd: string | undefined,
currency: Currency,
): string {
if (
storedUsd !== undefined &&
storedUsd !== "" &&
formValue.trim() === usdToInput(storedUsd, currency)
) {
return storedUsd;
}
return inputToUsd(formValue, currency);
}
/** DTO -> row edit state (exported for unit tests): provider and modelId are both entry fields, never decomposed. */
export function toRow(m: ModelsResponse["models"][number]): RowState {
const row: RowState = {
provider: m.provider,
modelId: m.modelId,
original: { provider: m.provider, modelId: m.modelId },
vision: m.vision !== false,
contextWindow: m.contextWindow !== undefined ? String(m.contextWindow) : "",
maxTokens: m.maxTokens !== undefined ? String(m.maxTokens) : "",
fastMode: m.fastMode === true,
clientType: m.clientType ?? "",
cacheRead: m.pricing ? String(m.pricing.cacheRead) : "",
cacheWrite: m.pricing ? String(m.pricing.cacheWrite) : "",
output: m.pricing ? String(m.pricing.output) : "",
baseUrl: m.credential?.baseUrl ?? "",
originalBaseUrl: m.credential?.baseUrl ?? "",
apiKeyInput: "",
clearApiKey: false,
};
if (m.displayName !== undefined) row.displayName = m.displayName;
if (m.envKey !== undefined) row.envKey = m.envKey;
if (m.envKeyMasked !== undefined) row.envKeyMasked = m.envKeyMasked;
if (m.credential) row.credential = m.credential;
if (m.discount !== undefined) row.discount = m.discount;
return row;
}
/**
* The env-fallback variables the server proved are set (exported for unit tests): it reports
* `envKeyMasked` only for a variable that currently holds a value, and an environment is
* process-wide, so one row carrying it settles the question for every entry reading the same
* variable. A hint may promise "leave this empty and the environment covers it" only for a
* variable in here — elsewhere the page cannot tell a set variable from an absent one, and an
* empty field would leave the model with no key at all.
*/
export function detectedEnvKeys(rows: readonly RowState[]): Set<string> {
const keys = new Set<string>();
for (const row of rows) {
if (row.envKeyMasked !== undefined && row.envKey !== undefined) keys.add(row.envKey);
}
return keys;
}
/**
* Whether the model dialog offers the fast-mode switch for a draft row, and on which protocol
* the parameter would travel.
*
* `protocol` is AgentHub's own answer (see fastModeProtocol): `undefined` means the routed
* client rejects `fast_mode` — or the id routes to no client at all — so arming the switch
* could only produce a turn-killing error, and it is not offered. `show` adds the one
* exception: a row that already stores fast mode keeps its switch regardless, because a
* value that arrived another way (a hand-edited config, `penguin config model add
* --fast-mode`, or an upstream id renamed afterwards) has to remain switchable off — the
* runtime rejection tells the user to turn it off in the model settings, and that has to be
* true. `protocol` also picks the warning copy: only Anthropic's fast mode is a gated
* research preview.
*
* The client type is resolved through protocolForPersist — the one the entry will actually
* be SAVED with — rather than the raw field, for the same reason envHintClientType exists: a
* custom-like group leaves the protocol empty until detection or a manual pick fills it in,
* and fastModeProtocol then falls back to routing by model id. Typing an id that routes to a
* client with no fast tier (`kimi-k3`, `gemini-3-pro`) into a custom group would hide a
* switch that the persisted `openai-chat` entry can in fact serve. An empty result keeps the
* id-based routing the preset and vendor groups genuinely use.
*/
export function fastModeState(
row: Pick<RowState, "provider" | "modelId" | "clientType" | "baseUrl" | "fastMode">,
): { protocol: FastModeProtocol | undefined; show: boolean } {
const protocol = fastModeProtocol(
row.modelId.trim(),
protocolForPersist(row.provider, row.clientType) || undefined,
row.baseUrl.trim() || undefined,
);
return { protocol, show: protocol !== undefined || row.fastMode };
}
/**
* Layout of the dialog's capability row, which carries the vision-support and fast-mode
* switches side by side in the two-up grid.
*
* Neither switch is guaranteed to be there: vision is read-only catalog metadata on preset
* models (no switch at all), and fast mode is withheld wherever the routed client rejects the
* parameter (see fastModeState). So the pair is a coincidence, not an invariant, and the row
* degrades in both directions — with neither switch it must not be rendered at all (an empty
* grid still draws the parent's `space-y` gap), and with exactly one the lone switch spans
* both columns rather than sitting in a half-width cell next to dead space.
*/
export function capabilityRow(present: { vision: boolean; fastMode: boolean }): {
show: boolean;
cellClass: string | undefined;
} {
const both = present.vision && present.fastMode;
return { show: present.vision || present.fastMode, cellClass: both ? undefined : "col-span-2" };
}
/** Row edit state -> wire entry (exported for unit tests): the single funnel into the config PUT. */
export function rowToEntry(row: RowState): ModelUpdateEntry {
// provider and modelId are always submitted as separate fields ((provider, modelId) is the entry's unique key, no concatenation).
const entry: ModelUpdateEntry = { provider: row.provider, modelId: row.modelId };
// Rename (either provider or model_id changing is a key change): include the original paired reference so the server
// migrates the credential and unknown fields (otherwise a full-table replace would drop them).
if (row.original && !sameModelRef(row.original, rowRef(row))) {
entry.renamedFrom = row.original;
}
// Display name: submitted whenever the row carries one at all, the empty string included —
// absent means "inherit whatever the catalog calls this model" and empty means "the user
// cleared it", so a row that simply has no name must not travel as a deletion. The server
// only persists a name that differs from the built-in catalog (keeps preset configs clean).
if (row.displayName !== undefined) entry.displayName = row.displayName.trim();
const cw = Number(row.contextWindow.trim());
if (row.contextWindow.trim() && Number.isFinite(cw)) entry.contextWindow = cw;
// Never persists an empty protocol for a custom-like entry (that entry could not start —
// see protocolForPersist); preset / vendor rows keep "" so AgentHub infers from the id.
const clientType = protocolForPersist(row.provider, row.clientType);
if (clientType) entry.clientType = clientType;
// Supported by default: submit false only when explicitly marked "unsupported" (preset vision models and checked custom models aren't persisted).
if (!row.vision) entry.vision = false;
// Output cap ("" = inherit the Agent setting): submitted only when filled; omitting clears the stored annotation.
const mt = Number(row.maxTokens.trim());
if (row.maxTokens.trim() && Number.isFinite(mt) && mt > 0) entry.maxTokens = mt;
// Off by default: submitted only when enabled (omitting clears the stored annotation; the server never persists false).
if (row.fastMode) entry.fastMode = true;
const cr = Number(row.cacheRead.trim());
const cwr = Number(row.cacheWrite.trim());
const out = Number(row.output.trim());
if (
row.cacheRead.trim() &&
row.cacheWrite.trim() &&
row.output.trim() &&
Number.isFinite(cr) &&
Number.isFinite(cwr) &&
Number.isFinite(out)
) {
entry.pricing = { cacheRead: cr, cacheWrite: cwr, output: out };
}
// Promotion: sent only when the preset sync declared one (a number stores it, null clears it).
// Every other save omits it and leaves the stored promotion to the server, which keeps it
// unless this entry renames the row or changes its price.
if (row.discountDeclared) entry.discount = row.discount ?? null;
if (row.apiKeyInput.trim()) entry.apiKey = row.apiKeyInput.trim();
if (row.clearApiKey) entry.clearApiKey = true;
const baseUrl = row.baseUrl.trim();
if (baseUrl !== row.originalBaseUrl) {
// Submit only on change: non-empty overrides, empty explicitly sets null to clear.
entry.baseUrl = baseUrl ? baseUrl : null;
}
return entry;
}
/**
* Private drag payload type of a provider-group reorder. Deliberately NOT the sidebar's
* group MIME: the sidebar renders alongside this page, so one shared type would let a
* group dragged out of the conversation list paint a drop line here (and vice versa) —
* two unrelated orders that happen to be dragged the same way.
*/
const MODEL_GROUP_DRAG_MIME = "application/x-penguin-model-group";
/**
* Is the drag in flight one of our group reorders? `types` is readable during dragover
* (unlike getData), so the payload authorizes the drop rather than React state alone:
* without it, a `dragGroup` left behind by a header that unmounted mid-drag would make the
* page swallow an unrelated drag, paint a phantom line, and commit on release.
*/
const isModelGroupDrag = (e: ReactDragEvent): boolean =>
e.dataTransfer.types.includes(MODEL_GROUP_DRAG_MIME);
/** Dragging a group needs a pointer that can drag — HTML5 drag-and-drop never fires from touch (the sidebar's query). */
const DRAG_POINTER_QUERY = "(hover: hover) and (pointer: fine)";
export function ModelsPage() {
useDocumentTitle(S.models.title);
const { currentProject, agents } = useProject();
const projectId = currentProject?.projectId ?? null;
const isOwner = currentProject?.role === "owner";
/** The Models trail's raised badge, or undefined — the header's two marks appear with it. */
const todo = useUpdateBadges().todos.models;
/** What the trail says, read at render time: `S` is a live binding swapped on locale change. */
const syncNote = todo ? S.todo.presetUpdates(todo.count) : "";
/** The notice's two counts, both off the delta the sync action itself computes. */
const syncCounts = todo ? noticeCounts(todo) : null;
/** The notice's sync confirmation is open (it lists the refs the delta named). */
const [syncConfirmOpen, setSyncConfirmOpen] = useState(false);
const [syncing, setSyncing] = useState(false);
const userId = useAuth().user?.userId ?? null;
/** Per-model speed results (in-memory, reset on every project switch; "pending" while that model's turn is running). */
const [speedResults, setSpeedResults] = useState<Map<string, SpeedResult | "pending">>(new Map());
/** Group whose speed-test confirmation dialog is open (provider id). */
const [speedFor, setSpeedFor] = useState<string | null>(null);
/** Group currently being speed-tested (provider id); tests run strictly one model at a time. */
const [speedRunning, setSpeedRunning] = useState<string | null>(null);
/**
* The running test was asked to stop. A ref for the loop, which reads it between probes; the
* state mirror disables the stop button meanwhile, since the probe in flight still has to
* come back before the loop can see it.
*/
const speedStopRef = useRef(false);
const [speedStopping, setSpeedStopping] = useState(false);
/** The balance pinned beside the user name, so its group's header keeps the pin to undo it. */
const pinnedBalance = usePinnedBalance();
const [rows, setRows] = useState<RowState[] | null>(null);
const [defaultModel, setDefaultModel] = useState<ModelRefDto | undefined>(undefined);
// Vision model used for read_file's proxy reads (describes images for session models with vision=false).
const [visionModel, setVisionModel] = useState<ModelRefDto | undefined>(undefined);
/** Edit target: paired reference of an existing row. */
const [editing, setEditing] = useState<ModelRefDto | null>(null);
/**
* Whether the dialog about to open should already have moved its row into the custom
* group: set by a card's "move to custom group" action, which is a shortcut into the
* config dialog rather than a write of its own — the move needs a protocol and a base URL,
* and the dialog is where those are picked and confirmed.
*/
const [editingMovedToCustom, setEditingMovedToCustom] = useState(false);
/** Target group (provider id) for adding a model: taken from the group header entry point, falling back to custom when empty. */
const [addingTo, setAddingTo] = useState<string | null>(null);
/**
* Close the config dialog. One helper because the remove action closes it from the write's
* outcome (see `onSubmit`) while cancel closes it on the way out — both must clear the
* three fields that say which entry point opened it.
*/
const closeModelDialog = () => {
setEditing(null);
setEditingMovedToCustom(false);
setAddingTo(null);
};
const [query, setQuery] = useState("");
/**
* Expanded vendor groups — hydrated from this Project's persisted set (DeepSeek-only
* on a first visit; every other group, including user-defined ones arriving with the
* async row load, starts collapsed), written back on every toggle so the user's
* choices survive a refresh. Searching force-opens the rendered groups without
* touching this set (see model-group-expansion.ts).
*/
const [expanded, setExpanded] = useState<Set<string>>(() => loadExpandedProviders(projectId));
// Project resolved on first load / switched: swap in that Project's persisted expansion set.
useEffect(() => {
setExpanded(loadExpandedProviders(projectId));
}, [projectId]);
/**
* This Project's manual group order (empty = the catalog's own sequence). Hydrated and
* re-hydrated exactly like the expansion set above, and written back on every drop.
*/
const [groupOrder, setGroupOrder] = useState<readonly string[]>(() =>
loadModelGroupOrder(projectId),
);
useEffect(() => {
setGroupOrder(loadModelGroupOrder(projectId));
}, [projectId]);
/**
* Whether the reorder gesture is offered at all. A stored order still APPLIES without
* it: the arrangement is per Project and implicit, so there is nothing to degrade —
* a phone renders what its owner arranged at a desk.
*/
const [canDrag, setCanDrag] = useState(() => window.matchMedia(DRAG_POINTER_QUERY).matches);
useEffect(() => {
const mq = window.matchMedia(DRAG_POINTER_QUERY);
const onChange = (e: MediaQueryListEvent) => setCanDrag(e.matches);
mq.addEventListener("change", onChange);
return () => mq.removeEventListener("change", onChange);
}, []);
/** Group header being dragged (its provider id) and the live drop hint (target group + which edge). */
const [dragGroup, setDragGroup] = useState<string | null>(null);
const [groupDropHint, setGroupDropHint] = useState<{ key: string; after: boolean } | null>(null);
/** Vendor group (provider id) currently having its API key configured in bulk. */
const [groupKeyFor, setGroupKeyFor] = useState<string | null>(null);
/** Vendor group (provider id) whose API key is being copied from the account's own user keys. */
const [assignKeyFor, setAssignKeyFor] = useState<string | null>(null);
/** Vendor group (provider id) whose authorization dialog is open (groups that publish a key-minting flow only). */
const [oauthFor, setOauthFor] = useState<string | null>(null);
/** Whether the open authorization actually wrote a key — see the dialog's `onClose`. */
const keyLanded = useRef(false);
/** User-defined group (provider id) whose delete confirmation is open (built-in groups never offer this). */
const [deleteGroupFor, setDeleteGroupFor] = useState<string | null>(null);
/**
* The words of the last refused group delete / preset sync, drawn inside that confirmation
* (`refusal` on the card) so the reason is still there when the user presses retry. Cleared
* when the confirmation opens again: a fresh attempt has not been refused yet.
*/
const [deleteGroupRefusal, setDeleteGroupRefusal] = useState<string | null>(null);
const [syncRefusal, setSyncRefusal] = useState<string | null>(null);
/** "Add group" popup (user-defined group): create-only hands off to that group's add-model dialog, import mode fills the group from its endpoint (see AddGroupDialog). */
const [addGroupOpen, setAddGroupOpen] = useState(false);
/** "Add models with AI" dialog: the prompt goes to the Project's default agent. */
const [aiAddOpen, setAiAddOpen] = useState(false);
/** Initial load failure: shown inline only when the whole page has no content (there's no context to pop a toast against). */
const [loadError, setLoadError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
// Currency follows the user setting (toggled in sidebar settings).
const { currency } = useTheme();
/**
* Lifetime Token total per model, keyed by the paired reference. Fetched on its own rather
* than folded into the model list: it is telemetry hanging off a configuration page, and a
* stats failure must cost the figure, not the page — so the failure path just leaves the map
* empty and every card renders without its number.
*/
const [usedTokens, setUsedTokens] = useState<Map<string, number>>(new Map());
const hourTick = useHourTick();
const load = useCallback(async () => {
if (!projectId) return;
setRows(null);
setLoadError(null);
// Speed results are keyed by (provider, model_id) only, so another Project's identically
// named model would inherit a timing measured against a different endpoint and key —
// drop them along with the rows they annotate whenever the active Project changes.
setSpeedResults(new Map());
try {
const res = await api.getModels(projectId);
setRows(res.models.map(toRow));
setDefaultModel(res.defaultModel);
setVisionModel(res.visionModel);
} catch (e) {
setLoadError(apiErrorText(e));
}
try {
const totals = await api.getUsageModelTotals(projectId);
setUsedTokens(
new Map(totals.totals.map((t) => [refMapKey(t.provider, t.modelId), t.tokens])),
);
} catch {
// Fail-soft, and deliberately silent: the page's job is configuring models, and a figure
// that could not be read is shown as absent rather than as an error the user cannot act on.
setUsedTokens(new Map());
}
}, [projectId]);
useEffect(() => {
void load();
}, [load]);
/**
* Changes save immediately (dialog confirm / set default / set vision model / delete):
* avoids the trap of "still have to click save after confirming". On failure, the error
* is echoed back with the table the caller names (see `refusedRows`), so a retry starts
* from something the server still holds rather than from a change it declined.
*
* The answer is a {@link WriteOutcome}, not a boolean: a refusal carries the server's words so
* the caller can put them in the card that asked for the write (see `refusalOf`). They are not
* raised as a toast here — the two call sites with no card still on screen add the toast
* themselves, and every other one shows the reason where the retry button is.
*/
const persist = async (
nextRows: RowState[],
nextDefault: ModelRefDto | undefined,
nextVision: ModelRefDto | undefined,
/** Success toast text (defaults to "saved"). */
successText?: string,
/**
* The table to leave on the page when the write is refused. Default: the attempted rows,
* which is right for a write made on the page itself (the bulk key for a group). Every
* write made from the config dialog passes the table as it stood instead: its attempted
* rows are what the server declined, and showing them — for the instant before the caller
* restores the real table, or for good — unmounts that dialog, which is gated on its row
* still being in the table, and claims a change that did not happen.
*/
refusedRows?: RowState[],
): Promise<WriteOutcome> => {
// Unreachable through the page (it renders nothing without a Project, and every caller is
// behind that gate). The generic sentence is what a write that never left would report.
if (!projectId) return { ok: false, reason: S.common.unknownError };
setBusy(true);
// The vision model pointer must point to a row that still exists and isn't marked "doesn't support images" (invalidated on delete/re-annotation).
const effectiveVision =
nextVision && nextRows.some((r) => sameModelRef(rowRef(r), nextVision) && r.vision)
? nextVision
: undefined;
try {
const body: ModelsUpdateRequest = { models: nextRows.map(rowToEntry) };
if (nextDefault) body.defaultModel = nextDefault;
if (effectiveVision) body.visionModel = effectiveVision;
const res = await api.putModels(projectId, body);
setRows(res.models.map(toRow));
setDefaultModel(res.defaultModel);
setVisionModel(res.visionModel);
// Default model changed: drop the stored draft's model selection so the draft chat
// follows the new default (a stored pick would otherwise pin the old model forever).
if (userId && res.defaultModel && !sameModelRef(res.defaultModel, defaultModel)) {
clearDraftModelRef(userId, projectId);
}
toastSuccess(successText ?? S.common.saved);
return { ok: true };
} catch (e) {
setRows(refusedRows ?? nextRows);
if (nextDefault !== undefined) setDefaultModel(nextDefault);
if (effectiveVision !== undefined) setVisionModel(effectiveVision);
return { ok: false, reason: apiErrorText(e) };
} finally {
setBusy(false);
}
};
const groups = useMemo(
() => (rows ? groupModelRows(rows, query, groupOrder) : []),
[rows, query, groupOrder],
);
/**
* Every group the library could show, empty built-ins included — the sequence a drop is
* committed against, so a provider currently holding no models keeps its catalog place
* rather than arriving as a newcomer the day one is added to it.
*/
const allKeys = useMemo(() => allGroupKeys(rows ?? []), [rows]);
/** Env-fallback variables the server reported a value for: the only ones a key hint may promise. */
const envKeysDetected = useMemo(() => detectedEnvKeys(rows ?? []), [rows]);
/** Non-empty search query: groups are filtered to matches and force-opened while it lasts. */
const searching = query.trim() !== "";
/**
* "Sync presets": merge the built-in catalog into the current table (union; the catalog wins
* on the facts it tracks about a model, while base URLs, keys and output caps stay as this
* install has them, and local additions are untouched — see catalog-sync.ts). No-op with a
* toast when everything is already up to date.
*
* Returns what the write answered — `ok` for the no-op too, since the table in hand then
* matches the catalog. The notice's confirmation keeps itself open until then and draws the
* refusal inside itself; the toolbar button that runs the same merge has no card to draw it
* in, so that caller raises the toast (`refusalOf`).
*/
const syncPresets = async (): Promise<WriteOutcome> => {
if (!rows) return { ok: false, reason: S.common.unknownError };
const merged = syncRowsWithCatalog(rows);
if (merged.added === 0 && merged.updated === 0) {
toastInfo(S.models.syncUpToDate);
// Re-probe here too: the badge is gated on a cached probe, and an entry brought back into
// line by a hand edit leaves that probe claiming a change this sync has just found none
// of. Without it the notice keeps offering a button that can only answer "already
// up to date" — a loop the user gets out of only by dismissing or reloading.
refreshProjectTodos(projectId);
return { ok: true };
}
// A refused write takes the merge back off the screen. `persist` keeps the attempted rows
// for a field edit the user is still holding, but a preset sync is a batch the catalog
// describes, and those rows are exactly what the server declined: left on screen they make
// the retry compute an empty delta, so it answers "already up to date" without sending
// anything while the notice still names every missing entry (measured on a refused write:
// the retry produced no PUT at all and the server kept its old table).
const before = rows;
const outcome = await persist(
merged.rows,
defaultModel,
visionModel,
S.models.syncDone(merged.added, merged.updated),
);
if (!outcome.ok) setRows(before);
// The Models nav badge is gated on the SAVED table, which this page holds only as row
// state: re-probe it so the dot goes down on the server's answer rather than on the
// assumption that the write covered everything the catalog offered.
refreshProjectTodos(projectId);
return outcome;
};
const syncPlatformModels = async () => {
if (!projectId) return;
setBusy(true);
try {
const res = await api.syncPlatformModels(projectId);
setRows(res.models.map(toRow));
setDefaultModel(res.defaultModel);
setVisionModel(res.visionModel);
if (res.added === 0 && res.updated === 0) toastInfo(S.models.syncUpToDate);
else toastSuccess(S.models.syncDone(res.added, res.updated));
} catch (error) {
if (error instanceof ApiError && error.code === "platform_reauthorization_required") {
keyLanded.current = false;
setOauthFor(PENGUIN_GO_PROVIDER_ID);
} else {
toastError(apiErrorText(error));
}
} finally {
setBusy(false);
}
};
/**
* Group speed test: one real request per model, strictly sequential (concurrent probes
* trip provider rate limits), each result written to the card as it lands. The
* confirmation dialog (speedFor) has already warned about quota by the time this runs.
* A stop takes effect between probes: the one in flight is not abandoned (its request is
* already billed), its result lands like the others, and no further probe starts.
*/
const runSpeedTest = async (providerId: string) => {
if (!projectId || !rows) return;
const targets = rows.filter((r) => r.provider === providerId);
speedStopRef.current = false;
setSpeedRunning(providerId);
try {
for (const row of targets) {
if (speedStopRef.current) break;
const key = refMapKey(row.provider, row.modelId);
setSpeedResults((prev) => new Map(prev).set(key, "pending"));
try {
const res = await api.testModel(projectId, {
provider: row.provider,
modelId: row.modelId,
speed: true,
});
setSpeedResults((prev) => new Map(prev).set(key, res));
} catch (e) {
setSpeedResults((prev) =>
new Map(prev).set(key, {
ok: false,
message: apiErrorText(e),
}),
);
}
}
} finally {
setSpeedRunning(null);
setSpeedStopping(false);
}
};
const stopSpeedTest = () => {
speedStopRef.current = true;
setSpeedStopping(true);
};
/**
* Import-mode landing from the add-group dialog: one table PUT with the appended rows,
* then the new group is opened so the result is visible immediately. The answer is
* persist's own verdict, not a boolean: the dialog stays up with its fields when the save
* was refused, so it is also the card that carries the reason (see `groupImportRefusal`).
*
* A failed save is rolled back to the table as it stood: persist otherwise keeps the
* attempted rows on screen (right for a field edit the user is still holding), which
* here would show the whole group as if it existed and make the dialog's own name check
* report the name as taken on the retry.
*
* The refusal is deliberately not raised as a toast: the dialog that asked is still on
* screen, with the fields the retry sends, and a notification sits over it and leaves after
* six seconds — leaving that dialog looking exactly as it did before the press, with no
* account of why the group is still missing from the page behind it.
*/
const importGroup = async (
nextRows: RowState[],
name: string,
added: number,
skipped: number,
): Promise<WriteOutcome> => {
// Unreachable through the page (it renders nothing without a Project, and the dialog is
// behind that gate). The generic sentence is what a write that never left would report.
if (!projectId) return { ok: false, reason: S.common.unknownError };
const before = rows;
const outcome = await persist(
nextRows,
defaultModel,
visionModel,
S.models.groupImported(added, skipped),
);
if (!outcome.ok) {
setRows(before);
return outcome;
}
if (!expanded.has(name)) {
const next = new Set(expanded);
next.add(name);
setExpanded(next);
saveExpandedProviders(projectId, next);
}
setAddGroupOpen(false);
return outcome;
};
const editingRow =
editing !== null ? rows?.find((r) => sameModelRef(rowRef(r), editing)) : undefined;
if (!projectId) return null;
/**
* Header toggles are inert while searching: every rendered group is force-opened (see
* isGroupExpanded), so a flip would change nothing visibly and only silently mutate the
* state restored once the query clears. Computed outside the state updater (sidebar
* toggleGroup convention): the persistence write is a side effect, and updaters must
* stay pure (double-invoked in StrictMode).
*/
const toggleGroup = (id: string) => {
if (searching) return;
const next = toggleExpandedProvider(expanded, id);
setExpanded(next);
saveExpandedProviders(projectId, next);
};
/**
* Drag-reorder wiring of one group header. Returns the props the header row spreads and
* the edge a drop would land on, or nothing at all when the gesture is not offered:
* without a drag-capable pointer, and while a search query is active — the query filters
* the list to matches, so a drop there would commit an arrangement made against a subset
* the user is about to dismiss.
*/
const groupDragProps = (key: string) => {
if (!canDrag || searching) {
return { header: {}, dropEdge: null as "above" | "below" | null };
}
const dragging = dragGroup;
/** Which half of the header the pointer is in — the edge the drop would land on. */
const edgeOf = (e: ReactDragEvent) => {
const rect = e.currentTarget.getBoundingClientRect();
return e.clientY - rect.top > rect.height / 2;
};
const acceptsDrop = dragging !== null && dragging !== key;
return {
header: {
draggable: true,
onDragStart: (e: ReactDragEvent) => {
// dragstart fires AT the source node, so target === currentTarget exactly when
// the header row itself is what the browser picked up. A drag begun on anything
// inside it that is natively draggable (selected text, a link) belongs to that
// element, and claiming it would overwrite its payload and effect and turn a
// release over any other header into a silent reorder.
if (e.target !== e.currentTarget) return;
e.dataTransfer.setData(MODEL_GROUP_DRAG_MIME, key);
e.dataTransfer.effectAllowed = "move" as const;
setDragGroup(key);
},
onDragEnd: () => {
setDragGroup(null);
setGroupDropHint(null);
},
onDragOver: (e: ReactDragEvent) => {
if (!acceptsDrop || !isModelGroupDrag(e)) return;
e.preventDefault();
// preventDefault alone only says "a drop may land here"; the effect still has to
// be one effectAllowed permits, or a modifier held during the drag resolves it to
// "none" and the drop event never fires.
e.dataTransfer.dropEffect = "move";
const after = edgeOf(e);
setGroupDropHint((prev) =>
prev?.key === key && prev.after === after ? prev : { key, after },
);
},
// dragleave also fires when the pointer merely crosses onto one of the header's OWN
// children — the collapse button spans most of the row, and up to six actions
// follow it — so clearing unconditionally strobes the indicator. relatedTarget is
// where the drag is going: still inside means nothing changed.
onDragLeave: (e: ReactDragEvent) => {
const to = e.relatedTarget;
if (to instanceof Node && e.currentTarget.contains(to)) return;
setGroupDropHint((prev) => (prev?.key === key ? null : prev));
},
onDrop: (e: ReactDragEvent) => {
if (!acceptsDrop || dragging === null || !isModelGroupDrag(e)) return;
e.preventDefault();
const next = commitModelGroupOrder(groupOrder, allKeys, dragging, key, edgeOf(e));
// commitModelGroupOrder hands back its input for a drop that moves nothing: no state
// update, and no freshly allocated identical array written to storage.
if (next !== groupOrder) {
setGroupOrder(next);
saveModelGroupOrder(projectId, next);
}
setDragGroup(null);
setGroupDropHint(null);
},
},
dropEdge:
acceptsDrop && groupDropHint?.key === key
? groupDropHint.after
? ("below" as const)
: ("above" as const)
: null,
};
};
// Which dialog the open authorization runs: the group's descriptor decides, so a group with
// a bridge flow gets the shared bridge dialog and every other authorizable group gets the
// PKCE one. Null means the open group authorizes some other way (or none).
const oauthFlow = oauthFor === null ? undefined : providerInfo(oauthFor)?.bridgeAuth?.flow;
const oauthKeyAuth = oauthFlow === undefined ? null : KEY_AUTH[oauthFlow];
/**
* One of a group header's actions (group-header.ts decides which, and in what order). Every
* button keeps an accessible name of "action group" and a title; on a narrow header the ones
* that carry words drop them and keep their icon.
*/
const renderGroupAction = (
group: (typeof groups)[number],
action: GroupHeaderAction,
keyStored: boolean,
): ReactNode => {
const { provider } = group;
switch (action) {
case "balance":
return <GroupBalance projectId={projectId} provider={provider} />;
case "connect": {
// The status is the group holding a stored key, however it got there; the button
// runs the group's flow again once it does, for a fresh key or another account.
const status = keyStored ? S.models.connectedStatus : S.models.notConnectedStatus;
const verb = keyStored ? S.models.reconnect : S.models.oauthKey;
return (
<span className="flex shrink-0 items-center gap-2">
<span
data-tooltip={status}
className={`${HEADER_TEXT} gap-1 whitespace-nowrap text-gray-500 dark:text-gray-400`}
>
<span
aria-hidden
className={`h-1.5 w-1.5 shrink-0 rounded-full ${keyStored ? toneDot.success : toneDot.muted}`}
/>
{/* The words give way on a narrow header; the dot and its tooltip stay. */}
<span className="sr-only @2xl:not-sr-only">{status}</span>
</span>
{isOwner && (
<Button
size="icon"
variant="ghost"
className={HEADER_BUTTON}
disabled={busy}
aria-label={`${verb} ${provider.label}`}
title={verb}
onClick={() => {
keyLanded.current = false;
setOauthFor(group.provider.id);
}}
>
<GlyphIcon d={ICONS.chainLink} size={ICON_SIZE.groupHeaderAction} />
<span className={HEADER_LABEL}>{verb}</span>
</Button>
)}
</span>
);
}
case "platformSync":
// A stored Penguin Go key enables catalog refresh, but connecting stays a separate
// action so the owner can replace the key with another account's.
return (
<Button
size="icon"
variant="ghost"
className={HEADER_BUTTON}
disabled={busy}
aria-label={`${S.models.platformSync} ${provider.label}`}
title={S.models.platformSync}
onClick={() => void syncPlatformModels()}
>
<GlyphIcon d={ICONS.rotateCw} size={ICON_SIZE.groupHeaderAction} />
<span className={HEADER_LABEL}>{S.models.platformSync}</span>
</Button>
);
case "groupKey":
// One key written across the whole group, overwriting what each row holds; a single
// model still takes its own in the model dialog.
return (
<Button
size="icon"
variant="ghost"
className={HEADER_BUTTON}
disabled={busy}
aria-label={`${S.models.groupApiKey} ${provider.label}`}
title={S.models.groupApiKey}
onClick={() => setGroupKeyFor(group.provider.id)}
>
<GlyphIcon d={ICONS.key} size={ICON_SIZE.groupHeaderAction} />
<span className={HEADER_LABEL}>{S.models.groupApiKey}</span>
</Button>
);
case "assignUserKey":
// The account's own global secrets, copied onto this group as its API key. It stands
// beside Enter key because it writes the same field; what differs is where the value comes
// from — and only the server can read it, so the copy is made there (see the dialog).
return (
<Button
size="icon"
variant="ghost"
className={HEADER_BUTTON}
disabled={busy}
aria-label={`${S.models.assignUserKey} ${provider.label}`}
title={S.models.assignUserKey}
onClick={() => setAssignKeyFor(group.provider.id)}
>
<GlyphIcon d={ICONS.user} size={ICON_SIZE.groupHeaderAction} />
<span className={HEADER_LABEL}>{S.models.assignUserKey}</span>
</Button>
);
case "speedTest": {
// One icon for both directions: it starts a run (after the confirmation) and, while
// its own group's run is going, stops it — the gauge turns into the registry's square in
// a circle. Every other group's waits its turn.
const running = speedRunning === group.provider.id;
const verb = running ? S.models.speedTestStop : S.models.speedTest;
return (
<Button
size="icon"
variant="ghost"
className={HEADER_SQUARE}
disabled={busy || (running ? speedStopping : speedRunning !== null)}
aria-label={`${verb} ${provider.label}`}
title={verb}
onClick={() => (running ? stopSpeedTest() : setSpeedFor(group.provider.id))}
>
<GlyphIcon
d={running ? ICONS.stopCircle : GAUGE_ICON}
size={ICON_SIZE.groupHeaderAction}
/>
</Button>
);
}
case "addModel":
// Only the groups that take hand-added models: custom, vLLM and user-defined ones. The
// rest carry the catalog's presets, which the server enforces too (model_not_addable).
return (
<Button
size="icon"
variant="ghost"
className={HEADER_BUTTON}
disabled={busy}
aria-label={`${S.models.addToGroup} ${provider.label}`}
title={S.models.addToGroup}
onClick={() => setAddingTo(group.provider.id)}
>
<GlyphIcon d={ICONS.plus} size={ICON_SIZE.groupHeaderAction} />
<span className={HEADER_LABEL}>{S.models.addToGroup}</span>
</Button>
);
case "deleteGroup":
// Whole-group delete, user-defined groups only: a built-in group is catalog identity
// (its rows delete one by one), a user-defined group exists solely through its rows.
return (
<Button
size="icon"
variant="ghost"
className={HEADER_BUTTON}
disabled={busy}
aria-label={`${S.models.deleteGroup} ${provider.label}`}
title={S.models.deleteGroup}
onClick={() => {
setDeleteGroupFor(group.provider.id);
// A new attempt, not the one that was refused: the card opens with no reason in it.
setDeleteGroupRefusal(null);
}}
>
<GlyphIcon d={ICONS.trash} size={ICON_SIZE.groupHeaderAction} />
<span className={HEADER_LABEL}>{S.models.deleteGroup}</span>
</Button>
);
}
};
return (
<PageFrame>
{/* The header holds search, the owner-only "sync presets" action and the pair of create
buttons — the AI path and the group form, offered side by side (per-model entry points
still live in each group header); on narrow screens the actions wrap to their own line
and the search box shrinks flexibly, fixed width at >=sm. A member reads why nothing
here is editable behind the title's "?". */}
<PageHeader
title={S.models.title}
info={isOwner ? undefined : S.models.readOnlyHint}
actions={
<>
<div className="min-w-0 flex-1 sm:w-56 sm:flex-none">
<Input
size="sm"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={S.models.searchPlaceholder}
/>
</div>
{/* The action appears only while a sync is actually waiting, and the accent says so
— a preset sync with nothing to sync is a no-op, and a permanent button spent the
header's width on one. That is also why the dot is gone: it marked this button as
the end of the models trail, and on a button that exists only when the trail does,
it would be lit every time it was seen. The sr-only sentence stays, folding what is
waiting into the accessible name in the wording the trail carried down.
Owner-only — the gate never raises this for a member. */}
{isOwner && todo && (
<Button
size="sm"
variant="primary"
onClick={() => void syncPresets()}
disabled={busy || rows === null}
title={`${S.models.syncCatalogHint} · ${syncNote}`}
>
{S.models.syncCatalog}
<span className="sr-only"> · {syncNote}</span>
</Button>
)}
{isOwner && (
<AiCreateButtons
size="sm"
// Only the form needs the table: AddGroupDialog is mounted behind `rows`, so
// without it the manual button would be a dead click. The AI path is left live
// precisely because a failed load is one of the things it can repair.
manualDisabled={rows === null}
onAi={() => setAiAddOpen(true)}
onManual={() => setAddGroupOpen(true)}
/>
)}
</>
}
>
{/* Last stop on the Models trail, in the one shape all four dismissible trails use:
directly under the title, naming what is waiting, carrying the sync itself, and
carrying the way down for someone who has looked and decided to stay off the
catalog. This is the one page whose two counts are both real — the catalog is a
list of entries, so an entry the table lacks is genuinely new — and both come off
the delta the sync action itself computes (catalog-sync.ts), never a second count.
The toolbar's "sync presets" button is unchanged and still runs it directly. */}
{isOwner && todo && syncCounts && (
<TodoNotice
text={
syncCounts.added === null
? S.todo.changesUpgradable(syncCounts.updated)
: S.todo.changesWithAdded(syncCounts.added, syncCounts.updated)
}
actionLabel={S.todo.updateNow}
busy={syncing}
onAction={() => {
setSyncConfirmOpen(true);
// A new attempt, not the one that was refused: the card opens with no reason in it.
setSyncRefusal(null);
}}
dismissLabel={S.todo.dismiss}
onDismiss={() => dismissTodo(projectId, "models", todo.signature)}
/>
)}
</PageHeader>
{rows === null ? (
<SkeletonList rows={4} />
) : rows.length === 0 ? (
<EmptyState
title={S.models.empty}
action={
isOwner && <Button onClick={() => setAddingTo("custom")}>{S.models.addCustom}</Button>
}
/>
) : groups.length === 0 ? (
<EmptyState title={S.models.noSearchResults} />
) : (
<div className="space-y-3">
{groups.map((group) => {
const open = isGroupExpanded(expanded, group.provider.id, searching);
const drag = groupDragProps(group.provider.id);
const keyStored = groupKeyStored(group.rows);
const actions = groupHeaderActions(group.provider, {
isOwner,
keyStored,
keyFromEnv: groupKeyFromEnv(group.rows),
balancePinned: isPinned(pinnedBalance, projectId, group.provider.id),
});
return (
// The drop indicator is drawn against the WHOLE group, so "below" reads as
// after this group and its model cards rather than between the header and
// its own first card. It needs this wrapper to live in: the section clips
// its children (overflow-hidden carries the expand/collapse transition).
// Absolutely positioned, so it costs no layout width and cannot push the
// header's actions out of a narrow page.
<div key={group.provider.id} className="relative">
{drag.dropEdge !== null && (
<div
aria-hidden
className={`pointer-events-none absolute inset-x-0 z-10 h-0.5 rounded-full bg-accent ${
drag.dropEdge === "above" ? "-top-1.5" : "-bottom-1.5"
}`}
/>
)}
<section className="overflow-hidden rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">
{/* Group header: collapse button (logo + vendor name + count + chevron) +
the group's actions on the right, in group-header.ts's order. Actions are
separate elements because buttons can't nest. The row is a size
container: the sidebar can narrow it while the viewport remains
desktop-sized, so labels respond to this row's actual width rather than
viewport breakpoints. Narrow rows never hide an action — each one keeps
its icon (with aria-label + title) and only sheds its text. When even the
icons leave the name too little room, the actions move to a line of their
own below it, as one block (the name keeps a floor, so it is never
squeezed to nothing). The row is also the drag handle for reordering the
group (groupDragProps). */}
<div
{...drag.header}
className={`@container flex flex-wrap items-center gap-x-2 bg-gray-50 pr-1.5 transition-colors duration-150 hover:bg-gray-100 dark:bg-gray-900/60 dark:hover:bg-gray-800/60${canDrag && !searching ? " cursor-grab" : ""}`}
>
<button
type="button"
aria-expanded={open}
onClick={() => toggleGroup(group.provider.id)}
className="flex min-w-[10rem] flex-1 items-center gap-2 px-3 py-2 text-left"
>
<ProviderLogo
provider={group.provider.id}
className="h-5 w-5 shrink-0 text-gray-700 dark:text-gray-300"
/>
{/* The vendor name is the only thing in this button allowed to take
the remaining space, and the only one that truncates. */}
<span className="min-w-0 truncate text-sm font-semibold">
{group.provider.label}
</span>
{/* The count as the model picker's rail writes it: a bare number, with
the words kept for assistive tech. */}
<span
aria-hidden
className="shrink-0 text-xs tabular-nums text-gray-400 dark:text-gray-500"
>
{group.rows.length}
</span>
<span className="sr-only">{S.models.modelCount(group.rows.length)}</span>
{/* The chevron follows the name and its count rather than the row's far
edge, so it reads as part of the group it folds. */}
<Chevron open={open} className="text-gray-400" />
</button>
{actions.length > 0 && (
<div className="ml-auto flex shrink-0 items-center gap-2 py-1">
{actions.map((action) => (
<Fragment key={action}>
{renderGroupAction(group, action, keyStored)}
{/* A rule between the account's figure and the group's status and
actions, drawn only when something follows the balance. */}
{action === "balance" && dividerAfterBalance(actions) && (
<span
aria-hidden
className="h-7 w-px shrink-0 bg-gray-300 dark:bg-gray-600"
/>
)}
</Fragment>
))}
</div>
)}
</div>
{/* Expand/collapse: grid-template-rows goes between 0fr and 1fr, with the
inner overflow-hidden handling clipping — no need to measure content height.
The grid carries the theme's layout motion, which decides how the fold moves
(and stills it under reduced motion). Content stays in the DOM while
collapsed (height is 0), so both directions animate. The section keeps its
own head rather than being a CollapsibleSection: the head is the group's
drag handle and a size container, and its chevron follows the group's name. */}
<div
data-layout-motion
className={`grid ${open ? "grid-rows-[1fr]" : "grid-rows-[0fr]"}`}
>
{/* inert while collapsed: a card with zero height shouldn't still be Tab-focusable or clickable. */}
<div className="overflow-hidden" inert={!open}>
<div
className={`grid grid-cols-1 gap-2 border-t border-gray-200 p-3 transition-opacity duration-200 sm:grid-cols-2 lg:grid-cols-3 dark:border-gray-800 ${open ? "opacity-100" : "opacity-0"}`}
>
{group.rows.length === 0 ? (
// An empty group only ever occurs for custom (always shown when there's no search query, to host the add entry point).
<p className="col-span-full py-1 text-center text-xs text-gray-400 dark:text-gray-500">
{S.models.groupEmptyHint}
</p>
) : (
group.rows.map((row) => (
<ModelCard
key={`${row.provider}:${row.modelId}`}
row={row}
currency={currency}
isDefault={sameModelRef(rowRef(row), defaultModel)}
isVisionModel={sameModelRef(rowRef(row), visionModel)}
speed={speedResults.get(refMapKey(row.provider, row.modelId))}
usedTokens={usedTokens.get(refMapKey(row.provider, row.modelId))}
hourTick={hourTick}
onOpen={() => {
setEditingMovedToCustom(false);
setEditing(rowRef(row));
}}
onMoveToCustom={
isOwner
? () => {
setEditingMovedToCustom(true);
setEditing(rowRef(row));
}
: undefined
}
onSyncPresets={isOwner ? () => void syncPresets() : undefined}
/>
))
)}
</div>
</div>
</div>
</section>
</div>
);
})}
{isOwner && query.trim() === "" && (
// "Add group" (user-defined group): hidden while searching (the group list itself is being filtered).
<button
type="button"
onClick={() => setAddGroupOpen(true)}
className="w-full rounded-md border border-dashed border-gray-300 px-3 py-2.5 text-sm text-gray-500 transition-colors hover:border-gray-400 hover:text-gray-700 dark:border-gray-700 dark:text-gray-400 dark:hover:border-gray-600 dark:hover:text-gray-200"
>
+ {S.models.addGroup}
</button>
)}
</div>
)}
{loadError && <p className="mt-3 text-xs text-red-600 dark:text-red-400">{loadError}</p>}
{rows && groupKeyFor && (
<GroupKeyDialog
// A user-defined group isn't in the catalog list: synthesize vendor info with custom semantics (label is the group name).
provider={
MODEL_PROVIDERS.find((p) => p.id === groupKeyFor) ?? userProviderInfo(groupKeyFor)
}
count={rows.filter((r) => r.provider === groupKeyFor).length}
detectedEnvKeys={envKeysDetected}
onClose={() => setGroupKeyFor(null)}
onSubmit={(key) => {
const target = groupKeyFor;
setGroupKeyFor(null);
const affected = rows.filter((r) => r.provider === target);
if (affected.length === 0) return;
const nextRows = rows.map((r) =>
r.provider === target ? { ...r, apiKeyInput: key, clearApiKey: false } : r,
);
// Success toast is shown inside persist (with "configured N" text); a refusal is
// raised here because this dialog closes on submit and has nothing left to draw it
// in (no false success report either — persist swallows the error, so a .then can't
// unconditionally report success).
void persist(
nextRows,
defaultModel,
visionModel,
S.models.groupKeyApplied(affected.length),
).then((outcome) => {
if (!outcome.ok) toastError(outcome.reason);
});
}}
/>
)}
{/* The group's key copied from the account's own global secrets. Unlike its neighbours this
dialog does its own write (the value lives only on the server, so it cannot go through
the page's whole-table PUT): it closes on success and the page reloads the table to show
the masked key it now holds. */}
{projectId && assignKeyFor !== null && (
<AssignUserKeyDialog
projectId={projectId}
provider={assignKeyFor}
providerLabel={MODEL_PROVIDERS.find((p) => p.id === assignKeyFor)?.label ?? assignKeyFor}
count={rows?.filter((r) => r.provider === assignKeyFor).length ?? 0}
onClose={() => setAssignKeyFor(null)}
onAssigned={(applied) => {
setAssignKeyFor(null);
toastSuccess(S.models.groupKeyApplied(applied));
void load();
}}
/>
)}
{/* NOT gated on `rows`, unlike its neighbours. This dialog outlives a table reload: it
stays open after the key lands to report the outcome, and `load()` blanks `rows` on
its first line, so gating it there would unmount it mid-flow — and its mount effect
opens a NEW authorization, which is how a completed authorization ended up offering
itself again. `count` is only read while the flow is still running, so a reload's
momentary absence of rows reads as zero and is never seen. */}
{projectId &&
oauthFor !== null &&
(oauthKeyAuth !== null ? (
<KeyAuthDialog
projectId={projectId}
providerLabel={
MODEL_PROVIDERS.find((provider) => provider.id === oauthFor)?.label ?? oauthFor
}
count={rows?.filter((row) => row.provider === oauthFor).length ?? 0}
endpoints={oauthKeyAuth.endpoints}
texts={oauthKeyAuth.texts}
onClose={() => {
setOauthFor(null);
if (keyLanded.current) void load();
keyLanded.current = false;
}}
onApplied={() => {
keyLanded.current = true;
}}
/>
) : (
<ModelOAuthDialog
projectId={projectId}
provider={MODEL_PROVIDERS.find((p) => p.id === oauthFor) ?? userProviderInfo(oauthFor)}
count={rows?.filter((r) => r.provider === oauthFor).length ?? 0}
onClose={() => {
setOauthFor(null);
// The reload waits for the dismissal rather than racing the open dialog: the key
// was written server-side, so the table in hand is stale in exactly one place, and
// reloading brings the masked key back. Gated on a key having landed, because
// `load` also drops this Project's speed results — measurements that cost real API
// quota and live only in page memory — and a cancelled flow changed nothing.
if (keyLanded.current) void load();
keyLanded.current = false;
}}
onApplied={() => {
// The dialog stays open and reports the outcome itself (its `done` phase), because
// the authorization ran in another tab and a toast would be announced to a window
// nobody is looking at. All this seam does is record that the dismissal has a
// reload to do.
keyLanded.current = true;
}}
/>
))}
{rows && deleteGroupFor !== null && (
<ConfirmModal
open
title={S.models.deleteGroupTitle}
tone="danger"
busy={busy}
onClose={() => setDeleteGroupFor(null)}
onConfirm={() => {
const target = deleteGroupFor;
const before = rows;
const removed = rows.filter((r) => r.provider === target);
if (removed.length === 0) {
setDeleteGroupFor(null);
return;
}
// Same pointer rule as single-model delete: a default/vision reference into the
// deleted group is dropped, otherwise the server rejects the dangling pair.
// Only a written delete dismisses the dialog. A refused one has to put the group
// back on the page as well: `persist` keeps the attempted rows for a field edit the
// user is still holding, but a refused group delete would otherwise leave the page
// without that group while the server still holds it — and the group's own header,
// the only way back to this action, goes with it, so the retry needs a reload
// (measured on a refused write: dialog gone, no `probegroup` anywhere on the page,
// 2 rows still on the server). Keeping the confirmation means the retry is the same
// click, against the sentence whose count the restored rows still match — and the
// server's own words for the refusal sit inside it (`refusal`), not in a toast that
// would have dismissed itself long before the retry.
void persist(
before.filter((r) => r.provider !== target),
defaultModel?.provider === target ? undefined : defaultModel,
visionModel?.provider === target ? undefined : visionModel,
S.models.groupDeleted(removed.length),
).then((outcome) => {
if (outcome.ok) {
setDeleteGroupFor(null);
return;
}
setDeleteGroupRefusal(refusalOf(outcome));
setRows(before);
});
}}
confirmLabel={S.common.confirm}
cancelLabel={S.common.cancel}
refusal={deleteGroupRefusal === null ? undefined : S.common.refused(deleteGroupRefusal)}
>
<p className="text-sm text-gray-700 dark:text-gray-300">
{/* Offered on user-defined groups only, whose display info is always synthesized. */}
{S.models.deleteGroupConfirm(
userProviderInfo(deleteGroupFor).label,
rows.filter((r) => r.provider === deleteGroupFor).length,
)}
</p>
</ConfirmModal>
)}
{/* The notice's bulk sync. Same union the toolbar button runs (syncPresets), but
confirm-first: the button on the notice is reached from a block announcing a batch, and
a sync rewrites the catalog-owned fields of every entry it names. The body is the
toolbar button's own description of those semantics, verbatim — the wording that has
always stated what a sync keeps and what it overwrites. */}
{todo && syncConfirmOpen && (
<ConfirmModal
open
title={S.todo.modelsConfirmTitle(todo.count)}
tone="primary"
confirmLabel={S.models.syncCatalog}
cancelLabel={S.common.cancel}
busy={syncing}
onClose={() => setSyncConfirmOpen(false)}
onConfirm={() => {
setSyncing(true);
// Only a written merge dismisses the dialog. A refused one keeps the sentence and
// the list of refs it names, so the retry is this same confirmation — the table
// behind it has been put back, and finding the notice again to start over is work
// the failure does not justify. The refusal's words stay in the card (`refusal`).
void syncPresets()
.then((outcome) => {
if (outcome.ok) setSyncConfirmOpen(false);
else setSyncRefusal(refusalOf(outcome));
})
.finally(() => setSyncing(false));
}}
refusal={syncRefusal === null ? undefined : S.common.refused(syncRefusal)}
>
<div className="space-y-3">
<p className="text-sm text-gray-600 dark:text-gray-300">{S.models.syncCatalogHint}</p>
<p className="text-xs text-gray-500 dark:text-gray-400">{S.todo.willTouch}</p>
<ul className="max-h-60 divide-y divide-gray-100 overflow-y-auto rounded-md border border-gray-200 dark:divide-gray-800 dark:border-gray-800">
{todo.items.map((ref) => (
<li key={ref} className="px-3 py-1.5 font-mono text-xs">
{ref}
</li>
))}
</ul>
</div>
</ConfirmModal>
)}
{speedFor !== null && (
<Modal open title={S.models.speedTestTitle} onClose={() => setSpeedFor(null)}>
<p className="text-sm text-gray-600 dark:text-gray-300">
{S.models.speedTestConfirm(rows?.filter((r) => r.provider === speedFor).length ?? 0)}
</p>
{/* This dialog builds its action row in the body rather than through Modal's
`footer`, so it carries the footer's sm rung itself. */}
<div className="mt-4 flex justify-end gap-2">
<Button size="sm" onClick={() => setSpeedFor(null)}>
{S.common.cancel}
</Button>
<Button
size="sm"
variant="primary"
onClick={() => {
const id = speedFor;
setSpeedFor(null);
if (id) void runSpeedTest(id);
}}
>
{S.models.speedTestStart}
</Button>
</div>
</Modal>
)}
{/* The AI path for what the group import cannot read: a listing page that is not an
OpenAI-compatible /models endpoint, or a service described in words. The table reloads
on every mount, so the group the agent adds is there when the page is next visited. */}
{projectId !== null && (
<AiCreateModal
open={aiAddOpen}
onClose={() => setAiAddOpen(false)}
title={S.models.aiAddTitle}
intro={S.models.aiAddIntro}
placeholder={S.models.aiAddPlaceholder}
examples={S.models.aiAddExamples}
tail={S.models.aiAddTail(projectId)}
agents={agents}
/>
)}
{rows && addGroupOpen && (
<AddGroupDialog
projectId={projectId}
rows={rows}
onClose={() => setAddGroupOpen(false)}
onManual={(name) => {
setAddGroupOpen(false);
setAddingTo(name);
}}
onImport={importGroup}
/>
)}
{rows && (addingTo !== null || editingRow) && (
<ModelDialog
projectId={projectId}
row={addingTo !== null ? null : (editingRow ?? null)}
addProvider={addingTo ?? "custom"}
movedToCustom={editingMovedToCustom}
existingRefs={rows.map(rowRef)}
detectedEnvKeys={envKeysDetected}
currency={currency}
canEdit={isOwner}
isDefault={editingRow !== undefined && sameModelRef(rowRef(editingRow), defaultModel)}
isVisionModel={editingRow !== undefined && sameModelRef(rowRef(editingRow), visionModel)}
onClose={closeModelDialog}
// The sync rewrites the very row this dialog was seeded from, so the dialog goes
// first and the merge runs against the table, not around an open form.
onSyncPresets={
isOwner
? () => {
closeModelDialog();
void syncPresets();
}
: undefined
}
onSubmit={(next, action) => {
const isNew = addingTo !== null;
if (action === "remove") {
// Filter by the **identity as loaded**: rows / pointers are both keyed by the
// paired reference as loaded. If the user edited identity fields before
// deleting, next's current reference wouldn't match any row -> nothing gets
// deleted while it still reports "saved".
const removed = next.original;
const before = rows;
// The dialog and its confirmation stay open until the delete is written: a
// refused one used to take the model off the page (persist keeps the attempted
// rows) while the server still held it, and the card that opens this dialog went
// with it, so the only way back to the retry was a reload (measured on a refused
// write: no dialog, zero matches for the model's name, the row still on the
// server). Keeping both means the retry is the same click against the same
// sentence, and the restored table matches what the server kept.
return persist(
before.filter((r) => !sameModelRef(rowRef(r), removed)),
sameModelRef(removed, defaultModel) ? undefined : defaultModel,
sameModelRef(removed, visionModel) ? undefined : visionModel,
undefined,
before,
).then((outcome) => {
if (outcome.ok) closeModelDialog();
return outcome;
});
}
const nextRows = isNew
? [...rows, next]
: rows.map((r) => (sameModelRef(rowRef(r), editing) ? next : r));
const ptr = nextPointers({
editing: isNew ? null : editing,
ref: rowRef(next),
action,
defaultModel,
visionModel,
});
// Save / set-default / set-vision-proxy report back too, and the dialog stays up
// until they do. A refused one leaves the page on the table and the pointers the
// server still holds: the draft lives in the dialog, so there is nothing to keep
// on screen for a retry — and a refused "set as default" used to leave the card
// wearing the 默认 tag while the server still pointed elsewhere (measured: page
// said 默认 on the edited model, `defaultModel` on the server unchanged, both
// dialogs gone). `before` goes in as `refusedRows` for the same reason the delete
// passes it: a rename or a move to another group would otherwise take the dialog
// (gated on its row still being in the table) down for one render.
const before = rows;
const beforeDefault = defaultModel;
const beforeVision = visionModel;
return persist(nextRows, ptr.defaultModel, ptr.visionModel, undefined, before).then(
(outcome) => {
if (outcome.ok) {
closeModelDialog();
return outcome;
}
setDefaultModel(beforeDefault);
setVisionModel(beforeVision);
return outcome;
},
);
}}
/>
)}
</PageFrame>
);
}
// ---------------------------------------------------------------------------
// Add-group dialog
// ---------------------------------------------------------------------------
/**
* "Add group" in two modes, chosen under the name field:
*
* - **Create only** — the light path: a valid name hands off to that group's add-model
* dialog (groups are carried by model entries, so the group appears once the first
* model saves; canceling leaves nothing behind).
* - **Import models** — fills the brand-new group from its endpoint, in the add-model
* dialog's field rhythm: API key first, then the base URL with the detect action at its
* top-right and the in-field protocol picker as manual override (ProtocolSuffixMenu —
* the same one-to-one path menu). Only once a protocol is determined (detected or
* picked) does the "import all models" action appear; it lists the endpoint
* (POST models/list) and hands the appended rows to the page for one table PUT.
*
* Detection failure turns the suffix amber and keeps both ways out usable — pick the
* protocol by hand, or switch back to create-only. Errors render inside the dialog;
* nothing persists until a listing succeeded.
*/
function AddGroupDialog({
projectId,
rows,
onClose,
onManual,
onImport,
}: {
projectId: string;
rows: RowState[];
onClose: () => void;
/** Create-only confirm: open the add-model dialog for the named group. */
onManual: (name: string) => void;
/**
* Import landing: persist the appended rows. A refused save answers `ok: false` and leaves the
* dialog open, so its reason has somewhere to be drawn (`groupImportRefusal`).
*/
onImport: (
nextRows: RowState[],
name: string,
added: number,
skipped: number,
) => Promise<WriteOutcome>;
}) {
const [name, setName] = useState("");
const [nameError, setNameError] = useState<string | null>(null);
const [mode, setMode] = useState<"create" | "import">("create");
const [apiKey, setApiKey] = useState("");
const [baseUrl, setBaseUrl] = useState("");
/** The protocol the import will speak: null until a detection lands or the user picks one. */
const [clientType, setClientType] = useState<ProtocolClientType | null>(null);
const [detecting, setDetecting] = useState(false);
const [detectFailed, setDetectFailed] = useState(false);
/** Progress line while list/save runs (null = idle); also gates every action against re-entry. */
const [importing, setImporting] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
/** Detection run counter: a manual pick or an edited URL supersedes an in-flight run (same convention as the model dialog). */
const detectSeq = useRef(0);
const validName = (): string | null => {
const trimmed = name.trim();
if (!/^[a-z0-9][a-z0-9_-]{0,31}$/.test(trimmed)) {
setNameError(S.models.groupNameInvalid);
return null;
}
if (MODEL_PROVIDERS.some((p) => p.id === trimmed) || rows.some((r) => r.provider === trimmed)) {
setNameError(S.models.groupNameExists);
return null;
}
return trimmed;
};
const confirmCreate = () => {
const n = validName();
if (n) onManual(n);
};
const detect = async () => {
const url = baseUrl.trim();
setError(null);
if (!detectableBaseUrl(url)) {
setError(S.models.groupImportNeedUrl);
return;
}
const seq = ++detectSeq.current;
setDetecting(true);
setDetectFailed(false);
try {
const key = apiKey.trim();
const res = await api.detectProtocol(projectId, {
baseUrl: url,
...(key ? { apiKey: key } : {}),
});
if (seq !== detectSeq.current) return;
const detected = res.detected !== undefined ? protocolSelectorValue(res.detected) : null;
if (detected !== null) {
setClientType(detected);
const name = S.models.protocolNames[detected] ?? detected;
// The protocol may have answered on a tidied-up form of the URL (a `/v1` added or
// dropped, a pasted endpoint path removed); the import must speak to that one, so
// the field takes it and the toast says so.
if (res.baseUrl !== undefined && res.baseUrl !== url) {
setBaseUrl(res.baseUrl);
toastSuccess(S.models.detectedProtocolAndUrl(name, res.baseUrl));
} else {
toastSuccess(S.models.detectedProtocol(name));
}
} else {
setDetectFailed(true);
// Same condition the model dialog reports, so it gets the same sentence.
setError(S.models.detectFailedBody);
}
} catch (e) {
if (seq !== detectSeq.current) return;
setDetectFailed(true);
setError(apiErrorText(e));
} finally {
if (seq === detectSeq.current) setDetecting(false);
}
};
const pickProtocol = (t: ProtocolClientType) => {
detectSeq.current++;
setDetecting(false);
setDetectFailed(false);
setError(null);
setClientType(t);
};
const runImport = async () => {
const n = validName();
if (!n || clientType === null) return;
const url = baseUrl.trim();
if (!detectableBaseUrl(url)) {
setError(S.models.groupImportNeedUrl);
return;
}
setError(null);
setImporting(S.models.groupImportListing);
try {
const key = apiKey.trim();
const listed = await api.listEndpointModels(projectId, {
baseUrl: url,
clientType,
...(key ? { apiKey: key } : {}),
});
if (!listed.ok || !listed.models) {
setError(
listed.unsupported
? S.models.groupImportUnsupported
: (listed.message ?? S.models.groupImportFailed),
);
return;
}
const built = buildImportedRows(rows, n, listed.models, {
baseUrl: url,
clientType,
apiKey: key,
});
if (built.added === 0) {
setError(S.models.groupImportEmpty);
return;
}
setImporting(S.models.groupImportSaving(built.added));
// The verdict decides the dialog's fate: a written import closes it (the landing above
// does that), a refused one keeps it up, so the reason goes into the slot this dialog
// already uses for its own failures — under the button that retries it.
const outcome = await onImport([...rows, ...built.rows], n, built.added, built.skipped);
const refusal = groupImportRefusal(n, outcome);
if (refusal !== null) setError(refusal);
} catch (e) {
setError(apiErrorText(e));
} finally {
setImporting(null);
}
};
const busy = importing !== null;
const suffixLabel =
clientType === null ? S.models.protocolUnset : protocolPathForModel(name.trim(), clientType);
return (
<Modal
open
title={S.models.addGroupTitle}
onClose={() => !busy && onClose()}
widthClass="sm:max-w-sm"
footer={
<>
<Button size="sm" disabled={busy} onClick={onClose}>
{S.common.cancel}
</Button>
{mode === "create" ? (
<Button size="sm" variant="primary" onClick={confirmCreate}>
{S.common.confirm}
</Button>
) : (
// The import action exists only once the protocol is determined (detected or
// hand-picked): before that there is nothing meaningful to run.
clientType !== null && (
<Button size="sm" variant="primary" disabled={busy} onClick={() => void runImport()}>
{S.models.groupImportAll}
</Button>
)
)}
</>
}
>
<div className="space-y-3">
<div className="block">
<Input
size="sm"
label={S.models.groupNameLabel}
info={S.models.addGroupDesc}
infoLabel={S.models.groupNameLabel}
required
value={name}
invalid={Boolean(nameError)}
onChange={(e) => {
setName(e.target.value);
setNameError(null);
}}
onKeyDown={(e) => {
if (e.key === "Enter" && mode === "create") confirmCreate();
}}
placeholder={S.models.groupNameHint}
className="font-mono"
autoFocus
/>
{nameError && <FieldError>{nameError}</FieldError>}
</div>
<Segmented
cols={2}
options={[
{ value: "create", label: S.models.groupModeCreate },
{ value: "import", label: S.models.groupModeImport },
]}
value={mode}
// The mode switch retires the previous answer: a refused import's sentence, or a
// failed listing's, described the flow the reader just left.
onChange={(next) => {
setMode(next);
setError(null);
}}
/>
{mode === "import" && (
<>
<PasswordInput
size="sm"
label={S.models.apiKey}
value={apiKey}
onChange={(e) => {
setApiKey(e.target.value);
setError(null);
}}
className="font-mono"
autoComplete="off"
placeholder={S.models.groupImportKeyHint}
/>
{/* Base URL with the detect action at its top-right and the in-field protocol
picker — the add-model dialog's idiom, so the two flows read as one. */}
<div className="block">
<span className="mb-1 flex items-baseline justify-between gap-2">
<FieldLabel required block={false}>
{S.models.baseUrl}
</FieldLabel>
<Button
variant="link"
size="sm"
loading={detecting}
disabled={busy}
onClick={() => void detect()}
title={S.models.detectProtocolHint}
data-tooltip-extra
className="shrink-0"
>
{detecting ? S.models.detecting : S.models.detectProtocol}
</Button>
</span>
<div className="relative">
<Input
size="sm"
aria-label={S.models.baseUrl}
required
value={baseUrl}
disabled={busy}
onChange={(e) => {
// An edited URL retires the previous verdict: protocol and failure tone
// both described the old endpoint.
detectSeq.current++;
setDetecting(false);
setDetectFailed(false);
setError(null);
setBaseUrl(e.target.value);
}}
className="font-mono"
style={{ paddingRight: `calc(${displayWidthCh(suffixLabel)}ch + 2.25rem)` }}
title={S.models.baseUrlSuffixTitle}
placeholder="https://…"
/>
<div className="absolute inset-y-0 right-1 flex items-center">
<ProtocolSuffixMenu
value={clientType}
path={suffixLabel}
detecting={detecting}
tone={detectFailed ? "warn" : null}
onPick={pickProtocol}
/>
</div>
</div>
</div>
{importing !== null && (
<p className="text-xs text-gray-500 dark:text-gray-400">{importing}</p>
)}
</>
)}
{error && <FieldError>{error}</FieldError>}
</div>
</Modal>
);
}
// ---------------------------------------------------------------------------
// Model card
// ---------------------------------------------------------------------------
/**
* Card: display name + lifetime Token spend + status badges; context / pricing / key status folded
* into one line of small text; group speed-test results (TTFT / TPS, tone-colored) ride the
* title row's right edge. All three lines are one click target opening the config dialog (the
* model homepage link lives in there); a row whose model id its group cannot route adds a
* warning strip below them, which carries its own action and therefore its own click target.
*/
export function ModelCard({
row,
currency,
isDefault,
isVisionModel,
speed,
usedTokens,
hourTick,
onOpen,
onMoveToCustom,
onSyncPresets,
}: {
row: RowState;
currency: Currency;
isDefault: boolean;
isVisionModel: boolean;
speed?: SpeedResult | "pending";
/** Lifetime Tokens spent on this model; absent for a model that has never run. */
usedTokens?: number;
/** Bumped on the hour (see useHourTick): the cue to re-read a time-of-day price. */
hourTick: number;
onOpen: () => void;
/** Opens the config dialog with this row already moved to the custom group; absent for a member, who cannot write the config. */
onMoveToCustom?: () => void;
/** Runs the header's "sync presets" merge, which writes back a built-in model's missing protocol pin; absent for a member. */
onSyncPresets?: () => void;
}) {
/**
* A stored entry that sits in a vendor group under an id AgentHub cannot place, and which
* of the two fixes it needs. Saving one is refused now, so this can only be a row that
* predates that rule — it stays in the config untouched, and the card is where its owner
* finds out, because every other sign of it arrives as a failed request minutes into a
* conversation.
*/
const fix = unroutableFix(row.provider, row.modelId, row.clientType);
const priced = row.cacheRead || row.cacheWrite || row.output;
/**
* What is taken off this row's list price right now: its running promotion, its live
* off-peak tier, or both. `discountedPrice` returns nothing for a row with neither — no
* promotion, and a schedule that is inside its peak windows or on a price edited away from
* the catalog's peak price.
*
* `hourTick` is in the dependency list for the schedule: a scheduled row's price changes on
* the hour with nobody touching the page, and a card left open would otherwise keep printing
* a rate that stopped applying.
*/
const discount = useMemo(() => discountedPrice(row), [row, hourTick]);
// The buckets to print: what the seller bills right now. The stored numbers are the list
// price, so they differ whenever a discount applies.
const shownPrice = discount
? {
cacheRead: String(discount.billed.cacheRead),
cacheWrite: String(discount.billed.cacheWrite),
output: String(discount.billed.output),
}
: { cacheRead: row.cacheRead, cacheWrite: row.cacheWrite, output: row.output };
/**
* Every standing mark this row carries (model-tags.ts, shared with the model picker's rows),
* in one horizontal row of its own.
*
* They had been sharing the title's line, where each was width the model's NAME had to give
* up — a long name truncated to make room for a mark that could have been read anywhere. A
* row of their own costs one line and gives the name the whole of the first.
*/
const tags = modelTags({
isDefault,
vision: row.vision,
isVisionModel,
fastMode: row.fastMode,
free: isFreeModel(row),
discount,
});
const priceLine = (a: string, b: string, c: string): string =>
`${displayPrice(a, currency)} / ${displayPrice(b, currency)} / ${displayPrice(c, currency)}`;
const meta: ReactNode[] = [
row.contextWindow ? humanizeTokens(Number(row.contextWindow)) : null,
// Three prices (cache read / cache write / output); units are explained in the config dialog, not repeated on the card.
// One price, the one being billed right now. What the row would cost without the promotion
// answers no question a reader of this list is asking, and spending the meta line's width
// on it pushes out the figures that do.
priced ? (
<span>{priceLine(shownPrice.cacheRead, shownPrice.cacheWrite, shownPrice.output)}</span>
) : null,
// Key status (see keyStatusText): the stored mask, a detected env fallback's mask, a plain
// "configured" for a key typed but not yet saved, or "not configured".
keyStatusText(row),
].filter((v) => v !== null);
const speedBadges =
speed === "pending" ? (
<span className="shrink-0 text-xs text-gray-400">{S.models.speedPending}</span>
) : speed ? (
speed.ok ? (
<span className="flex shrink-0 items-center gap-1.5 text-xs font-medium">
{speed.ttftMs !== undefined && (
<span
className={`flex items-center gap-1 ${TONE_CLASS[ttftTone(speed.ttftMs)]}`}
data-tooltip={S.models.ttftTitle}
>
<GlyphIcon d={CLOCK_ICON} size={11} />
{Math.round(speed.ttftMs)}ms
</span>
)}
{speed.tps !== undefined && (
<span
className={`flex items-center gap-1 ${TONE_CLASS[tpsTone(speed.tps)]}`}
data-tooltip={S.models.tpsTitle}
>
<GlyphIcon d={ZAP_ICON} size={11} />
{speed.tps} tok/s
</span>
)}
</span>
) : (
<span
className="shrink-0 text-xs font-medium text-red-600 dark:text-red-400"
data-tooltip={speed.message}
data-tooltip-extra
>
{S.models.speedFailed}
</span>
)
) : null;
return (
// The card is a box holding the button rather than being one: the routing warning below
// carries an action of its own, and buttons cannot nest (the group header solves the same
// problem the same way). overflow-hidden lets the warning strip fill the rounded corners.
<div className="flex w-full flex-col overflow-hidden rounded-md border border-gray-200 transition-colors duration-150 hover:border-gray-300 hover:bg-gray-50 dark:border-gray-800 dark:hover:border-gray-700 dark:hover:bg-gray-800/40">
<button
type="button"
onClick={onOpen}
className="flex w-full flex-1 flex-col gap-1 px-3 py-2.5 text-left"
>
{/* 1. What the model is called — the name alone. The upstream id used to share this row,
but it is a detail you go looking for rather than one you scan by, and it is a click
away in the config dialog; the width it was taking now belongs to the name. */}
<span className="flex w-full min-w-0 items-baseline gap-2">
<span className="min-w-0 flex-1 truncate text-sm font-medium">
{modelLabelOf(row.displayName, row.modelId)}
</span>
{/* What this model has spent over its whole life, on the row's right edge. Recessive by
design — grey, on the small rung below the name: it is context for a name you are
scanning past, not a figure the page is about. A model that has never run shows
nothing rather than a zero, which would read as a measurement instead of an
absence. */}
{usedTokens !== undefined && usedTokens > 0 && (
<span
className="shrink-0 text-xs tabular-nums text-gray-400 dark:text-gray-500"
data-tooltip={S.models.usedTokensTitle}
>
{S.models.usedTokens(humanizeTokens(usedTokens))}
</span>
)}
</span>
{/* 2. Every standing mark, on one row of its own (see `tags`). The row is rendered even
when empty: most models carry no mark at all, and letting it collapse would leave the
grid ragged — cards in the same row of a two-column grid stretch to the tallest, so an
absent line shows up as uneven padding rather than as a shorter card. Its height is
the tags' own, so a card with marks and a card without are exactly as tall. */}
<span className="flex min-h-[17px] w-full flex-wrap items-center gap-1">
{tags.map((tag) => (
<span
key={tag.key}
data-tooltip={tag.title}
className={`${TAG_SHAPE} ${tag.className}`}
>
{tag.label}
</span>
))}
</span>
{/* 3. Meta line: the truncating text takes the flexible space; speed badges keep their own
non-shrinking slot on the right so the numbers never wrap or get pushed out. */}
<span className="flex w-full items-center gap-1.5">
<span className="min-w-0 flex-1 truncate text-xs text-gray-400 dark:text-gray-500">
{meta.map((part, i) => (
<Fragment key={i}>
{i > 0 && " · "}
{part}
</Fragment>
))}
</span>
{speedBadges}
</span>
</button>
{/* The routing warning and its way out, which differ by what the catalog knows (see
unroutableFix). Both actions run a flow the page already has — the header's preset
sync, or the move the config dialog's own button performs — so the owner lands where
the problem is fixed rather than on a second explanation. */}
{fix !== null && (
<NoticeStrip
tone="attention"
className="flex items-center justify-between gap-2 border-t px-3 py-2 text-xs"
>
<span className="min-w-0">
{fix === "sync" ? S.models.vendorRowStalePin : S.models.vendorRowUnroutable}
</span>
{fix === "sync" && onSyncPresets && (
<Button size="sm" className="shrink-0" onClick={onSyncPresets}>
{S.models.syncCatalog}
</Button>
)}
{fix === "custom" && onMoveToCustom && (
<Button size="sm" className="shrink-0" onClick={onMoveToCustom}>
{S.models.moveToCustomGroup}
</Button>
)}
</NoticeStrip>
)}
</div>
);
}
// ---------------------------------------------------------------------------
// Config dialog (shared by editing an existing model / adding a custom model)
// ---------------------------------------------------------------------------
type DialogAction = "save" | "setDefault" | "setVisionModel" | "remove";
/** Confirmation text per action (S is a live runtime binding, must be read at render time, not frozen at module scope). */
const CONFIRM_TITLE: Record<DialogAction, () => string> = {
save: () => S.models.confirmSaveTitle,
setDefault: () => S.models.confirmDefaultTitle,
setVisionModel: () => S.models.confirmVisionModelTitle,
remove: () => S.models.confirmDeleteTitle,
};
const CONFIRM_BODY: Record<DialogAction, (name: string) => string> = {
save: (n) => S.models.confirmSave(n),
setDefault: (n) => S.models.confirmDefault(n),
setVisionModel: (n) => S.models.confirmVisionModel(n),
remove: (n) => S.models.confirmDelete(n),
};
function ModelDialog({
projectId,
row,
addProvider,
movedToCustom,
existingRefs,
detectedEnvKeys,
currency,
canEdit,
isDefault,
isVisionModel,
onClose,
onSyncPresets,
onSubmit,
}: {
projectId: string;
row: RowState | null;
/** Target group for add mode (row is null): the group of the header entry point / falls back to custom when empty. */
addProvider: string;
/** Edit mode: open with the row already moved into the custom group (a card's "move to custom group" action). */
movedToCustom: boolean;
existingRefs: ModelRefDto[];
/** Env-fallback variables the server reported a value for (see detectedEnvKeys): the only ones the key hint may promise. */
detectedEnvKeys: ReadonlySet<string>;
currency: Currency;
canEdit: boolean;
isDefault: boolean;
isVisionModel: boolean;
onClose: () => void;
/** Closes the dialog and runs the header's "sync presets" merge; absent for a member, who cannot write the config. */
onSyncPresets?: () => void;
/**
* Commit one action and report what its write answered. Every action answers now: this
* dialog and its confirmation stay up until the answer arrives, so a refused save, a
* refused "set as default / as vision proxy" and a refused delete all keep their sentence
* and their retry where the user left them. Only a written change closes them (the page
* does that for the actions it owns); a refusal also carries the server's words, which the
* confirmation draws in its `refusal` slot. `void` stays in the type for a caller with
* nothing to wait for.
*/
onSubmit: (row: RowState, action: DialogAction) => Promise<WriteOutcome> | void;
}) {
// Pricing input is displayed/entered in the current currency; converted back to USD storage on submit (RowState always stores USD).
const [form, setForm] = useState<RowState>(() => {
if (row) {
return {
...row,
cacheRead: usdToInput(row.cacheRead, currency),
cacheWrite: usdToInput(row.cacheWrite, currency),
output: usdToInput(row.output, currency),
// Opened from a card's "move to custom group": the same edit the dialog's own button
// makes, applied before the form is first painted so the user arrives at the protocol
// control instead of having to find the move again in here.
...(movedToCustom
? {
provider: "custom",
clientType: clientTypeAfterProviderChange("custom", row.clientType),
}
: {}),
};
}
// New model: protocol follows group semantics — a group that pins one (OpenRouter,
// vLLM) hands it to the new entry outright; custom / user-defined groups and the
// remaining gateways use a fixed openai-chat protocol (env fallback OPENAI_*), and
// gateways additionally pre-fill their endpoint base URL. provider keeps the entry
// point's original value (a user-defined group must not collapse into custom), stored as
// a separate field from model_id, with no concatenation on save.
//
// A first-party vendor group cannot be reached here at all: it carries the built-in
// catalog and nothing else, so no entry point opens this dialog on one (the group
// headers drop the action, the empty state opens custom, and a new group's name may not
// collide with a built-in id).
const info = providerInfo(addProvider);
const pinnedClientType = providerClientType(addProvider);
return {
provider: addProvider,
modelId: "",
original: null,
// A new custom model claims no vision support until it is detected or switched on by
// hand (per maintainer). A gateway add keeps the old optimistic default: its ids are
// catalog-known, so the capability is already established for them.
vision: !isCustomLikeGroup(addProvider),
contextWindow: "",
maxTokens: "",
fastMode: false,
// No protocol is preselected for a custom / user-defined group: it is detected from
// the endpoint (on demand, or on save while still unset) or picked by hand. A gateway
// takes the protocol its group pins, or the preset Chat Completions pin where the group
// pins nothing.
clientType: pinnedClientType ?? (isCustomLikeGroup(addProvider) ? "" : "openai-chat"),
cacheRead: "",
cacheWrite: "",
output: "",
baseUrl: info?.gatewayBaseUrl ?? "",
originalBaseUrl: "",
apiKeyInput: "",
clearApiKey: false,
};
});
/** Field-level validation errors: text below the corresponding input, input highlighted red — closer to the error site than a top-level banner. */
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
/** Connectivity test in progress. */
const [testing, setTesting] = useState(false);
/**
* The sentence the last refused probe left under the button row (model-test-refusal.ts). It
* lives on the dialog rather than in a toast because the form it names is on the dialog: cleared
* by every edit (the probe sent exactly the values it describes) and at the start of the next
* probe.
*/
const [testRefusal, setTestRefusal] = useState<string | null>(null);
/**
* Action pending confirmation: anything that writes to the Project config goes through a
* confirmation step — save config / set as default / set as vision proxy model / delete.
* (Adding a new custom model isn't confirmed: opening the dialog is itself a clear intent.)
*/
const [confirming, setConfirming] = useState<DialogAction | null>(null);
/**
* The server's words for the last refused write, drawn in the confirmation's `refusal` slot.
* It lives with the confirmation rather than with the page because that card is what the user
* is looking at while they retry: the reason has to survive the toast that would otherwise be
* the only trace of it (a toast dismisses itself after six seconds, over the card, not in it).
*/
const [refusal, setRefusal] = useState<string | null>(null);
/**
* Open the confirmation for one action, without the previous refusal: that sentence belonged
* to the write that was refused, and a confirmation opened now has not been tried yet.
*/
const confirm = (action: DialogAction) => {
setRefusal(null);
setConfirming(action);
};
/**
* The confirmed write is on the wire: its confirmation waits for the answer instead of
* closing on the click, and its buttons are locked so a second click cannot fire a rival
* write against the same sentence.
*/
const [writing, setWriting] = useState(false);
/** Fast mode is being switched ON and awaits the premium-billing warning's confirmation. */
const [confirmingFastMode, setConfirmingFastMode] = useState(false);
/** Protocol detection in progress (custom / user-defined groups only). */
const [detecting, setDetecting] = useState(false);
/**
* Whether the last detection run came back empty, purely to tint the suffix trigger
* amber. That tint is the control's own appearance, not a message occupying the form —
* the wording of a miss lives in `detectRefusal` below. A hit needs neither, because the
* suffix then shows the protocol it applied.
*/
const [detectFailed, setDetectFailed] = useState(false);
/**
* The sentence a detection that found nothing left under the base URL field (detect-refusal.ts).
* It lives on the dialog for the same reason the connectivity test's line does: the URL and the
* API key it names are the fields the reader is about to change, and a toast would be gone before
* they finished reading it against them. Cleared by every edit, by a manual pick, and at the
* start of the next manual run.
*/
const [detectRefusal, setDetectRefusal] = useState<string | null>(null);
/**
* Monotonic run counter: each detection captures it and only the newest run may apply
* its result — a manual protocol pick or a re-run supersedes anything still in flight.
*/
const detectSeq = useRef(0);
/**
* The run currently in flight, so a second trigger joins it instead of starting a rival
* probe: clicking Detect while the save path is already probing (or vice versa) must not
* double-fire, and the save path needs the SAME run's verdict to decide whether to go on.
*/
const detectInFlight = useRef<Promise<DetectOutcome | null> | null>(null);
/** Vision probe in progress (its own control, so its own busy state). */
const [visionDetecting, setVisionDetecting] = useState(false);
/**
* The sentence the last vision probe that decided nothing left under the vision switch
* (vision-refusal.ts). It lives on the dialog for the same reason the other two probes' lines do:
* it names the key, the URL and the id this form holds, and a toast would be gone before the
* reader had read it against them. Cleared by every edit and at the start of the next press.
*/
const [visionRefusal, setVisionRefusal] = useState<string | null>(null);
/** Single-flight guard for the vision probe: it bills the user, so never twice at once. */
const visionInFlight = useRef<Promise<void> | null>(null);
const isNew = row === null;
const preset = row !== null && isPreset(row);
/**
* Whether this row is still the catalog's own: a built-in model, in the group the catalog
* keeps it in, under the id the catalog knows. Its endpoint and its three prices belong to
* the catalog — the entry ships with both and 「同步预置」 maintains them — so this dialog
* shows them read-only (per owner, 2026-10-07). A row repointed at a proxy is no longer the
* catalog's model, and the deliberate way to build one is to move this row into a custom
* group first — which is exactly what unlocks the two fields here, because the check reads
* the CURRENT reference rather than the identity as loaded (isPreset): moving the row out of
* its group unlocks them, an id retyped onto another catalog model keeps them locked (it is
* that model now), and an id retyped off the catalog unlocks them (that row is the user's
* own). A hand-added row in a vendor group is never a catalog row either — no id there means
* the lock, and none of those rows has one.
*/
const official = catalogEntryFor(form.provider, form.modelId.trim()) !== undefined;
/** The loaded row's running promotion, explained under the price fields. */
const promotion = fractionOff(row?.discount);
// Read from the live form, not the saved row, so editing the upstream id, the protocol or
// the base URL updates the answer as it is typed.
const { protocol: fastProtocol, show: showFastMode } = fastModeState(form);
// Vision support and fast mode share one row; either can be missing, so the row's own
// presence and the cell width follow from which switches are actually there (capabilityRow).
const showVision = !preset;
const { show: showCapabilityRow, cellClass: toggleCellClass } = capabilityRow({
vision: showVision,
fastMode: showFastMode,
});
const set = (patch: Partial<RowState>) => {
setForm((prev) => ({ ...prev, ...patch }));
// A refused probe described the values it was sent: any edit makes that sentence describe a
// form that is no longer on screen, so it goes with the field it named. Same for the detection
// and vision lines below — both read the URL, the key and the id, so every one of them retires
// it.
setTestRefusal(null);
setDetectRefusal(null);
setVisionRefusal(null);
// Clear the error marker for whichever field was changed (keys match RowState field names).
setFieldErrors((prev) => {
const next = { ...prev };
for (const k of Object.keys(patch)) delete next[k as keyof FieldErrors];
return next;
});
};
/**
* What a failed probe says: the sentence under the button (model-test-refusal.ts), not a toast —
* the form it describes is right there, and a toast would be gone before the reader finished
* reading the reason against it. The refusal is judged on the form as it was pressed, because
* that is what the probe sent.
*/
const reportTestFailure = (answer: ModelTestAnswer) => {
const fix = unroutableFix(form.provider, form.modelId, form.clientType);
// An entry its group cannot place gets the advice instead of the route's sentence (see
// modelTestRefusal); that sentence is not lost — it goes to the console, where whoever reads
// a report can still find the id and the client types it named. Every other failure is
// relayed in the line itself, so only this case needs the extra copy.
if (fix !== null) {
const relayed =
answer.result === null
? refusalText(answer.error)
: (answer.result.message ?? S.common.unknownError);
console.warn(`[models] ${form.provider}/${form.modelId.trim()}: ${relayed}`);
}
setTestRefusal(modelTestRefusal(answer, fix));
};
/**
* Connectivity test: POST /models/test, sending the paired reference (provider, modelId)
* in the request body (no URL-encoding concerns), along with the form's not-yet-saved
* apiKey / baseUrl as overrides — so the user can verify right after typing a key without
* saving first (an unsaved new model is entirely sourced from the request body: verify
* before persisting).
*/
const runTest = async () => {
setTesting(true);
// The previous probe's sentence described a form that may have been edited since, and this
// press is a new question: the line goes while the answer is in flight.
setTestRefusal(null);
try {
// Always tests against the **current form draft**, unaffected by already-persisted
// values (per user intent: test exactly what's typed right now):
// - API key: use it if newly typed; if "clear" is checked, send clearApiKey (the
// server won't fall back to the stored key); only if neither applies does the server
// read the stored key (the frontend never sees the plaintext key, only its mask).
// - base URL isn't sensitive, so the frontend always sends the form's current value (empty means null = explicitly no base URL).
const key = form.apiKeyInput.trim();
const bu = form.baseUrl.trim();
const body: ModelTestRequest = {
provider: form.provider,
modelId: form.modelId.trim(),
baseUrl: bu ? bu : null,
};
if (key) body.apiKey = key;
else if (form.clearApiKey) body.clearApiKey = true;
if (form.clientType.trim()) body.clientType = form.clientType.trim();
// Like base URL, the form's current value is always sent (not just when true): an
// unsaved toggle-off must override a stored fast_mode=true, so the probe tests
// exactly the draft's serving tier.
body.fastMode = form.fastMode;
const res = await api.testModel(projectId, body);
if (res.ok) toastSuccess(S.models.testOk(res.latencyMs ?? 0));
else reportTestFailure({ result: res });
} catch (e) {
reportTestFailure({ result: null, error: e });
} finally {
setTesting(false);
}
};
/**
* Protocol detection: POST /models/detect probes the base URL for the three generic
* protocols (openai-responses → ant-messages → openai-chat, first hit wins) and applies
* the result to the form's clientType. Resolves to the detected client type, or null
* when nothing matched / the probe failed, so the save path can decide from the same run
* whether it may go on.
*
* No API key is required. The server resolves the probe credential in three layers — the
* key typed here, else this entry's stored key, else the environment variable for
* whichever protocol each probe speaks (ANTHROPIC_* / OPENAI_*) — and a keyless probe
* still identifies a route that answers in a protocol's own error shape. So the button
* is always live and a failure explains itself afterwards instead of being pre-empted by
* a disabled control.
*
* Outcomes are announced differently by kind. A hit is a toast (`detectedProtocol*`): transient,
* non-blocking, and the suffix then shows the protocol it applied — nothing to read against the
* form. The Toaster portals to document.body at z-[100] against the Modal's z-50, so that toast
* renders above this dialog rather than behind or clipped by it. A miss is NOT a toast: it is a
* sentence under the base URL field (`detectRefusal`, built by detect-refusal.ts), where
* the two fields it names are, and where it stays until the form changes — a toast left a form
* that looked untouched with nothing on it saying the button had been pressed.
*
* Every failure names the two things the user can act on (API key, base URL) — see
* detectProtocolRefusal for the one shape that does not, and why.
*
* A stale run (superseded by a manual pick or a newer run) discards its result instead
* of clobbering the form, and stays silent.
*/
const detectOnce = async (mode: DetectMode): Promise<DetectOutcome | null> => {
// What a miss is reported as depends on who asked. A manual run explains itself in the form; a
// save run silently resolves to the compatible client and says so, because the save it was
// serving is still going through — that note reports a write that happened, not a refusal.
const failed = (press: DetectPress) => {
setDetectFailed(true);
if (mode === "save") toastInfo(S.models.detectFellBack);
else setDetectRefusal(detectProtocolRefusal(press));
};
// The previous answer described a URL that may have been edited since, and this press is a new
// question: the line goes while that answer is in flight.
if (mode === "manual") setDetectRefusal(null);
const baseUrl = form.baseUrl.trim();
// An unusable URL is just another failure: the server would 400 it, and the user gets
// the same message either way rather than a distinct piece of API error text.
if (!detectableBaseUrl(baseUrl)) {
failed({ kind: "unprobeable" });
return null;
}
const seq = ++detectSeq.current;
setDetecting(true);
setDetectFailed(false);
try {
const body: ModelProtocolDetectRequest = { baseUrl };
const key = form.apiKeyInput.trim();
if (key) body.apiKey = key;
else if (form.clearApiKey) body.clearApiKey = true;
const modelId = form.modelId.trim();
if (modelId) {
body.provider = form.provider;
body.modelId = modelId;
}
const res = await api.detectProtocol(projectId, body);
if (seq !== detectSeq.current) return null;
if (res.detected) {
// The protocol may have answered on a tidied-up form of the URL (a `/v1` added or
// dropped, a pasted endpoint path removed). Saving the typed form would persist a
// base URL the detected protocol is not served at, so the field takes the one that
// answered and the outcome carries it on to the save path.
const served = res.baseUrl;
const patch = served !== undefined && served !== baseUrl ? { baseUrl: served } : {};
set({ clientType: res.detected, ...patch });
return { clientType: res.detected, ...patch };
}
failed({ kind: "answer", result: res });
return null;
} catch (e) {
if (seq === detectSeq.current) failed({ kind: "failed", error: e });
return null;
} finally {
if (seq === detectSeq.current) setDetecting(false);
}
};
/**
* Single-flight wrapper: a second trigger joins the run already in progress rather than
* starting a rival probe (the button while the save path is probing, or vice versa).
*/
const runDetect = (mode: DetectMode): Promise<DetectOutcome | null> => {
if (detectInFlight.current) return detectInFlight.current;
const run = detectOnce(mode).finally(() => {
detectInFlight.current = null;
});
detectInFlight.current = run;
return run;
};
/**
* The Detect button. Announces BOTH outcomes: the user asked a question and gets an
* answer either way. (The save path calls runDetect directly instead — a hit there needs
* no announcement of its own, since the save it was serving carries straight on.)
*/
const detectFromButton = async () => {
const detected = await runDetect("manual");
if (detected === null) return; // detectOnce already put the miss in the form
const name = S.models.protocolNames[detected.clientType] ?? detected.clientType;
toastSuccess(
detected.baseUrl === undefined
? S.models.detectedProtocol(name)
: S.models.detectedProtocolAndUrl(name, detected.baseUrl),
);
};
/**
* Vision probe. Mirrors protocol detection — always clickable, single-flight — with one
* deliberate difference: it is a REAL completion on the user's credential
* (an image request cannot be shaped to cost nothing the way the protocol probes are), so
* it only ever runs from this button, never implicitly and never on save.
*
* Three outcomes, because "the probe failed" and "the model says no" are different facts:
* a hit switches vision ON, a definitive image rejection switches it OFF, and a probe
* that learned nothing leaves the switch exactly as the user had it — and, unlike the other
* two, has to say why on the form itself (vision-refusal.ts): the sentence names what was
* probed, and nothing here writes anything the reader could read the answer off instead.
*/
const detectVisionFromButton = async () => {
if (visionInFlight.current) return;
const modelId = form.modelId.trim();
if (!modelId) {
// Nothing is asked of the route without an id, but the press still happened: the line says
// why, next to the control, instead of only in a toast that is gone by the time the reader
// has scrolled to the id it names.
setVisionRefusal(visionProbeRefusal({ kind: "unprobeable" }));
return;
}
// This run describes the form as it stands now; the previous line described the one it replaced.
setVisionRefusal(null);
setVisionDetecting(true);
const run = (async () => {
try {
const body: ModelVisionDetectRequest = { provider: form.provider, modelId };
const key = form.apiKeyInput.trim();
if (key) body.apiKey = key;
else if (form.clearApiKey) body.clearApiKey = true;
const bu = form.baseUrl.trim();
body.baseUrl = bu ? bu : null;
if (form.clientType.trim()) body.clientType = form.clientType.trim();
const res = await api.detectVision(projectId, body);
if (res.outcome === "supported") {
set({ vision: true });
toastSuccess(S.models.detectVisionOk);
} else if (res.outcome === "unsupported") {
set({ vision: false });
toastInfo(S.models.detectVisionNo);
} else {
// Learned nothing: the switch stays as the reader left it, and the line carries the
// provider's own sentence back to the form.
setVisionRefusal(visionProbeRefusal({ kind: "answer", result: res }));
}
} catch (e) {
setVisionRefusal(visionProbeRefusal({ kind: "failed", error: e }));
} finally {
setVisionDetecting(false);
}
})();
visionInFlight.current = run.finally(() => {
visionInFlight.current = null;
});
await visionInFlight.current;
};
/**
* Manual protocol override from the in-field picker. Bumping the run counter supersedes
* any in-flight detection, so a late result cannot clobber a choice the user just made.
*/
const pickProtocol = (clientType: ProtocolClientType) => {
detectSeq.current++;
setDetecting(false);
setDetectFailed(false);
set({ clientType });
};
/**
* Validate and convert pricing back to USD storage; returns null on validation failure —
* every error is placed below the offending input, which is highlighted red (no more
* top-level banner: it's too far from the error site, and with three price fields it's
* hard to tell which one is wrong).
*/
// base URL required-field policy: an OpenAI-protocol endpoint can't be
// inferred — required for custom / user-defined groups and entries with an explicit
// openai protocol (gateway groups already have it pre-filled); optional for entries
// auto-routed within a first-party vendor group (the client has its own official
// default endpoint). The Penguin Go relay is also required: its shared key must never
// fall through to a vendor default. Shared by validation and the label's required "*" mark.
const openAiLike =
form.clientType.trim().toLowerCase().includes("openai") ||
form.provider === "custom" ||
providerInfo(form.provider) === undefined;
// An official row is exempt whatever the group would otherwise require: the field is
// read-only there, so requiring it could only mark a row unsaveable over a value nobody can
// type — and the endpoint it asks for is the one the catalog already states (a Penguin Go row
// arrives with the relay's).
const baseUrlRequired =
!official && (form.provider === PENGUIN_GO_PROVIDER_ID || (!preset && openAiLike));
// Custom-like groups (custom + user-defined) pick among AgentHub's generic protocol
// clients: the base URL field's suffix becomes the protocol picker there, unless the
// entry carries a legacy vendor-pinned client_type — that keeps the read-only note below
// instead. Gateways stay pinned to their preset protocol (their base URL is fixed too).
const customLikeGroup = form.provider === "custom" || providerInfo(form.provider) === undefined;
const showProtocolSelector =
customLikeGroup && isGenericProtocolClientType(form.clientType) && !preset;
// A viewer without edit rights gets the plain grey suffix: the picker would offer writes
// the save path rejects anyway.
const showProtocolPicker = showProtocolSelector && canEdit;
// Protocol-path suffix shown inside the base URL field (every model, even while the
// field is empty): the path the client appends to the base URL, i.e. the endpoint
// shape a custom URL must serve. Recomputed from the live form so switching the
// group in add mode updates it.
const protocolPath = protocolPathForModel(form.provider, form.clientType);
// Which protocol the picker shows as chosen — null while a fresh custom model has none.
const protocolChoice = protocolSelectorValue(form.clientType);
// In the picker, an unchosen protocol has no path to show: the field would otherwise
// display /chat/completions and read as a decision the user never made. The placeholder
// takes its place until a pick or a detection lands. (The read-only suffix used by preset
// groups keeps showing the real path — those entries genuinely route that way.)
const suffixLabel =
showProtocolPicker && protocolChoice === null ? S.models.protocolUnset : protocolPath;
const modelLabel = modelLabelOf(form.displayName, form.modelId);
const validated = (): RowState | null => {
const modelId = form.modelId.trim();
const ref: ModelRefDto = { provider: form.provider, modelId };
const baseUrl = form.baseUrl.trim();
const errs: FieldErrors = {};
if (!modelId) errs.modelId = S.common.requiredField;
// A new or renamed (provider, modelId) must not duplicate another entry (renaming back to itself isn't a conflict).
else if (!sameModelRef(ref, form.original) && existingRefs.some((r) => sameModelRef(r, ref))) {
errs.modelId = S.models.modelIdExists;
}
if (baseUrlRequired && !baseUrl) errs.baseUrl = S.models.baseUrlRequired;
// Under PUT full-table replace semantics, omitting pricing means deleting it: all three
// prices must be either all empty or all filled, to avoid a partial entry silently
// clearing already-configured pricing (context window likewise must be a valid number, to prevent silent loss).
const priceFields = [
["cacheRead", form.cacheRead.trim()],
["cacheWrite", form.cacheWrite.trim()],
["output", form.output.trim()],
] as const;
const filled = priceFields.filter(([, v]) => v !== "").length;
for (const [key, v] of priceFields) {
// Partial fill: highlight the missing fields red (the filled-in ones are fine).
if (v === "" && filled > 0) errs[key] = S.models.pricingAllOrNone;
else if (v !== "" && !Number.isFinite(Number(v))) errs[key] = S.models.pricingInvalid;
}
const contextWindow = form.contextWindow.trim();
if (contextWindow && !Number.isFinite(Number(contextWindow))) {
errs.contextWindow = S.models.contextWindowInvalid;
}
// Output cap: digits-only input can still hold "0"/pasted junk; the server requires a positive integer.
const maxTokensInput = form.maxTokens.trim();
if (
maxTokensInput &&
!(Number.isInteger(Number(maxTokensInput)) && Number(maxTokensInput) > 0)
) {
errs.maxTokens = S.models.maxTokensInvalid;
}
if (Object.keys(errs).length > 0) {
setFieldErrors(errs);
return null;
}
setFieldErrors({});
const cacheRead = priceToSubmit(form.cacheRead, row?.cacheRead, currency);
const cacheWrite = priceToSubmit(form.cacheWrite, row?.cacheWrite, currency);
const output = priceToSubmit(form.output, row?.output, currency);
// The server cancels the promotion of a row saved with a new price or identity. A promotion
// the preset sync declared (still on the row when that sync's save failed) would restate it
// instead, so the declaration goes, and with it the promotion the card would otherwise keep
// showing until the save lands.
const cancelsPromotion =
row !== null &&
(cacheRead !== row.cacheRead ||
cacheWrite !== row.cacheWrite ||
output !== row.output ||
form.provider !== row.provider ||
modelId !== row.modelId);
return {
...form,
modelId,
// Custom models with an empty context window fall back to the default value (preset models left empty just mean "unknown", not auto-filled).
contextWindow:
!preset && !contextWindow ? String(CUSTOM_CONTEXT_DEFAULT) : form.contextWindow,
cacheRead,
cacheWrite,
output,
...(cancelsPromotion ? { discount: undefined, discountDeclared: undefined } : {}),
};
};
/**
* Commit one dialog action. Saving a custom-like entry whose protocol is still unset
* detects it FIRST and continues with whatever comes back: asking the endpoint is more
* reliable than guessing, so it is worth the round-trip.
*
* A probe that finds nothing no longer blocks (per maintainer: 默认都走兼容类型). The save
* goes through on the compatible client, with a toast saying that is what happened —
* detection is an accuracy improvement, not a gate, and refusing to save left the user
* stuck on an endpoint that simply cannot be probed. Nothing unstartable is written
* either way, because the fallback is a real client.
*
* The other actions (set-default / set-vision-proxy / remove) do not probe: they are not
* the user saying "this model is ready", and rowToEntry's fallback still applies.
*/
const submit = async (action: DialogAction) => {
const next = validated();
if (!next) return;
let payload = next;
if (needsProtocolDetectOnSave(action, next.provider, next.clientType)) {
// Joins a run already started from the Detect button rather than probing twice.
const detected = await runDetect("save");
payload = {
...next,
clientType: detected?.clientType ?? DEFAULT_CUSTOM_CLIENT_TYPE,
// The draft was snapshotted before the probe, so a base URL the probe corrected
// has to be carried over by hand — otherwise the entry saves a URL the detected
// protocol is not served at.
...(detected?.baseUrl !== undefined ? { baseUrl: detected.baseUrl } : {}),
};
}
const written = onSubmit(payload, action);
if (written === undefined) return;
// Every action reports back now, not just the remove: a refused save or a refused
// "set as default" used to take this dialog and its confirmation down with the request,
// so the sentence that named the change was gone and the only way to retry was to find
// the card again (and the page behind it showed the change the server had refused).
// Keeping both until the answer arrives makes the retry the same click, and the answer
// brings the server's words with it, which the confirmation then shows beside that click.
setRefusal(null);
setWriting(true);
try {
const outcome = await written;
if (outcome.ok) setConfirming(null);
else setRefusal(refusalOf(outcome));
} finally {
setWriting(false);
}
};
// Provider info for the current group (updates live as the group dropdown
// changes): the "get model id / API key" links come from it (shown next to
// the model id and API key labels in both the add and edit dialogs; custom
// and self-defined groups have no link).
const dialogProvider = providerInfo(form.provider);
// The variable a blank key may be PRESENTED as covered by, for the entry as drafted (core's
// modelEnvPreviewKey, which the server's masked preview reads too): undefined for every row
// whose endpoint is not the vendor's own — a gateway's preset base URL, a custom or vLLM
// server, a vendor row re-pointed at a proxy — and for a keyless vLLM / custom row with no
// base URL. The hint and the stored-mask block below follow this.
const liveEnvKey = envHintKeyFor(form.provider, form.modelId, form.clientType, form.baseUrl);
// The protocol this group pins on every entry, user-added ones included (OpenRouter,
// vLLM); undefined for every group that leaves the protocol to auto-routing, a gateway
// preset, or detection.
const pinnedGroupClientType = providerClientType(form.provider);
// An id this entry's group cannot place, and which fix it needs (see unroutableFix). The
// save is refused by the server for a new or rekeyed entry, so the warning and its way out
// are shown before the attempt; a row that was already stored keeps saving and carries the
// same warning on its card.
const routingFix = unroutableFix(form.provider, form.modelId, form.clientType);
const routingFixMessage =
routingFix === "sync" ? S.models.vendorRowStalePin : S.models.autoRouteNone;
/** Identity section: upstream model id (renamable; "get model id" link next
* to the label) + display name and group side by side (both editable;
* group is the entry's provider field — changing either is a key change,
* submitted together as renamedFrom). */
const identityFields = (
<>
<label className="block">
<span className="mb-1 flex items-baseline justify-between gap-2">
<FieldLabel required block={false}>
{S.models.modelId}
</FieldLabel>
<span className="flex shrink-0 items-baseline gap-2">
{/* The model-homepage entry lives in the dialog header (top-right button); only the "get model ids" provider link stays here. */}
{dialogProvider?.modelsUrl && (
<Link
href={dialogProvider.modelsUrl}
external
variant="standalone"
className="shrink-0 text-xs"
>
{S.models.getModelIds}
</Link>
)}
</span>
</span>
<Input
size="sm"
required
value={form.modelId}
disabled={!canEdit}
invalid={Boolean(fieldErrors.modelId)}
onChange={(e) => set({ modelId: e.target.value })}
className="font-mono"
autoFocus={isNew}
placeholder={S.models.modelIdHint}
/>
{fieldErrors.modelId && <FieldError>{fieldErrors.modelId}</FieldError>}
</label>
{routingFix !== null && (
<NoticeStrip
tone="attention"
role="alert"
className="flex items-center justify-between gap-3 rounded-md border px-2.5 py-2 text-xs"
>
{/* A built-in model whose stored entry lost its protocol pin needs the preset sync,
not a move: the same split the card makes, so the two places the owner can read
about one row never give opposite advice. */}
<span>{routingFixMessage}</span>
{/* Syncing rewrites the table this form was seeded from, so the dialog closes on the
way (the page's own handler does that); nothing typed here is worth keeping for a
row whose protocol is about to be restored from the catalog. */}
{routingFix === "sync" && onSyncPresets && (
<Button size="sm" className="shrink-0" onClick={onSyncPresets}>
{S.models.syncCatalog}
</Button>
)}
{routingFix === "custom" && (
<Button
size="sm"
className="shrink-0"
onClick={() =>
set({
provider: "custom",
clientType: clientTypeAfterProviderChange("custom", form.clientType),
})
}
>
{S.models.useCustomGroup}
</Button>
)}
</NoticeStrip>
)}
<div className="grid grid-cols-2 gap-2">
<Input
size="sm"
label={S.models.displayName}
value={form.displayName ?? ""}
disabled={!canEdit}
onChange={(e) => set({ displayName: e.target.value })}
placeholder={S.models.displayNameHint}
/>
<Select
size="sm"
label={S.models.providerGroup}
value={form.provider}
disabled={!canEdit}
onChange={(e) => {
const provider = e.target.value;
set({ provider, clientType: clientTypeAfterProviderChange(provider, form.clientType) });
}}
>
{/* Built-in groups: the ones that take hand-added models (custom, vLLM), and the
group the row was loaded in — a row already in a gateway or vendor group may stay
there, but no other row may be moved into one (the server refuses that as an
addition, model_not_addable). The current value stays listed so it is valid. */}
{MODEL_PROVIDERS.filter(
(p) =>
isAddableGroup(p.id) || p.id === row?.original?.provider || p.id === form.provider,
).map((p) => (
<option key={p.id} value={p.id}>
{p.label}
</option>
))}
{/* Self-defined groups are listed too (including the current value): options
= non-catalog providers among existing entries (plus the current
provider as a fallback), sorted by name and appended after the
built-in groups — keeps the selected value always valid, and lets an
entry be regrouped into an existing self-defined group. */}
{[...new Set(existingRefs.map((r) => r.provider).concat(form.provider))]
.filter((p) => !MODEL_PROVIDERS.some((k) => k.id === p))
.sort()
.map((p) => (
<option key={p} value={p}>
{p}
</option>
))}
</Select>
</div>
</>
);
// The variable a blank API key would actually be covered by: no stored key, the entry
// routes to a variable (resolved live, so it follows the id / protocol as they are
// edited), and that variable is one the server reported a value for. Knowing a variable's
// *name* is not knowing it is set — promising an unset one would tell the user to leave
// the field empty and leave the model with no key at all.
const envHintKey =
!form.credential?.apiKeyMasked && liveEnvKey !== undefined && detectedEnvKeys.has(liveEnvKey)
? liveEnvKey
: undefined;
// Hint for a blank API key: an existing key means keep the original value; a covered
// variable means the environment answers for it; neither means there is nothing truthful
// to say, so the field carries no placeholder.
const apiKeyHint = form.credential?.apiKeyMasked
? S.models.apiKeyKeepHint
: envHintKey !== undefined
? S.models.apiKeyEnvHint(envHintKey)
: undefined;
// Default endpoint note (zhipu / moonshot each have domestic / international
// endpoints): shown only when the env fallback hint appears (hence keyed off the same
// envHintKey) and this entry actually goes through the provider's own client (the
// resolved envKey matches the provider) — entries going through the OpenAI
// client (OPENAI_API_KEY) have no provider default endpoint to speak of.
const envNote =
envHintKey !== undefined && envHintKey === dialogProvider?.envKey
? S.models.providerEnvNotes[form.provider]
: undefined;
return (
<Modal
open
title={
isNew
? customLikeGroup
? // Custom / user-defined groups no longer pin one protocol (detection + selector), so the title drops the "(OpenAI protocol)" suffix gateways keep.
S.models.addTitleCustom
: S.models.addTitle
: S.models.editTitle
}
onClose={onClose}
widthClass="sm:max-w-lg"
footer={
<>
<Button size="sm" onClick={onClose}>
{S.common.cancel}
</Button>
{canEdit && (
<Button
size="sm"
variant="primary"
// Saving may have to probe the endpoint first (protocol still unset), which
// is a network round-trip: the label says so and the button locks, matching
// the "test connection" convention used inside this dialog. It also locks
// while the write itself is on the wire (a new model has no confirmation, so
// this is the only button that could send a second one).
disabled={detecting || writing}
onClick={() => {
// Validate first: if validation fails, the inline field errors show right away without popping the confirm dialog.
if (!validated()) return;
if (isNew || row === null) {
void submit("save");
return;
}
// Nothing changed: report it instead of confirming a no-op write (the
// baseline is rebuilt exactly like the form's initial state, so a plain
// JSON compare is field-exact).
const initial: RowState = {
...row,
cacheRead: usdToInput(row.cacheRead, currency),
cacheWrite: usdToInput(row.cacheWrite, currency),
output: usdToInput(row.output, currency),
};
if (JSON.stringify(form) === JSON.stringify(initial)) {
toastInfo(S.common.noChangesToSave);
return;
}
confirm("save");
}}
>
{detecting ? S.models.detecting : S.common.confirm}
</Button>
)}
</>
}
>
<div className="space-y-3">
{/* Header: the logo, and beside it one line each for the name, the upstream id and the
marks. The marks used to share the name's line, where they pushed a long name into
wrapping under them and left the header two ragged lines tall; on a line of their
own the name keeps the width it needs. Same pills the cards wear, so the list and
the dialog agree about what a mark looks like. The model homepage entry stays a
small secondary button on the right — a property of the model, not an input. */}
{!isNew && (
<div className="flex items-center gap-3 rounded-md bg-gray-50 px-3 py-2 dark:bg-gray-800/60">
<ProviderLogo
provider={form.provider}
className="h-6 w-6 shrink-0 text-gray-700 dark:text-gray-300"
/>
<div className="flex min-w-0 flex-1 flex-col gap-1">
<span className="truncate text-sm font-medium">{modelLabel}</span>
{/* Upstream id in small text: when there's no display name the line above is
already showing it, so don't repeat. Tested on the trimmed value, not on
`undefined`: clearing the field leaves an empty string, which is just as
nameless. */}
{form.displayName?.trim() && (
<span className="truncate font-mono text-xs text-gray-500 dark:text-gray-400">
{form.modelId}
</span>
)}
{(isDefault || form.vision || isVisionModel) && (
<span className="flex flex-wrap items-center gap-1 pt-0.5">
{isDefault && (
<span className={`${TAG_SHAPE} ${TAG_INK.status}`}>{S.models.default}</span>
)}
{form.vision && (
<span className={`${TAG_SHAPE} ${TAG_INK.capability}`}>
{S.models.visionBadge}
</span>
)}
{isVisionModel && (
<span className={`${TAG_SHAPE} ${TAG_INK.capability}`}>
{S.models.visionModelBadge}
</span>
)}
</span>
)}
</div>
{row && modelHomepageUrl(row.provider, row.modelId) && (
<a
href={modelHomepageUrl(row.provider, row.modelId)}
target="_blank"
rel="noopener noreferrer"
className={`${buttonClass("secondary", "sm")} shrink-0`}
>
{S.models.homepage}
{/* External-link glyph (opens in a new tab) */}
<GlyphIcon d={ICONS.externalLink} />
</a>
)}
</div>
)}
{/* Adding a model: protocol note first (preset direct-vendor group = only the
vendor's official protocol, named via the group label — the in-field suffix
on the base URL below says which path; a group that pins a protocol = that
protocol, named outright, with the endpoint the user's own for a self-hosted
group and already filled in for a gateway; custom / self-defined group / an
unpinned gateway = fixed OpenAI protocol), then the identity fields ("get model
id / API key" links next to the respective inputs; fill in the id to test
connectivity — verify before saving). */}
{isNew && (
<>
<p className="text-xs text-gray-500 dark:text-gray-400">
{pinnedGroupClientType !== undefined
? dialogProvider?.gatewayBaseUrl !== undefined
? S.models.addProtocolHintPinnedGateway(pinnedGroupClientType)
: S.models.addProtocolHintPinned(pinnedGroupClientType)
: customLikeGroup
? S.models.addProtocolHintDetect
: S.models.addProtocolHint}
</p>
{identityFields}
</>
)}
{/* Model-level actions pinned at the top: test connectivity (for a new model,
fill in the id and key to verify before saving) / set default / set as
vision proxy model / remove. */}
{canEdit && (
<div className="space-y-1.5">
<div className="flex flex-wrap items-center gap-2">
<Button
size="sm"
disabled={testing || !form.modelId.trim()}
onClick={() => void runTest()}
>
{testing ? S.models.testing : S.models.testConnection}
</Button>
{!isNew && !isDefault && (
<Button size="sm" onClick={() => confirm("setDefault")}>
{S.models.setDefault}
</Button>
)}
{!isNew && form.vision && !isVisionModel && (
<Button
size="sm"
title={S.models.visionModelHint}
// The hint says what setting this model as the vision one does, which its label cannot.
data-tooltip-extra
onClick={() => confirm("setVisionModel")}
>
{S.models.setVisionModel}
</Button>
)}
{!isNew && (
<>
<span className="min-w-0 flex-1" />
<Button size="sm" variant="danger" onClick={() => confirm("remove")}>
{S.models.remove}
</Button>
</>
)}
</div>
{testRefusal !== null && (
// Under the buttons that asked, not over the dialog: `line-clamp-2` keeps a long
// upstream sentence from heightening it, and the whole text is on hover, the way
// every other refusal slot in the app carries its longer form.
<p
role="alert"
data-tooltip={testRefusal}
data-tooltip-content="text"
className={`line-clamp-2 break-words text-xs ${toneInk.danger}`}
>
{testRefusal}
</p>
)}
</div>
)}
{/* 1) API key — the most commonly used, placed first in the field section; "get API key"
link next to the label. PasswordInput carries its own show/hide toggle and brings its
own <label> wrapper, so this outer container is a <div> (a nested <label> is invalid). */}
<div className="block">
<span className="mb-1 flex items-baseline justify-between gap-2">
<FieldLabel block={false}>{S.models.apiKey}</FieldLabel>
{dialogProvider?.apiKeyUrl && (
<Link
href={dialogProvider.apiKeyUrl}
external
variant="standalone"
className="shrink-0 text-xs"
>
{S.models.getApiKey}
</Link>
)}
</span>
<PasswordInput
size="sm"
aria-label={S.models.apiKey}
value={form.apiKeyInput}
disabled={!canEdit}
onChange={(e) => set({ apiKeyInput: e.target.value, clearApiKey: false })}
className="font-mono"
autoComplete="off"
autoFocus={!isNew}
placeholder={apiKeyHint}
/>
</div>
{envNote && <p className="text-xs text-gray-400 dark:text-gray-500">{envNote}</p>}
{form.credential?.apiKeyMasked && !form.apiKeyInput && (
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-500 dark:text-gray-400">
<span className="font-mono">{form.credential.apiKeyMasked}</span>
{form.credential.createdAt && (
<span className="text-gray-400">
{S.common.created} {formatDateTime(form.credential.createdAt)}
</span>
)}
{canEdit && (
<Checkbox
checked={form.clearApiKey}
onChange={(on) => set({ clearApiKey: on })}
label={S.models.clearApiKey}
/>
)}
</div>
)}
{/* Detected first-party env fallback, shown like a stored key (same slot, same mask
rule): the created-at position says where the key comes from instead, and there is
no clear control — an environment variable cannot be cleared from here. Typing a new
key hides this like the stored block; once saved, the stored key takes priority and
the display switches to the stored form. The mask is the SAVED row's: once the draft
resolves to another variable or to none (a proxy base URL typed over a vendor row),
it is hidden rather than left promising a key the draft will not have. */}
{!form.credential?.apiKeyMasked &&
form.envKeyMasked !== undefined &&
liveEnvKey === form.envKey &&
!form.apiKeyInput && (
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-500 dark:text-gray-400">
<span className="font-mono">{form.envKeyMasked}</span>
<span className="text-gray-400">{S.models.readFromEnv}</span>
</div>
)}
{/* 2) base URL (required for custom / user-defined groups and explicit openai protocol — see
baseUrlRequired). The in-field suffix at the right edge shows the protocol path the
client appends to the base URL — the endpoint shape a custom URL must serve; it
renders for every model and stays while the field is empty (hints the shape before
typing). It looks like the unit affix of the context window / max tokens fields
below, but it can be a menu button, which Input's `affix` does not take, so it is
positioned by hand and the error text sits outside the relative wrapper (see
Input.invalid).
For custom / user-defined groups that suffix IS the protocol SELECTOR (see
protocol-suffix.tsx): the path is one-to-one with the three generic protocol
clients, so picking one reuses it instead of taking a form row of its own.
Elsewhere (preset groups, read-only viewers) it stays the plain grey label it has
always been.
The detect ACTION sits at this field's top-right instead, next to the label — the
same idiom as the API key field's "get API key" link above (per maintainer). It is
gated on the API key, and a disabled row buried inside the suffix menu could not
say so where the user is looking.
A <div>, not a <label>: the picker is a <button>, and a label may not contain a
second labelable element besides its control — the click would fire the button AND
re-focus the input. Same shape as the API key block above; the input carries an
aria-label so it stays named. */}
<div className="block">
{showProtocolPicker ? (
<span className="mb-1 flex items-baseline justify-between gap-2">
<FieldLabel required={baseUrlRequired} block={false}>
{S.models.baseUrl}
</FieldLabel>
{/* Always live: no API key is needed (the server falls back to the stored key
and then to the protocol's env var), and anything that does go wrong is
explained below this field. `detecting` only guards re-entrancy. */}
<Button
variant="link"
size="sm"
loading={detecting}
onClick={() => void detectFromButton()}
title={S.models.detectProtocolHint}
className="shrink-0"
>
{detecting ? S.models.detecting : S.models.detectProtocol}
</Button>
</span>
) : (
<FieldLabel required={baseUrlRequired}>{S.models.baseUrl}</FieldLabel>
)}
<div className="relative">
<Input
size="sm"
aria-label={S.models.baseUrl}
required={baseUrlRequired}
value={form.baseUrl}
disabled={!canEdit || official}
invalid={Boolean(fieldErrors.baseUrl)}
// Editing the URL retires the previous run's verdict: it described the old
// endpoint, and leaving it up would keep asserting a result for a URL that is
// no longer in the field.
onChange={(e) => {
setDetectFailed(false);
set({ baseUrl: e.target.value });
}}
// Detection on leaving the field (custom / user-defined groups): only a
// probeable URL the user actually changed in this dialog triggers a run —
// typing never fires requests, and a click-through must not rewrite a working
className="font-mono"
// Reserve room so the typed URL never slides under the suffix. Input and
// suffix share the same monospace size, so the suffix width is its display
// width in ch (CJK placeholder glyphs count double), plus the right offset
// and — for the interactive version — its padding, gap and chevron. The
// picker never changes width between states, so this holds for all of them.
style={{
paddingRight: `calc(${displayWidthCh(suffixLabel)}ch + ${showProtocolPicker ? "2.25rem" : "1.25rem"})`,
}}
// The read-only suffix is hover-transparent (pointer-events-none), so the
// explanation rides on the input's title; the picker carries its own. On an
// official row that title is the lock note instead: the suffix it would explain
// is still shown (the row does route that way), but what the reader needs to know
// is why the field will not take an edit.
title={official ? S.models.officialLockedHint : S.models.baseUrlSuffixTitle}
placeholder={preset ? S.models.baseUrlHint : "https://…"}
/>
{showProtocolPicker ? (
<div className="absolute inset-y-0 right-1 flex items-center">
<ProtocolSuffixMenu
value={protocolChoice}
path={suffixLabel}
detecting={detecting}
tone={detectFailed ? "warn" : null}
onPick={pickProtocol}
/>
</div>
) : (
<span className="pointer-events-none absolute inset-y-0 right-2 flex items-center font-mono text-xs text-gray-400">
{protocolPath}
</span>
)}
</div>
{fieldErrors.baseUrl && <FieldError>{fieldErrors.baseUrl}</FieldError>}
{detectRefusal !== null && (
// Under the field the probe read (the button that asked sits in the label row above),
// and the same slot the connectivity test's refusal uses: `line-clamp-2` keeps a long
// upstream sentence from heightening the form, and the whole text is on hover.
<p
role="alert"
data-tooltip={detectRefusal}
data-tooltip-content="text"
className={`mt-1 line-clamp-2 break-words text-xs ${toneInk.danger}`}
>
{detectRefusal}
</p>
)}
{/* Why the field above (and the price row below) will not take an edit — one line for
both, since the lock is one rule. It is shown rather than left to the greyed
control alone: a read-only field with no reason reads as a broken one, and the way
out (`moveToCustomGroup`, the same action the card offers) is the half of the
answer a reader cannot guess. */}
{official && (
<p className="mt-1 text-xs text-gray-400 dark:text-gray-500">
{S.models.officialLockedHint}
</p>
)}
{/* A detection VERDICT takes no room here (per maintainer): a hit needs none, because
where the protocol ended up is the suffix above, which is the thing that holds it.
A miss is not a verdict but a refusal, and it does get a line — the one drawn above
the lock note (detectRefusal): it names the URL and the key, both within a glance of
it, and it stays until the form changes. Idle and post-hit layouts stay identical:
that line exists only while there is something to account for. */}
</div>
{/* 3) Context window + max output tokens side by side (one row): the "Token" unit
sits inside each box as a muted right suffix. Placeholders cannot scroll, so at
this half width they carry only a short line; the full explanation lives in the
input's title (hover) — the owner explicitly prefers saving the vertical space
over a visible hint line. Only field errors appear under a cell. Max output
tokens: per-model cap on the request's output — when set it wins over the
Agent's system_config value; empty inherits it (lets a small-context local
model stay under its window). */}
<div className="grid grid-cols-2 items-start gap-2">
<Input
label={S.models.contextWindow}
size="sm"
value={form.contextWindow}
inputMode="numeric"
disabled={!canEdit}
error={fieldErrors.contextWindow}
onChange={(e) => set({ contextWindow: digitsOnly(e.target.value) })}
// Half-width cell: the placeholder is wider than the box in English, and an input
// clips at its padding box, so an unclipped one runs past the value area and collides
// with the unit. `truncate` ends it in an ellipsis instead, which reads as "there is
// more" rather than as text colliding; the title has it in full.
className="truncate font-mono"
affix={{ trailing: S.models.tokenUnit }}
// The title mirrors the placeholder: at half width the (EN) copy can clip, hover reveals it in full.
title={
preset
? S.models.contextWindowHint
: S.models.contextWindowDefaultHint(CUSTOM_CONTEXT_DEFAULT)
}
placeholder={
preset
? S.models.contextWindowHint
: S.models.contextWindowDefaultHint(CUSTOM_CONTEXT_DEFAULT)
}
/>
<Input
label={S.models.maxTokens}
size="sm"
value={form.maxTokens}
inputMode="numeric"
disabled={!canEdit}
error={fieldErrors.maxTokens}
onChange={(e) => set({ maxTokens: digitsOnly(e.target.value) })}
// Truncated for the same reason as the context window beside it.
className="truncate font-mono"
affix={{ trailing: S.models.tokenUnit }}
// Short placeholder (fits the half-width box); the full explanation incl. the small-context advice is the hover title.
title={S.models.maxTokensTitle}
placeholder={S.models.maxTokensHint}
/>
</div>
{/* 4) Pricing: three fields side by side with self-contained labels (… price) — no
standalone section heading; currency and unit (/M tok) are shown inside the input.
Errors land right under the offending field (which is also outlined red): with
three fields side by side, only sticking close to the field makes clear which one it is. */}
<div className="grid grid-cols-3 items-start gap-2">
{(
[
["cacheRead", S.models.priceCacheRead, form.cacheRead],
["cacheWrite", S.models.priceCacheWrite, form.cacheWrite],
["output", S.models.priceOutput, form.output],
] as Array<[keyof FieldErrors & keyof RowState, string, string]>
).map(([key, label, value]) => (
<Input
key={key}
label={label}
size="sm"
value={value}
inputMode="decimal"
// Official rows keep the catalog's list price (see `official`); the value stays
// visible, the hover title says why it cannot be typed over.
disabled={!canEdit || official}
title={official ? S.models.officialLockedHint : undefined}
error={fieldErrors[key]}
onChange={(e) => set({ [key]: decimalOnly(e.target.value) })}
className="text-right font-mono"
affix={{ leading: CURRENCY_SYMBOL[currency], trailing: S.models.priceUnitShort }}
/>
))}
</div>
{/* The fields hold the list price, not the promotional price the card prints: the
promotion is stored apart and taken off when usage is priced. It is said here, in
view while the prices are typed, because typing a different price cancels it. */}
{promotion !== undefined && (
<p className="text-xs text-gray-500 dark:text-gray-400">
{S.models.promotionPriceHint(Math.round(promotion * 100))}
</p>
)}
{/* 5) Identity: model id (renamable) + display name and group (side by side) */}
{!isNew && identityFields}
{/* Legacy entries carrying a client_type other than the standard openai-chat
(historical config): read-only display. Compared canonically so the deprecated
bare "openai" spelling (pre-0.4.2 configs) is not flagged as legacy either,
skipped when the protocol selector above already represents it (generic protocol
types in custom-like groups are editable there), and skipped when the value IS
the group's own pin — that is this group's normal protocol, not a leftover from
an older config, and "kept as configured" would misdescribe it. */}
{!isNew &&
!preset &&
!showProtocolSelector &&
form.clientType &&
form.clientType !== pinnedGroupClientType &&
canonicalClientType(form.clientType) !== "openai-chat" && (
<p className="text-xs text-gray-400 dark:text-gray-500">
{S.models.clientTypeLocked(form.clientType)}
</p>
)}
{/* 6) Capability switches — vision support and fast mode side by side on one row,
reusing the dialog's two-up grid (same `grid grid-cols-2 items-start gap-2` as the
context-window / max-tokens row above, which already carries two full inputs at
phone width; two compact switches are strictly narrower). `items-start` keeps both
cells top-aligned when only one of them grows a muted hint line, and the hint text
wraps inside its half-width cell rather than overflowing. Each switch is optional,
so the row itself is conditional and a lone switch takes the whole width
(toggleCellClass) — the layout must not depend on both being present. */}
{showCapabilityRow && (
<div className="grid grid-cols-2 items-start gap-2">
{/* Vision capability: for preset models it's flagged by the built-in catalog
(read-only, so no cell at all); custom models toggle it here — an iOS-style
switch sitting inline right next to the label (per owner: no full-row stretch,
no standing explanation text). Only the OFF state shows one small muted line:
images are then read via the configured vision proxy model (read_file hands them to it). */}
{showVision && (
<div className={toggleCellClass}>
{/* Detect sits inline after the switch — the protocol control's idiom, but next
to the setting it fills in rather than at a field's top-right, since this row
has no field to hang off. Always clickable and single-flight, like protocol
detection; it just costs a real (tiny) completion, so it never runs on its own.
Its two verdicts announce themselves through the switch they moved, while a
press that decided nothing leaves the line drawn below (visionRefusal).
`flex-wrap` is what lets the switch and the trigger share a half-width cell:
when they do not both fit, the trigger drops onto its own line inside the cell
instead of widening the grid column. */}
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
<label
className={`inline-flex items-center gap-2 ${canEdit ? "cursor-pointer" : "cursor-not-allowed"}`}
>
<span className="text-xs font-semibold text-gray-600 dark:text-gray-400">
{S.models.vision}
</span>
<Switch
checked={form.vision}
disabled={!canEdit}
onChange={(vision) => set({ vision })}
aria-label={S.models.vision}
/>
</label>
{canEdit && (
<Button
variant="link"
size="sm"
loading={visionDetecting}
onClick={() => void detectVisionFromButton()}
title={S.models.detectVisionHint}
data-tooltip-extra
className="shrink-0"
>
{visionDetecting ? S.models.detectingVision : S.models.detectVision}
</Button>
)}
</div>
{visionRefusal !== null && (
// Under the switch row the button sits in, inside this half-width cell:
// `line-clamp-2` keeps a long upstream sentence from heightening the form, and the
// whole text is on hover, the way every other refusal slot carries its longer form.
// Drawn above the off-state hint so it stays adjacent to the control that was
// pressed; the hint is a standing explanation, not the answer to this press.
<p
role="alert"
data-tooltip={visionRefusal}
data-tooltip-content="text"
className={`mt-1 line-clamp-2 break-words text-xs ${toneInk.danger}`}
>
{visionRefusal}
</p>
)}
{!form.vision && (
<p className="mt-1 text-xs text-gray-400 dark:text-gray-500">
{S.models.visionOffProxyHint}
</p>
)}
</div>
)}
{/* Fast mode: per-model opt-in to the provider's faster serving tier (premium
pricing). Offered only where AgentHub's routed client actually puts the
parameter on the wire (fastModeProtocol) — a model whose client rejects it
would otherwise arm a switch that kills the next turn. Same inline-switch shape
as vision; the one small muted line appears in the non-default (ON) state, and
the label's hover title reveals it before toggling. Enabling is confirmed
(premium billing), disabling is immediate. */}
{showFastMode && (
<div className={toggleCellClass}>
<label
className={`inline-flex items-center gap-2 ${canEdit ? "cursor-pointer" : "cursor-not-allowed"}`}
data-tooltip={S.models.fastModeHint}
data-tooltip-extra
>
<span className="text-xs font-semibold text-gray-600 dark:text-gray-400">
{S.models.fastMode}
</span>
<Switch
checked={form.fastMode}
disabled={!canEdit}
onChange={(fastMode) => {
// Only the ON direction is confirmed: it is the one that starts spending
// at premium rates. Turning it off costs nothing and must stay one click
// — it is the documented escape from a model that rejects the parameter.
if (fastMode) setConfirmingFastMode(true);
else set({ fastMode: false });
}}
aria-label={S.models.fastMode}
/>
</label>
{form.fastMode && (
<p className="mt-1 text-xs text-gray-400 dark:text-gray-500">
{S.models.fastModeHint}
</p>
)}
{/* Reachable only for a stored annotation the rule would not have offered (a
hand-edited config, `--fast-mode`, or an id renamed after the fact): the
switch is kept visible precisely so it can be turned off, and says why it
should be. */}
{form.fastMode && fastProtocol === undefined && (
<p className={`mt-1 text-xs ${toneInk.attention}`}>
{S.models.fastModeUnsupported}
</p>
)}
</div>
)}
</div>
)}
</div>
{/* Premium-billing warning, stacked on the config dialog the same way: fast mode moves
the model onto the provider's premium price list while the recorded per-token prices
stay standard, so the Cost center under-reports it — and on the Anthropic protocol
access is a gated research preview that answers 429 until granted. Warning tone (the
alert triangle) rather than the save pencil: nothing is being written yet, the point
is what enabling costs. */}
{confirmingFastMode && (
<ConfirmModal
open
title={S.models.fastModeConfirmTitle}
tone="danger"
onClose={() => setConfirmingFastMode(false)}
onConfirm={() => {
setConfirmingFastMode(false);
set({ fastMode: true });
}}
confirmLabel={S.common.confirm}
cancelLabel={S.common.cancel}
>
<p className="text-sm text-gray-700 dark:text-gray-300">{S.models.fastModeConfirmBody}</p>
{fastProtocol === "anthropic" && (
<p className="mt-2 text-sm text-gray-700 dark:text-gray-300">
{S.models.fastModeConfirmPreview}
</p>
)}
</ConfirmModal>
)}
{/* Confirmation before writing config (save / set default / set as vision proxy model / remove): stacked on top of the config dialog. */}
{confirming && (
<ConfirmModal
open
title={CONFIRM_TITLE[confirming]()}
tone={confirming === "remove" ? "danger" : "primary"}
busy={writing}
onClose={() => setConfirming(null)}
onConfirm={() => {
const action = confirming;
// The confirmation lives until its write lands (see `submit`): dismissed on the
// click it could only ever say nothing about a refusal.
void submit(action);
}}
confirmLabel={S.common.confirm}
cancelLabel={S.common.cancel}
// A refused write's words, inside the card that asked for it: the toast they used to
// ride on dismissed itself, and the retry is the button right below this line.
refusal={refusal === null ? undefined : S.common.refused(refusal)}
>
<p className="text-sm text-gray-700 dark:text-gray-300">
{CONFIRM_BODY[confirming](modelLabel)}
</p>
</ConfirmModal>
)}
</Modal>
);
}
// ---------------------------------------------------------------------------
// Set a single API key for an entire provider group
// ---------------------------------------------------------------------------
/** Write the same API key to every model in a provider group (one account's key is usually valid for all of that provider's models). */
function GroupKeyDialog({
provider,
count,
detectedEnvKeys,
onClose,
onSubmit,
}: {
provider: ModelProviderInfo;
count: number;
/** Env-fallback variables the server reported a value for (see detectedEnvKeys). */
detectedEnvKeys: ReadonlySet<string>;
onClose: () => void;
onSubmit: (apiKey: string) => void;
}) {
const [key, setKey] = useState("");
const groupEnvKey = providerEnvFallbackKey(provider.id);
return (
<Modal
open
title={S.models.groupApiKeyTitle(provider.label)}
onClose={onClose}
footer={
<>
<Button size="sm" onClick={onClose}>
{S.common.cancel}
</Button>
<Button
size="sm"
variant="primary"
disabled={!key.trim()}
onClick={() => onSubmit(key.trim())}
>
{S.common.confirm}
</Button>
</>
}
>
<div className="space-y-2">
<Input
size="sm"
label={S.models.apiKey}
required
type="password"
value={key}
onChange={(e) => setKey(e.target.value)}
className="font-mono"
autoComplete="off"
autoFocus
// Only promise the variable when this group's rows may fall back to it at all
// (providerEnvFallbackKey: never a gateway, custom, vLLM or user-defined group —
// the OpenAI key an Anthropic row proved set is not this gateway's key) AND the
// server reported a value for it: the group's variable name is always known,
// which says nothing about whether it is set.
placeholder={
groupEnvKey !== undefined && detectedEnvKeys.has(groupEnvKey)
? S.models.apiKeyEnvHint(groupEnvKey)
: undefined
}
/>
<p className="text-xs text-gray-500 dark:text-gray-400">
{S.models.groupApiKeyHint(count)}
</p>
{/* Default endpoint note (zhipu / moonshot): same wording as the single-model dialog's env fallback hint. */}
{S.models.providerEnvNotes[provider.id] && (
<p className="text-xs text-gray-400 dark:text-gray-500">
{S.models.providerEnvNotes[provider.id]}
</p>
)}
{provider.apiKeyUrl && (
<Link href={provider.apiKeyUrl} external variant="standalone" className="text-xs">
{S.models.getApiKey}
</Link>
)}
</div>
</Modal>
);
}
// ---------------------------------------------------------------------------
// Copy one of the account's global secrets onto a group as its API key
// ---------------------------------------------------------------------------
/**
* The account's own user keys, offered one at a time (a model holds ONE key), plus the copy
* itself. The list is a fresh read every time the dialog opens and is read-only: editing the
* account's table is the account menu's dialog, and this one copies.
*
* The write is this dialog's own (POST ···/models/assign-user-key) rather than the page's
* whole-table PUT, because the value never reaches the browser: the request names the entry and
* the server takes the plaintext from the user vault and writes it into the model config. That is
* also why the dialog, not the page, reports a refusal — nothing has changed when one comes back.
*/
function AssignUserKeyDialog({
projectId,
provider,
providerLabel,
count,
onClose,
onAssigned,
}: {
projectId: string;
/** The group's provider id — what the server writes the key onto. */
provider: string;
providerLabel: string;
/** How many models of the group take it (the count the copy reports). */
count: number;
onClose: () => void;
onAssigned: (applied: number) => void;
}) {
const [entries, setEntries] = useState<VaultEntryInfo[] | null>(null);
const [picked, setPicked] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
let cancelled = false;
void (async () => {
try {
const table = await api.getUserVault();
if (!cancelled) setEntries(table.entries);
} catch (e) {
if (!cancelled) setError(apiErrorText(e));
}
})();
return () => {
cancelled = true;
};
}, []);
const confirm = async () => {
if (picked === null) return;
setBusy(true);
setError(null);
try {
const res = await api.assignUserKeyToModels(projectId, { provider, key: picked });
if (res.applied === 0) {
// Nothing was written, so nothing is reported as written: a group with no rows is the
// only way here, and it closes nothing.
setError(S.models.assignUserKeyMissing);
setBusy(false);
return;
}
onAssigned(res.applied);
} catch (e) {
setError(apiErrorText(e));
setBusy(false);
}
};
return (
<Modal
open
title={S.models.assignUserKeyTitle(providerLabel)}
onClose={onClose}
widthClass="sm:max-w-lg"
footer={
<>
<Button size="sm" onClick={onClose}>
{S.common.cancel}
</Button>
<Button
size="sm"
variant="primary"
disabled={busy || picked === null}
onClick={() => void confirm()}
>
{S.common.confirm}
</Button>
</>
}
>
<div className="space-y-3">
<p className="text-xs leading-relaxed text-gray-500 dark:text-gray-400">
{S.models.assignUserKeyHint(count)}
</p>
{/* The reason stands ABOVE what this dialog offers, never instead of it: a refused copy
writes nothing, leaves the entry picked and keeps 确认 as the retry, so replacing the
list would take away the choice that retry repeats — and every other entry one might
pick instead — at the very moment the person is deciding what to do about it. Only a
failed READ has nothing to list behind it, and that is what replaces the skeleton. */}
{error !== null && <p className="text-xs text-red-600 dark:text-red-400">{error}</p>}
{entries === null ? (
error === null ? (
<SkeletonList rows={3} />
) : null
) : entries.length === 0 ? (
<EmptyState dashed title={S.models.assignUserKeyEmpty} />
) : (
<div className="overflow-y-auto rounded-md border border-gray-200 dark:border-gray-800">
{entries.map((entry) => (
<div
key={entry.key}
className="flex items-center justify-between gap-3 border-b border-gray-100 px-3 py-2 last:border-b-0 dark:border-gray-800/60"
>
<Checkbox
checked={picked === entry.key}
// One key per model: picking a second replaces the first, the way a radio would.
onChange={(on) => setPicked(on ? entry.key : null)}
label={<span className="font-mono text-xs">{entry.key}</span>}
/>
<span className="shrink-0 font-mono text-xs text-gray-500 dark:text-gray-400">
{entry.valueMasked}
</span>
</div>
))}
</div>
)}
</div>
</Modal>
);
}
// ---------------------------------------------------------------------------
// Authorize a new API key for a provider group
// ---------------------------------------------------------------------------
/** Where the dialog is: opening a flow, holding one, waiting on an outcome, or reporting a failure. */
/**
* `done` exists because the authorization happens in ANOTHER TAB. A toast fired at the moment
* the poll sees the key would be announced to a window the user is not looking at, and by the
* time they switch back it has faded — the outcome of the one step they left the app for is the
* one thing they must not have to guess at. So the dialog stays put and says it instead, and is
* dismissed deliberately.
*/
type OAuthPhase = "starting" | "ready" | "waiting" | "failed" | "done";
/** How often the redirect flow's outcome is asked for while the user is in the other tab. */
const OAUTH_POLL_MS = 2000;
/**
* Mint a fresh API key for a whole provider group by authorizing in the browser.
*
* The dialog never handles the key, and never handles the PKCE verifier either: it opens a
* flow, sends the user to the provider's page, and asks the server how that flow ended. Two
* routes back — the provider redirects to the server (polled here), or, when that redirect
* cannot reach the harness, the user carries a one-time code across by hand. The server has
* the last word on which: it opens a manual flow when the provider would refuse to redirect to
* the address this page is served from, and the dialog follows the flow it was given.
*/
function ModelOAuthDialog({
projectId,
provider,
count,
onClose,
onApplied,
}: {
projectId: string;
provider: ModelProviderInfo;
/** Models in the group; every one of them gets the new key. */
count: number;
onClose: () => void;
onApplied: (applied: number) => void;
}) {
/** The route back the user picked. */
const [manual, setManual] = useState(false);
/**
* Set once a redirect was asked for and the server opened a manual flow: the provider does not
* redirect to this address (plain HTTP to anything but loopback), so the code is the only way
* back for as long as the dialog is open, and the switch to the redirect is withdrawn.
*/
const [redirectRefused, setRedirectRefused] = useState(false);
/** Whether the flow in hand takes the code by hand rather than through the redirect. */
const byHand = manual || redirectRefused;
const [phase, setPhase] = useState<OAuthPhase>("starting");
const [flow, setFlow] = useState<{ flowId: string; authorizeUrl: string } | null>(null);
const [error, setError] = useState<string | null>(null);
const [code, setCode] = useState("");
/** How many models the key was written to — the sentence the `done` phase reports. */
const [applied, setApplied] = useState(0);
/** Bumped to reopen a flow after a failure; switching modes reopens one too (the URL differs). */
const [attempt, setAttempt] = useState(0);
// Latest-callback ref: the parent passes an inline arrow, and depending on its identity
// would tear down and restart the poll interval on every render.
const onAppliedRef = useRef(onApplied);
onAppliedRef.current = onApplied;
// A flow is opened as soon as the dialog shows, so the authorize URL is already in hand
// when the button is pressed — window.open then runs inside that click's own user
// activation, which is what keeps a popup blocker out of the way.
useEffect(() => {
let cancelled = false;
setPhase("starting");
setFlow(null);
setError(null);
setCode("");
void (async () => {
try {
const res = await api.startModelOAuth(projectId, {
provider: provider.id,
mode: manual ? "manual" : "callback",
});
if (cancelled) return;
if (!manual && res.mode === "manual") setRedirectRefused(true);
setFlow(res);
setPhase("ready");
} catch (e) {
if (cancelled) return;
setError(apiErrorText(e));
setPhase("failed");
}
})();
return () => {
cancelled = true;
};
}, [projectId, provider.id, manual, attempt]);
// Redirect mode: the outcome lands on the server, so this tab only learns of it by asking.
// A flow that has expired answers 404, which reads the same as never coming back.
useEffect(() => {
if (phase !== "waiting" || byHand || flow === null) return;
let stopped = false;
const tick = async (): Promise<void> => {
try {
const res = await api.getModelOAuthStatus(projectId, flow.flowId);
if (stopped) return;
if (res.status === "done") {
// The server's own count, not the table in hand: `rows` is kept through a rejected
// save so the user can fix and retry, so it can name models the server never wrote.
const n = res.applied ?? count;
setApplied(n);
setPhase("done");
onAppliedRef.current(n);
return;
}
if (res.status === "error") {
setError(res.error ? S.models.oauthErrors[res.error] : S.models.oauthTimedOut);
setPhase("failed");
}
} catch {
if (stopped) return;
setError(S.models.oauthTimedOut);
setPhase("failed");
}
};
const timer = window.setInterval(() => void tick(), OAUTH_POLL_MS);
return () => {
stopped = true;
window.clearInterval(timer);
};
}, [phase, byHand, flow, projectId, count]);
const openAuthorizePage = (): void => {
if (flow === null) return;
window.open(flow.authorizeUrl, "_blank", "noopener,noreferrer");
if (!byHand) setPhase("waiting");
};
const submitCode = async (): Promise<void> => {
if (flow === null) return;
setPhase("waiting");
setError(null);
try {
const res = await api.submitModelOAuthCode(projectId, flow.flowId, code.trim());
if (res.ok) {
const n = res.applied ?? count;
setApplied(n);
setPhase("done");
onAppliedRef.current(n);
return;
}
setError(res.error ? S.models.oauthErrors[res.error] : S.models.oauthTimedOut);
setPhase("failed");
} catch (e) {
setError(apiErrorText(e));
setPhase("failed");
}
};
const primary =
phase === "failed" ? (
<Button size="sm" variant="primary" onClick={() => setAttempt((n) => n + 1)}>
{S.models.oauthRetry}
</Button>
) : byHand ? (
<Button
size="sm"
variant="primary"
disabled={flow === null || phase === "waiting" || !code.trim()}
onClick={() => void submitCode()}
>
{S.models.oauthSubmitCode}
</Button>
) : (
<Button size="sm" variant="primary" disabled={flow === null} onClick={openAuthorizePage}>
{S.models.oauthAuthorize}
</Button>
);
return (
<Modal
open
title={S.models.oauthTitle(provider.label)}
onClose={onClose}
footer={
// Done is an outcome, not a choice: a "cancel" beside it would offer to undo a key that
// is already written.
phase === "done" ? (
<Button size="sm" onClick={onClose}>
{S.common.close}
</Button>
) : (
<>
<Button size="sm" onClick={onClose}>
{S.common.cancel}
</Button>
{primary}
</>
)
}
>
<div className="space-y-3">
{phase === "done" ? (
<p className="text-sm text-gray-700 dark:text-gray-300">
{S.models.oauthAppliedBody(provider.label, applied)}
</p>
) : (
<p className="text-sm text-gray-700 dark:text-gray-300">
{S.models.oauthIntro(provider.label, count)}
</p>
)}
{phase !== "done" && byHand && (
<>
{/* In the dialog body, directly above the code Input: it takes the same rung the
field does, not the page-level md. */}
<Button size="sm" variant="ghost" disabled={flow === null} onClick={openAuthorizePage}>
<GlyphIcon d={SIGN_IN_ICON} size={13} />
{S.models.oauthAuthorize}
</Button>
<Input
size="sm"
label={S.models.oauthCodeLabel}
hint={S.models.oauthManualHint}
value={code}
onChange={(e) => setCode(e.target.value)}
className="font-mono"
autoComplete="off"
/>
</>
)}
{phase === "waiting" && !byHand && (
<p className="flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400">
<Spinner size="xs" label={S.common.loading} />
{S.models.oauthWaiting}
</p>
)}
{error !== null && <p className="text-xs text-red-600 dark:text-red-400">{error}</p>}
{phase !== "done" && !redirectRefused && (
<Button variant="link" size="sm" onClick={() => setManual((v) => !v)}>
{manual ? S.models.oauthCallbackSwitch : S.models.oauthManualSwitch}
</Button>
)}
</div>
</Modal>
);
}