From bec4af555d354481f5466694c06be09df2d69500 Mon Sep 17 00:00:00 2001 From: Steven Nguyen Date: Sun, 16 Aug 2026 22:49:04 -0700 Subject: [PATCH 1/7] feat: implement real-time AI chat and task status management with Supabase integration --- app/api/ai/design/route.ts | 106 ++ components/editor/ai-chat-context.tsx | 38 + components/editor/ai-sidebar.tsx | 259 +++- components/editor/ai-status-context.tsx | 47 + components/editor/canvas-wrapper.tsx | 17 + components/editor/editor-chrome.tsx | 99 +- components/editor/live-cursors.tsx | 24 +- components/editor/realtime-canvas.tsx | 88 ++ components/editor/starter-templates.ts | 99 +- context/architecture-context.md | 8 + context/code-standards.md | 3 +- .../feature-specs/23-design-agent-logic.md | 7 +- .../feature-specs/27-spec-generation-flow.md | 15 +- context/progress-tracker.md | 144 +- context/project-overview.md | 2 +- hooks/use-ai-task-status.ts | 318 +++++ hooks/use-realtime-chat.ts | 213 +++ hooks/use-realtime-flow.ts | 78 +- hooks/use-realtime-presence.ts | 13 + lib/ai/task-runs.ts | 108 ++ lib/canvas-storage.ts | 15 +- lib/realtime.ts | 42 + lib/supabase/admin.ts | 25 + package-lock.json | 140 +- package.json | 5 +- scratch/test-ai-chat-functional.ts | 280 ++++ scratch/test-ai-presence-state.ts | 69 + scratch/test-handle-resolution.ts | 112 ++ scratch/test-sidebar-chat.ts | 110 ++ supabase/config.toml | 7 +- supabase/functions/_shared/design-agent.ts | 1254 +++++++++++++++++ supabase/functions/ai-worker/index.ts | 465 ++++++ supabase/functions/deno.json | 8 + ...60817000000_create_task_runs_and_queue.sql | 333 +++++ supabase/seed.sql | 5 + tsconfig.json | 3 +- types/canvas.ts | 112 ++ types/tasks.ts | 177 +++ 38 files changed, 4706 insertions(+), 142 deletions(-) create mode 100644 app/api/ai/design/route.ts create mode 100644 components/editor/ai-chat-context.tsx create mode 100644 components/editor/ai-status-context.tsx create mode 100644 hooks/use-ai-task-status.ts create mode 100644 hooks/use-realtime-chat.ts create mode 100644 lib/ai/task-runs.ts create mode 100644 lib/supabase/admin.ts create mode 100644 scratch/test-ai-chat-functional.ts create mode 100644 scratch/test-ai-presence-state.ts create mode 100644 scratch/test-handle-resolution.ts create mode 100644 scratch/test-sidebar-chat.ts create mode 100644 supabase/functions/_shared/design-agent.ts create mode 100644 supabase/functions/ai-worker/index.ts create mode 100644 supabase/functions/deno.json create mode 100644 supabase/migrations/20260817000000_create_task_runs_and_queue.sql create mode 100644 types/tasks.ts diff --git a/app/api/ai/design/route.ts b/app/api/ai/design/route.ts new file mode 100644 index 0000000..597c3dc --- /dev/null +++ b/app/api/ai/design/route.ts @@ -0,0 +1,106 @@ +import { NextRequest, NextResponse } from "next/server"; +import { createClient, getCurrentUser } from "@/lib/supabase/server"; +import { hasProjectAccess } from "@/lib/project-access"; +import { + enqueueTaskRun, + invokeAiWorkerFastPath, + ActiveTaskRunConflictError, +} from "@/lib/ai/task-runs"; + +export async function POST(req: NextRequest) { + let body: unknown; + try { + body = await req.json(); + } catch { + return NextResponse.json( + { error: "Invalid JSON request body" }, + { status: 400 } + ); + } + + if (!body || typeof body !== "object") { + return NextResponse.json( + { error: "Request body must be a JSON object" }, + { status: 400 } + ); + } + + const { prompt, roomId } = body as { prompt?: unknown; roomId?: unknown }; + + if (typeof prompt !== "string" || !prompt.trim()) { + return NextResponse.json( + { error: "A non-empty prompt is required" }, + { status: 400 } + ); + } + + if (typeof roomId !== "string" || !roomId.trim()) { + return NextResponse.json( + { error: "A valid roomId is required" }, + { status: 400 } + ); + } + + const trimmedPrompt = prompt.trim(); + const trimmedRoomId = roomId.trim(); + + // 1. Authenticate user + const supabase = await createClient(); + const user = await getCurrentUser(supabase); + + if (!user) { + return NextResponse.json( + { error: "Unauthorized" }, + { status: 401 } + ); + } + + // 2. Resolve project access from roomId (projectId) + const hasAccess = await hasProjectAccess(supabase, trimmedRoomId, { + userId: user.id, + email: user.email ?? "", + }); + + if (!hasAccess) { + return NextResponse.json( + { error: "Project not found or access denied" }, + { status: 403 } + ); + } + + // 3. Transactionally enqueue task run + let runId: string; + try { + runId = await enqueueTaskRun({ + projectId: trimmedRoomId, + userId: user.id, + kind: "design", + input: { + prompt: trimmedPrompt, + roomId: trimmedRoomId, + }, + }); + } catch (err: unknown) { + if (err instanceof ActiveTaskRunConflictError) { + return NextResponse.json( + { error: "An AI generation task is already active for this project" }, + { status: 409 } + ); + } + console.error("[POST /api/ai/design] Enqueue error:", err); + return NextResponse.json( + { error: "Failed to enqueue design generation task" }, + { status: 500 } + ); + } + + // 4. Best-effort fast-path Edge Function invocation + // Fast-path invocation does not block or fail durability + void invokeAiWorkerFastPath(); + + // 5. Return run ID with HTTP 202 Accepted + return NextResponse.json( + { runId }, + { status: 202 } + ); +} diff --git a/components/editor/ai-chat-context.tsx b/components/editor/ai-chat-context.tsx new file mode 100644 index 0000000..ab474ca --- /dev/null +++ b/components/editor/ai-chat-context.tsx @@ -0,0 +1,38 @@ +"use client"; + +import React, { createContext, useContext } from "react"; +import type { AiChatMessage } from "@/types/tasks"; + +export interface AiChatContextValue { + messages: AiChatMessage[]; + sendMessage: (content: string) => Promise; + sendError: string | null; + clearSendError: () => void; + setSendError?: (error: string | null) => void; + registerSendHandler: ( + handler: ((content: string) => Promise) | null + ) => void; + setMessages: React.Dispatch>; + addMessage: (message: AiChatMessage) => void; + currentUserId: string | null; +} + +const AiChatContext = createContext(null); + +export function AiChatProvider({ + value, + children, +}: { + value: AiChatContextValue; + children: React.ReactNode; +}) { + return ( + + {children} + + ); +} + +export function useAiChat(): AiChatContextValue | null { + return useContext(AiChatContext); +} diff --git a/components/editor/ai-sidebar.tsx b/components/editor/ai-sidebar.tsx index eff48f3..69da081 100644 --- a/components/editor/ai-sidebar.tsx +++ b/components/editor/ai-sidebar.tsx @@ -1,6 +1,6 @@ "use client"; -import React, { useState, useRef, useEffect } from "react"; +import React, { useState, useRef, useEffect, useMemo } from "react"; import { X, Sparkles, @@ -11,24 +11,46 @@ import { ShoppingCart, MessageSquare, GitBranch, + Loader2, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { ScrollArea } from "@/components/ui/scroll-area"; import { GhostLogo } from "@/components/ui/ghost-logo"; +import { useAiStatus } from "@/components/editor/ai-status-context"; +import { useAiChat } from "@/components/editor/ai-chat-context"; +import { getSenderDisplayName } from "@/types/tasks"; import { cn } from "@/lib/utils"; interface AiSidebarProps { isOpen: boolean; onClose: () => void; + projectId?: string; } -interface ChatMessage { - id: string; - role: "user" | "assistant"; - content: string; - timestamp: string; +function formatMessageTime(timestamp: string): string { + try { + const date = new Date(timestamp); + if (isNaN(date.getTime())) { + return timestamp; + } + return date.toLocaleTimeString([], { + hour: "2-digit", + minute: "2-digit", + }); + } catch { + return timestamp; + } } +const STEP_LABELS: Record = { + start: "Starting", + analyzing: "Analyzing Architecture", + generating: "Generating Components", + updating_canvas: "Updating Canvas", + complete: "Generation Complete", + failed: "Generation Failed", +}; + const STARTER_PROMPTS = [ { title: "Design an e-commerce backend", @@ -49,17 +71,29 @@ const STARTER_PROMPTS = [ export function AiSidebar({ isOpen, onClose }: AiSidebarProps) { const [activeTab, setActiveTab] = useState<"architect" | "specs">("architect"); - const [messages, setMessages] = useState([]); const [input, setInput] = useState(""); const textareaRef = useRef(null); const messagesEndRef = useRef(null); + const aiStatus = useAiStatus(); + const isAiActive = aiStatus?.isAiActive ?? false; + const latestStatus = aiStatus?.latestStatus ?? null; + const activeTaskRun = aiStatus?.activeTaskRun ?? null; + + const aiChat = useAiChat(); + const messages = useMemo(() => aiChat?.messages ?? [], [aiChat?.messages]); + const sendError = aiChat?.sendError ?? null; + const currentUserId = aiChat?.currentUserId ?? null; + useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); }, [messages]); const handleInputChange = (e: React.ChangeEvent) => { setInput(e.target.value); + if (aiChat?.sendError) { + aiChat.clearSendError(); + } if (textareaRef.current) { textareaRef.current.style.height = "auto"; textareaRef.current.style.height = `${Math.min( @@ -69,32 +103,28 @@ export function AiSidebar({ isOpen, onClose }: AiSidebarProps) { } }; - const handleSendMessage = (textToSend?: string) => { + const handleSendMessage = async (textToSend?: string) => { + if (isAiActive) return; const content = (textToSend ?? input).trim(); if (!content) return; - const userMessage: ChatMessage = { - id: `msg-${crypto.randomUUID()}`, - role: "user", - content, - timestamp: new Date().toLocaleTimeString([], { - hour: "2-digit", - minute: "2-digit", - }), - }; - - setMessages((prev) => [...prev, userMessage]); - setInput(""); - - if (textareaRef.current) { - textareaRef.current.style.height = "72px"; + if (aiChat) { + const success = await aiChat.sendMessage(content); + if (success) { + setInput(""); + if (textareaRef.current) { + textareaRef.current.style.height = "72px"; + } + } } }; const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); - handleSendMessage(); + if (!isAiActive) { + void handleSendMessage(); + } } }; @@ -219,8 +249,12 @@ export function AiSidebar({ isOpen, onClose }: AiSidebarProps) { + + )} + +