Open History to see the last commit
1import { useEffect, useId, useRef, useState } from 'react'
2import { KeyRoundIcon, XIcon } from 'lucide-react'
3import { useByok } from '@tanstack/ai-react'
4import { byok } from '@/chat/byok'
5import { Button } from '@/components/ui/button'
6
7export function OpenaiKey() {
8 const snapshot = useByok(byok)
9 const [open, setOpen] = useState(false)
10 const [value, setValue] = useState('')
11 const titleId = useId()
12 const inputRef = useRef<HTMLInputElement>(null)
13 const status = snapshot.status.openai
14 const saved = status?.state === 'set'
15
16 useEffect(() => {
17 if (!open) return
18 inputRef.current?.focus()
19 function onKey(event: KeyboardEvent) {
20 if (event.key === 'Escape') setOpen(false)
21 }
22 window.addEventListener('keydown', onKey)
23 return () => window.removeEventListener('keydown', onKey)
24 }, [open])
25
26 return (
27 <>
28 <Button
29 aria-label="OpenAI key"
30 onClick={() => setOpen(true)}
31 size="icon-sm"
32 type="button"
33 variant="ghost"
34 >
35 <KeyRoundIcon className="size-4" />
36 </Button>
37 {open ? (
38 <div
39 className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"
40 onClick={() => setOpen(false)}
41 >
42 <div
43 aria-labelledby={titleId}
44 aria-modal="true"
45 className="w-full max-w-sm rounded-xl border bg-card p-4 shadow-lg"
46 onClick={(event) => event.stopPropagation()}
47 role="dialog"
48 >
49 <div className="mb-3 flex items-center justify-between">
50 <h2 className="text-sm font-medium" id={titleId}>
51 OpenAI key
52 </h2>
53 <Button
54 aria-label="Close"
55 onClick={() => setOpen(false)}
56 size="icon-sm"
57 type="button"
58 variant="ghost"
59 >
60 <XIcon className="size-4" />
61 </Button>
62 </div>
63 <p className="text-muted-foreground mb-3 text-xs">
64 Paste a key to send it from this browser. If you leave this empty,
65 the server uses OPENAI_API_KEY from .env.
66 </p>
67 <form
68 className="space-y-3"
69 onSubmit={(event) => {
70 event.preventDefault()
71 const next = value.trim()
72 if (!next) return
73 void byok.update('openai', next)
74 setValue('')
75 setOpen(false)
76 }}
77 >
78 <input
79 autoComplete="off"
80 className="h-9 w-full rounded-md border bg-transparent px-3 text-sm outline-none"
81 onChange={(event) => setValue(event.currentTarget.value)}
82 placeholder={saved ? status.masked : 'sk-...'}
83 ref={inputRef}
84 type="password"
85 value={value}
86 />
87 <div className="flex justify-end gap-2">
88 {saved ? (
89 <Button
90 onClick={() => void byok.clear('openai')}
91 size="sm"
92 type="button"
93 variant="ghost"
94 >
95 Clear
96 </Button>
97 ) : null}
98 <Button disabled={!value.trim()} size="sm" type="submit">
99 Save
100 </Button>
101 </div>
102 </form>
103 </div>
104 </div>
105 ) : null}
106 </>
107 )
108}