feat(infra): Postgres portability, Oracle cutover scripts, and DB kill-switch essay

Vendor-neutral DATABASE_URL helpers, dump/restore/sync tooling, and one-command
Oracle migration after a single console VM step. Publishes the studio-stack
thoughts article and hardens build (dynamic layout, resilient sitemap).

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
g-butandCursor committed 2026-05-23 11:24:20 +02:00
1 parent f8c7a97533
commit ec6f423b0f
63 files changed
+2470 -499

No files matched your search

+9 -1
View File
@@ -1,6 +1,14 @@
# ── Required ────────────────────────────────────────────────────────────────
# PostgreSQL connection string
# PostgreSQL — see docs/infrastructure/postgres-portability.md
#
# Local dev (Docker): direct URL only
DATABASE_URL=postgresql://cockpit:changeme@localhost:5432/cockpit
#
# Production (Vercel): set BOTH on the host — not in .env.local
# DATABASE_URL — direct (:5432) for migrations + LISTEN/NOTIFY
# DATABASE_POOL_URL — pooled (:6432 / PgBouncer / Neon pooler) for app queries
#
# Legacy Neon names still work: NEON_DATABASE_URL (pool), NEON_DATABASE_URL_DIRECT (direct)
# Random secret for signing sessions — generate with: openssl rand -base64 32
AUTH_SECRET=
+2
View File
@@ -13,3 +13,5 @@ next-env.d.ts
**/__pycache__/
*.pyc
.vercel
.env.vercel.production
/backups/
+11 -4
View File
@@ -61,13 +61,18 @@ src/
Set these required environment variables in `.env.local`:
```bash
DATABASE_URL=postgresql://localhost/cockpit
DATABASE_URL=postgresql://cockpit:changeme@localhost:5432/cockpit
AUTH_SECRET=replace-me
AUTH_GITHUB_ID=replace-me
AUTH_GITHUB_SECRET=replace-me
GITHUB_CLIENT_ID=replace-me
GITHUB_CLIENT_SECRET=replace-me
```
Postgres needs a local `cockpit` database. Then push the schema:
**Local dev only** — never point `.env.local` at a cloud Postgres URL. Production uses
`DATABASE_URL` (direct) + `DATABASE_POOL_URL` (pooled) on Vercel. See
[`docs/infrastructure/postgres-portability.md`](docs/infrastructure/postgres-portability.md)
for switching hosts (Neon → Oracle/Hetzner) without code changes.
Postgres needs a local `cockpit` database (`docker compose up db -d`). Then push the schema:
```bash
DATABASE_URL=$YOUR_URL npx drizzle-kit push
@@ -91,6 +96,8 @@ data, either:
npm run dev # Start the dev server on :3000
npm run build # Production build (uses real DB connection)
npm run smoke # Curl every page + DB-backed GET API and assert 2xx/3xx
npm run test:db-url # Postgres URL resolution (portability)
npm run db:dump # pg_dump backup (DATABASE_URL=direct)
npm run lint # ESLint
```
@@ -8,6 +8,9 @@ featured: false
author: Ivy
readingTimeMin: 5
---
> **Update (May 2026):** Neon free tier suspended our production database when egress exceeded 5 GB/month. Cockpit's daemon + serverless traffic pattern is a poor fit for that tier. See the follow-up: [The Database Kill Switch](/thoughts/the-database-kill-switch-neon-oracle-and-the-studio-stack).
## The Current State
Cockpit's AI inference goes through openclaw, which routes to a locally-running Codex model (the `openclaw-infer` process). For short tasks like the AI Merge queue feature, this works — but it takes 4 minutes. That is not fast enough for an interactive tool. The operator clicks "AI merge," watches a spinner for four minutes, and wonders if it is broken.
@@ -0,0 +1,357 @@
---
title: The Database Kill Switch — Neon, Oracle, Hetzner, and the Studio Stack
summary: Cockpit signed us out, wiped our projects from view, and taught us that "free Postgres" is not one thing. A field guide to egress cliffs, daemon traffic, and why a product studio needs one database trunk — not twelve Neon saplings.
excerpt: Your app did not forget you. Your database vendor suspended compute because you moved too many bytes. Here is what that means, why Cockpit is the worst possible customer for Neon free, and where we are going instead.
publishedAt: 2026-05-22
tags: infrastructure,database,neon,postgres,vercel,architecture,studio
featured: true
author: g
readingTimeMin: 22
---
## You Did Not Forget Your Password. The Database Got Turned Off.
One morning Cockpit stopped letting anyone sign in. The Control page looked like a fresh install: no projects, daemon offline, onboarding banners everywhere. The natural reaction is to blame auth — wrong password, expired session, GitHub OAuth misconfigured.
None of that was the problem.
The error from Postgres, when you finally looked past the generic "incorrect email or password" message, was stranger:
> **Your project has exceeded the data transfer quota. Upgrade your plan to increase limits.**
Translation: **Neon turned the database off.** Not deleted. Not corrupted. *Suspended.* Like a landlord cutting power because you ran the dryer too often.
The app was fine. Vercel was fine. The code was fine. **The bytes leaving the database hit a free-tier ceiling** — and on Neon free, that ceiling has teeth.
This essay is what we learned fixing it, and how we think about database hosting when you are not building one CRUD app but a **control plane** that polls, pushes, streams, and never quite goes to sleep.
---
## A Quick Map of Where Data Lives
Before the jargon, picture the stack Cockpit actually runs:
```mermaid
flowchart TB
subgraph browser["Your browser"]
UI[Cockpit UI on Vercel]
end
subgraph vercel["Vercel serverless"]
API[Next.js API routes]
end
subgraph neon["Neon Postgres (managed)"]
DB[(Rows: users, projects, people, queue…)]
end
subgraph laptop["Your machine"]
Daemon[cockpit-daemon.sh]
Zellij[Zellij + agents]
end
UI --> API
API --> DB
Daemon -->|push every ~2s| API
API --> DB
Zellij --> Daemon
```
Three clients hammer one database:
1. **You**, clicking around the UI.
2. **Vercel**, spinning up serverless functions that each open a connection, run queries, return JSON.
3. **The daemon**, a small bash loop on your laptop that long-polls the cloud and **pushes runtime state every couple of seconds** so Control shows live Zellij tabs.
That third client is unusual. Most "Next.js + Postgres" tutorials assume your database sighs with relief at 3am. Cockpit's database gets pinged like a group chat where someone never mutes notifications.
---
## Concept 1: Postgres Is a Server, Not a File
If you have only ever used SQLite or "database = file on disk," managed Postgres takes a minute to internalize.
**PostgreSQL is a program** listening on a port (usually 5432). Your app sends **SQL over the network**. The server returns **rows** — serialized as bytes — back over the network.
Every `SELECT * FROM people` is not "reading a file." It is:
1. TCP connection (maybe TLS handshake)
2. Query parsed and executed
3. **Result set streamed back to the client**
Those returned bytes are what vendors often call **egress** (data leaving *their* data center toward *your* app). Ingress is the trip in. Writes cost too, but for read-heavy dashboards **egress is the silent budget line**.
Neon free includes about **5 GB of public egress per month**. That sounds like a lot until you multiply:
| Traffic source | Rough math |
|----------------|------------|
| Daemon push every 2s | ~43,000 requests/day |
| Each request touches DB read/write | kilobytes add up |
| Control page polling / SSE | more reads |
| Local dev accidentally pointed at prod | you pay twice — once in life, once in egress |
| 1,300+ contact rows with JSONB | fat result sets |
We did not hit 5 GB because Cockpit is badly written. We hit it because **the product shape is chatty** — and free tier pricing assumes you are not.
---
## Concept 2: Direct vs Pool — Two URLs, One Database
Another lesson that only bites in serverless: **how you connect matters**.
PostgreSQL has a limited number of concurrent connections. Vercel functions are **many short-lived processes**. If each one opens a raw connection to Postgres, you exhaust `max_connections` and get errors that look like random 500s.
The fix is a **pooler** — typically **PgBouncer** — sitting in front of Postgres:
```
Vercel function ──► pooler :6432 ──► postgres :5432
(many clients, few server conns)
```
Cockpit now uses two environment variables (vendor-neutral names):
| Variable | Use |
|----------|-----|
| `DATABASE_URL` | **Direct** connection — migrations, `LISTEN/NOTIFY`, DDL |
| `DATABASE_POOL_URL` | **Pooled** connection — normal app queries on Vercel |
Some features **cannot** go through a pooler. Cockpit's Control SSE stream uses Postgres `LISTEN` for sub-second updates when the daemon pushes state. Poolers in transaction mode drop long-lived listeners. So you need **both** URLs in production.
Neon gives you a `-pooler` host automatically. Self-hosted Oracle/Hetzner setup means you run PgBouncer yourself — we packaged that in `infra/postgres-host/` for when we migrate.
**Takeaway:** "Just give me one connection string" works on localhost. Serverless production wants two.
---
## Concept 3: Managed vs Self-Hosted — Who Owns the Kill Switch?
| | **Managed** (Neon, Supabase, RDS…) | **Self-hosted** (Oracle VM, Hetzner VPS) |
|--|-------------------------------------|------------------------------------------|
| You operate | Connection strings | OS patches, Postgres backups, PgBouncer, firewall |
| Vendor operates | Postgres version, uptime, quotas | Power and disk (hopefully) |
| Billing | Usage meters — egress, CU-hours, storage | Fixed monthly (or $0 Oracle Always Free) |
| Kill switch | **Quota exceeded → suspend** | **You forget backups → regret** |
Managed is renting an apartment with utilities included until you blast the AC. Self-hosted is owning a small house — nobody cuts your power for bandwidth, but the roof is yours.
Cockpit's outage was a **managed kill switch**: zero bytes malicious, just economics.
---
## What Actually Happened to Us (Timeline)
Worth documenting because it explains why production felt like a "new account."
1. **Production** lived on Neon project `ep-bold-shape-…` (EU).
2. **Local dev** was also pointed at that same Neon URL — the opposite of "local Docker for dev, cloud for prod."
3. **Daemon** ran 24/7 with `COCKPIT_DAEMON_FORCE_REMOTE=1`, pushing to Vercel → Neon constantly.
4. **Egress quota** exhausted. Neon suspended compute. Sign-in failed. Control empty.
5. **Emergency fix:** new Neon project `bitbaum-pg` (fresh quota), schema pushed, Vercel env updated, redeploy.
6. **Empty account:** new database has no rows. GitHub sign-in creates a user; zero projects. Correct behavior for an empty DB — infuriating for a human.
7. **Restore:** copied data from **local** Postgres (which still had 20 projects and 1,300 people) into production with `scripts/db/sync-user-data.sh`.
The old Neon project still holds whatever was only in prod at freeze time — **still unreachable** until quota resets or we pay. Local dev had been a accidental backup. Not a strategy. A rescue.
---
## The Studio Sprawl Problem
Cockpit is one repo in a folder of many. A scan of `~/dev` showed the pattern:
- **Six+ apps** on various Neon endpoints
- **Two+ Supabase projects** (orangecat, printcraft — auth, storage, RLS)
- Some apps sharing one Neon host; some alone
- Each `.env.local` a snowflake
That is not a platform. That is **twelve free trials wearing a trench coat**.
The bitbaum README says "shared infrastructure, many products." The infra stack said "one Neon signup per side project." Those two sentences were fighting each other.
**Rule we are adopting:** one Postgres **trunk** (one VM or one paid org strategy), **many databases** (`cockpit`, `kivvi`, `revampit`, …). Vercel stays per-app. Supabase stays where the product *is* Supabase.
---
## Option A: Neon Free — The Free Tier That Fired Us
**Pros**
- Sign up in minutes, no credit card
- Branching, serverless scale-to-zero, pretty dashboard
- Perfect for a **hackathon CRUD app** or a schema you touch twice a week
**Cons (for Cockpit)**
- **5 GB egress** then **hard suspend** — not throttle, *off*
- Chatty apps burn quota silently until auth breaks
- Easy to accidentally aim local dev at prod
- Multiple projects ≠ multiple free lunches if org egress is shared
**Verdict:** Neon free is **not a production home for Cockpit**. It can be a **temporary bridge** (what `bitbaum-pg` is today) or a **preview database** for branches. Not the trunk.
---
## Option B: Neon Launch (~$5/mo and up)
**Pros**
- Same DX, no ops, 100 GB egress on paid tiers
- Fixes the immediate "turned off" problem with money
- Drizzle, Auth.js, Vercel — unchanged
**Cons**
- Usage-based bill grows with daemon traffic and project count
- **Per-app Neon** across a studio multiplies cost and complexity
- Still two URLs, still metered egress beyond allowance
**Verdict:** Reasonable for **one flagship SaaS** with bursty traffic. Poor fit for **George + twelve repos + always-on daemon**. You are paying rent on every sapling instead of one yard.
---
## Option C: Supabase — Keep It Where the Product Is Supabase
Orangecat is not "Postgres with extra steps." It is **Postgres + Auth + RLS + Storage + Realtime** as one product. Moving orangecat to a raw VM Postgres would be a **rewrite**, not a migration.
**Pros**
- BaaS features integrated; RLS in the database layer
- Free tier generous for **full-stack** use (with idle pause caveats)
**Cons**
- Paying for a bundle when you only need Postgres (Cockpit uses Auth.js — wrong fit)
- Same egress class of limits on free
- Two active free projects per org
**Verdict:** **Stay on Supabase for Supabase apps.** Do not force Cockpit onto it just to consolidate bills.
---
## Option D: Oracle Always Free — The Controversial $0 Datacenter
Oracle's Always Free tier is the internet's favorite punchline and secret weapon: up to **4 ARM cores, 24 GB RAM, 200 GB disk**, absurd **egress** compared to Neon free.
**Pros**
- **$0** with real hardware specs
- One VM runs Postgres + PgBouncer for **many databases**
- Egress cliff essentially gone for studio-scale traffic
- Matches "I run a product studio, not one startup" economics
**Cons**
- **Signup and capacity** — "Out of host capacity in Frankfurt" is a meme for a reason
- **You are the DBA** — backups, upgrades, TLS, firewall
- ARM — fine for Node/Postgres; occasional binary annoyance
- Oracle support is "community forum and vibes"
**Verdict:** **Best $0 trunk** for Cockpit + sibling Drizzle apps if you can provision the VM. We packaged `infra/postgres-host/` and `scripts/db/deploy-host.sh` for this path.
---
## Option E: Hetzner — What Levelsio Pays €7 For
Pieter Levels does not use Oracle free because he hates money. He uses Hetzner because **€7/month buys boring reliability** — instant provisioning, EU datacenter, predictable invoice, no quota suspend at 5 GB.
**Pros**
- **CX32 ~€7/mo** — run dozens of small app databases on one box
- 20 TB traffic included — daemon can be daemon
- Simple mental model: one bill, one SSH key, one backup cron
**Cons**
- Not free
- Still self-hosted Postgres (same ops as Oracle, easier signup)
**Verdict:** **Best paid trunk** for a multi-project studio. Upgrade path from Oracle without architectural change — `pg_dump`, new URL, redeploy.
---
## Side-by-Side (Cockpit-Shaped)
| | Neon free | Neon paid | Oracle free | Hetzner ~€7 |
|--|-----------|-----------|-------------|-------------|
| **Monthly cost** | $0 | $5+ | $0 | ~€7 |
| **Survives daemon 24/7** | ❌ | ✅ | ✅ | ✅ |
| **Survives dev mistake** | ❌ | ⚠️ | ✅ | ✅ |
| **Ops burden** | None | None | Medium | Medium |
| **Studio (10 DBs)** | Fragile | Expensive | ✅ one VM | ✅ one VM |
| **Kill switch** | Quota | Bill | You forget backups | You forget backups |
---
## Our Recommendation (May 2026)
**Short term:** `bitbaum-pg` keeps production alive while we migrate — not a destination.
**Medium term (free):** **Oracle Always Free VM** → Postgres 17 + PgBouncer → one database per project → Vercel env points at VM.
**When revenue or stress appears:** Same layout on **Hetzner CX32**. No Neon Scale per app. No five VPSes.
**Permanent exceptions:** **Supabase** for orangecat / printcraft. **Local Docker** for every `.env.local`. **Never** prod URL on the laptop.
**Neon free verdict for Cockpit:** *workable as a lab; unworkable as production.* The product is a **life OS + fleet command center**, not a todo app you open twice a week.
---
## What We Built So Switching Is Boring
The goal is: **host change = env vars + dump/restore**, not a rewrite.
Already in the repo:
- `src/lib/db-url.ts` — vendor-neutral pool vs direct URLs
- `docs/infrastructure/postgres-portability.md` — cutover checklist
- `scripts/db/dump.sh` / `restore.sh` — portable backups
- `scripts/db/sync-user-data.sh` — user-scoped row copy between hosts
- `infra/postgres-host/` — Docker Compose for Postgres + PgBouncer on any VM
Switching from Neon → Oracle → Hetzner should feel like changing landlords, not rebuilding the house.
---
## Rules We Are Actually Going to Follow
Because the best infrastructure essay is useless if `.env.local` still points at prod on Tuesday.
1. **Local dev uses local Postgres only.** Docker Compose on `localhost:5432`. Full stop.
2. **Production uses two URLs** — direct + pool — on Vercel.
3. **One trunk, many databases** — not one Neon project per hack.
4. **Daemon off** when not testing Control — or accept you are paying (in quota or €) for always-on.
5. **Supabase stays Supabase** — don't migrate BaaS apps to raw Postgres without a design doc and a long holiday.
6. **Backups before heroics** — `npm run db:dump` before any cutover. Local dev accidentally saved us once. That is not a backup strategy.
---
## The Deeper Lesson (Why This Is Interesting)
Serverless changed **where code runs** — functions appear, handle a request, vanish. It did not change **where truth lives**. Truth still lives in Postgres rows: your projects, your people, your queue, your session handoff metadata.
Managed Postgres vendors price along axes that assume:
- Moderate read/write volume
- Connections that behave like a small pool of app servers
- Humans who do not aim their dev laptop at production
Cockpit violates all three. It is a **control plane** — closer to observability or ops tooling than to a marketing site. The database sees traffic patterns like a **monitoring agent**, not like a blog.
That mismatch is the real story. Neon free did not "fail." **We picked a pricing model that assumes a different species of app.**
Once you see that, the fix is obvious: either **pay for managed** at the tier that matches chatty traffic, or **own the metal** (Oracle/Hetzner) and stop negotiating with egress meters.
---
## Closing: The Walk Test Applies to Data Too
We wrote elsewhere about the **Walk Test** — Cockpit must work from your phone while the daemon keeps running at home. That test fails if the cloud database is suspended because you moved five gigabytes of rows.
Infrastructure is not separate from product. **The kill switch on the database is a kill switch on the walk.**
We are moving the trunk to infrastructure we control — first Oracle free, then Hetzner when €7 is cheaper than anxiety. Neon free stays in the toolbox for experiments, not for the fleet.
If you are building something quiet, Neon free is lovely. If you are building something that ** listens for NOTIFY and pushes state every two seconds**, buy the house — or take Oracle's weird free one — and sleep through the night.
---
*Follow-up to [Groq, Neon, and the Next Infrastructure Layer](/thoughts/groq-neon-and-the-next-infra-layer) — written when Neon was "already provisioned, just wire Vercel." We wired it. Then it turned us off. This is the corrected chapter.*
+8 -5
View File
@@ -2,8 +2,8 @@
---
created_date: 2026-05-21
last_modified_date: 2026-05-21
last_modified_summary: Document runtime_snapshots openTabs push for cloud Live Zellij panel; note Control fleet-first layout.
last_modified_date: 2026-05-22
last_modified_summary: Link to thoughts article on database kill switch and studio trunk strategy.
---
Cockpit is a **hybrid** product: the hosted web app (cloud control plane) owns auth, the database, and the UI; your machine (local runtime) executes agents, git, calendar, and terminal injection.
@@ -14,16 +14,17 @@ This document is the SSOT for onboarding and support — keep it aligned with `D
| Step | Where | Install required? |
|------|-------|-----------------|
| 1. Sign in (GitHub OAuth) | Browser | No |
| 2. Onboarding (username, optional project) | Browser | No |
| 1. Sign in (GitHub OAuth or email) | Browser | No |
| 2. Onboarding — username, optional first project, connect machine | Browser | No (runtime step skippable) |
| 3. Use goals, projects metadata, prompts library, settings | Browser | No |
| 4. Dispatch agents from Control | Browser + **local setup** | Yes — see below |
| 4. Dispatch agents from Control | Browser + **local setup** | Yes — onboarding step 3 or Settings |
### Local setup (agent dispatch only)
1. **[Zellij](https://zellij.dev/)** — terminal multiplexer; Cockpit injects prompts into tabs.
2. **At least one agent CLI** on `$PATH` — not all of them:
- Claude Code (`claude`)
- Cursor Agent (`agent` — [install](https://cursor.com/docs/cli))
- Codex (`codex`)
- Gemini CLI (`gemini`)
- openclaw
@@ -105,5 +106,7 @@ Until the daemon connects, Control **queues** dispatches and runs them when the
## Related docs
- `CLAUDE.md` — engineering conventions
- `docs/infrastructure/postgres-portability.md` — vendor-neutral DB env vars, dump/restore, future Oracle/Hetzner migration
- [The Database Kill Switch](/thoughts/the-database-kill-switch-neon-oracle-and-the-studio-stack) — postmortem, egress, Neon vs Oracle vs Hetzner
- `home/README.md` — experimental local Brain+Bridge+Worker stack (`:3001`), separate from SaaS default path
- `docs/debt-reduction-roadmap.md` — orchestration consolidation plan
+141
View File
@@ -0,0 +1,141 @@
# Postgres portability (studio-wide)
---
created_date: 2026-05-22
last_modified_date: 2026-05-23
last_modified_summary: Document Oracle bootstrap/cutover scripts and one-console-step flow.
---
Goal: **switching Postgres host later is a config + dump/restore job**, not a code rewrite.
Long-form narrative: [The Database Kill Switch](/thoughts/the-database-kill-switch-neon-oracle-and-the-studio-stack).
Applies to Cockpit first; copy the same env pattern to other Drizzle/Prisma apps in `~/dev`.
## Principles
1. **Standard Postgres only** — no vendor-specific SQL, extensions, or SDKs in app code.
2. **Two URLs in production** — direct for migrations/LISTEN; pooled for serverless queries.
3. **Local dev never hits cloud** — `.env.local` → Docker Postgres on `localhost`.
4. **One database per project** on a shared host (Oracle/Hetzner) when you migrate — not one Neon project per app.
5. **Supabase stays Supabase** — orangecat/printcraft use auth, RLS, storage; do not force them onto plain Postgres without a rewrite.
## Environment variables (SSOT)
| Variable | Purpose | Who sets it |
|----------|---------|-------------|
| `DATABASE_URL` | **Direct** session (`:5432`) — migrations, `drizzle-kit push`, LISTEN/NOTIFY | Vercel + local dev |
| `DATABASE_POOL_URL` | **Pooled** session (PgBouncer `:6432`, Neon pooler, Supabase pooler) — app runtime queries | Vercel production only |
**Local dev:** set `DATABASE_URL` only. Pool URL falls back to the same value.
**Legacy (Cockpit still reads these):** `NEON_DATABASE_URL` → pool, `NEON_DATABASE_URL_DIRECT` → direct. Prefer the neutral names on new hosts.
Implementation: `src/lib/db-url.ts` — `getDatabasePoolUrl()`, `getDatabaseDirectUrl()`.
## Dev vs production
```
┌─────────────────────────────────────────────────────────────┐
│ Laptop: docker compose up db │
│ DATABASE_URL=postgresql://cockpit:changeme@localhost:5432/cockpit
│ (never the cloud URL in .env.local) │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ Vercel (unchanged app code when host changes) │
│ DATABASE_URL=postgresql://user:pass@host:5432/cockpit │
│ DATABASE_POOL_URL=postgresql://user:pass@host:6432/cockpit │
└─────────────────────────────────────────────────────────────┘
```
## Self-hosted target layout (Oracle or Hetzner)
One VM, Postgres 17, optional PgBouncer:
```bash
# On the VM (example)
createdb cockpit
createdb kivvi
createdb revampit
# … one DB per project
# PgBouncer listens on 6432 → forwards to localhost:5432
```
Point each Vercel project at its own database name on the same host.
## Migration runbook (when you switch)
### Full database (schema + data)
```bash
# 1. Backup source
DATABASE_URL="$OLD_DIRECT_URL" ./scripts/db/dump.sh cockpit-pre-migrate.sql.gz
# 2. Create empty DB on new host, push schema
DATABASE_URL="$NEW_DIRECT_URL" npm run migrate
# 3. Restore
DATABASE_URL="$NEW_DIRECT_URL" ./scripts/db/restore.sh cockpit-pre-migrate.sql.gz
# 4. Update Vercel env (both URLs), redeploy
# 5. Smoke test sign-in + one CRUD path + Control daemon push
```
### User data only (schema already on target)
```bash
SOURCE_DATABASE_URL="$OLD" TARGET_DATABASE_URL="$NEW" TARGET_USER_ID="<uuid>" \
./scripts/db/sync-user-data.sh
```
### Cutover checklist
- [ ] `DATABASE_URL` (direct) and `DATABASE_POOL_URL` (pool) set on Vercel
- [ ] Local `.env.local` still points at Docker — not new prod
- [ ] `npm run migrate` succeeds against new direct URL
- [ ] Auth sign-in works
- [ ] Control SSE / daemon push updates `runtime_snapshots`
- [ ] Decommission old Neon project after 7 days
## Cockpit scripts
| Script | Purpose |
|--------|---------|
| `npm run test:db-url` | Assert URL resolution logic |
| `scripts/db/dump.sh` | Portable `pg_dump` backup |
| `scripts/db/restore.sh` | Restore into target DB |
| `scripts/db/sync-user-data.sh` | Copy user-owned rows between DBs |
| `scripts/migrate-local-to-neon.sh` | Wrapper → `sync-user-data.sh` |
| `npm run db:oracle-bootstrap` | SSH key + cloud-init for Oracle VM (one-time) |
| `npm run db:oracle-cutover` | Dump Neon → deploy VM stack → restore → Vercel env + redeploy |
## Oracle cutover (minimal manual steps)
1. **One-time on laptop:** `npm run db:oracle-bootstrap` — writes `~/.config/cockpit/oracle-migration.env` and `oracle-cloud-init.yaml`.
2. **One-time in Oracle Console (~5 min):** Create **VM.Standard.A1.Flex** Ubuntu ARM instance; paste cloud-init; note public IP.
3. **Automated:** `ORACLE_HOST=<ip> npm run db:oracle-cutover` — dumps current prod, installs Docker stack on VM, restores, updates Vercel `DATABASE_URL` + `DATABASE_POOL_URL`, redeploys.
Cloud-init template: `infra/postgres-host/cloud-init.yaml`. Public ports: `5432` (direct), `6432` (PgBouncer). Use a strong generated password only — no Neon-style SSL required for initial cutover (`sslmode=disable` on pool URL).
## What we are *not* doing yet
- Supabase-native apps (orangecat) stay on Supabase
## Interim production (2026-05-22)
Neon project `bitbaum-pg` replaced quota-exhausted `ep-bold-shape-…`. See [The Database Kill Switch](/thoughts/the-database-kill-switch-neon-oracle-and-the-studio-stack) for the full postmortem and target architecture (Oracle/Hetzner trunk).
Vercel uses `DATABASE_URL` (direct) + `DATABASE_POOL_URL` (pooler). Local dev uses Docker only.
When the VM is ready, `pg_dump` from bitbaum-pg → restore on self-hosted → update Vercel env.
## Other projects in `~/dev`
| Pattern | Action |
|---------|--------|
| Drizzle/Prisma + Neon | Add `DATABASE_POOL_URL` on Vercel; local Docker only |
| Supabase-native (orangecat, printcraft) | Keep Supabase; skip this doc for DB |
| Local-only (reparaturbonus, datacat) | Already portable — use same dump/restore pattern |
Extract `src/lib/db-url.ts` into a shared snippet or copy per repo when you migrate the second app.
+8 -2
View File
@@ -1,11 +1,17 @@
import { defineConfig } from "drizzle-kit";
import { getDatabaseDirectUrl } from "./src/lib/db-url";
const url = getDatabaseDirectUrl();
if (!url) {
throw new Error("DATABASE_URL is required for drizzle-kit (direct connection, not pool URL)");
}
export default defineConfig({
schema: "./src/db/schema",
out: "./drizzle",
dialect: "postgresql",
dbCredentials: {
// Use direct (non-pooled) URL for migrations — pooler doesn't support DDL
url: process.env.NEON_DATABASE_URL_DIRECT ?? process.env.DATABASE_URL!,
// Direct URL only — poolers (Neon, PgBouncer) do not support DDL reliably.
url,
},
});
+3
View File
@@ -0,0 +1,3 @@
# Copy to .env on the VM — never commit .env
POSTGRES_USER=studio
POSTGRES_PASSWORD=generate-with-openssl-rand-base64-24
+29
View File
@@ -0,0 +1,29 @@
#cloud-config
# Oracle Always Free — Ubuntu 22.04/24.04 ARM (VM.Standard.A1.Flex)
# Paste into: Instance → "Cloud-init script" when creating the VM.
# Replace __SSH_PUBLIC_KEY__ with output from: scripts/db/oracle-bootstrap.sh
package_update: true
packages:
- docker.io
- docker-compose-v2
- ufw
ssh_authorized_keys:
- __SSH_PUBLIC_KEY__
users:
- default
- name: ubuntu
groups: docker
sudo: ALL=(ALL) NOPASSWD:ALL
runcmd:
- systemctl enable --now docker
- usermod -aG docker ubuntu
- ufw allow 22/tcp
- ufw allow 5432/tcp
- ufw allow 6432/tcp
- ufw --force enable
final_message: "Cockpit Postgres host ready. Run oracle-cutover.sh from your laptop."
@@ -0,0 +1,9 @@
# Override: expose Postgres + PgBouncer on all interfaces (Oracle/Hetzner public IP).
# Used by scripts/db/oracle-cutover.sh — protect with strong POSTGRES_PASSWORD + firewall.
services:
postgres:
ports:
- "0.0.0.0:5432:5432"
pgbouncer:
ports:
- "0.0.0.0:6432:5432"
+44
View File
@@ -0,0 +1,44 @@
# Self-hosted Postgres for Cockpit + studio apps (Oracle Always Free / Hetzner VPS).
# Run on a VM with: docker compose up -d
#
# Expose:
# :5432 direct → DATABASE_URL (migrations, LISTEN/NOTIFY)
# :6432 pool → DATABASE_POOL_URL (Vercel / serverless)
#
# See docs/infrastructure/postgres-portability.md
services:
postgres:
image: postgres:17-alpine
restart: unless-stopped
environment:
POSTGRES_USER: ${POSTGRES_USER:-studio}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
volumes:
- pg_data:/var/lib/postgresql/data
- ./init:/docker-entrypoint-initdb.d:ro
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-studio}"]
interval: 5s
timeout: 3s
retries: 10
ports:
- "127.0.0.1:5432:5432"
pgbouncer:
image: edoburu/pgbouncer:v1.24.1-p1
restart: unless-stopped
depends_on:
postgres:
condition: service_healthy
environment:
DATABASE_URL: postgres://${POSTGRES_USER:-studio}:${POSTGRES_PASSWORD}@postgres:5432/cockpit
POOL_MODE: transaction
MAX_CLIENT_CONN: 200
DEFAULT_POOL_SIZE: 20
AUTH_TYPE: scram-sha-256
ports:
- "127.0.0.1:6432:5432"
volumes:
pg_data:
+14
View File
@@ -0,0 +1,14 @@
#!/bin/bash
# Creates one database per studio project. Extend this list as you migrate apps.
set -euo pipefail
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname postgres <<'EOSQL'
CREATE DATABASE cockpit;
CREATE DATABASE kivvi;
CREATE DATABASE revampit;
CREATE DATABASE revamp_info;
CREATE DATABASE aoz_housing;
CREATE DATABASE petvity;
CREATE DATABASE vitareba;
CREATE DATABASE surf_your_life;
EOSQL
+18
View File
@@ -7,6 +7,9 @@
"": {
"name": "cockpit",
"version": "0.1.0",
"workspaces": [
"packages/*"
],
"dependencies": {
"@auth/drizzle-adapter": "^1.11.2",
"@base-ui/react": "^1.3.0",
@@ -622,6 +625,10 @@
"integrity": "sha512-lB59uJoaGIfOOL9knQqQRfhl9g7x8/wqFkp13zTdkRu1huG9kg6IJs1O8hqj9rs6h7orGxHJUKb+mX3rPbWGhA==",
"license": "Apache-2.0"
},
"node_modules/@cockpit/agent": {
"resolved": "packages/agent",
"link": true
},
"node_modules/@dnd-kit/accessibility": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",
@@ -13414,6 +13421,17 @@
"peerDependencies": {
"zod": "^3.25.0 || ^4.0.0"
}
},
"packages/agent": {
"name": "@cockpit/agent",
"version": "0.1.0",
"license": "MIT",
"bin": {
"cockpit-agent": "bin/cockpit-agent.js"
},
"engines": {
"node": ">=18"
}
}
}
}
+7
View File
@@ -16,6 +16,13 @@
"check:design": "bash scripts/check-design-system.sh",
"smoke": "bash scripts/smoke.sh",
"test:home": "bash scripts/test-home.sh",
"test:control-presenter": "npx tsx scripts/test/control-presenter.ts",
"test:onboarding": "npx tsx scripts/test/onboarding.ts",
"test:db-url": "npx tsx scripts/test/db-url.ts",
"db:dump": "bash scripts/db/dump.sh",
"db:restore": "bash scripts/db/restore.sh",
"db:oracle-bootstrap": "bash scripts/db/oracle-bootstrap.sh",
"db:oracle-cutover": "bash scripts/db/oracle-cutover.sh",
"wait:vercel": "bash scripts/wait-for-vercel.sh",
"ship": "git push origin main && bash scripts/wait-for-vercel.sh",
"prepare": "husky"
+6 -1
View File
@@ -18,11 +18,16 @@ check_none() {
fi
}
check_none "custom ui-* classes used inside @apply" '@apply .*ui-' src/app/globals.css
check_none "custom ui-* classes used inside @apply in TSX" '@apply .*ui-' src/components src/app -g '*.tsx'
check_none "raw shared search input recipe outside primitive" 'w-full rounded-2xl border border-border-default bg-surface-overlay .*pl-11 .*pr-16' src/components src/app -g '!src/app/globals.css'
check_none "raw code-surface recipe outside primitive" 'rounded-\[1\.5rem\] border border-border-subtle bg-surface-overlay p-4 .*leading-relaxed text-text-secondary' src/components src/app -g '!src/app/globals.css'
check_none "raw subtle link text recipe outside primitive" 'text-xs text-text-tertiary .*hover:text-text-secondary' src/components src/app -g '!src/app/globals.css'
# Layer 4: JSX must not use raw palette or white-opacity utilities — auth/public
# tokens live in globals.css ui-auth-* / ui-public-* / ui-brand-* classes.
check_none "raw palette colors in components" 'text-gray-|text-slate-|text-zinc-|text-blue-|text-green-|text-red-|text-purple-|text-yellow-|text-orange-|text-cyan-|text-violet-|bg-gray-|bg-blue-|bg-green-|bg-red-|bg-\[#|text-\[#|text-\[1[0-9]px\]|text-\[8px\]' src/components src/app -g '*.tsx' -g '!**/opengraph-image.tsx'
check_none "raw white opacity utilities in JSX" 'text-white/|bg-white/|border-white/' src/components src/app -g '*.tsx' -g '!**/opengraph-image.tsx'
if [[ "$fail" -ne 0 ]]; then
exit 1
fi
+14 -4
View File
@@ -488,21 +488,31 @@ _sentinel() {
echo "null"
}
# Scan /proc once; output lines of "<cwd> <agent_basename>" for all running agents.
# Scan /proc once; output lines of "<cwd> <agent_id>" for all running agents.
_scan_agents() {
for pd in /proc/[0-9]*/; do
pd="${pd%/}"
[ -f "$pd/cmdline" ] || continue
local argv0 basename
local argv0 basename agent_id
argv0=$(tr '\0' '\n' < "$pd/cmdline" 2>/dev/null | head -1) || continue
basename="${argv0##*/}"
case "$basename" in
claude|codex|gemini|openclaw) ;;
claude|codex|gemini|openclaw)
agent_id="$basename"
;;
agent)
# Cursor Agent CLI — skip unrelated `agent` binaries on PATH.
if [[ "$argv0" == *".local/bin/agent"* ]] || [[ "$argv0" == *"/.cursor/"* ]]; then
agent_id="cursor"
else
continue
fi
;;
*) continue ;;
esac
local cwd
cwd=$(readlink "$pd/cwd" 2>/dev/null) || continue
echo "$cwd $basename"
echo "$cwd $agent_id"
done
}
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env bash
# Bootstrap Postgres host on a fresh Ubuntu VM (Oracle Always Free / Hetzner).
#
# Usage (on the VM):
# curl -fsSL https://raw.githubusercontent.com/.../deploy-host.sh | bash
# Or copy infra/postgres-host/ to the VM and run:
# cd infra/postgres-host && cp .env.example .env && $EDITOR .env && ./deploy-host.sh
#
# After deploy:
# DATABASE_URL=postgresql://studio:PASS@HOST:5432/cockpit
# DATABASE_POOL_URL=postgresql://studio:PASS@HOST:6432/cockpit
# Open :5432/:6432 to Vercel IPs only, or use Cloudflare Tunnel (recommended).
set -euo pipefail
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
HOST_DIR="$DIR/../../infra/postgres-host"
if [ ! -f "$HOST_DIR/.env" ]; then
echo "Create $HOST_DIR/.env from .env.example first." >&2
exit 2
fi
if ! command -v docker >/dev/null 2>&1; then
echo "Installing Docker..."
curl -fsSL https://get.docker.com | sh
sudo usermod -aG docker "$USER" 2>/dev/null || true
fi
chmod +x "$HOST_DIR/init/"*.sh 2>/dev/null || true
docker compose -f "$HOST_DIR/docker-compose.yml" --env-file "$HOST_DIR/.env" up -d
echo ""
echo "Postgres host is up (localhost-only ports bound — open firewall or tunnel for Vercel)."
echo "Next: DATABASE_URL on Vercel → push schema with npm run migrate"
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env bash
# Logical backup of the Cockpit database (portable across Postgres hosts).
#
# Usage:
# DATABASE_URL=postgresql://... ./scripts/db/dump.sh [output.sql.gz]
#
# Defaults DATABASE_URL from .env.local when unset (direct URL preferred).
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
if [ -z "${DATABASE_URL:-}" ] && [ -f "$ROOT/.env.local" ]; then
set -a
# shellcheck source=/dev/null
source "$ROOT/.env.local"
set +a
fi
URL="${DATABASE_URL:-${NEON_DATABASE_URL_DIRECT:-}}"
if [ -z "$URL" ]; then
echo "ERROR: set DATABASE_URL (direct connection) before running." >&2
exit 2
fi
OUT="${1:-$ROOT/backups/cockpit-$(date +%Y%m%d-%H%M%S).sql.gz}"
mkdir -p "$(dirname "$OUT")"
echo "Dumping to $OUT ..."
pg_dump "$URL" --no-owner --no-acl --format=plain | gzip > "$OUT"
echo "Done ($(du -h "$OUT" | cut -f1))"
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env bash
# One-time setup for Oracle migration: SSH key, DB password, cloud-init snippet.
# Run once: ./scripts/db/oracle-bootstrap.sh
# Then create Oracle VM (console) with generated cloud-init, run oracle-cutover.sh
set -euo pipefail
CONFIG_DIR="${HOME}/.config/cockpit"
CONFIG_FILE="${CONFIG_DIR}/oracle-migration.env"
KEY="${CONFIG_DIR}/oracle_ed25519"
CLOUD_INIT_OUT="${CONFIG_DIR}/oracle-cloud-init.yaml"
mkdir -p "$CONFIG_DIR"
chmod 700 "$CONFIG_DIR"
if [ ! -f "$KEY" ]; then
ssh-keygen -t ed25519 -f "$KEY" -N "" -C "cockpit-oracle-$(date +%Y%m%d)"
echo "Created SSH key: $KEY"
fi
if [ ! -f "$CONFIG_FILE" ]; then
PW="$(openssl rand -base64 24 | tr -d '/+=' | head -c 32)"
cat > "$CONFIG_FILE" <<EOF
# Cockpit Oracle migration — generated $(date -Iseconds)
ORACLE_SSH_KEY=$KEY
ORACLE_SSH_USER=ubuntu
POSTGRES_USER=studio
POSTGRES_PASSWORD=$PW
ORACLE_HOST=
EOF
chmod 600 "$CONFIG_FILE"
echo "Wrote $CONFIG_FILE"
else
# shellcheck source=/dev/null
source "$CONFIG_FILE"
fi
PUBKEY="$(cat "${KEY}.pub")"
sed "s|__SSH_PUBLIC_KEY__|${PUBKEY}|" "$(dirname "$0")/../../infra/postgres-host/cloud-init.yaml" > "$CLOUD_INIT_OUT"
echo ""
echo "=== Oracle bootstrap complete ==="
echo ""
echo "ONE manual step in Oracle Cloud Console (≈5 min):"
echo " 1. Compute → Instances → Create instance"
echo " 2. Shape: VM.Standard.A1.Flex (Ampere) — 1 OCPU, 6 GB RAM is enough"
echo " 3. Image: Ubuntu 22.04 or 24.04 (aarch64)"
echo " 4. Paste cloud-init from: $CLOUD_INIT_OUT"
echo " 5. Note the public IP when the instance is RUNNING"
echo ""
echo "Then run (automated from here):"
echo " ORACLE_HOST=<public-ip> npm run db:oracle-cutover"
echo ""
echo "Or add ORACLE_HOST to $CONFIG_FILE and run:"
echo " npm run db:oracle-cutover"
echo ""
+136
View File
@@ -0,0 +1,136 @@
#!/usr/bin/env bash
# Migrate Cockpit production Postgres: Neon → Oracle VM (minimal manual steps).
#
# Prerequisites (one-time):
# ./scripts/db/oracle-bootstrap.sh
# Create Oracle VM with generated cloud-init (~5 min in console)
#
# Usage:
# ORACLE_HOST=1.2.3.4 npm run db:oracle-cutover
# npm run db:oracle-cutover # if ORACLE_HOST is in ~/.config/cockpit/oracle-migration.env
#
# This script: dump prod → deploy docker on VM → restore → update Vercel → redeploy.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
CONFIG_FILE="${COCKPIT_ORACLE_CONFIG:-${HOME}/.config/cockpit/oracle-migration.env}"
BACKUP="${ROOT}/backups/oracle-cutover-$(date +%Y%m%d-%H%M%S).sql.gz"
if [ ! -f "$CONFIG_FILE" ]; then
echo "Run ./scripts/db/oracle-bootstrap.sh first." >&2
exit 2
fi
# shellcheck source=/dev/null
source "$CONFIG_FILE"
ORACLE_HOST="${ORACLE_HOST:-${1:-}}"
if [ -z "$ORACLE_HOST" ]; then
echo "Set ORACLE_HOST (public IP of Oracle VM)." >&2
echo " ORACLE_HOST=x.x.x.x npm run db:oracle-cutover" >&2
exit 2
fi
SSH_KEY="${ORACLE_SSH_KEY:?}"
SSH_USER="${ORACLE_SSH_USER:-ubuntu}"
PGUSER="${POSTGRES_USER:-studio}"
PGPASS="${POSTGRES_PASSWORD:?}"
if [ ! -f "$SSH_KEY" ]; then
echo "SSH key missing: $SSH_KEY" >&2
exit 2
fi
SOURCE_URL="${SOURCE_DATABASE_URL:-}"
if [ -z "$SOURCE_URL" ] && [ -f "$ROOT/.env.vercel.production" ]; then
set -a
# shellcheck source=/dev/null
source "$ROOT/.env.vercel.production"
set +a
SOURCE_URL="${DATABASE_URL:-}"
fi
if [ -z "$SOURCE_URL" ]; then
echo "SOURCE_DATABASE_URL or .env.vercel.production DATABASE_URL required." >&2
exit 2
fi
SSH=(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=15 -i "$SSH_KEY" "${SSH_USER}@${ORACLE_HOST}")
SCP=(scp -o StrictHostKeyChecking=accept-new -i "$SSH_KEY")
echo "=== 1/6 Waiting for SSH on ${ORACLE_HOST} ==="
for i in $(seq 1 30); do
if "${SSH[@]}" "echo ok" 2>/dev/null; then break; fi
if [ "$i" -eq 30 ]; then echo "SSH not ready. Is the VM running with cloud-init?" >&2; exit 1; fi
sleep 10
done
echo "=== 2/6 Dumping production database ==="
mkdir -p "${ROOT}/backups"
DATABASE_URL="$SOURCE_URL" bash "$ROOT/scripts/db/dump.sh" "$BACKUP"
echo "=== 3/6 Deploying Postgres stack on VM ==="
HOST_DIR="/home/${SSH_USER}/cockpit-postgres-host"
"${SSH[@]}" "mkdir -p ${HOST_DIR}/init"
"${SCP[@]}" -r "$ROOT/infra/postgres-host/docker-compose.yml" \
"$ROOT/infra/postgres-host/docker-compose.public.yml" \
"${SSH_USER}@${ORACLE_HOST}:${HOST_DIR}/"
"${SCP[@]}" "$ROOT/infra/postgres-host/init/"*.sh "${SSH_USER}@${ORACLE_HOST}:${HOST_DIR}/init/"
REMOTE_ENV="${HOST_DIR}/.env"
"${SSH[@]}" "cat > ${REMOTE_ENV}" <<EOF
POSTGRES_USER=${PGUSER}
POSTGRES_PASSWORD=${PGPASS}
EOF
"${SSH[@]}" bash <<REMOTE
set -euo pipefail
cd ${HOST_DIR}
chmod +x init/*.sh
sudo docker compose --env-file .env \
-f docker-compose.yml \
-f docker-compose.public.yml \
up -d
for i in \$(seq 1 30); do
if sudo docker compose exec -T postgres pg_isready -U ${PGUSER} >/dev/null 2>&1; then break; fi
sleep 2
done
sudo docker compose exec -T postgres psql -U ${PGUSER} -d postgres -c "SELECT 1 FROM pg_database WHERE datname='cockpit'" | grep -q 1 || \
sudo docker compose exec -T postgres psql -U ${PGUSER} -d postgres -c "CREATE DATABASE cockpit;"
REMOTE
echo "=== 4/6 Restoring dump into cockpit database ==="
DIRECT="postgresql://${PGUSER}:${PGPASS}@${ORACLE_HOST}:5432/cockpit"
gunzip -c "$BACKUP" | psql "$DIRECT" -v ON_ERROR_STOP=1 -q
POOL="postgresql://${PGUSER}:${PGPASS}@${ORACLE_HOST}:6432/cockpit?sslmode=disable"
echo "=== 5/6 Updating Vercel production env ==="
cd "$ROOT"
vercel env rm DATABASE_URL production -y 2>/dev/null || true
printf '%s' "$DIRECT" | vercel env add DATABASE_URL production
vercel env rm DATABASE_POOL_URL production -y 2>/dev/null || true
printf '%s' "$POOL" | vercel env add DATABASE_POOL_URL production
echo "=== 6/6 Redeploying production ==="
if npm run build >/tmp/cockpit-build.log 2>&1; then
vercel deploy --prod --yes 2>&1 | tail -5
else
echo "Build failed — redeploying last known good deployment with new DB env..."
LAST=$(vercel ls --prod 2>/dev/null | awk '/Ready/ {print $2; exit}')
if [ -n "$LAST" ]; then
vercel redeploy "$LAST" --target production 2>&1 | tail -5
else
echo "Could not redeploy. Update env manually and redeploy from Vercel dashboard." >&2
exit 1
fi
fi
echo ""
echo "=== Cutover complete ==="
echo " Direct : ${DIRECT}"
echo " Pool : ${POOL}"
echo " Backup : ${BACKUP}"
echo ""
curl -sS "https://cockpitapp.vercel.app/api/setup" || true
echo ""
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env bash
# Restore a pg_dump plain SQL backup produced by scripts/db/dump.sh
#
# Usage:
# DATABASE_URL=postgresql://... ./scripts/db/restore.sh backup.sql.gz
#
# WARNING: restores into the target database as-is. Prefer an empty DB or
# use --clean manually on a custom dump if you need replace semantics.
set -euo pipefail
if [ $# -lt 1 ]; then
echo "Usage: DATABASE_URL=... $0 <backup.sql.gz>" >&2
exit 2
fi
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
if [ -z "${DATABASE_URL:-}" ] && [ -f "$ROOT/.env.local" ]; then
set -a
# shellcheck source=/dev/null
source "$ROOT/.env.local"
set +a
fi
URL="${DATABASE_URL:-${NEON_DATABASE_URL_DIRECT:-}}"
if [ -z "$URL" ]; then
echo "ERROR: set DATABASE_URL (direct connection) before running." >&2
exit 2
fi
BACKUP="$1"
if [ ! -f "$BACKUP" ]; then
echo "ERROR: file not found: $BACKUP" >&2
exit 2
fi
echo "Restoring $BACKUP into target database ..."
gunzip -c "$BACKUP" | psql "$URL" -v ON_ERROR_STOP=1
echo "Done."
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env bash
# Copy user-owned rows from one Postgres database to another, rewriting user_id.
# Vendor-neutral — works for local→Neon, Neon→Hetzner, Neon→Oracle, etc.
#
# Usage:
# SOURCE_DATABASE_URL=... TARGET_DATABASE_URL=... TARGET_USER_ID=<uuid> \
# ./scripts/db/sync-user-data.sh [--dry-run] [--force]
#
# Env vars:
# SOURCE_DATABASE_URL Source (defaults to local cockpit Postgres)
# TARGET_DATABASE_URL Target direct URL. REQUIRED.
# SOURCE_USER_ID Source user_id to rewrite (default: dev seed UUID)
# TARGET_USER_ID Target user_id in destination. REQUIRED.
#
# Legacy aliases (still accepted):
# LOCAL_DATABASE_URL, NEON_DATABASE_URL / NEON_DATABASE_URL_DIRECT, NEON_USER_ID
#
# Prerequisites: psql + pg_dump in PATH.
set -euo pipefail
SOURCE_URL="${SOURCE_DATABASE_URL:-${LOCAL_DATABASE_URL:-postgresql://cockpit:cockpit_local@127.0.0.1:5432/cockpit}}"
TARGET_URL="${TARGET_DATABASE_URL:-${NEON_DATABASE_URL:-${NEON_DATABASE_URL_DIRECT:-}}}"
SOURCE_USER_ID="${SOURCE_USER_ID:-${LOCAL_USER_ID:-00000000-0000-0000-0000-000000000001}}"
TARGET_USER_ID="${TARGET_USER_ID:-${NEON_USER_ID:-}}"
if [ -z "$TARGET_URL" ]; then
echo "ERROR: set TARGET_DATABASE_URL before running." >&2
exit 2
fi
if [ -z "$TARGET_USER_ID" ]; then
echo "ERROR: set TARGET_USER_ID to the destination user's UUID." >&2
echo "Find it via: psql \"\$TARGET_DATABASE_URL\" -c \"SELECT id, email FROM users\"" >&2
exit 2
fi
DRY_RUN=false
FORCE=false
for arg in "$@"; do
[[ "$arg" == "--dry-run" ]] && DRY_RUN=true
[[ "$arg" == "--force" ]] && FORCE=true
done
echo "=== Postgres user-data sync ==="
echo " Source user_id : $SOURCE_USER_ID"
echo " Target user_id : $TARGET_USER_ID"
$DRY_RUN && echo " MODE: DRY RUN (no writes to target)"
echo ""
TABLES=(
orgs
org_memberships
entities
attributes
entity_relations
interactions
alerts
user_projects
goals
subscriptions
commitments
events
actions
habits
habit_completions
orchestration_runs
orchestration_events
project_states
prompt_history
pending_commands
)
echo "Verifying target connection..."
TARGET_USER_COUNT=$(psql "$TARGET_URL" -t -c "SELECT count(*) FROM users;" 2>/dev/null | tr -d ' \n')
[[ -z "$TARGET_USER_COUNT" || "$TARGET_USER_COUNT" == "0" ]] && { echo "ERROR: target users table empty or unreachable."; exit 1; }
echo " Target users: $TARGET_USER_COUNT ✓"
TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT
IMPORTED=0
SKIPPED=0
for t in "${TABLES[@]}"; do
SOURCE_COUNT=$(psql "$SOURCE_URL" -t -c "SELECT count(*) FROM $t;" 2>/dev/null | tr -d ' \n')
TARGET_COUNT=$(psql "$TARGET_URL" -t -c "SELECT count(*) FROM $t;" 2>/dev/null | tr -d ' \n')
if [[ "$SOURCE_COUNT" == "0" ]]; then
echo " $t: 0 rows — skip"
SKIPPED=$((SKIPPED + 1))
continue
fi
if [[ "$TARGET_COUNT" != "0" && "$FORCE" == "false" ]]; then
echo " $t: already has $TARGET_COUNT rows — skip (--force to overwrite)"
SKIPPED=$((SKIPPED + 1))
continue
fi
echo -n " $t: $SOURCE_COUNT rows — "
COPY_FILE="$TMPDIR/${t}.copy"
pg_dump "$SOURCE_URL" \
--table="$t" \
--data-only \
--no-comments \
--no-owner \
--no-privileges \
2>/dev/null \
| awk '/^COPY /,/^\\./' \
| sed "s/$SOURCE_USER_ID/$TARGET_USER_ID/g" \
> "$COPY_FILE"
if $DRY_RUN; then
echo "would import (dry run)"
head -3 "$COPY_FILE"
continue
fi
if [[ "$TARGET_COUNT" != "0" && "$FORCE" == "true" ]]; then
psql "$TARGET_URL" -c "TRUNCATE TABLE $t CASCADE;" 2>/dev/null
fi
RESULT=$(psql "$TARGET_URL" -f "$COPY_FILE" 2>&1)
if echo "$RESULT" | grep -q "^COPY"; then
ROWS=$(echo "$RESULT" | grep "^COPY" | awk '{print $2}')
echo "imported $ROWS rows ✓"
IMPORTED=$((IMPORTED + 1))
else
echo "ERROR"
echo "$RESULT" | head -5
fi
done
echo ""
echo "=== Verification ==="
psql "$TARGET_URL" -c "
SELECT 'entities' as t, count(*) FROM entities
UNION ALL SELECT 'user_projects', count(*) FROM user_projects
UNION ALL SELECT 'goals', count(*) FROM goals
UNION ALL SELECT 'subscriptions', count(*) FROM subscriptions
UNION ALL SELECT 'commitments', count(*) FROM commitments
UNION ALL SELECT 'events', count(*) FROM events
UNION ALL SELECT 'interactions', count(*) FROM interactions
UNION ALL SELECT 'prompt_history', count(*) FROM prompt_history
UNION ALL SELECT 'orchestration_events', count(*) FROM orchestration_events
ORDER BY t;" 2>/dev/null
echo ""
echo "Done: $IMPORTED tables imported, $SKIPPED skipped."
+2 -159
View File
@@ -1,160 +1,3 @@
#!/usr/bin/env bash
# Migrate all user data from local Postgres to Neon, rewriting the default
# user_id to the GitHub OAuth user_id found in Neon.
#
# Uses COPY format (binary-safe, fast) and imports in FK dependency order.
# Tables with no rows are skipped. Re-runnable: skips tables already populated.
#
# Usage:
# LOCAL_DATABASE_URL=... NEON_DATABASE_URL=... NEON_USER_ID=<uuid> \
# ./scripts/migrate-local-to-neon.sh [--dry-run] [--force]
#
# Env vars:
# LOCAL_DATABASE_URL Source (defaults to local cockpit Postgres on 5432)
# NEON_DATABASE_URL Target (also accepts NEON_DATABASE_URL_DIRECT — same
# resolution as drizzle.config.ts). REQUIRED.
# LOCAL_USER_ID Source user_id to rewrite (defaults to the dev seed
# UUID 00000000-0000-0000-0000-000000000001).
# NEON_USER_ID Target user_id (the GitHub OAuth row in Neon). REQUIRED.
#
# Prerequisites: psql + pg_dump in PATH, local Postgres running.
#
# Security note: NEVER hardcode connection strings here. Prior versions of
# this file leaked the Neon password into git history; rotate the password
# on Neon if you pulled this repo before the refactor that removed it.
set -euo pipefail
LOCAL_URL="${LOCAL_DATABASE_URL:-postgresql://cockpit:cockpit_local@127.0.0.1:5432/cockpit}"
NEON_URL="${NEON_DATABASE_URL:-${NEON_DATABASE_URL_DIRECT:-}}"
LOCAL_USER_ID="${LOCAL_USER_ID:-00000000-0000-0000-0000-000000000001}"
if [ -z "$NEON_URL" ]; then
echo "ERROR: set NEON_DATABASE_URL (or NEON_DATABASE_URL_DIRECT) before running." >&2
echo "Get one via: neonctl connection-string --project-id <id> --pooled false" >&2
exit 2
fi
if [ -z "${NEON_USER_ID:-}" ]; then
echo "ERROR: set NEON_USER_ID to the target user's UUID in Neon." >&2
echo "Find it via: psql \"\$NEON_DATABASE_URL\" -c \"SELECT id, email FROM users\"" >&2
exit 2
fi
DRY_RUN=false
FORCE=false
for arg in "$@"; do
[[ "$arg" == "--dry-run" ]] && DRY_RUN=true
[[ "$arg" == "--force" ]] && FORCE=true
done
echo "=== Local → Neon data migration ==="
echo " Local user_id : $LOCAL_USER_ID"
echo " Neon user_id : $NEON_USER_ID"
$DRY_RUN && echo " MODE: DRY RUN (no writes to Neon)"
echo ""
# Tables in FK-safe import order (parents before children)
TABLES=(
entities
attributes
entity_relations
interactions
alerts
user_projects
goals
subscriptions
commitments
events
actions
habits
habit_completions
orchestration_runs
orchestration_events
project_states
prompt_history
pending_commands
)
# Verify Neon reachable and user exists
echo "Verifying Neon connection..."
NEON_USER_COUNT=$(psql "$NEON_URL" -t -c "SELECT count(*) FROM users;" 2>/dev/null | tr -d ' \n')
[[ -z "$NEON_USER_COUNT" || "$NEON_USER_COUNT" == "0" ]] && { echo "ERROR: Neon users table empty or unreachable."; exit 1; }
echo " Neon users: $NEON_USER_COUNT ✓"
TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT
IMPORTED=0
SKIPPED=0
for t in "${TABLES[@]}"; do
LOCAL_COUNT=$(psql "$LOCAL_URL" -t -c "SELECT count(*) FROM $t;" 2>/dev/null | tr -d ' \n')
NEON_COUNT=$(psql "$NEON_URL" -t -c "SELECT count(*) FROM $t;" 2>/dev/null | tr -d ' \n')
if [[ "$LOCAL_COUNT" == "0" ]]; then
echo " $t: 0 rows — skip"
SKIPPED=$((SKIPPED + 1))
continue
fi
if [[ "$NEON_COUNT" != "0" && "$FORCE" == "false" ]]; then
echo " $t: already has $NEON_COUNT rows — skip (--force to overwrite)"
SKIPPED=$((SKIPPED + 1))
continue
fi
echo -n " $t: $LOCAL_COUNT rows — "
COPY_FILE="$TMPDIR/${t}.copy"
# Extract COPY data from pg_dump (between COPY header and \. terminator)
pg_dump "$LOCAL_URL" \
--table="$t" \
--data-only \
--no-comments \
--no-owner \
--no-privileges \
2>/dev/null \
| awk '/^COPY /,/^\\./' \
| sed "s/$LOCAL_USER_ID/$NEON_USER_ID/g" \
> "$COPY_FILE"
if $DRY_RUN; then
echo "would import (dry run)"
head -3 "$COPY_FILE"
continue
fi
if [[ "$NEON_COUNT" != "0" && "$FORCE" == "true" ]]; then
psql "$NEON_URL" -c "TRUNCATE TABLE $t CASCADE;" 2>/dev/null
fi
# Feed COPY data into Neon
RESULT=$(psql "$NEON_URL" -f "$COPY_FILE" 2>&1)
if echo "$RESULT" | grep -q "^COPY"; then
ROWS=$(echo "$RESULT" | grep "^COPY" | awk '{print $2}')
echo "imported $ROWS rows ✓"
IMPORTED=$((IMPORTED + 1))
else
echo "ERROR"
echo "$RESULT" | head -5
fi
done
echo ""
echo "=== Verification ==="
psql "$NEON_URL" -c "
SELECT 'entities' as t, count(*) FROM entities
UNION ALL SELECT 'user_projects', count(*) FROM user_projects
UNION ALL SELECT 'goals', count(*) FROM goals
UNION ALL SELECT 'subscriptions', count(*) FROM subscriptions
UNION ALL SELECT 'commitments', count(*) FROM commitments
UNION ALL SELECT 'events', count(*) FROM events
UNION ALL SELECT 'interactions', count(*) FROM interactions
UNION ALL SELECT 'prompt_history', count(*) FROM prompt_history
UNION ALL SELECT 'orchestration_events', count(*) FROM orchestration_events
ORDER BY t;" 2>/dev/null
echo ""
echo "Done: $IMPORTED tables imported, $SKIPPED skipped."
# Backward-compatible wrapper — prefer scripts/db/sync-user-data.sh
exec "$(dirname "$0")/db/sync-user-data.sh" "$@"
+1
View File
@@ -54,6 +54,7 @@ PUBLIC_API_ROUTES=(
)
AUTH_API_ROUTES=(
"/api/me"
"/api/onboarding"
"/api/crons"
"/api/goals"
"/api/habits"
+103
View File
@@ -0,0 +1,103 @@
/**
* Inline self-tests for control-presenter live tab mapping.
* Run: npm run test:control-presenter
*/
import {
buildLiveTabRows,
findProjectForOpenTab,
formatAgentRuntimeLabel,
} from "@/components/control/control-presenter";
import type { ProjectState } from "@/lib/control-types";
function stubProject(overrides: Partial<ProjectState> & Pick<ProjectState, "tab">): ProjectState {
return {
id: "1",
projectId: null,
liveTab: overrides.tab,
dir: "/tmp/proj",
agentPref: "claude",
modelPref: null,
session: null,
git: null,
sessionLifecycleSignals: true,
agentRunning: false,
activeAgents: [],
profile: null,
currentPrompt: null,
readyAt: null,
lockAt: null,
closingAt: null,
closedAt: null,
recentCustomPrompts: [],
recentInjections: [],
recentOutcomes: [],
latestOrchestrationRun: null,
...overrides,
};
}
function assert(condition: boolean, message: string): void {
if (!condition) throw new Error(message);
}
function runTests(): void {
let passed = 0;
const check = (label: string, fn: () => void) => {
fn();
passed += 1;
console.log(` ✓ ${label}`);
};
check("findProjectForOpenTab exact match", () => {
const projects = [stubProject({ tab: "Cockpit", liveTab: "Cockpit" })];
assert(findProjectForOpenTab("cockpit", projects)?.tab === "Cockpit", "expected Cockpit");
});
check("findProjectForOpenTab prefix match (agent suffix tab)", () => {
const projects = [stubProject({ tab: "Cockpit", liveTab: "Cockpit Claude" })];
assert(findProjectForOpenTab("Cockpit Claude", projects)?.tab === "Cockpit", "expected prefix match");
});
check("buildLiveTabRows sorts Working before Open", () => {
const nowS = 1_700_000_000;
const projects = [
stubProject({
tab: "IdleProj",
liveTab: "IdleProj",
agentRunning: false,
}),
stubProject({
tab: "Active",
liveTab: "Active",
agentRunning: true,
currentPrompt: { key: "k", label: "Fix tests", startedAt: nowS - 10 },
activeAgents: ["claude"],
}),
];
const rows = buildLiveTabRows(["Active", "Mystery"], projects, nowS);
assert(rows[0]?.tabName === "Active", "working tab first");
assert(rows[0]?.stateLabel === "Working", "working state");
assert(rows[1]?.tabName === "Mystery", "unregistered second");
assert(rows[1]?.registered === false, "unregistered flag");
});
check("formatAgentRuntimeLabel maps cursor agent id", () => {
const label = formatAgentRuntimeLabel(stubProject({
tab: "X",
activeAgents: ["cursor"],
}));
assert(label === "Cursor", `expected Cursor, got ${label}`);
});
check("formatAgentRuntimeLabel maps legacy agent basename", () => {
const label = formatAgentRuntimeLabel(stubProject({
tab: "X",
activeAgents: ["agent"],
}));
assert(label === "Cursor", `expected Cursor, got ${label}`);
});
console.log(`\n${passed}/${passed} passed`);
}
runTests();
+98
View File
@@ -0,0 +1,98 @@
/**
* Inline self-tests for db-url resolution.
* Run: npm run test:db-url
*/
import { getDatabaseDirectUrl, getDatabasePoolUrl } from "@/lib/db-url";
function assert(condition: boolean, message: string): void {
if (!condition) throw new Error(message);
}
function withEnv(
vars: Record<string, string | undefined>,
fn: () => void,
): void {
const prior = new Map<string, string | undefined>();
for (const key of Object.keys(vars)) {
prior.set(key, process.env[key]);
const value = vars[key];
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
try {
fn();
} finally {
for (const [key, value] of prior) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
}
}
function runTests(): void {
let passed = 0;
const check = (label: string, fn: () => void) => {
fn();
passed += 1;
console.log(` ✓ ${label}`);
};
check("pool prefers DATABASE_POOL_URL", () => {
withEnv(
{
DATABASE_POOL_URL: "postgres://pool",
DATABASE_URL: "postgres://direct",
NEON_DATABASE_URL: "postgres://legacy-pool",
},
() => assert(getDatabasePoolUrl() === "postgres://pool", "expected pool"),
);
});
check("pool falls back to legacy NEON_DATABASE_URL", () => {
withEnv(
{
DATABASE_POOL_URL: undefined,
DATABASE_URL: "postgres://direct",
NEON_DATABASE_URL: "postgres://legacy-pool",
},
() => assert(getDatabasePoolUrl() === "postgres://legacy-pool", "expected legacy pool"),
);
});
check("pool falls back to DATABASE_URL for local dev", () => {
withEnv(
{
DATABASE_POOL_URL: undefined,
DATABASE_URL: "postgres://local",
NEON_DATABASE_URL: undefined,
},
() => assert(getDatabasePoolUrl() === "postgres://local", "expected local"),
);
});
check("direct prefers DATABASE_URL", () => {
withEnv(
{
DATABASE_URL: "postgres://direct",
NEON_DATABASE_URL_DIRECT: "postgres://legacy-direct",
},
() => assert(getDatabaseDirectUrl() === "postgres://direct", "expected direct"),
);
});
check("direct does not fall back to pool URL", () => {
withEnv(
{
DATABASE_URL: undefined,
NEON_DATABASE_URL_DIRECT: undefined,
DATABASE_POOL_URL: "postgres://pool-only",
NEON_DATABASE_URL: "postgres://pool-only",
},
() => assert(getDatabaseDirectUrl() === undefined, "direct must stay undefined"),
);
});
console.log(`\n${passed} passed`);
}
runTests();
+45
View File
@@ -0,0 +1,45 @@
/**
* Inline self-tests for onboarding helpers.
* Run: npm run test:onboarding
*/
import {
suggestUsername,
hasValidUsername,
isOnboardingComplete,
} from "@/lib/onboarding";
function assert(condition: boolean, message: string): void {
if (!condition) throw new Error(message);
}
function runTests(): void {
let passed = 0;
const check = (label: string, fn: () => void) => {
fn();
passed += 1;
console.log(` ✓ ${label}`);
};
check("suggestUsername from display name", () => {
assert(suggestUsername("Jane Doe", null) === "jane-doe", "expected jane-doe");
});
check("suggestUsername from email", () => {
assert(suggestUsername(null, "builder@example.com") === "builder", "expected builder");
});
check("hasValidUsername rejects short handles", () => {
assert(!hasValidUsername("a"), "single char invalid");
assert(hasValidUsername("ab"), "two chars valid");
});
check("isOnboardingComplete requires username and timestamp", () => {
assert(!isOnboardingComplete({ username: "you", onboardedAt: null }), "needs onboardedAt");
assert(!isOnboardingComplete({ username: null, onboardedAt: new Date() }), "needs username");
assert(isOnboardingComplete({ username: "you", onboardedAt: new Date() }), "complete");
});
console.log(`\n${passed}/${passed} passed`);
}
runTests();
+8 -1
View File
@@ -17,13 +17,20 @@ const LaunchAgentBody = z.object({
const AGENT_BASENAMES = new Set(["claude", "codex", "gemini", "openclaw"]);
function isCursorAgentArgv0(argv0: string): boolean {
return argv0.includes(".local/bin/agent") || argv0.includes("/.cursor/");
}
function isAgentRunningIn(dir: string): boolean {
try {
for (const entry of fs.readdirSync("/proc")) {
if (!/^\d+$/.test(entry)) continue;
try {
const argv0 = fs.readFileSync(`/proc/${entry}/cmdline`, "utf8").split("\0")[0] ?? "";
if (!AGENT_BASENAMES.has(argv0.split("/").pop() ?? "")) continue;
const basename = argv0.split("/").pop() ?? "";
const isKnownAgent = AGENT_BASENAMES.has(basename)
|| (basename === "agent" && isCursorAgentArgv0(argv0));
if (!isKnownAgent) continue;
if (fs.readlinkSync(`/proc/${entry}/cwd`) === dir) return true;
} catch { /* skip */ }
}
+17 -4
View File
@@ -46,6 +46,7 @@ type SlowCache = {
zellijTabs: string[];
dirs: string[]; // dirs list used to build this cache
builtAt: number;
runtimeSnapshotUpdatedAt: Date | null;
};
let slowCache: SlowCache | null = null;
@@ -66,7 +67,13 @@ async function buildSlowData(userId: string, dirs: string[]): Promise<SlowCache>
: (runtimeSnapshot?.openTabs?.length
? runtimeSnapshot.openTabs
: dbStates.filter((s) => s.tabOpen).map((s) => s.tabName));
return { gitMap, zellijTabs, dirs, builtAt: Date.now() };
return {
gitMap,
zellijTabs,
dirs,
builtAt: Date.now(),
runtimeSnapshotUpdatedAt: runtimeSnapshot?.updatedAt ?? null,
};
}
async function getSlowData(userId: string, dirs: string[]): Promise<SlowCache> {
@@ -224,7 +231,7 @@ export async function GET() {
const dirs = projects.map((p) => p.dir);
// Slow data (git + DB) served from cache — no fork needed for CWD check
const { gitMap, zellijTabs } = await getSlowData(userId, dirs);
const { gitMap, zellijTabs, runtimeSnapshotUpdatedAt } = await getSlowData(userId, dirs);
// Detect any known agent running in a project dir — not just the configured default
const agentProcesses = getAgentProcesses(agentRegistry.agents);
const projectKeys = projects.map((p) => p.tab);
@@ -473,8 +480,14 @@ export async function GET() {
zellijTabs,
recentActivity: recentActivity ?? [],
runtimeAvailable: isRuntimeAvailable(),
daemonLastPushedAt: !isRuntimeAvailable() && dbStatesArr.length > 0
? dbStatesArr.reduce((max, s) => s.updatedAt > max ? s.updatedAt : max, dbStatesArr[0].updatedAt).toISOString()
daemonLastPushedAt: !isRuntimeAvailable()
? (() => {
let maxAt: Date | null = runtimeSnapshotUpdatedAt;
for (const s of dbStatesArr) {
if (!maxAt || s.updatedAt > maxAt) maxAt = s.updatedAt;
}
return maxAt?.toISOString() ?? null;
})()
: null,
failedCommands: failedCommands ?? [],
} satisfies ControlData);
+5 -3
View File
@@ -11,6 +11,7 @@ import { isRuntimeAvailable } from "@/lib/runtime";
import { NOTIFY_CHANNEL } from "@/db/setup-notify-trigger";
import type { FastProjectState } from "@/lib/control-fast-state";
import { sseBus } from "@/lib/sse-bus";
import { getDatabaseDirectUrl } from "@/lib/db-url";
import postgres from "postgres";
export const dynamic = "force-dynamic";
@@ -190,10 +191,11 @@ export async function GET() {
sseBus.on("sentinel-changed", onSentinelChanged);
// Vercel-only: Postgres LISTEN/NOTIFY for sub-second state propagation.
// Must use DATABASE_URL (direct), not NEON_DATABASE_URL (pooler — no persistent LISTEN).
// Must use a direct URL — poolers do not support persistent LISTEN.
let pgListener: ReturnType<typeof postgres> | null = null;
if (!isRuntimeAvailable() && process.env.DATABASE_URL) {
pgListener = postgres(process.env.DATABASE_URL, { max: 1 });
const directDatabaseUrl = getDatabaseDirectUrl();
if (!isRuntimeAvailable() && directDatabaseUrl) {
pgListener = postgres(directDatabaseUrl, { max: 1 });
pgListener.listen(NOTIFY_CHANNEL, (notifyUserId) => {
if (notifyUserId === userId) scheduledTick();
}).catch((err) => console.warn("[control/stream] LISTEN setup failed:", err));
+1 -3
View File
@@ -10,7 +10,6 @@ const PatchBody = z.object({
z.string().min(2).max(40).regex(/^[a-z0-9-]+$/, "Lowercase letters, numbers and hyphens only"),
).optional(),
name: z.string().trim().min(1).max(120).optional(),
onboardedAt: z.string().datetime().optional(),
});
export async function GET() {
@@ -26,7 +25,7 @@ export async function PATCH(req: NextRequest) {
if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const dataOrResp = await readJsonBody(req, PatchBody);
if (dataOrResp instanceof NextResponse) return dataOrResp;
const { username, name, onboardedAt } = dataOrResp;
const { username, name } = dataOrResp;
if (username) {
const existing = await getUserByUsername(username);
@@ -38,7 +37,6 @@ export async function PATCH(req: NextRequest) {
const updated = await updateUser(userId, {
username,
name,
onboardedAt: onboardedAt ? new Date(onboardedAt) : undefined,
});
return NextResponse.json(updated);
+74
View File
@@ -0,0 +1,74 @@
import { NextResponse } from "next/server";
import { getSessionUserId } from "@/lib/session";
import { getUserById, updateUser } from "@/db/queries/users";
import { isTeamInvitee } from "@/db/queries/orgs";
import { getRuntimeSnapshot } from "@/db/queries/runtime-snapshots";
import { getProjectStatesByUserId } from "@/db/queries/project-states";
import { isRuntimeAvailable } from "@/lib/runtime";
import { hasValidUsername, isOnboardingComplete, suggestUsername } from "@/lib/onboarding";
async function getDaemonConnectionStatus(userId: string) {
const [snapshot, states] = await Promise.all([
getRuntimeSnapshot(userId).catch(() => null),
getProjectStatesByUserId(userId).catch(() => []),
]);
let lastAt: Date | null = snapshot?.updatedAt ?? null;
for (const row of states) {
if (!lastAt || row.updatedAt > lastAt) lastAt = row.updatedAt;
}
const lastPushedAt = lastAt?.toISOString() ?? null;
const connected = lastAt != null;
const live = lastAt != null && Date.now() - lastAt.getTime() < 90_000;
return { connected, live, lastPushedAt };
}
export async function GET() {
const userId = await getSessionUserId();
if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const user = await getUserById(userId);
if (!user) return NextResponse.json({ error: "Not found" }, { status: 404 });
const [teamInvitee, daemon] = await Promise.all([
isTeamInvitee(userId),
isRuntimeAvailable()
? Promise.resolve({ connected: true, live: true, lastPushedAt: new Date().toISOString() })
: getDaemonConnectionStatus(userId),
]);
return NextResponse.json({
complete: isOnboardingComplete(user),
username: user.username,
suggestedUsername: suggestUsername(user.name, user.email),
isTeamInvitee: teamInvitee,
runtimeAvailable: isRuntimeAvailable(),
daemonConnected: daemon.connected,
daemonLive: daemon.live,
daemonLastPushedAt: daemon.lastPushedAt,
});
}
export async function POST() {
const userId = await getSessionUserId();
if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const user = await getUserById(userId);
if (!user) return NextResponse.json({ error: "Not found" }, { status: 404 });
if (!hasValidUsername(user.username)) {
return NextResponse.json(
{ error: "Choose a username before finishing onboarding." },
{ status: 400 },
);
}
if (isOnboardingComplete(user)) {
return NextResponse.json({ ok: true, user });
}
const updated = await updateUser(userId, { onboardedAt: new Date() });
return NextResponse.json({ ok: true, user: updated });
}
+1 -1
View File
@@ -294,7 +294,7 @@ function BeaconBody({
key={r.customPrompt}
onClick={() => setCustom(r.customPrompt)}
title={r.customPrompt}
className="ui-chip-action-compact max-w-[18rem] truncate text-left text-text-tertiary hover:text-text-secondary"
className="ui-chip-truncate-label"
>
{r.count > 1 && <span className="mr-1.5">used {r.count}×</span>}
{r.customPrompt.length > 60 ? r.customPrompt.slice(0, 60) + "…" : r.customPrompt}
+9
View File
@@ -0,0 +1,9 @@
export const dynamic = "force-dynamic";
export default function ForgotPasswordLayout({
children,
}: {
children: React.ReactNode;
}) {
return children;
}
+254
View File
@@ -439,6 +439,139 @@
.ui-public-pricing-card-highlighted {
@apply border-white/[0.18] bg-white/[0.06];
}
.ui-public-primary-action-compact {
@apply rounded-full bg-white !py-2 !px-5 text-sm font-semibold text-black transition-opacity hover:opacity-85;
}
.ui-public-section-kicker {
@apply mb-3 text-xs font-semibold uppercase tracking-[0.12em] text-white/25;
}
.ui-public-section-title {
@apply text-2xl font-bold tracking-tight text-white/80;
}
.ui-public-section-title-spaced {
@apply mb-8 text-2xl font-bold tracking-tight text-white/80 sm:mb-12;
}
.ui-public-section-note {
@apply mb-8 sm:mb-12 text-sm text-white/30;
}
.ui-public-pricing-popular {
@apply mb-4 inline-flex items-center rounded-full bg-white/[0.08] px-2.5 py-1 text-micro font-semibold uppercase tracking-widest text-white/50;
}
.ui-public-pricing-plan {
@apply mb-1 text-xs font-semibold uppercase tracking-widest text-white/30;
}
.ui-public-pricing-price-row {
@apply flex items-baseline gap-1;
}
.ui-public-pricing-price {
@apply text-4xl font-bold tracking-tight text-white/90;
}
.ui-public-pricing-period {
@apply text-sm text-white/30;
}
.ui-public-pricing-annual {
@apply mb-1 text-xs text-white/40;
}
.ui-public-pricing-tagline {
@apply mb-6 mt-3 text-sm leading-relaxed text-white/40;
}
.ui-public-pricing-divider {
@apply border-t border-white/[0.06] pt-5;
}
.ui-public-pricing-features {
@apply space-y-2.5 text-left;
}
.ui-public-pricing-feature {
@apply flex items-start gap-2.5 text-sm text-white/40;
}
.ui-public-pricing-check {
@apply mt-0.5 shrink-0 text-white/20;
}
.ui-public-doc-header {
@apply mb-16 border-b border-white/[0.08] pb-12;
}
.ui-public-doc-meta-row {
@apply mb-6 flex flex-wrap items-center gap-3;
}
.ui-public-doc-badge {
@apply rounded-full border border-white/[0.12] bg-white/[0.06] px-3 py-1 font-mono text-xs text-white/40;
}
.ui-public-doc-meta {
@apply font-mono text-xs text-white/25;
}
.ui-public-doc-title {
@apply mb-5 font-bold tracking-tight text-white;
font-size: clamp(2rem, 5vw, 3.25rem);
line-height: 1.05;
letter-spacing: -0.03em;
}
.ui-public-doc-subtitle {
@apply text-lg leading-relaxed text-white/40 sm:text-xl;
}
.ui-public-prose {
@apply space-y-8;
}
.ui-public-prose-h2 {
@apply pt-6 text-2xl font-semibold tracking-tight text-white/90;
letter-spacing: -0.02em;
}
.ui-public-prose-h3 {
@apply pt-2 text-lg font-semibold text-white/80;
}
.ui-public-prose-p {
@apply text-base leading-[1.8] text-white/50;
}
.ui-public-prose-blockquote {
@apply border-l-2 border-white/20 pl-6;
}
.ui-public-prose-blockquote-p {
@apply text-base italic leading-relaxed text-white/35;
}
.ui-public-prose-li {
@apply flex items-start gap-3 text-base leading-relaxed text-white/45;
}
.ui-public-prose-bullet {
@apply mt-2.5 h-1 w-1 shrink-0 rounded-full bg-white/25;
}
.ui-public-prose-ol-index {
@apply mt-1 shrink-0 font-mono text-xs text-white/25;
}
.ui-public-code-block {
@apply overflow-x-auto rounded-xl border border-white/[0.08] bg-white/[0.04] p-5;
}
.ui-public-code-lang {
@apply mb-3 font-mono text-micro uppercase tracking-widest text-white/20;
}
.ui-public-code-pre {
@apply font-mono text-sm leading-relaxed text-white/60;
}
.ui-public-doc-footer {
@apply mt-24 border-t border-white/[0.08] pt-16 text-center;
}
.ui-public-doc-footer-title {
@apply mb-2 text-sm font-medium text-white/60;
}
.ui-public-doc-footer-note {
@apply mb-8 text-sm text-white/30;
}
.ui-brand-mark {
@apply flex items-center justify-center rounded-2xl border border-border-default bg-surface-overlay;
}
.ui-brand-mark-inverted {
@apply flex items-center justify-center rounded-2xl border border-white/12 bg-white/[0.03];
}
.ui-brand-mark-compact {
@apply h-10 w-10;
}
.ui-brand-mark-default {
@apply h-11 w-11;
}
.ui-brand-kicker-inverted {
@apply text-xs font-semibold uppercase tracking-[0.12em] text-white/38;
}
.ui-brand-wordmark-inverted {
@apply mt-1 block text-2xl font-medium tracking-display text-white;
}
.ui-auth-label {
@apply block text-sm font-medium text-white/[0.55];
}
@@ -488,6 +621,123 @@
.ui-auth-input-disabled {
@apply cursor-not-allowed text-white/[0.60] opacity-50;
}
.ui-auth-container {
@apply w-full max-w-[400px];
}
.ui-auth-progress-row {
@apply mb-8 flex items-center gap-1.5;
}
.ui-auth-progress-segment {
@apply h-0.5 flex-1 rounded-full bg-white/[0.12] transition-all;
}
.ui-auth-progress-segment-active {
@apply bg-white/50;
}
.ui-auth-body {
@apply text-sm leading-relaxed text-white/40;
}
.ui-auth-list {
@apply ml-4 list-decimal space-y-2 text-sm text-white/50;
}
.ui-auth-link {
@apply text-white/70 underline-offset-2 hover:underline;
}
.ui-auth-inline-code {
@apply rounded bg-white/[0.06] px-1 py-0.5 text-xs text-white/60;
}
.ui-auth-inset-panel {
@apply rounded-xl border border-white/[0.12] bg-white/[0.04] p-3;
}
.ui-auth-inset-label {
@apply mb-1.5 text-xs font-medium text-white/40;
}
.ui-auth-mono {
@apply min-w-0 truncate font-mono text-xs text-white/70;
}
.ui-auth-mono-wrap {
@apply min-w-0 break-all font-mono text-xs leading-relaxed text-white/70;
}
.ui-auth-selectable-card {
@apply w-full rounded-xl border border-white/[0.07] bg-white/[0.03] px-3.5 py-3 text-left transition-all hover:border-white/[0.14] hover:bg-white/[0.06];
}
.ui-auth-selectable-card-selected {
@apply border-white/30 bg-white/10;
}
.ui-auth-confirmation-row {
@apply flex items-center gap-2.5 rounded-xl border border-white/[0.14] bg-white/[0.06] px-3.5 py-3;
}
.ui-auth-status-banner {
@apply flex items-center gap-2 rounded-xl border border-white/[0.14] bg-white/[0.06] px-3.5 py-3 text-sm text-white/70;
}
.ui-auth-muted-link {
@apply text-xs text-white/30 transition-colors hover:text-white/55;
}
.ui-auth-hint {
@apply text-center text-sm text-white/35;
}
.ui-auth-hint-emphasis {
@apply text-center text-sm text-white/50;
}
.ui-auth-hint-link {
@apply text-white/60 underline underline-offset-2 transition-colors hover:text-white/80;
}
.ui-auth-mode-tabs {
@apply mb-6 flex rounded-xl border border-white/[0.08] bg-white/[0.03] p-1;
}
.ui-auth-mode-tab {
@apply flex-1 rounded-lg py-2 text-sm font-medium text-white/30 transition-colors hover:text-white/55;
}
.ui-auth-mode-tab-active {
@apply bg-white/[0.09] text-white/80;
}
.ui-auth-prefix-field {
@apply flex w-full items-center gap-0 rounded-xl border border-white/[0.10] bg-white/[0.06] !py-0 px-4 text-sm text-white outline-none transition-colors focus:border-white/[0.30];
}
.ui-auth-prefix-label {
@apply shrink-0 select-none py-3 text-sm text-white/30;
}
.ui-auth-prefix-input {
@apply flex-1 bg-transparent py-3 text-sm text-white outline-none placeholder:text-white/[0.20];
}
.ui-auth-loading {
@apply flex items-center justify-center py-16;
}
.ui-auth-spinner {
@apply h-6 w-6 animate-spin text-white/30;
}
.ui-auth-spinner-sm {
@apply h-5 w-5 animate-spin text-white/30;
}
.ui-auth-repo-hint {
@apply text-xs text-white/40;
}
.ui-auth-repo-scroll {
@apply max-h-60 space-y-1.5 overflow-y-auto pr-1;
}
.ui-auth-repo-name {
@apply truncate text-sm font-medium text-white/80;
}
.ui-auth-repo-desc {
@apply mt-1 truncate text-xs text-white/35;
}
.ui-auth-icon-muted {
@apply shrink-0 text-white/40;
}
.ui-auth-icon-faint {
@apply h-3 w-3 shrink-0 text-white/30;
}
.ui-auth-status-meta {
@apply text-xs text-white/35;
}
.ui-auth-meta-inline {
@apply flex shrink-0 items-center gap-1 text-xs text-white/30;
}
.ui-auth-owner-note {
@apply text-sm text-white/35;
}
.ui-auth-row-actions {
@apply flex gap-2;
}
/* Loading spinners — applied to Loader2 icon className */
.ui-spinner { @apply h-4 w-4 animate-spin; }
@@ -551,6 +801,9 @@
.ui-chip-action-compact {
@apply inline-flex min-h-11 sm:min-h-0 items-center rounded-xl border border-border-subtle bg-surface-overlay px-3 py-1.5 text-xs text-text-secondary transition-colors hover:border-border-default hover:text-text-primary disabled:opacity-40;
}
.ui-chip-truncate-label {
@apply inline-flex min-h-11 max-w-[18rem] items-center truncate rounded-xl border border-border-subtle bg-surface-overlay px-3 py-1.5 text-left text-xs text-text-tertiary transition-colors hover:border-border-default hover:text-text-secondary sm:min-h-0 disabled:opacity-40;
}
/* Pill action button — Today page quick-action chips (Log, Capture, Plan day, etc.) */
.ui-btn-pill {
@apply flex items-center gap-1.5 rounded-full border border-border-subtle bg-surface-raised px-3 py-1.5 text-xs text-text-secondary transition-colors hover:bg-surface-overlay min-h-11 sm:min-h-0;
@@ -847,6 +1100,7 @@
.ui-lang-rb { @apply bg-red-500/20 text-red-300; }
.ui-lang-cs { @apply bg-purple-500/20 text-purple-300; }
.ui-lang-java { @apply bg-amber-500/20 text-amber-300; }
.ui-lang-default { @apply bg-white/10 text-white/50; }
/* ── End brand / category colors ─────────────────────────────────────────── */
+1 -1
View File
@@ -55,7 +55,7 @@ export default function InvitePage({ params }: { params: Promise<{ token: string
const result = await signIn("user-password", { userId: data.userId, password, redirect: false });
if (result?.ok) {
router.push(ROUTES.APP_HOME);
router.push(ROUTES.ONBOARDING);
} else {
router.push(ROUTES.SIGN_IN);
}
+3
View File
@@ -64,6 +64,9 @@ export const viewport: Viewport = {
],
};
// Client auth/onboarding pages use hooks; avoid static prerender failures (Next 16 + React 19).
export const dynamic = "force-dynamic";
export default function RootLayout({
children,
}: Readonly<{
+109 -137
View File
@@ -3,9 +3,9 @@
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { Loader2, GitBranch, Star, Lock } from "lucide-react";
import { GitBranch } from "lucide-react";
import { normalizeUsername } from "@/lib/username";
import { postJson, patchJson, throwApiError } from "@/lib/api/fetch";
import { postJson, patchJson, throwApiError, getJson } from "@/lib/api/fetch";
import { ROUTES } from "@/config/auth";
import { APP_DOMAIN } from "@/config/brand";
import {
@@ -15,113 +15,77 @@ import {
AuthInput,
AuthSubmitButton,
AuthHeading,
AuthProgressBar,
AuthPrefixField,
AuthLoadingCenter,
} from "@/components/auth/AuthShell";
import { ConnectMachineStep } from "@/components/onboarding/ConnectMachineStep";
import { RepoPicker } from "@/components/onboarding/RepoPicker";
import type { GitHubRepo } from "@/app/api/github/repos/route";
// ── Repo picker ───────────────────────────────────────────────────────────────
type OnboardingStep = "username" | "project" | "connect";
const LANG_COLORS: Record<string, string> = {
TypeScript: "ui-lang-ts",
JavaScript: "ui-lang-js",
Python: "ui-lang-py",
Go: "ui-lang-go",
Rust: "ui-lang-rs",
Ruby: "ui-lang-rb",
"C#": "ui-lang-cs",
Java: "ui-lang-java",
type OnboardingBootstrap = {
complete?: boolean;
suggestedUsername?: string;
isTeamInvitee?: boolean;
};
function RepoPicker({
onSelect,
}: {
onSelect: (repo: GitHubRepo) => void;
}) {
const [repos, setRepos] = useState<GitHubRepo[]>([]);
const [hasGithub, setHasGithub] = useState<boolean | null>(null);
const [loading, setLoading] = useState(true);
const [selected, setSelected] = useState<number | null>(null);
useEffect(() => {
fetch("/api/github/repos")
.then((r) => r.json())
.then((d: { repos?: GitHubRepo[]; hasGithub?: boolean }) => {
setRepos(d.repos ?? []);
setHasGithub(d.hasGithub ?? false);
})
.catch(() => setHasGithub(false))
.finally(() => setLoading(false));
}, []);
if (loading) {
return (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-5 w-5 animate-spin text-white/30" />
</div>
);
}
if (!hasGithub || repos.length === 0) return null;
return (
<div className="space-y-2">
<p className="text-xs text-white/40">Your GitHub repos — pick one to start</p>
<div className="max-h-60 space-y-1.5 overflow-y-auto pr-1">
{repos.map((repo) => {
const isSelected = selected === repo.id;
const langColor = repo.language ? (LANG_COLORS[repo.language] ?? "bg-white/10 text-white/50") : null;
return (
<button
key={repo.id}
type="button"
onClick={() => {
setSelected(repo.id);
onSelect(repo);
}}
className={`w-full rounded-xl border px-3.5 py-3 text-left transition-all ${
isSelected
? "border-white/30 bg-white/10"
: "border-white/[0.07] bg-white/[0.03] hover:border-white/[0.14] hover:bg-white/[0.06]"
}`}
>
<div className="flex items-center gap-2">
{repo.private && <Lock className="h-3 w-3 shrink-0 text-white/30" />}
<span className="truncate text-sm font-medium text-white/80">{repo.name}</span>
{langColor && (
<span className={`ml-auto shrink-0 rounded-md px-1.5 py-0.5 text-xs font-medium ${langColor}`}>
{repo.language}
</span>
)}
{repo.stargazers_count > 0 && (
<span className="flex shrink-0 items-center gap-1 text-xs text-white/30">
<Star className="h-3 w-3" />
{repo.stargazers_count}
</span>
)}
</div>
{repo.description && (
<p className="mt-1 truncate text-xs text-white/35">{repo.description}</p>
)}
</button>
);
})}
</div>
</div>
);
function stepIndex(step: OnboardingStep): number {
if (step === "username") return 0;
if (step === "project") return 1;
return 2;
}
// ── Page ──────────────────────────────────────────────────────────────────────
export default function OnboardingPage() {
const router = useRouter();
const { update } = useSession();
const [step, setStep] = useState<"username" | "project">("username");
const [username, setUsername] = useState("");
const [bootstrapping, setBootstrapping] = useState(true);
const [step, setStep] = useState<OnboardingStep>("username");
const [isTeamInvitee, setIsTeamInvitee] = useState(false);
const [username, setUsername] = useState("");
const [projectName, setProjectName] = useState("");
const [dirPath, setDirPath] = useState("");
const [gitUrl, setGitUrl] = useState("");
const [showManual, setShowManual] = useState(false);
const [saving, setSaving] = useState(false);
const [error, setError] = useState("");
const [dirPath, setDirPath] = useState("");
const [gitUrl, setGitUrl] = useState("");
const [showManual, setShowManual] = useState(false);
const [saving, setSaving] = useState(false);
const [error, setError] = useState("");
useEffect(() => {
getJson<OnboardingBootstrap>("/api/onboarding")
.then((data) => {
if (data.complete) {
router.replace(ROUTES.APP_HOME);
return;
}
if (data.suggestedUsername) {
setUsername((prev) => prev || data.suggestedUsername || "");
}
if (data.isTeamInvitee) {
setIsTeamInvitee(true);
}
})
.catch(() => { /* stay on page */ })
.finally(() => setBootstrapping(false));
}, [router]);
async function finishOnboarding() {
setSaving(true);
setError("");
try {
const res = await postJson("/api/onboarding", {});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error ?? "Failed to complete onboarding");
}
await update();
router.push(ROUTES.APP_HOME);
} catch (e) {
setError(e instanceof Error ? e.message : "Something went wrong");
} finally {
setSaving(false);
}
}
async function saveUsername() {
if (!username.trim()) return;
@@ -132,18 +96,10 @@ export default function OnboardingPage() {
if (!res.ok) await throwApiError(res, "Failed to save username");
await update();
// Team members already have org projects — skip the project step for them.
const orgsData: { orgs?: { id: string }[] } = await fetch("/api/orgs")
.then((r) => r.json())
.catch(() => ({ orgs: [] }));
if (orgsData.orgs && orgsData.orgs.length > 0) {
await patchJson("/api/me", { onboardedAt: new Date().toISOString() });
await update();
router.push(ROUTES.APP_HOME);
return;
}
setStep("project");
const status = await getJson<OnboardingBootstrap>("/api/onboarding");
const teamInvitee = status.isTeamInvitee ?? false;
setIsTeamInvitee(teamInvitee);
setStep(teamInvitee ? "connect" : "project");
} catch (e) {
setError(e instanceof Error ? e.message : "Something went wrong");
} finally {
@@ -168,9 +124,7 @@ export default function OnboardingPage() {
gitUrl: gitUrl.trim() || undefined,
});
}
await patchJson("/api/me", { onboardedAt: new Date().toISOString() });
await update();
router.push(ROUTES.APP_HOME);
setStep("connect");
} catch (e) {
setError(e instanceof Error ? e.message : "Something went wrong");
} finally {
@@ -178,13 +132,17 @@ export default function OnboardingPage() {
}
}
if (bootstrapping) {
return (
<AuthShell>
<AuthLoadingCenter />
</AuthShell>
);
}
return (
<AuthShell>
{/* Step progress */}
<div className="mb-8 flex items-center gap-1.5">
<div className="h-0.5 flex-1 rounded-full bg-white/50" />
<div className={`h-0.5 flex-1 rounded-full transition-all ${step === "project" ? "bg-white/50" : "bg-white/[0.12]"}`} />
</div>
<AuthProgressBar activeStep={stepIndex(step)} />
{step === "username" ? (
<>
@@ -194,17 +152,13 @@ export default function OnboardingPage() {
/>
<AuthCard>
<AuthField label="Username">
<div className="ui-auth-input flex items-center gap-0 !py-0">
<span className="shrink-0 py-3 text-sm text-white/30 select-none">{APP_DOMAIN}/u/</span>
<input
autoFocus
value={username}
onChange={(e) => setUsername(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && saveUsername()}
placeholder="yourname"
className="flex-1 bg-transparent py-3 text-sm text-white outline-none placeholder:text-white/[0.20]"
/>
</div>
<AuthPrefixField
prefix={`${APP_DOMAIN}/u/`}
value={username}
onChange={setUsername}
onEnter={saveUsername}
placeholder="yourname"
/>
</AuthField>
{error && <p className="ui-error">{error}</p>}
<AuthSubmitButton
@@ -216,7 +170,7 @@ export default function OnboardingPage() {
/>
</AuthCard>
</>
) : (
) : step === "project" ? (
<>
<AuthHeading
title="Add your first project"
@@ -225,20 +179,19 @@ export default function OnboardingPage() {
<AuthCard>
<RepoPicker onSelect={handleRepoSelect} />
{/* Selected repo confirmation or manual entry */}
{projectName && !showManual ? (
<div className="space-y-3">
<div className="flex items-center gap-2.5 rounded-xl border border-white/[0.14] bg-white/[0.06] px-3.5 py-3">
<GitBranch className="h-4 w-4 shrink-0 text-white/40" />
<div className="ui-auth-confirmation-row">
<GitBranch className="h-4 w-4 ui-auth-icon-muted" />
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-white/80">{projectName}</p>
{gitUrl && <p className="truncate text-xs text-white/35">{gitUrl}</p>}
<p className="ui-auth-repo-name">{projectName}</p>
{gitUrl && <p className="ui-auth-repo-desc">{gitUrl}</p>}
</div>
</div>
<button
type="button"
onClick={() => setShowManual(true)}
className="text-xs text-white/30 transition-colors hover:text-white/55"
className="ui-auth-muted-link"
>
Enter details manually instead
</button>
@@ -274,7 +227,7 @@ export default function OnboardingPage() {
{error && <p className="ui-error">{error}</p>}
<div className="flex gap-2">
<div className="ui-auth-row-actions">
<button
type="button"
onClick={() => saveProject(true)}
@@ -289,11 +242,30 @@ export default function OnboardingPage() {
disabled={saving || !projectName.trim()}
className="ui-auth-submit-btn flex-1"
>
{saving ? "Saving…" : "Let's go →"}
{saving ? "Saving…" : "Continue →"}
</button>
</div>
</AuthCard>
</>
) : (
<>
<AuthHeading
title="Connect your machine"
description={
isTeamInvitee
? "Dispatch agents from your local runtime when you're ready."
: "Last step — link the computer where your agents run."
}
/>
<AuthCard>
<ConnectMachineStep
saving={saving}
onComplete={finishOnboarding}
onSkip={finishOnboarding}
/>
{error && <p className="ui-error mt-3">{error}</p>}
</AuthCard>
</>
)}
</AuthShell>
);
+20 -35
View File
@@ -18,7 +18,9 @@ export default async function LandingPage() {
if ((await getUserCount()) === 0) redirect("/setup");
const session = await auth();
if (session?.user) redirect(ROUTES.APP_HOME);
if (session?.user) {
redirect(session.user.onboardedAt ? ROUTES.APP_HOME : ROUTES.ONBOARDING);
}
const stripeReady = isStripeReady();
@@ -30,7 +32,7 @@ export default async function LandingPage() {
<Link href={ROUTES.SIGN_IN} className="ui-public-nav-link hidden sm:block">
Sign in
</Link>
<Link href={ROUTES.SIGN_IN} className="ui-public-primary-action !py-2 !px-5 text-sm">
<Link href={ROUTES.SIGN_IN} className="ui-public-primary-action-compact">
Get started →
</Link>
</div>
@@ -38,7 +40,6 @@ export default async function LandingPage() {
>
<main className="relative z-10 flex flex-col items-center px-6 pb-16 pt-16 text-center sm:pb-32 sm:pt-28">
{/* Hero */}
<h1 className="ui-public-title max-w-5xl">
{LANDING_HEADLINE[0]}
<br />
@@ -58,14 +59,9 @@ export default async function LandingPage() {
</Link>
</div>
{/* Features */}
<div id="features" className="mt-16 sm:mt-32 w-full max-w-4xl scroll-mt-24">
<p className="mb-3 text-xs font-semibold uppercase tracking-[0.12em] text-white/25">
What it does
</p>
<h2 className="mb-8 sm:mb-12 text-2xl font-bold tracking-tight text-white/80">
One surface. Every system.
</h2>
<p className="ui-public-section-kicker">What it does</p>
<h2 className="ui-public-section-title-spaced">One surface. Every system.</h2>
<div className="grid gap-4 sm:grid-cols-3">
{LANDING_FEATURES.map(({ icon, title, body }) => (
<div key={title} className="ui-public-feature-card">
@@ -77,15 +73,10 @@ export default async function LandingPage() {
</div>
</div>
{/* Pricing */}
<div id="pricing" className="mt-16 sm:mt-32 w-full max-w-4xl scroll-mt-24">
<p className="mb-3 text-xs font-semibold uppercase tracking-[0.12em] text-white/25">
Pricing
</p>
<h2 className="mb-2 text-2xl font-bold tracking-tight text-white/80">
Simple, honest pricing
</h2>
<p className="mb-8 sm:mb-12 text-sm text-white/30">Billed annually · cancel any time</p>
<p className="ui-public-section-kicker">Pricing</p>
<h2 className="ui-public-section-title mb-2">Simple, honest pricing</h2>
<p className="ui-public-section-note">Billed annually · cancel any time</p>
<div className="grid gap-4 sm:grid-cols-3">
{LANDING_PRICING.map((tier) => (
<div
@@ -93,21 +84,15 @@ export default async function LandingPage() {
className={`ui-public-pricing-card${tier.highlighted ? " ui-public-pricing-card-highlighted" : ""}`}
>
{tier.highlighted && (
<div className="mb-4 inline-flex items-center rounded-full bg-white/[0.08] px-2.5 py-1 text-micro font-semibold uppercase tracking-widest text-white/50">
Most popular
</div>
<div className="ui-public-pricing-popular">Most popular</div>
)}
<div className="mb-1 text-xs font-semibold uppercase tracking-widest text-white/30">
{tier.name}
<div className="ui-public-pricing-plan">{tier.name}</div>
<div className="ui-public-pricing-price-row">
<span className="ui-public-pricing-price">${tier.monthly}</span>
<span className="ui-public-pricing-period">/mo</span>
</div>
<div className="flex items-baseline gap-1">
<span className="text-4xl font-bold tracking-tight text-white/90">
${tier.monthly}
</span>
<span className="text-sm text-white/30">/mo</span>
</div>
<p className="mb-1 text-xs text-white/40">${tier.annual}/yr billed annually</p>
<p className="mb-6 mt-3 text-sm leading-relaxed text-white/40">{tier.tagline}</p>
<p className="ui-public-pricing-annual">${tier.annual}/yr billed annually</p>
<p className="ui-public-pricing-tagline">{tier.tagline}</p>
<Link
href={
stripeReady
@@ -122,11 +107,11 @@ export default async function LandingPage() {
>
{tier.cta}
</Link>
<div className="border-t border-white/[0.06] pt-5">
<ul className="space-y-2.5 text-left">
<div className="ui-public-pricing-divider">
<ul className="ui-public-pricing-features">
{tier.features.map((feature) => (
<li key={feature} className="flex items-start gap-2.5 text-sm text-white/40">
<span className="mt-0.5 shrink-0 text-white/20">✓</span>
<li key={feature} className="ui-public-pricing-feature">
<span className="ui-public-pricing-check">✓</span>
{feature}
</li>
))}
+2 -5
View File
@@ -2,8 +2,7 @@
import { signOut } from "next-auth/react";
import { useEffect } from "react";
import { AuthShell, AuthHeading } from "@/components/auth/AuthShell";
import { Loader2 } from "lucide-react";
import { AuthShell, AuthHeading, AuthLoadingCenter } from "@/components/auth/AuthShell";
import { ROUTES } from "@/config/auth";
export default function SignOutPage() {
@@ -17,9 +16,7 @@ export default function SignOutPage() {
title="Signing out…"
description="You'll be redirected to the sign-in page."
/>
<div className="flex justify-center">
<Loader2 className="h-6 w-6 animate-spin text-white/30" />
</div>
<AuthLoadingCenter />
</AuthShell>
);
}
+6 -1
View File
@@ -15,7 +15,12 @@ import { getDefaultUser } from "@/db/queries/users";
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const now = new Date();
const thoughts = listThoughts();
const defaultUser = await getDefaultUser();
let defaultUser: Awaited<ReturnType<typeof getDefaultUser>> | undefined;
try {
defaultUser = await getDefaultUser();
} catch {
// Build/CI may run without a reachable DB — static routes still ship.
}
const base: MetadataRoute.Sitemap = [
{ url: `${APP_URL}/`, lastModified: now, changeFrequency: "weekly", priority: 1.0 },
+26 -25
View File
@@ -55,7 +55,7 @@ function VerifyEmailInner() {
description="This verification link is invalid or has expired. Enter your email to get a new one."
/>
{sent ? (
<p className="text-center text-sm text-white/50">
<p className="ui-auth-hint-emphasis">
Check your inbox — a new verification link is on the way.
</p>
) : (
@@ -87,7 +87,6 @@ function VerifyEmailInner() {
);
}
// Default: verify-email landing for users who registered but haven't clicked yet
return (
<AuthShell>
<AuthHeading
@@ -95,34 +94,36 @@ function VerifyEmailInner() {
description="We sent you a verification link. Click it to activate your account."
/>
{sent ? (
<p className="text-center text-sm text-white/50">
<p className="ui-auth-hint-emphasis">
New link sent — check your inbox (and spam folder).
</p>
) : (
<AuthCard>
<p className="mb-4 text-sm text-white/50">
Didn&apos;t get the email? Enter your address to resend it.
<>
<p className="ui-auth-hint-emphasis mb-4">
Didn&apos;t get it? Enter your email and we&apos;ll send another.
</p>
<form onSubmit={handleResend} className="space-y-3">
<AuthField label="Email">
<AuthInput
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="you@example.com"
autoComplete="email"
required
<AuthCard>
<form onSubmit={handleResend} className="space-y-3">
<AuthField label="Email">
<AuthInput
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="you@example.com"
autoComplete="email"
required
/>
</AuthField>
{reqError && <p className="ui-error">{reqError}</p>}
<AuthSubmitButton
loading={loading}
disabled={!email}
label="Resend link →"
loadingLabel="Sending…"
/>
</AuthField>
{reqError && <p className="ui-error">{reqError}</p>}
<AuthSubmitButton
loading={loading}
disabled={!email}
label="Resend verification →"
loadingLabel="Sending…"
/>
</form>
</AuthCard>
</form>
</AuthCard>
</>
)}
<AuthFooterLink href={ROUTES.SIGN_IN}>← Back to sign in</AuthFooterLink>
</AuthShell>
+23 -41
View File
@@ -8,7 +8,6 @@ import { ROUTES } from "@/config/auth";
import { APP_NAME } from "@/config/brand";
export const metadata: Metadata = {
// Root layout's title template appends "— Cockpit" — don't double it here.
title: "Whitepaper",
description: "A technical architecture for sustained autonomous execution across many projects simultaneously.",
};
@@ -53,56 +52,40 @@ export default function WhitepaperPage() {
)}
>
<div className="relative z-10 mx-auto max-w-3xl px-6 pb-32 pt-16 sm:px-10">
{/* Header */}
<div className="mb-16 border-b border-white/[0.08] pb-12">
<div className="mb-6 flex flex-wrap items-center gap-3">
<span className="rounded-full border border-white/[0.12] bg-white/[0.06] px-3 py-1 font-mono text-xs text-white/40">
WHITEPAPER
</span>
<span className="font-mono text-xs text-white/25">v{version}</span>
<div className="ui-public-doc-header">
<div className="ui-public-doc-meta-row">
<span className="ui-public-doc-badge">WHITEPAPER</span>
<span className="ui-public-doc-meta">v{version}</span>
{publishedAt && (
<span className="font-mono text-xs text-white/25">{publishedAt}</span>
<span className="ui-public-doc-meta">{publishedAt}</span>
)}
</div>
<h1 className="mb-5 font-bold tracking-tight text-white" style={{ fontSize: "clamp(2rem, 5vw, 3.25rem)", lineHeight: 1.05, letterSpacing: "-0.03em" }}>
{title}
</h1>
<h1 className="ui-public-doc-title">{title}</h1>
{subtitle && (
<p className="text-lg leading-relaxed text-white/40 sm:text-xl">
{subtitle}
</p>
<p className="ui-public-doc-subtitle">{subtitle}</p>
)}
</div>
{/* Body */}
<article className="space-y-8">
<article className="ui-public-prose">
{blocks.map((block, i) => {
switch (block.type) {
case "h2":
return (
<h2 key={i} className="pt-6 text-2xl font-semibold tracking-tight text-white/90" style={{ letterSpacing: "-0.02em" }}>
{block.text}
</h2>
);
return <h2 key={i} className="ui-public-prose-h2">{block.text}</h2>;
case "h3":
return (
<h3 key={i} className="pt-2 text-lg font-semibold text-white/80">
{block.text}
</h3>
);
return <h3 key={i} className="ui-public-prose-h3">{block.text}</h3>;
case "p":
return (
<p
key={i}
className="text-base leading-[1.8] text-white/50"
className="ui-public-prose-p"
dangerouslySetInnerHTML={{ __html: renderInline(block.text) }}
/>
);
case "blockquote":
return (
<blockquote key={i} className="border-l-2 border-white/20 pl-6">
<blockquote key={i} className="ui-public-prose-blockquote">
{block.text.map((line, j) => (
<p key={j} className="text-base italic leading-relaxed text-white/35">{line}</p>
<p key={j} className="ui-public-prose-blockquote-p">{line}</p>
))}
</blockquote>
);
@@ -110,8 +93,8 @@ export default function WhitepaperPage() {
return (
<ul key={i} className="space-y-2 pl-4">
{block.items.map((item, j) => (
<li key={j} className="flex items-start gap-3 text-base leading-relaxed text-white/45">
<span className="mt-2.5 h-1 w-1 shrink-0 rounded-full bg-white/25" />
<li key={j} className="ui-public-prose-li">
<span className="ui-public-prose-bullet" />
<span dangerouslySetInnerHTML={{ __html: renderInline(item) }} />
</li>
))}
@@ -121,8 +104,8 @@ export default function WhitepaperPage() {
return (
<ol key={i} className="space-y-2 pl-4">
{block.items.map((item, j) => (
<li key={j} className="flex items-start gap-3 text-base leading-relaxed text-white/45">
<span className="shrink-0 font-mono text-xs text-white/25 mt-1">{j + 1}.</span>
<li key={j} className="ui-public-prose-li">
<span className="ui-public-prose-ol-index">{j + 1}.</span>
<span dangerouslySetInnerHTML={{ __html: renderInline(item) }} />
</li>
))}
@@ -130,11 +113,11 @@ export default function WhitepaperPage() {
);
case "code":
return (
<div key={i} className="overflow-x-auto rounded-xl border border-white/[0.08] bg-white/[0.04] p-5">
<div key={i} className="ui-public-code-block">
{block.lang && (
<p className="mb-3 font-mono text-micro uppercase tracking-widest text-white/20">{block.lang}</p>
<p className="ui-public-code-lang">{block.lang}</p>
)}
<pre className="font-mono text-sm leading-relaxed text-white/60">
<pre className="ui-public-code-pre">
<code>{block.text}</code>
</pre>
</div>
@@ -145,10 +128,9 @@ export default function WhitepaperPage() {
})}
</article>
{/* Footer CTA */}
<div className="mt-24 border-t border-white/[0.08] pt-16 text-center">
<p className="mb-2 text-sm font-medium text-white/60">Ready to close the execution gap?</p>
<p className="mb-8 text-sm text-white/30">Start using {APP_NAME} as your builder operating system.</p>
<div className="ui-public-doc-footer">
<p className="ui-public-doc-footer-title">Ready to close the execution gap?</p>
<p className="ui-public-doc-footer-note">Start using {APP_NAME} as your builder operating system.</p>
<div className="flex flex-wrap items-center justify-center gap-3">
<Link href={ROUTES.SIGN_IN} className="ui-public-primary-action">
Get started →
+76 -1
View File
@@ -1,4 +1,5 @@
import Link from "next/link";
import { Loader2 } from "lucide-react";
import { PublicSurface } from "@/components/public/PublicSurface";
import { PUBLIC_SURFACE } from "@/config/ui";
import { PUBLIC_NAV_LINKS } from "@/config/auth";
@@ -92,7 +93,7 @@ export function AuthShell({
className="relative z-10 flex items-center justify-center px-4 pb-16"
style={{ minHeight: `calc(100vh - ${PUBLIC_SURFACE.navHeightPx}px)` }}
>
<div className="w-full max-w-[400px]">{children}</div>
<div className="ui-auth-container">{children}</div>
</main>
</PublicSurface>
);
@@ -145,3 +146,77 @@ export function AuthSecondaryButton({
</button>
);
}
export function AuthProgressBar({ activeStep, steps = 3 }: { activeStep: number; steps?: number }) {
return (
<div className="ui-auth-progress-row">
{Array.from({ length: steps }, (_, i) => (
<div
key={i}
className={`ui-auth-progress-segment${i <= activeStep ? " ui-auth-progress-segment-active" : ""}`}
/>
))}
</div>
);
}
export function AuthPrefixField({
prefix,
value,
onChange,
onEnter,
placeholder,
}: {
prefix: string;
value: string;
onChange: (value: string) => void;
onEnter?: () => void;
placeholder?: string;
}) {
return (
<div className="ui-auth-prefix-field">
<span className="ui-auth-prefix-label">{prefix}</span>
<input
autoFocus
value={value}
onChange={(e) => onChange(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && onEnter?.()}
placeholder={placeholder}
className="ui-auth-prefix-input"
/>
</div>
);
}
export function AuthLoadingCenter({ size = "md" }: { size?: "sm" | "md" }) {
return (
<div className="ui-auth-loading">
<Loader2 className={size === "sm" ? "ui-auth-spinner-sm" : "ui-auth-spinner"} />
</div>
);
}
export function AuthModeTabs({
tabs,
active,
onChange,
}: {
tabs: Array<{ id: string; label: string }>;
active: string;
onChange: (id: string) => void;
}) {
return (
<div className="ui-auth-mode-tabs">
{tabs.map((tab) => (
<button
key={tab.id}
type="button"
onClick={() => onChange(tab.id)}
className={active === tab.id ? "ui-auth-mode-tab ui-auth-mode-tab-active" : "ui-auth-mode-tab"}
>
{tab.label}
</button>
))}
</div>
);
}
+13 -29
View File
@@ -7,7 +7,7 @@ import { ROUTES } from "@/config/auth";
import { APP_NAME } from "@/config/brand";
import {
AuthShell, AuthCard, AuthField, AuthInput, AuthSubmitButton,
AuthDivider, AuthHeading, AuthSecondaryButton,
AuthDivider, AuthHeading, AuthSecondaryButton, AuthModeTabs,
} from "@/components/auth/AuthShell";
import Link from "next/link";
@@ -117,30 +117,14 @@ function FormInner({
{/* Mode tabs — only show owner key tab when LOCAL_AUTH_PASSWORD is configured */}
{localAuthEnabled && (
<div className="mb-6 flex rounded-xl border border-white/[0.08] bg-white/[0.03] p-1">
<button
type="button"
onClick={() => switchMode("email")}
className={`flex-1 rounded-lg py-2 text-sm font-medium transition-colors ${
mode === "email"
? "bg-white/[0.09] text-white/80"
: "text-white/30 hover:text-white/55"
}`}
>
Email
</button>
<button
type="button"
onClick={() => switchMode("owner")}
className={`flex-1 rounded-lg py-2 text-sm font-medium transition-colors ${
mode === "owner"
? "bg-white/[0.09] text-white/80"
: "text-white/30 hover:text-white/55"
}`}
>
Owner key
</button>
</div>
<AuthModeTabs
tabs={[
{ id: "email", label: "Email" },
{ id: "owner", label: "Owner key" },
]}
active={mode}
onChange={(id) => switchMode(id as Mode)}
/>
)}
{mode === "email" ? (
@@ -226,9 +210,9 @@ function FormInner({
label="Sign in →"
loadingLabel="Signing in…"
/>
<p className="text-center text-sm text-white/35">
<p className="ui-auth-hint">
No account?{" "}
<Link href={ROUTES.SIGN_UP} className="text-white/60 underline underline-offset-2 hover:text-white/80 transition-colors">
<Link href={ROUTES.SIGN_UP} className="ui-auth-hint-link">
Create one free →
</Link>
</p>
@@ -236,8 +220,8 @@ function FormInner({
</AuthCard>
) : (
<AuthCard>
<p className="text-sm text-white/35">
Use the owner password set in <code className="rounded bg-white/[0.06] px-1.5 py-0.5 text-xs text-white/50">LOCAL_AUTH_PASSWORD</code>.
<p className="ui-auth-owner-note">
Use the owner password set in <code className="ui-auth-inline-code">LOCAL_AUTH_PASSWORD</code>.
</p>
<form onSubmit={handleOwnerPassword} className="space-y-3">
<AuthField label="Owner password">
+11 -1
View File
@@ -1,6 +1,6 @@
"use client";
import { useState } from "react";
import { useState, useEffect } from "react";
import { useLocalStorageState } from "@/hooks/use-local-storage-state";
import { RefreshCw, Sparkles, Plus, Moon, LayoutList, LayoutGrid } from "lucide-react";
import { cn } from "@/lib/utils";
@@ -42,6 +42,16 @@ export function ControlPanel() {
(v) => v,
(raw) => raw === "commander" ? "commander" : "full",
);
// First mobile visit: default to commander (live tabs + fleet) instead of full metrics wall.
useEffect(() => {
try {
if (localStorage.getItem("control:view-mode") !== null) return;
if (window.matchMedia("(max-width: 767px)").matches) {
setViewMode("commander");
}
} catch { /* ignore */ }
}, [setViewMode]);
const [activityOpen, setActivityOpen] = useState(false);
const [idleOpen, setIdleOpen] = useState(true);
const [expandedTabs, setExpandedTabs] = useState<Set<string>>(new Set());
+5 -1
View File
@@ -230,8 +230,12 @@ function attentionScore(project: ProjectState): { score: number; reason: string
}
export function formatAgentRuntimeLabel(project: ProjectState): string {
const labels: Record<string, string> = {
cursor: "Cursor",
agent: "Cursor",
};
return project.activeAgents
.map((name) => name[0]?.toUpperCase() + name.slice(1))
.map((name) => labels[name] ?? (name[0]?.toUpperCase() + name.slice(1)))
.join(", ");
}
@@ -121,7 +121,7 @@ export function IntentButtonPanel({
key={r.customPrompt}
onClick={() => onCustomChange(r.customPrompt)}
title={`Reuse this prompt: ${r.customPrompt}`}
className="ui-chip-action-compact max-w-[18rem] truncate text-left text-text-tertiary hover:text-text-secondary"
className="ui-chip-truncate-label"
>
{(() => { const t = r.customPrompt.replace(/\s+/g, " ").trim(); return t.length > 50 ? t.slice(0, 50) + "…" : t; })()}
</button>
@@ -224,7 +224,7 @@ export function IntentButtonPanel({
key={r.customPrompt}
onClick={() => onCustomChange(r.customPrompt)}
title={`Reuse this prompt: ${r.customPrompt}`}
className="ui-chip-action-compact max-w-[18rem] truncate text-left text-text-tertiary hover:text-text-secondary"
className="ui-chip-truncate-label"
>
{r.count > 1 && <span className="mr-1.5">used {r.count}×</span>}
{(() => { const t = r.customPrompt.replace(/\s+/g, " ").trim(); return t.length > 60 ? t.slice(0, 60) + "…" : t; })()}
@@ -0,0 +1,169 @@
"use client";
import { useState, useEffect, useCallback } from "react";
import { Check, Copy, Loader2, Terminal, Wifi } from "lucide-react";
import { getJson, postJson } from "@/lib/api/fetch";
import { APP_NAME, APP_SLUG, APP_URL } from "@/config/brand";
type Props = {
saving: boolean;
onComplete: () => void;
onSkip: () => void;
};
type OnboardingStatus = {
daemonConnected: boolean;
daemonLastPushedAt: string | null;
};
export function ConnectMachineStep({ saving, onComplete, onSkip }: Props) {
const [status, setStatus] = useState<OnboardingStatus | null>(null);
const [generating, setGenerating] = useState(false);
const [token, setToken] = useState<string | null>(null);
const [error, setError] = useState("");
const [copied, setCopied] = useState<"token" | "cmd" | null>(null);
const refreshStatus = useCallback(async () => {
try {
const data = await getJson<OnboardingStatus>("/api/onboarding");
setStatus(data);
return data;
} catch {
return null;
}
}, []);
useEffect(() => {
void refreshStatus();
const id = setInterval(() => { void refreshStatus(); }, 4000);
return () => clearInterval(id);
}, [refreshStatus]);
async function generateToken() {
setGenerating(true);
setError("");
try {
const res = await postJson("/api/agent-tokens", { label: "My machine" });
const data = await res.json();
if (!res.ok) throw new Error(data.error ?? "Failed to generate token");
setToken(data.token as string);
} catch (e) {
setError(e instanceof Error ? e.message : "Something went wrong");
} finally {
setGenerating(false);
}
}
async function copy(text: string, kind: "token" | "cmd") {
await navigator.clipboard.writeText(text);
setCopied(kind);
setTimeout(() => setCopied(null), 2000);
}
const initCommand = token
? `npx @${APP_SLUG}/agent init --token ${token} --base-url ${APP_URL}`
: null;
const connected = status?.daemonConnected ?? false;
return (
<div className="space-y-4">
<p className="ui-auth-body">
{APP_NAME} dispatches agents from your machine. Generate a token, run one command in your terminal,
then start the daemon — or skip and set this up later in Settings.
</p>
<ol className="ui-auth-list">
<li>
Install{" "}
<a href="https://zellij.dev/" target="_blank" rel="noopener noreferrer" className="ui-auth-link">
Zellij
</a>{" "}
and at least one agent CLI (Claude, Cursor, Codex, …).
</li>
<li>Generate a token and run the init command below.</li>
<li>
Start the daemon:{" "}
<code className="ui-auth-inline-code">./scripts/cockpit-daemon.sh</code>
</li>
</ol>
{!token ? (
<button
type="button"
onClick={generateToken}
disabled={generating}
className="ui-auth-submit-btn gap-2"
>
{generating ? <Loader2 className="ui-auth-spinner-sm" /> : <Terminal className="h-4 w-4" />}
{generating ? "Generating…" : "Generate agent token"}
</button>
) : (
<div className="space-y-3">
<div className="ui-auth-inset-panel">
<p className="ui-auth-inset-label">Token (copy now — shown once)</p>
<div className="flex items-center gap-2">
<code className="ui-auth-mono">{token}</code>
<button
type="button"
onClick={() => copy(token, "token")}
className="ui-btn-icon shrink-0"
aria-label="Copy token"
>
{copied === "token" ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
</button>
</div>
</div>
{initCommand && (
<div className="ui-auth-inset-panel">
<p className="ui-auth-inset-label">Run on your machine</p>
<div className="flex items-start gap-2">
<code className="ui-auth-mono-wrap">{initCommand}</code>
<button
type="button"
onClick={() => copy(initCommand, "cmd")}
className="ui-btn-icon shrink-0"
aria-label="Copy command"
>
{copied === "cmd" ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
</button>
</div>
</div>
)}
</div>
)}
{connected && (
<div className="ui-auth-status-banner">
<Wifi className="h-4 w-4 shrink-0 text-status-positive" />
Machine connected
{status?.daemonLastPushedAt && (
<span className="ui-auth-status-meta">· syncing</span>
)}
</div>
)}
{error && <p className="ui-error">{error}</p>}
<div className="ui-auth-row-actions pt-1">
<button
type="button"
onClick={onSkip}
disabled={saving}
className="ui-auth-secondary-btn flex-1"
>
Skip for now
</button>
<button
type="button"
onClick={onComplete}
disabled={saving}
className="ui-auth-submit-btn flex-1"
>
{saving ? "Saving…" : connected ? "Finish →" : "Continue →"}
</button>
</div>
</div>
);
}
+86
View File
@@ -0,0 +1,86 @@
"use client";
import { useState, useEffect } from "react";
import { Loader2, Lock, Star } from "lucide-react";
import type { GitHubRepo } from "@/app/api/github/repos/route";
const LANG_COLORS: Record<string, string> = {
TypeScript: "ui-lang-ts",
JavaScript: "ui-lang-js",
Python: "ui-lang-py",
Go: "ui-lang-go",
Rust: "ui-lang-rs",
Ruby: "ui-lang-rb",
"C#": "ui-lang-cs",
Java: "ui-lang-java",
};
export function RepoPicker({ onSelect }: { onSelect: (repo: GitHubRepo) => void }) {
const [repos, setRepos] = useState<GitHubRepo[]>([]);
const [hasGithub, setHasGithub] = useState<boolean | null>(null);
const [loading, setLoading] = useState(true);
const [selected, setSelected] = useState<number | null>(null);
useEffect(() => {
fetch("/api/github/repos")
.then((r) => r.json())
.then((d: { repos?: GitHubRepo[]; hasGithub?: boolean }) => {
setRepos(d.repos ?? []);
setHasGithub(d.hasGithub ?? false);
})
.catch(() => setHasGithub(false))
.finally(() => setLoading(false));
}, []);
if (loading) {
return (
<div className="ui-auth-loading py-8">
<Loader2 className="ui-auth-spinner-sm" />
</div>
);
}
if (!hasGithub || repos.length === 0) return null;
return (
<div className="space-y-2">
<p className="ui-auth-repo-hint">Your GitHub repos — pick one to start</p>
<div className="ui-auth-repo-scroll">
{repos.map((repo) => {
const isSelected = selected === repo.id;
const langColor = repo.language ? (LANG_COLORS[repo.language] ?? "ui-lang-default") : null;
return (
<button
key={repo.id}
type="button"
onClick={() => {
setSelected(repo.id);
onSelect(repo);
}}
className={`ui-auth-selectable-card${isSelected ? " ui-auth-selectable-card-selected" : ""}`}
>
<div className="flex items-center gap-2">
{repo.private && <Lock className="ui-auth-icon-faint" />}
<span className="ui-auth-repo-name">{repo.name}</span>
{langColor && (
<span className={`ml-auto shrink-0 rounded-md px-1.5 py-0.5 text-xs font-medium ${langColor}`}>
{repo.language}
</span>
)}
{repo.stargazers_count > 0 && (
<span className="ui-auth-meta-inline">
<Star className="ui-auth-icon-faint" />
{repo.stargazers_count}
</span>
)}
</div>
{repo.description && (
<p className="ui-auth-repo-desc">{repo.description}</p>
)}
</button>
);
})}
</div>
</div>
);
}
+8 -14
View File
@@ -9,20 +9,12 @@ export function BrandMark({
showWordmark?: boolean;
inverted?: boolean;
}) {
const markSize = compact ? "ui-brand-mark-compact" : "ui-brand-mark-default";
const markSurface = inverted ? "ui-brand-mark-inverted" : "ui-brand-mark";
return (
<div className="flex items-center gap-3">
<div
className={
compact
? `flex h-10 w-10 items-center justify-center rounded-2xl border ${
inverted ? "border-white/12 bg-white/[0.03]" : "border-border-default bg-surface-overlay"
}`
: `flex h-11 w-11 items-center justify-center rounded-2xl border ${
inverted ? "border-white/12 bg-white/[0.03]" : "border-border-default bg-surface-overlay"
}`
}
aria-hidden
>
<div className={`${markSurface} ${markSize}`} aria-hidden>
<svg
width={compact ? 22 : 24}
height={compact ? 22 : 24}
@@ -39,8 +31,10 @@ export function BrandMark({
</div>
{showWordmark && !compact && (
<div className="min-w-0">
<p className={inverted ? "ui-kicker text-white/38" : "ui-kicker"}>{APP_KICKER}</p>
<span className={inverted ? "mt-1 block text-2xl font-medium tracking-display text-white" : "mt-1 block text-2xl font-medium tracking-display text-text-primary"}>{APP_NAME}</span>
<p className={inverted ? "ui-brand-kicker-inverted" : "ui-kicker"}>{APP_KICKER}</p>
<span className={inverted ? "ui-brand-wordmark-inverted" : "mt-1 block text-2xl font-medium tracking-display text-text-primary"}>
{APP_NAME}
</span>
</div>
)}
</div>
+2 -6
View File
@@ -1,13 +1,9 @@
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import { getDatabasePoolUrl } from "@/lib/db-url";
import * as schema from "./schema";
// NEON_DATABASE_URL = pooler endpoint (for API routes in serverless)
// DATABASE_URL = direct connection (local dev / migrations)
const DATABASE_URL = process.env.NEON_DATABASE_URL ?? process.env.DATABASE_URL;
if (!DATABASE_URL) {
throw new Error("DATABASE_URL or NEON_DATABASE_URL environment variable is required");
}
const DATABASE_URL = getDatabasePoolUrl();
/**
* Hot-reload-safe singleton client.
-1
View File
@@ -48,7 +48,6 @@ export async function acceptInvitation(
name,
email: invite.email ?? email ?? null,
passwordHash,
onboardedAt: new Date(),
})
.returning({ id: users.id });
+10 -1
View File
@@ -61,7 +61,6 @@ export async function addOrgMember(orgId: string, userId: string, role: "admin"
});
}
/** Returns the org owned by this user (their primary team). */
export async function getOwnerOrgId(userId: string): Promise<string | null> {
const [row] = await db
.select({ id: orgs.id })
@@ -70,3 +69,13 @@ export async function getOwnerOrgId(userId: string): Promise<string | null> {
.limit(1);
return row?.id ?? null;
}
/** True when the user belongs to someone else's org (team invite), not just their personal org. */
export async function isTeamInvitee(userId: string): Promise<boolean> {
const memberships = await db
.select({ ownerId: orgs.ownerId })
.from(orgMemberships)
.innerJoin(orgs, eq(orgs.id, orgMemberships.orgId))
.where(eq(orgMemberships.userId, userId));
return memberships.some((row) => row.ownerId !== userId);
}
+1 -1
View File
@@ -22,7 +22,7 @@ export async function createUser(data: { name: string; email: string; passwordHa
name: data.name,
email: data.email.toLowerCase().trim(),
passwordHash: data.passwordHash,
// onboardedAt intentionally left null — set by the /onboarding flow
// onboardedAt set server-side by POST /api/onboarding when username is valid
})
.returning({ id: users.id });
return user;
+3 -2
View File
@@ -1,5 +1,6 @@
import postgres from "postgres";
import { APP_SLUG } from "@/config/brand";
import { getDatabaseDirectUrl } from "@/lib/db-url";
// Postgres identifier (function + channel) names derived from APP_SLUG so a
// brand rename moves all three contract sites together: this file, the LISTEN
@@ -10,9 +11,9 @@ export const NOTIFY_FN_NAME = `${_slug}_notify_project_state`;
export const NOTIFY_CHANNEL = `${_slug}_state`;
// Installs a Postgres NOTIFY trigger on project_states (idempotent — safe to run on every boot).
// Must use DATABASE_URL (direct connection) — Neon pooler doesn't support DDL + NOTIFY.
// Must use a direct connection — poolers (Neon, PgBouncer transaction mode) break DDL + NOTIFY.
export async function setupNotifyTrigger(): Promise<void> {
const url = process.env.DATABASE_URL;
const url = getDatabaseDirectUrl();
if (!url) return;
const sql = postgres(url, { max: 1 });
try {
+1 -1
View File
@@ -12,7 +12,7 @@ export type AgentCatalog = {
};
function isSwitchableAgent(id: AgentOption): id is SwitchableAgent {
return id === "claude" || id === "codex" || id === "gemini";
return id === "claude" || id === "codex" || id === "gemini" || id === "cursor";
}
export function buildSwitchableAgentCatalog(models: Partial<Record<SwitchableAgent, string>>, defaultAgent: SwitchableAgent): AgentCatalog {
+1
View File
@@ -32,6 +32,7 @@ function normalizePreferences(raw: Partial<AgentPreferences & LegacyAgentConfig>
claude: sanitizeModel("claude", currentModels.claude),
codex: sanitizeModel("codex", currentModels.codex),
gemini: sanitizeModel("gemini", currentModels.gemini),
cursor: sanitizeModel("cursor", currentModels.cursor),
};
if (!currentModels[defaultAgent] && raw.model) {
+58 -3
View File
@@ -1,14 +1,15 @@
import fs from "fs";
import path from "path";
import { existsSync } from "fs";
import { execSync } from "child_process";
import { HOME } from "@/lib/constants";
import { shellEscape } from "@/lib/zellij";
const CLAUDE_SETTINGS_FILE = path.join(HOME, ".claude", "settings.json");
const DOTFILES_CLAUDE_SETTINGS_FILE = path.join(HOME, "dev", "dotfiles", ".claude", "settings.json");
export const AGENT_IDS = ["codex", "claude", "gemini"] as const;
export const AGENT_FALLBACK_ORDER: readonly Agent[] = ["claude", "codex", "gemini"];
export const AGENT_IDS = ["codex", "claude", "gemini", "cursor"] as const;
export const AGENT_FALLBACK_ORDER: readonly Agent[] = ["claude", "cursor", "codex", "gemini"];
export type Agent = (typeof AGENT_IDS)[number];
export type AgentOption = Agent | "openclaw";
@@ -16,6 +17,7 @@ export const AGENT_DEFAULT_MODELS: Record<Agent, string> = {
claude: "sonnet",
codex: "gpt-5.4",
gemini: "auto",
cursor: "auto",
};
export type AgentRegistryEntry = {
@@ -151,12 +153,46 @@ function getGeminiAvailability(): Pick<AgentRegistryEntry, "available" | "availa
};
}
/** Cursor Agent CLI (`agent`) — verify PATH binary is Cursor's, not a generic `agent`. */
function getCursorAvailability(): Pick<AgentRegistryEntry, "available" | "availabilityReason"> {
if (!commandExistsInPath("agent")) {
return {
available: false,
availabilityReason: "Cursor Agent CLI is not installed. Run: curl https://cursor.com/install -fsS | bash",
};
}
try {
const version = execSync("agent --version 2>&1", { encoding: "utf-8", timeout: 3000 }).trim();
if (/\d{4}\.\d{2}\.\d{2}/.test(version)) {
return { available: true };
}
} catch {
// Fall through — still allow if binary exists under Cursor's typical path.
}
const pathValue = process.env.PATH ?? "";
for (const dir of pathValue.split(":")) {
if (!dir) continue;
const candidate = `${dir}/agent`;
if (candidate.includes(".local/bin/agent") || candidate.includes(".cursor")) {
return { available: true };
}
}
return {
available: false,
availabilityReason: "An `agent` binary exists but does not look like Cursor Agent CLI.",
};
}
export function listAgentRegistry(): AgentRegistryEntry[] {
const codexDefaultModel = readConfiguredCodexModel() ?? AGENT_DEFAULT_MODELS.codex;
const claudeDefaultModel = readClaudeSettingsModel() ?? AGENT_DEFAULT_MODELS.claude;
const codexAvailability = getCodexAvailability();
const openclawAvailability = getOpenClawAvailability();
const geminiAvailability = getGeminiAvailability();
const cursorAvailability = getCursorAvailability();
return [
{
@@ -175,6 +211,22 @@ export function listAgentRegistry(): AgentRegistryEntry[] {
sessionLifecycleSignals: true,
},
},
{
id: "cursor",
label: "Cursor",
defaultModel: AGENT_DEFAULT_MODELS.cursor,
modelSuggestions: ["auto", "composer-1", "gpt-5.4", "claude-sonnet-4"],
processMatchers: ["agent"],
switchable: true,
quitCommand: "",
...cursorAvailability,
capabilities: {
tabSwitching: true,
manualPromptInjection: true,
autonomousPromptLoop: false,
sessionLifecycleSignals: false,
},
},
{
id: "codex",
label: "Codex",
@@ -229,11 +281,12 @@ export function listAgentRegistry(): AgentRegistryEntry[] {
export function sanitizeAgentId(value: string | undefined): Agent {
if (value === "claude") return "claude";
if (value === "gemini") return "gemini";
if (value === "cursor") return "cursor";
return "codex";
}
export function isAgentId(value: string | undefined | null): value is Agent {
return value === "claude" || value === "codex" || value === "gemini";
return value === "claude" || value === "codex" || value === "gemini" || value === "cursor";
}
export function looksLikeAgentCapacityIssue(text: string): boolean {
@@ -300,6 +353,8 @@ export function buildAgentOptionLaunchCommand(config: { agent: AgentOption; mode
}
case "openclaw":
return `source ~/.bashrc >/dev/null 2>&1 || true; cd ${escapedDir} && openclaw tui`;
case "cursor":
return `source ~/.bashrc >/dev/null 2>&1 || true; cd ${escapedDir} && agent`;
case "codex":
default: {
const escapedModel = shellEscape(model || AGENT_DEFAULT_MODELS.codex);
+7 -3
View File
@@ -74,9 +74,13 @@ export function getAgentProcesses(
const argv0 = cmdline.split("\0")[0] ?? "";
const basename = argv0.includes("/") ? argv0.split("/").pop()! : argv0;
const agent = agents.find((candidate) =>
candidate.processMatchers.some(
(m) => basename === m || basename === `${m}.exe` || basename.startsWith(`${m}-`),
)
candidate.processMatchers.some((m) => {
if (m === "agent" && candidate.id === "cursor") {
return basename === "agent"
&& (argv0.includes(".local/bin/agent") || argv0.includes("/.cursor/"));
}
return basename === m || basename === `${m}.exe` || basename.startsWith(`${m}-`);
}),
);
if (!agent) continue;
const cwd = fs.readlinkSync(`/proc/${entry}/cwd`);
+47
View File
@@ -0,0 +1,47 @@
/**
* SSOT for Postgres connection URLs — vendor-neutral.
*
* Any hosted Postgres (Neon, Supabase pooler, self-hosted PgBouncer on
* Oracle/Hetzner) uses the same two env vars:
*
* DATABASE_URL — direct session (migrations, LISTEN/NOTIFY, drizzle-kit)
* DATABASE_POOL_URL — pooled session for app queries (Vercel serverless)
*
* Local dev: set DATABASE_URL only (pool URL falls back to the same value).
*
* Legacy Neon names are still read for backward compatibility:
* NEON_DATABASE_URL_DIRECT → direct
* NEON_DATABASE_URL → pool
*/
const LEGACY_DIRECT = () =>
trimEnv(process.env.NEON_DATABASE_URL_DIRECT);
const LEGACY_POOL = () => trimEnv(process.env.NEON_DATABASE_URL);
function trimEnv(value: string | undefined): string | undefined {
const trimmed = value?.trim();
return trimmed || undefined;
}
/** Pooled URL for runtime queries (serverless-safe). */
export function getDatabasePoolUrl(): string {
const url =
trimEnv(process.env.DATABASE_POOL_URL) ??
LEGACY_POOL() ??
trimEnv(process.env.DATABASE_URL);
if (!url) {
throw new Error(
"DATABASE_POOL_URL or DATABASE_URL is required (legacy: NEON_DATABASE_URL)",
);
}
return url;
}
/**
* Direct URL for DDL, LISTEN/NOTIFY, and migrations.
* Never falls back to a pool URL — poolers break those features.
*/
export function getDatabaseDirectUrl(): string | undefined {
return trimEnv(process.env.DATABASE_URL) ?? LEGACY_DIRECT();
}
+31
View File
@@ -0,0 +1,31 @@
import { normalizeUsername } from "@/lib/username";
/** Suggest a handle from OAuth name or email local-part. */
export function suggestUsername(
name: string | null | undefined,
email: string | null | undefined,
): string {
if (name?.trim()) {
const fromName = normalizeUsername(name.trim().replace(/\s+/g, "-"));
if (fromName.length >= 2) return fromName.slice(0, 40);
}
if (email?.trim()) {
const local = email.split("@")[0] ?? "";
const fromEmail = normalizeUsername(local);
if (fromEmail.length >= 2) return fromEmail.slice(0, 40);
}
return "";
}
export function hasValidUsername(username: string | null | undefined): boolean {
if (!username?.trim()) return false;
const normalized = normalizeUsername(username);
return normalized.length >= 2 && /^[a-z0-9-]+$/.test(normalized);
}
export function isOnboardingComplete(user: {
username: string | null | undefined;
onboardedAt: Date | null | undefined;
}): boolean {
return user.onboardedAt != null && hasValidUsername(user.username);
}