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
feat: manage custom models from keys page (#327)
phoenix441dc92a1c16
diff --git a/client/src/pages/KeysPage.tsx b/client/src/pages/KeysPage.tsxindex a994bb25..e60c009c 100644--- a/client/src/pages/KeysPage.tsx+++ b/client/src/pages/KeysPage.tsx@@ -8,8 +8,8 @@ import { Label } from '@/components/ui/label'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, Platform, ProviderQuotaState } from '../../../shared/types'-import { Pencil, ExternalLink, Globe } from 'lucide-react'+import type { ApiKey, ApiKeyModel, Platform, ProviderQuotaState } from '../../../shared/types'+import { ChevronDown, Pencil, ExternalLink, Globe, Trash2 } from 'lucide-react'import { formatSqliteUtcToLocalTime } from '@/lib/utils'import { useI18n } from '@/i18n'@@ -83,6 +83,23 @@ const CUSTOM_GROUP: { value: Platform; label: string; url: string } = {url: '',}+const CUSTOM_MODEL_KIND_LABEL: Record<ApiKeyModel['kind'], string> = {+ chat: 'keys.customTypeChat',+ embedding: 'keys.customTypeEmbedding',+ image: 'keys.customTypeImage',+ audio: 'keys.customTypeAudio',+}++function customModelDeleteKey(model: ApiKeyModel): string {+ return `${model.kind}:${model.id}`+}++function customModelDeletePath(model: ApiKeyModel): string {+ if (model.kind === 'chat') return `/api/models/custom/${model.id}`+ if (model.kind === 'embedding') return `/api/embeddings/custom/${model.id}`+ return `/api/media/custom/${model.id}`+}+const statusDot: Record<string, string> = {healthy: 'bg-emerald-500',rate_limited: 'bg-amber-500',@@ -615,6 +632,8 @@ export default function KeysPage() {const [editingKeyId, setEditingKeyId] = useState<number | null>(null)const [editingLabel, setEditingLabel] = useState('')const [confirmDeleteId, setConfirmDeleteId] = useState<number | null>(null)+ const [confirmDeleteModelKey, setConfirmDeleteModelKey] = useState<string | null>(null)+ const [expandedKeyIds, setExpandedKeyIds] = useState<Set<number>>(new Set())const editInputRef = useRef<HTMLInputElement>(null)const { data: keys = [], isLoading } = useQuery<ApiKey[]>({@@ -650,6 +669,18 @@ export default function KeysPage() {},})+ 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: () => {@@ -708,6 +739,15 @@ export default function KeysPage() {}}+ 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()@@ -912,60 +952,124 @@ export default function KeysPage() {const status = h?.status ?? k.statusconst lastChecked = h?.lastCheckedAtconst 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="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}`} />- <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()+ <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)}>+ <Pencil className="size-3" />+ </Button>+ )}+ <Button variant="ghost" size="xs" onClick={() => checkKey.mutate(k.id)} disabled={checkKey.isPending}>+ {t('common.check')}+ </Button>+ <Button+ variant="ghost"+ size="xs"+ className={confirmDeleteId === k.id ? 'text-destructive' : 'text-muted-foreground hover:text-destructive'}+ onClick={() => {+ if (confirmDeleteId === k.id) {+ deleteKey.mutate(k.id)+ setConfirmDeleteId(null)+ } else {+ setConfirmDeleteId(k.id)+ setTimeout(() => setConfirmDeleteId(c => (c === k.id ? null : c)), 3000)+ }}}- 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>}- </>- )}- <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)}>- <Pencil className="size-3" />+ disabled={deleteKey.isPending}+ >+ {confirmDeleteId === k.id ? t('keys.confirmRemove') : t('common.remove')}</Button>+ </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)+ const confirming = confirmDeleteModelKey === modelKey+ 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>+ )}+ <Button+ type="button"+ variant="ghost"+ size="xs"+ className={`h-5 px-1 ${confirming ? 'text-destructive' : 'text-muted-foreground hover:text-destructive'}`}+ disabled={deleteCustomModel.isPending}+ onClick={() => {+ if (confirming) {+ deleteCustomModel.mutate(model)+ setConfirmDeleteModelKey(null)+ } else {+ setConfirmDeleteModelKey(modelKey)+ setTimeout(() => setConfirmDeleteModelKey(c => (c === modelKey ? null : c)), 3000)+ }+ }}+ title={t('common.remove')}+ >+ {confirming ? t('common.confirm') : <Trash2 className="size-3" />}+ </Button>+ </div>+ )+ })}+ </div>)}- <Button variant="ghost" size="xs" onClick={() => checkKey.mutate(k.id)} disabled={checkKey.isPending}>- {t('common.check')}- </Button>- <Button- variant="ghost"- size="xs"- className={confirmDeleteId === k.id ? 'text-destructive' : 'text-muted-foreground hover:text-destructive'}- onClick={() => {- if (confirmDeleteId === k.id) {- deleteKey.mutate(k.id)- setConfirmDeleteId(null)- } else {- setConfirmDeleteId(k.id)- setTimeout(() => setConfirmDeleteId(c => (c === k.id ? null : c)), 3000)- }- }}- disabled={deleteKey.isPending}- >- {confirmDeleteId === k.id ? t('keys.confirmRemove') : t('common.remove')}- </Button></div>)})}diff --git a/server/src/__tests__/routes/custom-modalities.test.ts b/server/src/__tests__/routes/custom-modalities.test.tsindex d3acca71..849615f3 100644--- a/server/src/__tests__/routes/custom-modalities.test.ts+++ b/server/src/__tests__/routes/custom-modalities.test.ts@@ -25,6 +25,17 @@ async function post(app: Express, path: string, body: unknown) {return { status: res.status, body: data };}+async function get(app: Express, path: string) {+ const server = app.listen(0);+ const addr = server.address() as any;+ const res = await realFetch(`http://127.0.0.1:${addr.port}${path}`, {+ headers: isGatedApiPath(path) ? { Authorization: `Bearer ${dashToken}` } : {},+ });+ const data = await res.json().catch(() => null);+ server.close();+ return { status: res.status, body: data };+}+async function del(app: Express, path: string) {const server = app.listen(0);const addr = server.address() as any;@@ -145,6 +156,87 @@ describe('custom provider modalities', () => {]);});+ it('lists chat, embedding, image, and audio models under their custom endpoint key', async () => {+ const fetchMock = vi.fn(async () => embeddingResponse(3));+ globalThis.fetch = fetchMock as any;++ const chat = await post(app, '/api/keys/custom', {+ baseUrl: 'http://127.0.0.1:8585/v1',+ model: 'local-chat',+ displayName: 'Local Chat',+ apiKey: 'endpoint-secret',+ label: 'Local endpoint',+ });+ expect(chat.status).toBe(201);+ expect((await post(app, '/api/embeddings/custom', {+ baseUrl: 'http://127.0.0.1:8585/v1',+ model: 'local-embed',+ family: 'local-list-family',+ displayName: 'Local Embed',+ })).status).toBe(201);+ expect((await post(app, '/api/media/custom', {+ baseUrl: 'http://127.0.0.1:8585/v1',+ model: 'local-image',+ modality: 'image',+ displayName: 'Local Image',+ })).status).toBe(201);+ expect((await post(app, '/api/media/custom', {+ baseUrl: 'http://127.0.0.1:8585/v1',+ model: 'local-audio',+ modality: 'audio',+ displayName: 'Local Audio',+ })).status).toBe(201);++ const keys = await get(app, '/api/keys');+ expect(keys.status).toBe(200);+ const custom = keys.body.find((k: any) => k.platform === 'custom' && k.baseUrl === 'http://127.0.0.1:8585/v1');+ expect(custom.label).toBe('Local endpoint');+ expect(custom.models.map((m: any) => `${m.kind}:${m.modelId}`).sort()).toEqual([+ 'audio:local-audio',+ 'chat:local-chat',+ 'embedding:local-embed',+ 'image:local-image',+ ]);+ expect(custom.models.find((m: any) => m.kind === 'embedding').family).toBe('local-list-family');+ });++ it('deletes individual custom models and removes the endpoint key only when none remain', async () => {+ const fetchMock = vi.fn(async () => embeddingResponse(3));+ globalThis.fetch = fetchMock as any;++ expect((await post(app, '/api/keys/custom', {+ baseUrl: 'http://127.0.0.1:8686/v1',+ model: 'local-chat',+ apiKey: 'endpoint-secret',+ })).status).toBe(201);+ expect((await post(app, '/api/embeddings/custom', {+ baseUrl: 'http://127.0.0.1:8686/v1',+ model: 'local-embed',+ family: 'local-delete-list-family',+ })).status).toBe(201);+ expect((await post(app, '/api/media/custom', {+ baseUrl: 'http://127.0.0.1:8686/v1',+ model: 'local-image',+ modality: 'image',+ })).status).toBe(201);++ const before = await get(app, '/api/keys');+ const key = before.body.find((k: any) => k.platform === 'custom' && k.baseUrl === 'http://127.0.0.1:8686/v1');+ const chat = key.models.find((m: any) => m.kind === 'chat');+ const embedding = key.models.find((m: any) => m.kind === 'embedding');+ const image = key.models.find((m: any) => m.kind === 'image');++ expect((await del(app, `/api/models/custom/${chat.id}`)).status).toBe(200);+ const afterChatDelete = await get(app, '/api/keys');+ const stillPresent = afterChatDelete.body.find((k: any) => k.id === key.id);+ expect(stillPresent.models.map((m: any) => m.kind).sort()).toEqual(['embedding', 'image']);++ expect((await del(app, `/api/embeddings/custom/${embedding.id}`)).status).toBe(200);+ expect((await del(app, `/api/media/custom/${image.id}`)).status).toBe(200);+ const afterAllDeleted = await get(app, '/api/keys');+ expect(afterAllDeleted.body.find((k: any) => k.id === key.id)).toBeUndefined();+ });+it('deleting a custom endpoint key removes bound embedding and media models', async () => {const fetchMock = vi.fn(async () => embeddingResponse(3));globalThis.fetch = fetchMock as any;diff --git a/server/src/lib/custom-provider-cleanup.ts b/server/src/lib/custom-provider-cleanup.tsnew file mode 100644index 00000000..bc772148--- /dev/null+++ b/server/src/lib/custom-provider-cleanup.ts@@ -0,0 +1,11 @@+import type Database from 'better-sqlite3';++export function deleteUnusedCustomEndpointKey(db: Database.Database, keyId: number | null | undefined) {+ if (keyId == null) return;+ const chat = db.prepare("SELECT COUNT(*) AS n FROM models WHERE platform = 'custom' AND key_id = ?").get(keyId) as { n: number };+ const embeddings = db.prepare("SELECT COUNT(*) AS n FROM embedding_models WHERE platform = 'custom' AND key_id = ?").get(keyId) as { n: number };+ const media = db.prepare("SELECT COUNT(*) AS n FROM media_models WHERE platform = 'custom' AND key_id = ?").get(keyId) as { n: number };+ if (chat.n + embeddings.n + media.n === 0) {+ db.prepare("DELETE FROM api_keys WHERE id = ? AND platform = 'custom'").run(keyId);+ }+}diff --git a/server/src/routes/embeddings.ts b/server/src/routes/embeddings.tsindex 8e37b08e..f9bad75d 100644--- a/server/src/routes/embeddings.ts+++ b/server/src/routes/embeddings.ts@@ -3,6 +3,7 @@ import type { Request, Response } from 'express';import { z } from 'zod';import { getDb, setSetting } from '../db/index.js';import { encrypt, decrypt, maskKey } from '../lib/crypto.js';+import { deleteUnusedCustomEndpointKey } from '../lib/custom-provider-cleanup.js';import {listEmbeddingModels,getDefaultFamily,@@ -265,13 +266,17 @@ embeddingsRouter.delete('/custom/:id', (req: Request, res: Response) => {}const db = getDb();- const row = db.prepare("SELECT family FROM embedding_models WHERE id = ? AND platform = 'custom'").get(id) as { family: string } | undefined;+ const row = db.prepare("SELECT family, key_id FROM embedding_models WHERE id = ? AND platform = 'custom'").get(id) as { family: string; key_id: number | null } | undefined;if (!row) {res.status(404).json({ error: { message: `Unknown custom embedding model ${id}` } });return;}- db.prepare("DELETE FROM embedding_models WHERE id = ? AND platform = 'custom'").run(id);+ const remove = db.transaction(() => {+ db.prepare("DELETE FROM embedding_models WHERE id = ? AND platform = 'custom'").run(id);+ deleteUnusedCustomEndpointKey(db, row.key_id);+ });+ remove();if (getDefaultFamily() === row.family) {const replacement = db.prepare('SELECT family FROM embedding_models ORDER BY family, priority LIMIT 1').get() as { family: string } | undefined;if (replacement) setSetting('embeddings_default_family', replacement.family);diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex 61370e6c..86fd8312 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -38,6 +38,45 @@ keysRouter.get('/', (_req: Request, res: Response) => {const db = getDb();const rows = db.prepare('SELECT * FROM api_keys ORDER BY created_at DESC').all() as any[];+ const customModels = [+ ...db.prepare(`+ SELECT key_id, id, 'chat' AS kind, model_id, display_name, NULL AS family+ FROM models+ WHERE platform = 'custom' AND key_id IS NOT NULL+ `).all() as any[],+ ...db.prepare(`+ SELECT key_id, id, 'embedding' AS kind, model_id, display_name, family+ FROM embedding_models+ WHERE platform = 'custom' AND key_id IS NOT NULL+ `).all() as any[],+ ...db.prepare(`+ SELECT key_id, id, modality AS kind, model_id, display_name, NULL AS family+ FROM media_models+ WHERE platform = 'custom' AND key_id IS NOT NULL+ `).all() as any[],+ ];+ const modelsByKeyId = new Map<number, any[]>();+ for (const m of customModels) {+ const keyId = Number(m.key_id);+ if (!Number.isInteger(keyId)) continue;+ const list = modelsByKeyId.get(keyId) ?? [];+ list.push({+ id: m.id,+ kind: m.kind,+ modelId: m.model_id,+ displayName: m.display_name,+ family: m.family ?? null,+ });+ modelsByKeyId.set(keyId, list);+ }+ for (const list of modelsByKeyId.values()) {+ list.sort((a, b) => {+ const ka = ['chat', 'embedding', 'image', 'audio'].indexOf(a.kind);+ const kb = ['chat', 'embedding', 'image', 'audio'].indexOf(b.kind);+ return (ka - kb) || String(a.displayName).localeCompare(String(b.displayName));+ });+ }+const keys = rows.map(row => {let maskedKey = '****';try {@@ -56,6 +95,7 @@ keysRouter.get('/', (_req: Request, res: Response) => {enabled: row.enabled === 1,createdAt: row.created_at,lastCheckedAt: row.last_checked_at,+ models: row.platform === 'custom' ? (modelsByKeyId.get(row.id) ?? []) : undefined,};});diff --git a/server/src/routes/media.ts b/server/src/routes/media.tsindex 7bff2889..b9e10e0c 100644--- a/server/src/routes/media.ts+++ b/server/src/routes/media.ts@@ -3,6 +3,7 @@ import type { Request, Response } from 'express';import { z } from 'zod';import { getDb } from '../db/index.js';import { encrypt, decrypt, maskKey } from '../lib/crypto.js';+import { deleteUnusedCustomEndpointKey } from '../lib/custom-provider-cleanup.js';import { listAllMediaModels } from '../services/media.js';export const mediaRouter = Router();@@ -189,10 +190,16 @@ mediaRouter.delete('/custom/:id', (req: Request, res: Response) => {return;}- const info = getDb().prepare("DELETE FROM media_models WHERE id = ? AND platform = 'custom'").run(id);- if (info.changes === 0) {+ const db = getDb();+ const row = db.prepare("SELECT key_id FROM media_models WHERE id = ? AND platform = 'custom'").get(id) as { key_id: number | null } | undefined;+ if (!row) {res.status(404).json({ error: { message: `Unknown custom media model ${id}` } });return;}+ const remove = db.transaction(() => {+ db.prepare("DELETE FROM media_models WHERE id = ? AND platform = 'custom'").run(id);+ deleteUnusedCustomEndpointKey(db, row.key_id);+ });+ remove();res.json({ success: true });});diff --git a/server/src/routes/models.ts b/server/src/routes/models.tsindex 2e9e3590..e92f7045 100644--- a/server/src/routes/models.ts+++ b/server/src/routes/models.ts@@ -2,6 +2,7 @@ import { Router } from 'express';import type { Request, Response } from 'express';import { getDb } from '../db/index.js';import { hasProvider } from '../providers/index.js';+import { deleteUnusedCustomEndpointKey } from '../lib/custom-provider-cleanup.js';export const modelsRouter = Router();@@ -13,7 +14,7 @@ modelsRouter.delete('/custom/:id', (req: Request, res: Response) => {}const db = getDb();- const row = db.prepare("SELECT id FROM models WHERE id = ? AND platform = 'custom'").get(id);+ const row = db.prepare("SELECT id, key_id FROM models WHERE id = ? AND platform = 'custom'").get(id) as { id: number; key_id: number | null } | undefined;if (!row) {res.status(404).json({ error: { message: `Unknown custom model ${id}` } });return;@@ -22,6 +23,7 @@ modelsRouter.delete('/custom/:id', (req: Request, res: Response) => {const remove = db.transaction(() => {db.prepare('DELETE FROM fallback_config WHERE model_db_id = ?').run(id);db.prepare("DELETE FROM models WHERE id = ? AND platform = 'custom'").run(id);+ deleteUnusedCustomEndpointKey(db, row.key_id);});remove();res.json({ success: true });diff --git a/shared/types.ts b/shared/types.tsindex 35ff3ffe..1c1e0579 100644--- a/shared/types.ts+++ b/shared/types.ts@@ -106,6 +106,14 @@ export interface ModelListRow {export type KeyStatus = 'healthy' | 'rate_limited' | 'invalid' | 'error' | 'unknown';+export interface ApiKeyModel {+ id: number;+ kind: 'chat' | 'embedding' | 'image' | 'audio';+ modelId: string;+ displayName: string;+ family?: string | null;+}+export interface ApiKey {id: number;platform: Platform;@@ -116,6 +124,7 @@ export interface ApiKey {enabled: boolean;createdAt: string;lastCheckedAt: string | null;+ models?: ApiKeyModel[];}export interface ApiKeyCreate {