Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

ByokKeyDialog.tsx

520 lines17.0 KB

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