-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathapp-builder-router.ts
More file actions
263 lines (235 loc) · 9.14 KB
/
app-builder-router.ts
File metadata and controls
263 lines (235 loc) · 9.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import 'server-only';
import { baseProcedure, createTRPCRouter } from '@/lib/trpc/init';
import { generateApiToken } from '@/lib/tokens';
import * as appBuilderService from '@/lib/app-builder/app-builder-service';
import {
createProjectBaseSchema,
projectIdBaseSchema,
sendMessageBaseSchema,
getImageUploadUrlSchema,
prepareLegacySessionBaseSchema,
migrateToGitHubSchema,
} from '@/routers/app-builder/schemas';
import { getBalanceForUser } from '@/lib/user.balance';
import { MIN_BALANCE_FOR_APP_BUILDER } from '@/lib/app-builder/constants';
import { generateImageUploadUrl } from '@/lib/r2/cloud-agent-attachments';
export const appBuilderRouter = createTRPCRouter({
/**
* Create a new project without starting streaming
* Returns projectId for the client to navigate to before streaming
*/
createProject: baseProcedure.input(createProjectBaseSchema).mutation(async ({ ctx, input }) => {
const owner = { type: 'user' as const, id: ctx.user.id };
const authToken = generateApiToken(ctx.user);
return appBuilderService.createProject({
owner,
prompt: input.prompt,
model: input.model,
title: input.title,
createdByUserId: ctx.user.id,
authToken,
images: input.images,
template: input.template,
mode: input.mode,
});
}),
/**
* Get preview URL for a project
*/
getPreviewUrl: baseProcedure.input(projectIdBaseSchema).query(async ({ ctx, input }) => {
return appBuilderService.getPreviewUrl(input.projectId, { type: 'user', id: ctx.user.id });
}),
/**
* Triggers a build for the specified project
*/
triggerBuild: baseProcedure.input(projectIdBaseSchema).mutation(async ({ ctx, input }) => {
return appBuilderService.triggerProjectBuild(input.projectId, {
type: 'user',
id: ctx.user.id,
});
}),
/**
* Get a single project with all messages and session state
*/
getProject: baseProcedure.input(projectIdBaseSchema).query(async ({ ctx, input }) => {
const authToken = generateApiToken(ctx.user);
return appBuilderService.getProject(
input.projectId,
{ type: 'user', id: ctx.user.id },
authToken
);
}),
/**
* List all projects for the current user (personal context only)
*/
listProjects: baseProcedure.query(async ({ ctx }) => {
return appBuilderService.listProjects({ type: 'user', id: ctx.user.id });
}),
/**
* Deploy an App Builder project to production
*/
deployProject: baseProcedure.input(projectIdBaseSchema).mutation(async ({ ctx, input }) => {
const owner = { type: 'user' as const, id: ctx.user.id };
return appBuilderService.deployProject(input.projectId, owner, ctx.user.id);
}),
/**
* Check user's access level for App Builder.
*
* Returns:
* - accessLevel: 'full' | 'limited' | 'blocked'
* - 'full': User has enough balance ($1+) to use all models
* - 'limited': User can use free models only (balance below $1)
* - 'blocked': Reserved for future use (e.g., if we need to block users entirely)
*
* Currently returns only 'full' or 'limited' - UI supports 'blocked' for easy future switch.
*/
checkEligibility: baseProcedure.query(async ({ ctx }) => {
const { balance } = await getBalanceForUser(ctx.user);
// Determine access level based on balance
// Currently only 'full' or 'limited' - change to 'blocked' if we need to restrict entirely
const accessLevel: 'full' | 'limited' | 'blocked' =
balance >= MIN_BALANCE_FOR_APP_BUILDER ? 'full' : 'limited';
return {
balance,
minBalance: MIN_BALANCE_FOR_APP_BUILDER,
accessLevel,
// Keep isEligible for backwards compatibility (true if full access)
isEligible: accessLevel === 'full',
};
}),
/**
* Generate a read-only clone token for a project
* Returns the token, git URL, and expiration time
*/
generateCloneToken: baseProcedure.input(projectIdBaseSchema).mutation(async ({ ctx, input }) => {
const owner = { type: 'user' as const, id: ctx.user.id };
return appBuilderService.generateCloneToken(input.projectId, owner);
}),
/**
* Delete a project and all associated resources
*/
deleteProject: baseProcedure.input(projectIdBaseSchema).mutation(async ({ ctx, input }) => {
await appBuilderService.deleteProject(input.projectId, { type: 'user', id: ctx.user.id });
return { success: true };
}),
/**
* Interrupt a running App Builder session
* Stops any ongoing Claude agent execution for the project
*/
interruptSession: baseProcedure.input(projectIdBaseSchema).mutation(async ({ ctx, input }) => {
const owner = { type: 'user' as const, id: ctx.user.id };
const authToken = generateApiToken(ctx.user);
const result = await appBuilderService.interruptSession(input.projectId, owner, authToken);
return { success: result.success };
}),
/**
* Generate a presigned URL for uploading an image attachment
*/
getImageUploadUrl: baseProcedure
.input(getImageUploadUrlSchema)
.mutation(async ({ ctx, input }) => {
return generateImageUploadUrl({
service: 'app-builder',
userId: ctx.user.id,
messageUuid: input.messageUuid,
imageId: input.imageId,
contentType: input.contentType,
contentLength: input.contentLength,
});
}),
// ============================================================================
// WebSocket-based streaming mutations
// ============================================================================
/**
* Start a Cloud Agent session for an existing project using WebSocket API.
* Returns immediately with session info - client connects to WebSocket separately for events.
*
* This is a mutation (not subscription) - it triggers the action and returns immediately.
* The client should then:
* 1. Fetch a stream ticket from /api/cloud-agent/sessions/stream-ticket
* 2. Connect to the WebSocket URL with the ticket
*/
startSession: baseProcedure.input(projectIdBaseSchema).mutation(async ({ ctx, input }) => {
const owner = { type: 'user' as const, id: ctx.user.id };
const authToken = generateApiToken(ctx.user);
const result = await appBuilderService.startSessionForProject({
projectId: input.projectId,
owner,
authToken,
});
return { cloudAgentSessionId: result.cloudAgentSessionId };
}),
/**
* Send a message to an existing App Builder session using WebSocket API.
* Returns immediately with session info - client connects to WebSocket separately for events.
*
* This is a mutation (not subscription) - it triggers the action and returns immediately.
* The client should then:
* 1. Fetch a stream ticket from /api/cloud-agent/sessions/stream-ticket
* 2. Connect to the WebSocket URL with the ticket
*/
sendMessage: baseProcedure.input(sendMessageBaseSchema).mutation(async ({ ctx, input }) => {
const owner = { type: 'user' as const, id: ctx.user.id };
const authToken = generateApiToken(ctx.user);
const result = await appBuilderService.sendMessage({
projectId: input.projectId,
owner,
message: input.message,
authToken,
images: input.images,
model: input.model,
forceNewSession: input.forceNewSession,
});
return {
cloudAgentSessionId: result.cloudAgentSessionId,
workerVersion: result.workerVersion,
};
}),
/**
* Prepare a legacy session and initiate it for WebSocket-based streaming.
*
* Legacy sessions (created before the prepare flow) don't have session state stored
* in the Durable Object, which means WebSocket replay doesn't work. This endpoint:
* 1. Backfills the DO with session metadata
* 2. Initiates the session to execute the first message
*
* Returns the cloudAgentSessionId for WebSocket connection.
* The client should connect to the WebSocket to receive the response.
*/
prepareLegacySession: baseProcedure
.input(prepareLegacySessionBaseSchema)
.mutation(async ({ ctx, input }) => {
const owner = { type: 'user' as const, id: ctx.user.id };
const authToken = generateApiToken(ctx.user);
const result = await appBuilderService.prepareLegacySession(
input.projectId,
owner,
authToken,
input.model,
input.prompt
);
return { cloudAgentSessionId: result.cloudAgentSessionId };
}),
// ============================================================================
// GitHub Migration
// ============================================================================
/**
* Pre-flight check for GitHub migration.
*/
canMigrateToGitHub: baseProcedure.input(projectIdBaseSchema).query(async ({ ctx, input }) => {
const owner = { type: 'user' as const, id: ctx.user.id };
return appBuilderService.canMigrateToGitHub(input.projectId, owner);
}),
/**
* Migrate an App Builder project to GitHub.
*/
migrateToGitHub: baseProcedure.input(migrateToGitHubSchema).mutation(async ({ ctx, input }) => {
const owner = { type: 'user' as const, id: ctx.user.id };
return appBuilderService.migrateProjectToGitHub({
projectId: input.projectId,
owner,
userId: ctx.user.id,
repoFullName: input.repoFullName,
});
}),
});