import { useRef, useState, type ReactNode } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { useSortable } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { useI18n } from '@/i18n'
import { CopyButton } from '@/components/copy-button'
import { Switch } from '@/components/ui/switch'
import { Tooltip } from '@/components/tooltip'
import {
cleanQuotaLabel,
formatContext,
groupMaxContext,
groupQuotaBadge,
isGroupDepleted,
memberEndpointTitle,
memberProviderLabel,
providerLabel,
tightestRateLimit,
type ModelGroupRow,
type RateLimitUsageRow,
type Row,
} from '@/lib/routing'
// The unified model/provider table pieces, extracted from FallbackPage so the
// Models page and the per-model detail page share one module.
// A 0..1 value as a thin horizontal bar with the number beside it.
export function AxisBar({ value, color }: { value: number | undefined; color: string }) {
const v = value ?? 0
return (
{value === undefined ? '–' : Math.round(v * 100)}
)
}
// The honest replacement for prior-valued bars (#580): a measured axis value
// only exists once a provider has served requests. Before that the bandit uses
// exploration priors (0.5 reliability / 0.6 speed) — rendering those as bars
// reads as a real, suspiciously identical measurement, so unmeasured providers
// get this explicit placeholder instead.
export function AxisNoData() {
const { t } = useI18n()
return (
{t('models.noData')}
)
}
// The min–max of the defined values, or null when none are defined.
function rangeOf(values: (number | undefined)[]): { min: number; max: number } | null {
const nums = values.filter((v): v is number => v !== undefined)
if (nums.length === 0) return null
return { min: Math.min(...nums), max: Math.max(...nums) }
}
// A group's axis as a min–max band across its providers, collapsing to the
// plain single-value bar when the providers agree (or there is only one).
// Groups show the true spread instead of silently promoting the best member's
// number to the whole group (#580).
function AxisRangeBar({ values, color }: { values: (number | undefined)[]; color: string }) {
const range = rangeOf(values)
if (range === null) return
const lo = Math.round(range.min * 100)
const hi = Math.round(range.max * 100)
if (lo === hi) return
return (
{lo}–{hi}
)
}
// The shared table header for the unified model/provider table — used by the
// Models page and the per-model detail page so their columns line up.
export function ModelTableHead() {
const { t } = useI18n()
return (
#
{t('models.columnModel')}
{t('strategies.weightReliability')}
{t('strategies.weightSpeed')}
{t('strategies.weightIntelligence')}
{t('strategies.guardrails')}
{t('strategies.scoreColumn')}
{t('models.columnOn')}
)
}
// ── One row of the unified table ────────────────────────────────────────────
// Time-window rate-limit pressure for one logical model or one provider row
// (#876). Shared by the Models table group header, the model detail page's
// summary badges and its per-provider rows so all three read identically.
// Renders nothing when there is no usage to report.
export function RateLimitBadge({ rows, size = 'sm' }: { rows: RateLimitUsageRow[]; size?: 'sm' | 'md' }) {
const { t } = useI18n()
const tightest = tightestRateLimit(rows)
if (!tightest) return null
const ratio = tightest.limit > 0 ? tightest.used / tightest.limit : 0
const tone = tightest.used >= tightest.limit
? 'bg-red-600/15 text-red-700 dark:text-red-400'
: ratio >= 0.7
? 'bg-amber-600/15 text-amber-700 dark:text-amber-400'
: 'bg-muted text-muted-foreground'
const scale = size === 'md' ? 'text-[11px] px-2 py-0.5' : 'text-[10px] px-1.5 py-0.5'
return (
{t('models.rateLimitUsage', { kind: tightest.kind, used: tightest.used, limit: tightest.limit })}
)
}
export function RowContent({
row,
rank,
draggable,
dragHandle,
onToggle,
providerName,
providerTitle,
rateUsage,
}: {
row: Row
rank: number
draggable: boolean
dragHandle?: ReactNode
onToggle: (modelDbId: number, enabled: boolean) => void
// Overrides the provider label — the model page passes an endpoint-qualified
// one when two custom endpoints serve this same model id (#651).
providerName?: string
// Hover text for that label, supplied ONLY when the caller actually had to
// disambiguate. Never derived from row.endpointScope here: every custom row
// carries a scope, so doing so would leak the base URL of a lone endpoint.
providerTitle?: string
// This provider's own time-window usage (#876), when the caller fetched it.
rateUsage?: RateLimitUsageRow
}) {
const { t } = useI18n()
const guard = (row.headroom ?? 1) * (row.rateLimit ?? 1)
return (
<>
{/* Token budget only when it's a real token count; rate-limited models
(NVIDIA's "free · 40 RPM") show their rate, not "… tok/mo".
The catalog figure is PER KEY. The router credits it once per key
it can rotate through, so an operator with three keys really does
have three times the budget — and reading the bare catalog string
back made it look like adding keys changed nothing (#688). The
multiplier is written as "× N" rather than a sentence so it needs
no translation, and the catalog's own wording ("~10-20M") is kept
instead of a computed total, which would state a range's high end
as if it were fact. */}
{[
(row.monthlyTokenBudgetTokens ?? 0) > 0
? t('models.tokPerMonth', { count: row.monthlyTokenBudget }) + (row.keyCount > 1 ? ` × ${row.keyCount}` : '')
: null,
row.rpmLimit ? t('models.rpmLimit', { count: row.rpmLimit }) : null,
row.rpdLimit ? t('models.rpdLimit', { count: row.rpdLimit }) : null,
].filter(Boolean).join(' · ') || cleanQuotaLabel(row.monthlyTokenBudget) || '—'}
{/* Reliability/speed are measured axes: with zero recorded requests the
scorer only has its exploration priors, so show an explicit "no data"
state instead of prior-valued bars (#580). Intelligence is catalog
metadata and stays. */}
>
)
}
// Shared drag-handle glyph (also used by the Embeddings provider list, so the
// two reorder surfaces look identical).
export const dragDots = (
)
// The rank cell, editable in manual mode (#1317). Dragging a model from rank
// 140 to rank 3 across a long chain is dozens of rows of pointer travel; an
// operator with a target rank in mind should just type it. The number is a
// button that swaps in a tiny inline input: Enter commits, Escape cancels,
// blur commits (matching how lightweight inline editors behave in spreadsheets
// and OS file renames). Out-of-range or unparseable values are clamped by the
// caller; an unchanged rank just closes the editor.
export function RankEditor({ rank, onMoveRank }: { rank: number; onMoveRank: (toRank: number) => void }) {
const { t } = useI18n()
const [editing, setEditing] = useState(false)
const [draft, setDraft] = useState('')
// Set once the edit is settled (Enter, Escape or blur). Unmounting a focused
// input can fire blur after Escape/Enter already ran, so without this guard
// Escape could fall through to the blur-commit path, or Enter commit twice.
const settled = useRef(false)
function commit() {
if (settled.current) return
settled.current = true
setEditing(false)
const n = Number.parseInt(draft, 10)
if (Number.isFinite(n) && n > 0 && n !== rank) onMoveRank(n)
}
function cancel() {
settled.current = true
setEditing(false)
}
if (editing) {
return (
setDraft(e.target.value)}
onClick={e => e.stopPropagation()}
onBlur={commit}
onKeyDown={e => {
e.stopPropagation()
if (e.key === 'Enter') commit()
if (e.key === 'Escape') cancel()
}}
aria-label={t('models.moveToRank')}
className="w-9 rounded border bg-background px-1 py-0.5 text-center font-mono text-xs tabular-nums"
/>
)
}
return (
)
}
// The collapsed header row for a logical-model group: name, provider count,
// union vision/tools badges, the best member's axis bars + score, and a single
// switch that enables/disables every provider in the group.
export function GroupHeaderCells({ group, rank, dragHandle, editableRank, onMoveRank, onToggleGroup, allRows, rateUsage }: {
group: ModelGroupRow
rank: number
dragHandle?: ReactNode
// Manual mode only: renders the rank as a click-to-type jump editor (#1317).
editableRank?: boolean
onMoveRank?: (toRank: number) => void
onToggleGroup: (memberIds: number[], enabled: boolean) => void
// Every configured row, for endpoint disambiguation. Two relays serving one
// model id land in different display groups the moment one copy is renamed,
// so the group's own members are not a complete sibling set (#651).
allRows?: readonly Row[]
// Time-window rate-limit usage by model db id (#876). Fetched ONCE at the page
// level and passed down: a query hook here would open one observer and one
// 15s poll timer per row, i.e. hundreds of them on a real catalog.
rateUsage?: ReadonlyMap
}) {
const { t } = useI18n()
const anyEnabled = group.members.some(m => m.enabled)
const solo = group.members.length === 1
const best = group.members.reduce((b, m) => ((m.score ?? -1) > (b.score ?? -1) ? m : b), group.members[0])
const guard = (best.headroom ?? 1) * (best.rateLimit ?? 1)
// Remaining time-window quota for this group (#876): the member with the most
// headroom decides the badge, since the group stays routable while any one of
// its providers can serve. Lookup is O(members) against the shared map.
const rateRows = rateUsage
? group.members.flatMap(m => rateUsage.get(m.modelDbId) ?? [])
: []
// Honest group display (#580): reliability/speed ranges come only from
// members that were actually measured; when none were, show "no data" rather
// than the shared exploration priors. Intelligence is catalog metadata, so
// its range spans every member. The score cell keeps the best member's score
// (that is what routing would pick) but labels it "best of N" with the
// per-provider breakdown in a tooltip.
const siblings = allRows ?? group.members
const measured = group.members.filter(m => (m.totalRequests ?? 0) > 0)
const scoreBreakdown = group.members
.map(m => `${memberProviderLabel(m, siblings)} ${m.score !== undefined ? m.score.toFixed(3) : '–'}`)
.join('\n')
const vision = group.members.some(m => m.supportsVision)
const tools = group.members.some(m => m.supportsTools)
const quota = groupQuotaBadge(group.members, t)
const maxCtx = groupMaxContext(group.members)
// The model name links to its own page, which lists every provider that serves
// it (replaces the old inline expansion).
const detailId = encodeURIComponent(group.members[0].canonicalId ?? group.members[0].modelId)
// The unified model string to paste into .env / API payloads (#343 quick-copy).
const copyId = group.members[0].canonicalId ?? group.members[0].modelId
return (
<>
{dragHandle ?? ·}
{editableRank && onMoveRank
?
: rank}
e.stopPropagation()} className="flex items-center gap-2 flex-wrap text-left min-w-0">
{group.label}
{solo
? {memberProviderLabel(group.members[0], siblings)}
: memberProviderLabel(m, siblings)).join('\n') })}>
{t('models.providerCount', { count: group.members.length })}}
{quota && (
{quota.text}
)}
{maxCtx > 0 && (
{t('models.ctxBadge', { size: formatContext(maxCtx) })}
)}
{vision && (
{t('models.vision')}
)}
{tools && (
{t('models.tools')}
)}
{/* Quick-copy the unified model id (#343). Stop propagation so it neither
follows the model link nor triggers the row's navigate-on-click. */}
e.stopPropagation()} className="shrink-0">