Open History to see the last commit
1import { useEffect, useState } from 'react'
2import { KeyRound, X } from 'lucide-react'
3import { useByok } from '@tanstack/ai-react'
4import { byok, KEYED_PROVIDERS } from '@/lib/byok'
5import type { KeyStatus } from '@tanstack/ai-client/byok'
6import type { ProviderId } from '@tanstack/ai/byok'
7
8export type ByokKeyDialogProps = {
9 open: boolean
10 onOpenChange: (open: boolean) => void
11 envStatus?: Record<string, boolean>
12}
13
14const STATUS_LABEL: Record<
15 KeyStatus['state'],
16 { label: string; className: string }
17> = {
18 empty: { label: 'Not set', className: 'text-gray-500' },
19 set: { label: 'Saved', className: 'text-gray-400' },
20 locked: { label: 'Locked', className: 'text-amber-400' },
21 error: { label: 'Check failed', className: 'text-red-400' },
22}
23
24export function ByokKeyDialog({
25 open,
26 onOpenChange,
27 envStatus,
28}: ByokKeyDialogProps) {
29 const snapshot = useByok(byok)
30 const [unlocking, setUnlocking] = useState(false)
31 const [actionError, setActionError] = useState('')
32
33 useEffect(() => {
34 if (!open) return
35 const onKey = (event: KeyboardEvent) => {
36 if (event.key === 'Escape') onOpenChange(false)
37 }
38 window.addEventListener('keydown', onKey)
39 return () => window.removeEventListener('keydown', onKey)
40 }, [open, onOpenChange])
41
42 const locked = snapshot.locked
43 const needsAttention =
44 locked ||
45 KEYED_PROVIDERS.every((provider) => {
46 const status = snapshot.status[provider.id]
47 const empty = !status || status.state === 'empty'
48 return empty && !envStatus?.[provider.id]
49 })
50
51 return (
52 <>
53 <button
54 type="button"
55 onClick={() => onOpenChange(true)}
56 title="API keys"
57 aria-label="API keys"
58 className="relative flex items-center justify-center rounded-lg border border-purple-500/20 bg-purple-500/10 p-2 text-purple-400 transition-colors hover:bg-purple-500/20"
59 >
60 <KeyRound className="h-5 w-5" />
61 {needsAttention ? (
62 <span className="absolute -right-1 -top-1 h-2.5 w-2.5 rounded-full bg-amber-400 ring-2 ring-gray-800" />
63 ) : null}
64 </button>
65
66 {open ? (
67 <div
68 className="fixed inset-0 z-50 overflow-y-auto bg-black/60"
69 onClick={() => onOpenChange(false)}
70 >
71 <div className="flex min-h-full items-center justify-center p-4">
72 <div
73 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"
74 onClick={(event) => event.stopPropagation()}
75 >
76 <div className="mb-1 flex items-center justify-between">
77 <h2 className="text-lg font-semibold text-white">API keys</h2>
78 <button
79 type="button"
80 onClick={() => onOpenChange(false)}
81 aria-label="Close"
82 className="text-gray-400 hover:text-white"
83 >
84 <X className="h-5 w-5" />
85 </button>
86 </div>
87 <p className="mb-4 text-sm leading-snug text-gray-400">
88 Keys stay in this browser and are sent per request in a header.
89 Never stored on the server. Providers with a server env key
90 already work without one.
91 </p>
92
93 {snapshot.locked ? (
94 <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">
95 <span>Saved keys are locked ({byok.storage.label}).</span>
96 <button
97 type="button"
98 disabled={unlocking}
99 className="rounded-md bg-purple-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-purple-500 disabled:opacity-50"
100 onClick={() => {
101 setUnlocking(true)
102 setActionError('')
103 void byok
104 .unlock()
105 .catch((error: unknown) =>
106 setActionError(
107 error instanceof Error
108 ? error.message
109 : 'Could not unlock keys',
110 ),
111 )
112 .finally(() => setUnlocking(false))
113 }}
114 >
115 {unlocking ? 'Unlocking…' : 'Unlock'}
116 </button>
117 </div>
118 ) : null}
119
120 {byok.storage.warning ? (
121 <p className="mb-3 text-xs text-amber-400">
122 {byok.storage.warning}
123 </p>
124 ) : null}
125 {snapshot.storageError ? (
126 <p className="mb-3 text-xs text-red-400">
127 {snapshot.storageError}
128 </p>
129 ) : null}
130 {actionError ? (
131 <p className="mb-3 text-xs text-red-400">{actionError}</p>
132 ) : null}
133
134 <div className="flex flex-col gap-4">
135 {KEYED_PROVIDERS.map((provider) => (
136 <ProviderRow
137 key={provider.id}
138 id={provider.id}
139 label={provider.label}
140 status={snapshot.status[provider.id]}
141 locked={snapshot.locked}
142 hasEnvKey={Boolean(envStatus?.[provider.id])}
143 />
144 ))}
145 </div>
146 </div>
147 </div>
148 </div>
149 ) : null}
150 </>
151 )
152}
153
154function ProviderRow({
155 id,
156 label,
157 status,
158 locked,
159 hasEnvKey,
160}: {
161 id: ProviderId
162 label: string
163 status: KeyStatus | undefined
164 locked: boolean
165 hasEnvKey: boolean
166}) {
167 const [draft, setDraft] = useState('')
168 const [rowError, setRowError] = useState('')
169 const state = status?.state ?? 'empty'
170 const masked = status && 'masked' in status ? status.masked : undefined
171 const isLocked = locked || state === 'locked'
172 const hasKey = state !== 'empty'
173
174 return (
175 <div className="flex flex-col gap-2 rounded-lg border border-gray-700 bg-gray-800/50 p-3">
176 <div className="flex items-center justify-between">
177 <span className="font-semibold text-white">{label}</span>
178 <PresenceBadge
179 state={state}
180 hasKey={hasKey}
181 isLocked={state === 'locked'}
182 hasEnvKey={hasEnvKey}
183 />
184 </div>
185
186 {hasKey && masked ? (
187 <div className="flex items-center justify-between gap-2">
188 <code className="font-mono tracking-wider text-gray-300">
189 {masked}
190 </code>
191 <button
192 type="button"
193 disabled={isLocked}
194 className="rounded-md border border-gray-600 bg-gray-800 px-2.5 py-1 text-sm text-gray-200 disabled:opacity-50"
195 onClick={() => {
196 setRowError('')
197 void byok
198 .clear(id)
199 .catch((error: unknown) =>
200 setRowError(
201 error instanceof Error
202 ? error.message
203 : 'Could not clear key',
204 ),
205 )
206 }}
207 >
208 Clear
209 </button>
210 </div>
211 ) : null}
212
213 {state === 'error' && status && 'message' in status ? (
214 <p className="text-xs text-red-400">{status.message}</p>
215 ) : null}
216 {rowError ? <p className="text-xs text-red-400">{rowError}</p> : null}
217
218 <form
219 className="flex gap-1.5"
220 onSubmit={(event) => {
221 event.preventDefault()
222 const next = draft.trim()
223 if (!next || isLocked) return
224 setRowError('')
225 void byok
226 .update(id, next)
227 .then(() => setDraft(''))
228 .catch((error: unknown) =>
229 setRowError(
230 error instanceof Error ? error.message : 'Could not save key',
231 ),
232 )
233 }}
234 >
235 <input
236 type="password"
237 autoComplete="off"
238 spellCheck={false}
239 disabled={isLocked}
240 placeholder={
241 isLocked
242 ? 'Unlock to replace…'
243 : hasKey
244 ? 'Replace key…'
245 : `Paste ${label} key…`
246 }
247 value={draft}
248 onChange={(event) => setDraft(event.target.value)}
249 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"
250 />
251 <button
252 type="submit"
253 disabled={!draft.trim() || isLocked}
254 className="rounded-md bg-purple-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50"
255 >
256 Save
257 </button>
258 </form>
259 </div>
260 )
261}
262
263function PresenceBadge({
264 state,
265 hasKey,
266 isLocked,
267 hasEnvKey,
268}: {
269 state: KeyStatus['state']
270 hasKey: boolean
271 isLocked: boolean
272 hasEnvKey: boolean
273}) {
274 if (hasKey && !isLocked) {
275 return (
276 <span className="text-xs font-semibold text-emerald-400">Your key</span>
277 )
278 }
279 if (isLocked) {
280 return <span className="text-xs font-semibold text-amber-400">Locked</span>
281 }
282 if (hasEnvKey) {
283 return (
284 <span className="text-xs font-semibold text-gray-400">Server key</span>
285 )
286 }
287 const { label, className } = STATUS_LABEL[state]
288 return <span className={`text-xs font-semibold ${className}`}>{label}</span>
289}