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(keys): allow editing key labels after creation (#136)
Davy38fe1116f4fa
diff --git a/client/src/pages/KeysPage.tsx b/client/src/pages/KeysPage.tsxindex 43053cad..2358aa61 100644--- a/client/src/pages/KeysPage.tsx+++ b/client/src/pages/KeysPage.tsx@@ -1,4 +1,4 @@-import { useState } from 'react'+import { useState, useRef, useEffect } from 'react'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'import { apiFetch } from '@/lib/api'import { Button } from '@/components/ui/button'@@ -8,6 +8,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@import { Switch } from '@/components/ui/switch'import { PageHeader } from '@/components/page-header'import type { ApiKey, Platform } from '../../../shared/types'+import { Pencil } from 'lucide-react'const PLATFORMS: { value: Platform; label: string }[] = [{ value: 'google', label: 'Google AI Studio' },@@ -133,6 +134,9 @@ export default function KeysPage() {const [apiKey, setApiKey] = useState('')const [accountId, setAccountId] = useState('')const [label, setLabel] = useState('')+ const [editingKeyId, setEditingKeyId] = useState<number | null>(null)+ const [editingLabel, setEditingLabel] = useState('')+ const editInputRef = useRef<HTMLInputElement>(null)const { data: keys = [], isLoading } = useQuery<ApiKey[]>({queryKey: ['keys'],@@ -196,6 +200,41 @@ export default function KeysPage() {},})+ 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 })+ }+ }++ useEffect(() => {+ if (editingKeyId !== null && editInputRef.current) {+ editInputRef.current.focus()+ }+ }, [editingKeyId])+const needsAccountId = platform === 'cloudflare'const handleSubmit = (e: React.FormEvent) => {@@ -320,11 +359,29 @@ export default function KeysPage() {const h = healthKeyMap.get(k.id)const status = h?.status ?? k.statusconst lastChecked = h?.lastCheckedAt+ const isEditing = editingKeyId === k.idreturn (<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>- {k.label && <span className="text-xs text-muted-foreground">{k.label}</span>}+ {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>}+ </>+ )}<span className="text-xs text-muted-foreground">{statusLabel[status] ?? status}</span><div className="flex-1" />{lastChecked && (@@ -332,6 +389,11 @@ export default function KeysPage() {{new Date(lastChecked).toLocaleTimeString([], { 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}>Check</Button>diff --git a/server/src/__tests__/routes/keys.test.ts b/server/src/__tests__/routes/keys.test.tsindex 0dc9d055..dbcdfdbe 100644--- a/server/src/__tests__/routes/keys.test.ts+++ b/server/src/__tests__/routes/keys.test.ts@@ -97,4 +97,77 @@ describe('Keys API', () => {const { status } = await request(app, 'DELETE', '/api/keys/99999');expect(status).toBe(404);});++ it('PATCH /api/keys/:id updates label', async () => {+ const { body: created } = await request(app, 'POST', '/api/keys', {+ platform: 'groq',+ key: 'gsk_test123456789',+ });++ const { status, body } = await request(app, 'PATCH', `/api/keys/${created.id}`, {+ label: 'Production key',+ });++ expect(status).toBe(200);+ expect(body.success).toBe(true);+ expect(body.label).toBe('Production key');++ const { body: keys } = await request(app, 'GET', '/api/keys');+ expect(keys[0].label).toBe('Production key');+ });++ it('PATCH /api/keys/:id updates both enabled and label', async () => {+ const { body: created } = await request(app, 'POST', '/api/keys', {+ platform: 'groq',+ key: 'gsk_test123456789',+ });++ const { status, body } = await request(app, 'PATCH', `/api/keys/${created.id}`, {+ enabled: false,+ label: 'Disabled key',+ });++ expect(status).toBe(200);+ expect(body.success).toBe(true);+ expect(body.enabled).toBe(false);+ expect(body.label).toBe('Disabled key');++ const { body: keys } = await request(app, 'GET', '/api/keys');+ expect(keys[0].enabled).toBe(false);+ expect(keys[0].label).toBe('Disabled key');+ });++ it('PATCH /api/keys/:id clears label', async () => {+ const { body: created } = await request(app, 'POST', '/api/keys', {+ platform: 'groq',+ key: 'gsk_test123456789',+ label: 'Temporary label',+ });++ const { status, body } = await request(app, 'PATCH', `/api/keys/${created.id}`, {+ label: '',+ });++ expect(status).toBe(200);+ expect(body.success).toBe(true);+ expect(body.label).toBe('');++ const { body: keys } = await request(app, 'GET', '/api/keys');+ expect(keys[0].label).toBe('');+ });++ it('PATCH /api/keys/:id returns 400 when no fields provided', async () => {+ const { body: created } = await request(app, 'POST', '/api/keys', {+ platform: 'groq',+ key: 'gsk_test123456789',+ });++ const { status } = await request(app, 'PATCH', `/api/keys/${created.id}`, {});+ expect(status).toBe(400);+ });++ it('PATCH /api/keys/:id returns 404 for nonexistent key', async () => {+ const { status } = await request(app, 'PATCH', '/api/keys/99999', { label: 'test' });+ expect(status).toBe(404);+ });});diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex e5a92450..f7b1b9d2 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -21,6 +21,13 @@ const addKeySchema = z.object({label: z.string().optional(),});+const updateKeySchema = z.object({+ enabled: z.boolean().optional(),+ label: z.string().optional(),+}).refine(data => data.enabled !== undefined || data.label !== undefined, {+ message: 'At least one of enabled or label must be provided',+});+// List all keys (masked)keysRouter.get('/', (_req: Request, res: Response) => {const db = getDb();@@ -115,7 +122,7 @@ keysRouter.patch('/platform/:platform', (req: Request, res: Response) => {res.json({ success: true, enabled, updatedKeys: result.changes });});-// Toggle enable/disable+// Update key (toggle enable/disable or edit label)keysRouter.patch('/:id', (req: Request, res: Response) => {const id = parseInt(req.params.id as string, 10);if (isNaN(id)) {@@ -123,19 +130,37 @@ keysRouter.patch('/:id', (req: Request, res: Response) => {return;}- const { enabled } = req.body;- if (typeof enabled !== 'boolean') {- res.status(400).json({ error: { message: 'enabled must be a boolean' } });+ const parsed = updateKeySchema.safeParse(req.body);+ if (!parsed.success) {+ res.status(400).json({ error: { message: parsed.error.errors.map(e => e.message).join(', ') } });return;}+ const { enabled, label } = parsed.data;+ const updates: string[] = [];+ const values: (string | number)[] = [];++ if (enabled !== undefined) {+ updates.push('enabled = ?');+ values.push(enabled ? 1 : 0);+ }+ if (label !== undefined) {+ updates.push('label = ?');+ values.push(label);+ }++ values.push(id);+const db = getDb();- const result = db.prepare('UPDATE api_keys SET enabled = ? WHERE id = ?').run(enabled ? 1 : 0, id);+ const result = db.prepare(`UPDATE api_keys SET ${updates.join(', ')} WHERE id = ?`).run(...values);if (result.changes === 0) {res.status(404).json({ error: { message: 'Key not found' } });return;}- res.json({ success: true, enabled });+ const response: Record<string, unknown> = { success: true };+ if (enabled !== undefined) response.enabled = enabled;+ if (label !== undefined) response.label = label;+ res.json(response);});