-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
702 lines (589 loc) · 23.1 KB
/
Copy pathmain.py
File metadata and controls
702 lines (589 loc) · 23.1 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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel
import asyncio
import json
import os
import io
import zipfile
import traceback
import uuid
from fastapi import Depends
from sqlalchemy import select, delete
from agent.service import agent_service
from auth.router import router
from auth.schema import ProjectsListResponse
from db.models import User, Chat, Message
from auth.dependencies import get_current_user
from sqlalchemy.ext.asyncio import AsyncSession
from db.base import get_db, AsyncSessionLocal
from auth.utils import decode_token
from utils.crypto import decrypt_api_key
app = FastAPI(title="Buildable")
origins = [
"http://localhost:3000",
]
# Add production frontend URL from env (e.g. https://buildable.vercel.app)
_prod_origin = os.getenv("FRONTEND_URL")
if _prod_origin:
origins.append(_prod_origin)
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(router=router)
active_streams: dict[str, asyncio.Queue] = {}
active_runs: dict[str, asyncio.Task] = {}
class ChatPayload(BaseModel):
prompt: str
class ChatMessagePayload(BaseModel):
prompt: str
class ProjectFilesResponse(BaseModel):
files: list[str]
sandbox_active: bool
@app.get("/")
async def get_health():
return {"message": "Welome", "status": "Healthy"}
@app.get("/chats/{id}/messages")
async def get_chat_messages(
id: str,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db)
):
"""Get message history for a chat"""
# Verify the chat exists and belongs to the user
result = await db.execute(select(Chat).where(Chat.id == id))
chat = result.scalar_one_or_none()
if not chat:
raise HTTPException(status_code=404, detail="Chat not found")
if chat.user_id != current_user.id:
raise HTTPException(status_code=403, detail="Not authorized to access this chat")
# Get all messages for the chat
result = await db.execute(
select(Message)
.where(Message.chat_id == id)
.order_by(Message.created_at)
)
messages = result.scalars().all()
return {
"chat": {
"id": chat.id,
"title": chat.title,
"app_url": chat.app_url,
"created_at": chat.created_at
},
"messages": [
{
"id": msg.id,
"role": msg.role,
"content": msg.content,
"event_type": msg.event_type,
"created_at": msg.created_at
}
for msg in messages
]
}
@app.post("/chat")
async def create_project(
payload: ChatPayload,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
# Generate UUID on backend
chat_id = str(uuid.uuid4())
prompt = payload.prompt
if not prompt:
return JSONResponse({"error": "Too short or no description"}, status_code=400)
# Decrypt user's OpenRouter API key
if not current_user.encrypted_openrouter_key:
return JSONResponse(
{"error": "No API key", "message": "Please add your OpenRouter API key in Settings before building."},
status_code=400,
)
openrouter_api_key = decrypt_api_key(current_user.encrypted_openrouter_key)
if chat_id in active_runs:
return JSONResponse(
{"error": "Project is being created. Kindly wait"}, status_code=400
)
new_chat = Chat(
id=chat_id,
user_id=current_user.id,
title=prompt[:100] if len(prompt) > 100 else prompt,
)
db.add(new_chat)
await db.commit()
# Create initial user message
user_message = Message(
id=str(uuid.uuid4()),
chat_id=chat_id,
role="user",
content=prompt
)
db.add(user_message)
await db.commit()
# Get or create event queue for this chat
event_queue = active_streams.get(chat_id)
if not event_queue:
event_queue = asyncio.Queue()
active_streams[chat_id] = event_queue
# Start agent task in background
async def agent_task():
try:
await agent_service.handle_first_build(
prompt=prompt, api_key=openrouter_api_key,
project_id=chat_id, event_queue=event_queue,
)
except Exception as e:
print(f"Agent error: {e}")
traceback.print_exc()
try:
async with AsyncSessionLocal() as error_db:
error_message = Message(
id=str(uuid.uuid4()),
chat_id=chat_id,
role="assistant",
content=f"Build failed: {str(e)}",
event_type="error"
)
error_db.add(error_message)
await error_db.commit()
except Exception as db_err:
print(f"Failed to store error message: {db_err}")
try:
event_queue.put_nowait({
"e": "error",
"message": f"Build failed: {str(e)}"
})
except Exception as queue_err:
print(f"Failed to send error to event queue: {queue_err}")
finally:
if chat_id in active_runs:
del active_runs[chat_id]
# Store the task
active_runs[chat_id] = asyncio.create_task(agent_task())
return {
"status": "success",
"message": "Chat created and agent started.",
"chat_id": chat_id,
}
async def _list_sandbox_files(sandbox) -> list:
"""List all project files in the sandbox, excluding build artifacts."""
proc = await sandbox.commands.run(
'find /home/user/react-app -type f '
'-not -path "*/node_modules/*" '
'-not -path "*/.git/*" '
'-not -path "*/__pycache__/*" '
'-not -path "*/.next/*" '
'-not -path "*/dist/*" '
'-not -path "*/build/*" '
'-not -name ".DS_Store" '
'-not -name "package-lock.json" '
'-not -name "yarn.lock" '
'2>/dev/null || echo ""',
timeout=10,
)
if proc.exit_code != 0:
raise Exception(f"Failed to list files: {proc.stderr}")
base = "/home/user/react-app/"
files = []
for line in proc.stdout.strip().split("\n"):
line = line.strip()
if line and line.startswith(base):
files.append(line[len(base):])
return files
@app.get("/projects/{id}/files", response_model=ProjectFilesResponse)
async def get_project_files(id: str, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
result = await db.execute(select(Chat).where(Chat.id == id))
chat = result.scalar_one_or_none()
if not chat or chat.user_id != current_user.id:
raise HTTPException(status_code=403, detail="Not authorized to access this project")
# Try live sandbox first (fastest, always up-to-date)
sandbox = agent_service.sandboxes.get(id)
if sandbox:
try:
files = await _list_sandbox_files(sandbox)
return {
"project_id": id,
"files": files,
"sandbox_id": sandbox.sandbox_id,
"sandbox_active": True,
}
except Exception as e:
print(f"Live sandbox file listing failed for {id}, falling back to disk: {e}")
# Sandbox not in memory or query failed — fall back to disk snapshot
metadata_file = os.path.join(agent_service.storage_base_path, id, "metadata.json")
if os.path.exists(metadata_file):
with open(metadata_file) as f:
metadata = json.load(f)
return {
"project_id": id,
"files": metadata.get("files", []),
"sandbox_id": metadata.get("sandbox_id"),
"sandbox_active": False,
}
raise HTTPException(status_code=404, detail="Project not found or no files available.")
@app.get("/projects/{id}/files/{file_path:path}")
async def get_file_content(
id: str,
file_path: str,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Get the content of a specific file from the project"""
result = await db.execute(select(Chat).where(Chat.id == id))
chat = result.scalar_one_or_none()
if not chat or chat.user_id != current_user.id:
raise HTTPException(status_code=403, detail="Not authorized to access this project")
# Try live sandbox first
sandbox = agent_service.sandboxes.get(id)
if sandbox:
try:
full_path = f"/home/user/react-app/{file_path}"
content = await sandbox.files.read(full_path)
return {"file_path": file_path, "content": content}
except Exception as e:
print(f"Live sandbox read failed for {file_path}, falling back to disk: {e}")
# Fall back to local cache, then R2
from utils.store import load_file_content
content = load_file_content(id, file_path)
if content:
return {"file_path": file_path, "content": content}
raise HTTPException(status_code=404, detail="File not found in sandbox or storage.")
@app.post("/projects/{id}/restart")
async def restart_project_sandbox(
id: str,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Recreate the E2B sandbox for an expired project, restore files, and restart Vite."""
result = await db.execute(select(Chat).where(Chat.id == id))
chat = result.scalar_one_or_none()
if not chat or chat.user_id != current_user.id:
raise HTTPException(status_code=403, detail="Not authorized to access this project")
try:
# Recreate (or reconnect to) the sandbox and restore files from disk
sandbox = await agent_service.get_e2b_sandbox(id)
# Ensure Vite is running — restoration doesn't start it automatically.
# pkill is best-effort; nohup forks to background so E2B returns
# exit code -1 (detached process) — both are safe to ignore.
try:
await sandbox.commands.run(
"pkill -f vite || true", cwd="/home/user/react-app"
)
except Exception:
pass
try:
await sandbox.commands.run(
"nohup npm run dev -- --host 0.0.0.0 > /tmp/vite.log 2>&1 &",
cwd="/home/user/react-app",
)
except Exception:
pass
await asyncio.sleep(10)
new_url = f"https://5173-{sandbox.sandbox_id}.e2b.app"
# Persist the new URL
chat.app_url = new_url
await db.commit()
return {"app_url": new_url}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to restart sandbox: {str(e)}")
@app.post("/projects/{id}/deploy")
async def deploy_project(
id: str,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Deploy a project to Cloudflare Pages via Wrangler inside the E2B sandbox."""
result = await db.execute(select(Chat).where(Chat.id == id))
chat = result.scalar_one_or_none()
if not chat or chat.user_id != current_user.id:
raise HTTPException(status_code=403, detail="Not authorized to access this project")
sandbox = agent_service.sandboxes.get(id)
if not sandbox:
# Try to reconnect
try:
sandbox = await agent_service.get_e2b_sandbox(id)
except Exception:
raise HTTPException(status_code=404, detail="Project sandbox not found or expired. Restart the project first.")
project_name = chat.title or f"buildable-{id[:8]}"
from utils.cloudflare import deploy_to_cloudflare
deploy_result = await deploy_to_cloudflare(sandbox, project_name)
if not deploy_result["success"]:
raise HTTPException(status_code=500, detail=deploy_result["error"])
# Save deployed URL to database
chat.deployed_url = deploy_result["url"]
await db.commit()
return {"success": True, "url": deploy_result["url"]}
@app.get("/projects/{id}/download")
async def download_all_files(
id: str,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Download all project files as a ZIP archive"""
result = await db.execute(select(Chat).where(Chat.id == id))
chat = result.scalar_one_or_none()
if not chat or chat.user_id != current_user.id:
raise HTTPException(status_code=403, detail="Not authorized to access this project")
sandbox = agent_service.sandboxes.get(id)
if not sandbox:
raise HTTPException(status_code=404, detail="Project sandbox not found or not active.")
try:
files = await _list_sandbox_files(sandbox)
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
for file_path in files:
try:
content = await sandbox.files.read(f"/home/user/react-app/{file_path}")
zip_file.writestr(file_path, content)
except Exception as e:
print(f"Failed to add {file_path} to ZIP: {e}")
zip_buffer.seek(0)
return StreamingResponse(
zip_buffer,
media_type="application/zip",
headers={"Content-Disposition": f"attachment; filename={id}-project.zip"}
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error creating ZIP: {str(e)}")
@app.delete("/projects/{id}")
async def delete_project(
id: str,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Delete a project — cancels active run, kills sandbox, removes disk files and DB records."""
result = await db.execute(select(Chat).where(Chat.id == id))
chat = result.scalar_one_or_none()
if not chat or chat.user_id != current_user.id:
raise HTTPException(status_code=403, detail="Not authorized to access this project")
# 1. Cancel active agent run
task = active_runs.pop(id, None)
if task and not task.done():
task.cancel()
try:
await task
except (asyncio.CancelledError, Exception):
pass
# 2. Close SSE queue (drain any waiting consumers)
active_streams.pop(id, None)
# 3. Kill E2B sandbox (best-effort — may already be dead)
sandbox = agent_service.sandboxes.pop(id, None)
agent_service.project_timestamps.pop(id, None)
if sandbox:
try:
await sandbox.kill()
except Exception:
pass
# 4. Delete from R2 + local cache
from utils.store import cleanup_project_store
cleanup_project_store(id)
# 5. Delete DB records (messages first, then chat)
await db.execute(delete(Message).where(Message.chat_id == id))
await db.delete(chat)
await db.commit()
return {"status": "deleted", "project_id": id}
@app.post("/chats/{id}/cancel")
async def cancel_build(
id: str,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Cancel an active build for a project."""
result = await db.execute(select(Chat).where(Chat.id == id))
chat = result.scalar_one_or_none()
if not chat or chat.user_id != current_user.id:
raise HTTPException(status_code=403, detail="Not authorized")
task = active_runs.pop(id, None)
if task and not task.done():
task.cancel()
try:
await task
except (asyncio.CancelledError, Exception):
pass
else:
# No active task — send cancelled event directly
event_queue = active_streams.get(id)
if event_queue:
await event_queue.put({"e": "cancelled", "message": "Build cancelled by user"})
return {"status": "cancelled"}
@app.get("/projects", response_model=ProjectsListResponse)
async def list_user_projects(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db)
):
"""List all Projects per user"""
result = await db.execute(
select(Chat).where(Chat.user_id == current_user.id).order_by(Chat.created_at.desc())
)
projects = result.scalars().all()
return ProjectsListResponse(projects=projects)
@app.get("/sse/{id}")
async def sse_stream(
id: str,
token: str = Query(...),
):
"""Server-Sent Events endpoint for streaming agent updates with JWT authentication"""
# Validate JWT token
payload = decode_token(token)
if payload is None:
raise HTTPException(status_code=401, detail="Invalid authentication token")
user_id = payload.get("sub")
if user_id is None:
raise HTTPException(status_code=401, detail="Invalid token payload")
# Verify user and chat ownership before streaming starts
async with AsyncSessionLocal() as db:
result = await db.execute(select(User).where(User.id == int(user_id)))
user = result.scalar_one_or_none()
if user is None:
raise HTTPException(status_code=404, detail="User not found")
result = await db.execute(select(Chat).where(Chat.id == id))
chat = result.scalar_one_or_none()
if chat is None:
raise HTTPException(status_code=404, detail="Chat not found")
if chat.user_id != user.id:
raise HTTPException(status_code=403, detail="Unauthorized: Chat belongs to another user")
chat_app_url = chat.app_url
chat_deployed_url = chat.deployed_url
# Reuse existing queue if agent is already running, otherwise create new
event_queue = active_streams.get(id)
if not event_queue:
event_queue = asyncio.Queue()
active_streams[id] = event_queue
async def event_generator():
"""Generate SSE events from the queue"""
try:
# Fetch message history in a short-lived session
async with AsyncSessionLocal() as db:
result = await db.execute(
select(Message)
.where(Message.chat_id == id)
.order_by(Message.created_at)
)
messages = result.scalars().all()
print(f"SSE: Sending history with {len(messages)} messages and app_url: {chat_app_url}")
history_event = {
"e": "history",
"messages": [
{
"id": msg.id,
"role": msg.role,
"content": msg.content,
"event_type": msg.event_type,
"created_at": msg.created_at.isoformat(),
"tool_calls": msg.tool_calls if hasattr(msg, 'tool_calls') else None
}
for msg in messages
],
"app_url": chat_app_url,
"deployed_url": chat_deployed_url
}
yield f"data: {json.dumps(history_event)}\n\n"
# Stream live events from queue
while True:
try:
event = await asyncio.wait_for(event_queue.get(), timeout=30.0)
print(f"SSE: Sending event for {id}: {event.get('e')}")
yield f"data: {json.dumps(event)}\n\n"
except asyncio.TimeoutError:
print(f"SSE: Sending keep-alive for {id}")
yield ": keep-alive\n\n"
except asyncio.CancelledError:
print(f"SSE connection closed for {id}")
except Exception as e:
print(f"Error in SSE event generator for {id}: {e}")
traceback.print_exc()
finally:
active_streams.pop(id, None)
print(f"SSE stream cleaned up for {id}")
return StreamingResponse(
event_generator(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no" # Disable nginx buffering
}
)
@app.post("/chats/{id}/messages")
async def send_message(
id: str,
payload: ChatMessagePayload,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db)
):
"""Send a new message to the chat and start agent processing"""
prompt = payload.prompt
if not prompt:
raise HTTPException(status_code=400, detail="No prompt provided")
# Verify chat exists and belongs to user
result = await db.execute(select(Chat).where(Chat.id == id))
chat = result.scalar_one_or_none()
if chat is None:
raise HTTPException(status_code=404, detail="Chat not found")
if chat.user_id != current_user.id:
raise HTTPException(status_code=403, detail="Unauthorized: Chat belongs to another user")
# Check if agent is already running
if id in active_runs:
raise HTTPException(
status_code=409,
detail="Project is being created. Please wait for the current build to complete."
)
# Store user message
user_message = Message(
id=str(uuid.uuid4()),
chat_id=id,
role="user",
content=prompt
)
db.add(user_message)
await db.commit()
# Get or create event queue
event_queue = active_streams.get(id)
if not event_queue:
event_queue = asyncio.Queue()
active_streams[id] = event_queue
# Decrypt user's OpenRouter API key for follow-up messages
if not current_user.encrypted_openrouter_key:
raise HTTPException(status_code=400, detail="Please add your OpenRouter API key in Settings before building.")
openrouter_api_key = decrypt_api_key(current_user.encrypted_openrouter_key)
async def agent_task():
try:
await agent_service.handle_follow_up(
message=prompt, api_key=openrouter_api_key,
project_id=id, event_queue=event_queue,
)
except Exception as e:
print(f"Error in agent task for project {id}: {e}")
traceback.print_exc()
try:
async with AsyncSessionLocal() as error_db:
error_message = Message(
id=str(uuid.uuid4()),
chat_id=id,
role="assistant",
content=f"Build failed: {str(e)}",
event_type="error"
)
error_db.add(error_message)
await error_db.commit()
except Exception as db_err:
print(f"Failed to store error message: {db_err}")
try:
event_queue.put_nowait({
"e": "error",
"message": f"Build failed: {str(e)}"
})
except Exception as queue_err:
print(f"Failed to send error to event queue: {queue_err}")
finally:
active_runs.pop(id, None)
active_runs[id] = asyncio.create_task(agent_task())
return {
"status": "accepted",
"message": "Message received and agent started",
}