Open History to see the last commit
1import { useEffect, useRef, useState } from 'react'
2import {
3 fetchServerSentEvents,
4 useAudioRecorder,
5 useTranscription,
6} from '@tanstack/ai-react'
7import type { ContentPart } from '@tanstack/ai/client'
8import {
9 Loader2Icon,
10 MicIcon,
11 PaperclipIcon,
12 SquareIcon,
13 XIcon,
14} from 'lucide-react'
15import { byok } from '@/chat/byok'
16import { useChatContext } from './ui-components'
17import {
18 PromptInput,
19 PromptInputButton,
20 PromptInputSubmit,
21 PromptInputTextarea,
22 PromptInputToolbar,
23 PromptInputTools,
24} from '@/components/ai/prompt-input'
25import { ModelSelector, type ChatModelId } from '@/components/ai/model-selector'
26import { OpenaiKey } from '@/components/chat/openai-key'
27import { setSelectedModel, selectedModel } from '@/chat/model'
28
29type Draft = {
30 id: string
31 part: ContentPart
32 label: string
33 preview?: string
34}
35
36async function fileToDraft(file: File): Promise<Draft> {
37 const value = await new Promise<string>((resolve, reject) => {
38 const reader = new FileReader()
39 reader.onload = () => {
40 const result = reader.result
41 if (typeof result !== 'string') {
42 reject(new Error('Could not read the file'))
43 return
44 }
45 const comma = result.indexOf(',')
46 resolve(comma === -1 ? result : result.slice(comma + 1))
47 }
48 reader.onerror = () =>
49 reject(reader.error ?? new Error('Could not read the file'))
50 reader.readAsDataURL(file)
51 })
52 const mimeType = file.type || 'application/octet-stream'
53 const source = { type: 'data' as const, value, mimeType }
54 const part: ContentPart = mimeType.startsWith('image/')
55 ? { type: 'image', source }
56 : mimeType.startsWith('audio/')
57 ? { type: 'audio', source }
58 : mimeType.startsWith('video/')
59 ? { type: 'video', source }
60 : { type: 'document', source }
61 return {
62 id: crypto.randomUUID(),
63 part,
64 label: file.name,
65 preview: mimeType.startsWith('image/')
66 ? URL.createObjectURL(file)
67 : undefined,
68 }
69}
70
71export function ChatPromptInput() {
72 const chat = useChatContext()
73 const [model, setModel] = useState<ChatModelId>(selectedModel)
74 const [text, setText] = useState('')
75 const [drafts, setDrafts] = useState<Array<Draft>>([])
76 const [inputError, setInputError] = useState<string | null>(null)
77 const [mounted, setMounted] = useState(false)
78 const fileRef = useRef<HTMLInputElement>(null)
79 const draftsRef = useRef(drafts)
80 draftsRef.current = drafts
81
82 useEffect(() => {
83 setMounted(true)
84 return () => {
85 for (const draft of draftsRef.current) {
86 if (draft.preview) URL.revokeObjectURL(draft.preview)
87 }
88 }
89 }, [])
90
91 const { generate: transcribe, isLoading: isTranscribing } = useTranscription({
92 threadId: 'voice-input',
93 connection: fetchServerSentEvents('/api/transcribe'),
94 byok,
95 byokProvider: () => 'openai',
96 onResult: (result) => {
97 setText((prev) => (prev ? `${prev} ${result.text}` : result.text))
98 },
99 onError: (error) => {
100 setInputError(
101 error instanceof Error ? error.message : 'Could not transcribe audio',
102 )
103 },
104 })
105
106 const {
107 isRecording,
108 isSupported: micSupported,
109 start: startRecording,
110 stop: stopRecording,
111 } = useAudioRecorder()
112
113 const status = chat.error ? 'error' : 'ready'
114
115 function removeDraft(id: string) {
116 setDrafts((prev) => {
117 const next = prev.filter((draft) => draft.id !== id)
118 const removed = prev.find((draft) => draft.id === id)
119 if (removed?.preview) URL.revokeObjectURL(removed.preview)
120 return next
121 })
122 }
123
124 function send() {
125 const trimmed = text.trim()
126 if (!trimmed && drafts.length === 0) return
127 if (drafts.length === 0) {
128 void chat.sendMessage(trimmed)
129 } else {
130 const content: Array<ContentPart> = []
131 if (trimmed) content.push({ type: 'text', content: trimmed })
132 for (const draft of drafts) content.push(draft.part)
133 void chat.sendMessage({ content })
134 for (const draft of drafts) {
135 if (draft.preview) URL.revokeObjectURL(draft.preview)
136 }
137 setDrafts([])
138 }
139 setText('')
140 }
141
142 async function toggleMic() {
143 try {
144 if (isRecording) {
145 const rec = await stopRecording()
146 const mimeType = rec.mimeType.split(';')[0] ?? rec.mimeType
147 await transcribe({ audio: `data:${mimeType};base64,${rec.base64}` })
148 return
149 }
150 setInputError(null)
151 await startRecording()
152 } catch (error) {
153 setInputError(
154 error instanceof Error ? error.message : 'Could not record audio',
155 )
156 }
157 }
158
159 return (
160 <PromptInput
161 onSubmit={(event) => {
162 event.preventDefault()
163 send()
164 }}
165 >
166 <input
167 accept="image/*,application/pdf,audio/*,video/*"
168 className="hidden"
169 multiple
170 onChange={(event) => {
171 const files = event.currentTarget.files
172 if (!files) return
173 void Promise.all(Array.from(files).map(fileToDraft))
174 .then((next) => {
175 setInputError(null)
176 setDrafts((prev) => [...prev, ...next])
177 })
178 .catch((error: unknown) => {
179 setInputError(
180 error instanceof Error
181 ? error.message
182 : 'Could not attach the file',
183 )
184 })
185 event.currentTarget.value = ''
186 }}
187 ref={fileRef}
188 type="file"
189 />
190 {drafts.length > 0 ? (
191 <div className="flex flex-wrap gap-2 px-3 pt-3">
192 {drafts.map((draft) => (
193 <div className="relative" key={draft.id}>
194 {draft.part.type === 'audio' && draft.preview ? (
195 <audio className="h-10 max-w-56" controls src={draft.preview} />
196 ) : draft.preview ? (
197 <img
198 alt=""
199 className="size-14 rounded-md object-cover"
200 src={draft.preview}
201 />
202 ) : (
203 <span className="block max-w-40 truncate rounded-md border px-2 py-1 text-xs">
204 {draft.label}
205 </span>
206 )}
207 <button
208 className="absolute -top-1 -right-1 rounded-full bg-destructive p-0.5 text-destructive-foreground"
209 onClick={() => removeDraft(draft.id)}
210 type="button"
211 >
212 <XIcon className="size-3" />
213 <span className="sr-only">Remove {draft.label}</span>
214 </button>
215 </div>
216 ))}
217 </div>
218 ) : null}
219 {inputError ? (
220 <p className="px-4 pt-2 text-destructive text-xs">{inputError}</p>
221 ) : null}
222 <PromptInputTextarea
223 name="message"
224 onChange={(event) => setText(event.currentTarget.value)}
225 onKeyDown={(event) => {
226 if (event.nativeEvent.isComposing) return
227 if (event.key !== 'Enter' || event.shiftKey) return
228 event.preventDefault()
229 send()
230 }}
231 placeholder="Plan a trip, attach a photo or PDF, or speak a plan…"
232 value={text}
233 />
234 <PromptInputToolbar>
235 <PromptInputTools>
236 <PromptInputButton
237 aria-label="Attach a photo, PDF, or clip"
238 disabled={chat.isLoading}
239 onClick={() => fileRef.current?.click()}
240 >
241 <PaperclipIcon className="size-4" />
242 </PromptInputButton>
243 {mounted && micSupported ? (
244 <PromptInputButton
245 aria-label={
246 isRecording ? 'Stop recording' : 'Record a voice note'
247 }
248 aria-pressed={isRecording}
249 disabled={chat.isLoading || isTranscribing}
250 onClick={() => void toggleMic()}
251 >
252 {isTranscribing ? (
253 <Loader2Icon className="size-4 animate-spin" />
254 ) : isRecording ? (
255 <SquareIcon className="size-4 text-destructive" />
256 ) : (
257 <MicIcon className="size-4" />
258 )}
259 </PromptInputButton>
260 ) : null}
261 <OpenaiKey />
262 <ModelSelector
263 onChange={(next) => {
264 setSelectedModel(next)
265 setModel(next)
266 }}
267 value={model}
268 />
269 </PromptInputTools>
270 <PromptInputSubmit
271 disabled={!text.trim() && drafts.length === 0}
272 status={status}
273 />
274 </PromptInputToolbar>
275 </PromptInput>
276 )
277}