Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -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=
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@

# testing
/coverage
/scratch/
scratch/

# next.js
/.next/
Expand All @@ -32,11 +34,13 @@ yarn-error.log*

# env files (can opt-in for committing if needed)
.env*
!.env.example
*.env
.env

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
.env
15 changes: 9 additions & 6 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

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.
- 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.
92 changes: 91 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,91 @@
# Ghost AI
# 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.
117 changes: 117 additions & 0 deletions app/api/ai/design/route.ts
Original file line number Diff line number Diff line change
@@ -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 }
);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

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 }
);
}
Loading