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

index.tsx

918 lines34.3 KB

1import { useEffect, useMemo, useRef, useState } from 'react'
2import { Link, createFileRoute } from '@tanstack/react-router'
3import {
4 Braces,
5 Code2,
6 Database,
7 FileAudio,
8 FileText,
9 Github,
10 Image,
11 ImagePlus,
12 Layers,
13 Mic,
14 Music,
15 PauseCircle,
16 Send,
17 Sparkles,
18 Square,
19 Video,
20 X,
21} from 'lucide-react'
22import ReactMarkdown from 'react-markdown'
23import rehypeRaw from 'rehype-raw'
24import rehypeSanitize from 'rehype-sanitize'
25import rehypeHighlight from 'rehype-highlight'
26import remarkGfm from 'remark-gfm'
27import {
28 fetchServerSentEvents,
29 useAudioRecorder,
30 useByok,
31 useChat,
32 useTranscription,
33} from '@tanstack/ai-react'
34import {
35 completeOpenRouterPkceIntoByok,
36 startOpenRouterPkceLogin,
37} from '@tanstack/ai-openrouter/pkce'
38import { refreshChatGptSignIn } from '@tanstack/ai-openai/siwc'
39import { clientTools } from '@tanstack/ai-client'
40import { ThinkingPart } from '@tanstack/ai-react/ui'
41import type { BoundInterrupts } from '@tanstack/ai-client'
42import type { UIMessage } from '@tanstack/ai-react'
43import type { ContentPart } from '@tanstack/ai'
44import type { GeminiInteractionsCustomEventValue } from '@tanstack/ai-gemini/experimental'
45import type { ProviderId } from '@tanstack/ai/byok'
46import type { ModelOption } from '@/lib/model-selection'
47import GuitarRecommendation from '@/components/example-GuitarRecommendation'
48import {
49 addToCartToolDef,
50 addToWishListToolDef,
51 getPersonalGuitarPreferenceToolDef,
52 recommendGuitarToolDef,
53} from '@/lib/guitar-tools'
54import { DEFAULT_MODEL_OPTION, MODEL_OPTIONS } from '@/lib/model-selection'
55import { byok, getEnvKeyStatus, toByokProvider } from '@/lib/byok'
56import { ByokKeyDialog } from '@/components/ByokKeyDialog'
57​
58/**
59 * Generate a random message ID
60 */
61function generateMessageId(): string {
62 return `msg-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`
64​
65const getPersonalGuitarPreferenceToolClient =
66 getPersonalGuitarPreferenceToolDef.client(() => ({ preference: 'acoustic' }))
67​
68const addToWishListToolClient = addToWishListToolDef.client((args) => {
69 const wishList = JSON.parse(localStorage.getItem('wishList') || '[]')
70 wishList.push(args.guitarId)
71 localStorage.setItem('wishList', JSON.stringify(wishList))
72 return {
73 success: true,
74 guitarId: args.guitarId,
75 totalItems: wishList.length,
76 }
77})
78​
79const addToCartToolClient = addToCartToolDef.client((args) => ({
80 success: true,
81 cartId: 'CART_CLIENT_' + Date.now(),
82 guitarId: args.guitarId,
83 quantity: args.quantity,
84 totalItems: args.quantity,
85}))
86​
87const recommendGuitarToolClient = recommendGuitarToolDef.client(({ id }) => ({
88 id: +id,
89}))
90​
91const tools = clientTools(
92 getPersonalGuitarPreferenceToolClient,
93 addToWishListToolClient,
94 addToCartToolClient,
95 recommendGuitarToolClient,
97​
98type ChatTools = typeof tools
99​
100function ChatInputArea({ children }: { children: React.ReactNode }) {
101 return (
102 <div className="border-t border-orange-500/10 bg-gray-900/80 backdrop-blur-sm">
103 <div className="w-full px-4 py-3">{children}</div>
104 </div>
105 )
107​
108function Messages({
109 messages,
110 interrupts,
111}: {
112 messages: ReadonlyArray<UIMessage>
113 interrupts: BoundInterrupts<ChatTools>
114}) {
115 const messagesContainerRef = useRef<HTMLDivElement>(null)
116 const hasRenderablePart = (message: UIMessage): boolean => {
117 return message.parts.some((part) => {
118 if (part.type === 'thinking') return true
119 // File-handle images have no local bytes or URL to show.
120 if (part.type === 'image' && part.source.type !== 'file') return true
121 if (part.type === 'text' && part.content.trim()) return true
122 if (
123 part.type === 'tool-call' &&
124 part.name === 'recommendGuitar' &&
125 part.output
126 ) {
127 return true
128 }
129 return false
130 })
131 }
132 const visibleMessages = messages.filter(hasRenderablePart)
133​
134 useEffect(() => {
135 if (messagesContainerRef.current) {
136 messagesContainerRef.current.scrollTop =
137 messagesContainerRef.current.scrollHeight
138 }
139 }, [visibleMessages, interrupts.length])
140​
141 if (!visibleMessages.length && interrupts.length === 0) {
142 return (
143 <div className="flex-1 overflow-y-auto px-4 py-8">
144 <div className="max-w-2xl mx-auto space-y-6">
145 <div className="text-center">
146 <h2 className="text-xl font-semibold text-white mb-2">
147 Welcome to TanStack AI
148 </h2>
149 <p className="text-gray-400 text-sm">
150 Start a conversation below, or explore generation demos:
151 </p>
152 </div>
153 <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
154 <Link
155 to="/generations/image"
156 className="flex flex-col items-center gap-2 p-4 bg-gray-800/50 border border-gray-700 rounded-lg hover:border-orange-500/40 hover:bg-gray-800 transition-colors"
157 >
158 <Image size={24} className="text-orange-400" />
159 <span className="text-sm text-gray-300">Image</span>
160 </Link>
161 <Link
162 to="/generations/speech"
163 className="flex flex-col items-center gap-2 p-4 bg-gray-800/50 border border-gray-700 rounded-lg hover:border-orange-500/40 hover:bg-gray-800 transition-colors"
164 >
165 <FileAudio size={24} className="text-orange-400" />
166 <span className="text-sm text-gray-300">Speech</span>
167 </Link>
168 <Link
169 to="/generations/audio"
170 className="flex flex-col items-center gap-2 p-4 bg-gray-800/50 border border-gray-700 rounded-lg hover:border-orange-500/40 hover:bg-gray-800 transition-colors"
171 >
172 <Music size={24} className="text-orange-400" />
173 <span className="text-sm text-gray-300">Audio</span>
174 </Link>
175 <Link
176 to="/generations/transcription"
177 className="flex flex-col items-center gap-2 p-4 bg-gray-800/50 border border-gray-700 rounded-lg hover:border-orange-500/40 hover:bg-gray-800 transition-colors"
178 >
179 <Mic size={24} className="text-orange-400" />
180 <span className="text-sm text-gray-300">Transcription</span>
181 </Link>
182 <Link
183 to="/generations/summarize"
184 className="flex flex-col items-center gap-2 p-4 bg-gray-800/50 border border-gray-700 rounded-lg hover:border-orange-500/40 hover:bg-gray-800 transition-colors"
185 >
186 <FileText size={24} className="text-orange-400" />
187 <span className="text-sm text-gray-300">Summarize</span>
188 </Link>
189 <Link
190 to="/generations/video"
191 className="flex flex-col items-center gap-2 p-4 bg-gray-800/50 border border-gray-700 rounded-lg hover:border-orange-500/40 hover:bg-gray-800 transition-colors"
192 >
193 <Video size={24} className="text-orange-400" />
194 <span className="text-sm text-gray-300">Video</span>
195 </Link>
196 <Link
197 to="/generations/persistent-generation"
198 className="flex flex-col items-center gap-2 p-4 bg-gray-800/50 border border-gray-700 rounded-lg hover:border-orange-500/40 hover:bg-gray-800 transition-colors"
199 >
200 <Database size={24} className="text-orange-400" />
201 <span className="text-sm text-gray-300">Persistence</span>
202 </Link>
203 <Link
204 to="/generations/structured-output"
205 className="flex flex-col items-center gap-2 p-4 bg-gray-800/50 border border-gray-700 rounded-lg hover:border-orange-500/40 hover:bg-gray-800 transition-colors"
206 >
207 <Braces size={24} className="text-orange-400" />
208 <span className="text-sm text-gray-300">Structured</span>
209 </Link>
210 <Link
211 to="/generations/structured-chat"
212 className="flex flex-col items-center gap-2 p-4 bg-gray-800/50 border border-gray-700 rounded-lg hover:border-orange-500/40 hover:bg-gray-800 transition-colors"
213 >
214 <Braces size={24} className="text-orange-400" />
215 <span className="text-sm text-gray-300">Structured Chat</span>
216 </Link>
217 <Link
218 to="/generations/openrouter-combined"
219 className="flex flex-col items-center gap-2 p-4 bg-gray-800/50 border border-gray-700 rounded-lg hover:border-orange-500/40 hover:bg-gray-800 transition-colors"
220 >
221 <Layers size={24} className="text-orange-400" />
222 <span className="text-sm text-gray-300">OpenRouter Combined</span>
223 </Link>
224 <Link
225 to="/typesafe-tools"
226 className="flex flex-col items-center gap-2 p-4 bg-gray-800/50 border border-gray-700 rounded-lg hover:border-orange-500/40 hover:bg-gray-800 transition-colors"
227 >
228 <Code2 size={24} className="text-orange-400" />
229 <span className="text-sm text-gray-300">Type-Safe Tools</span>
230 </Link>
231 <Link
232 to="/interrupts"
233 className="flex flex-col items-center gap-2 p-4 bg-gray-800/50 border border-gray-700 rounded-lg hover:border-orange-500/40 hover:bg-gray-800 transition-colors"
234 >
235 <PauseCircle size={24} className="text-orange-400" />
236 <span className="text-sm text-gray-300">Interrupts Lab</span>
237 </Link>
238 <Link
239 to="/generic-interrupts"
240 className="flex flex-col items-center gap-2 p-4 bg-gray-800/50 border border-gray-700 rounded-lg hover:border-orange-500/40 hover:bg-gray-800 transition-colors"
241 >
242 <Sparkles size={24} className="text-orange-400" />
243 <span className="text-sm text-gray-300">Generic Interrupts</span>
244 </Link>
245 <Link
246 to="/sandboxes"
247 className="flex flex-col items-center gap-2 p-4 bg-gray-800/50 border border-gray-700 rounded-lg hover:border-orange-500/40 hover:bg-gray-800 transition-colors"
248 >
249 <Github size={24} className="text-orange-400" />
250 <span className="text-sm text-gray-300">Sandboxes</span>
251 </Link>
252 <Link
253 to="/repo-report"
254 className="flex flex-col items-center gap-2 p-4 bg-gray-800/50 border border-gray-700 rounded-lg hover:border-orange-500/40 hover:bg-gray-800 transition-colors"
255 >
256 <FileText size={24} className="text-orange-400" />
257 <span className="text-sm text-gray-300">Repo report</span>
258 </Link>
259 <Link
260 to="/app-studio"
261 className="flex flex-col items-center gap-2 p-4 bg-gray-800/50 border border-gray-700 rounded-lg hover:border-orange-500/40 hover:bg-gray-800 transition-colors"
262 >
263 <Layers size={24} className="text-orange-400" />
264 <span className="text-sm text-gray-300">App Studio</span>
265 </Link>
266 </div>
267 </div>
268 </div>
269 )
270 }
271​
272 return (
273 <div
274 ref={messagesContainerRef}
275 className="flex-1 overflow-y-auto px-4 py-4"
276 >
277 {interrupts.map((interrupt) => {
278 if (interrupt.kind !== 'tool-approval') return null
279 return (
280 <div
281 key={interrupt.id}
282 className="p-4 bg-yellow-500/10 border border-yellow-500/20 rounded-lg mb-3"
283 >
284 <p className="text-white font-medium mb-2">
285 Approval required: {interrupt.toolName}
286 </p>
287 <div className="text-gray-300 text-sm mb-3">
288 <pre className="bg-gray-800 p-2 rounded text-xs overflow-x-auto">
289 {JSON.stringify(interrupt.originalArgs, null, 2)}
290 </pre>
291 </div>
292 <div className="flex gap-2">
293 <button
294 type="button"
295 onClick={() => interrupt.resolveInterrupt(true)}
296 className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg text-sm font-medium transition-colors"
297 >
298 Approve
299 </button>
300 <button
301 type="button"
302 onClick={() => interrupt.resolveInterrupt(false)}
303 className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg text-sm font-medium transition-colors"
304 >
305 Deny
306 </button>
307 <button
308 type="button"
309 onClick={() => interrupt.cancel()}
310 className="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg text-sm font-medium transition-colors"
311 >
312 Cancel
313 </button>
314 </div>
315 </div>
316 )
317 })}
318 {visibleMessages.map((message) => {
319 return (
320 <div
321 key={message.id}
322 className={`p-4 rounded-lg mb-2 ${
323 message.role === 'assistant'
324 ? 'bg-linear-to-r from-orange-500/5 to-red-600/5'
325 : 'bg-transparent'
326 }`}
327 >
328 <div className="flex items-start gap-4">
329 {message.role === 'assistant' ? (
330 <div className="w-8 h-8 rounded-lg bg-linear-to-r from-orange-500 to-red-600 flex items-center justify-center text-sm font-medium text-white shrink-0">
331 AI
332 </div>
333 ) : (
334 <div className="w-8 h-8 rounded-lg bg-gray-700 flex items-center justify-center text-sm font-medium text-white shrink-0">
335 U
336 </div>
337 )}
338 <div className="flex-1 min-w-0">
339 {/* Render parts in order */}
340 {message.parts.map((part, index) => {
341 if (part.type === 'thinking') {
342 // Check if thinking is complete (if there's a text part after)
343 const isComplete = message.parts
344 .slice(index + 1)
345 .some((p) => p.type === 'text')
346 return (
347 <div key={`thinking-${index}`} className="mt-2 mb-2">
348 <ThinkingPart
349 content={part.content}
350 isComplete={isComplete}
351 className="p-4 bg-gray-800/50 border border-gray-700/50 rounded-lg"
352 />
353 </div>
354 )
355 }
356​
357 if (part.type === 'text' && part.content) {
358 return (
359 <div
360 key={`text-${index}`}
361 className="text-white prose dark:prose-invert max-w-none"
362 >
363 <ReactMarkdown
364 rehypePlugins={[
365 rehypeRaw,
366 rehypeSanitize,
367 rehypeHighlight,
368 remarkGfm,
369 ]}
370 >
371 {part.content}
372 </ReactMarkdown>
373 </div>
374 )
375 }
376​
377 // Render image parts (file references have no local bytes
378 // or URL to render, so only url/data sources get an <img>)
379 if (part.type === 'image' && part.source.type !== 'file') {
380 const imageUrl =
381 part.source.type === 'url'
382 ? part.source.value
383 : `data:image/png;base64,${part.source.value}`
384 return (
385 <div key={`image-${index}`} className="mt-2 mb-2">
386 <img
387 src={imageUrl}
388 alt="Attached image"
389 className="max-w-md rounded-lg border border-gray-700"
390 />
391 </div>
392 )
393 }
394​
395 // Tool approvals render from bound `interrupts` above
396 // (resolveInterrupt). Skip legacy part.approval UI.
397 if (
398 part.type === 'tool-call' &&
399 part.state === 'approval-requested'
400 ) {
401 return null
402 }
403​
404 // Guitar recommendation card
405 if (
406 part.type === 'tool-call' &&
407 part.name === 'recommendGuitar' &&
408 part.output
409 ) {
410 return (
411 <div key={part.id} className="mt-2">
412 <GuitarRecommendation id={part.output?.id} />
413 </div>
414 )
415 }
416​
417 return null
418 })}
419 </div>
420 </div>
421 </div>
422 )
423 })}
424 </div>
425 )
427​
428function ChatPage() {
429 const [selectedModel, setSelectedModel] =
430 useState<ModelOption>(DEFAULT_MODEL_OPTION)
431 const [attachedImages, setAttachedImages] = useState<
432 Array<{ id: string; base64: string; mimeType: string; preview: string }>
433 >([])
434 const fileInputRef = useRef<HTMLInputElement>(null)
435 // Session-scoped Gemini Interactions id — the server surfaces it via a
436 // `gemini.interactionId` CUSTOM event, and we send it back as
437 // `previous_interaction_id` on the next turn. State (not ref) so a
438 // forwardedProps change triggers `useChat` to re-sync the payload.
439 const [interactionId, setInteractionId] = useState<string | undefined>(
440 undefined,
441 )
442 const selectedProviderRef = useRef(selectedModel.provider)
443 selectedProviderRef.current = selectedModel.provider
444 const snapshot = useByok(byok)
445 const [envKeyStatus, setEnvKeyStatus] = useState<Record<string, boolean>>({})
446 const [keyDialog, setKeyDialog] = useState<{
447 open: boolean
448 provider: ProviderId | null
449 }>({ open: false, provider: null })
450 const [openRouterCompleting, setOpenRouterCompleting] = useState(false)
451 const [openRouterError, setOpenRouterError] = useState<string | null>(null)
452​
453 useEffect(() => {
454 void getEnvKeyStatus().then(setEnvKeyStatus)
455 }, [])
456​
457 useEffect(() => {
458 setOpenRouterCompleting(true)
459 void completeOpenRouterPkceIntoByok(byok)
460 .catch((error: unknown) =>
461 setOpenRouterError(
462 error instanceof Error ? error.message : 'OpenRouter sign-in failed',
463 ),
464 )
465 .finally(() => setOpenRouterCompleting(false))
466 }, [])
467​
468 // A ChatGPT sign-in token lasts an hour. Refresh it before it expires.
469 useEffect(() => {
470 const refresh = () => {
471 void refreshChatGptSignIn(byok).catch((error: unknown) =>
472 console.warn('ChatGPT token refresh failed', error),
473 )
474 }
475 refresh()
476 const timer = setInterval(refresh, 60_000)
477 return () => clearInterval(timer)
478 }, [])
479​
480 useEffect(() => {
481 if (snapshot.prompt?.reason === 'missing') {
482 setKeyDialog({ open: true, provider: snapshot.prompt.provider })
483 }
484 }, [snapshot.prompt])
485​
486 const activeByokId = toByokProvider(selectedModel.provider)
487​
488 // Reset the interaction id whenever the user switches model/provider so
489 // we don't chain against a stale or wrong-model interaction. Messages
490 // are cleared too: the Gemini Interactions API can't replay history
491 // statelessly, so carrying messages from a different provider/model
492 // into a fresh interaction would surface as
493 // "cannot send prior conversation history on a fresh interaction".
494 useEffect(() => {
495 setInteractionId(undefined)
496 setMessages([])
497 }, [selectedModel.provider, selectedModel.model])
498​
499 const forwardedProps = useMemo(
500 () => ({
501 provider: selectedModel.provider,
502 model: selectedModel.model,
503 ...(selectedModel.provider === 'gemini-interactions' && interactionId
504 ? { previousInteractionId: interactionId }
505 : {}),
506 }),
507 [selectedModel.provider, selectedModel.model, interactionId],
508 )
509​
510 const {
511 messages,
512 setMessages,
513 sendMessage,
514 isLoading,
515 error,
516 interrupts,
517 stop,
518 } = useChat({
519 threadId: 'guitar-chat',
520 connection: fetchServerSentEvents('/api/tanchat'),
521 tools,
522 byok,
523 byokProvider: () => toByokProvider(selectedProviderRef.current),
524 forwardedProps,
525 onCustomEvent: (eventType, data, context) => {
526 console.log(
527 `[CustomEvent] ${eventType}`,
528 data,
529 context.toolCallId ? `(tool call: ${context.toolCallId})` : '',
530 )
531 if (eventType === 'gemini.interactionId') {
532 const value = data as
533 | GeminiInteractionsCustomEventValue<'gemini.interactionId'>
534 | undefined
535 if (value?.interactionId) setInteractionId(value.interactionId)
536 }
537 },
538 })
539 const [input, setInput] = useState('')
540​
541 // Voice input: record from the mic, transcribe via /api/transcribe, then drop
542 // the text into the composer for the user to review/edit/send. (Text chat
543 // models don't accept raw audio; transcription is the path that works.)
544 // `onResult`'s `r` infers as `TranscriptionResult` from the hook (no explicit
545 // type arg needed — the generation hooks' result-type inference handles it).
546 // Surface voice-input failures (permission denied, recorder error,
547 // transcription error) to the user rather than only logging them — a silent
548 // mic button is the worst outcome.
549 const [recordError, setRecordError] = useState<string | null>(null)
550​
551 const { generate: transcribe, isLoading: isTranscribing } = useTranscription({
552 threadId: 'voice-input',
553 connection: fetchServerSentEvents('/api/transcribe'),
554 onResult: (r) => setInput((prev) => (prev ? `${prev} ${r.text}` : r.text)),
555 // A failed transcription (network/provider) is just as silent as a mic
556 // failure if only logged — surface it in the same banner below.
557 onError: (err) => {
558 console.error('[transcribe]', err)
559 setRecordError(
560 err instanceof Error ? err.message : 'Could not transcribe audio',
561 )
562 },
563 })
564 // Errors reach us by rejecting start()/stop(), so we handle them in the
565 // try/catch below — a single channel, not an additional `onError` callback.
566 const {
567 isRecording,
568 isSupported: micSupported,
569 start: startRecording,
570 stop: stopRecording,
571 } = useAudioRecorder()
572​
573 const handleMicToggle = async () => {
574 try {
575 if (isRecording) {
576 const rec = await stopRecording()
577 // Strip the `;codecs=...` parameter so the provider gets a clean type.
578 const mimeType = rec.mimeType.split(';')[0]
579 await transcribe({ audio: `data:${mimeType};base64,${rec.base64}` })
580 } else {
581 setRecordError(null)
582 await startRecording()
583 }
584 } catch (err) {
585 console.error('[audio-recorder]', err)
586 setRecordError(
587 err instanceof Error ? err.message : 'Could not record audio',
588 )
589 }
590 }
591​
592 /**
593 * Handle file selection for image attachment
594 */
595 const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
596 const files = e.target.files
597 if (!files || files.length === 0) return
598​
599 const newImages: Array<{
600 id: string
601 base64: string
602 mimeType: string
603 preview: string
604 }> = []
605​
606 for (const file of Array.from(files)) {
607 if (!file.type.startsWith('image/')) continue
608​
609 const base64 = await new Promise<string>((resolve) => {
610 const reader = new FileReader()
611 reader.onload = () => {
612 const result = reader.result as string
613 // Remove data URL prefix (e.g., "data:image/png;base64,")
614 resolve(result.split(',')[1])
615 }
616 reader.readAsDataURL(file)
617 })
618​
619 const preview = URL.createObjectURL(file)
620 newImages.push({
621 id: generateMessageId(),
622 base64,
623 mimeType: file.type, // Capture the actual mime type
624 preview,
625 })
626 }
627​
628 setAttachedImages((prev) => [...prev, ...newImages])
629​
630 // Reset the file input
631 if (fileInputRef.current) {
632 fileInputRef.current.value = ''
633 }
634 }
635​
636 /**
637 * Remove an attached image
638 */
639 const removeImage = (id: string) => {
640 setAttachedImages((prev) => {
641 const image = prev.find((img) => img.id === id)
642 if (image) {
643 URL.revokeObjectURL(image.preview)
644 }
645 return prev.filter((img) => img.id !== id)
646 })
647 }
648​
649 /**
650 * Send message with optional image attachments
651 */
652 const handleSendMessage = () => {
653 if (!input.trim() && attachedImages.length === 0) return
654​
655 if (attachedImages.length > 0) {
656 // Build multimodal content array
657 const contentParts: Array<ContentPart> = []
658​
659 // Add text if present
660 if (input.trim()) {
661 contentParts.push({ type: 'text', content: input.trim() })
662 }
663​
664 // Add images with mime type metadata
665 for (const img of attachedImages) {
666 contentParts.push({
667 type: 'image',
668 source: { type: 'data', value: img.base64, mimeType: img.mimeType },
669 })
670 }
671​
672 // Send with custom message ID
673 sendMessage({
674 content: contentParts,
675 id: generateMessageId(),
676 })
677​
678 // Clean up image previews
679 attachedImages.forEach((img) => URL.revokeObjectURL(img.preview))
680 setAttachedImages([])
681 } else {
682 // Simple text message
683 sendMessage(input.trim())
684 }
685​
686 setInput('')
687 }
688​
689 return (
690 <div className="flex h-[calc(100vh-72px)] bg-gray-900">
691 {/* Chat */}
692 <div className="w-full flex flex-col">
693 {/* Model selector bar */}
694 <div className="border-b border-orange-500/20 bg-gray-800 px-4 py-3">
695 <div className="flex items-end gap-3">
696 <div className="flex-1">
697 <label className="text-sm text-gray-400 mb-2 block">
698 Select Model:
699 </label>
700 <select
701 value={MODEL_OPTIONS.findIndex(
702 (opt) =>
703 opt.provider === selectedModel.provider &&
704 opt.model === selectedModel.model,
705 )}
706 onChange={(e) => {
707 const option = MODEL_OPTIONS[parseInt(e.target.value)]
708 setSelectedModel(option)
709 }}
710 disabled={isLoading}
711 className="w-full rounded-lg border border-orange-500/20 bg-gray-900 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-orange-500/50 disabled:opacity-50"
712 >
713 {MODEL_OPTIONS.map((option, index) => (
714 <option key={index} value={index}>
715 {option.label}
716 </option>
717 ))}
718 </select>
719 </div>
720 <ByokKeyDialog
721 open={keyDialog.open}
722 onOpenChange={(open) => setKeyDialog((s) => ({ ...s, open }))}
723 envStatus={envKeyStatus}
724 activeProvider={activeByokId}
725 highlightProvider={keyDialog.provider}
726 openRouter={{
727 onLogin: () => {
728 setOpenRouterError(null)
729 void startOpenRouterPkceLogin().catch((error: unknown) =>
730 setOpenRouterError(
731 error instanceof Error
732 ? error.message
733 : 'OpenRouter sign-in failed',
734 ),
735 )
736 },
737 completing: openRouterCompleting,
738 error: openRouterError,
739 }}
740 />
741 <Link
742 to="/interrupts"
743 className="flex items-center gap-2 px-4 py-2 rounded-lg bg-orange-500/10 border border-orange-500/20 text-orange-400 hover:bg-orange-500/20 transition-colors text-sm font-medium whitespace-nowrap"
744 >
745 <PauseCircle className="w-4 h-4" />
746 Interrupts Lab
747 </Link>
748 <Link
749 to="/generic-interrupts"
750 className="flex items-center gap-2 px-4 py-2 rounded-lg bg-orange-500/10 border border-orange-500/20 text-orange-400 hover:bg-orange-500/20 transition-colors text-sm font-medium whitespace-nowrap"
751 >
752 <Sparkles className="w-4 h-4" />
753 Generic Interrupts
754 </Link>
755 <Link
756 to="/generations/image"
757 className="flex items-center gap-2 px-4 py-2 rounded-lg bg-orange-500/10 border border-orange-500/20 text-orange-400 hover:bg-orange-500/20 transition-colors text-sm font-medium whitespace-nowrap"
758 >
759 <Image className="w-4 h-4" />
760 Image Gen
761 </Link>
762 </div>
763 </div>
764​
765 <Messages messages={messages} interrupts={interrupts} />
766​
767 {error && (
768 <div className="mx-4 mt-2 p-3 bg-red-500/10 border border-red-500/30 rounded-lg text-red-400 text-sm">
769 {error.message}
770 </div>
771 )}
772​
773 {recordError && (
774 <div className="mx-4 mt-2 p-3 bg-red-500/10 border border-red-500/30 rounded-lg text-red-400 text-sm flex items-center justify-between gap-2">
775 <span>Voice input error: {recordError}</span>
776 <button
777 onClick={() => setRecordError(null)}
778 className="text-red-300 hover:text-red-200"
779 aria-label="Dismiss"
780 >
781 <X className="w-4 h-4" />
782 </button>
783 </div>
784 )}
785​
786 <ChatInputArea>
787 <div className="space-y-3">
788 {isLoading && (
789 <div className="flex items-center justify-center">
790 <button
791 onClick={stop}
792 className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg text-sm font-medium transition-colors flex items-center gap-2"
793 >
794 <Square className="w-4 h-4 fill-current" />
795 Stop
796 </button>
797 </div>
798 )}
799​
800 {/* Image attachment preview */}
801 {attachedImages.length > 0 && (
802 <div className="flex flex-wrap gap-2 p-2 bg-gray-800/50 rounded-lg border border-orange-500/20">
803 {attachedImages.map((img) => (
804 <div key={img.id} className="relative group">
805 <img
806 src={img.preview}
807 alt="Attached"
808 className="w-16 h-16 object-cover rounded-lg border border-gray-700"
809 />
810 <button
811 onClick={() => removeImage(img.id)}
812 className="absolute -top-2 -right-2 w-5 h-5 bg-red-600 hover:bg-red-700 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
813 >
814 <X className="w-3 h-3 text-white" />
815 </button>
816 </div>
817 ))}
818 </div>
819 )}
820​
821 <div className="relative flex items-end gap-2">
822 {/* Hidden file input */}
823 <input
824 ref={fileInputRef}
825 type="file"
826 accept="image/*"
827 multiple
828 onChange={handleFileSelect}
829 className="hidden"
830 />
831​
832 {/* Image attachment button */}
833 <button
834 onClick={() => fileInputRef.current?.click()}
835 disabled={isLoading}
836 className="p-3 text-gray-400 hover:text-orange-500 disabled:text-gray-600 transition-colors focus:outline-none"
837 title="Attach image"
838 >
839 <ImagePlus className="w-5 h-5" />
840 </button>
841​
842 {/* Mic / voice-input button */}
843 {micSupported && (
844 <button
845 onClick={() => void handleMicToggle()}
846 disabled={isLoading || isTranscribing}
847 className={`p-3 transition-colors focus:outline-none disabled:text-gray-600 ${
848 isRecording
849 ? 'text-red-500 hover:text-red-400 animate-pulse'
850 : 'text-gray-400 hover:text-orange-500'
851 }`}
852 title={
853 isRecording
854 ? 'Stop and transcribe'
855 : isTranscribing
856 ? 'Transcribing…'
857 : 'Record voice input'
858 }
859 >
860 {isRecording ? (
861 <Square className="w-5 h-5" />
862 ) : (
863 <Mic className="w-5 h-5" />
864 )}
865 </button>
866 )}
867​
868 <div className="flex-1 relative">
869 <textarea
870 value={input}
871 onChange={(e) => setInput(e.target.value)}
872 placeholder={
873 attachedImages.length > 0
874 ? 'Add a message about your image(s)...'
875 : "Type something clever (or don't, we won't judge)..."
876 }
877 className="w-full rounded-lg border border-orange-500/20 bg-gray-800/50 pl-4 pr-12 py-3 text-sm text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-orange-500/50 focus:border-transparent resize-none overflow-hidden shadow-lg"
878 rows={1}
879 style={{ minHeight: '44px', maxHeight: '200px' }}
880 disabled={isLoading}
881 onInput={(e) => {
882 const target = e.target as HTMLTextAreaElement
883 target.style.height = 'auto'
884 target.style.height =
885 Math.min(target.scrollHeight, 200) + 'px'
886 }}
887 onKeyDown={(e) => {
888 if (
889 e.key === 'Enter' &&
890 !e.shiftKey &&
891 (input.trim() || attachedImages.length > 0)
892 ) {
893 e.preventDefault()
894 handleSendMessage()
895 }
896 }}
897 />
898 <button
899 onClick={handleSendMessage}
900 disabled={
901 (!input.trim() && attachedImages.length === 0) || isLoading
902 }
903 className="absolute right-2 top-1/2 -translate-y-1/2 p-2 text-orange-500 hover:text-orange-400 disabled:text-gray-500 transition-colors focus:outline-none"
904 >
905 <Send className="w-4 h-4" />
906 </button>
907 </div>
908 </div>
909 </div>
910 </ChatInputArea>
911 </div>
912 </div>
913 )
915​
916export const Route = createFileRoute('/')({
917 component: ChatPage,
918})