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

app-studio.tsx

749 lines21.0 KB

1import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
4import { GitBranch, Play } from 'lucide-react'
5import ReactMarkdown from 'react-markdown'
6import rehypeHighlight from 'rehype-highlight'
7import rehypeRaw from 'rehype-raw'
8import rehypeSanitize from 'rehype-sanitize'
9import remarkGfm from 'remark-gfm'
10import {
11 errorMessageFromBody,
12 previewUrlFrom,
13 previewUrlFromText,
14 threadIdsFromForkBody,
15 variantPrompt,
16} from '../lib/app-studio-helpers'
17import type { UIMessage } from '@tanstack/ai-react'
18import './app-studio.css'
19​
20export const Route = createFileRoute('/app-studio')({
21 component: AppStudioPage,
22 head: () => ({
23 meta: [{ title: 'App Studio | TanStack AI' }],
24 }),
25})
26​
27const connection = fetchServerSentEvents('/api/app-studio')
28const THREADS_KEY = 'app-studio:threads'
29const EMPTY_PREVIEW_URLS: Array<string> = []
30​
31interface StudioThread {
32 id: string
33 title: string
34 parentId: string | null
35 variant?: 'A' | 'B'
36 inheritedPreviewUrls?: Array<string>
38​
39interface CompareState {
40 leftId: string
41 rightId: string
42 prompt: string
43 inheritedPreviewUrls: Array<string>
45​
46function loadThreads(): Array<StudioThread> {
47 if (typeof window === 'undefined') return []
48 try {
49 const raw = window.localStorage.getItem(THREADS_KEY)
50 const parsed: unknown = raw ? JSON.parse(raw) : null
51 if (!Array.isArray(parsed)) return []
52 return parsed.flatMap((item) => {
53 if (item === null || typeof item !== 'object') return []
54 const id = Reflect.get(item, 'id')
55 const title = Reflect.get(item, 'title')
56 const parentId = Reflect.get(item, 'parentId')
57 const variant = Reflect.get(item, 'variant')
58 const inherited = Reflect.get(item, 'inheritedPreviewUrls')
59 if (typeof id !== 'string' || typeof title !== 'string') return []
60 const inheritedPreviewUrls = Array.isArray(inherited)
61 ? inherited.filter((url) => typeof url === 'string')
62 : []
63 return [
64 {
65 id,
66 title,
67 parentId: typeof parentId === 'string' ? parentId : null,
68 ...(variant === 'A' || variant === 'B' ? { variant } : {}),
69 ...(inheritedPreviewUrls.length > 0 ? { inheritedPreviewUrls } : {}),
70 },
71 ]
72 })
73 } catch {
74 return []
75 }
77​
78function newThread(parentId: string | null = null): StudioThread {
79 return {
80 id: `studio-${crypto.randomUUID()}`,
81 title: parentId ? 'Fork' : 'New app',
82 parentId,
83 }
85​
86function ThreadNav({
87 threads,
88 activeId,
89 compare,
90 onSelect,
91 horizontal = false,
92}: {
93 threads: Array<StudioThread>
94 activeId: string
95 compare: CompareState | null
96 onSelect: (id: string) => void
97 horizontal?: boolean
98}) {
99 return (
100 <nav
101 aria-label="App chats"
102 className={
103 horizontal ? 'min-w-0 flex-1 overflow-x-auto' : 'flex-1 overflow-y-auto'
104 }
105 >
106 <ul
107 role="list"
108 className={horizontal ? 'flex gap-1' : 'flex flex-col gap-1'}
109 >
110 {threads.map((thread) => {
111 const isActive =
112 thread.id === activeId ||
113 thread.id === compare?.leftId ||
114 thread.id === compare?.rightId
115 return (
116 <li
117 key={thread.id}
118 className={
119 horizontal ? 'shrink-0' : thread.parentId ? 'ml-3' : ''
120 }
121 >
122 <button
123 type="button"
124 className={`app-studio-thread ${
125 horizontal ? 'app-studio-thread-horizontal' : ''
126 } ${isActive ? 'app-studio-thread-active' : ''}`}
127 aria-current={isActive ? 'page' : undefined}
128 onClick={() => onSelect(thread.id)}
129 >
130 {thread.title}
131 </button>
132 </li>
133 )
134 })}
135 </ul>
136 </nav>
137 )
139​
140function collectPreviewUrls(messages: Array<UIMessage>): Set<string> {
141 const urls = new Set<string>()
142 for (const message of messages) {
143 for (const part of message.parts) {
144 if (part.type === 'tool-call' && part.name === 'exposePreview') {
145 const url = previewUrlFrom(part.output)
146 if (url) urls.add(url)
147 }
148 if (part.type === 'text' && part.content) {
149 const url = previewUrlFromText(part.content)
150 if (url) urls.add(url)
151 }
152 }
153 }
154 return urls
156​
157function latestPreview(
158 messages: Array<UIMessage>,
159 skip: ReadonlySet<string> = new Set(),
160): string | null {
161 for (let index = messages.length - 1; index >= 0; index--) {
162 const message = messages[index]
163 if (!message) continue
164 for (const part of message.parts) {
165 if (part.type === 'tool-call' && part.name === 'exposePreview') {
166 const url = previewUrlFrom(part.output)
167 if (url && !skip.has(url)) return url
168 }
169 if (part.type === 'text' && part.content) {
170 const url = previewUrlFromText(part.content)
171 if (url && !skip.has(url)) return url
172 }
173 }
174 }
175 return null
177​
178function hasUserText(messages: Array<UIMessage>, text: string): boolean {
179 return messages.some(
180 (message) =>
181 message.role === 'user' &&
182 message.parts.some(
183 (part) => part.type === 'text' && part.content === text,
184 ),
185 )
187​
188function AppStudioPage() {
189 const [threads, setThreads] = useState<Array<StudioThread>>([])
190 const [activeId, setActiveId] = useState<string | null>(null)
191 const [hydrated, setHydrated] = useState(false)
192 const [compare, setCompare] = useState<CompareState | null>(null)
193 const [wantCompare, setWantCompare] = useState(false)
194 const [busy, setBusy] = useState(false)
195 const [error, setError] = useState<string | null>(null)
196​
197 useEffect(() => {
198 const loaded = loadThreads()
199 if (loaded.length === 0) {
200 const first = newThread()
201 setThreads([first])
202 setActiveId(first.id)
203 } else {
204 setThreads(loaded)
205 setActiveId(loaded[0]?.id ?? null)
206 }
207 setHydrated(true)
208 }, [])
209​
210 useEffect(() => {
211 if (!hydrated) return
212 window.localStorage.setItem(THREADS_KEY, JSON.stringify(threads))
213 }, [threads, hydrated])
214​
215 const createRoot = () => {
216 const thread = newThread()
217 setCompare(null)
218 setWantCompare(false)
219 setError(null)
220 setThreads((prev) => [thread, ...prev])
221 setActiveId(thread.id)
222 }
223​
224 const titleFrom = useCallback((id: string, title: string) => {
225 setThreads((prev) => {
226 let changed = false
227 const next = prev.map((thread) => {
228 if (
229 thread.id === id &&
230 (thread.title === 'New app' || thread.title === 'Fork')
231 ) {
232 changed = true
233 return { ...thread, title }
234 }
235 return thread
236 })
237 return changed ? next : prev
238 })
239 }, [])
240​
241 const forkOne = async (inheritedPreviewUrls: Array<string>) => {
242 if (!activeId || busy) return
243 setBusy(true)
244 setError(null)
245 try {
246 const response = await fetch('/api/app-studio-fork', {
247 method: 'POST',
248 headers: { 'content-type': 'application/json' },
249 body: JSON.stringify({ threadId: activeId, label: 'continue' }),
250 })
251 const body: unknown = await response.json()
252 if (!response.ok) {
253 throw new Error(errorMessageFromBody(body, 'Could not fork this chat'))
254 }
255 const [nextId] = threadIdsFromForkBody(body)
256 if (nextId === undefined) {
257 throw new Error('Could not fork this chat')
258 }
259 const child: StudioThread = {
260 id: nextId,
261 title: 'Fork',
262 parentId: activeId,
263 ...(inheritedPreviewUrls.length > 0 ? { inheritedPreviewUrls } : {}),
264 }
265 setThreads((prev) => [child, ...prev])
266 setCompare(null)
267 setActiveId(nextId)
268 } catch (cause) {
269 setError(
270 cause instanceof Error ? cause.message : 'Could not fork this chat',
271 )
272 } finally {
273 setBusy(false)
274 }
275 }
276​
277 const startCompare = async (
278 prompt: string,
279 inheritedPreviewUrls: Array<string>,
280 ) => {
281 if (!activeId || busy) return
282 setBusy(true)
283 setError(null)
284 try {
285 const response = await fetch('/api/app-studio-fork', {
286 method: 'POST',
287 headers: { 'content-type': 'application/json' },
288 body: JSON.stringify({
289 threadId: activeId,
290 count: 2,
291 label: 'compare',
292 }),
293 })
294 const body: unknown = await response.json()
295 if (!response.ok) {
296 throw new Error(
297 errorMessageFromBody(body, 'Could not start the comparison'),
298 )
299 }
300 const ids = threadIdsFromForkBody(body)
301 const leftId = ids[0]
302 const rightId = ids[1]
303 if (leftId === undefined || rightId === undefined) {
304 throw new Error('Could not start the comparison')
305 }
306 const inherited =
307 inheritedPreviewUrls.length > 0 ? { inheritedPreviewUrls } : {}
308 setThreads((prev) => [
309 {
310 id: leftId,
311 title: 'Variant A',
312 parentId: activeId,
313 variant: 'A',
314 ...inherited,
315 },
316 {
317 id: rightId,
318 title: 'Variant B',
319 parentId: activeId,
320 variant: 'B',
321 ...inherited,
322 },
323 ...prev,
324 ])
325 setCompare({ leftId, rightId, prompt, inheritedPreviewUrls })
326 setWantCompare(false)
327 } catch (cause) {
328 setError(
329 cause instanceof Error
330 ? cause.message
331 : 'Could not start the comparison',
332 )
333 } finally {
334 setBusy(false)
335 }
336 }
337​
338 const keepVariant = (id: string) => {
339 setActiveId(id)
340 setCompare(null)
341 }
342​
343 const onActiveTitle = useCallback(
344 (title: string) => {
345 if (activeId === null) return
346 titleFrom(activeId, title)
347 },
348 [activeId, titleFrom],
349 )
350​
351 if (!hydrated || !activeId) {
352 return (
353 <div className="app-studio flex h-[calc(100vh-4.5rem)] items-center justify-center text-sm">
354 <p role="status">Loading chats.</p>
355 </div>
356 )
357 }
358​
359 const selectThread = (id: string) => {
360 setCompare(null)
361 setWantCompare(false)
362 setActiveId(id)
363 }
364​
365 return (
366 <div className="app-studio flex h-[calc(100vh-4.5rem)]">
367 <aside className="hidden lg:flex w-64 shrink-0 border-r app-studio-rule p-3 flex-col gap-3">
368 <div className="flex items-center gap-3 px-1 pt-1">
369 <img
370 src="/brand/logos/tanstack-emblem-cream.svg"
371 alt=""
372 width={28}
373 height={36}
374 />
375 <div>
376 <p className="app-studio-kicker">TanStack AI</p>
377 <p className="app-studio-brand">App Studio</p>
378 </div>
379 </div>
380 <button
381 type="button"
382 className="app-studio-btn-primary justify-center"
383 onClick={createRoot}
384 >
385 Start new app
386 </button>
387 <ThreadNav
388 threads={threads}
389 activeId={activeId}
390 compare={compare}
391 onSelect={selectThread}
392 />
393 </aside>
394​
395 <main className="flex-1 min-w-0 flex flex-col">
396 <div className="lg:hidden border-b app-studio-rule p-2 flex items-center gap-2 overflow-x-auto">
397 <button
398 type="button"
399 className="app-studio-btn-primary shrink-0"
400 onClick={createRoot}
401 >
402 Start new app
403 </button>
404 <ThreadNav
405 threads={threads}
406 activeId={activeId}
407 compare={compare}
408 onSelect={selectThread}
409 horizontal
410 />
411 </div>
412 <header className="border-b app-studio-rule px-4 py-3">
413 <p className="app-studio-kicker">TanStack AI</p>
414 <h1 className="app-studio-title">App Studio</h1>
415 <p className="app-studio-lede mt-1">
416 Describe an app. The agent builds it in a sandbox and shows a
417 preview. Fork the chat to continue, or compare two directions and
418 keep one. Needs Docker and <code>XAI_API_KEY</code>.
419 </p>
420 </header>
421​
422 {error ? (
423 <p role="alert" className="app-studio-alert mx-4 mt-3">
424 {error}
425 </p>
426 ) : null}
427​
428 {compare ? (
429 <div className="flex-1 min-h-0 grid grid-cols-1 lg:grid-cols-2">
430 <ComparePane
431 threadId={compare.leftId}
432 label="A"
433 prompt={compare.prompt}
434 inheritedPreviewUrls={compare.inheritedPreviewUrls}
435 onKeep={() => keepVariant(compare.leftId)}
436 />
437 <ComparePane
438 threadId={compare.rightId}
439 label="B"
440 prompt={compare.prompt}
441 inheritedPreviewUrls={compare.inheritedPreviewUrls}
442 onKeep={() => keepVariant(compare.rightId)}
443 />
444 </div>
445 ) : (
446 <StudioPane
447 key={activeId}
448 threadId={activeId}
449 inheritedPreviewUrls={
450 threads.find((thread) => thread.id === activeId)
451 ?.inheritedPreviewUrls ?? EMPTY_PREVIEW_URLS
452 }
453 wantCompare={wantCompare}
454 setWantCompare={setWantCompare}
455 busy={busy}
456 onFork={forkOne}
457 onCompare={startCompare}
458 onTitle={onActiveTitle}
459 />
460 )}
461 </main>
462 </div>
463 )
465​
466function StudioPane({
467 threadId,
468 inheritedPreviewUrls,
469 wantCompare,
470 setWantCompare,
471 busy,
472 onFork,
473 onCompare,
474 onTitle,
475}: {
476 threadId: string
477 inheritedPreviewUrls: Array<string>
478 wantCompare: boolean
479 setWantCompare: (value: boolean) => void
480 busy: boolean
481 onFork: (inheritedPreviewUrls: Array<string>) => void
482 onCompare: (
483 prompt: string,
484 inheritedPreviewUrls: Array<string>,
485 ) => Promise<void>
486 onTitle: (title: string) => void
487}) {
488 const {
489 messages,
490 sendMessage,
491 isLoading,
492 error: chatError,
493 } = useChat({
494 threadId,
495 connection,
496 persistence: true,
497 })
498 const [input, setInput] = useState('')
499 const preview = useMemo(
500 () => latestPreview(messages, new Set(inheritedPreviewUrls)),
501 [inheritedPreviewUrls, messages],
502 )
503 const hasBuiltApp = messages.some(
504 (message) =>
505 message.role === 'assistant' &&
506 message.parts.some(
507 (part) =>
508 (part.type === 'text' && Boolean(part.content)) ||
509 part.type === 'tool-call',
510 ),
511 )
512​
513 useEffect(() => {
514 const firstUser = messages.find((message) => message.role === 'user')
515 const part = firstUser?.parts.find((item) => item.type === 'text')
516 if (part && 'content' in part && typeof part.content === 'string') {
517 onTitle(part.content.slice(0, 40))
518 }
519 }, [messages, onTitle])
520​
521 const send = async () => {
522 const trimmed = input.trim()
523 if (isLoading || busy) return
524 if (wantCompare) {
525 if (!hasBuiltApp) return
526 setInput('')
527 await onCompare(trimmed, [...collectPreviewUrls(messages)])
528 return
529 }
530 if (!trimmed) return
531 setInput('')
532 void sendMessage(trimmed)
533 }
534​
535 return (
536 <>
537 <div className="flex-1 min-h-0 grid grid-cols-1 lg:grid-cols-2">
538 <MessageList messages={messages} isLoading={isLoading} />
539 <PreviewFrame url={preview} title="App preview" />
540 </div>
541 <form
542 className="border-t app-studio-rule p-3 flex flex-col gap-2"
543 onSubmit={(event) => {
544 event.preventDefault()
545 void send()
546 }}
547 >
548 <label htmlFor="studio-prompt" className="text-sm">
549 {wantCompare ? 'Change to compare' : 'What to build'}
550 </label>
551 {chatError ? (
552 <p role="alert" className="app-studio-alert">
553 {chatError.message}
554 </p>
555 ) : null}
556 <textarea
557 id="studio-prompt"
558 className="app-studio-input"
559 rows={3}
560 value={input}
561 onChange={(event) => setInput(event.target.value)}
562 placeholder={
563 wantCompare
564 ? 'Make the board denser, or leave empty to compare two looks.'
565 : 'Build a kanban board with localStorage, then show the preview.'
566 }
567 />
568 <div className="flex flex-wrap items-center gap-3">
569 <label className="flex items-center gap-2 text-sm">
570 <input
571 type="checkbox"
572 checked={wantCompare}
573 disabled={!hasBuiltApp || busy || isLoading}
574 onChange={(event) => setWantCompare(event.target.checked)}
575 />
576 Compare two directions
577 </label>
578 <button
579 type="button"
580 className="app-studio-btn-secondary"
581 onClick={() => void onFork([...collectPreviewUrls(messages)])}
582 disabled={!hasBuiltApp || busy || isLoading}
583 >
584 <GitBranch className="w-4 h-4" aria-hidden="true" />
585 Fork chat
586 </button>
587 <button
588 type="submit"
589 className="app-studio-btn-primary"
590 disabled={
591 busy || isLoading || (!wantCompare && input.trim() === '')
592 }
593 >
594 <Play className="w-4 h-4" aria-hidden="true" />
595 {wantCompare ? 'Compare both' : 'Build'}
596 </button>
597 </div>
598 {!hasBuiltApp ? (
599 <p className="app-studio-hint">
600 Build the app first. Then you can fork the chat or compare two
601 directions.
602 </p>
603 ) : null}
604 </form>
605 </>
606 )
608​
609function ComparePane({
610 threadId,
611 label,
612 prompt,
613 inheritedPreviewUrls,
614 onKeep,
615}: {
616 threadId: string
617 label: 'A' | 'B'
618 prompt: string
619 inheritedPreviewUrls: Array<string>
620 onKeep: () => void
621}) {
622 const {
623 messages,
624 sendMessage,
625 isLoading,
626 error: chatError,
627 } = useChat({
628 threadId,
629 connection,
630 persistence: true,
631 })
632 const preview = useMemo(
633 () => latestPreview(messages, new Set(inheritedPreviewUrls)),
634 [inheritedPreviewUrls, messages],
635 )
636 const expected = variantPrompt(prompt, label)
637 const [waitedForHydrate, setWaitedForHydrate] = useState(false)
638 const sentVariant = useRef(false)
639​
640 useEffect(() => {
641 const timer = window.setTimeout(() => setWaitedForHydrate(true), 3000)
642 return () => window.clearTimeout(timer)
643 }, [])
644​
645 useEffect(() => {
646 if (sentVariant.current) return
647 if (hasUserText(messages, expected)) {
648 sentVariant.current = true
649 return
650 }
651 if (messages.length === 0 && !waitedForHydrate) return
652 sentVariant.current = true
653 void sendMessage(expected)
654 }, [expected, messages, sendMessage, waitedForHydrate])
655​
656 return (
657 <div className="min-h-0 flex flex-col border-t lg:border-t-0 lg:border-l app-studio-rule first:border-l-0">
658 <div className="flex items-center justify-between border-b app-studio-rule px-3 py-2">
659 <h2 className="text-sm font-medium">Variant {label}</h2>
660 <button
661 type="button"
662 className="app-studio-btn-primary"
663 onClick={onKeep}
664 disabled={isLoading}
665 >
666 Keep variant {label}
667 </button>
668 </div>
669 {chatError ? (
670 <p role="alert" className="app-studio-alert mx-3 mt-2">
671 {chatError.message}
672 </p>
673 ) : null}
674 <div className="flex-1 min-h-0 grid grid-rows-[minmax(7rem,28%)_minmax(0,1fr)]">
675 <MessageList messages={messages} isLoading={isLoading} />
676 <PreviewFrame url={preview} title={`Variant ${label} preview`} />
677 </div>
678 </div>
679 )
681​
682function MessageList({
683 messages,
684 isLoading,
685}: {
686 messages: Array<UIMessage>
687 isLoading: boolean
688}) {
689 const [node, setNode] = useState<HTMLDivElement | null>(null)
690 useEffect(() => {
691 node?.scrollTo({ top: node.scrollHeight })
692 }, [messages, node])
693​
694 return (
695 <div ref={setNode} className="overflow-y-auto p-3 text-sm space-y-3">
696 {messages.map((message) => (
697 <div key={message.id} className="space-y-2">
698 <div className="app-studio-role">{message.role}</div>
699 {message.parts.map((part, index) => {
700 const key = `${message.id}-${index}`
701 if (part.type === 'text' && part.content) {
702 return (
703 <div key={key} className="prose prose-invert max-w-none">
704 <ReactMarkdown
705 remarkPlugins={[remarkGfm]}
706 rehypePlugins={[rehypeRaw, rehypeSanitize, rehypeHighlight]}
707 >
708 {part.content}
709 </ReactMarkdown>
710 </div>
711 )
712 }
713 if (part.type === 'tool-call') {
714 return (
715 <div key={key} className="app-studio-tool">
716 {part.name}
717 </div>
718 )
719 }
720 return null
721 })}
722 </div>
723 ))}
724 {isLoading ? (
725 <p role="status" className="app-studio-status">
726 The agent is working in the sandbox.
727 </p>
728 ) : null}
729 </div>
730 )
732​
733function PreviewFrame({ url, title }: { url: string | null; title: string }) {
734 if (!url) {
735 return (
736 <div className="app-studio-preview-empty">
737 Preview appears here after the app is running.
738 </div>
739 )
740 }
741 return (
742 <iframe
743 title={title}
744 src={url}
745 sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
746 className="app-studio-preview"
747 />
748 )