Skip to content

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

Analytics: give custom endpoints their own identity (#889) (#958)

tashdroid3503f915f69b
diff --git a/client/src/pages/AnalyticsPage.tsx b/client/src/pages/AnalyticsPage.tsx
index 1444c936..b0cf9951 100644
--- a/client/src/pages/AnalyticsPage.tsx
+++ b/client/src/pages/AnalyticsPage.tsx
@@ -77,6 +77,13 @@ interface SummaryResponse {
interface ByPlatformRow {
platform: string
+ // Stable identity for the filter dropdown. For a catalog platform it equals
+ // `platform`; for a custom endpoint it is `custom:<base_url>` (#889), so each
+ // relay is filterable on its own instead of collapsing into 'custom'.
+ providerId: string
+ // Human display name. Catalog: the platform id. Custom: the endpoint host
+ // (e.g. 'relay.example.com') so several relays are distinguishable.
+ endpoint?: string
requests: number
successRate: number
avgLatencyMs: number
@@ -109,6 +116,11 @@ interface TimelineBucket {
interface ByModelRow {
platform: string
+ // Endpoint identity of the row (#889). The same model id served by two
+ // custom relays is two rows, one per relay, so the name has to say which.
+ // Same id/name pair /by-platform returns for that endpoint.
+ providerId?: string
+ endpoint?: string
modelId: string
displayName: string
requests: number
@@ -133,13 +145,19 @@ interface ByKeyRow {
interface ErrorDistribution {
byCategory: Array<{ category: string; count: number }>
- byPlatform: Array<{ platform: string; count: number }>
+ // One entry per provider — per custom ENDPOINT, not one pooled 'custom'
+ // entry (#889); `platform` is kept for the dot coloring.
+ byPlatform: Array<{ platform: string; providerId?: string; endpoint?: string; count: number }>
detailed: Array<{ platform: string; model_id: string; error_category: string; count: number }>
}
interface RecentErrorRow {
id: number
platform: string
+ // Which endpoint produced the error: the platform slug for catalog
+ // providers, the custom endpoint's host/path for a relay (#889).
+ providerId?: string
+ endpoint?: string
modelId: string
error: string
latencyMs: number
@@ -455,6 +473,11 @@ export default function AnalyticsPage() {
queryFn: () => apiFetch<ByPlatformRow[]>(`/api/analytics/by-platform?range=${range}`),
})
+ // Friendly display name per providerId: catalog → the platform id, custom →
+ // the endpoint host. Used by the filter dropdown so a selected custom relay
+ // shows 'relay.example.com', not 'custom:https://relay.example.com' (#889).
+ const providerDisplay = new Map(byPlatform.map((p) => [p.providerId, p.endpoint ?? p.platform]))
+
const { data: byClient = [] } = useQuery({
queryKey: ['analytics', 'by-client', range],
queryFn: () => apiFetch<ByClientRow[]>(`/api/analytics/by-client?range=${range}`),
@@ -501,7 +524,9 @@ export default function AnalyticsPage() {
queryFn: () => {
const params = new URLSearchParams({ range, limit: '100' })
if (statusFilter !== 'all') params.set('status', statusFilter)
- if (platformFilter !== 'all') params.set('platform', platformFilter)
+ // provider (not platform) so a selected custom relay filters to itself
+ // instead of every custom endpoint (#889). Catalog ids equal the platform.
+ if (platformFilter !== 'all') params.set('provider', platformFilter)
return apiFetch<RecentCallsResponse>(`/api/analytics/requests?${params}`)
},
})
@@ -655,7 +680,7 @@ export default function AnalyticsPage() {
<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 }} />
+ <XAxis dataKey={(row: ByPlatformRow) => row.endpoint ?? row.platform} tick={axisStyle} tickLine={false} axisLine={{ stroke: gridStyle }} />
<YAxis tick={axisStyle} tickLine={false} axisLine={false} />
<Tooltip contentStyle={tooltipStyle} />
<Bar dataKey="requests" name={t('analytics.requests')} fill={primaryFill} radius={[3, 3, 0, 0]} maxBarSize={24} />
@@ -688,7 +713,7 @@ export default function AnalyticsPage() {
<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 }} />
+ <XAxis dataKey={(row: ByPlatformRow) => row.endpoint ?? row.platform} tick={axisStyle} tickLine={false} axisLine={{ stroke: gridStyle }} />
<YAxis unit="ms" tick={axisStyle} tickLine={false} axisLine={false} />
<Tooltip contentStyle={tooltipStyle} />
<Legend wrapperStyle={{ fontSize: 12 }} iconType="rect" />
@@ -709,7 +734,7 @@ export default function AnalyticsPage() {
<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 }} />
+ <XAxis dataKey={(row: ByPlatformRow) => row.endpoint ?? row.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} />
@@ -742,7 +767,7 @@ export default function AnalyticsPage() {
<ResponsiveContainer width="100%" height={240}>
<BarChart data={errorDist.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 }} />
+ <XAxis dataKey={(row: ErrorDistribution['byPlatform'][number]) => row.endpoint ?? row.platform} tick={axisStyle} tickLine={false} axisLine={{ stroke: gridStyle }} />
<YAxis tick={axisStyle} tickLine={false} axisLine={false} />
<Tooltip contentStyle={tooltipStyle} />
<Bar dataKey="count" name={t('analytics.errors')} fill="var(--destructive)" radius={[3, 3, 0, 0]} maxBarSize={24} />
@@ -767,7 +792,7 @@ export default function AnalyticsPage() {
<TableBody>
{errors.slice(0, 20).map((e) => (
<TableRow key={e.id}>
- <TableCell className="pl-4 text-xs">{e.platform}</TableCell>
+ <TableCell className="pl-4 text-xs">{e.endpoint ?? e.platform}</TableCell>
<TableCell className="text-xs max-w-[200px] truncate">{e.error}</TableCell>
<TableCell className="text-right text-xs text-muted-foreground tabular-nums pr-4">
{formatSqliteUtcToLocalTime(e.createdAt, { hour: '2-digit', minute: '2-digit' })}
@@ -805,16 +830,16 @@ export default function AnalyticsPage() {
<Select value={platformFilter} onValueChange={(v) => setPlatformFilter(v ?? 'all')}>
<SelectTrigger size="sm" aria-label={t('common.provider')}>
<SelectValue>
- {(v: string) => (!v || v === 'all' ? t('analytics.allProviders') : v)}
+ {(v: string) => (!v || v === 'all' ? t('analytics.allProviders') : providerDisplay.get(v) ?? v)}
</SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem value="all">{t('analytics.allProviders')}</SelectItem>
{byPlatform.map((p) => (
- <SelectItem key={p.platform} value={p.platform}>
+ <SelectItem key={p.providerId} value={p.providerId}>
<span className="flex items-center gap-2">
<PlatformDot platform={p.platform} />
- <span>{p.platform}</span>
+ <span>{p.endpoint ?? p.platform}</span>
</span>
</SelectItem>
))}
@@ -909,11 +934,11 @@ export default function AnalyticsPage() {
</TableHeader>
<TableBody>
{byPlatform.map((p) => (
- <TableRow key={p.platform}>
+ <TableRow key={p.providerId}>
<TableCell className="pl-4 text-sm font-medium">
<span className="flex items-center gap-2">
<PlatformDot platform={p.platform} />
- {p.platform}
+ {p.endpoint ?? p.platform}
</span>
</TableCell>
<TableCell className="text-right tabular-nums">{p.requests}</TableCell>
@@ -957,10 +982,10 @@ export default function AnalyticsPage() {
</TableRow>
</TableHeader>
<TableBody>
- {byModel.map((m, i) => (
- <TableRow key={i}>
+ {byModel.map((m) => (
+ <TableRow key={`${m.providerId ?? m.platform}:${m.modelId}`}>
<TableCell className="pl-4 text-sm font-medium">{m.displayName}</TableCell>
- <TableCell className="text-xs text-muted-foreground">{m.platform}</TableCell>
+ <TableCell className="text-xs text-muted-foreground">{m.endpoint ?? 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>
diff --git a/server/src/__tests__/lib/module-purity.test.ts b/server/src/__tests__/lib/module-purity.test.ts
index f090c016..4908d287 100644
--- a/server/src/__tests__/lib/module-purity.test.ts
+++ b/server/src/__tests__/lib/module-purity.test.ts
@@ -34,6 +34,7 @@ const PURE_MODULES = [
'budget.ts',
'error-classify.ts',
'header-value.ts',
+ 'provider-identity.ts',
'structured-output.ts',
'tool-args.ts',
'tool-call-rescue.ts',
diff --git a/server/src/__tests__/lib/provider-identity.test.ts b/server/src/__tests__/lib/provider-identity.test.ts
new file mode 100644
index 00000000..b9b90c4c
--- /dev/null
+++ b/server/src/__tests__/lib/provider-identity.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from 'vitest';
+import { endpointHost, providerDisplayName, providerIdFor } from '../../lib/provider-identity.js';
+import { endpointScopeForBaseUrl } from '../../lib/endpoint-scope.js';
+
+describe('provider-identity', () => {
+ describe('endpointHost', () => {
+ it('returns the host (and port) of a base_url', () => {
+ expect(endpointHost('https://relay.example.com/v1')).toBe('relay.example.com');
+ expect(endpointHost('http://192.168.1.10:11434/v1')).toBe('192.168.1.10:11434');
+ expect(endpointHost('https://api.openrouter.ai')).toBe('api.openrouter.ai');
+ });
+
+ it('returns null for empty or unparseable input', () => {
+ expect(endpointHost(null)).toBeNull();
+ expect(endpointHost(undefined)).toBeNull();
+ expect(endpointHost('')).toBeNull();
+ expect(endpointHost('not a url')).toBeNull();
+ });
+ });
+
+ describe('providerIdFor', () => {
+ it('keeps the bare platform slug for catalog providers', () => {
+ expect(providerIdFor('groq', null)).toBe('groq');
+ expect(providerIdFor('openai', null)).toBe('openai');
+ });
+
+ it('names a custom endpoint by its base_url so relays never collide', () => {
+ expect(providerIdFor('custom', 'https://relay-a.example.com/v1')).toBe('custom:https://relay-a.example.com/v1');
+ expect(providerIdFor('custom', 'https://relay-b.example.com/v1')).toBe('custom:https://relay-b.example.com/v1');
+ // Two distinct relays → two distinct ids (the #889 collision).
+ expect(providerIdFor('custom', 'https://relay-a.example.com/v1'))
+ .not.toBe(providerIdFor('custom', 'https://relay-b.example.com/v1'));
+ });
+
+ it('falls back to the plain "custom" id when the key is gone', () => {
+ expect(providerIdFor('custom', null)).toBe('custom');
+ expect(providerIdFor('custom', undefined)).toBe('custom');
+ expect(providerIdFor('custom', '')).toBe('custom');
+ });
+
+ it('is the endpoint-scope token verbatim', () => {
+ // The caller hands in the NORMALIZED base_url (keys.ts on write, the SQL
+ // in routes/analytics.ts for older rows), so the id matches
+ // `models.endpoint_scope` for the same endpoint and this module needs no
+ // second definition of "same endpoint" of its own.
+ expect(providerIdFor('custom', endpointScopeForBaseUrl('https://relay-a.example.com/v1/')))
+ .toBe('custom:https://relay-a.example.com/v1');
+ });
+ });
+
+ describe('providerDisplayName', () => {
+ it('shows the endpoint host for custom rows', () => {
+ expect(providerDisplayName('custom', 'https://relay-a.example.com/v1')).toBe('relay-a.example.com');
+ expect(providerDisplayName('custom', 'http://192.168.1.10:11434/v1')).toBe('192.168.1.10:11434');
+ });
+
+ it('falls back to the platform when the host cannot be derived', () => {
+ expect(providerDisplayName('custom', null)).toBe('custom');
+ expect(providerDisplayName('custom', 'garbage')).toBe('custom');
+ });
+
+ it('shows the platform slug for catalog providers', () => {
+ expect(providerDisplayName('groq', null)).toBe('groq');
+ });
+
+ it('keeps the path when it, not the host, is what tells endpoints apart', () => {
+ // One gateway fronting two tenants: the host is identical, so a
+ // host-only name would collide and the operator could not tell the rows
+ // apart — #889 all over again, one level down.
+ const a = providerDisplayName('custom', 'https://gw.example.com/tenant-a/v1');
+ const b = providerDisplayName('custom', 'https://gw.example.com/tenant-b/v1');
+ expect(a).toBe('gw.example.com/tenant-a/v1');
+ expect(b).toBe('gw.example.com/tenant-b/v1');
+ expect(a).not.toBe(b);
+ });
+
+ it('drops only a trivial path, so the common case still reads as a host', () => {
+ // '/', '/v1', '/v1beta' say nothing a second endpoint on the host would
+ // not also say, so they are noise in the single-endpoint-per-host case.
+ expect(providerDisplayName('custom', 'https://relay.example.com')).toBe('relay.example.com');
+ expect(providerDisplayName('custom', 'https://relay.example.com/')).toBe('relay.example.com');
+ expect(providerDisplayName('custom', 'https://relay.example.com/v1')).toBe('relay.example.com');
+ expect(providerDisplayName('custom', 'https://relay.example.com/v1beta')).toBe('relay.example.com');
+ expect(providerDisplayName('custom', 'http://192.168.1.10:11434/v1')).toBe('192.168.1.10:11434');
+ });
+
+ it('does not collapse a kept path onto its own versioned form', () => {
+ // Trimming the '/v1' off a KEPT path would make these two endpoints
+ // display the same name, which is the collision this exists to prevent.
+ expect(providerDisplayName('custom', 'https://gw.example.com/tenant-a'))
+ .not.toBe(providerDisplayName('custom', 'https://gw.example.com/tenant-a/v1'));
+ });
+
+ it('names an endpoint the same way no matter which other endpoints exist', () => {
+ // Purely a function of this row's base_url (like endpoint-scope's
+ // handles), so /by-platform, /by-model and /errors agree on the name
+ // even though each sees a different subset of endpoints.
+ expect(providerDisplayName('custom', 'https://relay-a.example.com/v1/'))
+ .toBe(providerDisplayName('custom', 'https://relay-a.example.com/v1'));
+ });
+ });
+});
diff --git a/server/src/__tests__/routes/analytics.test.ts b/server/src/__tests__/routes/analytics.test.ts
index ba91db5b..fe6c1446 100644
--- a/server/src/__tests__/routes/analytics.test.ts
+++ b/server/src/__tests__/routes/analytics.test.ts
@@ -477,4 +477,350 @@ describe('Analytics API', () => {
expect(byKey.status).toBe(200);
});
});
+
+ // #889 — custom endpoints all share the platform id 'custom', so the
+ // provider breakdown must split them by the serving key's base_url (the
+ // canonical endpoint identity) instead of collapsing every relay into one
+ // "custom" row. These tests seed two distinct custom endpoints (plus a
+ // pooled second key on the first) and assert the split, the per-endpoint
+ // p95 scoping, and the recent-calls provider filter.
+ describe('custom endpoint identifiers (#889)', () => {
+ // Seed a custom endpoint key and return its id. base_url is the endpoint
+ // identity; the credential itself is a placeholder (never read here).
+ function insertCustomKey(id: number, baseUrl: string, label: string): void {
+ getDb().prepare(`
+ INSERT INTO api_keys (id, platform, label, encrypted_key, iv, auth_tag, base_url)
+ VALUES (?, 'custom', ?, 'x', 'x', 'x', ?)
+ `).run(id, label, baseUrl);
+ }
+
+ // A model row belonging to ONE endpoint (#651): `models` is unique on
+ // (platform, model_id, endpoint_scope), so two relays can each hold their
+ // own row for the same model id.
+ function insertScopedModel(modelId: string, displayName: string, endpointScope: string): void {
+ getDb().prepare(`
+ INSERT INTO models (platform, model_id, display_name, intelligence_rank, speed_rank, endpoint_scope)
+ VALUES ('custom', ?, ?, 50, 50, ?)
+ `).run(modelId, displayName, endpointScope);
+ }
+
+ beforeEach(() => {
+ getDb().prepare('DELETE FROM api_keys').run();
+ // Only endpoint-scoped rows; the seeded catalog ('' scope) stays put.
+ getDb().prepare("DELETE FROM models WHERE endpoint_scope <> ''").run();
+ });
+
+ it('splits custom endpoints into per-endpoint rows instead of one "custom" row', async () => {
+ insertCustomKey(1, 'https://relay-a.example.com/v1', 'Relay A');
+ insertCustomKey(2, 'https://relay-b.example.com/v1', 'Relay B');
+
+ // Two requests on relay A, one on relay B.
+ insertRaw({ platform: 'custom', keyId: 1, status: 'success', latencyMs: 100, createdAt: '2026-05-29 11:00:00' });
+ insertRaw({ platform: 'custom', keyId: 1, status: 'success', latencyMs: 120, createdAt: '2026-05-29 11:01:00' });
+ insertRaw({ platform: 'custom', keyId: 2, status: 'success', latencyMs: 900, createdAt: '2026-05-29 11:02:00' });
+
+ const { status, body } = await request(app, '/api/analytics/by-platform?range=24h');
+ expect(status).toBe(200);
+
+ // Two distinct custom rows — NOT a single collapsed "custom" row.
+ const customRows = body.filter((r: any) => r.platform === 'custom');
+ expect(customRows).toHaveLength(2);
+
+ const a = body.find((r: any) => r.providerId === 'custom:https://relay-a.example.com/v1');
+ const b = body.find((r: any) => r.providerId === 'custom:https://relay-b.example.com/v1');
+ expect(a).toBeDefined();
+ expect(b).toBeDefined();
+ expect(a.requests).toBe(2);
+ expect(b.requests).toBe(1);
+ // The operator-readable identifier is the endpoint host.
+ expect(a.endpoint).toBe('relay-a.example.com');
+ expect(b.endpoint).toBe('relay-b.example.com');
+ // Each row keeps the raw platform id for the platform-dot coloring.
+ expect(a.platform).toBe('custom');
+ expect(b.platform).toBe('custom');
+ });
+
+ it('groups a pooled endpoint (several keys, one base_url) into a single row', async () => {
+ // Two credentials for the SAME relay — the pooling case (#619). They
+ // share a base_url, so they must read as ONE endpoint, not two rows.
+ insertCustomKey(1, 'https://relay-a.example.com/v1', 'Relay A key 1');
+ insertCustomKey(2, 'https://relay-a.example.com/v1', 'Relay A key 2');
+
+ insertRaw({ platform: 'custom', keyId: 1, status: 'success', latencyMs: 100, createdAt: '2026-05-29 11:00:00' });
+ insertRaw({ platform: 'custom', keyId: 2, status: 'success', latencyMs: 110, createdAt: '2026-05-29 11:01:00' });
+
+ const { status, body } = await request(app, '/api/analytics/by-platform?range=24h');
+ expect(status).toBe(200);
+
+ const customRows = body.filter((r: any) => r.platform === 'custom');
+ expect(customRows).toHaveLength(1);
+ expect(customRows[0].providerId).toBe('custom:https://relay-a.example.com/v1');
+ expect(customRows[0].requests).toBe(2);
+ });
+
+ it('scopes p95 latency per endpoint, not across all custom traffic', async () => {
+ insertCustomKey(1, 'https://relay-a.example.com/v1', 'Relay A');
+ insertCustomKey(2, 'https://relay-b.example.com/v1', 'Relay B');
+
+ // Relay A: fast (100ms x10). Relay B: slow (1000ms x10). If p95 bled
+ // across the whole "custom" platform, A's p95 would be ~1000, not 100.
+ for (let i = 0; i < 10; i++) {
+ insertRaw({ platform: 'custom', keyId: 1, status: 'success', latencyMs: 100, createdAt: `2026-05-29 10:${String(i).padStart(2, '0')}:00` });
+ }
+ for (let i = 0; i < 10; i++) {
+ insertRaw({ platform: 'custom', keyId: 2, status: 'success', latencyMs: 1000, createdAt: `2026-05-29 10:${String(i).padStart(2, '0')}:30` });
+ }
+
+ const { status, body } = await request(app, '/api/analytics/by-platform?range=24h');
+ expect(status).toBe(200);
+
+ const a = body.find((r: any) => r.providerId === 'custom:https://relay-a.example.com/v1');
+ const b = body.find((r: any) => r.providerId === 'custom:https://relay-b.example.com/v1');
+ expect(a.p95LatencyMs).toBe(100);
+ expect(b.p95LatencyMs).toBe(1000);
+ });
+
+ it('keeps catalog providers on their bare platform id (no custom: prefix)', async () => {
+ insertRaw({ platform: 'groq', keyId: null, status: 'success', latencyMs: 100, createdAt: '2026-05-29 11:00: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.providerId).toBe('groq');
+ expect(groq.endpoint).toBe('groq');
+ });
+
+ it('falls back to the plain "custom" id when the key was deleted', async () => {
+ // A custom request whose key no longer exists: base_url is unknown, so
+ // the row keeps the pre-fix "custom" shape rather than a fake host.
+ insertRaw({ platform: 'custom', keyId: 99, status: 'success', latencyMs: 100, 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 === 'custom');
+ expect(row.providerId).toBe('custom');
+ expect(row.endpoint).toBe('custom');
+ });
+
+ it('filters recent calls by a custom endpoint providerId', async () => {
+ insertCustomKey(1, 'https://relay-a.example.com/v1', 'Relay A');
+ insertCustomKey(2, 'https://relay-b.example.com/v1', 'Relay B');
+
+ insertRaw({ platform: 'custom', keyId: 1, status: 'success', latencyMs: 100, createdAt: '2026-05-29 11:00:00' });
+ insertRaw({ platform: 'custom', keyId: 1, status: 'success', latencyMs: 120, createdAt: '2026-05-29 11:01:00' });
+ insertRaw({ platform: 'custom', keyId: 2, status: 'success', latencyMs: 900, createdAt: '2026-05-29 11:02:00' });
+
+ const a = await request(app, '/api/analytics/requests?range=24h&provider=' + encodeURIComponent('custom:https://relay-a.example.com/v1'));
+ expect(a.status).toBe(200);
+ expect(a.body.total).toBe(2);
+ expect(a.body.rows.every((r: any) => r.keyLabel === 'Relay A')).toBe(true);
+
+ const b = await request(app, '/api/analytics/requests?range=24h&provider=' + encodeURIComponent('custom:https://relay-b.example.com/v1'));
+ expect(b.status).toBe(200);
+ expect(b.body.total).toBe(1);
+ expect(b.body.rows[0].keyLabel).toBe('Relay B');
+ });
+
+ it('tells two endpoints on the same host apart', async () => {
+ // One gateway, two tenants. Host alone is the same string for both, so a
+ // host-only display name would show two identical rows the operator
+ // cannot match to an endpoint — the #889 collision one level down.
+ insertCustomKey(1, 'https://gw.example.com/tenant-a/v1', 'Tenant A');
+ insertCustomKey(2, 'https://gw.example.com/tenant-b/v1', 'Tenant B');
+
+ insertRaw({ platform: 'custom', keyId: 1, status: 'success', latencyMs: 100, createdAt: '2026-05-29 11:00:00' });
+ insertRaw({ platform: 'custom', keyId: 2, status: 'success', latencyMs: 200, createdAt: '2026-05-29 11:01:00' });
+
+ const { status, body } = await request(app, '/api/analytics/by-platform?range=24h');
+ expect(status).toBe(200);
+
+ const rows = body.filter((r: any) => r.platform === 'custom');
+ expect(rows).toHaveLength(2);
+ const names = rows.map((r: any) => r.endpoint).sort();
+ expect(names).toEqual(['gw.example.com/tenant-a/v1', 'gw.example.com/tenant-b/v1']);
+ // Distinct names, one per endpoint — not 'gw.example.com' twice.
+ expect(new Set(names).size).toBe(2);
+ });
+
+ it('groups an endpoint stored with and without a trailing slash as one row', async () => {
+ // keys.ts normalizes base_url on write, but rows written before it did
+ // carry the raw string. Same endpoint, so: one row, one id.
+ insertCustomKey(1, 'https://relay-a.example.com/v1', 'Relay A key 1');
+ insertCustomKey(2, 'https://relay-a.example.com/v1/', 'Relay A key 2');
+
+ insertRaw({ platform: 'custom', keyId: 1, status: 'success', latencyMs: 100, createdAt: '2026-05-29 11:00:00' });
+ insertRaw({ platform: 'custom', keyId: 2, status: 'success', latencyMs: 110, createdAt: '2026-05-29 11:01:00' });
+
+ const { status, body } = await request(app, '/api/analytics/by-platform?range=24h');
+ expect(status).toBe(200);
+
+ const rows = body.filter((r: any) => r.platform === 'custom');
+ expect(rows).toHaveLength(1);
+ expect(rows[0].providerId).toBe('custom:https://relay-a.example.com/v1');
+ expect(rows[0].requests).toBe(2);
+ });
+
+ it('names the endpoint behind each recent error', async () => {
+ insertCustomKey(1, 'https://relay-a.example.com/v1', 'Relay A');
+ insertCustomKey(2, 'https://relay-b.example.com/v1', 'Relay B');
+
+ insertRaw({ platform: 'custom', keyId: 1, status: 'error', error: 'relay A exploded', createdAt: '2026-05-29 11:00:00' });
+ insertRaw({ platform: 'custom', keyId: 2, status: 'error', error: 'relay B exploded', createdAt: '2026-05-29 11:01:00' });
+ insertRaw({ platform: 'groq', keyId: null, status: 'error', error: 'groq exploded', createdAt: '2026-05-29 11:02:00' });
+
+ const { status, body } = await request(app, '/api/analytics/errors?range=24h');
+ expect(status).toBe(200);
+
+ const a = body.find((r: any) => r.error === 'relay A exploded');
+ const b = body.find((r: any) => r.error === 'relay B exploded');
+ const groq = body.find((r: any) => r.error === 'groq exploded');
+ // Each error says WHICH relay failed instead of a bare 'custom'.
+ expect(a.providerId).toBe('custom:https://relay-a.example.com/v1');
+ expect(a.endpoint).toBe('relay-a.example.com');
+ expect(b.providerId).toBe('custom:https://relay-b.example.com/v1');
+ expect(b.endpoint).toBe('relay-b.example.com');
+ // The platform slug is still there for the client's dot coloring.
+ expect(a.platform).toBe('custom');
+ // Catalog providers are untouched.
+ expect(groq.providerId).toBe('groq');
+ expect(groq.endpoint).toBe('groq');
+ // An orphaned custom error keeps the pre-fix shape.
+ insertRaw({ platform: 'custom', keyId: 99, status: 'error', error: 'orphan exploded', createdAt: '2026-05-29 11:03:00' });
+ const again = await request(app, '/api/analytics/errors?range=24h');
+ const orphan = again.body.find((r: any) => r.error === 'orphan exploded');
+ expect(orphan.providerId).toBe('custom');
+ expect(orphan.endpoint).toBe('custom');
+ });
+
+ it('splits one model id across the relays that served it', async () => {
+ // The same model name behind two relays is two different services with
+ // two different latencies; one merged 'custom' row describes neither.
+ insertCustomKey(1, 'https://relay-a.example.com/v1', 'Relay A');
+ insertCustomKey(2, 'https://relay-b.example.com/v1', 'Relay B');
+ insertScopedModel('shared-model', 'Shared (A)', 'https://relay-a.example.com/v1');
+ insertScopedModel('shared-model', 'Shared (B)', 'https://relay-b.example.com/v1');
+
+ insertRaw({ platform: 'custom', keyId: 1, modelId: 'shared-model', status: 'success', latencyMs: 100, createdAt: '2026-05-29 11:00:00' });
+ insertRaw({ platform: 'custom', keyId: 1, modelId: 'shared-model', status: 'success', latencyMs: 100, createdAt: '2026-05-29 11:01:00' });
+ insertRaw({ platform: 'custom', keyId: 2, modelId: 'shared-model', status: 'success', latencyMs: 900, createdAt: '2026-05-29 11:02:00' });
+
+ const { status, body } = await request(app, '/api/analytics/by-model?range=24h');
+ expect(status).toBe(200);
+
+ const rows = body.filter((r: any) => r.modelId === 'shared-model');
+ expect(rows).toHaveLength(2);
+
+ const a = rows.find((r: any) => r.providerId === 'custom:https://relay-a.example.com/v1');
+ const b = rows.find((r: any) => r.providerId === 'custom:https://relay-b.example.com/v1');
+ expect(a.requests).toBe(2);
+ expect(b.requests).toBe(1);
+ // Counts are per endpoint, not the fan-out of one endpoint's requests
+ // across every models row that shares the id.
+ expect(a.requests + b.requests).toBe(3);
+ expect(a.endpoint).toBe('relay-a.example.com');
+ expect(b.endpoint).toBe('relay-b.example.com');
+ // Each row's latency is its own endpoint's, not the pooled average.
+ expect(a.avgLatencyMs).toBe(100);
+ expect(b.avgLatencyMs).toBe(900);
+ // The display name comes from the model row of the serving endpoint.
+ expect(a.displayName).toBe('Shared (A)');
+ expect(b.displayName).toBe('Shared (B)');
+ });
+
+ it('keeps catalog models on one row per platform in by-model', async () => {
+ insertRaw({ platform: 'groq', keyId: null, modelId: 'llama-3.1-8b-instant', status: 'success', latencyMs: 50, createdAt: '2026-05-29 11:00:00' });
+ insertRaw({ platform: 'groq', keyId: null, modelId: 'llama-3.1-8b-instant', status: 'success', latencyMs: 70, createdAt: '2026-05-29 11:01:00' });
+
+ const { status, body } = await request(app, '/api/analytics/by-model?range=24h');
+ expect(status).toBe(200);
+
+ const rows = body.filter((r: any) => r.platform === 'groq');
+ expect(rows).toHaveLength(1);
+ expect(rows[0].requests).toBe(2);
+ expect(rows[0].providerId).toBe('groq');
+ expect(rows[0].endpoint).toBe('groq');
+ });
+
+ it('splits the error distribution per custom endpoint', async () => {
+ insertCustomKey(1, 'https://relay-a.example.com/v1', 'Relay A');
+ insertCustomKey(2, 'https://relay-b.example.com/v1', 'Relay B');
+
+ insertRaw({ platform: 'custom', keyId: 1, status: 'error', error: '429 rate limit', createdAt: '2026-05-29 11:00:00' });
+ insertRaw({ platform: 'custom', keyId: 1, status: 'error', error: '429 rate limit', createdAt: '2026-05-29 11:01:00' });
+ insertRaw({ platform: 'custom', keyId: 2, status: 'error', error: 'timeout', createdAt: '2026-05-29 11:02:00' });
+ insertRaw({ platform: 'custom', keyId: 1, status: 'success', createdAt: '2026-05-29 11:03:00' });
+
+ const { status, body } = await request(app, '/api/analytics/error-distribution?range=24h');
+ expect(status).toBe(200);
+
+ const custom = body.byPlatform.filter((r: any) => r.platform === 'custom');
+ // Two bars, one per relay — not one 'custom' bar of 3 that names no
+ // endpoint the operator could go and fix.
+ expect(custom).toHaveLength(2);
+ const a = custom.find((r: any) => r.providerId === 'custom:https://relay-a.example.com/v1');
+ const b = custom.find((r: any) => r.providerId === 'custom:https://relay-b.example.com/v1');
+ expect(a.count).toBe(2);
+ expect(a.endpoint).toBe('relay-a.example.com');
+ expect(b.count).toBe(1);
+ expect(b.endpoint).toBe('relay-b.example.com');
+ // Category totals are endpoint-agnostic and must not change shape.
+ expect(body.byCategory.find((c: any) => c.category === 'Rate Limited (429)').count).toBe(2);
+ });
+
+ it('filters recent calls by the bare "custom" id to the orphaned rows only', async () => {
+ // The bare id is what /by-platform emits for rows whose endpoint is
+ // unknown. Selecting it must return exactly the rows that row counted —
+ // not every relay's traffic, which would contradict the count clicked.
+ insertCustomKey(1, 'https://relay-a.example.com/v1', 'Relay A');
+
+ insertRaw({ platform: 'custom', keyId: 1, status: 'success', createdAt: '2026-05-29 11:00:00' });
+ insertRaw({ platform: 'custom', keyId: 1, status: 'success', createdAt: '2026-05-29 11:01:00' });
+ // Key deleted after the fact (dangling id) and a row that never had one.
+ insertRaw({ platform: 'custom', keyId: 99, status: 'success', createdAt: '2026-05-29 11:02:00' });
+ insertRaw({ platform: 'custom', keyId: null, status: 'success', createdAt: '2026-05-29 11:03:00' });
+
+ const platforms = await request(app, '/api/analytics/by-platform?range=24h');
+ const orphanRow = platforms.body.find((r: any) => r.providerId === 'custom');
+ expect(orphanRow.requests).toBe(2);
+
+ const filtered = await request(app, '/api/analytics/requests?range=24h&provider=custom');
+ expect(filtered.status).toBe(200);
+ // The list agrees with the row: 2, not all 4 custom requests.
+ expect(filtered.body.total).toBe(orphanRow.requests);
+ expect(filtered.body.rows.every((r: any) => r.keyLabel === null)).toBe(true);
+
+ // The named endpoint still filters to itself...
+ const relayA = await request(app, '/api/analytics/requests?range=24h&provider=' + encodeURIComponent('custom:https://relay-a.example.com/v1'));
+ expect(relayA.body.total).toBe(2);
+ // ...and the legacy platform param keeps its pre-#889 meaning: all of it.
+ const legacy = await request(app, '/api/analytics/requests?range=24h&platform=custom');
+ expect(legacy.body.total).toBe(4);
+ });
+
+ it('still accepts the legacy platform filter and rejects malformed provider ids', async () => {
+ insertCustomKey(1, 'https://relay-a.example.com/v1', 'Relay A');
+ insertRaw({ platform: 'custom', keyId: 1, status: 'success', createdAt: '2026-05-29 11:00:00' });
+ insertRaw({ platform: 'groq', keyId: null, status: 'success', createdAt: '2026-05-29 11:01:00' });
+
+ // Legacy platform filter still works.
+ const legacy = await request(app, '/api/analytics/requests?range=24h&platform=groq');
+ expect(legacy.status).toBe(200);
+ expect(legacy.body.total).toBe(1);
+
+ // A 'custom:' id carries an arbitrary base_url, but it is applied as a
+ // BOUND parameter (never interpolated), so a hostile-looking value is
+ // safe — it simply matches nothing.
+ const customNoMatch = await request(app, '/api/analytics/requests?range=24h&provider=' + encodeURIComponent('custom:https://relay-a.example.com/v1; DROP TABLE requests'));
+ expect(customNoMatch.status).toBe(200);
+ expect(customNoMatch.body.total).toBe(0);
+
+ // Non-custom ids must be short slugs; anything else is a client bug.
+ for (const bad of ['has spaces', 'a\nb']) {
+ const res = await request(app, '/api/analytics/requests?range=24h&provider=' + encodeURIComponent(bad));
+ expect(res.status).toBe(400);
+ }
+ });
+ });
});
diff --git a/server/src/lib/provider-identity.ts b/server/src/lib/provider-identity.ts
new file mode 100644
index 00000000..977f857a
--- /dev/null
+++ b/server/src/lib/provider-identity.ts
@@ -0,0 +1,107 @@
+// ── Provider identity for analytics ─────────────────────────────────────────
+// Every custom OpenAI-compatible endpoint shares the platform id 'custom'
+// (see services/custom-endpoint.ts), so any analytics view that groups by
+// `platform` alone collapses every custom relay into a single "custom" row and
+// the operator can no longer tell which endpoint did what (#889).
+//
+// The canonical identity of a custom endpoint is the serving key's `base_url`
+// — custom-endpoint.ts already groups its credential pool by base_url, and the
+// router treats every key sharing a base_url as the same endpoint. Grouping by
+// base_url therefore splits one endpoint's pooled keys back into a single row
+// while keeping distinct endpoints apart.
+//
+// These helpers produce the stable id + display name the analytics endpoints
+// attach to each row. They are pure so they can be unit-tested without a DB —
+// module-purity.test.ts enforces that, which is also why they do not import
+// endpoint-scope.ts to normalize their input. The base_url they are handed is
+// expected to ALREADY be the normalized endpoint identity: keys.ts stores it
+// through normalizeBaseUrl(), and routes/analytics.ts re-applies the same
+// trailing-slash normalization in SQL for rows written before it did. That
+// keeps one definition of "same endpoint" (lib/endpoint-scope.ts) instead of a
+// second one hidden in here.
+
+/**
+ * The host (and port) of a custom endpoint's base_url — the short identifier
+ * that actually tells two endpoints apart. Mirrors the default label
+ * convention in services/custom-endpoint.ts (`new URL(baseUrl).host`) but
+ * returns null instead of a literal when the URL is unparseable, so callers
+ * can fall back to the generic 'custom' id rather than a fake host.
+ */
+export function endpointHost(baseUrl: string | null | undefined): string | null {
+ if (!baseUrl) return null;
+ try {
+ return new URL(baseUrl).host || null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The stable provider id for an analytics row. Non-custom platforms keep their
+ * bare slug ('groq', 'openai', …) so existing filters and the platform dot
+ * coloring are untouched. Custom endpoints get 'custom:<base_url>' so two
+ * relays never collide; a custom request whose key is gone (or never had a
+ * base_url) falls back to the plain 'custom' id, preserving the pre-fix shape.
+ */
+export function providerIdFor(platform: string, baseUrl: string | null | undefined): string {
+ if (platform !== 'custom') return platform;
+ // The base_url IS the endpoint-scope token of #651 (see the header), so this
+ // id agrees with `models.endpoint_scope` and with the router's view of which
+ // keys are one endpoint.
+ return baseUrl ? `custom:${baseUrl}` : 'custom';
+}
+
+/**
+ * The part of a base_url's path that carries identity of its own — '' when the
+ * path says nothing a second endpoint on the same host would not also say.
+ *
+ * The root ('/') and a lone API-version segment ('/v1', '/v1beta', '/v2') are
+ * trivial: every relay repeats them, so including them would only add noise to
+ * the common one-endpoint-per-host case. Anything else — a tenant, a project,
+ * a mount point — is exactly what tells two endpoints on one host apart, so it
+ * is kept VERBATIM, version suffix included. Trimming the '/v1' off a kept
+ * path would make '…/tenant-a' and '…/tenant-a/v1' display the same, which is
+ * the collision this exists to prevent.
+ */
+function endpointPathLabel(baseUrl: string): string {
+ let path: string;
+ try {
+ path = new URL(baseUrl).pathname.replace(/\/+$/, '');
+ } catch {
+ return '';
+ }
+ if (!path) return '';
+ const segments = path.slice(1).split('/');
+ if (segments.length === 1 && /^v\d+[a-z0-9._-]*$/i.test(segments[0])) return '';
+ return path;
+}
+
+/**
+ * The display name for an analytics row: the platform slug for catalog
+ * providers, and for a custom row the endpoint host plus any non-trivial path.
+ *
+ * Host alone is not an identity: a single gateway commonly fronts several
+ * endpoints ('https://gw.example.com/tenant-a/v1' and '…/tenant-b/v1'), and
+ * naming both of them 'gw.example.com' re-creates the #889 collision one level
+ * down — two rows the operator cannot tell apart. Appending the path makes the
+ * name injective on (host, path), while a bare '…/v1' endpoint still reads as
+ * the plain host it is.
+ *
+ * Derived purely from this row's base_url, like endpoint-scope's handles: the
+ * name never changes because some OTHER endpoint appeared or was deleted, so
+ * every view (by-platform, by-model, errors) agrees on what to call an
+ * endpoint even when they see different subsets of them.
+ *
+ * A null/unparseable base_url falls back to the platform, so there is always
+ * something to render.
+ */
+export function providerDisplayName(
+ platform: string,
+ baseUrl: string | null | undefined,
+): string {
+ if (platform !== 'custom') return platform;
+ if (!baseUrl) return platform;
+ const host = endpointHost(baseUrl);
+ if (!host) return platform;
+ return host + endpointPathLabel(baseUrl);
+}
diff --git a/server/src/routes/analytics.ts b/server/src/routes/analytics.ts
index 249a1c87..0d3c20b2 100644
--- a/server/src/routes/analytics.ts
+++ b/server/src/routes/analytics.ts
@@ -2,9 +2,24 @@ import { Router } from 'express';
import type { Request, Response } from 'express';
import { getDb } from '../db/index.js';
import { FALLBACK_INPUT_PER_M, FALLBACK_OUTPUT_PER_M } from '../db/model-pricing.js';
+import { providerIdFor, providerDisplayName } from '../lib/provider-identity.js';
+import { normalizeBaseUrl } from '../lib/endpoint-scope.js';
export const analyticsRouter = Router();
+// The endpoint identity of a request, in SQL: the serving key's base_url, ''
+// when the key is gone or carries none (every catalog key). Custom endpoints
+// all share the platform id 'custom' (services/custom-endpoint.ts), so any
+// view that groups by `platform` alone collapses every relay into one row and
+// the operator cannot tell which endpoint did what (#889) — this expression is
+// the second half of the grouping key everywhere that matters.
+//
+// rtrim/trim mirror lib/endpoint-scope.normalizeBaseUrl so the SQL side agrees
+// with the ids providerIdFor() builds: keys.ts normalizes base_url on write,
+// but rows stored before it did would otherwise split one endpoint in two.
+// Requires the query to LEFT JOIN api_keys as `k`.
+const ENDPOINT_ID_SQL = "COALESCE(rtrim(trim(k.base_url), '/'), '')";
+
// Format UTC timestamps the same way SQLite stores created_at text values.
const toSqliteDateTime = (timestamp: number) =>
new Date(timestamp).toISOString().slice(0, 19).replace('T', ' ');
@@ -195,7 +210,20 @@ analyticsRouter.get('/summary', (req: Request, res: Response) => {
});
});
-// Stats grouped by model
+// Stats grouped by model.
+//
+// The grouping key is (platform, endpoint, model_id), not (platform, model_id):
+// the same model id served by two different custom relays is two different
+// things — different latency, different failure modes — and merging them into
+// one row labelled "custom" is the #889 collision in its most misleading form,
+// because the merged row's numbers describe neither endpoint.
+//
+// The models join is endpoint-scoped for the same reason. `models` is unique on
+// (platform, model_id, endpoint_scope) since #651, so joining on
+// (platform, model_id) alone matches ONE row per relay that registered the
+// model and multiplies every request row by that count. Adding endpoint_scope
+// to the ON clause picks the row belonging to the endpoint that actually served
+// the request — the only one whose display name and pricing apply.
analyticsRouter.get('/by-model', (req: Request, res: Response) => {
const range = (req.query.range as string) ?? '7d';
const since = getSinceTimestamp(range);
@@ -204,6 +232,7 @@ analyticsRouter.get('/by-model', (req: Request, res: Response) => {
const rows = db.prepare(`
SELECT
r.platform,
+ ${ENDPOINT_ID_SQL} as base_url,
r.model_id,
m.display_name,
COUNT(*) as requests,
@@ -218,14 +247,21 @@ analyticsRouter.get('/by-model', (req: Request, res: Response) => {
r.output_tokens * COALESCE(m.paid_output_per_m, ?) / 1000000.0
ELSE 0 END) as est_cost
FROM requests r
- LEFT JOIN models m ON m.platform = r.platform AND m.model_id = r.model_id
+ LEFT JOIN api_keys k ON k.id = r.key_id
+ LEFT JOIN models m
+ ON m.platform = r.platform AND m.model_id = r.model_id
+ AND m.endpoint_scope = ${ENDPOINT_ID_SQL}
WHERE r.created_at >= ?
- GROUP BY r.platform, r.model_id
+ GROUP BY r.platform, ${ENDPOINT_ID_SQL}, r.model_id
ORDER BY requests DESC
`).all(FALLBACK_INPUT_PER_M, FALLBACK_OUTPUT_PER_M, since) as any[];
res.json(rows.map(r => ({
platform: r.platform,
+ // Same row identity as /by-platform, so a model row and a provider row for
+ // one endpoint carry the same id and the same operator-readable name.
+ providerId: providerIdFor(r.platform, r.base_url || null),
+ endpoint: providerDisplayName(r.platform, r.base_url || null),
modelId: r.model_id,
displayName: r.display_name ?? r.model_id,
requests: r.requests,
@@ -240,7 +276,16 @@ analyticsRouter.get('/by-model', (req: Request, res: Response) => {
})));
});
-// Stats grouped by platform
+// Stats grouped by platform.
+//
+// Custom endpoints all share the platform id 'custom' (services/custom-
+// endpoint.ts), so grouping by `platform` alone would collapse every custom
+// relay into one row and the operator could not tell which endpoint did what
+// (#889). We therefore also group by the serving key's base_url — the canonical
+// endpoint identity (custom-endpoint.ts pools credentials by base_url, and the
+// router treats every key sharing a base_url as one endpoint). Non-custom keys
+// carry no base_url, so COALESCE(base_url,'') keeps each of them in a single
+// per-platform group exactly as before.
analyticsRouter.get('/by-platform', (req: Request, res: Response) => {
const range = (req.query.range as string) ?? '7d';
const since = getSinceTimestamp(range);
@@ -248,31 +293,37 @@ analyticsRouter.get('/by-platform', (req: Request, res: Response) => {
const rows = db.prepare(`
SELECT
- platform,
+ r.platform,
+ ${ENDPOINT_ID_SQL} as base_url,
COUNT(*) as requests,
- COUNT(latency_ms) as latency_count,
- SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) * 100.0 / NULLIF(SUM(CASE WHEN status <> 'canceled' THEN 1 ELSE 0 END), 0) 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_tokens
- FROM requests
- WHERE created_at >= ?
- GROUP BY platform
+ COUNT(r.latency_ms) as latency_count,
+ SUM(CASE WHEN r.status = 'success' THEN 1 ELSE 0 END) * 100.0 / NULLIF(SUM(CASE WHEN r.status <> 'canceled' THEN 1 ELSE 0 END), 0) as success_rate,
+ AVG(r.latency_ms) as avg_latency_ms,
+ AVG(r.ttfb_ms) as avg_ttfb_ms,
+ SUM(CASE WHEN r.status = 'error' THEN 1 ELSE 0 END) as error_count,
+ AVG(CASE WHEN r.output_tokens > 0 AND r.latency_ms > 0
+ THEN r.output_tokens / (r.latency_ms / 1000.0) ELSE NULL END) as avg_tokens_per_second,
+ 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.created_at >= ?
+ GROUP BY r.platform, ${ENDPOINT_ID_SQL}
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.
+ // aggregate, so we take the nearest-rank value per group with a small
+ // ORDER BY/OFFSET query. The group count is tiny (one row per provider /
+ // custom endpoint), so the extra round-trips are negligible and keep the SQL
+ // readable. The WHERE must match the grouping exactly — platform AND the
+ // endpoint's base_url — or a custom endpoint's p95 would bleed in latency
+ // from every other custom endpoint.
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
+ SELECT r.latency_ms FROM requests r
+ LEFT JOIN api_keys k ON k.id = r.key_id
+ WHERE r.created_at >= ? AND r.platform = ? AND ${ENDPOINT_ID_SQL} = ? AND r.latency_ms IS NOT NULL
+ ORDER BY r.latency_ms ASC
LIMIT 1 OFFSET ?
`);
@@ -281,11 +332,20 @@ analyticsRouter.get('/by-platform', (req: Request, res: Response) => {
// 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 baseUrl: string | null = r.base_url || null;
const p95Row = latencyCount > 0
- ? (p95Stmt.get(since, r.platform, Math.floor((latencyCount - 1) * 0.95)) as { latency_ms: number } | undefined)
+ ? (p95Stmt.get(since, r.platform, r.base_url, Math.floor((latencyCount - 1) * 0.95)) as { latency_ms: number } | undefined)
: undefined;
return {
platform: r.platform,
+ // Stable, unique id for this row: the platform slug for catalog providers,
+ // 'custom:<base_url>' for custom endpoints (falls back to 'custom' when
+ // the key is gone). The client uses this as the chart key and the
+ // recent-calls filter value.
+ providerId: providerIdFor(r.platform, baseUrl),
+ // The short identifier the operator actually reads: the endpoint host for
+ // custom rows, the platform slug otherwise.
+ endpoint: providerDisplayName(r.platform, baseUrl),
requests: r.requests,
successRate: Math.round((r.success_rate ?? 0) * 10) / 10,
avgLatencyMs: Math.round(r.avg_latency_ms),
@@ -465,15 +525,30 @@ analyticsRouter.get('/error-distribution', (req: Request, res: Response) => {
ORDER BY count DESC
`).all(since) as any[];
- // Errors by platform
- const byPlatform = db.prepare(`
- SELECT platform, COUNT(*) as count
- FROM requests
- WHERE status = 'error' AND created_at >= ?
- GROUP BY platform
+ // Errors by provider. Endpoint-scoped like /by-platform: one bar per custom
+ // relay, not one bar pooling every relay's failures under "custom" (#889) —
+ // a bar the operator cannot act on, because it never says which endpoint is
+ // the one failing.
+ const byPlatformRows = db.prepare(`
+ SELECT r.platform, ${ENDPOINT_ID_SQL} as base_url, COUNT(*) as count
+ FROM requests r
+ LEFT JOIN api_keys k ON k.id = r.key_id
+ WHERE r.status = 'error' AND r.created_at >= ?
+ GROUP BY r.platform, ${ENDPOINT_ID_SQL}
ORDER BY count DESC
`).all(since) as any[];
+ const byPlatform = byPlatformRows.map(r => {
+ const baseUrl: string | null = r.base_url || null;
+ return {
+ // `platform` stays the raw slug: it is what the chart colors by.
+ platform: r.platform,
+ providerId: providerIdFor(r.platform, baseUrl),
+ endpoint: providerDisplayName(r.platform, baseUrl),
+ count: r.count,
+ };
+ });
+
res.json({
byCategory,
byPlatform,
@@ -487,22 +562,32 @@ analyticsRouter.get('/errors', (req: Request, res: Response) => {
const since = getSinceTimestamp(range);
const db = getDb();
+ // Joined to the serving key so each error names the endpoint it came from.
+ // Without it every custom relay's failures read as a bare "custom" in the
+ // panel (#889) and the operator has to guess which one broke.
const rows = db.prepare(`
- SELECT id, platform, model_id, error, latency_ms, created_at
- FROM requests
- WHERE status = 'error' AND created_at >= ?
- ORDER BY created_at DESC
+ SELECT r.id, r.platform, ${ENDPOINT_ID_SQL} as base_url, r.model_id, r.error,
+ r.latency_ms, r.created_at
+ FROM requests r
+ LEFT JOIN api_keys k ON k.id = r.key_id
+ WHERE r.status = 'error' AND r.created_at >= ?
+ ORDER BY r.created_at DESC
LIMIT 50
`).all(since) as any[];
- res.json(rows.map(r => ({
- id: r.id,
- platform: r.platform,
- modelId: r.model_id,
- error: r.error,
- latencyMs: r.latency_ms,
- createdAt: r.created_at,
- })));
+ res.json(rows.map(r => {
+ const baseUrl: string | null = r.base_url || null;
+ return {
+ id: r.id,
+ platform: r.platform,
+ providerId: providerIdFor(r.platform, baseUrl),
+ endpoint: providerDisplayName(r.platform, baseUrl),
+ modelId: r.model_id,
+ error: r.error,
+ latencyMs: r.latency_ms,
+ createdAt: r.created_at,
+ };
+ }));
});
// Recent calls — one row per proxied request, newest first, with the caller's
@@ -515,32 +600,74 @@ analyticsRouter.get('/requests', (req: Request, res: Response) => {
const limit = Math.min(Math.max(parseInt(req.query.limit as string, 10) || 100, 1), 500);
const offset = Math.max(parseInt(req.query.offset as string, 10) || 0, 0);
- // Optional filters. Both are validated (whitelist / shape) and applied as
+ // Optional filters. All are validated (whitelist / shape) and applied as
// bound parameters; absent filters keep the default behavior identical.
const status = req.query.status as string | undefined;
if (status !== undefined && status !== 'success' && status !== 'error' && status !== 'canceled') {
res.status(400).json({ error: "invalid status filter (expected 'success', 'error' or 'canceled')" });
return;
}
- // Platform ids are short slugs ('groq', 'pt-custom_1'); anything else is a
- // client bug, not a filter.
+ // Provider filter. The `provider` param carries the stable row id returned by
+ // /by-platform: a platform slug ('groq') or 'custom:<base_url>' for a custom
+ // endpoint (#889 — every custom relay shares the 'custom' platform id, so the
+ // endpoint's base_url is what actually selects one). The legacy `platform`
+ // param still works for old clients. Both are bound parameters, never
+ // interpolated, so the only validation needed is shape.
+ const provider = req.query.provider as string | undefined;
const platform = req.query.platform as string | undefined;
- if (platform !== undefined && !/^[A-Za-z0-9_-]{1,64}$/.test(platform)) {
- res.status(400).json({ error: 'invalid platform filter' });
- return;
+ let providerFilterSql = '';
+ const providerFilterParams: string[] = [];
+ if (provider !== undefined) {
+ if (provider.length > 256 || /[\r\n]/.test(provider)) {
+ res.status(400).json({ error: 'invalid provider filter' });
+ return;
+ }
+ if (provider === 'custom') {
+ // The BARE 'custom' id is the orphan bucket, not "all custom traffic":
+ // /by-platform emits it only for rows whose endpoint is unknown (the key
+ // was deleted, or never carried a base_url). Falling through to the slug
+ // branch below would filter on `platform = 'custom'` and return every
+ // relay's traffic — a list that contradicts the very row the user
+ // clicked, which counted the orphans alone. Match what that row counted.
+ providerFilterSql = ` AND r.platform = 'custom' AND ${ENDPOINT_ID_SQL} = ''`;
+ } else if (provider.startsWith('custom:')) {
+ // Select one custom endpoint by its base_url. Normalized on the way in
+ // for the same reason ENDPOINT_ID_SQL normalizes on the way out.
+ providerFilterSql = ` AND r.platform = 'custom' AND ${ENDPOINT_ID_SQL} = ?`;
+ providerFilterParams.push(normalizeBaseUrl(provider.slice('custom:'.length)));
+ } else if (/^[A-Za-z0-9_-]{1,64}$/.test(provider)) {
+ providerFilterSql = ' AND r.platform = ?';
+ providerFilterParams.push(provider);
+ } else {
+ res.status(400).json({ error: 'invalid provider filter' });
+ return;
+ }
+ } else if (platform !== undefined) {
+ // The legacy param keeps its pre-#889 meaning: `platform=custom` is every
+ // custom relay's traffic. Only the `provider` ids are endpoint-scoped.
+ // Platform ids are short slugs ('groq', 'pt-custom_1'); anything else is a
+ // client bug, not a filter.
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(platform)) {
+ res.status(400).json({ error: 'invalid platform filter' });
+ return;
+ }
+ providerFilterSql = ' AND r.platform = ?';
+ providerFilterParams.push(platform);
}
const db = getDb();
const filterSql =
(status !== undefined ? ' AND r.status = ?' : '') +
- (platform !== undefined ? ' AND r.platform = ?' : '');
+ providerFilterSql;
const filterParams = [
...(status !== undefined ? [status] : []),
- ...(platform !== undefined ? [platform] : []),
+ ...providerFilterParams,
];
const total = (db.prepare(
- `SELECT COUNT(*) as c FROM requests r WHERE r.created_at >= ?${filterSql}`
+ `SELECT COUNT(*) as c FROM requests r
+ LEFT JOIN api_keys k ON k.id = r.key_id
+ WHERE r.created_at >= ?${filterSql}`
).get(since, ...filterParams) as { c: number }).c;
const rows = db.prepare(`