Open History to see the last commit
1import { useState } from 'react'
2import { KeyRound, X } from 'lucide-react'
3import { useByok } from '@tanstack/ai-react'
4import { byok, KEYED_PROVIDERS, KEY_GROUPS } from '@/lib/byok'
5import type { KeyStatus } from '@tanstack/ai-client/byok'
6import type { ProviderId } from '@tanstack/ai/byok'
7import type { ReactNode } from 'react'
8
9export type ByokKeyDialogProps = {
10 open: boolean
11 onOpenChange: (open: boolean) => void
12 envStatus?: Record<string, boolean>
13 activeProvider?: ProviderId | null
14 highlightProvider?: ProviderId | null
15 openRouter?: {
16 onLogin: () => void
17 completing?: boolean
18 error?: string | null
19 }
20 trigger?: ReactNode
21 description?: string
22}
23
24const STATUS_LABEL: Record<
25 KeyStatus['state'],
26 { label: string; className: string }
27> = {
28 empty: { label: 'Not set', className: 'text-gray-500' },
29 set: { label: 'Saved', className: 'text-gray-400' },
30 locked: { label: 'Locked', className: 'text-amber-400' },
31 error: { label: 'Check failed', className: 'text-red-400' },
32}
33
34export function ByokKeyDialog({
35 open,
36 onOpenChange,
37 envStatus,
38 activeProvider = null,
39 highlightProvider = null,
40 openRouter,
41 trigger,
42 description = 'Keys stay in your browser and are sent per-request in a header — never stored on the server. Providers with a server key already work without one.',
43}: ByokKeyDialogProps) {
44 const snapshot = useByok(byok)
45 const [unlocking, setUnlocking] = useState(false)
46 const [actionError, setActionError] = useState('')
47
48 const activeStatus = activeProvider
49 ? snapshot.status[activeProvider]
50 : undefined
51 const activeNeedsKey =
52 activeProvider != null &&
53 !envStatus?.[activeProvider] &&
54 (!activeStatus || activeStatus.state === 'empty')
55
56 return (
57 <>
58 {trigger ?? (
59 <button
60 type="button"
61 onClick={() => onOpenChange(true)}
62 title="API keys"
63 aria-label="API keys"
64 className="relative flex items-center justify-center rounded-lg border border-orange-500/20 bg-orange-500/10 p-2 text-orange-400 transition-colors hover:bg-orange-500/20"
65 >
66 <KeyRound className="h-5 w-5" />
67 {activeNeedsKey ? (
68 <span className="absolute -right-1 -top-1 h-2.5 w-2.5 rounded-full bg-amber-400 ring-2 ring-gray-800" />
69 ) : null}
70 </button>
71 )}
72
73 {open ? (
74 <div
75 className="fixed inset-0 z-50 overflow-y-auto bg-black/60"
76 onClick={() => onOpenChange(false)}
77 >
78 <div className="flex min-h-full items-center justify-center p-4">
79 <div
80 className="max-h-[calc(100dvh-2rem)] w-full max-w-md overflow-y-auto rounded-xl border border-gray-700 bg-gray-900 p-5 shadow-2xl"
81 onClick={(event) => event.stopPropagation()}
82 >
83 <div className="mb-1 flex items-center justify-between">
84 <h2 className="text-lg font-semibold text-white">API keys</h2>
85 <button
86 type="button"
87 onClick={() => onOpenChange(false)}
88 aria-label="Close"
89 className="text-2xl leading-none text-gray-400 hover:text-white"
90 >
91 <X className="h-5 w-5" />
92 </button>
93 </div>
94 <p className="mb-4 text-sm leading-snug text-gray-400">
95 {description}
96 </p>
97
98 {snapshot.locked ? (
99 <div className="mb-4 flex items-center justify-between gap-2 rounded-lg border border-gray-700 bg-gray-800 p-3 text-sm text-gray-200">
100 <span>
101 Your saved keys are locked ({byok.storage.label}).
102 </span>
103 <button
104 type="button"
105 disabled={unlocking}
106 className="rounded-md bg-orange-500 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50"
107 onClick={() => {
108 setUnlocking(true)
109 setActionError('')
110 void byok
111 .unlock()
112 .catch((error: unknown) =>
113 setActionError(
114 error instanceof Error
115 ? error.message
116 : 'Could not unlock keys',
117 ),
118 )
119 .finally(() => setUnlocking(false))
120 }}
121 >
122 {unlocking ? 'Unlocking…' : 'Unlock'}
123 </button>
124 </div>
125 ) : null}
126
127 {byok.storage.warning ? (
128 <p className="mb-3 text-xs text-amber-400">
129 {byok.storage.warning}
130 </p>
131 ) : null}
132 {snapshot.storageError ? (
133 <p className="mb-3 text-xs text-red-400">
134 {snapshot.storageError}
135 </p>
136 ) : null}
137 {actionError ? (
138 <p className="mb-3 text-xs text-red-400">{actionError}</p>
139 ) : null}
140 {openRouter?.completing ? (
141 <p className="mb-3 text-xs text-gray-400">
142 Completing OpenRouter sign-in…
143 </p>
144 ) : null}
145 {openRouter?.error ? (
146 <p className="mb-3 text-xs text-red-400">{openRouter.error}</p>
147 ) : null}
148
149 <div className="flex flex-col gap-4">
150 {KEYED_PROVIDERS.map((provider) => {
151 const group = KEY_GROUPS.find((g) =>
152 g.fields.some((f) => f.provider.id === provider.id),
153 )
154 if (group) {
155 // Render the group once, where its first field sits.
156 if (group.fields[0].provider.id !== provider.id) return null
157 return (
158 <GroupRow
159 key={group.id}
160 label={group.label}
161 fields={group.fields}
162 statuses={snapshot.status}
163 locked={snapshot.locked}
164 envStatus={envStatus}
165 highlight={group.fields.some(
166 (f) => f.provider.id === highlightProvider,
167 )}
168 />
169 )
170 }
171 return (
172 <ProviderRow
173 key={provider.id}
174 id={provider.id}
175 label={provider.label}
176 status={snapshot.status[provider.id]}
177 locked={snapshot.locked}
178 hasEnvKey={Boolean(envStatus?.[provider.id])}
179 highlight={provider.id === highlightProvider}
180 openRouter={
181 provider.id === 'openrouter' ? openRouter : undefined
182 }
183 />
184 )
185 })}
186 </div>
187 </div>
188 </div>
189 </div>
190 ) : null}
191 </>
192 )
193}
194
195function ProviderRow({
196 id,
197 label,
198 status,
199 locked,
200 hasEnvKey,
201 highlight,
202 openRouter,
203}: {
204 id: ProviderId
205 label: string
206 status: KeyStatus | undefined
207 locked: boolean
208 hasEnvKey: boolean
209 highlight: boolean
210 openRouter?: ByokKeyDialogProps['openRouter']
211}) {
212 const [draft, setDraft] = useState('')
213 const [rowError, setRowError] = useState('')
214 const state = status?.state ?? 'empty'
215 const masked = status && 'masked' in status ? status.masked : undefined
216 const isLocked = locked || state === 'locked'
217 const hasKey = state !== 'empty'
218
219 return (
220 <div
221 className={`flex flex-col gap-2 rounded-lg border p-3 ${
222 highlight
223 ? 'border-amber-400/60 shadow-[0_0_0_1px_rgba(251,191,36,0.4)]'
224 : 'border-gray-700 bg-gray-800/50'
225 }`}
226 >
227 <div className="flex items-center justify-between">
228 <span className="font-semibold text-white">{label}</span>
229 <PresenceBadge
230 state={state}
231 hasKey={hasKey}
232 isLocked={state === 'locked'}
233 hasEnvKey={hasEnvKey}
234 />
235 </div>
236
237 {hasKey && masked ? (
238 <div className="flex items-center justify-between gap-2">
239 <code className="font-mono tracking-wider text-gray-300">
240 {masked}
241 </code>
242 <div className="flex gap-1.5">
243 <button
244 type="button"
245 disabled={isLocked}
246 className="rounded-md border border-gray-600 bg-gray-800 px-2.5 py-1 text-sm text-gray-200 disabled:opacity-50"
247 onClick={() => {
248 setRowError('')
249 void byok
250 .clear(id)
251 .catch((error: unknown) =>
252 setRowError(
253 error instanceof Error
254 ? error.message
255 : 'Could not clear key',
256 ),
257 )
258 }}
259 >
260 Clear
261 </button>
262 </div>
263 </div>
264 ) : null}
265
266 {id === 'openrouter' && openRouter && !hasKey ? (
267 <button
268 type="button"
269 className="w-full rounded-md border border-gray-600 bg-gray-800 px-3 py-2 text-sm font-semibold text-white"
270 onClick={openRouter.onLogin}
271 >
272 Sign in with OpenRouter
273 </button>
274 ) : null}
275
276 {state === 'error' && status && 'message' in status ? (
277 <p className="text-xs text-red-400">{status.message}</p>
278 ) : null}
279 {rowError ? <p className="text-xs text-red-400">{rowError}</p> : null}
280
281 <form
282 className="flex gap-1.5"
283 onSubmit={(event) => {
284 event.preventDefault()
285 const next = draft.trim()
286 if (!next || isLocked) return
287 setRowError('')
288 void byok
289 .update(id, next)
290 .then(() => setDraft(''))
291 .catch((error: unknown) =>
292 setRowError(
293 error instanceof Error ? error.message : 'Could not save key',
294 ),
295 )
296 }}
297 >
298 <input
299 type="password"
300 autoComplete="off"
301 spellCheck={false}
302 disabled={isLocked}
303 placeholder={
304 isLocked
305 ? 'Unlock to replace…'
306 : hasKey
307 ? 'Replace key…'
308 : `Paste ${label} key…`
309 }
310 value={draft}
311 onChange={(event) => setDraft(event.target.value)}
312 className="flex-1 rounded-md border border-gray-600 bg-gray-950 px-2 py-1.5 text-sm text-white placeholder-gray-500 disabled:opacity-50"
313 />
314 <button
315 type="submit"
316 disabled={!draft.trim() || isLocked}
317 className="rounded-md bg-orange-500 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50"
318 >
319 Save
320 </button>
321 </form>
322 </div>
323 )
324}
325
326/**
327 * One card for a credential made of several stored values (for example
328 * Cloudflare's account id + API token). Each field saves to its own id.
329 */
330function GroupRow({
331 label,
332 fields,
333 statuses,
334 locked,
335 envStatus,
336 highlight,
337}: {
338 label: string
339 fields: ReadonlyArray<{
340 provider: { id: ProviderId; label: string }
341 label: string
342 secret: boolean
343 }>
344 statuses: Record<string, KeyStatus | undefined>
345 locked: boolean
346 envStatus?: Record<string, boolean>
347 highlight: boolean
348}) {
349 const [drafts, setDrafts] = useState<Record<string, string>>({})
350 const [rowError, setRowError] = useState('')
351 const states = fields.map((f) => statuses[f.provider.id]?.state ?? 'empty')
352 const allSet = states.every((s) => s !== 'empty')
353 const anyLocked = locked || states.some((s) => s === 'locked')
354 const allEnv = fields.every((f) => Boolean(envStatus?.[f.provider.id]))
355 const state: KeyStatus['state'] = anyLocked
356 ? 'locked'
357 : states.includes('error')
358 ? 'error'
359 : allSet
360 ? 'set'
361 : 'empty'
362 const filled = fields.filter((f) => drafts[f.provider.id]?.trim())
363
364 return (
365 <div
366 className={`flex flex-col gap-2 rounded-lg border p-3 ${
367 highlight
368 ? 'border-amber-400/60 shadow-[0_0_0_1px_rgba(251,191,36,0.4)]'
369 : 'border-gray-700 bg-gray-800/50'
370 }`}
371 >
372 <div className="flex items-center justify-between">
373 <span className="font-semibold text-white">{label}</span>
374 <PresenceBadge
375 state={state}
376 hasKey={allSet}
377 isLocked={state === 'locked'}
378 hasEnvKey={allEnv}
379 />
380 </div>
381
382 {rowError ? <p className="text-xs text-red-400">{rowError}</p> : null}
383
384 <form
385 className="flex flex-col gap-1.5"
386 onSubmit={(event) => {
387 event.preventDefault()
388 if (filled.length === 0 || anyLocked) return
389 setRowError('')
390 // One at a time: passkey-backed storage runs a WebAuthn ceremony
391 // per write, and the browser rejects a second concurrent request.
392 void (async () => {
393 for (const f of filled) {
394 await byok.update(f.provider.id, drafts[f.provider.id]!.trim())
395 }
396 })()
397 .then(() => setDrafts({}))
398 .catch((error: unknown) =>
399 setRowError(
400 error instanceof Error ? error.message : 'Could not save keys',
401 ),
402 )
403 }}
404 >
405 {fields.map((field) => {
406 const status = statuses[field.provider.id]
407 const masked =
408 status && 'masked' in status ? status.masked : undefined
409 const hasKey = (status?.state ?? 'empty') !== 'empty'
410 return (
411 <label
412 key={field.provider.id}
413 className="flex items-center gap-2 text-xs text-gray-400"
414 >
415 <span className="w-24 shrink-0">{field.label}</span>
416 <input
417 type={field.secret ? 'password' : 'text'}
418 autoComplete="off"
419 spellCheck={false}
420 disabled={anyLocked}
421 placeholder={
422 anyLocked
423 ? 'Unlock to replace…'
424 : hasKey && masked
425 ? masked
426 : `Paste ${field.label}…`
427 }
428 value={drafts[field.provider.id] ?? ''}
429 onChange={(event) =>
430 setDrafts((prev) => ({
431 ...prev,
432 [field.provider.id]: event.target.value,
433 }))
434 }
435 className="flex-1 rounded-md border border-gray-600 bg-gray-950 px-2 py-1.5 text-sm text-white placeholder-gray-500 disabled:opacity-50"
436 />
437 </label>
438 )
439 })}
440 <div className="flex justify-end gap-1.5">
441 {allSet ? (
442 <button
443 type="button"
444 disabled={anyLocked}
445 className="rounded-md border border-gray-600 bg-gray-800 px-2.5 py-1 text-sm text-gray-200 disabled:opacity-50"
446 onClick={() => {
447 setRowError('')
448 void (async () => {
449 for (const f of fields) await byok.clear(f.provider.id)
450 })().catch((error: unknown) =>
451 setRowError(
452 error instanceof Error
453 ? error.message
454 : 'Could not clear keys',
455 ),
456 )
457 }}
458 >
459 Clear
460 </button>
461 ) : null}
462 <button
463 type="submit"
464 disabled={filled.length === 0 || anyLocked}
465 className="rounded-md bg-orange-500 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50"
466 >
467 Save
468 </button>
469 </div>
470 </form>
471 </div>
472 )
473}
474
475function PresenceBadge({
476 state,
477 hasKey,
478 isLocked,
479 hasEnvKey,
480}: {
481 state: KeyStatus['state']
482 hasKey: boolean
483 isLocked: boolean
484 hasEnvKey: boolean
485}) {
486 if (hasKey && !isLocked) {
487 return (
488 <span className="text-xs font-semibold text-emerald-400">Your key</span>
489 )
490 }
491 if (isLocked) {
492 return <span className="text-xs font-semibold text-amber-400">Locked</span>
493 }
494 if (hasEnvKey) {
495 return (
496 <span className="text-xs font-semibold text-gray-400">Server key</span>
497 )
498 }
499 const { label, className } = STATUS_LABEL[state]
500 return <span className={`text-xs font-semibold ${className}`}>{label}</span>
501}