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

index.tsx

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