Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 toServerSentEventsResponse,
6} from '@tanstack/ai'
7import { reconstructChat, withPersistence } from '@tanstack/ai-persistence'
8import { withLocks } from '@tanstack/ai/locks'
9import { withSandbox } from '@tanstack/ai-sandbox'
10import {
11 APP_STUDIO_SYSTEM_PROMPT,
12 buildAppStudioAdapter,
13 buildAppStudioSandbox,
14 makeExposePreviewTool,
15 missingAppStudioEnv,
16 tanstackStartRecipe,
17} from '../lib/app-studio'
18import {
19 appStudioInstances,
20 appStudioLocks,
21 appStudioSnapshots,
22} from '../lib/app-studio-store'
23
24function jsonError(status: number, error: string): Response {
25 return new Response(JSON.stringify({ error }), {
26 status,
27 statusText: error.slice(0, 64),
28 headers: { 'content-type': 'application/json' },
29 })
30}
31
32export const Route = createFileRoute('/api/app-studio')({
33 server: {
34 handlers: {
35 POST: async ({ request }) => {
36 const missing = missingAppStudioEnv()
37 if (missing.length > 0) {
38 return jsonError(
39 500,
40 `Missing required env: ${missing.join(', ')}. Set it and restart the dev server.`,
41 )
42 }
43
44 let params: Awaited<ReturnType<typeof chatParamsFromRequestBody>>
45 try {
46 params = await chatParamsFromRequestBody(await request.json())
47 } catch {
48 return jsonError(400, 'invalid JSON body')
49 }
50 const snapshots = appStudioSnapshots()
51 const instances = appStudioInstances()
52 const locks = appStudioLocks()
53 const sandbox = buildAppStudioSandbox()
54 const abortController = new AbortController()
55 request.signal.addEventListener('abort', () => abortController.abort())
56
57 const stream = chat({
58 adapter: buildAppStudioAdapter(),
59 messages: params.messages,
60 threadId: params.threadId,
61 runId: params.runId,
62 systemPrompts: [APP_STUDIO_SYSTEM_PROMPT],
63 tools: [
64 tanstackStartRecipe,
65 makeExposePreviewTool(sandbox, params.threadId, {
66 store: instances,
67 locks,
68 }),
69 ],
70 middleware: [
71 withPersistence(snapshots.persistence),
72 withLocks(locks),
73 withSandbox(sandbox, { instances, snapshots }),
74 ],
75 abortController,
76 })
77
78 return toServerSentEventsResponse(stream, { abortController })
79 },
80 GET: ({ request }) => {
81 return reconstructChat(appStudioSnapshots().persistence, request, {
82 authorize: async (threadId) => threadId.length > 0,
83 })
84 },
85 },
86 },
87})