7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
Redesign Keys page, expand Analytics, hover-reveal model copy button (#467)
Tashfeen9f6e2d3b63b0
diff --git a/client/src/components/keys/add-key-dialog.tsx b/client/src/components/keys/add-key-dialog.tsxnew file mode 100644index 00000000..ccc15d55--- /dev/null+++ b/client/src/components/keys/add-key-dialog.tsx@@ -0,0 +1,51 @@+import { useState } from 'react'+import { X } from 'lucide-react'+import { Dialog, DialogClose, DialogPopup, DialogTitle } from '@/components/ui/dialog'+import { SegmentedControl } from '@/components/ui/segmented-control'+import { useI18n } from '@/i18n'+import { AddKeyForm } from './add-key-form'+import { ImportKeysSection } from './import-keys-section'+import { CustomProviderSection } from './custom-provider-section'++type Pane = 'provider' | 'import' | 'custom'++// The single "Add key" surface: one dialog, three panes (paste a provider key,+// import a file, or point at a custom OpenAI-compatible endpoint). Each pane+// keeps its own mutation and asks the dialog to close on success.+export function AddKeyDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) {+ const { t } = useI18n()+ const [pane, setPane] = useState<Pane>('provider')+ const close = () => onOpenChange(false)++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogPopup maxWidth="max-w-3xl">+ <div className="mb-4 flex items-center justify-between gap-4">+ <DialogTitle>{t('keys.addKey')}</DialogTitle>+ <DialogClose+ aria-label={t('common.dismiss')}+ className="-mr-1 rounded-lg p-1 text-muted-foreground/70 transition-colors outline-none hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50"+ >+ <X className="size-4" />+ </DialogClose>+ </div>++ <SegmentedControl+ value={pane}+ onValueChange={setPane}+ options={[+ { value: 'provider', label: t('keys.paneProviderKey') },+ { value: 'import', label: t('keys.paneImportFile') },+ { value: 'custom', label: t('keys.paneCustomEndpoint') },+ ]}+ ariaLabel={t('keys.addKey')}+ className="mb-5"+ />++ {pane === 'provider' && <AddKeyForm onSuccess={close} />}+ {pane === 'import' && <ImportKeysSection onImported={close} />}+ {pane === 'custom' && <CustomProviderSection onAdded={close} />}+ </DialogPopup>+ </Dialog>+ )+}diff --git a/client/src/components/keys/add-key-form.tsx b/client/src/components/keys/add-key-form.tsxnew file mode 100644index 00000000..606821ac--- /dev/null+++ b/client/src/components/keys/add-key-form.tsx@@ -0,0 +1,137 @@+import { useState } from 'react'+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { apiFetch } from '@/lib/api'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'+import { FieldError } from '@/components/ui/field-error'+import type { Platform } from '../../../../shared/types'+import { useI18n } from '@/i18n'+import { toast } from '@/lib/toast'+import { GetKeyLink, PLATFORMS } from './shared'++// The "Provider key" pane of the Add key dialog: paste a credential for a known+// provider. Extracted verbatim from the old inline KeysPage form so all field+// validation, the keyless/Cloudflare special cases, and the POST /api/keys+// mutation stay identical. On success it toasts and asks the dialog to close.+export function AddKeyForm({ onSuccess }: { onSuccess: () => void }) {+ const { t } = useI18n()+ const queryClient = useQueryClient()+ const [platform, setPlatform] = useState<Platform | ''>('')+ const [apiKey, setApiKey] = useState('')+ const [accountId, setAccountId] = useState('')+ const [label, setLabel] = useState('')+ const [addAttempted, setAddAttempted] = useState(false)++ const addKey = useMutation({+ meta: { silenceToast: true },+ mutationFn: (body: { platform: string; key: string; label?: string }) =>+ apiFetch<{ notice?: string | null }>('/api/keys', { method: 'POST', body: JSON.stringify(body) }),+ onSuccess: (data) => {+ queryClient.invalidateQueries({ queryKey: ['keys'] })+ queryClient.invalidateQueries({ queryKey: ['health'] })+ queryClient.invalidateQueries({ queryKey: ['fallback'] })+ toast.success(t('keys.keyAdded'))+ // Server notice when the key is for a platform with no models in the+ // current catalog tier yet (#438) — surfaced as a toast now that the+ // dialog closes on success.+ if (data?.notice) toast.info(data.notice)+ onSuccess()+ },+ })++ const needsAccountId = platform === 'cloudflare'+ const isKeyless = PLATFORMS.find(p => p.value === platform)?.keyless ?? false++ // Field-level validation: the submit stays clickable and reveals what is+ // missing instead of being silently disabled.+ const platformError = !platform ? t('validation.required') : null+ const keyError = !isKeyless && !apiKey.trim() ? t('validation.required') : null+ const accountIdError = needsAccountId && !accountId.trim() ? t('validation.required') : null++ const handleSubmit = (e: React.FormEvent) => {+ e.preventDefault()+ if (platformError || keyError || accountIdError) {+ setAddAttempted(true)+ return+ }+ setAddAttempted(false)+ // Keyless providers submit an empty key; the backend stores a sentinel.+ const key = isKeyless ? '' : (needsAccountId ? `${accountId}:${apiKey}` : apiKey)+ addKey.mutate({ platform, key, label: label || undefined })+ }++ return (+ <div>+ <form onSubmit={handleSubmit} className="flex flex-wrap gap-3">+ <div className="space-y-1.5">+ <Label className="text-xs">{t('keys.platform')}</Label>+ <Select value={platform} onValueChange={(v) => setPlatform(v as Platform)}>+ <SelectTrigger className="w-[220px]" aria-invalid={addAttempted && !!platformError}>+ <SelectValue placeholder={t('keys.selectPlatform')} />+ </SelectTrigger>+ <SelectContent>+ {PLATFORMS.map(p => (+ <SelectItem key={p.value} value={p.value}>{p.label}</SelectItem>+ ))}+ </SelectContent>+ </Select>+ {addAttempted && <FieldError error={platformError} />}+ {(() => {+ const sel = PLATFORMS.find(p => p.value === platform)+ return sel?.url ? <div className="pt-0.5"><GetKeyLink url={sel.url} /></div> : null+ })()}+ </div>+ {needsAccountId && (+ <div className="space-y-1.5">+ <Label className="text-xs">{t('keys.accountId')}</Label>+ <Input+ value={accountId}+ onChange={e => setAccountId(e.target.value)}+ placeholder="a1b2c3d4…"+ className="w-[200px] font-mono text-xs"+ aria-invalid={addAttempted && !!accountIdError}+ />+ {addAttempted && <FieldError error={accountIdError} />}+ </div>+ )}+ <div className="space-y-1.5 flex-1 min-w-[240px]">+ <Label className="text-xs">{needsAccountId ? t('keys.apiToken') : t('keys.customApiKey')}</Label>+ <Input+ type="password"+ value={isKeyless ? '' : apiKey}+ onChange={e => setApiKey(e.target.value)}+ placeholder={isKeyless ? t('keys.noKeyNeededPlaceholder') : (needsAccountId ? t('keys.bearerTokenPlaceholder') : t('keys.pasteKeyPlaceholder'))}+ className="font-mono text-xs"+ disabled={isKeyless}+ aria-invalid={addAttempted && !!keyError}+ />+ {addAttempted && <FieldError error={keyError} />}+ {isKeyless && (+ <p className="text-[11px] text-muted-foreground">+ {t('keys.keylessHint')}+ </p>+ )}+ </div>+ <div className="space-y-1.5">+ <Label className="text-xs">{t('keys.label')}</Label>+ <div className="flex flex-wrap items-center space-x-3">+ <Input+ value={label}+ onChange={e => setLabel(e.target.value)}+ placeholder={t('keys.customDisplayNameOptional')}+ className="w-[160px]"+ />+ <Button type="submit" size="sm" disabled={addKey.isPending}>+ {addKey.isPending ? t('keys.adding') : isKeyless ? t('keys.enable') : t('keys.addKey')}+ </Button>+ </div>+ </div>+ </form>+ {addKey.isError && (+ <p className="text-destructive text-xs mt-2">{(addKey.error as Error).message}</p>+ )}+ </div>+ )+}diff --git a/client/src/components/keys/custom-provider-section.tsx b/client/src/components/keys/custom-provider-section.tsxindex 94816a0d..820c5a2e 100644--- a/client/src/components/keys/custom-provider-section.tsx+++ b/client/src/components/keys/custom-provider-section.tsx@@ -9,6 +9,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@import { FieldError } from '@/components/ui/field-error'import { isHttpUrl } from '@/lib/validate'import { useI18n } from '@/i18n'+import { toast } from '@/lib/toast'// Split a free-text model field on commas / newlines into a clean id list,// dropping blanks and duplicates so one endpoint can take several models. (#281)@@ -20,7 +21,10 @@ function parseModelList(raw: string): string[] {.filter(s => s.length > 0 && !seen.has(s) && seen.add(s))}-export function CustomProviderSection() {+// Always rendered inside the Add key dialog: no outer section chrome/heading.+// `onAdded` lets that dialog close (and surface a toast) once a custom model is+// saved.+export function CustomProviderSection({ onAdded }: { onAdded?: () => void } = {}) {const { t } = useI18n()const queryClient = useQueryClient()const [customType, setCustomType] = useState<'chat' | 'embedding' | 'image' | 'audio'>('chat')@@ -62,6 +66,10 @@ export function CustomProviderSection() {setModel('')setDisplayName('')setFamily('')+ if (onAdded) {+ toast.success(t('keys.modelAdded'))+ onAdded()+ }},})@@ -118,13 +126,8 @@ export function CustomProviderSection() {? t('keys.addImageModel'): t('keys.addAudioModel')- return (- <section>- <h2 className="text-sm font-medium mb-1">{t('keys.addCustom')}</h2>- <p className="text-xs text-muted-foreground mb-3">- {t('keys.addCustomDescription')}- </p>- <form onSubmit={submit} className="flex flex-wrap items-end gap-3 rounded-3xl border p-4 bg-card">+ const form = (+ <form onSubmit={submit} className="flex flex-wrap items-end gap-3"><div className="space-y-1.5"><Label className="text-xs">{t('keys.customType')}</Label><Select value={customType} onValueChange={(v) => setCustomType(v as typeof customType)}>@@ -197,9 +200,17 @@ export function CustomProviderSection() {{addCustom.isPending ? t('keys.addingCustom') : addLabel}</Button></form>- {addCustom.isError && (- <p className="text-destructive text-xs mt-2">{(addCustom.error as Error).message}</p>- )}- </section>+ )++ const errorLine = addCustom.isError ? (+ <p className="text-destructive text-xs mt-2">{(addCustom.error as Error).message}</p>+ ) : null++ return (+ <div>+ <p className="text-xs text-muted-foreground mb-3">{t('keys.addCustomDescription')}</p>+ {form}+ {errorLine}+ </div>)}diff --git a/client/src/components/keys/import-keys-section.tsx b/client/src/components/keys/import-keys-section.tsxindex ab740051..229c7cdd 100644--- a/client/src/components/keys/import-keys-section.tsx+++ b/client/src/components/keys/import-keys-section.tsx@@ -9,6 +9,7 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@import type { ImportKey, ImportSelectedResponse, Platform, PreviewKey, PreviewResponse } from '../../../../shared/types'import { Upload } from 'lucide-react'import { useI18n } from '@/i18n'+import { toast } from '@/lib/toast'import { PLATFORMS } from './shared'interface ImportRow extends PreviewKey {@@ -17,13 +18,15 @@ interface ImportRow extends PreviewKey {visible: boolean}-export function ImportKeysSection() {+// Always rendered inside the Add key dialog: no outer section chrome/heading.+// `onImported` lets that dialog close (and surface a result toast) once a batch+// import succeeds.+export function ImportKeysSection({ onImported }: { onImported?: () => void } = {}) {const { t } = useI18n()const queryClient = useQueryClient()const [files, setFiles] = useState<File[]>([])const [rows, setRows] = useState<ImportRow[]>([])const [skipped, setSkipped] = useState<string[]>([])- const [result, setResult] = useState<ImportSelectedResponse | null>(null)const importablePlatforms = PLATFORMS.filter(p => !p.keyless)@@ -51,7 +54,6 @@ export function ImportKeysSection() {}}))setSkipped(data.skipped)- setResult(null)},})@@ -63,10 +65,15 @@ export function ImportKeysSection() {body: JSON.stringify({ keys }),}),onSuccess: (data) => {- setResult(data)queryClient.invalidateQueries({ queryKey: ['keys'] })queryClient.invalidateQueries({ queryKey: ['health'] })queryClient.invalidateQueries({ queryKey: ['fallback'] })+ // The dialog closes on success, so surface the imported/failed counts as+ // a toast.+ if (onImported) {+ toast.success(t('keys.importResult', { imported: data.imported, failed: data.errors.length }))+ onImported()+ }},})@@ -87,31 +94,25 @@ export function ImportKeysSection() {setFiles(nextFiles)setRows([])setSkipped([])- setResult(null)preview.reset()importSelected.reset()}- return (- <section>- <div className="mb-3 flex flex-wrap items-center justify-between gap-3">- <div>- <h2 className="text-sm font-medium">{t('keys.importKeys')}</h2>- <p className="text-xs text-muted-foreground mt-0.5">{t('keys.importKeysDescription')}</p>- </div>- <Button- type="button"- size="sm"- variant="outline"- onClick={() => preview.mutate(files)}- disabled={files.length === 0 || preview.isPending}- >- <Upload className="size-3.5" />- {preview.isPending ? t('keys.previewing') : t('keys.previewFiles')}- </Button>- </div>+ const previewButton = (+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={() => preview.mutate(files)}+ disabled={files.length === 0 || preview.isPending}+ >+ <Upload className="size-3.5" />+ {preview.isPending ? t('keys.previewing') : t('keys.previewFiles')}+ </Button>+ )- <div className="rounded-3xl border bg-card p-4">+ const innerContent = (+ <><div className="flex flex-wrap items-end gap-3"><div className="min-w-[260px] flex-1 space-y-1.5"><Label className="text-xs">{t('keys.importFiles')}</Label>@@ -135,7 +136,7 @@ export function ImportKeysSection() {)}{rows.length > 0 && (- <div className="mt-4 overflow-hidden rounded-2xl border">+ <div className="mt-4 overflow-x-auto rounded-2xl border"><Table><TableHeader><TableRow>@@ -236,12 +237,16 @@ export function ImportKeysSection() {{importSelected.isError && (<p className="mt-3 text-xs text-destructive">{(importSelected.error as Error).message}</p>)}- {result && (- <p className="mt-3 text-xs text-muted-foreground">- {t('keys.importResult', { imported: result.imported, failed: result.errors.length })}- </p>- )}+ </>+ )++ return (+ <div className="space-y-4">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <p className="text-xs text-muted-foreground">{t('keys.importKeysDescription')}</p>+ {previewButton}</div>- </section>+ {innerContent}+ </div>)}diff --git a/client/src/components/keys/provider-list.tsx b/client/src/components/keys/provider-list.tsxnew file mode 100644index 00000000..1bddc1cb--- /dev/null+++ b/client/src/components/keys/provider-list.tsx@@ -0,0 +1,483 @@+import { useState, useRef, useEffect } from 'react'+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'+import { apiFetch } from '@/lib/api'+import { Button, buttonVariants } from '@/components/ui/button'+import { ConfirmButton } from '@/components/confirm-button'+import { Input } from '@/components/ui/input'+import { Switch } from '@/components/ui/switch'+import { Badge } from '@/components/ui/badge'+import { SegmentedControl } from '@/components/ui/segmented-control'+import { EmptyState } from '@/components/empty-state'+import { TableSkeleton } from '@/components/ui/skeleton'+import { Tooltip } from '@/components/tooltip'+import {+ DropdownMenu,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuCheckboxItem,+} from '@/components/ui/dropdown-menu'+import { ChevronDown, ExternalLink, KeyRound, MoreHorizontal, Pencil, Plus, RefreshCw, Search, Trash2 } from 'lucide-react'+import type { ApiKey, ApiKeyModel } from '../../../../shared/types'+import { formatSqliteUtcToLocalTime } from '@/lib/utils'+import { useI18n } from '@/i18n'+import {+ PLATFORMS,+ CUSTOM_GROUP,+ CUSTOM_MODEL_KIND_LABEL,+ customModelDeleteKey,+ customModelDeletePath,+ statusDot,+ statusLabelKey,+} from './shared'+import type { HealthData } from './shared'++type StatusFilter = 'all' | 'healthy' | 'issues' | 'disabled'++// The Providers tab body: a filter toolbar over a list of collapsible provider+// groups. Owns the keys/health/proxy queries and every per-key mutation so+// KeysPage stays a thin shell. `onAddKey` opens the shared Add key dialog.+export function ProviderList({ onAddKey }: { onAddKey: () => void }) {+ const { t } = useI18n()+ const queryClient = useQueryClient()++ const [editingKeyId, setEditingKeyId] = useState<number | null>(null)+ const [editingLabel, setEditingLabel] = useState('')+ const [expandedKeyIds, setExpandedKeyIds] = useState<Set<number>>(new Set())+ // Explicit user open/closed overrides per provider group; absent = default.+ const [groupOverrides, setGroupOverrides] = useState<Map<string, boolean>>(new Map())+ const [search, setSearch] = useState('')+ const [statusFilter, setStatusFilter] = useState<StatusFilter>('all')+ const editInputRef = useRef<HTMLInputElement>(null)++ const { data: keys = [], isLoading } = useQuery<ApiKey[]>({+ queryKey: ['keys'],+ queryFn: () => apiFetch('/api/keys'),+ })++ const { data: healthData } = useQuery<HealthData>({+ queryKey: ['health'],+ queryFn: () => apiFetch('/api/health'),+ refetchInterval: 30000,+ })++ const { data: proxyData } = useQuery<{ proxyUrl: string; enabled: boolean; bypassPlatforms: string[]; active: boolean }>({+ queryKey: ['proxy-url'],+ queryFn: () => apiFetch('/api/settings/proxy'),+ })+ const bypassPlatforms = proxyData?.bypassPlatforms ?? []+ const proxyEnabled = proxyData?.enabled ?? true++ const deleteKey = useMutation({+ mutationFn: (id: number) => apiFetch(`/api/keys/${id}`, { method: 'DELETE' }),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['keys'] })+ queryClient.invalidateQueries({ queryKey: ['health'] })+ },+ })++ const deleteCustomModel = useMutation({+ mutationFn: (model: ApiKeyModel) => apiFetch(customModelDeletePath(model), { method: 'DELETE' }),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['keys'] })+ queryClient.invalidateQueries({ queryKey: ['health'] })+ queryClient.invalidateQueries({ queryKey: ['fallback'] })+ queryClient.invalidateQueries({ queryKey: ['models'] })+ queryClient.invalidateQueries({ queryKey: ['embeddings'] })+ queryClient.invalidateQueries({ queryKey: ['media'] })+ },+ })++ const checkKey = useMutation({+ mutationFn: (keyId: number) => apiFetch(`/api/health/check/${keyId}`, { method: 'POST' }),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['health'] })+ queryClient.invalidateQueries({ queryKey: ['keys'] })+ },+ })++ const togglePlatform = useMutation({+ mutationFn: ({ platform, enabled }: { platform: string; enabled: boolean }) =>+ apiFetch(`/api/keys/platform/${platform}`, {+ method: 'PATCH',+ body: JSON.stringify({ enabled }),+ }),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['keys'] })+ queryClient.invalidateQueries({ queryKey: ['health'] })+ queryClient.invalidateQueries({ queryKey: ['fallback'] })+ },+ })++ const updateKey = useMutation({+ mutationFn: ({ id, label }: { id: number; label: string }) =>+ apiFetch(`/api/keys/${id}`, {+ method: 'PATCH',+ body: JSON.stringify({ label }),+ }),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['keys'] })+ setEditingKeyId(null)+ setEditingLabel('')+ },+ })++ const toggleBypass = useMutation({+ mutationFn: (platform: string) => {+ const next = bypassPlatforms.includes(platform)+ ? bypassPlatforms.filter(p => p !== platform)+ : [...bypassPlatforms, platform]+ return apiFetch('/api/settings/proxy', { method: 'PUT', body: JSON.stringify({ bypassPlatforms: next }) })+ },+ onSuccess: () => queryClient.invalidateQueries({ queryKey: ['proxy-url'] }),+ })++ function startEditing(key: ApiKey) {+ setEditingKeyId(key.id)+ setEditingLabel(key.label)+ }++ function cancelEditing() {+ setEditingKeyId(null)+ setEditingLabel('')+ }++ function saveEditing(id: number) {+ if (editingLabel !== undefined) {+ updateKey.mutate({ id, label: editingLabel })+ }+ }++ function toggleExpandedKey(id: number) {+ setExpandedKeyIds(prev => {+ const next = new Set(prev)+ if (next.has(id)) next.delete(id)+ else next.add(id)+ return next+ })+ }++ useEffect(() => {+ if (editingKeyId !== null && editInputRef.current) {+ editInputRef.current.focus()+ }+ }, [editingKeyId])++ const healthKeyMap = new Map<number, { status: string; lastCheckedAt: string | null }>()+ for (const k of healthData?.keys ?? []) healthKeyMap.set(k.id, k)+ const statusOf = (k: ApiKey) => healthKeyMap.get(k.id)?.status ?? k.status++ const grouped = [...PLATFORMS, CUSTOM_GROUP].map(p => ({+ ...p,+ keys: keys.filter(k => k.platform === p.value),+ })).filter(p => p.keys.length > 0)++ const totalProviders = grouped.length+ const totalKeys = grouped.reduce((n, g) => n + g.keys.length, 0)++ const q = search.trim().toLowerCase()++ function matchStatus(group: (typeof grouped)[number]): boolean {+ const enabled = group.keys.some(k => k.enabled)+ const hasIssue = group.keys.some(k => statusOf(k) !== 'healthy')+ switch (statusFilter) {+ case 'healthy': return enabled && !hasIssue+ case 'issues': return hasIssue+ case 'disabled': return !enabled+ default: return true+ }+ }++ // Search narrows either whole groups (label match) or the keys within them+ // (label / masked-key match); the status filter then trims the result set.+ const visibleGroups = grouped+ .map(group => {+ if (!q) return group+ if (group.label.toLowerCase().includes(q)) return group+ const matchingKeys = group.keys.filter(k =>+ (k.label ?? '').toLowerCase().includes(q) ||+ (k.maskedKey ?? '').toLowerCase().includes(q),+ )+ return { ...group, keys: matchingKeys }+ })+ .filter(group => group.keys.length > 0 && matchStatus(group))++ function isGroupExpanded(group: (typeof grouped)[number]): boolean {+ if (q) return true // an active search auto-expands every matching group+ const override = groupOverrides.get(group.value)+ if (override !== undefined) return override+ const hasIssue = group.keys.some(k => statusOf(k) !== 'healthy')+ return hasIssue || grouped.length <= 3+ }++ function toggleGroup(value: string, expanded: boolean) {+ setGroupOverrides(prev => {+ const next = new Map(prev)+ next.set(value, !expanded)+ return next+ })+ }++ if (isLoading) return <TableSkeleton rows={4} />++ if (keys.length === 0) {+ return (+ <EmptyState+ icon={KeyRound}+ title={t('keys.noProviderKeys')}+ action={+ <Button size="sm" onClick={onAddKey}>+ <Plus className="size-3.5" />+ {t('keys.addKey')}+ </Button>+ }+ />+ )+ }++ return (+ <div>+ <div className="mb-4 flex flex-wrap items-center gap-3">+ <div className="relative w-full sm:w-64">+ <Search className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />+ <Input+ value={search}+ onChange={e => setSearch(e.target.value)}+ placeholder={t('keys.filterPlaceholder')}+ className="h-8 pl-8"+ />+ </div>+ <SegmentedControl+ value={statusFilter}+ onValueChange={setStatusFilter}+ options={[+ { value: 'all', label: t('keys.filterAll') },+ { value: 'healthy', label: t('keys.filterHealthy') },+ { value: 'issues', label: t('keys.filterIssues') },+ { value: 'disabled', label: t('keys.filterDisabled') },+ ]}+ ariaLabel={t('keys.filterAll')}+ />+ <span className="flex-1" />+ <span className="text-xs text-muted-foreground tabular-nums">+ {t('keys.providerCountSummary', { providers: totalProviders, keys: totalKeys })}+ </span>+ </div>++ {visibleGroups.length === 0 ? (+ <EmptyState title={t('keys.noFilterMatch')} />+ ) : (+ <div className="space-y-4">+ {visibleGroups.map(group => {+ const expanded = isGroupExpanded(group)+ const healthyCount = group.keys.filter(k => statusOf(k) === 'healthy').length+ const issueCount = group.keys.filter(k => statusOf(k) !== 'healthy').length+ return (+ <div key={group.value}>+ <div className="flex items-center gap-2 pb-2">+ <Switch+ checked={group.keys.some(k => k.enabled)}+ onCheckedChange={(checked) =>+ togglePlatform.mutate({ platform: group.value, enabled: checked })+ }+ disabled={togglePlatform.isPending}+ />+ <button+ type="button"+ onClick={() => toggleGroup(group.value, expanded)}+ className="flex min-w-0 flex-1 items-center gap-2 text-left"+ aria-expanded={expanded}+ >+ <h3 className="text-sm font-medium">{group.label}</h3>+ <Badge variant="secondary" className="tabular-nums">{group.keys.length}</Badge>+ <span className="inline-flex items-center gap-2 text-xs text-muted-foreground">+ {healthyCount > 0 && (+ <span className="inline-flex items-center gap-1">+ <span className="size-1.5 rounded-full bg-emerald-500" />+ {t('keys.summaryHealthy', { count: healthyCount })}+ </span>+ )}+ {issueCount > 0 && (+ <span className="inline-flex items-center gap-1">+ <span className="size-1.5 rounded-full bg-rose-500" />+ {t(issueCount === 1 ? 'keys.summaryIssueOne' : 'keys.summaryIssueOther', { count: issueCount })}+ </span>+ )}+ </span>+ </button>+ {(group.url || proxyEnabled) && (+ <DropdownMenu>+ <DropdownMenuTrigger+ className={buttonVariants({ variant: 'ghost', size: 'icon-xs' })}+ aria-label={t('keys.providerActions')}+ >+ <MoreHorizontal />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-52">+ {group.url && (+ <DropdownMenuItem onClick={() => window.open(group.url, '_blank', 'noopener,noreferrer')}>+ {t('keys.getApiKey')}+ <ExternalLink className="ml-auto size-3.5" />+ </DropdownMenuItem>+ )}+ {proxyEnabled && (+ <DropdownMenuCheckboxItem+ checked={!bypassPlatforms.includes(group.value)}+ onCheckedChange={() => toggleBypass.mutate(group.value)}+ closeOnClick={false}+ >+ {t('keys.routeViaProxy')}+ </DropdownMenuCheckboxItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ <button+ type="button"+ onClick={() => toggleGroup(group.value, expanded)}+ aria-label={expanded ? t('common.hide') : t('common.show')}+ className={buttonVariants({ variant: 'ghost', size: 'icon-xs' })}+ >+ <ChevronDown className={`size-4 text-muted-foreground transition-transform ${expanded ? '' : '-rotate-90'}`} />+ </button>+ </div>++ {expanded && (+ <div className="rounded-2xl border divide-y bg-card overflow-hidden">+ {group.keys.map(k => {+ const status = statusOf(k)+ const lastChecked = healthKeyMap.get(k.id)?.lastCheckedAt+ const isEditing = editingKeyId === k.id+ const customModels = k.models ?? []+ const hasCustomModels = customModels.length > 0+ const isExpanded = expandedKeyIds.has(k.id)+ const isChecking = checkKey.isPending && checkKey.variables === k.id+ return (+ <div key={k.id} className="bg-card">+ <div className="group/krow flex items-center gap-3 px-4 py-3 hover:bg-muted/40 transition-colors">+ <span className={`size-1.5 rounded-full flex-shrink-0 ${statusDot[status] ?? statusDot.unknown}`} />+ {hasCustomModels && (+ <Button+ type="button"+ variant="ghost"+ size="xs"+ className="size-6 p-0 text-muted-foreground"+ onClick={() => toggleExpandedKey(k.id)}+ title={isExpanded ? t('common.hide') : t('common.show')}+ >+ <ChevronDown className={`size-3 transition-transform ${isExpanded ? 'rotate-180' : ''}`} />+ </Button>+ )}+ <code className="text-xs font-mono flex-shrink-0">{k.maskedKey}</code>+ {isEditing ? (+ <Input+ ref={editInputRef}+ value={editingLabel}+ onChange={e => setEditingLabel(e.target.value)}+ onKeyDown={e => {+ if (e.key === 'Enter') saveEditing(k.id)+ if (e.key === 'Escape') cancelEditing()+ }}+ onBlur={() => saveEditing(k.id)}+ className="h-6 w-[160px] text-xs"+ disabled={updateKey.isPending}+ />+ ) : (+ <>+ {k.label && <span className="text-xs text-muted-foreground">{k.label}</span>}+ {k.baseUrl && (+ <code className="text-[11px] text-muted-foreground font-mono truncate max-w-[260px]" title={k.baseUrl}>+ {k.baseUrl}+ </code>+ )}+ </>+ )}+ <span className="text-xs text-muted-foreground">{statusLabelKey[status] ? t(statusLabelKey[status]) : status}</span>+ <div className="flex-1" />+ {lastChecked && (+ <span className="text-[11px] text-muted-foreground tabular-nums">+ {formatSqliteUtcToLocalTime(lastChecked, { hour: '2-digit', minute: '2-digit' })}+ </span>+ )}+ <div className="flex items-center gap-0.5 opacity-0 transition-opacity group-hover/krow:opacity-100 focus-within:opacity-100 pointer-coarse:opacity-100">+ {!isEditing && (+ <Button+ variant="ghost"+ size="icon-xs"+ onClick={() => startEditing(k)}+ aria-label={t('keys.editLabel')}+ title={t('keys.editLabel')}+ >+ <Pencil className="size-3" />+ </Button>+ )}+ <Tooltip text={t('keys.checkNow')}>+ <Button+ variant="ghost"+ size="icon-xs"+ onClick={() => checkKey.mutate(k.id)}+ disabled={checkKey.isPending}+ aria-label={t('keys.checkNow')}+ >+ <RefreshCw className={`size-3 ${isChecking ? 'animate-spin' : ''}`} />+ </Button>+ </Tooltip>+ <ConfirmButton+ variant="ghost"+ size="icon-xs"+ armedSize="xs"+ className="text-muted-foreground hover:text-destructive"+ confirmLabel={t('keys.confirmRemove')}+ onConfirm={() => deleteKey.mutate(k.id)}+ disabled={deleteKey.isPending}+ title={t('common.remove')}+ aria-label={t('common.remove')}+ >+ <Trash2 className="size-3" />+ </ConfirmButton>+ </div>+ </div>+ {hasCustomModels && isExpanded && (+ <div className="flex flex-wrap gap-2 border-t bg-muted/20 px-4 py-3 pl-12">+ {customModels.map(model => {+ const modelKey = customModelDeleteKey(model)+ return (+ <div key={modelKey} className="inline-flex min-w-0 items-center gap-2 rounded-md border bg-background px-2 py-1 text-[11px]">+ <span className="rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted-foreground">+ {t(CUSTOM_MODEL_KIND_LABEL[model.kind])}+ </span>+ <span className="max-w-[180px] truncate font-medium" title={model.modelId}>+ {model.displayName}+ </span>+ {model.family && (+ <code className="max-w-[160px] truncate text-muted-foreground" title={model.family}>+ {model.family}+ </code>+ )}+ <ConfirmButton+ className="h-5 px-1 text-muted-foreground hover:text-destructive"+ disabled={deleteCustomModel.isPending}+ onConfirm={() => deleteCustomModel.mutate(model)}+ title={t('common.remove')}+ aria-label={t('common.remove')}+ >+ <Trash2 className="size-3" />+ </ConfirmButton>+ </div>+ )+ })}+ </div>+ )}+ </div>+ )+ })}+ </div>+ )}+ </div>+ )+ })}+ </div>+ )}+ </div>+ )+}diff --git a/client/src/components/model-table.tsx b/client/src/components/model-table.tsxindex c02e2897..0f53b40c 100644--- a/client/src/components/model-table.tsx+++ b/client/src/components/model-table.tsx@@ -209,7 +209,11 @@ export function GroupHeaderCells({ group, rank, dragHandle, onToggleGroup }: {{/* Quick-copy the unified model id (#343). Stop propagation so it neitherfollows the model link nor triggers the row's navigate-on-click. */}<span onClick={e => e.stopPropagation()} className="shrink-0">- <CopyButton text={copyId} className="size-6" label={t('models.copyModelId')} />+ <CopyButton+ text={copyId}+ label={t('models.copyModelId')}+ className="size-6 border-0 bg-transparent hover:bg-muted opacity-0 transition-opacity group-hover/row:opacity-100 focus-visible:opacity-100 pointer-coarse:opacity-100"+ /></span></div></td>@@ -251,7 +255,7 @@ export function SortableGroupRow({ group, rank, onToggleGroup }: {ref={setNodeRef}style={{ transform: CSS.Transform.toString(transform), transition }}onClick={() => navigate(`/models/chat/${detailId}`)}- className={`border-b last:border-0 bg-card cursor-pointer transition-colors hover:[&>td]:bg-muted/50 [&>td:first-child]:rounded-l-lg [&>td:last-child]:rounded-r-lg ${isDragging ? 'opacity-50' : ''} ${anyEnabled ? '' : 'opacity-50'}`}+ className={`group/row border-b last:border-0 bg-card cursor-pointer transition-colors hover:[&>td]:bg-muted/50 [&>td:first-child]:rounded-l-lg [&>td:last-child]:rounded-r-lg ${isDragging ? 'opacity-50' : ''} ${anyEnabled ? '' : 'opacity-50'}`}><GroupHeaderCells group={group} rank={rank} dragHandle={handle} onToggleGroup={onToggleGroup} /></tr>diff --git a/client/src/components/ui/dialog.tsx b/client/src/components/ui/dialog.tsxnew file mode 100644index 00000000..d2609736--- /dev/null+++ b/client/src/components/ui/dialog.tsx@@ -0,0 +1,71 @@+import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"++import { cn } from "@/lib/utils"++// App dialog primitive wrapping @base-ui/react Dialog. Centered card popup with+// a blurred backdrop; Escape + outside-press close and focus management come+// from base-ui. `modal` (default) traps focus and locks page scroll so the+// popup's own overflow-y is what scrolls, not the page behind it.+function Dialog({ ...props }: DialogPrimitive.Root.Props) {+ return <DialogPrimitive.Root data-slot="dialog" {...props} />+}++function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {+ return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />+}++function DialogClose({ ...props }: DialogPrimitive.Close.Props) {+ return <DialogPrimitive.Close data-slot="dialog-close" {...props} />+}++function DialogPopup({+ className,+ children,+ maxWidth = "max-w-lg",+ ...props+}: DialogPrimitive.Popup.Props & {+ /** Tailwind max-width class for the popup; overridable per dialog. */+ maxWidth?: string+}) {+ return (+ <DialogPrimitive.Portal>+ <DialogPrimitive.Backdrop+ data-slot="dialog-backdrop"+ className="fixed inset-0 z-50 bg-black/40 backdrop-blur-sm duration-100 data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0"+ />+ <DialogPrimitive.Popup+ data-slot="dialog-popup"+ className={cn(+ "fixed top-1/2 left-1/2 z-50 w-[calc(100%-2rem)] max-h-[85vh] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-3xl border bg-card p-6 text-card-foreground shadow-xl ring-1 ring-foreground/10 duration-100 outline-none data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",+ maxWidth,+ className,+ )}+ {...props}+ >+ {children}+ </DialogPrimitive.Popup>+ </DialogPrimitive.Portal>+ )+}++function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {+ return (+ <DialogPrimitive.Title+ data-slot="dialog-title"+ className={cn("font-heading text-base leading-snug font-medium", className)}+ {...props}+ />+ )+}++function DialogDescription({ className, ...props }: DialogPrimitive.Description.Props) {+ return (+ <DialogPrimitive.Description+ data-slot="dialog-description"+ className={cn("text-sm text-muted-foreground", className)}+ {...props}+ />+ )+}++export { Dialog, DialogTrigger, DialogClose, DialogPopup, DialogTitle, DialogDescription }diff --git a/client/src/i18n/locales/en.json b/client/src/i18n/locales/en.jsonindex 37facaf3..c81718ce 100644--- a/client/src/i18n/locales/en.json+++ b/client/src/i18n/locales/en.json@@ -56,7 +56,6 @@"noData": "No data yet","unsavedChanges": "Unsaved changes","saveChanges": "Save changes",- "check": "Check","remove": "Remove","unknownError": "Unknown error","model": "Model",@@ -222,6 +221,7 @@"familyHaiku": "Haiku","selectPlatform": "Select a provider","addKey": "Add key",+ "keyAdded": "Key added","adding": "Adding…","selectProvider": "Select a provider…","accountId": "Account ID",@@ -250,6 +250,7 @@"customFamilyPlaceholder": "defaults to model id","customApiKey": "API key","addModel": "Add model",+ "modelAdded": "Model added","addModels": "Add {count} models","addEmbeddingModel": "Add embedding","addImageModel": "Add image model",@@ -265,7 +266,9 @@"unifiedKeyDescAfter": "; it authenticates requests to this proxy.","serverUnreachableBefore": "Can't reach the server on ","serverUnreachableAfter": ". Make sure the backend is running. npm run dev starts both, and the server logs print under the server prefix.",- "addProvider": "Add a provider key",+ "paneProviderKey": "Provider key",+ "paneImportFile": "Import file",+ "paneCustomEndpoint": "Custom endpoint","platform": "Platform","apiToken": "API token","noKeyNeededPlaceholder": "No API key needed",@@ -274,10 +277,19 @@"keylessHint": "No API key needed: this provider's free tier is anonymous (rate-limited per IP).","enable": "Enable","noProviderKeys": "No provider keys yet. Add one above to start routing.",- "configuredProviders": "Configured providers",- "proxyToggleLabel": "proxy",- "keyCountOne": "{count} key",- "keyCountOther": "{count} keys",+ "filterPlaceholder": "Filter providers or keys",+ "filterAll": "All",+ "filterHealthy": "Healthy",+ "filterIssues": "Issues",+ "filterDisabled": "Disabled",+ "noFilterMatch": "No providers match your filters.",+ "providerCountSummary": "{providers} providers · {keys} keys",+ "summaryHealthy": "{count} healthy",+ "summaryIssueOne": "{count} issue",+ "summaryIssueOther": "{count} issues",+ "providerActions": "Provider actions",+ "routeViaProxy": "Route via proxy",+ "checkNow": "Check now","proxyEnvHintBefore": "Also configurable via the ","proxyEnvHintAfter": " environment variable (takes precedence). Leave blank to disable. Examples:","importKeys": "Import provider keys",@@ -322,15 +334,21 @@"range24h": "24h","range7d": "7d","range30d": "30d",+ "range90d": "90d","requests": "Requests","successRate": "Success rate","inputTokens": "Input tokens","outputTokens": "Output tokens","avgLatency": "Avg latency",+ "p95Latency": "P95 latency",+ "avgTtft": "Avg TTFT","estSavings": "Est. savings","requestsByProvider": "Requests by provider","avgLatencyByProvider": "Avg latency by provider",+ "ttftByProvider": "Time to first token by provider",+ "ttftEmpty": "No time to first token recorded yet.","requestsOverTime": "Requests over time",+ "tokensOverTime": "Tokens over time","byModel": "By model","byPlatform": "By platform","errors": "Errors",@@ -342,9 +360,11 @@"savingsHintExact": "You actually saved ${actual} over the last {range}. That is what the same tokens would have cost on paid APIs, priced per model. The number shown is your real 30-day total.","requestsHintPinned": "{pinned} of these requests pinned a specific model by name. {honored} were served by the pinned model; {failed} failed over to a different one. The rest were auto-routed.","requestsHintAuto": "All requests in this period were auto-routed; no client pinned a specific model by name.",+ "requestsHintTypes": "{chat} chat and {embedding} embedding requests.","rangeLabel24h": "24 hours","rangeLabel7d": "7 days","rangeLabel30d": "30 days",+ "rangeLabel90d": "90 days","spanDays": "{count} days","spanHours": "{count} hours","latencyMs": "Latency (ms)",@@ -356,6 +376,9 @@"message": "Message","time": "Time","perModelBreakdown": "Per-model breakdown",+ "usageByKey": "Usage by key",+ "keyColumn": "Key",+ "keyLabelFallback": "Key #{id}","errorsByProvider": "Errors by provider","recentErrors": "Recent errors","noErrors": "No errors"diff --git a/client/src/i18n/locales/es.json b/client/src/i18n/locales/es.jsonindex b09a37ed..382deed4 100644--- a/client/src/i18n/locales/es.json+++ b/client/src/i18n/locales/es.json@@ -56,7 +56,6 @@"noData": "Aún no hay datos","unsavedChanges": "Cambios sin guardar","saveChanges": "Guardar cambios",- "check": "Comprobar","remove": "Quitar","unknownError": "Error desconocido","model": "Modelo",@@ -204,6 +203,7 @@"familyHaiku": "Haiku","selectPlatform": "Selecciona un proveedor","addKey": "Añadir clave",+ "keyAdded": "Clave añadida","adding": "Añadiendo…","selectProvider": "Selecciona un proveedor…","accountId": "ID de cuenta",@@ -224,6 +224,7 @@"customDisplayNameOptional": "opcional","customApiKey": "Clave API","addModel": "Añadir modelo",+ "modelAdded": "Modelo añadido","addModels": "Añadir {count} modelos","addingCustom": "Añadiendo…","getApiKey": "Obtener clave API",@@ -236,7 +237,9 @@"unifiedKeyDescAfter": " de OpenAI; autentica las solicitudes a este proxy.","serverUnreachableBefore": "No se puede conectar con el servidor en ","serverUnreachableAfter": ". Asegúrate de que el backend esté en ejecución. npm run dev inicia ambos, y los registros del servidor se imprimen con el prefijo server.",- "addProvider": "Añadir una clave de proveedor",+ "paneProviderKey": "Clave de proveedor",+ "paneImportFile": "Importar archivo",+ "paneCustomEndpoint": "Endpoint personalizado","platform": "Plataforma","apiToken": "Token de API","noKeyNeededPlaceholder": "No se necesita clave API",@@ -245,10 +248,19 @@"keylessHint": "No se necesita clave API: el nivel gratuito de este proveedor es anónimo (con límite por IP).","enable": "Habilitar","noProviderKeys": "Aún no hay claves de proveedor. Añade una arriba para empezar a enrutar.",- "configuredProviders": "Proveedores configurados",- "proxyToggleLabel": "proxy",- "keyCountOne": "{count} clave",- "keyCountOther": "{count} claves",+ "filterPlaceholder": "Filtrar proveedores o claves",+ "filterAll": "Todos",+ "filterHealthy": "Correctos",+ "filterIssues": "Con problemas",+ "filterDisabled": "Deshabilitados",+ "noFilterMatch": "Ningún proveedor coincide con tus filtros.",+ "providerCountSummary": "{providers} proveedores · {keys} claves",+ "summaryHealthy": "{count} correctos",+ "summaryIssueOne": "{count} problema",+ "summaryIssueOther": "{count} problemas",+ "providerActions": "Acciones del proveedor",+ "routeViaProxy": "Enrutar por proxy",+ "checkNow": "Comprobar ahora","proxyEnvHintBefore": "También configurable mediante la variable de entorno ","proxyEnvHintAfter": " (tiene prioridad). Déjalo en blanco para desactivar. Ejemplos:","confirmRemove": "¿Confirmar?",@@ -304,15 +316,21 @@"range24h": "24 h","range7d": "7 d","range30d": "30 d",+ "range90d": "90 d","requests": "Solicitudes","successRate": "Tasa de éxito","inputTokens": "Tokens de entrada","outputTokens": "Tokens de salida","avgLatency": "Latencia media",+ "p95Latency": "Latencia P95",+ "avgTtft": "TTFT medio","estSavings": "Ahorro est.","requestsByProvider": "Solicitudes por proveedor","avgLatencyByProvider": "Latencia media por proveedor",+ "ttftByProvider": "Tiempo hasta el primer token por proveedor",+ "ttftEmpty": "Aún no se ha registrado el tiempo hasta el primer token.","requestsOverTime": "Solicitudes a lo largo del tiempo",+ "tokensOverTime": "Tokens a lo largo del tiempo","byModel": "Por modelo","byPlatform": "Por plataforma","errors": "Errores",@@ -324,9 +342,11 @@"savingsHintExact": "Realmente ahorraste {actual} $ en los últimos {range}. Eso es lo que los mismos tokens habrían costado en APIs de pago, con precio por modelo. La cifra mostrada es tu total real de 30 días.","requestsHintPinned": "{pinned} de estas solicitudes fijaron un modelo concreto por su nombre. {honored} fueron atendidas por el modelo fijado; {failed} conmutaron a otro. El resto se enrutaron automáticamente.","requestsHintAuto": "Todas las solicitudes de este periodo se enrutaron automáticamente; ningún cliente fijó un modelo concreto por su nombre.",+ "requestsHintTypes": "{chat} solicitudes de chat y {embedding} de embeddings.","rangeLabel24h": "24 horas","rangeLabel7d": "7 días","rangeLabel30d": "30 días",+ "rangeLabel90d": "90 días","spanDays": "{count} días","spanHours": "{count} horas","latencyMs": "Latencia (ms)",@@ -338,6 +358,9 @@"message": "Mensaje","time": "Hora","perModelBreakdown": "Desglose por modelo",+ "usageByKey": "Uso por clave",+ "keyColumn": "Clave",+ "keyLabelFallback": "Clave n.º {id}","errorsByProvider": "Errores por proveedor","recentErrors": "Errores recientes","noErrors": "Sin errores"diff --git a/client/src/i18n/locales/fr.json b/client/src/i18n/locales/fr.jsonindex 7aa3ebbd..77d3a964 100644--- a/client/src/i18n/locales/fr.json+++ b/client/src/i18n/locales/fr.json@@ -56,7 +56,6 @@"noData": "Aucune donnée pour l'instant","unsavedChanges": "Modifications non enregistrées","saveChanges": "Enregistrer les modifications",- "check": "Vérifier","remove": "Supprimer","unknownError": "Erreur inconnue","model": "Modèle",@@ -204,6 +203,7 @@"familyHaiku": "Haiku","selectPlatform": "Sélectionner un fournisseur","addKey": "Ajouter une clé",+ "keyAdded": "Clé ajoutée","adding": "Ajout…","selectProvider": "Sélectionner un fournisseur…","accountId": "ID de compte",@@ -224,6 +224,7 @@"customDisplayNameOptional": "facultatif","customApiKey": "Clé API","addModel": "Ajouter un modèle",+ "modelAdded": "Modèle ajouté","addModels": "Ajouter {count} modèles","addingCustom": "Ajout…","getApiKey": "Obtenir une clé API",@@ -236,7 +237,9 @@"unifiedKeyDescAfter": " OpenAI ; elle authentifie les requêtes vers ce proxy.","serverUnreachableBefore": "Impossible de joindre le serveur sur ","serverUnreachableAfter": ". Vérifiez que le backend est démarré. npm run dev lance les deux, et les journaux du serveur s'affichent sous le préfixe server.",- "addProvider": "Ajouter une clé de fournisseur",+ "paneProviderKey": "Clé de fournisseur",+ "paneImportFile": "Importer un fichier",+ "paneCustomEndpoint": "Endpoint personnalisé","platform": "Plateforme","apiToken": "Jeton API","noKeyNeededPlaceholder": "Aucune clé API requise",@@ -245,10 +248,19 @@"keylessHint": "Aucune clé API requise : l'offre gratuite de ce fournisseur est anonyme (limitée par IP).","enable": "Activer","noProviderKeys": "Aucune clé de fournisseur pour l'instant. Ajoutez-en une ci-dessus pour commencer le routage.",- "configuredProviders": "Fournisseurs configurés",- "proxyToggleLabel": "proxy",- "keyCountOne": "{count} clé",- "keyCountOther": "{count} clés",+ "filterPlaceholder": "Filtrer les fournisseurs ou les clés",+ "filterAll": "Tous",+ "filterHealthy": "Sains",+ "filterIssues": "Problèmes",+ "filterDisabled": "Désactivés",+ "noFilterMatch": "Aucun fournisseur ne correspond à vos filtres.",+ "providerCountSummary": "{providers} fournisseurs · {keys} clés",+ "summaryHealthy": "{count} sains",+ "summaryIssueOne": "{count} problème",+ "summaryIssueOther": "{count} problèmes",+ "providerActions": "Actions du fournisseur",+ "routeViaProxy": "Acheminer via le proxy",+ "checkNow": "Vérifier maintenant","proxyEnvHintBefore": "Également configurable via la variable d'environnement ","proxyEnvHintAfter": " (prioritaire). Laissez vide pour désactiver. Exemples :","confirmRemove": "Confirmer ?",@@ -304,15 +316,21 @@"range24h": "24 h","range7d": "7 j","range30d": "30 j",+ "range90d": "90 j","requests": "Requêtes","successRate": "Taux de réussite","inputTokens": "Tokens en entrée","outputTokens": "Tokens en sortie","avgLatency": "Latence moy.",+ "p95Latency": "Latence P95",+ "avgTtft": "TTFT moy.","estSavings": "Économies est.","requestsByProvider": "Requêtes par fournisseur","avgLatencyByProvider": "Latence moy. par fournisseur",+ "ttftByProvider": "Temps jusqu'au premier token par fournisseur",+ "ttftEmpty": "Aucun temps jusqu'au premier token enregistré pour l'instant.","requestsOverTime": "Requêtes au fil du temps",+ "tokensOverTime": "Tokens au fil du temps","byModel": "Par modèle","byPlatform": "Par plateforme","errors": "Erreurs",@@ -324,9 +342,11 @@"savingsHintExact": "Vous avez réellement économisé {actual} $ sur les {range} derniers. C'est ce que les mêmes tokens auraient coûté sur des API payantes, tarifés par modèle. Le chiffre affiché est votre total réel sur 30 jours.","requestsHintPinned": "{pinned} de ces requêtes ont épinglé un modèle précis par son nom. {honored} ont été traitées par le modèle épinglé ; {failed} ont basculé vers un autre. Les autres ont été routées automatiquement.","requestsHintAuto": "Toutes les requêtes de cette période ont été routées automatiquement ; aucun client n'a épinglé de modèle précis par son nom.",+ "requestsHintTypes": "{chat} requêtes de chat et {embedding} d'embeddings.","rangeLabel24h": "24 heures","rangeLabel7d": "7 jours","rangeLabel30d": "30 jours",+ "rangeLabel90d": "90 jours","spanDays": "{count} jours","spanHours": "{count} heures","latencyMs": "Latence (ms)",@@ -338,6 +358,9 @@"message": "Message","time": "Heure","perModelBreakdown": "Détail par modèle",+ "usageByKey": "Utilisation par clé",+ "keyColumn": "Clé",+ "keyLabelFallback": "Clé n° {id}","errorsByProvider": "Erreurs par fournisseur","recentErrors": "Erreurs récentes","noErrors": "Aucune erreur"diff --git a/client/src/i18n/locales/it.json b/client/src/i18n/locales/it.jsonindex 518f5dc5..0b30ecca 100644--- a/client/src/i18n/locales/it.json+++ b/client/src/i18n/locales/it.json@@ -56,7 +56,6 @@"noData": "Nessun dato ancora","unsavedChanges": "Modifiche non salvate","saveChanges": "Salva modifiche",- "check": "Verifica","remove": "Rimuovi","unknownError": "Errore sconosciuto","model": "Modello",@@ -204,6 +203,7 @@"familyHaiku": "Haiku","selectPlatform": "Seleziona un fornitore","addKey": "Aggiungi chiave",+ "keyAdded": "Chiave aggiunta","adding": "Aggiunta…","selectProvider": "Seleziona un fornitore…","accountId": "ID account",@@ -224,6 +224,7 @@"customDisplayNameOptional": "opzionale","customApiKey": "Chiave API","addModel": "Aggiungi modello",+ "modelAdded": "Modello aggiunto","addModels": "Aggiungi {count} modelli","addingCustom": "Aggiunta…","getApiKey": "Ottieni chiave API",@@ -236,7 +237,9 @@"unifiedKeyDescAfter": "; autentica le richieste a questo proxy.","serverUnreachableBefore": "Impossibile raggiungere il server su ","serverUnreachableAfter": ". Assicurati che il backend sia in esecuzione. npm run dev avvia entrambi, e i log del server vengono stampati con il prefisso server.",- "addProvider": "Aggiungi una chiave fornitore",+ "paneProviderKey": "Chiave fornitore",+ "paneImportFile": "Importa file",+ "paneCustomEndpoint": "Endpoint personalizzato","platform": "Piattaforma","apiToken": "Token API","noKeyNeededPlaceholder": "Nessuna chiave API necessaria",@@ -245,10 +248,19 @@"keylessHint": "Nessuna chiave API necessaria: il livello gratuito di questo fornitore è anonimo (limitato per IP).","enable": "Abilita","noProviderKeys": "Nessuna chiave fornitore ancora. Aggiungine una sopra per iniziare il routing.",- "configuredProviders": "Fornitori configurati",- "proxyToggleLabel": "proxy",- "keyCountOne": "{count} chiave",- "keyCountOther": "{count} chiavi",+ "filterPlaceholder": "Filtra fornitori o chiavi",+ "filterAll": "Tutti",+ "filterHealthy": "Funzionanti",+ "filterIssues": "Con problemi",+ "filterDisabled": "Disabilitati",+ "noFilterMatch": "Nessun fornitore corrisponde ai tuoi filtri.",+ "providerCountSummary": "{providers} fornitori · {keys} chiavi",+ "summaryHealthy": "{count} funzionanti",+ "summaryIssueOne": "{count} problema",+ "summaryIssueOther": "{count} problemi",+ "providerActions": "Azioni fornitore",+ "routeViaProxy": "Instrada tramite proxy",+ "checkNow": "Controlla ora","proxyEnvHintBefore": "Configurabile anche tramite la variabile d'ambiente ","proxyEnvHintAfter": " (ha precedenza). Lascia vuoto per disabilitare. Esempi:","confirmRemove": "Confermi?",@@ -304,15 +316,21 @@"range24h": "24h","range7d": "7g","range30d": "30g",+ "range90d": "90g","requests": "Richieste","successRate": "Tasso di successo","inputTokens": "Token in input","outputTokens": "Token in output","avgLatency": "Latenza media",+ "p95Latency": "Latenza P95",+ "avgTtft": "TTFT medio","estSavings": "Risparmio stimato","requestsByProvider": "Richieste per fornitore","avgLatencyByProvider": "Latenza media per fornitore",+ "ttftByProvider": "Tempo al primo token per fornitore",+ "ttftEmpty": "Ancora nessun tempo al primo token registrato.","requestsOverTime": "Richieste nel tempo",+ "tokensOverTime": "Token nel tempo","byModel": "Per modello","byPlatform": "Per piattaforma","errors": "Errori",@@ -324,9 +342,11 @@"savingsHintExact": "Hai effettivamente risparmiato ${actual} negli ultimi {range}. Questo è quanto gli stessi token sarebbero costati su API a pagamento, prezzate per modello. Il numero mostrato è il tuo totale reale di 30 giorni.","requestsHintPinned": "{pinned} di queste richieste hanno fissato un modello specifico per nome. {honored} sono state servite dal modello fissato; {failed} sono cadute in fallback su uno diverso. Le restanti sono state instradate automaticamente.","requestsHintAuto": "Tutte le richieste in questo periodo sono state instradate automaticamente; nessun client ha fissato un modello specifico per nome.",+ "requestsHintTypes": "{chat} richieste di chat e {embedding} di embedding.","rangeLabel24h": "24 ore","rangeLabel7d": "7 giorni","rangeLabel30d": "30 giorni",+ "rangeLabel90d": "90 giorni","spanDays": "{count} giorni","spanHours": "{count} ore","latencyMs": "Latenza (ms)",@@ -338,6 +358,9 @@"message": "Messaggio","time": "Ora","perModelBreakdown": "Analisi per modello",+ "usageByKey": "Utilizzo per chiave",+ "keyColumn": "Chiave",+ "keyLabelFallback": "Chiave n. {id}","errorsByProvider": "Errori per fornitore","recentErrors": "Errori recenti","noErrors": "Nessun errore"diff --git a/client/src/i18n/locales/pt-BR.json b/client/src/i18n/locales/pt-BR.jsonindex 0b5c0648..4dd8bb06 100644--- a/client/src/i18n/locales/pt-BR.json+++ b/client/src/i18n/locales/pt-BR.json@@ -56,7 +56,6 @@"noData": "Ainda não há dados","unsavedChanges": "Alterações não salvas","saveChanges": "Salvar alterações",- "check": "Verificar","remove": "Remover","unknownError": "Erro desconhecido","model": "Modelo",@@ -204,6 +203,7 @@"familyHaiku": "Haiku","selectPlatform": "Selecione um provedor","addKey": "Adicionar chave",+ "keyAdded": "Chave adicionada","adding": "Adicionando…","selectProvider": "Selecione um provedor…","accountId": "ID da conta",@@ -224,6 +224,7 @@"customDisplayNameOptional": "opcional","customApiKey": "Chave de API","addModel": "Adicionar modelo",+ "modelAdded": "Modelo adicionado","addModels": "Adicionar {count} modelos","addingCustom": "Adicionando…","getApiKey": "Obter chave de API",@@ -236,7 +237,9 @@"unifiedKeyDescAfter": " da OpenAI; ela autentica as solicitações a este proxy.","serverUnreachableBefore": "Não foi possível acessar o servidor em ","serverUnreachableAfter": ". Verifique se o backend está em execução. npm run dev inicia os dois, e os logs do servidor são impressos sob o prefixo server.",- "addProvider": "Adicionar uma chave de provedor",+ "paneProviderKey": "Chave de provedor",+ "paneImportFile": "Importar arquivo",+ "paneCustomEndpoint": "Endpoint personalizado","platform": "Plataforma","apiToken": "Token de API","noKeyNeededPlaceholder": "Nenhuma chave de API necessária",@@ -245,10 +248,19 @@"keylessHint": "Nenhuma chave de API necessária: o nível gratuito deste provedor é anônimo (com limite por IP).","enable": "Habilitar","noProviderKeys": "Ainda não há chaves de provedor. Adicione uma acima para começar o roteamento.",- "configuredProviders": "Provedores configurados",- "proxyToggleLabel": "proxy",- "keyCountOne": "{count} chave",- "keyCountOther": "{count} chaves",+ "filterPlaceholder": "Filtrar provedores ou chaves",+ "filterAll": "Todos",+ "filterHealthy": "Saudáveis",+ "filterIssues": "Com problemas",+ "filterDisabled": "Desabilitados",+ "noFilterMatch": "Nenhum provedor corresponde aos seus filtros.",+ "providerCountSummary": "{providers} provedores · {keys} chaves",+ "summaryHealthy": "{count} saudáveis",+ "summaryIssueOne": "{count} problema",+ "summaryIssueOther": "{count} problemas",+ "providerActions": "Ações do provedor",+ "routeViaProxy": "Rotear pelo proxy",+ "checkNow": "Verificar agora","proxyEnvHintBefore": "Também configurável pela variável de ambiente ","proxyEnvHintAfter": " (tem precedência). Deixe em branco para desativar. Exemplos:","confirmRemove": "Confirmar?",@@ -304,15 +316,21 @@"range24h": "24 h","range7d": "7 d","range30d": "30 d",+ "range90d": "90 d","requests": "Solicitações","successRate": "Taxa de sucesso","inputTokens": "Tokens de entrada","outputTokens": "Tokens de saída","avgLatency": "Latência média",+ "p95Latency": "Latência P95",+ "avgTtft": "TTFT médio","estSavings": "Economia est.","requestsByProvider": "Solicitações por provedor","avgLatencyByProvider": "Latência média por provedor",+ "ttftByProvider": "Tempo até o primeiro token por provedor",+ "ttftEmpty": "Nenhum tempo até o primeiro token registrado ainda.","requestsOverTime": "Solicitações ao longo do tempo",+ "tokensOverTime": "Tokens ao longo do tempo","byModel": "Por modelo","byPlatform": "Por plataforma","errors": "Erros",@@ -324,9 +342,11 @@"savingsHintExact": "Você economizou de fato {actual} $ nos últimos {range}. É quanto os mesmos tokens teriam custado em APIs pagas, com preço por modelo. O número exibido é o seu total real de 30 dias.","requestsHintPinned": "{pinned} destas solicitações fixaram um modelo específico pelo nome. {honored} foram atendidas pelo modelo fixado; {failed} fizeram fallback para outro. As demais foram roteadas automaticamente.","requestsHintAuto": "Todas as solicitações deste período foram roteadas automaticamente; nenhum cliente fixou um modelo específico pelo nome.",+ "requestsHintTypes": "{chat} solicitações de chat e {embedding} de embeddings.","rangeLabel24h": "24 horas","rangeLabel7d": "7 dias","rangeLabel30d": "30 dias",+ "rangeLabel90d": "90 dias","spanDays": "{count} dias","spanHours": "{count} horas","latencyMs": "Latência (ms)",@@ -338,6 +358,9 @@"message": "Mensagem","time": "Hora","perModelBreakdown": "Detalhamento por modelo",+ "usageByKey": "Uso por chave",+ "keyColumn": "Chave",+ "keyLabelFallback": "Chave nº {id}","errorsByProvider": "Erros por provedor","recentErrors": "Erros recentes","noErrors": "Sem erros"diff --git a/client/src/i18n/locales/zh-CN.json b/client/src/i18n/locales/zh-CN.jsonindex 105d4fb3..af5f2160 100644--- a/client/src/i18n/locales/zh-CN.json+++ b/client/src/i18n/locales/zh-CN.json@@ -56,7 +56,6 @@"noData": "暂无数据","unsavedChanges": "未保存的更改","saveChanges": "保存更改",- "check": "检查","remove": "移除","unknownError": "未知错误","model": "模型",@@ -204,6 +203,7 @@"familyHaiku": "Haiku","selectPlatform": "选择提供商","addKey": "添加密钥",+ "keyAdded": "密钥已添加","adding": "添加中…","selectProvider": "请选择提供商…","accountId": "账户 ID",@@ -224,6 +224,7 @@"customDisplayNameOptional": "可选","customApiKey": "API 密钥","addModel": "添加模型",+ "modelAdded": "模型已添加","addModels": "添加 {count} 个模型","addingCustom": "添加中…","getApiKey": "获取 API 密钥",@@ -236,7 +237,9 @@"unifiedKeyDescAfter": ";它用于对发往本代理的请求进行身份验证。","serverUnreachableBefore": "无法连接到位于 ","serverUnreachableAfter": " 的服务器。请确认后端正在运行。npm run dev 会同时启动两者,服务器日志会以 server 前缀打印。",- "addProvider": "添加提供方密钥",+ "paneProviderKey": "提供方密钥",+ "paneImportFile": "导入文件",+ "paneCustomEndpoint": "自定义端点","platform": "平台","apiToken": "API 令牌","noKeyNeededPlaceholder": "无需 API 密钥",@@ -245,10 +248,19 @@"keylessHint": "无需 API 密钥:该提供方的免费层是匿名的(按 IP 限流)。","enable": "启用","noProviderKeys": "尚无提供方密钥。在上方添加一个即可开始路由。",- "configuredProviders": "已配置的提供方",- "proxyToggleLabel": "代理",- "keyCountOne": "{count} 个密钥",- "keyCountOther": "{count} 个密钥",+ "filterPlaceholder": "筛选提供方或密钥",+ "filterAll": "全部",+ "filterHealthy": "健康",+ "filterIssues": "有问题",+ "filterDisabled": "已禁用",+ "noFilterMatch": "没有符合筛选条件的提供方。",+ "providerCountSummary": "{providers} 个提供方 · {keys} 个密钥",+ "summaryHealthy": "{count} 个健康",+ "summaryIssueOne": "{count} 个问题",+ "summaryIssueOther": "{count} 个问题",+ "providerActions": "提供方操作",+ "routeViaProxy": "通过代理路由",+ "checkNow": "立即检查","proxyEnvHintBefore": "也可通过 ","proxyEnvHintAfter": " 环境变量配置(优先生效)。留空则禁用。示例:","confirmRemove": "确认?",@@ -304,15 +316,21 @@"range24h": "24 小时","range7d": "7 天","range30d": "30 天",+ "range90d": "90 天","requests": "请求数","successRate": "成功率","inputTokens": "输入令牌","outputTokens": "输出令牌","avgLatency": "平均延迟",+ "p95Latency": "P95 延迟",+ "avgTtft": "平均首个令牌时间","estSavings": "预估节省","requestsByProvider": "按提供商的请求数","avgLatencyByProvider": "按提供商的平均延迟",+ "ttftByProvider": "按提供商的首个令牌时间",+ "ttftEmpty": "尚未记录首个令牌时间。","requestsOverTime": "请求趋势",+ "tokensOverTime": "令牌趋势","byModel": "按模型","byPlatform": "按提供商","errors": "错误",@@ -324,9 +342,11 @@"savingsHintExact": "在过去 {range},你实际节省了 ${actual}。这是相同的 token 在按模型计费的付费 API 上的花费。所显示的数字就是你真实的 30 天总额。","requestsHintPinned": "其中有 {pinned} 个请求按名称固定了特定模型。{honored} 个由所固定的模型处理;{failed} 个回退到了其他模型。其余为自动路由。","requestsHintAuto": "此期间的所有请求均为自动路由;没有客户端按名称固定特定模型。",+ "requestsHintTypes": "{chat} 个对话请求和 {embedding} 个嵌入请求。","rangeLabel24h": "24 小时","rangeLabel7d": "7 天","rangeLabel30d": "30 天",+ "rangeLabel90d": "90 天","spanDays": "{count} 天","spanHours": "{count} 小时","latencyMs": "延迟(毫秒)",@@ -338,6 +358,9 @@"message": "消息","time": "时间","perModelBreakdown": "按模型细分",+ "usageByKey": "按密钥统计的用量",+ "keyColumn": "密钥",+ "keyLabelFallback": "密钥 #{id}","errorsByProvider": "按提供方统计错误","recentErrors": "最近的错误","noErrors": "无错误"diff --git a/client/src/pages/AnalyticsPage.tsx b/client/src/pages/AnalyticsPage.tsxindex b3bac3c3..308996e5 100644--- a/client/src/pages/AnalyticsPage.tsx+++ b/client/src/pages/AnalyticsPage.tsx@@ -13,7 +13,87 @@ import { Tooltip as HoverTooltip } from '@/components/tooltip'import { formatSqliteUtcToLocalTime } from '@/lib/utils'import { useI18n } from '@/i18n'-type TimeRange = '24h' | '7d' | '30d'+type TimeRange = '24h' | '7d' | '30d' | '90d'++// Response shapes mirror the JSON emitted by server/src/routes/analytics.ts.+// Latency percentiles and TTFT are null when the raw window is empty (pruned).+interface SummaryResponse {+ totalRequests: number+ successRate: number+ totalInputTokens: number+ totalOutputTokens: number+ avgLatencyMs: number+ p50LatencyMs: number | null+ p95LatencyMs: number | null+ avgTtfbMs: number | null+ requestTypeCounts: { chat: number; embedding: number }+ estimatedCostSavings: number+ pinnedRequests: number+ pinHonoredRequests: number+ firstRequestAt: string | null+ lifetimeTotalRequests: number+}++interface ByPlatformRow {+ platform: string+ requests: number+ successRate: number+ avgLatencyMs: number+ p95LatencyMs: number | null+ avgTtfbMs: number | null+ errorCount: number+ avgTokensPerSecond: number | null+ totalInputTokens: number+ totalOutputTokens: number+}++interface TimelineBucket {+ timestamp: string+ requests: number+ successCount: number+ failureCount: number+ inputTokens: number+ outputTokens: number+}++interface ByModelRow {+ platform: string+ modelId: string+ displayName: string+ requests: number+ successRate: number+ avgLatencyMs: number+ totalInputTokens: number+ totalOutputTokens: number+ pinnedRequests: number+ estimatedCost: number+}++interface ByKeyRow {+ keyId: number+ label: string | null+ platform: string | null+ requests: number+ successRate: number+ avgLatencyMs: number+ totalInputTokens: number+ totalOutputTokens: number+}++interface ErrorDistribution {+ byCategory: Array<{ category: string; count: number }>+ byPlatform: Array<{ platform: string; count: number }>+ detailed: Array<{ platform: string; model_id: string; error_category: string; count: number }>+}++interface RecentErrorRow {+ id: number+ platform: string+ modelId: string+ error: string+ latencyMs: number+ createdAt: string+}function formatTokens(n?: number): string {if (!n) return '0'@@ -48,39 +128,61 @@ function Panel({ title, children }: { title: string; children: React.ReactNode }const axisStyle = { fontSize: 11, fill: 'var(--muted-foreground)' } as constconst gridStyle = 'var(--border)'const primaryFill = 'var(--foreground)'+const tooltipStyle = { backgroundColor: 'var(--popover)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 } as const++// Two categorical series hues, validated against the app's actual chart+// surfaces (light card #ffffff, dark card #101010) with the dataviz palette+// checker. Slot A (blue) = the "average / input" series; slot B (aqua) = the+// "p95 / output" series. The app's own --chart-* tokens are all grayscale+// (zero chroma), which fails the CVD separation check for a two-series chart,+// so we take the nearest passing categorical hues and theme them here.+const seriesA = 'var(--series-a)'+const seriesB = 'var(--series-b)'+const chartVars = `+.analytics-viz { --series-a: #2a78d6; --series-b: #1baf7a; }+.dark .analytics-viz { --series-a: #3987e5; --series-b: #199e70; }+`export default function AnalyticsPage() {const { t } = useI18n()const [range, setRange] = useState<TimeRange>('7d')+ // Capture "now" once at mount so the savings extrapolation below stays a pure+ // render (calling Date.now() during render is impure and non-deterministic).+ const [now] = useState(() => Date.now())const { data: summary, isLoading: summaryLoading } = useQuery({queryKey: ['analytics', 'summary', range],- queryFn: () => apiFetch<any>(`/api/analytics/summary?range=${range}`),+ queryFn: () => apiFetch<SummaryResponse>(`/api/analytics/summary?range=${range}`),})const { data: byPlatform = [] } = useQuery({queryKey: ['analytics', 'by-platform', range],- queryFn: () => apiFetch<any[]>(`/api/analytics/by-platform?range=${range}`),+ queryFn: () => apiFetch<ByPlatformRow[]>(`/api/analytics/by-platform?range=${range}`),})const { data: timeline = [] } = useQuery({queryKey: ['analytics', 'timeline', range],- queryFn: () => apiFetch<any[]>(`/api/analytics/timeline?range=${range}`),+ queryFn: () => apiFetch<TimelineBucket[]>(`/api/analytics/timeline?range=${range}`),})const { data: byModel = [] } = useQuery({queryKey: ['analytics', 'by-model', range],- queryFn: () => apiFetch<any[]>(`/api/analytics/by-model?range=${range}`),+ queryFn: () => apiFetch<ByModelRow[]>(`/api/analytics/by-model?range=${range}`),+ })++ const { data: byKey = [] } = useQuery({+ queryKey: ['analytics', 'by-key', range],+ queryFn: () => apiFetch<ByKeyRow[]>(`/api/analytics/by-key?range=${range}`),})const { data: errors = [] } = useQuery({queryKey: ['analytics', 'errors', range],- queryFn: () => apiFetch<any[]>(`/api/analytics/errors?range=${range}`),+ queryFn: () => apiFetch<RecentErrorRow[]>(`/api/analytics/errors?range=${range}`),})const { data: errorDist } = useQuery({queryKey: ['analytics', 'error-distribution', range],- queryFn: () => apiFetch<{ byCategory: any[]; byPlatform: any[]; detailed: any[] }>(`/api/analytics/error-distribution?range=${range}`),+ queryFn: () => apiFetch<ErrorDistribution>(`/api/analytics/error-distribution?range=${range}`),})// Savings card shows ONE stable monthly figure regardless of the selected@@ -92,7 +194,7 @@ export default function AnalyticsPage() {// with the 30d tab.const { data: summary30 } = useQuery({queryKey: ['analytics', 'summary', '30d'],- queryFn: () => apiFetch<any>(`/api/analytics/summary?range=30d`),+ queryFn: () => apiFetch<SummaryResponse>(`/api/analytics/summary?range=30d`),})const actualSavings = summary?.estimatedCostSavings ?? 0const baseSavings = summary30?.estimatedCostSavings ?? 0@@ -100,13 +202,16 @@ export default function AnalyticsPage() {if (!summary30?.firstRequestAt) return 30// SQLite stores UTC "YYYY-MM-DD HH:MM:SS"const first = new Date(summary30.firstRequestAt.replace(' ', 'T') + 'Z').getTime()- const days = (Date.now() - first) / 86_400_000+ const days = (now - first) / 86_400_000if (!Number.isFinite(days)) return 30return Math.min(Math.max(days, 1 / 24), 30)})()const extrapolated = spanDays < 29.5const savings30d = extrapolated ? baseSavings * (30 / spanDays) : baseSavings- const rangeLabel = range === '24h' ? t('analytics.rangeLabel24h') : range === '7d' ? t('analytics.rangeLabel7d') : t('analytics.rangeLabel30d')+ const rangeLabel = range === '24h' ? t('analytics.rangeLabel24h')+ : range === '7d' ? t('analytics.rangeLabel7d')+ : range === '30d' ? t('analytics.rangeLabel30d')+ : t('analytics.rangeLabel90d')const spanLabel = spanDays >= 2 ? t('analytics.spanDays', { count: Math.round(spanDays) }) : t('analytics.spanHours', { count: Math.max(1, Math.round(spanDays * 24)) })const savingsHint = extrapolated? t('analytics.savingsHint', { actual: actualSavings.toFixed(2), range: rangeLabel, span: spanLabel })@@ -116,12 +221,31 @@ export default function AnalyticsPage() {// Honored = that model actually served it (the rest failed over).const pinned = summary?.pinnedRequests ?? 0const pinHonored = summary?.pinHonoredRequests ?? 0- const requestsHint = pinned > 0+ const chatCount = summary?.requestTypeCounts?.chat ?? 0+ const embeddingCount = summary?.requestTypeCounts?.embedding ?? 0+ const requestsHint = (pinned > 0? t('analytics.requestsHintPinned', { pinned, honored: pinHonored, failed: pinned - pinHonored })- : t('analytics.requestsHintAuto')+ : t('analytics.requestsHintAuto'))+ + ' ' + t('analytics.requestsHintTypes', { chat: chatCount, embedding: embeddingCount })++ // Avg time-to-first-token is null when nothing streamed (or the raw window+ // was pruned); show a placeholder glyph rather than a misleading "0 ms".+ const avgTtfb = summary?.avgTtfbMs+ const ttftValue = avgTtfb != null ? `${avgTtfb} ms` : '—'++ // p95 latency is likewise null when the raw window was pruned; the server+ // does NOT coerce it (unlike avg latency), so a null must render the same+ // placeholder glyph instead of a misleading "0 ms".+ const p95Latency = summary?.p95LatencyMs+ const p95Value = p95Latency != null ? `${p95Latency} ms` : '—'++ // TTFT-by-provider is empty when no provider recorded a streaming first+ // token; render a muted line instead of an axis-only empty chart.+ const ttftHasData = byPlatform.some((p) => (p.avgTtfbMs ?? 0) > 0)return (- <div>+ <div className="analytics-viz">+ <style>{chartVars}</style><PageHeadertitle={t('analytics.title')}description={t('analytics.description')}@@ -129,9 +253,9 @@ export default function AnalyticsPage() {<SegmentedControlvalue={range}onValueChange={setRange}- options={(['24h', '7d', '30d'] as TimeRange[]).map(r => ({+ options={(['24h', '7d', '30d', '90d'] as TimeRange[]).map(r => ({value: r,- label: t(r === '24h' ? 'analytics.range24h' : r === '7d' ? 'analytics.range7d' : 'analytics.range30d'),+ label: t(r === '24h' ? 'analytics.range24h' : r === '7d' ? 'analytics.range7d' : r === '30d' ? 'analytics.range30d' : 'analytics.range90d'),}))}ariaLabel={t('analytics.title')}/>@@ -140,9 +264,9 @@ export default function AnalyticsPage() {<div className="space-y-6">{/* Summary stats */}- <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">+ <div className="grid grid-cols-2 md:grid-cols-4 xl:grid-cols-8 gap-3">{summaryLoading ? (- Array.from({ length: 6 }).map((_, i) => <Skeleton key={i} className="h-[74px] rounded-3xl" />)+ Array.from({ length: 8 }).map((_, i) => <Skeleton key={i} className="h-[74px] rounded-3xl" />)) : (<><Stat label={t('analytics.requests')} value={summary?.totalRequests ?? 0} hint={requestsHint} />@@ -150,6 +274,8 @@ export default function AnalyticsPage() {<Stat label={t('analytics.inputTokens')} value={formatTokens(summary?.totalInputTokens)} /><Stat label={t('analytics.outputTokens')} value={formatTokens(summary?.totalOutputTokens)} /><Stat label={t('analytics.avgLatency')} value={`${summary?.avgLatencyMs ?? 0} ms`} />+ <Stat label={t('analytics.p95Latency')} value={p95Value} />+ <Stat label={t('analytics.avgTtft')} value={ttftValue} />{/* Priced per request at the served model's paid-API equivalentrate (not a flat frontier-model rate) — see db/model-pricing.ts.The value is a 30-day projection; the hover hint tells the whole@@ -160,6 +286,47 @@ export default function AnalyticsPage() {</div><div className="grid grid-cols-1 lg:grid-cols-2 gap-6">+ <div className="lg:col-span-2">+ <Panel title={t('analytics.requestsOverTime')}>+ {timeline.length === 0 ? (+ <p className="text-sm text-muted-foreground text-center py-8">{t('common.noData')}</p>+ ) : (+ <ResponsiveContainer width="100%" height={240}>+ <LineChart data={timeline} margin={{ top: 6, right: 6, left: -12, bottom: 0 }}>+ <CartesianGrid strokeDasharray="2 4" stroke={gridStyle} />+ <XAxis dataKey="timestamp" tick={axisStyle} tickLine={false} axisLine={{ stroke: gridStyle }} />+ <YAxis tick={axisStyle} tickLine={false} axisLine={false} />+ <Tooltip contentStyle={tooltipStyle} />+ <Legend wrapperStyle={{ fontSize: 12 }} iconType="line" />+ <Line type="monotone" dataKey="successCount" name={t('common.success')} stroke={primaryFill} strokeWidth={1.5} dot={false} />+ <Line type="monotone" dataKey="failureCount" name={t('common.failures')} stroke="var(--destructive)" strokeWidth={1.5} dot={false} />+ </LineChart>+ </ResponsiveContainer>+ )}+ </Panel>+ </div>++ {/* Tokens over time: input vs output, one axis, two-series legend. */}+ <div className="lg:col-span-2">+ <Panel title={t('analytics.tokensOverTime')}>+ {timeline.length === 0 ? (+ <p className="text-sm text-muted-foreground text-center py-8">{t('common.noData')}</p>+ ) : (+ <ResponsiveContainer width="100%" height={240}>+ <LineChart data={timeline} margin={{ top: 6, right: 6, left: -12, bottom: 0 }}>+ <CartesianGrid strokeDasharray="2 4" stroke={gridStyle} />+ <XAxis dataKey="timestamp" tick={axisStyle} tickLine={false} axisLine={{ stroke: gridStyle }} />+ <YAxis tick={axisStyle} tickLine={false} axisLine={false} tickFormatter={(v: number) => formatTokens(v)} />+ <Tooltip contentStyle={tooltipStyle} formatter={(value) => formatTokens(Number(value))} />+ <Legend wrapperStyle={{ fontSize: 12 }} iconType="line" />+ <Line type="monotone" dataKey="inputTokens" name={t('analytics.inputTokens')} stroke={seriesA} strokeWidth={2} dot={false} />+ <Line type="monotone" dataKey="outputTokens" name={t('analytics.outputTokens')} stroke={seriesB} strokeWidth={2} dot={false} />+ </LineChart>+ </ResponsiveContainer>+ )}+ </Panel>+ </div>+<Panel title={t('analytics.requestsByProvider')}>{byPlatform.length === 0 ? (<p className="text-sm text-muted-foreground text-center py-8">{t('common.noData')}</p>@@ -169,13 +336,14 @@ export default function AnalyticsPage() {<CartesianGrid strokeDasharray="2 4" stroke={gridStyle} /><XAxis dataKey="platform" tick={axisStyle} tickLine={false} axisLine={{ stroke: gridStyle }} /><YAxis tick={axisStyle} tickLine={false} axisLine={false} />- <Tooltip contentStyle={{ backgroundColor: 'var(--popover)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 }} />- <Bar dataKey="requests" fill={primaryFill} radius={[3, 3, 0, 0]} />+ <Tooltip contentStyle={tooltipStyle} />+ <Bar dataKey="requests" name={t('analytics.requests')} fill={primaryFill} radius={[3, 3, 0, 0]} maxBarSize={24} /></BarChart></ResponsiveContainer>)}</Panel>+ {/* Latency by provider: grouped avg + p95, same unit (ms), one axis. */}<Panel title={t('analytics.avgLatencyByProvider')}>{byPlatform.length === 0 ? (<p className="text-sm text-muted-foreground text-center py-8">{t('common.noData')}</p>@@ -185,73 +353,50 @@ export default function AnalyticsPage() {<CartesianGrid strokeDasharray="2 4" stroke={gridStyle} /><XAxis dataKey="platform" tick={axisStyle} tickLine={false} axisLine={{ stroke: gridStyle }} /><YAxis unit="ms" tick={axisStyle} tickLine={false} axisLine={false} />- <Tooltip contentStyle={{ backgroundColor: 'var(--popover)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 }} />- <Bar dataKey="avgLatencyMs" name={t('analytics.latencyMs')} fill="var(--muted-foreground)" radius={[3, 3, 0, 0]} />+ <Tooltip contentStyle={tooltipStyle} />+ <Legend wrapperStyle={{ fontSize: 12 }} iconType="rect" />+ <Bar dataKey="avgLatencyMs" name={t('analytics.avgLatency')} fill={seriesA} radius={[3, 3, 0, 0]} maxBarSize={24} />+ <Bar dataKey="p95LatencyMs" name={t('analytics.p95Latency')} fill={seriesB} radius={[3, 3, 0, 0]} maxBarSize={24} /></BarChart></ResponsiveContainer>)}</Panel>- <div className="lg:col-span-2">- <Panel title={t('analytics.requestsOverTime')}>- {timeline.length === 0 ? (- <p className="text-sm text-muted-foreground text-center py-8">{t('common.noData')}</p>- ) : (- <ResponsiveContainer width="100%" height={240}>- <LineChart data={timeline} margin={{ top: 6, right: 6, left: -12, bottom: 0 }}>- <CartesianGrid strokeDasharray="2 4" stroke={gridStyle} />- <XAxis dataKey="timestamp" tick={axisStyle} tickLine={false} axisLine={{ stroke: gridStyle }} />- <YAxis tick={axisStyle} tickLine={false} axisLine={false} />- <Tooltip contentStyle={{ backgroundColor: 'var(--popover)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 }} />- <Legend wrapperStyle={{ fontSize: 12 }} iconType="line" />- <Line type="monotone" dataKey="successCount" name={t('common.success')} stroke={primaryFill} strokeWidth={1.5} dot={false} />- <Line type="monotone" dataKey="failureCount" name={t('common.failures')} stroke="var(--destructive)" strokeWidth={1.5} dot={false} />- </LineChart>- </ResponsiveContainer>- )}- </Panel>- </div>+ {/* Time to first token by provider (single series → no legend). */}+ <Panel title={t('analytics.ttftByProvider')}>+ {byPlatform.length === 0 ? (+ <p className="text-sm text-muted-foreground text-center py-8">{t('common.noData')}</p>+ ) : !ttftHasData ? (+ <p className="text-sm text-muted-foreground text-center py-8">{t('analytics.ttftEmpty')}</p>+ ) : (+ <ResponsiveContainer width="100%" height={240}>+ <BarChart data={byPlatform} margin={{ top: 6, right: 6, left: -12, bottom: 0 }}>+ <CartesianGrid strokeDasharray="2 4" stroke={gridStyle} />+ <XAxis dataKey="platform" tick={axisStyle} tickLine={false} axisLine={{ stroke: gridStyle }} />+ <YAxis unit="ms" tick={axisStyle} tickLine={false} axisLine={false} />+ <Tooltip contentStyle={tooltipStyle} />+ <Bar dataKey="avgTtfbMs" name={t('analytics.avgTtft')} fill={seriesA} radius={[3, 3, 0, 0]} maxBarSize={24} />+ </BarChart>+ </ResponsiveContainer>+ )}+ </Panel>- <div className="lg:col-span-2">- <Panel title={t('analytics.perModelBreakdown')}>- {byModel.length === 0 ? (- <p className="text-sm text-muted-foreground text-center py-8">{t('common.noData')}</p>- ) : (- <div className="max-h-[360px] overflow-y-auto -mx-4">- <Table>- <TableHeader>- <TableRow>- <TableHead className="pl-4">{t('common.model')}</TableHead>- <TableHead>{t('common.provider')}</TableHead>- <TableHead className="text-right">{t('analytics.requests')}</TableHead>- <TableHead className="text-right">{t('analytics.pinned')}</TableHead>- <TableHead className="text-right">{t('common.success')}</TableHead>- <TableHead className="text-right">{t('analytics.latency')}</TableHead>- <TableHead className="text-right">{t('analytics.inTokens')}</TableHead>- <TableHead className="text-right">{t('analytics.outTokens')}</TableHead>- <TableHead className="text-right pr-4">{t('analytics.saved')}</TableHead>- </TableRow>- </TableHeader>- <TableBody>- {byModel.map((m: any, i: number) => (- <TableRow key={i}>- <TableCell className="pl-4 text-sm font-medium">{m.displayName}</TableCell>- <TableCell className="text-xs text-muted-foreground">{m.platform}</TableCell>- <TableCell className="text-right tabular-nums">{m.requests}</TableCell>- <TableCell className="text-right tabular-nums">{m.pinnedRequests > 0 ? m.pinnedRequests : '—'}</TableCell>- <TableCell className="text-right tabular-nums">{m.successRate}%</TableCell>- <TableCell className="text-right tabular-nums">{m.avgLatencyMs} ms</TableCell>- <TableCell className="text-right tabular-nums">{formatTokens(m.totalInputTokens)}</TableCell>- <TableCell className="text-right tabular-nums">{formatTokens(m.totalOutputTokens)}</TableCell>- <TableCell className="text-right tabular-nums pr-4">${(m.estimatedCost ?? 0).toFixed(2)}</TableCell>- </TableRow>- ))}- </TableBody>- </Table>- </div>- )}- </Panel>- </div>+ {/* Errors by category: horizontal bars, destructive hue, no legend. */}+ <Panel title={t('analytics.errorDistribution')}>+ {!errorDist?.byCategory?.length ? (+ <p className="text-sm text-muted-foreground text-center py-8">{t('analytics.noErrors')}</p>+ ) : (+ <ResponsiveContainer width="100%" height={240}>+ <BarChart data={errorDist.byCategory} layout="vertical" margin={{ top: 6, right: 12, left: 8, bottom: 0 }}>+ <CartesianGrid strokeDasharray="2 4" stroke={gridStyle} horizontal={false} />+ <XAxis type="number" tick={axisStyle} tickLine={false} axisLine={{ stroke: gridStyle }} allowDecimals={false} />+ <YAxis type="category" dataKey="category" tick={axisStyle} tickLine={false} axisLine={false} width={128} />+ <Tooltip contentStyle={tooltipStyle} />+ <Bar dataKey="count" name={t('analytics.errors')} fill="var(--destructive)" radius={[0, 3, 3, 0]} maxBarSize={24} />+ </BarChart>+ </ResponsiveContainer>+ )}+ </Panel><Panel title={t('analytics.errorsByProvider')}>{!errorDist?.byPlatform?.length ? (@@ -262,8 +407,8 @@ export default function AnalyticsPage() {<CartesianGrid strokeDasharray="2 4" stroke={gridStyle} /><XAxis dataKey="platform" tick={axisStyle} tickLine={false} axisLine={{ stroke: gridStyle }} /><YAxis tick={axisStyle} tickLine={false} axisLine={false} />- <Tooltip contentStyle={{ backgroundColor: 'var(--popover)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 }} />- <Bar dataKey="count" fill="var(--destructive)" radius={[3, 3, 0, 0]} />+ <Tooltip contentStyle={tooltipStyle} />+ <Bar dataKey="count" name={t('analytics.errors')} fill="var(--destructive)" radius={[3, 3, 0, 0]} maxBarSize={24} /></BarChart></ResponsiveContainer>)}@@ -283,7 +428,7 @@ export default function AnalyticsPage() {</TableRow></TableHeader><TableBody>- {errors.slice(0, 20).map((e: any) => (+ {errors.slice(0, 20).map((e) => (<TableRow key={e.id}><TableCell className="pl-4 text-xs">{e.platform}</TableCell><TableCell className="text-xs max-w-[200px] truncate">{e.error}</TableCell>@@ -297,6 +442,85 @@ export default function AnalyticsPage() {</div>)}</Panel>++ <div className="lg:col-span-2">+ <Panel title={t('analytics.perModelBreakdown')}>+ {byModel.length === 0 ? (+ <p className="text-sm text-muted-foreground text-center py-8">{t('common.noData')}</p>+ ) : (+ <div className="max-h-[360px] overflow-y-auto -mx-4">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="pl-4">{t('common.model')}</TableHead>+ <TableHead>{t('common.provider')}</TableHead>+ <TableHead className="text-right">{t('analytics.requests')}</TableHead>+ <TableHead className="text-right">{t('analytics.pinned')}</TableHead>+ <TableHead className="text-right">{t('common.success')}</TableHead>+ <TableHead className="text-right">{t('analytics.latency')}</TableHead>+ <TableHead className="text-right">{t('analytics.inTokens')}</TableHead>+ <TableHead className="text-right">{t('analytics.outTokens')}</TableHead>+ <TableHead className="text-right pr-4">{t('analytics.saved')}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {byModel.map((m, i) => (+ <TableRow key={i}>+ <TableCell className="pl-4 text-sm font-medium">{m.displayName}</TableCell>+ <TableCell className="text-xs text-muted-foreground">{m.platform}</TableCell>+ <TableCell className="text-right tabular-nums">{m.requests}</TableCell>+ <TableCell className="text-right tabular-nums">{m.pinnedRequests > 0 ? m.pinnedRequests : '—'}</TableCell>+ <TableCell className="text-right tabular-nums">{m.successRate}%</TableCell>+ <TableCell className="text-right tabular-nums">{m.avgLatencyMs} ms</TableCell>+ <TableCell className="text-right tabular-nums">{formatTokens(m.totalInputTokens)}</TableCell>+ <TableCell className="text-right tabular-nums">{formatTokens(m.totalOutputTokens)}</TableCell>+ <TableCell className="text-right tabular-nums pr-4">${(m.estimatedCost ?? 0).toFixed(2)}</TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </div>+ )}+ </Panel>+ </div>++ {/* Usage by key: only rendered when the endpoint returns rows. */}+ {byKey.length > 0 && (+ <div className="lg:col-span-2">+ <Panel title={t('analytics.usageByKey')}>+ <div className="max-h-[360px] overflow-y-auto -mx-4">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="pl-4">{t('analytics.keyColumn')}</TableHead>+ <TableHead>{t('common.provider')}</TableHead>+ <TableHead className="text-right">{t('analytics.requests')}</TableHead>+ <TableHead className="text-right">{t('common.success')}</TableHead>+ <TableHead className="text-right">{t('analytics.latency')}</TableHead>+ <TableHead className="text-right">{t('analytics.inTokens')}</TableHead>+ <TableHead className="text-right pr-4">{t('analytics.outTokens')}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {byKey.map((k) => (+ <TableRow key={k.keyId}>+ <TableCell className="pl-4 text-sm font-medium">+ {k.label || t('analytics.keyLabelFallback', { id: k.keyId })}+ </TableCell>+ <TableCell className="text-xs text-muted-foreground">{k.platform ?? '—'}</TableCell>+ <TableCell className="text-right tabular-nums">{k.requests}</TableCell>+ <TableCell className="text-right tabular-nums">{k.successRate}%</TableCell>+ <TableCell className="text-right tabular-nums">{k.avgLatencyMs} ms</TableCell>+ <TableCell className="text-right tabular-nums">{formatTokens(k.totalInputTokens)}</TableCell>+ <TableCell className="text-right tabular-nums pr-4">{formatTokens(k.totalOutputTokens)}</TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </div>+ </Panel>+ </div>+ )}</div></div></div>diff --git a/client/src/pages/FallbackPage.tsx b/client/src/pages/FallbackPage.tsxindex 5c130a87..d3ec9a85 100644--- a/client/src/pages/FallbackPage.tsx+++ b/client/src/pages/FallbackPage.tsx@@ -387,7 +387,7 @@ export default function FallbackPage() {<trkey={g.key}onClick={() => navigate(`/models/chat/${encodeURIComponent(g.members[0].canonicalId ?? g.members[0].modelId)}`)}- className={`border-b last:border-0 cursor-pointer transition-colors hover:[&>td]:bg-muted/50 [&>td:first-child]:rounded-l-lg [&>td:last-child]:rounded-r-lg ${g.members.some(m => m.enabled) ? '' : 'opacity-50'}`}+ className={`group/row border-b last:border-0 cursor-pointer transition-colors hover:[&>td]:bg-muted/50 [&>td:first-child]:rounded-l-lg [&>td:last-child]:rounded-r-lg ${g.members.some(m => m.enabled) ? '' : 'opacity-50'}`}><GroupHeaderCells group={g} rank={rankByKey.get(g.key) ?? 0} onToggleGroup={handleGroupToggle} /></tr>diff --git a/client/src/pages/KeysPage.tsx b/client/src/pages/KeysPage.tsxindex 19dd63cb..c4f26ee3 100644--- a/client/src/pages/KeysPage.tsx+++ b/client/src/pages/KeysPage.tsx@@ -1,29 +1,19 @@-import { useState, useRef, useEffect } from 'react'+import { useState } from 'react'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'import { apiFetch } from '@/lib/api'import { Button } from '@/components/ui/button'-import { ConfirmButton } from '@/components/confirm-button'-import { Input } from '@/components/ui/input'-import { Label } from '@/components/ui/label'import { SegmentedControl } from '@/components/ui/segmented-control'-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'-import { Switch } from '@/components/ui/switch'import { PageHeader } from '@/components/page-header'-import type { ApiKey, ApiKeyModel, Platform } from '../../../shared/types'-import { ChevronDown, KeyRound, Pencil, Trash2 } from 'lucide-react'-import { EmptyState } from '@/components/empty-state'-import { FieldError } from '@/components/ui/field-error'-import { TableSkeleton } from '@/components/ui/skeleton'-import { formatSqliteUtcToLocalTime } from '@/lib/utils'+import type { ApiKey } from '../../../shared/types'+import { Plus } from 'lucide-react'import { useI18n } from '@/i18n'-import { GetKeyLink, PLATFORMS, CUSTOM_GROUP, CUSTOM_MODEL_KIND_LABEL, customModelDeleteKey, customModelDeletePath, statusDot, statusLabelKey } from '@/components/keys/shared'import type { HealthData } from '@/components/keys/shared'import { QuotaSignalsSection } from '@/components/keys/quota-signals-section'import { UnifiedKeySection } from '@/components/keys/unified-key-section'import { ProxySettingsSection } from '@/components/keys/proxy-settings-section'-import { ImportKeysSection } from '@/components/keys/import-keys-section'-import { CustomProviderSection } from '@/components/keys/custom-provider-section'import { AnthropicSection } from '@/components/keys/anthropic-section'+import { ProviderList } from '@/components/keys/provider-list'+import { AddKeyDialog } from '@/components/keys/add-key-dialog'type KeysTab = 'providers' | 'quotaSignals' | 'apiKey' | 'anthropic'const KEYS_TABS: { id: KeysTab; labelKey: string }[] = [@@ -37,19 +27,11 @@ export default function KeysPage() {const { t } = useI18n()const queryClient = useQueryClient()const [tab, setTab] = useState<KeysTab>('providers')- const [platform, setPlatform] = useState<Platform | ''>('')- const [apiKey, setApiKey] = useState('')- const [accountId, setAccountId] = useState('')- const [label, setLabel] = useState('')- const [editingKeyId, setEditingKeyId] = useState<number | null>(null)- const [editingLabel, setEditingLabel] = useState('')- // Server-supplied notice when a key is saved for a platform with no models in- // the current catalog tier yet (e.g. a newly added premium provider, #438).- const [addNotice, setAddNotice] = useState<string | null>(null)- const [expandedKeyIds, setExpandedKeyIds] = useState<Set<number>>(new Set())- const editInputRef = useRef<HTMLInputElement>(null)+ const [addOpen, setAddOpen] = useState(false)- const { data: keys = [], isLoading } = useQuery<ApiKey[]>({+ // Kept at page level for the header's "Check all" gate; ProviderList runs the+ // same query (deduped by react-query) for the list itself.+ const { data: keys = [] } = useQuery<ApiKey[]>({queryKey: ['keys'],queryFn: () => apiFetch('/api/keys'),})@@ -60,42 +42,6 @@ export default function KeysPage() {refetchInterval: 30000,})- const addKey = useMutation({- meta: { silenceToast: true },- mutationFn: (body: { platform: string; key: string; label?: string }) =>- apiFetch<{ notice?: string | null }>('/api/keys', { method: 'POST', body: JSON.stringify(body) }),- onSuccess: (data) => {- queryClient.invalidateQueries({ queryKey: ['keys'] })- queryClient.invalidateQueries({ queryKey: ['health'] })- queryClient.invalidateQueries({ queryKey: ['fallback'] })- setAddNotice(data?.notice ?? null)- setPlatform('')- setApiKey('')- setAccountId('')- setLabel('')- },- })-- const deleteKey = useMutation({- mutationFn: (id: number) => apiFetch(`/api/keys/${id}`, { method: 'DELETE' }),- onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ['keys'] })- queryClient.invalidateQueries({ queryKey: ['health'] })- },- })-- const deleteCustomModel = useMutation({- mutationFn: (model: ApiKeyModel) => apiFetch(customModelDeletePath(model), { method: 'DELETE' }),- onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ['keys'] })- queryClient.invalidateQueries({ queryKey: ['health'] })- queryClient.invalidateQueries({ queryKey: ['fallback'] })- queryClient.invalidateQueries({ queryKey: ['models'] })- queryClient.invalidateQueries({ queryKey: ['embeddings'] })- queryClient.invalidateQueries({ queryKey: ['media'] })- },- })-const checkAll = useMutation({mutationFn: () => apiFetch('/api/health/check-all', { method: 'POST' }),onSuccess: () => {@@ -104,119 +50,6 @@ export default function KeysPage() {},})- const checkKey = useMutation({- mutationFn: (keyId: number) => apiFetch(`/api/health/check/${keyId}`, { method: 'POST' }),- onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ['health'] })- queryClient.invalidateQueries({ queryKey: ['keys'] })- },- })-- const togglePlatform = useMutation({- mutationFn: ({ platform, enabled }: { platform: string; enabled: boolean }) =>- apiFetch(`/api/keys/platform/${platform}`, {- method: 'PATCH',- body: JSON.stringify({ enabled }),- }),- onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ['keys'] })- queryClient.invalidateQueries({ queryKey: ['health'] })- queryClient.invalidateQueries({ queryKey: ['fallback'] })- },- })-- const updateKey = useMutation({- mutationFn: ({ id, label }: { id: number; label: string }) =>- apiFetch(`/api/keys/${id}`, {- method: 'PATCH',- body: JSON.stringify({ label }),- }),- onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ['keys'] })- setEditingKeyId(null)- setEditingLabel('')- },- })-- function startEditing(key: ApiKey) {- setEditingKeyId(key.id)- setEditingLabel(key.label)- }-- function cancelEditing() {- setEditingKeyId(null)- setEditingLabel('')- }-- function saveEditing(id: number) {- if (editingLabel !== undefined) {- updateKey.mutate({ id, label: editingLabel })- }- }-- function toggleExpandedKey(id: number) {- setExpandedKeyIds(prev => {- const next = new Set(prev)- if (next.has(id)) next.delete(id)- else next.add(id)- return next- })- }-- useEffect(() => {- if (editingKeyId !== null && editInputRef.current) {- editInputRef.current.focus()- }- }, [editingKeyId])-- const needsAccountId = platform === 'cloudflare'- const isKeyless = PLATFORMS.find(p => p.value === platform)?.keyless ?? false-- // Field-level validation: the submit stays clickable and reveals what is- // missing instead of being silently disabled.- const [addAttempted, setAddAttempted] = useState(false)- const platformError = !platform ? t('validation.required') : null- const keyError = !isKeyless && !apiKey.trim() ? t('validation.required') : null- const accountIdError = needsAccountId && !accountId.trim() ? t('validation.required') : null-- const handleSubmit = (e: React.FormEvent) => {- e.preventDefault()- if (platformError || keyError || accountIdError) {- setAddAttempted(true)- return- }- setAddAttempted(false)- // Keyless providers submit an empty key; the backend stores a sentinel.- const key = isKeyless ? '' : (needsAccountId ? `${accountId}:${apiKey}` : apiKey)- addKey.mutate({ platform, key, label: label || undefined })- }-- const healthKeyMap = new Map<number, { status: string; lastCheckedAt: string | null }>()- for (const k of healthData?.keys ?? []) healthKeyMap.set(k.id, k)-- // Proxy bypass: shared query with ProxySettingsSection (same queryKey).- const { data: proxyData } = useQuery<{ proxyUrl: string; enabled: boolean; bypassPlatforms: string[]; active: boolean }>({- queryKey: ['proxy-url'],- queryFn: () => apiFetch('/api/settings/proxy'),- })- const bypassPlatforms = proxyData?.bypassPlatforms ?? []- const proxyEnabled = proxyData?.enabled ?? true-- const toggleBypass = useMutation({- mutationFn: (platform: string) => {- const next = bypassPlatforms.includes(platform)- ? bypassPlatforms.filter(p => p !== platform)- : [...bypassPlatforms, platform]- return apiFetch('/api/settings/proxy', { method: 'PUT', body: JSON.stringify({ bypassPlatforms: next }) })- },- onSuccess: () => queryClient.invalidateQueries({ queryKey: ['proxy-url'] }),- })-- const grouped = [...PLATFORMS, CUSTOM_GROUP].map(p => ({- ...p,- keys: keys.filter(k => k.platform === p.value),- })).filter(p => p.keys.length > 0)-return (<div><PageHeader@@ -229,6 +62,12 @@ export default function KeysPage() {{checkAll.isPending ? t('keys.checking') : t('keys.checkAll')}</Button>)}+ {tab === 'providers' && (+ <Button size="sm" onClick={() => setAddOpen(true)}>+ <Plus className="size-3.5" />+ {t('keys.addKey')}+ </Button>+ )}<SegmentedControlvalue={tab}onValueChange={setTab}@@ -253,245 +92,10 @@ export default function KeysPage() {<QuotaSignalsSection states={(healthData?.quotaStates ?? []).slice(0, 24)} />)}- {tab === 'providers' && (- <>- <ImportKeysSection />-- <section>- <h2 className="text-sm font-medium mb-3">{t('keys.addProvider')}</h2>- <form onSubmit={handleSubmit} className="flex flex-wrap gap-3 rounded-3xl border p-4 bg-card">- <div className="space-y-1.5">- <Label className="text-xs">{t('keys.platform')}</Label>- <Select value={platform} onValueChange={(v) => setPlatform(v as Platform)}>- <SelectTrigger className="w-[220px]" aria-invalid={addAttempted && !!platformError}>- <SelectValue placeholder={t('keys.selectPlatform')} />- </SelectTrigger>- <SelectContent>- {PLATFORMS.map(p => (- <SelectItem key={p.value} value={p.value}>{p.label}</SelectItem>- ))}- </SelectContent>- </Select>- {addAttempted && <FieldError error={platformError} />}- {(() => {- const sel = PLATFORMS.find(p => p.value === platform)- return sel?.url ? <div className="pt-0.5"><GetKeyLink url={sel.url} /></div> : null- })()}- </div>- {needsAccountId && (- <div className="space-y-1.5">- <Label className="text-xs">{t('keys.accountId')}</Label>- <Input- value={accountId}- onChange={e => setAccountId(e.target.value)}- placeholder="a1b2c3d4…"- className="w-[200px] font-mono text-xs"- aria-invalid={addAttempted && !!accountIdError}- />- {addAttempted && <FieldError error={accountIdError} />}- </div>- )}- <div className="space-y-1.5 flex-1 min-w-[240px]">- <Label className="text-xs">{needsAccountId ? t('keys.apiToken') : t('keys.customApiKey')}</Label>- <Input- type="password"- value={isKeyless ? '' : apiKey}- onChange={e => setApiKey(e.target.value)}- placeholder={isKeyless ? t('keys.noKeyNeededPlaceholder') : (needsAccountId ? t('keys.bearerTokenPlaceholder') : t('keys.pasteKeyPlaceholder'))}- className="font-mono text-xs"- disabled={isKeyless}- aria-invalid={addAttempted && !!keyError}- />- {addAttempted && <FieldError error={keyError} />}- {isKeyless && (- <p className="text-[11px] text-muted-foreground">- {t('keys.keylessHint')}- </p>- )}- </div>- <div className="space-y-1.5">- <Label className="text-xs">{t('keys.label')}</Label>- <div className="flex flex-wrap items-center space-x-3">- <Input- value={label}- onChange={e => setLabel(e.target.value)}- placeholder={t('keys.customDisplayNameOptional')}- className="w-[160px]"- />- <Button type="submit" size="sm" disabled={addKey.isPending}>- {addKey.isPending ? t('keys.adding') : isKeyless ? t('keys.enable') : t('keys.addKey')}- </Button>- </div>- </div>- </form>- {addKey.isError && (- <p className="text-destructive text-xs mt-2">{(addKey.error as Error).message}</p>- )}- {addNotice && (- <p className="text-amber-600 dark:text-amber-500 text-xs mt-2" role="status">{addNotice}</p>- )}- </section>-- <CustomProviderSection />-- <section>- <h2 className="text-sm font-medium mb-3">{t('keys.configuredProviders')}</h2>- {isLoading ? (- <TableSkeleton rows={4} />- ) : keys.length === 0 ? (- <EmptyState icon={KeyRound} title={t('keys.noProviderKeys')} />- ) : (- <div className="space-y-6">- {grouped.map(group => (- <div key={group.value}>- <div className="flex items-center justify-between mb-2">- <div className="flex items-center gap-2">- <Switch- checked={group.keys.some(k => k.enabled)}- onCheckedChange={(checked) =>- togglePlatform.mutate({ platform: group.value, enabled: checked })- }- disabled={togglePlatform.isPending}- />- <h3 className="text-sm font-medium">{group.label}</h3>- {proxyEnabled && (- <div className="inline-flex items-center gap-1.5 ml-1">- <span className="text-[10px] text-muted-foreground">{t('keys.proxyToggleLabel')}</span>- <Switch- checked={!bypassPlatforms.includes(group.value)}- onCheckedChange={() => toggleBypass.mutate(group.value)}- disabled={toggleBypass.isPending}- />- </div>- )}- <GetKeyLink url={group.url} />- </div>- <span className="text-xs text-muted-foreground tabular-nums">- {t(group.keys.length === 1 ? 'keys.keyCountOne' : 'keys.keyCountOther', { count: group.keys.length })}- </span>- </div>- <div className="rounded-2xl border divide-y bg-card overflow-hidden">- {group.keys.map(k => {- const h = healthKeyMap.get(k.id)- const status = h?.status ?? k.status- const lastChecked = h?.lastCheckedAt- const isEditing = editingKeyId === k.id- const customModels = k.models ?? []- const hasCustomModels = customModels.length > 0- const isExpanded = expandedKeyIds.has(k.id)- return (- <div key={k.id} className="bg-card">- <div className="flex items-center gap-3 px-4 py-3 hover:bg-muted/40 transition-colors">- <span className={`size-1.5 rounded-full flex-shrink-0 ${statusDot[status] ?? statusDot.unknown}`} />- {hasCustomModels && (- <Button- type="button"- variant="ghost"- size="xs"- className="size-6 p-0 text-muted-foreground"- onClick={() => toggleExpandedKey(k.id)}- title={isExpanded ? t('common.hide') : t('common.show')}- >- <ChevronDown className={`size-3 transition-transform ${isExpanded ? 'rotate-180' : ''}`} />- </Button>- )}- <code className="text-xs font-mono flex-shrink-0">{k.maskedKey}</code>- {isEditing ? (- <Input- ref={editInputRef}- value={editingLabel}- onChange={e => setEditingLabel(e.target.value)}- onKeyDown={e => {- if (e.key === 'Enter') saveEditing(k.id)- if (e.key === 'Escape') cancelEditing()- }}- onBlur={() => saveEditing(k.id)}- className="h-6 w-[160px] text-xs"- disabled={updateKey.isPending}- />- ) : (- <>- {k.label && <span className="text-xs text-muted-foreground">{k.label}</span>}- {k.baseUrl && (- <code className="text-[11px] text-muted-foreground font-mono truncate max-w-[260px]" title={k.baseUrl}>- {k.baseUrl}- </code>- )}- </>- )}- <span className="text-xs text-muted-foreground">{statusLabelKey[status] ? t(statusLabelKey[status]) : status}</span>- <div className="flex-1" />- {lastChecked && (- <span className="text-[11px] text-muted-foreground tabular-nums">- {formatSqliteUtcToLocalTime(lastChecked, { hour: '2-digit', minute: '2-digit' })}- </span>- )}- {!isEditing && (- <Button- variant="ghost"- size="xs"- onClick={() => startEditing(k)}- aria-label={t('keys.editLabel')}- title={t('keys.editLabel')}- >- <Pencil className="size-3" />- </Button>- )}- <Button variant="ghost" size="xs" onClick={() => checkKey.mutate(k.id)} disabled={checkKey.isPending}>- {t('common.check')}- </Button>- <ConfirmButton- className="text-muted-foreground hover:text-destructive"- confirmLabel={t('keys.confirmRemove')}- onConfirm={() => deleteKey.mutate(k.id)}- disabled={deleteKey.isPending}- >- {t('common.remove')}- </ConfirmButton>- </div>- {hasCustomModels && isExpanded && (- <div className="flex flex-wrap gap-2 border-t bg-muted/20 px-4 py-3 pl-12">- {customModels.map(model => {- const modelKey = customModelDeleteKey(model)- return (- <div key={modelKey} className="inline-flex min-w-0 items-center gap-2 rounded-md border bg-background px-2 py-1 text-[11px]">- <span className="rounded border px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted-foreground">- {t(CUSTOM_MODEL_KIND_LABEL[model.kind])}- </span>- <span className="max-w-[180px] truncate font-medium" title={model.modelId}>- {model.displayName}- </span>- {model.family && (- <code className="max-w-[160px] truncate text-muted-foreground" title={model.family}>- {model.family}- </code>- )}- <ConfirmButton- className="h-5 px-1 text-muted-foreground hover:text-destructive"- disabled={deleteCustomModel.isPending}- onConfirm={() => deleteCustomModel.mutate(model)}- title={t('common.remove')}- aria-label={t('common.remove')}- >- <Trash2 className="size-3" />- </ConfirmButton>- </div>- )- })}- </div>- )}- </div>- )- })}- </div>- </div>- ))}- </div>- )}- </section>- </>- )}+ {tab === 'providers' && <ProviderList onAddKey={() => setAddOpen(true)} />}</div>++ <AddKeyDialog open={addOpen} onOpenChange={setAddOpen} /></div>)}diff --git a/server/src/__tests__/routes/analytics.test.ts b/server/src/__tests__/routes/analytics.test.tsindex 6b193704..c5ab711e 100644--- a/server/src/__tests__/routes/analytics.test.ts+++ b/server/src/__tests__/routes/analytics.test.ts@@ -245,4 +245,180 @@ describe('Analytics API', () => {expect(row.pinnedRequests).toBe(1);});});++ // Raw-row insert covering the newer columns (ttfb_ms, request_type, key_id,+ // per-row latency). These feed the latency-percentile, TTFT, per-type, and+ // per-key analytics that only exist on the raw table. No aggregate upsert:+ // these tests assert the raw-scoped fields, not the hourly totals.+ function insertRaw(opts: {+ platform?: string;+ modelId?: string;+ keyId?: number | null;+ status?: 'success' | 'error';+ inputTokens?: number;+ outputTokens?: number;+ latencyMs?: number;+ ttfbMs?: number | null;+ requestType?: string;+ error?: string | null;+ createdAt: string;+ }) {+ const {+ platform = 'test',+ modelId = 'test-model',+ keyId = null,+ status = 'success',+ inputTokens = 0,+ outputTokens = 0,+ latencyMs = 0,+ ttfbMs = null,+ requestType = 'chat',+ error = null,+ createdAt,+ } = opts;+ getDb().prepare(`+ INSERT INTO requests (platform, model_id, key_id, status, input_tokens, output_tokens, latency_ms, ttfb_ms, request_type, error, created_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ `).run(platform, modelId, keyId, status, inputTokens, outputTokens, latencyMs, ttfbMs, requestType, error, createdAt);+ }++ describe('extended summary fields', () => {+ it('returns latency percentiles from the raw rows', async () => {+ // Latencies 10..100 in a 24h window → p50 = 50, p95 = 90 (nearest-rank),+ // avg = 55.+ for (let ms = 10; ms <= 100; ms += 10) {+ insertRaw({ latencyMs: ms, createdAt: '2026-05-29 11:00:00' });+ }++ const { status, body } = await request(app, '/api/analytics/summary?range=24h');++ expect(status).toBe(200);+ expect(body.p50LatencyMs).toBe(50);+ expect(body.p95LatencyMs).toBe(90);+ expect(body.avgLatencyMs).toBe(55);+ });++ it('returns null percentiles and TTFT when the raw window is empty', async () => {+ const { status, body } = await request(app, '/api/analytics/summary?range=24h');++ expect(status).toBe(200);+ expect(body.p50LatencyMs).toBeNull();+ expect(body.p95LatencyMs).toBeNull();+ expect(body.avgTtfbMs).toBeNull();+ });++ it('averages TTFT over rows that recorded it and ignores NULL ttfb', async () => {+ insertRaw({ ttfbMs: 100, createdAt: '2026-05-29 11:00:00' });+ insertRaw({ ttfbMs: 200, createdAt: '2026-05-29 11:01:00' });+ insertRaw({ ttfbMs: null, createdAt: '2026-05-29 11:02:00' });++ const { status, body } = await request(app, '/api/analytics/summary?range=24h');++ expect(status).toBe(200);+ expect(body.avgTtfbMs).toBe(150);+ });++ it('splits requests into chat and embedding counts', async () => {+ insertRaw({ requestType: 'chat', createdAt: '2026-05-29 11:00:00' });+ insertRaw({ requestType: 'chat', createdAt: '2026-05-29 11:01:00' });+ insertRaw({ requestType: 'embedding', createdAt: '2026-05-29 11:02:00' });++ const { status, body } = await request(app, '/api/analytics/summary?range=24h');++ expect(status).toBe(200);+ expect(body.requestTypeCounts).toEqual({ chat: 2, embedding: 1 });+ });+ });++ describe('extended by-platform fields', () => {+ it('adds p95 latency, avg TTFT, error count, and tokens/sec per platform', async () => {+ // groq: 1 success (100ms, ttfb 20, 1000 out tok) + 1 error (300ms, ttfb 40).+ insertRaw({ platform: 'groq', status: 'success', outputTokens: 1000, latencyMs: 100, ttfbMs: 20, createdAt: '2026-05-29 11:00:00' });+ insertRaw({ platform: 'groq', status: 'error', outputTokens: 0, latencyMs: 300, ttfbMs: 40, error: 'boom', createdAt: '2026-05-29 11:01:00' });++ const { status, body } = await request(app, '/api/analytics/by-platform?range=24h');++ expect(status).toBe(200);+ const groq = body.find((r: any) => r.platform === 'groq');+ expect(groq.errorCount).toBe(1);+ expect(groq.avgTtfbMs).toBe(30);+ // Only the success row qualifies (output>0 & latency>0): 1000 / 0.1 = 10000 tok/s.+ expect(groq.avgTokensPerSecond).toBe(10000);+ expect(typeof groq.p95LatencyMs).toBe('number');+ });++ it('reports null TTFT and tokens/sec when no rows qualify', async () => {+ insertRaw({ platform: 'nokey', status: 'success', outputTokens: 0, latencyMs: 0, ttfbMs: null, createdAt: '2026-05-29 11:00:00' });++ const { status, body } = await request(app, '/api/analytics/by-platform?range=24h');++ expect(status).toBe(200);+ const row = body.find((r: any) => r.platform === 'nokey');+ expect(row.avgTtfbMs).toBeNull();+ expect(row.avgTokensPerSecond).toBeNull();+ });+ });++ describe('by-key endpoint', () => {+ it('groups usage per key, joins the label, and keeps deleted keys', async () => {+ getDb().prepare('DELETE FROM api_keys').run();+ getDb().prepare(`+ INSERT INTO api_keys (id, platform, label, encrypted_key, iv, auth_tag)+ VALUES (1, 'groq', 'Prod key', 'x', 'x', 'x')+ `).run();++ // key 1 (exists): 3 rows, 2 success + 1 error, latency 100/200/300.+ insertRaw({ keyId: 1, status: 'success', inputTokens: 10, outputTokens: 5, latencyMs: 100, createdAt: '2026-05-29 11:00:00' });+ insertRaw({ keyId: 1, status: 'success', inputTokens: 20, outputTokens: 7, latencyMs: 200, createdAt: '2026-05-29 11:01:00' });+ insertRaw({ keyId: 1, status: 'error', inputTokens: 0, outputTokens: 0, latencyMs: 300, error: 'boom', createdAt: '2026-05-29 11:02:00' });+ // key 99 (deleted — no api_keys row): 2 rows.+ insertRaw({ keyId: 99, status: 'success', latencyMs: 50, createdAt: '2026-05-29 11:03:00' });+ insertRaw({ keyId: 99, status: 'success', latencyMs: 50, createdAt: '2026-05-29 11:04:00' });+ // key_id NULL row must be excluded entirely.+ insertRaw({ keyId: null, status: 'success', createdAt: '2026-05-29 11:05:00' });++ const { status, body } = await request(app, '/api/analytics/by-key?range=24h');++ expect(status).toBe(200);+ expect(body).toHaveLength(2);++ const k1 = body.find((r: any) => r.keyId === 1);+ expect(k1.label).toBe('Prod key');+ expect(k1.platform).toBe('groq');+ expect(k1.requests).toBe(3);+ expect(k1.successRate).toBe(66.7);+ expect(k1.avgLatencyMs).toBe(200);+ expect(k1.totalInputTokens).toBe(30);+ expect(k1.totalOutputTokens).toBe(12);++ const k99 = body.find((r: any) => r.keyId === 99);+ expect(k99.label).toBeNull();+ expect(k99.platform).toBeNull();+ expect(k99.requests).toBe(2);+ });+ });++ describe('90d range', () => {+ it('accepts range=90d across the analytics endpoints', async () => {+ insertRequest('2026-02-01 12:00:00'); // ~117 days ago — outside 90d+ insertRequest('2026-03-15 12:00:00'); // ~75 days ago — inside 90d+ insertRequest('2026-05-29 11:00:00'); // today — inside 90d++ const summary = await request(app, '/api/analytics/summary?range=90d');+ expect(summary.status).toBe(200);+ expect(summary.body.totalRequests).toBe(2);++ const timeline = await request(app, '/api/analytics/timeline?range=90d');+ expect(timeline.status).toBe(200);+ // Day-bucketed for 90d; the two in-window rows land on two days.+ expect(Array.isArray(timeline.body)).toBe(true);+ expect(timeline.body.every((b: any) => 'inputTokens' in b && 'outputTokens' in b)).toBe(true);++ const byPlatform = await request(app, '/api/analytics/by-platform?range=90d');+ expect(byPlatform.status).toBe(200);++ const byKey = await request(app, '/api/analytics/by-key?range=90d');+ expect(byKey.status).toBe(200);+ });+ });});diff --git a/server/src/routes/analytics.ts b/server/src/routes/analytics.tsindex 94773493..7a073082 100644--- a/server/src/routes/analytics.ts+++ b/server/src/routes/analytics.ts@@ -18,6 +18,8 @@ function getSinceTimestamp(range: string): string {return toSqliteDateTime(now - 24 * 60 * 60 * 1000);case '30d':return toSqliteDateTime(now - 30 * 24 * 60 * 60 * 1000);+ case '90d':+ return toSqliteDateTime(now - 90 * 24 * 60 * 60 * 1000);case '7d':default:return toSqliteDateTime(now - 7 * 24 * 60 * 60 * 1000);@@ -110,6 +112,50 @@ analyticsRouter.get('/summary', (req: Request, res: Response) => {FROM requests WHERE created_at >= ?`).get(since) as { pinned_count: number | null; pin_honored_count: number | null };+ // Latency percentiles, time-to-first-token, and the chat/embedding split all+ // live on the raw rows (the hourly aggregate keeps neither latency nor a+ // per-type breakdown). When the raw window is empty (older than the prune+ // horizon) we report null, not 0, so the UI can render a placeholder instead+ // of a misleading zero. Percentiles use nearest-rank via ORDER BY/OFFSET.+ // Only rows that actually recorded a latency participate in the percentile.+ // The IS NOT NULL guard must be on BOTH the offset-denominator count and the+ // ordered selection so they range over the same set: a NULL sorts first under+ // ORDER BY latency_ms ASC, so if it were counted but not filtered the offset+ // math would shift and a NULL could be selected (rendered as 0).+ const rawCount = (db.prepare(+ `SELECT COUNT(*) as c FROM requests WHERE created_at >= ? AND latency_ms IS NOT NULL`+ ).get(since) as { c: number }).c;+ const percentileAt = (fraction: number): number | null => {+ if (rawCount === 0) return null;+ const offset = Math.floor((rawCount - 1) * fraction);+ const row = db.prepare(`+ SELECT latency_ms FROM requests+ WHERE created_at >= ? AND latency_ms IS NOT NULL+ ORDER BY latency_ms ASC+ LIMIT 1 OFFSET ?+ `).get(since, offset) as { latency_ms: number } | undefined;+ return row ? Math.round(row.latency_ms) : null;+ };+ const p50LatencyMs = percentileAt(0.5);+ const p95LatencyMs = percentileAt(0.95);++ const ttfbRow = db.prepare(`+ SELECT AVG(ttfb_ms) as avg_ttfb_ms FROM requests+ WHERE created_at >= ? AND ttfb_ms IS NOT NULL+ `).get(since) as { avg_ttfb_ms: number | null } | undefined;+ const avgTtfbMs = ttfbRow?.avg_ttfb_ms != null ? Math.round(ttfbRow.avg_ttfb_ms) : null;++ const typeRows = db.prepare(`+ SELECT request_type, COUNT(*) as count FROM requests+ WHERE created_at >= ?+ GROUP BY request_type+ `).all(since) as Array<{ request_type: string; count: number }>;+ const requestTypeCounts = { chat: 0, embedding: 0 };+ for (const row of typeRows) {+ if (row.request_type === 'embedding') requestTypeCounts.embedding = row.count;+ else if (row.request_type === 'chat') requestTypeCounts.chat = row.count;+ }+const lifetimeFirst = readLifetimeSettings();res.json({@@ -118,6 +164,15 @@ analyticsRouter.get('/summary', (req: Request, res: Response) => {totalInputTokens: aggregate.total_input_tokens ?? 0,totalOutputTokens: aggregate.total_output_tokens ?? 0,avgLatencyMs: Math.round(latencyRow?.avg_latency_ms ?? 0),+ // Latency spread (raw rows): p50 typical, p95 tail. Null when the raw+ // window is empty.+ p50LatencyMs,+ p95LatencyMs,+ // Average streaming time-to-first-token over rows that recorded it; null+ // when none did (non-streaming traffic or pruned window).+ avgTtfbMs,+ // Chat vs embedding request split for the selected window.+ requestTypeCounts,estimatedCostSavings: Math.round((savings.est_savings ?? 0) * 100) / 100,// Pinned = requests where the client named a specific model (not 'auto').// Honored = the pinned model actually served it; the difference is@@ -187,8 +242,13 @@ analyticsRouter.get('/by-platform', (req: Request, res: Response) => {SELECTplatform,COUNT(*) as requests,+ COUNT(latency_ms) as latency_count,SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) * 100.0 / COUNT(*) as success_rate,AVG(latency_ms) as avg_latency_ms,+ AVG(ttfb_ms) as avg_ttfb_ms,+ SUM(CASE WHEN status = 'error' THEN 1 ELSE 0 END) as error_count,+ AVG(CASE WHEN output_tokens > 0 AND latency_ms > 0+ THEN output_tokens / (latency_ms / 1000.0) ELSE NULL END) as avg_tokens_per_second,SUM(input_tokens) as total_input_tokens,SUM(output_tokens) as total_output_tokensFROM requests@@ -197,8 +257,74 @@ analyticsRouter.get('/by-platform', (req: Request, res: Response) => {ORDER BY requests DESC`).all(since) as any[];+ // P95 latency is a per-group percentile; SQLite has no native percentile+ // aggregate, so we take the nearest-rank value per platform with a small+ // ORDER BY/OFFSET query. The platform count is tiny (one row per provider),+ // so the extra round-trips are negligible and keep the SQL readable.+ const p95Stmt = db.prepare(`+ SELECT latency_ms FROM requests+ WHERE created_at >= ? AND platform = ? AND latency_ms IS NOT NULL+ ORDER BY latency_ms ASC+ LIMIT 1 OFFSET ?+ `);++ res.json(rows.map(r => {+ // Offset math and the ordered selection both range over the non-null+ // latency rows (latency_count), so a NULL can neither be counted into the+ // denominator nor selected as the p95 value.+ const latencyCount = r.latency_count ?? 0;+ const p95Row = latencyCount > 0+ ? (p95Stmt.get(since, r.platform, Math.floor((latencyCount - 1) * 0.95)) as { latency_ms: number } | undefined)+ : undefined;+ return {+ platform: r.platform,+ requests: r.requests,+ successRate: Math.round(r.success_rate * 10) / 10,+ avgLatencyMs: Math.round(r.avg_latency_ms),+ p95LatencyMs: p95Row ? Math.round(p95Row.latency_ms) : null,+ avgTtfbMs: r.avg_ttfb_ms != null ? Math.round(r.avg_ttfb_ms) : null,+ errorCount: r.error_count ?? 0,+ avgTokensPerSecond: r.avg_tokens_per_second != null+ ? Math.round(r.avg_tokens_per_second * 10) / 10+ : null,+ totalInputTokens: r.total_input_tokens ?? 0,+ totalOutputTokens: r.total_output_tokens ?? 0,+ };+ }));+});++// Stats grouped by API key. Raw-row scoped (the hourly aggregate has no key+// dimension), LEFT JOINed to api_keys so a request whose key was later deleted+// still shows up with a null label — the keyId is always returned.+analyticsRouter.get('/by-key', (req: Request, res: Response) => {+ const range = (req.query.range as string) ?? '7d';+ const since = getSinceTimestamp(range);+ const db = getDb();++ const rows = db.prepare(`+ SELECT+ r.key_id as key_id,+ k.label as label,+ k.platform as platform,+ COUNT(*) as requests,+ SUM(CASE WHEN r.status = 'success' THEN 1 ELSE 0 END) * 100.0 / COUNT(*) as success_rate,+ AVG(r.latency_ms) as avg_latency_ms,+ SUM(r.input_tokens) as total_input_tokens,+ SUM(r.output_tokens) as total_output_tokens+ FROM requests r+ LEFT JOIN api_keys k ON k.id = r.key_id+ WHERE r.key_id IS NOT NULL AND r.created_at >= ?+ GROUP BY r.key_id+ ORDER BY requests DESC+ LIMIT 50+ `).all(since) as any[];+res.json(rows.map(r => ({- platform: r.platform,+ keyId: r.key_id,+ // Null when the key row was deleted, or the empty string when the key+ // exists but was never labelled; the client falls back to "Key #<id>".+ label: r.label ?? null,+ platform: r.platform ?? null,requests: r.requests,successRate: Math.round(r.success_rate * 10) / 10,avgLatencyMs: Math.round(r.avg_latency_ms),@@ -225,7 +351,9 @@ analyticsRouter.get('/timeline', (req: Request, res: Response) => {strftime('${dateFormat}', hour) as timestamp,SUM(total_requests) as requests,SUM(success_count) as success_count,- SUM(error_count) as failure_count+ SUM(error_count) as failure_count,+ SUM(input_tokens) as input_tokens,+ SUM(output_tokens) as output_tokensFROM request_hourlyWHERE hour >= ?GROUP BY strftime('${dateFormat}', hour)@@ -237,6 +365,8 @@ analyticsRouter.get('/timeline', (req: Request, res: Response) => {requests: r.requests,successCount: r.success_count,failureCount: r.failure_count,+ inputTokens: r.input_tokens ?? 0,+ outputTokens: r.output_tokens ?? 0,})));});