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 connection: fetchServerSentEvents('/api/transcribe'),
93 byok,
94 byokProvider: () => 'openai',
95 onResult: (result) => {
96 setText((prev) => (prev ? `${prev} ${result.text}` : result.text))
97 },
98 onError: (error) => {
99 setInputError(
100 error instanceof Error ? error.message : 'Could not transcribe audio',
101 )
102 },
103 })
104
105 const {
106 isRecording,
107 isSupported: micSupported,
108 start: startRecording,
109 stop: stopRecording,
110 } = useAudioRecorder()
111
112 const status = chat.error ? 'error' : 'ready'
113
114 function removeDraft(id: string) {
115 setDrafts((prev) => {
116 const next = prev.filter((draft) => draft.id !== id)
117 const removed = prev.find((draft) => draft.id === id)
118 if (removed?.preview) URL.revokeObjectURL(removed.preview)
119 return next
120 })
121 }
122
123 function send() {
124 const trimmed = text.trim()
125 if (!trimmed && drafts.length === 0) return
126 if (drafts.length === 0) {
127 void chat.sendMessage(trimmed)
128 } else {
129 const content: Array<ContentPart> = []
130 if (trimmed) content.push({ type: 'text', content: trimmed })
131 for (const draft of drafts) content.push(draft.part)
132 void chat.sendMessage({ content })
133 for (const draft of drafts) {
134 if (draft.preview) URL.revokeObjectURL(draft.preview)
135 }
136 setDrafts([])
137 }
138 setText('')
139 }
140
141 async function toggleMic() {
142 try {
143 if (isRecording) {
144 const rec = await stopRecording()
145 const mimeType = rec.mimeType.split(';')[0] ?? rec.mimeType
146 await transcribe({ audio: `data:${mimeType};base64,${rec.base64}` })
147 return
148 }
149 setInputError(null)
150 await startRecording()
151 } catch (error) {
152 setInputError(
153 error instanceof Error ? error.message : 'Could not record audio',
154 )
155 }
156 }
157
158 return (
159 <PromptInput
160 onSubmit={(event) => {
161 event.preventDefault()
162 send()
163 }}
164 >
165 <input
166 accept="image/*,application/pdf,audio/*,video/*"
167 className="hidden"
168 multiple
169 onChange={(event) => {
170 const files = event.currentTarget.files
171 if (!files) return
172 void Promise.all(Array.from(files).map(fileToDraft))
173 .then((next) => {
174 setInputError(null)
175 setDrafts((prev) => [...prev, ...next])
176 })
177 .catch((error: unknown) => {
178 setInputError(
179 error instanceof Error
180 ? error.message
181 : 'Could not attach the file',
182 )
183 })
184 event.currentTarget.value = ''
185 }}
186 ref={fileRef}
187 type="file"
188 />
189 {drafts.length > 0 ? (
190 <div className="flex flex-wrap gap-2 px-3 pt-3">
191 {drafts.map((draft) => (
192 <div className="relative" key={draft.id}>
193 {draft.part.type === 'audio' && draft.preview ? (
194 <audio className="h-10 max-w-56" controls src={draft.preview} />
195 ) : draft.preview ? (
196 <img
197 alt=""
198 className="size-14 rounded-md object-cover"
199 src={draft.preview}
200 />
201 ) : (
202 <span className="block max-w-40 truncate rounded-md border px-2 py-1 text-xs">
203 {draft.label}
204 </span>
205 )}
206 <button
207 className="absolute -top-1 -right-1 rounded-full bg-destructive p-0.5 text-destructive-foreground"
208 onClick={() => removeDraft(draft.id)}
209 type="button"
210 >
211 <XIcon className="size-3" />
212 <span className="sr-only">Remove {draft.label}</span>
213 </button>
214 </div>
215 ))}
216 </div>
217 ) : null}
218 {inputError ? (
219 <p className="px-4 pt-2 text-destructive text-xs">{inputError}</p>
220 ) : null}
221 <PromptInputTextarea
222 name="message"
223 onChange={(event) => setText(event.currentTarget.value)}
224 onKeyDown={(event) => {
225 if (event.nativeEvent.isComposing) return
226 if (event.key !== 'Enter' || event.shiftKey) return
227 event.preventDefault()
228 send()
229 }}
230 placeholder="Plan a trip, attach a photo or PDF, or speak a plan…"
231 value={text}
232 />
233 <PromptInputToolbar>
234 <PromptInputTools>
235 <PromptInputButton
236 aria-label="Attach a photo, PDF, or clip"
237 disabled={chat.isLoading}
238 onClick={() => fileRef.current?.click()}
239 >
240 <PaperclipIcon className="size-4" />
241 </PromptInputButton>
242 {mounted && micSupported ? (
243 <PromptInputButton
244 aria-label={
245 isRecording ? 'Stop recording' : 'Record a voice note'
246 }
247 aria-pressed={isRecording}
248 disabled={chat.isLoading || isTranscribing}
249 onClick={() => void toggleMic()}
250 >
251 {isTranscribing ? (
252 <Loader2Icon className="size-4 animate-spin" />
253 ) : isRecording ? (
254 <SquareIcon className="size-4 text-destructive" />
255 ) : (
256 <MicIcon className="size-4" />
257 )}
258 </PromptInputButton>
259 ) : null}
260 <OpenaiKey />
261 <ModelSelector
262 onChange={(next) => {
263 setSelectedModel(next)
264 setModel(next)
265 }}
266 value={model}
267 />
268 </PromptInputTools>
269 <PromptInputSubmit
270 disabled={!text.trim() && drafts.length === 0}
271 status={status}
272 />
273 </PromptInputToolbar>
274 </PromptInput>
275 )
276}