diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..16eefcf --- /dev/null +++ b/.env.example @@ -0,0 +1,16 @@ +# Local Ghost AI environment +# Copy to .env.local (Next.js) and supabase/functions/.env (Edge Functions). +# Never commit real keys. Hosted projects must use unique values, not these defaults. + +NEXT_PUBLIC_SUPABASE_URL=http://127.0.0.1:54321 +NEXT_PUBLIC_SUPABASE_ANON_KEY= +SUPABASE_SERVICE_ROLE_KEY= + +# Must match Vault secret `automations` (local seed sets local-dev-automation-secret). +AUTOMATION_SECRET=local-dev-automation-secret + +# Optional named secret map used by Edge Functions (JSON object). +# SUPABASE_SECRET_KEYS={"automations":"local-dev-automation-secret"} + +# OpenRouter key for design and spec workers. Set as an Edge Function secret in hosted projects. +OPENROUTER_API_KEY= diff --git a/.gitignore b/.gitignore index 6d805f8..8d25cda 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,8 @@ # testing /coverage +/scratch/ +scratch/ # next.js /.next/ @@ -32,6 +34,9 @@ yarn-error.log* # env files (can opt-in for committing if needed) .env* +!.env.example +*.env +.env # vercel .vercel @@ -39,4 +44,3 @@ yarn-error.log* # typescript *.tsbuildinfo next-env.d.ts -.env diff --git a/AGENTS.md b/AGENTS.md index 0ac61fb..94892ca 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,20 +23,23 @@ If implementation changes the architecture, scope, or standards documented in th ## Cursor Cloud specific instructions -Ghost AI is a single Next.js app (`next dev --turbopack`, port 3000) backed by **Supabase** (Auth + Postgres) — the only external service the current code touches. Liveblocks, Trigger.dev, and AI providers are documented future scope (specs 08–12) and are not installed or wired up yet. +Ghost AI is a single Next.js app (`next dev --turbopack`, port 3000) backed by **Supabase** (Auth, Postgres, Realtime, Storage, Queues, Cron, and Edge Functions). OpenRouter is the only external AI provider. Features through spec 29 are implemented. Liveblocks and Trigger.dev are not used. The VM image already has the Docker engine and the Supabase CLI installed; the update script only runs `npm install`. Bring the stack up in this order: 1. Ensure the Docker daemon is running (run `docker ps`; if it fails, start it with `sudo dockerd &` and wait a few seconds). `/etc/docker/daemon.json` is pre-configured for `fuse-overlayfs` with the containerd-snapshotter feature disabled, and `iptables` is set to the legacy backend — this is required for Docker to work in this VM. 2. From `/workspace`, run `supabase start`. This launches the local Supabase containers, applies everything in `supabase/migrations/`, and runs `supabase/seed.sql`. Get the local URL/keys anytime with `supabase status`. 3. Create `.env.local` (gitignored) if it is missing, pointing at the local stack. Do not hardcode keys here — read the current values from `supabase status` (fields `API URL`, `anon key`, and `service_role key`) and write them in: - - `NEXT_PUBLIC_SUPABASE_URL` — the `API URL` (local default `http://127.0.0.1:54321`) - - `NEXT_PUBLIC_SUPABASE_ANON_KEY` — the `anon key` (the standard, non-secret local demo JWT, stable across restarts) - - `SUPABASE_SERVICE_ROLE_KEY` — the `service_role key` (server-only; required for collaborator listing and Auth admin enrichment in spec 09). Never expose this to the browser. -4. `npm run dev` → http://localhost:3000. Unauthenticated visits redirect to `/login`; sign up/in creates a real Supabase Auth user (email confirmation is off locally). + - `NEXT_PUBLIC_SUPABASE_URL` — the `API URL` (local default `http://127.0.0.1:54321`) + - `NEXT_PUBLIC_SUPABASE_ANON_KEY` — the `anon key` (the standard, non-secret local demo JWT, stable across restarts) + - `SUPABASE_SERVICE_ROLE_KEY` — the `service_role key` (server-only; required for collaborator listing and Auth admin enrichment in spec 09). Never expose this to the browser. + - `AUTOMATION_SECRET` — `local-dev-automation-secret`, matching the value seeded into Vault for local worker invocation. +4. Copy `.env.example` to `supabase/functions/.env`, then set `OPENROUTER_API_KEY`. Keep the local `AUTOMATION_SECRET` aligned with the Vault `automations` secret seeded by `supabase/seed.sql`. +5. `npm run dev` → http://localhost:3000. Unauthenticated visits redirect to `/login`; sign up/in creates a real Supabase Auth user (email confirmation is off locally). Non-obvious gotchas: - **`supabase/seed.sql` is load-bearing locally, not just sample data.** Hosted Supabase auto-grants DML on `public` tables to the `anon`/`authenticated` roles; the local CLI does not, so without the seed's `GRANT`s every query fails with `permission denied for table projects` and `/editor` shows "Application error: a server-side exception". If you recreate the DB, re-run `supabase start`/`supabase db reset` so the seed re-applies (or apply `supabase/seed.sql` manually). - **`/editor/[roomId]` is implemented** (spec 08). Share dialog (spec 09) opens from the workspace navbar Share button. Collaborator list enrichment needs `SUPABASE_SERVICE_ROLE_KEY` in `.env.local`. -- **Lint has a pre-existing failure.** `npm run lint` reports a `prefer-const` error in `middleware.ts` that predates environment setup; `npm run build` passes cleanly. \ No newline at end of file +- AI generation needs both `AUTOMATION_SECRET` and `OPENROUTER_API_KEY`. Hosted projects must also set Vault `ai_worker_url` and use a unique automation secret shared with the Edge Function. +- `npm run lint` and `npm run build` are the standard repository checks. diff --git a/README.md b/README.md index 2ee174d..80ca50b 100644 --- a/README.md +++ b/README.md @@ -1 +1,91 @@ -# Ghost AI \ No newline at end of file +# Ghost AI + +Ghost AI is a collaborative system design workspace. Teams build architecture diagrams on a shared canvas, ask an AI agent to create or revise designs, and generate downloadable Markdown technical specifications. + +## Features + +- Supabase Auth with protected project workspaces +- Owner and collaborator access controls +- React Flow canvas with realtime nodes, edges, cursors, selections, and presence +- Starter architecture templates and canvas autosave +- Durable AI design and spec generation with Supabase Queues, Cron, and Edge Functions +- OpenRouter powered architecture generation +- Persisted Markdown specs with preview and secure download +- Light and dark themes + +Feature specifications 01 through 29 are implemented. See `context/progress-tracker.md` for acceptance gaps that still need follow-up. + +## Stack + +- Next.js 15.4, React 19, and TypeScript +- Tailwind CSS 4 and shadcn style UI primitives +- React Flow +- Supabase Auth, Postgres, Realtime, Storage, Queues, Cron, and Edge Functions +- OpenRouter + +## Local setup + +Requirements: + +- Node.js 22 or later +- Docker +- Supabase CLI + +Install dependencies and start Supabase: + +```bash +npm install +supabase start +``` + +Copy `.env.example` to `.env.local`. Fill the Supabase URL, anon key, and service role key from `supabase status`. Set `AUTOMATION_SECRET=local-dev-automation-secret` so it matches the Vault value from `supabase/seed.sql`. + +Copy `.env.example` to `supabase/functions/.env`. Set `OPENROUTER_API_KEY`. For local development, keep `AUTOMATION_SECRET=local-dev-automation-secret` so it matches the value seeded into Supabase Vault. + +Start the app: + +```bash +npm run dev +``` + +Open http://localhost:3000. Unauthenticated users are redirected to `/login`. + +## Environment variables + +| Variable | Used by | Purpose | +| --- | --- | --- | +| `NEXT_PUBLIC_SUPABASE_URL` | Next.js client and server | Supabase API URL | +| `NEXT_PUBLIC_SUPABASE_ANON_KEY` | Next.js client and server | Browser safe Supabase key | +| `SUPABASE_SERVICE_ROLE_KEY` | Next.js server | Admin enrichment, task enqueueing, and worker invocation | +| `AUTOMATION_SECRET` | Next.js server and Edge Function | Authenticates worker fast path and Cron calls | +| `OPENROUTER_API_KEY` | Edge Function | AI model access | + +Never expose the service role key, automation secret, or OpenRouter key to browser code. + +## Checks + +```bash +npm run lint +npm run build +``` + +## Project layout + +- `app/`: Next.js pages and route handlers +- `components/editor/`: canvas, workspace, AI, and spec UI +- `hooks/`: realtime, task status, autosave, and project hooks +- `lib/`: Supabase clients, access checks, and data helpers +- `supabase/functions/`: AI queue worker and generation handlers +- `supabase/migrations/`: database, RLS, Storage, Queue, and Cron changes +- `context/feature-specs/`: feature specifications 01 through 29 +- `context/`: product, architecture, UI, standards, and progress documentation + +## Hosted setup + +Before enabling AI generation in a hosted Supabase project: + +1. Set a unique Vault secret named `automations`. +2. Set the same value as the Edge Function secret `AUTOMATION_SECRET`. +3. Set Vault secret `ai_worker_url` to the hosted `ai-worker` function URL. +4. Set `OPENROUTER_API_KEY` as an Edge Function secret. +5. Confirm the `ai-worker-recovery` Cron job receives HTTP 202 responses. diff --git a/app/api/ai/design/route.ts b/app/api/ai/design/route.ts new file mode 100644 index 0000000..b6f49df --- /dev/null +++ b/app/api/ai/design/route.ts @@ -0,0 +1,117 @@ +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"; + +const MAX_DESIGN_PROMPT_LENGTH = 8_000; + +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(); + + if (trimmedPrompt.length > MAX_DESIGN_PROMPT_LENGTH) { + return NextResponse.json( + { error: `Prompt must be ${MAX_DESIGN_PROMPT_LENGTH} characters or fewer` }, + { status: 400 } + ); + } + + // 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 + invokeAiWorkerFastPath().catch((err) => { + console.error("[POST /api/ai/design] Fast-path invocation failed:", err); + }); + + // 5. Return run ID with HTTP 202 Accepted + return NextResponse.json( + { runId }, + { status: 202 } + ); +} diff --git a/app/api/ai/spec/route.ts b/app/api/ai/spec/route.ts new file mode 100644 index 0000000..c50bcd3 --- /dev/null +++ b/app/api/ai/spec/route.ts @@ -0,0 +1,151 @@ +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"; + +const MAX_SPEC_NODES = 250; +const MAX_SPEC_EDGES = 500; +const MAX_SPEC_CHAT_HISTORY = 50; + +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 { roomId, chatHistory, nodes, edges } = body as { + roomId?: unknown; + chatHistory?: unknown; + nodes?: unknown; + edges?: unknown; + }; + + if (typeof roomId !== "string" || !roomId.trim()) { + return NextResponse.json( + { error: "A valid roomId is required" }, + { status: 400 } + ); + } + + if (chatHistory !== undefined && !Array.isArray(chatHistory)) { + return NextResponse.json( + { error: "chatHistory must be an array if provided" }, + { status: 400 } + ); + } + + if (nodes !== undefined && !Array.isArray(nodes)) { + return NextResponse.json( + { error: "nodes must be an array if provided" }, + { status: 400 } + ); + } + + if (edges !== undefined && !Array.isArray(edges)) { + return NextResponse.json( + { error: "edges must be an array if provided" }, + { status: 400 } + ); + } + + const normalizedChatHistory = Array.isArray(chatHistory) + ? chatHistory.slice(-MAX_SPEC_CHAT_HISTORY) + : []; + const normalizedNodes = Array.isArray(nodes) ? nodes : []; + const normalizedEdges = Array.isArray(edges) ? edges : []; + + if (normalizedNodes.length > MAX_SPEC_NODES) { + return NextResponse.json( + { error: `nodes must contain ${MAX_SPEC_NODES} items or fewer` }, + { status: 400 } + ); + } + + if (normalizedEdges.length > MAX_SPEC_EDGES) { + return NextResponse.json( + { error: `edges must contain ${MAX_SPEC_EDGES} items or fewer` }, + { status: 400 } + ); + } + + const trimmedRoomId = roomId.trim(); + + // 1. Authenticate current 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); do not trust client-supplied project IDs + 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 spec task run and send payload to ai-generation queue + let runId: string; + try { + runId = await enqueueTaskRun({ + projectId: trimmedRoomId, + userId: user.id, + kind: "spec", + input: { + roomId: trimmedRoomId, + chatHistory: normalizedChatHistory, + nodes: normalizedNodes, + edges: normalizedEdges, + }, + }); + } 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/spec] Enqueue error:", err); + return NextResponse.json( + { error: "Failed to enqueue spec generation task" }, + { status: 500 } + ); + } + + // 4. Best-effort fast-path Edge Function invocation after transaction commits + invokeAiWorkerFastPath().catch((err) => { + console.error("[POST /api/ai/spec] Fast-path invocation failed:", err); + }); + + // 5. Return run ID with HTTP 202 Accepted + return NextResponse.json( + { runId }, + { status: 202 } + ); +} diff --git a/app/api/projects/[projectId]/collaborators/route.ts b/app/api/projects/[projectId]/collaborators/route.ts index 6a72d05..862a89f 100644 --- a/app/api/projects/[projectId]/collaborators/route.ts +++ b/app/api/projects/[projectId]/collaborators/route.ts @@ -96,7 +96,6 @@ export async function POST(req: Request, ctx: RouteContext) { projectId, email, ownerEmail: user.email ?? undefined, - ownerId: user.id, }); return NextResponse.json({ collaborator }, { status: 201 }); } catch (err) { @@ -152,7 +151,6 @@ export async function DELETE(req: Request, ctx: RouteContext) { await removeCollaborator(supabase, { projectId, email, - ownerId: user.id, ownerEmail: user.email ?? undefined, }); return NextResponse.json({ ok: true }); diff --git a/app/api/projects/[projectId]/route.ts b/app/api/projects/[projectId]/route.ts index e4c9ceb..90114ce 100644 --- a/app/api/projects/[projectId]/route.ts +++ b/app/api/projects/[projectId]/route.ts @@ -72,7 +72,7 @@ export async function DELETE(_req: Request, ctx: RouteContext) { return NextResponse.json({ error: "Forbidden" }, { status: 403 }); } - await deleteProject(supabase, projectId, user.id); + await deleteProject(supabase, projectId); return NextResponse.json({ ok: true }, { status: 200 }); } catch (err) { return errorResponse(err); diff --git a/app/api/projects/[projectId]/specs/[specId]/download/route.ts b/app/api/projects/[projectId]/specs/[specId]/download/route.ts new file mode 100644 index 0000000..05730a1 --- /dev/null +++ b/app/api/projects/[projectId]/specs/[specId]/download/route.ts @@ -0,0 +1,80 @@ +import { NextResponse } from "next/server"; +import { createClient, getCurrentUser } from "@/lib/supabase/server"; +import { getProject, errorResponse, StorageObjectNotFoundError } from "@/lib/projects/queries"; +import { hasProjectAccess } from "@/lib/project-access"; +import { + getProjectSpec, + downloadSpecMarkdown, + formatSpecFileName, +} from "@/lib/specs/queries"; + +interface RouteContext { + params: Promise<{ + projectId: string; + specId: string; + }>; +} + +export async function GET(_req: Request, ctx: RouteContext) { + try { + const supabase = await createClient(); + const user = await getCurrentUser(supabase); + if (!user) { + return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + } + + const { projectId, specId } = await ctx.params; + if (!projectId || !specId) { + return NextResponse.json( + { error: "Missing projectId or specId" }, + { status: 400 } + ); + } + + const identity = { userId: user.id, email: user.email ?? "" }; + const allowed = await hasProjectAccess(supabase, projectId, identity); + if (!allowed) { + return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + } + + const project = await getProject(supabase, projectId); + if (!project) { + return NextResponse.json({ error: "Project not found" }, { status: 404 }); + } + + const spec = await getProjectSpec(supabase, projectId, specId); + if (!spec) { + return NextResponse.json({ error: "Spec not found" }, { status: 404 }); + } + + let markdownContent: string; + try { + markdownContent = await downloadSpecMarkdown(supabase, spec.filePath); + } catch (storageErr) { + if (storageErr instanceof StorageObjectNotFoundError) { + return NextResponse.json( + { error: "Spec file not found in storage" }, + { status: 404 } + ); + } + throw storageErr; + } + + const fileName = formatSpecFileName({ + projectName: project.name, + taskRunId: spec.taskRunId, + createdAt: spec.createdAt, + }); + + return new Response(markdownContent, { + status: 200, + headers: { + "Content-Type": "text/markdown; charset=utf-8", + "Content-Disposition": `attachment; filename="${fileName}"`, + "Cache-Control": "private, no-cache, no-transform", + }, + }); + } catch (err) { + return errorResponse(err); + } +} diff --git a/app/api/projects/[projectId]/specs/[specId]/route.ts b/app/api/projects/[projectId]/specs/[specId]/route.ts new file mode 100644 index 0000000..7a3cb07 --- /dev/null +++ b/app/api/projects/[projectId]/specs/[specId]/route.ts @@ -0,0 +1,83 @@ +import { NextResponse } from "next/server"; +import { createClient, getCurrentUser } from "@/lib/supabase/server"; +import { getProject, errorResponse, StorageObjectNotFoundError } from "@/lib/projects/queries"; +import { hasProjectAccess } from "@/lib/project-access"; +import { + getProjectSpec, + downloadSpecMarkdown, + formatSpecFileName, +} from "@/lib/specs/queries"; +import { type ProjectSpecDetail } from "@/types/specs"; + +interface RouteContext { + params: Promise<{ + projectId: string; + specId: string; + }>; +} + +export async function GET(_req: Request, ctx: RouteContext) { + try { + const supabase = await createClient(); + const user = await getCurrentUser(supabase); + if (!user) { + return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + } + + const { projectId, specId } = await ctx.params; + if (!projectId || !specId) { + return NextResponse.json( + { error: "Missing projectId or specId" }, + { status: 400 } + ); + } + + const identity = { userId: user.id, email: user.email ?? "" }; + const allowed = await hasProjectAccess(supabase, projectId, identity); + if (!allowed) { + return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + } + + const project = await getProject(supabase, projectId); + if (!project) { + return NextResponse.json({ error: "Project not found" }, { status: 404 }); + } + + const spec = await getProjectSpec(supabase, projectId, specId); + if (!spec) { + return NextResponse.json({ error: "Spec not found" }, { status: 404 }); + } + + let content: string; + try { + content = await downloadSpecMarkdown(supabase, spec.filePath); + } catch (storageErr) { + if (storageErr instanceof StorageObjectNotFoundError) { + return NextResponse.json( + { error: "Spec file not found in storage" }, + { status: 404 } + ); + } + throw storageErr; + } + + const fileName = formatSpecFileName({ + projectName: project.name, + taskRunId: spec.taskRunId, + createdAt: spec.createdAt, + }); + + const specDetail: ProjectSpecDetail = { + id: spec.id, + taskRunId: spec.taskRunId, + projectId: spec.projectId, + createdAt: spec.createdAt, + fileName, + content, + }; + + return NextResponse.json({ spec: specDetail }); + } catch (err) { + return errorResponse(err); + } +} diff --git a/app/api/projects/[projectId]/specs/route.ts b/app/api/projects/[projectId]/specs/route.ts new file mode 100644 index 0000000..b3773ef --- /dev/null +++ b/app/api/projects/[projectId]/specs/route.ts @@ -0,0 +1,40 @@ +import { NextResponse } from "next/server"; +import { createClient, getCurrentUser } from "@/lib/supabase/server"; +import { getProject, errorResponse } from "@/lib/projects/queries"; +import { hasProjectAccess } from "@/lib/project-access"; +import { listProjectSpecs } from "@/lib/specs/queries"; + +interface RouteContext { + params: Promise<{ projectId: string }>; +} + +export async function GET(_req: Request, ctx: RouteContext) { + try { + const supabase = await createClient(); + const user = await getCurrentUser(supabase); + if (!user) { + return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + } + + const { projectId } = await ctx.params; + if (!projectId) { + return NextResponse.json({ error: "Missing project id" }, { status: 400 }); + } + + const identity = { userId: user.id, email: user.email ?? "" }; + const allowed = await hasProjectAccess(supabase, projectId, identity); + if (!allowed) { + return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + } + + const project = await getProject(supabase, projectId); + if (!project) { + return NextResponse.json({ error: "Project not found" }, { status: 404 }); + } + + const specs = await listProjectSpecs(supabase, projectId, project.name); + return NextResponse.json({ specs }); + } catch (err) { + return errorResponse(err); + } +} diff --git a/components/editor/ai-chat-context.tsx b/components/editor/ai-chat-context.tsx new file mode 100644 index 0000000..82d8944 --- /dev/null +++ b/components/editor/ai-chat-context.tsx @@ -0,0 +1,41 @@ +"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; + registerAddMessage?: ( + handler: ((message: AiChatMessage) => void) | null + ) => 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..c95b161 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,23 +11,35 @@ import { ShoppingCart, MessageSquare, GitBranch, + Loader2, + AlertCircle, + RefreshCw, + Eye, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { ScrollArea } from "@/components/ui/scroll-area"; import { GhostLogo } from "@/components/ui/ghost-logo"; -import { cn } from "@/lib/utils"; +import { useAiStatus } from "@/components/editor/ai-status-context"; +import { useAiChat } from "@/components/editor/ai-chat-context"; +import { useProjectSpecs } from "@/hooks/use-project-specs"; +import { SpecPreviewModal } from "@/components/editor/spec-preview-modal"; +import { getSenderDisplayName } from "@/types/tasks"; +import { cn, formatMessageTime, formatSpecDate } from "@/lib/utils"; interface AiSidebarProps { isOpen: boolean; onClose: () => void; + projectId?: string; } -interface ChatMessage { - id: string; - role: "user" | "assistant"; - content: string; - timestamp: string; -} +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 = [ { @@ -47,19 +59,50 @@ const STARTER_PROMPTS = [ }, ]; -export function AiSidebar({ isOpen, onClose }: AiSidebarProps) { +export function AiSidebar({ isOpen, onClose, projectId }: 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; + + // Specs integration hook + const { + specs, + loading: loadingSpecs, + error: specsError, + refreshSpecs, + selectedSpecId, + selectedSpec, + loadingDetail, + detailError, + openSpecPreview, + closeSpecPreview, + downloadSpec, + generateSpec, + generating: generatingSpec, + generationError, + clearGenerationError, + } = useProjectSpecs({ projectId, isAiActive }); + 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 +112,44 @@ 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(); + } + } + }; + + const handleGenerateSpecClick = async () => { + if (isAiActive || generatingSpec) return; + clearGenerationError(); + + const chatHistory = messages.map((m) => ({ + role: m.role, + content: m.content, + sender: m.sender, + })); + + const runId = await generateSpec({ chatHistory }); + if (runId && aiStatus?.trackRun) { + await aiStatus.trackRun(runId); } }; @@ -141,7 +196,7 @@ export function AiSidebar({ isOpen, onClose }: AiSidebarProps) { size="icon" onClick={onClose} aria-label="Close AI sidebar" - className="h-7 w-7 rounded-lg text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-elevated)]" + className="h-7 w-7 rounded-lg text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-elevated)] cursor-pointer" > @@ -162,7 +217,7 @@ export function AiSidebar({ isOpen, onClose }: AiSidebarProps) { type="button" onClick={() => setActiveTab("architect")} className={cn( - "relative z-10 flex items-center justify-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium transition-colors duration-200 whitespace-nowrap", + "relative z-10 flex items-center justify-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium transition-colors duration-200 whitespace-nowrap cursor-pointer", activeTab === "architect" ? "text-[var(--text-primary)] font-semibold" : "text-[var(--text-muted)] hover:text-[var(--text-secondary)]" @@ -176,7 +231,7 @@ export function AiSidebar({ isOpen, onClose }: AiSidebarProps) { type="button" onClick={() => setActiveTab("specs")} className={cn( - "relative z-10 flex items-center justify-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium transition-colors duration-200 whitespace-nowrap", + "relative z-10 flex items-center justify-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium transition-colors duration-200 whitespace-nowrap cursor-pointer", activeTab === "specs" ? "text-[var(--text-primary)] font-semibold" : "text-[var(--text-muted)] hover:text-[var(--text-secondary)]" @@ -184,6 +239,11 @@ export function AiSidebar({ isOpen, onClose }: AiSidebarProps) { > Specs + {specs.length > 0 && ( + + {specs.length} + + )} @@ -219,8 +279,12 @@ export function AiSidebar({ isOpen, onClose }: AiSidebarProps) { + + )} + +