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

index.tsx

916 lines34.2 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 connection: fetchServerSentEvents('/api/tanchat'),
520 tools,
521 byok,
522 byokProvider: () => toByokProvider(selectedProviderRef.current),
523 forwardedProps,
524 onCustomEvent: (eventType, data, context) => {
525 console.log(
526 `[CustomEvent] ${eventType}`,
527 data,
528 context.toolCallId ? `(tool call: ${context.toolCallId})` : '',
529 )
530 if (eventType === 'gemini.interactionId') {
531 const value = data as
532 | GeminiInteractionsCustomEventValue<'gemini.interactionId'>
533 | undefined
534 if (value?.interactionId) setInteractionId(value.interactionId)
535 }
536 },
537 })
538 const [input, setInput] = useState('')
539​
540 // Voice input: record from the mic, transcribe via /api/transcribe, then drop
541 // the text into the composer for the user to review/edit/send. (Text chat
542 // models don't accept raw audio; transcription is the path that works.)
543 // `onResult`'s `r` infers as `TranscriptionResult` from the hook (no explicit
544 // type arg needed — the generation hooks' result-type inference handles it).
545 // Surface voice-input failures (permission denied, recorder error,
546 // transcription error) to the user rather than only logging them — a silent
547 // mic button is the worst outcome.
548 const [recordError, setRecordError] = useState<string | null>(null)
549​
550 const { generate: transcribe, isLoading: isTranscribing } = useTranscription({
551 connection: fetchServerSentEvents('/api/transcribe'),
552 onResult: (r) => setInput((prev) => (prev ? `${prev} ${r.text}` : r.text)),
553 // A failed transcription (network/provider) is just as silent as a mic
554 // failure if only logged — surface it in the same banner below.
555 onError: (err) => {
556 console.error('[transcribe]', err)
557 setRecordError(
558 err instanceof Error ? err.message : 'Could not transcribe audio',
559 )
560 },
561 })
562 // Errors reach us by rejecting start()/stop(), so we handle them in the
563 // try/catch below — a single channel, not an additional `onError` callback.
564 const {
565 isRecording,
566 isSupported: micSupported,
567 start: startRecording,
568 stop: stopRecording,
569 } = useAudioRecorder()
570​
571 const handleMicToggle = async () => {
572 try {
573 if (isRecording) {
574 const rec = await stopRecording()
575 // Strip the `;codecs=...` parameter so the provider gets a clean type.
576 const mimeType = rec.mimeType.split(';')[0]
577 await transcribe({ audio: `data:${mimeType};base64,${rec.base64}` })
578 } else {
579 setRecordError(null)
580 await startRecording()
581 }
582 } catch (err) {
583 console.error('[audio-recorder]', err)
584 setRecordError(
585 err instanceof Error ? err.message : 'Could not record audio',
586 )
587 }
588 }
589​
590 /**
591 * Handle file selection for image attachment
592 */
593 const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
594 const files = e.target.files
595 if (!files || files.length === 0) return
596​
597 const newImages: Array<{
598 id: string
599 base64: string
600 mimeType: string
601 preview: string
602 }> = []
603​
604 for (const file of Array.from(files)) {
605 if (!file.type.startsWith('image/')) continue
606​
607 const base64 = await new Promise<string>((resolve) => {
608 const reader = new FileReader()
609 reader.onload = () => {
610 const result = reader.result as string
611 // Remove data URL prefix (e.g., "data:image/png;base64,")
612 resolve(result.split(',')[1])
613 }
614 reader.readAsDataURL(file)
615 })
616​
617 const preview = URL.createObjectURL(file)
618 newImages.push({
619 id: generateMessageId(),
620 base64,
621 mimeType: file.type, // Capture the actual mime type
622 preview,
623 })
624 }
625​
626 setAttachedImages((prev) => [...prev, ...newImages])
627​
628 // Reset the file input
629 if (fileInputRef.current) {
630 fileInputRef.current.value = ''
631 }
632 }
633​
634 /**
635 * Remove an attached image
636 */
637 const removeImage = (id: string) => {
638 setAttachedImages((prev) => {
639 const image = prev.find((img) => img.id === id)
640 if (image) {
641 URL.revokeObjectURL(image.preview)
642 }
643 return prev.filter((img) => img.id !== id)
644 })
645 }
646​
647 /**
648 * Send message with optional image attachments
649 */
650 const handleSendMessage = () => {
651 if (!input.trim() && attachedImages.length === 0) return
652​
653 if (attachedImages.length > 0) {
654 // Build multimodal content array
655 const contentParts: Array<ContentPart> = []
656​
657 // Add text if present
658 if (input.trim()) {
659 contentParts.push({ type: 'text', content: input.trim() })
660 }
661​
662 // Add images with mime type metadata
663 for (const img of attachedImages) {
664 contentParts.push({
665 type: 'image',
666 source: { type: 'data', value: img.base64, mimeType: img.mimeType },
667 })
668 }
669​
670 // Send with custom message ID
671 sendMessage({
672 content: contentParts,
673 id: generateMessageId(),
674 })
675​
676 // Clean up image previews
677 attachedImages.forEach((img) => URL.revokeObjectURL(img.preview))
678 setAttachedImages([])
679 } else {
680 // Simple text message
681 sendMessage(input.trim())
682 }
683​
684 setInput('')
685 }
686​
687 return (
688 <div className="flex h-[calc(100vh-72px)] bg-gray-900">
689 {/* Chat */}
690 <div className="w-full flex flex-col">
691 {/* Model selector bar */}
692 <div className="border-b border-orange-500/20 bg-gray-800 px-4 py-3">
693 <div className="flex items-end gap-3">
694 <div className="flex-1">
695 <label className="text-sm text-gray-400 mb-2 block">
696 Select Model:
697 </label>
698 <select
699 value={MODEL_OPTIONS.findIndex(
700 (opt) =>
701 opt.provider === selectedModel.provider &&
702 opt.model === selectedModel.model,
703 )}
704 onChange={(e) => {
705 const option = MODEL_OPTIONS[parseInt(e.target.value)]
706 setSelectedModel(option)
707 }}
708 disabled={isLoading}
709 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"
710 >
711 {MODEL_OPTIONS.map((option, index) => (
712 <option key={index} value={index}>
713 {option.label}
714 </option>
715 ))}
716 </select>
717 </div>
718 <ByokKeyDialog
719 open={keyDialog.open}
720 onOpenChange={(open) => setKeyDialog((s) => ({ ...s, open }))}
721 envStatus={envKeyStatus}
722 activeProvider={activeByokId}
723 highlightProvider={keyDialog.provider}
724 openRouter={{
725 onLogin: () => {
726 setOpenRouterError(null)
727 void startOpenRouterPkceLogin().catch((error: unknown) =>
728 setOpenRouterError(
729 error instanceof Error
730 ? error.message
731 : 'OpenRouter sign-in failed',
732 ),
733 )
734 },
735 completing: openRouterCompleting,
736 error: openRouterError,
737 }}
738 />
739 <Link
740 to="/interrupts"
741 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"
742 >
743 <PauseCircle className="w-4 h-4" />
744 Interrupts Lab
745 </Link>
746 <Link
747 to="/generic-interrupts"
748 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"
749 >
750 <Sparkles className="w-4 h-4" />
751 Generic Interrupts
752 </Link>
753 <Link
754 to="/generations/image"
755 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"
756 >
757 <Image className="w-4 h-4" />
758 Image Gen
759 </Link>
760 </div>
761 </div>
762​
763 <Messages messages={messages} interrupts={interrupts} />
764​
765 {error && (
766 <div className="mx-4 mt-2 p-3 bg-red-500/10 border border-red-500/30 rounded-lg text-red-400 text-sm">
767 {error.message}
768 </div>
769 )}
770​
771 {recordError && (
772 <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">
773 <span>Voice input error: {recordError}</span>
774 <button
775 onClick={() => setRecordError(null)}
776 className="text-red-300 hover:text-red-200"
777 aria-label="Dismiss"
778 >
779 <X className="w-4 h-4" />
780 </button>
781 </div>
782 )}
783​
784 <ChatInputArea>
785 <div className="space-y-3">
786 {isLoading && (
787 <div className="flex items-center justify-center">
788 <button
789 onClick={stop}
790 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"
791 >
792 <Square className="w-4 h-4 fill-current" />
793 Stop
794 </button>
795 </div>
796 )}
797​
798 {/* Image attachment preview */}
799 {attachedImages.length > 0 && (
800 <div className="flex flex-wrap gap-2 p-2 bg-gray-800/50 rounded-lg border border-orange-500/20">
801 {attachedImages.map((img) => (
802 <div key={img.id} className="relative group">
803 <img
804 src={img.preview}
805 alt="Attached"
806 className="w-16 h-16 object-cover rounded-lg border border-gray-700"
807 />
808 <button
809 onClick={() => removeImage(img.id)}
810 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"
811 >
812 <X className="w-3 h-3 text-white" />
813 </button>
814 </div>
815 ))}
816 </div>
817 )}
818​
819 <div className="relative flex items-end gap-2">
820 {/* Hidden file input */}
821 <input
822 ref={fileInputRef}
823 type="file"
824 accept="image/*"
825 multiple
826 onChange={handleFileSelect}
827 className="hidden"
828 />
829​
830 {/* Image attachment button */}
831 <button
832 onClick={() => fileInputRef.current?.click()}
833 disabled={isLoading}
834 className="p-3 text-gray-400 hover:text-orange-500 disabled:text-gray-600 transition-colors focus:outline-none"
835 title="Attach image"
836 >
837 <ImagePlus className="w-5 h-5" />
838 </button>
839​
840 {/* Mic / voice-input button */}
841 {micSupported && (
842 <button
843 onClick={() => void handleMicToggle()}
844 disabled={isLoading || isTranscribing}
845 className={`p-3 transition-colors focus:outline-none disabled:text-gray-600 ${
846 isRecording
847 ? 'text-red-500 hover:text-red-400 animate-pulse'
848 : 'text-gray-400 hover:text-orange-500'
849 }`}
850 title={
851 isRecording
852 ? 'Stop and transcribe'
853 : isTranscribing
854 ? 'Transcribing…'
855 : 'Record voice input'
856 }
857 >
858 {isRecording ? (
859 <Square className="w-5 h-5" />
860 ) : (
861 <Mic className="w-5 h-5" />
862 )}
863 </button>
864 )}
865​
866 <div className="flex-1 relative">
867 <textarea
868 value={input}
869 onChange={(e) => setInput(e.target.value)}
870 placeholder={
871 attachedImages.length > 0
872 ? 'Add a message about your image(s)...'
873 : "Type something clever (or don't, we won't judge)..."
874 }
875 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"
876 rows={1}
877 style={{ minHeight: '44px', maxHeight: '200px' }}
878 disabled={isLoading}
879 onInput={(e) => {
880 const target = e.target as HTMLTextAreaElement
881 target.style.height = 'auto'
882 target.style.height =
883 Math.min(target.scrollHeight, 200) + 'px'
884 }}
885 onKeyDown={(e) => {
886 if (
887 e.key === 'Enter' &&
888 !e.shiftKey &&
889 (input.trim() || attachedImages.length > 0)
890 ) {
891 e.preventDefault()
892 handleSendMessage()
893 }
894 }}
895 />
896 <button
897 onClick={handleSendMessage}
898 disabled={
899 (!input.trim() && attachedImages.length === 0) || isLoading
900 }
901 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"
902 >
903 <Send className="w-4 h-4" />
904 </button>
905 </div>
906 </div>
907 </div>
908 </ChatInputArea>
909 </div>
910 </div>
911 )
913​
914export const Route = createFileRoute('/')({
915 component: ChatPage,
916})