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

api.app-studio-fork.ts

57 lines1.8 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { buildAppStudioSandbox } from '../lib/app-studio'
3import { forkStudioThreads } from '../lib/app-studio-fork'
4import {
5 appStudioInstances,
6 appStudioLocks,
7 appStudioSnapshots,
8} from '../lib/app-studio-store'
9​
10function json(status: number, body: unknown): Response {
11 return new Response(JSON.stringify(body), {
12 status,
13 headers: { 'content-type': 'application/json' },
14 })
16​
17export const Route = createFileRoute('/api/app-studio-fork')({
18 server: {
19 handlers: {
20 POST: async ({ request }) => {
21 let body: unknown
22 try {
23 body = await request.json()
24 } catch {
25 return json(400, { error: 'invalid JSON body' })
26 }
27 if (body === null || typeof body !== 'object') {
28 return json(400, { error: 'invalid JSON body' })
29 }
30 const threadId = Reflect.get(body, 'threadId')
31 const label = Reflect.get(body, 'label')
32 const countValue = Reflect.get(body, 'count')
33 if (typeof threadId !== 'string' || threadId.length === 0) {
34 return json(400, { error: 'threadId is required' })
35 }
36 const count = countValue === 2 ? 2 : 1
37 try {
38 const result = await forkStudioThreads({
39 snapshots: appStudioSnapshots(),
40 threadId,
41 runId: `studio-fork-${crypto.randomUUID()}`,
42 count,
43 sandbox: buildAppStudioSandbox(),
44 instances: appStudioInstances(),
45 locks: appStudioLocks(),
46 ...(typeof label === 'string' && label.length > 0 ? { label } : {}),
47 })
48 return json(200, result)
49 } catch (error) {
50 return json(409, {
51 error: error instanceof Error ? error.message : 'fork failed',
52 })
53 }
54 },
55 },
56 },
57})