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

app-studio.tsx

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